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