]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/mount-util.c
Move fork_agent() into shared/
[thirdparty/systemd.git] / src / shared / mount-util.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
4349cd7c 2
11c3a366
TA
3#include <errno.h>
4#include <stdlib.h>
4349cd7c 5#include <sys/mount.h>
11c3a366 6#include <sys/stat.h>
4349cd7c 7#include <sys/statvfs.h>
11c3a366 8#include <unistd.h>
35fd3558
LP
9#include <linux/loop.h>
10#include <linux/fs.h>
4349cd7c 11
b5efdb8a 12#include "alloc-util.h"
70599967 13#include "dissect-image.h"
9e7f941a 14#include "extract-word.h"
4349cd7c
LP
15#include "fd-util.h"
16#include "fileio.h"
e1873695 17#include "fs-util.h"
93cc7779 18#include "hashmap.h"
9c653536 19#include "label.h"
13dcfe46 20#include "libmount-util.h"
1c092b62 21#include "missing_mount.h"
35fd3558 22#include "missing_syscall.h"
6af52c3a 23#include "mkdir.h"
4349cd7c 24#include "mount-util.h"
049af8ad 25#include "mountpoint-util.h"
2338a175 26#include "namespace-util.h"
4349cd7c
LP
27#include "parse-util.h"
28#include "path-util.h"
6af52c3a 29#include "process-util.h"
4349cd7c 30#include "set.h"
28126409 31#include "stat-util.h"
15a5e950 32#include "stdio-util.h"
4349cd7c 33#include "string-util.h"
6b7c9f8b 34#include "strv.h"
6af52c3a 35#include "tmpfile-util.h"
70599967 36#include "user-util.h"
4349cd7c 37
28126409
LP
38int mount_fd(const char *source,
39 int target_fd,
40 const char *filesystemtype,
41 unsigned long mountflags,
42 const void *data) {
43
44 char path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
45
46 xsprintf(path, "/proc/self/fd/%i", target_fd);
47 if (mount(source, path, filesystemtype, mountflags, data) < 0) {
48 if (errno != ENOENT)
49 return -errno;
50
51 /* ENOENT can mean two things: either that the source is missing, or that /proc/ isn't
52 * mounted. Check for the latter to generate better error messages. */
53 if (proc_mounted() == 0)
54 return -ENOSYS;
55
56 return -ENOENT;
57 }
58
59 return 0;
60}
61
62int mount_nofollow(
63 const char *source,
64 const char *target,
65 const char *filesystemtype,
66 unsigned long mountflags,
67 const void *data) {
68
69 _cleanup_close_ int fd = -1;
70
71 /* In almost all cases we want to manipulate the mount table without following symlinks, hence
72 * mount_nofollow() is usually the way to go. The only exceptions are environments where /proc/ is
73 * not available yet, since we need /proc/self/fd/ for this logic to work. i.e. during the early
74 * initialization of namespacing/container stuff where /proc is not yet mounted (and maybe even the
75 * fs to mount) we can only use traditional mount() directly.
76 *
77 * Note that this disables following only for the final component of the target, i.e symlinks within
78 * the path of the target are honoured, as are symlinks in the source path everywhere. */
79
80 fd = open(target, O_PATH|O_CLOEXEC|O_NOFOLLOW);
81 if (fd < 0)
82 return -errno;
83
84 return mount_fd(source, fd, filesystemtype, mountflags, data);
85}
86
4349cd7c 87int umount_recursive(const char *prefix, int flags) {
4349cd7c 88 int n = 0, r;
f8b1904f 89 bool again;
4349cd7c 90
9d0619de
LP
91 /* Try to umount everything recursively below a directory. Also, take care of stacked mounts, and
92 * keep unmounting them until they are gone. */
4349cd7c
LP
93
94 do {
13dcfe46
ZJS
95 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
96 _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
4349cd7c
LP
97
98 again = false;
4349cd7c 99
2f2d81d9 100 r = libmount_parse("/proc/self/mountinfo", NULL, &table, &iter);
fdeea3f4 101 if (r < 0)
13dcfe46 102 return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
35bbbf85 103
4349cd7c 104 for (;;) {
13dcfe46
ZJS
105 struct libmnt_fs *fs;
106 const char *path;
4349cd7c 107
13dcfe46
ZJS
108 r = mnt_table_next_fs(table, iter, &fs);
109 if (r == 1)
110 break;
111 if (r < 0)
112 return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
4349cd7c 113
13dcfe46
ZJS
114 path = mnt_fs_get_target(fs);
115 if (!path)
116 continue;
4349cd7c 117
13dcfe46 118 if (!path_startswith(path, prefix))
4349cd7c
LP
119 continue;
120
827ea521
LP
121 if (umount2(path, flags | UMOUNT_NOFOLLOW) < 0) {
122 log_debug_errno(errno, "Failed to umount %s, ignoring: %m", path);
4349cd7c
LP
123 continue;
124 }
125
13dcfe46 126 log_debug("Successfully unmounted %s", path);
6b7c9f8b 127
4349cd7c
LP
128 again = true;
129 n++;
130
131 break;
132 }
4349cd7c
LP
133 } while (again);
134
13dcfe46 135 return n;
4349cd7c
LP
136}
137
be3f3752 138/* Use this function only if you do not have direct access to /proc/self/mountinfo but the caller can open it
64e82c19
LP
139 * for you. This is the case when /proc is masked or not mounted. Otherwise, use bind_remount_recursive. */
140int bind_remount_recursive_with_mountinfo(
141 const char *prefix,
142 unsigned long new_flags,
143 unsigned long flags_mask,
6b000af4 144 char **deny_list,
64e82c19
LP
145 FILE *proc_self_mountinfo) {
146
ba8dced2 147 _cleanup_set_free_ Set *done = NULL;
670e8efd 148 unsigned n_tries = 0;
4349cd7c
LP
149 int r;
150
8403219f 151 assert(prefix);
ac9de0b3
TR
152 assert(proc_self_mountinfo);
153
ddc155b2
TM
154 /* Recursively remount a directory (and all its submounts) with desired flags (MS_READONLY,
155 * MS_NOSUID, MS_NOEXEC). If the directory is already mounted, we reuse the mount and simply mark it
156 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write operation), ditto for other flags. If it
157 * isn't we first make it one. Afterwards we apply (or remove) the flags to all submounts we can
158 * access, too. When mounts are stacked on the same mount point we only care for each individual
159 * "top-level" mount on each point, as we cannot influence/access the underlying mounts anyway. We do
160 * not have any effect on future submounts that might get propagated, they might be writable
4b6ef527
LP
161 * etc. This includes future submounts that have been triggered via autofs. Also note that we can't
162 * operate atomically here. Mounts established while we process the tree might or might not get
163 * noticed and thus might or might not be covered.
6b7c9f8b 164 *
6b000af4
LP
165 * If the "deny_list" parameter is specified it may contain a list of subtrees to exclude from the
166 * remount operation. Note that we'll ignore the deny list for the top-level path. */
4349cd7c 167
4349cd7c 168 for (;;) {
13dcfe46
ZJS
169 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
170 _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
ba8dced2 171 _cleanup_hashmap_free_ Hashmap *todo = NULL;
4349cd7c 172 bool top_autofs = false;
4349cd7c 173
670e8efd
LP
174 if (n_tries++ >= 32) /* Let's not retry this loop forever */
175 return -EBUSY;
176
ac9de0b3 177 rewind(proc_self_mountinfo);
4349cd7c 178
e2857b3d 179 r = libmount_parse("/proc/self/mountinfo", proc_self_mountinfo, &table, &iter);
13dcfe46
ZJS
180 if (r < 0)
181 return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
4349cd7c 182
13dcfe46 183 for (;;) {
ba8dced2
LP
184 _cleanup_free_ char *d = NULL;
185 const char *path, *type, *opts;
186 unsigned long flags = 0;
13dcfe46 187 struct libmnt_fs *fs;
4349cd7c 188
13dcfe46 189 r = mnt_table_next_fs(table, iter, &fs);
d6bfab11 190 if (r == 1) /* EOF */
13dcfe46 191 break;
4349cd7c 192 if (r < 0)
13dcfe46 193 return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
4349cd7c 194
13dcfe46 195 path = mnt_fs_get_target(fs);
d6bfab11 196 if (!path)
6b7c9f8b
LP
197 continue;
198
c6111b85 199 if (!path_startswith(path, prefix))
13dcfe46
ZJS
200 continue;
201
d6bfab11
LP
202 type = mnt_fs_get_fstype(fs);
203 if (!type)
204 continue;
205
206 /* Let's ignore autofs mounts. If they aren't triggered yet, we want to avoid
207 * triggering them, as we don't make any guarantees for future submounts anyway. If
208 * they are already triggered, then we will find another entry for this. */
209 if (streq(type, "autofs")) {
210 top_autofs = top_autofs || path_equal(path, prefix);
211 continue;
212 }
213
214 if (set_contains(done, path))
215 continue;
216
6b000af4 217 /* Ignore this mount if it is deny-listed, but only if it isn't the top-level mount
13dcfe46 218 * we shall operate on. */
c6111b85 219 if (!path_equal(path, prefix)) {
6b000af4 220 bool deny_listed = false;
6b7c9f8b
LP
221 char **i;
222
6b000af4 223 STRV_FOREACH(i, deny_list) {
c6111b85 224 if (path_equal(*i, prefix))
6b7c9f8b
LP
225 continue;
226
c6111b85 227 if (!path_startswith(*i, prefix))
6b7c9f8b
LP
228 continue;
229
13dcfe46 230 if (path_startswith(path, *i)) {
6b000af4 231 deny_listed = true;
d6bfab11 232 log_debug("Not remounting %s deny-listed by %s, called for %s", path, *i, prefix);
6b7c9f8b
LP
233 break;
234 }
235 }
d6bfab11 236
6b000af4 237 if (deny_listed)
6b7c9f8b
LP
238 continue;
239 }
240
ba8dced2
LP
241 opts = mnt_fs_get_vfs_options(fs);
242 if (opts) {
243 r = mnt_optstr_get_flags(opts, &flags, mnt_get_builtin_optmap(MNT_LINUX_MAP));
244 if (r < 0)
245 log_debug_errno(r, "Could not get flags for '%s', ignoring: %m", path);
246 }
247
248 d = strdup(path);
249 if (!d)
250 return -ENOMEM;
251
252 r = hashmap_ensure_put(&todo, &path_hash_ops_free, d, ULONG_TO_PTR(flags));
253 if (r == -EEXIST)
e0103063
LB
254 /* If the same path was recorded, but with different mount flags, update it:
255 * it means a mount point is overmounted, and libmount returns the "bottom" (or
256 * older one) first, but we want to reapply the flags from the "top" (or newer
257 * one). See: https://github.com/systemd/systemd/issues/20032
258 * Note that this shouldn't really fail, as we were just told that the key
259 * exists, and it's an update so we want 'd' to be freed immediately. */
260 r = hashmap_update(todo, d, ULONG_TO_PTR(flags));
d6bfab11
LP
261 if (r < 0)
262 return r;
ba8dced2
LP
263 if (r > 0)
264 TAKE_PTR(d);
4349cd7c
LP
265 }
266
5c5753b9
LP
267 /* Check if the top-level directory was among what we have seen so far. For that check both
268 * 'done' and 'todo'. Also check 'top_autofs' because if the top-level dir is an autofs we'll
269 * not include it in either set but will set this bool. */
c6111b85 270 if (!set_contains(done, prefix) &&
ba8dced2 271 !(top_autofs || hashmap_contains(todo, prefix))) {
5c5753b9 272
6b7c9f8b 273 /* The prefix directory itself is not yet a mount, make it one. */
c6111b85 274 r = mount_nofollow(prefix, prefix, NULL, MS_BIND|MS_REC, NULL);
511a8cfe
LP
275 if (r < 0)
276 return r;
4349cd7c 277
5c5753b9
LP
278 /* Immediately rescan, so that we pick up the new mount's flags */
279 continue;
4349cd7c
LP
280 }
281
5c5753b9 282 /* If we have no submounts to process anymore, we are done */
ba8dced2 283 if (hashmap_isempty(todo))
5c5753b9
LP
284 return 0;
285
ba8dced2
LP
286 for (;;) {
287 unsigned long flags;
288 char *x = NULL;
289
290 /* Take the first mount from our list of mounts to still process */
291 flags = PTR_TO_ULONG(hashmap_steal_first_key_and_value(todo, (void**) &x));
292 if (!x)
293 break;
4349cd7c 294
ba8dced2 295 r = set_ensure_consume(&done, &path_hash_ops_free, x);
4c701096 296 if (IN_SET(r, 0, -EEXIST))
ba8dced2 297 continue; /* Already done */
4349cd7c
LP
298 if (r < 0)
299 return r;
300
ba8dced2
LP
301 /* Now, remount this with the new flags set, but exclude MS_RELATIME from it. (It's
302 * the default anyway, thus redundant, and in userns we'll get an error if we try to
303 * explicitly enable it) */
304 r = mount_nofollow(NULL, x, NULL, ((flags & ~flags_mask)|MS_BIND|MS_REMOUNT|new_flags) & ~MS_RELATIME, NULL);
065b4774 305 if (r < 0) {
ba8dced2
LP
306 int q;
307
308 /* OK, so the remount of this entry failed. We'll ultimately ignore this in
309 * almost all cases (there are simply so many reasons why this can fail,
310 * think autofs, NFS, FUSE, …), but let's generate useful debug messages at
311 * the very least. */
312
313 q = path_is_mount_point(x, NULL, 0);
314 if (IN_SET(q, 0, -ENOENT)) {
315 /* Hmm, whaaaa? The mount point is not actually a mount point? Then
316 * it is either obstructed by a later mount or somebody has been
317 * racing against us and removed it. Either way the mount point
318 * doesn't matter to us, let's ignore it hence. */
319 log_debug_errno(r, "Mount point '%s' to remount is not a mount point anymore, ignoring remount failure: %m", x);
320 continue;
321 }
322 if (q < 0) /* Any other error on this? Just log and continue */
323 log_debug_errno(q, "Failed to determine whether '%s' is a mount point or not, ignoring: %m", x);
324
325 if (((flags ^ new_flags) & flags_mask & ~MS_RELATIME) == 0) { /* ignore MS_RELATIME while comparing */
326 log_debug_errno(r, "Couldn't remount '%s', but the flags already match what we want, hence ignoring: %m", x);
327 continue;
328 }
329
330 /* Make this fatal if this is the top-level mount */
331 if (path_equal(x, prefix))
065b4774
LP
332 return r;
333
ba8dced2
LP
334 /* If this is not the top-level mount, then handle this gracefully: log but
335 * otherwise ignore. With NFS, FUSE, autofs there are just too many reasons
336 * this might fail without a chance for us to do anything about it, let's
337 * hence be strict on the top-level mount and lenient on the inner ones. */
338 log_debug_errno(r, "Couldn't remount submount '%s' for unexpected reason, ignoring: %m", x);
ef454fd1
YW
339 continue;
340 }
98df8089 341
ba8dced2 342 log_debug("Remounted %s.", x);
4349cd7c
LP
343 }
344 }
345}
346
8403219f
LP
347int bind_remount_recursive(
348 const char *prefix,
349 unsigned long new_flags,
350 unsigned long flags_mask,
6b000af4 351 char **deny_list) {
8403219f 352
ac9de0b3 353 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
fdeea3f4 354 int r;
ac9de0b3 355
fdeea3f4
ZJS
356 r = fopen_unlocked("/proc/self/mountinfo", "re", &proc_self_mountinfo);
357 if (r < 0)
358 return r;
35bbbf85 359
6b000af4 360 return bind_remount_recursive_with_mountinfo(prefix, new_flags, flags_mask, deny_list, proc_self_mountinfo);
ac9de0b3
TR
361}
362
7cce68e1
LP
363int bind_remount_one_with_mountinfo(
364 const char *path,
365 unsigned long new_flags,
366 unsigned long flags_mask,
367 FILE *proc_self_mountinfo) {
368
369 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
2c5ff8ea
LP
370 unsigned long flags = 0;
371 struct libmnt_fs *fs;
372 const char *opts;
7cce68e1
LP
373 int r;
374
375 assert(path);
376 assert(proc_self_mountinfo);
377
378 rewind(proc_self_mountinfo);
379
380 table = mnt_new_table();
381 if (!table)
382 return -ENOMEM;
383
384 r = mnt_table_parse_stream(table, proc_self_mountinfo, "/proc/self/mountinfo");
385 if (r < 0)
386 return r;
387
2c5ff8ea 388 fs = mnt_table_find_target(table, path, MNT_ITER_FORWARD);
0338df47
LP
389 if (!fs) {
390 if (laccess(path, F_OK) < 0) /* Hmm, it's not in the mount table, but does it exist at all? */
391 return -errno;
392
2c5ff8ea 393 return -EINVAL; /* Not a mount point we recognize */
0338df47 394 }
2c5ff8ea
LP
395
396 opts = mnt_fs_get_vfs_options(fs);
397 if (opts) {
398 r = mnt_optstr_get_flags(opts, &flags, mnt_get_builtin_optmap(MNT_LINUX_MAP));
399 if (r < 0)
400 log_debug_errno(r, "Could not get flags for '%s', ignoring: %m", path);
401 }
7cce68e1 402
2c5ff8ea 403 r = mount_nofollow(NULL, path, NULL, ((flags & ~flags_mask)|MS_BIND|MS_REMOUNT|new_flags) & ~MS_RELATIME, NULL);
b23c6a64
LP
404 if (r < 0) {
405 if (((flags ^ new_flags) & flags_mask & ~MS_RELATIME) != 0) /* Ignore MS_RELATIME again,
406 * since kernel adds it in
407 * everywhere, because it's the
408 * default. */
409 return r;
410
411 /* Let's handle redundant remounts gracefully */
412 log_debug_errno(r, "Failed to remount '%s' but flags already match what we want, ignoring: %m", path);
413 }
7cce68e1
LP
414
415 return 0;
416}
417
4349cd7c
LP
418int mount_move_root(const char *path) {
419 assert(path);
420
421 if (chdir(path) < 0)
422 return -errno;
423
424 if (mount(path, "/", NULL, MS_MOVE, NULL) < 0)
425 return -errno;
426
427 if (chroot(".") < 0)
428 return -errno;
429
430 if (chdir("/") < 0)
431 return -errno;
432
433 return 0;
434}
4e036b7a 435
3f2c0bec
LP
436int repeat_unmount(const char *path, int flags) {
437 bool done = false;
438
439 assert(path);
440
441 /* If there are multiple mounts on a mount point, this
442 * removes them all */
443
444 for (;;) {
445 if (umount2(path, flags) < 0) {
446
447 if (errno == EINVAL)
448 return done;
449
450 return -errno;
451 }
452
453 done = true;
454 }
455}
c4b41707 456
48b747fa
LP
457int mode_to_inaccessible_node(
458 const char *runtime_dir,
459 mode_t mode,
460 char **ret) {
461
462 /* This function maps a node type to a corresponding inaccessible file node. These nodes are created
463 * during early boot by PID 1. In some cases we lacked the privs to create the character and block
464 * devices (maybe because we run in an userns environment, or miss CAP_SYS_MKNOD, or run with a
465 * devices policy that excludes device nodes with major and minor of 0), but that's fine, in that
466 * case we use an AF_UNIX file node instead, which is not the same, but close enough for most
467 * uses. And most importantly, the kernel allows bind mounts from socket nodes to any non-directory
468 * file nodes, and that's the most important thing that matters.
469 *
470 * Note that the runtime directory argument shall be the top-level runtime directory, i.e. /run/ if
471 * we operate in system context and $XDG_RUNTIME_DIR if we operate in user context. */
472
e5f10caf
AZ
473 _cleanup_free_ char *d = NULL;
474 const char *node = NULL;
e5f10caf 475
48b747fa
LP
476 assert(ret);
477
478 if (!runtime_dir)
479 runtime_dir = "/run";
fe80fcc7 480
c4b41707
AP
481 switch(mode & S_IFMT) {
482 case S_IFREG:
48b747fa 483 node = "/systemd/inaccessible/reg";
e5f10caf 484 break;
fe80fcc7 485
c4b41707 486 case S_IFDIR:
48b747fa 487 node = "/systemd/inaccessible/dir";
e5f10caf 488 break;
fe80fcc7 489
c4b41707 490 case S_IFCHR:
48b747fa 491 node = "/systemd/inaccessible/chr";
e5f10caf 492 break;
fe80fcc7 493
c4b41707 494 case S_IFBLK:
48b747fa 495 node = "/systemd/inaccessible/blk";
e5f10caf 496 break;
fe80fcc7 497
c4b41707 498 case S_IFIFO:
48b747fa 499 node = "/systemd/inaccessible/fifo";
e5f10caf 500 break;
fe80fcc7 501
c4b41707 502 case S_IFSOCK:
48b747fa 503 node = "/systemd/inaccessible/sock";
e5f10caf 504 break;
c4b41707 505 }
e5f10caf
AZ
506 if (!node)
507 return -EINVAL;
508
48b747fa
LP
509 d = path_join(runtime_dir, node);
510 if (!d)
511 return -ENOMEM;
512
cbed1dc8
LP
513 /* On new kernels unprivileged users are permitted to create 0:0 char device nodes (because they also
514 * act as whiteout inode for overlayfs), but no other char or block device nodes. On old kernels no
515 * device node whatsoever may be created by unprivileged processes. Hence, if the caller asks for the
516 * inaccessible block device node let's see if the block device node actually exists, and if not,
517 * fall back to the character device node. From there fall back to the socket device node. This means
518 * in the best case we'll get the right device node type — but if not we'll hopefully at least get a
519 * device node at all. */
520
521 if (S_ISBLK(mode) &&
522 access(d, F_OK) < 0 && errno == ENOENT) {
523 free(d);
524 d = path_join(runtime_dir, "/systemd/inaccessible/chr");
525 if (!d)
526 return -ENOMEM;
527 }
528
529 if (IN_SET(mode & S_IFMT, S_IFBLK, S_IFCHR) &&
530 access(d, F_OK) < 0 && errno == ENOENT) {
48b747fa
LP
531 free(d);
532 d = path_join(runtime_dir, "/systemd/inaccessible/sock");
533 if (!d)
534 return -ENOMEM;
535 }
e5f10caf 536
48b747fa 537 *ret = TAKE_PTR(d);
e5f10caf 538 return 0;
c4b41707 539}
60e76d48 540
51bb6a10 541int mount_flags_to_string(long unsigned flags, char **ret) {
1c092b62
YW
542 static const struct {
543 long unsigned flag;
544 const char *name;
545 } map[] = {
546 { .flag = MS_RDONLY, .name = "MS_RDONLY", },
547 { .flag = MS_NOSUID, .name = "MS_NOSUID", },
548 { .flag = MS_NODEV, .name = "MS_NODEV", },
549 { .flag = MS_NOEXEC, .name = "MS_NOEXEC", },
550 { .flag = MS_SYNCHRONOUS, .name = "MS_SYNCHRONOUS", },
551 { .flag = MS_REMOUNT, .name = "MS_REMOUNT", },
552 { .flag = MS_MANDLOCK, .name = "MS_MANDLOCK", },
553 { .flag = MS_DIRSYNC, .name = "MS_DIRSYNC", },
554 { .flag = MS_NOSYMFOLLOW, .name = "MS_NOSYMFOLLOW", },
555 { .flag = MS_NOATIME, .name = "MS_NOATIME", },
556 { .flag = MS_NODIRATIME, .name = "MS_NODIRATIME", },
557 { .flag = MS_BIND, .name = "MS_BIND", },
558 { .flag = MS_MOVE, .name = "MS_MOVE", },
559 { .flag = MS_REC, .name = "MS_REC", },
560 { .flag = MS_SILENT, .name = "MS_SILENT", },
561 { .flag = MS_POSIXACL, .name = "MS_POSIXACL", },
562 { .flag = MS_UNBINDABLE, .name = "MS_UNBINDABLE", },
563 { .flag = MS_PRIVATE, .name = "MS_PRIVATE", },
564 { .flag = MS_SLAVE, .name = "MS_SLAVE", },
565 { .flag = MS_SHARED, .name = "MS_SHARED", },
566 { .flag = MS_RELATIME, .name = "MS_RELATIME", },
567 { .flag = MS_KERNMOUNT, .name = "MS_KERNMOUNT", },
568 { .flag = MS_I_VERSION, .name = "MS_I_VERSION", },
569 { .flag = MS_STRICTATIME, .name = "MS_STRICTATIME", },
570 { .flag = MS_LAZYTIME, .name = "MS_LAZYTIME", },
571 };
572 _cleanup_free_ char *str = NULL;
573
4bee2333
YW
574 assert(ret);
575
1c092b62
YW
576 for (size_t i = 0; i < ELEMENTSOF(map); i++)
577 if (flags & map[i].flag) {
578 if (!strextend_with_separator(&str, "|", map[i].name))
579 return -ENOMEM;
580 flags &= ~map[i].flag;
581 }
582
583 if (!str || flags != 0)
584 if (strextendf_with_separator(&str, "|", "%lx", flags) < 0)
585 return -ENOMEM;
586
587 *ret = TAKE_PTR(str);
588 return 0;
60e76d48
ZJS
589}
590
511a8cfe 591int mount_verbose_full(
60e76d48
ZJS
592 int error_log_level,
593 const char *what,
594 const char *where,
595 const char *type,
596 unsigned long flags,
511a8cfe
LP
597 const char *options,
598 bool follow_symlink) {
60e76d48 599
6ef8df2b
YW
600 _cleanup_free_ char *fl = NULL, *o = NULL;
601 unsigned long f;
602 int r;
603
604 r = mount_option_mangle(options, flags, &f, &o);
605 if (r < 0)
606 return log_full_errno(error_log_level, r,
607 "Failed to mangle mount options %s: %m",
608 strempty(options));
60e76d48 609
1c092b62 610 (void) mount_flags_to_string(f, &fl);
60e76d48 611
6ef8df2b 612 if ((f & MS_REMOUNT) && !what && !type)
60e76d48 613 log_debug("Remounting %s (%s \"%s\")...",
6ef8df2b 614 where, strnull(fl), strempty(o));
60e76d48
ZJS
615 else if (!what && !type)
616 log_debug("Mounting %s (%s \"%s\")...",
6ef8df2b
YW
617 where, strnull(fl), strempty(o));
618 else if ((f & MS_BIND) && !type)
60e76d48 619 log_debug("Bind-mounting %s on %s (%s \"%s\")...",
6ef8df2b
YW
620 what, where, strnull(fl), strempty(o));
621 else if (f & MS_MOVE)
afe682bc 622 log_debug("Moving mount %s → %s (%s \"%s\")...",
6ef8df2b 623 what, where, strnull(fl), strempty(o));
60e76d48 624 else
3b493d94
LP
625 log_debug("Mounting %s (%s) on %s (%s \"%s\")...",
626 strna(what), strna(type), where, strnull(fl), strempty(o));
511a8cfe
LP
627
628 if (follow_symlink)
629 r = mount(what, where, type, f, o) < 0 ? -errno : 0;
630 else
631 r = mount_nofollow(what, where, type, f, o);
632 if (r < 0)
633 return log_full_errno(error_log_level, r,
3ccf6126
LP
634 "Failed to mount %s (type %s) on %s (%s \"%s\"): %m",
635 strna(what), strna(type), where, strnull(fl), strempty(o));
60e76d48
ZJS
636 return 0;
637}
638
30f5d104
LP
639int umount_verbose(
640 int error_log_level,
641 const char *what,
642 int flags) {
643
644 assert(what);
645
60e76d48 646 log_debug("Umounting %s...", what);
30f5d104
LP
647
648 if (umount2(what, flags) < 0)
649 return log_full_errno(error_log_level, errno,
650 "Failed to unmount %s: %m", what);
651
60e76d48
ZJS
652 return 0;
653}
83555251 654
9e7f941a
YW
655int mount_option_mangle(
656 const char *options,
657 unsigned long mount_flags,
658 unsigned long *ret_mount_flags,
659 char **ret_remaining_options) {
660
661 const struct libmnt_optmap *map;
662 _cleanup_free_ char *ret = NULL;
9e7f941a
YW
663 int r;
664
665 /* This extracts mount flags from the mount options, and store
666 * non-mount-flag options to '*ret_remaining_options'.
667 * E.g.,
668 * "rw,nosuid,nodev,relatime,size=1630748k,mode=700,uid=1000,gid=1000"
669 * is split to MS_NOSUID|MS_NODEV|MS_RELATIME and
670 * "size=1630748k,mode=700,uid=1000,gid=1000".
671 * See more examples in test-mount-utils.c.
672 *
673 * Note that if 'options' does not contain any non-mount-flag options,
5238e957 674 * then '*ret_remaining_options' is set to NULL instead of empty string.
9e7f941a
YW
675 * Note that this does not check validity of options stored in
676 * '*ret_remaining_options'.
677 * Note that if 'options' is NULL, then this just copies 'mount_flags'
678 * to '*ret_mount_flags'. */
679
680 assert(ret_mount_flags);
681 assert(ret_remaining_options);
682
683 map = mnt_get_builtin_optmap(MNT_LINUX_MAP);
684 if (!map)
685 return -EINVAL;
686
25086b4c 687 for (const char *p = options;;) {
9e7f941a
YW
688 _cleanup_free_ char *word = NULL;
689 const struct libmnt_optmap *ent;
690
9b23679e 691 r = extract_first_word(&p, &word, ",", EXTRACT_KEEP_QUOTE);
9e7f941a
YW
692 if (r < 0)
693 return r;
694 if (r == 0)
695 break;
696
697 for (ent = map; ent->name; ent++) {
698 /* All entries in MNT_LINUX_MAP do not take any argument.
699 * Thus, ent->name does not contain "=" or "[=]". */
700 if (!streq(word, ent->name))
701 continue;
702
703 if (!(ent->mask & MNT_INVERT))
704 mount_flags |= ent->id;
705 else if (mount_flags & ent->id)
706 mount_flags ^= ent->id;
707
708 break;
709 }
710
711 /* If 'word' is not a mount flag, then store it in '*ret_remaining_options'. */
c2bc710b 712 if (!ent->name && !strextend_with_separator(&ret, ",", word))
9e7f941a
YW
713 return -ENOMEM;
714 }
715
716 *ret_mount_flags = mount_flags;
ae2a15bc 717 *ret_remaining_options = TAKE_PTR(ret);
9e7f941a
YW
718
719 return 0;
720}
6af52c3a 721
70599967 722static int mount_in_namespace(
6af52c3a
LB
723 pid_t target,
724 const char *propagate_path,
725 const char *incoming_path,
726 const char *src,
727 const char *dest,
728 bool read_only,
70599967
LB
729 bool make_file_or_directory,
730 const MountOptions *options,
731 bool is_image) {
6af52c3a
LB
732
733 _cleanup_close_pair_ int errno_pipe_fd[2] = { -1, -1 };
f7c18d3d
LB
734 _cleanup_close_ int self_mntns_fd = -1, mntns_fd = -1, root_fd = -1, pidns_fd = -1, chased_src_fd = -1;
735 char mount_slave[] = "/tmp/propagate.XXXXXX", *mount_tmp, *mount_outside, *p,
736 chased_src[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
6af52c3a
LB
737 bool mount_slave_created = false, mount_slave_mounted = false,
738 mount_tmp_created = false, mount_tmp_mounted = false,
739 mount_outside_created = false, mount_outside_mounted = false;
2338a175 740 struct stat st, self_mntns_st;
6af52c3a
LB
741 pid_t child;
742 int r;
743
744 assert(target > 0);
745 assert(propagate_path);
746 assert(incoming_path);
747 assert(src);
748 assert(dest);
70599967 749 assert(!options || is_image);
6af52c3a 750
98f654fd 751 r = namespace_open(target, &pidns_fd, &mntns_fd, NULL, NULL, &root_fd);
2338a175
LB
752 if (r < 0)
753 return log_debug_errno(r, "Failed to retrieve FDs of the target process' namespace: %m");
754
755 if (fstat(mntns_fd, &st) < 0)
756 return log_debug_errno(errno, "Failed to fstat mount namespace FD of target process: %m");
757
758 r = namespace_open(0, NULL, &self_mntns_fd, NULL, NULL, NULL);
759 if (r < 0)
760 return log_debug_errno(r, "Failed to retrieve FDs of systemd's namespace: %m");
761
762 if (fstat(self_mntns_fd, &self_mntns_st) < 0)
763 return log_debug_errno(errno, "Failed to fstat mount namespace FD of systemd: %m");
764
765 /* We can't add new mounts at runtime if the process wasn't started in a namespace */
766 if (st.st_ino == self_mntns_st.st_ino && st.st_dev == self_mntns_st.st_dev)
767 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to activate bind mount in target, not running in a mount namespace");
768
6af52c3a
LB
769 /* One day, when bind mounting /proc/self/fd/n works across
770 * namespace boundaries we should rework this logic to make
771 * use of it... */
772
773 p = strjoina(propagate_path, "/");
774 r = laccess(p, F_OK);
775 if (r < 0)
776 return log_debug_errno(r == -ENOENT ? SYNTHETIC_ERRNO(EOPNOTSUPP) : r, "Target does not allow propagation of mount points");
777
f7c18d3d 778 r = chase_symlinks(src, NULL, CHASE_TRAIL_SLASH, NULL, &chased_src_fd);
6af52c3a
LB
779 if (r < 0)
780 return log_debug_errno(r, "Failed to resolve source path of %s: %m", src);
f7c18d3d 781 xsprintf(chased_src, "/proc/self/fd/%i", chased_src_fd);
6af52c3a 782
f7c18d3d
LB
783 if (fstat(chased_src_fd, &st) < 0)
784 return log_debug_errno(errno, "Failed to stat() resolved source path %s: %m", src);
6af52c3a 785 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… */
f7c18d3d 786 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Source directory %s can't be a symbolic link", src);
6af52c3a
LB
787
788 /* Our goal is to install a new bind mount into the container,
789 possibly read-only. This is irritatingly complex
790 unfortunately, currently.
791
792 First, we start by creating a private playground in /tmp,
793 that we can mount MS_SLAVE. (Which is necessary, since
794 MS_MOVE cannot be applied to mounts with MS_SHARED parent
795 mounts.) */
796
797 if (!mkdtemp(mount_slave))
798 return log_debug_errno(errno, "Failed to create playground %s: %m", mount_slave);
799
800 mount_slave_created = true;
801
802 r = mount_nofollow_verbose(LOG_DEBUG, mount_slave, mount_slave, NULL, MS_BIND, NULL);
803 if (r < 0)
804 goto finish;
805
806 mount_slave_mounted = true;
807
808 r = mount_nofollow_verbose(LOG_DEBUG, NULL, mount_slave, NULL, MS_SLAVE, NULL);
809 if (r < 0)
810 goto finish;
811
812 /* Second, we mount the source file or directory to a directory inside of our MS_SLAVE playground. */
813 mount_tmp = strjoina(mount_slave, "/mount");
70599967
LB
814 if (is_image)
815 r = mkdir_p(mount_tmp, 0700);
816 else
817 r = make_mount_point_inode_from_stat(&st, mount_tmp, 0700);
6af52c3a
LB
818 if (r < 0) {
819 log_debug_errno(r, "Failed to create temporary mount point %s: %m", mount_tmp);
820 goto finish;
821 }
822
823 mount_tmp_created = true;
824
70599967 825 if (is_image)
93f59701 826 r = verity_dissect_and_mount(chased_src, mount_tmp, options, NULL, NULL, NULL);
70599967
LB
827 else
828 r = mount_follow_verbose(LOG_DEBUG, chased_src, mount_tmp, NULL, MS_BIND, NULL);
6af52c3a
LB
829 if (r < 0)
830 goto finish;
831
832 mount_tmp_mounted = true;
833
834 /* Third, we remount the new bind mount read-only if requested. */
835 if (read_only) {
836 r = mount_nofollow_verbose(LOG_DEBUG, NULL, mount_tmp, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL);
837 if (r < 0)
838 goto finish;
839 }
840
841 /* Fourth, we move the new bind mount into the propagation directory. This way it will appear there read-only
842 * right-away. */
843
844 mount_outside = strjoina(propagate_path, "/XXXXXX");
70599967 845 if (is_image || S_ISDIR(st.st_mode))
6af52c3a
LB
846 r = mkdtemp(mount_outside) ? 0 : -errno;
847 else {
848 r = mkostemp_safe(mount_outside);
849 safe_close(r);
850 }
851 if (r < 0) {
852 log_debug_errno(r, "Cannot create propagation file or directory %s: %m", mount_outside);
853 goto finish;
854 }
855
856 mount_outside_created = true;
857
858 r = mount_nofollow_verbose(LOG_DEBUG, mount_tmp, mount_outside, NULL, MS_MOVE, NULL);
859 if (r < 0)
860 goto finish;
861
862 mount_outside_mounted = true;
863 mount_tmp_mounted = false;
864
70599967 865 if (is_image || S_ISDIR(st.st_mode))
6af52c3a
LB
866 (void) rmdir(mount_tmp);
867 else
868 (void) unlink(mount_tmp);
869 mount_tmp_created = false;
870
871 (void) umount_verbose(LOG_DEBUG, mount_slave, UMOUNT_NOFOLLOW);
872 mount_slave_mounted = false;
873
874 (void) rmdir(mount_slave);
875 mount_slave_created = false;
876
877 if (pipe2(errno_pipe_fd, O_CLOEXEC|O_NONBLOCK) < 0) {
878 log_debug_errno(errno, "Failed to create pipe: %m");
879 goto finish;
880 }
881
2338a175 882 r = namespace_fork("(sd-bindmnt)", "(sd-bindmnt-inner)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG,
98f654fd 883 pidns_fd, mntns_fd, -1, -1, root_fd, &child);
6af52c3a
LB
884 if (r < 0)
885 goto finish;
886 if (r == 0) {
2338a175 887 const char *mount_inside;
6af52c3a
LB
888
889 errno_pipe_fd[0] = safe_close(errno_pipe_fd[0]);
890
6af52c3a 891 if (make_file_or_directory) {
70599967
LB
892 if (!is_image) {
893 (void) mkdir_parents(dest, 0755);
894 (void) make_mount_point_inode_from_stat(&st, dest, 0700);
895 } else
896 (void) mkdir_p(dest, 0755);
6af52c3a
LB
897 }
898
899 /* Fifth, move the mount to the right place inside */
900 mount_inside = strjoina(incoming_path, basename(mount_outside));
901 r = mount_nofollow_verbose(LOG_ERR, mount_inside, dest, NULL, MS_MOVE, NULL);
902 if (r < 0)
903 goto child_fail;
904
905 _exit(EXIT_SUCCESS);
906
907 child_fail:
908 (void) write(errno_pipe_fd[1], &r, sizeof(r));
909 errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
910
911 _exit(EXIT_FAILURE);
912 }
913
914 errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
915
916 r = wait_for_terminate_and_check("(sd-bindmnt)", child, 0);
917 if (r < 0) {
918 log_debug_errno(r, "Failed to wait for child: %m");
919 goto finish;
920 }
921 if (r != EXIT_SUCCESS) {
922 if (read(errno_pipe_fd[0], &r, sizeof(r)) == sizeof(r))
923 log_debug_errno(r, "Failed to mount: %m");
924 else
925 log_debug("Child failed.");
926 goto finish;
927 }
928
929finish:
930 if (mount_outside_mounted)
931 (void) umount_verbose(LOG_DEBUG, mount_outside, UMOUNT_NOFOLLOW);
932 if (mount_outside_created) {
70599967 933 if (is_image || S_ISDIR(st.st_mode))
6af52c3a
LB
934 (void) rmdir(mount_outside);
935 else
936 (void) unlink(mount_outside);
937 }
938
939 if (mount_tmp_mounted)
940 (void) umount_verbose(LOG_DEBUG, mount_tmp, UMOUNT_NOFOLLOW);
941 if (mount_tmp_created) {
70599967 942 if (is_image || S_ISDIR(st.st_mode))
6af52c3a
LB
943 (void) rmdir(mount_tmp);
944 else
945 (void) unlink(mount_tmp);
946 }
947
948 if (mount_slave_mounted)
949 (void) umount_verbose(LOG_DEBUG, mount_slave, UMOUNT_NOFOLLOW);
950 if (mount_slave_created)
951 (void) rmdir(mount_slave);
952
953 return r;
954}
70599967
LB
955
956int bind_mount_in_namespace(
957 pid_t target,
958 const char *propagate_path,
959 const char *incoming_path,
960 const char *src,
961 const char *dest,
962 bool read_only,
963 bool make_file_or_directory) {
964
965 return mount_in_namespace(target, propagate_path, incoming_path, src, dest, read_only, make_file_or_directory, NULL, false);
966}
967
968int mount_image_in_namespace(
969 pid_t target,
970 const char *propagate_path,
971 const char *incoming_path,
972 const char *src,
973 const char *dest,
974 bool read_only,
975 bool make_file_or_directory,
976 const MountOptions *options) {
977
978 return mount_in_namespace(target, propagate_path, incoming_path, src, dest, read_only, make_file_or_directory, options, true);
979}
14a25e1f
LP
980
981int make_mount_point(const char *path) {
982 int r;
983
984 assert(path);
985
986 /* If 'path' is already a mount point, does nothing and returns 0. If it is not it makes it one, and returns 1. */
987
988 r = path_is_mount_point(path, NULL, 0);
989 if (r < 0)
990 return log_debug_errno(r, "Failed to determine whether '%s' is a mount point: %m", path);
991 if (r > 0)
992 return 0;
993
994 r = mount_nofollow_verbose(LOG_DEBUG, path, path, NULL, MS_BIND|MS_REC, NULL);
995 if (r < 0)
996 return r;
997
998 return 1;
999}
35fd3558
LP
1000
1001static int make_userns(uid_t uid_shift, uid_t uid_range) {
1002 char uid_map[STRLEN("/proc//uid_map") + DECIMAL_STR_MAX(uid_t) + 1], line[DECIMAL_STR_MAX(uid_t)*3+3+1];
1003 _cleanup_(sigkill_waitp) pid_t pid = 0;
1004 _cleanup_close_ int userns_fd = -1;
1005 int r;
1006
1007 /* Allocates a userns file descriptor with the mapping we need. For this we'll fork off a child
1008 * process whose only purpose is to give us a new user namespace. It's killed when we got it. */
1009
1010 r = safe_fork("(sd-mkuserns)", FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_NEW_USERNS, &pid);
1011 if (r < 0)
1012 return r;
1013 if (r == 0) {
1014 /* Child. We do nothing here, just freeze until somebody kills us. */
1015 freeze();
1016 _exit(EXIT_FAILURE);
1017 }
1018
1019 xsprintf(line, UID_FMT " " UID_FMT " " UID_FMT "\n", 0, uid_shift, uid_range);
1020
1021 xsprintf(uid_map, "/proc/" PID_FMT "/uid_map", pid);
1022 r = write_string_file(uid_map, line, WRITE_STRING_FILE_DISABLE_BUFFER);
1023 if (r < 0)
1024 return log_error_errno(r, "Failed to write UID map: %m");
1025
1026 /* We always assign the same UID and GID ranges */
1027 xsprintf(uid_map, "/proc/" PID_FMT "/gid_map", pid);
1028 r = write_string_file(uid_map, line, WRITE_STRING_FILE_DISABLE_BUFFER);
1029 if (r < 0)
1030 return log_error_errno(r, "Failed to write GID map: %m");
1031
1032 r = namespace_open(pid, NULL, NULL, NULL, &userns_fd, NULL);
1033 if (r < 0)
1034 return r;
1035
1036 return TAKE_FD(userns_fd);
1037}
1038
1039int remount_idmap(
1040 const char *p,
1041 uid_t uid_shift,
1042 uid_t uid_range) {
1043
1044 _cleanup_close_ int mount_fd = -1, userns_fd = -1;
1045 int r;
1046
1047 assert(p);
1048
1049 if (!userns_shift_range_valid(uid_shift, uid_range))
1050 return -EINVAL;
1051
1052 /* Clone the mount point */
1053 mount_fd = open_tree(-1, p, OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);
1054 if (mount_fd < 0)
1055 return log_debug_errno(errno, "Failed to open tree of mounted filesystem '%s': %m", p);
1056
1057 /* Create a user namespace mapping */
1058 userns_fd = make_userns(uid_shift, uid_range);
1059 if (userns_fd < 0)
1060 return userns_fd;
1061
1062 /* Set the user namespace mapping attribute on the cloned mount point */
1063 if (mount_setattr(mount_fd, "", AT_EMPTY_PATH | AT_RECURSIVE,
1064 &(struct mount_attr) {
1065 .attr_set = MOUNT_ATTR_IDMAP,
1066 .userns_fd = userns_fd,
1067 }, sizeof(struct mount_attr)) < 0)
1068 return log_debug_errno(errno, "Failed to change bind mount attributes for '%s': %m", p);
1069
1070 /* Remove the old mount point */
1071 r = umount_verbose(LOG_DEBUG, p, UMOUNT_NOFOLLOW);
1072 if (r < 0)
1073 return r;
1074
1075 /* And place the cloned version in its place */
1076 if (move_mount(mount_fd, "", -1, p, MOVE_MOUNT_F_EMPTY_PATH) < 0)
1077 return log_debug_errno(errno, "Failed to attach UID mapped mount to '%s': %m", p);
1078
1079 return 0;
1080}
9c653536
ZJS
1081
1082int make_mount_point_inode_from_stat(const struct stat *st, const char *dest, mode_t mode) {
1083 assert(st);
1084 assert(dest);
1085
1086 if (S_ISDIR(st->st_mode))
1087 return mkdir_label(dest, mode);
1088 else
1089 return mknod(dest, S_IFREG|(mode & ~0111), 0);
1090}
1091
1092int make_mount_point_inode_from_path(const char *source, const char *dest, mode_t mode) {
1093 struct stat st;
1094
1095 assert(source);
1096 assert(dest);
1097
1098 if (stat(source, &st) < 0)
1099 return -errno;
1100
1101 return make_mount_point_inode_from_stat(&st, dest, mode);
1102}