]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/mount-util.c
Merge pull request #4877 from evverx/fix-machine-id
[thirdparty/systemd.git] / src / basic / mount-util.c
CommitLineData
4349cd7c
LP
1/***
2 This file is part of systemd.
3
4 Copyright 2010 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18***/
19
11c3a366
TA
20#include <errno.h>
21#include <stdlib.h>
4349cd7c
LP
22#include <string.h>
23#include <sys/mount.h>
11c3a366 24#include <sys/stat.h>
4349cd7c 25#include <sys/statvfs.h>
11c3a366 26#include <unistd.h>
4349cd7c 27
b5efdb8a 28#include "alloc-util.h"
4349cd7c
LP
29#include "escape.h"
30#include "fd-util.h"
31#include "fileio.h"
e1873695 32#include "fs-util.h"
93cc7779 33#include "hashmap.h"
4349cd7c
LP
34#include "mount-util.h"
35#include "parse-util.h"
36#include "path-util.h"
37#include "set.h"
15a5e950 38#include "stdio-util.h"
4349cd7c 39#include "string-util.h"
6b7c9f8b 40#include "strv.h"
4349cd7c
LP
41
42static int fd_fdinfo_mnt_id(int fd, const char *filename, int flags, int *mnt_id) {
43 char path[strlen("/proc/self/fdinfo/") + DECIMAL_STR_MAX(int)];
44 _cleanup_free_ char *fdinfo = NULL;
45 _cleanup_close_ int subfd = -1;
46 char *p;
47 int r;
48
49 if ((flags & AT_EMPTY_PATH) && isempty(filename))
50 xsprintf(path, "/proc/self/fdinfo/%i", fd);
51 else {
c4b69156 52 subfd = openat(fd, filename, O_CLOEXEC|O_PATH);
4349cd7c
LP
53 if (subfd < 0)
54 return -errno;
55
56 xsprintf(path, "/proc/self/fdinfo/%i", subfd);
57 }
58
59 r = read_full_file(path, &fdinfo, NULL);
60 if (r == -ENOENT) /* The fdinfo directory is a relatively new addition */
61 return -EOPNOTSUPP;
62 if (r < 0)
63 return -errno;
64
65 p = startswith(fdinfo, "mnt_id:");
66 if (!p) {
67 p = strstr(fdinfo, "\nmnt_id:");
68 if (!p) /* The mnt_id field is a relatively new addition */
69 return -EOPNOTSUPP;
70
71 p += 8;
72 }
73
74 p += strspn(p, WHITESPACE);
75 p[strcspn(p, WHITESPACE)] = 0;
76
77 return safe_atoi(p, mnt_id);
78}
79
4349cd7c
LP
80int fd_is_mount_point(int fd, const char *filename, int flags) {
81 union file_handle_union h = FILE_HANDLE_INIT, h_parent = FILE_HANDLE_INIT;
82 int mount_id = -1, mount_id_parent = -1;
83 bool nosupp = false, check_st_dev = true;
84 struct stat a, b;
85 int r;
86
87 assert(fd >= 0);
88 assert(filename);
89
90 /* First we will try the name_to_handle_at() syscall, which
91 * tells us the mount id and an opaque file "handle". It is
92 * not supported everywhere though (kernel compile-time
93 * option, not all file systems are hooked up). If it works
94 * the mount id is usually good enough to tell us whether
95 * something is a mount point.
96 *
97 * If that didn't work we will try to read the mount id from
98 * /proc/self/fdinfo/<fd>. This is almost as good as
99 * name_to_handle_at(), however, does not return the
100 * opaque file handle. The opaque file handle is pretty useful
101 * to detect the root directory, which we should always
102 * consider a mount point. Hence we use this only as
103 * fallback. Exporting the mnt_id in fdinfo is a pretty recent
104 * kernel addition.
105 *
106 * As last fallback we do traditional fstat() based st_dev
107 * comparisons. This is how things were traditionally done,
61233823 108 * but unionfs breaks this since it exposes file
4349cd7c
LP
109 * systems with a variety of st_dev reported. Also, btrfs
110 * subvolumes have different st_dev, even though they aren't
111 * real mounts of their own. */
112
113 r = name_to_handle_at(fd, filename, &h.handle, &mount_id, flags);
114 if (r < 0) {
115 if (errno == ENOSYS)
116 /* This kernel does not support name_to_handle_at()
117 * fall back to simpler logic. */
118 goto fallback_fdinfo;
119 else if (errno == EOPNOTSUPP)
120 /* This kernel or file system does not support
121 * name_to_handle_at(), hence let's see if the
122 * upper fs supports it (in which case it is a
123 * mount point), otherwise fallback to the
124 * traditional stat() logic */
125 nosupp = true;
126 else
127 return -errno;
128 }
129
130 r = name_to_handle_at(fd, "", &h_parent.handle, &mount_id_parent, AT_EMPTY_PATH);
131 if (r < 0) {
132 if (errno == EOPNOTSUPP) {
133 if (nosupp)
134 /* Neither parent nor child do name_to_handle_at()?
135 We have no choice but to fall back. */
136 goto fallback_fdinfo;
137 else
138 /* The parent can't do name_to_handle_at() but the
139 * directory we are interested in can?
140 * If so, it must be a mount point. */
141 return 1;
142 } else
143 return -errno;
144 }
145
146 /* The parent can do name_to_handle_at() but the
147 * directory we are interested in can't? If so, it
148 * must be a mount point. */
149 if (nosupp)
150 return 1;
151
152 /* If the file handle for the directory we are
153 * interested in and its parent are identical, we
154 * assume this is the root directory, which is a mount
155 * point. */
156
157 if (h.handle.handle_bytes == h_parent.handle.handle_bytes &&
158 h.handle.handle_type == h_parent.handle.handle_type &&
159 memcmp(h.handle.f_handle, h_parent.handle.f_handle, h.handle.handle_bytes) == 0)
160 return 1;
161
162 return mount_id != mount_id_parent;
163
164fallback_fdinfo:
165 r = fd_fdinfo_mnt_id(fd, filename, flags, &mount_id);
548bd573 166 if (IN_SET(r, -EOPNOTSUPP, -EACCES))
4349cd7c
LP
167 goto fallback_fstat;
168 if (r < 0)
169 return r;
170
171 r = fd_fdinfo_mnt_id(fd, "", AT_EMPTY_PATH, &mount_id_parent);
172 if (r < 0)
173 return r;
174
175 if (mount_id != mount_id_parent)
176 return 1;
177
178 /* Hmm, so, the mount ids are the same. This leaves one
179 * special case though for the root file system. For that,
180 * let's see if the parent directory has the same inode as we
181 * are interested in. Hence, let's also do fstat() checks now,
182 * too, but avoid the st_dev comparisons, since they aren't
183 * that useful on unionfs mounts. */
184 check_st_dev = false;
185
186fallback_fstat:
187 /* yay for fstatat() taking a different set of flags than the other
188 * _at() above */
189 if (flags & AT_SYMLINK_FOLLOW)
190 flags &= ~AT_SYMLINK_FOLLOW;
191 else
192 flags |= AT_SYMLINK_NOFOLLOW;
193 if (fstatat(fd, filename, &a, flags) < 0)
194 return -errno;
195
196 if (fstatat(fd, "", &b, AT_EMPTY_PATH) < 0)
197 return -errno;
198
199 /* A directory with same device and inode as its parent? Must
200 * be the root directory */
201 if (a.st_dev == b.st_dev &&
202 a.st_ino == b.st_ino)
203 return 1;
204
205 return check_st_dev && (a.st_dev != b.st_dev);
206}
207
208/* flags can be AT_SYMLINK_FOLLOW or 0 */
e1873695 209int path_is_mount_point(const char *t, const char *root, int flags) {
4349cd7c 210 _cleanup_free_ char *canonical = NULL, *parent = NULL;
e1873695
LP
211 _cleanup_close_ int fd = -1;
212 int r;
4349cd7c
LP
213
214 assert(t);
215
216 if (path_equal(t, "/"))
217 return 1;
218
219 /* we need to resolve symlinks manually, we can't just rely on
220 * fd_is_mount_point() to do that for us; if we have a structure like
221 * /bin -> /usr/bin/ and /usr is a mount point, then the parent that we
222 * look at needs to be /usr, not /. */
223 if (flags & AT_SYMLINK_FOLLOW) {
c4f4fce7 224 r = chase_symlinks(t, root, 0, &canonical);
e1873695
LP
225 if (r < 0)
226 return r;
4349cd7c
LP
227
228 t = canonical;
229 }
230
231 parent = dirname_malloc(t);
232 if (!parent)
233 return -ENOMEM;
234
c4b69156 235 fd = openat(AT_FDCWD, parent, O_DIRECTORY|O_CLOEXEC|O_PATH);
4349cd7c
LP
236 if (fd < 0)
237 return -errno;
238
239 return fd_is_mount_point(fd, basename(t), flags);
240}
241
242int umount_recursive(const char *prefix, int flags) {
243 bool again;
244 int n = 0, r;
245
246 /* Try to umount everything recursively below a
247 * directory. Also, take care of stacked mounts, and keep
248 * unmounting them until they are gone. */
249
250 do {
251 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
252
253 again = false;
254 r = 0;
255
256 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
257 if (!proc_self_mountinfo)
258 return -errno;
259
260 for (;;) {
261 _cleanup_free_ char *path = NULL, *p = NULL;
262 int k;
263
264 k = fscanf(proc_self_mountinfo,
265 "%*s " /* (1) mount id */
266 "%*s " /* (2) parent id */
267 "%*s " /* (3) major:minor */
268 "%*s " /* (4) root */
269 "%ms " /* (5) mount point */
270 "%*s" /* (6) mount options */
271 "%*[^-]" /* (7) optional fields */
272 "- " /* (8) separator */
273 "%*s " /* (9) file system type */
274 "%*s" /* (10) mount source */
275 "%*s" /* (11) mount options 2 */
276 "%*[^\n]", /* some rubbish at the end */
277 &path);
278 if (k != 1) {
279 if (k == EOF)
280 break;
281
282 continue;
283 }
284
285 r = cunescape(path, UNESCAPE_RELAX, &p);
286 if (r < 0)
287 return r;
288
289 if (!path_startswith(p, prefix))
290 continue;
291
292 if (umount2(p, flags) < 0) {
6b7c9f8b 293 r = log_debug_errno(errno, "Failed to umount %s: %m", p);
4349cd7c
LP
294 continue;
295 }
296
6b7c9f8b
LP
297 log_debug("Successfully unmounted %s", p);
298
4349cd7c
LP
299 again = true;
300 n++;
301
302 break;
303 }
304
305 } while (again);
306
307 return r ? r : n;
308}
309
310static int get_mount_flags(const char *path, unsigned long *flags) {
311 struct statvfs buf;
312
313 if (statvfs(path, &buf) < 0)
314 return -errno;
315 *flags = buf.f_flag;
316 return 0;
317}
318
6b7c9f8b 319int bind_remount_recursive(const char *prefix, bool ro, char **blacklist) {
4349cd7c
LP
320 _cleanup_set_free_free_ Set *done = NULL;
321 _cleanup_free_ char *cleaned = NULL;
322 int r;
323
6b7c9f8b
LP
324 /* Recursively remount a directory (and all its submounts) read-only or read-write. If the directory is already
325 * mounted, we reuse the mount and simply mark it MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
326 * operation). If it isn't we first make it one. Afterwards we apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to
327 * all submounts we can access, too. When mounts are stacked on the same mount point we only care for each
328 * individual "top-level" mount on each point, as we cannot influence/access the underlying mounts anyway. We
329 * do not have any effect on future submounts that might get propagated, they migt be writable. This includes
330 * future submounts that have been triggered via autofs.
331 *
332 * If the "blacklist" parameter is specified it may contain a list of subtrees to exclude from the
333 * remount operation. Note that we'll ignore the blacklist for the top-level path. */
4349cd7c
LP
334
335 cleaned = strdup(prefix);
336 if (!cleaned)
337 return -ENOMEM;
338
339 path_kill_slashes(cleaned);
340
341 done = set_new(&string_hash_ops);
342 if (!done)
343 return -ENOMEM;
344
345 for (;;) {
346 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
347 _cleanup_set_free_free_ Set *todo = NULL;
348 bool top_autofs = false;
349 char *x;
350 unsigned long orig_flags;
351
352 todo = set_new(&string_hash_ops);
353 if (!todo)
354 return -ENOMEM;
355
356 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
357 if (!proc_self_mountinfo)
358 return -errno;
359
360 for (;;) {
361 _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
362 int k;
363
364 k = fscanf(proc_self_mountinfo,
365 "%*s " /* (1) mount id */
366 "%*s " /* (2) parent id */
367 "%*s " /* (3) major:minor */
368 "%*s " /* (4) root */
369 "%ms " /* (5) mount point */
370 "%*s" /* (6) mount options (superblock) */
371 "%*[^-]" /* (7) optional fields */
372 "- " /* (8) separator */
373 "%ms " /* (9) file system type */
374 "%*s" /* (10) mount source */
375 "%*s" /* (11) mount options (bind mount) */
376 "%*[^\n]", /* some rubbish at the end */
377 &path,
378 &type);
379 if (k != 2) {
380 if (k == EOF)
381 break;
382
383 continue;
384 }
385
386 r = cunescape(path, UNESCAPE_RELAX, &p);
387 if (r < 0)
388 return r;
389
6b7c9f8b
LP
390 if (!path_startswith(p, cleaned))
391 continue;
392
393 /* Ignore this mount if it is blacklisted, but only if it isn't the top-level mount we shall
394 * operate on. */
395 if (!path_equal(cleaned, p)) {
396 bool blacklisted = false;
397 char **i;
398
399 STRV_FOREACH(i, blacklist) {
400
401 if (path_equal(*i, cleaned))
402 continue;
403
404 if (!path_startswith(*i, cleaned))
405 continue;
406
407 if (path_startswith(p, *i)) {
408 blacklisted = true;
409 log_debug("Not remounting %s, because blacklisted by %s, called for %s", p, *i, cleaned);
410 break;
411 }
412 }
413 if (blacklisted)
414 continue;
415 }
416
4349cd7c
LP
417 /* Let's ignore autofs mounts. If they aren't
418 * triggered yet, we want to avoid triggering
419 * them, as we don't make any guarantees for
420 * future submounts anyway. If they are
421 * already triggered, then we will find
422 * another entry for this. */
423 if (streq(type, "autofs")) {
424 top_autofs = top_autofs || path_equal(cleaned, p);
425 continue;
426 }
427
6b7c9f8b 428 if (!set_contains(done, p)) {
4349cd7c
LP
429 r = set_consume(todo, p);
430 p = NULL;
4349cd7c
LP
431 if (r == -EEXIST)
432 continue;
433 if (r < 0)
434 return r;
435 }
436 }
437
438 /* If we have no submounts to process anymore and if
439 * the root is either already done, or an autofs, we
440 * are done */
441 if (set_isempty(todo) &&
442 (top_autofs || set_contains(done, cleaned)))
443 return 0;
444
445 if (!set_contains(done, cleaned) &&
446 !set_contains(todo, cleaned)) {
6b7c9f8b 447 /* The prefix directory itself is not yet a mount, make it one. */
4349cd7c
LP
448 if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
449 return -errno;
450
451 orig_flags = 0;
452 (void) get_mount_flags(cleaned, &orig_flags);
453 orig_flags &= ~MS_RDONLY;
454
455 if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
456 return -errno;
457
6b7c9f8b
LP
458 log_debug("Made top-level directory %s a mount point.", prefix);
459
4349cd7c
LP
460 x = strdup(cleaned);
461 if (!x)
462 return -ENOMEM;
463
464 r = set_consume(done, x);
465 if (r < 0)
466 return r;
467 }
468
469 while ((x = set_steal_first(todo))) {
470
471 r = set_consume(done, x);
472 if (r == -EEXIST || r == 0)
473 continue;
474 if (r < 0)
475 return r;
476
6b7c9f8b 477 /* Deal with mount points that are obstructed by a later mount */
e1873695 478 r = path_is_mount_point(x, NULL, 0);
98df8089
AC
479 if (r == -ENOENT || r == 0)
480 continue;
481 if (r < 0)
482 return r;
483
484 /* Try to reuse the original flag set */
4349cd7c
LP
485 orig_flags = 0;
486 (void) get_mount_flags(x, &orig_flags);
487 orig_flags &= ~MS_RDONLY;
488
98df8089
AC
489 if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
490 return -errno;
4349cd7c 491
6b7c9f8b 492 log_debug("Remounted %s read-only.", x);
4349cd7c
LP
493 }
494 }
495}
496
497int mount_move_root(const char *path) {
498 assert(path);
499
500 if (chdir(path) < 0)
501 return -errno;
502
503 if (mount(path, "/", NULL, MS_MOVE, NULL) < 0)
504 return -errno;
505
506 if (chroot(".") < 0)
507 return -errno;
508
509 if (chdir("/") < 0)
510 return -errno;
511
512 return 0;
513}
4e036b7a
LP
514
515bool fstype_is_network(const char *fstype) {
516 static const char table[] =
517 "afs\0"
518 "cifs\0"
519 "smbfs\0"
520 "sshfs\0"
521 "ncpfs\0"
522 "ncp\0"
523 "nfs\0"
524 "nfs4\0"
525 "gfs\0"
526 "gfs2\0"
a44cb5cb
ZJS
527 "glusterfs\0"
528 "pvfs2\0" /* OrangeFS */
0a86e681 529 "ocfs2\0"
67ae4366 530 "lustre\0"
a44cb5cb 531 ;
4e036b7a
LP
532
533 const char *x;
534
535 x = startswith(fstype, "fuse.");
536 if (x)
537 fstype = x;
538
539 return nulstr_contains(table, fstype);
540}
3f2c0bec
LP
541
542int repeat_unmount(const char *path, int flags) {
543 bool done = false;
544
545 assert(path);
546
547 /* If there are multiple mounts on a mount point, this
548 * removes them all */
549
550 for (;;) {
551 if (umount2(path, flags) < 0) {
552
553 if (errno == EINVAL)
554 return done;
555
556 return -errno;
557 }
558
559 done = true;
560 }
561}
c4b41707
AP
562
563const char* mode_to_inaccessible_node(mode_t mode) {
b3d1d516
AP
564 /* This function maps a node type to the correspondent inaccessible node type.
565 * Character and block inaccessible devices may not be created (because major=0 and minor=0),
566 * in such case we map character and block devices to the inaccessible node type socket. */
c4b41707
AP
567 switch(mode & S_IFMT) {
568 case S_IFREG:
569 return "/run/systemd/inaccessible/reg";
570 case S_IFDIR:
571 return "/run/systemd/inaccessible/dir";
572 case S_IFCHR:
b3d1d516
AP
573 if (access("/run/systemd/inaccessible/chr", F_OK) == 0)
574 return "/run/systemd/inaccessible/chr";
575 return "/run/systemd/inaccessible/sock";
c4b41707 576 case S_IFBLK:
b3d1d516
AP
577 if (access("/run/systemd/inaccessible/blk", F_OK) == 0)
578 return "/run/systemd/inaccessible/blk";
579 return "/run/systemd/inaccessible/sock";
c4b41707
AP
580 case S_IFIFO:
581 return "/run/systemd/inaccessible/fifo";
582 case S_IFSOCK:
583 return "/run/systemd/inaccessible/sock";
584 }
585 return NULL;
586}
60e76d48
ZJS
587
588#define FLAG(name) (flags & name ? STRINGIFY(name) "|" : "")
589static char* mount_flags_to_string(long unsigned flags) {
590 char *x;
591 _cleanup_free_ char *y = NULL;
592 long unsigned overflow;
593
594 overflow = flags & ~(MS_RDONLY |
595 MS_NOSUID |
596 MS_NODEV |
597 MS_NOEXEC |
598 MS_SYNCHRONOUS |
599 MS_REMOUNT |
600 MS_MANDLOCK |
601 MS_DIRSYNC |
602 MS_NOATIME |
603 MS_NODIRATIME |
604 MS_BIND |
605 MS_MOVE |
606 MS_REC |
607 MS_SILENT |
608 MS_POSIXACL |
609 MS_UNBINDABLE |
610 MS_PRIVATE |
611 MS_SLAVE |
612 MS_SHARED |
613 MS_RELATIME |
614 MS_KERNMOUNT |
615 MS_I_VERSION |
616 MS_STRICTATIME |
617 MS_LAZYTIME);
618
619 if (flags == 0 || overflow != 0)
620 if (asprintf(&y, "%lx", overflow) < 0)
621 return NULL;
622
623 x = strjoin(FLAG(MS_RDONLY),
624 FLAG(MS_NOSUID),
625 FLAG(MS_NODEV),
626 FLAG(MS_NOEXEC),
627 FLAG(MS_SYNCHRONOUS),
628 FLAG(MS_REMOUNT),
629 FLAG(MS_MANDLOCK),
630 FLAG(MS_DIRSYNC),
631 FLAG(MS_NOATIME),
632 FLAG(MS_NODIRATIME),
633 FLAG(MS_BIND),
634 FLAG(MS_MOVE),
635 FLAG(MS_REC),
636 FLAG(MS_SILENT),
637 FLAG(MS_POSIXACL),
638 FLAG(MS_UNBINDABLE),
639 FLAG(MS_PRIVATE),
640 FLAG(MS_SLAVE),
641 FLAG(MS_SHARED),
642 FLAG(MS_RELATIME),
643 FLAG(MS_KERNMOUNT),
644 FLAG(MS_I_VERSION),
645 FLAG(MS_STRICTATIME),
646 FLAG(MS_LAZYTIME),
605405c6 647 y);
60e76d48
ZJS
648 if (!x)
649 return NULL;
650 if (!y)
651 x[strlen(x) - 1] = '\0'; /* truncate the last | */
652 return x;
653}
654
655int mount_verbose(
656 int error_log_level,
657 const char *what,
658 const char *where,
659 const char *type,
660 unsigned long flags,
661 const char *options) {
662
663 _cleanup_free_ char *fl = NULL;
664
665 fl = mount_flags_to_string(flags);
666
667 if ((flags & MS_REMOUNT) && !what && !type)
668 log_debug("Remounting %s (%s \"%s\")...",
669 where, strnull(fl), strempty(options));
670 else if (!what && !type)
671 log_debug("Mounting %s (%s \"%s\")...",
672 where, strnull(fl), strempty(options));
673 else if ((flags & MS_BIND) && !type)
674 log_debug("Bind-mounting %s on %s (%s \"%s\")...",
675 what, where, strnull(fl), strempty(options));
676 else
677 log_debug("Mounting %s on %s (%s \"%s\")...",
678 strna(type), where, strnull(fl), strempty(options));
679 if (mount(what, where, type, flags, options) < 0)
680 return log_full_errno(error_log_level, errno,
681 "Failed to mount %s on %s (%s \"%s\"): %m",
682 strna(type), where, strnull(fl), strempty(options));
683 return 0;
684}
685
686int umount_verbose(const char *what) {
687 log_debug("Umounting %s...", what);
688 if (umount(what) < 0)
689 return log_error_errno(errno, "Failed to unmount %s: %m", what);
690 return 0;
691}