1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
7 #include <sys/statvfs.h>
9 #include <linux/loop.h>
14 #include "alloc-util.h"
15 #include "chase-symlinks.h"
16 #include "dissect-image.h"
17 #include "exec-util.h"
18 #include "extract-word.h"
22 #include "glyph-util.h"
24 #include "initrd-util.h"
26 #include "libmount-util.h"
27 #include "missing_mount.h"
28 #include "missing_syscall.h"
29 #include "mkdir-label.h"
30 #include "mount-util.h"
31 #include "mountpoint-util.h"
32 #include "namespace-util.h"
33 #include "parse-util.h"
34 #include "path-util.h"
35 #include "process-util.h"
37 #include "stat-util.h"
38 #include "stdio-util.h"
39 #include "string-table.h"
40 #include "string-util.h"
42 #include "tmpfile-util.h"
43 #include "user-util.h"
45 int umount_recursive(const char *prefix
, int flags
) {
49 /* Try to umount everything recursively below a directory. Also, take care of stacked mounts, and
50 * keep unmounting them until they are gone. */
53 _cleanup_(mnt_free_tablep
) struct libmnt_table
*table
= NULL
;
54 _cleanup_(mnt_free_iterp
) struct libmnt_iter
*iter
= NULL
;
58 r
= libmount_parse("/proc/self/mountinfo", NULL
, &table
, &iter
);
60 return log_debug_errno(r
, "Failed to parse /proc/self/mountinfo: %m");
66 r
= mnt_table_next_fs(table
, iter
, &fs
);
70 return log_debug_errno(r
, "Failed to get next entry from /proc/self/mountinfo: %m");
72 path
= mnt_fs_get_target(fs
);
76 if (!path_startswith(path
, prefix
))
79 if (umount2(path
, flags
| UMOUNT_NOFOLLOW
) < 0) {
80 log_debug_errno(errno
, "Failed to umount %s, ignoring: %m", path
);
84 log_debug("Successfully unmounted %s", path
);
96 #define MS_CONVERTIBLE_FLAGS (MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_NOSYMFOLLOW)
98 static uint64_t ms_flags_to_mount_attr(unsigned long a
) {
101 if (FLAGS_SET(a
, MS_RDONLY
))
102 f
|= MOUNT_ATTR_RDONLY
;
104 if (FLAGS_SET(a
, MS_NOSUID
))
105 f
|= MOUNT_ATTR_NOSUID
;
107 if (FLAGS_SET(a
, MS_NODEV
))
108 f
|= MOUNT_ATTR_NODEV
;
110 if (FLAGS_SET(a
, MS_NOEXEC
))
111 f
|= MOUNT_ATTR_NOEXEC
;
113 if (FLAGS_SET(a
, MS_NOSYMFOLLOW
))
114 f
|= MOUNT_ATTR_NOSYMFOLLOW
;
119 static bool skip_mount_set_attr
= false;
121 /* Use this function only if you do not have direct access to /proc/self/mountinfo but the caller can open it
122 * for you. This is the case when /proc is masked or not mounted. Otherwise, use bind_remount_recursive. */
123 int bind_remount_recursive_with_mountinfo(
125 unsigned long new_flags
,
126 unsigned long flags_mask
,
128 FILE *proc_self_mountinfo
) {
130 _cleanup_fclose_
FILE *proc_self_mountinfo_opened
= NULL
;
131 _cleanup_set_free_ Set
*done
= NULL
;
132 unsigned n_tries
= 0;
137 if ((flags_mask
& ~MS_CONVERTIBLE_FLAGS
) == 0 && strv_isempty(deny_list
) && !skip_mount_set_attr
) {
138 /* Let's take a shortcut for all the flags we know how to convert into mount_setattr() flags */
140 if (mount_setattr(AT_FDCWD
, prefix
, AT_SYMLINK_NOFOLLOW
|AT_RECURSIVE
,
141 &(struct mount_attr
) {
142 .attr_set
= ms_flags_to_mount_attr(new_flags
& flags_mask
),
143 .attr_clr
= ms_flags_to_mount_attr(~new_flags
& flags_mask
),
144 }, MOUNT_ATTR_SIZE_VER0
) < 0) {
146 log_debug_errno(errno
, "mount_setattr() failed, falling back to classic remounting: %m");
148 /* We fall through to classic behaviour if not supported (i.e. kernel < 5.12). We
149 * also do this for all other kinds of errors since they are so many different, and
150 * mount_setattr() has no graceful mode where it continues despite seeing errors one
151 * some mounts, but we want that. Moreover mount_setattr() only works on the mount
152 * point inode itself, not a non-mount point inode, and we want to support arbitrary
155 if (ERRNO_IS_NOT_SUPPORTED(errno
)) /* if not supported, then don't bother at all anymore */
156 skip_mount_set_attr
= true;
158 return 0; /* Nice, this worked! */
161 if (!proc_self_mountinfo
) {
162 r
= fopen_unlocked("/proc/self/mountinfo", "re", &proc_self_mountinfo_opened
);
166 proc_self_mountinfo
= proc_self_mountinfo_opened
;
169 /* Recursively remount a directory (and all its submounts) with desired flags (MS_READONLY,
170 * MS_NOSUID, MS_NOEXEC). If the directory is already mounted, we reuse the mount and simply mark it
171 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write operation), ditto for other flags. If it
172 * isn't we first make it one. Afterwards we apply (or remove) the flags to all submounts we can
173 * access, too. When mounts are stacked on the same mount point we only care for each individual
174 * "top-level" mount on each point, as we cannot influence/access the underlying mounts anyway. We do
175 * not have any effect on future submounts that might get propagated, they might be writable
176 * etc. This includes future submounts that have been triggered via autofs. Also note that we can't
177 * operate atomically here. Mounts established while we process the tree might or might not get
178 * noticed and thus might or might not be covered.
180 * If the "deny_list" parameter is specified it may contain a list of subtrees to exclude from the
181 * remount operation. Note that we'll ignore the deny list for the top-level path. */
184 _cleanup_(mnt_free_tablep
) struct libmnt_table
*table
= NULL
;
185 _cleanup_(mnt_free_iterp
) struct libmnt_iter
*iter
= NULL
;
186 _cleanup_hashmap_free_ Hashmap
*todo
= NULL
;
187 bool top_autofs
= false;
189 if (n_tries
++ >= 32) /* Let's not retry this loop forever */
192 rewind(proc_self_mountinfo
);
194 r
= libmount_parse("/proc/self/mountinfo", proc_self_mountinfo
, &table
, &iter
);
196 return log_debug_errno(r
, "Failed to parse /proc/self/mountinfo: %m");
199 _cleanup_free_
char *d
= NULL
;
200 const char *path
, *type
, *opts
;
201 unsigned long flags
= 0;
202 struct libmnt_fs
*fs
;
204 r
= mnt_table_next_fs(table
, iter
, &fs
);
205 if (r
== 1) /* EOF */
208 return log_debug_errno(r
, "Failed to get next entry from /proc/self/mountinfo: %m");
210 path
= mnt_fs_get_target(fs
);
214 if (!path_startswith(path
, prefix
))
217 type
= mnt_fs_get_fstype(fs
);
221 /* Let's ignore autofs mounts. If they aren't triggered yet, we want to avoid
222 * triggering them, as we don't make any guarantees for future submounts anyway. If
223 * they are already triggered, then we will find another entry for this. */
224 if (streq(type
, "autofs")) {
225 top_autofs
= top_autofs
|| path_equal(path
, prefix
);
229 if (set_contains(done
, path
))
232 /* Ignore this mount if it is deny-listed, but only if it isn't the top-level mount
233 * we shall operate on. */
234 if (!path_equal(path
, prefix
)) {
235 bool deny_listed
= false;
237 STRV_FOREACH(i
, deny_list
) {
238 if (path_equal(*i
, prefix
))
241 if (!path_startswith(*i
, prefix
))
244 if (path_startswith(path
, *i
)) {
246 log_debug("Not remounting %s deny-listed by %s, called for %s", path
, *i
, prefix
);
255 opts
= mnt_fs_get_vfs_options(fs
);
257 r
= mnt_optstr_get_flags(opts
, &flags
, mnt_get_builtin_optmap(MNT_LINUX_MAP
));
259 log_debug_errno(r
, "Could not get flags for '%s', ignoring: %m", path
);
266 r
= hashmap_ensure_put(&todo
, &path_hash_ops_free
, d
, ULONG_TO_PTR(flags
));
268 /* If the same path was recorded, but with different mount flags, update it:
269 * it means a mount point is overmounted, and libmount returns the "bottom" (or
270 * older one) first, but we want to reapply the flags from the "top" (or newer
271 * one). See: https://github.com/systemd/systemd/issues/20032
272 * Note that this shouldn't really fail, as we were just told that the key
273 * exists, and it's an update so we want 'd' to be freed immediately. */
274 r
= hashmap_update(todo
, d
, ULONG_TO_PTR(flags
));
281 /* Check if the top-level directory was among what we have seen so far. For that check both
282 * 'done' and 'todo'. Also check 'top_autofs' because if the top-level dir is an autofs we'll
283 * not include it in either set but will set this bool. */
284 if (!set_contains(done
, prefix
) &&
285 !(top_autofs
|| hashmap_contains(todo
, prefix
))) {
287 /* The prefix directory itself is not yet a mount, make it one. */
288 r
= mount_nofollow(prefix
, prefix
, NULL
, MS_BIND
|MS_REC
, NULL
);
292 /* Immediately rescan, so that we pick up the new mount's flags */
296 /* If we have no submounts to process anymore, we are done */
297 if (hashmap_isempty(todo
))
304 /* Take the first mount from our list of mounts to still process */
305 flags
= PTR_TO_ULONG(hashmap_steal_first_key_and_value(todo
, (void**) &x
));
309 r
= set_ensure_consume(&done
, &path_hash_ops_free
, x
);
310 if (IN_SET(r
, 0, -EEXIST
))
311 continue; /* Already done */
315 /* Now, remount this with the new flags set, but exclude MS_RELATIME from it. (It's
316 * the default anyway, thus redundant, and in userns we'll get an error if we try to
317 * explicitly enable it) */
318 r
= mount_nofollow(NULL
, x
, NULL
, ((flags
& ~flags_mask
)|MS_BIND
|MS_REMOUNT
|new_flags
) & ~MS_RELATIME
, NULL
);
322 /* OK, so the remount of this entry failed. We'll ultimately ignore this in
323 * almost all cases (there are simply so many reasons why this can fail,
324 * think autofs, NFS, FUSE, …), but let's generate useful debug messages at
327 q
= path_is_mount_point(x
, NULL
, 0);
328 if (IN_SET(q
, 0, -ENOENT
)) {
329 /* Hmm, whaaaa? The mount point is not actually a mount point? Then
330 * it is either obstructed by a later mount or somebody has been
331 * racing against us and removed it. Either way the mount point
332 * doesn't matter to us, let's ignore it hence. */
333 log_debug_errno(r
, "Mount point '%s' to remount is not a mount point anymore, ignoring remount failure: %m", x
);
336 if (q
< 0) /* Any other error on this? Just log and continue */
337 log_debug_errno(q
, "Failed to determine whether '%s' is a mount point or not, ignoring: %m", x
);
339 if (((flags
^ new_flags
) & flags_mask
& ~MS_RELATIME
) == 0) { /* ignore MS_RELATIME while comparing */
340 log_debug_errno(r
, "Couldn't remount '%s', but the flags already match what we want, hence ignoring: %m", x
);
344 /* Make this fatal if this is the top-level mount */
345 if (path_equal(x
, prefix
))
348 /* If this is not the top-level mount, then handle this gracefully: log but
349 * otherwise ignore. With NFS, FUSE, autofs there are just too many reasons
350 * this might fail without a chance for us to do anything about it, let's
351 * hence be strict on the top-level mount and lenient on the inner ones. */
352 log_debug_errno(r
, "Couldn't remount submount '%s' for unexpected reason, ignoring: %m", x
);
356 log_debug("Remounted %s.", x
);
361 int bind_remount_one_with_mountinfo(
363 unsigned long new_flags
,
364 unsigned long flags_mask
,
365 FILE *proc_self_mountinfo
) {
367 _cleanup_(mnt_free_tablep
) struct libmnt_table
*table
= NULL
;
368 unsigned long flags
= 0;
369 struct libmnt_fs
*fs
;
374 assert(proc_self_mountinfo
);
376 if ((flags_mask
& ~MS_CONVERTIBLE_FLAGS
) == 0 && !skip_mount_set_attr
) {
377 /* Let's take a shortcut for all the flags we know how to convert into mount_setattr() flags */
379 if (mount_setattr(AT_FDCWD
, path
, AT_SYMLINK_NOFOLLOW
,
380 &(struct mount_attr
) {
381 .attr_set
= ms_flags_to_mount_attr(new_flags
& flags_mask
),
382 .attr_clr
= ms_flags_to_mount_attr(~new_flags
& flags_mask
),
383 }, MOUNT_ATTR_SIZE_VER0
) < 0) {
385 log_debug_errno(errno
, "mount_setattr() didn't work, falling back to classic remounting: %m");
387 if (ERRNO_IS_NOT_SUPPORTED(errno
)) /* if not supported, then don't bother at all anymore */
388 skip_mount_set_attr
= true;
390 return 0; /* Nice, this worked! */
393 rewind(proc_self_mountinfo
);
395 table
= mnt_new_table();
399 r
= mnt_table_parse_stream(table
, proc_self_mountinfo
, "/proc/self/mountinfo");
403 fs
= mnt_table_find_target(table
, path
, MNT_ITER_FORWARD
);
405 if (laccess(path
, F_OK
) < 0) /* Hmm, it's not in the mount table, but does it exist at all? */
408 return -EINVAL
; /* Not a mount point we recognize */
411 opts
= mnt_fs_get_vfs_options(fs
);
413 r
= mnt_optstr_get_flags(opts
, &flags
, mnt_get_builtin_optmap(MNT_LINUX_MAP
));
415 log_debug_errno(r
, "Could not get flags for '%s', ignoring: %m", path
);
418 r
= mount_nofollow(NULL
, path
, NULL
, ((flags
& ~flags_mask
)|MS_BIND
|MS_REMOUNT
|new_flags
) & ~MS_RELATIME
, NULL
);
420 if (((flags
^ new_flags
) & flags_mask
& ~MS_RELATIME
) != 0) /* Ignore MS_RELATIME again,
421 * since kernel adds it in
422 * everywhere, because it's the
426 /* Let's handle redundant remounts gracefully */
427 log_debug_errno(r
, "Failed to remount '%s' but flags already match what we want, ignoring: %m", path
);
433 static int mount_switch_root_pivot(const char *path
, int fd_newroot
) {
434 _cleanup_close_
int fd_oldroot
= -EBADF
;
436 fd_oldroot
= open("/", O_PATH
|O_DIRECTORY
|O_CLOEXEC
|O_NOFOLLOW
);
438 return log_debug_errno(errno
, "Failed to open old rootfs");
440 /* Let the kernel tuck the new root under the old one. */
441 if (pivot_root(".", ".") < 0)
442 return log_debug_errno(errno
, "Failed to pivot root to new rootfs '%s': %m", path
);
444 /* At this point the new root is tucked under the old root. If we want
445 * to unmount it we cannot be fchdir()ed into it. So escape back to the
447 if (fchdir(fd_oldroot
) < 0)
448 return log_debug_errno(errno
, "Failed to change back to old rootfs: %m");
450 /* Note, usually we should set mount propagation up here but we'll
451 * assume that the caller has already done that. */
453 /* Get rid of the old root and reveal our brand new root. */
454 if (umount2(".", MNT_DETACH
) < 0)
455 return log_debug_errno(errno
, "Failed to unmount old rootfs: %m");
457 if (fchdir(fd_newroot
) < 0)
458 return log_debug_errno(errno
, "Failed to switch to new rootfs '%s': %m", path
);
463 static int mount_switch_root_move(const char *path
) {
464 if (mount(path
, "/", NULL
, MS_MOVE
, NULL
) < 0)
465 return log_debug_errno(errno
, "Failed to move new rootfs '%s': %m", path
);
468 return log_debug_errno(errno
, "Failed to chroot to new rootfs '%s': %m", path
);
471 return log_debug_errno(errno
, "Failed to chdir to new rootfs '%s': %m", path
);
476 int mount_switch_root(const char *path
, unsigned long mount_propagation_flag
) {
477 _cleanup_close_
int fd_newroot
= -EBADF
;
481 assert(mount_propagation_flag_is_valid(mount_propagation_flag
));
483 fd_newroot
= open(path
, O_PATH
|O_DIRECTORY
|O_CLOEXEC
|O_NOFOLLOW
);
485 return log_debug_errno(errno
, "Failed to open new rootfs '%s': %m", path
);
487 /* Change into the new rootfs. */
488 if (fchdir(fd_newroot
) < 0)
489 return log_debug_errno(errno
, "Failed to change into new rootfs '%s': %m", path
);
491 r
= mount_switch_root_pivot(path
, fd_newroot
);
493 /* Failed to pivot_root() fallback to MS_MOVE. For example, this may happen if the
494 * rootfs is an initramfs in which case pivot_root() isn't supported. */
495 log_debug_errno(r
, "Failed to pivot into new rootfs '%s': %m", path
);
496 r
= mount_switch_root_move(path
);
499 return log_debug_errno(r
, "Failed to switch to new rootfs '%s': %m", path
);
501 /* Finally, let's establish the requested propagation flags. */
502 if (mount_propagation_flag
== 0)
505 if (mount(NULL
, ".", NULL
, mount_propagation_flag
| MS_REC
, 0) < 0)
506 return log_debug_errno(errno
, "Failed to turn new rootfs '%s' into %s mount: %m",
507 mount_propagation_flag_to_string(mount_propagation_flag
), path
);
512 int repeat_unmount(const char *path
, int flags
) {
517 /* If there are multiple mounts on a mount point, this
518 * removes them all */
521 if (umount2(path
, flags
) < 0) {
533 int mode_to_inaccessible_node(
534 const char *runtime_dir
,
538 /* This function maps a node type to a corresponding inaccessible file node. These nodes are created
539 * during early boot by PID 1. In some cases we lacked the privs to create the character and block
540 * devices (maybe because we run in an userns environment, or miss CAP_SYS_MKNOD, or run with a
541 * devices policy that excludes device nodes with major and minor of 0), but that's fine, in that
542 * case we use an AF_UNIX file node instead, which is not the same, but close enough for most
543 * uses. And most importantly, the kernel allows bind mounts from socket nodes to any non-directory
544 * file nodes, and that's the most important thing that matters.
546 * Note that the runtime directory argument shall be the top-level runtime directory, i.e. /run/ if
547 * we operate in system context and $XDG_RUNTIME_DIR if we operate in user context. */
549 _cleanup_free_
char *d
= NULL
;
550 const char *node
= NULL
;
555 runtime_dir
= "/run";
557 switch (mode
& S_IFMT
) {
559 node
= "/systemd/inaccessible/reg";
563 node
= "/systemd/inaccessible/dir";
567 node
= "/systemd/inaccessible/chr";
571 node
= "/systemd/inaccessible/blk";
575 node
= "/systemd/inaccessible/fifo";
579 node
= "/systemd/inaccessible/sock";
585 d
= path_join(runtime_dir
, node
);
589 /* On new kernels unprivileged users are permitted to create 0:0 char device nodes (because they also
590 * act as whiteout inode for overlayfs), but no other char or block device nodes. On old kernels no
591 * device node whatsoever may be created by unprivileged processes. Hence, if the caller asks for the
592 * inaccessible block device node let's see if the block device node actually exists, and if not,
593 * fall back to the character device node. From there fall back to the socket device node. This means
594 * in the best case we'll get the right device node type — but if not we'll hopefully at least get a
595 * device node at all. */
598 access(d
, F_OK
) < 0 && errno
== ENOENT
) {
600 d
= path_join(runtime_dir
, "/systemd/inaccessible/chr");
605 if (IN_SET(mode
& S_IFMT
, S_IFBLK
, S_IFCHR
) &&
606 access(d
, F_OK
) < 0 && errno
== ENOENT
) {
608 d
= path_join(runtime_dir
, "/systemd/inaccessible/sock");
617 int mount_flags_to_string(unsigned long flags
, char **ret
) {
618 static const struct {
622 { .flag
= MS_RDONLY
, .name
= "MS_RDONLY", },
623 { .flag
= MS_NOSUID
, .name
= "MS_NOSUID", },
624 { .flag
= MS_NODEV
, .name
= "MS_NODEV", },
625 { .flag
= MS_NOEXEC
, .name
= "MS_NOEXEC", },
626 { .flag
= MS_SYNCHRONOUS
, .name
= "MS_SYNCHRONOUS", },
627 { .flag
= MS_REMOUNT
, .name
= "MS_REMOUNT", },
628 { .flag
= MS_MANDLOCK
, .name
= "MS_MANDLOCK", },
629 { .flag
= MS_DIRSYNC
, .name
= "MS_DIRSYNC", },
630 { .flag
= MS_NOSYMFOLLOW
, .name
= "MS_NOSYMFOLLOW", },
631 { .flag
= MS_NOATIME
, .name
= "MS_NOATIME", },
632 { .flag
= MS_NODIRATIME
, .name
= "MS_NODIRATIME", },
633 { .flag
= MS_BIND
, .name
= "MS_BIND", },
634 { .flag
= MS_MOVE
, .name
= "MS_MOVE", },
635 { .flag
= MS_REC
, .name
= "MS_REC", },
636 { .flag
= MS_SILENT
, .name
= "MS_SILENT", },
637 { .flag
= MS_POSIXACL
, .name
= "MS_POSIXACL", },
638 { .flag
= MS_UNBINDABLE
, .name
= "MS_UNBINDABLE", },
639 { .flag
= MS_PRIVATE
, .name
= "MS_PRIVATE", },
640 { .flag
= MS_SLAVE
, .name
= "MS_SLAVE", },
641 { .flag
= MS_SHARED
, .name
= "MS_SHARED", },
642 { .flag
= MS_RELATIME
, .name
= "MS_RELATIME", },
643 { .flag
= MS_KERNMOUNT
, .name
= "MS_KERNMOUNT", },
644 { .flag
= MS_I_VERSION
, .name
= "MS_I_VERSION", },
645 { .flag
= MS_STRICTATIME
, .name
= "MS_STRICTATIME", },
646 { .flag
= MS_LAZYTIME
, .name
= "MS_LAZYTIME", },
648 _cleanup_free_
char *str
= NULL
;
652 for (size_t i
= 0; i
< ELEMENTSOF(map
); i
++)
653 if (flags
& map
[i
].flag
) {
654 if (!strextend_with_separator(&str
, "|", map
[i
].name
))
656 flags
&= ~map
[i
].flag
;
659 if (!str
|| flags
!= 0)
660 if (strextendf_with_separator(&str
, "|", "%lx", flags
) < 0)
663 *ret
= TAKE_PTR(str
);
667 int mount_verbose_full(
674 bool follow_symlink
) {
676 _cleanup_free_
char *fl
= NULL
, *o
= NULL
;
680 r
= mount_option_mangle(options
, flags
, &f
, &o
);
682 return log_full_errno(error_log_level
, r
,
683 "Failed to mangle mount options %s: %m",
686 (void) mount_flags_to_string(f
, &fl
);
688 if ((f
& MS_REMOUNT
) && !what
&& !type
)
689 log_debug("Remounting %s (%s \"%s\")...",
690 where
, strnull(fl
), strempty(o
));
691 else if (!what
&& !type
)
692 log_debug("Mounting %s (%s \"%s\")...",
693 where
, strnull(fl
), strempty(o
));
694 else if ((f
& MS_BIND
) && !type
)
695 log_debug("Bind-mounting %s on %s (%s \"%s\")...",
696 what
, where
, strnull(fl
), strempty(o
));
697 else if (f
& MS_MOVE
)
698 log_debug("Moving mount %s %s %s (%s \"%s\")...",
699 what
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), where
, strnull(fl
), strempty(o
));
701 log_debug("Mounting %s (%s) on %s (%s \"%s\")...",
702 strna(what
), strna(type
), where
, strnull(fl
), strempty(o
));
705 r
= RET_NERRNO(mount(what
, where
, type
, f
, o
));
707 r
= mount_nofollow(what
, where
, type
, f
, o
);
709 return log_full_errno(error_log_level
, r
,
710 "Failed to mount %s (type %s) on %s (%s \"%s\"): %m",
711 strna(what
), strna(type
), where
, strnull(fl
), strempty(o
));
722 log_debug("Umounting %s...", what
);
724 if (umount2(what
, flags
) < 0)
725 return log_full_errno(error_log_level
, errno
,
726 "Failed to unmount %s: %m", what
);
731 int mount_option_mangle(
733 unsigned long mount_flags
,
734 unsigned long *ret_mount_flags
,
735 char **ret_remaining_options
) {
737 const struct libmnt_optmap
*map
;
738 _cleanup_free_
char *ret
= NULL
;
741 /* This extracts mount flags from the mount options, and stores
742 * non-mount-flag options to '*ret_remaining_options'.
744 * "rw,nosuid,nodev,relatime,size=1630748k,mode=0700,uid=1000,gid=1000"
745 * is split to MS_NOSUID|MS_NODEV|MS_RELATIME and
746 * "size=1630748k,mode=0700,uid=1000,gid=1000".
747 * See more examples in test-mount-util.c.
749 * If 'options' does not contain any non-mount-flag options,
750 * then '*ret_remaining_options' is set to NULL instead of empty string.
751 * The validity of options stored in '*ret_remaining_options' is not checked.
752 * If 'options' is NULL, this just copies 'mount_flags' to *ret_mount_flags. */
754 assert(ret_mount_flags
);
755 assert(ret_remaining_options
);
757 map
= mnt_get_builtin_optmap(MNT_LINUX_MAP
);
761 for (const char *p
= options
;;) {
762 _cleanup_free_
char *word
= NULL
;
763 const struct libmnt_optmap
*ent
;
765 r
= extract_first_word(&p
, &word
, ",", EXTRACT_KEEP_QUOTE
);
771 for (ent
= map
; ent
->name
; ent
++) {
772 /* All entries in MNT_LINUX_MAP do not take any argument.
773 * Thus, ent->name does not contain "=" or "[=]". */
774 if (!streq(word
, ent
->name
))
777 if (!(ent
->mask
& MNT_INVERT
))
778 mount_flags
|= ent
->id
;
779 else if (mount_flags
& ent
->id
)
780 mount_flags
^= ent
->id
;
785 /* If 'word' is not a mount flag, then store it in '*ret_remaining_options'. */
787 !startswith_no_case(word
, "x-") &&
788 !strextend_with_separator(&ret
, ",", word
))
792 *ret_mount_flags
= mount_flags
;
793 *ret_remaining_options
= TAKE_PTR(ret
);
798 static int mount_in_namespace(
800 const char *propagate_path
,
801 const char *incoming_path
,
805 bool make_file_or_directory
,
806 const MountOptions
*options
,
809 _cleanup_close_pair_
int errno_pipe_fd
[2] = PIPE_EBADF
;
810 _cleanup_close_
int mntns_fd
= -EBADF
, root_fd
= -EBADF
, pidns_fd
= -EBADF
, chased_src_fd
= -EBADF
;
811 char mount_slave
[] = "/tmp/propagate.XXXXXX", *mount_tmp
, *mount_outside
, *p
;
812 bool mount_slave_created
= false, mount_slave_mounted
= false,
813 mount_tmp_created
= false, mount_tmp_mounted
= false,
814 mount_outside_created
= false, mount_outside_mounted
= false;
815 _cleanup_free_
char *chased_src_path
= NULL
;
821 assert(propagate_path
);
822 assert(incoming_path
);
825 assert(!options
|| is_image
);
827 r
= namespace_open(target
, &pidns_fd
, &mntns_fd
, NULL
, NULL
, &root_fd
);
829 return log_debug_errno(r
, "Failed to retrieve FDs of the target process' namespace: %m");
831 r
= in_same_namespace(target
, 0, NAMESPACE_MOUNT
);
833 return log_debug_errno(r
, "Failed to determine if mount namespaces are equal: %m");
834 /* We can't add new mounts at runtime if the process wasn't started in a namespace */
836 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to activate bind mount in target, not running in a mount namespace");
838 /* One day, when bind mounting /proc/self/fd/n works across namespace boundaries we should rework
839 * this logic to make use of it... */
841 p
= strjoina(propagate_path
, "/");
842 r
= laccess(p
, F_OK
);
844 return log_debug_errno(r
== -ENOENT
? SYNTHETIC_ERRNO(EOPNOTSUPP
) : r
, "Target does not allow propagation of mount points");
846 r
= chase_symlinks(src
, NULL
, 0, &chased_src_path
, &chased_src_fd
);
848 return log_debug_errno(r
, "Failed to resolve source path of %s: %m", src
);
849 log_debug("Chased source path of %s to %s", src
, chased_src_path
);
851 if (fstat(chased_src_fd
, &st
) < 0)
852 return log_debug_errno(errno
, "Failed to stat() resolved source path %s: %m", src
);
853 if (S_ISLNK(st
.st_mode
)) /* This shouldn't really happen, given that we just chased the symlinks above, but let's better be safe… */
854 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "Source directory %s can't be a symbolic link", src
);
856 /* Our goal is to install a new bind mount into the container,
857 possibly read-only. This is irritatingly complex
858 unfortunately, currently.
860 First, we start by creating a private playground in /tmp,
861 that we can mount MS_SLAVE. (Which is necessary, since
862 MS_MOVE cannot be applied to mounts with MS_SHARED parent
865 if (!mkdtemp(mount_slave
))
866 return log_debug_errno(errno
, "Failed to create playground %s: %m", mount_slave
);
868 mount_slave_created
= true;
870 r
= mount_nofollow_verbose(LOG_DEBUG
, mount_slave
, mount_slave
, NULL
, MS_BIND
, NULL
);
874 mount_slave_mounted
= true;
876 r
= mount_nofollow_verbose(LOG_DEBUG
, NULL
, mount_slave
, NULL
, MS_SLAVE
, NULL
);
880 /* Second, we mount the source file or directory to a directory inside of our MS_SLAVE playground. */
881 mount_tmp
= strjoina(mount_slave
, "/mount");
883 r
= mkdir_p(mount_tmp
, 0700);
885 r
= make_mount_point_inode_from_stat(&st
, mount_tmp
, 0700);
887 log_debug_errno(r
, "Failed to create temporary mount point %s: %m", mount_tmp
);
891 mount_tmp_created
= true;
894 r
= verity_dissect_and_mount(chased_src_fd
, chased_src_path
, mount_tmp
, options
, NULL
, NULL
, NULL
, NULL
);
896 r
= mount_follow_verbose(LOG_DEBUG
, FORMAT_PROC_FD_PATH(chased_src_fd
), mount_tmp
, NULL
, MS_BIND
, NULL
);
900 mount_tmp_mounted
= true;
902 /* Third, we remount the new bind mount read-only if requested. */
904 r
= mount_nofollow_verbose(LOG_DEBUG
, NULL
, mount_tmp
, NULL
, MS_BIND
|MS_REMOUNT
|MS_RDONLY
, NULL
);
909 /* Fourth, we move the new bind mount into the propagation directory. This way it will appear there read-only
912 mount_outside
= strjoina(propagate_path
, "/XXXXXX");
913 if (is_image
|| S_ISDIR(st
.st_mode
))
914 r
= mkdtemp(mount_outside
) ? 0 : -errno
;
916 r
= mkostemp_safe(mount_outside
);
920 log_debug_errno(r
, "Cannot create propagation file or directory %s: %m", mount_outside
);
924 mount_outside_created
= true;
926 r
= mount_nofollow_verbose(LOG_DEBUG
, mount_tmp
, mount_outside
, NULL
, MS_MOVE
, NULL
);
930 mount_outside_mounted
= true;
931 mount_tmp_mounted
= false;
933 if (is_image
|| S_ISDIR(st
.st_mode
))
934 (void) rmdir(mount_tmp
);
936 (void) unlink(mount_tmp
);
937 mount_tmp_created
= false;
939 (void) umount_verbose(LOG_DEBUG
, mount_slave
, UMOUNT_NOFOLLOW
);
940 mount_slave_mounted
= false;
942 (void) rmdir(mount_slave
);
943 mount_slave_created
= false;
945 if (pipe2(errno_pipe_fd
, O_CLOEXEC
|O_NONBLOCK
) < 0) {
946 log_debug_errno(errno
, "Failed to create pipe: %m");
950 r
= namespace_fork("(sd-bindmnt)", "(sd-bindmnt-inner)", NULL
, 0, FORK_RESET_SIGNALS
|FORK_DEATHSIG
,
951 pidns_fd
, mntns_fd
, -1, -1, root_fd
, &child
);
955 const char *mount_inside
;
957 errno_pipe_fd
[0] = safe_close(errno_pipe_fd
[0]);
959 if (make_file_or_directory
) {
961 (void) mkdir_parents(dest
, 0755);
962 (void) make_mount_point_inode_from_stat(&st
, dest
, 0700);
964 (void) mkdir_p(dest
, 0755);
967 /* Fifth, move the mount to the right place inside */
968 mount_inside
= strjoina(incoming_path
, basename(mount_outside
));
969 r
= mount_nofollow_verbose(LOG_ERR
, mount_inside
, dest
, NULL
, MS_MOVE
, NULL
);
976 (void) write(errno_pipe_fd
[1], &r
, sizeof(r
));
977 errno_pipe_fd
[1] = safe_close(errno_pipe_fd
[1]);
982 errno_pipe_fd
[1] = safe_close(errno_pipe_fd
[1]);
984 r
= wait_for_terminate_and_check("(sd-bindmnt)", child
, 0);
986 log_debug_errno(r
, "Failed to wait for child: %m");
989 if (r
!= EXIT_SUCCESS
) {
990 if (read(errno_pipe_fd
[0], &r
, sizeof(r
)) == sizeof(r
))
991 log_debug_errno(r
, "Failed to mount: %m");
993 log_debug("Child failed.");
998 if (mount_outside_mounted
)
999 (void) umount_verbose(LOG_DEBUG
, mount_outside
, UMOUNT_NOFOLLOW
);
1000 if (mount_outside_created
) {
1001 if (is_image
|| S_ISDIR(st
.st_mode
))
1002 (void) rmdir(mount_outside
);
1004 (void) unlink(mount_outside
);
1007 if (mount_tmp_mounted
)
1008 (void) umount_verbose(LOG_DEBUG
, mount_tmp
, UMOUNT_NOFOLLOW
);
1009 if (mount_tmp_created
) {
1010 if (is_image
|| S_ISDIR(st
.st_mode
))
1011 (void) rmdir(mount_tmp
);
1013 (void) unlink(mount_tmp
);
1016 if (mount_slave_mounted
)
1017 (void) umount_verbose(LOG_DEBUG
, mount_slave
, UMOUNT_NOFOLLOW
);
1018 if (mount_slave_created
)
1019 (void) rmdir(mount_slave
);
1024 int bind_mount_in_namespace(
1026 const char *propagate_path
,
1027 const char *incoming_path
,
1031 bool make_file_or_directory
) {
1033 return mount_in_namespace(target
, propagate_path
, incoming_path
, src
, dest
, read_only
, make_file_or_directory
, NULL
, false);
1036 int mount_image_in_namespace(
1038 const char *propagate_path
,
1039 const char *incoming_path
,
1043 bool make_file_or_directory
,
1044 const MountOptions
*options
) {
1046 return mount_in_namespace(target
, propagate_path
, incoming_path
, src
, dest
, read_only
, make_file_or_directory
, options
, true);
1049 int make_mount_point(const char *path
) {
1054 /* If 'path' is already a mount point, does nothing and returns 0. If it is not it makes it one, and returns 1. */
1056 r
= path_is_mount_point(path
, NULL
, 0);
1058 return log_debug_errno(r
, "Failed to determine whether '%s' is a mount point: %m", path
);
1062 r
= mount_nofollow_verbose(LOG_DEBUG
, path
, path
, NULL
, MS_BIND
|MS_REC
, NULL
);
1069 static int make_userns(uid_t uid_shift
, uid_t uid_range
, uid_t owner
, RemountIdmapping idmapping
) {
1070 _cleanup_close_
int userns_fd
= -EBADF
;
1071 _cleanup_free_
char *line
= NULL
;
1073 /* Allocates a userns file descriptor with the mapping we need. For this we'll fork off a child
1074 * process whose only purpose is to give us a new user namespace. It's killed when we got it. */
1076 if (IN_SET(idmapping
, REMOUNT_IDMAPPING_NONE
, REMOUNT_IDMAPPING_HOST_ROOT
)) {
1077 if (asprintf(&line
, UID_FMT
" " UID_FMT
" " UID_FMT
"\n", 0u, uid_shift
, uid_range
) < 0)
1078 return log_oom_debug();
1080 /* If requested we'll include an entry in the mapping so that the host root user can make
1081 * changes to the uidmapped mount like it normally would. Specifically, we'll map the user
1082 * with UID_MAPPED_ROOT on the backing fs to UID 0. This is useful, since nspawn code wants
1083 * to create various missing inodes in the OS tree before booting into it, and this becomes
1084 * very easy and straightforward to do if it can just do it under its own regular UID. Note
1085 * that in that case the container's runtime uidmap (i.e. the one the container payload
1086 * processes run in) will leave this UID unmapped, i.e. if we accidentally leave files owned
1087 * by host root in the already uidmapped tree around they'll show up as owned by 'nobody',
1088 * which is safe. (Of course, we shouldn't leave such inodes around, but always chown() them
1089 * to the container's own UID range, but it's good to have a safety net, in case we
1091 if (idmapping
== REMOUNT_IDMAPPING_HOST_ROOT
)
1092 if (strextendf(&line
,
1093 UID_FMT
" " UID_FMT
" " UID_FMT
"\n",
1094 UID_MAPPED_ROOT
, 0u, 1u) < 0)
1095 return log_oom_debug();
1098 if (idmapping
== REMOUNT_IDMAPPING_HOST_OWNER
) {
1099 /* Remap the owner of the bind mounted directory to the root user within the container. This
1100 * way every file written by root within the container to the bind-mounted directory will
1101 * be owned by the original user. All other user will remain unmapped. */
1102 if (asprintf(&line
, UID_FMT
" " UID_FMT
" " UID_FMT
"\n", owner
, uid_shift
, 1u) < 0)
1103 return log_oom_debug();
1106 /* We always assign the same UID and GID ranges */
1107 userns_fd
= userns_acquire(line
, line
);
1109 return log_debug_errno(userns_fd
, "Failed to acquire new userns: %m");
1111 return TAKE_FD(userns_fd
);
1119 RemountIdmapping idmapping
) {
1121 _cleanup_close_
int mount_fd
= -EBADF
, userns_fd
= -EBADF
;
1126 if (!userns_shift_range_valid(uid_shift
, uid_range
))
1129 /* Clone the mount point */
1130 mount_fd
= open_tree(-1, p
, OPEN_TREE_CLONE
| OPEN_TREE_CLOEXEC
);
1132 return log_debug_errno(errno
, "Failed to open tree of mounted filesystem '%s': %m", p
);
1134 /* Create a user namespace mapping */
1135 userns_fd
= make_userns(uid_shift
, uid_range
, owner
, idmapping
);
1139 /* Set the user namespace mapping attribute on the cloned mount point */
1140 if (mount_setattr(mount_fd
, "", AT_EMPTY_PATH
| AT_RECURSIVE
,
1141 &(struct mount_attr
) {
1142 .attr_set
= MOUNT_ATTR_IDMAP
,
1143 .userns_fd
= userns_fd
,
1144 }, sizeof(struct mount_attr
)) < 0)
1145 return log_debug_errno(errno
, "Failed to change bind mount attributes for '%s': %m", p
);
1147 /* Remove the old mount point */
1148 r
= umount_verbose(LOG_DEBUG
, p
, UMOUNT_NOFOLLOW
);
1152 /* And place the cloned version in its place */
1153 if (move_mount(mount_fd
, "", -1, p
, MOVE_MOUNT_F_EMPTY_PATH
) < 0)
1154 return log_debug_errno(errno
, "Failed to attach UID mapped mount to '%s': %m", p
);
1159 int make_mount_point_inode_from_stat(const struct stat
*st
, const char *dest
, mode_t mode
) {
1163 if (S_ISDIR(st
->st_mode
))
1164 return mkdir_label(dest
, mode
);
1166 return RET_NERRNO(mknod(dest
, S_IFREG
|(mode
& ~0111), 0));
1169 int make_mount_point_inode_from_path(const char *source
, const char *dest
, mode_t mode
) {
1175 if (stat(source
, &st
) < 0)
1178 return make_mount_point_inode_from_stat(&st
, dest
, mode
);