1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
4 #include <linux/loop.h>
5 #include <linux/magic.h>
10 #include <sys/sysmacros.h>
16 #include "alloc-util.h"
17 #include "blockdev-util.h"
18 #include "btrfs-util.h"
20 #include "chattr-util.h"
22 #include "dirent-util.h"
23 #include "discover-image.h"
24 #include "dissect-image.h"
27 #include "extension-util.h"
31 #include "hostname-setup.h"
32 #include "id128-util.h"
33 #include "initrd-util.h"
34 #include "lock-util.h"
36 #include "loop-util.h"
38 #include "nulstr-util.h"
40 #include "path-util.h"
42 #include "runtime-scope.h"
43 #include "stat-util.h"
44 #include "string-table.h"
45 #include "string-util.h"
47 #include "time-util.h"
49 #include "xattr-util.h"
51 const char* const image_search_path
[_IMAGE_CLASS_MAX
] = {
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",
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",
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=. */
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 */
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",
79 /* Inside the initrd, use a slightly different set of search path (i.e. include .extra/sysext/ and
80 * .extra/confext/ in extension search dir) */
81 static 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) */
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 */
87 "/.extra/sysext\0", /* put sysext picked up by systemd-stub last, since not trusted */
89 [IMAGE_CONFEXT
] = "/run/confexts\0" /* only place symlinks here */
90 "/var/lib/confexts\0" /* the main place for images */
91 "/usr/local/lib/confexts\0"
92 "/.extra/confext\0", /* put confext picked up by systemd-stub last, since not trusted */
95 static const char* image_class_suffix_table
[_IMAGE_CLASS_MAX
] = {
96 [IMAGE_SYSEXT
] = ".sysext",
97 [IMAGE_CONFEXT
] = ".confext",
100 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(image_class_suffix
, ImageClass
);
102 static const char *const image_root_table
[_IMAGE_CLASS_MAX
] = {
103 [IMAGE_MACHINE
] = "/var/lib/machines",
104 [IMAGE_PORTABLE
] = "/var/lib/portables",
105 [IMAGE_SYSEXT
] = "/var/lib/extensions",
106 [IMAGE_CONFEXT
] = "/var/lib/confexts",
109 DEFINE_STRING_TABLE_LOOKUP_TO_STRING(image_root
, ImageClass
);
111 static const char *const image_root_runtime_table
[_IMAGE_CLASS_MAX
] = {
112 [IMAGE_MACHINE
] = "/run/machines",
113 [IMAGE_PORTABLE
] = "/run/portables",
114 [IMAGE_SYSEXT
] = "/run/extensions",
115 [IMAGE_CONFEXT
] = "/run/confexts",
118 DEFINE_STRING_TABLE_LOOKUP_TO_STRING(image_root_runtime
, ImageClass
);
120 static Image
* image_free(Image
*i
) {
127 strv_free(i
->machine_info
);
128 strv_free(i
->os_release
);
129 strv_free(i
->sysext_release
);
130 strv_free(i
->confext_release
);
135 DEFINE_TRIVIAL_REF_UNREF_FUNC(Image
, image
, image_free
);
136 DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(image_hash_ops
, char, string_hash_func
, string_compare_func
,
139 static char** image_settings_path(Image
*image
) {
140 _cleanup_strv_free_
char **l
= NULL
;
141 _cleanup_free_
char *fn
= NULL
;
151 fn
= strjoin(image
->name
, ".nspawn");
155 FOREACH_STRING(s
, "/etc/systemd/nspawn", "/run/systemd/nspawn") {
156 l
[i
] = path_join(s
, fn
);
163 r
= file_in_same_dir(image
->path
, fn
, l
+ i
);
167 log_debug_errno(r
, "Failed to generate .nspawn settings path from image path, ignoring: %m");
174 static int image_roothash_path(Image
*image
, char **ret
) {
175 _cleanup_free_
char *fn
= NULL
;
179 fn
= strjoin(image
->name
, ".roothash");
183 return file_in_same_dir(image
->path
, fn
, ret
);
186 static int image_new(
191 const char *filename
,
197 _cleanup_(image_unrefp
) Image
*i
= NULL
;
200 assert(t
< _IMAGE_TYPE_MAX
);
213 .read_only
= read_only
,
217 .usage_exclusive
= UINT64_MAX
,
219 .limit_exclusive
= UINT64_MAX
,
222 i
->name
= strdup(pretty
);
226 i
->path
= path_join(path
, filename
);
230 path_simplify(i
->path
);
237 static int extract_image_basename(
239 const char *class_suffix
, /* e.g. ".sysext" (this is an optional suffix) */
240 char **format_suffixes
, /* e.g. ".raw" (one of these will be required) */
244 _cleanup_free_
char *name
= NULL
, *suffix
= NULL
;
249 r
= path_extract_filename(path
, &name
);
253 if (format_suffixes
) {
254 char *e
= endswith_strv(name
, format_suffixes
);
255 if (!e
) /* Format suffix is required */
268 char *e
= endswith(name
, class_suffix
);
269 if (e
) { /* Class suffix is optional */
271 _cleanup_free_
char *j
= strjoin(e
, suffix
);
275 free_and_replace(suffix
, j
);
282 if (!image_name_is_valid(name
))
286 *ret_suffix
= TAKE_PTR(suffix
);
289 *ret_basename
= TAKE_PTR(name
);
294 static int image_update_quota(Image
*i
, int fd
) {
295 _cleanup_close_
int fd_close
= -EBADF
;
300 if (image_is_vendor(i
) || image_is_host(i
))
303 if (i
->type
!= IMAGE_SUBVOLUME
)
307 fd_close
= open(i
->path
, O_CLOEXEC
|O_DIRECTORY
);
312 /* Convert from O_PATH to proper fd, if needed */
313 fd
= fd_reopen_condition(fd
, O_CLOEXEC
|O_DIRECTORY
, O_PATH
, &fd_close
);
318 r
= btrfs_quota_scan_ongoing(fd
);
324 BtrfsQuotaInfo quota
;
325 r
= btrfs_subvol_get_subtree_quota_fd(fd
, 0, "a
);
329 i
->usage
= quota
.referenced
;
330 i
->usage_exclusive
= quota
.exclusive
;
331 i
->limit
= quota
.referenced_max
;
332 i
->limit_exclusive
= quota
.exclusive_max
;
337 static int image_make(
341 const char *dir_path
,
342 const char *filename
,
343 int fd
, /* O_PATH fd */
344 const struct stat
*st
,
347 _cleanup_free_
char *pretty_buffer
= NULL
;
351 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
352 assert(dir_path
|| dir_fd
== AT_FDCWD
);
355 /* We explicitly *do* follow symlinks here, since we want to allow symlinking trees, raw files and block
356 * devices into /var/lib/machines/, and treat them normally.
358 * This function returns -ENOENT if we can't find the image after all, and -EMEDIUMTYPE if it's not a file we
361 _cleanup_close_
int _fd
= -EBADF
;
363 /* If we didn't get an fd passed in, then let's pin it via O_PATH now */
364 _fd
= openat(dir_fd
, filename
, O_PATH
|O_CLOEXEC
);
369 st
= NULL
; /* refresh stat() data now that we have the inode pinned */
374 if (fstat(fd
, &stbuf
) < 0)
380 _cleanup_free_
char *parent
= NULL
;
382 (void) fd_get_path(dir_fd
, &parent
);
387 (dir_path
&& path_startswith(dir_path
, "/usr")) ||
388 (faccessat(fd
, "", W_OK
, AT_EACCESS
|AT_EMPTY_PATH
) < 0 && errno
== EROFS
);
390 if (S_ISDIR(st
->st_mode
)) {
391 unsigned file_attr
= 0;
398 r
= extract_image_basename(
400 image_class_suffix_to_string(c
),
401 /* format_suffixes= */ NULL
,
403 /* ret_suffix= */ NULL
);
407 pretty
= pretty_buffer
;
410 if (btrfs_might_be_subvol(st
)) {
412 r
= fd_is_fs_type(fd
, BTRFS_SUPER_MAGIC
);
416 BtrfsSubvolInfo info
;
418 /* It's a btrfs subvolume */
420 r
= btrfs_subvol_get_info_fd(fd
, 0, &info
);
424 r
= image_new(IMAGE_SUBVOLUME
,
429 info
.read_only
|| read_only
,
436 (void) image_update_quota(*ret
, fd
);
441 /* Get directory creation time (not available everywhere, but that's OK */
442 (void) fd_getcrtime(fd
, &crtime
);
444 /* If the IMMUTABLE bit is set, we consider the directory read-only. Since the ioctl is not
445 * supported everywhere we ignore failures. */
446 (void) read_attr_fd(fd
, &file_attr
);
448 /* It's just a normal directory. */
449 r
= image_new(IMAGE_DIRECTORY
,
454 read_only
|| (file_attr
& FS_IMMUTABLE_FL
),
456 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 */
463 } else if (S_ISREG(st
->st_mode
) && endswith(filename
, ".raw")) {
466 /* It's a RAW disk image */
471 (void) fd_getcrtime(fd
, &crtime
);
474 r
= extract_image_basename(
476 image_class_suffix_to_string(c
),
479 /* ret_suffix= */ NULL
);
483 pretty
= pretty_buffer
;
486 r
= image_new(IMAGE_RAW
,
491 !(st
->st_mode
& 0222) || read_only
,
493 timespec_load(&st
->st_mtim
),
498 (*ret
)->usage
= (*ret
)->usage_exclusive
= st
->st_blocks
* 512;
499 (*ret
)->limit
= (*ret
)->limit_exclusive
= st
->st_size
;
503 } else if (S_ISBLK(st
->st_mode
)) {
504 uint64_t size
= UINT64_MAX
;
512 r
= extract_image_basename(
514 /* class_suffix= */ NULL
,
515 /* format_suffix= */ NULL
,
517 /* ret_suffix= */ NULL
);
521 pretty
= pretty_buffer
;
524 _cleanup_close_
int block_fd
= fd_reopen(fd
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
526 log_debug_errno(errno
, "Failed to open block device %s/%s, ignoring: %m", strnull(dir_path
), filename
);
531 if (ioctl(block_fd
, BLKROGET
, &state
) < 0)
532 log_debug_errno(errno
, "Failed to issue BLKROGET on device %s/%s, ignoring: %m", strnull(dir_path
), filename
);
537 r
= blockdev_get_device_size(block_fd
, &size
);
539 log_debug_errno(r
, "Failed to issue BLKGETSIZE64 on device %s/%s, ignoring: %m", strnull(dir_path
), filename
);
541 block_fd
= safe_close(block_fd
);
544 r
= image_new(IMAGE_BLOCK
,
549 !(st
->st_mode
& 0222) || read_only
,
556 if (!IN_SET(size
, 0, UINT64_MAX
))
557 (*ret
)->usage
= (*ret
)->usage_exclusive
= (*ret
)->limit
= (*ret
)->limit_exclusive
= size
;
565 static int pick_image_search_path(
572 assert(scope
< _RUNTIME_SCOPE_MAX
&& scope
!= RUNTIME_SCOPE_GLOBAL
);
573 assert(class < _IMAGE_CLASS_MAX
);
582 _cleanup_strv_free_
char **a
= NULL
, **b
= NULL
;
584 r
= pick_image_search_path(RUNTIME_SCOPE_USER
, class, &a
);
588 r
= pick_image_search_path(RUNTIME_SCOPE_SYSTEM
, class, &b
);
592 r
= strv_extend_strv(&a
, b
, /* filter_duplicates= */ false);
602 case RUNTIME_SCOPE_SYSTEM
: {
604 /* Use the initrd search path if there is one, otherwise use the common one */
605 ns
= in_initrd() && image_search_path_initrd
[class] ?
606 image_search_path_initrd
[class] :
607 image_search_path
[class];
611 _cleanup_strv_free_
char **search
= strv_split_nulstr(ns
);
615 *ret
= TAKE_PTR(search
);
619 case RUNTIME_SCOPE_USER
: {
620 if (class != IMAGE_MACHINE
)
623 static const uint64_t dirs
[] = {
624 SD_PATH_USER_RUNTIME
,
625 SD_PATH_USER_STATE_PRIVATE
,
626 SD_PATH_USER_LIBRARY_PRIVATE
,
629 _cleanup_strv_free_
char **search
= NULL
;
630 FOREACH_ELEMENT(d
, dirs
) {
631 _cleanup_free_
char *p
= NULL
;
633 r
= sd_path_lookup(*d
, "machines", &p
);
634 if (r
== -ENXIO
) /* No XDG_RUNTIME_DIR set */
639 r
= strv_consume(&search
, TAKE_PTR(p
));
644 *ret
= TAKE_PTR(search
);
649 assert_not_reached();
656 static char** make_possible_filenames(ImageClass
class, const char *image_name
) {
657 _cleanup_strv_free_
char **l
= NULL
;
661 FOREACH_STRING(v_suffix
, "", ".v")
662 FOREACH_STRING(format_suffix
, "", ".raw") {
663 _cleanup_free_
char *j
= NULL
;
664 const char *class_suffix
;
666 class_suffix
= image_class_suffix_to_string(class);
668 j
= strjoin(image_name
, class_suffix
, format_suffix
, v_suffix
);
672 if (strv_consume(&l
, TAKE_PTR(j
)) < 0)
676 j
= strjoin(image_name
, format_suffix
, v_suffix
);
680 if (strv_consume(&l
, TAKE_PTR(j
)) < 0)
687 int image_find(RuntimeScope scope
,
693 /* As mentioned above, we follow symlinks on this fstatat(), because we want to permit people to
694 * symlink block devices into the search path. (For now, we disable that when operating relative to
695 * some root directory.) */
696 int open_flags
= root
? O_NOFOLLOW
: 0, r
;
698 assert(scope
< _RUNTIME_SCOPE_MAX
&& scope
!= RUNTIME_SCOPE_GLOBAL
);
700 assert(class < _IMAGE_CLASS_MAX
);
703 /* There are no images with invalid names */
704 if (!image_name_is_valid(name
))
707 _cleanup_strv_free_
char **names
= make_possible_filenames(class, name
);
711 _cleanup_strv_free_
char **search
= NULL
;
712 r
= pick_image_search_path(scope
, class, &search
);
716 STRV_FOREACH(path
, search
) {
717 _cleanup_free_
char *resolved
= NULL
;
718 _cleanup_closedir_
DIR *d
= NULL
;
720 r
= chase_and_opendir(*path
, root
, CHASE_PREFIX_ROOT
, &resolved
, &d
);
726 STRV_FOREACH(n
, names
) {
727 _cleanup_free_
char *fname_buf
= NULL
;
728 const char *fname
= *n
;
730 _cleanup_close_
int fd
= openat(dirfd(d
), fname
, O_PATH
|O_CLOEXEC
|open_flags
);
739 if (fstat(fd
, &st
) < 0)
742 if (endswith(fname
, ".raw")) {
743 if (!S_ISREG(st
.st_mode
)) {
744 log_debug("Ignoring non-regular file '%s' with .raw suffix.", fname
);
748 } else if (endswith(fname
, ".v")) {
750 if (!S_ISDIR(st
.st_mode
)) {
751 log_debug("Ignoring non-directory file '%s' with .v suffix.", fname
);
755 _cleanup_free_
char *suffix
= NULL
;
756 suffix
= strdup(ASSERT_PTR(startswith(fname
, name
)));
760 *ASSERT_PTR(endswith(suffix
, ".v")) = 0;
762 _cleanup_free_
char *vp
= path_join(resolved
, fname
);
766 PickFilter filter
= {
767 .type_mask
= endswith(suffix
, ".raw") ? (UINT32_C(1) << DT_REG
) | (UINT32_C(1) << DT_BLK
) : (UINT32_C(1) << DT_DIR
),
769 .architecture
= _ARCHITECTURE_INVALID
,
770 .suffix
= STRV_MAKE(suffix
),
773 _cleanup_(pick_result_done
) PickResult result
= PICK_RESULT_NULL
;
775 /* toplevel_fd= */ AT_FDCWD
,
778 PICK_ARCHITECTURE
|PICK_TRIES
,
781 log_debug_errno(r
, "Failed to pick versioned image on '%s', skipping: %m", vp
);
785 log_debug("Found versioned directory '%s', without matching entry, skipping: %m", vp
);
789 /* Refresh the stat data for the discovered target */
793 _cleanup_free_
char *bn
= NULL
;
794 r
= path_extract_filename(result
.path
, &bn
);
796 log_debug_errno(r
, "Failed to extract basename of image path '%s', skipping: %m", result
.path
);
800 fname_buf
= path_join(fname
, bn
);
806 } else if (!S_ISDIR(st
.st_mode
) && !S_ISBLK(st
.st_mode
)) {
807 log_debug("Ignoring non-directory and non-block device file '%s' without suffix.", fname
);
811 r
= image_make(class, name
, dirfd(d
), resolved
, fname
, fd
, &st
, ret
);
812 if (IN_SET(r
, -ENOENT
, -EMEDIUMTYPE
))
818 (*ret
)->discoverable
= true;
824 if (scope
== RUNTIME_SCOPE_SYSTEM
&& class == IMAGE_MACHINE
&& streq(name
, ".host")) {
825 r
= image_make(class,
827 /* dir_fd= */ AT_FDCWD
,
828 /* dir_path= */ NULL
,
829 /* filename= */ empty_to_root(root
),
837 (*ret
)->discoverable
= true;
845 int image_from_path(const char *path
, Image
**ret
) {
847 /* Note that we don't set the 'discoverable' field of the returned object, because we don't check here whether
848 * the image is in the image search path. And if it is we don't know if the path we used is actually not
849 * overridden by another, different image earlier in the search path */
851 if (path_equal(path
, "/"))
855 /* dir_fd= */ AT_FDCWD
,
856 /* dir_path= */ NULL
,
863 _IMAGE_CLASS_INVALID
,
865 /* dir_fd= */ AT_FDCWD
,
866 /* dir_path= */ NULL
,
867 /* filename= */ path
,
873 int image_find_harder(
876 const char *name_or_path
,
880 if (image_name_is_valid(name_or_path
))
881 return image_find(scope
, class, name_or_path
, root
, ret
);
883 return image_from_path(name_or_path
, ret
);
892 /* As mentioned above, we follow symlinks on this fstatat(), because we want to permit people to
893 * symlink block devices into the search path. (For now, we disable that when operating relative to
894 * some root directory.) */
895 int open_flags
= root
? O_NOFOLLOW
: 0, r
;
897 assert(scope
< _RUNTIME_SCOPE_MAX
&& scope
!= RUNTIME_SCOPE_GLOBAL
);
899 assert(class < _IMAGE_CLASS_MAX
);
902 _cleanup_strv_free_
char **search
= NULL
;
903 r
= pick_image_search_path(scope
, class, &search
);
907 STRV_FOREACH(path
, search
) {
908 _cleanup_free_
char *resolved
= NULL
;
909 _cleanup_closedir_
DIR *d
= NULL
;
911 r
= chase_and_opendir(*path
, root
, CHASE_PREFIX_ROOT
, &resolved
, &d
);
917 FOREACH_DIRENT_ALL(de
, d
, return -errno
) {
918 _cleanup_free_
char *pretty
= NULL
, *fname_buf
= NULL
;
919 _cleanup_(image_unrefp
) Image
*image
= NULL
;
920 const char *fname
= de
->d_name
;
922 if (dot_or_dot_dot(fname
))
925 _cleanup_close_
int fd
= openat(dirfd(d
), fname
, O_PATH
|O_CLOEXEC
|open_flags
);
930 continue; /* Vanished while we were looking at it */
934 if (fstat(fd
, &st
) < 0)
937 if (S_ISREG(st
.st_mode
)) {
938 r
= extract_image_basename(
940 image_class_suffix_to_string(class),
943 /* ret_suffix= */ NULL
);
945 log_debug_errno(r
, "Skipping directory entry '%s', which doesn't look like an image.", fname
);
948 } else if (S_ISDIR(st
.st_mode
)) {
951 v
= endswith(fname
, ".v");
953 _cleanup_free_
char *suffix
= NULL
, *nov
= NULL
;
955 nov
= strndup(fname
, v
- fname
); /* Chop off the .v */
959 r
= extract_image_basename(
961 image_class_suffix_to_string(class),
962 STRV_MAKE(".raw", ""),
966 log_debug_errno(r
, "Skipping directory entry '%s', which doesn't look like a versioned image.", fname
);
970 _cleanup_free_
char *vp
= path_join(resolved
, fname
);
974 PickFilter filter
= {
975 .type_mask
= endswith(suffix
, ".raw") ? (UINT32_C(1) << DT_REG
) | (UINT32_C(1) << DT_BLK
) : (UINT32_C(1) << DT_DIR
),
977 .architecture
= _ARCHITECTURE_INVALID
,
978 .suffix
= STRV_MAKE(suffix
),
981 _cleanup_(pick_result_done
) PickResult result
= PICK_RESULT_NULL
;
983 /* toplevel_fd= */ AT_FDCWD
,
986 PICK_ARCHITECTURE
|PICK_TRIES
,
989 log_debug_errno(r
, "Failed to pick versioned image on '%s', skipping: %m", vp
);
993 log_debug("Found versioned directory '%s', without matching entry, skipping: %m", vp
);
997 /* Refresh the stat data for the discovered target */
1001 _cleanup_free_
char *bn
= NULL
;
1002 r
= path_extract_filename(result
.path
, &bn
);
1004 log_debug_errno(r
, "Failed to extract basename of image path '%s', skipping: %m", result
.path
);
1008 fname_buf
= path_join(fname
, bn
);
1014 r
= extract_image_basename(
1016 image_class_suffix_to_string(class),
1017 /* format_suffixes= */ NULL
,
1019 /* ret_suffix= */ NULL
);
1021 log_debug_errno(r
, "Skipping directory entry '%s', which doesn't look like an image.", fname
);
1026 } else if (S_ISBLK(st
.st_mode
)) {
1027 r
= extract_image_basename(
1029 /* class_suffix= */ NULL
,
1030 /* format_suffix= */ NULL
,
1032 /* ret_suffix= */ NULL
);
1034 log_debug_errno(r
, "Skipping directory entry '%s', which doesn't look like an image.", fname
);
1038 log_debug("Skipping directory entry '%s', which is neither regular file, directory nor block device.", fname
);
1042 if (hashmap_contains(*images
, pretty
))
1045 r
= image_make(class, pretty
, dirfd(d
), resolved
, fname
, fd
, &st
, &image
);
1046 if (IN_SET(r
, -ENOENT
, -EMEDIUMTYPE
))
1051 image
->discoverable
= true;
1053 r
= hashmap_ensure_put(images
, &image_hash_ops
, image
->name
, image
);
1061 if (scope
== RUNTIME_SCOPE_SYSTEM
&& class == IMAGE_MACHINE
&& !hashmap_contains(*images
, ".host")) {
1062 _cleanup_(image_unrefp
) Image
*image
= NULL
;
1064 r
= image_make(IMAGE_MACHINE
,
1066 /* dir_fd= */ AT_FDCWD
,
1067 /* dir_path= */ NULL
,
1068 empty_to_root(root
),
1075 image
->discoverable
= true;
1077 r
= hashmap_ensure_put(images
, &image_hash_ops
, image
->name
, image
);
1087 int image_remove(Image
*i
) {
1088 _cleanup_(release_lock_file
) LockFile global_lock
= LOCK_FILE_INIT
, local_lock
= LOCK_FILE_INIT
;
1089 _cleanup_strv_free_
char **settings
= NULL
;
1090 _cleanup_free_
char *roothash
= NULL
;
1095 if (image_is_vendor(i
) || image_is_host(i
))
1098 settings
= image_settings_path(i
);
1102 r
= image_roothash_path(i
, &roothash
);
1106 /* Make sure we don't interfere with a running nspawn */
1107 r
= image_path_lock(i
->path
, LOCK_EX
|LOCK_NB
, &global_lock
, &local_lock
);
1113 case IMAGE_SUBVOLUME
:
1115 /* Let's unlink first, maybe it is a symlink? If that works we are happy. Otherwise, let's get out the
1117 if (unlink(i
->path
) < 0) {
1118 r
= btrfs_subvol_remove(i
->path
, BTRFS_REMOVE_RECURSIVE
|BTRFS_REMOVE_QUOTA
);
1125 case IMAGE_DIRECTORY
:
1126 /* Allow deletion of read-only directories */
1127 (void) chattr_path(i
->path
, 0, FS_IMMUTABLE_FL
);
1128 r
= rm_rf(i
->path
, REMOVE_ROOT
|REMOVE_PHYSICAL
|REMOVE_SUBVOLUME
);
1136 /* If this is inside of /dev, then it's a real block device, hence let's not touch the device node
1137 * itself (but let's remove the stuff stored alongside it). If it's anywhere else, let's try to unlink
1138 * the thing (it's most likely a symlink after all). */
1140 if (path_startswith(i
->path
, "/dev"))
1145 if (unlink(i
->path
) < 0)
1153 STRV_FOREACH(j
, settings
)
1154 if (unlink(*j
) < 0 && errno
!= ENOENT
)
1155 log_debug_errno(errno
, "Failed to unlink %s, ignoring: %m", *j
);
1157 if (unlink(roothash
) < 0 && errno
!= ENOENT
)
1158 log_debug_errno(errno
, "Failed to unlink %s, ignoring: %m", roothash
);
1163 static int rename_auxiliary_file(const char *path
, const char *new_name
, const char *suffix
) {
1164 _cleanup_free_
char *fn
= NULL
, *rs
= NULL
;
1167 fn
= strjoin(new_name
, suffix
);
1171 r
= file_in_same_dir(path
, fn
, &rs
);
1175 return rename_noreplace(AT_FDCWD
, path
, AT_FDCWD
, rs
);
1178 int image_rename(Image
*i
, const char *new_name
, RuntimeScope scope
) {
1179 _cleanup_(release_lock_file
) LockFile global_lock
= LOCK_FILE_INIT
, local_lock
= LOCK_FILE_INIT
, name_lock
= LOCK_FILE_INIT
;
1180 _cleanup_free_
char *new_path
= NULL
, *nn
= NULL
, *roothash
= NULL
;
1181 _cleanup_strv_free_
char **settings
= NULL
;
1182 unsigned file_attr
= 0;
1187 if (!image_name_is_valid(new_name
))
1190 if (image_is_vendor(i
) || image_is_host(i
))
1193 settings
= image_settings_path(i
);
1197 r
= image_roothash_path(i
, &roothash
);
1201 /* Make sure we don't interfere with a running nspawn */
1202 r
= image_path_lock(i
->path
, LOCK_EX
|LOCK_NB
, &global_lock
, &local_lock
);
1206 /* Make sure nobody takes the new name, between the time we
1207 * checked it is currently unused in all search paths, and the
1208 * time we take possession of it */
1209 r
= image_name_lock(new_name
, LOCK_EX
|LOCK_NB
, &name_lock
);
1213 r
= image_find(scope
, IMAGE_MACHINE
, new_name
, NULL
, NULL
);
1221 case IMAGE_DIRECTORY
:
1222 /* Turn of the immutable bit while we rename the image, so that we can rename it */
1223 (void) read_attr_at(AT_FDCWD
, i
->path
, &file_attr
);
1225 if (file_attr
& FS_IMMUTABLE_FL
)
1226 (void) chattr_path(i
->path
, 0, FS_IMMUTABLE_FL
);
1229 case IMAGE_SUBVOLUME
:
1230 r
= file_in_same_dir(i
->path
, new_name
, &new_path
);
1235 /* Refuse renaming raw block devices in /dev, the names are picked by udev after all. */
1236 if (path_startswith(i
->path
, "/dev"))
1239 r
= file_in_same_dir(i
->path
, new_name
, &new_path
);
1245 fn
= strjoina(new_name
, ".raw");
1247 r
= file_in_same_dir(i
->path
, fn
, &new_path
);
1257 nn
= strdup(new_name
);
1261 r
= rename_noreplace(AT_FDCWD
, i
->path
, AT_FDCWD
, new_path
);
1265 /* Restore the immutable bit, if it was set before */
1266 if (file_attr
& FS_IMMUTABLE_FL
)
1267 (void) chattr_path(new_path
, FS_IMMUTABLE_FL
, FS_IMMUTABLE_FL
);
1269 free_and_replace(i
->path
, new_path
);
1270 free_and_replace(i
->name
, nn
);
1272 STRV_FOREACH(j
, settings
) {
1273 r
= rename_auxiliary_file(*j
, new_name
, ".nspawn");
1274 if (r
< 0 && r
!= -ENOENT
)
1275 log_debug_errno(r
, "Failed to rename settings file %s, ignoring: %m", *j
);
1278 r
= rename_auxiliary_file(roothash
, new_name
, ".roothash");
1279 if (r
< 0 && r
!= -ENOENT
)
1280 log_debug_errno(r
, "Failed to rename roothash file %s, ignoring: %m", roothash
);
1285 static int clone_auxiliary_file(const char *path
, const char *new_name
, const char *suffix
) {
1286 _cleanup_free_
char *fn
= NULL
, *rs
= NULL
;
1289 fn
= strjoin(new_name
, suffix
);
1293 r
= file_in_same_dir(path
, fn
, &rs
);
1297 return copy_file_atomic(path
, rs
, 0664, COPY_REFLINK
);
1300 int image_clone(Image
*i
, const char *new_name
, bool read_only
, RuntimeScope scope
) {
1301 _cleanup_(release_lock_file
) LockFile name_lock
= LOCK_FILE_INIT
;
1302 _cleanup_strv_free_
char **settings
= NULL
;
1303 _cleanup_free_
char *roothash
= NULL
;
1304 const char *new_path
;
1309 if (!image_name_is_valid(new_name
))
1312 settings
= image_settings_path(i
);
1316 r
= image_roothash_path(i
, &roothash
);
1320 /* Make sure nobody takes the new name, between the time we
1321 * checked it is currently unused in all search paths, and the
1322 * time we take possession of it */
1323 r
= image_name_lock(new_name
, LOCK_EX
|LOCK_NB
, &name_lock
);
1327 r
= image_find(scope
, IMAGE_MACHINE
, new_name
, NULL
, NULL
);
1335 case IMAGE_SUBVOLUME
:
1336 case IMAGE_DIRECTORY
:
1337 /* If we can we'll always try to create a new btrfs subvolume here, even if the source is a plain
1340 new_path
= strjoina("/var/lib/machines/", new_name
);
1342 r
= btrfs_subvol_snapshot_at(AT_FDCWD
, i
->path
, AT_FDCWD
, new_path
,
1343 (read_only
? BTRFS_SNAPSHOT_READ_ONLY
: 0) |
1344 BTRFS_SNAPSHOT_FALLBACK_COPY
|
1345 BTRFS_SNAPSHOT_FALLBACK_DIRECTORY
|
1346 BTRFS_SNAPSHOT_FALLBACK_IMMUTABLE
|
1347 BTRFS_SNAPSHOT_RECURSIVE
|
1348 BTRFS_SNAPSHOT_QUOTA
);
1350 /* Enable "subtree" quotas for the copy, if we didn't copy any quota from the source. */
1351 (void) btrfs_subvol_auto_qgroup(new_path
, 0, true);
1356 new_path
= strjoina("/var/lib/machines/", new_name
, ".raw");
1358 r
= copy_file_atomic(i
->path
, new_path
, read_only
? 0444 : 0644,
1359 COPY_REFLINK
|COPY_CRTIME
|COPY_NOCOW_AFTER
);
1370 STRV_FOREACH(j
, settings
) {
1371 r
= clone_auxiliary_file(*j
, new_name
, ".nspawn");
1372 if (r
< 0 && r
!= -ENOENT
)
1373 log_debug_errno(r
, "Failed to clone settings %s, ignoring: %m", *j
);
1376 r
= clone_auxiliary_file(roothash
, new_name
, ".roothash");
1377 if (r
< 0 && r
!= -ENOENT
)
1378 log_debug_errno(r
, "Failed to clone root hash file %s, ignoring: %m", roothash
);
1383 int image_read_only(Image
*i
, bool b
) {
1384 _cleanup_(release_lock_file
) LockFile global_lock
= LOCK_FILE_INIT
, local_lock
= LOCK_FILE_INIT
;
1389 if (image_is_vendor(i
) || image_is_host(i
))
1392 /* Make sure we don't interfere with a running nspawn */
1393 r
= image_path_lock(i
->path
, LOCK_EX
|LOCK_NB
, &global_lock
, &local_lock
);
1399 case IMAGE_SUBVOLUME
:
1401 /* Note that we set the flag only on the top-level
1402 * subvolume of the image. */
1404 r
= btrfs_subvol_set_read_only(i
->path
, b
);
1410 case IMAGE_DIRECTORY
:
1411 /* For simple directory trees we cannot use the access
1412 mode of the top-level directory, since it has an
1413 effect on the container itself. However, we can
1414 use the "immutable" flag, to at least make the
1415 top-level directory read-only. It's not as good as
1416 a read-only subvolume, but at least something, and
1417 we can read the value back. */
1419 r
= chattr_path(i
->path
, b
? FS_IMMUTABLE_FL
: 0, FS_IMMUTABLE_FL
);
1428 if (stat(i
->path
, &st
) < 0)
1431 if (chmod(i
->path
, (st
.st_mode
& 0444) | (b
? 0000 : 0200)) < 0)
1434 /* If the images is now read-only, it's a good time to
1435 * defrag it, given that no write patterns will
1436 * fragment it again. */
1438 (void) btrfs_defrag(i
->path
);
1443 _cleanup_close_
int fd
= -EBADF
;
1447 fd
= open(i
->path
, O_CLOEXEC
|O_RDONLY
|O_NONBLOCK
|O_NOCTTY
);
1451 if (fstat(fd
, &st
) < 0)
1453 if (!S_ISBLK(st
.st_mode
))
1456 if (ioctl(fd
, BLKROSET
, &state
) < 0)
1470 static void make_lock_dir(void) {
1471 (void) mkdir_p("/run/systemd/nspawn", 0755);
1472 (void) mkdir("/run/systemd/nspawn/locks", 0700);
1475 int image_path_lock(
1478 LockFile
*ret_global
,
1479 LockFile
*ret_local
) {
1481 _cleanup_free_
char *p
= NULL
;
1482 LockFile t
= LOCK_FILE_INIT
;
1490 /* Locks an image path. This actually creates two locks: one "local" one, next to the image path
1491 * itself, which might be shared via NFS. And another "global" one, in /run, that uses the
1492 * device/inode number. This has the benefit that we can even lock a tree that is a mount point,
1495 if (!path_is_absolute(path
))
1498 switch (operation
& (LOCK_SH
|LOCK_EX
)) {
1509 if (getenv_bool("SYSTEMD_NSPAWN_LOCK") == 0) {
1510 *ret_local
= LOCK_FILE_INIT
;
1512 *ret_global
= LOCK_FILE_INIT
;
1516 /* Prohibit taking exclusive locks on the host image. We can't allow this, since we ourselves are
1517 * running off it after all, and we don't want any images to manipulate the host image. We make an
1518 * exception for shared locks however: we allow those (and make them NOPs since there's no point in
1519 * taking them if there can't be exclusive locks). Strictly speaking these are questionable as well,
1520 * since it means changes made to the host might propagate to the container as they happen (and a
1521 * shared lock kinda suggests that no changes happen at all while it is in place), but it's too
1522 * useful not to allow read-only containers off the host root, hence let's support this, and trust
1523 * the user to do the right thing with this. */
1524 if (path_equal(path
, "/")) {
1528 *ret_local
= LOCK_FILE_INIT
;
1530 *ret_global
= LOCK_FILE_INIT
;
1535 if (stat(path
, &st
) >= 0) {
1536 if (S_ISBLK(st
.st_mode
))
1537 r
= asprintf(&p
, "/run/systemd/nspawn/locks/block-%u:%u", major(st
.st_rdev
), minor(st
.st_rdev
));
1538 else if (S_ISDIR(st
.st_mode
) || S_ISREG(st
.st_mode
))
1539 r
= asprintf(&p
, "/run/systemd/nspawn/locks/inode-%lu:%lu", (unsigned long) st
.st_dev
, (unsigned long) st
.st_ino
);
1547 /* For block devices we don't need the "local" lock, as the major/minor lock above should be
1548 * sufficient, since block devices are host local anyway. */
1549 if (!path_startswith(path
, "/dev/")) {
1550 r
= make_lock_file_for(path
, operation
, &t
);
1552 if (!exclusive
&& r
== -EROFS
)
1553 log_debug_errno(r
, "Failed to create shared lock for '%s', ignoring: %m", path
);
1562 r
= make_lock_file(p
, operation
, ret_global
);
1564 release_lock_file(&t
);
1567 } else if (ret_global
)
1568 *ret_global
= LOCK_FILE_INIT
;
1574 int image_set_limit(Image
*i
, uint64_t referenced_max
) {
1579 if (image_is_vendor(i
) || image_is_host(i
))
1582 if (i
->type
!= IMAGE_SUBVOLUME
)
1585 /* We set the quota both for the subvolume as well as for the
1586 * subtree. The latter is mostly for historical reasons, since
1587 * we didn't use to have a concept of subtree quota, and hence
1588 * only modified the subvolume quota. */
1590 (void) btrfs_qgroup_set_limit(i
->path
, 0, referenced_max
);
1591 (void) btrfs_subvol_auto_qgroup(i
->path
, 0, true);
1592 r
= btrfs_subvol_set_subtree_quota_limit(i
->path
, 0, referenced_max
);
1596 (void) image_update_quota(i
, -EBADF
);
1600 int image_set_pool_limit(ImageClass
class, uint64_t referenced_max
) {
1604 assert(class >= 0 && class < _IMAGE_CLASS_MAX
);
1606 dir
= image_root_to_string(class);
1608 r
= btrfs_qgroup_set_limit(dir
, /* qgroupid = */ 0, referenced_max
);
1609 if (ERRNO_IS_NEG_NOT_SUPPORTED(r
))
1612 log_debug_errno(r
, "Failed to set limit on btrfs quota group for '%s', ignoring: %m", dir
);
1614 r
= btrfs_subvol_set_subtree_quota_limit(dir
, /* subvol_id = */ 0, referenced_max
);
1615 if (ERRNO_IS_NEG_NOT_SUPPORTED(r
))
1618 return log_debug_errno(r
, "Failed to set subtree quota limit for '%s': %m", dir
);
1623 int image_read_metadata(Image
*i
, const ImagePolicy
*image_policy
) {
1624 _cleanup_(release_lock_file
) LockFile global_lock
= LOCK_FILE_INIT
, local_lock
= LOCK_FILE_INIT
;
1629 r
= image_path_lock(i
->path
, LOCK_SH
|LOCK_NB
, &global_lock
, &local_lock
);
1635 case IMAGE_SUBVOLUME
:
1636 case IMAGE_DIRECTORY
: {
1637 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
, **sysext_release
= NULL
, **confext_release
= NULL
;
1638 _cleanup_free_
char *hostname
= NULL
, *path
= NULL
;
1639 sd_id128_t machine_id
= SD_ID128_NULL
;
1641 if (i
->class == IMAGE_SYSEXT
) {
1642 r
= extension_has_forbidden_content(i
->path
);
1646 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM
),
1647 "Conflicting content found in image %s, refusing.",
1651 r
= chase("/etc/hostname", i
->path
, CHASE_PREFIX_ROOT
|CHASE_TRAIL_SLASH
, &path
, NULL
);
1652 if (r
< 0 && r
!= -ENOENT
)
1653 log_debug_errno(r
, "Failed to chase /etc/hostname in image %s: %m", i
->name
);
1655 r
= read_etc_hostname(path
, /* substitute_wildcards= */ false, &hostname
);
1657 log_debug_errno(r
, "Failed to read /etc/hostname of image %s: %m", i
->name
);
1662 r
= id128_get_machine(i
->path
, &machine_id
);
1664 log_debug_errno(r
, "Failed to read machine ID in image %s, ignoring: %m", i
->name
);
1666 r
= chase("/etc/machine-info", i
->path
, CHASE_PREFIX_ROOT
|CHASE_TRAIL_SLASH
, &path
, NULL
);
1667 if (r
< 0 && r
!= -ENOENT
)
1668 log_debug_errno(r
, "Failed to chase /etc/machine-info in image %s: %m", i
->name
);
1670 r
= load_env_file_pairs(NULL
, path
, &machine_info
);
1672 log_debug_errno(r
, "Failed to parse machine-info data of %s: %m", i
->name
);
1675 r
= load_os_release_pairs(i
->path
, &os_release
);
1677 log_debug_errno(r
, "Failed to read os-release in image, ignoring: %m");
1679 r
= load_extension_release_pairs(i
->path
, IMAGE_SYSEXT
, i
->name
, /* relax_extension_release_check= */ false, &sysext_release
);
1681 log_debug_errno(r
, "Failed to read sysext-release in image, ignoring: %m");
1683 r
= load_extension_release_pairs(i
->path
, IMAGE_CONFEXT
, i
->name
, /* relax_extension_release_check= */ false, &confext_release
);
1685 log_debug_errno(r
, "Failed to read confext-release in image, ignoring: %m");
1687 free_and_replace(i
->hostname
, hostname
);
1688 i
->machine_id
= machine_id
;
1689 strv_free_and_replace(i
->machine_info
, machine_info
);
1690 strv_free_and_replace(i
->os_release
, os_release
);
1691 strv_free_and_replace(i
->sysext_release
, sysext_release
);
1692 strv_free_and_replace(i
->confext_release
, confext_release
);
1698 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
1699 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
1700 DissectImageFlags flags
=
1701 DISSECT_IMAGE_GENERIC_ROOT
|
1702 DISSECT_IMAGE_REQUIRE_ROOT
|
1703 DISSECT_IMAGE_RELAX_VAR_CHECK
|
1704 DISSECT_IMAGE_READ_ONLY
|
1705 DISSECT_IMAGE_USR_NO_ROOT
|
1706 DISSECT_IMAGE_ADD_PARTITION_DEVICES
|
1707 DISSECT_IMAGE_PIN_PARTITION_DEVICES
|
1708 DISSECT_IMAGE_VALIDATE_OS
|
1709 DISSECT_IMAGE_VALIDATE_OS_EXT
|
1710 DISSECT_IMAGE_ALLOW_USERSPACE_VERITY
;
1712 r
= loop_device_make_by_path(
1715 /* sector_size= */ UINT32_MAX
,
1722 r
= dissect_loop_device(
1725 /* mount_options= */ NULL
,
1727 /* image_filter= */ NULL
,
1733 r
= dissected_image_acquire_metadata(
1735 /* userns_fd= */ -EBADF
,
1740 free_and_replace(i
->hostname
, m
->hostname
);
1741 i
->machine_id
= m
->machine_id
;
1742 strv_free_and_replace(i
->machine_info
, m
->machine_info
);
1743 strv_free_and_replace(i
->os_release
, m
->os_release
);
1744 strv_free_and_replace(i
->sysext_release
, m
->sysext_release
);
1745 strv_free_and_replace(i
->confext_release
, m
->confext_release
);
1754 i
->metadata_valid
= true;
1759 int image_name_lock(const char *name
, int operation
, LockFile
*ret
) {
1765 /* Locks an image name, regardless of the precise path used. */
1767 if (streq(name
, ".host"))
1770 if (!image_name_is_valid(name
))
1773 if (getenv_bool("SYSTEMD_NSPAWN_LOCK") == 0) {
1774 *ret
= (LockFile
) LOCK_FILE_INIT
;
1780 p
= strjoina("/run/systemd/nspawn/locks/name-", name
);
1781 return make_lock_file(p
, operation
, ret
);
1784 bool image_in_search_path(
1788 const char *image
) {
1792 assert(scope
< _RUNTIME_SCOPE_MAX
&& scope
!= RUNTIME_SCOPE_GLOBAL
);
1794 assert(class < _IMAGE_CLASS_MAX
);
1797 _cleanup_strv_free_
char **search
= NULL
;
1798 r
= pick_image_search_path(scope
, class, &search
);
1802 STRV_FOREACH(path
, search
) {
1806 if (!empty_or_root(root
)) {
1807 q
= path_startswith(*path
, root
);
1813 p
= path_startswith(q
, *path
);
1817 /* Make sure there's a filename following */
1818 k
= strcspn(p
, "/");
1824 /* Accept trailing slashes */
1825 if (p
[strspn(p
, "/")] == 0)
1832 bool image_is_vendor(const struct Image
*i
) {
1835 return i
->path
&& path_startswith(i
->path
, "/usr");
1838 bool image_is_host(const struct Image
*i
) {
1841 if (i
->name
&& streq(i
->name
, ".host"))
1844 if (i
->path
&& path_equal(i
->path
, "/"))
1850 int image_to_json(const struct Image
*img
, sd_json_variant
**ret
) {
1853 return sd_json_buildo(
1855 SD_JSON_BUILD_PAIR_STRING("Type", image_type_to_string(img
->type
)),
1856 SD_JSON_BUILD_PAIR_STRING("Class", image_class_to_string(img
->class)),
1857 SD_JSON_BUILD_PAIR_STRING("Name", img
->name
),
1858 SD_JSON_BUILD_PAIR_CONDITION(!!img
->path
, "Path", SD_JSON_BUILD_STRING(img
->path
)),
1859 SD_JSON_BUILD_PAIR_BOOLEAN("ReadOnly", img
->read_only
),
1860 SD_JSON_BUILD_PAIR_CONDITION(img
->crtime
!= 0, "CreationTimestamp", SD_JSON_BUILD_UNSIGNED(img
->crtime
)),
1861 SD_JSON_BUILD_PAIR_CONDITION(img
->mtime
!= 0, "ModificationTimestamp", SD_JSON_BUILD_UNSIGNED(img
->mtime
)),
1862 SD_JSON_BUILD_PAIR_CONDITION(img
->usage
!= UINT64_MAX
, "Usage", SD_JSON_BUILD_UNSIGNED(img
->usage
)),
1863 SD_JSON_BUILD_PAIR_CONDITION(img
->usage_exclusive
!= UINT64_MAX
, "UsageExclusive", SD_JSON_BUILD_UNSIGNED(img
->usage_exclusive
)),
1864 SD_JSON_BUILD_PAIR_CONDITION(img
->limit
!= UINT64_MAX
, "Limit", SD_JSON_BUILD_UNSIGNED(img
->limit
)),
1865 SD_JSON_BUILD_PAIR_CONDITION(img
->limit_exclusive
!= UINT64_MAX
, "LimitExclusive", SD_JSON_BUILD_UNSIGNED(img
->limit_exclusive
)));
1868 static const char* const image_type_table
[_IMAGE_TYPE_MAX
] = {
1869 [IMAGE_DIRECTORY
] = "directory",
1870 [IMAGE_SUBVOLUME
] = "subvolume",
1871 [IMAGE_RAW
] = "raw",
1872 [IMAGE_BLOCK
] = "block",
1875 DEFINE_STRING_TABLE_LOOKUP(image_type
, ImageType
);