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