]> git.ipfire.org Git - thirdparty/systemd.git/blame_incremental - src/shared/mount-util.c
man: Fix typo in name of sd_id128_to_uuid_string
[thirdparty/systemd.git] / src / shared / mount-util.c
... / ...
CommitLineData
1/* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3#include <stdlib.h>
4#include <sys/mount.h>
5#include <sys/stat.h>
6#include <unistd.h>
7
8#include "alloc-util.h"
9#include "chase.h"
10#include "dissect-image.h"
11#include "errno-util.h"
12#include "extract-word.h"
13#include "fd-util.h"
14#include "fileio.h"
15#include "format-util.h"
16#include "fs-util.h"
17#include "fstab-util.h"
18#include "glyph-util.h"
19#include "hashmap.h"
20#include "libmount-util.h"
21#include "log.h"
22#include "missing_syscall.h"
23#include "mkdir-label.h"
24#include "mount-util.h"
25#include "mountpoint-util.h"
26#include "namespace-util.h"
27#include "os-util.h"
28#include "path-util.h"
29#include "pidref.h"
30#include "process-util.h"
31#include "set.h"
32#include "sort-util.h"
33#include "stat-util.h"
34#include "string-util.h"
35#include "strv.h"
36#include "tmpfile-util.h"
37#include "user-util.h"
38
39int umount_recursive_full(const char *prefix, int flags, char **keep) {
40 _cleanup_fclose_ FILE *f = NULL;
41 int n = 0, r;
42
43 /* Try to umount everything recursively below a directory. Also, take care of stacked mounts, and
44 * keep unmounting them until they are gone. */
45
46 f = fopen("/proc/self/mountinfo", "re"); /* Pin the file, in case we unmount /proc/ as part of the logic here */
47 if (!f)
48 return log_debug_errno(errno, "Failed to open %s: %m", "/proc/self/mountinfo");
49
50 for (;;) {
51 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
52 _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
53 bool again = false;
54
55 r = libmount_parse_mountinfo(f, &table, &iter);
56 if (r < 0)
57 return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
58
59 for (;;) {
60 bool shall_keep = false;
61 struct libmnt_fs *fs;
62 const char *path;
63
64 r = mnt_table_next_fs(table, iter, &fs);
65 if (r == 1)
66 break;
67 if (r < 0)
68 return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
69
70 path = mnt_fs_get_target(fs);
71 if (!path)
72 continue;
73
74 if (prefix && !path_startswith(path, prefix)) {
75 // FIXME: This is extremely noisy, we're probably doing something very wrong
76 // to trigger this so often, needs more investigation.
77 // log_trace("Not unmounting %s, outside of prefix: %s", path, prefix);
78 continue;
79 }
80
81 STRV_FOREACH(k, keep)
82 /* Match against anything in the path to the dirs to keep, or below the dirs to keep */
83 if (path_startswith(path, *k) || path_startswith(*k, path)) {
84 shall_keep = true;
85 break;
86 }
87 if (shall_keep) {
88 log_debug("Not unmounting %s, referenced by keep list.", path);
89 continue;
90 }
91
92 if (umount2(path, flags | UMOUNT_NOFOLLOW) < 0) {
93 log_debug_errno(errno, "Failed to umount %s, ignoring: %m", path);
94 continue;
95 }
96
97 log_trace("Successfully unmounted %s", path);
98
99 again = true;
100 n++;
101
102 break;
103 }
104
105 if (!again)
106 break;
107
108 rewind(f);
109 }
110
111 return n;
112}
113
114#define MS_CONVERTIBLE_FLAGS (MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_NOSYMFOLLOW)
115
116static uint64_t ms_flags_to_mount_attr(unsigned long a) {
117 uint64_t f = 0;
118
119 if (FLAGS_SET(a, MS_RDONLY))
120 f |= MOUNT_ATTR_RDONLY;
121
122 if (FLAGS_SET(a, MS_NOSUID))
123 f |= MOUNT_ATTR_NOSUID;
124
125 if (FLAGS_SET(a, MS_NODEV))
126 f |= MOUNT_ATTR_NODEV;
127
128 if (FLAGS_SET(a, MS_NOEXEC))
129 f |= MOUNT_ATTR_NOEXEC;
130
131 if (FLAGS_SET(a, MS_NOSYMFOLLOW))
132 f |= MOUNT_ATTR_NOSYMFOLLOW;
133
134 return f;
135}
136
137static bool skip_mount_set_attr = false;
138
139/* Use this function only if you do not have direct access to /proc/self/mountinfo but the caller can open it
140 * for you. This is the case when /proc is masked or not mounted. Otherwise, use bind_remount_recursive. */
141int bind_remount_recursive_with_mountinfo(
142 const char *prefix,
143 unsigned long new_flags,
144 unsigned long flags_mask,
145 char **deny_list,
146 FILE *proc_self_mountinfo) {
147
148 _cleanup_fclose_ FILE *proc_self_mountinfo_opened = NULL;
149 _cleanup_set_free_ Set *done = NULL;
150 unsigned n_tries = 0;
151 int r;
152
153 assert(prefix);
154
155 if ((flags_mask & ~MS_CONVERTIBLE_FLAGS) == 0 && strv_isempty(deny_list) && !skip_mount_set_attr) {
156 /* Let's take a shortcut for all the flags we know how to convert into mount_setattr() flags */
157
158 if (mount_setattr(AT_FDCWD, prefix, AT_SYMLINK_NOFOLLOW|AT_RECURSIVE,
159 &(struct mount_attr) {
160 .attr_set = ms_flags_to_mount_attr(new_flags & flags_mask),
161 .attr_clr = ms_flags_to_mount_attr(~new_flags & flags_mask),
162 }, MOUNT_ATTR_SIZE_VER0) < 0) {
163
164 log_debug_errno(errno, "mount_setattr() failed, falling back to classic remounting: %m");
165
166 /* We fall through to classic behaviour if not supported (i.e. kernel < 5.12). We
167 * also do this for all other kinds of errors since they are so many different, and
168 * mount_setattr() has no graceful mode where it continues despite seeing errors one
169 * some mounts, but we want that. Moreover mount_setattr() only works on the mount
170 * point inode itself, not a non-mount point inode, and we want to support arbitrary
171 * prefixes here. */
172
173 if (ERRNO_IS_NOT_SUPPORTED(errno)) /* if not supported, then don't bother at all anymore */
174 skip_mount_set_attr = true;
175 } else
176 return 0; /* Nice, this worked! */
177 }
178
179 if (!proc_self_mountinfo) {
180 r = fopen_unlocked("/proc/self/mountinfo", "re", &proc_self_mountinfo_opened);
181 if (r < 0)
182 return r;
183
184 proc_self_mountinfo = proc_self_mountinfo_opened;
185 }
186
187 /* Recursively remount a directory (and all its submounts) with desired flags (MS_READONLY,
188 * MS_NOSUID, MS_NOEXEC). If the directory is already mounted, we reuse the mount and simply mark it
189 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write operation), ditto for other flags. If it
190 * isn't we first make it one. Afterwards we apply (or remove) the flags to all submounts we can
191 * access, too. When mounts are stacked on the same mount point we only care for each individual
192 * "top-level" mount on each point, as we cannot influence/access the underlying mounts anyway. We do
193 * not have any effect on future submounts that might get propagated, they might be writable
194 * etc. This includes future submounts that have been triggered via autofs. Also note that we can't
195 * operate atomically here. Mounts established while we process the tree might or might not get
196 * noticed and thus might or might not be covered.
197 *
198 * If the "deny_list" parameter is specified it may contain a list of subtrees to exclude from the
199 * remount operation. Note that we'll ignore the deny list for the top-level path. */
200
201 for (;;) {
202 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
203 _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
204 _cleanup_hashmap_free_ Hashmap *todo = NULL;
205 bool top_autofs = false;
206
207 if (n_tries++ >= 32) /* Let's not retry this loop forever */
208 return -EBUSY;
209
210 rewind(proc_self_mountinfo);
211
212 r = libmount_parse_mountinfo(proc_self_mountinfo, &table, &iter);
213 if (r < 0)
214 return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
215
216 for (;;) {
217 _cleanup_free_ char *d = NULL;
218 const char *path, *type, *opts;
219 unsigned long flags = 0;
220 struct libmnt_fs *fs;
221
222 r = mnt_table_next_fs(table, iter, &fs);
223 if (r == 1) /* EOF */
224 break;
225 if (r < 0)
226 return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
227
228 path = mnt_fs_get_target(fs);
229 if (!path)
230 continue;
231
232 if (!path_startswith(path, prefix))
233 continue;
234
235 type = mnt_fs_get_fstype(fs);
236 if (!type)
237 continue;
238
239 /* Let's ignore autofs mounts. If they aren't triggered yet, we want to avoid
240 * triggering them, as we don't make any guarantees for future submounts anyway. If
241 * they are already triggered, then we will find another entry for this. */
242 if (streq(type, "autofs")) {
243 top_autofs = top_autofs || path_equal(path, prefix);
244 continue;
245 }
246
247 if (set_contains(done, path))
248 continue;
249
250 /* Ignore this mount if it is deny-listed, but only if it isn't the top-level mount
251 * we shall operate on. */
252 if (!path_equal(path, prefix)) {
253 bool deny_listed = false;
254
255 STRV_FOREACH(i, deny_list) {
256 if (path_equal(*i, prefix))
257 continue;
258
259 if (!path_startswith(*i, prefix))
260 continue;
261
262 if (path_startswith(path, *i)) {
263 deny_listed = true;
264 log_trace("Not remounting %s deny-listed by %s, called for %s", path, *i, prefix);
265 break;
266 }
267 }
268
269 if (deny_listed)
270 continue;
271 }
272
273 opts = mnt_fs_get_vfs_options(fs);
274 if (opts) {
275 r = mnt_optstr_get_flags(opts, &flags, mnt_get_builtin_optmap(MNT_LINUX_MAP));
276 if (r < 0)
277 log_debug_errno(r, "Could not get flags for '%s', ignoring: %m", path);
278 }
279
280 d = strdup(path);
281 if (!d)
282 return -ENOMEM;
283
284 r = hashmap_ensure_put(&todo, &path_hash_ops_free, d, ULONG_TO_PTR(flags));
285 if (r == -EEXIST)
286 /* If the same path was recorded, but with different mount flags, update it:
287 * it means a mount point is overmounted, and libmount returns the "bottom" (or
288 * older one) first, but we want to reapply the flags from the "top" (or newer
289 * one). See: https://github.com/systemd/systemd/issues/20032
290 * Note that this shouldn't really fail, as we were just told that the key
291 * exists, and it's an update so we want 'd' to be freed immediately. */
292 r = hashmap_update(todo, d, ULONG_TO_PTR(flags));
293 if (r < 0)
294 return r;
295 if (r > 0)
296 TAKE_PTR(d);
297 }
298
299 /* Check if the top-level directory was among what we have seen so far. For that check both
300 * 'done' and 'todo'. Also check 'top_autofs' because if the top-level dir is an autofs we'll
301 * not include it in either set but will set this bool. */
302 if (!set_contains(done, prefix) &&
303 !(top_autofs || hashmap_contains(todo, prefix))) {
304
305 /* The prefix directory itself is not yet a mount, make it one. */
306 r = mount_nofollow(prefix, prefix, NULL, MS_BIND|MS_REC, NULL);
307 if (r < 0)
308 return r;
309
310 /* Immediately rescan, so that we pick up the new mount's flags */
311 continue;
312 }
313
314 /* If we have no submounts to process anymore, we are done */
315 if (hashmap_isempty(todo))
316 return 0;
317
318 for (;;) {
319 unsigned long flags;
320 char *x = NULL;
321
322 /* Take the first mount from our list of mounts to still process */
323 flags = PTR_TO_ULONG(hashmap_steal_first_key_and_value(todo, (void**) &x));
324 if (!x)
325 break;
326
327 r = set_ensure_consume(&done, &path_hash_ops_free, x);
328 if (IN_SET(r, 0, -EEXIST))
329 continue; /* Already done */
330 if (r < 0)
331 return r;
332
333 /* Now, remount this with the new flags set, but exclude MS_RELATIME from it. (It's
334 * the default anyway, thus redundant, and in userns we'll get an error if we try to
335 * explicitly enable it) */
336 r = mount_nofollow(NULL, x, NULL, ((flags & ~flags_mask)|MS_BIND|MS_REMOUNT|new_flags) & ~MS_RELATIME, NULL);
337 if (r < 0) {
338 int q;
339
340 /* OK, so the remount of this entry failed. We'll ultimately ignore this in
341 * almost all cases (there are simply so many reasons why this can fail,
342 * think autofs, NFS, FUSE, …), but let's generate useful debug messages at
343 * the very least. */
344
345 q = path_is_mount_point(x);
346 if (IN_SET(q, 0, -ENOENT)) {
347 /* Hmm, whaaaa? The mount point is not actually a mount point? Then
348 * it is either obstructed by a later mount or somebody has been
349 * racing against us and removed it. Either way the mount point
350 * doesn't matter to us, let's ignore it hence. */
351 log_debug_errno(r, "Mount point '%s' to remount is not a mount point anymore, ignoring remount failure: %m", x);
352 continue;
353 }
354 if (q < 0) /* Any other error on this? Just log and continue */
355 log_debug_errno(q, "Failed to determine whether '%s' is a mount point or not, ignoring: %m", x);
356
357 if (((flags ^ new_flags) & flags_mask & ~MS_RELATIME) == 0) { /* ignore MS_RELATIME while comparing */
358 log_debug_errno(r, "Couldn't remount '%s', but the flags already match what we want, hence ignoring: %m", x);
359 continue;
360 }
361
362 /* Make this fatal if this is the top-level mount */
363 if (path_equal(x, prefix))
364 return r;
365
366 /* If this is not the top-level mount, then handle this gracefully: log but
367 * otherwise ignore. With NFS, FUSE, autofs there are just too many reasons
368 * this might fail without a chance for us to do anything about it, let's
369 * hence be strict on the top-level mount and lenient on the inner ones. */
370 log_debug_errno(r, "Couldn't remount submount '%s' for unexpected reason, ignoring: %m", x);
371 continue;
372 }
373
374 log_trace("Remounted %s.", x);
375 }
376 }
377}
378
379int bind_remount_one_with_mountinfo(
380 const char *path,
381 unsigned long new_flags,
382 unsigned long flags_mask,
383 FILE *proc_self_mountinfo) {
384
385 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
386 unsigned long flags = 0;
387 struct libmnt_fs *fs;
388 const char *opts;
389 int r;
390
391 assert(path);
392 assert(proc_self_mountinfo);
393
394 if ((flags_mask & ~MS_CONVERTIBLE_FLAGS) == 0 && !skip_mount_set_attr) {
395 /* Let's take a shortcut for all the flags we know how to convert into mount_setattr() flags */
396
397 if (mount_setattr(AT_FDCWD, path, AT_SYMLINK_NOFOLLOW,
398 &(struct mount_attr) {
399 .attr_set = ms_flags_to_mount_attr(new_flags & flags_mask),
400 .attr_clr = ms_flags_to_mount_attr(~new_flags & flags_mask),
401 }, MOUNT_ATTR_SIZE_VER0) < 0) {
402
403 log_debug_errno(errno, "mount_setattr() didn't work, falling back to classic remounting: %m");
404
405 if (ERRNO_IS_NOT_SUPPORTED(errno)) /* if not supported, then don't bother at all anymore */
406 skip_mount_set_attr = true;
407 } else
408 return 0; /* Nice, this worked! */
409 }
410
411 rewind(proc_self_mountinfo);
412
413 table = mnt_new_table();
414 if (!table)
415 return -ENOMEM;
416
417 r = mnt_table_parse_stream(table, proc_self_mountinfo, "/proc/self/mountinfo");
418 if (r < 0)
419 return r;
420
421 fs = mnt_table_find_target(table, path, MNT_ITER_FORWARD);
422 if (!fs) {
423 r = access_nofollow(path, F_OK); /* Hmm, it's not in the mount table, but does it exist at all? */
424 if (r < 0)
425 return r;
426
427 return -EINVAL; /* Not a mount point we recognize */
428 }
429
430 opts = mnt_fs_get_vfs_options(fs);
431 if (opts) {
432 r = mnt_optstr_get_flags(opts, &flags, mnt_get_builtin_optmap(MNT_LINUX_MAP));
433 if (r < 0)
434 log_debug_errno(r, "Could not get flags for '%s', ignoring: %m", path);
435 }
436
437 r = mount_nofollow(NULL, path, NULL, ((flags & ~flags_mask)|MS_BIND|MS_REMOUNT|new_flags) & ~MS_RELATIME, NULL);
438 if (r < 0) {
439 if (((flags ^ new_flags) & flags_mask & ~MS_RELATIME) != 0) /* Ignore MS_RELATIME again,
440 * since kernel adds it in
441 * everywhere, because it's the
442 * default. */
443 return r;
444
445 /* Let's handle redundant remounts gracefully */
446 log_debug_errno(r, "Failed to remount '%s' but flags already match what we want, ignoring: %m", path);
447 }
448
449 return 0;
450}
451
452int bind_remount_one(const char *path, unsigned long new_flags, unsigned long flags_mask) {
453 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
454
455 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
456 if (!proc_self_mountinfo)
457 return log_debug_errno(errno, "Failed to open %s: %m", "/proc/self/mountinfo");
458
459 return bind_remount_one_with_mountinfo(path, new_flags, flags_mask, proc_self_mountinfo);
460}
461
462static int mount_switch_root_pivot(int fd_newroot, const char *path) {
463 assert(fd_newroot >= 0);
464 assert(path);
465
466 /* Let the kernel tuck the new root under the old one. */
467 if (pivot_root(".", ".") < 0)
468 return log_debug_errno(errno, "Failed to pivot root to new rootfs '%s': %m", path);
469
470 /* Get rid of the old root and reveal our brand new root. (This will always operate on the top-most
471 * mount on our cwd, regardless what our current directory actually points to.) */
472 if (umount2(".", MNT_DETACH) < 0)
473 return log_debug_errno(errno, "Failed to unmount old rootfs: %m");
474
475 return 0;
476}
477
478static int mount_switch_root_move(int fd_newroot, const char *path) {
479 assert(fd_newroot >= 0);
480 assert(path);
481
482 /* Move the new root fs */
483 if (mount(".", "/", NULL, MS_MOVE, NULL) < 0)
484 return log_debug_errno(errno, "Failed to move new rootfs '%s': %m", path);
485
486 /* Also change root dir */
487 if (chroot(".") < 0)
488 return log_debug_errno(errno, "Failed to chroot to new rootfs '%s': %m", path);
489
490 return 0;
491}
492
493int mount_switch_root_full(const char *path, unsigned long mount_propagation_flag, bool force_ms_move) {
494 _cleanup_close_ int fd_newroot = -EBADF;
495 int r, is_current_root;
496
497 assert(path);
498 assert(mount_propagation_flag_is_valid(mount_propagation_flag));
499
500 fd_newroot = open(path, O_PATH|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW);
501 if (fd_newroot < 0)
502 return log_debug_errno(errno, "Failed to open new rootfs '%s': %m", path);
503
504 is_current_root = path_is_root_at(fd_newroot, NULL);
505 if (is_current_root < 0)
506 return log_debug_errno(is_current_root, "Failed to determine if target dir is our root already: %m");
507
508 /* Change into the new rootfs. */
509 if (fchdir(fd_newroot) < 0)
510 return log_debug_errno(errno, "Failed to chdir into new rootfs '%s': %m", path);
511
512 /* Make this a NOP if we are supposed to switch to our current root fs. After all, both pivot_root()
513 * and MS_MOVE don't like that. */
514 if (!is_current_root) {
515 if (!force_ms_move) {
516 r = mount_switch_root_pivot(fd_newroot, path);
517 if (r < 0) {
518 log_debug_errno(r, "Failed to pivot into new rootfs '%s', will try to use MS_MOVE instead: %m", path);
519 force_ms_move = true;
520 }
521 }
522 if (force_ms_move) {
523 /* Failed to pivot_root() fallback to MS_MOVE. For example, this may happen if the rootfs is
524 * an initramfs in which case pivot_root() isn't supported. */
525 r = mount_switch_root_move(fd_newroot, path);
526 if (r < 0)
527 return log_debug_errno(r, "Failed to switch to new rootfs '%s' with MS_MOVE: %m", path);
528 }
529 }
530
531 log_debug("Successfully switched root to '%s'.", path);
532
533 /* Finally, let's establish the requested propagation flags. */
534 if (mount_propagation_flag == 0)
535 return 0;
536
537 if (mount(NULL, ".", NULL, mount_propagation_flag | MS_REC, NULL) < 0)
538 return log_debug_errno(errno, "Failed to turn new rootfs '%s' into %s mount: %m",
539 mount_propagation_flag_to_string(mount_propagation_flag), path);
540
541 return 0;
542}
543
544int repeat_unmount(const char *path, int flags) {
545 bool done = false;
546
547 assert(path);
548
549 /* If there are multiple mounts on a mount point, this
550 * removes them all */
551
552 for (;;) {
553 if (umount2(path, flags) < 0) {
554
555 if (errno == EINVAL)
556 return done;
557
558 return -errno;
559 }
560
561 done = true;
562 }
563}
564
565int mode_to_inaccessible_node(
566 const char *runtime_dir,
567 mode_t mode,
568 char **ret) {
569
570 /* This function maps a node type to a corresponding inaccessible file node. These nodes are created
571 * during early boot by PID 1. In some cases we lacked the privs to create the character and block
572 * devices (maybe because we run in an userns environment, or miss CAP_SYS_MKNOD, or run with a
573 * devices policy that excludes device nodes with major and minor of 0), but that's fine, in that
574 * case we use an AF_UNIX file node instead, which is not the same, but close enough for most
575 * uses. And most importantly, the kernel allows bind mounts from socket nodes to any non-directory
576 * file nodes, and that's the most important thing that matters.
577 *
578 * Note that the runtime directory argument shall be the top-level runtime directory, i.e. /run/ if
579 * we operate in system context and $XDG_RUNTIME_DIR if we operate in user context. */
580
581 _cleanup_free_ char *d = NULL;
582 const char *node;
583
584 assert(ret);
585
586 if (!runtime_dir)
587 runtime_dir = "/run";
588
589 if (S_ISLNK(mode))
590 return -EINVAL;
591
592 node = inode_type_to_string(mode);
593 if (!node)
594 return -EINVAL;
595
596 d = path_join(runtime_dir, "systemd/inaccessible", node);
597 if (!d)
598 return -ENOMEM;
599
600 /* On new kernels unprivileged users are permitted to create 0:0 char device nodes (because they also
601 * act as whiteout inode for overlayfs), but no other char or block device nodes. On old kernels no
602 * device node whatsoever may be created by unprivileged processes. Hence, if the caller asks for the
603 * inaccessible block device node let's see if the block device node actually exists, and if not,
604 * fall back to the character device node. From there fall back to the socket device node. This means
605 * in the best case we'll get the right device node type — but if not we'll hopefully at least get a
606 * device node at all. */
607
608 if (S_ISBLK(mode) &&
609 access(d, F_OK) < 0 && errno == ENOENT) {
610 free(d);
611 d = path_join(runtime_dir, "/systemd/inaccessible/chr");
612 if (!d)
613 return -ENOMEM;
614 }
615
616 if (IN_SET(mode & S_IFMT, S_IFBLK, S_IFCHR) &&
617 access(d, F_OK) < 0 && errno == ENOENT) {
618 free(d);
619 d = path_join(runtime_dir, "/systemd/inaccessible/sock");
620 if (!d)
621 return -ENOMEM;
622 }
623
624 *ret = TAKE_PTR(d);
625 return 0;
626}
627
628int mount_flags_to_string(unsigned long flags, char **ret) {
629 static const struct {
630 unsigned long flag;
631 const char *name;
632 } map[] = {
633 { .flag = MS_RDONLY, .name = "MS_RDONLY", },
634 { .flag = MS_NOSUID, .name = "MS_NOSUID", },
635 { .flag = MS_NODEV, .name = "MS_NODEV", },
636 { .flag = MS_NOEXEC, .name = "MS_NOEXEC", },
637 { .flag = MS_SYNCHRONOUS, .name = "MS_SYNCHRONOUS", },
638 { .flag = MS_REMOUNT, .name = "MS_REMOUNT", },
639 { .flag = MS_MANDLOCK, .name = "MS_MANDLOCK", },
640 { .flag = MS_DIRSYNC, .name = "MS_DIRSYNC", },
641 { .flag = MS_NOSYMFOLLOW, .name = "MS_NOSYMFOLLOW", },
642 { .flag = MS_NOATIME, .name = "MS_NOATIME", },
643 { .flag = MS_NODIRATIME, .name = "MS_NODIRATIME", },
644 { .flag = MS_BIND, .name = "MS_BIND", },
645 { .flag = MS_MOVE, .name = "MS_MOVE", },
646 { .flag = MS_REC, .name = "MS_REC", },
647 { .flag = MS_SILENT, .name = "MS_SILENT", },
648 { .flag = MS_POSIXACL, .name = "MS_POSIXACL", },
649 { .flag = MS_UNBINDABLE, .name = "MS_UNBINDABLE", },
650 { .flag = MS_PRIVATE, .name = "MS_PRIVATE", },
651 { .flag = MS_SLAVE, .name = "MS_SLAVE", },
652 { .flag = MS_SHARED, .name = "MS_SHARED", },
653 { .flag = MS_RELATIME, .name = "MS_RELATIME", },
654 { .flag = MS_KERNMOUNT, .name = "MS_KERNMOUNT", },
655 { .flag = MS_I_VERSION, .name = "MS_I_VERSION", },
656 { .flag = MS_STRICTATIME, .name = "MS_STRICTATIME", },
657 { .flag = MS_LAZYTIME, .name = "MS_LAZYTIME", },
658 };
659 _cleanup_free_ char *str = NULL;
660
661 assert(ret);
662
663 FOREACH_ELEMENT(entry, map)
664 if (flags & entry->flag) {
665 if (!strextend_with_separator(&str, "|", entry->name))
666 return -ENOMEM;
667 flags &= ~entry->flag;
668 }
669
670 if (!str || flags != 0)
671 if (strextendf_with_separator(&str, "|", "%lx", flags) < 0)
672 return -ENOMEM;
673
674 *ret = TAKE_PTR(str);
675 return 0;
676}
677
678int mount_verbose_full(
679 int error_log_level,
680 const char *what,
681 const char *where,
682 const char *type,
683 unsigned long flags,
684 const char *options,
685 bool follow_symlink) {
686
687 _cleanup_free_ char *fl = NULL, *o = NULL;
688 unsigned long f;
689 int r;
690
691 r = mount_option_mangle(options, flags, &f, &o);
692 if (r < 0)
693 return log_full_errno(error_log_level, r,
694 "Failed to mangle mount options %s: %m",
695 strempty(options));
696
697 (void) mount_flags_to_string(f, &fl);
698
699 if (FLAGS_SET(f, MS_REMOUNT|MS_BIND))
700 log_debug("Changing mount flags %s (%s \"%s\")...",
701 where, strnull(fl), strempty(o));
702 else if (f & MS_REMOUNT)
703 log_debug("Remounting superblock %s (%s \"%s\")...",
704 where, strnull(fl), strempty(o));
705 else if (f & (MS_SHARED|MS_PRIVATE|MS_SLAVE|MS_UNBINDABLE))
706 log_debug("Changing mount propagation %s (%s \"%s\")",
707 where, strnull(fl), strempty(o));
708 else if (f & MS_BIND)
709 log_debug("Bind-mounting %s on %s (%s \"%s\")...",
710 what, where, strnull(fl), strempty(o));
711 else if (f & MS_MOVE)
712 log_debug("Moving mount %s %s %s (%s \"%s\")...",
713 what, glyph(GLYPH_ARROW_RIGHT), where, strnull(fl), strempty(o));
714 else
715 log_debug("Mounting %s (%s) on %s (%s \"%s\")...",
716 strna(what), strna(type), where, strnull(fl), strempty(o));
717
718 if (follow_symlink)
719 r = RET_NERRNO(mount(what, where, type, f, o));
720 else
721 r = mount_nofollow(what, where, type, f, o);
722 if (r < 0)
723 return log_full_errno(error_log_level, r,
724 "Failed to mount %s (type %s) on %s (%s \"%s\"): %m",
725 strna(what), strna(type), where, strnull(fl), strempty(o));
726 return 0;
727}
728
729int umount_verbose(
730 int error_log_level,
731 const char *where,
732 int flags) {
733
734 assert(where);
735
736 log_debug("Unmounting '%s'...", where);
737
738 if (umount2(where, flags) < 0)
739 return log_full_errno(error_log_level, errno, "Failed to unmount '%s': %m", where);
740
741 return 0;
742}
743
744int umountat_detach_verbose(
745 int error_log_level,
746 int fd,
747 const char *where) {
748
749 /* Similar to umountat_verbose(), but goes by fd + path. This implies MNT_DETACH, since to do this we
750 * must pin the inode in question via an fd. */
751
752 assert(fd >= 0 || fd == AT_FDCWD);
753
754 /* If neither fd nor path are specified take this as reference to the cwd */
755 if (fd == AT_FDCWD && isempty(where))
756 return umount_verbose(error_log_level, ".", MNT_DETACH|UMOUNT_NOFOLLOW);
757
758 /* If we don't actually take the fd into consideration for this operation shortcut things, so that we
759 * don't have to open the inode */
760 if (fd == AT_FDCWD || path_is_absolute(where))
761 return umount_verbose(error_log_level, where, MNT_DETACH|UMOUNT_NOFOLLOW);
762
763 _cleanup_free_ char *prefix = NULL;
764 const char *p;
765 if (fd_get_path(fd, &prefix) < 0)
766 p = "<fd>"; /* if we can't get the path, return something vaguely useful */
767 else
768 p = prefix;
769 _cleanup_free_ char *joined = isempty(where) ? strdup(p) : path_join(p, where);
770
771 log_debug("Unmounting '%s'...", strna(joined));
772
773 _cleanup_close_ int inode_fd = -EBADF;
774 int mnt_fd;
775 if (isempty(where))
776 mnt_fd = fd;
777 else {
778 inode_fd = openat(fd, where, O_PATH|O_CLOEXEC|O_NOFOLLOW);
779 if (inode_fd < 0)
780 return log_full_errno(error_log_level, errno, "Failed to pin '%s': %m", strna(joined));
781
782 mnt_fd = inode_fd;
783 }
784
785 if (umount2(FORMAT_PROC_FD_PATH(mnt_fd), MNT_DETACH) < 0)
786 return log_full_errno(error_log_level, errno, "Failed to unmount '%s': %m", strna(joined));
787
788 return 0;
789}
790
791int mount_exchange_graceful(int fsmount_fd, const char *dest, bool mount_beneath) {
792 int r;
793
794 assert(fsmount_fd >= 0);
795 assert(dest);
796
797 /* First, try to mount beneath an existing mount point, and if that works, umount the old mount,
798 * which is now at the top. This will ensure we can atomically replace a mount. Note that this works
799 * also in the case where there are submounts down the tree. Mount propagation is allowed but
800 * restricted to layouts that don't end up propagation the new mount on top of the mount stack. If
801 * this is not supported (minimum kernel v6.5), or if there is no mount on the mountpoint, we get
802 * -EINVAL and then we fallback to normal mounting. */
803
804 r = RET_NERRNO(move_mount(fsmount_fd, /* from_path = */ "",
805 /* to_fd = */ -EBADF, dest,
806 MOVE_MOUNT_F_EMPTY_PATH | (mount_beneath ? MOVE_MOUNT_BENEATH : 0)));
807 if (mount_beneath) {
808 if (r >= 0) /* Mounting beneath worked! Now unmount the upper mount. */
809 return umount_verbose(LOG_DEBUG, dest, UMOUNT_NOFOLLOW|MNT_DETACH);
810
811 if (r == -EINVAL) { /* Fallback if mount_beneath is not supported */
812 log_debug_errno(r,
813 "Cannot mount beneath '%s', falling back to overmount: %m",
814 dest);
815 return mount_exchange_graceful(fsmount_fd, dest, /* mount_beneath = */ false);
816 }
817 }
818
819 return r;
820}
821
822int mount_option_mangle(
823 const char *options,
824 unsigned long mount_flags,
825 unsigned long *ret_mount_flags,
826 char **ret_remaining_options) {
827
828 const struct libmnt_optmap *map;
829 _cleanup_free_ char *ret = NULL;
830 int r;
831
832 /* This extracts mount flags from the mount options, and stores
833 * non-mount-flag options to '*ret_remaining_options'.
834 * E.g.,
835 * "rw,nosuid,nodev,relatime,size=1630748k,mode=0700,uid=1000,gid=1000"
836 * is split to MS_NOSUID|MS_NODEV|MS_RELATIME and
837 * "size=1630748k,mode=0700,uid=1000,gid=1000".
838 * See more examples in test-mount-util.c.
839 *
840 * If 'options' does not contain any non-mount-flag options,
841 * then '*ret_remaining_options' is set to NULL instead of empty string.
842 * The validity of options stored in '*ret_remaining_options' is not checked.
843 * If 'options' is NULL, this just copies 'mount_flags' to *ret_mount_flags. */
844
845 assert(ret_mount_flags);
846 assert(ret_remaining_options);
847
848 map = mnt_get_builtin_optmap(MNT_LINUX_MAP);
849 if (!map)
850 return -EINVAL;
851
852 for (const char *p = options;;) {
853 _cleanup_free_ char *word = NULL;
854 const struct libmnt_optmap *ent;
855
856 r = extract_first_word(&p, &word, ",", EXTRACT_KEEP_QUOTE);
857 if (r < 0)
858 return r;
859 if (r == 0)
860 break;
861
862 for (ent = map; ent->name; ent++) {
863 /* All entries in MNT_LINUX_MAP do not take any argument.
864 * Thus, ent->name does not contain "=" or "[=]". */
865 if (!streq(word, ent->name))
866 continue;
867
868 if (!(ent->mask & MNT_INVERT))
869 mount_flags |= ent->id;
870 else
871 mount_flags &= ~ent->id;
872
873 break;
874 }
875
876 /* If 'word' is not a mount flag, then store it in '*ret_remaining_options'. */
877 if (!ent->name &&
878 !startswith_no_case(word, "x-") &&
879 !strextend_with_separator(&ret, ",", word))
880 return -ENOMEM;
881 }
882
883 *ret_mount_flags = mount_flags;
884 *ret_remaining_options = TAKE_PTR(ret);
885
886 return 0;
887}
888
889static int mount_in_namespace_legacy(
890 const char *chased_src_path,
891 int chased_src_fd,
892 struct stat *chased_src_st,
893 const char *propagate_path,
894 const char *incoming_path,
895 const char *dest,
896 int pidns_fd,
897 int mntns_fd,
898 int root_fd,
899 MountInNamespaceFlags flags,
900 const MountOptions *options,
901 const ImagePolicy *image_policy) {
902
903 _cleanup_close_pair_ int errno_pipe_fd[2] = EBADF_PAIR;
904 char mount_slave[] = "/tmp/propagate.XXXXXX", *mount_tmp, *mount_outside, *p;
905 bool mount_slave_created = false, mount_slave_mounted = false,
906 mount_tmp_created = false, mount_tmp_mounted = false,
907 mount_outside_created = false, mount_outside_mounted = false;
908 pid_t child;
909 int r;
910
911 assert(chased_src_path);
912 assert(chased_src_fd >= 0);
913 assert(chased_src_st);
914 assert(propagate_path);
915 assert(incoming_path);
916 assert(dest);
917 assert(pidns_fd >= 0);
918 assert(mntns_fd >= 0);
919 assert(root_fd >= 0);
920 assert(!options || (flags & MOUNT_IN_NAMESPACE_IS_IMAGE));
921
922 p = strjoina(propagate_path, "/");
923 r = access_nofollow(p, F_OK);
924 if (r < 0)
925 return log_debug_errno(r == -ENOENT ? SYNTHETIC_ERRNO(EOPNOTSUPP) : r, "Target does not allow propagation of mount points");
926
927 /* Our goal is to install a new bind mount into the container,
928 possibly read-only. This is irritatingly complex
929 unfortunately, currently.
930
931 First, we start by creating a private playground in /tmp,
932 that we can mount MS_SLAVE. (Which is necessary, since
933 MS_MOVE cannot be applied to mounts with MS_SHARED parent
934 mounts.) */
935
936 if (!mkdtemp(mount_slave))
937 return log_debug_errno(errno, "Failed to create playground %s: %m", mount_slave);
938
939 mount_slave_created = true;
940
941 r = mount_nofollow_verbose(LOG_DEBUG, mount_slave, mount_slave, NULL, MS_BIND, NULL);
942 if (r < 0)
943 goto finish;
944
945 mount_slave_mounted = true;
946
947 r = mount_nofollow_verbose(LOG_DEBUG, NULL, mount_slave, NULL, MS_SLAVE, NULL);
948 if (r < 0)
949 goto finish;
950
951 /* Second, we mount the source file or directory to a directory inside of our MS_SLAVE playground. */
952 mount_tmp = strjoina(mount_slave, "/mount");
953 r = make_mount_point_inode_from_mode(AT_FDCWD, mount_tmp, (flags & MOUNT_IN_NAMESPACE_IS_IMAGE) ? S_IFDIR : chased_src_st->st_mode, 0700);
954 if (r < 0) {
955 log_debug_errno(r, "Failed to create temporary mount point %s: %m", mount_tmp);
956 goto finish;
957 }
958
959 mount_tmp_created = true;
960
961 if (flags & MOUNT_IN_NAMESPACE_IS_IMAGE)
962 r = verity_dissect_and_mount(
963 chased_src_fd,
964 chased_src_path,
965 mount_tmp,
966 options,
967 image_policy,
968 /* image_filter= */ NULL,
969 /* extension_release_data= */ NULL,
970 /* required_class= */ _IMAGE_CLASS_INVALID,
971 /* verity= */ NULL,
972 /* ret_image= */ NULL);
973 else
974 r = mount_follow_verbose(LOG_DEBUG, FORMAT_PROC_FD_PATH(chased_src_fd), mount_tmp, NULL, MS_BIND, NULL);
975 if (r < 0)
976 goto finish;
977
978 mount_tmp_mounted = true;
979
980 /* Third, we remount the new bind mount read-only if requested. */
981 if (flags & MOUNT_IN_NAMESPACE_READ_ONLY) {
982 r = mount_nofollow_verbose(LOG_DEBUG, NULL, mount_tmp, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL);
983 if (r < 0)
984 goto finish;
985 }
986
987 /* Fourth, we move the new bind mount into the propagation directory. This way it will appear there read-only
988 * right-away. */
989
990 mount_outside = strjoina(propagate_path, "/XXXXXX");
991 if ((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || S_ISDIR(chased_src_st->st_mode))
992 r = mkdtemp(mount_outside) ? 0 : -errno;
993 else {
994 r = mkostemp_safe(mount_outside);
995 safe_close(r);
996 }
997 if (r < 0) {
998 log_debug_errno(r, "Cannot create propagation file or directory %s: %m", mount_outside);
999 goto finish;
1000 }
1001
1002 mount_outside_created = true;
1003
1004 r = mount_nofollow_verbose(LOG_DEBUG, mount_tmp, mount_outside, NULL, MS_MOVE, NULL);
1005 if (r < 0)
1006 goto finish;
1007
1008 mount_outside_mounted = true;
1009 mount_tmp_mounted = false;
1010
1011 if ((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || S_ISDIR(chased_src_st->st_mode))
1012 (void) rmdir(mount_tmp);
1013 else
1014 (void) unlink(mount_tmp);
1015 mount_tmp_created = false;
1016
1017 (void) umount_verbose(LOG_DEBUG, mount_slave, UMOUNT_NOFOLLOW);
1018 mount_slave_mounted = false;
1019
1020 (void) rmdir(mount_slave);
1021 mount_slave_created = false;
1022
1023 if (pipe2(errno_pipe_fd, O_CLOEXEC|O_NONBLOCK) < 0) {
1024 log_debug_errno(errno, "Failed to create pipe: %m");
1025 goto finish;
1026 }
1027
1028 r = namespace_fork(
1029 "(sd-bindmnt)",
1030 "(sd-bindmnt-inner)",
1031 /* except_fds= */ NULL,
1032 /* n_except_fds= */ 0,
1033 FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM,
1034 pidns_fd,
1035 mntns_fd,
1036 /* netns_fd= */ -EBADF,
1037 /* userns_fd= */ -EBADF,
1038 root_fd,
1039 &child);
1040 if (r < 0)
1041 goto finish;
1042 if (r == 0) {
1043 _cleanup_free_ char *mount_outside_fn = NULL, *mount_inside = NULL;
1044
1045 errno_pipe_fd[0] = safe_close(errno_pipe_fd[0]);
1046
1047 _cleanup_close_ int dest_fd = -EBADF;
1048 _cleanup_free_ char *dest_fn = NULL;
1049 r = chase(dest, /* root= */ NULL, CHASE_PARENT|CHASE_EXTRACT_FILENAME|((flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY) ? CHASE_MKDIR_0755 : 0), &dest_fn, &dest_fd);
1050 if (r < 0)
1051 log_debug_errno(r, "Failed to pin parent directory of mount '%s', ignoring: %m", dest);
1052 else if (flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY) {
1053 r = make_mount_point_inode_from_mode(dest_fd, dest_fn, (flags & MOUNT_IN_NAMESPACE_IS_IMAGE) ? S_IFDIR : chased_src_st->st_mode, 0700);
1054 if (r < 0)
1055 log_debug_errno(r, "Failed to make mount point inode of mount '%s', ignoring: %m", dest);
1056 }
1057
1058 /* Fifth, move the mount to the right place inside */
1059 r = path_extract_filename(mount_outside, &mount_outside_fn);
1060 if (r < 0) {
1061 log_debug_errno(r, "Failed to extract filename from propagation file or directory '%s': %m", mount_outside);
1062 report_errno_and_exit(errno_pipe_fd[1], r);
1063 }
1064
1065 mount_inside = path_join(incoming_path, mount_outside_fn);
1066 if (!mount_inside)
1067 report_errno_and_exit(errno_pipe_fd[1], log_oom_debug());
1068
1069 r = mount_nofollow_verbose(LOG_DEBUG, mount_inside, dest_fd >= 0 ? FORMAT_PROC_FD_PATH(dest_fd) : dest, /* fstype= */ NULL, MS_MOVE, /* options= */ NULL);
1070 if (r < 0)
1071 report_errno_and_exit(errno_pipe_fd[1], r);
1072
1073 _exit(EXIT_SUCCESS);
1074 }
1075
1076 errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
1077
1078 r = wait_for_terminate_and_check("(sd-bindmnt)", child, 0);
1079 if (r < 0) {
1080 log_debug_errno(r, "Failed to wait for child: %m");
1081 goto finish;
1082 }
1083 if (r != EXIT_SUCCESS) {
1084 if (read(errno_pipe_fd[0], &r, sizeof(r)) == sizeof(r))
1085 log_debug_errno(r, "Failed to mount: %m");
1086 else
1087 log_debug("Child failed.");
1088 goto finish;
1089 }
1090
1091finish:
1092 if (mount_outside_mounted)
1093 (void) umount_verbose(LOG_DEBUG, mount_outside, UMOUNT_NOFOLLOW);
1094 if (mount_outside_created) {
1095 if ((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || S_ISDIR(chased_src_st->st_mode))
1096 (void) rmdir(mount_outside);
1097 else
1098 (void) unlink(mount_outside);
1099 }
1100
1101 if (mount_tmp_mounted)
1102 (void) umount_verbose(LOG_DEBUG, mount_tmp, UMOUNT_NOFOLLOW);
1103 if (mount_tmp_created) {
1104 if ((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || S_ISDIR(chased_src_st->st_mode))
1105 (void) rmdir(mount_tmp);
1106 else
1107 (void) unlink(mount_tmp);
1108 }
1109
1110 if (mount_slave_mounted)
1111 (void) umount_verbose(LOG_DEBUG, mount_slave, UMOUNT_NOFOLLOW);
1112 if (mount_slave_created)
1113 (void) rmdir(mount_slave);
1114
1115 return r;
1116}
1117
1118static int mount_in_namespace(
1119 const PidRef *target,
1120 const char *propagate_path,
1121 const char *incoming_path,
1122 const char *src,
1123 const char *dest,
1124 MountInNamespaceFlags flags,
1125 const MountOptions *options,
1126 const ImagePolicy *image_policy) {
1127
1128 _cleanup_close_ int mntns_fd = -EBADF, root_fd = -EBADF, pidns_fd = -EBADF, chased_src_fd = -EBADF;
1129 _cleanup_free_ char *chased_src_path = NULL;
1130 struct stat st;
1131 int r;
1132
1133 assert(propagate_path);
1134 assert(incoming_path);
1135 assert(src);
1136 assert(dest);
1137 assert((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || (!options && !image_policy));
1138
1139 if (!pidref_is_set(target))
1140 return -ESRCH;
1141
1142 r = pidref_namespace_open(target, &pidns_fd, &mntns_fd, /* ret_netns_fd = */ NULL, /* ret_userns_fd = */ NULL, &root_fd);
1143 if (r < 0)
1144 return log_debug_errno(r, "Failed to retrieve FDs of the target process' namespace: %m");
1145
1146 r = is_our_namespace(mntns_fd, NAMESPACE_MOUNT);
1147 if (r < 0)
1148 return log_debug_errno(r, "Failed to determine if mount namespaces are equal: %m");
1149 /* We can't add new mounts at runtime if the process wasn't started in a namespace */
1150 if (r > 0)
1151 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to activate bind mount in target, not running in a mount namespace.");
1152
1153 r = chase(src, NULL, 0, &chased_src_path, &chased_src_fd);
1154 if (r < 0)
1155 return log_debug_errno(r, "Failed to resolve source path '%s': %m", src);
1156 log_debug("Chased source path '%s': %s", src, chased_src_path);
1157
1158 if (fstat(chased_src_fd, &st) < 0)
1159 return log_debug_errno(errno, "Failed to stat() resolved source path '%s': %m", src);
1160 if (S_ISLNK(st.st_mode)) /* This shouldn't really happen, given that we just chased the symlinks above, but let's better be safe… */
1161 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP), "Source path '%s' can't be a symbolic link.", src);
1162
1163 if (!mount_new_api_supported()) /* Fallback if we can't use the new mount API */
1164 return mount_in_namespace_legacy(
1165 chased_src_path,
1166 chased_src_fd,
1167 &st,
1168 propagate_path,
1169 incoming_path,
1170 dest,
1171 pidns_fd,
1172 mntns_fd,
1173 root_fd,
1174 flags,
1175 options,
1176 image_policy);
1177
1178 _cleanup_(dissected_image_unrefp) DissectedImage *img = NULL;
1179 _cleanup_close_ int new_mount_fd = -EBADF;
1180 _cleanup_close_pair_ int errno_pipe_fd[2] = EBADF_PAIR;
1181 pid_t child;
1182
1183 if (flags & MOUNT_IN_NAMESPACE_IS_IMAGE) {
1184 r = verity_dissect_and_mount(
1185 chased_src_fd,
1186 chased_src_path,
1187 /* dest= */ NULL,
1188 options,
1189 image_policy,
1190 /* image_filter= */ NULL,
1191 /* extension_release_data= */ NULL,
1192 /* required_class= */ _IMAGE_CLASS_INVALID,
1193 /* verity= */ NULL,
1194 &img);
1195 if (r < 0)
1196 return log_debug_errno(r,
1197 "Failed to dissect and mount image '%s': %m",
1198 chased_src_path);
1199 } else {
1200 new_mount_fd = open_tree(
1201 chased_src_fd,
1202 "",
1203 OPEN_TREE_CLONE|OPEN_TREE_CLOEXEC|AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH);
1204 if (new_mount_fd < 0)
1205 return log_debug_errno(
1206 errno,
1207 "Failed to open mount source '%s': %m",
1208 chased_src_path);
1209
1210 if ((flags & MOUNT_IN_NAMESPACE_READ_ONLY) && mount_setattr(new_mount_fd, "", AT_EMPTY_PATH,
1211 &(struct mount_attr) {
1212 .attr_set = MOUNT_ATTR_RDONLY,
1213 }, MOUNT_ATTR_SIZE_VER0) < 0)
1214 return log_debug_errno(errno,
1215 "Failed to set mount for '%s' to read only: %m",
1216 chased_src_path);
1217 }
1218
1219 if (pipe2(errno_pipe_fd, O_CLOEXEC|O_NONBLOCK) < 0)
1220 return log_debug_errno(errno, "Failed to create pipe: %m");
1221
1222 r = namespace_fork("(sd-bindmnt)",
1223 "(sd-bindmnt-inner)",
1224 /* except_fds= */ NULL,
1225 /* n_except_fds= */ 0,
1226 FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM,
1227 pidns_fd,
1228 mntns_fd,
1229 /* netns_fd= */ -EBADF,
1230 /* userns_fd= */ -EBADF,
1231 root_fd,
1232 &child);
1233 if (r < 0)
1234 return log_debug_errno(r, "Failed to fork off mount helper into namespace: %m");
1235 if (r == 0) {
1236 errno_pipe_fd[0] = safe_close(errno_pipe_fd[0]);
1237
1238 _cleanup_close_ int dest_fd = -EBADF;
1239 _cleanup_free_ char *dest_fn = NULL;
1240 r = chase(dest, /* root= */ NULL, CHASE_PARENT|CHASE_EXTRACT_FILENAME|((flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY) ? CHASE_MKDIR_0755 : 0), &dest_fn, &dest_fd);
1241 if (r < 0)
1242 report_errno_and_exit(errno_pipe_fd[1], r);
1243
1244 if (flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY)
1245 (void) make_mount_point_inode_from_mode(dest_fd, dest_fn, img ? S_IFDIR : st.st_mode, 0700);
1246
1247 if (img) {
1248 DissectImageFlags f =
1249 DISSECT_IMAGE_TRY_ATOMIC_MOUNT_EXCHANGE |
1250 DISSECT_IMAGE_ALLOW_USERSPACE_VERITY;
1251
1252 if (flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY)
1253 f |= DISSECT_IMAGE_MKDIR;
1254
1255 if (flags & MOUNT_IN_NAMESPACE_READ_ONLY)
1256 f |= DISSECT_IMAGE_READ_ONLY;
1257
1258 r = dissected_image_mount(
1259 img,
1260 dest,
1261 /* uid_shift= */ UID_INVALID,
1262 /* uid_range= */ UID_INVALID,
1263 /* userns_fd= */ -EBADF,
1264 f);
1265 } else
1266 r = mount_exchange_graceful(new_mount_fd, dest, /* mount_beneath= */ true);
1267
1268 report_errno_and_exit(errno_pipe_fd[1], r);
1269 }
1270
1271 errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
1272
1273 r = wait_for_terminate_and_check("(sd-bindmnt)", child, 0);
1274 if (r < 0)
1275 return log_debug_errno(r, "Failed to wait for child: %m");
1276 if (r != EXIT_SUCCESS) {
1277 if (read(errno_pipe_fd[0], &r, sizeof(r)) == sizeof(r))
1278 return log_debug_errno(r, "Failed to mount into namespace: %m");
1279
1280 return log_debug_errno(SYNTHETIC_ERRNO(EPROTO), "Child failed.");
1281 }
1282
1283 return 0;
1284}
1285
1286int bind_mount_in_namespace(
1287 const PidRef *target,
1288 const char *propagate_path,
1289 const char *incoming_path,
1290 const char *src,
1291 const char *dest,
1292 MountInNamespaceFlags flags) {
1293
1294 return mount_in_namespace(target,
1295 propagate_path,
1296 incoming_path,
1297 src,
1298 dest,
1299 flags & ~MOUNT_IN_NAMESPACE_IS_IMAGE,
1300 /* options = */ NULL,
1301 /* image_policy = */ NULL);
1302}
1303
1304int mount_image_in_namespace(
1305 const PidRef *target,
1306 const char *propagate_path,
1307 const char *incoming_path,
1308 const char *src,
1309 const char *dest,
1310 MountInNamespaceFlags flags,
1311 const MountOptions *options,
1312 const ImagePolicy *image_policy) {
1313
1314 return mount_in_namespace(target,
1315 propagate_path,
1316 incoming_path,
1317 src,
1318 dest,
1319 flags | MOUNT_IN_NAMESPACE_IS_IMAGE,
1320 options,
1321 image_policy);
1322}
1323
1324int make_mount_point(const char *path) {
1325 int r;
1326
1327 assert(path);
1328
1329 /* If 'path' is already a mount point, does nothing and returns 0. If it is not it makes it one, and returns 1. */
1330
1331 r = path_is_mount_point(path);
1332 if (r < 0)
1333 return log_debug_errno(r, "Failed to determine whether '%s' is a mount point: %m", path);
1334 if (r > 0)
1335 return 0;
1336
1337 r = mount_nofollow_verbose(LOG_DEBUG, path, path, NULL, MS_BIND|MS_REC, NULL);
1338 if (r < 0)
1339 return r;
1340
1341 return 1;
1342}
1343
1344int fd_make_mount_point(int fd) {
1345 int r;
1346
1347 assert(fd >= 0);
1348
1349 r = is_mount_point_at(fd, NULL, 0);
1350 if (r < 0)
1351 return log_debug_errno(r, "Failed to determine whether file descriptor is a mount point: %m");
1352 if (r > 0)
1353 return 0;
1354
1355 r = mount_follow_verbose(LOG_DEBUG, FORMAT_PROC_FD_PATH(fd), FORMAT_PROC_FD_PATH(fd), NULL, MS_BIND|MS_REC, NULL);
1356 if (r < 0)
1357 return r;
1358
1359 return 1;
1360}
1361
1362int make_userns(uid_t uid_shift,
1363 uid_t uid_range,
1364 uid_t source_owner,
1365 uid_t dest_owner,
1366 RemountIdmapping idmapping) {
1367
1368 _cleanup_close_ int userns_fd = -EBADF;
1369 _cleanup_free_ char *line = NULL;
1370 uid_t source_base = 0;
1371
1372 /* Allocates a userns file descriptor with the mapping we need. For this we'll fork off a child
1373 * process whose only purpose is to give us a new user namespace. It's killed when we got it. */
1374
1375 if (!userns_shift_range_valid(uid_shift, uid_range))
1376 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid UID range for user namespace.");
1377
1378 switch (idmapping) {
1379
1380 case REMOUNT_IDMAPPING_FOREIGN_WITH_HOST_ROOT:
1381 source_base = FOREIGN_UID_BASE;
1382 _fallthrough_;
1383
1384 case REMOUNT_IDMAPPING_NONE:
1385 case REMOUNT_IDMAPPING_HOST_ROOT:
1386
1387 if (asprintf(&line,
1388 UID_FMT " " UID_FMT " " UID_FMT "\n",
1389 source_base, uid_shift, uid_range) < 0)
1390 return log_oom_debug();
1391
1392 /* If requested we'll include an entry in the mapping so that the host root user can make
1393 * changes to the uidmapped mount like it normally would. Specifically, we'll map the user
1394 * with UID_MAPPED_ROOT on the backing fs to UID 0. This is useful, since nspawn code wants
1395 * to create various missing inodes in the OS tree before booting into it, and this becomes
1396 * very easy and straightforward to do if it can just do it under its own regular UID. Note
1397 * that in that case the container's runtime uidmap (i.e. the one the container payload
1398 * processes run in) will leave this UID unmapped, i.e. if we accidentally leave files owned
1399 * by host root in the already uidmapped tree around they'll show up as owned by 'nobody',
1400 * which is safe. (Of course, we shouldn't leave such inodes around, but always chown() them
1401 * to the container's own UID range, but it's good to have a safety net, in case we
1402 * forget it.) */
1403 if (idmapping == REMOUNT_IDMAPPING_HOST_ROOT)
1404 if (strextendf(&line,
1405 UID_FMT " " UID_FMT " " UID_FMT "\n",
1406 UID_MAPPED_ROOT, (uid_t) 0u, (uid_t) 1u) < 0)
1407 return log_oom_debug();
1408
1409 break;
1410
1411 case REMOUNT_IDMAPPING_HOST_OWNER:
1412 /* Remap the owner of the bind mounted directory to the root user within the container. This
1413 * way every file written by root within the container to the bind-mounted directory will
1414 * be owned by the original user from the host. All other users will remain unmapped. */
1415 if (asprintf(&line,
1416 UID_FMT " " UID_FMT " " UID_FMT "\n",
1417 source_owner, uid_shift, (uid_t) 1u) < 0)
1418 return log_oom_debug();
1419 break;
1420
1421 case REMOUNT_IDMAPPING_HOST_OWNER_TO_TARGET_OWNER:
1422 /* Remap the owner of the bind mounted directory to the owner of the target directory
1423 * within the container. This way every file written by target directory owner within the
1424 * container to the bind-mounted directory will be owned by the original host user.
1425 * All other users will remain unmapped. */
1426 if (asprintf(&line,
1427 UID_FMT " " UID_FMT " " UID_FMT "\n",
1428 source_owner, dest_owner, (uid_t) 1u) < 0)
1429 return log_oom_debug();
1430 break;
1431
1432 default:
1433 assert_not_reached();
1434 }
1435
1436 /* We always assign the same UID and GID ranges */
1437 userns_fd = userns_acquire(line, line, /* setgroups_deny= */ true);
1438 if (userns_fd < 0)
1439 return log_debug_errno(userns_fd, "Failed to acquire new userns: %m");
1440
1441 return TAKE_FD(userns_fd);
1442}
1443
1444int remount_idmap_fd(
1445 char **paths,
1446 int userns_fd,
1447 uint64_t extra_mount_attr_set) {
1448
1449 int r;
1450
1451 assert(userns_fd >= 0);
1452
1453 /* This remounts all specified paths with the specified userns as idmap. It will do so in the
1454 * order specified in the strv: the expectation is that the top-level directories are at the
1455 * beginning, and nested directories in the right, so that the tree can be built correctly from left
1456 * to right. */
1457
1458 size_t n = strv_length(paths);
1459 if (n == 0) /* Nothing to do? */
1460 return 0;
1461
1462 int *mount_fds = NULL;
1463 size_t n_mounts_fds = 0;
1464
1465 mount_fds = new(int, n);
1466 if (!mount_fds)
1467 return log_oom_debug();
1468
1469 CLEANUP_ARRAY(mount_fds, n_mounts_fds, close_many_and_free);
1470
1471 for (size_t i = 0; i < n; i++) {
1472 int mntfd;
1473
1474 /* Clone the mount point */
1475 mntfd = mount_fds[n_mounts_fds] = open_tree(-EBADF, paths[i], OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);
1476 if (mount_fds[n_mounts_fds] < 0)
1477 return log_debug_errno(errno, "Failed to open tree of mounted filesystem '%s': %m", paths[i]);
1478
1479 n_mounts_fds++;
1480
1481 /* Set the user namespace mapping attribute on the cloned mount point */
1482 if (mount_setattr(mntfd, "", AT_EMPTY_PATH,
1483 &(struct mount_attr) {
1484 .attr_set = MOUNT_ATTR_IDMAP | extra_mount_attr_set,
1485 .userns_fd = userns_fd,
1486 }, sizeof(struct mount_attr)) < 0)
1487 return log_debug_errno(errno, "Failed to change bind mount attributes for clone of '%s': %m", paths[i]);
1488 }
1489
1490 for (size_t i = n; i > 0; i--) { /* Unmount the paths right-to-left */
1491 /* Remove the old mount points now that we have a idmapped mounts as replacement for all of them */
1492 r = umount_verbose(LOG_DEBUG, paths[i-1], UMOUNT_NOFOLLOW);
1493 if (r < 0)
1494 return r;
1495 }
1496
1497 for (size_t i = 0; i < n; i++) { /* Mount the replacement mounts left-to-right */
1498 /* And place the cloned version in its place */
1499 log_debug("Mounting idmapped fs to '%s'", paths[i]);
1500 if (move_mount(mount_fds[i], "", -EBADF, paths[i], MOVE_MOUNT_F_EMPTY_PATH) < 0)
1501 return log_debug_errno(errno, "Failed to attach UID mapped mount to '%s': %m", paths[i]);
1502 }
1503
1504 return 0;
1505}
1506
1507int remount_idmap(
1508 char **p,
1509 uid_t uid_shift,
1510 uid_t uid_range,
1511 uid_t source_owner,
1512 uid_t dest_owner,
1513 RemountIdmapping idmapping) {
1514
1515 _cleanup_close_ int userns_fd = -EBADF;
1516
1517 userns_fd = make_userns(uid_shift, uid_range, source_owner, dest_owner, idmapping);
1518 if (userns_fd < 0)
1519 return userns_fd;
1520
1521 return remount_idmap_fd(p, userns_fd, /* extra_mount_attr_set= */ 0);
1522}
1523
1524static void sub_mount_clear(SubMount *s) {
1525 assert(s);
1526
1527 s->path = mfree(s->path);
1528 s->mount_fd = safe_close(s->mount_fd);
1529}
1530
1531void sub_mount_array_free(SubMount *s, size_t n) {
1532 assert(s || n == 0);
1533
1534 for (size_t i = 0; i < n; i++)
1535 sub_mount_clear(s + i);
1536
1537 free(s);
1538}
1539
1540static int sub_mount_compare(const SubMount *a, const SubMount *b) {
1541 assert(a);
1542 assert(b);
1543 assert(a->path);
1544 assert(b->path);
1545
1546 return path_compare(a->path, b->path);
1547}
1548
1549static void sub_mount_drop(SubMount *s, size_t n) {
1550 assert(s || n == 0);
1551
1552 for (size_t m = 0, i = 1; i < n; i++) {
1553 if (path_startswith(s[i].path, s[m].path))
1554 sub_mount_clear(s + i);
1555 else
1556 m = i;
1557 }
1558}
1559
1560int get_sub_mounts(const char *prefix, SubMount **ret_mounts, size_t *ret_n_mounts) {
1561
1562 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
1563 _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
1564 SubMount *mounts = NULL;
1565 size_t n = 0;
1566 int r;
1567
1568 CLEANUP_ARRAY(mounts, n, sub_mount_array_free);
1569
1570 assert(prefix);
1571 assert(ret_mounts);
1572 assert(ret_n_mounts);
1573
1574 r = libmount_parse_mountinfo(/* source = */ NULL, &table, &iter);
1575 if (r < 0)
1576 return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
1577
1578 for (;;) {
1579 _cleanup_close_ int mount_fd = -EBADF;
1580 _cleanup_free_ char *p = NULL;
1581 struct libmnt_fs *fs;
1582 const char *path;
1583 int id1, id2;
1584
1585 r = mnt_table_next_fs(table, iter, &fs);
1586 if (r == 1)
1587 break; /* EOF */
1588 if (r < 0)
1589 return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
1590
1591 path = mnt_fs_get_target(fs);
1592 if (!path)
1593 continue;
1594
1595 if (isempty(path_startswith(path, prefix)))
1596 continue;
1597
1598 id1 = mnt_fs_get_id(fs);
1599 r = path_get_mnt_id(path, &id2);
1600 if (r < 0) {
1601 log_debug_errno(r, "Failed to get mount ID of '%s', ignoring: %m", path);
1602 continue;
1603 }
1604 if (id1 != id2) {
1605 /* The path may be hidden by another over-mount or already remounted. */
1606 log_debug("The mount IDs of '%s' obtained by libmount and path_get_mnt_id() are different (%i vs %i), ignoring.",
1607 path, id1, id2);
1608 continue;
1609 }
1610
1611 mount_fd = open(path, O_CLOEXEC|O_PATH);
1612 if (mount_fd < 0) {
1613 if (errno == ENOENT) /* The path may be hidden by another over-mount or already unmounted. */
1614 continue;
1615
1616 return log_debug_errno(errno, "Failed to open subtree of mounted filesystem '%s': %m", path);
1617 }
1618
1619 p = strdup(path);
1620 if (!p)
1621 return log_oom_debug();
1622
1623 if (!GREEDY_REALLOC(mounts, n + 1))
1624 return log_oom_debug();
1625
1626 mounts[n++] = (SubMount) {
1627 .path = TAKE_PTR(p),
1628 .mount_fd = TAKE_FD(mount_fd),
1629 };
1630 }
1631
1632 typesafe_qsort(mounts, n, sub_mount_compare);
1633 sub_mount_drop(mounts, n);
1634
1635 *ret_mounts = TAKE_PTR(mounts);
1636 *ret_n_mounts = n;
1637 return 0;
1638}
1639
1640int bind_mount_submounts(
1641 const char *source,
1642 const char *target) {
1643
1644 SubMount *mounts = NULL;
1645 size_t n = 0;
1646 int ret = 0, r;
1647
1648 /* Bind mounts all child mounts of 'source' to 'target'. Useful when setting up a new procfs instance
1649 * with new mount options to copy the original submounts over. */
1650
1651 assert(source);
1652 assert(target);
1653
1654 CLEANUP_ARRAY(mounts, n, sub_mount_array_free);
1655
1656 r = get_sub_mounts(source, &mounts, &n);
1657 if (r < 0)
1658 return r;
1659
1660 FOREACH_ARRAY(m, mounts, n) {
1661 _cleanup_free_ char *t = NULL;
1662 const char *suffix;
1663
1664 if (isempty(m->path))
1665 continue;
1666
1667 assert_se(suffix = path_startswith(m->path, source));
1668
1669 t = path_join(target, suffix);
1670 if (!t)
1671 return -ENOMEM;
1672
1673 r = path_is_mount_point(t);
1674 if (r < 0) {
1675 log_debug_errno(r, "Failed to detect if '%s' already is a mount point, ignoring: %m", t);
1676 continue;
1677 }
1678 if (r > 0) {
1679 log_debug("Not bind mounting '%s' from '%s' to '%s', since there's already a mountpoint.", suffix, source, target);
1680 continue;
1681 }
1682
1683 r = mount_follow_verbose(LOG_DEBUG, FORMAT_PROC_FD_PATH(m->mount_fd), t, NULL, MS_BIND|MS_REC, NULL);
1684 if (r < 0 && ret == 0)
1685 ret = r;
1686 }
1687
1688 return ret;
1689}
1690
1691int make_mount_point_inode_from_mode(int dir_fd, const char *dest, mode_t source_mode, mode_t target_mode) {
1692 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
1693 assert(dest);
1694
1695 if (S_ISDIR(source_mode))
1696 return mkdirat_label(dir_fd, dest, target_mode & 07777);
1697 else
1698 return RET_NERRNO(mknodat(dir_fd, dest, S_IFREG|(target_mode & 07666), 0)); /* Mask off X bit */
1699}
1700
1701int make_mount_point_inode_from_path(const char *source, const char *dest, mode_t access_mode) {
1702 struct stat st;
1703
1704 assert(source);
1705 assert(dest);
1706
1707 if (stat(source, &st) < 0)
1708 return -errno;
1709
1710 return make_mount_point_inode_from_mode(AT_FDCWD, dest, st.st_mode, access_mode);
1711}
1712
1713int trigger_automount_at(int dir_fd, const char *path) {
1714 _cleanup_free_ char *nested = NULL;
1715
1716 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
1717
1718 nested = path_join(path, "a");
1719 if (!nested)
1720 return -ENOMEM;
1721
1722 (void) faccessat(dir_fd, nested, F_OK, 0);
1723
1724 return 0;
1725}
1726
1727unsigned long credentials_fs_mount_flags(bool ro) {
1728 /* A tight set of mount flags for credentials mounts */
1729 return MS_NODEV|MS_NOEXEC|MS_NOSUID|ms_nosymfollow_supported()|(ro ? MS_RDONLY : 0);
1730}
1731
1732int mount_credentials_fs(const char *path, size_t size, bool ro) {
1733 _cleanup_free_ char *opts = NULL;
1734 int r, noswap_supported;
1735
1736 /* Mounts a file system we can place credentials in, i.e. with tight access modes right from the
1737 * beginning, and ideally swapping turned off. In order of preference:
1738 *
1739 * 1. tmpfs if it supports "noswap"
1740 * 2. ramfs
1741 * 3. tmpfs if it doesn't support "noswap"
1742 */
1743
1744 noswap_supported = mount_option_supported("tmpfs", "noswap", NULL); /* Check explicitly to avoid kmsg noise */
1745 if (noswap_supported > 0) {
1746 _cleanup_free_ char *noswap_opts = NULL;
1747
1748 if (asprintf(&noswap_opts, "mode=0700,nr_inodes=1024,size=%zu,noswap", size) < 0)
1749 return -ENOMEM;
1750
1751 /* Best case: tmpfs with noswap (needs kernel >= 6.3) */
1752
1753 r = mount_nofollow_verbose(
1754 LOG_DEBUG,
1755 "tmpfs",
1756 path,
1757 "tmpfs",
1758 credentials_fs_mount_flags(ro),
1759 noswap_opts);
1760 if (r >= 0)
1761 return r;
1762 }
1763
1764 r = mount_nofollow_verbose(
1765 LOG_DEBUG,
1766 "ramfs",
1767 path,
1768 "ramfs",
1769 credentials_fs_mount_flags(ro),
1770 "mode=0700");
1771 if (r >= 0)
1772 return r;
1773
1774 if (asprintf(&opts, "mode=0700,nr_inodes=1024,size=%zu", size) < 0)
1775 return -ENOMEM;
1776
1777 return mount_nofollow_verbose(
1778 LOG_DEBUG,
1779 "tmpfs",
1780 path,
1781 "tmpfs",
1782 credentials_fs_mount_flags(ro),
1783 opts);
1784}
1785
1786int make_fsmount(
1787 int error_log_level,
1788 const char *what,
1789 const char *type,
1790 unsigned long flags,
1791 const char *options,
1792 int userns_fd) {
1793
1794 _cleanup_close_ int fs_fd = -EBADF, mnt_fd = -EBADF;
1795 _cleanup_free_ char *o = NULL;
1796 unsigned long f;
1797 int r;
1798
1799 assert(type);
1800 assert(what);
1801
1802 r = mount_option_mangle(options, flags, &f, &o);
1803 if (r < 0)
1804 return log_full_errno(
1805 error_log_level, r, "Failed to mangle mount options %s: %m",
1806 strempty(options));
1807
1808 if (DEBUG_LOGGING) {
1809 _cleanup_free_ char *fl = NULL;
1810 (void) mount_flags_to_string(f, &fl);
1811
1812 log_debug("Creating mount fd for %s (%s) (%s \"%s\")...",
1813 strna(what), strna(type), strnull(fl), strempty(o));
1814 }
1815
1816 fs_fd = fsopen(type, FSOPEN_CLOEXEC);
1817 if (fs_fd < 0)
1818 return log_full_errno(error_log_level, errno, "Failed to open superblock for \"%s\": %m", type);
1819
1820 if (fsconfig(fs_fd, FSCONFIG_SET_STRING, "source", what, 0) < 0)
1821 return log_full_errno(error_log_level, errno, "Failed to set mount source for \"%s\" to \"%s\": %m", type, what);
1822
1823 if (FLAGS_SET(f, MS_RDONLY))
1824 if (fsconfig(fs_fd, FSCONFIG_SET_FLAG, "ro", NULL, 0) < 0)
1825 return log_full_errno(error_log_level, errno, "Failed to set read only mount flag for \"%s\": %m", type);
1826
1827 for (const char *p = o;;) {
1828 _cleanup_free_ char *word = NULL;
1829 char *eq;
1830
1831 r = extract_first_word(&p, &word, ",", EXTRACT_KEEP_QUOTE);
1832 if (r < 0)
1833 return log_full_errno(error_log_level, r, "Failed to parse mount option string \"%s\": %m", o);
1834 if (r == 0)
1835 break;
1836
1837 eq = strchr(word, '=');
1838 if (eq) {
1839 *eq = 0;
1840 eq++;
1841
1842 if (fsconfig(fs_fd, FSCONFIG_SET_STRING, word, eq, 0) < 0)
1843 return log_full_errno(error_log_level, errno, "Failed to set mount option \"%s=%s\" for \"%s\": %m", word, eq, type);
1844 } else {
1845 if (fsconfig(fs_fd, FSCONFIG_SET_FLAG, word, NULL, 0) < 0)
1846 return log_full_errno(error_log_level, errno, "Failed to set mount flag \"%s\" for \"%s\": %m", word, type);
1847 }
1848 }
1849
1850 if (fsconfig(fs_fd, FSCONFIG_CMD_CREATE, NULL, NULL, 0) < 0)
1851 return log_full_errno(error_log_level, errno, "Failed to realize fs fd for \"%s\" (\"%s\"): %m", what, type);
1852
1853 mnt_fd = fsmount(fs_fd, FSMOUNT_CLOEXEC, 0);
1854 if (mnt_fd < 0)
1855 return log_full_errno(error_log_level, errno, "Failed to create mount fd for \"%s\" (\"%s\"): %m", what, type);
1856
1857 struct mount_attr ma = {
1858 .attr_set = ms_flags_to_mount_attr(f) | (userns_fd >= 0 ? MOUNT_ATTR_IDMAP : 0),
1859 .userns_fd = userns_fd,
1860 };
1861 if (ma.attr_set != 0 && mount_setattr(mnt_fd, "", AT_EMPTY_PATH|AT_RECURSIVE, &ma, MOUNT_ATTR_SIZE_VER0) < 0)
1862 return log_full_errno(error_log_level,
1863 errno,
1864 "Failed to set mount flags for \"%s\" (\"%s\"): %m",
1865 what,
1866 type);
1867
1868 return TAKE_FD(mnt_fd);
1869}
1870
1871char* umount_and_rmdir_and_free(char *p) {
1872 if (!p)
1873 return NULL;
1874
1875 PROTECT_ERRNO;
1876 (void) umount_recursive(p, 0);
1877 (void) rmdir(p);
1878 return mfree(p);
1879}
1880
1881char* umount_and_free(char *p) {
1882 if (!p)
1883 return NULL;
1884
1885 PROTECT_ERRNO;
1886 (void) umount_recursive(p, 0);
1887 return mfree(p);
1888}
1889
1890char* umount_and_unlink_and_free(char *p) {
1891 if (!p)
1892 return NULL;
1893
1894 PROTECT_ERRNO;
1895 (void) umount2(p, 0);
1896 (void) unlink(p);
1897 return mfree(p);
1898}
1899
1900int path_get_mount_info_at(
1901 int dir_fd,
1902 const char *path,
1903 char **ret_fstype,
1904 char **ret_options,
1905 char **ret_source) {
1906
1907 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
1908 _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
1909 int r, mnt_id;
1910
1911 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
1912
1913 r = path_get_mnt_id_at(dir_fd, path, &mnt_id);
1914 if (r < 0)
1915 return log_debug_errno(r, "Failed to get mount ID: %m");
1916
1917 /* When getting options is requested, we also need to parse utab, otherwise userspace options like
1918 * "_netdev" will be lost. */
1919 if (ret_options)
1920 r = libmount_parse_with_utab(&table, &iter);
1921 else
1922 r = libmount_parse_mountinfo(/* source = */ NULL, &table, &iter);
1923 if (r < 0)
1924 return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
1925
1926 for (;;) {
1927 struct libmnt_fs *fs;
1928
1929 r = mnt_table_next_fs(table, iter, &fs);
1930 if (r == 1)
1931 break; /* EOF */
1932 if (r < 0)
1933 return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
1934
1935 if (mnt_fs_get_id(fs) != mnt_id)
1936 continue;
1937
1938 _cleanup_free_ char *fstype = NULL, *options = NULL, *source = NULL;
1939
1940 if (ret_fstype) {
1941 fstype = strdup(strempty(mnt_fs_get_fstype(fs)));
1942 if (!fstype)
1943 return log_oom_debug();
1944 }
1945
1946 if (ret_options) {
1947 options = strdup(strempty(mnt_fs_get_options(fs)));
1948 if (!options)
1949 return log_oom_debug();
1950 }
1951
1952 if (ret_source) {
1953 source = strdup(strempty(mnt_fs_get_source(fs)));
1954 if (!source)
1955 return log_oom_debug();
1956 }
1957
1958 if (ret_fstype)
1959 *ret_fstype = TAKE_PTR(fstype);
1960 if (ret_options)
1961 *ret_options = TAKE_PTR(options);
1962 if (ret_source)
1963 *ret_source = TAKE_PTR(source);
1964
1965 return 0;
1966 }
1967
1968 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "Cannot find mount ID %i from /proc/self/mountinfo.", mnt_id);
1969}
1970
1971int path_is_network_fs_harder_at(int dir_fd, const char *path) {
1972 _cleanup_close_ int fd = -EBADF;
1973 int r;
1974
1975 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
1976
1977 fd = xopenat(dir_fd, path, O_PATH | O_CLOEXEC | O_NOFOLLOW);
1978 if (fd < 0)
1979 return fd;
1980
1981 r = fd_is_network_fs(fd);
1982 if (r != 0)
1983 return r;
1984
1985 _cleanup_free_ char *fstype = NULL, *options = NULL;
1986 r = path_get_mount_info_at(fd, /* path = */ NULL, &fstype, &options, /* ret_source = */ NULL);
1987 if (r < 0)
1988 return r;
1989
1990 if (fstype_is_network(fstype))
1991 return true;
1992
1993 if (fstab_test_option(options, "_netdev\0"))
1994 return true;
1995
1996 return false;
1997}