Debian Codegraph @

src/shared/discover-image.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <linux/loop.h>
5 #include <linux/magic.h>
6 #include <stdio.h>
7 #include <sys/file.h>
8 #include <sys/ioctl.h>
9 #include <sys/stat.h>
10 #include <unistd.h>
11
12 #include "sd-json.h"
13 #include "sd-path.h"
14 #include "sd-varlink.h"
15
16 #include "alloc-util.h"
17 #include "blockdev-util.h"
18 #include "btrfs-util.h"
19 #include "bus-get-properties.h"
20 #include "chase.h"
21 #include "chattr-util.h"
22 #include "copy.h"
23 #include "devnum-util.h"
24 #include "dirent-util.h"
25 #include "discover-image.h"
26 #include "dissect-image.h"
27 #include "env-file.h"
28 #include "env-util.h"
29 #include "extension-util.h"
30 #include "fd-util.h"
31 #include "fs-util.h"
32 #include "hashmap.h"
33 #include "hostname-setup.h"
34 #include "id128-util.h"
35 #include "label-util.h"
36 #include "lock-util.h"
37 #include "log.h"
38 #include "loop-util.h"
39 #include "mountpoint-util.h"
40 #include "mstack.h"
41 #include "namespace-util.h"
42 #include "nsresource.h"
43 #include "nulstr-util.h"
44 #include "os-util.h"
45 #include "path-lookup.h"
46 #include "path-util.h"
47 #include "process-util.h"
48 #include "recurse-dir.h"
49 #include "rm-rf.h"
50 #include "runtime-scope.h"
51 #include "stat-util.h"
52 #include "string-table.h"
53 #include "string-util.h"
54 #include "strv.h"
55 #include "time-util.h"
56 #include "uid-classification.h"
57 #include "vpick.h"
58 #include "xattr-util.h"
59
60 const char* const image_search_path[_IMAGE_CLASS_MAX] = {
61 [IMAGE_MACHINE] = "/etc/machines\0" /* only place symlinks here */
62 "/run/machines\0" /* and here too */
63 "/var/lib/machines\0" /* the main place for images */
64 "/var/lib/container\0" /* legacy */
65 "/usr/local/lib/machines\0"
66 "/usr/lib/machines\0",
67
68 [IMAGE_PORTABLE] = "/etc/portables\0" /* only place symlinks here */
69 "/run/portables\0" /* and here too */
70 "/var/lib/portables\0" /* the main place for images */
71 "/usr/local/lib/portables\0"
72 "/usr/lib/portables\0",
73
74 /* Note that we don't allow storing extensions under /usr/, unlike with other image types. That's
75 * because extension images are supposed to extend /usr/, so you get into recursive races, especially
76 * with directory-based extensions, as the kernel's OverlayFS explicitly checks for this and errors
77 * out with -ELOOP if it finds that a lowerdir= is a child of another lowerdir=. */
78 [IMAGE_SYSEXT] = "/etc/extensions\0" /* only place symlinks here */
79 "/run/extensions\0" /* and here too */
80 "/var/lib/extensions\0", /* the main place for images */
81
82 [IMAGE_CONFEXT] = "/run/confexts\0" /* only place symlinks here */
83 "/var/lib/confexts\0" /* the main place for images */
84 "/usr/local/lib/confexts\0"
85 "/usr/lib/confexts\0",
86 };
87
88 /* Inside the initrd, use a slightly different set of search path (i.e. include .extra/sysext/,
89 * /.extra/global_sysext, .extra/confext/, and /.extra/global_confext in extension search dir) */
90 static const char* const image_search_path_initrd[_IMAGE_CLASS_MAX] = {
91 /* (entries that aren't listed here will get the same search path as for the non initrd-case) */
92
93 [IMAGE_SYSEXT] = "/etc/extensions\0" /* only place symlinks here */
94 "/run/extensions\0" /* and here too */
95 "/var/lib/extensions\0" /* the main place for images */
96 "/.extra/sysext\0" /* put sysext (per-UKI and global) picked up by systemd-stub */
97 "/.extra/global_sysext\0", /* last, since not trusted */
98
99 [IMAGE_CONFEXT] = "/run/confexts\0" /* only place symlinks here */
100 "/var/lib/confexts\0" /* the main place for images */
101 "/usr/local/lib/confexts\0"
102 "/.extra/confext\0" /* put confext (per-UKI and global) picked up by systemd-stub */
103 "/.extra/global_confext\0", /* last, since not trusted. */
104 };
105
106 static const char* image_class_suffix_table[_IMAGE_CLASS_MAX] = {
107 [IMAGE_SYSEXT] = ".sysext",
108 [IMAGE_CONFEXT] = ".confext",
109 };
110
111 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(image_class_suffix, ImageClass);
112
113 static const char *const image_root_table[_IMAGE_CLASS_MAX] = {
114 [IMAGE_MACHINE] = "/var/lib/machines",
115 [IMAGE_PORTABLE] = "/var/lib/portables",
116 [IMAGE_SYSEXT] = "/var/lib/extensions",
117 [IMAGE_CONFEXT] = "/var/lib/confexts",
118 };
119
120 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(image_root, ImageClass);
121
122 static const char *const image_root_runtime_table[_IMAGE_CLASS_MAX] = {
123 [IMAGE_MACHINE] = "/run/machines",
124 [IMAGE_PORTABLE] = "/run/portables",
125 [IMAGE_SYSEXT] = "/run/extensions",
126 [IMAGE_CONFEXT] = "/run/confexts",
127 };
128
129 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(image_root_runtime, ImageClass);
130
131 static const char *const image_dirname_table[_IMAGE_CLASS_MAX] = {
132 [IMAGE_MACHINE] = "machines",
133 [IMAGE_PORTABLE] = "portables",
134 [IMAGE_SYSEXT] = "extensions",
135 [IMAGE_CONFEXT] = "confexts",
136 };
137
138 static const char auxiliary_suffixes_nulstr[] =
139 ".nspawn\0"
140 ".oci-config\0"
141 ".roothash\0"
142 ".roothash.p7s\0"
143 ".usrhash\0"
144 ".usrhash.p7s\0"
145 ".verity\0"
146 ".raw.tpmstate\0"
147 ".raw.efinvramstate\0";
148
149 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(image_dirname, ImageClass);
150
151 static Image* image_free(Image *i) {
152 assert(i);
153
154 free(i->name);
155 free(i->path);
156
157 free(i->fh);
158
159 free(i->hostname);
160 strv_free(i->machine_info);
161 strv_free(i->os_release);
162 strv_free(i->sysext_release);
163 strv_free(i->confext_release);
164
165 return mfree(i);
166 }
167
168 DEFINE_TRIVIAL_REF_UNREF_FUNC(Image, image, image_free);
169 DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(image_hash_ops, char, string_hash_func, string_compare_func,
170 Image, image_unref);
171
172 static char** image_settings_path(Image *image, RuntimeScope scope) {
173 _cleanup_strv_free_ char **l = NULL;
174 _cleanup_free_ char *fn = NULL;
175 size_t i = 0;
176 int r;
177
178 assert(image);
179
180 l = new0(char*, 5);
181 if (!l)
182 return NULL;
183
184 fn = strjoin(image->name, ".nspawn");
185 if (!fn)
186 return NULL;
187
188 static const uint64_t system_locations[] = {
189 SD_PATH_SYSTEM_CONFIGURATION,
190 SD_PATH_SYSTEM_RUNTIME,
191 SD_PATH_SYSTEM_LIBRARY_PRIVATE,
192 _SD_PATH_INVALID
193 };
194 static const uint64_t user_locations[] = {
195 SD_PATH_USER_CONFIGURATION,
196 SD_PATH_USER_RUNTIME,
197 SD_PATH_USER_LIBRARY_PRIVATE,
198 _SD_PATH_INVALID
199 };
200 const uint64_t *locations;
201
202 switch (scope) {
203 case RUNTIME_SCOPE_SYSTEM:
204 locations = system_locations;
205 break;
206
207 case RUNTIME_SCOPE_USER:
208 locations = user_locations;
209 break;
210
211 default:
212 assert_not_reached();
213 }
214
215 for (size_t k = 0; locations[k] != _SD_PATH_INVALID; k++) {
216 _cleanup_free_ char *s = NULL;
217 r = sd_path_lookup(locations[k], "systemd/nspawn", &s);
218 if (r == -ENXIO)
219 continue;
220 if (r < 0)
221 return NULL;
222
223 l[i] = path_join(s, fn);
224 if (!l[i])
225 return NULL;
226
227 i++;
228 }
229
230 r = file_in_same_dir(image->path, fn, l + i);
231 if (r == -ENOMEM)
232 return NULL;
233 if (r < 0)
234 log_debug_errno(r, "Failed to generate .nspawn settings path from image path, ignoring: %m");
235
236 strv_uniq(l);
237
238 return TAKE_PTR(l);
239 }
240
241 static int image_auxiliary_path(Image *image, const char *suffix, char **ret) {
242 assert(image);
243 assert(suffix);
244
245 _cleanup_free_ char *fn = strjoin(image->name, suffix);
246 if (!fn)
247 return -ENOMEM;
248
249 return file_in_same_dir(image->path, fn, ret);
250 }
251
252 static int image_new(
253 ImageType t,
254 ImageClass c,
255 const char *pretty,
256 const char *path,
257 bool read_only,
258 usec_t crtime,
259 usec_t mtime,
260 struct file_handle *fh,
261 uint64_t on_mount_id,
262 uint64_t inode,
263 Image **ret) {
264
265 _cleanup_(image_unrefp) Image *i = NULL;
266
267 assert(t >= 0);
268 assert(t < _IMAGE_TYPE_MAX);
269 assert(pretty);
270 assert(path);
271 assert(ret);
272
273 i = new(Image, 1);
274 if (!i)
275 return -ENOMEM;
276
277 *i = (Image) {
278 .n_ref = 1,
279 .type = t,
280 .class = c,
281 .read_only = read_only,
282 .crtime = crtime,
283 .mtime = mtime,
284 .on_mount_id = on_mount_id,
285 .inode = inode,
286 .usage = UINT64_MAX,
287 .usage_exclusive = UINT64_MAX,
288 .limit = UINT64_MAX,
289 .limit_exclusive = UINT64_MAX,
290 };
291
292 if (fh) {
293 i->fh = file_handle_dup(fh);
294 if (!i->fh)
295 return -ENOMEM;
296 }
297
298 i->name = strdup(pretty);
299 if (!i->name)
300 return -ENOMEM;
301
302 i->path = strdup(path);
303 if (!i->path)
304 return -ENOMEM;
305
306 path_simplify(i->path);
307
308 *ret = TAKE_PTR(i);
309
310 return 0;
311 }
312
313 static int extract_image_basename(
314 const char *path,
315 const char *class_suffix, /* e.g. ".sysext" (this is an optional suffix) */
316 char **format_suffixes, /* e.g. ".raw" (one of these will be required) */
317 char **ret_basename,
318 char **ret_suffix) {
319
320 _cleanup_free_ char *name = NULL, *suffix = NULL;
321 int r;
322
323 assert(path);
324
325 r = path_extract_filename(path, &name);
326 if (r < 0)
327 return r;
328
329 if (format_suffixes) {
330 char *e = endswith_strv(name, format_suffixes);
331 if (!e) /* Format suffix is required */
332 return -EINVAL;
333
334 if (ret_suffix) {
335 suffix = strdup(e);
336 if (!suffix)
337 return -ENOMEM;
338 }
339
340 *e = 0;
341 }
342
343 if (class_suffix) {
344 char *e = endswith(name, class_suffix);
345 if (e) { /* Class suffix is optional */
346 if (ret_suffix) {
347 _cleanup_free_ char *j = strjoin(e, suffix);
348 if (!j)
349 return -ENOMEM;
350
351 free_and_replace(suffix, j);
352 }
353
354 *e = 0;
355 }
356 }
357
358 if (!image_name_is_valid(name))
359 return -EINVAL;
360
361 if (ret_suffix)
362 *ret_suffix = TAKE_PTR(suffix);
363
364 if (ret_basename)
365 *ret_basename = TAKE_PTR(name);
366
367 return 0;
368 }
369
370 static int image_update_quota(Image *i, int fd) {
371 _cleanup_close_ int fd_close = -EBADF;
372 int r;
373
374 assert(i);
375
376 if (image_is_vendor(i) || image_is_host(i))
377 return -EROFS;
378
379 if (i->type != IMAGE_SUBVOLUME)
380 return -EOPNOTSUPP;
381
382 if (fd < 0) {
383 fd_close = open(i->path, O_CLOEXEC|O_DIRECTORY);
384 if (fd_close < 0)
385 return -errno;
386 fd = fd_close;
387 } else {
388 /* Convert from O_PATH to proper fd, if needed */
389 fd = fd_reopen_condition(fd, O_CLOEXEC|O_DIRECTORY, O_PATH, &fd_close);
390 if (fd < 0)
391 return fd;
392 }
393
394 r = btrfs_quota_scan_ongoing(fd);
395 if (r < 0)
396 return r;
397 if (r > 0)
398 return 0;
399
400 BtrfsQuotaInfo quota;
401 r = btrfs_subvol_get_subtree_quota_fd(fd, 0, &quota);
402 if (r < 0)
403 return r;
404
405 i->usage = quota.referenced;
406 i->usage_exclusive = quota.exclusive;
407 i->limit = quota.referenced_max;
408 i->limit_exclusive = quota.exclusive_max;
409
410 return 1;
411 }
412
413 static int image_make(
414 ImageClass c,
415 const char *pretty,
416 int fd, /* O_PATH fd */
417 const char *path,
418 const struct stat *st,
419 Image **ret) {
420
421 _cleanup_free_ char *pretty_buffer = NULL;
422 bool read_only;
423 int r;
424
425 assert(path);
426 assert(path_is_absolute(path));
427
428 /* We explicitly *do* follow symlinks here, since we want to allow symlinking trees, raw files and block
429 * devices into /var/lib/machines/, and treat them normally.
430 * Note that if the caller does not want to follow symlinks (and does not care about symlink races)
431 * then the caller should pass in a resolved path and an fd.
432 *
433 * This function returns -ENOENT if we can't find the image after all, and -EMEDIUMTYPE if it's not a file we
434 * recognize. */
435
436 _cleanup_close_ int _fd = -EBADF;
437 if (fd < 0) {
438 /* If we didn't get an fd passed in, then let's pin it via O_PATH now */
439 _fd = open(path, O_PATH|O_CLOEXEC);
440 if (_fd < 0)
441 return -errno;
442
443 fd = _fd;
444 st = NULL; /* refresh stat() data now that we have the inode pinned */
445 }
446
447 struct stat stbuf;
448 if (!st) {
449 if (fstat(fd, &stbuf) < 0)
450 return -errno;
451
452 st = &stbuf;
453 }
454
455 read_only =
456 path_startswith(path, "/usr") ||
457 (faccessat(fd, "", W_OK, AT_EACCESS|AT_EMPTY_PATH) < 0 && errno == EROFS);
458
459 _cleanup_free_ struct file_handle *fh = NULL;
460 uint64_t on_mount_id;
461 int _mnt_id;
462
463 /* The fallback is required for CentOS 9 compatibility when working on a directory located on an
464 * overlayfs. */
465 r = name_to_handle_at_try_fid(fd, /* path= */ NULL, &fh, &_mnt_id, &on_mount_id, AT_EMPTY_PATH);
466 if (r < 0) {
467 if (is_name_to_handle_at_fatal_error(r))
468 return r;
469
470 r = path_get_unique_mnt_id_at(fd, /* path= */ NULL, &on_mount_id);
471 if (r < 0) {
472 if (!ERRNO_IS_NEG_NOT_SUPPORTED(r) && r != -EUNATCH)
473 return r;
474
475 int on_mount_id_fallback = -1;
476 r = path_get_mnt_id_at(fd, /* path= */ NULL, &on_mount_id_fallback);
477 if (r < 0)
478 return r;
479
480 on_mount_id = on_mount_id_fallback;
481 }
482 } else if (r == 0)
483 on_mount_id = _mnt_id;
484
485 if (S_ISDIR(st->st_mode)) {
486
487 if (!ret)
488 return 0;
489
490 if (endswith(path, ".mstack")) {
491 usec_t crtime = 0;
492 r = fd_getcrtime(fd, &crtime);
493 if (r < 0)
494 log_debug_errno(r, "Unable to read creation time of '%s', ignoring: %m", path);
495
496 if (!pretty) {
497 r = extract_image_basename(
498 path,
499 image_class_suffix_to_string(c),
500 STRV_MAKE(".mstack"),
501 &pretty_buffer,
502 /* ret_suffix= */ NULL);
503 if (r < 0)
504 return r;
505
506 pretty = pretty_buffer;
507 }
508
509 _cleanup_(mstack_freep) MStack *mstack = NULL;
510 r = mstack_load(path, fd, &mstack);
511 if (r < 0) {
512 log_debug_errno(r, "Failed to load mstack '%s', ignoring: %m", path);
513 read_only = true;
514 } else if (!read_only) {
515 r = mstack_is_read_only(mstack);
516 if (r < 0)
517 log_debug_errno(r, "Failed to determine if mstack '%s' is read-only, assuming it is: %m", path);
518
519 read_only = r != 0;
520 }
521
522 r = image_new(IMAGE_MSTACK,
523 c,
524 pretty,
525 path,
526 read_only,
527 crtime,
528 /* mtime= */ 0,
529 fh,
530 on_mount_id,
531 (uint64_t) st->st_ino,
532 ret);
533 if (r < 0)
534 return r;
535
536 if (mstack) {
537 r = mstack_is_foreign_uid_owned(mstack);
538 if (r < 0)
539 log_debug_errno(r, "Failed to determine if mstack '%s' is foreign UID owned, assuming it is not: %m", path);
540 if (r > 0)
541 (*ret)->foreign_uid_owned = true;
542 }
543
544 return 0;
545 }
546
547 if (!pretty) {
548 r = extract_image_basename(
549 path,
550 image_class_suffix_to_string(c),
551 /* format_suffixes= */ NULL,
552 &pretty_buffer,
553 /* ret_suffix= */ NULL);
554 if (r < 0)
555 return r;
556
557 pretty = pretty_buffer;
558 }
559
560 if (btrfs_might_be_subvol(st)) {
561
562 r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
563 if (r < 0)
564 return r;
565 if (r > 0) {
566 BtrfsSubvolInfo info;
567
568 /* It's a btrfs subvolume */
569
570 r = btrfs_subvol_get_info_fd(fd, 0, &info);
571 if (r < 0)
572 return r;
573
574 r = image_new(IMAGE_SUBVOLUME,
575 c,
576 pretty,
577 path,
578 info.read_only || read_only,
579 info.otime,
580 info.ctime,
581 fh,
582 on_mount_id,
583 (uint64_t) st->st_ino,
584 ret);
585 if (r < 0)
586 return r;
587
588 (*ret)->foreign_uid_owned = uid_is_foreign(st->st_uid);
589 (void) image_update_quota(*ret, fd);
590 return 0;
591 }
592 }
593
594 /* Get directory creation time (not available everywhere, but that's OK */
595 usec_t crtime = 0;
596 (void) fd_getcrtime(fd, &crtime);
597
598 /* If the IMMUTABLE bit is set, we consider the directory read-only. Since the ioctl is not
599 * supported everywhere we ignore failures. */
600 unsigned file_attr = 0;
601 (void) read_attr_fd(fd, &file_attr);
602
603 /* It's just a normal directory. */
604 r = image_new(IMAGE_DIRECTORY,
605 c,
606 pretty,
607 path,
608 read_only || (file_attr & FS_IMMUTABLE_FL),
609 crtime,
610 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 */
611 fh,
612 on_mount_id,
613 (uint64_t) st->st_ino,
614 ret);
615 if (r < 0)
616 return r;
617
618 (*ret)->foreign_uid_owned = uid_is_foreign(st->st_uid);
619 return 0;
620
621 } else if (S_ISREG(st->st_mode) && endswith(path, ".raw")) {
622 usec_t crtime = 0;
623
624 /* It's a RAW disk image */
625
626 if (!ret)
627 return 0;
628
629 (void) fd_getcrtime(fd, &crtime);
630
631 if (!pretty) {
632 r = extract_image_basename(
633 path,
634 image_class_suffix_to_string(c),
635 STRV_MAKE(".raw"),
636 &pretty_buffer,
637 /* ret_suffix= */ NULL);
638 if (r < 0)
639 return r;
640
641 pretty = pretty_buffer;
642 }
643
644 r = image_new(IMAGE_RAW,
645 c,
646 pretty,
647 path,
648 !(st->st_mode & 0222) || read_only,
649 crtime,
650 timespec_load(&st->st_mtim),
651 fh,
652 on_mount_id,
653 (uint64_t) st->st_ino,
654 ret);
655 if (r < 0)
656 return r;
657
658 (*ret)->usage = (*ret)->usage_exclusive = st->st_blocks * 512;
659 (*ret)->limit = (*ret)->limit_exclusive = st->st_size;
660
661 return 0;
662
663 } else if (S_ISBLK(st->st_mode)) {
664 uint64_t size = UINT64_MAX;
665
666 /* A block device */
667
668 if (!ret)
669 return 0;
670
671 if (!pretty) {
672 r = extract_image_basename(
673 path,
674 /* class_suffix= */ NULL,
675 /* format_suffix= */ NULL,
676 &pretty_buffer,
677 /* ret_suffix= */ NULL);
678 if (r < 0)
679 return r;
680
681 pretty = pretty_buffer;
682 }
683
684 _cleanup_close_ int block_fd = fd_reopen(fd, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
685 if (block_fd < 0)
686 log_debug_errno(errno, "Failed to open block device '%s', ignoring: %m", path);
687 else {
688 if (!read_only) {
689 int state = 0;
690
691 if (ioctl(block_fd, BLKROGET, &state) < 0)
692 log_debug_errno(errno, "Failed to issue BLKROGET on device '%s', ignoring: %m", path);
693 else if (state)
694 read_only = true;
695 }
696
697 r = blockdev_get_device_size(block_fd, &size);
698 if (r < 0)
699 log_debug_errno(r, "Failed to issue BLKGETSIZE64 on device '%s', ignoring: %m", path);
700
701 block_fd = safe_close(block_fd);
702 }
703
704 r = image_new(IMAGE_BLOCK,
705 c,
706 pretty,
707 path,
708 !(st->st_mode & 0222) || read_only,
709 0,
710 0,
711 fh,
712 on_mount_id,
713 (uint64_t) st->st_ino,
714 ret);
715 if (r < 0)
716 return r;
717
718 if (!IN_SET(size, 0, UINT64_MAX))
719 (*ret)->usage = (*ret)->usage_exclusive = (*ret)->limit = (*ret)->limit_exclusive = size;
720
721 return 0;
722 }
723
724 return -EMEDIUMTYPE;
725 }
726
727 static int pick_image_search_path(
728 RuntimeScope scope,
729 ImageClass class,
730 const char *root,
731 char ***ret) {
732
733 int r;
734
735 assert(scope < _RUNTIME_SCOPE_MAX && scope != RUNTIME_SCOPE_GLOBAL);
736 assert(class < _IMAGE_CLASS_MAX);
737 assert(ret);
738
739 if (class < 0) {
740 *ret = NULL;
741 return 0;
742 }
743
744 if (scope < 0) {
745 _cleanup_strv_free_ char **a = NULL, **b = NULL;
746
747 r = pick_image_search_path(RUNTIME_SCOPE_USER, class, root, &a);
748 if (r < 0)
749 return r;
750
751 r = pick_image_search_path(RUNTIME_SCOPE_SYSTEM, class, root, &b);
752 if (r < 0)
753 return r;
754
755 r = strv_extend_strv(&a, b, /* filter_duplicates= */ false);
756 if (r < 0)
757 return r;
758
759 *ret = TAKE_PTR(a);
760 return 0;
761 }
762
763 switch (scope) {
764
765 case RUNTIME_SCOPE_SYSTEM: {
766 const char *ns;
767 bool is_initrd;
768
769 r = chase_and_access("/etc/initrd-release", root, CHASE_PREFIX_ROOT, F_OK, /* ret_path= */ NULL);
770 if (r < 0 && r != -ENOENT)
771 return r;
772 is_initrd = r >= 0;
773
774 /* Use the initrd search path if there is one, otherwise use the common one */
775 ns = is_initrd && image_search_path_initrd[class] ?
776 image_search_path_initrd[class] :
777 image_search_path[class];
778 if (!ns)
779 break;
780
781 _cleanup_strv_free_ char **search = strv_split_nulstr(ns);
782 if (!search)
783 return -ENOMEM;
784
785 *ret = TAKE_PTR(search);
786 return 0;
787 }
788
789 case RUNTIME_SCOPE_USER: {
790 if (!IN_SET(class, IMAGE_MACHINE, IMAGE_PORTABLE))
791 break;
792
793 static const uint64_t dirs[] = {
794 SD_PATH_USER_RUNTIME,
795 SD_PATH_USER_STATE_PRIVATE,
796 SD_PATH_USER_LIBRARY_PRIVATE,
797 };
798
799 _cleanup_strv_free_ char **search = NULL;
800 FOREACH_ELEMENT(d, dirs) {
801 _cleanup_free_ char *p = NULL;
802
803 r = sd_path_lookup(*d, image_dirname_to_string(class), &p);
804 if (r == -ENXIO) /* No XDG_RUNTIME_DIR set */
805 continue;
806 if (r < 0)
807 return r;
808
809 r = strv_consume(&search, TAKE_PTR(p));
810 if (r < 0)
811 return r;
812 }
813
814 *ret = TAKE_PTR(search);
815 return 0;
816 }
817
818 default:
819 assert_not_reached();
820 }
821
822 *ret = NULL;
823 return 0;
824 }
825
826 static char** make_possible_filenames(ImageClass class, const char *image_name) {
827 _cleanup_strv_free_ char **l = NULL;
828
829 assert(image_name);
830
831 FOREACH_STRING(v_suffix, "", ".v")
832 FOREACH_STRING(format_suffix, "", ".raw", ".mstack") {
833 _cleanup_free_ char *j = NULL;
834 const char *class_suffix;
835
836 class_suffix = image_class_suffix_to_string(class);
837 if (class_suffix) {
838 j = strjoin(image_name, class_suffix, format_suffix, v_suffix);
839 if (!j)
840 return NULL;
841
842 if (strv_consume(&l, TAKE_PTR(j)) < 0)
843 return NULL;
844 }
845
846 j = strjoin(image_name, format_suffix, v_suffix);
847 if (!j)
848 return NULL;
849
850 if (strv_consume(&l, TAKE_PTR(j)) < 0)
851 return NULL;
852 }
853
854 return TAKE_PTR(l);
855 }
856
857 int image_find(RuntimeScope scope,
858 ImageClass class,
859 const char *name,
860 const char *root,
861 Image **ret) {
862
863 int r;
864
865 assert(scope < _RUNTIME_SCOPE_MAX && scope != RUNTIME_SCOPE_GLOBAL);
866 assert(class >= 0);
867 assert(class < _IMAGE_CLASS_MAX);
868 assert(name);
869
870 /* There are no images with invalid names */
871 if (!image_name_is_valid(name))
872 return -ENOENT;
873
874 _cleanup_strv_free_ char **names = make_possible_filenames(class, name);
875 if (!names)
876 return -ENOMEM;
877
878 _cleanup_close_ int rfd = XAT_FDROOT; /* We only expect absolute paths */
879 if (root) {
880 rfd = open(root, O_CLOEXEC|O_DIRECTORY|O_PATH);
881 if (rfd < 0)
882 return log_debug_errno(errno, "Failed to open root directory '%s': %m", root);
883 }
884
885 _cleanup_strv_free_ char **search = NULL;
886 r = pick_image_search_path(scope, class, root, &search);
887 if (r < 0)
888 return r;
889
890 STRV_FOREACH(s, search) {
891 _cleanup_closedir_ DIR *d = NULL;
892 _cleanup_free_ char *search_path = NULL;
893
894 r = chase_and_opendirat(rfd, rfd, *s, /* chase_flags= */ 0, &search_path, &d);
895 if (r == -ENOENT)
896 continue;
897 if (r < 0)
898 return r;
899
900 STRV_FOREACH(n, names) {
901 const char *fname = *n;
902 _cleanup_free_ char *fname_path = NULL, *chased_path = NULL, *resolved_file = NULL;
903 _cleanup_close_ int fd = -EBADF;
904
905 fname_path = path_join(search_path, fname);
906 if (!fname_path)
907 return -ENOMEM;
908
909 /* Follow symlinks only inside given root */
910 r = chaseat(rfd, rfd, fname_path, /* flags= */ 0, &chased_path, &fd);
911 if (r == -ENOENT)
912 continue;
913 if (r < 0)
914 return r;
915
916 r = chaseat_prefix_root(chased_path, root, &resolved_file);
917 if (r < 0)
918 return r;
919
920 struct stat st;
921 if (fstat(fd, &st) < 0)
922 return -errno;
923
924 if (endswith(fname, ".raw")) {
925 if (!S_ISREG(st.st_mode)) {
926 log_debug("Ignoring non-regular file '%s' with .raw suffix.", fname);
927 continue;
928 }
929 } else if (endswith(fname, ".mstack")) {
930
931 if (!S_ISDIR(st.st_mode)) {
932 log_debug("Ignoring non-directory '%s' with .mstack suffix.", fname);
933 continue;
934 }
935
936 } else if (endswith(fname, ".v")) {
937
938 if (!S_ISDIR(st.st_mode)) {
939 log_debug("Ignoring non-directory file '%s' with .v suffix.", fname);
940 continue;
941 }
942
943 _cleanup_free_ char *suffix = NULL;
944 suffix = strdup(ASSERT_PTR(startswith(fname, name)));
945 if (!suffix)
946 return -ENOMEM;
947
948 *ASSERT_PTR(endswith(suffix, ".v")) = 0;
949
950 PickFilter filter = {
951 .type_mask = endswith(suffix, ".raw") ? (UINT32_C(1) << DT_REG) | (UINT32_C(1) << DT_BLK) : (UINT32_C(1) << DT_DIR),
952 .basename = name,
953 .architecture = _ARCHITECTURE_INVALID,
954 .suffix = suffix,
955 };
956
957 _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
958 r = path_pick(root,
959 rfd,
960 fname_path, /* This has to be the unresolved entry with the .v suffix */
961 &filter,
962 /* n_filters= */ 1,
963 PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
964 &result);
965 if (r < 0) {
966 log_debug_errno(r, "Failed to pick versioned image on '%s%s', skipping: %m", empty_to_root(root), skip_leading_slash(fname_path));
967 continue;
968 }
969 if (!result.path) {
970 log_debug("Found versioned directory '%s%s', without matching entry, skipping.", empty_to_root(root), skip_leading_slash(fname_path));
971 continue;
972 }
973
974 /* Refresh the stat data for the discovered target */
975 st = result.st;
976 close_and_replace(fd, result.fd);
977 free(resolved_file);
978 resolved_file = path_join(root, result.path);
979 if (!resolved_file)
980 return -ENOMEM;
981
982 /* fname and fname_path are invalid now because they would need to be set
983 * from result.path by extracting the filename to set
984 * fname = path_join(fname, filename) and then
985 * fname_path = path_join(*s, fname) but since they are unused we don't do it */
986 fname = NULL;
987 fname_path = mfree(fname_path);
988 } else if (!S_ISDIR(st.st_mode) && !S_ISBLK(st.st_mode)) {
989 log_debug("Ignoring non-directory and non-block device file '%s' without suffix.", fname);
990 continue;
991 }
992
993 /* Only put resolved paths into the image entry (incl. --root=).
994 * Defending against symlink races is not done
995 * and would be a TODO. */
996 r = image_make(class, name, fd, resolved_file, &st, ret);
997 if (IN_SET(r, -ENOENT, -EMEDIUMTYPE))
998 continue;
999 if (r < 0)
1000 return r;
1001
1002 if (ret)
1003 (*ret)->discoverable = true;
1004
1005 return 1;
1006 }
1007 }
1008
1009 if (scope == RUNTIME_SCOPE_SYSTEM && class == IMAGE_MACHINE && streq(name, ".host")) {
1010 r = image_make(class,
1011 ".host",
1012 /* fd= */ -EBADF,
1013 /* path= */ empty_to_root(root),
1014 /* st= */ NULL,
1015 ret);
1016 if (r < 0)
1017 return r;
1018
1019 if (ret)
1020 (*ret)->discoverable = true;
1021
1022 return 1;
1023 }
1024
1025 return -ENOENT;
1026 };
1027
1028 int image_from_path(const char *path, Image **ret) {
1029 int r;
1030
1031 /* Note that we don't set the 'discoverable' field of the returned object, because we don't check here whether
1032 * the image is in the image search path. And if it is we don't know if the path we used is actually not
1033 * overridden by another, different image earlier in the search path */
1034
1035 if (path_equal(path, "/"))
1036 return image_make(
1037 IMAGE_MACHINE,
1038 ".host",
1039 /* fd= */ -EBADF,
1040 /* path= */ "/",
1041 /* st= */ NULL,
1042 ret);
1043
1044 _cleanup_free_ char *absolute = NULL;
1045 r = path_make_absolute_cwd(path, &absolute);
1046 if (r < 0)
1047 return r;
1048
1049 return image_make(
1050 _IMAGE_CLASS_INVALID,
1051 /* pretty= */ NULL,
1052 /* fd= */ -EBADF,
1053 absolute,
1054 /* st= */ NULL,
1055 ret);
1056 }
1057
1058 int image_find_harder(
1059 RuntimeScope scope,
1060 ImageClass class,
1061 const char *name_or_path,
1062 const char *root,
1063 Image **ret) {
1064
1065 if (image_name_is_valid(name_or_path))
1066 return image_find(scope, class, name_or_path, root, ret);
1067
1068 return image_from_path(name_or_path, ret);
1069 }
1070
1071 int image_discover(
1072 RuntimeScope scope,
1073 ImageClass class,
1074 const char *root,
1075 Hashmap **images) {
1076
1077 int r;
1078
1079 assert(scope < _RUNTIME_SCOPE_MAX && scope != RUNTIME_SCOPE_GLOBAL);
1080 assert(class >= 0);
1081 assert(class < _IMAGE_CLASS_MAX);
1082 assert(images);
1083
1084 _cleanup_close_ int rfd = XAT_FDROOT; /* We only expect absolute paths */
1085 if (root) {
1086 rfd = open(root, O_CLOEXEC|O_DIRECTORY|O_PATH);
1087 if (rfd < 0)
1088 return log_debug_errno(errno, "Failed to open root directory '%s': %m", root);
1089 }
1090
1091 _cleanup_strv_free_ char **search = NULL;
1092 r = pick_image_search_path(scope, class, root, &search);
1093 if (r < 0)
1094 return r;
1095
1096 STRV_FOREACH(s, search) {
1097 _cleanup_closedir_ DIR *d = NULL;
1098 _cleanup_free_ char *search_path = NULL;
1099
1100 r = chase_and_opendirat(rfd, rfd, *s, /* chase_flags= */ 0, &search_path, &d);
1101 if (r == -ENOENT)
1102 continue;
1103 if (r < 0)
1104 return r;
1105
1106 FOREACH_DIRENT_ALL(de, d, return -errno) {
1107 _cleanup_free_ char *pretty = NULL, *fname_path = NULL, *chased_path = NULL, *resolved_file = NULL;
1108 _cleanup_(image_unrefp) Image *image = NULL;
1109 const char *fname = de->d_name;
1110 _cleanup_close_ int fd = -EBADF;
1111
1112 if (dot_or_dot_dot(fname))
1113 continue;
1114
1115 /* Ignore sysupdate temporary files */
1116 if (startswith(fname, ".sysupdate."))
1117 continue;
1118
1119 fname_path = path_join(search_path, fname);
1120 if (!fname_path)
1121 return -ENOMEM;
1122
1123 /* Follow symlinks only inside given root */
1124 r = chaseat(rfd, rfd, fname_path, /* flags= */ 0, &chased_path, &fd);
1125 if (r == -ENOENT)
1126 continue;
1127 if (r < 0)
1128 return r;
1129
1130 r = chaseat_prefix_root(chased_path, root, &resolved_file);
1131 if (r < 0)
1132 return r;
1133
1134 struct stat st;
1135 if (fstat(fd, &st) < 0)
1136 return -errno;
1137
1138 if (S_ISREG(st.st_mode)) {
1139 r = extract_image_basename(
1140 fname,
1141 image_class_suffix_to_string(class),
1142 STRV_MAKE(".raw"),
1143 &pretty,
1144 /* ret_suffix= */ NULL);
1145 if (r < 0) {
1146 log_debug_errno(r, "Skipping directory entry '%s', which doesn't look like an image.", fname);
1147 continue;
1148 }
1149 } else if (S_ISDIR(st.st_mode)) {
1150 const char *v;
1151
1152 v = endswith(fname, ".v");
1153 if (v) {
1154 _cleanup_free_ char *suffix = NULL, *nov = NULL;
1155
1156 nov = strndup(fname, v - fname); /* Chop off the .v */
1157 if (!nov)
1158 return -ENOMEM;
1159
1160 r = extract_image_basename(
1161 nov,
1162 image_class_suffix_to_string(class),
1163 STRV_MAKE(".raw", ".mstack", ""),
1164 &pretty,
1165 &suffix);
1166 if (r < 0) {
1167 log_debug_errno(r, "Skipping directory entry '%s', which doesn't look like a versioned image.", fname);
1168 continue;
1169 }
1170
1171 PickFilter filter = {
1172 .type_mask = endswith(suffix, ".raw") ? (UINT32_C(1) << DT_REG) | (UINT32_C(1) << DT_BLK) : (UINT32_C(1) << DT_DIR),
1173 .basename = pretty,
1174 .architecture = _ARCHITECTURE_INVALID,
1175 .suffix = suffix,
1176 };
1177
1178 _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
1179 r = path_pick(root,
1180 rfd,
1181 fname_path, /* This has to be the unresolved entry with the .v suffix */
1182 &filter,
1183 /* n_filters= */ 1,
1184 PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
1185 &result);
1186 if (r < 0) {
1187 log_debug_errno(r, "Failed to pick versioned image on '%s%s', skipping: %m", empty_to_root(root), skip_leading_slash(fname_path));
1188 continue;
1189 }
1190 if (!result.path) {
1191 log_debug("Found versioned directory '%s%s', without matching entry, skipping.", empty_to_root(root), skip_leading_slash(fname_path));
1192 continue;
1193 }
1194
1195 /* Refresh the stat data for the discovered target */
1196 st = result.st;
1197 close_and_replace(fd, result.fd);
1198 free(resolved_file);
1199 resolved_file = path_join(root, result.path);
1200 if (!resolved_file)
1201 return -ENOMEM;
1202
1203 /* fname and fname_path are invalid now because they would need to
1204 * be set from result.path by extracting the filename to set
1205 * fname = path_join(fname, filename) and then
1206 * fname_path = path_join(*s, fname) but since they are unused we
1207 * don't do it */
1208 fname = NULL;
1209 fname_path = mfree(fname_path);
1210 } else {
1211 r = extract_image_basename(
1212 fname,
1213 image_class_suffix_to_string(class),
1214 STRV_MAKE(".mstack", ""),
1215 &pretty,
1216 /* ret_suffix= */ NULL);
1217 if (r < 0) {
1218 log_debug_errno(r, "Skipping directory entry '%s', which doesn't look like an image.", fname);
1219 continue;
1220 }
1221 }
1222
1223 } else if (S_ISBLK(st.st_mode)) {
1224 r = extract_image_basename(
1225 fname,
1226 /* class_suffix= */ NULL,
1227 /* format_suffix= */ NULL,
1228 &pretty,
1229 /* ret_suffix= */ NULL);
1230 if (r < 0) {
1231 log_debug_errno(r, "Skipping directory entry '%s', which doesn't look like an image.", fname);
1232 continue;
1233 }
1234 } else {
1235 log_debug("Skipping directory entry '%s', which is neither regular file, directory nor block device.", fname);
1236 continue;
1237 }
1238
1239 if (hashmap_contains(*images, pretty))
1240 continue;
1241
1242 /* Only put resolved paths into the image entry.
1243 * Defending against symlink races is not done
1244 * and would be a TODO. */
1245 r = image_make(class, pretty, fd, resolved_file, &st, &image);
1246 if (IN_SET(r, -ENOENT, -EMEDIUMTYPE))
1247 continue;
1248 if (r < 0)
1249 return r;
1250
1251 image->discoverable = true;
1252
1253 r = hashmap_ensure_put(images, &image_hash_ops, image->name, image);
1254 if (r < 0)
1255 return r;
1256
1257 TAKE_PTR(image);
1258 }
1259 }
1260
1261 if (scope == RUNTIME_SCOPE_SYSTEM && class == IMAGE_MACHINE && !hashmap_contains(*images, ".host")) {
1262 _cleanup_(image_unrefp) Image *image = NULL;
1263
1264 r = image_make(IMAGE_MACHINE,
1265 ".host",
1266 /* fd= */ -EBADF,
1267 /* path= */ empty_to_root(root),
1268 /* st= */ NULL,
1269 &image);
1270 if (r < 0)
1271 return r;
1272
1273 image->discoverable = true;
1274
1275 r = hashmap_ensure_put(images, &image_hash_ops, image->name, image);
1276 if (r < 0)
1277 return r;
1278
1279 image = NULL;
1280 }
1281
1282 return 0;
1283 }
1284
1285 static int unpriv_remove_cb(
1286 RecurseDirEvent event,
1287 const char *path,
1288 int dir_fd,
1289 int inode_fd,
1290 const struct dirent *de,
1291 const struct statx *sx,
1292 void *userdata) {
1293
1294 int r, userns_fd = PTR_TO_FD(userdata);
1295
1296 assert(sx);
1297
1298 if (event == RECURSE_DIR_ENTER &&
1299 S_ISDIR(sx->stx_mode) &&
1300 uid_is_foreign(sx->stx_uid)) {
1301
1302 /* This is owned by the foreign UID range, and a dir, let's remove it via mountfsd userns
1303 * shenanigans. */
1304
1305 _cleanup_close_ int tree_fd = -EBADF;
1306 r = mountfsd_mount_directory_fd(
1307 /* vl= */ NULL,
1308 inode_fd,
1309 userns_fd,
1310 DISSECT_IMAGE_FOREIGN_UID,
1311 &tree_fd);
1312 if (r < 0)
1313 return r;
1314
1315 /* Fork off child that moves into userns and does the copying */
1316 r = pidref_safe_fork_full(
1317 "rm-tree",
1318 /* stdio_fds= */ NULL,
1319 (int[]) { userns_fd, tree_fd, }, 2,
1320 FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGTERM|FORK_WAIT|FORK_REOPEN_LOG,
1321 /* ret= */ NULL);
1322 if (r < 0)
1323 log_debug_errno(r, "Process that was supposed to remove subtree '%s' failed, ignoring: %m", empty_to_root(path));
1324 else if (r == 0) {
1325 /* child */
1326
1327 r = namespace_enter(
1328 /* pidns_fd= */ -EBADF,
1329 /* mntns_fd= */ -EBADF,
1330 /* netns_fd= */ -EBADF,
1331 userns_fd,
1332 /* root_fd= */ -EBADF);
1333 if (r < 0) {
1334 log_debug_errno(r, "Failed to join user namespace: %m");
1335 _exit(EXIT_FAILURE);
1336 }
1337
1338 _cleanup_close_ int dfd = fd_reopen(tree_fd, O_DIRECTORY|O_CLOEXEC);
1339 if (dfd < 0) {
1340 log_error_errno(r, "Failed to reopen tree fd: %m");
1341 _exit(EXIT_FAILURE);
1342 }
1343
1344 r = rm_rf_children(dfd, REMOVE_PHYSICAL|REMOVE_SUBVOLUME|REMOVE_CHMOD, /* root_dev= */ NULL);
1345 if (r < 0) {
1346 log_error_errno(r, "Failed to empty '%s' directory in foreign UID mode: %m", empty_to_root(path));
1347 _exit(EXIT_FAILURE);
1348 }
1349
1350 _exit(EXIT_SUCCESS);
1351 }
1352
1353 /* Don't descent further into this one, and delete it immediately */
1354 return RECURSE_DIR_UNLINK_GRACEFUL;
1355 }
1356
1357 /* Everything else try to remove */
1358 if (event == RECURSE_DIR_LEAVE)
1359 return RECURSE_DIR_UNLINK_GRACEFUL;
1360
1361 return RECURSE_DIR_CONTINUE;
1362 }
1363
1364 static int unprivileged_remove(Image *i) {
1365 int r;
1366
1367 assert(i);
1368
1369 /* We want this to work in complex .mstack/ hierarchies, where the main directory (and maybe a .v/
1370 * directory below or two) might be owned by the user themselves, but some subdirs might be owned by
1371 * the foreign UID range. We deal with this by recursively descending down the tree, and removing
1372 * foreign-owned ranges via userns shenanigans, and the rest just like that. */
1373
1374 _cleanup_close_ int userns_fd = nsresource_allocate_userns(
1375 /* vl= */ NULL,
1376 /* name= */ NULL,
1377 /* size= */ NSRESOURCE_UIDS_64K);
1378 if (userns_fd < 0)
1379 return log_debug_errno(userns_fd, "Failed to allocate transient user namespace: %m");
1380
1381 r = recurse_dir_at(
1382 AT_FDCWD,
1383 i->path,
1384 /* statx_mask= */ STATX_TYPE|STATX_UID,
1385 /* n_depth_max= */ UINT_MAX,
1386 RECURSE_DIR_IGNORE_DOT|RECURSE_DIR_ENSURE_TYPE|RECURSE_DIR_SAME_MOUNT|RECURSE_DIR_INODE_FD|RECURSE_DIR_TOPLEVEL,
1387 unpriv_remove_cb,
1388 FD_TO_PTR(userns_fd));
1389 if (r < 0)
1390 return r;
1391
1392 return 0;
1393 }
1394
1395 int image_remove(Image *i, RuntimeScope scope) {
1396 _cleanup_(release_lock_file) LockFile global_lock = LOCK_FILE_INIT, local_lock = LOCK_FILE_INIT;
1397 _cleanup_strv_free_ char **settings = NULL;
1398 int r;
1399
1400 assert(i);
1401
1402 if (image_is_vendor(i) || image_is_host(i))
1403 return -EROFS;
1404
1405 settings = image_settings_path(i, scope);
1406 if (!settings)
1407 return -ENOMEM;
1408
1409 /* Make sure we don't interfere with a running nspawn */
1410 r = image_path_lock(scope, i->path, LOCK_EX|LOCK_NB, &global_lock, &local_lock);
1411 if (r < 0)
1412 return r;
1413
1414 switch (i->type) {
1415
1416 case IMAGE_SUBVOLUME:
1417
1418 /* Let's unlink first, maybe it is a symlink? If that works we are happy. Otherwise, let's get out the
1419 * big guns */
1420 if (unlink(i->path) < 0) {
1421 r = btrfs_subvol_remove(i->path, BTRFS_REMOVE_RECURSIVE|BTRFS_REMOVE_QUOTA);
1422 if (r < 0)
1423 return r;
1424 }
1425
1426 break;
1427
1428 case IMAGE_DIRECTORY:
1429 /* Allow deletion of read-only directories */
1430 (void) chattr_path(i->path, 0, FS_IMMUTABLE_FL);
1431
1432 _fallthrough_;
1433
1434 case IMAGE_MSTACK:
1435 /* If this is foreign owned, try an unprivileged remove first, but accept if that doesn't work, and do it directly either way, maybe it works */
1436 if (i->foreign_uid_owned)
1437 (void) unprivileged_remove(i);
1438
1439 r = rm_rf(i->path, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_SUBVOLUME);
1440 if (r < 0)
1441 return r;
1442
1443 break;
1444
1445 case IMAGE_BLOCK:
1446
1447 /* If this is inside of /dev, then it's a real block device, hence let's not touch the device node
1448 * itself (but let's remove the stuff stored alongside it). If it's anywhere else, let's try to unlink
1449 * the thing (it's most likely a symlink after all). */
1450
1451 if (path_startswith(i->path, "/dev"))
1452 break;
1453
1454 _fallthrough_;
1455 case IMAGE_RAW:
1456 if (unlink(i->path) < 0)
1457 return -errno;
1458 break;
1459
1460 default:
1461 return -EOPNOTSUPP;
1462 }
1463
1464 STRV_FOREACH(j, settings)
1465 if (unlink(*j) < 0 && errno != ENOENT)
1466 log_debug_errno(errno, "Failed to unlink %s, ignoring: %m", *j);
1467
1468 NULSTR_FOREACH(suffix, auxiliary_suffixes_nulstr) {
1469 _cleanup_free_ char *aux = NULL;
1470 r = image_auxiliary_path(i, suffix, &aux);
1471 if (r < 0)
1472 return r;
1473
1474 if (unlink(aux) < 0 && errno != ENOENT)
1475 log_debug_errno(errno, "Failed to unlink %s, ignoring: %m", aux);
1476 }
1477
1478 return 0;
1479 }
1480
1481 static int rename_auxiliary_file(const char *path, const char *new_name, const char *suffix) {
1482 int r;
1483
1484 assert(path);
1485 assert(new_name);
1486 assert(suffix);
1487
1488 _cleanup_free_ char *fn = strjoin(new_name, suffix);
1489 if (!fn)
1490 return -ENOMEM;
1491
1492 _cleanup_free_ char *rs = NULL;
1493 r = file_in_same_dir(path, fn, &rs);
1494 if (r < 0)
1495 return r;
1496
1497 return rename_noreplace(AT_FDCWD, path, AT_FDCWD, rs);
1498 }
1499
1500 int image_rename(Image *i, const char *new_name, RuntimeScope scope) {
1501 _cleanup_(release_lock_file) LockFile global_lock = LOCK_FILE_INIT, local_lock = LOCK_FILE_INIT, name_lock = LOCK_FILE_INIT;
1502 _cleanup_free_ char *new_path = NULL, *nn = NULL;
1503 _cleanup_strv_free_ char **settings = NULL;
1504 unsigned file_attr = 0;
1505 int r;
1506
1507 assert(i);
1508
1509 if (!image_name_is_valid(new_name))
1510 return -EINVAL;
1511
1512 if (image_is_vendor(i) || image_is_host(i))
1513 return -EROFS;
1514
1515 settings = image_settings_path(i, scope);
1516 if (!settings)
1517 return -ENOMEM;
1518
1519 /* Make sure we don't interfere with a running nspawn */
1520 r = image_path_lock(scope, i->path, LOCK_EX|LOCK_NB, &global_lock, &local_lock);
1521 if (r < 0)
1522 return r;
1523
1524 /* Make sure nobody takes the new name, between the time we
1525 * checked it is currently unused in all search paths, and the
1526 * time we take possession of it */
1527 r = image_name_lock(scope, new_name, LOCK_EX|LOCK_NB, &name_lock);
1528 if (r < 0)
1529 return r;
1530
1531 r = image_find(scope, IMAGE_MACHINE, new_name, NULL, NULL);
1532 if (r >= 0)
1533 return -EEXIST;
1534 if (r != -ENOENT)
1535 return r;
1536
1537 switch (i->type) {
1538
1539 case IMAGE_DIRECTORY:
1540 /* Turn of the immutable bit while we rename the image, so that we can rename it */
1541 (void) read_attr_at(AT_FDCWD, i->path, &file_attr);
1542
1543 if (file_attr & FS_IMMUTABLE_FL)
1544 (void) chattr_path(i->path, 0, FS_IMMUTABLE_FL);
1545
1546 _fallthrough_;
1547 case IMAGE_SUBVOLUME:
1548 r = file_in_same_dir(i->path, new_name, &new_path);
1549 break;
1550
1551 case IMAGE_BLOCK:
1552
1553 /* Refuse renaming raw block devices in /dev, the names are picked by udev after all. */
1554 if (path_startswith(i->path, "/dev"))
1555 return -EROFS;
1556
1557 r = file_in_same_dir(i->path, new_name, &new_path);
1558 break;
1559
1560 case IMAGE_RAW: {
1561 const char *fn;
1562
1563 fn = strjoina(new_name, ".raw");
1564
1565 r = file_in_same_dir(i->path, fn, &new_path);
1566 break;
1567 }
1568
1569 default:
1570 return -EOPNOTSUPP;
1571 }
1572 if (r < 0)
1573 return r;
1574
1575 nn = strdup(new_name);
1576 if (!nn)
1577 return -ENOMEM;
1578
1579 r = rename_noreplace(AT_FDCWD, i->path, AT_FDCWD, new_path);
1580 if (r < 0)
1581 return r;
1582
1583 /* Restore the immutable bit, if it was set before */
1584 if (file_attr & FS_IMMUTABLE_FL)
1585 (void) chattr_path(new_path, FS_IMMUTABLE_FL, FS_IMMUTABLE_FL);
1586
1587 free_and_replace(i->path, new_path);
1588 free_and_replace(i->name, nn);
1589
1590 STRV_FOREACH(j, settings) {
1591 r = rename_auxiliary_file(*j, new_name, ".nspawn");
1592 if (r < 0 && r != -ENOENT)
1593 log_debug_errno(r, "Failed to rename settings file %s, ignoring: %m", *j);
1594 }
1595
1596 NULSTR_FOREACH(suffix, auxiliary_suffixes_nulstr) {
1597 _cleanup_free_ char *aux = NULL;
1598 r = image_auxiliary_path(i, suffix, &aux);
1599 if (r < 0)
1600 return r;
1601
1602 r = rename_auxiliary_file(aux, new_name, suffix);
1603 if (r < 0 && r != -ENOENT)
1604 log_debug_errno(r, "Failed to rename roothash file %s, ignoring: %m", aux);
1605 }
1606
1607 return 0;
1608 }
1609
1610 static int clone_auxiliary_file(const char *path, const char *new_name, const char *suffix) {
1611 int r;
1612
1613 assert(path);
1614 assert(new_name);
1615 assert(suffix);
1616
1617 _cleanup_free_ char *fn = strjoin(new_name, suffix);
1618 if (!fn)
1619 return -ENOMEM;
1620
1621 _cleanup_free_ char *rs = NULL;
1622 r = file_in_same_dir(path, fn, &rs);
1623 if (r < 0)
1624 return r;
1625
1626 return copy_file_atomic(path, rs, 0664, COPY_REFLINK);
1627 }
1628
1629 static int get_pool_directory(
1630 RuntimeScope scope,
1631 ImageClass class,
1632 const char *fname,
1633 const char *suffix,
1634 char **ret) {
1635
1636 int r;
1637
1638 assert(scope >= 0);
1639 assert(scope < _RUNTIME_SCOPE_MAX);
1640 assert(class >= 0);
1641 assert(class < _IMAGE_CLASS_MAX);
1642 assert(ret);
1643
1644 _cleanup_free_ char *root = NULL;
1645 switch (scope) {
1646
1647 case RUNTIME_SCOPE_SYSTEM:
1648 r = sd_path_lookup(SD_PATH_SYSTEM_STATE_PRIVATE, /* suffix= */ NULL, &root);
1649 break;
1650
1651 case RUNTIME_SCOPE_USER:
1652 r = sd_path_lookup(SD_PATH_USER_STATE_PRIVATE, /* suffix= */ NULL, &root);
1653 break;
1654
1655 default:
1656 return -EOPNOTSUPP;
1657 }
1658 if (r < 0)
1659 return r;
1660
1661 const char *n = image_dirname_to_string(class);
1662 if (!n)
1663 return -EOPNOTSUPP;
1664
1665 _cleanup_free_ char *j = NULL;
1666 const char *fn;
1667 if (fname && suffix) {
1668 j = strjoin(fname, suffix);
1669 if (!j)
1670 return -ENOMEM;
1671 fn = j;
1672 } else
1673 fn = fname ?: suffix;
1674
1675 _cleanup_free_ char *p = path_join(root, n, fn);
1676 if (!p)
1677 return -ENOMEM;
1678
1679 *ret = TAKE_PTR(p);
1680 return 0;
1681 }
1682
1683 static int unprivileged_clone(Image *i, const char *new_path) {
1684 int r;
1685
1686 assert(i);
1687 assert(new_path);
1688
1689 _cleanup_close_ int userns_fd = nsresource_allocate_userns(
1690 /* vl= */ NULL,
1691 /* name= */ NULL,
1692 /* size= */ NSRESOURCE_UIDS_64K);
1693 if (userns_fd < 0)
1694 return log_debug_errno(userns_fd, "Failed to allocate transient user namespace: %m");
1695
1696 _cleanup_(sd_varlink_unrefp) sd_varlink *link = NULL;
1697 r = mountfsd_connect(&link);
1698 if (r < 0)
1699 return r;
1700
1701 /* Map original image */
1702 _cleanup_close_ int tree_fd = -EBADF;
1703 r = mountfsd_mount_directory(
1704 link,
1705 i->path,
1706 userns_fd,
1707 DISSECT_IMAGE_FOREIGN_UID,
1708 &tree_fd);
1709 if (r < 0)
1710 return r;
1711
1712 /* Make new image */
1713 _cleanup_close_ int new_fd = -EBADF;
1714 r = mountfsd_make_directory(
1715 link,
1716 new_path,
1717 MODE_INVALID,
1718 /* flags= */ 0,
1719 &new_fd);
1720 if (r < 0)
1721 return 0;
1722
1723 /* Mount new image */
1724 _cleanup_close_ int target_fd = -EBADF;
1725 r = mountfsd_mount_directory_fd(
1726 link,
1727 new_fd,
1728 userns_fd,
1729 DISSECT_IMAGE_FOREIGN_UID,
1730 &target_fd);
1731 if (r < 0)
1732 return r;
1733
1734 link = sd_varlink_unref(link);
1735
1736 /* Fork off child that moves into userns and does the copying */
1737 return copy_tree_at_foreign(tree_fd, target_fd, userns_fd);
1738 }
1739
1740 int image_clone(Image *i, const char *new_name, bool read_only, RuntimeScope scope) {
1741 _cleanup_(release_lock_file) LockFile name_lock = LOCK_FILE_INIT;
1742 _cleanup_strv_free_ char **settings = NULL;
1743 int r;
1744
1745 assert(i);
1746
1747 if (!image_name_is_valid(new_name))
1748 return -EINVAL;
1749
1750 settings = image_settings_path(i, scope);
1751 if (!settings)
1752 return -ENOMEM;
1753
1754 /* Make sure nobody takes the new name, between the time we
1755 * checked it is currently unused in all search paths, and the
1756 * time we take possession of it */
1757 r = image_name_lock(scope, new_name, LOCK_EX|LOCK_NB, &name_lock);
1758 if (r < 0)
1759 return r;
1760
1761 r = image_find(scope, i->class, new_name, NULL, NULL);
1762 if (r >= 0)
1763 return -EEXIST;
1764 if (r != -ENOENT)
1765 return r;
1766
1767 switch (i->type) {
1768
1769 case IMAGE_SUBVOLUME:
1770 case IMAGE_DIRECTORY: {
1771 /* If we can we'll always try to create a new btrfs subvolume here, even if the source is a plain
1772 * directory. */
1773
1774 _cleanup_free_ char *new_path = NULL;
1775 r = get_pool_directory(scope, i->class, new_name, /* suffix= */ NULL, &new_path);
1776 if (r < 0)
1777 return r;
1778
1779 if (i->foreign_uid_owned)
1780 r = unprivileged_clone(i, new_path);
1781 else {
1782 r = btrfs_subvol_snapshot_at(
1783 AT_FDCWD, i->path,
1784 AT_FDCWD, new_path,
1785 (read_only ? BTRFS_SNAPSHOT_READ_ONLY : 0) |
1786 BTRFS_SNAPSHOT_FALLBACK_COPY |
1787 BTRFS_SNAPSHOT_FALLBACK_DIRECTORY |
1788 BTRFS_SNAPSHOT_FALLBACK_IMMUTABLE |
1789 BTRFS_SNAPSHOT_RECURSIVE |
1790 BTRFS_SNAPSHOT_QUOTA);
1791 if (r >= 0)
1792 /* Enable "subtree" quotas for the copy, if we didn't copy any quota from the source. */
1793 (void) btrfs_subvol_auto_qgroup(new_path, /* subvol_id= */ 0, /* create_intermediary_qgroup= */ true);
1794 }
1795
1796 break;
1797 }
1798
1799 case IMAGE_RAW: {
1800 _cleanup_free_ char *new_path = NULL;
1801 r = get_pool_directory(scope, i->class, new_name, ".raw", &new_path);
1802 if (r < 0)
1803 return r;
1804
1805 r = copy_file_atomic(i->path, new_path, read_only ? 0444 : 0644,
1806 COPY_REFLINK|COPY_CRTIME|COPY_NOCOW_AFTER);
1807 break;
1808 }
1809
1810 case IMAGE_BLOCK:
1811 default:
1812 return -EOPNOTSUPP;
1813 }
1814 if (r < 0)
1815 return r;
1816
1817 STRV_FOREACH(j, settings) {
1818 r = clone_auxiliary_file(*j, new_name, ".nspawn");
1819 if (r < 0 && r != -ENOENT)
1820 log_debug_errno(r, "Failed to clone settings %s, ignoring: %m", *j);
1821 }
1822
1823 NULSTR_FOREACH(suffix, auxiliary_suffixes_nulstr) {
1824 _cleanup_free_ char *aux = NULL;
1825 r = image_auxiliary_path(i, suffix, &aux);
1826 if (r < 0)
1827 return r;
1828
1829 r = clone_auxiliary_file(aux, new_name, suffix);
1830 if (r < 0 && r != -ENOENT)
1831 log_debug_errno(r, "Failed to clone root hash file %s, ignoring: %m", aux);
1832 }
1833
1834 return 0;
1835 }
1836
1837 int image_read_only(Image *i, bool b, RuntimeScope scope) {
1838 _cleanup_(release_lock_file) LockFile global_lock = LOCK_FILE_INIT, local_lock = LOCK_FILE_INIT;
1839 int r;
1840
1841 assert(i);
1842
1843 if (image_is_vendor(i) || image_is_host(i) || image_is_hidden(i))
1844 return -EROFS;
1845
1846 /* Make sure we don't interfere with a running nspawn */
1847 r = image_path_lock(scope, i->path, LOCK_EX|LOCK_NB, &global_lock, &local_lock);
1848 if (r < 0)
1849 return r;
1850
1851 switch (i->type) {
1852
1853 case IMAGE_SUBVOLUME:
1854
1855 /* Note that we set the flag only on the top-level
1856 * subvolume of the image. */
1857
1858 r = btrfs_subvol_set_read_only(i->path, b);
1859 if (r < 0)
1860 return r;
1861
1862 break;
1863
1864 case IMAGE_DIRECTORY:
1865 /* For simple directory trees we cannot use the access
1866 mode of the top-level directory, since it has an
1867 effect on the container itself. However, we can
1868 use the "immutable" flag, to at least make the
1869 top-level directory read-only. It's not as good as
1870 a read-only subvolume, but at least something, and
1871 we can read the value back. */
1872
1873 r = chattr_path(i->path, b ? FS_IMMUTABLE_FL : 0, FS_IMMUTABLE_FL);
1874 if (r < 0)
1875 return r;
1876
1877 break;
1878
1879 case IMAGE_RAW: {
1880 struct stat st;
1881
1882 if (stat(i->path, &st) < 0)
1883 return -errno;
1884
1885 if (chmod(i->path, (st.st_mode & 0444) | (b ? 0000 : 0200)) < 0)
1886 return -errno;
1887
1888 /* If the images is now read-only, it's a good time to
1889 * defrag it, given that no write patterns will
1890 * fragment it again. */
1891 if (b)
1892 (void) btrfs_defrag(i->path);
1893 break;
1894 }
1895
1896 case IMAGE_BLOCK: {
1897 _cleanup_close_ int fd = -EBADF;
1898 int state = b;
1899
1900 fd = open(i->path, O_CLOEXEC|O_RDONLY|O_NONBLOCK|O_NOCTTY);
1901 if (fd < 0)
1902 return -errno;
1903
1904 r = fd_verify_block(fd);
1905 if (r < 0)
1906 return r;
1907
1908 if (ioctl(fd, BLKROSET, &state) < 0)
1909 return -errno;
1910
1911 break;
1912 }
1913
1914 default:
1915 return -EOPNOTSUPP;
1916 }
1917
1918 i->read_only = b;
1919 return 0;
1920 }
1921
1922 static int make_lock_dir(RuntimeScope scope) {
1923 int r;
1924
1925 _cleanup_free_ char *p = NULL;
1926 r = runtime_directory_generic(scope, "systemd", &p);
1927 if (r < 0)
1928 return r;
1929
1930 _cleanup_close_ int pfd = open_mkdir_at(AT_FDCWD, p, O_CLOEXEC, 0755);
1931 if (pfd < 0)
1932 return pfd;
1933
1934 _cleanup_close_ int nfd = open_mkdir_at(pfd, "nspawn", O_CLOEXEC, 0755);
1935 if (nfd < 0)
1936 return nfd;
1937
1938 r = RET_NERRNO(mkdirat(nfd, "locks", 0700));
1939 if (r == -EEXIST)
1940 return 0;
1941 if (r < 0)
1942 return r;
1943
1944 return 1;
1945 }
1946
1947 int image_path_lock(
1948 RuntimeScope scope,
1949 const char *path,
1950 int operation,
1951 LockFile *ret_global,
1952 LockFile *ret_local) {
1953
1954 _cleanup_free_ char *p = NULL;
1955 LockFile t = LOCK_FILE_INIT;
1956 struct stat st;
1957 bool exclusive;
1958 int r;
1959
1960 assert(path);
1961 assert(ret_local);
1962
1963 /* Locks an image path. This actually creates two locks: one "local" one, next to the image path
1964 * itself, which might be shared via NFS. And another "global" one, in /run/, that uses the
1965 * device/inode number. This has the benefit that we can even lock a tree that is a mount point,
1966 * correctly. */
1967
1968 if (!path_is_absolute(path))
1969 return -EINVAL;
1970
1971 switch (operation & (LOCK_SH|LOCK_EX)) {
1972 case LOCK_SH:
1973 exclusive = false;
1974 break;
1975 case LOCK_EX:
1976 exclusive = true;
1977 break;
1978 default:
1979 return -EINVAL;
1980 }
1981
1982 if (getenv_bool("SYSTEMD_NSPAWN_LOCK") == 0) {
1983 *ret_local = LOCK_FILE_INIT;
1984 if (ret_global)
1985 *ret_global = LOCK_FILE_INIT;
1986 return 0;
1987 }
1988
1989 /* Prohibit taking exclusive locks on the host image. We can't allow this, since we ourselves are
1990 * running off it after all, and we don't want any images to manipulate the host image. We make an
1991 * exception for shared locks however: we allow those (and make them NOPs since there's no point in
1992 * taking them if there can't be exclusive locks). Strictly speaking these are questionable as well,
1993 * since it means changes made to the host might propagate to the container as they happen (and a
1994 * shared lock kinda suggests that no changes happen at all while it is in place), but it's too
1995 * useful not to allow read-only containers off the host root, hence let's support this, and trust
1996 * the user to do the right thing with this. */
1997 if (path_equal(path, "/")) {
1998 if (exclusive)
1999 return -EBUSY;
2000
2001 *ret_local = LOCK_FILE_INIT;
2002 if (ret_global)
2003 *ret_global = LOCK_FILE_INIT;
2004 return 0;
2005 }
2006
2007 if (ret_global) {
2008 if (stat(path, &st) < 0)
2009 log_debug_errno(errno, "Failed to stat() image '%s', not locking image: %m", path);
2010 else {
2011 r = runtime_directory_generic(scope, "systemd/nspawn/locks/", &p);
2012 if (r < 0)
2013 return r;
2014
2015 if (S_ISBLK(st.st_mode))
2016 r = strextendf(&p, "block-" DEVNUM_FORMAT_STR, DEVNUM_FORMAT_VAL(st.st_rdev));
2017 else if (S_ISDIR(st.st_mode) || S_ISREG(st.st_mode))
2018 r = strextendf(&p, "inode-%" PRIu64 ":%" PRIu64, (uint64_t) st.st_dev, (uint64_t) st.st_ino);
2019 else
2020 return -ENOTTY;
2021 if (r < 0)
2022 return r;
2023 }
2024 }
2025
2026 /* For block devices we don't need the "local" lock, as the major/minor lock above should be
2027 * sufficient, since block devices are host local anyway. */
2028 if (!path_startswith(path, "/dev/")) {
2029 r = make_lock_file_for(path, operation, &t);
2030 if (r < 0) {
2031 if (exclusive || r != -EROFS)
2032 return r;
2033
2034 log_debug_errno(r, "Failed to create shared lock for '%s', ignoring: %m", path);
2035 }
2036 }
2037
2038 if (p) {
2039 (void) make_lock_dir(scope);
2040
2041 r = make_lock_file(p, operation, ret_global);
2042 if (r < 0) {
2043 release_lock_file(&t);
2044 return r;
2045 }
2046 } else if (ret_global)
2047 *ret_global = LOCK_FILE_INIT;
2048
2049 *ret_local = t;
2050 return 0;
2051 }
2052
2053 int image_set_limit(Image *i, uint64_t referenced_max) {
2054 int r;
2055
2056 assert(i);
2057
2058 if (image_is_vendor(i) || image_is_host(i))
2059 return -EROFS;
2060
2061 if (i->type != IMAGE_SUBVOLUME)
2062 return -EOPNOTSUPP;
2063
2064 /* We set the quota both for the subvolume as well as for the
2065 * subtree. The latter is mostly for historical reasons, since
2066 * we didn't use to have a concept of subtree quota, and hence
2067 * only modified the subvolume quota. */
2068
2069 (void) btrfs_qgroup_set_limit(i->path, 0, referenced_max);
2070 (void) btrfs_subvol_auto_qgroup(i->path, 0, true);
2071 r = btrfs_subvol_set_subtree_quota_limit(i->path, 0, referenced_max);
2072 if (r < 0)
2073 return r;
2074
2075 (void) image_update_quota(i, -EBADF);
2076 return 0;
2077 }
2078
2079 int image_set_pool_limit(RuntimeScope scope, ImageClass class, uint64_t referenced_max) {
2080 int r;
2081
2082 assert(scope >= 0 && scope < _RUNTIME_SCOPE_MAX);
2083 assert(class >= 0 && class < _IMAGE_CLASS_MAX);
2084
2085 _cleanup_free_ char *pool = NULL;
2086 r = get_pool_directory(scope, class, /* fname= */ NULL, /* suffix= */ NULL, &pool);
2087 if (r < 0)
2088 return r;
2089
2090 r = btrfs_qgroup_set_limit(pool, /* qgroupid= */ 0, referenced_max);
2091 if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
2092 return r;
2093 if (r < 0)
2094 log_debug_errno(r, "Failed to set limit on btrfs quota group for '%s', ignoring: %m", pool);
2095
2096 r = btrfs_subvol_set_subtree_quota_limit(pool, /* subvol_id= */ 0, referenced_max);
2097 if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
2098 return r;
2099 if (r < 0)
2100 return log_debug_errno(r, "Failed to set subtree quota limit for '%s': %m", pool);
2101
2102 return 0;
2103 }
2104
2105 int image_get_pool_path(RuntimeScope scope, ImageClass class, char **ret) {
2106 assert(scope >= 0 && scope < _RUNTIME_SCOPE_MAX);
2107 assert(class >= 0 && class < _IMAGE_CLASS_MAX);
2108 assert(ret);
2109
2110 return get_pool_directory(scope, class, /* fname= */ NULL, /* suffix= */ NULL, ret);
2111 }
2112
2113 int image_get_pool_usage(RuntimeScope scope, ImageClass class, uint64_t *ret) {
2114 int r;
2115
2116 assert(scope >= 0 && scope < _RUNTIME_SCOPE_MAX);
2117 assert(class >= 0 && class < _IMAGE_CLASS_MAX);
2118 assert(ret);
2119
2120 _cleanup_free_ char *pool = NULL;
2121 r = get_pool_directory(scope, class, /* fname= */ NULL, /* suffix= */ NULL, &pool);
2122 if (r < 0)
2123 return r;
2124
2125 _cleanup_close_ int fd = open(pool, O_RDONLY|O_CLOEXEC|O_DIRECTORY);
2126 if (fd < 0)
2127 return -errno;
2128
2129 BtrfsQuotaInfo q;
2130 r = btrfs_subvol_get_subtree_quota_fd(fd, /* subvol_id= */ 0, &q);
2131 if (r < 0)
2132 return r;
2133
2134 *ret = q.referenced;
2135 return 0;
2136 }
2137
2138 int image_get_pool_limit(RuntimeScope scope, ImageClass class, uint64_t *ret) {
2139 int r;
2140
2141 assert(scope >= 0 && scope < _RUNTIME_SCOPE_MAX);
2142 assert(class >= 0 && class < _IMAGE_CLASS_MAX);
2143 assert(ret);
2144
2145 _cleanup_free_ char *pool = NULL;
2146 r = get_pool_directory(scope, class, /* fname= */ NULL, /* suffix= */ NULL, &pool);
2147 if (r < 0)
2148 return r;
2149
2150 _cleanup_close_ int fd = open(pool, O_RDONLY|O_CLOEXEC|O_DIRECTORY);
2151 if (fd < 0)
2152 return -errno;
2153
2154 BtrfsQuotaInfo q;
2155 r = btrfs_subvol_get_subtree_quota_fd(fd, /* subvol_id= */ 0, &q);
2156 if (r < 0)
2157 return r;
2158
2159 *ret = q.referenced_max;
2160 return 0;
2161 }
2162
2163 static int check_btrfs(const char *path) {
2164 struct statfs sfs;
2165 int r;
2166
2167 if (statfs(path, &sfs) < 0) {
2168 if (errno != ENOENT)
2169 return -errno;
2170
2171 _cleanup_free_ char *parent = NULL;
2172 r = path_extract_directory(path, &parent);
2173 if (r < 0)
2174 return r;
2175
2176 if (statfs(parent, &sfs) < 0)
2177 return -errno;
2178 }
2179
2180 return F_TYPE_EQUAL(sfs.f_type, BTRFS_SUPER_MAGIC);
2181 }
2182
2183 int image_setup_pool(RuntimeScope scope, ImageClass class, bool use_btrfs_subvol, bool use_btrfs_quota) {
2184 int r;
2185
2186 assert(class >= 0 && class < _IMAGE_CLASS_MAX);
2187
2188 _cleanup_free_ char *pool = NULL;
2189 r = image_get_pool_path(scope, class, &pool);
2190 if (r < 0)
2191 return r;
2192
2193 r = check_btrfs(pool);
2194 if (r <= 0)
2195 return r;
2196
2197 if (!use_btrfs_subvol)
2198 return 0;
2199
2200 (void) btrfs_subvol_make_label(pool);
2201
2202 if (!use_btrfs_quota)
2203 return 0;
2204
2205 r = btrfs_quota_enable(pool, /* b= */ true);
2206 if (r < 0)
2207 log_warning_errno(r, "Failed to enable quota for %s, ignoring: %m", pool);
2208
2209 r = btrfs_subvol_auto_qgroup(pool, /* subvol_id= */ 0, /* create_intermediary_qgroup= */ true);
2210 if (r < 0)
2211 log_warning_errno(r, "Failed to set up default quota hierarchy for %s, ignoring: %m", pool);
2212
2213 return 0;
2214 }
2215
2216 int image_read_metadata(Image *i, const char *root, const ImagePolicy *image_policy, RuntimeScope scope) {
2217 _cleanup_(release_lock_file) LockFile global_lock = LOCK_FILE_INIT, local_lock = LOCK_FILE_INIT;
2218 int r;
2219
2220 assert(i);
2221
2222 r = image_path_lock(scope, i->path, LOCK_SH|LOCK_NB, &global_lock, &local_lock);
2223 if (r < 0)
2224 return r;
2225
2226 switch (i->type) {
2227
2228 case IMAGE_SUBVOLUME:
2229 case IMAGE_DIRECTORY: {
2230 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL, **sysext_release = NULL, **confext_release = NULL;
2231 _cleanup_free_ char *hostname = NULL, *path = NULL;
2232 sd_id128_t machine_id = SD_ID128_NULL;
2233
2234 if (i->class == IMAGE_SYSEXT) {
2235 r = extension_has_forbidden_content(i->path);
2236 if (r < 0)
2237 return r;
2238 if (r > 0)
2239 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM),
2240 "Conflicting content found in image %s, refusing.",
2241 i->name);
2242 }
2243
2244 r = chase("/etc/hostname", i->path, CHASE_PREFIX_ROOT|CHASE_TRAIL_SLASH, &path, NULL);
2245 if (r < 0 && r != -ENOENT)
2246 log_debug_errno(r, "Failed to chase /etc/hostname in image %s: %m", i->name);
2247 else if (r >= 0) {
2248 r = read_etc_hostname(path, /* substitute_wildcards= */ false, &hostname);
2249 if (r < 0)
2250 log_debug_errno(r, "Failed to read /etc/hostname of image %s: %m", i->name);
2251 }
2252
2253 path = mfree(path);
2254
2255 r = id128_get_machine(i->path, &machine_id);
2256 if (r < 0)
2257 log_debug_errno(r, "Failed to read machine ID in image %s, ignoring: %m", i->name);
2258
2259 r = chase("/etc/machine-info", i->path, CHASE_PREFIX_ROOT|CHASE_TRAIL_SLASH, &path, NULL);
2260 if (r < 0 && r != -ENOENT)
2261 log_debug_errno(r, "Failed to chase /etc/machine-info in image %s: %m", i->name);
2262 else if (r >= 0) {
2263 r = load_env_file_pairs(NULL, path, &machine_info);
2264 if (r < 0)
2265 log_debug_errno(r, "Failed to parse machine-info data of %s: %m", i->name);
2266 }
2267
2268 r = load_os_release_pairs(i->path, &os_release);
2269 if (r < 0)
2270 log_debug_errno(r, "Failed to read os-release in image, ignoring: %m");
2271
2272 r = load_extension_release_pairs(i->path, IMAGE_SYSEXT, i->name, /* relax_extension_release_check= */ false, &sysext_release);
2273 if (r < 0)
2274 log_debug_errno(r, "Failed to read sysext-release in image, ignoring: %m");
2275
2276 r = load_extension_release_pairs(i->path, IMAGE_CONFEXT, i->name, /* relax_extension_release_check= */ false, &confext_release);
2277 if (r < 0)
2278 log_debug_errno(r, "Failed to read confext-release in image, ignoring: %m");
2279
2280 free_and_replace(i->hostname, hostname);
2281 i->machine_id = machine_id;
2282 strv_free_and_replace(i->machine_info, machine_info);
2283 strv_free_and_replace(i->os_release, os_release);
2284 strv_free_and_replace(i->sysext_release, sysext_release);
2285 strv_free_and_replace(i->confext_release, confext_release);
2286 break;
2287 }
2288
2289 case IMAGE_RAW:
2290 case IMAGE_BLOCK: {
2291 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
2292 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
2293 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
2294 DissectImageFlags flags =
2295 DISSECT_IMAGE_GENERIC_ROOT |
2296 DISSECT_IMAGE_REQUIRE_ROOT |
2297 DISSECT_IMAGE_RELAX_VAR_CHECK |
2298 DISSECT_IMAGE_READ_ONLY |
2299 DISSECT_IMAGE_USR_NO_ROOT |
2300 DISSECT_IMAGE_ADD_PARTITION_DEVICES |
2301 DISSECT_IMAGE_PIN_PARTITION_DEVICES |
2302 DISSECT_IMAGE_VALIDATE_OS |
2303 DISSECT_IMAGE_VALIDATE_OS_EXT |
2304 DISSECT_IMAGE_ALLOW_USERSPACE_VERITY;
2305
2306 r = loop_device_make_by_path(
2307 i->path,
2308 O_RDONLY,
2309 /* sector_size= */ UINT32_MAX,
2310 LO_FLAGS_PARTSCAN,
2311 LOCK_SH,
2312 &d);
2313 if (r < 0)
2314 return log_debug_errno(r, "Failed to create loopback device of '%s': %m", i->path);
2315
2316 r = dissect_loop_device(
2317 d,
2318 &verity,
2319 /* mount_options= */ NULL,
2320 image_policy,
2321 /* image_filter= */ NULL,
2322 flags,
2323 &m);
2324 if (r < 0)
2325 return log_debug_errno(r, "Failed to dissect image '%s': %m", i->path);
2326
2327 r = dissected_image_load_verity_sig_partition(
2328 m,
2329 d->fd,
2330 &verity);
2331 if (r < 0)
2332 return log_debug_errno(r, "Failed to load Verity signature partition of '%s': %m", i->path);
2333
2334 r = dissected_image_guess_verity_roothash(
2335 m,
2336 &verity);
2337 if (r < 0)
2338 return log_debug_errno(r, "Failed to guess Verity root hash of '%s': %m", i->path);
2339
2340 r = dissected_image_decrypt(
2341 m,
2342 root,
2343 /* passphrase= */ NULL,
2344 &verity,
2345 image_policy,
2346 flags);
2347 if (r < 0)
2348 return log_debug_errno(r, "Failed to decrypt image '%s': %m", i->path);
2349
2350 /* Do not use the image name derived from the backing file of the loop device */
2351 r = free_and_strdup(&m->image_name, i->name);
2352 if (r < 0)
2353 return r;
2354
2355 r = dissected_image_acquire_metadata(
2356 m,
2357 /* userns_fd= */ -EBADF,
2358 flags);
2359 if (r < 0)
2360 return log_debug_errno(r, "Failed to acquire metadata from image '%s': %m", i->path);
2361
2362 free_and_replace(i->hostname, m->hostname);
2363 i->machine_id = m->machine_id;
2364 strv_free_and_replace(i->machine_info, m->machine_info);
2365 strv_free_and_replace(i->os_release, m->os_release);
2366 strv_free_and_replace(i->sysext_release, m->sysext_release);
2367 strv_free_and_replace(i->confext_release, m->confext_release);
2368 break;
2369 }
2370
2371 default:
2372 return -EOPNOTSUPP;
2373 }
2374
2375 i->metadata_valid = true;
2376
2377 return 0;
2378 }
2379
2380 int image_name_lock(
2381 RuntimeScope scope,
2382 const char *name,
2383 int operation,
2384 LockFile *ret) {
2385
2386 int r;
2387
2388 assert(name);
2389 assert(ret);
2390
2391 /* Locks an image name, regardless of the precise path used. */
2392
2393 if (streq(name, ".host"))
2394 return -EBUSY;
2395
2396 if (!image_name_is_valid(name))
2397 return -EINVAL;
2398
2399 if (getenv_bool("SYSTEMD_NSPAWN_LOCK") == 0) {
2400 *ret = (LockFile) LOCK_FILE_INIT;
2401 return 0;
2402 }
2403
2404 (void) make_lock_dir(scope);
2405
2406 _cleanup_free_ char *p = NULL;
2407 r = runtime_directory_generic(scope, "systemd/nspawn/locks/name-", &p);
2408 if (r < 0)
2409 return r;
2410
2411 if (!strextend(&p, name))
2412 return -ENOMEM;
2413
2414 return make_lock_file(p, operation, ret);
2415 }
2416
2417 bool image_in_search_path(
2418 RuntimeScope scope,
2419 ImageClass class,
2420 const char *root,
2421 const char *image) {
2422
2423 int r;
2424
2425 assert(scope < _RUNTIME_SCOPE_MAX && scope != RUNTIME_SCOPE_GLOBAL);
2426 assert(class >= 0);
2427 assert(class < _IMAGE_CLASS_MAX);
2428 assert(image);
2429
2430 _cleanup_strv_free_ char **search = NULL;
2431 r = pick_image_search_path(scope, class, root, &search);
2432 if (r < 0)
2433 return r;
2434
2435 STRV_FOREACH(path, search) {
2436 const char *p, *q;
2437 size_t k;
2438
2439 if (!empty_or_root(root)) {
2440 q = path_startswith(*path, root);
2441 if (!q)
2442 continue;
2443 } else
2444 q = *path;
2445
2446 p = path_startswith(q, *path);
2447 if (!p)
2448 continue;
2449
2450 /* Make sure there's a filename following */
2451 k = strcspn(p, "/");
2452 if (k == 0)
2453 continue;
2454
2455 p += k;
2456
2457 /* Accept trailing slashes */
2458 if (p[strspn(p, "/")] == 0)
2459 return true;
2460 }
2461
2462 return false;
2463 }
2464
2465 bool image_is_vendor(const struct Image *i) {
2466 assert(i);
2467
2468 return i->path && path_startswith(i->path, "/usr");
2469 }
2470
2471 bool image_is_host(const struct Image *i) {
2472 assert(i);
2473
2474 if (i->name && streq(i->name, ".host"))
2475 return true;
2476
2477 if (i->path && path_equal(i->path, "/"))
2478 return true;
2479
2480 return false;
2481 }
2482
2483 int image_to_json(const struct Image *img, sd_json_variant **ret) {
2484 assert(img);
2485
2486 return sd_json_buildo(
2487 ret,
2488 SD_JSON_BUILD_PAIR_STRING("Type", image_type_to_string(img->type)),
2489 SD_JSON_BUILD_PAIR_STRING("Class", image_class_to_string(img->class)),
2490 SD_JSON_BUILD_PAIR_STRING("Name", img->name),
2491 SD_JSON_BUILD_PAIR_CONDITION(!!img->path, "Path", SD_JSON_BUILD_STRING(img->path)),
2492 SD_JSON_BUILD_PAIR_BOOLEAN("ReadOnly", image_is_read_only(img)),
2493 SD_JSON_BUILD_PAIR_CONDITION(img->crtime != 0, "CreationTimestamp", SD_JSON_BUILD_UNSIGNED(img->crtime)),
2494 SD_JSON_BUILD_PAIR_CONDITION(img->mtime != 0, "ModificationTimestamp", SD_JSON_BUILD_UNSIGNED(img->mtime)),
2495 SD_JSON_BUILD_PAIR_CONDITION(img->usage != UINT64_MAX, "Usage", SD_JSON_BUILD_UNSIGNED(img->usage)),
2496 SD_JSON_BUILD_PAIR_CONDITION(img->usage_exclusive != UINT64_MAX, "UsageExclusive", SD_JSON_BUILD_UNSIGNED(img->usage_exclusive)),
2497 SD_JSON_BUILD_PAIR_CONDITION(img->limit != UINT64_MAX, "Limit", SD_JSON_BUILD_UNSIGNED(img->limit)),
2498 SD_JSON_BUILD_PAIR_CONDITION(img->limit_exclusive != UINT64_MAX, "LimitExclusive", SD_JSON_BUILD_UNSIGNED(img->limit_exclusive)));
2499 }
2500
2501 static const char* const image_type_table[_IMAGE_TYPE_MAX] = {
2502 [IMAGE_DIRECTORY] = "directory",
2503 [IMAGE_SUBVOLUME] = "subvolume",
2504 [IMAGE_RAW] = "raw",
2505 [IMAGE_BLOCK] = "block",
2506 [IMAGE_MSTACK] = "mstack",
2507 };
2508
2509 DEFINE_STRING_TABLE_LOOKUP(image_type, ImageType);
2510
2511 int image_root_pick(
2512 RuntimeScope scope,
2513 ImageClass c,
2514 bool runtime,
2515 char **ret) {
2516
2517 int r;
2518
2519 assert(scope >= 0);
2520 assert(scope < _RUNTIME_SCOPE_MAX);
2521 assert(c >= 0);
2522 assert(c < _IMAGE_CLASS_MAX);
2523 assert(ret);
2524
2525 /* Picks the primary target directory for downloads, depending on invocation contexts */
2526
2527 _cleanup_free_ char *s = NULL;
2528 switch (scope) {
2529
2530 case RUNTIME_SCOPE_SYSTEM: {
2531 s = strdup(runtime ? image_root_runtime_to_string(c) : image_root_to_string(c));
2532 if (!s)
2533 return -ENOMEM;
2534
2535 break;
2536 }
2537
2538 case RUNTIME_SCOPE_USER:
2539 r = sd_path_lookup(runtime ? SD_PATH_USER_RUNTIME : SD_PATH_USER_STATE_PRIVATE, "machines", &s);
2540 if (r < 0)
2541 return r;
2542
2543 break;
2544
2545 default:
2546 return -EOPNOTSUPP;
2547 }
2548
2549 *ret = TAKE_PTR(s);
2550 return 0;
2551 }
2552
2553 BUS_DEFINE_PROPERTY_GET(bus_property_get_image_is_read_only, "b", Image, (int) image_is_read_only);