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