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 "btrfs-util.h"
18 #include "chattr-util.h"
20 #include "dirent-util.h"
21 #include "discover-image.h"
22 #include "dissect-image.h"
25 #include "extension-util.h"
29 #include "hostname-setup.h"
30 #include "id128-util.h"
31 #include "initrd-util.h"
32 #include "lock-util.h"
34 #include "loop-util.h"
37 #include "nulstr-util.h"
39 #include "path-util.h"
41 #include "stat-util.h"
42 #include "string-table.h"
43 #include "string-util.h"
45 #include "time-util.h"
47 #include "xattr-util.h"
49 static const char* const image_search_path
[_IMAGE_CLASS_MAX
] = {
50 [IMAGE_MACHINE
] = "/etc/machines\0" /* only place symlinks here */
51 "/run/machines\0" /* and here too */
52 "/var/lib/machines\0" /* the main place for images */
53 "/var/lib/container\0" /* legacy */
54 "/usr/local/lib/machines\0"
55 "/usr/lib/machines\0",
57 [IMAGE_PORTABLE
] = "/etc/portables\0" /* only place symlinks here */
58 "/run/portables\0" /* and here too */
59 "/var/lib/portables\0" /* the main place for images */
60 "/usr/local/lib/portables\0"
61 "/usr/lib/portables\0",
63 /* Note that we don't allow storing extensions under /usr/, unlike with other image types. That's
64 * because extension images are supposed to extend /usr/, so you get into recursive races, especially
65 * with directory-based extensions, as the kernel's OverlayFS explicitly checks for this and errors
66 * out with -ELOOP if it finds that a lowerdir= is a child of another lowerdir=. */
67 [IMAGE_SYSEXT
] = "/etc/extensions\0" /* only place symlinks here */
68 "/run/extensions\0" /* and here too */
69 "/var/lib/extensions\0", /* the main place for images */
71 [IMAGE_CONFEXT
] = "/run/confexts\0" /* only place symlinks here */
72 "/var/lib/confexts\0" /* the main place for images */
73 "/usr/local/lib/confexts\0"
74 "/usr/lib/confexts\0",
77 /* Inside the initrd, use a slightly different set of search path (i.e. include .extra/sysext in extension
79 static const char* const image_search_path_initrd
[_IMAGE_CLASS_MAX
] = {
80 /* (entries that aren't listed here will get the same search path as for the non initrd-case) */
82 [IMAGE_SYSEXT
] = "/etc/extensions\0" /* only place symlinks here */
83 "/run/extensions\0" /* and here too */
84 "/var/lib/extensions\0" /* the main place for images */
85 "/usr/local/lib/extensions\0"
86 "/usr/lib/extensions\0"
87 "/.extra/sysext\0" /* put sysext picked up by systemd-stub last, since not trusted */
90 static Image
*image_free(Image
*i
) {
97 strv_free(i
->machine_info
);
98 strv_free(i
->os_release
);
99 strv_free(i
->extension_release
);
104 DEFINE_TRIVIAL_REF_UNREF_FUNC(Image
, image
, image_free
);
105 DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(image_hash_ops
, char, string_hash_func
, string_compare_func
,
108 static char **image_settings_path(Image
*image
) {
109 _cleanup_strv_free_
char **l
= NULL
;
110 _cleanup_free_
char *fn
= NULL
;
120 fn
= strjoin(image
->name
, ".nspawn");
124 FOREACH_STRING(s
, "/etc/systemd/nspawn", "/run/systemd/nspawn") {
125 l
[i
] = path_join(s
, fn
);
132 r
= file_in_same_dir(image
->path
, fn
, l
+ i
);
136 log_debug_errno(r
, "Failed to generate .nspawn settings path from image path, ignoring: %m");
143 static int image_roothash_path(Image
*image
, char **ret
) {
144 _cleanup_free_
char *fn
= NULL
;
148 fn
= strjoin(image
->name
, ".roothash");
152 return file_in_same_dir(image
->path
, fn
, ret
);
155 static int image_new(
160 const char *filename
,
166 _cleanup_(image_unrefp
) Image
*i
= NULL
;
169 assert(t
< _IMAGE_TYPE_MAX
);
182 .read_only
= read_only
,
186 .usage_exclusive
= UINT64_MAX
,
188 .limit_exclusive
= UINT64_MAX
,
191 i
->name
= strdup(pretty
);
195 i
->path
= path_join(path
, filename
);
199 path_simplify(i
->path
);
206 static int extract_pretty(const char *path
, const char *suffix
, char **ret
) {
207 _cleanup_free_
char *name
= NULL
;
213 p
= last_path_component(path
);
215 name
= strdupcspn(p
, "/");
222 e
= endswith(name
, suffix
);
229 if (!image_name_is_valid(name
))
232 *ret
= TAKE_PTR(name
);
236 static int image_make(
241 const char *filename
,
242 const struct stat
*st
,
245 _cleanup_free_
char *pretty_buffer
= NULL
, *parent
= NULL
;
250 assert(dfd
>= 0 || dfd
== AT_FDCWD
);
251 assert(path
|| dfd
== AT_FDCWD
);
254 /* We explicitly *do* follow symlinks here, since we want to allow symlinking trees, raw files and block
255 * devices into /var/lib/machines/, and treat them normally.
257 * This function returns -ENOENT if we can't find the image after all, and -EMEDIUMTYPE if it's not a file we
261 if (fstatat(dfd
, filename
, &stbuf
, 0) < 0)
269 (void) safe_getcwd(&parent
);
271 (void) fd_get_path(dfd
, &parent
);
275 (path
&& path_startswith(path
, "/usr")) ||
276 (faccessat(dfd
, filename
, W_OK
, AT_EACCESS
) < 0 && errno
== EROFS
);
278 if (S_ISDIR(st
->st_mode
)) {
279 _cleanup_close_
int fd
= -EBADF
;
280 unsigned file_attr
= 0;
287 r
= extract_pretty(filename
, NULL
, &pretty_buffer
);
291 pretty
= pretty_buffer
;
294 fd
= openat(dfd
, filename
, O_CLOEXEC
|O_NOCTTY
|O_DIRECTORY
);
298 if (btrfs_might_be_subvol(st
)) {
300 r
= fd_is_fs_type(fd
, BTRFS_SUPER_MAGIC
);
304 BtrfsSubvolInfo info
;
306 /* It's a btrfs subvolume */
308 r
= btrfs_subvol_get_info_fd(fd
, 0, &info
);
312 r
= image_new(IMAGE_SUBVOLUME
,
317 info
.read_only
|| read_only
,
324 if (btrfs_quota_scan_ongoing(fd
) == 0) {
325 BtrfsQuotaInfo quota
;
327 r
= btrfs_subvol_get_subtree_quota_fd(fd
, 0, "a
);
329 (*ret
)->usage
= quota
.referenced
;
330 (*ret
)->usage_exclusive
= quota
.exclusive
;
332 (*ret
)->limit
= quota
.referenced_max
;
333 (*ret
)->limit_exclusive
= quota
.exclusive_max
;
341 /* Get directory creation time (not available everywhere, but that's OK */
342 (void) fd_getcrtime(fd
, &crtime
);
344 /* If the IMMUTABLE bit is set, we consider the directory read-only. Since the ioctl is not
345 * supported everywhere we ignore failures. */
346 (void) read_attr_fd(fd
, &file_attr
);
348 /* It's just a normal directory. */
349 r
= image_new(IMAGE_DIRECTORY
,
354 read_only
|| (file_attr
& FS_IMMUTABLE_FL
),
356 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 */
363 } else if (S_ISREG(st
->st_mode
) && endswith(filename
, ".raw")) {
366 /* It's a RAW disk image */
371 (void) fd_getcrtime_at(dfd
, filename
, AT_SYMLINK_FOLLOW
, &crtime
);
374 r
= extract_pretty(filename
, ".raw", &pretty_buffer
);
378 pretty
= pretty_buffer
;
381 r
= image_new(IMAGE_RAW
,
386 !(st
->st_mode
& 0222) || read_only
,
388 timespec_load(&st
->st_mtim
),
393 (*ret
)->usage
= (*ret
)->usage_exclusive
= st
->st_blocks
* 512;
394 (*ret
)->limit
= (*ret
)->limit_exclusive
= st
->st_size
;
398 } else if (S_ISBLK(st
->st_mode
)) {
399 _cleanup_close_
int block_fd
= -EBADF
;
400 uint64_t size
= UINT64_MAX
;
408 r
= extract_pretty(filename
, NULL
, &pretty_buffer
);
412 pretty
= pretty_buffer
;
415 block_fd
= openat(dfd
, filename
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
417 log_debug_errno(errno
, "Failed to open block device %s/%s, ignoring: %m", path
?: strnull(parent
), filename
);
419 /* Refresh stat data after opening the node */
420 if (fstat(block_fd
, &stbuf
) < 0)
424 if (!S_ISBLK(st
->st_mode
)) /* Verify that what we opened is actually what we think it is */
430 if (ioctl(block_fd
, BLKROGET
, &state
) < 0)
431 log_debug_errno(errno
, "Failed to issue BLKROGET on device %s/%s, ignoring: %m", path
?: strnull(parent
), filename
);
436 if (ioctl(block_fd
, BLKGETSIZE64
, &size
) < 0)
437 log_debug_errno(errno
, "Failed to issue BLKGETSIZE64 on device %s/%s, ignoring: %m", path
?: strnull(parent
), filename
);
439 block_fd
= safe_close(block_fd
);
442 r
= image_new(IMAGE_BLOCK
,
447 !(st
->st_mode
& 0222) || read_only
,
454 if (!IN_SET(size
, 0, UINT64_MAX
))
455 (*ret
)->usage
= (*ret
)->usage_exclusive
= (*ret
)->limit
= (*ret
)->limit_exclusive
= size
;
463 static const char *pick_image_search_path(ImageClass
class) {
464 if (class < 0 || class >= _IMAGE_CLASS_MAX
)
467 /* Use the initrd search path if there is one, otherwise use the common one */
468 return in_initrd() && image_search_path_initrd
[class] ? image_search_path_initrd
[class] : image_search_path
[class];
471 int image_find(ImageClass
class,
479 assert(class < _IMAGE_CLASS_MAX
);
482 /* There are no images with invalid names */
483 if (!image_name_is_valid(name
))
486 NULSTR_FOREACH(path
, pick_image_search_path(class)) {
487 _cleanup_free_
char *resolved
= NULL
;
488 _cleanup_closedir_
DIR *d
= NULL
;
492 r
= chase_and_opendir(path
, root
, CHASE_PREFIX_ROOT
, &resolved
, &d
);
498 /* As mentioned above, we follow symlinks on this fstatat(), because we want to permit people
499 * to symlink block devices into the search path. (For now, we disable that when operating
500 * relative to some root directory.) */
501 flags
= root
? AT_SYMLINK_NOFOLLOW
: 0;
502 if (fstatat(dirfd(d
), name
, &st
, flags
) < 0) {
503 _cleanup_free_
char *raw
= NULL
;
508 raw
= strjoin(name
, ".raw");
512 if (fstatat(dirfd(d
), raw
, &st
, flags
) < 0) {
519 if (!S_ISREG(st
.st_mode
))
522 r
= image_make(class, name
, dirfd(d
), resolved
, raw
, &st
, ret
);
525 if (!S_ISDIR(st
.st_mode
) && !S_ISBLK(st
.st_mode
))
528 r
= image_make(class, name
, dirfd(d
), resolved
, name
, &st
, ret
);
530 if (IN_SET(r
, -ENOENT
, -EMEDIUMTYPE
))
536 (*ret
)->discoverable
= true;
541 if (class == IMAGE_MACHINE
&& streq(name
, ".host")) {
542 r
= image_make(class, ".host", AT_FDCWD
, NULL
, empty_to_root(root
), NULL
, ret
);
547 (*ret
)->discoverable
= true;
555 int image_from_path(const char *path
, Image
**ret
) {
557 /* Note that we don't set the 'discoverable' field of the returned object, because we don't check here whether
558 * the image is in the image search path. And if it is we don't know if the path we used is actually not
559 * overridden by another, different image earlier in the search path */
561 if (path_equal(path
, "/"))
562 return image_make(IMAGE_MACHINE
, ".host", AT_FDCWD
, NULL
, "/", NULL
, ret
);
564 return image_make(_IMAGE_CLASS_INVALID
, NULL
, AT_FDCWD
, NULL
, path
, NULL
, ret
);
567 int image_find_harder(ImageClass
class, const char *name_or_path
, const char *root
, Image
**ret
) {
568 if (image_name_is_valid(name_or_path
))
569 return image_find(class, name_or_path
, root
, ret
);
571 return image_from_path(name_or_path
, ret
);
582 assert(class < _IMAGE_CLASS_MAX
);
585 NULSTR_FOREACH(path
, pick_image_search_path(class)) {
586 _cleanup_free_
char *resolved
= NULL
;
587 _cleanup_closedir_
DIR *d
= NULL
;
589 r
= chase_and_opendir(path
, root
, CHASE_PREFIX_ROOT
, &resolved
, &d
);
595 FOREACH_DIRENT_ALL(de
, d
, return -errno
) {
596 _cleanup_(image_unrefp
) Image
*image
= NULL
;
597 _cleanup_free_
char *truncated
= NULL
;
602 if (dot_or_dot_dot(de
->d_name
))
605 /* As mentioned above, we follow symlinks on this fstatat(), because we want to
606 * permit people to symlink block devices into the search path. */
607 flags
= root
? AT_SYMLINK_NOFOLLOW
: 0;
608 if (fstatat(dirfd(d
), de
->d_name
, &st
, flags
) < 0) {
615 if (S_ISREG(st
.st_mode
)) {
618 e
= endswith(de
->d_name
, ".raw");
622 truncated
= strndup(de
->d_name
, e
- de
->d_name
);
627 } else if (S_ISDIR(st
.st_mode
) || S_ISBLK(st
.st_mode
))
632 if (!image_name_is_valid(pretty
))
635 if (hashmap_contains(h
, pretty
))
638 r
= image_make(class, pretty
, dirfd(d
), resolved
, de
->d_name
, &st
, &image
);
639 if (IN_SET(r
, -ENOENT
, -EMEDIUMTYPE
))
644 image
->discoverable
= true;
646 r
= hashmap_put(h
, image
->name
, image
);
654 if (class == IMAGE_MACHINE
&& !hashmap_contains(h
, ".host")) {
655 _cleanup_(image_unrefp
) Image
*image
= NULL
;
657 r
= image_make(IMAGE_MACHINE
, ".host", AT_FDCWD
, NULL
, empty_to_root("/"), NULL
, &image
);
661 image
->discoverable
= true;
663 r
= hashmap_put(h
, image
->name
, image
);
673 int image_remove(Image
*i
) {
674 _cleanup_(release_lock_file
) LockFile global_lock
= LOCK_FILE_INIT
, local_lock
= LOCK_FILE_INIT
;
675 _cleanup_strv_free_
char **settings
= NULL
;
676 _cleanup_free_
char *roothash
= NULL
;
681 if (IMAGE_IS_VENDOR(i
) || IMAGE_IS_HOST(i
))
684 settings
= image_settings_path(i
);
688 r
= image_roothash_path(i
, &roothash
);
692 /* Make sure we don't interfere with a running nspawn */
693 r
= image_path_lock(i
->path
, LOCK_EX
|LOCK_NB
, &global_lock
, &local_lock
);
699 case IMAGE_SUBVOLUME
:
701 /* Let's unlink first, maybe it is a symlink? If that works we are happy. Otherwise, let's get out the
703 if (unlink(i
->path
) < 0) {
704 r
= btrfs_subvol_remove(i
->path
, BTRFS_REMOVE_RECURSIVE
|BTRFS_REMOVE_QUOTA
);
711 case IMAGE_DIRECTORY
:
712 /* Allow deletion of read-only directories */
713 (void) chattr_path(i
->path
, 0, FS_IMMUTABLE_FL
, NULL
);
714 r
= rm_rf(i
->path
, REMOVE_ROOT
|REMOVE_PHYSICAL
|REMOVE_SUBVOLUME
);
722 /* If this is inside of /dev, then it's a real block device, hence let's not touch the device node
723 * itself (but let's remove the stuff stored alongside it). If it's anywhere else, let's try to unlink
724 * the thing (it's most likely a symlink after all). */
726 if (path_startswith(i
->path
, "/dev"))
731 if (unlink(i
->path
) < 0)
739 STRV_FOREACH(j
, settings
)
740 if (unlink(*j
) < 0 && errno
!= ENOENT
)
741 log_debug_errno(errno
, "Failed to unlink %s, ignoring: %m", *j
);
743 if (unlink(roothash
) < 0 && errno
!= ENOENT
)
744 log_debug_errno(errno
, "Failed to unlink %s, ignoring: %m", roothash
);
749 static int rename_auxiliary_file(const char *path
, const char *new_name
, const char *suffix
) {
750 _cleanup_free_
char *fn
= NULL
, *rs
= NULL
;
753 fn
= strjoin(new_name
, suffix
);
757 r
= file_in_same_dir(path
, fn
, &rs
);
761 return rename_noreplace(AT_FDCWD
, path
, AT_FDCWD
, rs
);
764 int image_rename(Image
*i
, const char *new_name
) {
765 _cleanup_(release_lock_file
) LockFile global_lock
= LOCK_FILE_INIT
, local_lock
= LOCK_FILE_INIT
, name_lock
= LOCK_FILE_INIT
;
766 _cleanup_free_
char *new_path
= NULL
, *nn
= NULL
, *roothash
= NULL
;
767 _cleanup_strv_free_
char **settings
= NULL
;
768 unsigned file_attr
= 0;
773 if (!image_name_is_valid(new_name
))
776 if (IMAGE_IS_VENDOR(i
) || IMAGE_IS_HOST(i
))
779 settings
= image_settings_path(i
);
783 r
= image_roothash_path(i
, &roothash
);
787 /* Make sure we don't interfere with a running nspawn */
788 r
= image_path_lock(i
->path
, LOCK_EX
|LOCK_NB
, &global_lock
, &local_lock
);
792 /* Make sure nobody takes the new name, between the time we
793 * checked it is currently unused in all search paths, and the
794 * time we take possession of it */
795 r
= image_name_lock(new_name
, LOCK_EX
|LOCK_NB
, &name_lock
);
799 r
= image_find(IMAGE_MACHINE
, new_name
, NULL
, NULL
);
807 case IMAGE_DIRECTORY
:
808 /* Turn of the immutable bit while we rename the image, so that we can rename it */
809 (void) read_attr_path(i
->path
, &file_attr
);
811 if (file_attr
& FS_IMMUTABLE_FL
)
812 (void) chattr_path(i
->path
, 0, FS_IMMUTABLE_FL
, NULL
);
815 case IMAGE_SUBVOLUME
:
816 r
= file_in_same_dir(i
->path
, new_name
, &new_path
);
821 /* Refuse renaming raw block devices in /dev, the names are picked by udev after all. */
822 if (path_startswith(i
->path
, "/dev"))
825 r
= file_in_same_dir(i
->path
, new_name
, &new_path
);
831 fn
= strjoina(new_name
, ".raw");
833 r
= file_in_same_dir(i
->path
, fn
, &new_path
);
843 nn
= strdup(new_name
);
847 r
= rename_noreplace(AT_FDCWD
, i
->path
, AT_FDCWD
, new_path
);
851 /* Restore the immutable bit, if it was set before */
852 if (file_attr
& FS_IMMUTABLE_FL
)
853 (void) chattr_path(new_path
, FS_IMMUTABLE_FL
, FS_IMMUTABLE_FL
, NULL
);
855 free_and_replace(i
->path
, new_path
);
856 free_and_replace(i
->name
, nn
);
858 STRV_FOREACH(j
, settings
) {
859 r
= rename_auxiliary_file(*j
, new_name
, ".nspawn");
860 if (r
< 0 && r
!= -ENOENT
)
861 log_debug_errno(r
, "Failed to rename settings file %s, ignoring: %m", *j
);
864 r
= rename_auxiliary_file(roothash
, new_name
, ".roothash");
865 if (r
< 0 && r
!= -ENOENT
)
866 log_debug_errno(r
, "Failed to rename roothash file %s, ignoring: %m", roothash
);
871 static int clone_auxiliary_file(const char *path
, const char *new_name
, const char *suffix
) {
872 _cleanup_free_
char *fn
= NULL
, *rs
= NULL
;
875 fn
= strjoin(new_name
, suffix
);
879 r
= file_in_same_dir(path
, fn
, &rs
);
883 return copy_file_atomic(path
, rs
, 0664, COPY_REFLINK
);
886 int image_clone(Image
*i
, const char *new_name
, bool read_only
) {
887 _cleanup_(release_lock_file
) LockFile name_lock
= LOCK_FILE_INIT
;
888 _cleanup_strv_free_
char **settings
= NULL
;
889 _cleanup_free_
char *roothash
= NULL
;
890 const char *new_path
;
895 if (!image_name_is_valid(new_name
))
898 settings
= image_settings_path(i
);
902 r
= image_roothash_path(i
, &roothash
);
906 /* Make sure nobody takes the new name, between the time we
907 * checked it is currently unused in all search paths, and the
908 * time we take possession of it */
909 r
= image_name_lock(new_name
, LOCK_EX
|LOCK_NB
, &name_lock
);
913 r
= image_find(IMAGE_MACHINE
, new_name
, NULL
, NULL
);
921 case IMAGE_SUBVOLUME
:
922 case IMAGE_DIRECTORY
:
923 /* If we can we'll always try to create a new btrfs subvolume here, even if the source is a plain
926 new_path
= strjoina("/var/lib/machines/", new_name
);
928 r
= btrfs_subvol_snapshot(i
->path
, new_path
,
929 (read_only
? BTRFS_SNAPSHOT_READ_ONLY
: 0) |
930 BTRFS_SNAPSHOT_FALLBACK_COPY
|
931 BTRFS_SNAPSHOT_FALLBACK_DIRECTORY
|
932 BTRFS_SNAPSHOT_FALLBACK_IMMUTABLE
|
933 BTRFS_SNAPSHOT_RECURSIVE
|
934 BTRFS_SNAPSHOT_QUOTA
);
936 /* Enable "subtree" quotas for the copy, if we didn't copy any quota from the source. */
937 (void) btrfs_subvol_auto_qgroup(new_path
, 0, true);
942 new_path
= strjoina("/var/lib/machines/", new_name
, ".raw");
944 r
= copy_file_atomic_full(i
->path
, new_path
, read_only
? 0444 : 0644, FS_NOCOW_FL
, FS_NOCOW_FL
,
945 COPY_REFLINK
|COPY_CRTIME
, NULL
, NULL
);
956 STRV_FOREACH(j
, settings
) {
957 r
= clone_auxiliary_file(*j
, new_name
, ".nspawn");
958 if (r
< 0 && r
!= -ENOENT
)
959 log_debug_errno(r
, "Failed to clone settings %s, ignoring: %m", *j
);
962 r
= clone_auxiliary_file(roothash
, new_name
, ".roothash");
963 if (r
< 0 && r
!= -ENOENT
)
964 log_debug_errno(r
, "Failed to clone root hash file %s, ignoring: %m", roothash
);
969 int image_read_only(Image
*i
, bool b
) {
970 _cleanup_(release_lock_file
) LockFile global_lock
= LOCK_FILE_INIT
, local_lock
= LOCK_FILE_INIT
;
975 if (IMAGE_IS_VENDOR(i
) || IMAGE_IS_HOST(i
))
978 /* Make sure we don't interfere with a running nspawn */
979 r
= image_path_lock(i
->path
, LOCK_EX
|LOCK_NB
, &global_lock
, &local_lock
);
985 case IMAGE_SUBVOLUME
:
987 /* Note that we set the flag only on the top-level
988 * subvolume of the image. */
990 r
= btrfs_subvol_set_read_only(i
->path
, b
);
996 case IMAGE_DIRECTORY
:
997 /* For simple directory trees we cannot use the access
998 mode of the top-level directory, since it has an
999 effect on the container itself. However, we can
1000 use the "immutable" flag, to at least make the
1001 top-level directory read-only. It's not as good as
1002 a read-only subvolume, but at least something, and
1003 we can read the value back. */
1005 r
= chattr_path(i
->path
, b
? FS_IMMUTABLE_FL
: 0, FS_IMMUTABLE_FL
, NULL
);
1014 if (stat(i
->path
, &st
) < 0)
1017 if (chmod(i
->path
, (st
.st_mode
& 0444) | (b
? 0000 : 0200)) < 0)
1020 /* If the images is now read-only, it's a good time to
1021 * defrag it, given that no write patterns will
1022 * fragment it again. */
1024 (void) btrfs_defrag(i
->path
);
1029 _cleanup_close_
int fd
= -EBADF
;
1033 fd
= open(i
->path
, O_CLOEXEC
|O_RDONLY
|O_NONBLOCK
|O_NOCTTY
);
1037 if (fstat(fd
, &st
) < 0)
1039 if (!S_ISBLK(st
.st_mode
))
1042 if (ioctl(fd
, BLKROSET
, &state
) < 0)
1055 int image_path_lock(const char *path
, int operation
, LockFile
*global
, LockFile
*local
) {
1056 _cleanup_free_
char *p
= NULL
;
1057 LockFile t
= LOCK_FILE_INIT
;
1066 /* Locks an image path. This actually creates two locks: one "local" one, next to the image path
1067 * itself, which might be shared via NFS. And another "global" one, in /run, that uses the
1068 * device/inode number. This has the benefit that we can even lock a tree that is a mount point,
1071 if (!path_is_absolute(path
))
1074 switch (operation
& (LOCK_SH
|LOCK_EX
)) {
1085 if (getenv_bool("SYSTEMD_NSPAWN_LOCK") == 0) {
1086 *local
= *global
= (LockFile
) LOCK_FILE_INIT
;
1090 /* Prohibit taking exclusive locks on the host image. We can't allow this, since we ourselves are
1091 * running off it after all, and we don't want any images to manipulate the host image. We make an
1092 * exception for shared locks however: we allow those (and make them NOPs since there's no point in
1093 * taking them if there can't be exclusive locks). Strictly speaking these are questionable as well,
1094 * since it means changes made to the host might propagate to the container as they happen (and a
1095 * shared lock kinda suggests that no changes happen at all while it is in place), but it's too
1096 * useful not to allow read-only containers off the host root, hence let's support this, and trust
1097 * the user to do the right thing with this. */
1098 if (path_equal(path
, "/")) {
1102 *local
= *global
= (LockFile
) LOCK_FILE_INIT
;
1106 if (stat(path
, &st
) >= 0) {
1107 if (S_ISBLK(st
.st_mode
))
1108 r
= asprintf(&p
, "/run/systemd/nspawn/locks/block-%u:%u", major(st
.st_rdev
), minor(st
.st_rdev
));
1109 else if (S_ISDIR(st
.st_mode
) || S_ISREG(st
.st_mode
))
1110 r
= asprintf(&p
, "/run/systemd/nspawn/locks/inode-%lu:%lu", (unsigned long) st
.st_dev
, (unsigned long) st
.st_ino
);
1117 /* For block devices we don't need the "local" lock, as the major/minor lock above should be
1118 * sufficient, since block devices are host local anyway. */
1119 if (!path_startswith(path
, "/dev/")) {
1120 r
= make_lock_file_for(path
, operation
, &t
);
1122 if (!exclusive
&& r
== -EROFS
)
1123 log_debug_errno(r
, "Failed to create shared lock for '%s', ignoring: %m", path
);
1130 (void) mkdir_p("/run/systemd/nspawn/locks", 0700);
1132 r
= make_lock_file(p
, operation
, global
);
1134 release_lock_file(&t
);
1138 *global
= (LockFile
) LOCK_FILE_INIT
;
1144 int image_set_limit(Image
*i
, uint64_t referenced_max
) {
1147 if (IMAGE_IS_VENDOR(i
) || IMAGE_IS_HOST(i
))
1150 if (i
->type
!= IMAGE_SUBVOLUME
)
1153 /* We set the quota both for the subvolume as well as for the
1154 * subtree. The latter is mostly for historical reasons, since
1155 * we didn't use to have a concept of subtree quota, and hence
1156 * only modified the subvolume quota. */
1158 (void) btrfs_qgroup_set_limit(i
->path
, 0, referenced_max
);
1159 (void) btrfs_subvol_auto_qgroup(i
->path
, 0, true);
1160 return btrfs_subvol_set_subtree_quota_limit(i
->path
, 0, referenced_max
);
1163 int image_read_metadata(Image
*i
, const ImagePolicy
*image_policy
) {
1164 _cleanup_(release_lock_file
) LockFile global_lock
= LOCK_FILE_INIT
, local_lock
= LOCK_FILE_INIT
;
1169 r
= image_path_lock(i
->path
, LOCK_SH
|LOCK_NB
, &global_lock
, &local_lock
);
1175 case IMAGE_SUBVOLUME
:
1176 case IMAGE_DIRECTORY
: {
1177 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
, **extension_release
= NULL
;
1178 sd_id128_t machine_id
= SD_ID128_NULL
;
1179 _cleanup_free_
char *hostname
= NULL
;
1180 _cleanup_free_
char *path
= NULL
;
1182 if (i
->class == IMAGE_SYSEXT
) {
1183 r
= extension_has_forbidden_content(i
->path
);
1187 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM
),
1188 "Conflicting content found in image %s, refusing.",
1192 r
= chase("/etc/hostname", i
->path
, CHASE_PREFIX_ROOT
|CHASE_TRAIL_SLASH
, &path
, NULL
);
1193 if (r
< 0 && r
!= -ENOENT
)
1194 log_debug_errno(r
, "Failed to chase /etc/hostname in image %s: %m", i
->name
);
1196 r
= read_etc_hostname(path
, &hostname
);
1198 log_debug_errno(errno
, "Failed to read /etc/hostname of image %s: %m", i
->name
);
1203 r
= id128_get_machine(i
->path
, &machine_id
);
1205 log_debug_errno(r
, "Failed to read machine ID in image %s, ignoring: %m", i
->name
);
1207 r
= chase("/etc/machine-info", i
->path
, CHASE_PREFIX_ROOT
|CHASE_TRAIL_SLASH
, &path
, NULL
);
1208 if (r
< 0 && r
!= -ENOENT
)
1209 log_debug_errno(r
, "Failed to chase /etc/machine-info in image %s: %m", i
->name
);
1211 r
= load_env_file_pairs(NULL
, path
, &machine_info
);
1213 log_debug_errno(r
, "Failed to parse machine-info data of %s: %m", i
->name
);
1216 r
= load_os_release_pairs(i
->path
, &os_release
);
1218 log_debug_errno(r
, "Failed to read os-release in image, ignoring: %m");
1220 r
= load_extension_release_pairs(i
->path
, i
->class, i
->name
, /* relax_extension_release_check= */ false, &extension_release
);
1222 log_debug_errno(r
, "Failed to read extension-release in image, ignoring: %m");
1224 free_and_replace(i
->hostname
, hostname
);
1225 i
->machine_id
= machine_id
;
1226 strv_free_and_replace(i
->machine_info
, machine_info
);
1227 strv_free_and_replace(i
->os_release
, os_release
);
1228 strv_free_and_replace(i
->extension_release
, extension_release
);
1235 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
1236 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
1238 r
= loop_device_make_by_path(i
->path
, O_RDONLY
, /* sector_size= */ UINT32_MAX
, LO_FLAGS_PARTSCAN
, LOCK_SH
, &d
);
1242 r
= dissect_loop_device(
1245 /* mount_options= */ NULL
,
1247 DISSECT_IMAGE_GENERIC_ROOT
|
1248 DISSECT_IMAGE_REQUIRE_ROOT
|
1249 DISSECT_IMAGE_RELAX_VAR_CHECK
|
1250 DISSECT_IMAGE_READ_ONLY
|
1251 DISSECT_IMAGE_USR_NO_ROOT
|
1252 DISSECT_IMAGE_ADD_PARTITION_DEVICES
|
1253 DISSECT_IMAGE_PIN_PARTITION_DEVICES
,
1258 r
= dissected_image_acquire_metadata(m
,
1259 DISSECT_IMAGE_VALIDATE_OS
|
1260 DISSECT_IMAGE_VALIDATE_OS_EXT
);
1264 free_and_replace(i
->hostname
, m
->hostname
);
1265 i
->machine_id
= m
->machine_id
;
1266 strv_free_and_replace(i
->machine_info
, m
->machine_info
);
1267 strv_free_and_replace(i
->os_release
, m
->os_release
);
1268 strv_free_and_replace(i
->extension_release
, m
->extension_release
);
1277 i
->metadata_valid
= true;
1282 int image_name_lock(const char *name
, int operation
, LockFile
*ret
) {
1288 /* Locks an image name, regardless of the precise path used. */
1290 if (streq(name
, ".host"))
1293 if (!image_name_is_valid(name
))
1296 if (getenv_bool("SYSTEMD_NSPAWN_LOCK") == 0) {
1297 *ret
= (LockFile
) LOCK_FILE_INIT
;
1301 (void) mkdir_p("/run/systemd/nspawn/locks", 0700);
1303 p
= strjoina("/run/systemd/nspawn/locks/name-", name
);
1304 return make_lock_file(p
, operation
, ret
);
1307 bool image_in_search_path(
1310 const char *image
) {
1314 NULSTR_FOREACH(path
, pick_image_search_path(class)) {
1318 if (!empty_or_root(root
)) {
1319 q
= path_startswith(path
, root
);
1325 p
= path_startswith(q
, path
);
1329 /* Make sure there's a filename following */
1330 k
= strcspn(p
, "/");
1336 /* Accept trailing slashes */
1337 if (p
[strspn(p
, "/")] == 0)
1345 static const char* const image_type_table
[_IMAGE_TYPE_MAX
] = {
1346 [IMAGE_DIRECTORY
] = "directory",
1347 [IMAGE_SUBVOLUME
] = "subvolume",
1348 [IMAGE_RAW
] = "raw",
1349 [IMAGE_BLOCK
] = "block",
1352 DEFINE_STRING_TABLE_LOOKUP(image_type
, ImageType
);