1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
6 #include <linux/loop.h>
7 #include <linux/magic.h>
11 #include <sys/ioctl.h>
15 #include "alloc-util.h"
16 #include "blockdev-util.h"
17 #include "btrfs-util.h"
19 #include "chattr-util.h"
21 #include "dirent-util.h"
22 #include "discover-image.h"
23 #include "dissect-image.h"
26 #include "extension-util.h"
30 #include "hostname-setup.h"
31 #include "id128-util.h"
32 #include "initrd-util.h"
33 #include "lock-util.h"
35 #include "loop-util.h"
38 #include "nulstr-util.h"
40 #include "path-util.h"
42 #include "stat-util.h"
43 #include "string-table.h"
44 #include "string-util.h"
46 #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 Image
*image_free(Image
*i
) {
118 strv_free(i
->machine_info
);
119 strv_free(i
->os_release
);
120 strv_free(i
->sysext_release
);
121 strv_free(i
->confext_release
);
126 DEFINE_TRIVIAL_REF_UNREF_FUNC(Image
, image
, image_free
);
127 DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(image_hash_ops
, char, string_hash_func
, string_compare_func
,
130 static char **image_settings_path(Image
*image
) {
131 _cleanup_strv_free_
char **l
= NULL
;
132 _cleanup_free_
char *fn
= NULL
;
142 fn
= strjoin(image
->name
, ".nspawn");
146 FOREACH_STRING(s
, "/etc/systemd/nspawn", "/run/systemd/nspawn") {
147 l
[i
] = path_join(s
, fn
);
154 r
= file_in_same_dir(image
->path
, fn
, l
+ i
);
158 log_debug_errno(r
, "Failed to generate .nspawn settings path from image path, ignoring: %m");
165 static int image_roothash_path(Image
*image
, char **ret
) {
166 _cleanup_free_
char *fn
= NULL
;
170 fn
= strjoin(image
->name
, ".roothash");
174 return file_in_same_dir(image
->path
, fn
, ret
);
177 static int image_new(
182 const char *filename
,
188 _cleanup_(image_unrefp
) Image
*i
= NULL
;
191 assert(t
< _IMAGE_TYPE_MAX
);
204 .read_only
= read_only
,
208 .usage_exclusive
= UINT64_MAX
,
210 .limit_exclusive
= UINT64_MAX
,
213 i
->name
= strdup(pretty
);
217 i
->path
= path_join(path
, filename
);
221 path_simplify(i
->path
);
228 static int extract_image_basename(
230 const char *class_suffix
, /* e.g. ".sysext" (this is an optional suffix) */
231 char **format_suffixes
, /* e.g. ".raw" (one of these will be required) */
235 _cleanup_free_
char *name
= NULL
, *suffix
= NULL
;
240 r
= path_extract_filename(path
, &name
);
244 if (format_suffixes
) {
245 char *e
= endswith_strv(name
, format_suffixes
);
246 if (!e
) /* Format suffix is required */
259 char *e
= endswith(name
, class_suffix
);
260 if (e
) { /* Class suffix is optional */
262 _cleanup_free_
char *j
= strjoin(e
, suffix
);
266 free_and_replace(suffix
, j
);
273 if (!image_name_is_valid(name
))
277 *ret_suffix
= TAKE_PTR(suffix
);
280 *ret_basename
= TAKE_PTR(name
);
285 static int image_make(
290 const char *filename
,
291 const struct stat
*st
,
294 _cleanup_free_
char *pretty_buffer
= NULL
, *parent
= NULL
;
299 assert(dfd
>= 0 || dfd
== AT_FDCWD
);
300 assert(path
|| dfd
== AT_FDCWD
);
303 /* We explicitly *do* follow symlinks here, since we want to allow symlinking trees, raw files and block
304 * devices into /var/lib/machines/, and treat them normally.
306 * This function returns -ENOENT if we can't find the image after all, and -EMEDIUMTYPE if it's not a file we
310 if (fstatat(dfd
, filename
, &stbuf
, 0) < 0)
318 (void) safe_getcwd(&parent
);
320 (void) fd_get_path(dfd
, &parent
);
324 (path
&& path_startswith(path
, "/usr")) ||
325 (faccessat(dfd
, filename
, W_OK
, AT_EACCESS
) < 0 && errno
== EROFS
);
327 if (S_ISDIR(st
->st_mode
)) {
328 _cleanup_close_
int fd
= -EBADF
;
329 unsigned file_attr
= 0;
336 r
= extract_image_basename(
338 image_class_suffix_to_string(c
),
339 /* format_suffix= */ NULL
,
341 /* ret_suffix= */ NULL
);
345 pretty
= pretty_buffer
;
348 fd
= openat(dfd
, filename
, O_CLOEXEC
|O_NOCTTY
|O_DIRECTORY
);
352 if (btrfs_might_be_subvol(st
)) {
354 r
= fd_is_fs_type(fd
, BTRFS_SUPER_MAGIC
);
358 BtrfsSubvolInfo info
;
360 /* It's a btrfs subvolume */
362 r
= btrfs_subvol_get_info_fd(fd
, 0, &info
);
366 r
= image_new(IMAGE_SUBVOLUME
,
371 info
.read_only
|| read_only
,
378 if (btrfs_quota_scan_ongoing(fd
) == 0) {
379 BtrfsQuotaInfo quota
;
381 r
= btrfs_subvol_get_subtree_quota_fd(fd
, 0, "a
);
383 (*ret
)->usage
= quota
.referenced
;
384 (*ret
)->usage_exclusive
= quota
.exclusive
;
386 (*ret
)->limit
= quota
.referenced_max
;
387 (*ret
)->limit_exclusive
= quota
.exclusive_max
;
395 /* Get directory creation time (not available everywhere, but that's OK */
396 (void) fd_getcrtime(fd
, &crtime
);
398 /* If the IMMUTABLE bit is set, we consider the directory read-only. Since the ioctl is not
399 * supported everywhere we ignore failures. */
400 (void) read_attr_fd(fd
, &file_attr
);
402 /* It's just a normal directory. */
403 r
= image_new(IMAGE_DIRECTORY
,
408 read_only
|| (file_attr
& FS_IMMUTABLE_FL
),
410 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 */
417 } else if (S_ISREG(st
->st_mode
) && endswith(filename
, ".raw")) {
420 /* It's a RAW disk image */
425 (void) fd_getcrtime_at(dfd
, filename
, AT_SYMLINK_FOLLOW
, &crtime
);
428 r
= extract_image_basename(
430 image_class_suffix_to_string(c
),
433 /* ret_suffix= */ NULL
);
437 pretty
= pretty_buffer
;
440 r
= image_new(IMAGE_RAW
,
445 !(st
->st_mode
& 0222) || read_only
,
447 timespec_load(&st
->st_mtim
),
452 (*ret
)->usage
= (*ret
)->usage_exclusive
= st
->st_blocks
* 512;
453 (*ret
)->limit
= (*ret
)->limit_exclusive
= st
->st_size
;
457 } else if (S_ISBLK(st
->st_mode
)) {
458 _cleanup_close_
int block_fd
= -EBADF
;
459 uint64_t size
= UINT64_MAX
;
467 r
= extract_image_basename(
469 /* class_suffix= */ NULL
,
470 /* format_suffix= */ NULL
,
472 /* ret_suffix= */ NULL
);
476 pretty
= pretty_buffer
;
479 block_fd
= openat(dfd
, filename
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
481 log_debug_errno(errno
, "Failed to open block device %s/%s, ignoring: %m", path
?: strnull(parent
), filename
);
483 /* Refresh stat data after opening the node */
484 if (fstat(block_fd
, &stbuf
) < 0)
488 if (!S_ISBLK(st
->st_mode
)) /* Verify that what we opened is actually what we think it is */
494 if (ioctl(block_fd
, BLKROGET
, &state
) < 0)
495 log_debug_errno(errno
, "Failed to issue BLKROGET on device %s/%s, ignoring: %m", path
?: strnull(parent
), filename
);
500 r
= blockdev_get_device_size(block_fd
, &size
);
502 log_debug_errno(r
, "Failed to issue BLKGETSIZE64 on device %s/%s, ignoring: %m", path
?: strnull(parent
), filename
);
504 block_fd
= safe_close(block_fd
);
507 r
= image_new(IMAGE_BLOCK
,
512 !(st
->st_mode
& 0222) || read_only
,
519 if (!IN_SET(size
, 0, UINT64_MAX
))
520 (*ret
)->usage
= (*ret
)->usage_exclusive
= (*ret
)->limit
= (*ret
)->limit_exclusive
= size
;
528 static const char *pick_image_search_path(ImageClass
class) {
529 if (class < 0 || class >= _IMAGE_CLASS_MAX
)
532 /* Use the initrd search path if there is one, otherwise use the common one */
533 return in_initrd() && image_search_path_initrd
[class] ? image_search_path_initrd
[class] : image_search_path
[class];
536 static char **make_possible_filenames(ImageClass
class, const char *image_name
) {
537 _cleanup_strv_free_
char **l
= NULL
;
541 FOREACH_STRING(v_suffix
, "", ".v")
542 FOREACH_STRING(format_suffix
, "", ".raw") {
543 _cleanup_free_
char *j
= NULL
;
544 const char *class_suffix
;
546 class_suffix
= image_class_suffix_to_string(class);
548 j
= strjoin(image_name
, class_suffix
, format_suffix
, v_suffix
);
552 if (strv_consume(&l
, TAKE_PTR(j
)) < 0)
556 j
= strjoin(image_name
, format_suffix
, v_suffix
);
560 if (strv_consume(&l
, TAKE_PTR(j
)) < 0)
567 int image_find(ImageClass
class,
575 assert(class < _IMAGE_CLASS_MAX
);
578 /* There are no images with invalid names */
579 if (!image_name_is_valid(name
))
582 _cleanup_strv_free_
char **names
= make_possible_filenames(class, name
);
586 NULSTR_FOREACH(path
, pick_image_search_path(class)) {
587 _cleanup_free_
char *resolved
= NULL
;
588 _cleanup_closedir_
DIR *d
= NULL
;
592 r
= chase_and_opendir(path
, root
, CHASE_PREFIX_ROOT
, &resolved
, &d
);
598 /* As mentioned above, we follow symlinks on this fstatat(), because we want to permit people
599 * to symlink block devices into the search path. (For now, we disable that when operating
600 * relative to some root directory.) */
601 flags
= root
? AT_SYMLINK_NOFOLLOW
: 0;
603 STRV_FOREACH(n
, names
) {
604 _cleanup_free_
char *fname_buf
= NULL
;
605 const char *fname
= *n
;
607 if (fstatat(dirfd(d
), fname
, &st
, flags
) < 0) {
611 continue; /* Vanished while we were looking at it */
614 if (endswith(fname
, ".raw")) {
615 if (!S_ISREG(st
.st_mode
)) {
616 log_debug("Ignoring non-regular file '%s' with .raw suffix.", fname
);
620 } else if (endswith(fname
, ".v")) {
622 if (!S_ISDIR(st
.st_mode
)) {
623 log_debug("Ignoring non-directory file '%s' with .v suffix.", fname
);
627 _cleanup_free_
char *suffix
= NULL
;
628 suffix
= strdup(ASSERT_PTR(startswith(fname
, name
)));
632 *ASSERT_PTR(endswith(suffix
, ".v")) = 0;
634 _cleanup_free_
char *vp
= path_join(resolved
, fname
);
638 PickFilter filter
= {
639 .type_mask
= endswith(suffix
, ".raw") ? (UINT32_C(1) << DT_REG
) | (UINT32_C(1) << DT_BLK
) : (UINT32_C(1) << DT_DIR
),
641 .architecture
= _ARCHITECTURE_INVALID
,
642 .suffix
= STRV_MAKE(suffix
),
645 _cleanup_(pick_result_done
) PickResult result
= PICK_RESULT_NULL
;
647 /* toplevel_fd= */ AT_FDCWD
,
650 PICK_ARCHITECTURE
|PICK_TRIES
,
653 log_debug_errno(r
, "Failed to pick versioned image on '%s', skipping: %m", vp
);
657 log_debug("Found versioned directory '%s', without matching entry, skipping: %m", vp
);
661 /* Refresh the stat data for the discovered target */
664 _cleanup_free_
char *bn
= NULL
;
665 r
= path_extract_filename(result
.path
, &bn
);
667 log_debug_errno(r
, "Failed to extract basename of image path '%s', skipping: %m", result
.path
);
671 fname_buf
= path_join(fname
, bn
);
677 } else if (!S_ISDIR(st
.st_mode
) && !S_ISBLK(st
.st_mode
)) {
678 log_debug("Ignoring non-directory and non-block device file '%s' without suffix.", fname
);
682 r
= image_make(class, name
, dirfd(d
), resolved
, fname
, &st
, ret
);
683 if (IN_SET(r
, -ENOENT
, -EMEDIUMTYPE
))
689 (*ret
)->discoverable
= true;
695 if (class == IMAGE_MACHINE
&& streq(name
, ".host")) {
696 r
= image_make(class, ".host", AT_FDCWD
, NULL
, empty_to_root(root
), NULL
, ret
);
701 (*ret
)->discoverable
= true;
709 int image_from_path(const char *path
, Image
**ret
) {
711 /* Note that we don't set the 'discoverable' field of the returned object, because we don't check here whether
712 * the image is in the image search path. And if it is we don't know if the path we used is actually not
713 * overridden by another, different image earlier in the search path */
715 if (path_equal(path
, "/"))
716 return image_make(IMAGE_MACHINE
, ".host", AT_FDCWD
, NULL
, "/", NULL
, ret
);
718 return image_make(_IMAGE_CLASS_INVALID
, NULL
, AT_FDCWD
, NULL
, path
, NULL
, ret
);
721 int image_find_harder(ImageClass
class, const char *name_or_path
, const char *root
, Image
**ret
) {
722 if (image_name_is_valid(name_or_path
))
723 return image_find(class, name_or_path
, root
, ret
);
725 return image_from_path(name_or_path
, ret
);
736 assert(class < _IMAGE_CLASS_MAX
);
739 NULSTR_FOREACH(path
, pick_image_search_path(class)) {
740 _cleanup_free_
char *resolved
= NULL
;
741 _cleanup_closedir_
DIR *d
= NULL
;
743 r
= chase_and_opendir(path
, root
, CHASE_PREFIX_ROOT
, &resolved
, &d
);
749 FOREACH_DIRENT_ALL(de
, d
, return -errno
) {
750 _cleanup_free_
char *pretty
= NULL
, *fname_buf
= NULL
;
751 _cleanup_(image_unrefp
) Image
*image
= NULL
;
752 const char *fname
= de
->d_name
;
756 if (dot_or_dot_dot(fname
))
759 /* As mentioned above, we follow symlinks on this fstatat(), because we want to
760 * permit people to symlink block devices into the search path. */
761 flags
= root
? AT_SYMLINK_NOFOLLOW
: 0;
762 if (fstatat(dirfd(d
), fname
, &st
, flags
) < 0) {
769 if (S_ISREG(st
.st_mode
)) {
770 r
= extract_image_basename(
772 image_class_suffix_to_string(class),
777 log_debug_errno(r
, "Skipping directory entry '%s', which doesn't look like an image.", fname
);
780 } else if (S_ISDIR(st
.st_mode
)) {
783 v
= endswith(fname
, ".v");
785 _cleanup_free_
char *suffix
= NULL
, *nov
= NULL
;
787 nov
= strndup(fname
, v
- fname
); /* Chop off the .v */
791 r
= extract_image_basename(
793 image_class_suffix_to_string(class),
794 STRV_MAKE(".raw", ""),
798 log_debug_errno(r
, "Skipping directory entry '%s', which doesn't look like a versioned image.", fname
);
802 _cleanup_free_
char *vp
= path_join(resolved
, fname
);
806 PickFilter filter
= {
807 .type_mask
= endswith(suffix
, ".raw") ? (UINT32_C(1) << DT_REG
) | (UINT32_C(1) << DT_BLK
) : (UINT32_C(1) << DT_DIR
),
809 .architecture
= _ARCHITECTURE_INVALID
,
810 .suffix
= STRV_MAKE(suffix
),
813 _cleanup_(pick_result_done
) PickResult result
= PICK_RESULT_NULL
;
815 /* toplevel_fd= */ AT_FDCWD
,
818 PICK_ARCHITECTURE
|PICK_TRIES
,
821 log_debug_errno(r
, "Failed to pick versioned image on '%s', skipping: %m", vp
);
825 log_debug("Found versioned directory '%s', without matching entry, skipping: %m", vp
);
829 /* Refresh the stat data for the discovered target */
832 _cleanup_free_
char *bn
= NULL
;
833 r
= path_extract_filename(result
.path
, &bn
);
835 log_debug_errno(r
, "Failed to extract basename of image path '%s', skipping: %m", result
.path
);
839 fname_buf
= path_join(fname
, bn
);
845 r
= extract_image_basename(
847 image_class_suffix_to_string(class),
848 /* format_suffix= */ NULL
,
850 /* ret_suffix= */ NULL
);
852 log_debug_errno(r
, "Skipping directory entry '%s', which doesn't look like an image.", fname
);
857 } else if (S_ISBLK(st
.st_mode
)) {
858 r
= extract_image_basename(
860 /* class_suffix= */ NULL
,
861 /* format_suffix= */ NULL
,
863 /* ret_v_suffix= */ NULL
);
865 log_debug_errno(r
, "Skipping directory entry '%s', which doesn't look like an image.", fname
);
869 log_debug("Skipping directory entry '%s', which is neither regular file, directory nor block device.", fname
);
873 if (hashmap_contains(h
, pretty
))
876 r
= image_make(class, pretty
, dirfd(d
), resolved
, fname
, &st
, &image
);
877 if (IN_SET(r
, -ENOENT
, -EMEDIUMTYPE
))
882 image
->discoverable
= true;
884 r
= hashmap_put(h
, image
->name
, image
);
892 if (class == IMAGE_MACHINE
&& !hashmap_contains(h
, ".host")) {
893 _cleanup_(image_unrefp
) Image
*image
= NULL
;
895 r
= image_make(IMAGE_MACHINE
, ".host", AT_FDCWD
, NULL
, empty_to_root("/"), NULL
, &image
);
899 image
->discoverable
= true;
901 r
= hashmap_put(h
, image
->name
, image
);
911 int image_remove(Image
*i
) {
912 _cleanup_(release_lock_file
) LockFile global_lock
= LOCK_FILE_INIT
, local_lock
= LOCK_FILE_INIT
;
913 _cleanup_strv_free_
char **settings
= NULL
;
914 _cleanup_free_
char *roothash
= NULL
;
919 if (IMAGE_IS_VENDOR(i
) || IMAGE_IS_HOST(i
))
922 settings
= image_settings_path(i
);
926 r
= image_roothash_path(i
, &roothash
);
930 /* Make sure we don't interfere with a running nspawn */
931 r
= image_path_lock(i
->path
, LOCK_EX
|LOCK_NB
, &global_lock
, &local_lock
);
937 case IMAGE_SUBVOLUME
:
939 /* Let's unlink first, maybe it is a symlink? If that works we are happy. Otherwise, let's get out the
941 if (unlink(i
->path
) < 0) {
942 r
= btrfs_subvol_remove(i
->path
, BTRFS_REMOVE_RECURSIVE
|BTRFS_REMOVE_QUOTA
);
949 case IMAGE_DIRECTORY
:
950 /* Allow deletion of read-only directories */
951 (void) chattr_path(i
->path
, 0, FS_IMMUTABLE_FL
, NULL
);
952 r
= rm_rf(i
->path
, REMOVE_ROOT
|REMOVE_PHYSICAL
|REMOVE_SUBVOLUME
);
960 /* If this is inside of /dev, then it's a real block device, hence let's not touch the device node
961 * itself (but let's remove the stuff stored alongside it). If it's anywhere else, let's try to unlink
962 * the thing (it's most likely a symlink after all). */
964 if (path_startswith(i
->path
, "/dev"))
969 if (unlink(i
->path
) < 0)
977 STRV_FOREACH(j
, settings
)
978 if (unlink(*j
) < 0 && errno
!= ENOENT
)
979 log_debug_errno(errno
, "Failed to unlink %s, ignoring: %m", *j
);
981 if (unlink(roothash
) < 0 && errno
!= ENOENT
)
982 log_debug_errno(errno
, "Failed to unlink %s, ignoring: %m", roothash
);
987 static int rename_auxiliary_file(const char *path
, const char *new_name
, const char *suffix
) {
988 _cleanup_free_
char *fn
= NULL
, *rs
= NULL
;
991 fn
= strjoin(new_name
, suffix
);
995 r
= file_in_same_dir(path
, fn
, &rs
);
999 return rename_noreplace(AT_FDCWD
, path
, AT_FDCWD
, rs
);
1002 int image_rename(Image
*i
, const char *new_name
) {
1003 _cleanup_(release_lock_file
) LockFile global_lock
= LOCK_FILE_INIT
, local_lock
= LOCK_FILE_INIT
, name_lock
= LOCK_FILE_INIT
;
1004 _cleanup_free_
char *new_path
= NULL
, *nn
= NULL
, *roothash
= NULL
;
1005 _cleanup_strv_free_
char **settings
= NULL
;
1006 unsigned file_attr
= 0;
1011 if (!image_name_is_valid(new_name
))
1014 if (IMAGE_IS_VENDOR(i
) || IMAGE_IS_HOST(i
))
1017 settings
= image_settings_path(i
);
1021 r
= image_roothash_path(i
, &roothash
);
1025 /* Make sure we don't interfere with a running nspawn */
1026 r
= image_path_lock(i
->path
, LOCK_EX
|LOCK_NB
, &global_lock
, &local_lock
);
1030 /* Make sure nobody takes the new name, between the time we
1031 * checked it is currently unused in all search paths, and the
1032 * time we take possession of it */
1033 r
= image_name_lock(new_name
, LOCK_EX
|LOCK_NB
, &name_lock
);
1037 r
= image_find(IMAGE_MACHINE
, new_name
, NULL
, NULL
);
1045 case IMAGE_DIRECTORY
:
1046 /* Turn of the immutable bit while we rename the image, so that we can rename it */
1047 (void) read_attr_path(i
->path
, &file_attr
);
1049 if (file_attr
& FS_IMMUTABLE_FL
)
1050 (void) chattr_path(i
->path
, 0, FS_IMMUTABLE_FL
, NULL
);
1053 case IMAGE_SUBVOLUME
:
1054 r
= file_in_same_dir(i
->path
, new_name
, &new_path
);
1059 /* Refuse renaming raw block devices in /dev, the names are picked by udev after all. */
1060 if (path_startswith(i
->path
, "/dev"))
1063 r
= file_in_same_dir(i
->path
, new_name
, &new_path
);
1069 fn
= strjoina(new_name
, ".raw");
1071 r
= file_in_same_dir(i
->path
, fn
, &new_path
);
1081 nn
= strdup(new_name
);
1085 r
= rename_noreplace(AT_FDCWD
, i
->path
, AT_FDCWD
, new_path
);
1089 /* Restore the immutable bit, if it was set before */
1090 if (file_attr
& FS_IMMUTABLE_FL
)
1091 (void) chattr_path(new_path
, FS_IMMUTABLE_FL
, FS_IMMUTABLE_FL
, NULL
);
1093 free_and_replace(i
->path
, new_path
);
1094 free_and_replace(i
->name
, nn
);
1096 STRV_FOREACH(j
, settings
) {
1097 r
= rename_auxiliary_file(*j
, new_name
, ".nspawn");
1098 if (r
< 0 && r
!= -ENOENT
)
1099 log_debug_errno(r
, "Failed to rename settings file %s, ignoring: %m", *j
);
1102 r
= rename_auxiliary_file(roothash
, new_name
, ".roothash");
1103 if (r
< 0 && r
!= -ENOENT
)
1104 log_debug_errno(r
, "Failed to rename roothash file %s, ignoring: %m", roothash
);
1109 static int clone_auxiliary_file(const char *path
, const char *new_name
, const char *suffix
) {
1110 _cleanup_free_
char *fn
= NULL
, *rs
= NULL
;
1113 fn
= strjoin(new_name
, suffix
);
1117 r
= file_in_same_dir(path
, fn
, &rs
);
1121 return copy_file_atomic(path
, rs
, 0664, COPY_REFLINK
);
1124 int image_clone(Image
*i
, const char *new_name
, bool read_only
) {
1125 _cleanup_(release_lock_file
) LockFile name_lock
= LOCK_FILE_INIT
;
1126 _cleanup_strv_free_
char **settings
= NULL
;
1127 _cleanup_free_
char *roothash
= NULL
;
1128 const char *new_path
;
1133 if (!image_name_is_valid(new_name
))
1136 settings
= image_settings_path(i
);
1140 r
= image_roothash_path(i
, &roothash
);
1144 /* Make sure nobody takes the new name, between the time we
1145 * checked it is currently unused in all search paths, and the
1146 * time we take possession of it */
1147 r
= image_name_lock(new_name
, LOCK_EX
|LOCK_NB
, &name_lock
);
1151 r
= image_find(IMAGE_MACHINE
, new_name
, NULL
, NULL
);
1159 case IMAGE_SUBVOLUME
:
1160 case IMAGE_DIRECTORY
:
1161 /* If we can we'll always try to create a new btrfs subvolume here, even if the source is a plain
1164 new_path
= strjoina("/var/lib/machines/", new_name
);
1166 r
= btrfs_subvol_snapshot_at(AT_FDCWD
, i
->path
, AT_FDCWD
, new_path
,
1167 (read_only
? BTRFS_SNAPSHOT_READ_ONLY
: 0) |
1168 BTRFS_SNAPSHOT_FALLBACK_COPY
|
1169 BTRFS_SNAPSHOT_FALLBACK_DIRECTORY
|
1170 BTRFS_SNAPSHOT_FALLBACK_IMMUTABLE
|
1171 BTRFS_SNAPSHOT_RECURSIVE
|
1172 BTRFS_SNAPSHOT_QUOTA
);
1174 /* Enable "subtree" quotas for the copy, if we didn't copy any quota from the source. */
1175 (void) btrfs_subvol_auto_qgroup(new_path
, 0, true);
1180 new_path
= strjoina("/var/lib/machines/", new_name
, ".raw");
1182 r
= copy_file_atomic_full(i
->path
, new_path
, read_only
? 0444 : 0644, FS_NOCOW_FL
, FS_NOCOW_FL
,
1183 COPY_REFLINK
|COPY_CRTIME
, NULL
, NULL
);
1194 STRV_FOREACH(j
, settings
) {
1195 r
= clone_auxiliary_file(*j
, new_name
, ".nspawn");
1196 if (r
< 0 && r
!= -ENOENT
)
1197 log_debug_errno(r
, "Failed to clone settings %s, ignoring: %m", *j
);
1200 r
= clone_auxiliary_file(roothash
, new_name
, ".roothash");
1201 if (r
< 0 && r
!= -ENOENT
)
1202 log_debug_errno(r
, "Failed to clone root hash file %s, ignoring: %m", roothash
);
1207 int image_read_only(Image
*i
, bool b
) {
1208 _cleanup_(release_lock_file
) LockFile global_lock
= LOCK_FILE_INIT
, local_lock
= LOCK_FILE_INIT
;
1213 if (IMAGE_IS_VENDOR(i
) || IMAGE_IS_HOST(i
))
1216 /* Make sure we don't interfere with a running nspawn */
1217 r
= image_path_lock(i
->path
, LOCK_EX
|LOCK_NB
, &global_lock
, &local_lock
);
1223 case IMAGE_SUBVOLUME
:
1225 /* Note that we set the flag only on the top-level
1226 * subvolume of the image. */
1228 r
= btrfs_subvol_set_read_only(i
->path
, b
);
1234 case IMAGE_DIRECTORY
:
1235 /* For simple directory trees we cannot use the access
1236 mode of the top-level directory, since it has an
1237 effect on the container itself. However, we can
1238 use the "immutable" flag, to at least make the
1239 top-level directory read-only. It's not as good as
1240 a read-only subvolume, but at least something, and
1241 we can read the value back. */
1243 r
= chattr_path(i
->path
, b
? FS_IMMUTABLE_FL
: 0, FS_IMMUTABLE_FL
, NULL
);
1252 if (stat(i
->path
, &st
) < 0)
1255 if (chmod(i
->path
, (st
.st_mode
& 0444) | (b
? 0000 : 0200)) < 0)
1258 /* If the images is now read-only, it's a good time to
1259 * defrag it, given that no write patterns will
1260 * fragment it again. */
1262 (void) btrfs_defrag(i
->path
);
1267 _cleanup_close_
int fd
= -EBADF
;
1271 fd
= open(i
->path
, O_CLOEXEC
|O_RDONLY
|O_NONBLOCK
|O_NOCTTY
);
1275 if (fstat(fd
, &st
) < 0)
1277 if (!S_ISBLK(st
.st_mode
))
1280 if (ioctl(fd
, BLKROSET
, &state
) < 0)
1293 static void make_lock_dir(void) {
1294 (void) mkdir_p("/run/systemd/nspawn", 0755);
1295 (void) mkdir("/run/systemd/nspawn/locks", 0700);
1298 int image_path_lock(
1301 LockFile
*ret_global
,
1302 LockFile
*ret_local
) {
1304 _cleanup_free_
char *p
= NULL
;
1305 LockFile t
= LOCK_FILE_INIT
;
1313 /* Locks an image path. This actually creates two locks: one "local" one, next to the image path
1314 * itself, which might be shared via NFS. And another "global" one, in /run, that uses the
1315 * device/inode number. This has the benefit that we can even lock a tree that is a mount point,
1318 if (!path_is_absolute(path
))
1321 switch (operation
& (LOCK_SH
|LOCK_EX
)) {
1332 if (getenv_bool("SYSTEMD_NSPAWN_LOCK") == 0) {
1333 *ret_local
= LOCK_FILE_INIT
;
1335 *ret_global
= LOCK_FILE_INIT
;
1339 /* Prohibit taking exclusive locks on the host image. We can't allow this, since we ourselves are
1340 * running off it after all, and we don't want any images to manipulate the host image. We make an
1341 * exception for shared locks however: we allow those (and make them NOPs since there's no point in
1342 * taking them if there can't be exclusive locks). Strictly speaking these are questionable as well,
1343 * since it means changes made to the host might propagate to the container as they happen (and a
1344 * shared lock kinda suggests that no changes happen at all while it is in place), but it's too
1345 * useful not to allow read-only containers off the host root, hence let's support this, and trust
1346 * the user to do the right thing with this. */
1347 if (path_equal(path
, "/")) {
1351 *ret_local
= LOCK_FILE_INIT
;
1353 *ret_global
= LOCK_FILE_INIT
;
1358 if (stat(path
, &st
) >= 0) {
1359 if (S_ISBLK(st
.st_mode
))
1360 r
= asprintf(&p
, "/run/systemd/nspawn/locks/block-%u:%u", major(st
.st_rdev
), minor(st
.st_rdev
));
1361 else if (S_ISDIR(st
.st_mode
) || S_ISREG(st
.st_mode
))
1362 r
= asprintf(&p
, "/run/systemd/nspawn/locks/inode-%lu:%lu", (unsigned long) st
.st_dev
, (unsigned long) st
.st_ino
);
1370 /* For block devices we don't need the "local" lock, as the major/minor lock above should be
1371 * sufficient, since block devices are host local anyway. */
1372 if (!path_startswith(path
, "/dev/")) {
1373 r
= make_lock_file_for(path
, operation
, &t
);
1375 if (!exclusive
&& r
== -EROFS
)
1376 log_debug_errno(r
, "Failed to create shared lock for '%s', ignoring: %m", path
);
1385 r
= make_lock_file(p
, operation
, ret_global
);
1387 release_lock_file(&t
);
1390 } else if (ret_global
)
1391 *ret_global
= LOCK_FILE_INIT
;
1397 int image_set_limit(Image
*i
, uint64_t referenced_max
) {
1400 if (IMAGE_IS_VENDOR(i
) || IMAGE_IS_HOST(i
))
1403 if (i
->type
!= IMAGE_SUBVOLUME
)
1406 /* We set the quota both for the subvolume as well as for the
1407 * subtree. The latter is mostly for historical reasons, since
1408 * we didn't use to have a concept of subtree quota, and hence
1409 * only modified the subvolume quota. */
1411 (void) btrfs_qgroup_set_limit(i
->path
, 0, referenced_max
);
1412 (void) btrfs_subvol_auto_qgroup(i
->path
, 0, true);
1413 return btrfs_subvol_set_subtree_quota_limit(i
->path
, 0, referenced_max
);
1416 int image_read_metadata(Image
*i
, const ImagePolicy
*image_policy
) {
1417 _cleanup_(release_lock_file
) LockFile global_lock
= LOCK_FILE_INIT
, local_lock
= LOCK_FILE_INIT
;
1422 r
= image_path_lock(i
->path
, LOCK_SH
|LOCK_NB
, &global_lock
, &local_lock
);
1428 case IMAGE_SUBVOLUME
:
1429 case IMAGE_DIRECTORY
: {
1430 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
, **sysext_release
= NULL
, **confext_release
= NULL
;
1431 _cleanup_free_
char *hostname
= NULL
, *path
= NULL
;
1432 sd_id128_t machine_id
= SD_ID128_NULL
;
1434 if (i
->class == IMAGE_SYSEXT
) {
1435 r
= extension_has_forbidden_content(i
->path
);
1439 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM
),
1440 "Conflicting content found in image %s, refusing.",
1444 r
= chase("/etc/hostname", i
->path
, CHASE_PREFIX_ROOT
|CHASE_TRAIL_SLASH
, &path
, NULL
);
1445 if (r
< 0 && r
!= -ENOENT
)
1446 log_debug_errno(r
, "Failed to chase /etc/hostname in image %s: %m", i
->name
);
1448 r
= read_etc_hostname(path
, &hostname
);
1450 log_debug_errno(errno
, "Failed to read /etc/hostname of image %s: %m", i
->name
);
1455 r
= id128_get_machine(i
->path
, &machine_id
);
1457 log_debug_errno(r
, "Failed to read machine ID in image %s, ignoring: %m", i
->name
);
1459 r
= chase("/etc/machine-info", i
->path
, CHASE_PREFIX_ROOT
|CHASE_TRAIL_SLASH
, &path
, NULL
);
1460 if (r
< 0 && r
!= -ENOENT
)
1461 log_debug_errno(r
, "Failed to chase /etc/machine-info in image %s: %m", i
->name
);
1463 r
= load_env_file_pairs(NULL
, path
, &machine_info
);
1465 log_debug_errno(r
, "Failed to parse machine-info data of %s: %m", i
->name
);
1468 r
= load_os_release_pairs(i
->path
, &os_release
);
1470 log_debug_errno(r
, "Failed to read os-release in image, ignoring: %m");
1472 r
= load_extension_release_pairs(i
->path
, IMAGE_SYSEXT
, i
->name
, /* relax_extension_release_check= */ false, &sysext_release
);
1474 log_debug_errno(r
, "Failed to read sysext-release in image, ignoring: %m");
1476 r
= load_extension_release_pairs(i
->path
, IMAGE_CONFEXT
, i
->name
, /* relax_extension_release_check= */ false, &confext_release
);
1478 log_debug_errno(r
, "Failed to read confext-release in image, ignoring: %m");
1480 free_and_replace(i
->hostname
, hostname
);
1481 i
->machine_id
= machine_id
;
1482 strv_free_and_replace(i
->machine_info
, machine_info
);
1483 strv_free_and_replace(i
->os_release
, os_release
);
1484 strv_free_and_replace(i
->sysext_release
, sysext_release
);
1485 strv_free_and_replace(i
->confext_release
, confext_release
);
1491 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
1492 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
1493 DissectImageFlags flags
=
1494 DISSECT_IMAGE_GENERIC_ROOT
|
1495 DISSECT_IMAGE_REQUIRE_ROOT
|
1496 DISSECT_IMAGE_RELAX_VAR_CHECK
|
1497 DISSECT_IMAGE_READ_ONLY
|
1498 DISSECT_IMAGE_USR_NO_ROOT
|
1499 DISSECT_IMAGE_ADD_PARTITION_DEVICES
|
1500 DISSECT_IMAGE_PIN_PARTITION_DEVICES
|
1501 DISSECT_IMAGE_VALIDATE_OS
|
1502 DISSECT_IMAGE_VALIDATE_OS_EXT
|
1503 DISSECT_IMAGE_ALLOW_USERSPACE_VERITY
;
1505 r
= loop_device_make_by_path(
1508 /* sector_size= */ UINT32_MAX
,
1515 r
= dissect_loop_device(
1518 /* mount_options= */ NULL
,
1525 r
= dissected_image_acquire_metadata(
1527 /* userns_fd= */ -EBADF
,
1532 free_and_replace(i
->hostname
, m
->hostname
);
1533 i
->machine_id
= m
->machine_id
;
1534 strv_free_and_replace(i
->machine_info
, m
->machine_info
);
1535 strv_free_and_replace(i
->os_release
, m
->os_release
);
1536 strv_free_and_replace(i
->sysext_release
, m
->sysext_release
);
1537 strv_free_and_replace(i
->confext_release
, m
->confext_release
);
1546 i
->metadata_valid
= true;
1551 int image_name_lock(const char *name
, int operation
, LockFile
*ret
) {
1557 /* Locks an image name, regardless of the precise path used. */
1559 if (streq(name
, ".host"))
1562 if (!image_name_is_valid(name
))
1565 if (getenv_bool("SYSTEMD_NSPAWN_LOCK") == 0) {
1566 *ret
= (LockFile
) LOCK_FILE_INIT
;
1572 p
= strjoina("/run/systemd/nspawn/locks/name-", name
);
1573 return make_lock_file(p
, operation
, ret
);
1576 bool image_in_search_path(
1579 const char *image
) {
1583 NULSTR_FOREACH(path
, pick_image_search_path(class)) {
1587 if (!empty_or_root(root
)) {
1588 q
= path_startswith(path
, root
);
1594 p
= path_startswith(q
, path
);
1598 /* Make sure there's a filename following */
1599 k
= strcspn(p
, "/");
1605 /* Accept trailing slashes */
1606 if (p
[strspn(p
, "/")] == 0)
1613 int image_to_json(const struct Image
*img
, JsonVariant
**ret
) {
1616 return json_build(ret
,
1618 JSON_BUILD_PAIR_STRING("Type", image_type_to_string(img
->type
)),
1619 JSON_BUILD_PAIR_STRING("Class", image_class_to_string(img
->class)),
1620 JSON_BUILD_PAIR_STRING("Name", img
->name
),
1621 JSON_BUILD_PAIR_CONDITION(img
->path
, "Path", JSON_BUILD_STRING(img
->path
)),
1622 JSON_BUILD_PAIR_BOOLEAN("ReadOnly", img
->read_only
),
1623 JSON_BUILD_PAIR_CONDITION(img
->crtime
!= 0, "CreationTimestamp", JSON_BUILD_UNSIGNED(img
->crtime
)),
1624 JSON_BUILD_PAIR_CONDITION(img
->mtime
!= 0, "ModificationTimestamp", JSON_BUILD_UNSIGNED(img
->mtime
)),
1625 JSON_BUILD_PAIR_CONDITION(img
->usage
!= UINT64_MAX
, "Usage", JSON_BUILD_UNSIGNED(img
->usage
)),
1626 JSON_BUILD_PAIR_CONDITION(img
->usage_exclusive
!= UINT64_MAX
, "UsageExclusive", JSON_BUILD_UNSIGNED(img
->usage_exclusive
)),
1627 JSON_BUILD_PAIR_CONDITION(img
->limit
!= UINT64_MAX
, "Limit", JSON_BUILD_UNSIGNED(img
->limit
)),
1628 JSON_BUILD_PAIR_CONDITION(img
->limit_exclusive
!= UINT64_MAX
, "LimitExclusive", JSON_BUILD_UNSIGNED(img
->limit_exclusive
))));
1631 static const char* const image_type_table
[_IMAGE_TYPE_MAX
] = {
1632 [IMAGE_DIRECTORY
] = "directory",
1633 [IMAGE_SUBVOLUME
] = "subvolume",
1634 [IMAGE_RAW
] = "raw",
1635 [IMAGE_BLOCK
] = "block",
1638 DEFINE_STRING_TABLE_LOOKUP(image_type
, ImageType
);