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"
48 #include "xattr-util.h"
50 static const char* const image_search_path
[_IMAGE_CLASS_MAX
] = {
51 [IMAGE_MACHINE
] = "/etc/machines\0" /* only place symlinks here */
52 "/run/machines\0" /* and here too */
53 "/var/lib/machines\0" /* the main place for images */
54 "/var/lib/container\0" /* legacy */
55 "/usr/local/lib/machines\0"
56 "/usr/lib/machines\0",
58 [IMAGE_PORTABLE
] = "/etc/portables\0" /* only place symlinks here */
59 "/run/portables\0" /* and here too */
60 "/var/lib/portables\0" /* the main place for images */
61 "/usr/local/lib/portables\0"
62 "/usr/lib/portables\0",
64 /* Note that we don't allow storing extensions under /usr/, unlike with other image types. That's
65 * because extension images are supposed to extend /usr/, so you get into recursive races, especially
66 * with directory-based extensions, as the kernel's OverlayFS explicitly checks for this and errors
67 * out with -ELOOP if it finds that a lowerdir= is a child of another lowerdir=. */
68 [IMAGE_SYSEXT
] = "/etc/extensions\0" /* only place symlinks here */
69 "/run/extensions\0" /* and here too */
70 "/var/lib/extensions\0", /* the main place for images */
72 [IMAGE_CONFEXT
] = "/run/confexts\0" /* only place symlinks here */
73 "/var/lib/confexts\0" /* the main place for images */
74 "/usr/local/lib/confexts\0"
75 "/usr/lib/confexts\0",
78 /* Inside the initrd, use a slightly different set of search path (i.e. include .extra/sysext in extension
80 static const char* const image_search_path_initrd
[_IMAGE_CLASS_MAX
] = {
81 /* (entries that aren't listed here will get the same search path as for the non initrd-case) */
83 [IMAGE_SYSEXT
] = "/etc/extensions\0" /* only place symlinks here */
84 "/run/extensions\0" /* and here too */
85 "/var/lib/extensions\0" /* the main place for images */
86 "/.extra/sysext\0" /* put sysext picked up by systemd-stub last, since not trusted */
89 static const char* image_class_suffix_table
[_IMAGE_CLASS_MAX
] = {
90 [IMAGE_SYSEXT
] = ".sysext",
91 [IMAGE_CONFEXT
] = ".confext",
94 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(image_class_suffix
, ImageClass
);
96 static Image
*image_free(Image
*i
) {
103 strv_free(i
->machine_info
);
104 strv_free(i
->os_release
);
105 strv_free(i
->sysext_release
);
106 strv_free(i
->confext_release
);
111 DEFINE_TRIVIAL_REF_UNREF_FUNC(Image
, image
, image_free
);
112 DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(image_hash_ops
, char, string_hash_func
, string_compare_func
,
115 static char **image_settings_path(Image
*image
) {
116 _cleanup_strv_free_
char **l
= NULL
;
117 _cleanup_free_
char *fn
= NULL
;
127 fn
= strjoin(image
->name
, ".nspawn");
131 FOREACH_STRING(s
, "/etc/systemd/nspawn", "/run/systemd/nspawn") {
132 l
[i
] = path_join(s
, fn
);
139 r
= file_in_same_dir(image
->path
, fn
, l
+ i
);
143 log_debug_errno(r
, "Failed to generate .nspawn settings path from image path, ignoring: %m");
150 static int image_roothash_path(Image
*image
, char **ret
) {
151 _cleanup_free_
char *fn
= NULL
;
155 fn
= strjoin(image
->name
, ".roothash");
159 return file_in_same_dir(image
->path
, fn
, ret
);
162 static int image_new(
167 const char *filename
,
173 _cleanup_(image_unrefp
) Image
*i
= NULL
;
176 assert(t
< _IMAGE_TYPE_MAX
);
189 .read_only
= read_only
,
193 .usage_exclusive
= UINT64_MAX
,
195 .limit_exclusive
= UINT64_MAX
,
198 i
->name
= strdup(pretty
);
202 i
->path
= path_join(path
, filename
);
206 path_simplify(i
->path
);
213 static int extract_pretty(
215 const char *class_suffix
,
216 const char *format_suffix
,
219 _cleanup_free_
char *name
= NULL
;
225 r
= path_extract_filename(path
, &name
);
230 char *e
= endswith(name
, format_suffix
);
231 if (!e
) /* Format suffix is required */
238 char *e
= endswith(name
, class_suffix
);
239 if (e
) /* Class suffix is optional */
243 if (!image_name_is_valid(name
))
246 *ret
= TAKE_PTR(name
);
250 static int image_make(
255 const char *filename
,
256 const struct stat
*st
,
259 _cleanup_free_
char *pretty_buffer
= NULL
, *parent
= NULL
;
264 assert(dfd
>= 0 || dfd
== AT_FDCWD
);
265 assert(path
|| dfd
== AT_FDCWD
);
268 /* We explicitly *do* follow symlinks here, since we want to allow symlinking trees, raw files and block
269 * devices into /var/lib/machines/, and treat them normally.
271 * This function returns -ENOENT if we can't find the image after all, and -EMEDIUMTYPE if it's not a file we
275 if (fstatat(dfd
, filename
, &stbuf
, 0) < 0)
283 (void) safe_getcwd(&parent
);
285 (void) fd_get_path(dfd
, &parent
);
289 (path
&& path_startswith(path
, "/usr")) ||
290 (faccessat(dfd
, filename
, W_OK
, AT_EACCESS
) < 0 && errno
== EROFS
);
292 if (S_ISDIR(st
->st_mode
)) {
293 _cleanup_close_
int fd
= -EBADF
;
294 unsigned file_attr
= 0;
301 r
= extract_pretty(filename
, image_class_suffix_to_string(c
), NULL
, &pretty_buffer
);
305 pretty
= pretty_buffer
;
308 fd
= openat(dfd
, filename
, O_CLOEXEC
|O_NOCTTY
|O_DIRECTORY
);
312 if (btrfs_might_be_subvol(st
)) {
314 r
= fd_is_fs_type(fd
, BTRFS_SUPER_MAGIC
);
318 BtrfsSubvolInfo info
;
320 /* It's a btrfs subvolume */
322 r
= btrfs_subvol_get_info_fd(fd
, 0, &info
);
326 r
= image_new(IMAGE_SUBVOLUME
,
331 info
.read_only
|| read_only
,
338 if (btrfs_quota_scan_ongoing(fd
) == 0) {
339 BtrfsQuotaInfo quota
;
341 r
= btrfs_subvol_get_subtree_quota_fd(fd
, 0, "a
);
343 (*ret
)->usage
= quota
.referenced
;
344 (*ret
)->usage_exclusive
= quota
.exclusive
;
346 (*ret
)->limit
= quota
.referenced_max
;
347 (*ret
)->limit_exclusive
= quota
.exclusive_max
;
355 /* Get directory creation time (not available everywhere, but that's OK */
356 (void) fd_getcrtime(fd
, &crtime
);
358 /* If the IMMUTABLE bit is set, we consider the directory read-only. Since the ioctl is not
359 * supported everywhere we ignore failures. */
360 (void) read_attr_fd(fd
, &file_attr
);
362 /* It's just a normal directory. */
363 r
= image_new(IMAGE_DIRECTORY
,
368 read_only
|| (file_attr
& FS_IMMUTABLE_FL
),
370 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 */
377 } else if (S_ISREG(st
->st_mode
) && endswith(filename
, ".raw")) {
380 /* It's a RAW disk image */
385 (void) fd_getcrtime_at(dfd
, filename
, AT_SYMLINK_FOLLOW
, &crtime
);
388 r
= extract_pretty(filename
, image_class_suffix_to_string(c
), ".raw", &pretty_buffer
);
392 pretty
= pretty_buffer
;
395 r
= image_new(IMAGE_RAW
,
400 !(st
->st_mode
& 0222) || read_only
,
402 timespec_load(&st
->st_mtim
),
407 (*ret
)->usage
= (*ret
)->usage_exclusive
= st
->st_blocks
* 512;
408 (*ret
)->limit
= (*ret
)->limit_exclusive
= st
->st_size
;
412 } else if (S_ISBLK(st
->st_mode
)) {
413 _cleanup_close_
int block_fd
= -EBADF
;
414 uint64_t size
= UINT64_MAX
;
422 r
= extract_pretty(filename
, NULL
, NULL
, &pretty_buffer
);
426 pretty
= pretty_buffer
;
429 block_fd
= openat(dfd
, filename
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
431 log_debug_errno(errno
, "Failed to open block device %s/%s, ignoring: %m", path
?: strnull(parent
), filename
);
433 /* Refresh stat data after opening the node */
434 if (fstat(block_fd
, &stbuf
) < 0)
438 if (!S_ISBLK(st
->st_mode
)) /* Verify that what we opened is actually what we think it is */
444 if (ioctl(block_fd
, BLKROGET
, &state
) < 0)
445 log_debug_errno(errno
, "Failed to issue BLKROGET on device %s/%s, ignoring: %m", path
?: strnull(parent
), filename
);
450 r
= blockdev_get_device_size(block_fd
, &size
);
452 log_debug_errno(r
, "Failed to issue BLKGETSIZE64 on device %s/%s, ignoring: %m", path
?: strnull(parent
), filename
);
454 block_fd
= safe_close(block_fd
);
457 r
= image_new(IMAGE_BLOCK
,
462 !(st
->st_mode
& 0222) || read_only
,
469 if (!IN_SET(size
, 0, UINT64_MAX
))
470 (*ret
)->usage
= (*ret
)->usage_exclusive
= (*ret
)->limit
= (*ret
)->limit_exclusive
= size
;
478 static const char *pick_image_search_path(ImageClass
class) {
479 if (class < 0 || class >= _IMAGE_CLASS_MAX
)
482 /* Use the initrd search path if there is one, otherwise use the common one */
483 return in_initrd() && image_search_path_initrd
[class] ? image_search_path_initrd
[class] : image_search_path
[class];
486 int image_find(ImageClass
class,
494 assert(class < _IMAGE_CLASS_MAX
);
497 /* There are no images with invalid names */
498 if (!image_name_is_valid(name
))
501 NULSTR_FOREACH(path
, pick_image_search_path(class)) {
502 _cleanup_free_
char *resolved
= NULL
;
503 _cleanup_closedir_
DIR *d
= NULL
;
507 r
= chase_and_opendir(path
, root
, CHASE_PREFIX_ROOT
, &resolved
, &d
);
513 /* As mentioned above, we follow symlinks on this fstatat(), because we want to permit people
514 * to symlink block devices into the search path. (For now, we disable that when operating
515 * relative to some root directory.) */
516 flags
= root
? AT_SYMLINK_NOFOLLOW
: 0;
517 if (fstatat(dirfd(d
), name
, &st
, flags
) < 0) {
518 _cleanup_free_
char *raw
= NULL
;
523 raw
= strjoin(name
, ".raw");
527 if (fstatat(dirfd(d
), raw
, &st
, flags
) < 0) {
534 if (!S_ISREG(st
.st_mode
))
537 r
= image_make(class, name
, dirfd(d
), resolved
, raw
, &st
, ret
);
540 if (!S_ISDIR(st
.st_mode
) && !S_ISBLK(st
.st_mode
))
543 r
= image_make(class, name
, dirfd(d
), resolved
, name
, &st
, ret
);
545 if (IN_SET(r
, -ENOENT
, -EMEDIUMTYPE
))
551 (*ret
)->discoverable
= true;
556 if (class == IMAGE_MACHINE
&& streq(name
, ".host")) {
557 r
= image_make(class, ".host", AT_FDCWD
, NULL
, empty_to_root(root
), NULL
, ret
);
562 (*ret
)->discoverable
= true;
570 int image_from_path(const char *path
, Image
**ret
) {
572 /* Note that we don't set the 'discoverable' field of the returned object, because we don't check here whether
573 * the image is in the image search path. And if it is we don't know if the path we used is actually not
574 * overridden by another, different image earlier in the search path */
576 if (path_equal(path
, "/"))
577 return image_make(IMAGE_MACHINE
, ".host", AT_FDCWD
, NULL
, "/", NULL
, ret
);
579 return image_make(_IMAGE_CLASS_INVALID
, NULL
, AT_FDCWD
, NULL
, path
, NULL
, ret
);
582 int image_find_harder(ImageClass
class, const char *name_or_path
, const char *root
, Image
**ret
) {
583 if (image_name_is_valid(name_or_path
))
584 return image_find(class, name_or_path
, root
, ret
);
586 return image_from_path(name_or_path
, ret
);
597 assert(class < _IMAGE_CLASS_MAX
);
600 NULSTR_FOREACH(path
, pick_image_search_path(class)) {
601 _cleanup_free_
char *resolved
= NULL
;
602 _cleanup_closedir_
DIR *d
= NULL
;
604 r
= chase_and_opendir(path
, root
, CHASE_PREFIX_ROOT
, &resolved
, &d
);
610 FOREACH_DIRENT_ALL(de
, d
, return -errno
) {
611 _cleanup_(image_unrefp
) Image
*image
= NULL
;
612 _cleanup_free_
char *pretty
= NULL
;
616 if (dot_or_dot_dot(de
->d_name
))
619 /* As mentioned above, we follow symlinks on this fstatat(), because we want to
620 * permit people to symlink block devices into the search path. */
621 flags
= root
? AT_SYMLINK_NOFOLLOW
: 0;
622 if (fstatat(dirfd(d
), de
->d_name
, &st
, flags
) < 0) {
629 if (S_ISREG(st
.st_mode
))
630 r
= extract_pretty(de
->d_name
, image_class_suffix_to_string(class), ".raw", &pretty
);
631 else if (S_ISDIR(st
.st_mode
))
632 r
= extract_pretty(de
->d_name
, image_class_suffix_to_string(class), NULL
, &pretty
);
633 else if (S_ISBLK(st
.st_mode
))
634 r
= extract_pretty(de
->d_name
, NULL
, NULL
, &pretty
);
636 log_debug("Skipping directory entry '%s', which is neither regular file, directory nor block device.", de
->d_name
);
640 log_debug_errno(r
, "Skipping directory entry '%s', which doesn't look like an image.", de
->d_name
);
644 if (hashmap_contains(h
, pretty
))
647 r
= image_make(class, pretty
, dirfd(d
), resolved
, de
->d_name
, &st
, &image
);
648 if (IN_SET(r
, -ENOENT
, -EMEDIUMTYPE
))
653 image
->discoverable
= true;
655 r
= hashmap_put(h
, image
->name
, image
);
663 if (class == IMAGE_MACHINE
&& !hashmap_contains(h
, ".host")) {
664 _cleanup_(image_unrefp
) Image
*image
= NULL
;
666 r
= image_make(IMAGE_MACHINE
, ".host", AT_FDCWD
, NULL
, empty_to_root("/"), NULL
, &image
);
670 image
->discoverable
= true;
672 r
= hashmap_put(h
, image
->name
, image
);
682 int image_remove(Image
*i
) {
683 _cleanup_(release_lock_file
) LockFile global_lock
= LOCK_FILE_INIT
, local_lock
= LOCK_FILE_INIT
;
684 _cleanup_strv_free_
char **settings
= NULL
;
685 _cleanup_free_
char *roothash
= NULL
;
690 if (IMAGE_IS_VENDOR(i
) || IMAGE_IS_HOST(i
))
693 settings
= image_settings_path(i
);
697 r
= image_roothash_path(i
, &roothash
);
701 /* Make sure we don't interfere with a running nspawn */
702 r
= image_path_lock(i
->path
, LOCK_EX
|LOCK_NB
, &global_lock
, &local_lock
);
708 case IMAGE_SUBVOLUME
:
710 /* Let's unlink first, maybe it is a symlink? If that works we are happy. Otherwise, let's get out the
712 if (unlink(i
->path
) < 0) {
713 r
= btrfs_subvol_remove(i
->path
, BTRFS_REMOVE_RECURSIVE
|BTRFS_REMOVE_QUOTA
);
720 case IMAGE_DIRECTORY
:
721 /* Allow deletion of read-only directories */
722 (void) chattr_path(i
->path
, 0, FS_IMMUTABLE_FL
, NULL
);
723 r
= rm_rf(i
->path
, REMOVE_ROOT
|REMOVE_PHYSICAL
|REMOVE_SUBVOLUME
);
731 /* If this is inside of /dev, then it's a real block device, hence let's not touch the device node
732 * itself (but let's remove the stuff stored alongside it). If it's anywhere else, let's try to unlink
733 * the thing (it's most likely a symlink after all). */
735 if (path_startswith(i
->path
, "/dev"))
740 if (unlink(i
->path
) < 0)
748 STRV_FOREACH(j
, settings
)
749 if (unlink(*j
) < 0 && errno
!= ENOENT
)
750 log_debug_errno(errno
, "Failed to unlink %s, ignoring: %m", *j
);
752 if (unlink(roothash
) < 0 && errno
!= ENOENT
)
753 log_debug_errno(errno
, "Failed to unlink %s, ignoring: %m", roothash
);
758 static int rename_auxiliary_file(const char *path
, const char *new_name
, const char *suffix
) {
759 _cleanup_free_
char *fn
= NULL
, *rs
= NULL
;
762 fn
= strjoin(new_name
, suffix
);
766 r
= file_in_same_dir(path
, fn
, &rs
);
770 return rename_noreplace(AT_FDCWD
, path
, AT_FDCWD
, rs
);
773 int image_rename(Image
*i
, const char *new_name
) {
774 _cleanup_(release_lock_file
) LockFile global_lock
= LOCK_FILE_INIT
, local_lock
= LOCK_FILE_INIT
, name_lock
= LOCK_FILE_INIT
;
775 _cleanup_free_
char *new_path
= NULL
, *nn
= NULL
, *roothash
= NULL
;
776 _cleanup_strv_free_
char **settings
= NULL
;
777 unsigned file_attr
= 0;
782 if (!image_name_is_valid(new_name
))
785 if (IMAGE_IS_VENDOR(i
) || IMAGE_IS_HOST(i
))
788 settings
= image_settings_path(i
);
792 r
= image_roothash_path(i
, &roothash
);
796 /* Make sure we don't interfere with a running nspawn */
797 r
= image_path_lock(i
->path
, LOCK_EX
|LOCK_NB
, &global_lock
, &local_lock
);
801 /* Make sure nobody takes the new name, between the time we
802 * checked it is currently unused in all search paths, and the
803 * time we take possession of it */
804 r
= image_name_lock(new_name
, LOCK_EX
|LOCK_NB
, &name_lock
);
808 r
= image_find(IMAGE_MACHINE
, new_name
, NULL
, NULL
);
816 case IMAGE_DIRECTORY
:
817 /* Turn of the immutable bit while we rename the image, so that we can rename it */
818 (void) read_attr_path(i
->path
, &file_attr
);
820 if (file_attr
& FS_IMMUTABLE_FL
)
821 (void) chattr_path(i
->path
, 0, FS_IMMUTABLE_FL
, NULL
);
824 case IMAGE_SUBVOLUME
:
825 r
= file_in_same_dir(i
->path
, new_name
, &new_path
);
830 /* Refuse renaming raw block devices in /dev, the names are picked by udev after all. */
831 if (path_startswith(i
->path
, "/dev"))
834 r
= file_in_same_dir(i
->path
, new_name
, &new_path
);
840 fn
= strjoina(new_name
, ".raw");
842 r
= file_in_same_dir(i
->path
, fn
, &new_path
);
852 nn
= strdup(new_name
);
856 r
= rename_noreplace(AT_FDCWD
, i
->path
, AT_FDCWD
, new_path
);
860 /* Restore the immutable bit, if it was set before */
861 if (file_attr
& FS_IMMUTABLE_FL
)
862 (void) chattr_path(new_path
, FS_IMMUTABLE_FL
, FS_IMMUTABLE_FL
, NULL
);
864 free_and_replace(i
->path
, new_path
);
865 free_and_replace(i
->name
, nn
);
867 STRV_FOREACH(j
, settings
) {
868 r
= rename_auxiliary_file(*j
, new_name
, ".nspawn");
869 if (r
< 0 && r
!= -ENOENT
)
870 log_debug_errno(r
, "Failed to rename settings file %s, ignoring: %m", *j
);
873 r
= rename_auxiliary_file(roothash
, new_name
, ".roothash");
874 if (r
< 0 && r
!= -ENOENT
)
875 log_debug_errno(r
, "Failed to rename roothash file %s, ignoring: %m", roothash
);
880 static int clone_auxiliary_file(const char *path
, const char *new_name
, const char *suffix
) {
881 _cleanup_free_
char *fn
= NULL
, *rs
= NULL
;
884 fn
= strjoin(new_name
, suffix
);
888 r
= file_in_same_dir(path
, fn
, &rs
);
892 return copy_file_atomic(path
, rs
, 0664, COPY_REFLINK
);
895 int image_clone(Image
*i
, const char *new_name
, bool read_only
) {
896 _cleanup_(release_lock_file
) LockFile name_lock
= LOCK_FILE_INIT
;
897 _cleanup_strv_free_
char **settings
= NULL
;
898 _cleanup_free_
char *roothash
= NULL
;
899 const char *new_path
;
904 if (!image_name_is_valid(new_name
))
907 settings
= image_settings_path(i
);
911 r
= image_roothash_path(i
, &roothash
);
915 /* Make sure nobody takes the new name, between the time we
916 * checked it is currently unused in all search paths, and the
917 * time we take possession of it */
918 r
= image_name_lock(new_name
, LOCK_EX
|LOCK_NB
, &name_lock
);
922 r
= image_find(IMAGE_MACHINE
, new_name
, NULL
, NULL
);
930 case IMAGE_SUBVOLUME
:
931 case IMAGE_DIRECTORY
:
932 /* If we can we'll always try to create a new btrfs subvolume here, even if the source is a plain
935 new_path
= strjoina("/var/lib/machines/", new_name
);
937 r
= btrfs_subvol_snapshot_at(AT_FDCWD
, i
->path
, AT_FDCWD
, new_path
,
938 (read_only
? BTRFS_SNAPSHOT_READ_ONLY
: 0) |
939 BTRFS_SNAPSHOT_FALLBACK_COPY
|
940 BTRFS_SNAPSHOT_FALLBACK_DIRECTORY
|
941 BTRFS_SNAPSHOT_FALLBACK_IMMUTABLE
|
942 BTRFS_SNAPSHOT_RECURSIVE
|
943 BTRFS_SNAPSHOT_QUOTA
);
945 /* Enable "subtree" quotas for the copy, if we didn't copy any quota from the source. */
946 (void) btrfs_subvol_auto_qgroup(new_path
, 0, true);
951 new_path
= strjoina("/var/lib/machines/", new_name
, ".raw");
953 r
= copy_file_atomic_full(i
->path
, new_path
, read_only
? 0444 : 0644, FS_NOCOW_FL
, FS_NOCOW_FL
,
954 COPY_REFLINK
|COPY_CRTIME
, NULL
, NULL
);
965 STRV_FOREACH(j
, settings
) {
966 r
= clone_auxiliary_file(*j
, new_name
, ".nspawn");
967 if (r
< 0 && r
!= -ENOENT
)
968 log_debug_errno(r
, "Failed to clone settings %s, ignoring: %m", *j
);
971 r
= clone_auxiliary_file(roothash
, new_name
, ".roothash");
972 if (r
< 0 && r
!= -ENOENT
)
973 log_debug_errno(r
, "Failed to clone root hash file %s, ignoring: %m", roothash
);
978 int image_read_only(Image
*i
, bool b
) {
979 _cleanup_(release_lock_file
) LockFile global_lock
= LOCK_FILE_INIT
, local_lock
= LOCK_FILE_INIT
;
984 if (IMAGE_IS_VENDOR(i
) || IMAGE_IS_HOST(i
))
987 /* Make sure we don't interfere with a running nspawn */
988 r
= image_path_lock(i
->path
, LOCK_EX
|LOCK_NB
, &global_lock
, &local_lock
);
994 case IMAGE_SUBVOLUME
:
996 /* Note that we set the flag only on the top-level
997 * subvolume of the image. */
999 r
= btrfs_subvol_set_read_only(i
->path
, b
);
1005 case IMAGE_DIRECTORY
:
1006 /* For simple directory trees we cannot use the access
1007 mode of the top-level directory, since it has an
1008 effect on the container itself. However, we can
1009 use the "immutable" flag, to at least make the
1010 top-level directory read-only. It's not as good as
1011 a read-only subvolume, but at least something, and
1012 we can read the value back. */
1014 r
= chattr_path(i
->path
, b
? FS_IMMUTABLE_FL
: 0, FS_IMMUTABLE_FL
, NULL
);
1023 if (stat(i
->path
, &st
) < 0)
1026 if (chmod(i
->path
, (st
.st_mode
& 0444) | (b
? 0000 : 0200)) < 0)
1029 /* If the images is now read-only, it's a good time to
1030 * defrag it, given that no write patterns will
1031 * fragment it again. */
1033 (void) btrfs_defrag(i
->path
);
1038 _cleanup_close_
int fd
= -EBADF
;
1042 fd
= open(i
->path
, O_CLOEXEC
|O_RDONLY
|O_NONBLOCK
|O_NOCTTY
);
1046 if (fstat(fd
, &st
) < 0)
1048 if (!S_ISBLK(st
.st_mode
))
1051 if (ioctl(fd
, BLKROSET
, &state
) < 0)
1064 int image_path_lock(const char *path
, int operation
, LockFile
*global
, LockFile
*local
) {
1065 _cleanup_free_
char *p
= NULL
;
1066 LockFile t
= LOCK_FILE_INIT
;
1075 /* Locks an image path. This actually creates two locks: one "local" one, next to the image path
1076 * itself, which might be shared via NFS. And another "global" one, in /run, that uses the
1077 * device/inode number. This has the benefit that we can even lock a tree that is a mount point,
1080 if (!path_is_absolute(path
))
1083 switch (operation
& (LOCK_SH
|LOCK_EX
)) {
1094 if (getenv_bool("SYSTEMD_NSPAWN_LOCK") == 0) {
1095 *local
= *global
= (LockFile
) LOCK_FILE_INIT
;
1099 /* Prohibit taking exclusive locks on the host image. We can't allow this, since we ourselves are
1100 * running off it after all, and we don't want any images to manipulate the host image. We make an
1101 * exception for shared locks however: we allow those (and make them NOPs since there's no point in
1102 * taking them if there can't be exclusive locks). Strictly speaking these are questionable as well,
1103 * since it means changes made to the host might propagate to the container as they happen (and a
1104 * shared lock kinda suggests that no changes happen at all while it is in place), but it's too
1105 * useful not to allow read-only containers off the host root, hence let's support this, and trust
1106 * the user to do the right thing with this. */
1107 if (path_equal(path
, "/")) {
1111 *local
= *global
= (LockFile
) LOCK_FILE_INIT
;
1115 if (stat(path
, &st
) >= 0) {
1116 if (S_ISBLK(st
.st_mode
))
1117 r
= asprintf(&p
, "/run/systemd/nspawn/locks/block-%u:%u", major(st
.st_rdev
), minor(st
.st_rdev
));
1118 else if (S_ISDIR(st
.st_mode
) || S_ISREG(st
.st_mode
))
1119 r
= asprintf(&p
, "/run/systemd/nspawn/locks/inode-%lu:%lu", (unsigned long) st
.st_dev
, (unsigned long) st
.st_ino
);
1126 /* For block devices we don't need the "local" lock, as the major/minor lock above should be
1127 * sufficient, since block devices are host local anyway. */
1128 if (!path_startswith(path
, "/dev/")) {
1129 r
= make_lock_file_for(path
, operation
, &t
);
1131 if (!exclusive
&& r
== -EROFS
)
1132 log_debug_errno(r
, "Failed to create shared lock for '%s', ignoring: %m", path
);
1139 (void) mkdir_p("/run/systemd/nspawn/locks", 0700);
1141 r
= make_lock_file(p
, operation
, global
);
1143 release_lock_file(&t
);
1147 *global
= (LockFile
) LOCK_FILE_INIT
;
1153 int image_set_limit(Image
*i
, uint64_t referenced_max
) {
1156 if (IMAGE_IS_VENDOR(i
) || IMAGE_IS_HOST(i
))
1159 if (i
->type
!= IMAGE_SUBVOLUME
)
1162 /* We set the quota both for the subvolume as well as for the
1163 * subtree. The latter is mostly for historical reasons, since
1164 * we didn't use to have a concept of subtree quota, and hence
1165 * only modified the subvolume quota. */
1167 (void) btrfs_qgroup_set_limit(i
->path
, 0, referenced_max
);
1168 (void) btrfs_subvol_auto_qgroup(i
->path
, 0, true);
1169 return btrfs_subvol_set_subtree_quota_limit(i
->path
, 0, referenced_max
);
1172 int image_read_metadata(Image
*i
, const ImagePolicy
*image_policy
) {
1173 _cleanup_(release_lock_file
) LockFile global_lock
= LOCK_FILE_INIT
, local_lock
= LOCK_FILE_INIT
;
1178 r
= image_path_lock(i
->path
, LOCK_SH
|LOCK_NB
, &global_lock
, &local_lock
);
1184 case IMAGE_SUBVOLUME
:
1185 case IMAGE_DIRECTORY
: {
1186 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
, **sysext_release
= NULL
, **confext_release
= NULL
;
1187 _cleanup_free_
char *hostname
= NULL
, *path
= NULL
;
1188 sd_id128_t machine_id
= SD_ID128_NULL
;
1190 if (i
->class == IMAGE_SYSEXT
) {
1191 r
= extension_has_forbidden_content(i
->path
);
1195 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM
),
1196 "Conflicting content found in image %s, refusing.",
1200 r
= chase("/etc/hostname", i
->path
, CHASE_PREFIX_ROOT
|CHASE_TRAIL_SLASH
, &path
, NULL
);
1201 if (r
< 0 && r
!= -ENOENT
)
1202 log_debug_errno(r
, "Failed to chase /etc/hostname in image %s: %m", i
->name
);
1204 r
= read_etc_hostname(path
, &hostname
);
1206 log_debug_errno(errno
, "Failed to read /etc/hostname of image %s: %m", i
->name
);
1211 r
= id128_get_machine(i
->path
, &machine_id
);
1213 log_debug_errno(r
, "Failed to read machine ID in image %s, ignoring: %m", i
->name
);
1215 r
= chase("/etc/machine-info", i
->path
, CHASE_PREFIX_ROOT
|CHASE_TRAIL_SLASH
, &path
, NULL
);
1216 if (r
< 0 && r
!= -ENOENT
)
1217 log_debug_errno(r
, "Failed to chase /etc/machine-info in image %s: %m", i
->name
);
1219 r
= load_env_file_pairs(NULL
, path
, &machine_info
);
1221 log_debug_errno(r
, "Failed to parse machine-info data of %s: %m", i
->name
);
1224 r
= load_os_release_pairs(i
->path
, &os_release
);
1226 log_debug_errno(r
, "Failed to read os-release in image, ignoring: %m");
1228 r
= load_extension_release_pairs(i
->path
, IMAGE_SYSEXT
, i
->name
, /* relax_extension_release_check= */ false, &sysext_release
);
1230 log_debug_errno(r
, "Failed to read sysext-release in image, ignoring: %m");
1232 r
= load_extension_release_pairs(i
->path
, IMAGE_CONFEXT
, i
->name
, /* relax_extension_release_check= */ false, &confext_release
);
1234 log_debug_errno(r
, "Failed to read confext-release in image, ignoring: %m");
1236 free_and_replace(i
->hostname
, hostname
);
1237 i
->machine_id
= machine_id
;
1238 strv_free_and_replace(i
->machine_info
, machine_info
);
1239 strv_free_and_replace(i
->os_release
, os_release
);
1240 strv_free_and_replace(i
->sysext_release
, sysext_release
);
1241 strv_free_and_replace(i
->confext_release
, confext_release
);
1247 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
1248 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
1250 r
= loop_device_make_by_path(i
->path
, O_RDONLY
, /* sector_size= */ UINT32_MAX
, LO_FLAGS_PARTSCAN
, LOCK_SH
, &d
);
1254 r
= dissect_loop_device(
1257 /* mount_options= */ NULL
,
1259 DISSECT_IMAGE_GENERIC_ROOT
|
1260 DISSECT_IMAGE_REQUIRE_ROOT
|
1261 DISSECT_IMAGE_RELAX_VAR_CHECK
|
1262 DISSECT_IMAGE_READ_ONLY
|
1263 DISSECT_IMAGE_USR_NO_ROOT
|
1264 DISSECT_IMAGE_ADD_PARTITION_DEVICES
|
1265 DISSECT_IMAGE_PIN_PARTITION_DEVICES
,
1270 r
= dissected_image_acquire_metadata(m
,
1271 DISSECT_IMAGE_VALIDATE_OS
|
1272 DISSECT_IMAGE_VALIDATE_OS_EXT
);
1276 free_and_replace(i
->hostname
, m
->hostname
);
1277 i
->machine_id
= m
->machine_id
;
1278 strv_free_and_replace(i
->machine_info
, m
->machine_info
);
1279 strv_free_and_replace(i
->os_release
, m
->os_release
);
1280 strv_free_and_replace(i
->sysext_release
, m
->sysext_release
);
1281 strv_free_and_replace(i
->confext_release
, m
->confext_release
);
1290 i
->metadata_valid
= true;
1295 int image_name_lock(const char *name
, int operation
, LockFile
*ret
) {
1301 /* Locks an image name, regardless of the precise path used. */
1303 if (streq(name
, ".host"))
1306 if (!image_name_is_valid(name
))
1309 if (getenv_bool("SYSTEMD_NSPAWN_LOCK") == 0) {
1310 *ret
= (LockFile
) LOCK_FILE_INIT
;
1314 (void) mkdir_p("/run/systemd/nspawn/locks", 0700);
1316 p
= strjoina("/run/systemd/nspawn/locks/name-", name
);
1317 return make_lock_file(p
, operation
, ret
);
1320 bool image_in_search_path(
1323 const char *image
) {
1327 NULSTR_FOREACH(path
, pick_image_search_path(class)) {
1331 if (!empty_or_root(root
)) {
1332 q
= path_startswith(path
, root
);
1338 p
= path_startswith(q
, path
);
1342 /* Make sure there's a filename following */
1343 k
= strcspn(p
, "/");
1349 /* Accept trailing slashes */
1350 if (p
[strspn(p
, "/")] == 0)
1358 int image_to_json(const struct Image
*img
, JsonVariant
**ret
) {
1361 return json_build(ret
,
1363 JSON_BUILD_PAIR_STRING("Type", image_type_to_string(img
->type
)),
1364 JSON_BUILD_PAIR_STRING("Class", image_class_to_string(img
->class)),
1365 JSON_BUILD_PAIR_STRING("Name", img
->name
),
1366 JSON_BUILD_PAIR_CONDITION(img
->path
, "Path", JSON_BUILD_STRING(img
->path
)),
1367 JSON_BUILD_PAIR_BOOLEAN("ReadOnly", img
->read_only
),
1368 JSON_BUILD_PAIR_CONDITION(img
->crtime
!= 0, "CreationTimestamp", JSON_BUILD_UNSIGNED(img
->crtime
)),
1369 JSON_BUILD_PAIR_CONDITION(img
->mtime
!= 0, "ModificationTimestamp", JSON_BUILD_UNSIGNED(img
->mtime
)),
1370 JSON_BUILD_PAIR_CONDITION(img
->usage
!= UINT64_MAX
, "Usage", JSON_BUILD_UNSIGNED(img
->usage
)),
1371 JSON_BUILD_PAIR_CONDITION(img
->usage_exclusive
!= UINT64_MAX
, "UsageExclusive", JSON_BUILD_UNSIGNED(img
->usage_exclusive
)),
1372 JSON_BUILD_PAIR_CONDITION(img
->limit
!= UINT64_MAX
, "Limit", JSON_BUILD_UNSIGNED(img
->limit
)),
1373 JSON_BUILD_PAIR_CONDITION(img
->limit_exclusive
!= UINT64_MAX
, "LimitExclusive", JSON_BUILD_UNSIGNED(img
->limit_exclusive
))));
1376 static const char* const image_type_table
[_IMAGE_TYPE_MAX
] = {
1377 [IMAGE_DIRECTORY
] = "directory",
1378 [IMAGE_SUBVOLUME
] = "subvolume",
1379 [IMAGE_RAW
] = "raw",
1380 [IMAGE_BLOCK
] = "block",
1383 DEFINE_STRING_TABLE_LOOKUP(image_type
, ImageType
);