]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/mount-util.c
dissect: split verity_dissect_and_mount helper out for reuse
[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>
4349cd7c 9
b5efdb8a 10#include "alloc-util.h"
9e7f941a 11#include "extract-word.h"
4349cd7c
LP
12#include "fd-util.h"
13#include "fileio.h"
e1873695 14#include "fs-util.h"
93cc7779 15#include "hashmap.h"
13dcfe46 16#include "libmount-util.h"
6af52c3a 17#include "mkdir.h"
4349cd7c 18#include "mount-util.h"
049af8ad 19#include "mountpoint-util.h"
2338a175 20#include "namespace-util.h"
4349cd7c
LP
21#include "parse-util.h"
22#include "path-util.h"
6af52c3a 23#include "process-util.h"
4349cd7c 24#include "set.h"
28126409 25#include "stat-util.h"
15a5e950 26#include "stdio-util.h"
4349cd7c 27#include "string-util.h"
6b7c9f8b 28#include "strv.h"
6af52c3a 29#include "tmpfile-util.h"
4349cd7c 30
28126409
LP
31int mount_fd(const char *source,
32 int target_fd,
33 const char *filesystemtype,
34 unsigned long mountflags,
35 const void *data) {
36
37 char path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
38
39 xsprintf(path, "/proc/self/fd/%i", target_fd);
40 if (mount(source, path, filesystemtype, mountflags, data) < 0) {
41 if (errno != ENOENT)
42 return -errno;
43
44 /* ENOENT can mean two things: either that the source is missing, or that /proc/ isn't
45 * mounted. Check for the latter to generate better error messages. */
46 if (proc_mounted() == 0)
47 return -ENOSYS;
48
49 return -ENOENT;
50 }
51
52 return 0;
53}
54
55int mount_nofollow(
56 const char *source,
57 const char *target,
58 const char *filesystemtype,
59 unsigned long mountflags,
60 const void *data) {
61
62 _cleanup_close_ int fd = -1;
63
64 /* In almost all cases we want to manipulate the mount table without following symlinks, hence
65 * mount_nofollow() is usually the way to go. The only exceptions are environments where /proc/ is
66 * not available yet, since we need /proc/self/fd/ for this logic to work. i.e. during the early
67 * initialization of namespacing/container stuff where /proc is not yet mounted (and maybe even the
68 * fs to mount) we can only use traditional mount() directly.
69 *
70 * Note that this disables following only for the final component of the target, i.e symlinks within
71 * the path of the target are honoured, as are symlinks in the source path everywhere. */
72
73 fd = open(target, O_PATH|O_CLOEXEC|O_NOFOLLOW);
74 if (fd < 0)
75 return -errno;
76
77 return mount_fd(source, fd, filesystemtype, mountflags, data);
78}
79
4349cd7c 80int umount_recursive(const char *prefix, int flags) {
4349cd7c 81 int n = 0, r;
f8b1904f 82 bool again;
4349cd7c
LP
83
84 /* Try to umount everything recursively below a
85 * directory. Also, take care of stacked mounts, and keep
86 * unmounting them until they are gone. */
87
88 do {
13dcfe46
ZJS
89 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
90 _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
4349cd7c
LP
91
92 again = false;
4349cd7c 93
2f2d81d9 94 r = libmount_parse("/proc/self/mountinfo", NULL, &table, &iter);
fdeea3f4 95 if (r < 0)
13dcfe46 96 return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
35bbbf85 97
4349cd7c 98 for (;;) {
13dcfe46
ZJS
99 struct libmnt_fs *fs;
100 const char *path;
4349cd7c 101
13dcfe46
ZJS
102 r = mnt_table_next_fs(table, iter, &fs);
103 if (r == 1)
104 break;
105 if (r < 0)
106 return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
4349cd7c 107
13dcfe46
ZJS
108 path = mnt_fs_get_target(fs);
109 if (!path)
110 continue;
4349cd7c 111
13dcfe46 112 if (!path_startswith(path, prefix))
4349cd7c
LP
113 continue;
114
827ea521
LP
115 if (umount2(path, flags | UMOUNT_NOFOLLOW) < 0) {
116 log_debug_errno(errno, "Failed to umount %s, ignoring: %m", path);
4349cd7c
LP
117 continue;
118 }
119
13dcfe46 120 log_debug("Successfully unmounted %s", path);
6b7c9f8b 121
4349cd7c
LP
122 again = true;
123 n++;
124
125 break;
126 }
4349cd7c
LP
127 } while (again);
128
13dcfe46 129 return n;
4349cd7c
LP
130}
131
08b1f5c7
LP
132static int get_mount_flags(
133 struct libmnt_table *table,
134 const char *path,
135 unsigned long *ret) {
5012d567
LP
136
137 _cleanup_close_ int fd = -1;
08b1f5c7
LP
138 struct libmnt_fs *fs;
139 struct statvfs buf;
140 const char *opts;
5012d567 141 int r;
d34a4008 142
08b1f5c7
LP
143 /* Get the mount flags for the mountpoint at "path" from "table". We have a fallback using statvfs()
144 * in place (which provides us with mostly the same info), but it's just a fallback, since using it
5012d567
LP
145 * means triggering autofs or NFS mounts, which we'd rather avoid needlessly.
146 *
147 * This generally doesn't follow symlinks. */
08b1f5c7 148
d34a4008 149 fs = mnt_table_find_target(table, path, MNT_ITER_FORWARD);
38288f0b 150 if (!fs) {
08b1f5c7 151 log_debug("Could not find '%s' in mount table, ignoring.", path);
d34a4008
JU
152 goto fallback;
153 }
154
155 opts = mnt_fs_get_vfs_options(fs);
08b1f5c7
LP
156 if (!opts) {
157 *ret = 0;
158 return 0;
159 }
160
161 r = mnt_optstr_get_flags(opts, ret, mnt_get_builtin_optmap(MNT_LINUX_MAP));
d34a4008 162 if (r != 0) {
08b1f5c7 163 log_debug_errno(r, "Could not get flags for '%s', ignoring: %m", path);
d34a4008
JU
164 goto fallback;
165 }
4349cd7c 166
08b1f5c7
LP
167 /* MS_RELATIME is default and trying to set it in an unprivileged container causes EPERM */
168 *ret &= ~MS_RELATIME;
d34a4008
JU
169 return 0;
170
171fallback:
5012d567
LP
172 fd = open(path, O_PATH|O_CLOEXEC|O_NOFOLLOW);
173 if (fd < 0)
174 return -errno;
175
176 if (fstatvfs(fd, &buf) < 0)
4349cd7c 177 return -errno;
d34a4008 178
08b1f5c7
LP
179 /* The statvfs() flags and the mount flags mostly have the same values, but for some cases do
180 * not. Hence map the flags manually. (Strictly speaking, ST_RELATIME/MS_RELATIME is the most
181 * prominent one that doesn't match, but that's the one we mask away anyway, see above.) */
182
183 *ret =
184 FLAGS_SET(buf.f_flag, ST_RDONLY) * MS_RDONLY |
185 FLAGS_SET(buf.f_flag, ST_NODEV) * MS_NODEV |
186 FLAGS_SET(buf.f_flag, ST_NOEXEC) * MS_NOEXEC |
187 FLAGS_SET(buf.f_flag, ST_NOSUID) * MS_NOSUID |
188 FLAGS_SET(buf.f_flag, ST_NOATIME) * MS_NOATIME |
189 FLAGS_SET(buf.f_flag, ST_NODIRATIME) * MS_NODIRATIME;
190
4349cd7c
LP
191 return 0;
192}
193
be3f3752 194/* Use this function only if you do not have direct access to /proc/self/mountinfo but the caller can open it
64e82c19
LP
195 * for you. This is the case when /proc is masked or not mounted. Otherwise, use bind_remount_recursive. */
196int bind_remount_recursive_with_mountinfo(
197 const char *prefix,
198 unsigned long new_flags,
199 unsigned long flags_mask,
6b000af4 200 char **deny_list,
64e82c19
LP
201 FILE *proc_self_mountinfo) {
202
4349cd7c 203 _cleanup_set_free_free_ Set *done = NULL;
f3dab34d 204 _cleanup_free_ char *simplified = NULL;
4349cd7c
LP
205 int r;
206
8403219f 207 assert(prefix);
ac9de0b3
TR
208 assert(proc_self_mountinfo);
209
6b7c9f8b
LP
210 /* Recursively remount a directory (and all its submounts) read-only or read-write. If the directory is already
211 * mounted, we reuse the mount and simply mark it MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
212 * operation). If it isn't we first make it one. Afterwards we apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to
213 * all submounts we can access, too. When mounts are stacked on the same mount point we only care for each
214 * individual "top-level" mount on each point, as we cannot influence/access the underlying mounts anyway. We
86b52a39 215 * do not have any effect on future submounts that might get propagated, they might be writable. This includes
6b7c9f8b
LP
216 * future submounts that have been triggered via autofs.
217 *
6b000af4
LP
218 * If the "deny_list" parameter is specified it may contain a list of subtrees to exclude from the
219 * remount operation. Note that we'll ignore the deny list for the top-level path. */
4349cd7c 220
f3dab34d
LP
221 simplified = strdup(prefix);
222 if (!simplified)
4349cd7c
LP
223 return -ENOMEM;
224
f3dab34d 225 path_simplify(simplified, false);
4349cd7c 226
548f6937 227 done = set_new(&path_hash_ops);
4349cd7c
LP
228 if (!done)
229 return -ENOMEM;
230
231 for (;;) {
4349cd7c 232 _cleanup_set_free_free_ Set *todo = NULL;
13dcfe46
ZJS
233 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
234 _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
4349cd7c
LP
235 bool top_autofs = false;
236 char *x;
237 unsigned long orig_flags;
238
548f6937 239 todo = set_new(&path_hash_ops);
4349cd7c
LP
240 if (!todo)
241 return -ENOMEM;
242
ac9de0b3 243 rewind(proc_self_mountinfo);
4349cd7c 244
e2857b3d 245 r = libmount_parse("/proc/self/mountinfo", proc_self_mountinfo, &table, &iter);
13dcfe46
ZJS
246 if (r < 0)
247 return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
4349cd7c 248
13dcfe46
ZJS
249 for (;;) {
250 struct libmnt_fs *fs;
251 const char *path, *type;
4349cd7c 252
13dcfe46
ZJS
253 r = mnt_table_next_fs(table, iter, &fs);
254 if (r == 1)
255 break;
4349cd7c 256 if (r < 0)
13dcfe46 257 return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
4349cd7c 258
13dcfe46
ZJS
259 path = mnt_fs_get_target(fs);
260 type = mnt_fs_get_fstype(fs);
261 if (!path || !type)
6b7c9f8b
LP
262 continue;
263
f3dab34d 264 if (!path_startswith(path, simplified))
13dcfe46
ZJS
265 continue;
266
6b000af4 267 /* Ignore this mount if it is deny-listed, but only if it isn't the top-level mount
13dcfe46 268 * we shall operate on. */
f3dab34d 269 if (!path_equal(path, simplified)) {
6b000af4 270 bool deny_listed = false;
6b7c9f8b
LP
271 char **i;
272
6b000af4 273 STRV_FOREACH(i, deny_list) {
f3dab34d 274 if (path_equal(*i, simplified))
6b7c9f8b
LP
275 continue;
276
f3dab34d 277 if (!path_startswith(*i, simplified))
6b7c9f8b
LP
278 continue;
279
13dcfe46 280 if (path_startswith(path, *i)) {
6b000af4
LP
281 deny_listed = true;
282 log_debug("Not remounting %s deny-listed by %s, called for %s",
f3dab34d 283 path, *i, simplified);
6b7c9f8b
LP
284 break;
285 }
286 }
6b000af4 287 if (deny_listed)
6b7c9f8b
LP
288 continue;
289 }
290
4349cd7c
LP
291 /* Let's ignore autofs mounts. If they aren't
292 * triggered yet, we want to avoid triggering
293 * them, as we don't make any guarantees for
294 * future submounts anyway. If they are
295 * already triggered, then we will find
296 * another entry for this. */
297 if (streq(type, "autofs")) {
f3dab34d 298 top_autofs = top_autofs || path_equal(path, simplified);
4349cd7c
LP
299 continue;
300 }
301
13dcfe46 302 if (!set_contains(done, path)) {
be327321 303 r = set_put_strdup(&todo, path);
4349cd7c
LP
304 if (r < 0)
305 return r;
306 }
307 }
308
309 /* If we have no submounts to process anymore and if
310 * the root is either already done, or an autofs, we
311 * are done */
312 if (set_isempty(todo) &&
f3dab34d 313 (top_autofs || set_contains(done, simplified)))
4349cd7c
LP
314 return 0;
315
f3dab34d
LP
316 if (!set_contains(done, simplified) &&
317 !set_contains(todo, simplified)) {
6b7c9f8b 318 /* The prefix directory itself is not yet a mount, make it one. */
511a8cfe
LP
319 r = mount_nofollow(simplified, simplified, NULL, MS_BIND|MS_REC, NULL);
320 if (r < 0)
321 return r;
4349cd7c
LP
322
323 orig_flags = 0;
08b1f5c7 324 (void) get_mount_flags(table, simplified, &orig_flags);
4349cd7c 325
511a8cfe
LP
326 r = mount_nofollow(NULL, simplified, NULL, (orig_flags & ~flags_mask)|MS_BIND|MS_REMOUNT|new_flags, NULL);
327 if (r < 0)
328 return r;
4349cd7c 329
6b7c9f8b
LP
330 log_debug("Made top-level directory %s a mount point.", prefix);
331
be327321 332 r = set_put_strdup(&done, simplified);
4349cd7c
LP
333 if (r < 0)
334 return r;
335 }
336
337 while ((x = set_steal_first(todo))) {
338
339 r = set_consume(done, x);
4c701096 340 if (IN_SET(r, 0, -EEXIST))
4349cd7c
LP
341 continue;
342 if (r < 0)
343 return r;
344
6b7c9f8b 345 /* Deal with mount points that are obstructed by a later mount */
e1873695 346 r = path_is_mount_point(x, NULL, 0);
4c701096 347 if (IN_SET(r, 0, -ENOENT))
98df8089 348 continue;
065b4774
LP
349 if (r < 0) {
350 if (!ERRNO_IS_PRIVILEGE(r))
351 return r;
352
53c442ef
YW
353 /* Even if root user invoke this, submounts under private FUSE or NFS mount points
354 * may not be acceessed. E.g.,
355 *
356 * $ bindfs --no-allow-other ~/mnt/mnt ~/mnt/mnt
357 * $ bindfs --no-allow-other ~/mnt ~/mnt
358 *
359 * Then, root user cannot access the mount point ~/mnt/mnt.
360 * In such cases, the submounts are ignored, as we have no way to manage them. */
ef454fd1
YW
361 log_debug_errno(r, "Failed to determine '%s' is mount point or not, ignoring: %m", x);
362 continue;
363 }
98df8089
AC
364
365 /* Try to reuse the original flag set */
4349cd7c 366 orig_flags = 0;
08b1f5c7 367 (void) get_mount_flags(table, x, &orig_flags);
4349cd7c 368
511a8cfe
LP
369 r = mount_nofollow(NULL, x, NULL, (orig_flags & ~flags_mask)|MS_BIND|MS_REMOUNT|new_flags, NULL);
370 if (r < 0)
371 return r;
4349cd7c 372
6b7c9f8b 373 log_debug("Remounted %s read-only.", x);
4349cd7c
LP
374 }
375 }
376}
377
8403219f
LP
378int bind_remount_recursive(
379 const char *prefix,
380 unsigned long new_flags,
381 unsigned long flags_mask,
6b000af4 382 char **deny_list) {
8403219f 383
ac9de0b3 384 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
fdeea3f4 385 int r;
ac9de0b3 386
fdeea3f4
ZJS
387 r = fopen_unlocked("/proc/self/mountinfo", "re", &proc_self_mountinfo);
388 if (r < 0)
389 return r;
35bbbf85 390
6b000af4 391 return bind_remount_recursive_with_mountinfo(prefix, new_flags, flags_mask, deny_list, proc_self_mountinfo);
ac9de0b3
TR
392}
393
7cce68e1
LP
394int bind_remount_one_with_mountinfo(
395 const char *path,
396 unsigned long new_flags,
397 unsigned long flags_mask,
398 FILE *proc_self_mountinfo) {
399
400 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
401 unsigned long orig_flags = 0;
402 int r;
403
404 assert(path);
405 assert(proc_self_mountinfo);
406
407 rewind(proc_self_mountinfo);
408
409 table = mnt_new_table();
410 if (!table)
411 return -ENOMEM;
412
413 r = mnt_table_parse_stream(table, proc_self_mountinfo, "/proc/self/mountinfo");
414 if (r < 0)
415 return r;
416
417 /* Try to reuse the original flag set */
418 (void) get_mount_flags(table, path, &orig_flags);
419
511a8cfe
LP
420 r = mount_nofollow(NULL, path, NULL, (orig_flags & ~flags_mask)|MS_BIND|MS_REMOUNT|new_flags, NULL);
421 if (r < 0)
422 return r;
7cce68e1
LP
423
424 return 0;
425}
426
4349cd7c
LP
427int mount_move_root(const char *path) {
428 assert(path);
429
430 if (chdir(path) < 0)
431 return -errno;
432
433 if (mount(path, "/", NULL, MS_MOVE, NULL) < 0)
434 return -errno;
435
436 if (chroot(".") < 0)
437 return -errno;
438
439 if (chdir("/") < 0)
440 return -errno;
441
442 return 0;
443}
4e036b7a 444
3f2c0bec
LP
445int repeat_unmount(const char *path, int flags) {
446 bool done = false;
447
448 assert(path);
449
450 /* If there are multiple mounts on a mount point, this
451 * removes them all */
452
453 for (;;) {
454 if (umount2(path, flags) < 0) {
455
456 if (errno == EINVAL)
457 return done;
458
459 return -errno;
460 }
461
462 done = true;
463 }
464}
c4b41707 465
48b747fa
LP
466int mode_to_inaccessible_node(
467 const char *runtime_dir,
468 mode_t mode,
469 char **ret) {
470
471 /* This function maps a node type to a corresponding inaccessible file node. These nodes are created
472 * during early boot by PID 1. In some cases we lacked the privs to create the character and block
473 * devices (maybe because we run in an userns environment, or miss CAP_SYS_MKNOD, or run with a
474 * devices policy that excludes device nodes with major and minor of 0), but that's fine, in that
475 * case we use an AF_UNIX file node instead, which is not the same, but close enough for most
476 * uses. And most importantly, the kernel allows bind mounts from socket nodes to any non-directory
477 * file nodes, and that's the most important thing that matters.
478 *
479 * Note that the runtime directory argument shall be the top-level runtime directory, i.e. /run/ if
480 * we operate in system context and $XDG_RUNTIME_DIR if we operate in user context. */
481
e5f10caf
AZ
482 _cleanup_free_ char *d = NULL;
483 const char *node = NULL;
e5f10caf 484
48b747fa
LP
485 assert(ret);
486
487 if (!runtime_dir)
488 runtime_dir = "/run";
fe80fcc7 489
c4b41707
AP
490 switch(mode & S_IFMT) {
491 case S_IFREG:
48b747fa 492 node = "/systemd/inaccessible/reg";
e5f10caf 493 break;
fe80fcc7 494
c4b41707 495 case S_IFDIR:
48b747fa 496 node = "/systemd/inaccessible/dir";
e5f10caf 497 break;
fe80fcc7 498
c4b41707 499 case S_IFCHR:
48b747fa 500 node = "/systemd/inaccessible/chr";
e5f10caf 501 break;
fe80fcc7 502
c4b41707 503 case S_IFBLK:
48b747fa 504 node = "/systemd/inaccessible/blk";
e5f10caf 505 break;
fe80fcc7 506
c4b41707 507 case S_IFIFO:
48b747fa 508 node = "/systemd/inaccessible/fifo";
e5f10caf 509 break;
fe80fcc7 510
c4b41707 511 case S_IFSOCK:
48b747fa 512 node = "/systemd/inaccessible/sock";
e5f10caf 513 break;
c4b41707 514 }
e5f10caf
AZ
515 if (!node)
516 return -EINVAL;
517
48b747fa
LP
518 d = path_join(runtime_dir, node);
519 if (!d)
520 return -ENOMEM;
521
cbed1dc8
LP
522 /* On new kernels unprivileged users are permitted to create 0:0 char device nodes (because they also
523 * act as whiteout inode for overlayfs), but no other char or block device nodes. On old kernels no
524 * device node whatsoever may be created by unprivileged processes. Hence, if the caller asks for the
525 * inaccessible block device node let's see if the block device node actually exists, and if not,
526 * fall back to the character device node. From there fall back to the socket device node. This means
527 * in the best case we'll get the right device node type — but if not we'll hopefully at least get a
528 * device node at all. */
529
530 if (S_ISBLK(mode) &&
531 access(d, F_OK) < 0 && errno == ENOENT) {
532 free(d);
533 d = path_join(runtime_dir, "/systemd/inaccessible/chr");
534 if (!d)
535 return -ENOMEM;
536 }
537
538 if (IN_SET(mode & S_IFMT, S_IFBLK, S_IFCHR) &&
539 access(d, F_OK) < 0 && errno == ENOENT) {
48b747fa
LP
540 free(d);
541 d = path_join(runtime_dir, "/systemd/inaccessible/sock");
542 if (!d)
543 return -ENOMEM;
544 }
e5f10caf 545
48b747fa 546 *ret = TAKE_PTR(d);
e5f10caf 547 return 0;
c4b41707 548}
60e76d48
ZJS
549
550#define FLAG(name) (flags & name ? STRINGIFY(name) "|" : "")
551static char* mount_flags_to_string(long unsigned flags) {
552 char *x;
553 _cleanup_free_ char *y = NULL;
554 long unsigned overflow;
555
556 overflow = flags & ~(MS_RDONLY |
557 MS_NOSUID |
558 MS_NODEV |
559 MS_NOEXEC |
560 MS_SYNCHRONOUS |
561 MS_REMOUNT |
562 MS_MANDLOCK |
563 MS_DIRSYNC |
564 MS_NOATIME |
565 MS_NODIRATIME |
566 MS_BIND |
567 MS_MOVE |
568 MS_REC |
569 MS_SILENT |
570 MS_POSIXACL |
571 MS_UNBINDABLE |
572 MS_PRIVATE |
573 MS_SLAVE |
574 MS_SHARED |
575 MS_RELATIME |
576 MS_KERNMOUNT |
577 MS_I_VERSION |
578 MS_STRICTATIME |
579 MS_LAZYTIME);
580
581 if (flags == 0 || overflow != 0)
582 if (asprintf(&y, "%lx", overflow) < 0)
583 return NULL;
584
585 x = strjoin(FLAG(MS_RDONLY),
586 FLAG(MS_NOSUID),
587 FLAG(MS_NODEV),
588 FLAG(MS_NOEXEC),
589 FLAG(MS_SYNCHRONOUS),
590 FLAG(MS_REMOUNT),
591 FLAG(MS_MANDLOCK),
592 FLAG(MS_DIRSYNC),
593 FLAG(MS_NOATIME),
594 FLAG(MS_NODIRATIME),
595 FLAG(MS_BIND),
596 FLAG(MS_MOVE),
597 FLAG(MS_REC),
598 FLAG(MS_SILENT),
599 FLAG(MS_POSIXACL),
600 FLAG(MS_UNBINDABLE),
601 FLAG(MS_PRIVATE),
602 FLAG(MS_SLAVE),
603 FLAG(MS_SHARED),
604 FLAG(MS_RELATIME),
605 FLAG(MS_KERNMOUNT),
606 FLAG(MS_I_VERSION),
607 FLAG(MS_STRICTATIME),
608 FLAG(MS_LAZYTIME),
605405c6 609 y);
60e76d48
ZJS
610 if (!x)
611 return NULL;
612 if (!y)
613 x[strlen(x) - 1] = '\0'; /* truncate the last | */
614 return x;
615}
616
511a8cfe 617int mount_verbose_full(
60e76d48
ZJS
618 int error_log_level,
619 const char *what,
620 const char *where,
621 const char *type,
622 unsigned long flags,
511a8cfe
LP
623 const char *options,
624 bool follow_symlink) {
60e76d48 625
6ef8df2b
YW
626 _cleanup_free_ char *fl = NULL, *o = NULL;
627 unsigned long f;
628 int r;
629
630 r = mount_option_mangle(options, flags, &f, &o);
631 if (r < 0)
632 return log_full_errno(error_log_level, r,
633 "Failed to mangle mount options %s: %m",
634 strempty(options));
60e76d48 635
6ef8df2b 636 fl = mount_flags_to_string(f);
60e76d48 637
6ef8df2b 638 if ((f & MS_REMOUNT) && !what && !type)
60e76d48 639 log_debug("Remounting %s (%s \"%s\")...",
6ef8df2b 640 where, strnull(fl), strempty(o));
60e76d48
ZJS
641 else if (!what && !type)
642 log_debug("Mounting %s (%s \"%s\")...",
6ef8df2b
YW
643 where, strnull(fl), strempty(o));
644 else if ((f & MS_BIND) && !type)
60e76d48 645 log_debug("Bind-mounting %s on %s (%s \"%s\")...",
6ef8df2b
YW
646 what, where, strnull(fl), strempty(o));
647 else if (f & MS_MOVE)
afe682bc 648 log_debug("Moving mount %s → %s (%s \"%s\")...",
6ef8df2b 649 what, where, strnull(fl), strempty(o));
60e76d48 650 else
3b493d94
LP
651 log_debug("Mounting %s (%s) on %s (%s \"%s\")...",
652 strna(what), strna(type), where, strnull(fl), strempty(o));
511a8cfe
LP
653
654 if (follow_symlink)
655 r = mount(what, where, type, f, o) < 0 ? -errno : 0;
656 else
657 r = mount_nofollow(what, where, type, f, o);
658 if (r < 0)
659 return log_full_errno(error_log_level, r,
3ccf6126
LP
660 "Failed to mount %s (type %s) on %s (%s \"%s\"): %m",
661 strna(what), strna(type), where, strnull(fl), strempty(o));
60e76d48
ZJS
662 return 0;
663}
664
30f5d104
LP
665int umount_verbose(
666 int error_log_level,
667 const char *what,
668 int flags) {
669
670 assert(what);
671
60e76d48 672 log_debug("Umounting %s...", what);
30f5d104
LP
673
674 if (umount2(what, flags) < 0)
675 return log_full_errno(error_log_level, errno,
676 "Failed to unmount %s: %m", what);
677
60e76d48
ZJS
678 return 0;
679}
83555251 680
9e7f941a
YW
681int mount_option_mangle(
682 const char *options,
683 unsigned long mount_flags,
684 unsigned long *ret_mount_flags,
685 char **ret_remaining_options) {
686
687 const struct libmnt_optmap *map;
688 _cleanup_free_ char *ret = NULL;
689 const char *p;
690 int r;
691
692 /* This extracts mount flags from the mount options, and store
693 * non-mount-flag options to '*ret_remaining_options'.
694 * E.g.,
695 * "rw,nosuid,nodev,relatime,size=1630748k,mode=700,uid=1000,gid=1000"
696 * is split to MS_NOSUID|MS_NODEV|MS_RELATIME and
697 * "size=1630748k,mode=700,uid=1000,gid=1000".
698 * See more examples in test-mount-utils.c.
699 *
700 * Note that if 'options' does not contain any non-mount-flag options,
5238e957 701 * then '*ret_remaining_options' is set to NULL instead of empty string.
9e7f941a
YW
702 * Note that this does not check validity of options stored in
703 * '*ret_remaining_options'.
704 * Note that if 'options' is NULL, then this just copies 'mount_flags'
705 * to '*ret_mount_flags'. */
706
707 assert(ret_mount_flags);
708 assert(ret_remaining_options);
709
710 map = mnt_get_builtin_optmap(MNT_LINUX_MAP);
711 if (!map)
712 return -EINVAL;
713
714 p = options;
715 for (;;) {
716 _cleanup_free_ char *word = NULL;
717 const struct libmnt_optmap *ent;
718
4ec85141 719 r = extract_first_word(&p, &word, ",", EXTRACT_UNQUOTE);
9e7f941a
YW
720 if (r < 0)
721 return r;
722 if (r == 0)
723 break;
724
725 for (ent = map; ent->name; ent++) {
726 /* All entries in MNT_LINUX_MAP do not take any argument.
727 * Thus, ent->name does not contain "=" or "[=]". */
728 if (!streq(word, ent->name))
729 continue;
730
731 if (!(ent->mask & MNT_INVERT))
732 mount_flags |= ent->id;
733 else if (mount_flags & ent->id)
734 mount_flags ^= ent->id;
735
736 break;
737 }
738
739 /* If 'word' is not a mount flag, then store it in '*ret_remaining_options'. */
c2bc710b 740 if (!ent->name && !strextend_with_separator(&ret, ",", word))
9e7f941a
YW
741 return -ENOMEM;
742 }
743
744 *ret_mount_flags = mount_flags;
ae2a15bc 745 *ret_remaining_options = TAKE_PTR(ret);
9e7f941a
YW
746
747 return 0;
748}
6af52c3a
LB
749
750int bind_mount_in_namespace(
751 pid_t target,
752 const char *propagate_path,
753 const char *incoming_path,
754 const char *src,
755 const char *dest,
756 bool read_only,
757 bool make_file_or_directory) {
758
759 _cleanup_close_pair_ int errno_pipe_fd[2] = { -1, -1 };
f7c18d3d
LB
760 _cleanup_close_ int self_mntns_fd = -1, mntns_fd = -1, root_fd = -1, pidns_fd = -1, chased_src_fd = -1;
761 char mount_slave[] = "/tmp/propagate.XXXXXX", *mount_tmp, *mount_outside, *p,
762 chased_src[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
6af52c3a
LB
763 bool mount_slave_created = false, mount_slave_mounted = false,
764 mount_tmp_created = false, mount_tmp_mounted = false,
765 mount_outside_created = false, mount_outside_mounted = false;
2338a175 766 struct stat st, self_mntns_st;
6af52c3a
LB
767 pid_t child;
768 int r;
769
770 assert(target > 0);
771 assert(propagate_path);
772 assert(incoming_path);
773 assert(src);
774 assert(dest);
775
98f654fd 776 r = namespace_open(target, &pidns_fd, &mntns_fd, NULL, NULL, &root_fd);
2338a175
LB
777 if (r < 0)
778 return log_debug_errno(r, "Failed to retrieve FDs of the target process' namespace: %m");
779
780 if (fstat(mntns_fd, &st) < 0)
781 return log_debug_errno(errno, "Failed to fstat mount namespace FD of target process: %m");
782
783 r = namespace_open(0, NULL, &self_mntns_fd, NULL, NULL, NULL);
784 if (r < 0)
785 return log_debug_errno(r, "Failed to retrieve FDs of systemd's namespace: %m");
786
787 if (fstat(self_mntns_fd, &self_mntns_st) < 0)
788 return log_debug_errno(errno, "Failed to fstat mount namespace FD of systemd: %m");
789
790 /* We can't add new mounts at runtime if the process wasn't started in a namespace */
791 if (st.st_ino == self_mntns_st.st_ino && st.st_dev == self_mntns_st.st_dev)
792 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to activate bind mount in target, not running in a mount namespace");
793
6af52c3a
LB
794 /* One day, when bind mounting /proc/self/fd/n works across
795 * namespace boundaries we should rework this logic to make
796 * use of it... */
797
798 p = strjoina(propagate_path, "/");
799 r = laccess(p, F_OK);
800 if (r < 0)
801 return log_debug_errno(r == -ENOENT ? SYNTHETIC_ERRNO(EOPNOTSUPP) : r, "Target does not allow propagation of mount points");
802
f7c18d3d 803 r = chase_symlinks(src, NULL, CHASE_TRAIL_SLASH, NULL, &chased_src_fd);
6af52c3a
LB
804 if (r < 0)
805 return log_debug_errno(r, "Failed to resolve source path of %s: %m", src);
f7c18d3d 806 xsprintf(chased_src, "/proc/self/fd/%i", chased_src_fd);
6af52c3a 807
f7c18d3d
LB
808 if (fstat(chased_src_fd, &st) < 0)
809 return log_debug_errno(errno, "Failed to stat() resolved source path %s: %m", src);
6af52c3a 810 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 811 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Source directory %s can't be a symbolic link", src);
6af52c3a
LB
812
813 /* Our goal is to install a new bind mount into the container,
814 possibly read-only. This is irritatingly complex
815 unfortunately, currently.
816
817 First, we start by creating a private playground in /tmp,
818 that we can mount MS_SLAVE. (Which is necessary, since
819 MS_MOVE cannot be applied to mounts with MS_SHARED parent
820 mounts.) */
821
822 if (!mkdtemp(mount_slave))
823 return log_debug_errno(errno, "Failed to create playground %s: %m", mount_slave);
824
825 mount_slave_created = true;
826
827 r = mount_nofollow_verbose(LOG_DEBUG, mount_slave, mount_slave, NULL, MS_BIND, NULL);
828 if (r < 0)
829 goto finish;
830
831 mount_slave_mounted = true;
832
833 r = mount_nofollow_verbose(LOG_DEBUG, NULL, mount_slave, NULL, MS_SLAVE, NULL);
834 if (r < 0)
835 goto finish;
836
837 /* Second, we mount the source file or directory to a directory inside of our MS_SLAVE playground. */
838 mount_tmp = strjoina(mount_slave, "/mount");
839 r = make_mount_point_inode_from_stat(&st, mount_tmp, 0700);
840 if (r < 0) {
841 log_debug_errno(r, "Failed to create temporary mount point %s: %m", mount_tmp);
842 goto finish;
843 }
844
845 mount_tmp_created = true;
846
f7c18d3d 847 r = mount_follow_verbose(LOG_DEBUG, chased_src, mount_tmp, NULL, MS_BIND, NULL);
6af52c3a
LB
848 if (r < 0)
849 goto finish;
850
851 mount_tmp_mounted = true;
852
853 /* Third, we remount the new bind mount read-only if requested. */
854 if (read_only) {
855 r = mount_nofollow_verbose(LOG_DEBUG, NULL, mount_tmp, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL);
856 if (r < 0)
857 goto finish;
858 }
859
860 /* Fourth, we move the new bind mount into the propagation directory. This way it will appear there read-only
861 * right-away. */
862
863 mount_outside = strjoina(propagate_path, "/XXXXXX");
864 if (S_ISDIR(st.st_mode))
865 r = mkdtemp(mount_outside) ? 0 : -errno;
866 else {
867 r = mkostemp_safe(mount_outside);
868 safe_close(r);
869 }
870 if (r < 0) {
871 log_debug_errno(r, "Cannot create propagation file or directory %s: %m", mount_outside);
872 goto finish;
873 }
874
875 mount_outside_created = true;
876
877 r = mount_nofollow_verbose(LOG_DEBUG, mount_tmp, mount_outside, NULL, MS_MOVE, NULL);
878 if (r < 0)
879 goto finish;
880
881 mount_outside_mounted = true;
882 mount_tmp_mounted = false;
883
884 if (S_ISDIR(st.st_mode))
885 (void) rmdir(mount_tmp);
886 else
887 (void) unlink(mount_tmp);
888 mount_tmp_created = false;
889
890 (void) umount_verbose(LOG_DEBUG, mount_slave, UMOUNT_NOFOLLOW);
891 mount_slave_mounted = false;
892
893 (void) rmdir(mount_slave);
894 mount_slave_created = false;
895
896 if (pipe2(errno_pipe_fd, O_CLOEXEC|O_NONBLOCK) < 0) {
897 log_debug_errno(errno, "Failed to create pipe: %m");
898 goto finish;
899 }
900
2338a175 901 r = namespace_fork("(sd-bindmnt)", "(sd-bindmnt-inner)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG,
98f654fd 902 pidns_fd, mntns_fd, -1, -1, root_fd, &child);
6af52c3a
LB
903 if (r < 0)
904 goto finish;
905 if (r == 0) {
2338a175 906 const char *mount_inside;
6af52c3a
LB
907
908 errno_pipe_fd[0] = safe_close(errno_pipe_fd[0]);
909
6af52c3a
LB
910 if (make_file_or_directory) {
911 (void) mkdir_parents(dest, 0755);
912 (void) make_mount_point_inode_from_stat(&st, dest, 0700);
913 }
914
915 /* Fifth, move the mount to the right place inside */
916 mount_inside = strjoina(incoming_path, basename(mount_outside));
917 r = mount_nofollow_verbose(LOG_ERR, mount_inside, dest, NULL, MS_MOVE, NULL);
918 if (r < 0)
919 goto child_fail;
920
921 _exit(EXIT_SUCCESS);
922
923 child_fail:
924 (void) write(errno_pipe_fd[1], &r, sizeof(r));
925 errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
926
927 _exit(EXIT_FAILURE);
928 }
929
930 errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
931
932 r = wait_for_terminate_and_check("(sd-bindmnt)", child, 0);
933 if (r < 0) {
934 log_debug_errno(r, "Failed to wait for child: %m");
935 goto finish;
936 }
937 if (r != EXIT_SUCCESS) {
938 if (read(errno_pipe_fd[0], &r, sizeof(r)) == sizeof(r))
939 log_debug_errno(r, "Failed to mount: %m");
940 else
941 log_debug("Child failed.");
942 goto finish;
943 }
944
945finish:
946 if (mount_outside_mounted)
947 (void) umount_verbose(LOG_DEBUG, mount_outside, UMOUNT_NOFOLLOW);
948 if (mount_outside_created) {
949 if (S_ISDIR(st.st_mode))
950 (void) rmdir(mount_outside);
951 else
952 (void) unlink(mount_outside);
953 }
954
955 if (mount_tmp_mounted)
956 (void) umount_verbose(LOG_DEBUG, mount_tmp, UMOUNT_NOFOLLOW);
957 if (mount_tmp_created) {
958 if (S_ISDIR(st.st_mode))
959 (void) rmdir(mount_tmp);
960 else
961 (void) unlink(mount_tmp);
962 }
963
964 if (mount_slave_mounted)
965 (void) umount_verbose(LOG_DEBUG, mount_slave, UMOUNT_NOFOLLOW);
966 if (mount_slave_created)
967 (void) rmdir(mount_slave);
968
969 return r;
970}