]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/discover-image.c
vmspawn: Drop unused arg_settings_mask
[thirdparty/systemd.git] / src / shared / discover-image.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
cd61c3bf 2
ebd93cb6 3#include <fcntl.h>
e08f94ac 4#include <linux/loop.h>
65ddc2c5 5#include <linux/magic.h>
a8fbdf54 6#include <stdio.h>
e306723e 7#include <sys/file.h>
204f52e3 8#include <sys/ioctl.h>
a8fbdf54 9#include <sys/stat.h>
69a283c5 10#include <sys/sysmacros.h>
a8fbdf54 11#include <unistd.h>
546dbec5 12
69a283c5 13#include "sd-json.h"
1c0ade2e
LP
14#include "sd-path.h"
15
b5efdb8a 16#include "alloc-util.h"
01db9c85 17#include "blockdev-util.h"
cd61c3bf 18#include "btrfs-util.h"
f461a28d 19#include "chase.h"
c8b3094d 20#include "chattr-util.h"
ebd93cb6 21#include "copy.h"
a0956174 22#include "dirent-util.h"
57f1b61b 23#include "discover-image.h"
c7664c07 24#include "dissect-image.h"
686d13b9 25#include "env-file.h"
b6e953f2 26#include "env-util.h"
6afa5d86 27#include "extension-util.h"
3ffd4af2 28#include "fd-util.h"
f4f15635 29#include "fs-util.h"
a8fbdf54 30#include "hashmap.h"
e2054217 31#include "hostname-setup.h"
c7664c07 32#include "id128-util.h"
73740c9f 33#include "initrd-util.h"
64e89f56 34#include "lock-util.h"
a8fbdf54 35#include "log.h"
c7664c07 36#include "loop-util.h"
30535c16 37#include "mkdir.h"
d8b4d14d 38#include "nulstr-util.h"
d58ad743 39#include "os-util.h"
8e0b6570 40#include "path-util.h"
c6878637 41#include "rm-rf.h"
69a283c5 42#include "runtime-scope.h"
65ddc2c5 43#include "stat-util.h"
8b43440b 44#include "string-table.h"
07630cea 45#include "string-util.h"
8e0b6570 46#include "strv.h"
a8fbdf54 47#include "time-util.h"
a5ecdf7c 48#include "vpick.h"
89a5a90c 49#include "xattr-util.h"
cd61c3bf 50
f7178a04 51const char* const image_search_path[_IMAGE_CLASS_MAX] = {
9bca4ae4
LP
52 [IMAGE_MACHINE] = "/etc/machines\0" /* only place symlinks here */
53 "/run/machines\0" /* and here too */
54 "/var/lib/machines\0" /* the main place for images */
55 "/var/lib/container\0" /* legacy */
56 "/usr/local/lib/machines\0"
57 "/usr/lib/machines\0",
5ef46e5f 58
9bca4ae4
LP
59 [IMAGE_PORTABLE] = "/etc/portables\0" /* only place symlinks here */
60 "/run/portables\0" /* and here too */
61 "/var/lib/portables\0" /* the main place for images */
62 "/usr/local/lib/portables\0"
63 "/usr/lib/portables\0",
64
de862276
LB
65 /* Note that we don't allow storing extensions under /usr/, unlike with other image types. That's
66 * because extension images are supposed to extend /usr/, so you get into recursive races, especially
67 * with directory-based extensions, as the kernel's OverlayFS explicitly checks for this and errors
68 * out with -ELOOP if it finds that a lowerdir= is a child of another lowerdir=. */
b60e0f57 69 [IMAGE_SYSEXT] = "/etc/extensions\0" /* only place symlinks here */
70 "/run/extensions\0" /* and here too */
71 "/var/lib/extensions\0", /* the main place for images */
72
73 [IMAGE_CONFEXT] = "/run/confexts\0" /* only place symlinks here */
74 "/var/lib/confexts\0" /* the main place for images */
75 "/usr/local/lib/confexts\0"
76 "/usr/lib/confexts\0",
5ef46e5f 77};
c2ce6a3d 78
8d07a8d6
VK
79/* Inside the initrd, use a slightly different set of search path (i.e. include .extra/sysext/,
80 * /.extra/global_sysext, .extra/confext/, and /.extra/global_confext in extension search dir) */
73740c9f
LP
81static const char* const image_search_path_initrd[_IMAGE_CLASS_MAX] = {
82 /* (entries that aren't listed here will get the same search path as for the non initrd-case) */
83
b151e696
LP
84 [IMAGE_SYSEXT] = "/etc/extensions\0" /* only place symlinks here */
85 "/run/extensions\0" /* and here too */
86 "/var/lib/extensions\0" /* the main place for images */
8d07a8d6
VK
87 "/.extra/sysext\0" /* put sysext (per-UKI and global) picked up by systemd-stub */
88 "/.extra/global_sysext\0", /* last, since not trusted */
d4fee894
LP
89
90 [IMAGE_CONFEXT] = "/run/confexts\0" /* only place symlinks here */
91 "/var/lib/confexts\0" /* the main place for images */
92 "/usr/local/lib/confexts\0"
8d07a8d6
VK
93 "/.extra/confext\0" /* put confext (per-UKI and global) picked up by systemd-stub */
94 "/.extra/global_confext\0", /* last, since not trusted. */
73740c9f
LP
95};
96
a747994b
LP
97static const char* image_class_suffix_table[_IMAGE_CLASS_MAX] = {
98 [IMAGE_SYSEXT] = ".sysext",
99 [IMAGE_CONFEXT] = ".confext",
100};
101
102DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(image_class_suffix, ImageClass);
103
7af5785d
LP
104static const char *const image_root_table[_IMAGE_CLASS_MAX] = {
105 [IMAGE_MACHINE] = "/var/lib/machines",
106 [IMAGE_PORTABLE] = "/var/lib/portables",
107 [IMAGE_SYSEXT] = "/var/lib/extensions",
108 [IMAGE_CONFEXT] = "/var/lib/confexts",
109};
110
111DEFINE_STRING_TABLE_LOOKUP_TO_STRING(image_root, ImageClass);
112
8b918a3a
LP
113static const char *const image_root_runtime_table[_IMAGE_CLASS_MAX] = {
114 [IMAGE_MACHINE] = "/run/machines",
115 [IMAGE_PORTABLE] = "/run/portables",
116 [IMAGE_SYSEXT] = "/run/extensions",
117 [IMAGE_CONFEXT] = "/run/confexts",
118};
119
120DEFINE_STRING_TABLE_LOOKUP_TO_STRING(image_root_runtime, ImageClass);
121
d654b9dc 122static Image* image_free(Image *i) {
8301aa0b 123 assert(i);
9614bb06 124
cd61c3bf
LP
125 free(i->name);
126 free(i->path);
c7664c07
LP
127
128 free(i->hostname);
129 strv_free(i->machine_info);
130 strv_free(i->os_release);
a81fe93e
LP
131 strv_free(i->sysext_release);
132 strv_free(i->confext_release);
c7664c07 133
6b430fdb 134 return mfree(i);
cd61c3bf
LP
135}
136
8301aa0b 137DEFINE_TRIVIAL_REF_UNREF_FUNC(Image, image, image_free);
b07ec5a1
YW
138DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(image_hash_ops, char, string_hash_func, string_compare_func,
139 Image, image_unref);
9614bb06 140
d654b9dc 141static char** image_settings_path(Image *image) {
8e0b6570 142 _cleanup_strv_free_ char **l = NULL;
162f6477
LP
143 _cleanup_free_ char *fn = NULL;
144 size_t i = 0;
145 int r;
8e0b6570
LP
146
147 assert(image);
148
149 l = new0(char*, 4);
150 if (!l)
151 return NULL;
152
162f6477
LP
153 fn = strjoin(image->name, ".nspawn");
154 if (!fn)
155 return NULL;
8e0b6570 156
b910cc72
LP
157 FOREACH_STRING(s, "/etc/systemd/nspawn", "/run/systemd/nspawn") {
158 l[i] = path_join(s, fn);
8e0b6570
LP
159 if (!l[i])
160 return NULL;
161
162 i++;
163 }
164
162f6477
LP
165 r = file_in_same_dir(image->path, fn, l + i);
166 if (r == -ENOMEM)
8e0b6570 167 return NULL;
162f6477
LP
168 if (r < 0)
169 log_debug_errno(r, "Failed to generate .nspawn settings path from image path, ignoring: %m");
170
171 strv_uniq(l);
8e0b6570 172
ae2a15bc 173 return TAKE_PTR(l);
8e0b6570
LP
174}
175
162f6477
LP
176static int image_roothash_path(Image *image, char **ret) {
177 _cleanup_free_ char *fn = NULL;
bafbac4e
LP
178
179 assert(image);
180
162f6477
LP
181 fn = strjoin(image->name, ".roothash");
182 if (!fn)
183 return -ENOMEM;
bafbac4e 184
162f6477 185 return file_in_same_dir(image->path, fn, ret);
bafbac4e
LP
186}
187
c2ce6a3d 188static int image_new(
cd61c3bf 189 ImageType t,
3775e141 190 ImageClass c,
5fc7f358 191 const char *pretty,
cd61c3bf 192 const char *path,
5fc7f358 193 const char *filename,
cd61c3bf 194 bool read_only,
10f9c755 195 usec_t crtime,
cd61c3bf 196 usec_t mtime,
c2ce6a3d 197 Image **ret) {
cd61c3bf
LP
198
199 _cleanup_(image_unrefp) Image *i = NULL;
cd61c3bf 200
cd61c3bf
LP
201 assert(t >= 0);
202 assert(t < _IMAGE_TYPE_MAX);
5fc7f358
LP
203 assert(pretty);
204 assert(filename);
c2ce6a3d 205 assert(ret);
cd61c3bf 206
c2108701 207 i = new(Image, 1);
cd61c3bf
LP
208 if (!i)
209 return -ENOMEM;
210
c2108701
LP
211 *i = (Image) {
212 .n_ref = 1,
213 .type = t,
3775e141 214 .class = c,
c2108701
LP
215 .read_only = read_only,
216 .crtime = crtime,
217 .mtime = mtime,
218 .usage = UINT64_MAX,
219 .usage_exclusive = UINT64_MAX,
220 .limit = UINT64_MAX,
221 .limit_exclusive = UINT64_MAX,
222 };
cd61c3bf 223
5fc7f358 224 i->name = strdup(pretty);
cd61c3bf
LP
225 if (!i->name)
226 return -ENOMEM;
227
657ee2d8 228 i->path = path_join(path, filename);
5fc7f358
LP
229 if (!i->path)
230 return -ENOMEM;
231
4ff361cc 232 path_simplify(i->path);
cd61c3bf 233
1cc6c93a 234 *ret = TAKE_PTR(i);
c2ce6a3d 235
cd61c3bf
LP
236 return 0;
237}
238
a5ecdf7c 239static int extract_image_basename(
a747994b 240 const char *path,
a5ecdf7c
LP
241 const char *class_suffix, /* e.g. ".sysext" (this is an optional suffix) */
242 char **format_suffixes, /* e.g. ".raw" (one of these will be required) */
243 char **ret_basename,
244 char **ret_suffix) {
a747994b 245
a5ecdf7c 246 _cleanup_free_ char *name = NULL, *suffix = NULL;
a747994b 247 int r;
4756c94e
LP
248
249 assert(path);
4756c94e 250
a747994b
LP
251 r = path_extract_filename(path, &name);
252 if (r < 0)
253 return r;
4756c94e 254
a5ecdf7c 255 if (format_suffixes) {
2e6f012b 256 char *e = endswith_strv(name, format_suffixes);
a747994b 257 if (!e) /* Format suffix is required */
4756c94e
LP
258 return -EINVAL;
259
a5ecdf7c
LP
260 if (ret_suffix) {
261 suffix = strdup(e);
262 if (!suffix)
263 return -ENOMEM;
264 }
265
4756c94e
LP
266 *e = 0;
267 }
268
a747994b
LP
269 if (class_suffix) {
270 char *e = endswith(name, class_suffix);
a5ecdf7c
LP
271 if (e) { /* Class suffix is optional */
272 if (ret_suffix) {
273 _cleanup_free_ char *j = strjoin(e, suffix);
274 if (!j)
275 return -ENOMEM;
276
277 free_and_replace(suffix, j);
278 }
279
a747994b 280 *e = 0;
a5ecdf7c 281 }
a747994b
LP
282 }
283
4756c94e
LP
284 if (!image_name_is_valid(name))
285 return -EINVAL;
286
a5ecdf7c
LP
287 if (ret_suffix)
288 *ret_suffix = TAKE_PTR(suffix);
289
290 if (ret_basename)
291 *ret_basename = TAKE_PTR(name);
292
4756c94e
LP
293 return 0;
294}
295
96ac6d3f
YW
296static int image_update_quota(Image *i, int fd) {
297 _cleanup_close_ int fd_close = -EBADF;
298 int r;
299
300 assert(i);
301
73053472 302 if (image_is_vendor(i) || image_is_host(i))
96ac6d3f
YW
303 return -EROFS;
304
305 if (i->type != IMAGE_SUBVOLUME)
306 return -EOPNOTSUPP;
307
308 if (fd < 0) {
476b7c3a 309 fd_close = open(i->path, O_CLOEXEC|O_DIRECTORY);
96ac6d3f
YW
310 if (fd_close < 0)
311 return -errno;
312 fd = fd_close;
476b7c3a
LP
313 } else {
314 /* Convert from O_PATH to proper fd, if needed */
315 fd = fd_reopen_condition(fd, O_CLOEXEC|O_DIRECTORY, O_PATH, &fd_close);
316 if (fd < 0)
317 return fd;
96ac6d3f
YW
318 }
319
320 r = btrfs_quota_scan_ongoing(fd);
321 if (r < 0)
322 return r;
323 if (r > 0)
324 return 0;
325
326 BtrfsQuotaInfo quota;
327 r = btrfs_subvol_get_subtree_quota_fd(fd, 0, &quota);
328 if (r < 0)
329 return r;
330
331 i->usage = quota.referenced;
332 i->usage_exclusive = quota.exclusive;
333 i->limit = quota.referenced_max;
334 i->limit_exclusive = quota.exclusive_max;
335
336 return 1;
337}
338
5fc7f358 339static int image_make(
3775e141 340 ImageClass c,
5fc7f358 341 const char *pretty,
98e28335
LP
342 int dir_fd,
343 const char *dir_path,
5fc7f358 344 const char *filename,
98e28335 345 int fd, /* O_PATH fd */
3a6ce860 346 const struct stat *st,
5fc7f358
LP
347 Image **ret) {
348
98e28335 349 _cleanup_free_ char *pretty_buffer = NULL;
5fc7f358 350 bool read_only;
cd61c3bf
LP
351 int r;
352
98e28335
LP
353 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
354 assert(dir_path || dir_fd == AT_FDCWD);
5fc7f358 355 assert(filename);
cd61c3bf 356
eb38edce 357 /* We explicitly *do* follow symlinks here, since we want to allow symlinking trees, raw files and block
3a6ce860
LP
358 * devices into /var/lib/machines/, and treat them normally.
359 *
360 * This function returns -ENOENT if we can't find the image after all, and -EMEDIUMTYPE if it's not a file we
361 * recognize. */
cd61c3bf 362
98e28335
LP
363 _cleanup_close_ int _fd = -EBADF;
364 if (fd < 0) {
365 /* If we didn't get an fd passed in, then let's pin it via O_PATH now */
366 _fd = openat(dir_fd, filename, O_PATH|O_CLOEXEC);
367 if (_fd < 0)
368 return -errno;
369
370 fd = _fd;
371 st = NULL; /* refresh stat() data now that we have the inode pinned */
372 }
373
374 struct stat stbuf;
3a6ce860 375 if (!st) {
98e28335 376 if (fstat(fd, &stbuf) < 0)
3a6ce860
LP
377 return -errno;
378
379 st = &stbuf;
380 }
cd61c3bf 381
98e28335
LP
382 _cleanup_free_ char *parent = NULL;
383 if (!dir_path) {
384 (void) fd_get_path(dir_fd, &parent);
385 dir_path = parent;
386 }
bcb846f3 387
5fc7f358 388 read_only =
98e28335
LP
389 (dir_path && path_startswith(dir_path, "/usr")) ||
390 (faccessat(fd, "", W_OK, AT_EACCESS|AT_EMPTY_PATH) < 0 && errno == EROFS);
86e339c8 391
3a6ce860 392 if (S_ISDIR(st->st_mode)) {
01b72568 393 unsigned file_attr = 0;
02dcf215 394 usec_t crtime = 0;
cd61c3bf 395
c2ce6a3d 396 if (!ret)
3a6ce860 397 return 0;
cd61c3bf 398
4756c94e 399 if (!pretty) {
a5ecdf7c
LP
400 r = extract_image_basename(
401 filename,
402 image_class_suffix_to_string(c),
f15dcafd 403 /* format_suffixes= */ NULL,
a5ecdf7c
LP
404 &pretty_buffer,
405 /* ret_suffix= */ NULL);
4756c94e
LP
406 if (r < 0)
407 return r;
408
409 pretty = pretty_buffer;
410 }
5fc7f358 411
674b04ff 412 if (btrfs_might_be_subvol(st)) {
cd61c3bf 413
65ddc2c5 414 r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
21222ea5
LP
415 if (r < 0)
416 return r;
79de6eb1 417 if (r > 0) {
10f9c755 418 BtrfsSubvolInfo info;
cd61c3bf 419
c2ce6a3d 420 /* It's a btrfs subvolume */
cd61c3bf 421
5bcd08db 422 r = btrfs_subvol_get_info_fd(fd, 0, &info);
10f9c755
LP
423 if (r < 0)
424 return r;
c2ce6a3d
LP
425
426 r = image_new(IMAGE_SUBVOLUME,
3775e141 427 c,
5fc7f358 428 pretty,
98e28335 429 dir_path,
5fc7f358
LP
430 filename,
431 info.read_only || read_only,
10f9c755 432 info.otime,
4b270252 433 info.ctime,
c2ce6a3d
LP
434 ret);
435 if (r < 0)
436 return r;
437
96ac6d3f 438 (void) image_update_quota(*ret, fd);
3a6ce860 439 return 0;
cd61c3bf 440 }
c2ce6a3d 441 }
cd61c3bf 442
02dcf215 443 /* Get directory creation time (not available everywhere, but that's OK */
12a7f04a 444 (void) fd_getcrtime(fd, &crtime);
02dcf215
LP
445
446 /* If the IMMUTABLE bit is set, we consider the directory read-only. Since the ioctl is not
01b72568
LP
447 * supported everywhere we ignore failures. */
448 (void) read_attr_fd(fd, &file_attr);
cd61c3bf 449
01b72568 450 /* It's just a normal directory. */
c2ce6a3d 451 r = image_new(IMAGE_DIRECTORY,
3775e141 452 c,
5fc7f358 453 pretty,
98e28335 454 dir_path,
5fc7f358 455 filename,
01b72568 456 read_only || (file_attr & FS_IMMUTABLE_FL),
02dcf215
LP
457 crtime,
458 0, /* we don't use mtime of stat() here, since it's not the time of last change of the tree, but only of the top-level dir */
c2ce6a3d
LP
459 ret);
460 if (r < 0)
461 return r;
cd61c3bf 462
3a6ce860 463 return 0;
cd61c3bf 464
3a6ce860 465 } else if (S_ISREG(st->st_mode) && endswith(filename, ".raw")) {
10f9c755 466 usec_t crtime = 0;
cd61c3bf 467
aceac2f0 468 /* It's a RAW disk image */
cd61c3bf 469
c2ce6a3d 470 if (!ret)
3a6ce860 471 return 0;
cd61c3bf 472
98e28335 473 (void) fd_getcrtime(fd, &crtime);
10f9c755 474
4756c94e 475 if (!pretty) {
a5ecdf7c
LP
476 r = extract_image_basename(
477 filename,
478 image_class_suffix_to_string(c),
479 STRV_MAKE(".raw"),
480 &pretty_buffer,
481 /* ret_suffix= */ NULL);
4756c94e
LP
482 if (r < 0)
483 return r;
484
485 pretty = pretty_buffer;
486 }
10f9c755 487
aceac2f0 488 r = image_new(IMAGE_RAW,
3775e141 489 c,
5fc7f358 490 pretty,
98e28335 491 dir_path,
5fc7f358 492 filename,
3a6ce860 493 !(st->st_mode & 0222) || read_only,
10f9c755 494 crtime,
3a6ce860 495 timespec_load(&st->st_mtim),
c2ce6a3d
LP
496 ret);
497 if (r < 0)
498 return r;
cd61c3bf 499
3a6ce860
LP
500 (*ret)->usage = (*ret)->usage_exclusive = st->st_blocks * 512;
501 (*ret)->limit = (*ret)->limit_exclusive = st->st_size;
b6b18498 502
3a6ce860 503 return 0;
eb38edce 504
3a6ce860 505 } else if (S_ISBLK(st->st_mode)) {
eb38edce
LP
506 uint64_t size = UINT64_MAX;
507
508 /* A block device */
509
510 if (!ret)
3a6ce860 511 return 0;
eb38edce 512
4756c94e 513 if (!pretty) {
a5ecdf7c
LP
514 r = extract_image_basename(
515 filename,
516 /* class_suffix= */ NULL,
517 /* format_suffix= */ NULL,
518 &pretty_buffer,
519 /* ret_suffix= */ NULL);
4756c94e
LP
520 if (r < 0)
521 return r;
522
523 pretty = pretty_buffer;
524 }
eb38edce 525
98e28335 526 _cleanup_close_ int block_fd = fd_reopen(fd, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
eb38edce 527 if (block_fd < 0)
98e28335 528 log_debug_errno(errno, "Failed to open block device %s/%s, ignoring: %m", strnull(dir_path), filename);
eb38edce 529 else {
eb38edce
LP
530 if (!read_only) {
531 int state = 0;
532
533 if (ioctl(block_fd, BLKROGET, &state) < 0)
98e28335 534 log_debug_errno(errno, "Failed to issue BLKROGET on device %s/%s, ignoring: %m", strnull(dir_path), filename);
eb38edce
LP
535 else if (state)
536 read_only = true;
537 }
538
01db9c85
LP
539 r = blockdev_get_device_size(block_fd, &size);
540 if (r < 0)
98e28335 541 log_debug_errno(r, "Failed to issue BLKGETSIZE64 on device %s/%s, ignoring: %m", strnull(dir_path), filename);
eb38edce
LP
542
543 block_fd = safe_close(block_fd);
544 }
545
546 r = image_new(IMAGE_BLOCK,
3775e141 547 c,
eb38edce 548 pretty,
98e28335 549 dir_path,
eb38edce 550 filename,
3a6ce860 551 !(st->st_mode & 0222) || read_only,
eb38edce
LP
552 0,
553 0,
554 ret);
555 if (r < 0)
556 return r;
557
ed0cb346 558 if (!IN_SET(size, 0, UINT64_MAX))
eb38edce
LP
559 (*ret)->usage = (*ret)->usage_exclusive = (*ret)->limit = (*ret)->limit_exclusive = size;
560
3a6ce860 561 return 0;
c2ce6a3d 562 }
cd61c3bf 563
3a6ce860 564 return -EMEDIUMTYPE;
c2ce6a3d 565}
cd61c3bf 566
1c0ade2e
LP
567static int pick_image_search_path(
568 RuntimeScope scope,
569 ImageClass class,
570 char ***ret) {
571
572 int r;
573
574 assert(scope < _RUNTIME_SCOPE_MAX && scope != RUNTIME_SCOPE_GLOBAL);
575 assert(class < _IMAGE_CLASS_MAX);
576 assert(ret);
577
578 if (class < 0) {
579 *ret = NULL;
580 return 0;
581 }
582
583 if (scope < 0) {
584 _cleanup_strv_free_ char **a = NULL, **b = NULL;
585
586 r = pick_image_search_path(RUNTIME_SCOPE_USER, class, &a);
587 if (r < 0)
588 return r;
589
590 r = pick_image_search_path(RUNTIME_SCOPE_SYSTEM, class, &b);
591 if (r < 0)
592 return r;
593
594 r = strv_extend_strv(&a, b, /* filter_duplicates= */ false);
595 if (r < 0)
596 return r;
597
598 *ret = TAKE_PTR(a);
599 return 0;
600 }
601
602 switch (scope) {
603
604 case RUNTIME_SCOPE_SYSTEM: {
605 const char *ns;
606 /* Use the initrd search path if there is one, otherwise use the common one */
607 ns = in_initrd() && image_search_path_initrd[class] ?
608 image_search_path_initrd[class] :
609 image_search_path[class];
610 if (!ns)
611 break;
612
613 _cleanup_strv_free_ char **search = strv_split_nulstr(ns);
614 if (!search)
615 return -ENOMEM;
616
617 *ret = TAKE_PTR(search);
618 return 0;
619 }
620
621 case RUNTIME_SCOPE_USER: {
622 if (class != IMAGE_MACHINE)
623 break;
624
625 static const uint64_t dirs[] = {
626 SD_PATH_USER_RUNTIME,
627 SD_PATH_USER_STATE_PRIVATE,
628 SD_PATH_USER_LIBRARY_PRIVATE,
629 };
73740c9f 630
1c0ade2e
LP
631 _cleanup_strv_free_ char **search = NULL;
632 FOREACH_ELEMENT(d, dirs) {
633 _cleanup_free_ char *p = NULL;
634
635 r = sd_path_lookup(*d, "machines", &p);
636 if (r == -ENXIO) /* No XDG_RUNTIME_DIR set */
637 continue;
638 if (r < 0)
639 return r;
640
641 r = strv_consume(&search, TAKE_PTR(p));
642 if (r < 0)
643 return r;
644 }
645
646 *ret = TAKE_PTR(search);
647 return 0;
648 }
649
650 default:
651 assert_not_reached();
652 }
653
654 *ret = NULL;
655 return 0;
73740c9f
LP
656}
657
d654b9dc 658static char** make_possible_filenames(ImageClass class, const char *image_name) {
a5ecdf7c
LP
659 _cleanup_strv_free_ char **l = NULL;
660
661 assert(image_name);
662
663 FOREACH_STRING(v_suffix, "", ".v")
664 FOREACH_STRING(format_suffix, "", ".raw") {
665 _cleanup_free_ char *j = NULL;
666 const char *class_suffix;
667
668 class_suffix = image_class_suffix_to_string(class);
669 if (class_suffix) {
670 j = strjoin(image_name, class_suffix, format_suffix, v_suffix);
671 if (!j)
672 return NULL;
673
674 if (strv_consume(&l, TAKE_PTR(j)) < 0)
675 return NULL;
676 }
677
678 j = strjoin(image_name, format_suffix, v_suffix);
679 if (!j)
680 return NULL;
681
682 if (strv_consume(&l, TAKE_PTR(j)) < 0)
683 return NULL;
684 }
685
686 return TAKE_PTR(l);
687}
688
1c0ade2e
LP
689int image_find(RuntimeScope scope,
690 ImageClass class,
d577d4a4
LP
691 const char *name,
692 const char *root,
693 Image **ret) {
694
98e28335
LP
695 /* As mentioned above, we follow symlinks on this fstatat(), because we want to permit people to
696 * symlink block devices into the search path. (For now, we disable that when operating relative to
697 * some root directory.) */
698 int open_flags = root ? O_NOFOLLOW : 0, r;
cd61c3bf 699
1c0ade2e 700 assert(scope < _RUNTIME_SCOPE_MAX && scope != RUNTIME_SCOPE_GLOBAL);
5ef46e5f
LP
701 assert(class >= 0);
702 assert(class < _IMAGE_CLASS_MAX);
c2ce6a3d 703 assert(name);
cd61c3bf 704
c2ce6a3d
LP
705 /* There are no images with invalid names */
706 if (!image_name_is_valid(name))
3a6ce860 707 return -ENOENT;
cd61c3bf 708
a5ecdf7c
LP
709 _cleanup_strv_free_ char **names = make_possible_filenames(class, name);
710 if (!names)
711 return -ENOMEM;
712
1c0ade2e
LP
713 _cleanup_strv_free_ char **search = NULL;
714 r = pick_image_search_path(scope, class, &search);
715 if (r < 0)
716 return r;
717
718 STRV_FOREACH(path, search) {
d577d4a4 719 _cleanup_free_ char *resolved = NULL;
c2ce6a3d 720 _cleanup_closedir_ DIR *d = NULL;
cd61c3bf 721
1c0ade2e 722 r = chase_and_opendir(*path, root, CHASE_PREFIX_ROOT, &resolved, &d);
d577d4a4
LP
723 if (r == -ENOENT)
724 continue;
725 if (r < 0)
726 return r;
cd61c3bf 727
a5ecdf7c
LP
728 STRV_FOREACH(n, names) {
729 _cleanup_free_ char *fname_buf = NULL;
730 const char *fname = *n;
3a6ce860 731
98e28335
LP
732 _cleanup_close_ int fd = openat(dirfd(d), fname, O_PATH|O_CLOEXEC|open_flags);
733 if (fd < 0) {
a5ecdf7c
LP
734 if (errno != ENOENT)
735 return -errno;
5fc7f358 736
98e28335 737 continue;
a5ecdf7c
LP
738 }
739
98e28335
LP
740 struct stat st;
741 if (fstat(fd, &st) < 0)
742 return -errno;
743
a5ecdf7c
LP
744 if (endswith(fname, ".raw")) {
745 if (!S_ISREG(st.st_mode)) {
746 log_debug("Ignoring non-regular file '%s' with .raw suffix.", fname);
3a6ce860 747 continue;
a5ecdf7c 748 }
3a6ce860 749
a5ecdf7c 750 } else if (endswith(fname, ".v")) {
3a6ce860 751
a5ecdf7c
LP
752 if (!S_ISDIR(st.st_mode)) {
753 log_debug("Ignoring non-directory file '%s' with .v suffix.", fname);
754 continue;
755 }
756
757 _cleanup_free_ char *suffix = NULL;
758 suffix = strdup(ASSERT_PTR(startswith(fname, name)));
759 if (!suffix)
760 return -ENOMEM;
761
762 *ASSERT_PTR(endswith(suffix, ".v")) = 0;
763
764 _cleanup_free_ char *vp = path_join(resolved, fname);
765 if (!vp)
766 return -ENOMEM;
767
768 PickFilter filter = {
769 .type_mask = endswith(suffix, ".raw") ? (UINT32_C(1) << DT_REG) | (UINT32_C(1) << DT_BLK) : (UINT32_C(1) << DT_DIR),
770 .basename = name,
771 .architecture = _ARCHITECTURE_INVALID,
421a4ba7 772 .suffix = STRV_MAKE(suffix),
a5ecdf7c
LP
773 };
774
775 _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
776 r = path_pick(root,
777 /* toplevel_fd= */ AT_FDCWD,
778 vp,
779 &filter,
780 PICK_ARCHITECTURE|PICK_TRIES,
781 &result);
782 if (r < 0) {
783 log_debug_errno(r, "Failed to pick versioned image on '%s', skipping: %m", vp);
784 continue;
785 }
786 if (!result.path) {
787 log_debug("Found versioned directory '%s', without matching entry, skipping: %m", vp);
788 continue;
789 }
790
791 /* Refresh the stat data for the discovered target */
792 st = result.st;
98e28335 793 fd = safe_close(fd);
a5ecdf7c
LP
794
795 _cleanup_free_ char *bn = NULL;
796 r = path_extract_filename(result.path, &bn);
797 if (r < 0) {
798 log_debug_errno(r, "Failed to extract basename of image path '%s', skipping: %m", result.path);
799 continue;
800 }
801
802 fname_buf = path_join(fname, bn);
803 if (!fname_buf)
804 return log_oom();
3a6ce860 805
a5ecdf7c 806 fname = fname_buf;
3a6ce860 807
a5ecdf7c
LP
808 } else if (!S_ISDIR(st.st_mode) && !S_ISBLK(st.st_mode)) {
809 log_debug("Ignoring non-directory and non-block device file '%s' without suffix.", fname);
3a6ce860 810 continue;
a5ecdf7c 811 }
3a6ce860 812
98e28335 813 r = image_make(class, name, dirfd(d), resolved, fname, fd, &st, ret);
a5ecdf7c
LP
814 if (IN_SET(r, -ENOENT, -EMEDIUMTYPE))
815 continue;
816 if (r < 0)
817 return r;
cd61c3bf 818
a5ecdf7c
LP
819 if (ret)
820 (*ret)->discoverable = true;
cf604fd4 821
a5ecdf7c
LP
822 return 1;
823 }
c2ce6a3d
LP
824 }
825
1c0ade2e 826 if (scope == RUNTIME_SCOPE_SYSTEM && class == IMAGE_MACHINE && streq(name, ".host")) {
98e28335
LP
827 r = image_make(class,
828 ".host",
829 /* dir_fd= */ AT_FDCWD,
830 /* dir_path= */ NULL,
831 /* filename= */ empty_to_root(root),
832 /* fd= */ -EBADF,
833 /* st= */ NULL,
834 ret);
cf604fd4
LP
835 if (r < 0)
836 return r;
837
838 if (ret)
839 (*ret)->discoverable = true;
840
a5ecdf7c 841 return 1;
cf604fd4 842 }
5fc7f358 843
3a6ce860 844 return -ENOENT;
c2ce6a3d
LP
845};
846
2ddf182b 847int image_from_path(const char *path, Image **ret) {
cf604fd4
LP
848
849 /* Note that we don't set the 'discoverable' field of the returned object, because we don't check here whether
850 * the image is in the image search path. And if it is we don't know if the path we used is actually not
3fe91079 851 * overridden by another, different image earlier in the search path */
cf604fd4 852
2ddf182b 853 if (path_equal(path, "/"))
98e28335
LP
854 return image_make(
855 IMAGE_MACHINE,
856 ".host",
857 /* dir_fd= */ AT_FDCWD,
858 /* dir_path= */ NULL,
859 /* filename= */ "/",
860 /* fd= */ -EBADF,
861 /* st= */ NULL,
862 ret);
863
864 return image_make(
865 _IMAGE_CLASS_INVALID,
866 /* pretty= */ NULL,
867 /* dir_fd= */ AT_FDCWD,
868 /* dir_path= */ NULL,
869 /* filename= */ path,
870 /* fd= */ -EBADF,
871 /* st= */ NULL,
872 ret);
2ddf182b
LP
873}
874
1c0ade2e
LP
875int image_find_harder(
876 RuntimeScope scope,
877 ImageClass class,
878 const char *name_or_path,
879 const char *root,
880 Image **ret) {
881
2ddf182b 882 if (image_name_is_valid(name_or_path))
1c0ade2e 883 return image_find(scope, class, name_or_path, root, ret);
2ddf182b
LP
884
885 return image_from_path(name_or_path, ret);
886}
887
d577d4a4 888int image_discover(
1c0ade2e 889 RuntimeScope scope,
d577d4a4
LP
890 ImageClass class,
891 const char *root,
624d3698 892 Hashmap **images) {
d577d4a4 893
98e28335
LP
894 /* As mentioned above, we follow symlinks on this fstatat(), because we want to permit people to
895 * symlink block devices into the search path. (For now, we disable that when operating relative to
896 * some root directory.) */
897 int open_flags = root ? O_NOFOLLOW : 0, r;
c2ce6a3d 898
1c0ade2e 899 assert(scope < _RUNTIME_SCOPE_MAX && scope != RUNTIME_SCOPE_GLOBAL);
5ef46e5f
LP
900 assert(class >= 0);
901 assert(class < _IMAGE_CLASS_MAX);
624d3698 902 assert(images);
c2ce6a3d 903
1c0ade2e
LP
904 _cleanup_strv_free_ char **search = NULL;
905 r = pick_image_search_path(scope, class, &search);
906 if (r < 0)
907 return r;
908
909 STRV_FOREACH(path, search) {
d577d4a4 910 _cleanup_free_ char *resolved = NULL;
c2ce6a3d 911 _cleanup_closedir_ DIR *d = NULL;
c2ce6a3d 912
1c0ade2e 913 r = chase_and_opendir(*path, root, CHASE_PREFIX_ROOT, &resolved, &d);
d577d4a4
LP
914 if (r == -ENOENT)
915 continue;
916 if (r < 0)
917 return r;
c2ce6a3d
LP
918
919 FOREACH_DIRENT_ALL(de, d, return -errno) {
a5ecdf7c 920 _cleanup_free_ char *pretty = NULL, *fname_buf = NULL;
c2ce6a3d 921 _cleanup_(image_unrefp) Image *image = NULL;
a5ecdf7c 922 const char *fname = de->d_name;
c2ce6a3d 923
a5ecdf7c 924 if (dot_or_dot_dot(fname))
c2ce6a3d
LP
925 continue;
926
98e28335
LP
927 _cleanup_close_ int fd = openat(dirfd(d), fname, O_PATH|O_CLOEXEC|open_flags);
928 if (fd < 0) {
929 if (errno != ENOENT)
930 return -errno;
3a6ce860 931
98e28335 932 continue; /* Vanished while we were looking at it */
3a6ce860
LP
933 }
934
98e28335
LP
935 struct stat st;
936 if (fstat(fd, &st) < 0)
937 return -errno;
938
a5ecdf7c
LP
939 if (S_ISREG(st.st_mode)) {
940 r = extract_image_basename(
941 fname,
942 image_class_suffix_to_string(class),
943 STRV_MAKE(".raw"),
944 &pretty,
f15dcafd 945 /* ret_suffix= */ NULL);
a5ecdf7c
LP
946 if (r < 0) {
947 log_debug_errno(r, "Skipping directory entry '%s', which doesn't look like an image.", fname);
948 continue;
949 }
950 } else if (S_ISDIR(st.st_mode)) {
951 const char *v;
952
953 v = endswith(fname, ".v");
954 if (v) {
955 _cleanup_free_ char *suffix = NULL, *nov = NULL;
956
957 nov = strndup(fname, v - fname); /* Chop off the .v */
958 if (!nov)
959 return -ENOMEM;
960
961 r = extract_image_basename(
962 nov,
963 image_class_suffix_to_string(class),
964 STRV_MAKE(".raw", ""),
965 &pretty,
966 &suffix);
967 if (r < 0) {
968 log_debug_errno(r, "Skipping directory entry '%s', which doesn't look like a versioned image.", fname);
969 continue;
970 }
971
972 _cleanup_free_ char *vp = path_join(resolved, fname);
973 if (!vp)
974 return -ENOMEM;
975
976 PickFilter filter = {
977 .type_mask = endswith(suffix, ".raw") ? (UINT32_C(1) << DT_REG) | (UINT32_C(1) << DT_BLK) : (UINT32_C(1) << DT_DIR),
978 .basename = pretty,
979 .architecture = _ARCHITECTURE_INVALID,
421a4ba7 980 .suffix = STRV_MAKE(suffix),
a5ecdf7c
LP
981 };
982
983 _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
984 r = path_pick(root,
985 /* toplevel_fd= */ AT_FDCWD,
986 vp,
987 &filter,
988 PICK_ARCHITECTURE|PICK_TRIES,
989 &result);
990 if (r < 0) {
991 log_debug_errno(r, "Failed to pick versioned image on '%s', skipping: %m", vp);
992 continue;
993 }
994 if (!result.path) {
995 log_debug("Found versioned directory '%s', without matching entry, skipping: %m", vp);
996 continue;
997 }
998
999 /* Refresh the stat data for the discovered target */
1000 st = result.st;
98e28335 1001 fd = safe_close(fd);
a5ecdf7c
LP
1002
1003 _cleanup_free_ char *bn = NULL;
1004 r = path_extract_filename(result.path, &bn);
1005 if (r < 0) {
1006 log_debug_errno(r, "Failed to extract basename of image path '%s', skipping: %m", result.path);
1007 continue;
1008 }
1009
1010 fname_buf = path_join(fname, bn);
1011 if (!fname_buf)
1012 return log_oom();
1013
1014 fname = fname_buf;
1015 } else {
1016 r = extract_image_basename(
1017 fname,
1018 image_class_suffix_to_string(class),
f15dcafd 1019 /* format_suffixes= */ NULL,
a5ecdf7c
LP
1020 &pretty,
1021 /* ret_suffix= */ NULL);
1022 if (r < 0) {
1023 log_debug_errno(r, "Skipping directory entry '%s', which doesn't look like an image.", fname);
1024 continue;
1025 }
1026 }
1027
1028 } else if (S_ISBLK(st.st_mode)) {
1029 r = extract_image_basename(
1030 fname,
1031 /* class_suffix= */ NULL,
1032 /* format_suffix= */ NULL,
1033 &pretty,
f15dcafd 1034 /* ret_suffix= */ NULL);
a5ecdf7c
LP
1035 if (r < 0) {
1036 log_debug_errno(r, "Skipping directory entry '%s', which doesn't look like an image.", fname);
1037 continue;
1038 }
1039 } else {
1040 log_debug("Skipping directory entry '%s', which is neither regular file, directory nor block device.", fname);
1bf36bf9 1041 continue;
e7df707b 1042 }
1bf36bf9 1043
624d3698 1044 if (hashmap_contains(*images, pretty))
c2ce6a3d
LP
1045 continue;
1046
98e28335 1047 r = image_make(class, pretty, dirfd(d), resolved, fname, fd, &st, &image);
3a6ce860 1048 if (IN_SET(r, -ENOENT, -EMEDIUMTYPE))
c2ce6a3d
LP
1049 continue;
1050 if (r < 0)
1051 return r;
1052
cf604fd4
LP
1053 image->discoverable = true;
1054
624d3698 1055 r = hashmap_ensure_put(images, &image_hash_ops, image->name, image);
c2ce6a3d
LP
1056 if (r < 0)
1057 return r;
1058
5df1a553 1059 TAKE_PTR(image);
cd61c3bf
LP
1060 }
1061 }
1062
624d3698 1063 if (scope == RUNTIME_SCOPE_SYSTEM && class == IMAGE_MACHINE && !hashmap_contains(*images, ".host")) {
5fc7f358
LP
1064 _cleanup_(image_unrefp) Image *image = NULL;
1065
98e28335
LP
1066 r = image_make(IMAGE_MACHINE,
1067 ".host",
1068 /* dir_fd= */ AT_FDCWD,
1069 /* dir_path= */ NULL,
1070 empty_to_root(root),
1071 /* fd= */ -EBADF,
1072 /* st= */ NULL,
1073 &image);
5fc7f358
LP
1074 if (r < 0)
1075 return r;
1076
cf604fd4
LP
1077 image->discoverable = true;
1078
624d3698 1079 r = hashmap_ensure_put(images, &image_hash_ops, image->name, image);
5fc7f358
LP
1080 if (r < 0)
1081 return r;
1082
1083 image = NULL;
5fc7f358
LP
1084 }
1085
cd61c3bf
LP
1086 return 0;
1087}
1088
08682124 1089int image_remove(Image *i) {
8e766630 1090 _cleanup_(release_lock_file) LockFile global_lock = LOCK_FILE_INIT, local_lock = LOCK_FILE_INIT;
8e0b6570 1091 _cleanup_strv_free_ char **settings = NULL;
bafbac4e 1092 _cleanup_free_ char *roothash = NULL;
30535c16
LP
1093 int r;
1094
08682124
LP
1095 assert(i);
1096
73053472 1097 if (image_is_vendor(i) || image_is_host(i))
08682124
LP
1098 return -EROFS;
1099
8e0b6570
LP
1100 settings = image_settings_path(i);
1101 if (!settings)
1102 return -ENOMEM;
1103
162f6477
LP
1104 r = image_roothash_path(i, &roothash);
1105 if (r < 0)
1106 return r;
bafbac4e 1107
30535c16
LP
1108 /* Make sure we don't interfere with a running nspawn */
1109 r = image_path_lock(i->path, LOCK_EX|LOCK_NB, &global_lock, &local_lock);
1110 if (r < 0)
1111 return r;
1112
ebd93cb6
LP
1113 switch (i->type) {
1114
1115 case IMAGE_SUBVOLUME:
9fb0b9c7
LP
1116
1117 /* Let's unlink first, maybe it is a symlink? If that works we are happy. Otherwise, let's get out the
1118 * big guns */
1119 if (unlink(i->path) < 0) {
1120 r = btrfs_subvol_remove(i->path, BTRFS_REMOVE_RECURSIVE|BTRFS_REMOVE_QUOTA);
1121 if (r < 0)
1122 return r;
1123 }
1124
8e0b6570 1125 break;
ebd93cb6
LP
1126
1127 case IMAGE_DIRECTORY:
01b72568 1128 /* Allow deletion of read-only directories */
a997f338 1129 (void) chattr_path(i->path, 0, FS_IMMUTABLE_FL);
8e0b6570
LP
1130 r = rm_rf(i->path, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_SUBVOLUME);
1131 if (r < 0)
1132 return r;
1133
1134 break;
01b72568 1135
eb38edce
LP
1136 case IMAGE_BLOCK:
1137
1138 /* If this is inside of /dev, then it's a real block device, hence let's not touch the device node
1139 * itself (but let's remove the stuff stored alongside it). If it's anywhere else, let's try to unlink
1140 * the thing (it's most likely a symlink after all). */
1141
1142 if (path_startswith(i->path, "/dev"))
1143 break;
1144
4831981d 1145 _fallthrough_;
aceac2f0 1146 case IMAGE_RAW:
41d1ed05
LP
1147 if (unlink(i->path) < 0)
1148 return -errno;
8e0b6570 1149 break;
ebd93cb6
LP
1150
1151 default:
15411c0c 1152 return -EOPNOTSUPP;
ebd93cb6 1153 }
8e0b6570 1154
de010b0b 1155 STRV_FOREACH(j, settings)
8e0b6570
LP
1156 if (unlink(*j) < 0 && errno != ENOENT)
1157 log_debug_errno(errno, "Failed to unlink %s, ignoring: %m", *j);
8e0b6570 1158
bafbac4e
LP
1159 if (unlink(roothash) < 0 && errno != ENOENT)
1160 log_debug_errno(errno, "Failed to unlink %s, ignoring: %m", roothash);
1161
8e0b6570
LP
1162 return 0;
1163}
1164
bafbac4e 1165static int rename_auxiliary_file(const char *path, const char *new_name, const char *suffix) {
162f6477
LP
1166 _cleanup_free_ char *fn = NULL, *rs = NULL;
1167 int r;
8e0b6570 1168
162f6477
LP
1169 fn = strjoin(new_name, suffix);
1170 if (!fn)
8e0b6570
LP
1171 return -ENOMEM;
1172
162f6477
LP
1173 r = file_in_same_dir(path, fn, &rs);
1174 if (r < 0)
1175 return r;
1176
8e0b6570 1177 return rename_noreplace(AT_FDCWD, path, AT_FDCWD, rs);
ebd93cb6
LP
1178}
1179
1c0ade2e 1180int image_rename(Image *i, const char *new_name, RuntimeScope scope) {
8e766630 1181 _cleanup_(release_lock_file) LockFile global_lock = LOCK_FILE_INIT, local_lock = LOCK_FILE_INIT, name_lock = LOCK_FILE_INIT;
bafbac4e 1182 _cleanup_free_ char *new_path = NULL, *nn = NULL, *roothash = NULL;
8e0b6570 1183 _cleanup_strv_free_ char **settings = NULL;
01b72568 1184 unsigned file_attr = 0;
ebd93cb6
LP
1185 int r;
1186
1187 assert(i);
1188
1189 if (!image_name_is_valid(new_name))
1190 return -EINVAL;
1191
73053472 1192 if (image_is_vendor(i) || image_is_host(i))
ebd93cb6
LP
1193 return -EROFS;
1194
8e0b6570
LP
1195 settings = image_settings_path(i);
1196 if (!settings)
1197 return -ENOMEM;
1198
162f6477
LP
1199 r = image_roothash_path(i, &roothash);
1200 if (r < 0)
1201 return r;
bafbac4e 1202
30535c16
LP
1203 /* Make sure we don't interfere with a running nspawn */
1204 r = image_path_lock(i->path, LOCK_EX|LOCK_NB, &global_lock, &local_lock);
1205 if (r < 0)
1206 return r;
1207
1208 /* Make sure nobody takes the new name, between the time we
1209 * checked it is currently unused in all search paths, and the
f8e2f4d6 1210 * time we take possession of it */
30535c16
LP
1211 r = image_name_lock(new_name, LOCK_EX|LOCK_NB, &name_lock);
1212 if (r < 0)
1213 return r;
1214
1c0ade2e 1215 r = image_find(scope, IMAGE_MACHINE, new_name, NULL, NULL);
3a6ce860 1216 if (r >= 0)
ebd93cb6 1217 return -EEXIST;
3a6ce860
LP
1218 if (r != -ENOENT)
1219 return r;
ebd93cb6
LP
1220
1221 switch (i->type) {
1222
ebd93cb6 1223 case IMAGE_DIRECTORY:
01b72568 1224 /* Turn of the immutable bit while we rename the image, so that we can rename it */
5e496845 1225 (void) read_attr_at(AT_FDCWD, i->path, &file_attr);
01b72568
LP
1226
1227 if (file_attr & FS_IMMUTABLE_FL)
a997f338 1228 (void) chattr_path(i->path, 0, FS_IMMUTABLE_FL);
01b72568 1229
4831981d 1230 _fallthrough_;
01b72568 1231 case IMAGE_SUBVOLUME:
162f6477 1232 r = file_in_same_dir(i->path, new_name, &new_path);
ebd93cb6
LP
1233 break;
1234
eb38edce
LP
1235 case IMAGE_BLOCK:
1236
1237 /* Refuse renaming raw block devices in /dev, the names are picked by udev after all. */
1238 if (path_startswith(i->path, "/dev"))
1239 return -EROFS;
1240
162f6477 1241 r = file_in_same_dir(i->path, new_name, &new_path);
eb38edce
LP
1242 break;
1243
aceac2f0 1244 case IMAGE_RAW: {
ebd93cb6
LP
1245 const char *fn;
1246
63c372cb 1247 fn = strjoina(new_name, ".raw");
162f6477
LP
1248
1249 r = file_in_same_dir(i->path, fn, &new_path);
ebd93cb6
LP
1250 break;
1251 }
1252
1253 default:
15411c0c 1254 return -EOPNOTSUPP;
ebd93cb6 1255 }
162f6477
LP
1256 if (r < 0)
1257 return r;
ebd93cb6
LP
1258
1259 nn = strdup(new_name);
1260 if (!nn)
1261 return -ENOMEM;
1262
f85ef957
AC
1263 r = rename_noreplace(AT_FDCWD, i->path, AT_FDCWD, new_path);
1264 if (r < 0)
1265 return r;
ebd93cb6 1266
01b72568
LP
1267 /* Restore the immutable bit, if it was set before */
1268 if (file_attr & FS_IMMUTABLE_FL)
a997f338 1269 (void) chattr_path(new_path, FS_IMMUTABLE_FL, FS_IMMUTABLE_FL);
01b72568 1270
f9ecfd3b
DL
1271 free_and_replace(i->path, new_path);
1272 free_and_replace(i->name, nn);
ebd93cb6 1273
8e0b6570 1274 STRV_FOREACH(j, settings) {
bafbac4e 1275 r = rename_auxiliary_file(*j, new_name, ".nspawn");
8e0b6570
LP
1276 if (r < 0 && r != -ENOENT)
1277 log_debug_errno(r, "Failed to rename settings file %s, ignoring: %m", *j);
1278 }
1279
bafbac4e
LP
1280 r = rename_auxiliary_file(roothash, new_name, ".roothash");
1281 if (r < 0 && r != -ENOENT)
1282 log_debug_errno(r, "Failed to rename roothash file %s, ignoring: %m", roothash);
1283
ebd93cb6
LP
1284 return 0;
1285}
1286
bafbac4e 1287static int clone_auxiliary_file(const char *path, const char *new_name, const char *suffix) {
162f6477
LP
1288 _cleanup_free_ char *fn = NULL, *rs = NULL;
1289 int r;
8e0b6570 1290
162f6477
LP
1291 fn = strjoin(new_name, suffix);
1292 if (!fn)
8e0b6570
LP
1293 return -ENOMEM;
1294
162f6477
LP
1295 r = file_in_same_dir(path, fn, &rs);
1296 if (r < 0)
1297 return r;
1298
7c2f5495 1299 return copy_file_atomic(path, rs, 0664, COPY_REFLINK);
8e0b6570
LP
1300}
1301
1c0ade2e 1302int image_clone(Image *i, const char *new_name, bool read_only, RuntimeScope scope) {
8e766630 1303 _cleanup_(release_lock_file) LockFile name_lock = LOCK_FILE_INIT;
8e0b6570 1304 _cleanup_strv_free_ char **settings = NULL;
bafbac4e 1305 _cleanup_free_ char *roothash = NULL;
ebd93cb6
LP
1306 const char *new_path;
1307 int r;
1308
1309 assert(i);
1310
1311 if (!image_name_is_valid(new_name))
1312 return -EINVAL;
1313
8e0b6570
LP
1314 settings = image_settings_path(i);
1315 if (!settings)
1316 return -ENOMEM;
1317
162f6477
LP
1318 r = image_roothash_path(i, &roothash);
1319 if (r < 0)
1320 return r;
bafbac4e 1321
30535c16
LP
1322 /* Make sure nobody takes the new name, between the time we
1323 * checked it is currently unused in all search paths, and the
f8e2f4d6 1324 * time we take possession of it */
30535c16
LP
1325 r = image_name_lock(new_name, LOCK_EX|LOCK_NB, &name_lock);
1326 if (r < 0)
1327 return r;
1328
1c0ade2e 1329 r = image_find(scope, IMAGE_MACHINE, new_name, NULL, NULL);
3a6ce860 1330 if (r >= 0)
ebd93cb6 1331 return -EEXIST;
3a6ce860
LP
1332 if (r != -ENOENT)
1333 return r;
ebd93cb6
LP
1334
1335 switch (i->type) {
1336
1337 case IMAGE_SUBVOLUME:
1338 case IMAGE_DIRECTORY:
9a50e3ca 1339 /* If we can we'll always try to create a new btrfs subvolume here, even if the source is a plain
13e785f7 1340 * directory. */
9a50e3ca 1341
63c372cb 1342 new_path = strjoina("/var/lib/machines/", new_name);
ebd93cb6 1343
fab4ef72
DDM
1344 r = btrfs_subvol_snapshot_at(AT_FDCWD, i->path, AT_FDCWD, new_path,
1345 (read_only ? BTRFS_SNAPSHOT_READ_ONLY : 0) |
1346 BTRFS_SNAPSHOT_FALLBACK_COPY |
1347 BTRFS_SNAPSHOT_FALLBACK_DIRECTORY |
1348 BTRFS_SNAPSHOT_FALLBACK_IMMUTABLE |
1349 BTRFS_SNAPSHOT_RECURSIVE |
1350 BTRFS_SNAPSHOT_QUOTA);
17cbb288 1351 if (r >= 0)
9a50e3ca 1352 /* Enable "subtree" quotas for the copy, if we didn't copy any quota from the source. */
8120ee28 1353 (void) btrfs_subvol_auto_qgroup(new_path, 0, true);
5bcd08db 1354
ebd93cb6
LP
1355 break;
1356
aceac2f0 1357 case IMAGE_RAW:
63c372cb 1358 new_path = strjoina("/var/lib/machines/", new_name, ".raw");
ebd93cb6 1359
b1cfa930
DDM
1360 r = copy_file_atomic(i->path, new_path, read_only ? 0444 : 0644,
1361 COPY_REFLINK|COPY_CRTIME|COPY_NOCOW_AFTER);
ebd93cb6
LP
1362 break;
1363
eb38edce 1364 case IMAGE_BLOCK:
ebd93cb6 1365 default:
15411c0c 1366 return -EOPNOTSUPP;
ebd93cb6
LP
1367 }
1368
1369 if (r < 0)
1370 return r;
1371
8e0b6570 1372 STRV_FOREACH(j, settings) {
bafbac4e 1373 r = clone_auxiliary_file(*j, new_name, ".nspawn");
8e0b6570
LP
1374 if (r < 0 && r != -ENOENT)
1375 log_debug_errno(r, "Failed to clone settings %s, ignoring: %m", *j);
1376 }
1377
bafbac4e
LP
1378 r = clone_auxiliary_file(roothash, new_name, ".roothash");
1379 if (r < 0 && r != -ENOENT)
1380 log_debug_errno(r, "Failed to clone root hash file %s, ignoring: %m", roothash);
1381
ebd93cb6
LP
1382 return 0;
1383}
1384
1385int image_read_only(Image *i, bool b) {
8e766630 1386 _cleanup_(release_lock_file) LockFile global_lock = LOCK_FILE_INIT, local_lock = LOCK_FILE_INIT;
ebd93cb6 1387 int r;
c7664c07 1388
ebd93cb6
LP
1389 assert(i);
1390
73053472 1391 if (image_is_vendor(i) || image_is_host(i))
ebd93cb6
LP
1392 return -EROFS;
1393
30535c16
LP
1394 /* Make sure we don't interfere with a running nspawn */
1395 r = image_path_lock(i->path, LOCK_EX|LOCK_NB, &global_lock, &local_lock);
1396 if (r < 0)
1397 return r;
1398
ebd93cb6
LP
1399 switch (i->type) {
1400
1401 case IMAGE_SUBVOLUME:
5bcd08db
LP
1402
1403 /* Note that we set the flag only on the top-level
1404 * subvolume of the image. */
1405
ebd93cb6
LP
1406 r = btrfs_subvol_set_read_only(i->path, b);
1407 if (r < 0)
1408 return r;
01b72568
LP
1409
1410 break;
1411
1412 case IMAGE_DIRECTORY:
1413 /* For simple directory trees we cannot use the access
1414 mode of the top-level directory, since it has an
1415 effect on the container itself. However, we can
1416 use the "immutable" flag, to at least make the
1417 top-level directory read-only. It's not as good as
1418 a read-only subvolume, but at least something, and
13e785f7 1419 we can read the value back. */
01b72568 1420
a997f338 1421 r = chattr_path(i->path, b ? FS_IMMUTABLE_FL : 0, FS_IMMUTABLE_FL);
01b72568
LP
1422 if (r < 0)
1423 return r;
1424
ebd93cb6
LP
1425 break;
1426
aceac2f0 1427 case IMAGE_RAW: {
ebd93cb6
LP
1428 struct stat st;
1429
1430 if (stat(i->path, &st) < 0)
1431 return -errno;
1432
1433 if (chmod(i->path, (st.st_mode & 0444) | (b ? 0000 : 0200)) < 0)
1434 return -errno;
f2068bcc
LP
1435
1436 /* If the images is now read-only, it's a good time to
1437 * defrag it, given that no write patterns will
1438 * fragment it again. */
1439 if (b)
1440 (void) btrfs_defrag(i->path);
ebd93cb6
LP
1441 break;
1442 }
1443
eb38edce 1444 case IMAGE_BLOCK: {
254d1313 1445 _cleanup_close_ int fd = -EBADF;
eb38edce
LP
1446 struct stat st;
1447 int state = b;
1448
1449 fd = open(i->path, O_CLOEXEC|O_RDONLY|O_NONBLOCK|O_NOCTTY);
1450 if (fd < 0)
1451 return -errno;
1452
1453 if (fstat(fd, &st) < 0)
1454 return -errno;
1455 if (!S_ISBLK(st.st_mode))
1456 return -ENOTTY;
1457
1458 if (ioctl(fd, BLKROSET, &state) < 0)
1459 return -errno;
1460
1461 break;
1462 }
1463
ebd93cb6 1464 default:
15411c0c 1465 return -EOPNOTSUPP;
ebd93cb6
LP
1466 }
1467
608c321f 1468 i->read_only = b;
ebd93cb6 1469 return 0;
08682124
LP
1470}
1471
8759bc95
LP
1472static void make_lock_dir(void) {
1473 (void) mkdir_p("/run/systemd/nspawn", 0755);
1474 (void) mkdir("/run/systemd/nspawn/locks", 0700);
1475}
1476
cb1b813f
LP
1477int image_path_lock(
1478 const char *path,
1479 int operation,
1480 LockFile *ret_global,
1481 LockFile *ret_local) {
1482
30535c16
LP
1483 _cleanup_free_ char *p = NULL;
1484 LockFile t = LOCK_FILE_INIT;
1485 struct stat st;
f25bed67 1486 bool exclusive;
30535c16
LP
1487 int r;
1488
1489 assert(path);
cb1b813f 1490 assert(ret_local);
30535c16 1491
f25bed67
LP
1492 /* Locks an image path. This actually creates two locks: one "local" one, next to the image path
1493 * itself, which might be shared via NFS. And another "global" one, in /run, that uses the
1494 * device/inode number. This has the benefit that we can even lock a tree that is a mount point,
1495 * correctly. */
30535c16 1496
30535c16
LP
1497 if (!path_is_absolute(path))
1498 return -EINVAL;
1499
f25bed67
LP
1500 switch (operation & (LOCK_SH|LOCK_EX)) {
1501 case LOCK_SH:
1502 exclusive = false;
1503 break;
1504 case LOCK_EX:
1505 exclusive = true;
1506 break;
1507 default:
1508 return -EINVAL;
1509 }
1510
b6e953f2 1511 if (getenv_bool("SYSTEMD_NSPAWN_LOCK") == 0) {
cb1b813f
LP
1512 *ret_local = LOCK_FILE_INIT;
1513 if (ret_global)
1514 *ret_global = LOCK_FILE_INIT;
b6e953f2
LP
1515 return 0;
1516 }
1517
f25bed67
LP
1518 /* Prohibit taking exclusive locks on the host image. We can't allow this, since we ourselves are
1519 * running off it after all, and we don't want any images to manipulate the host image. We make an
1520 * exception for shared locks however: we allow those (and make them NOPs since there's no point in
1521 * taking them if there can't be exclusive locks). Strictly speaking these are questionable as well,
1522 * since it means changes made to the host might propagate to the container as they happen (and a
1523 * shared lock kinda suggests that no changes happen at all while it is in place), but it's too
1524 * useful not to allow read-only containers off the host root, hence let's support this, and trust
1525 * the user to do the right thing with this. */
1526 if (path_equal(path, "/")) {
1527 if (exclusive)
1528 return -EBUSY;
1529
cb1b813f
LP
1530 *ret_local = LOCK_FILE_INIT;
1531 if (ret_global)
1532 *ret_global = LOCK_FILE_INIT;
f25bed67
LP
1533 return 0;
1534 }
b6e953f2 1535
cb1b813f
LP
1536 if (ret_global) {
1537 if (stat(path, &st) >= 0) {
1538 if (S_ISBLK(st.st_mode))
1539 r = asprintf(&p, "/run/systemd/nspawn/locks/block-%u:%u", major(st.st_rdev), minor(st.st_rdev));
1540 else if (S_ISDIR(st.st_mode) || S_ISREG(st.st_mode))
1541 r = asprintf(&p, "/run/systemd/nspawn/locks/inode-%lu:%lu", (unsigned long) st.st_dev, (unsigned long) st.st_ino);
1542 else
1543 return -ENOTTY;
1544 if (r < 0)
1545 return -ENOMEM;
1546 }
30535c16
LP
1547 }
1548
f25bed67
LP
1549 /* For block devices we don't need the "local" lock, as the major/minor lock above should be
1550 * sufficient, since block devices are host local anyway. */
1551 if (!path_startswith(path, "/dev/")) {
eb38edce 1552 r = make_lock_file_for(path, operation, &t);
8be17c9b 1553 if (r < 0) {
f25bed67 1554 if (!exclusive && r == -EROFS)
771b7ead 1555 log_debug_errno(r, "Failed to create shared lock for '%s', ignoring: %m", path);
8be17c9b
LT
1556 else
1557 return r;
1558 }
eb38edce 1559 }
30535c16
LP
1560
1561 if (p) {
8759bc95 1562 make_lock_dir();
30535c16 1563
cb1b813f 1564 r = make_lock_file(p, operation, ret_global);
30535c16
LP
1565 if (r < 0) {
1566 release_lock_file(&t);
1567 return r;
1568 }
cb1b813f
LP
1569 } else if (ret_global)
1570 *ret_global = LOCK_FILE_INIT;
30535c16 1571
cb1b813f 1572 *ret_local = t;
30535c16
LP
1573 return 0;
1574}
1575
cb81cd80 1576int image_set_limit(Image *i, uint64_t referenced_max) {
96ac6d3f
YW
1577 int r;
1578
d6ce17c7
LP
1579 assert(i);
1580
73053472 1581 if (image_is_vendor(i) || image_is_host(i))
d6ce17c7
LP
1582 return -EROFS;
1583
1584 if (i->type != IMAGE_SUBVOLUME)
15411c0c 1585 return -EOPNOTSUPP;
d6ce17c7 1586
5bcd08db
LP
1587 /* We set the quota both for the subvolume as well as for the
1588 * subtree. The latter is mostly for historical reasons, since
1589 * we didn't use to have a concept of subtree quota, and hence
1590 * only modified the subvolume quota. */
1591
1592 (void) btrfs_qgroup_set_limit(i->path, 0, referenced_max);
1593 (void) btrfs_subvol_auto_qgroup(i->path, 0, true);
96ac6d3f
YW
1594 r = btrfs_subvol_set_subtree_quota_limit(i->path, 0, referenced_max);
1595 if (r < 0)
1596 return r;
1597
1598 (void) image_update_quota(i, -EBADF);
1599 return 0;
d6ce17c7
LP
1600}
1601
42f2740a
IK
1602int image_set_pool_limit(ImageClass class, uint64_t referenced_max) {
1603 const char *dir;
1604 int r;
1605
1606 assert(class >= 0 && class < _IMAGE_CLASS_MAX);
1607
1608 dir = image_root_to_string(class);
1609
1610 r = btrfs_qgroup_set_limit(dir, /* qgroupid = */ 0, referenced_max);
1611 if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
1612 return r;
1613 if (r < 0)
1614 log_debug_errno(r, "Failed to set limit on btrfs quota group for '%s', ignoring: %m", dir);
1615
1616 r = btrfs_subvol_set_subtree_quota_limit(dir, /* subvol_id = */ 0, referenced_max);
1617 if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
1618 return r;
1619 if (r < 0)
1620 return log_debug_errno(r, "Failed to set subtree quota limit for '%s': %m", dir);
1621
1622 return 0;
1623}
1624
84be0c71 1625int image_read_metadata(Image *i, const ImagePolicy *image_policy) {
8e766630 1626 _cleanup_(release_lock_file) LockFile global_lock = LOCK_FILE_INIT, local_lock = LOCK_FILE_INIT;
c7664c07
LP
1627 int r;
1628
1629 assert(i);
1630
1631 r = image_path_lock(i->path, LOCK_SH|LOCK_NB, &global_lock, &local_lock);
1632 if (r < 0)
1633 return r;
1634
1635 switch (i->type) {
1636
1637 case IMAGE_SUBVOLUME:
1638 case IMAGE_DIRECTORY: {
a81fe93e
LP
1639 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL, **sysext_release = NULL, **confext_release = NULL;
1640 _cleanup_free_ char *hostname = NULL, *path = NULL;
c7664c07 1641 sd_id128_t machine_id = SD_ID128_NULL;
c7664c07 1642
b60e0f57 1643 if (i->class == IMAGE_SYSEXT) {
6afa5d86
LB
1644 r = extension_has_forbidden_content(i->path);
1645 if (r < 0)
1646 return r;
1647 if (r > 0)
1648 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM),
1649 "Conflicting content found in image %s, refusing.",
1650 i->name);
1651 }
1652
f461a28d 1653 r = chase("/etc/hostname", i->path, CHASE_PREFIX_ROOT|CHASE_TRAIL_SLASH, &path, NULL);
c7664c07
LP
1654 if (r < 0 && r != -ENOENT)
1655 log_debug_errno(r, "Failed to chase /etc/hostname in image %s: %m", i->name);
1656 else if (r >= 0) {
af9c45d5 1657 r = read_etc_hostname(path, /* substitute_wildcards= */ false, &hostname);
c7664c07 1658 if (r < 0)
cc4482ee 1659 log_debug_errno(r, "Failed to read /etc/hostname of image %s: %m", i->name);
c7664c07
LP
1660 }
1661
1662 path = mfree(path);
1663
f7b5f399
YW
1664 r = id128_get_machine(i->path, &machine_id);
1665 if (r < 0)
1666 log_debug_errno(r, "Failed to read machine ID in image %s, ignoring: %m", i->name);
c7664c07 1667
f461a28d 1668 r = chase("/etc/machine-info", i->path, CHASE_PREFIX_ROOT|CHASE_TRAIL_SLASH, &path, NULL);
c7664c07
LP
1669 if (r < 0 && r != -ENOENT)
1670 log_debug_errno(r, "Failed to chase /etc/machine-info in image %s: %m", i->name);
1671 else if (r >= 0) {
aa8fbc74 1672 r = load_env_file_pairs(NULL, path, &machine_info);
c7664c07
LP
1673 if (r < 0)
1674 log_debug_errno(r, "Failed to parse machine-info data of %s: %m", i->name);
1675 }
1676
d58ad743
LP
1677 r = load_os_release_pairs(i->path, &os_release);
1678 if (r < 0)
1679 log_debug_errno(r, "Failed to read os-release in image, ignoring: %m");
c7664c07 1680
a81fe93e 1681 r = load_extension_release_pairs(i->path, IMAGE_SYSEXT, i->name, /* relax_extension_release_check= */ false, &sysext_release);
bcf94222 1682 if (r < 0)
a81fe93e
LP
1683 log_debug_errno(r, "Failed to read sysext-release in image, ignoring: %m");
1684
1685 r = load_extension_release_pairs(i->path, IMAGE_CONFEXT, i->name, /* relax_extension_release_check= */ false, &confext_release);
1686 if (r < 0)
1687 log_debug_errno(r, "Failed to read confext-release in image, ignoring: %m");
bcf94222 1688
c7664c07
LP
1689 free_and_replace(i->hostname, hostname);
1690 i->machine_id = machine_id;
1691 strv_free_and_replace(i->machine_info, machine_info);
1692 strv_free_and_replace(i->os_release, os_release);
a81fe93e
LP
1693 strv_free_and_replace(i->sysext_release, sysext_release);
1694 strv_free_and_replace(i->confext_release, confext_release);
c7664c07
LP
1695 break;
1696 }
1697
1698 case IMAGE_RAW:
1699 case IMAGE_BLOCK: {
1700 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
1701 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
f4a63ce2
LP
1702 DissectImageFlags flags =
1703 DISSECT_IMAGE_GENERIC_ROOT |
1704 DISSECT_IMAGE_REQUIRE_ROOT |
1705 DISSECT_IMAGE_RELAX_VAR_CHECK |
1706 DISSECT_IMAGE_READ_ONLY |
1707 DISSECT_IMAGE_USR_NO_ROOT |
1708 DISSECT_IMAGE_ADD_PARTITION_DEVICES |
1709 DISSECT_IMAGE_PIN_PARTITION_DEVICES |
1710 DISSECT_IMAGE_VALIDATE_OS |
1711 DISSECT_IMAGE_VALIDATE_OS_EXT |
1712 DISSECT_IMAGE_ALLOW_USERSPACE_VERITY;
1713
1714 r = loop_device_make_by_path(
1715 i->path,
1716 O_RDONLY,
1717 /* sector_size= */ UINT32_MAX,
1718 LO_FLAGS_PARTSCAN,
1719 LOCK_SH,
1720 &d);
41bc4849
LP
1721 if (r < 0)
1722 return r;
1723
bad31660
YW
1724 r = dissect_loop_device(
1725 d,
84be0c71
LP
1726 /* verity= */ NULL,
1727 /* mount_options= */ NULL,
1728 image_policy,
f1395724 1729 /* image_filter= */ NULL,
f4a63ce2 1730 flags,
75dc190d 1731 &m);
c7664c07
LP
1732 if (r < 0)
1733 return r;
1734
44e3097d
LP
1735 r = dissected_image_acquire_metadata(
1736 m,
1737 /* userns_fd= */ -EBADF,
1738 flags);
c7664c07
LP
1739 if (r < 0)
1740 return r;
1741
1742 free_and_replace(i->hostname, m->hostname);
1743 i->machine_id = m->machine_id;
1744 strv_free_and_replace(i->machine_info, m->machine_info);
1745 strv_free_and_replace(i->os_release, m->os_release);
a81fe93e
LP
1746 strv_free_and_replace(i->sysext_release, m->sysext_release);
1747 strv_free_and_replace(i->confext_release, m->confext_release);
c7664c07
LP
1748
1749 break;
1750 }
1751
1752 default:
1753 return -EOPNOTSUPP;
1754 }
1755
1756 i->metadata_valid = true;
1757
1758 return 0;
1759}
1760
30535c16 1761int image_name_lock(const char *name, int operation, LockFile *ret) {
99d97afc
LP
1762 const char *p;
1763
30535c16
LP
1764 assert(name);
1765 assert(ret);
1766
1767 /* Locks an image name, regardless of the precise path used. */
1768
99d97afc
LP
1769 if (streq(name, ".host"))
1770 return -EBUSY;
1771
30535c16
LP
1772 if (!image_name_is_valid(name))
1773 return -EINVAL;
1774
b6e953f2
LP
1775 if (getenv_bool("SYSTEMD_NSPAWN_LOCK") == 0) {
1776 *ret = (LockFile) LOCK_FILE_INIT;
1777 return 0;
1778 }
1779
8759bc95 1780 make_lock_dir();
99d97afc
LP
1781
1782 p = strjoina("/run/systemd/nspawn/locks/name-", name);
30535c16
LP
1783 return make_lock_file(p, operation, ret);
1784}
1785
d577d4a4 1786bool image_in_search_path(
1c0ade2e 1787 RuntimeScope scope,
d577d4a4
LP
1788 ImageClass class,
1789 const char *root,
1790 const char *image) {
1791
1c0ade2e
LP
1792 int r;
1793
1794 assert(scope < _RUNTIME_SCOPE_MAX && scope != RUNTIME_SCOPE_GLOBAL);
1795 assert(class >= 0);
1796 assert(class < _IMAGE_CLASS_MAX);
ace9ab19
LP
1797 assert(image);
1798
1c0ade2e
LP
1799 _cleanup_strv_free_ char **search = NULL;
1800 r = pick_image_search_path(scope, class, &search);
1801 if (r < 0)
1802 return r;
1803
1804 STRV_FOREACH(path, search) {
d577d4a4 1805 const char *p, *q;
ace9ab19
LP
1806 size_t k;
1807
d577d4a4 1808 if (!empty_or_root(root)) {
1c0ade2e 1809 q = path_startswith(*path, root);
d577d4a4
LP
1810 if (!q)
1811 continue;
1812 } else
1c0ade2e 1813 q = *path;
d577d4a4 1814
1c0ade2e 1815 p = path_startswith(q, *path);
ace9ab19
LP
1816 if (!p)
1817 continue;
1818
1819 /* Make sure there's a filename following */
1820 k = strcspn(p, "/");
1821 if (k == 0)
1822 continue;
1823
1824 p += k;
1825
1826 /* Accept trailing slashes */
1827 if (p[strspn(p, "/")] == 0)
1828 return true;
ace9ab19
LP
1829 }
1830
1831 return false;
1832}
1833
73053472
DDM
1834bool image_is_vendor(const struct Image *i) {
1835 assert(i);
1836
1837 return i->path && path_startswith(i->path, "/usr");
1838}
1839
1840bool image_is_host(const struct Image *i) {
1841 assert(i);
1842
1843 if (i->name && streq(i->name, ".host"))
1844 return true;
1845
1846 if (i->path && path_equal(i->path, "/"))
1847 return true;
1848
1849 return false;
1850}
1851
309a747f 1852int image_to_json(const struct Image *img, sd_json_variant **ret) {
f5151fb4
LP
1853 assert(img);
1854
be5bee2a
LP
1855 return sd_json_buildo(
1856 ret,
1857 SD_JSON_BUILD_PAIR_STRING("Type", image_type_to_string(img->type)),
1858 SD_JSON_BUILD_PAIR_STRING("Class", image_class_to_string(img->class)),
1859 SD_JSON_BUILD_PAIR_STRING("Name", img->name),
1860 SD_JSON_BUILD_PAIR_CONDITION(!!img->path, "Path", SD_JSON_BUILD_STRING(img->path)),
1861 SD_JSON_BUILD_PAIR_BOOLEAN("ReadOnly", img->read_only),
1862 SD_JSON_BUILD_PAIR_CONDITION(img->crtime != 0, "CreationTimestamp", SD_JSON_BUILD_UNSIGNED(img->crtime)),
1863 SD_JSON_BUILD_PAIR_CONDITION(img->mtime != 0, "ModificationTimestamp", SD_JSON_BUILD_UNSIGNED(img->mtime)),
1864 SD_JSON_BUILD_PAIR_CONDITION(img->usage != UINT64_MAX, "Usage", SD_JSON_BUILD_UNSIGNED(img->usage)),
1865 SD_JSON_BUILD_PAIR_CONDITION(img->usage_exclusive != UINT64_MAX, "UsageExclusive", SD_JSON_BUILD_UNSIGNED(img->usage_exclusive)),
1866 SD_JSON_BUILD_PAIR_CONDITION(img->limit != UINT64_MAX, "Limit", SD_JSON_BUILD_UNSIGNED(img->limit)),
1867 SD_JSON_BUILD_PAIR_CONDITION(img->limit_exclusive != UINT64_MAX, "LimitExclusive", SD_JSON_BUILD_UNSIGNED(img->limit_exclusive)));
f5151fb4
LP
1868}
1869
cd61c3bf
LP
1870static const char* const image_type_table[_IMAGE_TYPE_MAX] = {
1871 [IMAGE_DIRECTORY] = "directory",
1872 [IMAGE_SUBVOLUME] = "subvolume",
25cdbd04
LP
1873 [IMAGE_RAW] = "raw",
1874 [IMAGE_BLOCK] = "block",
cd61c3bf
LP
1875};
1876
1877DEFINE_STRING_TABLE_LOOKUP(image_type, ImageType);