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