]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/mount-util.c
Merge pull request #12119 from keszybz/voidify-mkdir-p
[thirdparty/systemd.git] / src / shared / mount-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <stdio_ext.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <sys/mount.h>
8 #include <sys/stat.h>
9 #include <sys/statvfs.h>
10 #include <unistd.h>
11
12 /* Include later */
13 #include <libmount.h>
14
15 #include "alloc-util.h"
16 #include "escape.h"
17 #include "extract-word.h"
18 #include "fd-util.h"
19 #include "fileio.h"
20 #include "fs-util.h"
21 #include "hashmap.h"
22 #include "mount-util.h"
23 #include "mountpoint-util.h"
24 #include "parse-util.h"
25 #include "path-util.h"
26 #include "set.h"
27 #include "stdio-util.h"
28 #include "string-util.h"
29 #include "strv.h"
30
31 int umount_recursive(const char *prefix, int flags) {
32 int n = 0, r;
33 bool again;
34
35 /* Try to umount everything recursively below a
36 * directory. Also, take care of stacked mounts, and keep
37 * unmounting them until they are gone. */
38
39 do {
40 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
41
42 again = false;
43 r = 0;
44
45 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
46 if (!proc_self_mountinfo)
47 return -errno;
48
49 (void) __fsetlocking(proc_self_mountinfo, FSETLOCKING_BYCALLER);
50
51 for (;;) {
52 _cleanup_free_ char *path = NULL, *p = NULL;
53 int k;
54
55 k = fscanf(proc_self_mountinfo,
56 "%*s " /* (1) mount id */
57 "%*s " /* (2) parent id */
58 "%*s " /* (3) major:minor */
59 "%*s " /* (4) root */
60 "%ms " /* (5) mount point */
61 "%*s" /* (6) mount options */
62 "%*[^-]" /* (7) optional fields */
63 "- " /* (8) separator */
64 "%*s " /* (9) file system type */
65 "%*s" /* (10) mount source */
66 "%*s" /* (11) mount options 2 */
67 "%*[^\n]", /* some rubbish at the end */
68 &path);
69 if (k != 1) {
70 if (k == EOF)
71 break;
72
73 continue;
74 }
75
76 k = cunescape(path, UNESCAPE_RELAX, &p);
77 if (k < 0)
78 return k;
79
80 if (!path_startswith(p, prefix))
81 continue;
82
83 if (umount2(p, flags) < 0) {
84 r = log_debug_errno(errno, "Failed to umount %s: %m", p);
85 continue;
86 }
87
88 log_debug("Successfully unmounted %s", p);
89
90 again = true;
91 n++;
92
93 break;
94 }
95
96 } while (again);
97
98 return r < 0 ? r : n;
99 }
100
101 static int get_mount_flags(const char *path, unsigned long *flags) {
102 struct statvfs buf;
103
104 if (statvfs(path, &buf) < 0)
105 return -errno;
106 *flags = buf.f_flag;
107 return 0;
108 }
109
110 /* Use this function only if you do not have direct access to /proc/self/mountinfo but the caller can open it
111 * for you. This is the case when /proc is masked or not mounted. Otherwise, use bind_remount_recursive. */
112 int bind_remount_recursive_with_mountinfo(
113 const char *prefix,
114 unsigned long new_flags,
115 unsigned long flags_mask,
116 char **blacklist,
117 FILE *proc_self_mountinfo) {
118
119 _cleanup_set_free_free_ Set *done = NULL;
120 _cleanup_free_ char *cleaned = NULL;
121 int r;
122
123 assert(proc_self_mountinfo);
124
125 /* Recursively remount a directory (and all its submounts) read-only or read-write. If the directory is already
126 * mounted, we reuse the mount and simply mark it MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
127 * operation). If it isn't we first make it one. Afterwards we apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to
128 * all submounts we can access, too. When mounts are stacked on the same mount point we only care for each
129 * individual "top-level" mount on each point, as we cannot influence/access the underlying mounts anyway. We
130 * do not have any effect on future submounts that might get propagated, they migt be writable. This includes
131 * future submounts that have been triggered via autofs.
132 *
133 * If the "blacklist" parameter is specified it may contain a list of subtrees to exclude from the
134 * remount operation. Note that we'll ignore the blacklist for the top-level path. */
135
136 cleaned = strdup(prefix);
137 if (!cleaned)
138 return -ENOMEM;
139
140 path_simplify(cleaned, false);
141
142 done = set_new(&path_hash_ops);
143 if (!done)
144 return -ENOMEM;
145
146 for (;;) {
147 _cleanup_set_free_free_ Set *todo = NULL;
148 bool top_autofs = false;
149 char *x;
150 unsigned long orig_flags;
151
152 todo = set_new(&path_hash_ops);
153 if (!todo)
154 return -ENOMEM;
155
156 rewind(proc_self_mountinfo);
157
158 for (;;) {
159 _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
160 int k;
161
162 k = fscanf(proc_self_mountinfo,
163 "%*s " /* (1) mount id */
164 "%*s " /* (2) parent id */
165 "%*s " /* (3) major:minor */
166 "%*s " /* (4) root */
167 "%ms " /* (5) mount point */
168 "%*s" /* (6) mount options (superblock) */
169 "%*[^-]" /* (7) optional fields */
170 "- " /* (8) separator */
171 "%ms " /* (9) file system type */
172 "%*s" /* (10) mount source */
173 "%*s" /* (11) mount options (bind mount) */
174 "%*[^\n]", /* some rubbish at the end */
175 &path,
176 &type);
177 if (k != 2) {
178 if (k == EOF)
179 break;
180
181 continue;
182 }
183
184 r = cunescape(path, UNESCAPE_RELAX, &p);
185 if (r < 0)
186 return r;
187
188 if (!path_startswith(p, cleaned))
189 continue;
190
191 /* Ignore this mount if it is blacklisted, but only if it isn't the top-level mount we shall
192 * operate on. */
193 if (!path_equal(cleaned, p)) {
194 bool blacklisted = false;
195 char **i;
196
197 STRV_FOREACH(i, blacklist) {
198
199 if (path_equal(*i, cleaned))
200 continue;
201
202 if (!path_startswith(*i, cleaned))
203 continue;
204
205 if (path_startswith(p, *i)) {
206 blacklisted = true;
207 log_debug("Not remounting %s blacklisted by %s, called for %s", p, *i, cleaned);
208 break;
209 }
210 }
211 if (blacklisted)
212 continue;
213 }
214
215 /* Let's ignore autofs mounts. If they aren't
216 * triggered yet, we want to avoid triggering
217 * them, as we don't make any guarantees for
218 * future submounts anyway. If they are
219 * already triggered, then we will find
220 * another entry for this. */
221 if (streq(type, "autofs")) {
222 top_autofs = top_autofs || path_equal(cleaned, p);
223 continue;
224 }
225
226 if (!set_contains(done, p)) {
227 r = set_consume(todo, p);
228 p = NULL;
229 if (r == -EEXIST)
230 continue;
231 if (r < 0)
232 return r;
233 }
234 }
235
236 /* If we have no submounts to process anymore and if
237 * the root is either already done, or an autofs, we
238 * are done */
239 if (set_isempty(todo) &&
240 (top_autofs || set_contains(done, cleaned)))
241 return 0;
242
243 if (!set_contains(done, cleaned) &&
244 !set_contains(todo, cleaned)) {
245 /* The prefix directory itself is not yet a mount, make it one. */
246 if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
247 return -errno;
248
249 orig_flags = 0;
250 (void) get_mount_flags(cleaned, &orig_flags);
251 orig_flags &= ~MS_RDONLY;
252
253 if (mount(NULL, cleaned, NULL, (orig_flags & ~flags_mask)|MS_BIND|MS_REMOUNT|new_flags, NULL) < 0)
254 return -errno;
255
256 log_debug("Made top-level directory %s a mount point.", prefix);
257
258 r = set_put_strdup(done, cleaned);
259 if (r < 0)
260 return r;
261 }
262
263 while ((x = set_steal_first(todo))) {
264
265 r = set_consume(done, x);
266 if (IN_SET(r, 0, -EEXIST))
267 continue;
268 if (r < 0)
269 return r;
270
271 /* Deal with mount points that are obstructed by a later mount */
272 r = path_is_mount_point(x, NULL, 0);
273 if (IN_SET(r, 0, -ENOENT))
274 continue;
275 if (IN_SET(r, -EACCES, -EPERM)) {
276 /* Even if root user invoke this, submounts under private FUSE or NFS mount points
277 * may not be acceessed. E.g.,
278 *
279 * $ bindfs --no-allow-other ~/mnt/mnt ~/mnt/mnt
280 * $ bindfs --no-allow-other ~/mnt ~/mnt
281 *
282 * Then, root user cannot access the mount point ~/mnt/mnt.
283 * In such cases, the submounts are ignored, as we have no way to manage them. */
284 log_debug_errno(r, "Failed to determine '%s' is mount point or not, ignoring: %m", x);
285 continue;
286 }
287 if (r < 0)
288 return r;
289
290 /* Try to reuse the original flag set */
291 orig_flags = 0;
292 (void) get_mount_flags(x, &orig_flags);
293 orig_flags &= ~MS_RDONLY;
294
295 if (mount(NULL, x, NULL, (orig_flags & ~flags_mask)|MS_BIND|MS_REMOUNT|new_flags, NULL) < 0)
296 return -errno;
297
298 log_debug("Remounted %s read-only.", x);
299 }
300 }
301 }
302
303 int bind_remount_recursive(const char *prefix, unsigned long new_flags, unsigned long flags_mask, char **blacklist) {
304 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
305
306 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
307 if (!proc_self_mountinfo)
308 return -errno;
309
310 (void) __fsetlocking(proc_self_mountinfo, FSETLOCKING_BYCALLER);
311
312 return bind_remount_recursive_with_mountinfo(prefix, new_flags, flags_mask, blacklist, proc_self_mountinfo);
313 }
314
315 int mount_move_root(const char *path) {
316 assert(path);
317
318 if (chdir(path) < 0)
319 return -errno;
320
321 if (mount(path, "/", NULL, MS_MOVE, NULL) < 0)
322 return -errno;
323
324 if (chroot(".") < 0)
325 return -errno;
326
327 if (chdir("/") < 0)
328 return -errno;
329
330 return 0;
331 }
332
333 int repeat_unmount(const char *path, int flags) {
334 bool done = false;
335
336 assert(path);
337
338 /* If there are multiple mounts on a mount point, this
339 * removes them all */
340
341 for (;;) {
342 if (umount2(path, flags) < 0) {
343
344 if (errno == EINVAL)
345 return done;
346
347 return -errno;
348 }
349
350 done = true;
351 }
352 }
353
354 const char* mode_to_inaccessible_node(mode_t mode) {
355 /* This function maps a node type to a corresponding inaccessible file node. These nodes are created during
356 * early boot by PID 1. In some cases we lacked the privs to create the character and block devices (maybe
357 * because we run in an userns environment, or miss CAP_SYS_MKNOD, or run with a devices policy that excludes
358 * device nodes with major and minor of 0), but that's fine, in that case we use an AF_UNIX file node instead,
359 * which is not the same, but close enough for most uses. And most importantly, the kernel allows bind mounts
360 * from socket nodes to any non-directory file nodes, and that's the most important thing that matters. */
361
362 switch(mode & S_IFMT) {
363 case S_IFREG:
364 return "/run/systemd/inaccessible/reg";
365
366 case S_IFDIR:
367 return "/run/systemd/inaccessible/dir";
368
369 case S_IFCHR:
370 if (access("/run/systemd/inaccessible/chr", F_OK) == 0)
371 return "/run/systemd/inaccessible/chr";
372 return "/run/systemd/inaccessible/sock";
373
374 case S_IFBLK:
375 if (access("/run/systemd/inaccessible/blk", F_OK) == 0)
376 return "/run/systemd/inaccessible/blk";
377 return "/run/systemd/inaccessible/sock";
378
379 case S_IFIFO:
380 return "/run/systemd/inaccessible/fifo";
381
382 case S_IFSOCK:
383 return "/run/systemd/inaccessible/sock";
384 }
385 return NULL;
386 }
387
388 #define FLAG(name) (flags & name ? STRINGIFY(name) "|" : "")
389 static char* mount_flags_to_string(long unsigned flags) {
390 char *x;
391 _cleanup_free_ char *y = NULL;
392 long unsigned overflow;
393
394 overflow = flags & ~(MS_RDONLY |
395 MS_NOSUID |
396 MS_NODEV |
397 MS_NOEXEC |
398 MS_SYNCHRONOUS |
399 MS_REMOUNT |
400 MS_MANDLOCK |
401 MS_DIRSYNC |
402 MS_NOATIME |
403 MS_NODIRATIME |
404 MS_BIND |
405 MS_MOVE |
406 MS_REC |
407 MS_SILENT |
408 MS_POSIXACL |
409 MS_UNBINDABLE |
410 MS_PRIVATE |
411 MS_SLAVE |
412 MS_SHARED |
413 MS_RELATIME |
414 MS_KERNMOUNT |
415 MS_I_VERSION |
416 MS_STRICTATIME |
417 MS_LAZYTIME);
418
419 if (flags == 0 || overflow != 0)
420 if (asprintf(&y, "%lx", overflow) < 0)
421 return NULL;
422
423 x = strjoin(FLAG(MS_RDONLY),
424 FLAG(MS_NOSUID),
425 FLAG(MS_NODEV),
426 FLAG(MS_NOEXEC),
427 FLAG(MS_SYNCHRONOUS),
428 FLAG(MS_REMOUNT),
429 FLAG(MS_MANDLOCK),
430 FLAG(MS_DIRSYNC),
431 FLAG(MS_NOATIME),
432 FLAG(MS_NODIRATIME),
433 FLAG(MS_BIND),
434 FLAG(MS_MOVE),
435 FLAG(MS_REC),
436 FLAG(MS_SILENT),
437 FLAG(MS_POSIXACL),
438 FLAG(MS_UNBINDABLE),
439 FLAG(MS_PRIVATE),
440 FLAG(MS_SLAVE),
441 FLAG(MS_SHARED),
442 FLAG(MS_RELATIME),
443 FLAG(MS_KERNMOUNT),
444 FLAG(MS_I_VERSION),
445 FLAG(MS_STRICTATIME),
446 FLAG(MS_LAZYTIME),
447 y);
448 if (!x)
449 return NULL;
450 if (!y)
451 x[strlen(x) - 1] = '\0'; /* truncate the last | */
452 return x;
453 }
454
455 int mount_verbose(
456 int error_log_level,
457 const char *what,
458 const char *where,
459 const char *type,
460 unsigned long flags,
461 const char *options) {
462
463 _cleanup_free_ char *fl = NULL, *o = NULL;
464 unsigned long f;
465 int r;
466
467 r = mount_option_mangle(options, flags, &f, &o);
468 if (r < 0)
469 return log_full_errno(error_log_level, r,
470 "Failed to mangle mount options %s: %m",
471 strempty(options));
472
473 fl = mount_flags_to_string(f);
474
475 if ((f & MS_REMOUNT) && !what && !type)
476 log_debug("Remounting %s (%s \"%s\")...",
477 where, strnull(fl), strempty(o));
478 else if (!what && !type)
479 log_debug("Mounting %s (%s \"%s\")...",
480 where, strnull(fl), strempty(o));
481 else if ((f & MS_BIND) && !type)
482 log_debug("Bind-mounting %s on %s (%s \"%s\")...",
483 what, where, strnull(fl), strempty(o));
484 else if (f & MS_MOVE)
485 log_debug("Moving mount %s → %s (%s \"%s\")...",
486 what, where, strnull(fl), strempty(o));
487 else
488 log_debug("Mounting %s on %s (%s \"%s\")...",
489 strna(type), where, strnull(fl), strempty(o));
490 if (mount(what, where, type, f, o) < 0)
491 return log_full_errno(error_log_level, errno,
492 "Failed to mount %s (type %s) on %s (%s \"%s\"): %m",
493 strna(what), strna(type), where, strnull(fl), strempty(o));
494 return 0;
495 }
496
497 int umount_verbose(const char *what) {
498 log_debug("Umounting %s...", what);
499 if (umount(what) < 0)
500 return log_error_errno(errno, "Failed to unmount %s: %m", what);
501 return 0;
502 }
503
504 int mount_option_mangle(
505 const char *options,
506 unsigned long mount_flags,
507 unsigned long *ret_mount_flags,
508 char **ret_remaining_options) {
509
510 const struct libmnt_optmap *map;
511 _cleanup_free_ char *ret = NULL;
512 const char *p;
513 int r;
514
515 /* This extracts mount flags from the mount options, and store
516 * non-mount-flag options to '*ret_remaining_options'.
517 * E.g.,
518 * "rw,nosuid,nodev,relatime,size=1630748k,mode=700,uid=1000,gid=1000"
519 * is split to MS_NOSUID|MS_NODEV|MS_RELATIME and
520 * "size=1630748k,mode=700,uid=1000,gid=1000".
521 * See more examples in test-mount-utils.c.
522 *
523 * Note that if 'options' does not contain any non-mount-flag options,
524 * then '*ret_remaining_options' is set to NULL instread of empty string.
525 * Note that this does not check validity of options stored in
526 * '*ret_remaining_options'.
527 * Note that if 'options' is NULL, then this just copies 'mount_flags'
528 * to '*ret_mount_flags'. */
529
530 assert(ret_mount_flags);
531 assert(ret_remaining_options);
532
533 map = mnt_get_builtin_optmap(MNT_LINUX_MAP);
534 if (!map)
535 return -EINVAL;
536
537 p = options;
538 for (;;) {
539 _cleanup_free_ char *word = NULL;
540 const struct libmnt_optmap *ent;
541
542 r = extract_first_word(&p, &word, ",", EXTRACT_QUOTES);
543 if (r < 0)
544 return r;
545 if (r == 0)
546 break;
547
548 for (ent = map; ent->name; ent++) {
549 /* All entries in MNT_LINUX_MAP do not take any argument.
550 * Thus, ent->name does not contain "=" or "[=]". */
551 if (!streq(word, ent->name))
552 continue;
553
554 if (!(ent->mask & MNT_INVERT))
555 mount_flags |= ent->id;
556 else if (mount_flags & ent->id)
557 mount_flags ^= ent->id;
558
559 break;
560 }
561
562 /* If 'word' is not a mount flag, then store it in '*ret_remaining_options'. */
563 if (!ent->name && !strextend_with_separator(&ret, ",", word, NULL))
564 return -ENOMEM;
565 }
566
567 *ret_mount_flags = mount_flags;
568 *ret_remaining_options = TAKE_PTR(ret);
569
570 return 0;
571 }