1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2010 Lennart Poettering
7 //#include <stdio_ext.h>
10 #include <sys/mount.h>
12 #include <sys/statvfs.h>
16 //#include <libmount.h>
18 #include "alloc-util.h"
20 //#include "extract-word.h"
25 #include "mount-util.h"
26 #include "parse-util.h"
27 #include "path-util.h"
29 #include "stdio-util.h"
30 #include "string-util.h"
33 /* This is the original MAX_HANDLE_SZ definition from the kernel, when the API was introduced. We use that in place of
34 * any more currently defined value to future-proof things: if the size is increased in the API headers, and our code
35 * is recompiled then it would cease working on old kernels, as those refuse any sizes larger than this value with
36 * EINVAL right-away. Hence, let's disconnect ourselves from any such API changes, and stick to the original definition
37 * from when it was introduced. We use it as a start value only anyway (see below), and hence should be able to deal
38 * with large file handles anyway. */
39 #define ORIGINAL_MAX_HANDLE_SZ 128
41 int name_to_handle_at_loop(
44 struct file_handle **ret_handle,
48 _cleanup_free_ struct file_handle *h = NULL;
49 size_t n = ORIGINAL_MAX_HANDLE_SZ;
51 /* We need to invoke name_to_handle_at() in a loop, given that it might return EOVERFLOW when the specified
52 * buffer is too small. Note that in contrast to what the docs might suggest, MAX_HANDLE_SZ is only good as a
53 * start value, it is not an upper bound on the buffer size required.
55 * This improves on raw name_to_handle_at() also in one other regard: ret_handle and ret_mnt_id can be passed
56 * as NULL if there's no interest in either. */
61 h = malloc0(offsetof(struct file_handle, f_handle) + n);
67 if (name_to_handle_at(fd, path, h, &mnt_id, flags) >= 0) {
70 *ret_handle = TAKE_PTR(h);
77 if (errno != EOVERFLOW)
80 if (!ret_handle && ret_mnt_id && mnt_id >= 0) {
82 /* As it appears, name_to_handle_at() fills in mnt_id even when it returns EOVERFLOW when the
83 * buffer is too small, but that's undocumented. Hence, let's make use of this if it appears to
84 * be filled in, and the caller was interested in only the mount ID an nothing else. */
90 /* If name_to_handle_at() didn't increase the byte size, then this EOVERFLOW is caused by something
91 * else (apparently EOVERFLOW is returned for untriggered nfs4 mounts sometimes), not by the too small
92 * buffer. In that case propagate EOVERFLOW */
93 if (h->handle_bytes <= n)
96 /* The buffer was too small. Size the new buffer by what name_to_handle_at() returned. */
98 if (offsetof(struct file_handle, f_handle) + n < n) /* check for addition overflow */
105 static int fd_fdinfo_mnt_id(int fd, const char *filename, int flags, int *mnt_id) {
106 char path[STRLEN("/proc/self/fdinfo/") + DECIMAL_STR_MAX(int)];
107 _cleanup_free_ char *fdinfo = NULL;
108 _cleanup_close_ int subfd = -1;
112 if ((flags & AT_EMPTY_PATH) && isempty(filename))
113 xsprintf(path, "/proc/self/fdinfo/%i", fd);
115 subfd = openat(fd, filename, O_CLOEXEC|O_PATH);
119 xsprintf(path, "/proc/self/fdinfo/%i", subfd);
122 r = read_full_file(path, &fdinfo, NULL);
123 if (r == -ENOENT) /* The fdinfo directory is a relatively new addition */
128 p = startswith(fdinfo, "mnt_id:");
130 p = strstr(fdinfo, "\nmnt_id:");
131 if (!p) /* The mnt_id field is a relatively new addition */
137 p += strspn(p, WHITESPACE);
138 p[strcspn(p, WHITESPACE)] = 0;
140 return safe_atoi(p, mnt_id);
143 int fd_is_mount_point(int fd, const char *filename, int flags) {
144 _cleanup_free_ struct file_handle *h = NULL, *h_parent = NULL;
145 int mount_id = -1, mount_id_parent = -1;
146 bool nosupp = false, check_st_dev = true;
153 /* First we will try the name_to_handle_at() syscall, which
154 * tells us the mount id and an opaque file "handle". It is
155 * not supported everywhere though (kernel compile-time
156 * option, not all file systems are hooked up). If it works
157 * the mount id is usually good enough to tell us whether
158 * something is a mount point.
160 * If that didn't work we will try to read the mount id from
161 * /proc/self/fdinfo/<fd>. This is almost as good as
162 * name_to_handle_at(), however, does not return the
163 * opaque file handle. The opaque file handle is pretty useful
164 * to detect the root directory, which we should always
165 * consider a mount point. Hence we use this only as
166 * fallback. Exporting the mnt_id in fdinfo is a pretty recent
169 * As last fallback we do traditional fstat() based st_dev
170 * comparisons. This is how things were traditionally done,
171 * but unionfs breaks this since it exposes file
172 * systems with a variety of st_dev reported. Also, btrfs
173 * subvolumes have different st_dev, even though they aren't
174 * real mounts of their own. */
176 r = name_to_handle_at_loop(fd, filename, &h, &mount_id, flags);
177 if (IN_SET(r, -ENOSYS, -EACCES, -EPERM, -EOVERFLOW, -EINVAL))
178 /* This kernel does not support name_to_handle_at() at all (ENOSYS), or the syscall was blocked
179 * (EACCES/EPERM; maybe through seccomp, because we are running inside of a container?), or the mount
180 * point is not triggered yet (EOVERFLOW, think nfs4), or some general name_to_handle_at() flakiness
181 * (EINVAL): fall back to simpler logic. */
182 goto fallback_fdinfo;
183 else if (r == -EOPNOTSUPP)
184 /* This kernel or file system does not support name_to_handle_at(), hence let's see if the upper fs
185 * supports it (in which case it is a mount point), otherwise fallback to the traditional stat()
191 r = name_to_handle_at_loop(fd, "", &h_parent, &mount_id_parent, AT_EMPTY_PATH);
192 if (r == -EOPNOTSUPP) {
194 /* Neither parent nor child do name_to_handle_at()? We have no choice but to fall back. */
195 goto fallback_fdinfo;
197 /* The parent can't do name_to_handle_at() but the directory we are interested in can? If so,
198 * it must be a mount point. */
203 /* The parent can do name_to_handle_at() but the
204 * directory we are interested in can't? If so, it
205 * must be a mount point. */
209 /* If the file handle for the directory we are
210 * interested in and its parent are identical, we
211 * assume this is the root directory, which is a mount
214 if (h->handle_bytes == h_parent->handle_bytes &&
215 h->handle_type == h_parent->handle_type &&
216 memcmp(h->f_handle, h_parent->f_handle, h->handle_bytes) == 0)
219 return mount_id != mount_id_parent;
222 r = fd_fdinfo_mnt_id(fd, filename, flags, &mount_id);
223 if (IN_SET(r, -EOPNOTSUPP, -EACCES, -EPERM))
228 r = fd_fdinfo_mnt_id(fd, "", AT_EMPTY_PATH, &mount_id_parent);
232 if (mount_id != mount_id_parent)
235 /* Hmm, so, the mount ids are the same. This leaves one
236 * special case though for the root file system. For that,
237 * let's see if the parent directory has the same inode as we
238 * are interested in. Hence, let's also do fstat() checks now,
239 * too, but avoid the st_dev comparisons, since they aren't
240 * that useful on unionfs mounts. */
241 check_st_dev = false;
244 /* yay for fstatat() taking a different set of flags than the other
246 if (flags & AT_SYMLINK_FOLLOW)
247 flags &= ~AT_SYMLINK_FOLLOW;
249 flags |= AT_SYMLINK_NOFOLLOW;
250 if (fstatat(fd, filename, &a, flags) < 0)
253 if (fstatat(fd, "", &b, AT_EMPTY_PATH) < 0)
256 /* A directory with same device and inode as its parent? Must
257 * be the root directory */
258 if (a.st_dev == b.st_dev &&
259 a.st_ino == b.st_ino)
262 return check_st_dev && (a.st_dev != b.st_dev);
265 /* flags can be AT_SYMLINK_FOLLOW or 0 */
266 int path_is_mount_point(const char *t, const char *root, int flags) {
267 _cleanup_free_ char *canonical = NULL, *parent = NULL;
268 _cleanup_close_ int fd = -1;
272 assert((flags & ~AT_SYMLINK_FOLLOW) == 0);
274 if (path_equal(t, "/"))
277 /* we need to resolve symlinks manually, we can't just rely on
278 * fd_is_mount_point() to do that for us; if we have a structure like
279 * /bin -> /usr/bin/ and /usr is a mount point, then the parent that we
280 * look at needs to be /usr, not /. */
281 if (flags & AT_SYMLINK_FOLLOW) {
282 r = chase_symlinks(t, root, CHASE_TRAIL_SLASH, &canonical);
289 parent = dirname_malloc(t);
293 fd = openat(AT_FDCWD, parent, O_DIRECTORY|O_CLOEXEC|O_PATH);
297 return fd_is_mount_point(fd, last_path_component(t), flags);
300 int path_get_mnt_id(const char *path, int *ret) {
303 r = name_to_handle_at_loop(AT_FDCWD, path, NULL, ret, 0);
304 if (IN_SET(r, -EOPNOTSUPP, -ENOSYS, -EACCES, -EPERM, -EOVERFLOW, -EINVAL)) /* kernel/fs don't support this, or seccomp blocks access, or untriggered mount, or name_to_handle_at() is flaky */
305 return fd_fdinfo_mnt_id(AT_FDCWD, path, 0, ret);
310 #if 0 /// UNNEEDED by elogind
311 int umount_recursive(const char *prefix, int flags) {
315 /* Try to umount everything recursively below a
316 * directory. Also, take care of stacked mounts, and keep
317 * unmounting them until they are gone. */
320 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
325 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
326 if (!proc_self_mountinfo)
329 (void) __fsetlocking(proc_self_mountinfo, FSETLOCKING_BYCALLER);
332 _cleanup_free_ char *path = NULL, *p = NULL;
335 k = fscanf(proc_self_mountinfo,
336 "%*s " /* (1) mount id */
337 "%*s " /* (2) parent id */
338 "%*s " /* (3) major:minor */
339 "%*s " /* (4) root */
340 "%ms " /* (5) mount point */
341 "%*s" /* (6) mount options */
342 "%*[^-]" /* (7) optional fields */
343 "- " /* (8) separator */
344 "%*s " /* (9) file system type */
345 "%*s" /* (10) mount source */
346 "%*s" /* (11) mount options 2 */
347 "%*[^\n]", /* some rubbish at the end */
356 r = cunescape(path, UNESCAPE_RELAX, &p);
360 if (!path_startswith(p, prefix))
363 if (umount2(p, flags) < 0) {
364 r = log_debug_errno(errno, "Failed to umount %s: %m", p);
368 log_debug("Successfully unmounted %s", p);
381 static int get_mount_flags(const char *path, unsigned long *flags) {
384 if (statvfs(path, &buf) < 0)
390 /* Use this function only if do you have direct access to /proc/self/mountinfo
391 * and need the caller to open it for you. This is the case when /proc is
392 * masked or not mounted. Otherwise, use bind_remount_recursive. */
393 int bind_remount_recursive_with_mountinfo(const char *prefix, bool ro, char **blacklist, FILE *proc_self_mountinfo) {
394 _cleanup_set_free_free_ Set *done = NULL;
395 _cleanup_free_ char *cleaned = NULL;
398 assert(proc_self_mountinfo);
400 /* Recursively remount a directory (and all its submounts) read-only or read-write. If the directory is already
401 * mounted, we reuse the mount and simply mark it MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
402 * operation). If it isn't we first make it one. Afterwards we apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to
403 * all submounts we can access, too. When mounts are stacked on the same mount point we only care for each
404 * individual "top-level" mount on each point, as we cannot influence/access the underlying mounts anyway. We
405 * do not have any effect on future submounts that might get propagated, they migt be writable. This includes
406 * future submounts that have been triggered via autofs.
408 * If the "blacklist" parameter is specified it may contain a list of subtrees to exclude from the
409 * remount operation. Note that we'll ignore the blacklist for the top-level path. */
411 cleaned = strdup(prefix);
415 path_simplify(cleaned, false);
417 done = set_new(&path_hash_ops);
422 _cleanup_set_free_free_ Set *todo = NULL;
423 bool top_autofs = false;
425 unsigned long orig_flags;
427 todo = set_new(&path_hash_ops);
431 rewind(proc_self_mountinfo);
434 _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
437 k = fscanf(proc_self_mountinfo,
438 "%*s " /* (1) mount id */
439 "%*s " /* (2) parent id */
440 "%*s " /* (3) major:minor */
441 "%*s " /* (4) root */
442 "%ms " /* (5) mount point */
443 "%*s" /* (6) mount options (superblock) */
444 "%*[^-]" /* (7) optional fields */
445 "- " /* (8) separator */
446 "%ms " /* (9) file system type */
447 "%*s" /* (10) mount source */
448 "%*s" /* (11) mount options (bind mount) */
449 "%*[^\n]", /* some rubbish at the end */
459 r = cunescape(path, UNESCAPE_RELAX, &p);
463 if (!path_startswith(p, cleaned))
466 /* Ignore this mount if it is blacklisted, but only if it isn't the top-level mount we shall
468 if (!path_equal(cleaned, p)) {
469 bool blacklisted = false;
472 STRV_FOREACH(i, blacklist) {
474 if (path_equal(*i, cleaned))
477 if (!path_startswith(*i, cleaned))
480 if (path_startswith(p, *i)) {
482 log_debug("Not remounting %s, because blacklisted by %s, called for %s", p, *i, cleaned);
490 /* Let's ignore autofs mounts. If they aren't
491 * triggered yet, we want to avoid triggering
492 * them, as we don't make any guarantees for
493 * future submounts anyway. If they are
494 * already triggered, then we will find
495 * another entry for this. */
496 if (streq(type, "autofs")) {
497 top_autofs = top_autofs || path_equal(cleaned, p);
501 if (!set_contains(done, p)) {
502 r = set_consume(todo, p);
511 /* If we have no submounts to process anymore and if
512 * the root is either already done, or an autofs, we
514 if (set_isempty(todo) &&
515 (top_autofs || set_contains(done, cleaned)))
518 if (!set_contains(done, cleaned) &&
519 !set_contains(todo, cleaned)) {
520 /* The prefix directory itself is not yet a mount, make it one. */
521 if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
525 (void) get_mount_flags(cleaned, &orig_flags);
526 orig_flags &= ~MS_RDONLY;
528 if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
531 log_debug("Made top-level directory %s a mount point.", prefix);
537 r = set_consume(done, x);
542 while ((x = set_steal_first(todo))) {
544 r = set_consume(done, x);
545 if (IN_SET(r, 0, -EEXIST))
550 /* Deal with mount points that are obstructed by a later mount */
551 r = path_is_mount_point(x, NULL, 0);
552 if (IN_SET(r, 0, -ENOENT))
557 /* Try to reuse the original flag set */
559 (void) get_mount_flags(x, &orig_flags);
560 orig_flags &= ~MS_RDONLY;
562 if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
565 log_debug("Remounted %s read-only.", x);
570 int bind_remount_recursive(const char *prefix, bool ro, char **blacklist) {
571 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
573 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
574 if (!proc_self_mountinfo)
577 (void) __fsetlocking(proc_self_mountinfo, FSETLOCKING_BYCALLER);
579 return bind_remount_recursive_with_mountinfo(prefix, ro, blacklist, proc_self_mountinfo);
582 int mount_move_root(const char *path) {
588 if (mount(path, "/", NULL, MS_MOVE, NULL) < 0)
600 bool fstype_is_network(const char *fstype) {
603 x = startswith(fstype, "fuse.");
607 return STR_IN_SET(fstype,
619 "pvfs2", /* OrangeFS */
624 bool fstype_is_api_vfs(const char *fstype) {
625 return STR_IN_SET(fstype,
648 bool fstype_is_ro(const char *fstype) {
649 /* All Linux file systems that are necessarily read-only */
650 return STR_IN_SET(fstype,
656 bool fstype_can_discard(const char *fstype) {
657 return STR_IN_SET(fstype,
664 bool fstype_can_uid_gid(const char *fstype) {
666 /* All file systems that have a uid=/gid= mount option that fixates the owners of all files and directories,
667 * current and future. */
669 return STR_IN_SET(fstype,
680 int repeat_unmount(const char *path, int flags) {
685 /* If there are multiple mounts on a mount point, this
686 * removes them all */
689 if (umount2(path, flags) < 0) {
702 const char* mode_to_inaccessible_node(mode_t mode) {
703 /* This function maps a node type to a corresponding inaccessible file node. These nodes are created during
704 * early boot by PID 1. In some cases we lacked the privs to create the character and block devices (maybe
705 * because we run in an userns environment, or miss CAP_SYS_MKNOD, or run with a devices policy that excludes
706 * device nodes with major and minor of 0), but that's fine, in that case we use an AF_UNIX file node instead,
707 * which is not the same, but close enough for most uses. And most importantly, the kernel allows bind mounts
708 * from socket nodes to any non-directory file nodes, and that's the most important thing that matters. */
710 switch(mode & S_IFMT) {
712 return "/run/systemd/inaccessible/reg";
715 return "/run/systemd/inaccessible/dir";
718 if (access("/run/systemd/inaccessible/chr", F_OK) == 0)
719 return "/run/systemd/inaccessible/chr";
720 return "/run/systemd/inaccessible/sock";
723 if (access("/run/systemd/inaccessible/blk", F_OK) == 0)
724 return "/run/systemd/inaccessible/blk";
725 return "/run/systemd/inaccessible/sock";
728 return "/run/systemd/inaccessible/fifo";
731 return "/run/systemd/inaccessible/sock";
736 #if 0 /// UNNEEDED by elogind
737 #define FLAG(name) (flags & name ? STRINGIFY(name) "|" : "")
738 static char* mount_flags_to_string(long unsigned flags) {
740 _cleanup_free_ char *y = NULL;
741 long unsigned overflow;
743 overflow = flags & ~(MS_RDONLY |
768 if (flags == 0 || overflow != 0)
769 if (asprintf(&y, "%lx", overflow) < 0)
772 x = strjoin(FLAG(MS_RDONLY),
776 FLAG(MS_SYNCHRONOUS),
794 FLAG(MS_STRICTATIME),
800 x[strlen(x) - 1] = '\0'; /* truncate the last | */
810 const char *options) {
812 _cleanup_free_ char *fl = NULL, *o = NULL;
816 r = mount_option_mangle(options, flags, &f, &o);
818 return log_full_errno(error_log_level, r,
819 "Failed to mangle mount options %s: %m",
822 fl = mount_flags_to_string(f);
824 if ((f & MS_REMOUNT) && !what && !type)
825 log_debug("Remounting %s (%s \"%s\")...",
826 where, strnull(fl), strempty(o));
827 else if (!what && !type)
828 log_debug("Mounting %s (%s \"%s\")...",
829 where, strnull(fl), strempty(o));
830 else if ((f & MS_BIND) && !type)
831 log_debug("Bind-mounting %s on %s (%s \"%s\")...",
832 what, where, strnull(fl), strempty(o));
833 else if (f & MS_MOVE)
834 log_debug("Moving mount %s → %s (%s \"%s\")...",
835 what, where, strnull(fl), strempty(o));
837 log_debug("Mounting %s on %s (%s \"%s\")...",
838 strna(type), where, strnull(fl), strempty(o));
839 if (mount(what, where, type, f, o) < 0)
840 return log_full_errno(error_log_level, errno,
841 "Failed to mount %s on %s (%s \"%s\"): %m",
842 strna(type), where, strnull(fl), strempty(o));
846 int umount_verbose(const char *what) {
847 log_debug("Umounting %s...", what);
848 if (umount(what) < 0)
849 return log_error_errno(errno, "Failed to unmount %s: %m", what);
854 const char *mount_propagation_flags_to_string(unsigned long flags) {
856 switch (flags & (MS_SHARED|MS_SLAVE|MS_PRIVATE)) {
870 int mount_propagation_flags_from_string(const char *name, unsigned long *ret) {
874 else if (streq(name, "shared"))
876 else if (streq(name, "slave"))
878 else if (streq(name, "private"))
885 #if 0 /// UNNEEDED by elogind
886 int mount_option_mangle(
888 unsigned long mount_flags,
889 unsigned long *ret_mount_flags,
890 char **ret_remaining_options) {
892 const struct libmnt_optmap *map;
893 _cleanup_free_ char *ret = NULL;
897 /* This extracts mount flags from the mount options, and store
898 * non-mount-flag options to '*ret_remaining_options'.
900 * "rw,nosuid,nodev,relatime,size=1630748k,mode=700,uid=1000,gid=1000"
901 * is split to MS_NOSUID|MS_NODEV|MS_RELATIME and
902 * "size=1630748k,mode=700,uid=1000,gid=1000".
903 * See more examples in test-mount-utils.c.
905 * Note that if 'options' does not contain any non-mount-flag options,
906 * then '*ret_remaining_options' is set to NULL instread of empty string.
907 * Note that this does not check validity of options stored in
908 * '*ret_remaining_options'.
909 * Note that if 'options' is NULL, then this just copies 'mount_flags'
910 * to '*ret_mount_flags'. */
912 assert(ret_mount_flags);
913 assert(ret_remaining_options);
915 map = mnt_get_builtin_optmap(MNT_LINUX_MAP);
921 _cleanup_free_ char *word = NULL;
922 const struct libmnt_optmap *ent;
924 r = extract_first_word(&p, &word, ",", EXTRACT_QUOTES);
930 for (ent = map; ent->name; ent++) {
931 /* All entries in MNT_LINUX_MAP do not take any argument.
932 * Thus, ent->name does not contain "=" or "[=]". */
933 if (!streq(word, ent->name))
936 if (!(ent->mask & MNT_INVERT))
937 mount_flags |= ent->id;
938 else if (mount_flags & ent->id)
939 mount_flags ^= ent->id;
944 /* If 'word' is not a mount flag, then store it in '*ret_remaining_options'. */
945 if (!ent->name && !strextend_with_separator(&ret, ",", word, NULL))
949 *ret_mount_flags = mount_flags;
950 *ret_remaining_options = TAKE_PTR(ret);