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