1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2010 Lennart Poettering
7 systemd is free software; you can redistribute it and/or modify it
8 under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 2.1 of the License, or
10 (at your option) any later version.
12 systemd is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public License
18 along with systemd; If not, see <http://www.gnu.org/licenses/>.
24 #include <sys/mount.h>
26 #include <sys/statvfs.h>
29 #include "alloc-util.h"
35 #include "mount-util.h"
36 #include "parse-util.h"
37 #include "path-util.h"
39 #include "stdio-util.h"
40 #include "string-util.h"
43 int name_to_handle_at_loop(
46 struct file_handle
**ret_handle
,
50 _cleanup_free_
struct file_handle
*h
;
51 size_t n
= MAX_HANDLE_SZ
;
53 /* We need to invoke name_to_handle_at() in a loop, given that it might return EOVERFLOW when the specified
54 * buffer is too small. Note that in contrast to what the docs might suggest, MAX_HANDLE_SZ is only good as a
55 * start value, it is not an upper bound on the buffer size required.
57 * This improves on raw name_to_handle_at() also in one other regard: ret_handle and ret_mnt_id can be passed
58 * as NULL if there's no interest in either. */
60 h
= malloc0(offsetof(struct file_handle
, f_handle
) + n
);
69 if (name_to_handle_at(fd
, path
, h
, &mnt_id
, flags
) >= 0) {
81 if (errno
!= EOVERFLOW
)
84 if (!ret_handle
&& ret_mnt_id
&& mnt_id
>= 0) {
86 /* As it appears, name_to_handle_at() fills in mnt_id even when it returns EOVERFLOW when the
87 * buffer is too small, but that's undocumented. Hence, let's make use of this if it appears to
88 * be filled in, and the caller was interested in only the mount ID an nothing else. */
94 /* If name_to_handle_at() didn't increase the byte size, then this EOVERFLOW is caused by something
95 * else (apparently EOVERFLOW is returned for untriggered nfs4 mounts sometimes), not by the too small
96 * buffer. In that case propagate EOVERFLOW */
97 if (h
->handle_bytes
<= n
)
100 /* The buffer was too small. Size the new buffer by what name_to_handle_at() returned. */
102 if (offsetof(struct file_handle
, f_handle
) + n
< n
) /* check for addition overflow */
106 h
= malloc0(offsetof(struct file_handle
, f_handle
) + n
);
114 static int fd_fdinfo_mnt_id(int fd
, const char *filename
, int flags
, int *mnt_id
) {
115 char path
[strlen("/proc/self/fdinfo/") + DECIMAL_STR_MAX(int)];
116 _cleanup_free_
char *fdinfo
= NULL
;
117 _cleanup_close_
int subfd
= -1;
121 if ((flags
& AT_EMPTY_PATH
) && isempty(filename
))
122 xsprintf(path
, "/proc/self/fdinfo/%i", fd
);
124 subfd
= openat(fd
, filename
, O_CLOEXEC
|O_PATH
);
128 xsprintf(path
, "/proc/self/fdinfo/%i", subfd
);
131 r
= read_full_file(path
, &fdinfo
, NULL
);
132 if (r
== -ENOENT
) /* The fdinfo directory is a relatively new addition */
137 p
= startswith(fdinfo
, "mnt_id:");
139 p
= strstr(fdinfo
, "\nmnt_id:");
140 if (!p
) /* The mnt_id field is a relatively new addition */
146 p
+= strspn(p
, WHITESPACE
);
147 p
[strcspn(p
, WHITESPACE
)] = 0;
149 return safe_atoi(p
, mnt_id
);
152 int fd_is_mount_point(int fd
, const char *filename
, int flags
) {
153 _cleanup_free_
struct file_handle
*h
= NULL
, *h_parent
= NULL
;
154 int mount_id
= -1, mount_id_parent
= -1;
155 bool nosupp
= false, check_st_dev
= true;
162 /* First we will try the name_to_handle_at() syscall, which
163 * tells us the mount id and an opaque file "handle". It is
164 * not supported everywhere though (kernel compile-time
165 * option, not all file systems are hooked up). If it works
166 * the mount id is usually good enough to tell us whether
167 * something is a mount point.
169 * If that didn't work we will try to read the mount id from
170 * /proc/self/fdinfo/<fd>. This is almost as good as
171 * name_to_handle_at(), however, does not return the
172 * opaque file handle. The opaque file handle is pretty useful
173 * to detect the root directory, which we should always
174 * consider a mount point. Hence we use this only as
175 * fallback. Exporting the mnt_id in fdinfo is a pretty recent
178 * As last fallback we do traditional fstat() based st_dev
179 * comparisons. This is how things were traditionally done,
180 * but unionfs breaks this since it exposes file
181 * systems with a variety of st_dev reported. Also, btrfs
182 * subvolumes have different st_dev, even though they aren't
183 * real mounts of their own. */
185 r
= name_to_handle_at_loop(fd
, filename
, &h
, &mount_id
, flags
);
186 if (IN_SET(r
, -ENOSYS
, -EACCES
, -EPERM
, -EOVERFLOW
))
187 /* This kernel does not support name_to_handle_at() at all (ENOSYS), or the syscall was blocked
188 * (EACCES/EPERM; maybe through seccomp, because we are running inside of a container?), or the mount
189 * point is not triggered yet (EOVERFLOW, thinkg nfs4): fall back to simpler logic. */
190 goto fallback_fdinfo
;
191 else if (r
== -EOPNOTSUPP
)
192 /* This kernel or file system does not support name_to_handle_at(), hence let's see if the upper fs
193 * supports it (in which case it is a mount point), otherwise fallback to the traditional stat()
199 r
= name_to_handle_at_loop(fd
, "", &h_parent
, &mount_id_parent
, AT_EMPTY_PATH
);
200 if (r
== -EOPNOTSUPP
) {
202 /* Neither parent nor child do name_to_handle_at()? We have no choice but to fall back. */
203 goto fallback_fdinfo
;
205 /* The parent can't do name_to_handle_at() but the directory we are interested in can? If so,
206 * it must be a mount point. */
211 /* The parent can do name_to_handle_at() but the
212 * directory we are interested in can't? If so, it
213 * must be a mount point. */
217 /* If the file handle for the directory we are
218 * interested in and its parent are identical, we
219 * assume this is the root directory, which is a mount
222 if (h
->handle_bytes
== h_parent
->handle_bytes
&&
223 h
->handle_type
== h_parent
->handle_type
&&
224 memcmp(h
->f_handle
, h_parent
->f_handle
, h
->handle_bytes
) == 0)
227 return mount_id
!= mount_id_parent
;
230 r
= fd_fdinfo_mnt_id(fd
, filename
, flags
, &mount_id
);
231 if (IN_SET(r
, -EOPNOTSUPP
, -EACCES
, -EPERM
))
236 r
= fd_fdinfo_mnt_id(fd
, "", AT_EMPTY_PATH
, &mount_id_parent
);
240 if (mount_id
!= mount_id_parent
)
243 /* Hmm, so, the mount ids are the same. This leaves one
244 * special case though for the root file system. For that,
245 * let's see if the parent directory has the same inode as we
246 * are interested in. Hence, let's also do fstat() checks now,
247 * too, but avoid the st_dev comparisons, since they aren't
248 * that useful on unionfs mounts. */
249 check_st_dev
= false;
252 /* yay for fstatat() taking a different set of flags than the other
254 if (flags
& AT_SYMLINK_FOLLOW
)
255 flags
&= ~AT_SYMLINK_FOLLOW
;
257 flags
|= AT_SYMLINK_NOFOLLOW
;
258 if (fstatat(fd
, filename
, &a
, flags
) < 0)
261 if (fstatat(fd
, "", &b
, AT_EMPTY_PATH
) < 0)
264 /* A directory with same device and inode as its parent? Must
265 * be the root directory */
266 if (a
.st_dev
== b
.st_dev
&&
267 a
.st_ino
== b
.st_ino
)
270 return check_st_dev
&& (a
.st_dev
!= b
.st_dev
);
273 /* flags can be AT_SYMLINK_FOLLOW or 0 */
274 int path_is_mount_point(const char *t
, const char *root
, int flags
) {
275 _cleanup_free_
char *canonical
= NULL
, *parent
= NULL
;
276 _cleanup_close_
int fd
= -1;
281 if (path_equal(t
, "/"))
284 /* we need to resolve symlinks manually, we can't just rely on
285 * fd_is_mount_point() to do that for us; if we have a structure like
286 * /bin -> /usr/bin/ and /usr is a mount point, then the parent that we
287 * look at needs to be /usr, not /. */
288 if (flags
& AT_SYMLINK_FOLLOW
) {
289 r
= chase_symlinks(t
, root
, 0, &canonical
);
296 parent
= dirname_malloc(t
);
300 fd
= openat(AT_FDCWD
, parent
, O_DIRECTORY
|O_CLOEXEC
|O_PATH
);
304 return fd_is_mount_point(fd
, basename(t
), flags
);
307 int path_get_mnt_id(const char *path
, int *ret
) {
310 r
= name_to_handle_at_loop(AT_FDCWD
, path
, NULL
, ret
, 0);
311 if (IN_SET(r
, -EOPNOTSUPP
, -ENOSYS
, -EACCES
, -EPERM
, -EOVERFLOW
)) /* kernel/fs don't support this, or seccomp blocks access, or untriggered mount */
312 return fd_fdinfo_mnt_id(AT_FDCWD
, path
, 0, ret
);
317 int umount_recursive(const char *prefix
, int flags
) {
321 /* Try to umount everything recursively below a
322 * directory. Also, take care of stacked mounts, and keep
323 * unmounting them until they are gone. */
326 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
331 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
332 if (!proc_self_mountinfo
)
336 _cleanup_free_
char *path
= NULL
, *p
= NULL
;
339 k
= fscanf(proc_self_mountinfo
,
340 "%*s " /* (1) mount id */
341 "%*s " /* (2) parent id */
342 "%*s " /* (3) major:minor */
343 "%*s " /* (4) root */
344 "%ms " /* (5) mount point */
345 "%*s" /* (6) mount options */
346 "%*[^-]" /* (7) optional fields */
347 "- " /* (8) separator */
348 "%*s " /* (9) file system type */
349 "%*s" /* (10) mount source */
350 "%*s" /* (11) mount options 2 */
351 "%*[^\n]", /* some rubbish at the end */
360 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
364 if (!path_startswith(p
, prefix
))
367 if (umount2(p
, flags
) < 0) {
368 r
= log_debug_errno(errno
, "Failed to umount %s: %m", p
);
372 log_debug("Successfully unmounted %s", p
);
385 static int get_mount_flags(const char *path
, unsigned long *flags
) {
388 if (statvfs(path
, &buf
) < 0)
394 /* Use this function only if do you have direct access to /proc/self/mountinfo
395 * and need the caller to open it for you. This is the case when /proc is
396 * masked or not mounted. Otherwise, use bind_remount_recursive. */
397 int bind_remount_recursive_with_mountinfo(const char *prefix
, bool ro
, char **blacklist
, FILE *proc_self_mountinfo
) {
398 _cleanup_set_free_free_ Set
*done
= NULL
;
399 _cleanup_free_
char *cleaned
= NULL
;
402 assert(proc_self_mountinfo
);
404 /* Recursively remount a directory (and all its submounts) read-only or read-write. If the directory is already
405 * mounted, we reuse the mount and simply mark it MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
406 * operation). If it isn't we first make it one. Afterwards we apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to
407 * all submounts we can access, too. When mounts are stacked on the same mount point we only care for each
408 * individual "top-level" mount on each point, as we cannot influence/access the underlying mounts anyway. We
409 * do not have any effect on future submounts that might get propagated, they migt be writable. This includes
410 * future submounts that have been triggered via autofs.
412 * If the "blacklist" parameter is specified it may contain a list of subtrees to exclude from the
413 * remount operation. Note that we'll ignore the blacklist for the top-level path. */
415 cleaned
= strdup(prefix
);
419 path_kill_slashes(cleaned
);
421 done
= set_new(&string_hash_ops
);
426 _cleanup_set_free_free_ Set
*todo
= NULL
;
427 bool top_autofs
= false;
429 unsigned long orig_flags
;
431 todo
= set_new(&string_hash_ops
);
435 rewind(proc_self_mountinfo
);
438 _cleanup_free_
char *path
= NULL
, *p
= NULL
, *type
= NULL
;
441 k
= fscanf(proc_self_mountinfo
,
442 "%*s " /* (1) mount id */
443 "%*s " /* (2) parent id */
444 "%*s " /* (3) major:minor */
445 "%*s " /* (4) root */
446 "%ms " /* (5) mount point */
447 "%*s" /* (6) mount options (superblock) */
448 "%*[^-]" /* (7) optional fields */
449 "- " /* (8) separator */
450 "%ms " /* (9) file system type */
451 "%*s" /* (10) mount source */
452 "%*s" /* (11) mount options (bind mount) */
453 "%*[^\n]", /* some rubbish at the end */
463 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
467 if (!path_startswith(p
, cleaned
))
470 /* Ignore this mount if it is blacklisted, but only if it isn't the top-level mount we shall
472 if (!path_equal(cleaned
, p
)) {
473 bool blacklisted
= false;
476 STRV_FOREACH(i
, blacklist
) {
478 if (path_equal(*i
, cleaned
))
481 if (!path_startswith(*i
, cleaned
))
484 if (path_startswith(p
, *i
)) {
486 log_debug("Not remounting %s, because blacklisted by %s, called for %s", p
, *i
, cleaned
);
494 /* Let's ignore autofs mounts. If they aren't
495 * triggered yet, we want to avoid triggering
496 * them, as we don't make any guarantees for
497 * future submounts anyway. If they are
498 * already triggered, then we will find
499 * another entry for this. */
500 if (streq(type
, "autofs")) {
501 top_autofs
= top_autofs
|| path_equal(cleaned
, p
);
505 if (!set_contains(done
, p
)) {
506 r
= set_consume(todo
, p
);
515 /* If we have no submounts to process anymore and if
516 * the root is either already done, or an autofs, we
518 if (set_isempty(todo
) &&
519 (top_autofs
|| set_contains(done
, cleaned
)))
522 if (!set_contains(done
, cleaned
) &&
523 !set_contains(todo
, cleaned
)) {
524 /* The prefix directory itself is not yet a mount, make it one. */
525 if (mount(cleaned
, cleaned
, NULL
, MS_BIND
|MS_REC
, NULL
) < 0)
529 (void) get_mount_flags(cleaned
, &orig_flags
);
530 orig_flags
&= ~MS_RDONLY
;
532 if (mount(NULL
, prefix
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0)
535 log_debug("Made top-level directory %s a mount point.", prefix
);
541 r
= set_consume(done
, x
);
546 while ((x
= set_steal_first(todo
))) {
548 r
= set_consume(done
, x
);
549 if (IN_SET(r
, 0, -EEXIST
))
554 /* Deal with mount points that are obstructed by a later mount */
555 r
= path_is_mount_point(x
, NULL
, 0);
556 if (IN_SET(r
, 0, -ENOENT
))
561 /* Try to reuse the original flag set */
563 (void) get_mount_flags(x
, &orig_flags
);
564 orig_flags
&= ~MS_RDONLY
;
566 if (mount(NULL
, x
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0)
569 log_debug("Remounted %s read-only.", x
);
574 int bind_remount_recursive(const char *prefix
, bool ro
, char **blacklist
) {
575 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
577 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
578 if (!proc_self_mountinfo
)
581 return bind_remount_recursive_with_mountinfo(prefix
, ro
, blacklist
, proc_self_mountinfo
);
584 int mount_move_root(const char *path
) {
590 if (mount(path
, "/", NULL
, MS_MOVE
, NULL
) < 0)
602 bool fstype_is_network(const char *fstype
) {
605 x
= startswith(fstype
, "fuse.");
609 return STR_IN_SET(fstype
,
621 "pvfs2", /* OrangeFS */
626 bool fstype_is_api_vfs(const char *fstype
) {
627 return STR_IN_SET(fstype
,
650 bool fstype_is_ro(const char *fstype
) {
651 /* All Linux file systems that are necessarily read-only */
652 return STR_IN_SET(fstype
,
658 bool fstype_can_discard(const char *fstype
) {
659 return STR_IN_SET(fstype
,
666 int repeat_unmount(const char *path
, int flags
) {
671 /* If there are multiple mounts on a mount point, this
672 * removes them all */
675 if (umount2(path
, flags
) < 0) {
687 const char* mode_to_inaccessible_node(mode_t mode
) {
688 /* This function maps a node type to the correspondent inaccessible node type.
689 * Character and block inaccessible devices may not be created (because major=0 and minor=0),
690 * in such case we map character and block devices to the inaccessible node type socket. */
691 switch(mode
& S_IFMT
) {
693 return "/run/systemd/inaccessible/reg";
695 return "/run/systemd/inaccessible/dir";
697 if (access("/run/systemd/inaccessible/chr", F_OK
) == 0)
698 return "/run/systemd/inaccessible/chr";
699 return "/run/systemd/inaccessible/sock";
701 if (access("/run/systemd/inaccessible/blk", F_OK
) == 0)
702 return "/run/systemd/inaccessible/blk";
703 return "/run/systemd/inaccessible/sock";
705 return "/run/systemd/inaccessible/fifo";
707 return "/run/systemd/inaccessible/sock";
712 #define FLAG(name) (flags & name ? STRINGIFY(name) "|" : "")
713 static char* mount_flags_to_string(long unsigned flags
) {
715 _cleanup_free_
char *y
= NULL
;
716 long unsigned overflow
;
718 overflow
= flags
& ~(MS_RDONLY
|
743 if (flags
== 0 || overflow
!= 0)
744 if (asprintf(&y
, "%lx", overflow
) < 0)
747 x
= strjoin(FLAG(MS_RDONLY
),
751 FLAG(MS_SYNCHRONOUS
),
769 FLAG(MS_STRICTATIME
),
775 x
[strlen(x
) - 1] = '\0'; /* truncate the last | */
785 const char *options
) {
787 _cleanup_free_
char *fl
= NULL
;
789 fl
= mount_flags_to_string(flags
);
791 if ((flags
& MS_REMOUNT
) && !what
&& !type
)
792 log_debug("Remounting %s (%s \"%s\")...",
793 where
, strnull(fl
), strempty(options
));
794 else if (!what
&& !type
)
795 log_debug("Mounting %s (%s \"%s\")...",
796 where
, strnull(fl
), strempty(options
));
797 else if ((flags
& MS_BIND
) && !type
)
798 log_debug("Bind-mounting %s on %s (%s \"%s\")...",
799 what
, where
, strnull(fl
), strempty(options
));
800 else if (flags
& MS_MOVE
)
801 log_debug("Moving mount %s → %s (%s \"%s\")...",
802 what
, where
, strnull(fl
), strempty(options
));
804 log_debug("Mounting %s on %s (%s \"%s\")...",
805 strna(type
), where
, strnull(fl
), strempty(options
));
806 if (mount(what
, where
, type
, flags
, options
) < 0)
807 return log_full_errno(error_log_level
, errno
,
808 "Failed to mount %s on %s (%s \"%s\"): %m",
809 strna(type
), where
, strnull(fl
), strempty(options
));
813 int umount_verbose(const char *what
) {
814 log_debug("Umounting %s...", what
);
815 if (umount(what
) < 0)
816 return log_error_errno(errno
, "Failed to unmount %s: %m", what
);
820 const char *mount_propagation_flags_to_string(unsigned long flags
) {
822 switch (flags
& (MS_SHARED
|MS_SLAVE
|MS_PRIVATE
)) {
837 int mount_propagation_flags_from_string(const char *name
, unsigned long *ret
) {
841 else if (streq(name
, "shared"))
843 else if (streq(name
, "slave"))
845 else if (streq(name
, "private"))