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/,
80 * /.extra/global_sysext, .extra/confext/, and /.extra/global_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 (per-UKI and global) picked up by systemd-stub */
88 "/.extra/global_sysext\0", /* last, since not trusted */
90 [IMAGE_CONFEXT
] = "/run/confexts\0" /* only place symlinks here */
91 "/var/lib/confexts\0" /* the main place for images */
92 "/usr/local/lib/confexts\0"
93 "/.extra/confext\0" /* put confext (per-UKI and global) picked up by systemd-stub */
94 "/.extra/global_confext\0", /* last, since not trusted. */
97 static const char* image_class_suffix_table
[_IMAGE_CLASS_MAX
] = {
98 [IMAGE_SYSEXT
] = ".sysext",
99 [IMAGE_CONFEXT
] = ".confext",
102 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(image_class_suffix
, ImageClass
);
104 static const char *const image_root_table
[_IMAGE_CLASS_MAX
] = {
105 [IMAGE_MACHINE
] = "/var/lib/machines",
106 [IMAGE_PORTABLE
] = "/var/lib/portables",
107 [IMAGE_SYSEXT
] = "/var/lib/extensions",
108 [IMAGE_CONFEXT
] = "/var/lib/confexts",
111 DEFINE_STRING_TABLE_LOOKUP_TO_STRING(image_root
, ImageClass
);
113 static const char *const image_root_runtime_table
[_IMAGE_CLASS_MAX
] = {
114 [IMAGE_MACHINE
] = "/run/machines",
115 [IMAGE_PORTABLE
] = "/run/portables",
116 [IMAGE_SYSEXT
] = "/run/extensions",
117 [IMAGE_CONFEXT
] = "/run/confexts",
120 DEFINE_STRING_TABLE_LOOKUP_TO_STRING(image_root_runtime
, ImageClass
);
122 static Image
* image_free(Image
*i
) {
129 strv_free(i
->machine_info
);
130 strv_free(i
->os_release
);
131 strv_free(i
->sysext_release
);
132 strv_free(i
->confext_release
);
137 DEFINE_TRIVIAL_REF_UNREF_FUNC(Image
, image
, image_free
);
138 DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(image_hash_ops
, char, string_hash_func
, string_compare_func
,
141 static char** image_settings_path(Image
*image
) {
142 _cleanup_strv_free_
char **l
= NULL
;
143 _cleanup_free_
char *fn
= NULL
;
153 fn
= strjoin(image
->name
, ".nspawn");
157 FOREACH_STRING(s
, "/etc/systemd/nspawn", "/run/systemd/nspawn") {
158 l
[i
] = path_join(s
, fn
);
165 r
= file_in_same_dir(image
->path
, fn
, l
+ i
);
169 log_debug_errno(r
, "Failed to generate .nspawn settings path from image path, ignoring: %m");
176 static int image_roothash_path(Image
*image
, char **ret
) {
177 _cleanup_free_
char *fn
= NULL
;
181 fn
= strjoin(image
->name
, ".roothash");
185 return file_in_same_dir(image
->path
, fn
, ret
);
188 static int image_new(
193 const char *filename
,
199 _cleanup_(image_unrefp
) Image
*i
= NULL
;
202 assert(t
< _IMAGE_TYPE_MAX
);
215 .read_only
= read_only
,
219 .usage_exclusive
= UINT64_MAX
,
221 .limit_exclusive
= UINT64_MAX
,
224 i
->name
= strdup(pretty
);
228 i
->path
= path_join(path
, filename
);
232 path_simplify(i
->path
);
239 static int extract_image_basename(
241 const char *class_suffix
, /* e.g. ".sysext" (this is an optional suffix) */
242 char **format_suffixes
, /* e.g. ".raw" (one of these will be required) */
246 _cleanup_free_
char *name
= NULL
, *suffix
= NULL
;
251 r
= path_extract_filename(path
, &name
);
255 if (format_suffixes
) {
256 char *e
= endswith_strv(name
, format_suffixes
);
257 if (!e
) /* Format suffix is required */
270 char *e
= endswith(name
, class_suffix
);
271 if (e
) { /* Class suffix is optional */
273 _cleanup_free_
char *j
= strjoin(e
, suffix
);
277 free_and_replace(suffix
, j
);
284 if (!image_name_is_valid(name
))
288 *ret_suffix
= TAKE_PTR(suffix
);
291 *ret_basename
= TAKE_PTR(name
);
296 static int image_update_quota(Image
*i
, int fd
) {
297 _cleanup_close_
int fd_close
= -EBADF
;
302 if (image_is_vendor(i
) || image_is_host(i
))
305 if (i
->type
!= IMAGE_SUBVOLUME
)
309 fd_close
= open(i
->path
, O_CLOEXEC
|O_DIRECTORY
);
314 /* Convert from O_PATH to proper fd, if needed */
315 fd
= fd_reopen_condition(fd
, O_CLOEXEC
|O_DIRECTORY
, O_PATH
, &fd_close
);
320 r
= btrfs_quota_scan_ongoing(fd
);
326 BtrfsQuotaInfo quota
;
327 r
= btrfs_subvol_get_subtree_quota_fd(fd
, 0, "a
);
331 i
->usage
= quota
.referenced
;
332 i
->usage_exclusive
= quota
.exclusive
;
333 i
->limit
= quota
.referenced_max
;
334 i
->limit_exclusive
= quota
.exclusive_max
;
339 static int image_make(
343 const char *dir_path
,
344 const char *filename
,
345 int fd
, /* O_PATH fd */
346 const struct stat
*st
,
349 _cleanup_free_
char *pretty_buffer
= NULL
;
353 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
354 assert(dir_path
|| dir_fd
== AT_FDCWD
);
357 /* We explicitly *do* follow symlinks here, since we want to allow symlinking trees, raw files and block
358 * devices into /var/lib/machines/, and treat them normally.
360 * This function returns -ENOENT if we can't find the image after all, and -EMEDIUMTYPE if it's not a file we
363 _cleanup_close_
int _fd
= -EBADF
;
365 /* If we didn't get an fd passed in, then let's pin it via O_PATH now */
366 _fd
= openat(dir_fd
, filename
, O_PATH
|O_CLOEXEC
);
371 st
= NULL
; /* refresh stat() data now that we have the inode pinned */
376 if (fstat(fd
, &stbuf
) < 0)
382 _cleanup_free_
char *parent
= NULL
;
384 (void) fd_get_path(dir_fd
, &parent
);
389 (dir_path
&& path_startswith(dir_path
, "/usr")) ||
390 (faccessat(fd
, "", W_OK
, AT_EACCESS
|AT_EMPTY_PATH
) < 0 && errno
== EROFS
);
392 if (S_ISDIR(st
->st_mode
)) {
393 unsigned file_attr
= 0;
400 r
= extract_image_basename(
402 image_class_suffix_to_string(c
),
403 /* format_suffixes= */ NULL
,
405 /* ret_suffix= */ NULL
);
409 pretty
= pretty_buffer
;
412 if (btrfs_might_be_subvol(st
)) {
414 r
= fd_is_fs_type(fd
, BTRFS_SUPER_MAGIC
);
418 BtrfsSubvolInfo info
;
420 /* It's a btrfs subvolume */
422 r
= btrfs_subvol_get_info_fd(fd
, 0, &info
);
426 r
= image_new(IMAGE_SUBVOLUME
,
431 info
.read_only
|| read_only
,
438 (void) image_update_quota(*ret
, fd
);
443 /* Get directory creation time (not available everywhere, but that's OK */
444 (void) fd_getcrtime(fd
, &crtime
);
446 /* If the IMMUTABLE bit is set, we consider the directory read-only. Since the ioctl is not
447 * supported everywhere we ignore failures. */
448 (void) read_attr_fd(fd
, &file_attr
);
450 /* It's just a normal directory. */
451 r
= image_new(IMAGE_DIRECTORY
,
456 read_only
|| (file_attr
& FS_IMMUTABLE_FL
),
458 0, /* we don't use mtime of stat() here, since it's not the time of last change of the tree, but only of the top-level dir */
465 } else if (S_ISREG(st
->st_mode
) && endswith(filename
, ".raw")) {
468 /* It's a RAW disk image */
473 (void) fd_getcrtime(fd
, &crtime
);
476 r
= extract_image_basename(
478 image_class_suffix_to_string(c
),
481 /* ret_suffix= */ NULL
);
485 pretty
= pretty_buffer
;
488 r
= image_new(IMAGE_RAW
,
493 !(st
->st_mode
& 0222) || read_only
,
495 timespec_load(&st
->st_mtim
),
500 (*ret
)->usage
= (*ret
)->usage_exclusive
= st
->st_blocks
* 512;
501 (*ret
)->limit
= (*ret
)->limit_exclusive
= st
->st_size
;
505 } else if (S_ISBLK(st
->st_mode
)) {
506 uint64_t size
= UINT64_MAX
;
514 r
= extract_image_basename(
516 /* class_suffix= */ NULL
,
517 /* format_suffix= */ NULL
,
519 /* ret_suffix= */ NULL
);
523 pretty
= pretty_buffer
;
526 _cleanup_close_
int block_fd
= fd_reopen(fd
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
528 log_debug_errno(errno
, "Failed to open block device %s/%s, ignoring: %m", strnull(dir_path
), filename
);
533 if (ioctl(block_fd
, BLKROGET
, &state
) < 0)
534 log_debug_errno(errno
, "Failed to issue BLKROGET on device %s/%s, ignoring: %m", strnull(dir_path
), filename
);
539 r
= blockdev_get_device_size(block_fd
, &size
);
541 log_debug_errno(r
, "Failed to issue BLKGETSIZE64 on device %s/%s, ignoring: %m", strnull(dir_path
), filename
);
543 block_fd
= safe_close(block_fd
);
546 r
= image_new(IMAGE_BLOCK
,
551 !(st
->st_mode
& 0222) || read_only
,
558 if (!IN_SET(size
, 0, UINT64_MAX
))
559 (*ret
)->usage
= (*ret
)->usage_exclusive
= (*ret
)->limit
= (*ret
)->limit_exclusive
= size
;
567 static int pick_image_search_path(
574 assert(scope
< _RUNTIME_SCOPE_MAX
&& scope
!= RUNTIME_SCOPE_GLOBAL
);
575 assert(class < _IMAGE_CLASS_MAX
);
584 _cleanup_strv_free_
char **a
= NULL
, **b
= NULL
;
586 r
= pick_image_search_path(RUNTIME_SCOPE_USER
, class, &a
);
590 r
= pick_image_search_path(RUNTIME_SCOPE_SYSTEM
, class, &b
);
594 r
= strv_extend_strv(&a
, b
, /* filter_duplicates= */ false);
604 case RUNTIME_SCOPE_SYSTEM
: {
606 /* Use the initrd search path if there is one, otherwise use the common one */
607 ns
= in_initrd() && image_search_path_initrd
[class] ?
608 image_search_path_initrd
[class] :
609 image_search_path
[class];
613 _cleanup_strv_free_
char **search
= strv_split_nulstr(ns
);
617 *ret
= TAKE_PTR(search
);
621 case RUNTIME_SCOPE_USER
: {
622 if (class != IMAGE_MACHINE
)
625 static const uint64_t dirs
[] = {
626 SD_PATH_USER_RUNTIME
,
627 SD_PATH_USER_STATE_PRIVATE
,
628 SD_PATH_USER_LIBRARY_PRIVATE
,
631 _cleanup_strv_free_
char **search
= NULL
;
632 FOREACH_ELEMENT(d
, dirs
) {
633 _cleanup_free_
char *p
= NULL
;
635 r
= sd_path_lookup(*d
, "machines", &p
);
636 if (r
== -ENXIO
) /* No XDG_RUNTIME_DIR set */
641 r
= strv_consume(&search
, TAKE_PTR(p
));
646 *ret
= TAKE_PTR(search
);
651 assert_not_reached();
658 static char** make_possible_filenames(ImageClass
class, const char *image_name
) {
659 _cleanup_strv_free_
char **l
= NULL
;
663 FOREACH_STRING(v_suffix
, "", ".v")
664 FOREACH_STRING(format_suffix
, "", ".raw") {
665 _cleanup_free_
char *j
= NULL
;
666 const char *class_suffix
;
668 class_suffix
= image_class_suffix_to_string(class);
670 j
= strjoin(image_name
, class_suffix
, format_suffix
, v_suffix
);
674 if (strv_consume(&l
, TAKE_PTR(j
)) < 0)
678 j
= strjoin(image_name
, format_suffix
, v_suffix
);
682 if (strv_consume(&l
, TAKE_PTR(j
)) < 0)
689 int image_find(RuntimeScope scope
,
695 /* As mentioned above, we follow symlinks on this fstatat(), because we want to permit people to
696 * symlink block devices into the search path. (For now, we disable that when operating relative to
697 * some root directory.) */
698 int open_flags
= root
? O_NOFOLLOW
: 0, r
;
700 assert(scope
< _RUNTIME_SCOPE_MAX
&& scope
!= RUNTIME_SCOPE_GLOBAL
);
702 assert(class < _IMAGE_CLASS_MAX
);
705 /* There are no images with invalid names */
706 if (!image_name_is_valid(name
))
709 _cleanup_strv_free_
char **names
= make_possible_filenames(class, name
);
713 _cleanup_strv_free_
char **search
= NULL
;
714 r
= pick_image_search_path(scope
, class, &search
);
718 STRV_FOREACH(path
, search
) {
719 _cleanup_free_
char *resolved
= NULL
;
720 _cleanup_closedir_
DIR *d
= NULL
;
722 r
= chase_and_opendir(*path
, root
, CHASE_PREFIX_ROOT
, &resolved
, &d
);
728 STRV_FOREACH(n
, names
) {
729 _cleanup_free_
char *fname_buf
= NULL
;
730 const char *fname
= *n
;
732 _cleanup_close_
int fd
= openat(dirfd(d
), fname
, O_PATH
|O_CLOEXEC
|open_flags
);
741 if (fstat(fd
, &st
) < 0)
744 if (endswith(fname
, ".raw")) {
745 if (!S_ISREG(st
.st_mode
)) {
746 log_debug("Ignoring non-regular file '%s' with .raw suffix.", fname
);
750 } else if (endswith(fname
, ".v")) {
752 if (!S_ISDIR(st
.st_mode
)) {
753 log_debug("Ignoring non-directory file '%s' with .v suffix.", fname
);
757 _cleanup_free_
char *suffix
= NULL
;
758 suffix
= strdup(ASSERT_PTR(startswith(fname
, name
)));
762 *ASSERT_PTR(endswith(suffix
, ".v")) = 0;
764 _cleanup_free_
char *vp
= path_join(resolved
, fname
);
768 PickFilter filter
= {
769 .type_mask
= endswith(suffix
, ".raw") ? (UINT32_C(1) << DT_REG
) | (UINT32_C(1) << DT_BLK
) : (UINT32_C(1) << DT_DIR
),
771 .architecture
= _ARCHITECTURE_INVALID
,
772 .suffix
= STRV_MAKE(suffix
),
775 _cleanup_(pick_result_done
) PickResult result
= PICK_RESULT_NULL
;
777 /* toplevel_fd= */ AT_FDCWD
,
780 PICK_ARCHITECTURE
|PICK_TRIES
,
783 log_debug_errno(r
, "Failed to pick versioned image on '%s', skipping: %m", vp
);
787 log_debug("Found versioned directory '%s', without matching entry, skipping: %m", vp
);
791 /* Refresh the stat data for the discovered target */
795 _cleanup_free_
char *bn
= NULL
;
796 r
= path_extract_filename(result
.path
, &bn
);
798 log_debug_errno(r
, "Failed to extract basename of image path '%s', skipping: %m", result
.path
);
802 fname_buf
= path_join(fname
, bn
);
808 } else if (!S_ISDIR(st
.st_mode
) && !S_ISBLK(st
.st_mode
)) {
809 log_debug("Ignoring non-directory and non-block device file '%s' without suffix.", fname
);
813 r
= image_make(class, name
, dirfd(d
), resolved
, fname
, fd
, &st
, ret
);
814 if (IN_SET(r
, -ENOENT
, -EMEDIUMTYPE
))
820 (*ret
)->discoverable
= true;
826 if (scope
== RUNTIME_SCOPE_SYSTEM
&& class == IMAGE_MACHINE
&& streq(name
, ".host")) {
827 r
= image_make(class,
829 /* dir_fd= */ AT_FDCWD
,
830 /* dir_path= */ NULL
,
831 /* filename= */ empty_to_root(root
),
839 (*ret
)->discoverable
= true;
847 int image_from_path(const char *path
, Image
**ret
) {
849 /* Note that we don't set the 'discoverable' field of the returned object, because we don't check here whether
850 * the image is in the image search path. And if it is we don't know if the path we used is actually not
851 * overridden by another, different image earlier in the search path */
853 if (path_equal(path
, "/"))
857 /* dir_fd= */ AT_FDCWD
,
858 /* dir_path= */ NULL
,
865 _IMAGE_CLASS_INVALID
,
867 /* dir_fd= */ AT_FDCWD
,
868 /* dir_path= */ NULL
,
869 /* filename= */ path
,
875 int image_find_harder(
878 const char *name_or_path
,
882 if (image_name_is_valid(name_or_path
))
883 return image_find(scope
, class, name_or_path
, root
, ret
);
885 return image_from_path(name_or_path
, ret
);
894 /* As mentioned above, we follow symlinks on this fstatat(), because we want to permit people to
895 * symlink block devices into the search path. (For now, we disable that when operating relative to
896 * some root directory.) */
897 int open_flags
= root
? O_NOFOLLOW
: 0, r
;
899 assert(scope
< _RUNTIME_SCOPE_MAX
&& scope
!= RUNTIME_SCOPE_GLOBAL
);
901 assert(class < _IMAGE_CLASS_MAX
);
904 _cleanup_strv_free_
char **search
= NULL
;
905 r
= pick_image_search_path(scope
, class, &search
);
909 STRV_FOREACH(path
, search
) {
910 _cleanup_free_
char *resolved
= NULL
;
911 _cleanup_closedir_
DIR *d
= NULL
;
913 r
= chase_and_opendir(*path
, root
, CHASE_PREFIX_ROOT
, &resolved
, &d
);
919 FOREACH_DIRENT_ALL(de
, d
, return -errno
) {
920 _cleanup_free_
char *pretty
= NULL
, *fname_buf
= NULL
;
921 _cleanup_(image_unrefp
) Image
*image
= NULL
;
922 const char *fname
= de
->d_name
;
924 if (dot_or_dot_dot(fname
))
927 _cleanup_close_
int fd
= openat(dirfd(d
), fname
, O_PATH
|O_CLOEXEC
|open_flags
);
932 continue; /* Vanished while we were looking at it */
936 if (fstat(fd
, &st
) < 0)
939 if (S_ISREG(st
.st_mode
)) {
940 r
= extract_image_basename(
942 image_class_suffix_to_string(class),
945 /* ret_suffix= */ NULL
);
947 log_debug_errno(r
, "Skipping directory entry '%s', which doesn't look like an image.", fname
);
950 } else if (S_ISDIR(st
.st_mode
)) {
953 v
= endswith(fname
, ".v");
955 _cleanup_free_
char *suffix
= NULL
, *nov
= NULL
;
957 nov
= strndup(fname
, v
- fname
); /* Chop off the .v */
961 r
= extract_image_basename(
963 image_class_suffix_to_string(class),
964 STRV_MAKE(".raw", ""),
968 log_debug_errno(r
, "Skipping directory entry '%s', which doesn't look like a versioned image.", fname
);
972 _cleanup_free_
char *vp
= path_join(resolved
, fname
);
976 PickFilter filter
= {
977 .type_mask
= endswith(suffix
, ".raw") ? (UINT32_C(1) << DT_REG
) | (UINT32_C(1) << DT_BLK
) : (UINT32_C(1) << DT_DIR
),
979 .architecture
= _ARCHITECTURE_INVALID
,
980 .suffix
= STRV_MAKE(suffix
),
983 _cleanup_(pick_result_done
) PickResult result
= PICK_RESULT_NULL
;
985 /* toplevel_fd= */ AT_FDCWD
,
988 PICK_ARCHITECTURE
|PICK_TRIES
,
991 log_debug_errno(r
, "Failed to pick versioned image on '%s', skipping: %m", vp
);
995 log_debug("Found versioned directory '%s', without matching entry, skipping: %m", vp
);
999 /* Refresh the stat data for the discovered target */
1001 fd
= safe_close(fd
);
1003 _cleanup_free_
char *bn
= NULL
;
1004 r
= path_extract_filename(result
.path
, &bn
);
1006 log_debug_errno(r
, "Failed to extract basename of image path '%s', skipping: %m", result
.path
);
1010 fname_buf
= path_join(fname
, bn
);
1016 r
= extract_image_basename(
1018 image_class_suffix_to_string(class),
1019 /* format_suffixes= */ NULL
,
1021 /* ret_suffix= */ NULL
);
1023 log_debug_errno(r
, "Skipping directory entry '%s', which doesn't look like an image.", fname
);
1028 } else if (S_ISBLK(st
.st_mode
)) {
1029 r
= extract_image_basename(
1031 /* class_suffix= */ NULL
,
1032 /* format_suffix= */ NULL
,
1034 /* ret_suffix= */ NULL
);
1036 log_debug_errno(r
, "Skipping directory entry '%s', which doesn't look like an image.", fname
);
1040 log_debug("Skipping directory entry '%s', which is neither regular file, directory nor block device.", fname
);
1044 if (hashmap_contains(*images
, pretty
))
1047 r
= image_make(class, pretty
, dirfd(d
), resolved
, fname
, fd
, &st
, &image
);
1048 if (IN_SET(r
, -ENOENT
, -EMEDIUMTYPE
))
1053 image
->discoverable
= true;
1055 r
= hashmap_ensure_put(images
, &image_hash_ops
, image
->name
, image
);
1063 if (scope
== RUNTIME_SCOPE_SYSTEM
&& class == IMAGE_MACHINE
&& !hashmap_contains(*images
, ".host")) {
1064 _cleanup_(image_unrefp
) Image
*image
= NULL
;
1066 r
= image_make(IMAGE_MACHINE
,
1068 /* dir_fd= */ AT_FDCWD
,
1069 /* dir_path= */ NULL
,
1070 empty_to_root(root
),
1077 image
->discoverable
= true;
1079 r
= hashmap_ensure_put(images
, &image_hash_ops
, image
->name
, image
);
1089 int image_remove(Image
*i
) {
1090 _cleanup_(release_lock_file
) LockFile global_lock
= LOCK_FILE_INIT
, local_lock
= LOCK_FILE_INIT
;
1091 _cleanup_strv_free_
char **settings
= NULL
;
1092 _cleanup_free_
char *roothash
= NULL
;
1097 if (image_is_vendor(i
) || image_is_host(i
))
1100 settings
= image_settings_path(i
);
1104 r
= image_roothash_path(i
, &roothash
);
1108 /* Make sure we don't interfere with a running nspawn */
1109 r
= image_path_lock(i
->path
, LOCK_EX
|LOCK_NB
, &global_lock
, &local_lock
);
1115 case IMAGE_SUBVOLUME
:
1117 /* Let's unlink first, maybe it is a symlink? If that works we are happy. Otherwise, let's get out the
1119 if (unlink(i
->path
) < 0) {
1120 r
= btrfs_subvol_remove(i
->path
, BTRFS_REMOVE_RECURSIVE
|BTRFS_REMOVE_QUOTA
);
1127 case IMAGE_DIRECTORY
:
1128 /* Allow deletion of read-only directories */
1129 (void) chattr_path(i
->path
, 0, FS_IMMUTABLE_FL
);
1130 r
= rm_rf(i
->path
, REMOVE_ROOT
|REMOVE_PHYSICAL
|REMOVE_SUBVOLUME
);
1138 /* If this is inside of /dev, then it's a real block device, hence let's not touch the device node
1139 * itself (but let's remove the stuff stored alongside it). If it's anywhere else, let's try to unlink
1140 * the thing (it's most likely a symlink after all). */
1142 if (path_startswith(i
->path
, "/dev"))
1147 if (unlink(i
->path
) < 0)
1155 STRV_FOREACH(j
, settings
)
1156 if (unlink(*j
) < 0 && errno
!= ENOENT
)
1157 log_debug_errno(errno
, "Failed to unlink %s, ignoring: %m", *j
);
1159 if (unlink(roothash
) < 0 && errno
!= ENOENT
)
1160 log_debug_errno(errno
, "Failed to unlink %s, ignoring: %m", roothash
);
1165 static int rename_auxiliary_file(const char *path
, const char *new_name
, const char *suffix
) {
1166 _cleanup_free_
char *fn
= NULL
, *rs
= NULL
;
1169 fn
= strjoin(new_name
, suffix
);
1173 r
= file_in_same_dir(path
, fn
, &rs
);
1177 return rename_noreplace(AT_FDCWD
, path
, AT_FDCWD
, rs
);
1180 int image_rename(Image
*i
, const char *new_name
, RuntimeScope scope
) {
1181 _cleanup_(release_lock_file
) LockFile global_lock
= LOCK_FILE_INIT
, local_lock
= LOCK_FILE_INIT
, name_lock
= LOCK_FILE_INIT
;
1182 _cleanup_free_
char *new_path
= NULL
, *nn
= NULL
, *roothash
= NULL
;
1183 _cleanup_strv_free_
char **settings
= NULL
;
1184 unsigned file_attr
= 0;
1189 if (!image_name_is_valid(new_name
))
1192 if (image_is_vendor(i
) || image_is_host(i
))
1195 settings
= image_settings_path(i
);
1199 r
= image_roothash_path(i
, &roothash
);
1203 /* Make sure we don't interfere with a running nspawn */
1204 r
= image_path_lock(i
->path
, LOCK_EX
|LOCK_NB
, &global_lock
, &local_lock
);
1208 /* Make sure nobody takes the new name, between the time we
1209 * checked it is currently unused in all search paths, and the
1210 * time we take possession of it */
1211 r
= image_name_lock(new_name
, LOCK_EX
|LOCK_NB
, &name_lock
);
1215 r
= image_find(scope
, IMAGE_MACHINE
, new_name
, NULL
, NULL
);
1223 case IMAGE_DIRECTORY
:
1224 /* Turn of the immutable bit while we rename the image, so that we can rename it */
1225 (void) read_attr_at(AT_FDCWD
, i
->path
, &file_attr
);
1227 if (file_attr
& FS_IMMUTABLE_FL
)
1228 (void) chattr_path(i
->path
, 0, FS_IMMUTABLE_FL
);
1231 case IMAGE_SUBVOLUME
:
1232 r
= file_in_same_dir(i
->path
, new_name
, &new_path
);
1237 /* Refuse renaming raw block devices in /dev, the names are picked by udev after all. */
1238 if (path_startswith(i
->path
, "/dev"))
1241 r
= file_in_same_dir(i
->path
, new_name
, &new_path
);
1247 fn
= strjoina(new_name
, ".raw");
1249 r
= file_in_same_dir(i
->path
, fn
, &new_path
);
1259 nn
= strdup(new_name
);
1263 r
= rename_noreplace(AT_FDCWD
, i
->path
, AT_FDCWD
, new_path
);
1267 /* Restore the immutable bit, if it was set before */
1268 if (file_attr
& FS_IMMUTABLE_FL
)
1269 (void) chattr_path(new_path
, FS_IMMUTABLE_FL
, FS_IMMUTABLE_FL
);
1271 free_and_replace(i
->path
, new_path
);
1272 free_and_replace(i
->name
, nn
);
1274 STRV_FOREACH(j
, settings
) {
1275 r
= rename_auxiliary_file(*j
, new_name
, ".nspawn");
1276 if (r
< 0 && r
!= -ENOENT
)
1277 log_debug_errno(r
, "Failed to rename settings file %s, ignoring: %m", *j
);
1280 r
= rename_auxiliary_file(roothash
, new_name
, ".roothash");
1281 if (r
< 0 && r
!= -ENOENT
)
1282 log_debug_errno(r
, "Failed to rename roothash file %s, ignoring: %m", roothash
);
1287 static int clone_auxiliary_file(const char *path
, const char *new_name
, const char *suffix
) {
1288 _cleanup_free_
char *fn
= NULL
, *rs
= NULL
;
1291 fn
= strjoin(new_name
, suffix
);
1295 r
= file_in_same_dir(path
, fn
, &rs
);
1299 return copy_file_atomic(path
, rs
, 0664, COPY_REFLINK
);
1302 int image_clone(Image
*i
, const char *new_name
, bool read_only
, RuntimeScope scope
) {
1303 _cleanup_(release_lock_file
) LockFile name_lock
= LOCK_FILE_INIT
;
1304 _cleanup_strv_free_
char **settings
= NULL
;
1305 _cleanup_free_
char *roothash
= NULL
;
1306 const char *new_path
;
1311 if (!image_name_is_valid(new_name
))
1314 settings
= image_settings_path(i
);
1318 r
= image_roothash_path(i
, &roothash
);
1322 /* Make sure nobody takes the new name, between the time we
1323 * checked it is currently unused in all search paths, and the
1324 * time we take possession of it */
1325 r
= image_name_lock(new_name
, LOCK_EX
|LOCK_NB
, &name_lock
);
1329 r
= image_find(scope
, IMAGE_MACHINE
, new_name
, NULL
, NULL
);
1337 case IMAGE_SUBVOLUME
:
1338 case IMAGE_DIRECTORY
:
1339 /* If we can we'll always try to create a new btrfs subvolume here, even if the source is a plain
1342 new_path
= strjoina("/var/lib/machines/", new_name
);
1344 r
= btrfs_subvol_snapshot_at(AT_FDCWD
, i
->path
, AT_FDCWD
, new_path
,
1345 (read_only
? BTRFS_SNAPSHOT_READ_ONLY
: 0) |
1346 BTRFS_SNAPSHOT_FALLBACK_COPY
|
1347 BTRFS_SNAPSHOT_FALLBACK_DIRECTORY
|
1348 BTRFS_SNAPSHOT_FALLBACK_IMMUTABLE
|
1349 BTRFS_SNAPSHOT_RECURSIVE
|
1350 BTRFS_SNAPSHOT_QUOTA
);
1352 /* Enable "subtree" quotas for the copy, if we didn't copy any quota from the source. */
1353 (void) btrfs_subvol_auto_qgroup(new_path
, 0, true);
1358 new_path
= strjoina("/var/lib/machines/", new_name
, ".raw");
1360 r
= copy_file_atomic(i
->path
, new_path
, read_only
? 0444 : 0644,
1361 COPY_REFLINK
|COPY_CRTIME
|COPY_NOCOW_AFTER
);
1372 STRV_FOREACH(j
, settings
) {
1373 r
= clone_auxiliary_file(*j
, new_name
, ".nspawn");
1374 if (r
< 0 && r
!= -ENOENT
)
1375 log_debug_errno(r
, "Failed to clone settings %s, ignoring: %m", *j
);
1378 r
= clone_auxiliary_file(roothash
, new_name
, ".roothash");
1379 if (r
< 0 && r
!= -ENOENT
)
1380 log_debug_errno(r
, "Failed to clone root hash file %s, ignoring: %m", roothash
);
1385 int image_read_only(Image
*i
, bool b
) {
1386 _cleanup_(release_lock_file
) LockFile global_lock
= LOCK_FILE_INIT
, local_lock
= LOCK_FILE_INIT
;
1391 if (image_is_vendor(i
) || image_is_host(i
))
1394 /* Make sure we don't interfere with a running nspawn */
1395 r
= image_path_lock(i
->path
, LOCK_EX
|LOCK_NB
, &global_lock
, &local_lock
);
1401 case IMAGE_SUBVOLUME
:
1403 /* Note that we set the flag only on the top-level
1404 * subvolume of the image. */
1406 r
= btrfs_subvol_set_read_only(i
->path
, b
);
1412 case IMAGE_DIRECTORY
:
1413 /* For simple directory trees we cannot use the access
1414 mode of the top-level directory, since it has an
1415 effect on the container itself. However, we can
1416 use the "immutable" flag, to at least make the
1417 top-level directory read-only. It's not as good as
1418 a read-only subvolume, but at least something, and
1419 we can read the value back. */
1421 r
= chattr_path(i
->path
, b
? FS_IMMUTABLE_FL
: 0, FS_IMMUTABLE_FL
);
1430 if (stat(i
->path
, &st
) < 0)
1433 if (chmod(i
->path
, (st
.st_mode
& 0444) | (b
? 0000 : 0200)) < 0)
1436 /* If the images is now read-only, it's a good time to
1437 * defrag it, given that no write patterns will
1438 * fragment it again. */
1440 (void) btrfs_defrag(i
->path
);
1445 _cleanup_close_
int fd
= -EBADF
;
1449 fd
= open(i
->path
, O_CLOEXEC
|O_RDONLY
|O_NONBLOCK
|O_NOCTTY
);
1453 if (fstat(fd
, &st
) < 0)
1455 if (!S_ISBLK(st
.st_mode
))
1458 if (ioctl(fd
, BLKROSET
, &state
) < 0)
1472 static void make_lock_dir(void) {
1473 (void) mkdir_p("/run/systemd/nspawn", 0755);
1474 (void) mkdir("/run/systemd/nspawn/locks", 0700);
1477 int image_path_lock(
1480 LockFile
*ret_global
,
1481 LockFile
*ret_local
) {
1483 _cleanup_free_
char *p
= NULL
;
1484 LockFile t
= LOCK_FILE_INIT
;
1492 /* Locks an image path. This actually creates two locks: one "local" one, next to the image path
1493 * itself, which might be shared via NFS. And another "global" one, in /run, that uses the
1494 * device/inode number. This has the benefit that we can even lock a tree that is a mount point,
1497 if (!path_is_absolute(path
))
1500 switch (operation
& (LOCK_SH
|LOCK_EX
)) {
1511 if (getenv_bool("SYSTEMD_NSPAWN_LOCK") == 0) {
1512 *ret_local
= LOCK_FILE_INIT
;
1514 *ret_global
= LOCK_FILE_INIT
;
1518 /* Prohibit taking exclusive locks on the host image. We can't allow this, since we ourselves are
1519 * running off it after all, and we don't want any images to manipulate the host image. We make an
1520 * exception for shared locks however: we allow those (and make them NOPs since there's no point in
1521 * taking them if there can't be exclusive locks). Strictly speaking these are questionable as well,
1522 * since it means changes made to the host might propagate to the container as they happen (and a
1523 * shared lock kinda suggests that no changes happen at all while it is in place), but it's too
1524 * useful not to allow read-only containers off the host root, hence let's support this, and trust
1525 * the user to do the right thing with this. */
1526 if (path_equal(path
, "/")) {
1530 *ret_local
= LOCK_FILE_INIT
;
1532 *ret_global
= LOCK_FILE_INIT
;
1537 if (stat(path
, &st
) >= 0) {
1538 if (S_ISBLK(st
.st_mode
))
1539 r
= asprintf(&p
, "/run/systemd/nspawn/locks/block-%u:%u", major(st
.st_rdev
), minor(st
.st_rdev
));
1540 else if (S_ISDIR(st
.st_mode
) || S_ISREG(st
.st_mode
))
1541 r
= asprintf(&p
, "/run/systemd/nspawn/locks/inode-%lu:%lu", (unsigned long) st
.st_dev
, (unsigned long) st
.st_ino
);
1549 /* For block devices we don't need the "local" lock, as the major/minor lock above should be
1550 * sufficient, since block devices are host local anyway. */
1551 if (!path_startswith(path
, "/dev/")) {
1552 r
= make_lock_file_for(path
, operation
, &t
);
1554 if (!exclusive
&& r
== -EROFS
)
1555 log_debug_errno(r
, "Failed to create shared lock for '%s', ignoring: %m", path
);
1564 r
= make_lock_file(p
, operation
, ret_global
);
1566 release_lock_file(&t
);
1569 } else if (ret_global
)
1570 *ret_global
= LOCK_FILE_INIT
;
1576 int image_set_limit(Image
*i
, uint64_t referenced_max
) {
1581 if (image_is_vendor(i
) || image_is_host(i
))
1584 if (i
->type
!= IMAGE_SUBVOLUME
)
1587 /* We set the quota both for the subvolume as well as for the
1588 * subtree. The latter is mostly for historical reasons, since
1589 * we didn't use to have a concept of subtree quota, and hence
1590 * only modified the subvolume quota. */
1592 (void) btrfs_qgroup_set_limit(i
->path
, 0, referenced_max
);
1593 (void) btrfs_subvol_auto_qgroup(i
->path
, 0, true);
1594 r
= btrfs_subvol_set_subtree_quota_limit(i
->path
, 0, referenced_max
);
1598 (void) image_update_quota(i
, -EBADF
);
1602 int image_set_pool_limit(ImageClass
class, uint64_t referenced_max
) {
1606 assert(class >= 0 && class < _IMAGE_CLASS_MAX
);
1608 dir
= image_root_to_string(class);
1610 r
= btrfs_qgroup_set_limit(dir
, /* qgroupid = */ 0, referenced_max
);
1611 if (ERRNO_IS_NEG_NOT_SUPPORTED(r
))
1614 log_debug_errno(r
, "Failed to set limit on btrfs quota group for '%s', ignoring: %m", dir
);
1616 r
= btrfs_subvol_set_subtree_quota_limit(dir
, /* subvol_id = */ 0, referenced_max
);
1617 if (ERRNO_IS_NEG_NOT_SUPPORTED(r
))
1620 return log_debug_errno(r
, "Failed to set subtree quota limit for '%s': %m", dir
);
1625 int image_read_metadata(Image
*i
, const ImagePolicy
*image_policy
) {
1626 _cleanup_(release_lock_file
) LockFile global_lock
= LOCK_FILE_INIT
, local_lock
= LOCK_FILE_INIT
;
1631 r
= image_path_lock(i
->path
, LOCK_SH
|LOCK_NB
, &global_lock
, &local_lock
);
1637 case IMAGE_SUBVOLUME
:
1638 case IMAGE_DIRECTORY
: {
1639 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
, **sysext_release
= NULL
, **confext_release
= NULL
;
1640 _cleanup_free_
char *hostname
= NULL
, *path
= NULL
;
1641 sd_id128_t machine_id
= SD_ID128_NULL
;
1643 if (i
->class == IMAGE_SYSEXT
) {
1644 r
= extension_has_forbidden_content(i
->path
);
1648 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM
),
1649 "Conflicting content found in image %s, refusing.",
1653 r
= chase("/etc/hostname", i
->path
, CHASE_PREFIX_ROOT
|CHASE_TRAIL_SLASH
, &path
, NULL
);
1654 if (r
< 0 && r
!= -ENOENT
)
1655 log_debug_errno(r
, "Failed to chase /etc/hostname in image %s: %m", i
->name
);
1657 r
= read_etc_hostname(path
, /* substitute_wildcards= */ false, &hostname
);
1659 log_debug_errno(r
, "Failed to read /etc/hostname of image %s: %m", i
->name
);
1664 r
= id128_get_machine(i
->path
, &machine_id
);
1666 log_debug_errno(r
, "Failed to read machine ID in image %s, ignoring: %m", i
->name
);
1668 r
= chase("/etc/machine-info", i
->path
, CHASE_PREFIX_ROOT
|CHASE_TRAIL_SLASH
, &path
, NULL
);
1669 if (r
< 0 && r
!= -ENOENT
)
1670 log_debug_errno(r
, "Failed to chase /etc/machine-info in image %s: %m", i
->name
);
1672 r
= load_env_file_pairs(NULL
, path
, &machine_info
);
1674 log_debug_errno(r
, "Failed to parse machine-info data of %s: %m", i
->name
);
1677 r
= load_os_release_pairs(i
->path
, &os_release
);
1679 log_debug_errno(r
, "Failed to read os-release in image, ignoring: %m");
1681 r
= load_extension_release_pairs(i
->path
, IMAGE_SYSEXT
, i
->name
, /* relax_extension_release_check= */ false, &sysext_release
);
1683 log_debug_errno(r
, "Failed to read sysext-release in image, ignoring: %m");
1685 r
= load_extension_release_pairs(i
->path
, IMAGE_CONFEXT
, i
->name
, /* relax_extension_release_check= */ false, &confext_release
);
1687 log_debug_errno(r
, "Failed to read confext-release in image, ignoring: %m");
1689 free_and_replace(i
->hostname
, hostname
);
1690 i
->machine_id
= machine_id
;
1691 strv_free_and_replace(i
->machine_info
, machine_info
);
1692 strv_free_and_replace(i
->os_release
, os_release
);
1693 strv_free_and_replace(i
->sysext_release
, sysext_release
);
1694 strv_free_and_replace(i
->confext_release
, confext_release
);
1700 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
1701 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
1702 DissectImageFlags flags
=
1703 DISSECT_IMAGE_GENERIC_ROOT
|
1704 DISSECT_IMAGE_REQUIRE_ROOT
|
1705 DISSECT_IMAGE_RELAX_VAR_CHECK
|
1706 DISSECT_IMAGE_READ_ONLY
|
1707 DISSECT_IMAGE_USR_NO_ROOT
|
1708 DISSECT_IMAGE_ADD_PARTITION_DEVICES
|
1709 DISSECT_IMAGE_PIN_PARTITION_DEVICES
|
1710 DISSECT_IMAGE_VALIDATE_OS
|
1711 DISSECT_IMAGE_VALIDATE_OS_EXT
|
1712 DISSECT_IMAGE_ALLOW_USERSPACE_VERITY
;
1714 r
= loop_device_make_by_path(
1717 /* sector_size= */ UINT32_MAX
,
1724 r
= dissect_loop_device(
1727 /* mount_options= */ NULL
,
1729 /* image_filter= */ NULL
,
1735 r
= dissected_image_acquire_metadata(
1737 /* userns_fd= */ -EBADF
,
1742 free_and_replace(i
->hostname
, m
->hostname
);
1743 i
->machine_id
= m
->machine_id
;
1744 strv_free_and_replace(i
->machine_info
, m
->machine_info
);
1745 strv_free_and_replace(i
->os_release
, m
->os_release
);
1746 strv_free_and_replace(i
->sysext_release
, m
->sysext_release
);
1747 strv_free_and_replace(i
->confext_release
, m
->confext_release
);
1756 i
->metadata_valid
= true;
1761 int image_name_lock(const char *name
, int operation
, LockFile
*ret
) {
1767 /* Locks an image name, regardless of the precise path used. */
1769 if (streq(name
, ".host"))
1772 if (!image_name_is_valid(name
))
1775 if (getenv_bool("SYSTEMD_NSPAWN_LOCK") == 0) {
1776 *ret
= (LockFile
) LOCK_FILE_INIT
;
1782 p
= strjoina("/run/systemd/nspawn/locks/name-", name
);
1783 return make_lock_file(p
, operation
, ret
);
1786 bool image_in_search_path(
1790 const char *image
) {
1794 assert(scope
< _RUNTIME_SCOPE_MAX
&& scope
!= RUNTIME_SCOPE_GLOBAL
);
1796 assert(class < _IMAGE_CLASS_MAX
);
1799 _cleanup_strv_free_
char **search
= NULL
;
1800 r
= pick_image_search_path(scope
, class, &search
);
1804 STRV_FOREACH(path
, search
) {
1808 if (!empty_or_root(root
)) {
1809 q
= path_startswith(*path
, root
);
1815 p
= path_startswith(q
, *path
);
1819 /* Make sure there's a filename following */
1820 k
= strcspn(p
, "/");
1826 /* Accept trailing slashes */
1827 if (p
[strspn(p
, "/")] == 0)
1834 bool image_is_vendor(const struct Image
*i
) {
1837 return i
->path
&& path_startswith(i
->path
, "/usr");
1840 bool image_is_host(const struct Image
*i
) {
1843 if (i
->name
&& streq(i
->name
, ".host"))
1846 if (i
->path
&& path_equal(i
->path
, "/"))
1852 int image_to_json(const struct Image
*img
, sd_json_variant
**ret
) {
1855 return sd_json_buildo(
1857 SD_JSON_BUILD_PAIR_STRING("Type", image_type_to_string(img
->type
)),
1858 SD_JSON_BUILD_PAIR_STRING("Class", image_class_to_string(img
->class)),
1859 SD_JSON_BUILD_PAIR_STRING("Name", img
->name
),
1860 SD_JSON_BUILD_PAIR_CONDITION(!!img
->path
, "Path", SD_JSON_BUILD_STRING(img
->path
)),
1861 SD_JSON_BUILD_PAIR_BOOLEAN("ReadOnly", img
->read_only
),
1862 SD_JSON_BUILD_PAIR_CONDITION(img
->crtime
!= 0, "CreationTimestamp", SD_JSON_BUILD_UNSIGNED(img
->crtime
)),
1863 SD_JSON_BUILD_PAIR_CONDITION(img
->mtime
!= 0, "ModificationTimestamp", SD_JSON_BUILD_UNSIGNED(img
->mtime
)),
1864 SD_JSON_BUILD_PAIR_CONDITION(img
->usage
!= UINT64_MAX
, "Usage", SD_JSON_BUILD_UNSIGNED(img
->usage
)),
1865 SD_JSON_BUILD_PAIR_CONDITION(img
->usage_exclusive
!= UINT64_MAX
, "UsageExclusive", SD_JSON_BUILD_UNSIGNED(img
->usage_exclusive
)),
1866 SD_JSON_BUILD_PAIR_CONDITION(img
->limit
!= UINT64_MAX
, "Limit", SD_JSON_BUILD_UNSIGNED(img
->limit
)),
1867 SD_JSON_BUILD_PAIR_CONDITION(img
->limit_exclusive
!= UINT64_MAX
, "LimitExclusive", SD_JSON_BUILD_UNSIGNED(img
->limit_exclusive
)));
1870 static const char* const image_type_table
[_IMAGE_TYPE_MAX
] = {
1871 [IMAGE_DIRECTORY
] = "directory",
1872 [IMAGE_SUBVOLUME
] = "subvolume",
1873 [IMAGE_RAW
] = "raw",
1874 [IMAGE_BLOCK
] = "block",
1877 DEFINE_STRING_TABLE_LOOKUP(image_type
, ImageType
);