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