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