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