1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
7 #include <sys/statvfs.h>
9 #include <linux/loop.h>
14 #include "alloc-util.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"
25 #include "label-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 "sort-util.h"
38 #include "stat-util.h"
39 #include "stdio-util.h"
40 #include "string-table.h"
41 #include "string-util.h"
43 #include "tmpfile-util.h"
44 #include "user-util.h"
46 int umount_recursive_full(const char *prefix
, int flags
, char **keep
) {
47 _cleanup_fclose_
FILE *f
= NULL
;
50 /* Try to umount everything recursively below a directory. Also, take care of stacked mounts, and
51 * keep unmounting them until they are gone. */
53 f
= fopen("/proc/self/mountinfo", "re"); /* Pin the file, in case we unmount /proc/ as part of the logic here */
55 return log_debug_errno(errno
, "Failed to open /proc/self/mountinfo: %m");
58 _cleanup_(mnt_free_tablep
) struct libmnt_table
*table
= NULL
;
59 _cleanup_(mnt_free_iterp
) struct libmnt_iter
*iter
= NULL
;
62 r
= libmount_parse("/proc/self/mountinfo", f
, &table
, &iter
);
64 return log_debug_errno(r
, "Failed to parse /proc/self/mountinfo: %m");
67 bool shall_keep
= false;
71 r
= mnt_table_next_fs(table
, iter
, &fs
);
75 return log_debug_errno(r
, "Failed to get next entry from /proc/self/mountinfo: %m");
77 path
= mnt_fs_get_target(fs
);
81 if (prefix
&& !path_startswith(path
, prefix
)) {
82 log_trace("Not unmounting %s, outside of prefix: %s", path
, prefix
);
87 /* Match against anything in the path to the dirs to keep, or below the dirs to keep */
88 if (path_startswith(path
, *k
) || path_startswith(*k
, path
)) {
93 log_debug("Not unmounting %s, referenced by keep list.", path
);
97 if (umount2(path
, flags
| UMOUNT_NOFOLLOW
) < 0) {
98 log_debug_errno(errno
, "Failed to umount %s, ignoring: %m", path
);
102 log_trace("Successfully unmounted %s", path
);
119 #define MS_CONVERTIBLE_FLAGS (MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_NOSYMFOLLOW)
121 static uint64_t ms_flags_to_mount_attr(unsigned long a
) {
124 if (FLAGS_SET(a
, MS_RDONLY
))
125 f
|= MOUNT_ATTR_RDONLY
;
127 if (FLAGS_SET(a
, MS_NOSUID
))
128 f
|= MOUNT_ATTR_NOSUID
;
130 if (FLAGS_SET(a
, MS_NODEV
))
131 f
|= MOUNT_ATTR_NODEV
;
133 if (FLAGS_SET(a
, MS_NOEXEC
))
134 f
|= MOUNT_ATTR_NOEXEC
;
136 if (FLAGS_SET(a
, MS_NOSYMFOLLOW
))
137 f
|= MOUNT_ATTR_NOSYMFOLLOW
;
142 static bool skip_mount_set_attr
= false;
144 /* Use this function only if you do not have direct access to /proc/self/mountinfo but the caller can open it
145 * for you. This is the case when /proc is masked or not mounted. Otherwise, use bind_remount_recursive. */
146 int bind_remount_recursive_with_mountinfo(
148 unsigned long new_flags
,
149 unsigned long flags_mask
,
151 FILE *proc_self_mountinfo
) {
153 _cleanup_fclose_
FILE *proc_self_mountinfo_opened
= NULL
;
154 _cleanup_set_free_ Set
*done
= NULL
;
155 unsigned n_tries
= 0;
160 if ((flags_mask
& ~MS_CONVERTIBLE_FLAGS
) == 0 && strv_isempty(deny_list
) && !skip_mount_set_attr
) {
161 /* Let's take a shortcut for all the flags we know how to convert into mount_setattr() flags */
163 if (mount_setattr(AT_FDCWD
, prefix
, AT_SYMLINK_NOFOLLOW
|AT_RECURSIVE
,
164 &(struct mount_attr
) {
165 .attr_set
= ms_flags_to_mount_attr(new_flags
& flags_mask
),
166 .attr_clr
= ms_flags_to_mount_attr(~new_flags
& flags_mask
),
167 }, MOUNT_ATTR_SIZE_VER0
) < 0) {
169 log_debug_errno(errno
, "mount_setattr() failed, falling back to classic remounting: %m");
171 /* We fall through to classic behaviour if not supported (i.e. kernel < 5.12). We
172 * also do this for all other kinds of errors since they are so many different, and
173 * mount_setattr() has no graceful mode where it continues despite seeing errors one
174 * some mounts, but we want that. Moreover mount_setattr() only works on the mount
175 * point inode itself, not a non-mount point inode, and we want to support arbitrary
178 if (ERRNO_IS_NOT_SUPPORTED(errno
)) /* if not supported, then don't bother at all anymore */
179 skip_mount_set_attr
= true;
181 return 0; /* Nice, this worked! */
184 if (!proc_self_mountinfo
) {
185 r
= fopen_unlocked("/proc/self/mountinfo", "re", &proc_self_mountinfo_opened
);
189 proc_self_mountinfo
= proc_self_mountinfo_opened
;
192 /* Recursively remount a directory (and all its submounts) with desired flags (MS_READONLY,
193 * MS_NOSUID, MS_NOEXEC). If the directory is already mounted, we reuse the mount and simply mark it
194 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write operation), ditto for other flags. If it
195 * isn't we first make it one. Afterwards we apply (or remove) the flags to all submounts we can
196 * access, too. When mounts are stacked on the same mount point we only care for each individual
197 * "top-level" mount on each point, as we cannot influence/access the underlying mounts anyway. We do
198 * not have any effect on future submounts that might get propagated, they might be writable
199 * etc. This includes future submounts that have been triggered via autofs. Also note that we can't
200 * operate atomically here. Mounts established while we process the tree might or might not get
201 * noticed and thus might or might not be covered.
203 * If the "deny_list" parameter is specified it may contain a list of subtrees to exclude from the
204 * remount operation. Note that we'll ignore the deny list for the top-level path. */
207 _cleanup_(mnt_free_tablep
) struct libmnt_table
*table
= NULL
;
208 _cleanup_(mnt_free_iterp
) struct libmnt_iter
*iter
= NULL
;
209 _cleanup_hashmap_free_ Hashmap
*todo
= NULL
;
210 bool top_autofs
= false;
212 if (n_tries
++ >= 32) /* Let's not retry this loop forever */
215 rewind(proc_self_mountinfo
);
217 r
= libmount_parse("/proc/self/mountinfo", proc_self_mountinfo
, &table
, &iter
);
219 return log_debug_errno(r
, "Failed to parse /proc/self/mountinfo: %m");
222 _cleanup_free_
char *d
= NULL
;
223 const char *path
, *type
, *opts
;
224 unsigned long flags
= 0;
225 struct libmnt_fs
*fs
;
227 r
= mnt_table_next_fs(table
, iter
, &fs
);
228 if (r
== 1) /* EOF */
231 return log_debug_errno(r
, "Failed to get next entry from /proc/self/mountinfo: %m");
233 path
= mnt_fs_get_target(fs
);
237 if (!path_startswith(path
, prefix
))
240 type
= mnt_fs_get_fstype(fs
);
244 /* Let's ignore autofs mounts. If they aren't triggered yet, we want to avoid
245 * triggering them, as we don't make any guarantees for future submounts anyway. If
246 * they are already triggered, then we will find another entry for this. */
247 if (streq(type
, "autofs")) {
248 top_autofs
= top_autofs
|| path_equal(path
, prefix
);
252 if (set_contains(done
, path
))
255 /* Ignore this mount if it is deny-listed, but only if it isn't the top-level mount
256 * we shall operate on. */
257 if (!path_equal(path
, prefix
)) {
258 bool deny_listed
= false;
260 STRV_FOREACH(i
, deny_list
) {
261 if (path_equal(*i
, prefix
))
264 if (!path_startswith(*i
, prefix
))
267 if (path_startswith(path
, *i
)) {
269 log_trace("Not remounting %s deny-listed by %s, called for %s", path
, *i
, prefix
);
278 opts
= mnt_fs_get_vfs_options(fs
);
280 r
= mnt_optstr_get_flags(opts
, &flags
, mnt_get_builtin_optmap(MNT_LINUX_MAP
));
282 log_debug_errno(r
, "Could not get flags for '%s', ignoring: %m", path
);
289 r
= hashmap_ensure_put(&todo
, &path_hash_ops_free
, d
, ULONG_TO_PTR(flags
));
291 /* If the same path was recorded, but with different mount flags, update it:
292 * it means a mount point is overmounted, and libmount returns the "bottom" (or
293 * older one) first, but we want to reapply the flags from the "top" (or newer
294 * one). See: https://github.com/systemd/systemd/issues/20032
295 * Note that this shouldn't really fail, as we were just told that the key
296 * exists, and it's an update so we want 'd' to be freed immediately. */
297 r
= hashmap_update(todo
, d
, ULONG_TO_PTR(flags
));
304 /* Check if the top-level directory was among what we have seen so far. For that check both
305 * 'done' and 'todo'. Also check 'top_autofs' because if the top-level dir is an autofs we'll
306 * not include it in either set but will set this bool. */
307 if (!set_contains(done
, prefix
) &&
308 !(top_autofs
|| hashmap_contains(todo
, prefix
))) {
310 /* The prefix directory itself is not yet a mount, make it one. */
311 r
= mount_nofollow(prefix
, prefix
, NULL
, MS_BIND
|MS_REC
, NULL
);
315 /* Immediately rescan, so that we pick up the new mount's flags */
319 /* If we have no submounts to process anymore, we are done */
320 if (hashmap_isempty(todo
))
327 /* Take the first mount from our list of mounts to still process */
328 flags
= PTR_TO_ULONG(hashmap_steal_first_key_and_value(todo
, (void**) &x
));
332 r
= set_ensure_consume(&done
, &path_hash_ops_free
, x
);
333 if (IN_SET(r
, 0, -EEXIST
))
334 continue; /* Already done */
338 /* Now, remount this with the new flags set, but exclude MS_RELATIME from it. (It's
339 * the default anyway, thus redundant, and in userns we'll get an error if we try to
340 * explicitly enable it) */
341 r
= mount_nofollow(NULL
, x
, NULL
, ((flags
& ~flags_mask
)|MS_BIND
|MS_REMOUNT
|new_flags
) & ~MS_RELATIME
, NULL
);
345 /* OK, so the remount of this entry failed. We'll ultimately ignore this in
346 * almost all cases (there are simply so many reasons why this can fail,
347 * think autofs, NFS, FUSE, …), but let's generate useful debug messages at
350 q
= path_is_mount_point(x
);
351 if (IN_SET(q
, 0, -ENOENT
)) {
352 /* Hmm, whaaaa? The mount point is not actually a mount point? Then
353 * it is either obstructed by a later mount or somebody has been
354 * racing against us and removed it. Either way the mount point
355 * doesn't matter to us, let's ignore it hence. */
356 log_debug_errno(r
, "Mount point '%s' to remount is not a mount point anymore, ignoring remount failure: %m", x
);
359 if (q
< 0) /* Any other error on this? Just log and continue */
360 log_debug_errno(q
, "Failed to determine whether '%s' is a mount point or not, ignoring: %m", x
);
362 if (((flags
^ new_flags
) & flags_mask
& ~MS_RELATIME
) == 0) { /* ignore MS_RELATIME while comparing */
363 log_debug_errno(r
, "Couldn't remount '%s', but the flags already match what we want, hence ignoring: %m", x
);
367 /* Make this fatal if this is the top-level mount */
368 if (path_equal(x
, prefix
))
371 /* If this is not the top-level mount, then handle this gracefully: log but
372 * otherwise ignore. With NFS, FUSE, autofs there are just too many reasons
373 * this might fail without a chance for us to do anything about it, let's
374 * hence be strict on the top-level mount and lenient on the inner ones. */
375 log_debug_errno(r
, "Couldn't remount submount '%s' for unexpected reason, ignoring: %m", x
);
379 log_trace("Remounted %s.", x
);
384 int bind_remount_one_with_mountinfo(
386 unsigned long new_flags
,
387 unsigned long flags_mask
,
388 FILE *proc_self_mountinfo
) {
390 _cleanup_(mnt_free_tablep
) struct libmnt_table
*table
= NULL
;
391 unsigned long flags
= 0;
392 struct libmnt_fs
*fs
;
397 assert(proc_self_mountinfo
);
399 if ((flags_mask
& ~MS_CONVERTIBLE_FLAGS
) == 0 && !skip_mount_set_attr
) {
400 /* Let's take a shortcut for all the flags we know how to convert into mount_setattr() flags */
402 if (mount_setattr(AT_FDCWD
, path
, AT_SYMLINK_NOFOLLOW
,
403 &(struct mount_attr
) {
404 .attr_set
= ms_flags_to_mount_attr(new_flags
& flags_mask
),
405 .attr_clr
= ms_flags_to_mount_attr(~new_flags
& flags_mask
),
406 }, MOUNT_ATTR_SIZE_VER0
) < 0) {
408 log_debug_errno(errno
, "mount_setattr() didn't work, falling back to classic remounting: %m");
410 if (ERRNO_IS_NOT_SUPPORTED(errno
)) /* if not supported, then don't bother at all anymore */
411 skip_mount_set_attr
= true;
413 return 0; /* Nice, this worked! */
416 rewind(proc_self_mountinfo
);
418 table
= mnt_new_table();
422 r
= mnt_table_parse_stream(table
, proc_self_mountinfo
, "/proc/self/mountinfo");
426 fs
= mnt_table_find_target(table
, path
, MNT_ITER_FORWARD
);
428 if (laccess(path
, F_OK
) < 0) /* Hmm, it's not in the mount table, but does it exist at all? */
431 return -EINVAL
; /* Not a mount point we recognize */
434 opts
= mnt_fs_get_vfs_options(fs
);
436 r
= mnt_optstr_get_flags(opts
, &flags
, mnt_get_builtin_optmap(MNT_LINUX_MAP
));
438 log_debug_errno(r
, "Could not get flags for '%s', ignoring: %m", path
);
441 r
= mount_nofollow(NULL
, path
, NULL
, ((flags
& ~flags_mask
)|MS_BIND
|MS_REMOUNT
|new_flags
) & ~MS_RELATIME
, NULL
);
443 if (((flags
^ new_flags
) & flags_mask
& ~MS_RELATIME
) != 0) /* Ignore MS_RELATIME again,
444 * since kernel adds it in
445 * everywhere, because it's the
449 /* Let's handle redundant remounts gracefully */
450 log_debug_errno(r
, "Failed to remount '%s' but flags already match what we want, ignoring: %m", path
);
456 static int mount_switch_root_pivot(int fd_newroot
, const char *path
) {
457 assert(fd_newroot
>= 0);
460 /* Let the kernel tuck the new root under the old one. */
461 if (pivot_root(".", ".") < 0)
462 return log_debug_errno(errno
, "Failed to pivot root to new rootfs '%s': %m", path
);
464 /* Get rid of the old root and reveal our brand new root. (This will always operate on the top-most
465 * mount on our cwd, regardless what our current directory actually points to.) */
466 if (umount2(".", MNT_DETACH
) < 0)
467 return log_debug_errno(errno
, "Failed to unmount old rootfs: %m");
472 static int mount_switch_root_move(int fd_newroot
, const char *path
) {
473 assert(fd_newroot
>= 0);
476 /* Move the new root fs */
477 if (mount(".", "/", NULL
, MS_MOVE
, NULL
) < 0)
478 return log_debug_errno(errno
, "Failed to move new rootfs '%s': %m", path
);
480 /* Also change root dir */
482 return log_debug_errno(errno
, "Failed to chroot to new rootfs '%s': %m", path
);
487 int mount_switch_root_full(const char *path
, unsigned long mount_propagation_flag
, bool force_ms_move
) {
488 _cleanup_close_
int fd_newroot
= -EBADF
;
489 int r
, is_current_root
;
492 assert(mount_propagation_flag_is_valid(mount_propagation_flag
));
494 fd_newroot
= open(path
, O_PATH
|O_DIRECTORY
|O_CLOEXEC
|O_NOFOLLOW
);
496 return log_debug_errno(errno
, "Failed to open new rootfs '%s': %m", path
);
498 is_current_root
= path_is_root_at(fd_newroot
, NULL
);
499 if (is_current_root
< 0)
500 return log_debug_errno(is_current_root
, "Failed to determine if target dir is our root already: %m");
502 /* Change into the new rootfs. */
503 if (fchdir(fd_newroot
) < 0)
504 return log_debug_errno(errno
, "Failed to chdir into new rootfs '%s': %m", path
);
506 /* Make this a NOP if we are supposed to switch to our current root fs. After all, both pivot_root()
507 * and MS_MOVE don't like that. */
508 if (!is_current_root
) {
509 if (!force_ms_move
) {
510 r
= mount_switch_root_pivot(fd_newroot
, path
);
512 log_debug_errno(r
, "Failed to pivot into new rootfs '%s', will try to use MS_MOVE instead: %m", path
);
513 force_ms_move
= true;
517 /* Failed to pivot_root() fallback to MS_MOVE. For example, this may happen if the rootfs is
518 * an initramfs in which case pivot_root() isn't supported. */
519 r
= mount_switch_root_move(fd_newroot
, path
);
521 return log_debug_errno(r
, "Failed to switch to new rootfs '%s' with MS_MOVE: %m", path
);
525 /* Finally, let's establish the requested propagation flags. */
526 if (mount_propagation_flag
== 0)
529 if (mount(NULL
, ".", NULL
, mount_propagation_flag
| MS_REC
, 0) < 0)
530 return log_debug_errno(errno
, "Failed to turn new rootfs '%s' into %s mount: %m",
531 mount_propagation_flag_to_string(mount_propagation_flag
), path
);
536 int repeat_unmount(const char *path
, int flags
) {
541 /* If there are multiple mounts on a mount point, this
542 * removes them all */
545 if (umount2(path
, flags
) < 0) {
557 int mode_to_inaccessible_node(
558 const char *runtime_dir
,
562 /* This function maps a node type to a corresponding inaccessible file node. These nodes are created
563 * during early boot by PID 1. In some cases we lacked the privs to create the character and block
564 * devices (maybe because we run in an userns environment, or miss CAP_SYS_MKNOD, or run with a
565 * devices policy that excludes device nodes with major and minor of 0), but that's fine, in that
566 * case we use an AF_UNIX file node instead, which is not the same, but close enough for most
567 * uses. And most importantly, the kernel allows bind mounts from socket nodes to any non-directory
568 * file nodes, and that's the most important thing that matters.
570 * Note that the runtime directory argument shall be the top-level runtime directory, i.e. /run/ if
571 * we operate in system context and $XDG_RUNTIME_DIR if we operate in user context. */
573 _cleanup_free_
char *d
= NULL
;
579 runtime_dir
= "/run";
584 node
= inode_type_to_string(mode
);
588 d
= path_join(runtime_dir
, "systemd/inaccessible", node
);
592 /* On new kernels unprivileged users are permitted to create 0:0 char device nodes (because they also
593 * act as whiteout inode for overlayfs), but no other char or block device nodes. On old kernels no
594 * device node whatsoever may be created by unprivileged processes. Hence, if the caller asks for the
595 * inaccessible block device node let's see if the block device node actually exists, and if not,
596 * fall back to the character device node. From there fall back to the socket device node. This means
597 * in the best case we'll get the right device node type — but if not we'll hopefully at least get a
598 * device node at all. */
601 access(d
, F_OK
) < 0 && errno
== ENOENT
) {
603 d
= path_join(runtime_dir
, "/systemd/inaccessible/chr");
608 if (IN_SET(mode
& S_IFMT
, S_IFBLK
, S_IFCHR
) &&
609 access(d
, F_OK
) < 0 && errno
== ENOENT
) {
611 d
= path_join(runtime_dir
, "/systemd/inaccessible/sock");
620 int mount_flags_to_string(unsigned long flags
, char **ret
) {
621 static const struct {
625 { .flag
= MS_RDONLY
, .name
= "MS_RDONLY", },
626 { .flag
= MS_NOSUID
, .name
= "MS_NOSUID", },
627 { .flag
= MS_NODEV
, .name
= "MS_NODEV", },
628 { .flag
= MS_NOEXEC
, .name
= "MS_NOEXEC", },
629 { .flag
= MS_SYNCHRONOUS
, .name
= "MS_SYNCHRONOUS", },
630 { .flag
= MS_REMOUNT
, .name
= "MS_REMOUNT", },
631 { .flag
= MS_MANDLOCK
, .name
= "MS_MANDLOCK", },
632 { .flag
= MS_DIRSYNC
, .name
= "MS_DIRSYNC", },
633 { .flag
= MS_NOSYMFOLLOW
, .name
= "MS_NOSYMFOLLOW", },
634 { .flag
= MS_NOATIME
, .name
= "MS_NOATIME", },
635 { .flag
= MS_NODIRATIME
, .name
= "MS_NODIRATIME", },
636 { .flag
= MS_BIND
, .name
= "MS_BIND", },
637 { .flag
= MS_MOVE
, .name
= "MS_MOVE", },
638 { .flag
= MS_REC
, .name
= "MS_REC", },
639 { .flag
= MS_SILENT
, .name
= "MS_SILENT", },
640 { .flag
= MS_POSIXACL
, .name
= "MS_POSIXACL", },
641 { .flag
= MS_UNBINDABLE
, .name
= "MS_UNBINDABLE", },
642 { .flag
= MS_PRIVATE
, .name
= "MS_PRIVATE", },
643 { .flag
= MS_SLAVE
, .name
= "MS_SLAVE", },
644 { .flag
= MS_SHARED
, .name
= "MS_SHARED", },
645 { .flag
= MS_RELATIME
, .name
= "MS_RELATIME", },
646 { .flag
= MS_KERNMOUNT
, .name
= "MS_KERNMOUNT", },
647 { .flag
= MS_I_VERSION
, .name
= "MS_I_VERSION", },
648 { .flag
= MS_STRICTATIME
, .name
= "MS_STRICTATIME", },
649 { .flag
= MS_LAZYTIME
, .name
= "MS_LAZYTIME", },
651 _cleanup_free_
char *str
= NULL
;
655 for (size_t i
= 0; i
< ELEMENTSOF(map
); i
++)
656 if (flags
& map
[i
].flag
) {
657 if (!strextend_with_separator(&str
, "|", map
[i
].name
))
659 flags
&= ~map
[i
].flag
;
662 if (!str
|| flags
!= 0)
663 if (strextendf_with_separator(&str
, "|", "%lx", flags
) < 0)
666 *ret
= TAKE_PTR(str
);
670 int mount_verbose_full(
677 bool follow_symlink
) {
679 _cleanup_free_
char *fl
= NULL
, *o
= NULL
;
683 r
= mount_option_mangle(options
, flags
, &f
, &o
);
685 return log_full_errno(error_log_level
, r
,
686 "Failed to mangle mount options %s: %m",
689 (void) mount_flags_to_string(f
, &fl
);
691 if (FLAGS_SET(f
, MS_REMOUNT
|MS_BIND
))
692 log_debug("Changing mount flags %s (%s \"%s\")...",
693 where
, strnull(fl
), strempty(o
));
694 else if (f
& MS_REMOUNT
)
695 log_debug("Remounting superblock %s (%s \"%s\")...",
696 where
, strnull(fl
), strempty(o
));
697 else if (f
& (MS_SHARED
|MS_PRIVATE
|MS_SLAVE
|MS_UNBINDABLE
))
698 log_debug("Changing mount propagation %s (%s \"%s\")",
699 where
, strnull(fl
), strempty(o
));
700 else if (f
& MS_BIND
)
701 log_debug("Bind-mounting %s on %s (%s \"%s\")...",
702 what
, where
, strnull(fl
), strempty(o
));
703 else if (f
& MS_MOVE
)
704 log_debug("Moving mount %s %s %s (%s \"%s\")...",
705 what
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), where
, strnull(fl
), strempty(o
));
707 log_debug("Mounting %s (%s) on %s (%s \"%s\")...",
708 strna(what
), strna(type
), where
, strnull(fl
), strempty(o
));
711 r
= RET_NERRNO(mount(what
, where
, type
, f
, o
));
713 r
= mount_nofollow(what
, where
, type
, f
, o
);
715 return log_full_errno(error_log_level
, r
,
716 "Failed to mount %s (type %s) on %s (%s \"%s\"): %m",
717 strna(what
), strna(type
), where
, strnull(fl
), strempty(o
));
728 log_debug("Umounting %s...", what
);
730 if (umount2(what
, flags
) < 0)
731 return log_full_errno(error_log_level
, errno
,
732 "Failed to unmount %s: %m", what
);
737 int mount_exchange_graceful(int fsmount_fd
, const char *dest
, bool mount_beneath
) {
740 assert(fsmount_fd
>= 0);
743 /* First, try to mount beneath an existing mount point, and if that works, umount the old mount,
744 * which is now at the top. This will ensure we can atomically replace a mount. Note that this works
745 * also in the case where there are submounts down the tree. Mount propagation is allowed but
746 * restricted to layouts that don't end up propagation the new mount on top of the mount stack. If
747 * this is not supported (minimum kernel v6.5), or if there is no mount on the mountpoint, we get
748 * -EINVAL and then we fallback to normal mounting. */
750 r
= RET_NERRNO(move_mount(
755 MOVE_MOUNT_F_EMPTY_PATH
| (mount_beneath
? MOVE_MOUNT_BENEATH
: 0)));
757 if (r
== -EINVAL
) { /* Fallback if mount_beneath is not supported */
759 "Failed to mount beneath '%s', falling back to overmount",
761 return RET_NERRNO(move_mount(
766 MOVE_MOUNT_F_EMPTY_PATH
));
769 if (r
>= 0) /* If it is, now remove the old mount */
770 return umount_verbose(LOG_DEBUG
, dest
, UMOUNT_NOFOLLOW
|MNT_DETACH
);
776 int mount_option_mangle(
778 unsigned long mount_flags
,
779 unsigned long *ret_mount_flags
,
780 char **ret_remaining_options
) {
782 const struct libmnt_optmap
*map
;
783 _cleanup_free_
char *ret
= NULL
;
786 /* This extracts mount flags from the mount options, and stores
787 * non-mount-flag options to '*ret_remaining_options'.
789 * "rw,nosuid,nodev,relatime,size=1630748k,mode=0700,uid=1000,gid=1000"
790 * is split to MS_NOSUID|MS_NODEV|MS_RELATIME and
791 * "size=1630748k,mode=0700,uid=1000,gid=1000".
792 * See more examples in test-mount-util.c.
794 * If 'options' does not contain any non-mount-flag options,
795 * then '*ret_remaining_options' is set to NULL instead of empty string.
796 * The validity of options stored in '*ret_remaining_options' is not checked.
797 * If 'options' is NULL, this just copies 'mount_flags' to *ret_mount_flags. */
799 assert(ret_mount_flags
);
800 assert(ret_remaining_options
);
802 map
= mnt_get_builtin_optmap(MNT_LINUX_MAP
);
806 for (const char *p
= options
;;) {
807 _cleanup_free_
char *word
= NULL
;
808 const struct libmnt_optmap
*ent
;
810 r
= extract_first_word(&p
, &word
, ",", EXTRACT_KEEP_QUOTE
);
816 for (ent
= map
; ent
->name
; ent
++) {
817 /* All entries in MNT_LINUX_MAP do not take any argument.
818 * Thus, ent->name does not contain "=" or "[=]". */
819 if (!streq(word
, ent
->name
))
822 if (!(ent
->mask
& MNT_INVERT
))
823 mount_flags
|= ent
->id
;
825 mount_flags
&= ~ent
->id
;
830 /* If 'word' is not a mount flag, then store it in '*ret_remaining_options'. */
832 !startswith_no_case(word
, "x-") &&
833 !strextend_with_separator(&ret
, ",", word
))
837 *ret_mount_flags
= mount_flags
;
838 *ret_remaining_options
= TAKE_PTR(ret
);
843 static int mount_in_namespace_legacy(
844 const char *chased_src_path
,
846 struct stat
*chased_src_st
,
847 const char *propagate_path
,
848 const char *incoming_path
,
854 bool make_file_or_directory
,
855 const MountOptions
*options
,
856 const ImagePolicy
*image_policy
,
859 _cleanup_close_pair_
int errno_pipe_fd
[2] = EBADF_PAIR
;
860 char mount_slave
[] = "/tmp/propagate.XXXXXX", *mount_tmp
, *mount_outside
, *p
;
861 bool mount_slave_created
= false, mount_slave_mounted
= false,
862 mount_tmp_created
= false, mount_tmp_mounted
= false,
863 mount_outside_created
= false, mount_outside_mounted
= false;
867 assert(chased_src_path
);
868 assert(chased_src_fd
>= 0);
869 assert(chased_src_st
);
870 assert(propagate_path
);
871 assert(incoming_path
);
873 assert(pidns_fd
>= 0);
874 assert(mntns_fd
>= 0);
875 assert(root_fd
>= 0);
876 assert(!options
|| is_image
);
878 p
= strjoina(propagate_path
, "/");
879 r
= laccess(p
, F_OK
);
881 return log_debug_errno(r
== -ENOENT
? SYNTHETIC_ERRNO(EOPNOTSUPP
) : r
, "Target does not allow propagation of mount points");
883 /* Our goal is to install a new bind mount into the container,
884 possibly read-only. This is irritatingly complex
885 unfortunately, currently.
887 First, we start by creating a private playground in /tmp,
888 that we can mount MS_SLAVE. (Which is necessary, since
889 MS_MOVE cannot be applied to mounts with MS_SHARED parent
892 if (!mkdtemp(mount_slave
))
893 return log_debug_errno(errno
, "Failed to create playground %s: %m", mount_slave
);
895 mount_slave_created
= true;
897 r
= mount_nofollow_verbose(LOG_DEBUG
, mount_slave
, mount_slave
, NULL
, MS_BIND
, NULL
);
901 mount_slave_mounted
= true;
903 r
= mount_nofollow_verbose(LOG_DEBUG
, NULL
, mount_slave
, NULL
, MS_SLAVE
, NULL
);
907 /* Second, we mount the source file or directory to a directory inside of our MS_SLAVE playground. */
908 mount_tmp
= strjoina(mount_slave
, "/mount");
910 r
= mkdir_p(mount_tmp
, 0700);
912 r
= make_mount_point_inode_from_stat(chased_src_st
, mount_tmp
, 0700);
914 log_debug_errno(r
, "Failed to create temporary mount point %s: %m", mount_tmp
);
918 mount_tmp_created
= true;
921 r
= verity_dissect_and_mount(
927 /* required_host_os_release_id= */ NULL
,
928 /* required_host_os_release_version_id= */ NULL
,
929 /* required_host_os_release_sysext_level= */ NULL
,
930 /* required_host_os_release_confext_level= */ NULL
,
931 /* required_sysext_scope= */ NULL
,
932 /* ret_image= */ NULL
);
934 r
= mount_follow_verbose(LOG_DEBUG
, FORMAT_PROC_FD_PATH(chased_src_fd
), mount_tmp
, NULL
, MS_BIND
, NULL
);
938 mount_tmp_mounted
= true;
940 /* Third, we remount the new bind mount read-only if requested. */
942 r
= mount_nofollow_verbose(LOG_DEBUG
, NULL
, mount_tmp
, NULL
, MS_BIND
|MS_REMOUNT
|MS_RDONLY
, NULL
);
947 /* Fourth, we move the new bind mount into the propagation directory. This way it will appear there read-only
950 mount_outside
= strjoina(propagate_path
, "/XXXXXX");
951 if (is_image
|| S_ISDIR(chased_src_st
->st_mode
))
952 r
= mkdtemp(mount_outside
) ? 0 : -errno
;
954 r
= mkostemp_safe(mount_outside
);
958 log_debug_errno(r
, "Cannot create propagation file or directory %s: %m", mount_outside
);
962 mount_outside_created
= true;
964 r
= mount_nofollow_verbose(LOG_DEBUG
, mount_tmp
, mount_outside
, NULL
, MS_MOVE
, NULL
);
968 mount_outside_mounted
= true;
969 mount_tmp_mounted
= false;
971 if (is_image
|| S_ISDIR(chased_src_st
->st_mode
))
972 (void) rmdir(mount_tmp
);
974 (void) unlink(mount_tmp
);
975 mount_tmp_created
= false;
977 (void) umount_verbose(LOG_DEBUG
, mount_slave
, UMOUNT_NOFOLLOW
);
978 mount_slave_mounted
= false;
980 (void) rmdir(mount_slave
);
981 mount_slave_created
= false;
983 if (pipe2(errno_pipe_fd
, O_CLOEXEC
|O_NONBLOCK
) < 0) {
984 log_debug_errno(errno
, "Failed to create pipe: %m");
988 r
= namespace_fork("(sd-bindmnt)", "(sd-bindmnt-inner)", NULL
, 0, FORK_RESET_SIGNALS
|FORK_DEATHSIG_SIGTERM
,
989 pidns_fd
, mntns_fd
, -1, -1, root_fd
, &child
);
993 _cleanup_free_
char *mount_outside_fn
= NULL
, *mount_inside
= NULL
;
995 errno_pipe_fd
[0] = safe_close(errno_pipe_fd
[0]);
997 if (make_file_or_directory
) {
999 (void) mkdir_parents(dest
, 0755);
1000 (void) make_mount_point_inode_from_stat(chased_src_st
, dest
, 0700);
1002 (void) mkdir_p(dest
, 0755);
1005 /* Fifth, move the mount to the right place inside */
1006 r
= path_extract_filename(mount_outside
, &mount_outside_fn
);
1008 log_debug_errno(r
, "Failed to extract filename from propagation file or directory '%s': %m", mount_outside
);
1012 mount_inside
= path_join(incoming_path
, mount_outside_fn
);
1013 if (!mount_inside
) {
1014 r
= log_oom_debug();
1018 r
= mount_nofollow_verbose(LOG_DEBUG
, mount_inside
, dest
, NULL
, MS_MOVE
, NULL
);
1022 _exit(EXIT_SUCCESS
);
1025 (void) write(errno_pipe_fd
[1], &r
, sizeof(r
));
1026 errno_pipe_fd
[1] = safe_close(errno_pipe_fd
[1]);
1028 _exit(EXIT_FAILURE
);
1031 errno_pipe_fd
[1] = safe_close(errno_pipe_fd
[1]);
1033 r
= wait_for_terminate_and_check("(sd-bindmnt)", child
, 0);
1035 log_debug_errno(r
, "Failed to wait for child: %m");
1038 if (r
!= EXIT_SUCCESS
) {
1039 if (read(errno_pipe_fd
[0], &r
, sizeof(r
)) == sizeof(r
))
1040 log_debug_errno(r
, "Failed to mount: %m");
1042 log_debug("Child failed.");
1047 if (mount_outside_mounted
)
1048 (void) umount_verbose(LOG_DEBUG
, mount_outside
, UMOUNT_NOFOLLOW
);
1049 if (mount_outside_created
) {
1050 if (is_image
|| S_ISDIR(chased_src_st
->st_mode
))
1051 (void) rmdir(mount_outside
);
1053 (void) unlink(mount_outside
);
1056 if (mount_tmp_mounted
)
1057 (void) umount_verbose(LOG_DEBUG
, mount_tmp
, UMOUNT_NOFOLLOW
);
1058 if (mount_tmp_created
) {
1059 if (is_image
|| S_ISDIR(chased_src_st
->st_mode
))
1060 (void) rmdir(mount_tmp
);
1062 (void) unlink(mount_tmp
);
1065 if (mount_slave_mounted
)
1066 (void) umount_verbose(LOG_DEBUG
, mount_slave
, UMOUNT_NOFOLLOW
);
1067 if (mount_slave_created
)
1068 (void) rmdir(mount_slave
);
1073 static int mount_in_namespace(
1074 const PidRef
*target
,
1075 const char *propagate_path
,
1076 const char *incoming_path
,
1080 bool make_file_or_directory
,
1081 const MountOptions
*options
,
1082 const ImagePolicy
*image_policy
,
1085 _cleanup_(dissected_image_unrefp
) DissectedImage
*img
= NULL
;
1086 _cleanup_close_pair_
int errno_pipe_fd
[2] = EBADF_PAIR
;
1087 _cleanup_close_
int mntns_fd
= -EBADF
, root_fd
= -EBADF
, pidns_fd
= -EBADF
, chased_src_fd
= -EBADF
,
1088 new_mount_fd
= -EBADF
;
1089 _cleanup_free_
char *chased_src_path
= NULL
;
1094 assert(propagate_path
);
1095 assert(incoming_path
);
1098 assert(!options
|| is_image
);
1100 if (!pidref_is_set(target
))
1103 r
= namespace_open(target
->pid
, &pidns_fd
, &mntns_fd
, /* ret_netns_fd = */ NULL
, /* ret_userns_fd = */ NULL
, &root_fd
);
1105 return log_debug_errno(r
, "Failed to retrieve FDs of the target process' namespace: %m");
1107 r
= in_same_namespace(target
->pid
, 0, NAMESPACE_MOUNT
);
1109 return log_debug_errno(r
, "Failed to determine if mount namespaces are equal: %m");
1110 /* We can't add new mounts at runtime if the process wasn't started in a namespace */
1112 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to activate bind mount in target, not running in a mount namespace");
1114 r
= pidref_verify(target
);
1116 return log_debug_errno(r
, "Failed to verify target process '" PID_FMT
"': %m", target
->pid
);
1118 r
= chase(src
, NULL
, 0, &chased_src_path
, &chased_src_fd
);
1120 return log_debug_errno(r
, "Failed to resolve source path of %s: %m", src
);
1121 log_debug("Chased source path of %s to %s", src
, chased_src_path
);
1123 if (fstat(chased_src_fd
, &st
) < 0)
1124 return log_debug_errno(errno
, "Failed to stat() resolved source path %s: %m", src
);
1125 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… */
1126 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "Source directory %s can't be a symbolic link", src
);
1128 if (!mount_new_api_supported()) /* Fallback if we can't use the new mount API */
1129 return mount_in_namespace_legacy(
1140 make_file_or_directory
,
1146 r
= verity_dissect_and_mount(
1152 /* required_host_os_release_id= */ NULL
,
1153 /* required_host_os_release_version_id= */ NULL
,
1154 /* required_host_os_release_sysext_level= */ NULL
,
1155 /* required_host_os_release_confext_level= */ NULL
,
1156 /* required_sysext_scope= */ NULL
,
1159 return log_debug_errno(
1161 "Failed to dissect and mount image %s: %m",
1164 new_mount_fd
= open_tree(
1167 OPEN_TREE_CLONE
|OPEN_TREE_CLOEXEC
|AT_SYMLINK_NOFOLLOW
|AT_EMPTY_PATH
);
1168 if (new_mount_fd
< 0)
1169 return log_debug_errno(
1171 "Failed to open mount point \"%s\": %m",
1174 if (read_only
&& mount_setattr(new_mount_fd
, "", AT_EMPTY_PATH
,
1175 &(struct mount_attr
) {
1176 .attr_set
= MOUNT_ATTR_RDONLY
,
1177 }, MOUNT_ATTR_SIZE_VER0
) < 0)
1178 return log_debug_errno(
1180 "Failed to set mount flags for \"%s\": %m",
1184 if (pipe2(errno_pipe_fd
, O_CLOEXEC
|O_NONBLOCK
) < 0)
1185 return log_debug_errno(errno
, "Failed to create pipe: %m");
1187 r
= namespace_fork("(sd-bindmnt)",
1188 "(sd-bindmnt-inner)",
1189 /* except_fds= */ NULL
,
1190 /* n_except_fds= */ 0,
1191 FORK_RESET_SIGNALS
|FORK_DEATHSIG_SIGTERM
,
1195 /* userns_fd= */ -1,
1199 return log_debug_errno(r
, "Failed to fork off: %m");
1201 errno_pipe_fd
[0] = safe_close(errno_pipe_fd
[0]);
1203 if (make_file_or_directory
)
1204 (void) mkdir_parents(dest
, 0755);
1207 DissectImageFlags f
= DISSECT_IMAGE_TRY_ATOMIC_MOUNT_EXCHANGE
;
1209 if (make_file_or_directory
)
1210 f
|= DISSECT_IMAGE_MKDIR
;
1213 f
|= DISSECT_IMAGE_READ_ONLY
;
1215 r
= dissected_image_mount(
1218 /* uid_shift= */ UID_INVALID
,
1219 /* uid_range= */ UID_INVALID
,
1220 /* userns_fd= */ -EBADF
,
1223 if (make_file_or_directory
)
1224 (void) make_mount_point_inode_from_stat(&st
, dest
, 0700);
1226 r
= mount_exchange_graceful(new_mount_fd
, dest
, /* mount_beneath= */ true);
1229 (void) write(errno_pipe_fd
[1], &r
, sizeof(r
));
1230 errno_pipe_fd
[1] = safe_close(errno_pipe_fd
[1]);
1232 _exit(EXIT_FAILURE
);
1235 _exit(EXIT_SUCCESS
);
1238 errno_pipe_fd
[1] = safe_close(errno_pipe_fd
[1]);
1240 r
= wait_for_terminate_and_check("(sd-bindmnt)", child
, 0);
1242 return log_debug_errno(r
, "Failed to wait for child: %m");
1243 if (r
!= EXIT_SUCCESS
) {
1244 if (read(errno_pipe_fd
[0], &r
, sizeof(r
)) == sizeof(r
))
1245 return log_debug_errno(r
, "Failed to mount: %m");
1247 return log_debug_errno(SYNTHETIC_ERRNO(EPROTO
), "Child failed.");
1253 int bind_mount_in_namespace(
1255 const char *propagate_path
,
1256 const char *incoming_path
,
1260 bool make_file_or_directory
) {
1262 return mount_in_namespace(target
, propagate_path
, incoming_path
, src
, dest
, read_only
, make_file_or_directory
, /* options= */ NULL
, /* image_policy= */ NULL
, /* is_image= */ false);
1265 int mount_image_in_namespace(
1267 const char *propagate_path
,
1268 const char *incoming_path
,
1272 bool make_file_or_directory
,
1273 const MountOptions
*options
,
1274 const ImagePolicy
*image_policy
) {
1276 return mount_in_namespace(target
, propagate_path
, incoming_path
, src
, dest
, read_only
, make_file_or_directory
, options
, image_policy
, /* is_image=*/ true);
1279 int make_mount_point(const char *path
) {
1284 /* If 'path' is already a mount point, does nothing and returns 0. If it is not it makes it one, and returns 1. */
1286 r
= path_is_mount_point(path
);
1288 return log_debug_errno(r
, "Failed to determine whether '%s' is a mount point: %m", path
);
1292 r
= mount_nofollow_verbose(LOG_DEBUG
, path
, path
, NULL
, MS_BIND
|MS_REC
, NULL
);
1299 int fd_make_mount_point(int fd
) {
1304 r
= fd_is_mount_point(fd
, NULL
, 0);
1306 return log_debug_errno(r
, "Failed to determine whether file descriptor is a mount point: %m");
1310 r
= mount_follow_verbose(LOG_DEBUG
, FORMAT_PROC_FD_PATH(fd
), FORMAT_PROC_FD_PATH(fd
), NULL
, MS_BIND
|MS_REC
, NULL
);
1317 int make_userns(uid_t uid_shift
, uid_t uid_range
, uid_t owner
, RemountIdmapping idmapping
) {
1318 _cleanup_close_
int userns_fd
= -EBADF
;
1319 _cleanup_free_
char *line
= NULL
;
1321 /* Allocates a userns file descriptor with the mapping we need. For this we'll fork off a child
1322 * process whose only purpose is to give us a new user namespace. It's killed when we got it. */
1324 if (!userns_shift_range_valid(uid_shift
, uid_range
))
1327 if (IN_SET(idmapping
, REMOUNT_IDMAPPING_NONE
, REMOUNT_IDMAPPING_HOST_ROOT
)) {
1328 if (asprintf(&line
, UID_FMT
" " UID_FMT
" " UID_FMT
"\n", 0u, uid_shift
, uid_range
) < 0)
1329 return log_oom_debug();
1331 /* If requested we'll include an entry in the mapping so that the host root user can make
1332 * changes to the uidmapped mount like it normally would. Specifically, we'll map the user
1333 * with UID_MAPPED_ROOT on the backing fs to UID 0. This is useful, since nspawn code wants
1334 * to create various missing inodes in the OS tree before booting into it, and this becomes
1335 * very easy and straightforward to do if it can just do it under its own regular UID. Note
1336 * that in that case the container's runtime uidmap (i.e. the one the container payload
1337 * processes run in) will leave this UID unmapped, i.e. if we accidentally leave files owned
1338 * by host root in the already uidmapped tree around they'll show up as owned by 'nobody',
1339 * which is safe. (Of course, we shouldn't leave such inodes around, but always chown() them
1340 * to the container's own UID range, but it's good to have a safety net, in case we
1342 if (idmapping
== REMOUNT_IDMAPPING_HOST_ROOT
)
1343 if (strextendf(&line
,
1344 UID_FMT
" " UID_FMT
" " UID_FMT
"\n",
1345 UID_MAPPED_ROOT
, 0u, 1u) < 0)
1346 return log_oom_debug();
1349 if (idmapping
== REMOUNT_IDMAPPING_HOST_OWNER
) {
1350 /* Remap the owner of the bind mounted directory to the root user within the container. This
1351 * way every file written by root within the container to the bind-mounted directory will
1352 * be owned by the original user. All other user will remain unmapped. */
1353 if (asprintf(&line
, UID_FMT
" " UID_FMT
" " UID_FMT
"\n", owner
, uid_shift
, 1u) < 0)
1354 return log_oom_debug();
1357 /* We always assign the same UID and GID ranges */
1358 userns_fd
= userns_acquire(line
, line
);
1360 return log_debug_errno(userns_fd
, "Failed to acquire new userns: %m");
1362 return TAKE_FD(userns_fd
);
1365 int remount_idmap_fd(
1371 assert(userns_fd
>= 0);
1373 /* This remounts all specified paths with the specified userns as idmap. It will do so in in the
1374 * order specified in the strv: the expectation is that the top-level directories are at the
1375 * beginning, and nested directories in the right, so that the tree can be built correctly from left
1378 size_t n
= strv_length(paths
);
1379 if (n
== 0) /* Nothing to do? */
1382 int *mount_fds
= NULL
;
1383 size_t n_mounts_fds
= 0;
1385 mount_fds
= new(int, n
);
1387 return log_oom_debug();
1389 CLEANUP_ARRAY(mount_fds
, n_mounts_fds
, close_many_and_free
);
1391 for (size_t i
= 0; i
< n
; i
++) {
1394 /* Clone the mount point */
1395 mntfd
= mount_fds
[n_mounts_fds
] = open_tree(-EBADF
, paths
[i
], OPEN_TREE_CLONE
| OPEN_TREE_CLOEXEC
);
1396 if (mount_fds
[n_mounts_fds
] < 0)
1397 return log_debug_errno(errno
, "Failed to open tree of mounted filesystem '%s': %m", paths
[i
]);
1401 /* Set the user namespace mapping attribute on the cloned mount point */
1402 if (mount_setattr(mntfd
, "", AT_EMPTY_PATH
,
1403 &(struct mount_attr
) {
1404 .attr_set
= MOUNT_ATTR_IDMAP
,
1405 .userns_fd
= userns_fd
,
1406 }, sizeof(struct mount_attr
)) < 0)
1407 return log_debug_errno(errno
, "Failed to change bind mount attributes for clone of '%s': %m", paths
[i
]);
1410 for (size_t i
= n
; i
> 0; i
--) { /* Unmount the paths right-to-left */
1411 /* Remove the old mount points now that we have a idmapped mounts as replacement for all of them */
1412 r
= umount_verbose(LOG_DEBUG
, paths
[i
-1], UMOUNT_NOFOLLOW
);
1417 for (size_t i
= 0; i
< n
; i
++) { /* Mount the replacement mounts left-to-right */
1418 /* And place the cloned version in its place */
1419 log_debug("Mounting idmapped fs to '%s'", paths
[i
]);
1420 if (move_mount(mount_fds
[i
], "", -EBADF
, paths
[i
], MOVE_MOUNT_F_EMPTY_PATH
) < 0)
1421 return log_debug_errno(errno
, "Failed to attach UID mapped mount to '%s': %m", paths
[i
]);
1427 int remount_idmap(char **p
, uid_t uid_shift
, uid_t uid_range
, uid_t owner
, RemountIdmapping idmapping
) {
1428 _cleanup_close_
int userns_fd
= -EBADF
;
1430 userns_fd
= make_userns(uid_shift
, uid_range
, owner
, idmapping
);
1434 return remount_idmap_fd(p
, userns_fd
);
1437 typedef struct SubMount
{
1442 static void sub_mount_clear(SubMount
*s
) {
1445 s
->path
= mfree(s
->path
);
1446 s
->mount_fd
= safe_close(s
->mount_fd
);
1449 static void sub_mount_array_free(SubMount
*s
, size_t n
) {
1450 assert(s
|| n
== 0);
1452 for (size_t i
= 0; i
< n
; i
++)
1453 sub_mount_clear(s
+ i
);
1458 static int sub_mount_compare(const SubMount
*a
, const SubMount
*b
) {
1464 return path_compare(a
->path
, b
->path
);
1467 static void sub_mount_drop(SubMount
*s
, size_t n
) {
1468 assert(s
|| n
== 0);
1470 for (size_t m
= 0, i
= 1; i
< n
; i
++) {
1471 if (path_startswith(s
[i
].path
, s
[m
].path
))
1472 sub_mount_clear(s
+ i
);
1478 static int get_sub_mounts(
1480 SubMount
**ret_mounts
,
1481 size_t *ret_n_mounts
) {
1482 _cleanup_(mnt_free_tablep
) struct libmnt_table
*table
= NULL
;
1483 _cleanup_(mnt_free_iterp
) struct libmnt_iter
*iter
= NULL
;
1484 SubMount
*mounts
= NULL
;
1488 CLEANUP_ARRAY(mounts
, n
, sub_mount_array_free
);
1492 assert(ret_n_mounts
);
1494 r
= libmount_parse("/proc/self/mountinfo", NULL
, &table
, &iter
);
1496 return log_debug_errno(r
, "Failed to parse /proc/self/mountinfo: %m");
1499 _cleanup_close_
int mount_fd
= -EBADF
;
1500 _cleanup_free_
char *p
= NULL
;
1501 struct libmnt_fs
*fs
;
1505 r
= mnt_table_next_fs(table
, iter
, &fs
);
1509 return log_debug_errno(r
, "Failed to get next entry from /proc/self/mountinfo: %m");
1511 path
= mnt_fs_get_target(fs
);
1515 if (isempty(path_startswith(path
, prefix
)))
1518 id1
= mnt_fs_get_id(fs
);
1519 r
= path_get_mnt_id(path
, &id2
);
1521 log_debug_errno(r
, "Failed to get mount ID of '%s', ignoring: %m", path
);
1525 /* The path may be hidden by another over-mount or already remounted. */
1526 log_debug("The mount IDs of '%s' obtained by libmount and path_get_mnt_id() are different (%i vs %i), ignoring.",
1531 mount_fd
= open(path
, O_CLOEXEC
|O_PATH
);
1533 if (errno
== ENOENT
) /* The path may be hidden by another over-mount or already unmounted. */
1536 return log_debug_errno(errno
, "Failed to open subtree of mounted filesystem '%s': %m", path
);
1541 return log_oom_debug();
1543 if (!GREEDY_REALLOC(mounts
, n
+ 1))
1544 return log_oom_debug();
1546 mounts
[n
++] = (SubMount
) {
1547 .path
= TAKE_PTR(p
),
1548 .mount_fd
= TAKE_FD(mount_fd
),
1552 typesafe_qsort(mounts
, n
, sub_mount_compare
);
1553 sub_mount_drop(mounts
, n
);
1555 *ret_mounts
= TAKE_PTR(mounts
);
1560 int bind_mount_submounts(
1562 const char *target
) {
1564 SubMount
*mounts
= NULL
;
1568 /* Bind mounts all child mounts of 'source' to 'target'. Useful when setting up a new procfs instance
1569 * with new mount options to copy the original submounts over. */
1574 CLEANUP_ARRAY(mounts
, n
, sub_mount_array_free
);
1576 r
= get_sub_mounts(source
, &mounts
, &n
);
1580 FOREACH_ARRAY(m
, mounts
, n
) {
1581 _cleanup_free_
char *t
= NULL
;
1584 if (isempty(m
->path
))
1587 assert_se(suffix
= path_startswith(m
->path
, source
));
1589 t
= path_join(target
, suffix
);
1593 r
= path_is_mount_point(t
);
1595 log_debug_errno(r
, "Failed to detect if '%s' already is a mount point, ignoring: %m", t
);
1599 log_debug("Not bind mounting '%s' from '%s' to '%s', since there's already a mountpoint.", suffix
, source
, target
);
1603 r
= mount_follow_verbose(LOG_DEBUG
, FORMAT_PROC_FD_PATH(m
->mount_fd
), t
, NULL
, MS_BIND
|MS_REC
, NULL
);
1604 if (r
< 0 && ret
== 0)
1611 int make_mount_point_inode_from_stat(const struct stat
*st
, const char *dest
, mode_t mode
) {
1615 if (S_ISDIR(st
->st_mode
))
1616 return mkdir_label(dest
, mode
);
1618 return RET_NERRNO(mknod(dest
, S_IFREG
|(mode
& ~0111), 0));
1621 int make_mount_point_inode_from_path(const char *source
, const char *dest
, mode_t mode
) {
1627 if (stat(source
, &st
) < 0)
1630 return make_mount_point_inode_from_stat(&st
, dest
, mode
);
1633 int trigger_automount_at(int dir_fd
, const char *path
) {
1634 _cleanup_free_
char *nested
= NULL
;
1636 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
1638 nested
= path_join(path
, "a");
1642 (void) faccessat(dir_fd
, nested
, F_OK
, 0);
1647 unsigned long credentials_fs_mount_flags(bool ro
) {
1648 /* A tight set of mount flags for credentials mounts */
1649 return MS_NODEV
|MS_NOEXEC
|MS_NOSUID
|ms_nosymfollow_supported()|(ro
? MS_RDONLY
: 0);
1652 int mount_credentials_fs(const char *path
, size_t size
, bool ro
) {
1653 _cleanup_free_
char *opts
= NULL
;
1654 int r
, noswap_supported
;
1656 /* Mounts a file system we can place credentials in, i.e. with tight access modes right from the
1657 * beginning, and ideally swapping turned off. In order of preference:
1659 * 1. tmpfs if it supports "noswap"
1661 * 3. tmpfs if it doesn't support "noswap"
1664 noswap_supported
= mount_option_supported("tmpfs", "noswap", NULL
); /* Check explicitly to avoid kmsg noise */
1665 if (noswap_supported
> 0) {
1666 _cleanup_free_
char *noswap_opts
= NULL
;
1668 if (asprintf(&noswap_opts
, "mode=0700,nr_inodes=1024,size=%zu,noswap", size
) < 0)
1671 /* Best case: tmpfs with noswap (needs kernel >= 6.3) */
1673 r
= mount_nofollow_verbose(
1678 credentials_fs_mount_flags(ro
),
1684 r
= mount_nofollow_verbose(
1689 credentials_fs_mount_flags(ro
),
1694 if (asprintf(&opts
, "mode=0700,nr_inodes=1024,size=%zu", size
) < 0)
1697 return mount_nofollow_verbose(
1702 credentials_fs_mount_flags(ro
),
1707 int error_log_level
,
1710 unsigned long flags
,
1711 const char *options
,
1714 _cleanup_close_
int fs_fd
= -EBADF
, mnt_fd
= -EBADF
;
1715 _cleanup_free_
char *o
= NULL
;
1722 r
= mount_option_mangle(options
, flags
, &f
, &o
);
1724 return log_full_errno(
1725 error_log_level
, r
, "Failed to mangle mount options %s: %m",
1728 if (DEBUG_LOGGING
) {
1729 _cleanup_free_
char *fl
= NULL
;
1730 (void) mount_flags_to_string(f
, &fl
);
1732 log_debug("Creating mount fd for %s (%s) (%s \"%s\")...",
1733 strna(what
), strna(type
), strnull(fl
), strempty(o
));
1736 fs_fd
= fsopen(type
, FSOPEN_CLOEXEC
);
1738 return log_full_errno(error_log_level
, errno
, "Failed to open superblock for \"%s\": %m", type
);
1740 if (fsconfig(fs_fd
, FSCONFIG_SET_STRING
, "source", what
, 0) < 0)
1741 return log_full_errno(error_log_level
, errno
, "Failed to set mount source for \"%s\" to \"%s\": %m", type
, what
);
1743 if (FLAGS_SET(f
, MS_RDONLY
))
1744 if (fsconfig(fs_fd
, FSCONFIG_SET_FLAG
, "ro", NULL
, 0) < 0)
1745 return log_full_errno(error_log_level
, errno
, "Failed to set read only mount flag for \"%s\": %m", type
);
1747 for (const char *p
= o
;;) {
1748 _cleanup_free_
char *word
= NULL
;
1751 r
= extract_first_word(&p
, &word
, ",", EXTRACT_KEEP_QUOTE
);
1753 return log_full_errno(error_log_level
, r
, "Failed to parse mount option string \"%s\": %m", o
);
1757 eq
= strchr(word
, '=');
1762 if (fsconfig(fs_fd
, FSCONFIG_SET_STRING
, word
, eq
, 0) < 0)
1763 return log_full_errno(error_log_level
, errno
, "Failed to set mount option \"%s=%s\" for \"%s\": %m", word
, eq
, type
);
1765 if (fsconfig(fs_fd
, FSCONFIG_SET_FLAG
, word
, NULL
, 0) < 0)
1766 return log_full_errno(error_log_level
, errno
, "Failed to set mount flag \"%s\" for \"%s\": %m", word
, type
);
1770 if (fsconfig(fs_fd
, FSCONFIG_CMD_CREATE
, NULL
, NULL
, 0) < 0)
1771 return log_full_errno(error_log_level
, errno
, "Failed to realize fs fd for \"%s\" (\"%s\"): %m", what
, type
);
1773 mnt_fd
= fsmount(fs_fd
, FSMOUNT_CLOEXEC
, 0);
1775 return log_full_errno(error_log_level
, errno
, "Failed to create mount fd for \"%s\" (\"%s\"): %m", what
, type
);
1777 if (mount_setattr(mnt_fd
, "", AT_EMPTY_PATH
|AT_RECURSIVE
,
1778 &(struct mount_attr
) {
1779 .attr_set
= ms_flags_to_mount_attr(f
) | (userns_fd
>= 0 ? MOUNT_ATTR_IDMAP
: 0),
1780 .userns_fd
= userns_fd
,
1781 }, MOUNT_ATTR_SIZE_VER0
) < 0)
1782 return log_full_errno(error_log_level
,
1784 "Failed to set mount flags for \"%s\" (\"%s\"): %m",
1788 return TAKE_FD(mnt_fd
);