1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
8 #include "alloc-util.h"
10 #include "dissect-image.h"
11 #include "errno-util.h"
12 #include "extract-word.h"
15 #include "format-util.h"
17 #include "fstab-util.h"
18 #include "glyph-util.h"
20 #include "libmount-util.h"
22 #include "missing_syscall.h"
23 #include "mkdir-label.h"
24 #include "mount-util.h"
25 #include "mountpoint-util.h"
26 #include "namespace-util.h"
28 #include "path-util.h"
30 #include "process-util.h"
32 #include "sort-util.h"
33 #include "stat-util.h"
34 #include "string-util.h"
36 #include "tmpfile-util.h"
37 #include "user-util.h"
39 int umount_recursive_full(const char *prefix
, int flags
, char **keep
) {
40 _cleanup_fclose_
FILE *f
= NULL
;
43 /* Try to umount everything recursively below a directory. Also, take care of stacked mounts, and
44 * keep unmounting them until they are gone. */
46 f
= fopen("/proc/self/mountinfo", "re"); /* Pin the file, in case we unmount /proc/ as part of the logic here */
48 return log_debug_errno(errno
, "Failed to open %s: %m", "/proc/self/mountinfo");
51 _cleanup_(mnt_free_tablep
) struct libmnt_table
*table
= NULL
;
52 _cleanup_(mnt_free_iterp
) struct libmnt_iter
*iter
= NULL
;
55 r
= libmount_parse_mountinfo(f
, &table
, &iter
);
57 return log_debug_errno(r
, "Failed to parse /proc/self/mountinfo: %m");
60 bool shall_keep
= false;
64 r
= mnt_table_next_fs(table
, iter
, &fs
);
68 return log_debug_errno(r
, "Failed to get next entry from /proc/self/mountinfo: %m");
70 path
= mnt_fs_get_target(fs
);
74 if (prefix
&& !path_startswith(path
, prefix
)) {
75 // FIXME: This is extremely noisy, we're probably doing something very wrong
76 // to trigger this so often, needs more investigation.
77 // log_trace("Not unmounting %s, outside of prefix: %s", path, prefix);
82 /* Match against anything in the path to the dirs to keep, or below the dirs to keep */
83 if (path_startswith(path
, *k
) || path_startswith(*k
, path
)) {
88 log_debug("Not unmounting %s, referenced by keep list.", path
);
92 if (umount2(path
, flags
| UMOUNT_NOFOLLOW
) < 0) {
93 log_debug_errno(errno
, "Failed to umount %s, ignoring: %m", path
);
97 log_trace("Successfully unmounted %s", path
);
114 #define MS_CONVERTIBLE_FLAGS (MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_NOSYMFOLLOW)
116 static uint64_t ms_flags_to_mount_attr(unsigned long a
) {
119 if (FLAGS_SET(a
, MS_RDONLY
))
120 f
|= MOUNT_ATTR_RDONLY
;
122 if (FLAGS_SET(a
, MS_NOSUID
))
123 f
|= MOUNT_ATTR_NOSUID
;
125 if (FLAGS_SET(a
, MS_NODEV
))
126 f
|= MOUNT_ATTR_NODEV
;
128 if (FLAGS_SET(a
, MS_NOEXEC
))
129 f
|= MOUNT_ATTR_NOEXEC
;
131 if (FLAGS_SET(a
, MS_NOSYMFOLLOW
))
132 f
|= MOUNT_ATTR_NOSYMFOLLOW
;
137 static bool skip_mount_set_attr
= false;
139 /* Use this function only if you do not have direct access to /proc/self/mountinfo but the caller can open it
140 * for you. This is the case when /proc is masked or not mounted. Otherwise, use bind_remount_recursive. */
141 int bind_remount_recursive_with_mountinfo(
143 unsigned long new_flags
,
144 unsigned long flags_mask
,
146 FILE *proc_self_mountinfo
) {
148 _cleanup_fclose_
FILE *proc_self_mountinfo_opened
= NULL
;
149 _cleanup_set_free_ Set
*done
= NULL
;
150 unsigned n_tries
= 0;
155 if ((flags_mask
& ~MS_CONVERTIBLE_FLAGS
) == 0 && strv_isempty(deny_list
) && !skip_mount_set_attr
) {
156 /* Let's take a shortcut for all the flags we know how to convert into mount_setattr() flags */
158 if (mount_setattr(AT_FDCWD
, prefix
, AT_SYMLINK_NOFOLLOW
|AT_RECURSIVE
,
159 &(struct mount_attr
) {
160 .attr_set
= ms_flags_to_mount_attr(new_flags
& flags_mask
),
161 .attr_clr
= ms_flags_to_mount_attr(~new_flags
& flags_mask
),
162 }, MOUNT_ATTR_SIZE_VER0
) < 0) {
164 log_debug_errno(errno
, "mount_setattr() failed, falling back to classic remounting: %m");
166 /* We fall through to classic behaviour if not supported (i.e. kernel < 5.12). We
167 * also do this for all other kinds of errors since they are so many different, and
168 * mount_setattr() has no graceful mode where it continues despite seeing errors one
169 * some mounts, but we want that. Moreover mount_setattr() only works on the mount
170 * point inode itself, not a non-mount point inode, and we want to support arbitrary
173 if (ERRNO_IS_NOT_SUPPORTED(errno
)) /* if not supported, then don't bother at all anymore */
174 skip_mount_set_attr
= true;
176 return 0; /* Nice, this worked! */
179 if (!proc_self_mountinfo
) {
180 r
= fopen_unlocked("/proc/self/mountinfo", "re", &proc_self_mountinfo_opened
);
184 proc_self_mountinfo
= proc_self_mountinfo_opened
;
187 /* Recursively remount a directory (and all its submounts) with desired flags (MS_READONLY,
188 * MS_NOSUID, MS_NOEXEC). If the directory is already mounted, we reuse the mount and simply mark it
189 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write operation), ditto for other flags. If it
190 * isn't we first make it one. Afterwards we apply (or remove) the flags to all submounts we can
191 * access, too. When mounts are stacked on the same mount point we only care for each individual
192 * "top-level" mount on each point, as we cannot influence/access the underlying mounts anyway. We do
193 * not have any effect on future submounts that might get propagated, they might be writable
194 * etc. This includes future submounts that have been triggered via autofs. Also note that we can't
195 * operate atomically here. Mounts established while we process the tree might or might not get
196 * noticed and thus might or might not be covered.
198 * If the "deny_list" parameter is specified it may contain a list of subtrees to exclude from the
199 * remount operation. Note that we'll ignore the deny list for the top-level path. */
202 _cleanup_(mnt_free_tablep
) struct libmnt_table
*table
= NULL
;
203 _cleanup_(mnt_free_iterp
) struct libmnt_iter
*iter
= NULL
;
204 _cleanup_hashmap_free_ Hashmap
*todo
= NULL
;
205 bool top_autofs
= false;
207 if (n_tries
++ >= 32) /* Let's not retry this loop forever */
210 rewind(proc_self_mountinfo
);
212 r
= libmount_parse_mountinfo(proc_self_mountinfo
, &table
, &iter
);
214 return log_debug_errno(r
, "Failed to parse /proc/self/mountinfo: %m");
217 _cleanup_free_
char *d
= NULL
;
218 const char *path
, *type
, *opts
;
219 unsigned long flags
= 0;
220 struct libmnt_fs
*fs
;
222 r
= mnt_table_next_fs(table
, iter
, &fs
);
223 if (r
== 1) /* EOF */
226 return log_debug_errno(r
, "Failed to get next entry from /proc/self/mountinfo: %m");
228 path
= mnt_fs_get_target(fs
);
232 if (!path_startswith(path
, prefix
))
235 type
= mnt_fs_get_fstype(fs
);
239 /* Let's ignore autofs mounts. If they aren't triggered yet, we want to avoid
240 * triggering them, as we don't make any guarantees for future submounts anyway. If
241 * they are already triggered, then we will find another entry for this. */
242 if (streq(type
, "autofs")) {
243 top_autofs
= top_autofs
|| path_equal(path
, prefix
);
247 if (set_contains(done
, path
))
250 /* Ignore this mount if it is deny-listed, but only if it isn't the top-level mount
251 * we shall operate on. */
252 if (!path_equal(path
, prefix
)) {
253 bool deny_listed
= false;
255 STRV_FOREACH(i
, deny_list
) {
256 if (path_equal(*i
, prefix
))
259 if (!path_startswith(*i
, prefix
))
262 if (path_startswith(path
, *i
)) {
264 log_trace("Not remounting %s deny-listed by %s, called for %s", path
, *i
, prefix
);
273 opts
= mnt_fs_get_vfs_options(fs
);
275 r
= mnt_optstr_get_flags(opts
, &flags
, mnt_get_builtin_optmap(MNT_LINUX_MAP
));
277 log_debug_errno(r
, "Could not get flags for '%s', ignoring: %m", path
);
284 r
= hashmap_ensure_put(&todo
, &path_hash_ops_free
, d
, ULONG_TO_PTR(flags
));
286 /* If the same path was recorded, but with different mount flags, update it:
287 * it means a mount point is overmounted, and libmount returns the "bottom" (or
288 * older one) first, but we want to reapply the flags from the "top" (or newer
289 * one). See: https://github.com/systemd/systemd/issues/20032
290 * Note that this shouldn't really fail, as we were just told that the key
291 * exists, and it's an update so we want 'd' to be freed immediately. */
292 r
= hashmap_update(todo
, d
, ULONG_TO_PTR(flags
));
299 /* Check if the top-level directory was among what we have seen so far. For that check both
300 * 'done' and 'todo'. Also check 'top_autofs' because if the top-level dir is an autofs we'll
301 * not include it in either set but will set this bool. */
302 if (!set_contains(done
, prefix
) &&
303 !(top_autofs
|| hashmap_contains(todo
, prefix
))) {
305 /* The prefix directory itself is not yet a mount, make it one. */
306 r
= mount_nofollow(prefix
, prefix
, NULL
, MS_BIND
|MS_REC
, NULL
);
310 /* Immediately rescan, so that we pick up the new mount's flags */
314 /* If we have no submounts to process anymore, we are done */
315 if (hashmap_isempty(todo
))
322 /* Take the first mount from our list of mounts to still process */
323 flags
= PTR_TO_ULONG(hashmap_steal_first_key_and_value(todo
, (void**) &x
));
327 r
= set_ensure_consume(&done
, &path_hash_ops_free
, x
);
328 if (IN_SET(r
, 0, -EEXIST
))
329 continue; /* Already done */
333 /* Now, remount this with the new flags set, but exclude MS_RELATIME from it. (It's
334 * the default anyway, thus redundant, and in userns we'll get an error if we try to
335 * explicitly enable it) */
336 r
= mount_nofollow(NULL
, x
, NULL
, ((flags
& ~flags_mask
)|MS_BIND
|MS_REMOUNT
|new_flags
) & ~MS_RELATIME
, NULL
);
340 /* OK, so the remount of this entry failed. We'll ultimately ignore this in
341 * almost all cases (there are simply so many reasons why this can fail,
342 * think autofs, NFS, FUSE, …), but let's generate useful debug messages at
345 q
= path_is_mount_point(x
);
346 if (IN_SET(q
, 0, -ENOENT
)) {
347 /* Hmm, whaaaa? The mount point is not actually a mount point? Then
348 * it is either obstructed by a later mount or somebody has been
349 * racing against us and removed it. Either way the mount point
350 * doesn't matter to us, let's ignore it hence. */
351 log_debug_errno(r
, "Mount point '%s' to remount is not a mount point anymore, ignoring remount failure: %m", x
);
354 if (q
< 0) /* Any other error on this? Just log and continue */
355 log_debug_errno(q
, "Failed to determine whether '%s' is a mount point or not, ignoring: %m", x
);
357 if (((flags
^ new_flags
) & flags_mask
& ~MS_RELATIME
) == 0) { /* ignore MS_RELATIME while comparing */
358 log_debug_errno(r
, "Couldn't remount '%s', but the flags already match what we want, hence ignoring: %m", x
);
362 /* Make this fatal if this is the top-level mount */
363 if (path_equal(x
, prefix
))
366 /* If this is not the top-level mount, then handle this gracefully: log but
367 * otherwise ignore. With NFS, FUSE, autofs there are just too many reasons
368 * this might fail without a chance for us to do anything about it, let's
369 * hence be strict on the top-level mount and lenient on the inner ones. */
370 log_debug_errno(r
, "Couldn't remount submount '%s' for unexpected reason, ignoring: %m", x
);
374 log_trace("Remounted %s.", x
);
379 int bind_remount_one_with_mountinfo(
381 unsigned long new_flags
,
382 unsigned long flags_mask
,
383 FILE *proc_self_mountinfo
) {
385 _cleanup_(mnt_free_tablep
) struct libmnt_table
*table
= NULL
;
386 unsigned long flags
= 0;
387 struct libmnt_fs
*fs
;
392 assert(proc_self_mountinfo
);
394 if ((flags_mask
& ~MS_CONVERTIBLE_FLAGS
) == 0 && !skip_mount_set_attr
) {
395 /* Let's take a shortcut for all the flags we know how to convert into mount_setattr() flags */
397 if (mount_setattr(AT_FDCWD
, path
, AT_SYMLINK_NOFOLLOW
,
398 &(struct mount_attr
) {
399 .attr_set
= ms_flags_to_mount_attr(new_flags
& flags_mask
),
400 .attr_clr
= ms_flags_to_mount_attr(~new_flags
& flags_mask
),
401 }, MOUNT_ATTR_SIZE_VER0
) < 0) {
403 log_debug_errno(errno
, "mount_setattr() didn't work, falling back to classic remounting: %m");
405 if (ERRNO_IS_NOT_SUPPORTED(errno
)) /* if not supported, then don't bother at all anymore */
406 skip_mount_set_attr
= true;
408 return 0; /* Nice, this worked! */
411 rewind(proc_self_mountinfo
);
413 table
= mnt_new_table();
417 r
= mnt_table_parse_stream(table
, proc_self_mountinfo
, "/proc/self/mountinfo");
421 fs
= mnt_table_find_target(table
, path
, MNT_ITER_FORWARD
);
423 r
= access_nofollow(path
, F_OK
); /* Hmm, it's not in the mount table, but does it exist at all? */
427 return -EINVAL
; /* Not a mount point we recognize */
430 opts
= mnt_fs_get_vfs_options(fs
);
432 r
= mnt_optstr_get_flags(opts
, &flags
, mnt_get_builtin_optmap(MNT_LINUX_MAP
));
434 log_debug_errno(r
, "Could not get flags for '%s', ignoring: %m", path
);
437 r
= mount_nofollow(NULL
, path
, NULL
, ((flags
& ~flags_mask
)|MS_BIND
|MS_REMOUNT
|new_flags
) & ~MS_RELATIME
, NULL
);
439 if (((flags
^ new_flags
) & flags_mask
& ~MS_RELATIME
) != 0) /* Ignore MS_RELATIME again,
440 * since kernel adds it in
441 * everywhere, because it's the
445 /* Let's handle redundant remounts gracefully */
446 log_debug_errno(r
, "Failed to remount '%s' but flags already match what we want, ignoring: %m", path
);
452 int bind_remount_one(const char *path
, unsigned long new_flags
, unsigned long flags_mask
) {
453 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
455 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
456 if (!proc_self_mountinfo
)
457 return log_debug_errno(errno
, "Failed to open %s: %m", "/proc/self/mountinfo");
459 return bind_remount_one_with_mountinfo(path
, new_flags
, flags_mask
, proc_self_mountinfo
);
462 static int mount_switch_root_pivot(int fd_newroot
, const char *path
) {
463 assert(fd_newroot
>= 0);
466 /* Let the kernel tuck the new root under the old one. */
467 if (pivot_root(".", ".") < 0)
468 return log_debug_errno(errno
, "Failed to pivot root to new rootfs '%s': %m", path
);
470 /* Get rid of the old root and reveal our brand new root. (This will always operate on the top-most
471 * mount on our cwd, regardless what our current directory actually points to.) */
472 if (umount2(".", MNT_DETACH
) < 0)
473 return log_debug_errno(errno
, "Failed to unmount old rootfs: %m");
478 static int mount_switch_root_move(int fd_newroot
, const char *path
) {
479 assert(fd_newroot
>= 0);
482 /* Move the new root fs */
483 if (mount(".", "/", NULL
, MS_MOVE
, NULL
) < 0)
484 return log_debug_errno(errno
, "Failed to move new rootfs '%s': %m", path
);
486 /* Also change root dir */
488 return log_debug_errno(errno
, "Failed to chroot to new rootfs '%s': %m", path
);
493 int mount_switch_root_full(const char *path
, unsigned long mount_propagation_flag
, bool force_ms_move
) {
494 _cleanup_close_
int fd_newroot
= -EBADF
;
495 int r
, is_current_root
;
498 assert(mount_propagation_flag_is_valid(mount_propagation_flag
));
500 fd_newroot
= open(path
, O_PATH
|O_DIRECTORY
|O_CLOEXEC
|O_NOFOLLOW
);
502 return log_debug_errno(errno
, "Failed to open new rootfs '%s': %m", path
);
504 is_current_root
= path_is_root_at(fd_newroot
, NULL
);
505 if (is_current_root
< 0)
506 return log_debug_errno(is_current_root
, "Failed to determine if target dir is our root already: %m");
508 /* Change into the new rootfs. */
509 if (fchdir(fd_newroot
) < 0)
510 return log_debug_errno(errno
, "Failed to chdir into new rootfs '%s': %m", path
);
512 /* Make this a NOP if we are supposed to switch to our current root fs. After all, both pivot_root()
513 * and MS_MOVE don't like that. */
514 if (!is_current_root
) {
515 if (!force_ms_move
) {
516 r
= mount_switch_root_pivot(fd_newroot
, path
);
518 log_debug_errno(r
, "Failed to pivot into new rootfs '%s', will try to use MS_MOVE instead: %m", path
);
519 force_ms_move
= true;
523 /* Failed to pivot_root() fallback to MS_MOVE. For example, this may happen if the rootfs is
524 * an initramfs in which case pivot_root() isn't supported. */
525 r
= mount_switch_root_move(fd_newroot
, path
);
527 return log_debug_errno(r
, "Failed to switch to new rootfs '%s' with MS_MOVE: %m", path
);
531 log_debug("Successfully switched root to '%s'.", path
);
533 /* Finally, let's establish the requested propagation flags. */
534 if (mount_propagation_flag
== 0)
537 if (mount(NULL
, ".", NULL
, mount_propagation_flag
| MS_REC
, NULL
) < 0)
538 return log_debug_errno(errno
, "Failed to turn new rootfs '%s' into %s mount: %m",
539 mount_propagation_flag_to_string(mount_propagation_flag
), path
);
544 int repeat_unmount(const char *path
, int flags
) {
549 /* If there are multiple mounts on a mount point, this
550 * removes them all */
553 if (umount2(path
, flags
) < 0) {
565 int mode_to_inaccessible_node(
566 const char *runtime_dir
,
570 /* This function maps a node type to a corresponding inaccessible file node. These nodes are created
571 * during early boot by PID 1. In some cases we lacked the privs to create the character and block
572 * devices (maybe because we run in an userns environment, or miss CAP_SYS_MKNOD, or run with a
573 * devices policy that excludes device nodes with major and minor of 0), but that's fine, in that
574 * case we use an AF_UNIX file node instead, which is not the same, but close enough for most
575 * uses. And most importantly, the kernel allows bind mounts from socket nodes to any non-directory
576 * file nodes, and that's the most important thing that matters.
578 * Note that the runtime directory argument shall be the top-level runtime directory, i.e. /run/ if
579 * we operate in system context and $XDG_RUNTIME_DIR if we operate in user context. */
581 _cleanup_free_
char *d
= NULL
;
587 runtime_dir
= "/run";
592 node
= inode_type_to_string(mode
);
596 d
= path_join(runtime_dir
, "systemd/inaccessible", node
);
600 /* On new kernels unprivileged users are permitted to create 0:0 char device nodes (because they also
601 * act as whiteout inode for overlayfs), but no other char or block device nodes. On old kernels no
602 * device node whatsoever may be created by unprivileged processes. Hence, if the caller asks for the
603 * inaccessible block device node let's see if the block device node actually exists, and if not,
604 * fall back to the character device node. From there fall back to the socket device node. This means
605 * in the best case we'll get the right device node type — but if not we'll hopefully at least get a
606 * device node at all. */
609 access(d
, F_OK
) < 0 && errno
== ENOENT
) {
611 d
= path_join(runtime_dir
, "/systemd/inaccessible/chr");
616 if (IN_SET(mode
& S_IFMT
, S_IFBLK
, S_IFCHR
) &&
617 access(d
, F_OK
) < 0 && errno
== ENOENT
) {
619 d
= path_join(runtime_dir
, "/systemd/inaccessible/sock");
628 int mount_flags_to_string(unsigned long flags
, char **ret
) {
629 static const struct {
633 { .flag
= MS_RDONLY
, .name
= "MS_RDONLY", },
634 { .flag
= MS_NOSUID
, .name
= "MS_NOSUID", },
635 { .flag
= MS_NODEV
, .name
= "MS_NODEV", },
636 { .flag
= MS_NOEXEC
, .name
= "MS_NOEXEC", },
637 { .flag
= MS_SYNCHRONOUS
, .name
= "MS_SYNCHRONOUS", },
638 { .flag
= MS_REMOUNT
, .name
= "MS_REMOUNT", },
639 { .flag
= MS_MANDLOCK
, .name
= "MS_MANDLOCK", },
640 { .flag
= MS_DIRSYNC
, .name
= "MS_DIRSYNC", },
641 { .flag
= MS_NOSYMFOLLOW
, .name
= "MS_NOSYMFOLLOW", },
642 { .flag
= MS_NOATIME
, .name
= "MS_NOATIME", },
643 { .flag
= MS_NODIRATIME
, .name
= "MS_NODIRATIME", },
644 { .flag
= MS_BIND
, .name
= "MS_BIND", },
645 { .flag
= MS_MOVE
, .name
= "MS_MOVE", },
646 { .flag
= MS_REC
, .name
= "MS_REC", },
647 { .flag
= MS_SILENT
, .name
= "MS_SILENT", },
648 { .flag
= MS_POSIXACL
, .name
= "MS_POSIXACL", },
649 { .flag
= MS_UNBINDABLE
, .name
= "MS_UNBINDABLE", },
650 { .flag
= MS_PRIVATE
, .name
= "MS_PRIVATE", },
651 { .flag
= MS_SLAVE
, .name
= "MS_SLAVE", },
652 { .flag
= MS_SHARED
, .name
= "MS_SHARED", },
653 { .flag
= MS_RELATIME
, .name
= "MS_RELATIME", },
654 { .flag
= MS_KERNMOUNT
, .name
= "MS_KERNMOUNT", },
655 { .flag
= MS_I_VERSION
, .name
= "MS_I_VERSION", },
656 { .flag
= MS_STRICTATIME
, .name
= "MS_STRICTATIME", },
657 { .flag
= MS_LAZYTIME
, .name
= "MS_LAZYTIME", },
659 _cleanup_free_
char *str
= NULL
;
663 FOREACH_ELEMENT(entry
, map
)
664 if (flags
& entry
->flag
) {
665 if (!strextend_with_separator(&str
, "|", entry
->name
))
667 flags
&= ~entry
->flag
;
670 if (!str
|| flags
!= 0)
671 if (strextendf_with_separator(&str
, "|", "%lx", flags
) < 0)
674 *ret
= TAKE_PTR(str
);
678 int mount_verbose_full(
685 bool follow_symlink
) {
687 _cleanup_free_
char *fl
= NULL
, *o
= NULL
;
691 r
= mount_option_mangle(options
, flags
, &f
, &o
);
693 return log_full_errno(error_log_level
, r
,
694 "Failed to mangle mount options %s: %m",
697 (void) mount_flags_to_string(f
, &fl
);
699 if (FLAGS_SET(f
, MS_REMOUNT
|MS_BIND
))
700 log_debug("Changing mount flags %s (%s \"%s\")...",
701 where
, strnull(fl
), strempty(o
));
702 else if (f
& MS_REMOUNT
)
703 log_debug("Remounting superblock %s (%s \"%s\")...",
704 where
, strnull(fl
), strempty(o
));
705 else if (f
& (MS_SHARED
|MS_PRIVATE
|MS_SLAVE
|MS_UNBINDABLE
))
706 log_debug("Changing mount propagation %s (%s \"%s\")",
707 where
, strnull(fl
), strempty(o
));
708 else if (f
& MS_BIND
)
709 log_debug("Bind-mounting %s on %s (%s \"%s\")...",
710 what
, where
, strnull(fl
), strempty(o
));
711 else if (f
& MS_MOVE
)
712 log_debug("Moving mount %s %s %s (%s \"%s\")...",
713 what
, glyph(GLYPH_ARROW_RIGHT
), where
, strnull(fl
), strempty(o
));
715 log_debug("Mounting %s (%s) on %s (%s \"%s\")...",
716 strna(what
), strna(type
), where
, strnull(fl
), strempty(o
));
719 r
= RET_NERRNO(mount(what
, where
, type
, f
, o
));
721 r
= mount_nofollow(what
, where
, type
, f
, o
);
723 return log_full_errno(error_log_level
, r
,
724 "Failed to mount %s (type %s) on %s (%s \"%s\"): %m",
725 strna(what
), strna(type
), where
, strnull(fl
), strempty(o
));
736 log_debug("Unmounting '%s'...", where
);
738 if (umount2(where
, flags
) < 0)
739 return log_full_errno(error_log_level
, errno
, "Failed to unmount '%s': %m", where
);
744 int umountat_detach_verbose(
749 /* Similar to umountat_verbose(), but goes by fd + path. This implies MNT_DETACH, since to do this we
750 * must pin the inode in question via an fd. */
752 assert(fd
>= 0 || fd
== AT_FDCWD
);
754 /* If neither fd nor path are specified take this as reference to the cwd */
755 if (fd
== AT_FDCWD
&& isempty(where
))
756 return umount_verbose(error_log_level
, ".", MNT_DETACH
|UMOUNT_NOFOLLOW
);
758 /* If we don't actually take the fd into consideration for this operation shortcut things, so that we
759 * don't have to open the inode */
760 if (fd
== AT_FDCWD
|| path_is_absolute(where
))
761 return umount_verbose(error_log_level
, where
, MNT_DETACH
|UMOUNT_NOFOLLOW
);
763 _cleanup_free_
char *prefix
= NULL
;
765 if (fd_get_path(fd
, &prefix
) < 0)
766 p
= "<fd>"; /* if we can't get the path, return something vaguely useful */
769 _cleanup_free_
char *joined
= isempty(where
) ? strdup(p
) : path_join(p
, where
);
771 log_debug("Unmounting '%s'...", strna(joined
));
773 _cleanup_close_
int inode_fd
= -EBADF
;
778 inode_fd
= openat(fd
, where
, O_PATH
|O_CLOEXEC
|O_NOFOLLOW
);
780 return log_full_errno(error_log_level
, errno
, "Failed to pin '%s': %m", strna(joined
));
785 if (umount2(FORMAT_PROC_FD_PATH(mnt_fd
), MNT_DETACH
) < 0)
786 return log_full_errno(error_log_level
, errno
, "Failed to unmount '%s': %m", strna(joined
));
791 int mount_exchange_graceful(int fsmount_fd
, const char *dest
, bool mount_beneath
) {
794 assert(fsmount_fd
>= 0);
797 /* First, try to mount beneath an existing mount point, and if that works, umount the old mount,
798 * which is now at the top. This will ensure we can atomically replace a mount. Note that this works
799 * also in the case where there are submounts down the tree. Mount propagation is allowed but
800 * restricted to layouts that don't end up propagation the new mount on top of the mount stack. If
801 * this is not supported (minimum kernel v6.5), or if there is no mount on the mountpoint, we get
802 * -EINVAL and then we fallback to normal mounting. */
804 r
= RET_NERRNO(move_mount(fsmount_fd
, /* from_path = */ "",
805 /* to_fd = */ -EBADF
, dest
,
806 MOVE_MOUNT_F_EMPTY_PATH
| (mount_beneath
? MOVE_MOUNT_BENEATH
: 0)));
808 if (r
>= 0) /* Mounting beneath worked! Now unmount the upper mount. */
809 return umount_verbose(LOG_DEBUG
, dest
, UMOUNT_NOFOLLOW
|MNT_DETACH
);
811 if (r
== -EINVAL
) { /* Fallback if mount_beneath is not supported */
813 "Cannot mount beneath '%s', falling back to overmount: %m",
815 return mount_exchange_graceful(fsmount_fd
, dest
, /* mount_beneath = */ false);
822 int mount_option_mangle(
824 unsigned long mount_flags
,
825 unsigned long *ret_mount_flags
,
826 char **ret_remaining_options
) {
828 const struct libmnt_optmap
*map
;
829 _cleanup_free_
char *ret
= NULL
;
832 /* This extracts mount flags from the mount options, and stores
833 * non-mount-flag options to '*ret_remaining_options'.
835 * "rw,nosuid,nodev,relatime,size=1630748k,mode=0700,uid=1000,gid=1000"
836 * is split to MS_NOSUID|MS_NODEV|MS_RELATIME and
837 * "size=1630748k,mode=0700,uid=1000,gid=1000".
838 * See more examples in test-mount-util.c.
840 * If 'options' does not contain any non-mount-flag options,
841 * then '*ret_remaining_options' is set to NULL instead of empty string.
842 * The validity of options stored in '*ret_remaining_options' is not checked.
843 * If 'options' is NULL, this just copies 'mount_flags' to *ret_mount_flags. */
845 assert(ret_mount_flags
);
846 assert(ret_remaining_options
);
848 map
= mnt_get_builtin_optmap(MNT_LINUX_MAP
);
852 for (const char *p
= options
;;) {
853 _cleanup_free_
char *word
= NULL
;
854 const struct libmnt_optmap
*ent
;
856 r
= extract_first_word(&p
, &word
, ",", EXTRACT_KEEP_QUOTE
);
862 for (ent
= map
; ent
->name
; ent
++) {
863 /* All entries in MNT_LINUX_MAP do not take any argument.
864 * Thus, ent->name does not contain "=" or "[=]". */
865 if (!streq(word
, ent
->name
))
868 if (!(ent
->mask
& MNT_INVERT
))
869 mount_flags
|= ent
->id
;
871 mount_flags
&= ~ent
->id
;
876 /* If 'word' is not a mount flag, then store it in '*ret_remaining_options'. */
878 !startswith_no_case(word
, "x-") &&
879 !strextend_with_separator(&ret
, ",", word
))
883 *ret_mount_flags
= mount_flags
;
884 *ret_remaining_options
= TAKE_PTR(ret
);
889 static int mount_in_namespace_legacy(
890 const char *chased_src_path
,
892 struct stat
*chased_src_st
,
893 const char *propagate_path
,
894 const char *incoming_path
,
899 MountInNamespaceFlags flags
,
900 const MountOptions
*options
,
901 const ImagePolicy
*image_policy
) {
903 _cleanup_close_pair_
int errno_pipe_fd
[2] = EBADF_PAIR
;
904 char mount_slave
[] = "/tmp/propagate.XXXXXX", *mount_tmp
, *mount_outside
, *p
;
905 bool mount_slave_created
= false, mount_slave_mounted
= false,
906 mount_tmp_created
= false, mount_tmp_mounted
= false,
907 mount_outside_created
= false, mount_outside_mounted
= false;
911 assert(chased_src_path
);
912 assert(chased_src_fd
>= 0);
913 assert(chased_src_st
);
914 assert(propagate_path
);
915 assert(incoming_path
);
917 assert(pidns_fd
>= 0);
918 assert(mntns_fd
>= 0);
919 assert(root_fd
>= 0);
920 assert(!options
|| (flags
& MOUNT_IN_NAMESPACE_IS_IMAGE
));
922 p
= strjoina(propagate_path
, "/");
923 r
= access_nofollow(p
, F_OK
);
925 return log_debug_errno(r
== -ENOENT
? SYNTHETIC_ERRNO(EOPNOTSUPP
) : r
, "Target does not allow propagation of mount points");
927 /* Our goal is to install a new bind mount into the container,
928 possibly read-only. This is irritatingly complex
929 unfortunately, currently.
931 First, we start by creating a private playground in /tmp,
932 that we can mount MS_SLAVE. (Which is necessary, since
933 MS_MOVE cannot be applied to mounts with MS_SHARED parent
936 if (!mkdtemp(mount_slave
))
937 return log_debug_errno(errno
, "Failed to create playground %s: %m", mount_slave
);
939 mount_slave_created
= true;
941 r
= mount_nofollow_verbose(LOG_DEBUG
, mount_slave
, mount_slave
, NULL
, MS_BIND
, NULL
);
945 mount_slave_mounted
= true;
947 r
= mount_nofollow_verbose(LOG_DEBUG
, NULL
, mount_slave
, NULL
, MS_SLAVE
, NULL
);
951 /* Second, we mount the source file or directory to a directory inside of our MS_SLAVE playground. */
952 mount_tmp
= strjoina(mount_slave
, "/mount");
953 r
= make_mount_point_inode_from_mode(AT_FDCWD
, mount_tmp
, (flags
& MOUNT_IN_NAMESPACE_IS_IMAGE
) ? S_IFDIR
: chased_src_st
->st_mode
, 0700);
955 log_debug_errno(r
, "Failed to create temporary mount point %s: %m", mount_tmp
);
959 mount_tmp_created
= true;
961 if (flags
& MOUNT_IN_NAMESPACE_IS_IMAGE
)
962 r
= verity_dissect_and_mount(
968 /* image_filter= */ NULL
,
969 /* extension_release_data= */ NULL
,
970 /* required_class= */ _IMAGE_CLASS_INVALID
,
972 /* ret_image= */ NULL
);
974 r
= mount_follow_verbose(LOG_DEBUG
, FORMAT_PROC_FD_PATH(chased_src_fd
), mount_tmp
, NULL
, MS_BIND
, NULL
);
978 mount_tmp_mounted
= true;
980 /* Third, we remount the new bind mount read-only if requested. */
981 if (flags
& MOUNT_IN_NAMESPACE_READ_ONLY
) {
982 r
= mount_nofollow_verbose(LOG_DEBUG
, NULL
, mount_tmp
, NULL
, MS_BIND
|MS_REMOUNT
|MS_RDONLY
, NULL
);
987 /* Fourth, we move the new bind mount into the propagation directory. This way it will appear there read-only
990 mount_outside
= strjoina(propagate_path
, "/XXXXXX");
991 if ((flags
& MOUNT_IN_NAMESPACE_IS_IMAGE
) || S_ISDIR(chased_src_st
->st_mode
))
992 r
= mkdtemp(mount_outside
) ? 0 : -errno
;
994 r
= mkostemp_safe(mount_outside
);
998 log_debug_errno(r
, "Cannot create propagation file or directory %s: %m", mount_outside
);
1002 mount_outside_created
= true;
1004 r
= mount_nofollow_verbose(LOG_DEBUG
, mount_tmp
, mount_outside
, NULL
, MS_MOVE
, NULL
);
1008 mount_outside_mounted
= true;
1009 mount_tmp_mounted
= false;
1011 if ((flags
& MOUNT_IN_NAMESPACE_IS_IMAGE
) || S_ISDIR(chased_src_st
->st_mode
))
1012 (void) rmdir(mount_tmp
);
1014 (void) unlink(mount_tmp
);
1015 mount_tmp_created
= false;
1017 (void) umount_verbose(LOG_DEBUG
, mount_slave
, UMOUNT_NOFOLLOW
);
1018 mount_slave_mounted
= false;
1020 (void) rmdir(mount_slave
);
1021 mount_slave_created
= false;
1023 if (pipe2(errno_pipe_fd
, O_CLOEXEC
|O_NONBLOCK
) < 0) {
1024 log_debug_errno(errno
, "Failed to create pipe: %m");
1030 "(sd-bindmnt-inner)",
1031 /* except_fds= */ NULL
,
1032 /* n_except_fds= */ 0,
1033 FORK_RESET_SIGNALS
|FORK_DEATHSIG_SIGTERM
,
1036 /* netns_fd= */ -EBADF
,
1037 /* userns_fd= */ -EBADF
,
1043 _cleanup_free_
char *mount_outside_fn
= NULL
, *mount_inside
= NULL
;
1045 errno_pipe_fd
[0] = safe_close(errno_pipe_fd
[0]);
1047 _cleanup_close_
int dest_fd
= -EBADF
;
1048 _cleanup_free_
char *dest_fn
= NULL
;
1049 r
= chase(dest
, /* root= */ NULL
, CHASE_PARENT
|CHASE_EXTRACT_FILENAME
|((flags
& MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY
) ? CHASE_MKDIR_0755
: 0), &dest_fn
, &dest_fd
);
1051 log_debug_errno(r
, "Failed to pin parent directory of mount '%s', ignoring: %m", dest
);
1052 else if (flags
& MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY
) {
1053 r
= make_mount_point_inode_from_mode(dest_fd
, dest_fn
, (flags
& MOUNT_IN_NAMESPACE_IS_IMAGE
) ? S_IFDIR
: chased_src_st
->st_mode
, 0700);
1055 log_debug_errno(r
, "Failed to make mount point inode of mount '%s', ignoring: %m", dest
);
1058 /* Fifth, move the mount to the right place inside */
1059 r
= path_extract_filename(mount_outside
, &mount_outside_fn
);
1061 log_debug_errno(r
, "Failed to extract filename from propagation file or directory '%s': %m", mount_outside
);
1062 report_errno_and_exit(errno_pipe_fd
[1], r
);
1065 mount_inside
= path_join(incoming_path
, mount_outside_fn
);
1067 report_errno_and_exit(errno_pipe_fd
[1], log_oom_debug());
1069 r
= mount_nofollow_verbose(LOG_DEBUG
, mount_inside
, dest_fd
>= 0 ? FORMAT_PROC_FD_PATH(dest_fd
) : dest
, /* fstype= */ NULL
, MS_MOVE
, /* options= */ NULL
);
1071 report_errno_and_exit(errno_pipe_fd
[1], r
);
1073 _exit(EXIT_SUCCESS
);
1076 errno_pipe_fd
[1] = safe_close(errno_pipe_fd
[1]);
1078 r
= wait_for_terminate_and_check("(sd-bindmnt)", child
, 0);
1080 log_debug_errno(r
, "Failed to wait for child: %m");
1083 if (r
!= EXIT_SUCCESS
) {
1084 if (read(errno_pipe_fd
[0], &r
, sizeof(r
)) == sizeof(r
))
1085 log_debug_errno(r
, "Failed to mount: %m");
1087 log_debug("Child failed.");
1092 if (mount_outside_mounted
)
1093 (void) umount_verbose(LOG_DEBUG
, mount_outside
, UMOUNT_NOFOLLOW
);
1094 if (mount_outside_created
) {
1095 if ((flags
& MOUNT_IN_NAMESPACE_IS_IMAGE
) || S_ISDIR(chased_src_st
->st_mode
))
1096 (void) rmdir(mount_outside
);
1098 (void) unlink(mount_outside
);
1101 if (mount_tmp_mounted
)
1102 (void) umount_verbose(LOG_DEBUG
, mount_tmp
, UMOUNT_NOFOLLOW
);
1103 if (mount_tmp_created
) {
1104 if ((flags
& MOUNT_IN_NAMESPACE_IS_IMAGE
) || S_ISDIR(chased_src_st
->st_mode
))
1105 (void) rmdir(mount_tmp
);
1107 (void) unlink(mount_tmp
);
1110 if (mount_slave_mounted
)
1111 (void) umount_verbose(LOG_DEBUG
, mount_slave
, UMOUNT_NOFOLLOW
);
1112 if (mount_slave_created
)
1113 (void) rmdir(mount_slave
);
1118 static int mount_in_namespace(
1119 const PidRef
*target
,
1120 const char *propagate_path
,
1121 const char *incoming_path
,
1124 MountInNamespaceFlags flags
,
1125 const MountOptions
*options
,
1126 const ImagePolicy
*image_policy
) {
1128 _cleanup_close_
int mntns_fd
= -EBADF
, root_fd
= -EBADF
, pidns_fd
= -EBADF
, chased_src_fd
= -EBADF
;
1129 _cleanup_free_
char *chased_src_path
= NULL
;
1133 assert(propagate_path
);
1134 assert(incoming_path
);
1137 assert((flags
& MOUNT_IN_NAMESPACE_IS_IMAGE
) || (!options
&& !image_policy
));
1139 if (!pidref_is_set(target
))
1142 r
= pidref_namespace_open(target
, &pidns_fd
, &mntns_fd
, /* ret_netns_fd = */ NULL
, /* ret_userns_fd = */ NULL
, &root_fd
);
1144 return log_debug_errno(r
, "Failed to retrieve FDs of the target process' namespace: %m");
1146 r
= is_our_namespace(mntns_fd
, NAMESPACE_MOUNT
);
1148 return log_debug_errno(r
, "Failed to determine if mount namespaces are equal: %m");
1149 /* We can't add new mounts at runtime if the process wasn't started in a namespace */
1151 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to activate bind mount in target, not running in a mount namespace.");
1153 r
= chase(src
, NULL
, 0, &chased_src_path
, &chased_src_fd
);
1155 return log_debug_errno(r
, "Failed to resolve source path '%s': %m", src
);
1156 log_debug("Chased source path '%s': %s", src
, chased_src_path
);
1158 if (fstat(chased_src_fd
, &st
) < 0)
1159 return log_debug_errno(errno
, "Failed to stat() resolved source path '%s': %m", src
);
1160 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… */
1161 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP
), "Source path '%s' can't be a symbolic link.", src
);
1163 if (!mount_new_api_supported()) /* Fallback if we can't use the new mount API */
1164 return mount_in_namespace_legacy(
1178 _cleanup_(dissected_image_unrefp
) DissectedImage
*img
= NULL
;
1179 _cleanup_close_
int new_mount_fd
= -EBADF
;
1180 _cleanup_close_pair_
int errno_pipe_fd
[2] = EBADF_PAIR
;
1183 if (flags
& MOUNT_IN_NAMESPACE_IS_IMAGE
) {
1184 r
= verity_dissect_and_mount(
1190 /* image_filter= */ NULL
,
1191 /* extension_release_data= */ NULL
,
1192 /* required_class= */ _IMAGE_CLASS_INVALID
,
1196 return log_debug_errno(r
,
1197 "Failed to dissect and mount image '%s': %m",
1200 new_mount_fd
= open_tree(
1203 OPEN_TREE_CLONE
|OPEN_TREE_CLOEXEC
|AT_SYMLINK_NOFOLLOW
|AT_EMPTY_PATH
);
1204 if (new_mount_fd
< 0)
1205 return log_debug_errno(
1207 "Failed to open mount source '%s': %m",
1210 if ((flags
& MOUNT_IN_NAMESPACE_READ_ONLY
) && mount_setattr(new_mount_fd
, "", AT_EMPTY_PATH
,
1211 &(struct mount_attr
) {
1212 .attr_set
= MOUNT_ATTR_RDONLY
,
1213 }, MOUNT_ATTR_SIZE_VER0
) < 0)
1214 return log_debug_errno(errno
,
1215 "Failed to set mount for '%s' to read only: %m",
1219 if (pipe2(errno_pipe_fd
, O_CLOEXEC
|O_NONBLOCK
) < 0)
1220 return log_debug_errno(errno
, "Failed to create pipe: %m");
1222 r
= namespace_fork("(sd-bindmnt)",
1223 "(sd-bindmnt-inner)",
1224 /* except_fds= */ NULL
,
1225 /* n_except_fds= */ 0,
1226 FORK_RESET_SIGNALS
|FORK_DEATHSIG_SIGTERM
,
1229 /* netns_fd= */ -EBADF
,
1230 /* userns_fd= */ -EBADF
,
1234 return log_debug_errno(r
, "Failed to fork off mount helper into namespace: %m");
1236 errno_pipe_fd
[0] = safe_close(errno_pipe_fd
[0]);
1238 _cleanup_close_
int dest_fd
= -EBADF
;
1239 _cleanup_free_
char *dest_fn
= NULL
;
1240 r
= chase(dest
, /* root= */ NULL
, CHASE_PARENT
|CHASE_EXTRACT_FILENAME
|((flags
& MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY
) ? CHASE_MKDIR_0755
: 0), &dest_fn
, &dest_fd
);
1242 report_errno_and_exit(errno_pipe_fd
[1], r
);
1244 if (flags
& MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY
)
1245 (void) make_mount_point_inode_from_mode(dest_fd
, dest_fn
, img
? S_IFDIR
: st
.st_mode
, 0700);
1248 DissectImageFlags f
=
1249 DISSECT_IMAGE_TRY_ATOMIC_MOUNT_EXCHANGE
|
1250 DISSECT_IMAGE_ALLOW_USERSPACE_VERITY
;
1252 if (flags
& MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY
)
1253 f
|= DISSECT_IMAGE_MKDIR
;
1255 if (flags
& MOUNT_IN_NAMESPACE_READ_ONLY
)
1256 f
|= DISSECT_IMAGE_READ_ONLY
;
1258 r
= dissected_image_mount(
1261 /* uid_shift= */ UID_INVALID
,
1262 /* uid_range= */ UID_INVALID
,
1263 /* userns_fd= */ -EBADF
,
1266 r
= mount_exchange_graceful(new_mount_fd
, dest
, /* mount_beneath= */ true);
1268 report_errno_and_exit(errno_pipe_fd
[1], r
);
1271 errno_pipe_fd
[1] = safe_close(errno_pipe_fd
[1]);
1273 r
= wait_for_terminate_and_check("(sd-bindmnt)", child
, 0);
1275 return log_debug_errno(r
, "Failed to wait for child: %m");
1276 if (r
!= EXIT_SUCCESS
) {
1277 if (read(errno_pipe_fd
[0], &r
, sizeof(r
)) == sizeof(r
))
1278 return log_debug_errno(r
, "Failed to mount into namespace: %m");
1280 return log_debug_errno(SYNTHETIC_ERRNO(EPROTO
), "Child failed.");
1286 int bind_mount_in_namespace(
1287 const PidRef
*target
,
1288 const char *propagate_path
,
1289 const char *incoming_path
,
1292 MountInNamespaceFlags flags
) {
1294 return mount_in_namespace(target
,
1299 flags
& ~MOUNT_IN_NAMESPACE_IS_IMAGE
,
1300 /* options = */ NULL
,
1301 /* image_policy = */ NULL
);
1304 int mount_image_in_namespace(
1305 const PidRef
*target
,
1306 const char *propagate_path
,
1307 const char *incoming_path
,
1310 MountInNamespaceFlags flags
,
1311 const MountOptions
*options
,
1312 const ImagePolicy
*image_policy
) {
1314 return mount_in_namespace(target
,
1319 flags
| MOUNT_IN_NAMESPACE_IS_IMAGE
,
1324 int make_mount_point(const char *path
) {
1329 /* If 'path' is already a mount point, does nothing and returns 0. If it is not it makes it one, and returns 1. */
1331 r
= path_is_mount_point(path
);
1333 return log_debug_errno(r
, "Failed to determine whether '%s' is a mount point: %m", path
);
1337 r
= mount_nofollow_verbose(LOG_DEBUG
, path
, path
, NULL
, MS_BIND
|MS_REC
, NULL
);
1344 int fd_make_mount_point(int fd
) {
1349 r
= is_mount_point_at(fd
, NULL
, 0);
1351 return log_debug_errno(r
, "Failed to determine whether file descriptor is a mount point: %m");
1355 r
= mount_follow_verbose(LOG_DEBUG
, FORMAT_PROC_FD_PATH(fd
), FORMAT_PROC_FD_PATH(fd
), NULL
, MS_BIND
|MS_REC
, NULL
);
1362 int make_userns(uid_t uid_shift
,
1366 RemountIdmapping idmapping
) {
1368 _cleanup_close_
int userns_fd
= -EBADF
;
1369 _cleanup_free_
char *line
= NULL
;
1370 uid_t source_base
= 0;
1372 /* Allocates a userns file descriptor with the mapping we need. For this we'll fork off a child
1373 * process whose only purpose is to give us a new user namespace. It's killed when we got it. */
1375 if (!userns_shift_range_valid(uid_shift
, uid_range
))
1376 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid UID range for user namespace.");
1378 switch (idmapping
) {
1380 case REMOUNT_IDMAPPING_FOREIGN_WITH_HOST_ROOT
:
1381 source_base
= FOREIGN_UID_BASE
;
1384 case REMOUNT_IDMAPPING_NONE
:
1385 case REMOUNT_IDMAPPING_HOST_ROOT
:
1388 UID_FMT
" " UID_FMT
" " UID_FMT
"\n",
1389 source_base
, uid_shift
, uid_range
) < 0)
1390 return log_oom_debug();
1392 /* If requested we'll include an entry in the mapping so that the host root user can make
1393 * changes to the uidmapped mount like it normally would. Specifically, we'll map the user
1394 * with UID_MAPPED_ROOT on the backing fs to UID 0. This is useful, since nspawn code wants
1395 * to create various missing inodes in the OS tree before booting into it, and this becomes
1396 * very easy and straightforward to do if it can just do it under its own regular UID. Note
1397 * that in that case the container's runtime uidmap (i.e. the one the container payload
1398 * processes run in) will leave this UID unmapped, i.e. if we accidentally leave files owned
1399 * by host root in the already uidmapped tree around they'll show up as owned by 'nobody',
1400 * which is safe. (Of course, we shouldn't leave such inodes around, but always chown() them
1401 * to the container's own UID range, but it's good to have a safety net, in case we
1403 if (idmapping
== REMOUNT_IDMAPPING_HOST_ROOT
)
1404 if (strextendf(&line
,
1405 UID_FMT
" " UID_FMT
" " UID_FMT
"\n",
1406 UID_MAPPED_ROOT
, (uid_t
) 0u, (uid_t
) 1u) < 0)
1407 return log_oom_debug();
1411 case REMOUNT_IDMAPPING_HOST_OWNER
:
1412 /* Remap the owner of the bind mounted directory to the root user within the container. This
1413 * way every file written by root within the container to the bind-mounted directory will
1414 * be owned by the original user from the host. All other users will remain unmapped. */
1416 UID_FMT
" " UID_FMT
" " UID_FMT
"\n",
1417 source_owner
, uid_shift
, (uid_t
) 1u) < 0)
1418 return log_oom_debug();
1421 case REMOUNT_IDMAPPING_HOST_OWNER_TO_TARGET_OWNER
:
1422 /* Remap the owner of the bind mounted directory to the owner of the target directory
1423 * within the container. This way every file written by target directory owner within the
1424 * container to the bind-mounted directory will be owned by the original host user.
1425 * All other users will remain unmapped. */
1427 UID_FMT
" " UID_FMT
" " UID_FMT
"\n",
1428 source_owner
, dest_owner
, (uid_t
) 1u) < 0)
1429 return log_oom_debug();
1433 assert_not_reached();
1436 /* We always assign the same UID and GID ranges */
1437 userns_fd
= userns_acquire(line
, line
, /* setgroups_deny= */ true);
1439 return log_debug_errno(userns_fd
, "Failed to acquire new userns: %m");
1441 return TAKE_FD(userns_fd
);
1444 int remount_idmap_fd(
1447 uint64_t extra_mount_attr_set
) {
1451 assert(userns_fd
>= 0);
1453 /* This remounts all specified paths with the specified userns as idmap. It will do so in the
1454 * order specified in the strv: the expectation is that the top-level directories are at the
1455 * beginning, and nested directories in the right, so that the tree can be built correctly from left
1458 size_t n
= strv_length(paths
);
1459 if (n
== 0) /* Nothing to do? */
1462 int *mount_fds
= NULL
;
1463 size_t n_mounts_fds
= 0;
1465 mount_fds
= new(int, n
);
1467 return log_oom_debug();
1469 CLEANUP_ARRAY(mount_fds
, n_mounts_fds
, close_many_and_free
);
1471 for (size_t i
= 0; i
< n
; i
++) {
1474 /* Clone the mount point */
1475 mntfd
= mount_fds
[n_mounts_fds
] = open_tree(-EBADF
, paths
[i
], OPEN_TREE_CLONE
| OPEN_TREE_CLOEXEC
);
1476 if (mount_fds
[n_mounts_fds
] < 0)
1477 return log_debug_errno(errno
, "Failed to open tree of mounted filesystem '%s': %m", paths
[i
]);
1481 /* Set the user namespace mapping attribute on the cloned mount point */
1482 if (mount_setattr(mntfd
, "", AT_EMPTY_PATH
,
1483 &(struct mount_attr
) {
1484 .attr_set
= MOUNT_ATTR_IDMAP
| extra_mount_attr_set
,
1485 .userns_fd
= userns_fd
,
1486 }, sizeof(struct mount_attr
)) < 0)
1487 return log_debug_errno(errno
, "Failed to change bind mount attributes for clone of '%s': %m", paths
[i
]);
1490 for (size_t i
= n
; i
> 0; i
--) { /* Unmount the paths right-to-left */
1491 /* Remove the old mount points now that we have a idmapped mounts as replacement for all of them */
1492 r
= umount_verbose(LOG_DEBUG
, paths
[i
-1], UMOUNT_NOFOLLOW
);
1497 for (size_t i
= 0; i
< n
; i
++) { /* Mount the replacement mounts left-to-right */
1498 /* And place the cloned version in its place */
1499 log_debug("Mounting idmapped fs to '%s'", paths
[i
]);
1500 if (move_mount(mount_fds
[i
], "", -EBADF
, paths
[i
], MOVE_MOUNT_F_EMPTY_PATH
) < 0)
1501 return log_debug_errno(errno
, "Failed to attach UID mapped mount to '%s': %m", paths
[i
]);
1513 RemountIdmapping idmapping
) {
1515 _cleanup_close_
int userns_fd
= -EBADF
;
1517 userns_fd
= make_userns(uid_shift
, uid_range
, source_owner
, dest_owner
, idmapping
);
1521 return remount_idmap_fd(p
, userns_fd
, /* extra_mount_attr_set= */ 0);
1524 static void sub_mount_clear(SubMount
*s
) {
1527 s
->path
= mfree(s
->path
);
1528 s
->mount_fd
= safe_close(s
->mount_fd
);
1531 void sub_mount_array_free(SubMount
*s
, size_t n
) {
1532 assert(s
|| n
== 0);
1534 for (size_t i
= 0; i
< n
; i
++)
1535 sub_mount_clear(s
+ i
);
1540 static int sub_mount_compare(const SubMount
*a
, const SubMount
*b
) {
1546 return path_compare(a
->path
, b
->path
);
1549 static void sub_mount_drop(SubMount
*s
, size_t n
) {
1550 assert(s
|| n
== 0);
1552 for (size_t m
= 0, i
= 1; i
< n
; i
++) {
1553 if (path_startswith(s
[i
].path
, s
[m
].path
))
1554 sub_mount_clear(s
+ i
);
1560 int get_sub_mounts(const char *prefix
, SubMount
**ret_mounts
, size_t *ret_n_mounts
) {
1562 _cleanup_(mnt_free_tablep
) struct libmnt_table
*table
= NULL
;
1563 _cleanup_(mnt_free_iterp
) struct libmnt_iter
*iter
= NULL
;
1564 SubMount
*mounts
= NULL
;
1568 CLEANUP_ARRAY(mounts
, n
, sub_mount_array_free
);
1572 assert(ret_n_mounts
);
1574 r
= libmount_parse_mountinfo(/* source = */ NULL
, &table
, &iter
);
1576 return log_debug_errno(r
, "Failed to parse /proc/self/mountinfo: %m");
1579 _cleanup_close_
int mount_fd
= -EBADF
;
1580 _cleanup_free_
char *p
= NULL
;
1581 struct libmnt_fs
*fs
;
1585 r
= mnt_table_next_fs(table
, iter
, &fs
);
1589 return log_debug_errno(r
, "Failed to get next entry from /proc/self/mountinfo: %m");
1591 path
= mnt_fs_get_target(fs
);
1595 if (isempty(path_startswith(path
, prefix
)))
1598 id1
= mnt_fs_get_id(fs
);
1599 r
= path_get_mnt_id(path
, &id2
);
1601 log_debug_errno(r
, "Failed to get mount ID of '%s', ignoring: %m", path
);
1605 /* The path may be hidden by another over-mount or already remounted. */
1606 log_debug("The mount IDs of '%s' obtained by libmount and path_get_mnt_id() are different (%i vs %i), ignoring.",
1611 mount_fd
= open(path
, O_CLOEXEC
|O_PATH
);
1613 if (errno
== ENOENT
) /* The path may be hidden by another over-mount or already unmounted. */
1616 return log_debug_errno(errno
, "Failed to open subtree of mounted filesystem '%s': %m", path
);
1621 return log_oom_debug();
1623 if (!GREEDY_REALLOC(mounts
, n
+ 1))
1624 return log_oom_debug();
1626 mounts
[n
++] = (SubMount
) {
1627 .path
= TAKE_PTR(p
),
1628 .mount_fd
= TAKE_FD(mount_fd
),
1632 typesafe_qsort(mounts
, n
, sub_mount_compare
);
1633 sub_mount_drop(mounts
, n
);
1635 *ret_mounts
= TAKE_PTR(mounts
);
1640 int bind_mount_submounts(
1642 const char *target
) {
1644 SubMount
*mounts
= NULL
;
1648 /* Bind mounts all child mounts of 'source' to 'target'. Useful when setting up a new procfs instance
1649 * with new mount options to copy the original submounts over. */
1654 CLEANUP_ARRAY(mounts
, n
, sub_mount_array_free
);
1656 r
= get_sub_mounts(source
, &mounts
, &n
);
1660 FOREACH_ARRAY(m
, mounts
, n
) {
1661 _cleanup_free_
char *t
= NULL
;
1664 if (isempty(m
->path
))
1667 assert_se(suffix
= path_startswith(m
->path
, source
));
1669 t
= path_join(target
, suffix
);
1673 r
= path_is_mount_point(t
);
1675 log_debug_errno(r
, "Failed to detect if '%s' already is a mount point, ignoring: %m", t
);
1679 log_debug("Not bind mounting '%s' from '%s' to '%s', since there's already a mountpoint.", suffix
, source
, target
);
1683 r
= mount_follow_verbose(LOG_DEBUG
, FORMAT_PROC_FD_PATH(m
->mount_fd
), t
, NULL
, MS_BIND
|MS_REC
, NULL
);
1684 if (r
< 0 && ret
== 0)
1691 int make_mount_point_inode_from_mode(int dir_fd
, const char *dest
, mode_t source_mode
, mode_t target_mode
) {
1692 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
1695 if (S_ISDIR(source_mode
))
1696 return mkdirat_label(dir_fd
, dest
, target_mode
& 07777);
1698 return RET_NERRNO(mknodat(dir_fd
, dest
, S_IFREG
|(target_mode
& 07666), 0)); /* Mask off X bit */
1701 int make_mount_point_inode_from_path(const char *source
, const char *dest
, mode_t access_mode
) {
1707 if (stat(source
, &st
) < 0)
1710 return make_mount_point_inode_from_mode(AT_FDCWD
, dest
, st
.st_mode
, access_mode
);
1713 int trigger_automount_at(int dir_fd
, const char *path
) {
1714 _cleanup_free_
char *nested
= NULL
;
1716 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
1718 nested
= path_join(path
, "a");
1722 (void) faccessat(dir_fd
, nested
, F_OK
, 0);
1727 unsigned long credentials_fs_mount_flags(bool ro
) {
1728 /* A tight set of mount flags for credentials mounts */
1729 return MS_NODEV
|MS_NOEXEC
|MS_NOSUID
|ms_nosymfollow_supported()|(ro
? MS_RDONLY
: 0);
1732 int mount_credentials_fs(const char *path
, size_t size
, bool ro
) {
1733 _cleanup_free_
char *opts
= NULL
;
1734 int r
, noswap_supported
;
1736 /* Mounts a file system we can place credentials in, i.e. with tight access modes right from the
1737 * beginning, and ideally swapping turned off. In order of preference:
1739 * 1. tmpfs if it supports "noswap"
1741 * 3. tmpfs if it doesn't support "noswap"
1744 noswap_supported
= mount_option_supported("tmpfs", "noswap", NULL
); /* Check explicitly to avoid kmsg noise */
1745 if (noswap_supported
> 0) {
1746 _cleanup_free_
char *noswap_opts
= NULL
;
1748 if (asprintf(&noswap_opts
, "mode=0700,nr_inodes=1024,size=%zu,noswap", size
) < 0)
1751 /* Best case: tmpfs with noswap (needs kernel >= 6.3) */
1753 r
= mount_nofollow_verbose(
1758 credentials_fs_mount_flags(ro
),
1764 r
= mount_nofollow_verbose(
1769 credentials_fs_mount_flags(ro
),
1774 if (asprintf(&opts
, "mode=0700,nr_inodes=1024,size=%zu", size
) < 0)
1777 return mount_nofollow_verbose(
1782 credentials_fs_mount_flags(ro
),
1787 int error_log_level
,
1790 unsigned long flags
,
1791 const char *options
,
1794 _cleanup_close_
int fs_fd
= -EBADF
, mnt_fd
= -EBADF
;
1795 _cleanup_free_
char *o
= NULL
;
1802 r
= mount_option_mangle(options
, flags
, &f
, &o
);
1804 return log_full_errno(
1805 error_log_level
, r
, "Failed to mangle mount options %s: %m",
1808 if (DEBUG_LOGGING
) {
1809 _cleanup_free_
char *fl
= NULL
;
1810 (void) mount_flags_to_string(f
, &fl
);
1812 log_debug("Creating mount fd for %s (%s) (%s \"%s\")...",
1813 strna(what
), strna(type
), strnull(fl
), strempty(o
));
1816 fs_fd
= fsopen(type
, FSOPEN_CLOEXEC
);
1818 return log_full_errno(error_log_level
, errno
, "Failed to open superblock for \"%s\": %m", type
);
1820 if (fsconfig(fs_fd
, FSCONFIG_SET_STRING
, "source", what
, 0) < 0)
1821 return log_full_errno(error_log_level
, errno
, "Failed to set mount source for \"%s\" to \"%s\": %m", type
, what
);
1823 if (FLAGS_SET(f
, MS_RDONLY
))
1824 if (fsconfig(fs_fd
, FSCONFIG_SET_FLAG
, "ro", NULL
, 0) < 0)
1825 return log_full_errno(error_log_level
, errno
, "Failed to set read only mount flag for \"%s\": %m", type
);
1827 for (const char *p
= o
;;) {
1828 _cleanup_free_
char *word
= NULL
;
1831 r
= extract_first_word(&p
, &word
, ",", EXTRACT_KEEP_QUOTE
);
1833 return log_full_errno(error_log_level
, r
, "Failed to parse mount option string \"%s\": %m", o
);
1837 eq
= strchr(word
, '=');
1842 if (fsconfig(fs_fd
, FSCONFIG_SET_STRING
, word
, eq
, 0) < 0)
1843 return log_full_errno(error_log_level
, errno
, "Failed to set mount option \"%s=%s\" for \"%s\": %m", word
, eq
, type
);
1845 if (fsconfig(fs_fd
, FSCONFIG_SET_FLAG
, word
, NULL
, 0) < 0)
1846 return log_full_errno(error_log_level
, errno
, "Failed to set mount flag \"%s\" for \"%s\": %m", word
, type
);
1850 if (fsconfig(fs_fd
, FSCONFIG_CMD_CREATE
, NULL
, NULL
, 0) < 0)
1851 return log_full_errno(error_log_level
, errno
, "Failed to realize fs fd for \"%s\" (\"%s\"): %m", what
, type
);
1853 mnt_fd
= fsmount(fs_fd
, FSMOUNT_CLOEXEC
, 0);
1855 return log_full_errno(error_log_level
, errno
, "Failed to create mount fd for \"%s\" (\"%s\"): %m", what
, type
);
1857 struct mount_attr ma
= {
1858 .attr_set
= ms_flags_to_mount_attr(f
) | (userns_fd
>= 0 ? MOUNT_ATTR_IDMAP
: 0),
1859 .userns_fd
= userns_fd
,
1861 if (ma
.attr_set
!= 0 && mount_setattr(mnt_fd
, "", AT_EMPTY_PATH
|AT_RECURSIVE
, &ma
, MOUNT_ATTR_SIZE_VER0
) < 0)
1862 return log_full_errno(error_log_level
,
1864 "Failed to set mount flags for \"%s\" (\"%s\"): %m",
1868 return TAKE_FD(mnt_fd
);
1871 char* umount_and_rmdir_and_free(char *p
) {
1876 (void) umount_recursive(p
, 0);
1881 char* umount_and_free(char *p
) {
1886 (void) umount_recursive(p
, 0);
1890 char* umount_and_unlink_and_free(char *p
) {
1895 (void) umount2(p
, 0);
1900 int path_get_mount_info_at(
1905 char **ret_source
) {
1907 _cleanup_(mnt_free_tablep
) struct libmnt_table
*table
= NULL
;
1908 _cleanup_(mnt_free_iterp
) struct libmnt_iter
*iter
= NULL
;
1911 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
1913 r
= path_get_mnt_id_at(dir_fd
, path
, &mnt_id
);
1915 return log_debug_errno(r
, "Failed to get mount ID: %m");
1917 /* When getting options is requested, we also need to parse utab, otherwise userspace options like
1918 * "_netdev" will be lost. */
1920 r
= libmount_parse_with_utab(&table
, &iter
);
1922 r
= libmount_parse_mountinfo(/* source = */ NULL
, &table
, &iter
);
1924 return log_debug_errno(r
, "Failed to parse /proc/self/mountinfo: %m");
1927 struct libmnt_fs
*fs
;
1929 r
= mnt_table_next_fs(table
, iter
, &fs
);
1933 return log_debug_errno(r
, "Failed to get next entry from /proc/self/mountinfo: %m");
1935 if (mnt_fs_get_id(fs
) != mnt_id
)
1938 _cleanup_free_
char *fstype
= NULL
, *options
= NULL
, *source
= NULL
;
1941 fstype
= strdup(strempty(mnt_fs_get_fstype(fs
)));
1943 return log_oom_debug();
1947 options
= strdup(strempty(mnt_fs_get_options(fs
)));
1949 return log_oom_debug();
1953 source
= strdup(strempty(mnt_fs_get_source(fs
)));
1955 return log_oom_debug();
1959 *ret_fstype
= TAKE_PTR(fstype
);
1961 *ret_options
= TAKE_PTR(options
);
1963 *ret_source
= TAKE_PTR(source
);
1968 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE
), "Cannot find mount ID %i from /proc/self/mountinfo.", mnt_id
);
1971 int path_is_network_fs_harder_at(int dir_fd
, const char *path
) {
1972 _cleanup_close_
int fd
= -EBADF
;
1975 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
1977 fd
= xopenat(dir_fd
, path
, O_PATH
| O_CLOEXEC
| O_NOFOLLOW
);
1981 r
= fd_is_network_fs(fd
);
1985 _cleanup_free_
char *fstype
= NULL
, *options
= NULL
;
1986 r
= path_get_mount_info_at(fd
, /* path = */ NULL
, &fstype
, &options
, /* ret_source = */ NULL
);
1990 if (fstype_is_network(fstype
))
1993 if (fstab_test_option(options
, "_netdev\0"))