1 /* SPDX-License-Identifier: LGPL-2.1+ */
7 #include <sys/statvfs.h>
10 #include "alloc-util.h"
11 #include "extract-word.h"
16 #include "libmount-util.h"
17 #include "mount-util.h"
18 #include "mountpoint-util.h"
19 #include "parse-util.h"
20 #include "path-util.h"
22 #include "stdio-util.h"
23 #include "string-util.h"
26 int umount_recursive(const char *prefix
, int flags
) {
30 /* Try to umount everything recursively below a
31 * directory. Also, take care of stacked mounts, and keep
32 * unmounting them until they are gone. */
35 _cleanup_(mnt_free_tablep
) struct libmnt_table
*table
= NULL
;
36 _cleanup_(mnt_free_iterp
) struct libmnt_iter
*iter
= NULL
;
40 r
= libmount_parse("/proc/self/mountinfo", NULL
, &table
, &iter
);
42 return log_debug_errno(r
, "Failed to parse /proc/self/mountinfo: %m");
48 r
= mnt_table_next_fs(table
, iter
, &fs
);
52 return log_debug_errno(r
, "Failed to get next entry from /proc/self/mountinfo: %m");
54 path
= mnt_fs_get_target(fs
);
58 if (!path_startswith(path
, prefix
))
61 if (umount2(path
, flags
) < 0) {
62 r
= log_debug_errno(errno
, "Failed to umount %s: %m", path
);
66 log_debug("Successfully unmounted %s", path
);
79 static int get_mount_flags(
80 struct libmnt_table
*table
,
88 /* Get the mount flags for the mountpoint at "path" from "table". We have a fallback using statvfs()
89 * in place (which provides us with mostly the same info), but it's just a fallback, since using it
90 * means triggering autofs or NFS mounts, which we'd rather avoid needlessly. */
92 fs
= mnt_table_find_target(table
, path
, MNT_ITER_FORWARD
);
94 log_debug("Could not find '%s' in mount table, ignoring.", path
);
98 opts
= mnt_fs_get_vfs_options(fs
);
104 r
= mnt_optstr_get_flags(opts
, ret
, mnt_get_builtin_optmap(MNT_LINUX_MAP
));
106 log_debug_errno(r
, "Could not get flags for '%s', ignoring: %m", path
);
110 /* MS_RELATIME is default and trying to set it in an unprivileged container causes EPERM */
111 *ret
&= ~MS_RELATIME
;
115 if (statvfs(path
, &buf
) < 0)
118 /* The statvfs() flags and the mount flags mostly have the same values, but for some cases do
119 * not. Hence map the flags manually. (Strictly speaking, ST_RELATIME/MS_RELATIME is the most
120 * prominent one that doesn't match, but that's the one we mask away anyway, see above.) */
123 FLAGS_SET(buf
.f_flag
, ST_RDONLY
) * MS_RDONLY
|
124 FLAGS_SET(buf
.f_flag
, ST_NODEV
) * MS_NODEV
|
125 FLAGS_SET(buf
.f_flag
, ST_NOEXEC
) * MS_NOEXEC
|
126 FLAGS_SET(buf
.f_flag
, ST_NOSUID
) * MS_NOSUID
|
127 FLAGS_SET(buf
.f_flag
, ST_NOATIME
) * MS_NOATIME
|
128 FLAGS_SET(buf
.f_flag
, ST_NODIRATIME
) * MS_NODIRATIME
;
133 /* Use this function only if you do not have direct access to /proc/self/mountinfo but the caller can open it
134 * for you. This is the case when /proc is masked or not mounted. Otherwise, use bind_remount_recursive. */
135 int bind_remount_recursive_with_mountinfo(
137 unsigned long new_flags
,
138 unsigned long flags_mask
,
140 FILE *proc_self_mountinfo
) {
142 _cleanup_set_free_free_ Set
*done
= NULL
;
143 _cleanup_free_
char *simplified
= NULL
;
147 assert(proc_self_mountinfo
);
149 /* Recursively remount a directory (and all its submounts) read-only or read-write. If the directory is already
150 * mounted, we reuse the mount and simply mark it MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
151 * operation). If it isn't we first make it one. Afterwards we apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to
152 * all submounts we can access, too. When mounts are stacked on the same mount point we only care for each
153 * individual "top-level" mount on each point, as we cannot influence/access the underlying mounts anyway. We
154 * do not have any effect on future submounts that might get propagated, they might be writable. This includes
155 * future submounts that have been triggered via autofs.
157 * If the "deny_list" parameter is specified it may contain a list of subtrees to exclude from the
158 * remount operation. Note that we'll ignore the deny list for the top-level path. */
160 simplified
= strdup(prefix
);
164 path_simplify(simplified
, false);
166 done
= set_new(&path_hash_ops
);
171 _cleanup_set_free_free_ Set
*todo
= NULL
;
172 _cleanup_(mnt_free_tablep
) struct libmnt_table
*table
= NULL
;
173 _cleanup_(mnt_free_iterp
) struct libmnt_iter
*iter
= NULL
;
174 bool top_autofs
= false;
176 unsigned long orig_flags
;
178 todo
= set_new(&path_hash_ops
);
182 rewind(proc_self_mountinfo
);
184 r
= libmount_parse("/proc/self/mountinfo", proc_self_mountinfo
, &table
, &iter
);
186 return log_debug_errno(r
, "Failed to parse /proc/self/mountinfo: %m");
189 struct libmnt_fs
*fs
;
190 const char *path
, *type
;
192 r
= mnt_table_next_fs(table
, iter
, &fs
);
196 return log_debug_errno(r
, "Failed to get next entry from /proc/self/mountinfo: %m");
198 path
= mnt_fs_get_target(fs
);
199 type
= mnt_fs_get_fstype(fs
);
203 if (!path_startswith(path
, simplified
))
206 /* Ignore this mount if it is deny-listed, but only if it isn't the top-level mount
207 * we shall operate on. */
208 if (!path_equal(path
, simplified
)) {
209 bool deny_listed
= false;
212 STRV_FOREACH(i
, deny_list
) {
213 if (path_equal(*i
, simplified
))
216 if (!path_startswith(*i
, simplified
))
219 if (path_startswith(path
, *i
)) {
221 log_debug("Not remounting %s deny-listed by %s, called for %s",
222 path
, *i
, simplified
);
230 /* Let's ignore autofs mounts. If they aren't
231 * triggered yet, we want to avoid triggering
232 * them, as we don't make any guarantees for
233 * future submounts anyway. If they are
234 * already triggered, then we will find
235 * another entry for this. */
236 if (streq(type
, "autofs")) {
237 top_autofs
= top_autofs
|| path_equal(path
, simplified
);
241 if (!set_contains(done
, path
)) {
242 r
= set_put_strdup(&todo
, path
);
248 /* If we have no submounts to process anymore and if
249 * the root is either already done, or an autofs, we
251 if (set_isempty(todo
) &&
252 (top_autofs
|| set_contains(done
, simplified
)))
255 if (!set_contains(done
, simplified
) &&
256 !set_contains(todo
, simplified
)) {
257 /* The prefix directory itself is not yet a mount, make it one. */
258 if (mount(simplified
, simplified
, NULL
, MS_BIND
|MS_REC
, NULL
) < 0)
262 (void) get_mount_flags(table
, simplified
, &orig_flags
);
264 if (mount(NULL
, simplified
, NULL
, (orig_flags
& ~flags_mask
)|MS_BIND
|MS_REMOUNT
|new_flags
, NULL
) < 0)
267 log_debug("Made top-level directory %s a mount point.", prefix
);
269 r
= set_put_strdup(&done
, simplified
);
274 while ((x
= set_steal_first(todo
))) {
276 r
= set_consume(done
, x
);
277 if (IN_SET(r
, 0, -EEXIST
))
282 /* Deal with mount points that are obstructed by a later mount */
283 r
= path_is_mount_point(x
, NULL
, 0);
284 if (IN_SET(r
, 0, -ENOENT
))
286 if (IN_SET(r
, -EACCES
, -EPERM
)) {
287 /* Even if root user invoke this, submounts under private FUSE or NFS mount points
288 * may not be acceessed. E.g.,
290 * $ bindfs --no-allow-other ~/mnt/mnt ~/mnt/mnt
291 * $ bindfs --no-allow-other ~/mnt ~/mnt
293 * Then, root user cannot access the mount point ~/mnt/mnt.
294 * In such cases, the submounts are ignored, as we have no way to manage them. */
295 log_debug_errno(r
, "Failed to determine '%s' is mount point or not, ignoring: %m", x
);
301 /* Try to reuse the original flag set */
303 (void) get_mount_flags(table
, x
, &orig_flags
);
305 if (mount(NULL
, x
, NULL
, (orig_flags
& ~flags_mask
)|MS_BIND
|MS_REMOUNT
|new_flags
, NULL
) < 0)
308 log_debug("Remounted %s read-only.", x
);
313 int bind_remount_recursive(
315 unsigned long new_flags
,
316 unsigned long flags_mask
,
319 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
322 r
= fopen_unlocked("/proc/self/mountinfo", "re", &proc_self_mountinfo
);
326 return bind_remount_recursive_with_mountinfo(prefix
, new_flags
, flags_mask
, deny_list
, proc_self_mountinfo
);
329 int bind_remount_one_with_mountinfo(
331 unsigned long new_flags
,
332 unsigned long flags_mask
,
333 FILE *proc_self_mountinfo
) {
335 _cleanup_(mnt_free_tablep
) struct libmnt_table
*table
= NULL
;
336 unsigned long orig_flags
= 0;
340 assert(proc_self_mountinfo
);
342 rewind(proc_self_mountinfo
);
344 table
= mnt_new_table();
348 r
= mnt_table_parse_stream(table
, proc_self_mountinfo
, "/proc/self/mountinfo");
352 /* Try to reuse the original flag set */
353 (void) get_mount_flags(table
, path
, &orig_flags
);
355 if (mount(NULL
, path
, NULL
, (orig_flags
& ~flags_mask
)|MS_BIND
|MS_REMOUNT
|new_flags
, NULL
) < 0)
361 int mount_move_root(const char *path
) {
367 if (mount(path
, "/", NULL
, MS_MOVE
, NULL
) < 0)
379 int repeat_unmount(const char *path
, int flags
) {
384 /* If there are multiple mounts on a mount point, this
385 * removes them all */
388 if (umount2(path
, flags
) < 0) {
400 int mode_to_inaccessible_node(
401 const char *runtime_dir
,
405 /* This function maps a node type to a corresponding inaccessible file node. These nodes are created
406 * during early boot by PID 1. In some cases we lacked the privs to create the character and block
407 * devices (maybe because we run in an userns environment, or miss CAP_SYS_MKNOD, or run with a
408 * devices policy that excludes device nodes with major and minor of 0), but that's fine, in that
409 * case we use an AF_UNIX file node instead, which is not the same, but close enough for most
410 * uses. And most importantly, the kernel allows bind mounts from socket nodes to any non-directory
411 * file nodes, and that's the most important thing that matters.
413 * Note that the runtime directory argument shall be the top-level runtime directory, i.e. /run/ if
414 * we operate in system context and $XDG_RUNTIME_DIR if we operate in user context. */
416 _cleanup_free_
char *d
= NULL
;
417 const char *node
= NULL
;
418 bool fallback
= false;
423 runtime_dir
= "/run";
425 switch(mode
& S_IFMT
) {
427 node
= "/systemd/inaccessible/reg";
431 node
= "/systemd/inaccessible/dir";
435 node
= "/systemd/inaccessible/chr";
440 node
= "/systemd/inaccessible/blk";
445 node
= "/systemd/inaccessible/fifo";
449 node
= "/systemd/inaccessible/sock";
455 d
= path_join(runtime_dir
, node
);
459 if (fallback
&& access(d
, F_OK
) < 0) {
461 d
= path_join(runtime_dir
, "/systemd/inaccessible/sock");
470 #define FLAG(name) (flags & name ? STRINGIFY(name) "|" : "")
471 static char* mount_flags_to_string(long unsigned flags
) {
473 _cleanup_free_
char *y
= NULL
;
474 long unsigned overflow
;
476 overflow
= flags
& ~(MS_RDONLY
|
501 if (flags
== 0 || overflow
!= 0)
502 if (asprintf(&y
, "%lx", overflow
) < 0)
505 x
= strjoin(FLAG(MS_RDONLY
),
509 FLAG(MS_SYNCHRONOUS
),
527 FLAG(MS_STRICTATIME
),
533 x
[strlen(x
) - 1] = '\0'; /* truncate the last | */
543 const char *options
) {
545 _cleanup_free_
char *fl
= NULL
, *o
= NULL
;
549 r
= mount_option_mangle(options
, flags
, &f
, &o
);
551 return log_full_errno(error_log_level
, r
,
552 "Failed to mangle mount options %s: %m",
555 fl
= mount_flags_to_string(f
);
557 if ((f
& MS_REMOUNT
) && !what
&& !type
)
558 log_debug("Remounting %s (%s \"%s\")...",
559 where
, strnull(fl
), strempty(o
));
560 else if (!what
&& !type
)
561 log_debug("Mounting %s (%s \"%s\")...",
562 where
, strnull(fl
), strempty(o
));
563 else if ((f
& MS_BIND
) && !type
)
564 log_debug("Bind-mounting %s on %s (%s \"%s\")...",
565 what
, where
, strnull(fl
), strempty(o
));
566 else if (f
& MS_MOVE
)
567 log_debug("Moving mount %s → %s (%s \"%s\")...",
568 what
, where
, strnull(fl
), strempty(o
));
570 log_debug("Mounting %s on %s (%s \"%s\")...",
571 strna(type
), where
, strnull(fl
), strempty(o
));
572 if (mount(what
, where
, type
, f
, o
) < 0)
573 return log_full_errno(error_log_level
, errno
,
574 "Failed to mount %s (type %s) on %s (%s \"%s\"): %m",
575 strna(what
), strna(type
), where
, strnull(fl
), strempty(o
));
579 int umount_verbose(const char *what
) {
580 log_debug("Umounting %s...", what
);
581 if (umount(what
) < 0)
582 return log_error_errno(errno
, "Failed to unmount %s: %m", what
);
586 int mount_option_mangle(
588 unsigned long mount_flags
,
589 unsigned long *ret_mount_flags
,
590 char **ret_remaining_options
) {
592 const struct libmnt_optmap
*map
;
593 _cleanup_free_
char *ret
= NULL
;
597 /* This extracts mount flags from the mount options, and store
598 * non-mount-flag options to '*ret_remaining_options'.
600 * "rw,nosuid,nodev,relatime,size=1630748k,mode=700,uid=1000,gid=1000"
601 * is split to MS_NOSUID|MS_NODEV|MS_RELATIME and
602 * "size=1630748k,mode=700,uid=1000,gid=1000".
603 * See more examples in test-mount-utils.c.
605 * Note that if 'options' does not contain any non-mount-flag options,
606 * then '*ret_remaining_options' is set to NULL instead of empty string.
607 * Note that this does not check validity of options stored in
608 * '*ret_remaining_options'.
609 * Note that if 'options' is NULL, then this just copies 'mount_flags'
610 * to '*ret_mount_flags'. */
612 assert(ret_mount_flags
);
613 assert(ret_remaining_options
);
615 map
= mnt_get_builtin_optmap(MNT_LINUX_MAP
);
621 _cleanup_free_
char *word
= NULL
;
622 const struct libmnt_optmap
*ent
;
624 r
= extract_first_word(&p
, &word
, ",", EXTRACT_UNQUOTE
);
630 for (ent
= map
; ent
->name
; ent
++) {
631 /* All entries in MNT_LINUX_MAP do not take any argument.
632 * Thus, ent->name does not contain "=" or "[=]". */
633 if (!streq(word
, ent
->name
))
636 if (!(ent
->mask
& MNT_INVERT
))
637 mount_flags
|= ent
->id
;
638 else if (mount_flags
& ent
->id
)
639 mount_flags
^= ent
->id
;
644 /* If 'word' is not a mount flag, then store it in '*ret_remaining_options'. */
645 if (!ent
->name
&& !strextend_with_separator(&ret
, ",", word
, NULL
))
649 *ret_mount_flags
= mount_flags
;
650 *ret_remaining_options
= TAKE_PTR(ret
);