]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/nspawn/nspawn-mount.c
9b7ceb6bdc7b4768bafac900f3ce35a093c2520f
[thirdparty/systemd.git] / src / nspawn / nspawn-mount.c
1 /***
2 This file is part of systemd.
3
4 Copyright 2015 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <sys/mount.h>
21 #include <linux/magic.h>
22
23 #include "alloc-util.h"
24 #include "escape.h"
25 #include "fd-util.h"
26 #include "fileio.h"
27 #include "fs-util.h"
28 #include "label.h"
29 #include "mkdir.h"
30 #include "mount-util.h"
31 #include "nspawn-mount.h"
32 #include "parse-util.h"
33 #include "path-util.h"
34 #include "rm-rf.h"
35 #include "set.h"
36 #include "stat-util.h"
37 #include "string-util.h"
38 #include "strv.h"
39 #include "user-util.h"
40 #include "util.h"
41
42 CustomMount* custom_mount_add(CustomMount **l, unsigned *n, CustomMountType t) {
43 CustomMount *c, *ret;
44
45 assert(l);
46 assert(n);
47 assert(t >= 0);
48 assert(t < _CUSTOM_MOUNT_TYPE_MAX);
49
50 c = realloc_multiply(*l, (*n + 1), sizeof(CustomMount));
51 if (!c)
52 return NULL;
53
54 *l = c;
55 ret = *l + *n;
56 (*n)++;
57
58 *ret = (CustomMount) { .type = t };
59
60 return ret;
61 }
62
63 void custom_mount_free_all(CustomMount *l, unsigned n) {
64 unsigned i;
65
66 for (i = 0; i < n; i++) {
67 CustomMount *m = l + i;
68
69 free(m->source);
70 free(m->destination);
71 free(m->options);
72
73 if (m->work_dir) {
74 (void) rm_rf(m->work_dir, REMOVE_ROOT|REMOVE_PHYSICAL);
75 free(m->work_dir);
76 }
77
78 if (m->rm_rf_tmpdir) {
79 (void) rm_rf(m->rm_rf_tmpdir, REMOVE_ROOT|REMOVE_PHYSICAL);
80 free(m->rm_rf_tmpdir);
81 }
82
83 strv_free(m->lower);
84 }
85
86 free(l);
87 }
88
89 static int custom_mount_compare(const void *a, const void *b) {
90 const CustomMount *x = a, *y = b;
91 int r;
92
93 r = path_compare(x->destination, y->destination);
94 if (r != 0)
95 return r;
96
97 if (x->type < y->type)
98 return -1;
99 if (x->type > y->type)
100 return 1;
101
102 return 0;
103 }
104
105 static bool source_path_is_valid(const char *p) {
106 assert(p);
107
108 if (*p == '+')
109 p++;
110
111 return path_is_absolute(p);
112 }
113
114 static char *resolve_source_path(const char *dest, const char *source) {
115
116 if (!source)
117 return NULL;
118
119 if (source[0] == '+')
120 return prefix_root(dest, source + 1);
121
122 return strdup(source);
123 }
124
125 int custom_mount_prepare_all(const char *dest, CustomMount *l, unsigned n) {
126 unsigned i;
127 int r;
128
129 /* Prepare all custom mounts. This will make source we know all temporary directories. This is called in the
130 * parent process, so that we know the temporary directories to remove on exit before we fork off the
131 * children. */
132
133 assert(l || n == 0);
134
135 /* Order the custom mounts, and make sure we have a working directory */
136 qsort_safe(l, n, sizeof(CustomMount), custom_mount_compare);
137
138 for (i = 0; i < n; i++) {
139 CustomMount *m = l + i;
140
141 if (m->source) {
142 char *s;
143
144 s = resolve_source_path(dest, m->source);
145 if (!s)
146 return log_oom();
147
148 free(m->source);
149 m->source = s;
150 } else {
151 /* No source specified? In that case, use a throw-away temporary directory in /var/tmp */
152
153 m->rm_rf_tmpdir = strdup("/var/tmp/nspawn-temp-XXXXXX");
154 if (!m->rm_rf_tmpdir)
155 return log_oom();
156
157 if (!mkdtemp(m->rm_rf_tmpdir)) {
158 m->rm_rf_tmpdir = mfree(m->rm_rf_tmpdir);
159 return log_error_errno(errno, "Failed to acquire temporary directory: %m");
160 }
161
162 m->source = strjoin(m->rm_rf_tmpdir, "/src");
163 if (!m->source)
164 return log_oom();
165
166 if (mkdir(m->source, 0755) < 0)
167 return log_error_errno(errno, "Failed to create %s: %m", m->source);
168 }
169
170 if (m->type == CUSTOM_MOUNT_OVERLAY) {
171 char **j;
172
173 STRV_FOREACH(j, m->lower) {
174 char *s;
175
176 s = resolve_source_path(dest, *j);
177 if (!s)
178 return log_oom();
179
180 free(*j);
181 *j = s;
182 }
183
184 if (m->work_dir) {
185 char *s;
186
187 s = resolve_source_path(dest, m->work_dir);
188 if (!s)
189 return log_oom();
190
191 free(m->work_dir);
192 m->work_dir = s;
193 } else {
194 assert(m->source);
195
196 r = tempfn_random(m->source, NULL, &m->work_dir);
197 if (r < 0)
198 return log_error_errno(r, "Failed to acquire working directory: %m");
199 }
200
201 (void) mkdir_label(m->work_dir, 0700);
202 }
203 }
204
205 return 0;
206 }
207
208 int bind_mount_parse(CustomMount **l, unsigned *n, const char *s, bool read_only) {
209 _cleanup_free_ char *source = NULL, *destination = NULL, *opts = NULL;
210 const char *p = s;
211 CustomMount *m;
212 int r;
213
214 assert(l);
215 assert(n);
216
217 r = extract_many_words(&p, ":", EXTRACT_DONT_COALESCE_SEPARATORS, &source, &destination, NULL);
218 if (r < 0)
219 return r;
220 if (r == 0)
221 return -EINVAL;
222 if (r == 1) {
223 destination = strdup(source[0] == '+' ? source+1 : source);
224 if (!destination)
225 return -ENOMEM;
226 }
227 if (r == 2 && !isempty(p)) {
228 opts = strdup(p);
229 if (!opts)
230 return -ENOMEM;
231 }
232
233 if (isempty(source))
234 source = NULL;
235 else if (!source_path_is_valid(source))
236 return -EINVAL;
237
238 if (!path_is_absolute(destination))
239 return -EINVAL;
240
241 m = custom_mount_add(l, n, CUSTOM_MOUNT_BIND);
242 if (!m)
243 return -ENOMEM;
244
245 m->source = source;
246 m->destination = destination;
247 m->read_only = read_only;
248 m->options = opts;
249
250 source = destination = opts = NULL;
251 return 0;
252 }
253
254 int tmpfs_mount_parse(CustomMount **l, unsigned *n, const char *s) {
255 _cleanup_free_ char *path = NULL, *opts = NULL;
256 const char *p = s;
257 CustomMount *m;
258 int r;
259
260 assert(l);
261 assert(n);
262 assert(s);
263
264 r = extract_first_word(&p, &path, ":", EXTRACT_DONT_COALESCE_SEPARATORS);
265 if (r < 0)
266 return r;
267 if (r == 0)
268 return -EINVAL;
269
270 if (isempty(p))
271 opts = strdup("mode=0755");
272 else
273 opts = strdup(p);
274 if (!opts)
275 return -ENOMEM;
276
277 if (!path_is_absolute(path))
278 return -EINVAL;
279
280 m = custom_mount_add(l, n, CUSTOM_MOUNT_TMPFS);
281 if (!m)
282 return -ENOMEM;
283
284 m->destination = path;
285 m->options = opts;
286
287 path = opts = NULL;
288 return 0;
289 }
290
291 int overlay_mount_parse(CustomMount **l, unsigned *n, const char *s, bool read_only) {
292 _cleanup_free_ char *upper = NULL, *destination = NULL;
293 _cleanup_strv_free_ char **lower = NULL;
294 CustomMount *m;
295 int k;
296
297 k = strv_split_extract(&lower, s, ":", EXTRACT_DONT_COALESCE_SEPARATORS);
298 if (k < 0)
299 return k;
300 if (k < 2)
301 return -EADDRNOTAVAIL;
302 if (k == 2) {
303 /* If two parameters are specified, the first one is the lower, the second one the upper directory. And
304 * we'll also define the destination mount point the same as the upper. */
305
306 if (!source_path_is_valid(lower[0]) ||
307 !source_path_is_valid(lower[1]))
308 return -EINVAL;
309
310 upper = lower[1];
311 lower[1] = NULL;
312
313 destination = strdup(upper[0] == '+' ? upper+1 : upper); /* take the destination without "+" prefix */
314 if (!destination)
315 return -ENOMEM;
316 } else {
317 char **i;
318
319 /* If more than two parameters are specified, the last one is the destination, the second to last one
320 * the "upper", and all before that the "lower" directories. */
321
322 destination = lower[k - 1];
323 upper = lower[k - 2];
324 lower[k - 2] = NULL;
325
326 STRV_FOREACH(i, lower)
327 if (!source_path_is_valid(*i))
328 return -EINVAL;
329
330 /* If the upper directory is unspecified, then let's create it automatically as a throw-away directory
331 * in /var/tmp */
332 if (isempty(upper))
333 upper = NULL;
334 else if (!source_path_is_valid(upper))
335 return -EINVAL;
336
337 if (!path_is_absolute(destination))
338 return -EINVAL;
339 }
340
341 m = custom_mount_add(l, n, CUSTOM_MOUNT_OVERLAY);
342 if (!m)
343 return -ENOMEM;
344
345 m->destination = destination;
346 m->source = upper;
347 m->lower = lower;
348 m->read_only = read_only;
349
350 upper = destination = NULL;
351 lower = NULL;
352
353 return 0;
354 }
355
356 static int tmpfs_patch_options(
357 const char *options,
358 bool userns,
359 uid_t uid_shift, uid_t uid_range,
360 bool patch_ids,
361 const char *selinux_apifs_context,
362 char **ret) {
363
364 char *buf = NULL;
365
366 if ((userns && uid_shift != 0) || patch_ids) {
367 assert(uid_shift != UID_INVALID);
368
369 if (asprintf(&buf, "%s%suid=" UID_FMT ",gid=" UID_FMT,
370 options ?: "", options ? "," : "",
371 uid_shift, uid_shift) < 0)
372 return -ENOMEM;
373
374 options = buf;
375 }
376
377 #if HAVE_SELINUX
378 if (selinux_apifs_context) {
379 char *t;
380
381 t = strjoin(options ?: "", options ? "," : "",
382 "context=\"", selinux_apifs_context, "\"");
383 free(buf);
384 if (!t)
385 return -ENOMEM;
386
387 buf = t;
388 }
389 #endif
390
391 if (!buf && options) {
392 buf = strdup(options);
393 if (!buf)
394 return -ENOMEM;
395 }
396 *ret = buf;
397
398 return !!buf;
399 }
400
401 int mount_sysfs(const char *dest, MountSettingsMask mount_settings) {
402 const char *full, *top, *x;
403 int r;
404 unsigned long extra_flags = 0;
405
406 top = prefix_roota(dest, "/sys");
407 r = path_check_fstype(top, SYSFS_MAGIC);
408 if (r < 0)
409 return log_error_errno(r, "Failed to determine filesystem type of %s: %m", top);
410 /* /sys might already be mounted as sysfs by the outer child in the
411 * !netns case. In this case, it's all good. Don't touch it because we
412 * don't have the right to do so, see https://github.com/systemd/systemd/issues/1555.
413 */
414 if (r > 0)
415 return 0;
416
417 full = prefix_roota(top, "/full");
418
419 (void) mkdir(full, 0755);
420
421 if (mount_settings & MOUNT_APPLY_APIVFS_RO)
422 extra_flags |= MS_RDONLY;
423
424 r = mount_verbose(LOG_ERR, "sysfs", full, "sysfs",
425 MS_NOSUID|MS_NOEXEC|MS_NODEV|extra_flags, NULL);
426 if (r < 0)
427 return r;
428
429 FOREACH_STRING(x, "block", "bus", "class", "dev", "devices", "kernel") {
430 _cleanup_free_ char *from = NULL, *to = NULL;
431
432 from = prefix_root(full, x);
433 if (!from)
434 return log_oom();
435
436 to = prefix_root(top, x);
437 if (!to)
438 return log_oom();
439
440 (void) mkdir(to, 0755);
441
442 r = mount_verbose(LOG_ERR, from, to, NULL, MS_BIND, NULL);
443 if (r < 0)
444 return r;
445
446 r = mount_verbose(LOG_ERR, NULL, to, NULL,
447 MS_BIND|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT|extra_flags, NULL);
448 if (r < 0)
449 return r;
450 }
451
452 r = umount_verbose(full);
453 if (r < 0)
454 return r;
455
456 if (rmdir(full) < 0)
457 return log_error_errno(errno, "Failed to remove %s: %m", full);
458
459 /* Create mountpoint for cgroups. Otherwise we are not allowed since we
460 * remount /sys read-only.
461 */
462 if (cg_ns_supported()) {
463 x = prefix_roota(top, "/fs/cgroup");
464 (void) mkdir_p(x, 0755);
465 }
466
467 return mount_verbose(LOG_ERR, NULL, top, NULL,
468 MS_BIND|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT|extra_flags, NULL);
469 }
470
471 static int mkdir_userns(const char *path, mode_t mode, MountSettingsMask mask, uid_t uid_shift) {
472 int r;
473
474 assert(path);
475
476 r = mkdir(path, mode);
477 if (r < 0 && errno != EEXIST)
478 return -errno;
479
480 if ((mask & MOUNT_USE_USERNS) == 0)
481 return 0;
482
483 if (mask & MOUNT_IN_USERNS)
484 return 0;
485
486 r = lchown(path, uid_shift, uid_shift);
487 if (r < 0)
488 return -errno;
489
490 return 0;
491 }
492
493 static int mkdir_userns_p(const char *prefix, const char *path, mode_t mode, MountSettingsMask mask, uid_t uid_shift) {
494 const char *p, *e;
495 int r;
496
497 assert(path);
498
499 if (prefix && !path_startswith(path, prefix))
500 return -ENOTDIR;
501
502 /* create every parent directory in the path, except the last component */
503 p = path + strspn(path, "/");
504 for (;;) {
505 char t[strlen(path) + 1];
506
507 e = p + strcspn(p, "/");
508 p = e + strspn(e, "/");
509
510 /* Is this the last component? If so, then we're done */
511 if (*p == 0)
512 break;
513
514 memcpy(t, path, e - path);
515 t[e-path] = 0;
516
517 if (prefix && path_startswith(prefix, t))
518 continue;
519
520 r = mkdir_userns(t, mode, mask, uid_shift);
521 if (r < 0)
522 return r;
523 }
524
525 return mkdir_userns(path, mode, mask, uid_shift);
526 }
527
528 int mount_all(const char *dest,
529 MountSettingsMask mount_settings,
530 uid_t uid_shift, uid_t uid_range,
531 const char *selinux_apifs_context) {
532
533 typedef struct MountPoint {
534 const char *what;
535 const char *where;
536 const char *type;
537 const char *options;
538 unsigned long flags;
539 MountSettingsMask mount_settings;
540 } MountPoint;
541
542 static const MountPoint mount_table[] = {
543 /* inner child mounts */
544 { "proc", "/proc", "proc", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV, MOUNT_FATAL|MOUNT_IN_USERNS },
545 { "/proc/sys", "/proc/sys", NULL, NULL, MS_BIND, MOUNT_FATAL|MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO }, /* Bind mount first ... */
546 { "/proc/sys/net", "/proc/sys/net", NULL, NULL, MS_BIND, MOUNT_FATAL|MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO|MOUNT_APPLY_APIVFS_NETNS }, /* (except for this) */
547 { NULL, "/proc/sys", NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT, MOUNT_FATAL|MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO }, /* ... then, make it r/o */
548 { "/proc/sysrq-trigger", "/proc/sysrq-trigger", NULL, NULL, MS_BIND, MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO }, /* Bind mount first ... */
549 { NULL, "/proc/sysrq-trigger", NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT, MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO }, /* ... then, make it r/o */
550
551 /* outer child mounts */
552 { "tmpfs", "/tmp", "tmpfs", "mode=1777", MS_NOSUID|MS_NODEV|MS_STRICTATIME, MOUNT_FATAL },
553 { "tmpfs", "/sys", "tmpfs", "mode=755", MS_NOSUID|MS_NOEXEC|MS_NODEV, MOUNT_FATAL|MOUNT_APPLY_APIVFS_NETNS },
554 { "sysfs", "/sys", "sysfs", NULL, MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV, MOUNT_FATAL|MOUNT_APPLY_APIVFS_RO }, /* skipped if above was mounted */
555 { "sysfs", "/sys", "sysfs", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV, MOUNT_FATAL }, /* skipped if above was mounted */
556
557 { "tmpfs", "/dev", "tmpfs", "mode=755", MS_NOSUID|MS_STRICTATIME, MOUNT_FATAL },
558 { "tmpfs", "/dev/shm", "tmpfs", "mode=1777", MS_NOSUID|MS_NODEV|MS_STRICTATIME, MOUNT_FATAL },
559 { "tmpfs", "/run", "tmpfs", "mode=755", MS_NOSUID|MS_NODEV|MS_STRICTATIME, MOUNT_FATAL },
560 #if HAVE_SELINUX
561 { "/sys/fs/selinux", "/sys/fs/selinux", NULL, NULL, MS_BIND, 0 }, /* Bind mount first */
562 { NULL, "/sys/fs/selinux", NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT, 0 }, /* Then, make it r/o */
563 #endif
564 };
565
566 unsigned k;
567 int r;
568 bool use_userns = (mount_settings & MOUNT_USE_USERNS);
569 bool netns = (mount_settings & MOUNT_APPLY_APIVFS_NETNS);
570 bool ro = (mount_settings & MOUNT_APPLY_APIVFS_RO);
571 bool in_userns = (mount_settings & MOUNT_IN_USERNS);
572
573 for (k = 0; k < ELEMENTSOF(mount_table); k++) {
574 _cleanup_free_ char *where = NULL, *options = NULL;
575 const char *o;
576 bool fatal = (mount_table[k].mount_settings & MOUNT_FATAL);
577
578 if (in_userns != (bool)(mount_table[k].mount_settings & MOUNT_IN_USERNS))
579 continue;
580
581 if (!netns && (bool)(mount_table[k].mount_settings & MOUNT_APPLY_APIVFS_NETNS))
582 continue;
583
584 if (!ro && (bool)(mount_table[k].mount_settings & MOUNT_APPLY_APIVFS_RO))
585 continue;
586
587 r = chase_symlinks(mount_table[k].where, dest, CHASE_NONEXISTENT|CHASE_PREFIX_ROOT, &where);
588 if (r < 0)
589 return log_error_errno(r, "Failed to resolve %s/%s: %m", dest, mount_table[k].where);
590
591 r = path_is_mount_point(where, NULL, 0);
592 if (r < 0 && r != -ENOENT)
593 return log_error_errno(r, "Failed to detect whether %s is a mount point: %m", where);
594
595 /* Skip this entry if it is not a remount. */
596 if (mount_table[k].what && r > 0)
597 continue;
598
599 r = mkdir_userns_p(dest, where, 0755, mount_settings, uid_shift);
600 if (r < 0 && r != -EEXIST) {
601 if (fatal && r != -EROFS)
602 return log_error_errno(r, "Failed to create directory %s: %m", where);
603
604 log_debug_errno(r, "Failed to create directory %s: %m", where);
605 /* If we failed mkdir() or chown() due to the root
606 * directory being read only, attempt to mount this fs
607 * anyway and let mount_verbose log any errors */
608 if (r != -EROFS)
609 continue;
610 }
611
612 o = mount_table[k].options;
613 if (streq_ptr(mount_table[k].type, "tmpfs")) {
614 if (in_userns)
615 r = tmpfs_patch_options(o, use_userns, 0, uid_range, true, selinux_apifs_context, &options);
616 else
617 r = tmpfs_patch_options(o, use_userns, uid_shift, uid_range, false, selinux_apifs_context, &options);
618 if (r < 0)
619 return log_oom();
620 if (r > 0)
621 o = options;
622 }
623
624 r = mount_verbose(fatal ? LOG_ERR : LOG_DEBUG,
625 mount_table[k].what,
626 where,
627 mount_table[k].type,
628 mount_table[k].flags,
629 o);
630 if (r < 0 && fatal)
631 return r;
632 }
633
634 return 0;
635 }
636
637 static int parse_mount_bind_options(const char *options, unsigned long *mount_flags, char **mount_opts) {
638 const char *p = options;
639 unsigned long flags = *mount_flags;
640 char *opts = NULL;
641 int r;
642
643 assert(options);
644
645 for (;;) {
646 _cleanup_free_ char *word = NULL;
647
648 r = extract_first_word(&p, &word, ",", 0);
649 if (r < 0)
650 return log_error_errno(r, "Failed to extract mount option: %m");
651 if (r == 0)
652 break;
653
654 if (streq(word, "rbind"))
655 flags |= MS_REC;
656 else if (streq(word, "norbind"))
657 flags &= ~MS_REC;
658 else {
659 log_error("Invalid bind mount option: %s", word);
660 return -EINVAL;
661 }
662 }
663
664 *mount_flags = flags;
665 /* in the future mount_opts will hold string options for mount(2) */
666 *mount_opts = opts;
667
668 return 0;
669 }
670
671 static int mount_bind(const char *dest, CustomMount *m) {
672
673 _cleanup_free_ char *mount_opts = NULL, *where = NULL;
674 unsigned long mount_flags = MS_BIND | MS_REC;
675 struct stat source_st, dest_st;
676 int r;
677
678 assert(dest);
679 assert(m);
680
681 if (m->options) {
682 r = parse_mount_bind_options(m->options, &mount_flags, &mount_opts);
683 if (r < 0)
684 return r;
685 }
686
687 if (stat(m->source, &source_st) < 0)
688 return log_error_errno(errno, "Failed to stat %s: %m", m->source);
689
690 r = chase_symlinks(m->destination, dest, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT, &where);
691 if (r < 0)
692 return log_error_errno(r, "Failed to resolve %s/%s: %m", dest, m->destination);
693 if (r > 0) { /* Path exists already? */
694
695 if (stat(where, &dest_st) < 0)
696 return log_error_errno(errno, "Failed to stat %s: %m", where);
697
698 if (S_ISDIR(source_st.st_mode) && !S_ISDIR(dest_st.st_mode)) {
699 log_error("Cannot bind mount directory %s on file %s.", m->source, where);
700 return -EINVAL;
701 }
702
703 if (!S_ISDIR(source_st.st_mode) && S_ISDIR(dest_st.st_mode)) {
704 log_error("Cannot bind mount file %s on directory %s.", m->source, where);
705 return -EINVAL;
706 }
707
708 } else { /* Path doesn't exist yet? */
709 r = mkdir_parents_label(where, 0755);
710 if (r < 0)
711 return log_error_errno(r, "Failed to make parents of %s: %m", where);
712
713 /* Create the mount point. Any non-directory file can be
714 * mounted on any non-directory file (regular, fifo, socket,
715 * char, block).
716 */
717 if (S_ISDIR(source_st.st_mode))
718 r = mkdir_label(where, 0755);
719 else
720 r = touch(where);
721 if (r < 0)
722 return log_error_errno(r, "Failed to create mount point %s: %m", where);
723
724 }
725
726 r = mount_verbose(LOG_ERR, m->source, where, NULL, mount_flags, mount_opts);
727 if (r < 0)
728 return r;
729
730 if (m->read_only) {
731 r = bind_remount_recursive(where, true, NULL);
732 if (r < 0)
733 return log_error_errno(r, "Read-only bind mount failed: %m");
734 }
735
736 return 0;
737 }
738
739 static int mount_tmpfs(
740 const char *dest,
741 CustomMount *m,
742 bool userns, uid_t uid_shift, uid_t uid_range,
743 const char *selinux_apifs_context) {
744
745 const char *options;
746 _cleanup_free_ char *buf = NULL, *where = NULL;
747 int r;
748
749 assert(dest);
750 assert(m);
751
752 r = chase_symlinks(m->destination, dest, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT, &where);
753 if (r < 0)
754 return log_error_errno(r, "Failed to resolve %s/%s: %m", dest, m->destination);
755 if (r == 0) { /* Doesn't exist yet? */
756 r = mkdir_p_label(where, 0755);
757 if (r < 0)
758 return log_error_errno(r, "Creating mount point for tmpfs %s failed: %m", where);
759 }
760
761 r = tmpfs_patch_options(m->options, userns, uid_shift, uid_range, false, selinux_apifs_context, &buf);
762 if (r < 0)
763 return log_oom();
764 options = r > 0 ? buf : m->options;
765
766 return mount_verbose(LOG_ERR, "tmpfs", where, "tmpfs", MS_NODEV|MS_STRICTATIME, options);
767 }
768
769 static char *joined_and_escaped_lower_dirs(char **lower) {
770 _cleanup_strv_free_ char **sv = NULL;
771
772 sv = strv_copy(lower);
773 if (!sv)
774 return NULL;
775
776 strv_reverse(sv);
777
778 if (!strv_shell_escape(sv, ",:"))
779 return NULL;
780
781 return strv_join(sv, ":");
782 }
783
784 static int mount_overlay(const char *dest, CustomMount *m) {
785
786 _cleanup_free_ char *lower = NULL, *where = NULL, *escaped_source = NULL;
787 const char *options;
788 int r;
789
790 assert(dest);
791 assert(m);
792
793 r = chase_symlinks(m->destination, dest, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT, &where);
794 if (r < 0)
795 return log_error_errno(r, "Failed to resolve %s/%s: %m", dest, m->destination);
796 if (r == 0) { /* Doesn't exist yet? */
797 r = mkdir_label(where, 0755);
798 if (r < 0)
799 return log_error_errno(r, "Creating mount point for overlay %s failed: %m", where);
800 }
801
802 (void) mkdir_p_label(m->source, 0755);
803
804 lower = joined_and_escaped_lower_dirs(m->lower);
805 if (!lower)
806 return log_oom();
807
808 escaped_source = shell_escape(m->source, ",:");
809 if (!escaped_source)
810 return log_oom();
811
812 if (m->read_only)
813 options = strjoina("lowerdir=", escaped_source, ":", lower);
814 else {
815 _cleanup_free_ char *escaped_work_dir = NULL;
816
817 escaped_work_dir = shell_escape(m->work_dir, ",:");
818 if (!escaped_work_dir)
819 return log_oom();
820
821 options = strjoina("lowerdir=", lower, ",upperdir=", escaped_source, ",workdir=", escaped_work_dir);
822 }
823
824 return mount_verbose(LOG_ERR, "overlay", where, "overlay", m->read_only ? MS_RDONLY : 0, options);
825 }
826
827 int mount_custom(
828 const char *dest,
829 CustomMount *mounts, unsigned n,
830 bool userns, uid_t uid_shift, uid_t uid_range,
831 const char *selinux_apifs_context) {
832
833 unsigned i;
834 int r;
835
836 assert(dest);
837
838 for (i = 0; i < n; i++) {
839 CustomMount *m = mounts + i;
840
841 switch (m->type) {
842
843 case CUSTOM_MOUNT_BIND:
844 r = mount_bind(dest, m);
845 break;
846
847 case CUSTOM_MOUNT_TMPFS:
848 r = mount_tmpfs(dest, m, userns, uid_shift, uid_range, selinux_apifs_context);
849 break;
850
851 case CUSTOM_MOUNT_OVERLAY:
852 r = mount_overlay(dest, m);
853 break;
854
855 default:
856 assert_not_reached("Unknown custom mount type");
857 }
858
859 if (r < 0)
860 return r;
861 }
862
863 return 0;
864 }
865
866 /* Retrieve existing subsystems. This function is called in a new cgroup
867 * namespace.
868 */
869 static int get_controllers(Set *subsystems) {
870 _cleanup_fclose_ FILE *f = NULL;
871 char line[LINE_MAX];
872
873 assert(subsystems);
874
875 f = fopen("/proc/self/cgroup", "re");
876 if (!f)
877 return errno == ENOENT ? -ESRCH : -errno;
878
879 FOREACH_LINE(line, f, return -errno) {
880 int r;
881 char *e, *l, *p;
882
883 l = strchr(line, ':');
884 if (!l)
885 continue;
886
887 l++;
888 e = strchr(l, ':');
889 if (!e)
890 continue;
891
892 *e = 0;
893
894 if (STR_IN_SET(l, "", "name=systemd", "name=unified"))
895 continue;
896
897 p = strdup(l);
898 if (!p)
899 return -ENOMEM;
900
901 r = set_consume(subsystems, p);
902 if (r < 0)
903 return r;
904 }
905
906 return 0;
907 }
908
909 static int mount_legacy_cgroup_hierarchy(
910 const char *dest,
911 const char *controller,
912 const char *hierarchy,
913 bool read_only) {
914
915 const char *to, *fstype, *opts;
916 int r;
917
918 to = strjoina(strempty(dest), "/sys/fs/cgroup/", hierarchy);
919
920 r = path_is_mount_point(to, dest, 0);
921 if (r < 0 && r != -ENOENT)
922 return log_error_errno(r, "Failed to determine if %s is mounted already: %m", to);
923 if (r > 0)
924 return 0;
925
926 mkdir_p(to, 0755);
927
928 /* The superblock mount options of the mount point need to be
929 * identical to the hosts', and hence writable... */
930 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER_HYBRID)) {
931 fstype = "cgroup2";
932 opts = NULL;
933 } else if (streq(controller, SYSTEMD_CGROUP_CONTROLLER_LEGACY)) {
934 fstype = "cgroup";
935 opts = "none,name=systemd,xattr";
936 } else {
937 fstype = "cgroup";
938 opts = controller;
939 }
940
941 r = mount_verbose(LOG_ERR, "cgroup", to, fstype, MS_NOSUID|MS_NOEXEC|MS_NODEV, opts);
942 if (r < 0)
943 return r;
944
945 /* ... hence let's only make the bind mount read-only, not the superblock. */
946 if (read_only) {
947 r = mount_verbose(LOG_ERR, NULL, to, NULL,
948 MS_BIND|MS_REMOUNT|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_RDONLY, NULL);
949 if (r < 0)
950 return r;
951 }
952
953 return 1;
954 }
955
956 /* Mount a legacy cgroup hierarchy when cgroup namespaces are supported. */
957 static int mount_legacy_cgns_supported(
958 const char *dest,
959 CGroupUnified unified_requested,
960 bool userns,
961 uid_t uid_shift,
962 uid_t uid_range,
963 const char *selinux_apifs_context) {
964
965 _cleanup_set_free_free_ Set *controllers = NULL;
966 const char *cgroup_root = "/sys/fs/cgroup", *c;
967 int r;
968
969 (void) mkdir_p(cgroup_root, 0755);
970
971 /* Mount a tmpfs to /sys/fs/cgroup if it's not mounted there yet. */
972 r = path_is_mount_point(cgroup_root, dest, AT_SYMLINK_FOLLOW);
973 if (r < 0)
974 return log_error_errno(r, "Failed to determine if /sys/fs/cgroup is already mounted: %m");
975 if (r == 0) {
976 _cleanup_free_ char *options = NULL;
977
978 /* When cgroup namespaces are enabled and user namespaces are
979 * used then the mount of the cgroupfs is done *inside* the new
980 * user namespace. We're root in the new user namespace and the
981 * kernel will happily translate our uid/gid to the correct
982 * uid/gid as seen from e.g. /proc/1/mountinfo. So we simply
983 * pass uid 0 and not uid_shift to tmpfs_patch_options().
984 */
985 r = tmpfs_patch_options("mode=755", userns, 0, uid_range, true, selinux_apifs_context, &options);
986 if (r < 0)
987 return log_oom();
988
989 r = mount_verbose(LOG_ERR, "tmpfs", cgroup_root, "tmpfs",
990 MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME, options);
991 if (r < 0)
992 return r;
993 }
994
995 r = cg_all_unified();
996 if (r < 0)
997 return r;
998 if (r > 0)
999 goto skip_controllers;
1000
1001 controllers = set_new(&string_hash_ops);
1002 if (!controllers)
1003 return log_oom();
1004
1005 r = get_controllers(controllers);
1006 if (r < 0)
1007 return log_error_errno(r, "Failed to determine cgroup controllers: %m");
1008
1009 for (;;) {
1010 _cleanup_free_ const char *controller = NULL;
1011
1012 controller = set_steal_first(controllers);
1013 if (!controller)
1014 break;
1015
1016 r = mount_legacy_cgroup_hierarchy("", controller, controller, !userns);
1017 if (r < 0)
1018 return r;
1019
1020 /* When multiple hierarchies are co-mounted, make their
1021 * constituting individual hierarchies a symlink to the
1022 * co-mount.
1023 */
1024 c = controller;
1025 for (;;) {
1026 _cleanup_free_ char *target = NULL, *tok = NULL;
1027
1028 r = extract_first_word(&c, &tok, ",", 0);
1029 if (r < 0)
1030 return log_error_errno(r, "Failed to extract co-mounted cgroup controller: %m");
1031 if (r == 0)
1032 break;
1033
1034 target = prefix_root("/sys/fs/cgroup", tok);
1035 if (!target)
1036 return log_oom();
1037
1038 if (streq(controller, tok))
1039 break;
1040
1041 r = symlink_idempotent(controller, target);
1042 if (r == -EINVAL)
1043 return log_error_errno(r, "Invalid existing symlink for combined hierarchy: %m");
1044 if (r < 0)
1045 return log_error_errno(r, "Failed to create symlink for combined hierarchy: %m");
1046 }
1047 }
1048
1049 skip_controllers:
1050 if (unified_requested >= CGROUP_UNIFIED_SYSTEMD) {
1051 r = mount_legacy_cgroup_hierarchy("", SYSTEMD_CGROUP_CONTROLLER_HYBRID, "unified", false);
1052 if (r < 0)
1053 return r;
1054 }
1055
1056 r = mount_legacy_cgroup_hierarchy("", SYSTEMD_CGROUP_CONTROLLER_LEGACY, "systemd", false);
1057 if (r < 0)
1058 return r;
1059
1060 if (!userns)
1061 return mount_verbose(LOG_ERR, NULL, cgroup_root, NULL,
1062 MS_REMOUNT|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME|MS_RDONLY, "mode=755");
1063
1064 return 0;
1065 }
1066
1067 /* Mount legacy cgroup hierarchy when cgroup namespaces are unsupported. */
1068 static int mount_legacy_cgns_unsupported(
1069 const char *dest,
1070 CGroupUnified unified_requested,
1071 bool userns,
1072 uid_t uid_shift,
1073 uid_t uid_range,
1074 const char *selinux_apifs_context) {
1075
1076 _cleanup_set_free_free_ Set *controllers = NULL;
1077 const char *cgroup_root;
1078 int r;
1079
1080 cgroup_root = prefix_roota(dest, "/sys/fs/cgroup");
1081
1082 (void) mkdir_p(cgroup_root, 0755);
1083
1084 /* Mount a tmpfs to /sys/fs/cgroup if it's not mounted there yet. */
1085 r = path_is_mount_point(cgroup_root, dest, AT_SYMLINK_FOLLOW);
1086 if (r < 0)
1087 return log_error_errno(r, "Failed to determine if /sys/fs/cgroup is already mounted: %m");
1088 if (r == 0) {
1089 _cleanup_free_ char *options = NULL;
1090
1091 r = tmpfs_patch_options("mode=755", userns, uid_shift, uid_range, false, selinux_apifs_context, &options);
1092 if (r < 0)
1093 return log_oom();
1094
1095 r = mount_verbose(LOG_ERR, "tmpfs", cgroup_root, "tmpfs",
1096 MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME, options);
1097 if (r < 0)
1098 return r;
1099 }
1100
1101 r = cg_all_unified();
1102 if (r < 0)
1103 return r;
1104 if (r > 0)
1105 goto skip_controllers;
1106
1107 controllers = set_new(&string_hash_ops);
1108 if (!controllers)
1109 return log_oom();
1110
1111 r = cg_kernel_controllers(controllers);
1112 if (r < 0)
1113 return log_error_errno(r, "Failed to determine cgroup controllers: %m");
1114
1115 for (;;) {
1116 _cleanup_free_ char *controller = NULL, *origin = NULL, *combined = NULL;
1117
1118 controller = set_steal_first(controllers);
1119 if (!controller)
1120 break;
1121
1122 origin = prefix_root("/sys/fs/cgroup/", controller);
1123 if (!origin)
1124 return log_oom();
1125
1126 r = readlink_malloc(origin, &combined);
1127 if (r == -EINVAL) {
1128 /* Not a symbolic link, but directly a single cgroup hierarchy */
1129
1130 r = mount_legacy_cgroup_hierarchy(dest, controller, controller, true);
1131 if (r < 0)
1132 return r;
1133
1134 } else if (r < 0)
1135 return log_error_errno(r, "Failed to read link %s: %m", origin);
1136 else {
1137 _cleanup_free_ char *target = NULL;
1138
1139 target = prefix_root(dest, origin);
1140 if (!target)
1141 return log_oom();
1142
1143 /* A symbolic link, a combination of controllers in one hierarchy */
1144
1145 if (!filename_is_valid(combined)) {
1146 log_warning("Ignoring invalid combined hierarchy %s.", combined);
1147 continue;
1148 }
1149
1150 r = mount_legacy_cgroup_hierarchy(dest, combined, combined, true);
1151 if (r < 0)
1152 return r;
1153
1154 r = symlink_idempotent(combined, target);
1155 if (r == -EINVAL)
1156 return log_error_errno(r, "Invalid existing symlink for combined hierarchy: %m");
1157 if (r < 0)
1158 return log_error_errno(r, "Failed to create symlink for combined hierarchy: %m");
1159 }
1160 }
1161
1162 skip_controllers:
1163 if (unified_requested >= CGROUP_UNIFIED_SYSTEMD) {
1164 r = mount_legacy_cgroup_hierarchy(dest, SYSTEMD_CGROUP_CONTROLLER_HYBRID, "unified", false);
1165 if (r < 0)
1166 return r;
1167 }
1168
1169 r = mount_legacy_cgroup_hierarchy(dest, SYSTEMD_CGROUP_CONTROLLER_LEGACY, "systemd", false);
1170 if (r < 0)
1171 return r;
1172
1173 return mount_verbose(LOG_ERR, NULL, cgroup_root, NULL,
1174 MS_REMOUNT|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME|MS_RDONLY, "mode=755");
1175 }
1176
1177 static int mount_unified_cgroups(const char *dest) {
1178 const char *p;
1179 int r;
1180
1181 assert(dest);
1182
1183 p = prefix_roota(dest, "/sys/fs/cgroup");
1184
1185 (void) mkdir_p(p, 0755);
1186
1187 r = path_is_mount_point(p, dest, AT_SYMLINK_FOLLOW);
1188 if (r < 0)
1189 return log_error_errno(r, "Failed to determine if %s is mounted already: %m", p);
1190 if (r > 0) {
1191 p = prefix_roota(dest, "/sys/fs/cgroup/cgroup.procs");
1192 if (access(p, F_OK) >= 0)
1193 return 0;
1194 if (errno != ENOENT)
1195 return log_error_errno(errno, "Failed to determine if mount point %s contains the unified cgroup hierarchy: %m", p);
1196
1197 log_error("%s is already mounted but not a unified cgroup hierarchy. Refusing.", p);
1198 return -EINVAL;
1199 }
1200
1201 return mount_verbose(LOG_ERR, "cgroup", p, "cgroup2", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
1202 }
1203
1204 int mount_cgroups(
1205 const char *dest,
1206 CGroupUnified unified_requested,
1207 bool userns,
1208 uid_t uid_shift,
1209 uid_t uid_range,
1210 const char *selinux_apifs_context,
1211 bool use_cgns) {
1212
1213 if (unified_requested >= CGROUP_UNIFIED_ALL)
1214 return mount_unified_cgroups(dest);
1215 else if (use_cgns)
1216 return mount_legacy_cgns_supported(dest, unified_requested, userns, uid_shift, uid_range, selinux_apifs_context);
1217
1218 return mount_legacy_cgns_unsupported(dest, unified_requested, userns, uid_shift, uid_range, selinux_apifs_context);
1219 }
1220
1221 static int mount_systemd_cgroup_writable_one(const char *systemd_own, const char *systemd_root)
1222 {
1223 int r;
1224
1225 /* Make our own cgroup a (writable) bind mount */
1226 r = mount_verbose(LOG_ERR, systemd_own, systemd_own, NULL, MS_BIND, NULL);
1227 if (r < 0)
1228 return r;
1229
1230 /* And then remount the systemd cgroup root read-only */
1231 return mount_verbose(LOG_ERR, NULL, systemd_root, NULL,
1232 MS_BIND|MS_REMOUNT|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_RDONLY, NULL);
1233 }
1234
1235 int mount_systemd_cgroup_writable(
1236 const char *dest,
1237 CGroupUnified unified_requested) {
1238
1239 _cleanup_free_ char *own_cgroup_path = NULL;
1240 int r;
1241
1242 assert(dest);
1243
1244 r = cg_pid_get_path(NULL, 0, &own_cgroup_path);
1245 if (r < 0)
1246 return log_error_errno(r, "Failed to determine our own cgroup path: %m");
1247
1248 /* If we are living in the top-level, then there's nothing to do... */
1249 if (path_equal(own_cgroup_path, "/"))
1250 return 0;
1251
1252 if (unified_requested >= CGROUP_UNIFIED_ALL)
1253 return mount_systemd_cgroup_writable_one(strjoina(dest, "/sys/fs/cgroup", own_cgroup_path),
1254 prefix_roota(dest, "/sys/fs/cgroup"));
1255
1256 if (unified_requested >= CGROUP_UNIFIED_SYSTEMD) {
1257 r = mount_systemd_cgroup_writable_one(strjoina(dest, "/sys/fs/cgroup/unified", own_cgroup_path),
1258 prefix_roota(dest, "/sys/fs/cgroup/unified"));
1259 if (r < 0)
1260 return r;
1261 }
1262
1263 return mount_systemd_cgroup_writable_one(strjoina(dest, "/sys/fs/cgroup/systemd", own_cgroup_path),
1264 prefix_roota(dest, "/sys/fs/cgroup/systemd"));
1265 }
1266
1267 int setup_volatile_state(
1268 const char *directory,
1269 VolatileMode mode,
1270 bool userns, uid_t uid_shift, uid_t uid_range,
1271 const char *selinux_apifs_context) {
1272
1273 _cleanup_free_ char *buf = NULL;
1274 const char *p, *options;
1275 int r;
1276
1277 assert(directory);
1278
1279 if (mode != VOLATILE_STATE)
1280 return 0;
1281
1282 /* --volatile=state means we simply overmount /var
1283 with a tmpfs, and the rest read-only. */
1284
1285 r = bind_remount_recursive(directory, true, NULL);
1286 if (r < 0)
1287 return log_error_errno(r, "Failed to remount %s read-only: %m", directory);
1288
1289 p = prefix_roota(directory, "/var");
1290 r = mkdir(p, 0755);
1291 if (r < 0 && errno != EEXIST)
1292 return log_error_errno(errno, "Failed to create %s: %m", directory);
1293
1294 options = "mode=755";
1295 r = tmpfs_patch_options(options, userns, uid_shift, uid_range, false, selinux_apifs_context, &buf);
1296 if (r < 0)
1297 return log_oom();
1298 if (r > 0)
1299 options = buf;
1300
1301 return mount_verbose(LOG_ERR, "tmpfs", p, "tmpfs", MS_STRICTATIME, options);
1302 }
1303
1304 int setup_volatile(
1305 const char *directory,
1306 VolatileMode mode,
1307 bool userns, uid_t uid_shift, uid_t uid_range,
1308 const char *selinux_apifs_context) {
1309
1310 bool tmpfs_mounted = false, bind_mounted = false;
1311 char template[] = "/tmp/nspawn-volatile-XXXXXX";
1312 _cleanup_free_ char *buf = NULL;
1313 const char *f, *t, *options;
1314 int r;
1315
1316 assert(directory);
1317
1318 if (mode != VOLATILE_YES)
1319 return 0;
1320
1321 /* --volatile=yes means we mount a tmpfs to the root dir, and
1322 the original /usr to use inside it, and that read-only. */
1323
1324 if (!mkdtemp(template))
1325 return log_error_errno(errno, "Failed to create temporary directory: %m");
1326
1327 options = "mode=755";
1328 r = tmpfs_patch_options(options, userns, uid_shift, uid_range, false, selinux_apifs_context, &buf);
1329 if (r < 0)
1330 return log_oom();
1331 if (r > 0)
1332 options = buf;
1333
1334 r = mount_verbose(LOG_ERR, "tmpfs", template, "tmpfs", MS_STRICTATIME, options);
1335 if (r < 0)
1336 goto fail;
1337
1338 tmpfs_mounted = true;
1339
1340 f = prefix_roota(directory, "/usr");
1341 t = prefix_roota(template, "/usr");
1342
1343 r = mkdir(t, 0755);
1344 if (r < 0 && errno != EEXIST) {
1345 r = log_error_errno(errno, "Failed to create %s: %m", t);
1346 goto fail;
1347 }
1348
1349 r = mount_verbose(LOG_ERR, f, t, NULL, MS_BIND|MS_REC, NULL);
1350 if (r < 0)
1351 goto fail;
1352
1353 bind_mounted = true;
1354
1355 r = bind_remount_recursive(t, true, NULL);
1356 if (r < 0) {
1357 log_error_errno(r, "Failed to remount %s read-only: %m", t);
1358 goto fail;
1359 }
1360
1361 r = mount_verbose(LOG_ERR, template, directory, NULL, MS_MOVE, NULL);
1362 if (r < 0)
1363 goto fail;
1364
1365 (void) rmdir(template);
1366
1367 return 0;
1368
1369 fail:
1370 if (bind_mounted)
1371 (void) umount_verbose(t);
1372
1373 if (tmpfs_mounted)
1374 (void) umount_verbose(template);
1375 (void) rmdir(template);
1376 return r;
1377 }
1378
1379 /* Expects *pivot_root_new and *pivot_root_old to be initialised to allocated memory or NULL. */
1380 int pivot_root_parse(char **pivot_root_new, char **pivot_root_old, const char *s) {
1381 _cleanup_free_ char *root_new = NULL, *root_old = NULL;
1382 const char *p = s;
1383 int r;
1384
1385 assert(pivot_root_new);
1386 assert(pivot_root_old);
1387
1388 r = extract_first_word(&p, &root_new, ":", EXTRACT_DONT_COALESCE_SEPARATORS);
1389 if (r < 0)
1390 return r;
1391 if (r == 0)
1392 return -EINVAL;
1393
1394 if (isempty(p))
1395 root_old = NULL;
1396 else {
1397 root_old = strdup(p);
1398 if (!root_old)
1399 return -ENOMEM;
1400 }
1401
1402 if (!path_is_absolute(root_new))
1403 return -EINVAL;
1404 if (root_old && !path_is_absolute(root_old))
1405 return -EINVAL;
1406
1407 free_and_replace(*pivot_root_new, root_new);
1408 free_and_replace(*pivot_root_old, root_old);
1409
1410 return 0;
1411 }
1412
1413 int setup_pivot_root(const char *directory, const char *pivot_root_new, const char *pivot_root_old) {
1414 _cleanup_free_ char *directory_pivot_root_new = NULL;
1415 _cleanup_free_ char *pivot_tmp_pivot_root_old = NULL;
1416 char pivot_tmp[] = "/tmp/nspawn-pivot-XXXXXX";
1417 bool remove_pivot_tmp = false;
1418 int r;
1419
1420 assert(directory);
1421
1422 if (!pivot_root_new)
1423 return 0;
1424
1425 /* Pivot pivot_root_new to / and the existing / to pivot_root_old.
1426 * If pivot_root_old is NULL, the existing / disappears.
1427 * This requires a temporary directory, pivot_tmp, which is
1428 * not a child of either.
1429 *
1430 * This is typically used for OSTree-style containers, where
1431 * the root partition contains several sysroots which could be
1432 * run. Normally, one would be chosen by the bootloader and
1433 * pivoted to / by initramfs.
1434 *
1435 * For example, for an OSTree deployment, pivot_root_new
1436 * would be: /ostree/deploy/$os/deploy/$checksum. Note that this
1437 * code doesn’t do the /var mount which OSTree expects: use
1438 * --bind +/sysroot/ostree/deploy/$os/var:/var for that.
1439 *
1440 * So in the OSTree case, we’ll end up with something like:
1441 * - directory = /tmp/nspawn-root-123456
1442 * - pivot_root_new = /ostree/deploy/os/deploy/123abc
1443 * - pivot_root_old = /sysroot
1444 * - directory_pivot_root_new =
1445 * /tmp/nspawn-root-123456/ostree/deploy/os/deploy/123abc
1446 * - pivot_tmp = /tmp/nspawn-pivot-123456
1447 * - pivot_tmp_pivot_root_old = /tmp/nspawn-pivot-123456/sysroot
1448 *
1449 * Requires all file systems at directory and below to be mounted
1450 * MS_PRIVATE or MS_SLAVE so they can be moved.
1451 */
1452 directory_pivot_root_new = prefix_root(directory, pivot_root_new);
1453
1454 /* Remount directory_pivot_root_new to make it movable. */
1455 r = mount_verbose(LOG_ERR, directory_pivot_root_new, directory_pivot_root_new, NULL, MS_BIND, NULL);
1456 if (r < 0)
1457 goto done;
1458
1459 if (pivot_root_old) {
1460 if (!mkdtemp(pivot_tmp)) {
1461 r = log_error_errno(errno, "Failed to create temporary directory: %m");
1462 goto done;
1463 }
1464
1465 remove_pivot_tmp = true;
1466 pivot_tmp_pivot_root_old = prefix_root(pivot_tmp, pivot_root_old);
1467
1468 r = mount_verbose(LOG_ERR, directory_pivot_root_new, pivot_tmp, NULL, MS_MOVE, NULL);
1469 if (r < 0)
1470 goto done;
1471
1472 r = mount_verbose(LOG_ERR, directory, pivot_tmp_pivot_root_old, NULL, MS_MOVE, NULL);
1473 if (r < 0)
1474 goto done;
1475
1476 r = mount_verbose(LOG_ERR, pivot_tmp, directory, NULL, MS_MOVE, NULL);
1477 if (r < 0)
1478 goto done;
1479 } else {
1480 r = mount_verbose(LOG_ERR, directory_pivot_root_new, directory, NULL, MS_MOVE, NULL);
1481 if (r < 0)
1482 goto done;
1483 }
1484
1485 done:
1486 if (remove_pivot_tmp)
1487 (void) rmdir(pivot_tmp);
1488
1489 return r;
1490 }