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