]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/nspawn/nspawn-mount.c
Merge pull request #21172 from poettering/fix-systemctl-cgroup-tree
[thirdparty/systemd.git] / src / nspawn / nspawn-mount.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
e83bebef 2
4f5dd394 3#include <sys/mount.h>
07630cea 4#include <linux/magic.h>
e83bebef 5
b5efdb8a 6#include "alloc-util.h"
f4351959 7#include "chase-symlinks.h"
4f5dd394 8#include "escape.h"
0996ef00 9#include "fd-util.h"
ca78ad1d 10#include "format-util.h"
f4f15635 11#include "fs-util.h"
e83bebef 12#include "label.h"
4f5dd394 13#include "mkdir.h"
4349cd7c 14#include "mount-util.h"
049af8ad 15#include "mountpoint-util.h"
6bedfcbb
LP
16#include "nspawn-mount.h"
17#include "parse-util.h"
4f5dd394
LP
18#include "path-util.h"
19#include "rm-rf.h"
e83bebef 20#include "set.h"
760877e9 21#include "sort-util.h"
8fcde012 22#include "stat-util.h"
07630cea 23#include "string-util.h"
4f5dd394 24#include "strv.h"
e4de7287 25#include "tmpfile-util.h"
ee104e11 26#include "user-util.h"
e83bebef 27
88614c8a 28CustomMount* custom_mount_add(CustomMount **l, size_t *n, CustomMountType t) {
e83bebef
LP
29 CustomMount *c, *ret;
30
31 assert(l);
32 assert(n);
33 assert(t >= 0);
34 assert(t < _CUSTOM_MOUNT_TYPE_MAX);
35
aa484f35 36 c = reallocarray(*l, *n + 1, sizeof(CustomMount));
e83bebef
LP
37 if (!c)
38 return NULL;
39
40 *l = c;
41 ret = *l + *n;
42 (*n)++;
43
511a8cfe
LP
44 *ret = (CustomMount) {
45 .type = t
46 };
e83bebef
LP
47
48 return ret;
49}
50
88614c8a 51void custom_mount_free_all(CustomMount *l, size_t n) {
d2b99ed7 52 for (size_t i = 0; i < n; i++) {
e83bebef
LP
53 CustomMount *m = l + i;
54
55 free(m->source);
56 free(m->destination);
57 free(m->options);
58
59 if (m->work_dir) {
60 (void) rm_rf(m->work_dir, REMOVE_ROOT|REMOVE_PHYSICAL);
61 free(m->work_dir);
62 }
63
c7a4890c
LP
64 if (m->rm_rf_tmpdir) {
65 (void) rm_rf(m->rm_rf_tmpdir, REMOVE_ROOT|REMOVE_PHYSICAL);
66 free(m->rm_rf_tmpdir);
67 }
68
e83bebef 69 strv_free(m->lower);
de40a303 70 free(m->type_argument);
e83bebef
LP
71 }
72
73 free(l);
74}
75
93bab288 76static int custom_mount_compare(const CustomMount *a, const CustomMount *b) {
e83bebef
LP
77 int r;
78
93bab288 79 r = path_compare(a->destination, b->destination);
e83bebef
LP
80 if (r != 0)
81 return r;
82
93bab288 83 return CMP(a->type, b->type);
e83bebef
LP
84}
85
86c0dd4a
LP
86static bool source_path_is_valid(const char *p) {
87 assert(p);
88
89 if (*p == '+')
90 p++;
91
92 return path_is_absolute(p);
93}
94
95static char *resolve_source_path(const char *dest, const char *source) {
86c0dd4a
LP
96 if (!source)
97 return NULL;
98
99 if (source[0] == '+')
c6134d3e 100 return path_join(dest, source + 1);
86c0dd4a
LP
101
102 return strdup(source);
103}
104
d0556c55
LP
105static int allocate_temporary_source(CustomMount *m) {
106 assert(m);
107 assert(!m->source);
108 assert(!m->rm_rf_tmpdir);
109
110 m->rm_rf_tmpdir = strdup("/var/tmp/nspawn-temp-XXXXXX");
111 if (!m->rm_rf_tmpdir)
112 return log_oom();
113
114 if (!mkdtemp(m->rm_rf_tmpdir)) {
115 m->rm_rf_tmpdir = mfree(m->rm_rf_tmpdir);
116 return log_error_errno(errno, "Failed to acquire temporary directory: %m");
117 }
118
119 m->source = path_join(m->rm_rf_tmpdir, "src");
120 if (!m->source)
121 return log_oom();
122
123 if (mkdir(m->source, 0755) < 0)
124 return log_error_errno(errno, "Failed to create %s: %m", m->source);
125
126 return 0;
127}
128
88614c8a 129int custom_mount_prepare_all(const char *dest, CustomMount *l, size_t n) {
86c0dd4a
LP
130 int r;
131
132 /* Prepare all custom mounts. This will make source we know all temporary directories. This is called in the
133 * parent process, so that we know the temporary directories to remove on exit before we fork off the
134 * children. */
135
136 assert(l || n == 0);
137
138 /* Order the custom mounts, and make sure we have a working directory */
93bab288 139 typesafe_qsort(l, n, custom_mount_compare);
86c0dd4a 140
d2b99ed7 141 for (size_t i = 0; i < n; i++) {
86c0dd4a
LP
142 CustomMount *m = l + i;
143
de40a303
LP
144 /* /proc we mount in the inner child, i.e. when we acquired CLONE_NEWPID. All other mounts we mount
145 * already in the outer child, so that the mounts are already established before CLONE_NEWPID and in
146 * particular CLONE_NEWUSER. This also means any custom mounts below /proc also need to be mounted in
147 * the inner child, not the outer one. Determine this here. */
148 m->in_userns = path_startswith(m->destination, "/proc");
86c0dd4a 149
de40a303
LP
150 if (m->type == CUSTOM_MOUNT_BIND) {
151 if (m->source) {
152 char *s;
86c0dd4a 153
de40a303
LP
154 s = resolve_source_path(dest, m->source);
155 if (!s)
156 return log_oom();
c7a4890c 157
de40a303
LP
158 free_and_replace(m->source, s);
159 } else {
160 /* No source specified? In that case, use a throw-away temporary directory in /var/tmp */
c7a4890c 161
d0556c55
LP
162 r = allocate_temporary_source(m);
163 if (r < 0)
164 return r;
de40a303 165 }
86c0dd4a
LP
166 }
167
168 if (m->type == CUSTOM_MOUNT_OVERLAY) {
169 char **j;
170
171 STRV_FOREACH(j, m->lower) {
172 char *s;
173
174 s = resolve_source_path(dest, *j);
175 if (!s)
176 return log_oom();
177
10af01a5 178 free_and_replace(*j, s);
86c0dd4a
LP
179 }
180
d0556c55
LP
181 if (m->source) {
182 char *s;
183
184 s = resolve_source_path(dest, m->source);
185 if (!s)
186 return log_oom();
187
188 free_and_replace(m->source, s);
189 } else {
190 r = allocate_temporary_source(m);
191 if (r < 0)
192 return r;
193 }
194
86c0dd4a
LP
195 if (m->work_dir) {
196 char *s;
197
198 s = resolve_source_path(dest, m->work_dir);
199 if (!s)
200 return log_oom();
201
10af01a5 202 free_and_replace(m->work_dir, s);
86c0dd4a 203 } else {
86c0dd4a
LP
204 r = tempfn_random(m->source, NULL, &m->work_dir);
205 if (r < 0)
206 return log_error_errno(r, "Failed to acquire working directory: %m");
207 }
208
209 (void) mkdir_label(m->work_dir, 0700);
210 }
211 }
212
213 return 0;
214}
215
88614c8a 216int bind_mount_parse(CustomMount **l, size_t *n, const char *s, bool read_only) {
e83bebef
LP
217 _cleanup_free_ char *source = NULL, *destination = NULL, *opts = NULL;
218 const char *p = s;
219 CustomMount *m;
220 int r;
221
222 assert(l);
223 assert(n);
224
225 r = extract_many_words(&p, ":", EXTRACT_DONT_COALESCE_SEPARATORS, &source, &destination, NULL);
226 if (r < 0)
227 return r;
228 if (r == 0)
229 return -EINVAL;
e83bebef 230 if (r == 1) {
86c0dd4a 231 destination = strdup(source[0] == '+' ? source+1 : source);
e83bebef
LP
232 if (!destination)
233 return -ENOMEM;
234 }
e83bebef
LP
235 if (r == 2 && !isempty(p)) {
236 opts = strdup(p);
237 if (!opts)
238 return -ENOMEM;
239 }
240
c7a4890c 241 if (isempty(source))
0e636bf5 242 source = mfree(source);
c7a4890c 243 else if (!source_path_is_valid(source))
e83bebef 244 return -EINVAL;
c7a4890c 245
e83bebef
LP
246 if (!path_is_absolute(destination))
247 return -EINVAL;
248
249 m = custom_mount_add(l, n, CUSTOM_MOUNT_BIND);
250 if (!m)
48cbe5f8 251 return -ENOMEM;
e83bebef 252
0e636bf5
ZJS
253 m->source = TAKE_PTR(source);
254 m->destination = TAKE_PTR(destination);
e83bebef 255 m->read_only = read_only;
0e636bf5 256 m->options = TAKE_PTR(opts);
de40a303 257
e83bebef
LP
258 return 0;
259}
260
88614c8a 261int tmpfs_mount_parse(CustomMount **l, size_t *n, const char *s) {
e83bebef
LP
262 _cleanup_free_ char *path = NULL, *opts = NULL;
263 const char *p = s;
264 CustomMount *m;
265 int r;
266
267 assert(l);
268 assert(n);
269 assert(s);
270
271 r = extract_first_word(&p, &path, ":", EXTRACT_DONT_COALESCE_SEPARATORS);
272 if (r < 0)
273 return r;
274 if (r == 0)
275 return -EINVAL;
276
277 if (isempty(p))
278 opts = strdup("mode=0755");
279 else
280 opts = strdup(p);
281 if (!opts)
282 return -ENOMEM;
283
284 if (!path_is_absolute(path))
285 return -EINVAL;
286
287 m = custom_mount_add(l, n, CUSTOM_MOUNT_TMPFS);
288 if (!m)
289 return -ENOMEM;
290
1cc6c93a
YW
291 m->destination = TAKE_PTR(path);
292 m->options = TAKE_PTR(opts);
e83bebef 293
e83bebef
LP
294 return 0;
295}
296
88614c8a 297int overlay_mount_parse(CustomMount **l, size_t *n, const char *s, bool read_only) {
ad85779a
LP
298 _cleanup_free_ char *upper = NULL, *destination = NULL;
299 _cleanup_strv_free_ char **lower = NULL;
300 CustomMount *m;
86c0dd4a 301 int k;
ad85779a 302
90e30d76 303 k = strv_split_full(&lower, s, ":", EXTRACT_DONT_COALESCE_SEPARATORS);
86c0dd4a
LP
304 if (k < 0)
305 return k;
ad85779a
LP
306 if (k < 2)
307 return -EADDRNOTAVAIL;
308 if (k == 2) {
86c0dd4a
LP
309 /* If two parameters are specified, the first one is the lower, the second one the upper directory. And
310 * we'll also define the destination mount point the same as the upper. */
311
312 if (!source_path_is_valid(lower[0]) ||
313 !source_path_is_valid(lower[1]))
314 return -EINVAL;
315
ae2a15bc 316 upper = TAKE_PTR(lower[1]);
ad85779a 317
86c0dd4a 318 destination = strdup(upper[0] == '+' ? upper+1 : upper); /* take the destination without "+" prefix */
ad85779a
LP
319 if (!destination)
320 return -ENOMEM;
ad85779a 321 } else {
c7a4890c 322 char **i;
86c0dd4a
LP
323
324 /* If more than two parameters are specified, the last one is the destination, the second to last one
325 * the "upper", and all before that the "lower" directories. */
326
ad85779a 327 destination = lower[k - 1];
ae2a15bc 328 upper = TAKE_PTR(lower[k - 2]);
86c0dd4a 329
c7a4890c
LP
330 STRV_FOREACH(i, lower)
331 if (!source_path_is_valid(*i))
332 return -EINVAL;
333
334 /* If the upper directory is unspecified, then let's create it automatically as a throw-away directory
335 * in /var/tmp */
336 if (isempty(upper))
1d0c1146 337 upper = mfree(upper);
c7a4890c
LP
338 else if (!source_path_is_valid(upper))
339 return -EINVAL;
340
86c0dd4a
LP
341 if (!path_is_absolute(destination))
342 return -EINVAL;
ad85779a
LP
343 }
344
345 m = custom_mount_add(l, n, CUSTOM_MOUNT_OVERLAY);
346 if (!m)
347 return -ENOMEM;
348
1cc6c93a
YW
349 m->destination = TAKE_PTR(destination);
350 m->source = TAKE_PTR(upper);
351 m->lower = TAKE_PTR(lower);
ad85779a
LP
352 m->read_only = read_only;
353
ad85779a
LP
354 return 0;
355}
356
de40a303
LP
357int inaccessible_mount_parse(CustomMount **l, size_t *n, const char *s) {
358 _cleanup_free_ char *path = NULL;
359 CustomMount *m;
360
361 assert(l);
362 assert(n);
363 assert(s);
364
365 if (!path_is_absolute(s))
366 return -EINVAL;
367
368 path = strdup(s);
369 if (!path)
370 return -ENOMEM;
371
372 m = custom_mount_add(l, n, CUSTOM_MOUNT_INACCESSIBLE);
373 if (!m)
374 return -ENOMEM;
375
376 m->destination = TAKE_PTR(path);
377 return 0;
378}
379
04029482 380int tmpfs_patch_options(
e83bebef 381 const char *options,
2fa017f1 382 uid_t uid_shift,
e83bebef
LP
383 const char *selinux_apifs_context,
384 char **ret) {
385
cfea7618 386 _cleanup_free_ char *buf = NULL;
e83bebef 387
cfea7618 388 assert(ret);
e83bebef 389
cfea7618
YW
390 if (options) {
391 buf = strdup(options);
392 if (!buf)
393 return -ENOMEM;
e83bebef
LP
394 }
395
cfea7618
YW
396 if (uid_shift != UID_INVALID)
397 if (strextendf_with_separator(&buf, ",", "uid=" UID_FMT ",gid=" UID_FMT, uid_shift, uid_shift) < 0)
e83bebef 398 return -ENOMEM;
e83bebef 399
cfea7618
YW
400#if HAVE_SELINUX
401 if (selinux_apifs_context)
d3d15594 402 if (strextendf_with_separator(&buf, ",", "context=\"%s\"", selinux_apifs_context) < 0)
0996ef00 403 return -ENOMEM;
cfea7618 404#endif
0996ef00 405
cfea7618
YW
406 *ret = TAKE_PTR(buf);
407 return !!*ret;
e83bebef
LP
408}
409
4f086aab 410int mount_sysfs(const char *dest, MountSettingsMask mount_settings) {
d8fc6a00 411 const char *full, *top, *x;
d1678248 412 int r;
4f086aab 413 unsigned long extra_flags = 0;
d8fc6a00
LP
414
415 top = prefix_roota(dest, "/sys");
40fd52f2 416 r = path_is_fs_type(top, SYSFS_MAGIC);
d1678248
ILG
417 if (r < 0)
418 return log_error_errno(r, "Failed to determine filesystem type of %s: %m", top);
419 /* /sys might already be mounted as sysfs by the outer child in the
420 * !netns case. In this case, it's all good. Don't touch it because we
421 * don't have the right to do so, see https://github.com/systemd/systemd/issues/1555.
422 */
423 if (r > 0)
424 return 0;
425
d8fc6a00
LP
426 full = prefix_roota(top, "/full");
427
428 (void) mkdir(full, 0755);
429
bd6609eb 430 if (FLAGS_SET(mount_settings, MOUNT_APPLY_APIVFS_RO))
4f086aab
SU
431 extra_flags |= MS_RDONLY;
432
511a8cfe
LP
433 r = mount_nofollow_verbose(LOG_ERR, "sysfs", full, "sysfs",
434 MS_NOSUID|MS_NOEXEC|MS_NODEV|extra_flags, NULL);
60e76d48
ZJS
435 if (r < 0)
436 return r;
d8fc6a00
LP
437
438 FOREACH_STRING(x, "block", "bus", "class", "dev", "devices", "kernel") {
439 _cleanup_free_ char *from = NULL, *to = NULL;
440
c6134d3e 441 from = path_join(full, x);
d8fc6a00
LP
442 if (!from)
443 return log_oom();
444
c6134d3e 445 to = path_join(top, x);
d8fc6a00
LP
446 if (!to)
447 return log_oom();
448
449 (void) mkdir(to, 0755);
450
511a8cfe 451 r = mount_nofollow_verbose(LOG_ERR, from, to, NULL, MS_BIND, NULL);
60e76d48
ZJS
452 if (r < 0)
453 return r;
d8fc6a00 454
511a8cfe
LP
455 r = mount_nofollow_verbose(LOG_ERR, NULL, to, NULL,
456 MS_BIND|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT|extra_flags, NULL);
60e76d48
ZJS
457 if (r < 0)
458 return r;
d8fc6a00
LP
459 }
460
30f5d104 461 r = umount_verbose(LOG_ERR, full, UMOUNT_NOFOLLOW);
60e76d48
ZJS
462 if (r < 0)
463 return r;
d8fc6a00
LP
464
465 if (rmdir(full) < 0)
466 return log_error_errno(errno, "Failed to remove %s: %m", full);
467
0996ef00
CB
468 /* Create mountpoint for cgroups. Otherwise we are not allowed since we
469 * remount /sys read-only.
470 */
677a72cd
LS
471 x = prefix_roota(top, "/fs/cgroup");
472 (void) mkdir_p(x, 0755);
d8fc6a00 473
511a8cfe
LP
474 return mount_nofollow_verbose(LOG_ERR, NULL, top, NULL,
475 MS_BIND|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT|extra_flags, NULL);
d8fc6a00
LP
476}
477
e83bebef 478int mount_all(const char *dest,
4f086aab 479 MountSettingsMask mount_settings,
2fa017f1 480 uid_t uid_shift,
e83bebef
LP
481 const char *selinux_apifs_context) {
482
de40a303
LP
483#define PROC_INACCESSIBLE_REG(path) \
484 { "/run/systemd/inaccessible/reg", (path), NULL, NULL, MS_BIND, \
485 MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO }, /* Bind mount first ... */ \
d4b653c5
LP
486 { NULL, (path), NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT, \
487 MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO } /* Then, make it r/o */
488
489#define PROC_READ_ONLY(path) \
490 { (path), (path), NULL, NULL, MS_BIND, \
491 MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO }, /* Bind mount first ... */ \
492 { NULL, (path), NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT, \
493 MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO } /* Then, make it r/o */
494
e83bebef
LP
495 typedef struct MountPoint {
496 const char *what;
497 const char *where;
498 const char *type;
499 const char *options;
500 unsigned long flags;
4f086aab 501 MountSettingsMask mount_settings;
e83bebef
LP
502 } MountPoint;
503
504 static const MountPoint mount_table[] = {
d4b653c5
LP
505 /* First we list inner child mounts (i.e. mounts applied *after* entering user namespacing) */
506 { "proc", "/proc", "proc", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV,
511a8cfe 507 MOUNT_FATAL|MOUNT_IN_USERNS|MOUNT_MKDIR|MOUNT_FOLLOW_SYMLINKS }, /* we follow symlinks here since not following them requires /proc/ already being mounted, which we don't have here. */
d4b653c5
LP
508
509 { "/proc/sys", "/proc/sys", NULL, NULL, MS_BIND,
510 MOUNT_FATAL|MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO }, /* Bind mount first ... */
511
512 { "/proc/sys/net", "/proc/sys/net", NULL, NULL, MS_BIND,
513 MOUNT_FATAL|MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO|MOUNT_APPLY_APIVFS_NETNS }, /* (except for this) */
514
515 { NULL, "/proc/sys", NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT,
516 MOUNT_FATAL|MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO }, /* ... then, make it r/o */
517
518 /* Make these files inaccessible to container payloads: they potentially leak information about kernel
519 * internals or the host's execution environment to the container */
de40a303
LP
520 PROC_INACCESSIBLE_REG("/proc/kallsyms"),
521 PROC_INACCESSIBLE_REG("/proc/kcore"),
522 PROC_INACCESSIBLE_REG("/proc/keys"),
523 PROC_INACCESSIBLE_REG("/proc/sysrq-trigger"),
524 PROC_INACCESSIBLE_REG("/proc/timer_list"),
d4b653c5
LP
525
526 /* Make these directories read-only to container payloads: they show hardware information, and in some
527 * cases contain tunables the container really shouldn't have access to. */
528 PROC_READ_ONLY("/proc/acpi"),
529 PROC_READ_ONLY("/proc/apm"),
530 PROC_READ_ONLY("/proc/asound"),
531 PROC_READ_ONLY("/proc/bus"),
532 PROC_READ_ONLY("/proc/fs"),
533 PROC_READ_ONLY("/proc/irq"),
534 PROC_READ_ONLY("/proc/scsi"),
535
e1bb4b0d 536 { "mqueue", "/dev/mqueue", "mqueue", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV,
dcff2fa5 537 MOUNT_IN_USERNS|MOUNT_MKDIR },
849b9b85 538
d4b653c5 539 /* Then we list outer child mounts (i.e. mounts applied *before* entering user namespacing) */
b67ec8e5 540 { "tmpfs", "/tmp", "tmpfs", "mode=1777" NESTED_TMPFS_LIMITS, MS_NOSUID|MS_NODEV|MS_STRICTATIME,
dcff2fa5 541 MOUNT_FATAL|MOUNT_APPLY_TMPFS_TMP|MOUNT_MKDIR },
e1bb4b0d 542 { "tmpfs", "/sys", "tmpfs", "mode=555" TMPFS_LIMITS_SYS, MS_NOSUID|MS_NOEXEC|MS_NODEV,
dcff2fa5 543 MOUNT_FATAL|MOUNT_APPLY_APIVFS_NETNS|MOUNT_MKDIR },
e1bb4b0d 544 { "sysfs", "/sys", "sysfs", NULL, MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV,
dcff2fa5 545 MOUNT_FATAL|MOUNT_APPLY_APIVFS_RO|MOUNT_MKDIR }, /* skipped if above was mounted */
e1bb4b0d 546 { "sysfs", "/sys", "sysfs", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV,
dcff2fa5 547 MOUNT_FATAL|MOUNT_MKDIR }, /* skipped if above was mounted */
e1bb4b0d 548 { "tmpfs", "/dev", "tmpfs", "mode=755" TMPFS_LIMITS_DEV, MS_NOSUID|MS_STRICTATIME,
dcff2fa5 549 MOUNT_FATAL|MOUNT_MKDIR },
b67ec8e5 550 { "tmpfs", "/dev/shm", "tmpfs", "mode=1777" NESTED_TMPFS_LIMITS, MS_NOSUID|MS_NODEV|MS_STRICTATIME,
dcff2fa5 551 MOUNT_FATAL|MOUNT_MKDIR },
e1bb4b0d 552 { "tmpfs", "/run", "tmpfs", "mode=755" TMPFS_LIMITS_RUN, MS_NOSUID|MS_NODEV|MS_STRICTATIME,
dcff2fa5 553 MOUNT_FATAL|MOUNT_MKDIR },
d64e32c2
LP
554 { "/run/host", "/run/host", NULL, NULL, MS_BIND,
555 MOUNT_FATAL|MOUNT_MKDIR|MOUNT_PREFIX_ROOT }, /* Prepare this so that we can make it read-only when we are done */
556 { "/etc/os-release", "/run/host/os-release", NULL, NULL, MS_BIND,
557 MOUNT_TOUCH }, /* As per kernel interface requirements, bind mount first (creating mount points) and make read-only later */
558 { "/usr/lib/os-release", "/run/host/os-release", NULL, NULL, MS_BIND,
559 MOUNT_FATAL }, /* If /etc/os-release doesn't exist use the version in /usr/lib as fallback */
560 { NULL, "/run/host/os-release", NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT,
561 MOUNT_FATAL },
562 { NULL, "/run/host", NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT,
563 MOUNT_FATAL|MOUNT_IN_USERNS },
349cc4a5 564#if HAVE_SELINUX
e1bb4b0d 565 { "/sys/fs/selinux", "/sys/fs/selinux", NULL, NULL, MS_BIND,
6fe01ced 566 MOUNT_MKDIR }, /* Bind mount first (mkdir/chown the mount point in case /sys/ is mounted as minimal skeleton tmpfs) */
e1bb4b0d 567 { NULL, "/sys/fs/selinux", NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT,
6fe01ced 568 0 }, /* Then, make it r/o (don't mkdir/chown the mount point here, the previous entry already did that) */
e83bebef
LP
569#endif
570 };
571
bd6609eb
DDM
572 bool use_userns = FLAGS_SET(mount_settings, MOUNT_USE_USERNS);
573 bool netns = FLAGS_SET(mount_settings, MOUNT_APPLY_APIVFS_NETNS);
574 bool ro = FLAGS_SET(mount_settings, MOUNT_APPLY_APIVFS_RO);
575 bool in_userns = FLAGS_SET(mount_settings, MOUNT_IN_USERNS);
576 bool tmpfs_tmp = FLAGS_SET(mount_settings, MOUNT_APPLY_TMPFS_TMP);
88614c8a 577 int r;
e83bebef 578
d2b99ed7 579 for (size_t k = 0; k < ELEMENTSOF(mount_table); k++) {
d64e32c2 580 _cleanup_free_ char *where = NULL, *options = NULL, *prefixed = NULL;
bd6609eb 581 bool fatal = FLAGS_SET(mount_table[k].mount_settings, MOUNT_FATAL);
d64e32c2 582 const char *o;
4f086aab 583
bd6609eb 584 if (in_userns != FLAGS_SET(mount_table[k].mount_settings, MOUNT_IN_USERNS))
4f086aab 585 continue;
e83bebef 586
bd6609eb 587 if (!netns && FLAGS_SET(mount_table[k].mount_settings, MOUNT_APPLY_APIVFS_NETNS))
d1678248
ILG
588 continue;
589
bd6609eb 590 if (!ro && FLAGS_SET(mount_table[k].mount_settings, MOUNT_APPLY_APIVFS_RO))
e83bebef
LP
591 continue;
592
bd6609eb 593 if (!tmpfs_tmp && FLAGS_SET(mount_table[k].mount_settings, MOUNT_APPLY_TMPFS_TMP))
1099ceeb
LP
594 continue;
595
a5648b80 596 r = chase_symlinks(mount_table[k].where, dest, CHASE_NONEXISTENT|CHASE_PREFIX_ROOT, &where, NULL);
8ce48cf0 597 if (r < 0)
ec57bd42 598 return log_error_errno(r, "Failed to resolve %s/%s: %m", dest, mount_table[k].where);
e83bebef 599
e83bebef 600 /* Skip this entry if it is not a remount. */
de40a303
LP
601 if (mount_table[k].what) {
602 r = path_is_mount_point(where, NULL, 0);
603 if (r < 0 && r != -ENOENT)
604 return log_error_errno(r, "Failed to detect whether %s is a mount point: %m", where);
605 if (r > 0)
606 continue;
607 }
e83bebef 608
d64e32c2 609 if ((mount_table[k].mount_settings & (MOUNT_MKDIR|MOUNT_TOUCH)) != 0) {
b3b1a08a 610 uid_t u = (use_userns && !in_userns) ? uid_shift : UID_INVALID;
e1bb4b0d
LB
611
612 if (FLAGS_SET(mount_table[k].mount_settings, MOUNT_TOUCH))
613 r = mkdir_parents_safe(dest, where, 0755, u, u, 0);
614 else
615 r = mkdir_p_safe(dest, where, 0755, u, u, 0);
dcff2fa5
LP
616 if (r < 0 && r != -EEXIST) {
617 if (fatal && r != -EROFS)
618 return log_error_errno(r, "Failed to create directory %s: %m", where);
e83bebef 619
dcff2fa5
LP
620 log_debug_errno(r, "Failed to create directory %s: %m", where);
621
622 /* If we failed mkdir() or chown() due to the root directory being read only,
623 * attempt to mount this fs anyway and let mount_verbose log any errors */
624 if (r != -EROFS)
625 continue;
626 }
d64e32c2
LP
627 }
628
629 if (FLAGS_SET(mount_table[k].mount_settings, MOUNT_TOUCH)) {
630 r = touch(where);
631 if (r < 0 && r != -EEXIST) {
632 if (fatal && r != -EROFS)
633 return log_error_errno(r, "Failed to create file %s: %m", where);
634
635 log_debug_errno(r, "Failed to create file %s: %m", where);
636 if (r != -EROFS)
637 continue;
e1bb4b0d 638 }
e83bebef
LP
639 }
640
641 o = mount_table[k].options;
642 if (streq_ptr(mount_table[k].type, "tmpfs")) {
2fa017f1 643 r = tmpfs_patch_options(o, in_userns ? 0 : uid_shift, selinux_apifs_context, &options);
e83bebef
LP
644 if (r < 0)
645 return log_oom();
646 if (r > 0)
647 o = options;
648 }
649
d64e32c2
LP
650 if (FLAGS_SET(mount_table[k].mount_settings, MOUNT_PREFIX_ROOT)) {
651 /* Optionally prefix the mount source with the root dir. This is useful in bind
652 * mounts to be created within the container image before we transition into it. Note
653 * that MOUNT_IN_USERNS is run after we transitioned hence prefixing is not ncessary
654 * for those. */
655 r = chase_symlinks(mount_table[k].what, dest, CHASE_PREFIX_ROOT, &prefixed, NULL);
656 if (r < 0)
657 return log_error_errno(r, "Failed to resolve %s/%s: %m", dest, mount_table[k].what);
658 }
659
511a8cfe
LP
660 r = mount_verbose_full(
661 fatal ? LOG_ERR : LOG_DEBUG,
662 prefixed ?: mount_table[k].what,
663 where,
664 mount_table[k].type,
665 mount_table[k].flags,
666 o,
667 FLAGS_SET(mount_table[k].mount_settings, MOUNT_FOLLOW_SYMLINKS));
4f086aab 668 if (r < 0 && fatal)
60e76d48 669 return r;
e83bebef
LP
670 }
671
672 return 0;
673}
674
c0c8f718 675static int parse_mount_bind_options(const char *options, unsigned long *mount_flags, char **mount_opts, bool *idmapped) {
a11fd406
ILG
676 unsigned long flags = *mount_flags;
677 char *opts = NULL;
c0c8f718 678 bool flag_idmapped = *idmapped;
a11fd406
ILG
679 int r;
680
681 assert(options);
682
683 for (;;) {
684 _cleanup_free_ char *word = NULL;
685
d2b99ed7 686 r = extract_first_word(&options, &word, ",", 0);
a11fd406
ILG
687 if (r < 0)
688 return log_error_errno(r, "Failed to extract mount option: %m");
689 if (r == 0)
690 break;
691
692 if (streq(word, "rbind"))
693 flags |= MS_REC;
694 else if (streq(word, "norbind"))
695 flags &= ~MS_REC;
c0c8f718
AV
696 else if (streq(word, "idmap"))
697 flag_idmapped = true;
698 else if (streq(word, "noidmap"))
699 flag_idmapped = false;
d2b99ed7 700 else
38288f0b 701 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
d2b99ed7 702 "Invalid bind mount option: %s", word);
a11fd406
ILG
703 }
704
705 *mount_flags = flags;
c0c8f718 706 *idmapped = flag_idmapped;
a11fd406
ILG
707 /* in the future mount_opts will hold string options for mount(2) */
708 *mount_opts = opts;
709
710 return 0;
711}
712
c0c8f718 713static int mount_bind(const char *dest, CustomMount *m, uid_t uid_shift, uid_t uid_range) {
a11fd406
ILG
714 _cleanup_free_ char *mount_opts = NULL, *where = NULL;
715 unsigned long mount_flags = MS_BIND | MS_REC;
68cf43c3 716 struct stat source_st, dest_st;
e83bebef 717 int r;
c0c8f718 718 bool idmapped = false;
e83bebef 719
86c0dd4a 720 assert(dest);
e83bebef
LP
721 assert(m);
722
a11fd406 723 if (m->options) {
c0c8f718 724 r = parse_mount_bind_options(m->options, &mount_flags, &mount_opts, &idmapped);
a11fd406
ILG
725 if (r < 0)
726 return r;
727 }
728
07bca16f
LP
729 /* If this is a bind mount from a temporary sources change ownership of the source to the container's
730 * root UID. Otherwise it would always show up as "nobody" if user namespacing is used. */
731 if (m->rm_rf_tmpdir && chown(m->source, uid_shift, uid_shift) < 0)
732 return log_error_errno(errno, "Failed to chown %s: %m", m->source);
733
e83bebef
LP
734 if (stat(m->source, &source_st) < 0)
735 return log_error_errno(errno, "Failed to stat %s: %m", m->source);
736
a5648b80 737 r = chase_symlinks(m->destination, dest, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT, &where, NULL);
68cf43c3 738 if (r < 0)
ec57bd42 739 return log_error_errno(r, "Failed to resolve %s/%s: %m", dest, m->destination);
8ce48cf0
LP
740 if (r > 0) { /* Path exists already? */
741
742 if (stat(where, &dest_st) < 0)
743 return log_error_errno(errno, "Failed to stat %s: %m", where);
e83bebef 744
baaa35ad
ZJS
745 if (S_ISDIR(source_st.st_mode) && !S_ISDIR(dest_st.st_mode))
746 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
747 "Cannot bind mount directory %s on file %s.",
748 m->source, where);
749
750 if (!S_ISDIR(source_st.st_mode) && S_ISDIR(dest_st.st_mode))
751 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
752 "Cannot bind mount file %s on directory %s.",
753 m->source, where);
e83bebef 754
8ce48cf0 755 } else { /* Path doesn't exist yet? */
e83bebef
LP
756 r = mkdir_parents_label(where, 0755);
757 if (r < 0)
758 return log_error_errno(r, "Failed to make parents of %s: %m", where);
b97e83cb
BN
759
760 /* Create the mount point. Any non-directory file can be
761 * mounted on any non-directory file (regular, fifo, socket,
762 * char, block).
763 */
764 if (S_ISDIR(source_st.st_mode))
765 r = mkdir_label(where, 0755);
766 else
767 r = touch(where);
768 if (r < 0)
769 return log_error_errno(r, "Failed to create mount point %s: %m", where);
8ce48cf0 770 }
e83bebef 771
511a8cfe 772 r = mount_nofollow_verbose(LOG_ERR, m->source, where, NULL, mount_flags, mount_opts);
60e76d48
ZJS
773 if (r < 0)
774 return r;
e83bebef
LP
775
776 if (m->read_only) {
64e82c19 777 r = bind_remount_recursive(where, MS_RDONLY, MS_RDONLY, NULL);
e83bebef
LP
778 if (r < 0)
779 return log_error_errno(r, "Read-only bind mount failed: %m");
780 }
781
c0c8f718
AV
782 if (idmapped) {
783 r = remount_idmap(where, uid_shift, uid_range);
784 if (r < 0)
785 return log_error_errno(r, "Failed to map ids for bind mount %s: %m", where);
786 }
787
e83bebef
LP
788 return 0;
789}
790
e091a5df 791static int mount_tmpfs(const char *dest, CustomMount *m, uid_t uid_shift, const char *selinux_apifs_context) {
68cf43c3
LP
792 const char *options;
793 _cleanup_free_ char *buf = NULL, *where = NULL;
e83bebef
LP
794 int r;
795
796 assert(dest);
797 assert(m);
798
a5648b80 799 r = chase_symlinks(m->destination, dest, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT, &where, NULL);
68cf43c3 800 if (r < 0)
ec57bd42 801 return log_error_errno(r, "Failed to resolve %s/%s: %m", dest, m->destination);
8ce48cf0
LP
802 if (r == 0) { /* Doesn't exist yet? */
803 r = mkdir_p_label(where, 0755);
804 if (r < 0)
805 return log_error_errno(r, "Creating mount point for tmpfs %s failed: %m", where);
806 }
e83bebef 807
2fa017f1 808 r = tmpfs_patch_options(m->options, uid_shift == 0 ? UID_INVALID : uid_shift, selinux_apifs_context, &buf);
e83bebef
LP
809 if (r < 0)
810 return log_oom();
811 options = r > 0 ? buf : m->options;
812
511a8cfe 813 return mount_nofollow_verbose(LOG_ERR, "tmpfs", where, "tmpfs", MS_NODEV|MS_STRICTATIME, options);
e83bebef
LP
814}
815
86c0dd4a 816static char *joined_and_escaped_lower_dirs(char **lower) {
e83bebef
LP
817 _cleanup_strv_free_ char **sv = NULL;
818
819 sv = strv_copy(lower);
820 if (!sv)
821 return NULL;
822
823 strv_reverse(sv);
824
825 if (!strv_shell_escape(sv, ",:"))
826 return NULL;
827
828 return strv_join(sv, ":");
829}
830
831static int mount_overlay(const char *dest, CustomMount *m) {
86c0dd4a 832 _cleanup_free_ char *lower = NULL, *where = NULL, *escaped_source = NULL;
68cf43c3 833 const char *options;
e83bebef
LP
834 int r;
835
836 assert(dest);
837 assert(m);
838
a5648b80 839 r = chase_symlinks(m->destination, dest, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT, &where, NULL);
68cf43c3 840 if (r < 0)
ec57bd42 841 return log_error_errno(r, "Failed to resolve %s/%s: %m", dest, m->destination);
8ce48cf0
LP
842 if (r == 0) { /* Doesn't exist yet? */
843 r = mkdir_label(where, 0755);
844 if (r < 0)
845 return log_error_errno(r, "Creating mount point for overlay %s failed: %m", where);
846 }
e83bebef
LP
847
848 (void) mkdir_p_label(m->source, 0755);
849
850 lower = joined_and_escaped_lower_dirs(m->lower);
851 if (!lower)
852 return log_oom();
853
86c0dd4a
LP
854 escaped_source = shell_escape(m->source, ",:");
855 if (!escaped_source)
856 return log_oom();
e83bebef 857
86c0dd4a 858 if (m->read_only)
e83bebef 859 options = strjoina("lowerdir=", escaped_source, ":", lower);
86c0dd4a
LP
860 else {
861 _cleanup_free_ char *escaped_work_dir = NULL;
e83bebef 862
e83bebef
LP
863 escaped_work_dir = shell_escape(m->work_dir, ",:");
864 if (!escaped_work_dir)
865 return log_oom();
866
867 options = strjoina("lowerdir=", lower, ",upperdir=", escaped_source, ",workdir=", escaped_work_dir);
868 }
869
511a8cfe 870 return mount_nofollow_verbose(LOG_ERR, "overlay", where, "overlay", m->read_only ? MS_RDONLY : 0, options);
e83bebef
LP
871}
872
de40a303 873static int mount_inaccessible(const char *dest, CustomMount *m) {
e5f10caf 874 _cleanup_free_ char *where = NULL, *source = NULL;
de40a303
LP
875 struct stat st;
876 int r;
877
878 assert(dest);
879 assert(m);
880
a5648b80 881 r = chase_symlinks_and_stat(m->destination, dest, CHASE_PREFIX_ROOT, &where, &st, NULL);
de40a303
LP
882 if (r < 0) {
883 log_full_errno(m->graceful ? LOG_DEBUG : LOG_ERR, r, "Failed to resolve %s/%s: %m", dest, m->destination);
884 return m->graceful ? 0 : r;
885 }
886
48b747fa 887 r = mode_to_inaccessible_node(NULL, st.st_mode, &source);
e5f10caf
AZ
888 if (r < 0)
889 return m->graceful ? 0 : r;
de40a303 890
511a8cfe 891 r = mount_nofollow_verbose(m->graceful ? LOG_DEBUG : LOG_ERR, source, where, NULL, MS_BIND, NULL);
de40a303
LP
892 if (r < 0)
893 return m->graceful ? 0 : r;
894
511a8cfe 895 r = mount_nofollow_verbose(m->graceful ? LOG_DEBUG : LOG_ERR, NULL, where, NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, NULL);
2c9b7a7e 896 if (r < 0) {
30f5d104 897 (void) umount_verbose(m->graceful ? LOG_DEBUG : LOG_ERR, where, UMOUNT_NOFOLLOW);
de40a303 898 return m->graceful ? 0 : r;
2c9b7a7e 899 }
de40a303
LP
900
901 return 0;
902}
903
904static int mount_arbitrary(const char *dest, CustomMount *m) {
905 _cleanup_free_ char *where = NULL;
906 int r;
907
908 assert(dest);
909 assert(m);
910
a5648b80 911 r = chase_symlinks(m->destination, dest, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT, &where, NULL);
de40a303
LP
912 if (r < 0)
913 return log_error_errno(r, "Failed to resolve %s/%s: %m", dest, m->destination);
914 if (r == 0) { /* Doesn't exist yet? */
915 r = mkdir_p_label(where, 0755);
916 if (r < 0)
917 return log_error_errno(r, "Creating mount point for mount %s failed: %m", where);
918 }
919
511a8cfe 920 return mount_nofollow_verbose(LOG_ERR, m->source, where, m->type_argument, 0, m->options);
de40a303
LP
921}
922
e83bebef
LP
923int mount_custom(
924 const char *dest,
88614c8a 925 CustomMount *mounts, size_t n,
e091a5df 926 uid_t uid_shift,
c0c8f718 927 uid_t uid_range,
de40a303 928 const char *selinux_apifs_context,
5f0a6347 929 MountSettingsMask mount_settings) {
e83bebef
LP
930 int r;
931
932 assert(dest);
933
d2b99ed7 934 for (size_t i = 0; i < n; i++) {
e83bebef
LP
935 CustomMount *m = mounts + i;
936
bd6609eb 937 if (FLAGS_SET(mount_settings, MOUNT_IN_USERNS) != m->in_userns)
5f0a6347
DDM
938 continue;
939
bd6609eb 940 if (FLAGS_SET(mount_settings, MOUNT_ROOT_ONLY) && !path_equal(m->destination, "/"))
5f0a6347
DDM
941 continue;
942
bd6609eb 943 if (FLAGS_SET(mount_settings, MOUNT_NON_ROOT_ONLY) && path_equal(m->destination, "/"))
de40a303
LP
944 continue;
945
e83bebef
LP
946 switch (m->type) {
947
948 case CUSTOM_MOUNT_BIND:
c0c8f718 949 r = mount_bind(dest, m, uid_shift, uid_range);
e83bebef
LP
950 break;
951
952 case CUSTOM_MOUNT_TMPFS:
e091a5df 953 r = mount_tmpfs(dest, m, uid_shift, selinux_apifs_context);
e83bebef
LP
954 break;
955
956 case CUSTOM_MOUNT_OVERLAY:
957 r = mount_overlay(dest, m);
958 break;
959
de40a303
LP
960 case CUSTOM_MOUNT_INACCESSIBLE:
961 r = mount_inaccessible(dest, m);
962 break;
963
964 case CUSTOM_MOUNT_ARBITRARY:
965 r = mount_arbitrary(dest, m);
966 break;
967
e83bebef 968 default:
04499a70 969 assert_not_reached();
e83bebef
LP
970 }
971
972 if (r < 0)
973 return r;
974 }
975
976 return 0;
977}
978
bbd407ea 979bool has_custom_root_mount(const CustomMount *mounts, size_t n) {
d2b99ed7
ZJS
980 for (size_t i = 0; i < n; i++)
981 if (path_equal(mounts[i].destination, "/"))
bbd407ea 982 return true;
bbd407ea
DDM
983
984 return false;
985}
986
e091a5df 987static int setup_volatile_state(const char *directory, uid_t uid_shift, const char *selinux_apifs_context) {
e83bebef
LP
988 _cleanup_free_ char *buf = NULL;
989 const char *p, *options;
990 int r;
991
992 assert(directory);
993
e5b43a04 994 /* --volatile=state means we simply overmount /var with a tmpfs, and the rest read-only. */
e83bebef 995
64e82c19 996 r = bind_remount_recursive(directory, MS_RDONLY, MS_RDONLY, NULL);
e83bebef
LP
997 if (r < 0)
998 return log_error_errno(r, "Failed to remount %s read-only: %m", directory);
999
1000 p = prefix_roota(directory, "/var");
1001 r = mkdir(p, 0755);
1002 if (r < 0 && errno != EEXIST)
1003 return log_error_errno(errno, "Failed to create %s: %m", directory);
1004
7d85383e 1005 options = "mode=755" TMPFS_LIMITS_VOLATILE_STATE;
2fa017f1 1006 r = tmpfs_patch_options(options, uid_shift == 0 ? UID_INVALID : uid_shift, selinux_apifs_context, &buf);
e83bebef
LP
1007 if (r < 0)
1008 return log_oom();
1009 if (r > 0)
1010 options = buf;
1011
511a8cfe 1012 return mount_nofollow_verbose(LOG_ERR, "tmpfs", p, "tmpfs", MS_STRICTATIME, options);
e83bebef
LP
1013}
1014
e091a5df 1015static int setup_volatile_yes(const char *directory, uid_t uid_shift, const char *selinux_apifs_context) {
e83bebef
LP
1016 bool tmpfs_mounted = false, bind_mounted = false;
1017 char template[] = "/tmp/nspawn-volatile-XXXXXX";
07b9f3f0 1018 _cleanup_free_ char *buf = NULL, *bindir = NULL;
e83bebef 1019 const char *f, *t, *options;
07b9f3f0 1020 struct stat st;
e83bebef
LP
1021 int r;
1022
1023 assert(directory);
1024
07b9f3f0
LP
1025 /* --volatile=yes means we mount a tmpfs to the root dir, and the original /usr to use inside it, and
1026 * that read-only. Before we start setting this up let's validate if the image has the /usr merge
1027 * implemented, and let's output a friendly log message if it hasn't. */
1028
1029 bindir = path_join(directory, "/bin");
1030 if (!bindir)
1031 return log_oom();
1032 if (lstat(bindir, &st) < 0) {
1033 if (errno != ENOENT)
1034 return log_error_errno(errno, "Failed to stat /bin directory below image: %m");
1035
1036 /* ENOENT is fine, just means the image is probably just a naked /usr and we can create the
1037 * rest. */
1038 } else if (S_ISDIR(st.st_mode))
1039 return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
1040 "Sorry, --volatile=yes mode is not supported with OS images that have not merged /bin/, /sbin/, /lib/, /lib64/ into /usr/. "
1041 "Please work with your distribution and help them adopt the merged /usr scheme.");
1042 else if (!S_ISLNK(st.st_mode))
1043 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1044 "Error starting image: if --volatile=yes is used /bin must be a symlink (for merged /usr support) or non-existent (in which case a symlink is created automatically).");
e83bebef
LP
1045
1046 if (!mkdtemp(template))
1047 return log_error_errno(errno, "Failed to create temporary directory: %m");
1048
7d85383e 1049 options = "mode=755" TMPFS_LIMITS_ROOTFS;
2fa017f1 1050 r = tmpfs_patch_options(options, uid_shift == 0 ? UID_INVALID : uid_shift, selinux_apifs_context, &buf);
e83bebef 1051 if (r < 0)
c55d0ae7 1052 goto fail;
e83bebef
LP
1053 if (r > 0)
1054 options = buf;
1055
511a8cfe 1056 r = mount_nofollow_verbose(LOG_ERR, "tmpfs", template, "tmpfs", MS_STRICTATIME, options);
60e76d48 1057 if (r < 0)
e83bebef 1058 goto fail;
e83bebef
LP
1059
1060 tmpfs_mounted = true;
1061
1062 f = prefix_roota(directory, "/usr");
1063 t = prefix_roota(template, "/usr");
1064
1065 r = mkdir(t, 0755);
1066 if (r < 0 && errno != EEXIST) {
1067 r = log_error_errno(errno, "Failed to create %s: %m", t);
1068 goto fail;
1069 }
1070
511a8cfe 1071 r = mount_nofollow_verbose(LOG_ERR, f, t, NULL, MS_BIND|MS_REC, NULL);
60e76d48 1072 if (r < 0)
e83bebef 1073 goto fail;
e83bebef
LP
1074
1075 bind_mounted = true;
1076
64e82c19 1077 r = bind_remount_recursive(t, MS_RDONLY, MS_RDONLY, NULL);
e83bebef
LP
1078 if (r < 0) {
1079 log_error_errno(r, "Failed to remount %s read-only: %m", t);
1080 goto fail;
1081 }
1082
511a8cfe 1083 r = mount_nofollow_verbose(LOG_ERR, template, directory, NULL, MS_MOVE, NULL);
60e76d48 1084 if (r < 0)
e83bebef 1085 goto fail;
e83bebef
LP
1086
1087 (void) rmdir(template);
1088
1089 return 0;
1090
1091fail:
1092 if (bind_mounted)
30f5d104 1093 (void) umount_verbose(LOG_ERR, t, UMOUNT_NOFOLLOW);
e83bebef
LP
1094
1095 if (tmpfs_mounted)
30f5d104
LP
1096 (void) umount_verbose(LOG_ERR, template, UMOUNT_NOFOLLOW);
1097
e83bebef
LP
1098 (void) rmdir(template);
1099 return r;
1100}
b53ede69 1101
e091a5df 1102static int setup_volatile_overlay(const char *directory, uid_t uid_shift, const char *selinux_apifs_context) {
6c610aca
LP
1103 _cleanup_free_ char *buf = NULL, *escaped_directory = NULL, *escaped_upper = NULL, *escaped_work = NULL;
1104 char template[] = "/tmp/nspawn-volatile-XXXXXX";
1105 const char *upper, *work, *options;
1106 bool tmpfs_mounted = false;
1107 int r;
1108
1109 assert(directory);
1110
1111 /* --volatile=overlay means we mount an overlayfs to the root dir. */
1112
1113 if (!mkdtemp(template))
1114 return log_error_errno(errno, "Failed to create temporary directory: %m");
1115
7d85383e 1116 options = "mode=755" TMPFS_LIMITS_ROOTFS;
6c610aca
LP
1117 r = tmpfs_patch_options(options, uid_shift == 0 ? UID_INVALID : uid_shift, selinux_apifs_context, &buf);
1118 if (r < 0)
1119 goto finish;
1120 if (r > 0)
1121 options = buf;
1122
511a8cfe 1123 r = mount_nofollow_verbose(LOG_ERR, "tmpfs", template, "tmpfs", MS_STRICTATIME, options);
6c610aca
LP
1124 if (r < 0)
1125 goto finish;
1126
1127 tmpfs_mounted = true;
1128
1129 upper = strjoina(template, "/upper");
1130 work = strjoina(template, "/work");
1131
1132 if (mkdir(upper, 0755) < 0) {
1133 r = log_error_errno(errno, "Failed to create %s: %m", upper);
1134 goto finish;
1135 }
1136 if (mkdir(work, 0755) < 0) {
1137 r = log_error_errno(errno, "Failed to create %s: %m", work);
1138 goto finish;
1139 }
1140
1141 /* And now, let's overmount the root dir with an overlayfs that uses the root dir as lower dir. It's kinda nice
1142 * that the kernel allows us to do that without going through some mount point rearrangements. */
1143
1144 escaped_directory = shell_escape(directory, ",:");
1145 escaped_upper = shell_escape(upper, ",:");
1146 escaped_work = shell_escape(work, ",:");
1147 if (!escaped_directory || !escaped_upper || !escaped_work) {
1148 r = -ENOMEM;
1149 goto finish;
1150 }
1151
1152 options = strjoina("lowerdir=", escaped_directory, ",upperdir=", escaped_upper, ",workdir=", escaped_work);
511a8cfe 1153 r = mount_nofollow_verbose(LOG_ERR, "overlay", directory, "overlay", 0, options);
6c610aca
LP
1154
1155finish:
1156 if (tmpfs_mounted)
30f5d104 1157 (void) umount_verbose(LOG_ERR, template, UMOUNT_NOFOLLOW);
6c610aca
LP
1158
1159 (void) rmdir(template);
1160 return r;
1161}
1162
e5b43a04
LP
1163int setup_volatile_mode(
1164 const char *directory,
1165 VolatileMode mode,
e091a5df 1166 uid_t uid_shift,
e5b43a04
LP
1167 const char *selinux_apifs_context) {
1168
1169 switch (mode) {
1170
1171 case VOLATILE_YES:
e091a5df 1172 return setup_volatile_yes(directory, uid_shift, selinux_apifs_context);
e5b43a04
LP
1173
1174 case VOLATILE_STATE:
e091a5df 1175 return setup_volatile_state(directory, uid_shift, selinux_apifs_context);
e5b43a04 1176
6c610aca 1177 case VOLATILE_OVERLAY:
e091a5df 1178 return setup_volatile_overlay(directory, uid_shift, selinux_apifs_context);
6c610aca 1179
e5b43a04
LP
1180 default:
1181 return 0;
1182 }
1183}
1184
b53ede69
PW
1185/* Expects *pivot_root_new and *pivot_root_old to be initialised to allocated memory or NULL. */
1186int pivot_root_parse(char **pivot_root_new, char **pivot_root_old, const char *s) {
1187 _cleanup_free_ char *root_new = NULL, *root_old = NULL;
1188 const char *p = s;
1189 int r;
1190
1191 assert(pivot_root_new);
1192 assert(pivot_root_old);
1193
1194 r = extract_first_word(&p, &root_new, ":", EXTRACT_DONT_COALESCE_SEPARATORS);
1195 if (r < 0)
1196 return r;
1197 if (r == 0)
1198 return -EINVAL;
1199
1200 if (isempty(p))
1201 root_old = NULL;
1202 else {
1203 root_old = strdup(p);
1204 if (!root_old)
1205 return -ENOMEM;
1206 }
1207
1208 if (!path_is_absolute(root_new))
1209 return -EINVAL;
1210 if (root_old && !path_is_absolute(root_old))
1211 return -EINVAL;
1212
1213 free_and_replace(*pivot_root_new, root_new);
1214 free_and_replace(*pivot_root_old, root_old);
1215
1216 return 0;
1217}
1218
1219int setup_pivot_root(const char *directory, const char *pivot_root_new, const char *pivot_root_old) {
1220 _cleanup_free_ char *directory_pivot_root_new = NULL;
1221 _cleanup_free_ char *pivot_tmp_pivot_root_old = NULL;
1222 char pivot_tmp[] = "/tmp/nspawn-pivot-XXXXXX";
1223 bool remove_pivot_tmp = false;
1224 int r;
1225
1226 assert(directory);
1227
1228 if (!pivot_root_new)
1229 return 0;
1230
1231 /* Pivot pivot_root_new to / and the existing / to pivot_root_old.
1232 * If pivot_root_old is NULL, the existing / disappears.
1233 * This requires a temporary directory, pivot_tmp, which is
1234 * not a child of either.
1235 *
1236 * This is typically used for OSTree-style containers, where
1237 * the root partition contains several sysroots which could be
1238 * run. Normally, one would be chosen by the bootloader and
1239 * pivoted to / by initramfs.
1240 *
1241 * For example, for an OSTree deployment, pivot_root_new
1242 * would be: /ostree/deploy/$os/deploy/$checksum. Note that this
1243 * code doesn’t do the /var mount which OSTree expects: use
1244 * --bind +/sysroot/ostree/deploy/$os/var:/var for that.
1245 *
1246 * So in the OSTree case, we’ll end up with something like:
1247 * - directory = /tmp/nspawn-root-123456
1248 * - pivot_root_new = /ostree/deploy/os/deploy/123abc
1249 * - pivot_root_old = /sysroot
1250 * - directory_pivot_root_new =
1251 * /tmp/nspawn-root-123456/ostree/deploy/os/deploy/123abc
1252 * - pivot_tmp = /tmp/nspawn-pivot-123456
1253 * - pivot_tmp_pivot_root_old = /tmp/nspawn-pivot-123456/sysroot
1254 *
1255 * Requires all file systems at directory and below to be mounted
1256 * MS_PRIVATE or MS_SLAVE so they can be moved.
1257 */
c6134d3e
LP
1258 directory_pivot_root_new = path_join(directory, pivot_root_new);
1259 if (!directory_pivot_root_new)
1260 return log_oom();
b53ede69
PW
1261
1262 /* Remount directory_pivot_root_new to make it movable. */
511a8cfe 1263 r = mount_nofollow_verbose(LOG_ERR, directory_pivot_root_new, directory_pivot_root_new, NULL, MS_BIND, NULL);
b53ede69
PW
1264 if (r < 0)
1265 goto done;
1266
1267 if (pivot_root_old) {
1268 if (!mkdtemp(pivot_tmp)) {
1269 r = log_error_errno(errno, "Failed to create temporary directory: %m");
1270 goto done;
1271 }
1272
1273 remove_pivot_tmp = true;
c6134d3e
LP
1274 pivot_tmp_pivot_root_old = path_join(pivot_tmp, pivot_root_old);
1275 if (!pivot_tmp_pivot_root_old) {
1276 r = log_oom();
1277 goto done;
1278 }
b53ede69 1279
511a8cfe 1280 r = mount_nofollow_verbose(LOG_ERR, directory_pivot_root_new, pivot_tmp, NULL, MS_MOVE, NULL);
b53ede69
PW
1281 if (r < 0)
1282 goto done;
1283
511a8cfe 1284 r = mount_nofollow_verbose(LOG_ERR, directory, pivot_tmp_pivot_root_old, NULL, MS_MOVE, NULL);
b53ede69
PW
1285 if (r < 0)
1286 goto done;
1287
511a8cfe 1288 r = mount_nofollow_verbose(LOG_ERR, pivot_tmp, directory, NULL, MS_MOVE, NULL);
b53ede69
PW
1289 if (r < 0)
1290 goto done;
1291 } else {
511a8cfe 1292 r = mount_nofollow_verbose(LOG_ERR, directory_pivot_root_new, directory, NULL, MS_MOVE, NULL);
b53ede69
PW
1293 if (r < 0)
1294 goto done;
1295 }
1296
1297done:
1298 if (remove_pivot_tmp)
1299 (void) rmdir(pivot_tmp);
1300
1301 return r;
1302}