]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/cgroups/cgfsng.c
Merge pull request #2212 from tych0/cgroup-escape-host-unpriv
[mirror_lxc.git] / src / lxc / cgroups / cgfsng.c
1 /*
2 * lxc: linux Container library
3 *
4 * Copyright © 2016 Canonical Ltd.
5 *
6 * Authors:
7 * Serge Hallyn <serge.hallyn@ubuntu.com>
8 * Christian Brauner <christian.brauner@ubuntu.com>
9 *
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
14 *
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 */
24
25 /*
26 * cgfs-ng.c: this is a new, simplified implementation of a filesystem
27 * cgroup backend. The original cgfs.c was designed to be as flexible
28 * as possible. It would try to find cgroup filesystems no matter where
29 * or how you had them mounted, and deduce the most usable mount for
30 * each controller.
31 *
32 * This new implementation assumes that cgroup filesystems are mounted
33 * under /sys/fs/cgroup/clist where clist is either the controller, or
34 * a comman-separated list of controllers.
35 */
36
37 #include "config.h"
38
39 #include <ctype.h>
40 #include <dirent.h>
41 #include <errno.h>
42 #include <grp.h>
43 #include <stdint.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
48 #include <linux/kdev_t.h>
49 #include <linux/types.h>
50 #include <sys/types.h>
51
52 #include "caps.h"
53 #include "cgroup.h"
54 #include "cgroup_utils.h"
55 #include "commands.h"
56 #include "conf.h"
57 #include "log.h"
58 #include "storage/storage.h"
59 #include "utils.h"
60
61 lxc_log_define(lxc_cgfsng, lxc);
62
63 static struct cgroup_ops cgfsng_ops;
64
65 /* A descriptor for a mounted hierarchy
66 *
67 * @controllers
68 * - legacy hierarchy
69 * Either NULL, or a null-terminated list of all the co-mounted controllers.
70 * - unified hierarchy
71 * Either NULL, or a null-terminated list of all enabled controllers.
72 *
73 * @mountpoint
74 * - The mountpoint we will use.
75 * - legacy hierarchy
76 * It will be either /sys/fs/cgroup/controller or
77 * /sys/fs/cgroup/controllerlist.
78 * - unified hierarchy
79 * It will either be /sys/fs/cgroup or /sys/fs/cgroup/<mountpoint-name>
80 * depending on whether this is a hybrid cgroup layout (mix of legacy and
81 * unified hierarchies) or a pure unified cgroup layout.
82 *
83 * @base_cgroup
84 * - The cgroup under which the container cgroup path
85 * is created. This will be either the caller's cgroup (if not root), or
86 * init's cgroup (if root).
87 *
88 * @fullcgpath
89 * - The full path to the containers cgroup.
90 *
91 * @version
92 * - legacy hierarchy
93 * If the hierarchy is a legacy hierarchy this will be set to
94 * CGROUP_SUPER_MAGIC.
95 * - unified hierarchy
96 * If the hierarchy is a legacy hierarchy this will be set to
97 * CGROUP2_SUPER_MAGIC.
98 */
99 struct hierarchy {
100 char **controllers;
101 char *mountpoint;
102 char *base_cgroup;
103 char *fullcgpath;
104 int version;
105 };
106
107 /* The cgroup data which is attached to the lxc_handler.
108 *
109 * @cgroup_pattern
110 * - A copy of lxc.cgroup.pattern.
111 *
112 * @container_cgroup
113 * - If not null, the cgroup which was created for the container. For each
114 * hierarchy, it is created under the @hierarchy->base_cgroup directory.
115 * Relative to the base_cgroup it is the same for all hierarchies.
116 *
117 * @name
118 * - The name of the container.
119 *
120 * @cgroup_meta
121 * - A copy of the container's cgroup information. This overrides
122 * @cgroup_pattern.
123 *
124 * @cgroup_layout
125 * - What cgroup layout the container is running with.
126 * - CGROUP_LAYOUT_UNKNOWN
127 * The cgroup layout could not be determined. This should be treated as an
128 * error condition.
129 * - CGROUP_LAYOUT_LEGACY
130 * The container is running with all controllers mounted into legacy cgroup
131 * hierarchies.
132 * - CGROUP_LAYOUT_HYBRID
133 * The container is running with at least one controller mounted into a
134 * legacy cgroup hierarchy and a mountpoint for the unified hierarchy. The
135 * unified hierarchy can be empty (no controllers enabled) or non-empty
136 * (controllers enabled).
137 * - CGROUP_LAYOUT_UNIFIED
138 * The container is running on a pure unified cgroup hierarchy. The unified
139 * hierarchy can be empty (no controllers enabled) or non-empty (controllers
140 * enabled).
141 */
142 struct cgfsng_handler_data {
143 char *cgroup_pattern;
144 char *container_cgroup; /* cgroup we created for the container */
145 char *name; /* container name */
146 /* per-container cgroup information */
147 struct lxc_cgroup cgroup_meta;
148 cgroup_layout_t cgroup_layout;
149 };
150
151 /* @hierarchies
152 * - A NULL-terminated array of struct hierarchy, one per legacy hierarchy. No
153 * duplicates. First sufficient, writeable mounted hierarchy wins.
154 */
155 struct hierarchy **hierarchies;
156 /* Pointer to the unified hierarchy in the null terminated list @hierarchies.
157 * This is merely a convenience for hybrid cgroup layouts to easily retrieve the
158 * unified hierarchy without iterating throught @hierarchies.
159 */
160 struct hierarchy *unified;
161 /*
162 * @cgroup_layout
163 * - What cgroup layout the container is running with.
164 * - CGROUP_LAYOUT_UNKNOWN
165 * The cgroup layout could not be determined. This should be treated as an
166 * error condition.
167 * - CGROUP_LAYOUT_LEGACY
168 * The container is running with all controllers mounted into legacy cgroup
169 * hierarchies.
170 * - CGROUP_LAYOUT_HYBRID
171 * The container is running with at least one controller mounted into a
172 * legacy cgroup hierarchy and a mountpoint for the unified hierarchy. The
173 * unified hierarchy can be empty (no controllers enabled) or non-empty
174 * (controllers enabled).
175 * - CGROUP_LAYOUT_UNIFIED
176 * The container is running on a pure unified cgroup hierarchy. The unified
177 * hierarchy can be empty (no controllers enabled) or non-empty (controllers
178 * enabled).
179 */
180 cgroup_layout_t cgroup_layout;
181 /* What controllers is the container supposed to use. */
182 char *cgroup_use;
183
184 /* @lxc_cgfsng_debug
185 * - Whether to print debug info to stdout for the cgfsng driver.
186 */
187 static bool lxc_cgfsng_debug;
188
189 #define CGFSNG_DEBUG(format, ...) \
190 do { \
191 if (lxc_cgfsng_debug) \
192 printf("cgfsng: " format, ##__VA_ARGS__); \
193 } while (0)
194
195 static void free_string_list(char **clist)
196 {
197 int i;
198
199 if (!clist)
200 return;
201
202 for (i = 0; clist[i]; i++)
203 free(clist[i]);
204
205 free(clist);
206 }
207
208 /* Allocate a pointer, do not fail. */
209 static void *must_alloc(size_t sz)
210 {
211 return must_realloc(NULL, sz);
212 }
213
214 /* Given a pointer to a null-terminated array of pointers, realloc to add one
215 * entry, and point the new entry to NULL. Do not fail. Return the index to the
216 * second-to-last entry - that is, the one which is now available for use
217 * (keeping the list null-terminated).
218 */
219 static int append_null_to_list(void ***list)
220 {
221 int newentry = 0;
222
223 if (*list)
224 for (; (*list)[newentry]; newentry++)
225 ;
226
227 *list = must_realloc(*list, (newentry + 2) * sizeof(void **));
228 (*list)[newentry + 1] = NULL;
229 return newentry;
230 }
231
232 /* Given a null-terminated array of strings, check whether @entry is one of the
233 * strings.
234 */
235 static bool string_in_list(char **list, const char *entry)
236 {
237 int i;
238
239 if (!list)
240 return false;
241
242 for (i = 0; list[i]; i++)
243 if (strcmp(list[i], entry) == 0)
244 return true;
245
246 return false;
247 }
248
249 /* Return a copy of @entry prepending "name=", i.e. turn "systemd" into
250 * "name=systemd". Do not fail.
251 */
252 static char *cg_legacy_must_prefix_named(char *entry)
253 {
254 size_t len;
255 char *prefixed;
256
257 len = strlen(entry);
258 prefixed = must_alloc(len + 6);
259
260 memcpy(prefixed, "name=", sizeof("name=") - 1);
261 memcpy(prefixed + sizeof("name=") - 1, entry, len);
262 prefixed[len + 5] = '\0';
263 return prefixed;
264 }
265
266 /* Append an entry to the clist. Do not fail. @clist must be NULL the first time
267 * we are called.
268 *
269 * We also handle named subsystems here. Any controller which is not a kernel
270 * subsystem, we prefix "name=". Any which is both a kernel and named subsystem,
271 * we refuse to use because we're not sure which we have here.
272 * (TODO: We could work around this in some cases by just remounting to be
273 * unambiguous, or by comparing mountpoint contents with current cgroup.)
274 *
275 * The last entry will always be NULL.
276 */
277 static void must_append_controller(char **klist, char **nlist, char ***clist,
278 char *entry)
279 {
280 int newentry;
281 char *copy;
282
283 if (string_in_list(klist, entry) && string_in_list(nlist, entry)) {
284 ERROR("Refusing to use ambiguous controller \"%s\"", entry);
285 ERROR("It is both a named and kernel subsystem");
286 return;
287 }
288
289 newentry = append_null_to_list((void ***)clist);
290
291 if (strncmp(entry, "name=", 5) == 0)
292 copy = must_copy_string(entry);
293 else if (string_in_list(klist, entry))
294 copy = must_copy_string(entry);
295 else
296 copy = cg_legacy_must_prefix_named(entry);
297
298 (*clist)[newentry] = copy;
299 }
300
301 static void free_handler_data(struct cgfsng_handler_data *d)
302 {
303 free(d->cgroup_pattern);
304 free(d->container_cgroup);
305 free(d->name);
306 if (d->cgroup_meta.dir)
307 free(d->cgroup_meta.dir);
308 if (d->cgroup_meta.controllers)
309 free(d->cgroup_meta.controllers);
310 free(d);
311 }
312
313 /* Given a handler's cgroup data, return the struct hierarchy for the controller
314 * @c, or NULL if there is none.
315 */
316 struct hierarchy *get_hierarchy(const char *c)
317 {
318 int i;
319
320 if (!hierarchies)
321 return NULL;
322
323 for (i = 0; hierarchies[i]; i++) {
324 if (!c) {
325 /* This is the empty unified hierarchy. */
326 if (hierarchies[i]->controllers &&
327 !hierarchies[i]->controllers[0])
328 return hierarchies[i];
329
330 continue;
331 }
332
333 if (string_in_list(hierarchies[i]->controllers, c))
334 return hierarchies[i];
335 }
336
337 return NULL;
338 }
339
340 #define BATCH_SIZE 50
341 static void batch_realloc(char **mem, size_t oldlen, size_t newlen)
342 {
343 int newbatches = (newlen / BATCH_SIZE) + 1;
344 int oldbatches = (oldlen / BATCH_SIZE) + 1;
345
346 if (!*mem || newbatches > oldbatches) {
347 *mem = must_realloc(*mem, newbatches * BATCH_SIZE);
348 }
349 }
350
351 static void append_line(char **dest, size_t oldlen, char *new, size_t newlen)
352 {
353 size_t full = oldlen + newlen;
354
355 batch_realloc(dest, oldlen, full + 1);
356
357 memcpy(*dest + oldlen, new, newlen + 1);
358 }
359
360 /* Slurp in a whole file */
361 static char *read_file(const char *fnam)
362 {
363 FILE *f;
364 char *line = NULL, *buf = NULL;
365 size_t len = 0, fulllen = 0;
366 int linelen;
367
368 f = fopen(fnam, "r");
369 if (!f)
370 return NULL;
371 while ((linelen = getline(&line, &len, f)) != -1) {
372 append_line(&buf, fulllen, line, linelen);
373 fulllen += linelen;
374 }
375 fclose(f);
376 free(line);
377 return buf;
378 }
379
380 /* Taken over modified from the kernel sources. */
381 #define NBITS 32 /* bits in uint32_t */
382 #define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
383 #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, NBITS)
384
385 static void set_bit(unsigned bit, uint32_t *bitarr)
386 {
387 bitarr[bit / NBITS] |= (1 << (bit % NBITS));
388 }
389
390 static void clear_bit(unsigned bit, uint32_t *bitarr)
391 {
392 bitarr[bit / NBITS] &= ~(1 << (bit % NBITS));
393 }
394
395 static bool is_set(unsigned bit, uint32_t *bitarr)
396 {
397 return (bitarr[bit / NBITS] & (1 << (bit % NBITS))) != 0;
398 }
399
400 /* Create cpumask from cpulist aka turn:
401 *
402 * 0,2-3
403 *
404 * into bit array
405 *
406 * 1 0 1 1
407 */
408 static uint32_t *lxc_cpumask(char *buf, size_t nbits)
409 {
410 char *token;
411 size_t arrlen;
412 uint32_t *bitarr;
413 char *saveptr = NULL;
414
415 arrlen = BITS_TO_LONGS(nbits);
416 bitarr = calloc(arrlen, sizeof(uint32_t));
417 if (!bitarr)
418 return NULL;
419
420 for (; (token = strtok_r(buf, ",", &saveptr)); buf = NULL) {
421 errno = 0;
422 unsigned end, start;
423 char *range;
424
425 start = strtoul(token, NULL, 0);
426 end = start;
427 range = strchr(token, '-');
428 if (range)
429 end = strtoul(range + 1, NULL, 0);
430
431 if (!(start <= end)) {
432 free(bitarr);
433 return NULL;
434 }
435
436 if (end >= nbits) {
437 free(bitarr);
438 return NULL;
439 }
440
441 while (start <= end)
442 set_bit(start++, bitarr);
443 }
444
445 return bitarr;
446 }
447
448 /* Turn cpumask into simple, comma-separated cpulist. */
449 static char *lxc_cpumask_to_cpulist(uint32_t *bitarr, size_t nbits)
450 {
451 int ret;
452 size_t i;
453 char **cpulist = NULL;
454 char numstr[LXC_NUMSTRLEN64] = {0};
455
456 for (i = 0; i <= nbits; i++) {
457 if (!is_set(i, bitarr))
458 continue;
459
460 ret = snprintf(numstr, LXC_NUMSTRLEN64, "%zu", i);
461 if (ret < 0 || (size_t)ret >= LXC_NUMSTRLEN64) {
462 lxc_free_array((void **)cpulist, free);
463 return NULL;
464 }
465
466 ret = lxc_append_string(&cpulist, numstr);
467 if (ret < 0) {
468 lxc_free_array((void **)cpulist, free);
469 return NULL;
470 }
471 }
472
473 if (!cpulist)
474 return NULL;
475
476 return lxc_string_join(",", (const char **)cpulist, false);
477 }
478
479 static ssize_t get_max_cpus(char *cpulist)
480 {
481 char *c1, *c2;
482 char *maxcpus = cpulist;
483 size_t cpus = 0;
484
485 c1 = strrchr(maxcpus, ',');
486 if (c1)
487 c1++;
488
489 c2 = strrchr(maxcpus, '-');
490 if (c2)
491 c2++;
492
493 if (!c1 && !c2)
494 c1 = maxcpus;
495 else if (c1 > c2)
496 c2 = c1;
497 else if (c1 < c2)
498 c1 = c2;
499 else if (!c1 && c2)
500 c1 = c2;
501
502 errno = 0;
503 cpus = strtoul(c1, NULL, 0);
504 if (errno != 0)
505 return -1;
506
507 return cpus;
508 }
509
510 #define __ISOL_CPUS "/sys/devices/system/cpu/isolated"
511 static bool cg_legacy_filter_and_set_cpus(char *path, bool am_initialized)
512 {
513 int ret;
514 ssize_t i;
515 char *lastslash, *fpath, oldv;
516 ssize_t maxisol = 0, maxposs = 0;
517 char *cpulist = NULL, *isolcpus = NULL, *posscpus = NULL;
518 uint32_t *isolmask = NULL, *possmask = NULL;
519 bool bret = false, flipped_bit = false;
520
521 lastslash = strrchr(path, '/');
522 if (!lastslash) {
523 ERROR("Failed to detect \"/\" in \"%s\"", path);
524 return bret;
525 }
526 oldv = *lastslash;
527 *lastslash = '\0';
528 fpath = must_make_path(path, "cpuset.cpus", NULL);
529 posscpus = read_file(fpath);
530 if (!posscpus) {
531 SYSERROR("Failed to read file \"%s\"", fpath);
532 goto on_error;
533 }
534
535 /* Get maximum number of cpus found in possible cpuset. */
536 maxposs = get_max_cpus(posscpus);
537 if (maxposs < 0)
538 goto on_error;
539
540 if (!file_exists(__ISOL_CPUS)) {
541 /* This system doesn't expose isolated cpus. */
542 DEBUG("The path \""__ISOL_CPUS"\" to read isolated cpus from does not exist");
543 cpulist = posscpus;
544 /* No isolated cpus but we weren't already initialized by
545 * someone. We should simply copy the parents cpuset.cpus
546 * values.
547 */
548 if (!am_initialized) {
549 DEBUG("Copying cpu settings of parent cgroup");
550 goto copy_parent;
551 }
552 /* No isolated cpus but we were already initialized by someone.
553 * Nothing more to do for us.
554 */
555 goto on_success;
556 }
557
558 isolcpus = read_file(__ISOL_CPUS);
559 if (!isolcpus) {
560 SYSERROR("Failed to read file \""__ISOL_CPUS"\"");
561 goto on_error;
562 }
563 if (!isdigit(isolcpus[0])) {
564 TRACE("No isolated cpus detected");
565 cpulist = posscpus;
566 /* No isolated cpus but we weren't already initialized by
567 * someone. We should simply copy the parents cpuset.cpus
568 * values.
569 */
570 if (!am_initialized) {
571 DEBUG("Copying cpu settings of parent cgroup");
572 goto copy_parent;
573 }
574 /* No isolated cpus but we were already initialized by someone.
575 * Nothing more to do for us.
576 */
577 goto on_success;
578 }
579
580 /* Get maximum number of cpus found in isolated cpuset. */
581 maxisol = get_max_cpus(isolcpus);
582 if (maxisol < 0)
583 goto on_error;
584
585 if (maxposs < maxisol)
586 maxposs = maxisol;
587 maxposs++;
588
589 possmask = lxc_cpumask(posscpus, maxposs);
590 if (!possmask) {
591 ERROR("Failed to create cpumask for possible cpus");
592 goto on_error;
593 }
594
595 isolmask = lxc_cpumask(isolcpus, maxposs);
596 if (!isolmask) {
597 ERROR("Failed to create cpumask for isolated cpus");
598 goto on_error;
599 }
600
601 for (i = 0; i <= maxposs; i++) {
602 if (!is_set(i, isolmask) || !is_set(i, possmask))
603 continue;
604
605 flipped_bit = true;
606 clear_bit(i, possmask);
607 }
608
609 if (!flipped_bit) {
610 DEBUG("No isolated cpus present in cpuset");
611 goto on_success;
612 }
613 DEBUG("Removed isolated cpus from cpuset");
614
615 cpulist = lxc_cpumask_to_cpulist(possmask, maxposs);
616 if (!cpulist) {
617 ERROR("Failed to create cpu list");
618 goto on_error;
619 }
620
621 copy_parent:
622 *lastslash = oldv;
623 free(fpath);
624 fpath = must_make_path(path, "cpuset.cpus", NULL);
625 ret = lxc_write_to_file(fpath, cpulist, strlen(cpulist), false);
626 if (ret < 0) {
627 SYSERROR("Failed to write cpu list to \"%s\"", fpath);
628 goto on_error;
629 }
630
631 on_success:
632 bret = true;
633
634 on_error:
635 free(fpath);
636
637 free(isolcpus);
638 free(isolmask);
639
640 if (posscpus != cpulist)
641 free(posscpus);
642 free(possmask);
643
644 free(cpulist);
645 return bret;
646 }
647
648 /* Copy contents of parent(@path)/@file to @path/@file */
649 static bool copy_parent_file(char *path, char *file)
650 {
651 int ret;
652 char *fpath, *lastslash, oldv;
653 int len = 0;
654 char *value = NULL;
655
656 lastslash = strrchr(path, '/');
657 if (!lastslash) {
658 ERROR("Failed to detect \"/\" in \"%s\"", path);
659 return false;
660 }
661 oldv = *lastslash;
662 *lastslash = '\0';
663 fpath = must_make_path(path, file, NULL);
664 len = lxc_read_from_file(fpath, NULL, 0);
665 if (len <= 0)
666 goto on_error;
667
668 value = must_alloc(len + 1);
669 ret = lxc_read_from_file(fpath, value, len);
670 if (ret != len)
671 goto on_error;
672 free(fpath);
673
674 *lastslash = oldv;
675 fpath = must_make_path(path, file, NULL);
676 ret = lxc_write_to_file(fpath, value, len, false);
677 if (ret < 0)
678 SYSERROR("Failed to write \"%s\" to file \"%s\"", value, fpath);
679 free(fpath);
680 free(value);
681 return ret >= 0;
682
683 on_error:
684 SYSERROR("Failed to read file \"%s\"", fpath);
685 free(fpath);
686 free(value);
687 return false;
688 }
689
690 /* Initialize the cpuset hierarchy in first directory of @gname and set
691 * cgroup.clone_children so that children inherit settings. Since the
692 * h->base_path is populated by init or ourselves, we know it is already
693 * initialized.
694 */
695 static bool cg_legacy_handle_cpuset_hierarchy(struct hierarchy *h, char *cgname)
696 {
697 int ret;
698 char v;
699 char *cgpath, *clonechildrenpath, *slash;
700
701 if (!string_in_list(h->controllers, "cpuset"))
702 return true;
703
704 if (*cgname == '/')
705 cgname++;
706 slash = strchr(cgname, '/');
707 if (slash)
708 *slash = '\0';
709
710 cgpath = must_make_path(h->mountpoint, h->base_cgroup, cgname, NULL);
711 if (slash)
712 *slash = '/';
713
714 ret = mkdir(cgpath, 0755);
715 if (ret < 0) {
716 if (errno != EEXIST) {
717 SYSERROR("Failed to create directory \"%s\"", cgpath);
718 free(cgpath);
719 return false;
720 }
721 }
722
723 clonechildrenpath =
724 must_make_path(cgpath, "cgroup.clone_children", NULL);
725 /* unified hierarchy doesn't have clone_children */
726 if (!file_exists(clonechildrenpath)) {
727 free(clonechildrenpath);
728 free(cgpath);
729 return true;
730 }
731
732 ret = lxc_read_from_file(clonechildrenpath, &v, 1);
733 if (ret < 0) {
734 SYSERROR("Failed to read file \"%s\"", clonechildrenpath);
735 free(clonechildrenpath);
736 free(cgpath);
737 return false;
738 }
739
740 /* Make sure any isolated cpus are removed from cpuset.cpus. */
741 if (!cg_legacy_filter_and_set_cpus(cgpath, v == '1')) {
742 SYSERROR("Failed to remove isolated cpus");
743 free(clonechildrenpath);
744 free(cgpath);
745 return false;
746 }
747
748 /* Already set for us by someone else. */
749 if (v == '1') {
750 DEBUG("\"cgroup.clone_children\" was already set to \"1\"");
751 free(clonechildrenpath);
752 free(cgpath);
753 return true;
754 }
755
756 /* copy parent's settings */
757 if (!copy_parent_file(cgpath, "cpuset.mems")) {
758 SYSERROR("Failed to copy \"cpuset.mems\" settings");
759 free(cgpath);
760 free(clonechildrenpath);
761 return false;
762 }
763 free(cgpath);
764
765 ret = lxc_write_to_file(clonechildrenpath, "1", 1, false);
766 if (ret < 0) {
767 /* Set clone_children so children inherit our settings */
768 SYSERROR("Failed to write 1 to \"%s\"", clonechildrenpath);
769 free(clonechildrenpath);
770 return false;
771 }
772 free(clonechildrenpath);
773 return true;
774 }
775
776 /* Given two null-terminated lists of strings, return true if any string is in
777 * both.
778 */
779 static bool controller_lists_intersect(char **l1, char **l2)
780 {
781 int i;
782
783 if (!l1 || !l2)
784 return false;
785
786 for (i = 0; l1[i]; i++) {
787 if (string_in_list(l2, l1[i]))
788 return true;
789 }
790
791 return false;
792 }
793
794 /* For a null-terminated list of controllers @clist, return true if any of those
795 * controllers is already listed the null-terminated list of hierarchies @hlist.
796 * Realistically, if one is present, all must be present.
797 */
798 static bool controller_list_is_dup(struct hierarchy **hlist, char **clist)
799 {
800 int i;
801
802 if (!hlist)
803 return false;
804
805 for (i = 0; hlist[i]; i++)
806 if (controller_lists_intersect(hlist[i]->controllers, clist))
807 return true;
808
809 return false;
810 }
811
812 /* Return true if the controller @entry is found in the null-terminated list of
813 * hierarchies @hlist.
814 */
815 static bool controller_found(struct hierarchy **hlist, char *entry)
816 {
817 int i;
818
819 if (!hlist)
820 return false;
821
822 for (i = 0; hlist[i]; i++)
823 if (string_in_list(hlist[i]->controllers, entry))
824 return true;
825
826 return false;
827 }
828
829 /* Return true if all of the controllers which we require have been found. The
830 * required list is freezer and anything in lxc.cgroup.use.
831 */
832 static bool all_controllers_found(void)
833 {
834 char *p;
835 char *saveptr = NULL;
836 struct hierarchy **hlist = hierarchies;
837
838 if (!controller_found(hlist, "freezer")) {
839 CGFSNG_DEBUG("No freezer controller mountpoint found\n");
840 return false;
841 }
842
843 if (!cgroup_use)
844 return true;
845
846 for (; (p = strtok_r(cgroup_use, ",", &saveptr)); cgroup_use = NULL)
847 if (!controller_found(hlist, p)) {
848 CGFSNG_DEBUG("No %s controller mountpoint found\n", p);
849 return false;
850 }
851
852 return true;
853 }
854
855 /* Get the controllers from a mountinfo line There are other ways we could get
856 * this info. For lxcfs, field 3 is /cgroup/controller-list. For cgroupfs, we
857 * could parse the mount options. But we simply assume that the mountpoint must
858 * be /sys/fs/cgroup/controller-list
859 */
860 static char **cg_hybrid_get_controllers(char **klist, char **nlist, char *line,
861 int type)
862 {
863 /* The fourth field is /sys/fs/cgroup/comma-delimited-controller-list
864 * for legacy hierarchies.
865 */
866 int i;
867 char *dup, *p2, *tok;
868 char *p = line, *saveptr = NULL, *sep = ",";
869 char **aret = NULL;
870
871 for (i = 0; i < 4; i++) {
872 p = strchr(p, ' ');
873 if (!p)
874 return NULL;
875 p++;
876 }
877
878 /* Note, if we change how mountinfo works, then our caller will need to
879 * verify /sys/fs/cgroup/ in this field.
880 */
881 if (strncmp(p, "/sys/fs/cgroup/", 15) != 0) {
882 CGFSNG_DEBUG("Found hierarchy not under /sys/fs/cgroup: \"%s\"\n", p);
883 return NULL;
884 }
885
886 p += 15;
887 p2 = strchr(p, ' ');
888 if (!p2) {
889 CGFSNG_DEBUG("Corrupt mountinfo\n");
890 return NULL;
891 }
892 *p2 = '\0';
893
894 if (type == CGROUP_SUPER_MAGIC) {
895 /* strdup() here for v1 hierarchies. Otherwise strtok_r() will
896 * destroy mountpoints such as "/sys/fs/cgroup/cpu,cpuacct".
897 */
898 dup = strdup(p);
899 if (!dup)
900 return NULL;
901
902 for (tok = strtok_r(dup, sep, &saveptr); tok;
903 tok = strtok_r(NULL, sep, &saveptr))
904 must_append_controller(klist, nlist, &aret, tok);
905
906 free(dup);
907 }
908 *p2 = ' ';
909
910 return aret;
911 }
912
913 static char **cg_unified_make_empty_controller(void)
914 {
915 int newentry;
916 char **aret = NULL;
917
918 newentry = append_null_to_list((void ***)&aret);
919 aret[newentry] = NULL;
920 return aret;
921 }
922
923 static char **cg_unified_get_controllers(const char *file)
924 {
925 char *buf, *tok;
926 char *saveptr = NULL, *sep = " \t\n";
927 char **aret = NULL;
928
929 buf = read_file(file);
930 if (!buf)
931 return NULL;
932
933 for (tok = strtok_r(buf, sep, &saveptr); tok;
934 tok = strtok_r(NULL, sep, &saveptr)) {
935 int newentry;
936 char *copy;
937
938 newentry = append_null_to_list((void ***)&aret);
939 copy = must_copy_string(tok);
940 aret[newentry] = copy;
941 }
942
943 free(buf);
944 return aret;
945 }
946
947 static struct hierarchy *add_hierarchy(char **clist, char *mountpoint,
948 char *base_cgroup, int type)
949 {
950 struct hierarchy *new;
951 int newentry;
952
953 new = must_alloc(sizeof(*new));
954 new->controllers = clist;
955 new->mountpoint = mountpoint;
956 new->base_cgroup = base_cgroup;
957 new->fullcgpath = NULL;
958 new->version = type;
959
960 newentry = append_null_to_list((void ***)&hierarchies);
961 hierarchies[newentry] = new;
962 return new;
963 }
964
965 /* Get a copy of the mountpoint from @line, which is a line from
966 * /proc/self/mountinfo.
967 */
968 static char *cg_hybrid_get_mountpoint(char *line)
969 {
970 int i;
971 size_t len;
972 char *p2;
973 char *p = line, *sret = NULL;
974
975 for (i = 0; i < 4; i++) {
976 p = strchr(p, ' ');
977 if (!p)
978 return NULL;
979 p++;
980 }
981
982 if (strncmp(p, "/sys/fs/cgroup/", 15) != 0)
983 return NULL;
984
985 p2 = strchr(p + 15, ' ');
986 if (!p2)
987 return NULL;
988 *p2 = '\0';
989
990 len = strlen(p);
991 sret = must_alloc(len + 1);
992 memcpy(sret, p, len);
993 sret[len] = '\0';
994 return sret;
995 }
996
997 /* Given a multi-line string, return a null-terminated copy of the current line. */
998 static char *copy_to_eol(char *p)
999 {
1000 char *p2 = strchr(p, '\n'), *sret;
1001 size_t len;
1002
1003 if (!p2)
1004 return NULL;
1005
1006 len = p2 - p;
1007 sret = must_alloc(len + 1);
1008 memcpy(sret, p, len);
1009 sret[len] = '\0';
1010 return sret;
1011 }
1012
1013 /* cgline: pointer to character after the first ':' in a line in a \n-terminated
1014 * /proc/self/cgroup file. Check whether controller c is present.
1015 */
1016 static bool controller_in_clist(char *cgline, char *c)
1017 {
1018 char *tok, *saveptr = NULL, *eol, *tmp;
1019 size_t len;
1020
1021 eol = strchr(cgline, ':');
1022 if (!eol)
1023 return false;
1024
1025 len = eol - cgline;
1026 tmp = alloca(len + 1);
1027 memcpy(tmp, cgline, len);
1028 tmp[len] = '\0';
1029
1030 for (tok = strtok_r(tmp, ",", &saveptr); tok;
1031 tok = strtok_r(NULL, ",", &saveptr)) {
1032 if (strcmp(tok, c) == 0)
1033 return true;
1034 }
1035
1036 return false;
1037 }
1038
1039 /* @basecginfo is a copy of /proc/$$/cgroup. Return the current cgroup for
1040 * @controller.
1041 */
1042 static char *cg_hybrid_get_current_cgroup(char *basecginfo, char *controller,
1043 int type)
1044 {
1045 char *p = basecginfo;
1046
1047 for (;;) {
1048 bool is_cgv2_base_cgroup = false;
1049
1050 /* cgroup v2 entry in "/proc/<pid>/cgroup": "0::/some/path" */
1051 if ((type == CGROUP2_SUPER_MAGIC) && (*p == '0'))
1052 is_cgv2_base_cgroup = true;
1053
1054 p = strchr(p, ':');
1055 if (!p)
1056 return NULL;
1057 p++;
1058
1059 if (is_cgv2_base_cgroup || (controller && controller_in_clist(p, controller))) {
1060 p = strchr(p, ':');
1061 if (!p)
1062 return NULL;
1063 p++;
1064 return copy_to_eol(p);
1065 }
1066
1067 p = strchr(p, '\n');
1068 if (!p)
1069 return NULL;
1070 p++;
1071 }
1072 }
1073
1074 static void must_append_string(char ***list, char *entry)
1075 {
1076 int newentry;
1077 char *copy;
1078
1079 newentry = append_null_to_list((void ***)list);
1080 copy = must_copy_string(entry);
1081 (*list)[newentry] = copy;
1082 }
1083
1084 static int get_existing_subsystems(char ***klist, char ***nlist)
1085 {
1086 FILE *f;
1087 char *line = NULL;
1088 size_t len = 0;
1089
1090 f = fopen("/proc/self/cgroup", "r");
1091 if (!f)
1092 return -1;
1093
1094 while (getline(&line, &len, f) != -1) {
1095 char *p, *p2, *tok, *saveptr = NULL;
1096 p = strchr(line, ':');
1097 if (!p)
1098 continue;
1099 p++;
1100 p2 = strchr(p, ':');
1101 if (!p2)
1102 continue;
1103 *p2 = '\0';
1104
1105 /* If the kernel has cgroup v2 support, then /proc/self/cgroup
1106 * contains an entry of the form:
1107 *
1108 * 0::/some/path
1109 *
1110 * In this case we use "cgroup2" as controller name.
1111 */
1112 if ((p2 - p) == 0) {
1113 must_append_string(klist, "cgroup2");
1114 continue;
1115 }
1116
1117 for (tok = strtok_r(p, ",", &saveptr); tok;
1118 tok = strtok_r(NULL, ",", &saveptr)) {
1119 if (strncmp(tok, "name=", 5) == 0)
1120 must_append_string(nlist, tok);
1121 else
1122 must_append_string(klist, tok);
1123 }
1124 }
1125
1126 free(line);
1127 fclose(f);
1128 return 0;
1129 }
1130
1131 static void trim(char *s)
1132 {
1133 size_t len;
1134
1135 len = strlen(s);
1136 while ((len > 1) && (s[len - 1] == '\n'))
1137 s[--len] = '\0';
1138 }
1139
1140 static void lxc_cgfsng_print_handler_data(const struct cgfsng_handler_data *d)
1141 {
1142 printf("Cgroup information:\n");
1143 printf(" container name: %s\n", d->name ? d->name : "(null)");
1144 printf(" lxc.cgroup.use: %s\n", cgroup_use ? cgroup_use : "(null)");
1145 printf(" lxc.cgroup.pattern: %s\n",
1146 d->cgroup_pattern ? d->cgroup_pattern : "(null)");
1147 printf(" lxc.cgroup.dir: %s\n",
1148 d->cgroup_meta.dir ? d->cgroup_meta.dir : "(null)");
1149 printf(" cgroup: %s\n",
1150 d->container_cgroup ? d->container_cgroup : "(null)");
1151 }
1152
1153 static void lxc_cgfsng_print_hierarchies()
1154 {
1155 int i;
1156 struct hierarchy **it;
1157
1158 if (!hierarchies) {
1159 printf(" No hierarchies found\n");
1160 return;
1161 }
1162
1163 printf(" Hierarchies:\n");
1164 for (i = 0, it = hierarchies; it && *it; it++, i++) {
1165 int j;
1166 char **cit;
1167
1168 printf(" %d: base_cgroup: %s\n", i, (*it)->base_cgroup ? (*it)->base_cgroup : "(null)");
1169 printf(" mountpoint: %s\n", (*it)->mountpoint ? (*it)->mountpoint : "(null)");
1170 printf(" controllers:\n");
1171 for (j = 0, cit = (*it)->controllers; cit && *cit; cit++, j++)
1172 printf(" %d: %s\n", j, *cit);
1173 }
1174 }
1175
1176 static void lxc_cgfsng_print_basecg_debuginfo(char *basecginfo, char **klist,
1177 char **nlist)
1178 {
1179 int k;
1180 char **it;
1181
1182 printf("basecginfo is:\n");
1183 printf("%s\n", basecginfo);
1184
1185 for (k = 0, it = klist; it && *it; it++, k++)
1186 printf("kernel subsystem %d: %s\n", k, *it);
1187
1188 for (k = 0, it = nlist; it && *it; it++, k++)
1189 printf("named subsystem %d: %s\n", k, *it);
1190 }
1191
1192 static void lxc_cgfsng_print_debuginfo(const struct cgfsng_handler_data *d)
1193 {
1194 lxc_cgfsng_print_handler_data(d);
1195 lxc_cgfsng_print_hierarchies();
1196 }
1197
1198 /* At startup, parse_hierarchies finds all the info we need about cgroup
1199 * mountpoints and current cgroups, and stores it in @d.
1200 */
1201 static bool cg_hybrid_init(void)
1202 {
1203 int ret;
1204 char *basecginfo;
1205 bool will_escape;
1206 FILE *f;
1207 size_t len = 0;
1208 char *line = NULL;
1209 char **klist = NULL, **nlist = NULL;
1210
1211 /* Root spawned containers escape the current cgroup, so use init's
1212 * cgroups as our base in that case.
1213 */
1214 will_escape = (geteuid() == 0);
1215 if (will_escape)
1216 basecginfo = read_file("/proc/1/cgroup");
1217 else
1218 basecginfo = read_file("/proc/self/cgroup");
1219 if (!basecginfo)
1220 return false;
1221
1222 ret = get_existing_subsystems(&klist, &nlist);
1223 if (ret < 0) {
1224 CGFSNG_DEBUG("Failed to retrieve available legacy cgroup controllers\n");
1225 free(basecginfo);
1226 return false;
1227 }
1228
1229 f = fopen("/proc/self/mountinfo", "r");
1230 if (!f) {
1231 CGFSNG_DEBUG("Failed to open \"/proc/self/mountinfo\"\n");
1232 free(basecginfo);
1233 return false;
1234 }
1235
1236 if (lxc_cgfsng_debug)
1237 lxc_cgfsng_print_basecg_debuginfo(basecginfo, klist, nlist);
1238
1239 while (getline(&line, &len, f) != -1) {
1240 int type;
1241 bool writeable;
1242 struct hierarchy *new;
1243 char *base_cgroup = NULL, *mountpoint = NULL;
1244 char **controller_list = NULL;
1245
1246 type = get_cgroup_version(line);
1247 if (type == 0)
1248 continue;
1249
1250 if (type == CGROUP2_SUPER_MAGIC && unified)
1251 continue;
1252
1253 if (cgroup_layout == CGROUP_LAYOUT_UNKNOWN) {
1254 if (type == CGROUP2_SUPER_MAGIC)
1255 cgroup_layout = CGROUP_LAYOUT_UNIFIED;
1256 else if (type == CGROUP_SUPER_MAGIC)
1257 cgroup_layout = CGROUP_LAYOUT_LEGACY;
1258 } else if (cgroup_layout == CGROUP_LAYOUT_UNIFIED) {
1259 if (type == CGROUP_SUPER_MAGIC)
1260 cgroup_layout = CGROUP_LAYOUT_HYBRID;
1261 } else if (cgroup_layout == CGROUP_LAYOUT_LEGACY) {
1262 if (type == CGROUP2_SUPER_MAGIC)
1263 cgroup_layout = CGROUP_LAYOUT_HYBRID;
1264 }
1265
1266 controller_list = cg_hybrid_get_controllers(klist, nlist, line, type);
1267 if (!controller_list && type == CGROUP_SUPER_MAGIC)
1268 continue;
1269
1270 if (type == CGROUP_SUPER_MAGIC)
1271 if (controller_list_is_dup(hierarchies, controller_list))
1272 goto next;
1273
1274 mountpoint = cg_hybrid_get_mountpoint(line);
1275 if (!mountpoint) {
1276 CGFSNG_DEBUG("Failed parsing mountpoint from \"%s\"\n", line);
1277 goto next;
1278 }
1279
1280 if (type == CGROUP_SUPER_MAGIC)
1281 base_cgroup = cg_hybrid_get_current_cgroup(basecginfo, controller_list[0], CGROUP_SUPER_MAGIC);
1282 else
1283 base_cgroup = cg_hybrid_get_current_cgroup(basecginfo, NULL, CGROUP2_SUPER_MAGIC);
1284 if (!base_cgroup) {
1285 CGFSNG_DEBUG("Failed to find current cgroup\n");
1286 goto next;
1287 }
1288
1289 trim(base_cgroup);
1290 prune_init_scope(base_cgroup);
1291 if (type == CGROUP2_SUPER_MAGIC)
1292 writeable = test_writeable_v2(mountpoint, base_cgroup);
1293 else
1294 writeable = test_writeable_v1(mountpoint, base_cgroup);
1295 if (!writeable)
1296 goto next;
1297
1298 if (type == CGROUP2_SUPER_MAGIC) {
1299 char *cgv2_ctrl_path;
1300
1301 cgv2_ctrl_path = must_make_path(mountpoint, base_cgroup,
1302 "cgroup.controllers",
1303 NULL);
1304
1305 controller_list = cg_unified_get_controllers(cgv2_ctrl_path);
1306 free(cgv2_ctrl_path);
1307 if (!controller_list) {
1308 controller_list = cg_unified_make_empty_controller();
1309 CGFSNG_DEBUG("No controllers are enabled for "
1310 "delegation in the unified hierarchy\n");
1311 }
1312 }
1313
1314 new = add_hierarchy(controller_list, mountpoint, base_cgroup, type);
1315 if (type == CGROUP2_SUPER_MAGIC && !unified)
1316 unified = new;
1317
1318 continue;
1319
1320 next:
1321 free_string_list(controller_list);
1322 free(mountpoint);
1323 free(base_cgroup);
1324 }
1325
1326 free_string_list(klist);
1327 free_string_list(nlist);
1328
1329 free(basecginfo);
1330
1331 fclose(f);
1332 free(line);
1333
1334 if (lxc_cgfsng_debug) {
1335 printf("Writable cgroup hierarchies:\n");
1336 lxc_cgfsng_print_hierarchies();
1337 }
1338
1339 /* verify that all controllers in cgroup.use and all crucial
1340 * controllers are accounted for
1341 */
1342 if (!all_controllers_found())
1343 return false;
1344
1345 return true;
1346 }
1347
1348 static int cg_is_pure_unified(void)
1349 {
1350
1351 int ret;
1352 struct statfs fs;
1353
1354 ret = statfs("/sys/fs/cgroup", &fs);
1355 if (ret < 0)
1356 return -ENOMEDIUM;
1357
1358 if (is_fs_type(&fs, CGROUP2_SUPER_MAGIC))
1359 return CGROUP2_SUPER_MAGIC;
1360
1361 return 0;
1362 }
1363
1364 /* Get current cgroup from /proc/self/cgroup for the cgroupfs v2 hierarchy. */
1365 static char *cg_unified_get_current_cgroup(void)
1366 {
1367 char *basecginfo, *base_cgroup;
1368 bool will_escape;
1369 char *copy = NULL;
1370
1371 will_escape = !am_host_unpriv();
1372 if (will_escape)
1373 basecginfo = read_file("/proc/1/cgroup");
1374 else
1375 basecginfo = read_file("/proc/self/cgroup");
1376 if (!basecginfo)
1377 return NULL;
1378
1379 base_cgroup = strstr(basecginfo, "0::/");
1380 if (!base_cgroup)
1381 goto cleanup_on_err;
1382
1383 base_cgroup = base_cgroup + 3;
1384 copy = copy_to_eol(base_cgroup);
1385 if (!copy)
1386 goto cleanup_on_err;
1387
1388 cleanup_on_err:
1389 free(basecginfo);
1390 if (copy)
1391 trim(copy);
1392
1393 return copy;
1394 }
1395
1396 static int cg_unified_init(void)
1397 {
1398 int ret;
1399 char *mountpoint, *subtree_path;
1400 char **delegatable;
1401 char *base_cgroup = NULL;
1402
1403 ret = cg_is_pure_unified();
1404 if (ret == -ENOMEDIUM)
1405 return -ENOMEDIUM;
1406
1407 if (ret != CGROUP2_SUPER_MAGIC)
1408 return 0;
1409
1410 base_cgroup = cg_unified_get_current_cgroup();
1411 if (!base_cgroup)
1412 return -EINVAL;
1413 prune_init_scope(base_cgroup);
1414
1415 /* We assume that we have already been given controllers to delegate
1416 * further down the hierarchy. If not it is up to the user to delegate
1417 * them to us.
1418 */
1419 mountpoint = must_copy_string("/sys/fs/cgroup");
1420 subtree_path = must_make_path(mountpoint, base_cgroup,
1421 "cgroup.subtree_control", NULL);
1422 delegatable = cg_unified_get_controllers(subtree_path);
1423 free(subtree_path);
1424 if (!delegatable)
1425 delegatable = cg_unified_make_empty_controller();
1426 if (!delegatable[0])
1427 CGFSNG_DEBUG("No controllers are enabled for delegation\n");
1428
1429 /* TODO: If the user requested specific controllers via lxc.cgroup.use
1430 * we should verify here. The reason I'm not doing it right is that I'm
1431 * not convinced that lxc.cgroup.use will be the future since it is a
1432 * global property. I much rather have an option that lets you request
1433 * controllers per container.
1434 */
1435
1436 add_hierarchy(delegatable, mountpoint, base_cgroup, CGROUP2_SUPER_MAGIC);
1437 unified = hierarchies[0];
1438
1439 cgroup_layout = CGROUP_LAYOUT_UNIFIED;
1440 return CGROUP2_SUPER_MAGIC;
1441 }
1442
1443 static bool cg_init(void)
1444 {
1445 int ret;
1446 const char *tmp;
1447
1448 errno = 0;
1449 tmp = lxc_global_config_value("lxc.cgroup.use");
1450 if (!cgroup_use && errno != 0) { /* lxc.cgroup.use can be NULL */
1451 CGFSNG_DEBUG("Failed to retrieve list of cgroups to use\n");
1452 return false;
1453 }
1454 cgroup_use = must_copy_string(tmp);
1455
1456 ret = cg_unified_init();
1457 if (ret < 0)
1458 return false;
1459
1460 if (ret == CGROUP2_SUPER_MAGIC)
1461 return true;
1462
1463 return cg_hybrid_init();
1464 }
1465
1466 static void *cgfsng_init(struct lxc_handler *handler)
1467 {
1468 const char *cgroup_pattern;
1469 struct cgfsng_handler_data *d;
1470
1471 d = must_alloc(sizeof(*d));
1472 memset(d, 0, sizeof(*d));
1473
1474 /* copy container name */
1475 d->name = must_copy_string(handler->name);
1476
1477 /* copy per-container cgroup information */
1478 d->cgroup_meta.dir = NULL;
1479 d->cgroup_meta.controllers = NULL;
1480 if (handler->conf) {
1481 d->cgroup_meta.dir = must_copy_string(handler->conf->cgroup_meta.dir);
1482 d->cgroup_meta.controllers = must_copy_string(handler->conf->cgroup_meta.controllers);
1483 }
1484
1485 /* copy system-wide cgroup information */
1486 cgroup_pattern = lxc_global_config_value("lxc.cgroup.pattern");
1487 if (!cgroup_pattern) {
1488 /* lxc.cgroup.pattern is only NULL on error. */
1489 ERROR("Failed to retrieve cgroup pattern");
1490 goto out_free;
1491 }
1492 d->cgroup_pattern = must_copy_string(cgroup_pattern);
1493
1494 d->cgroup_layout = cgroup_layout;
1495 if (d->cgroup_layout == CGROUP_LAYOUT_LEGACY)
1496 TRACE("Running with legacy cgroup layout");
1497 else if (d->cgroup_layout == CGROUP_LAYOUT_HYBRID)
1498 TRACE("Running with hybrid cgroup layout");
1499 else if (d->cgroup_layout == CGROUP_LAYOUT_UNIFIED)
1500 TRACE("Running with unified cgroup layout");
1501 else
1502 WARN("Running with unknown cgroup layout");
1503
1504 if (lxc_cgfsng_debug)
1505 lxc_cgfsng_print_debuginfo(d);
1506
1507 return d;
1508
1509 out_free:
1510 free_handler_data(d);
1511 return NULL;
1512 }
1513
1514 static int recursive_destroy(char *dirname)
1515 {
1516 int ret;
1517 struct dirent *direntp;
1518 DIR *dir;
1519 int r = 0;
1520
1521 dir = opendir(dirname);
1522 if (!dir)
1523 return -1;
1524
1525 while ((direntp = readdir(dir))) {
1526 char *pathname;
1527 struct stat mystat;
1528
1529 if (!strcmp(direntp->d_name, ".") ||
1530 !strcmp(direntp->d_name, ".."))
1531 continue;
1532
1533 pathname = must_make_path(dirname, direntp->d_name, NULL);
1534
1535 ret = lstat(pathname, &mystat);
1536 if (ret < 0) {
1537 if (!r)
1538 WARN("Failed to stat \"%s\"", pathname);
1539 r = -1;
1540 goto next;
1541 }
1542
1543 if (!S_ISDIR(mystat.st_mode))
1544 goto next;
1545
1546 ret = recursive_destroy(pathname);
1547 if (ret < 0)
1548 r = -1;
1549 next:
1550 free(pathname);
1551 }
1552
1553 ret = rmdir(dirname);
1554 if (ret < 0) {
1555 if (!r)
1556 WARN("%s - Failed to delete \"%s\"", strerror(errno), dirname);
1557 r = -1;
1558 }
1559
1560 ret = closedir(dir);
1561 if (ret < 0) {
1562 if (!r)
1563 WARN("%s - Failed to delete \"%s\"", strerror(errno), dirname);
1564 r = -1;
1565 }
1566
1567 return r;
1568 }
1569
1570 static int cgroup_rmdir(char *container_cgroup)
1571 {
1572 int i;
1573
1574 if (!container_cgroup || !hierarchies)
1575 return 0;
1576
1577 for (i = 0; hierarchies[i]; i++) {
1578 int ret;
1579 struct hierarchy *h = hierarchies[i];
1580
1581 if (!h->fullcgpath)
1582 continue;
1583
1584 ret = recursive_destroy(h->fullcgpath);
1585 if (ret < 0)
1586 WARN("Failed to destroy \"%s\"", h->fullcgpath);
1587
1588 free(h->fullcgpath);
1589 h->fullcgpath = NULL;
1590 }
1591
1592 return 0;
1593 }
1594
1595 struct generic_userns_exec_data {
1596 struct cgfsng_handler_data *d;
1597 struct lxc_conf *conf;
1598 uid_t origuid; /* target uid in parent namespace */
1599 char *path;
1600 };
1601
1602 static int cgroup_rmdir_wrapper(void *data)
1603 {
1604 int ret;
1605 struct generic_userns_exec_data *arg = data;
1606 uid_t nsuid = (arg->conf->root_nsuid_map != NULL) ? 0 : arg->conf->init_uid;
1607 gid_t nsgid = (arg->conf->root_nsgid_map != NULL) ? 0 : arg->conf->init_gid;
1608
1609 ret = setresgid(nsgid, nsgid, nsgid);
1610 if (ret < 0) {
1611 SYSERROR("Failed to setresgid(%d, %d, %d)", (int)nsgid,
1612 (int)nsgid, (int)nsgid);
1613 return -1;
1614 }
1615
1616 ret = setresuid(nsuid, nsuid, nsuid);
1617 if (ret < 0) {
1618 SYSERROR("Failed to setresuid(%d, %d, %d)", (int)nsuid,
1619 (int)nsuid, (int)nsuid);
1620 return -1;
1621 }
1622
1623 ret = setgroups(0, NULL);
1624 if (ret < 0 && errno != EPERM) {
1625 SYSERROR("Failed to setgroups(0, NULL)");
1626 return -1;
1627 }
1628
1629 return cgroup_rmdir(arg->d->container_cgroup);
1630 }
1631
1632 static void cgfsng_destroy(void *hdata, struct lxc_conf *conf)
1633 {
1634 int ret;
1635 struct cgfsng_handler_data *d = hdata;
1636 struct generic_userns_exec_data wrap;
1637
1638 if (!d)
1639 return;
1640
1641 wrap.origuid = 0;
1642 wrap.d = hdata;
1643 wrap.conf = conf;
1644
1645 if (conf && !lxc_list_empty(&conf->id_map))
1646 ret = userns_exec_1(conf, cgroup_rmdir_wrapper, &wrap,
1647 "cgroup_rmdir_wrapper");
1648 else
1649 ret = cgroup_rmdir(d->container_cgroup);
1650 if (ret < 0) {
1651 WARN("Failed to destroy cgroups");
1652 return;
1653 }
1654
1655 free_handler_data(d);
1656 }
1657
1658 struct cgroup_ops *cgfsng_ops_init(void)
1659 {
1660 if (getenv("LXC_DEBUG_CGFSNG"))
1661 lxc_cgfsng_debug = true;
1662
1663 if (!cg_init())
1664 return NULL;
1665
1666 return &cgfsng_ops;
1667 }
1668
1669 static bool cg_unified_create_cgroup(struct hierarchy *h, char *cgname)
1670 {
1671 size_t i, parts_len;
1672 char **it;
1673 size_t full_len = 0;
1674 char *add_controllers = NULL, *cgroup = NULL;
1675 char **parts = NULL;
1676 bool bret = false;
1677
1678 if (h->version != CGROUP2_SUPER_MAGIC)
1679 return true;
1680
1681 if (!h->controllers)
1682 return true;
1683
1684 /* For now we simply enable all controllers that we have detected by
1685 * creating a string like "+memory +pids +cpu +io".
1686 * TODO: In the near future we might want to support "-<controller>"
1687 * etc. but whether supporting semantics like this make sense will need
1688 * some thinking.
1689 */
1690 for (it = h->controllers; it && *it; it++) {
1691 full_len += strlen(*it) + 2;
1692 add_controllers = must_realloc(add_controllers, full_len + 1);
1693 if (h->controllers[0] == *it)
1694 add_controllers[0] = '\0';
1695 strcat(add_controllers, "+");
1696 strcat(add_controllers, *it);
1697 if ((it + 1) && *(it + 1))
1698 strcat(add_controllers, " ");
1699 }
1700
1701 parts = lxc_string_split(cgname, '/');
1702 if (!parts)
1703 goto on_error;
1704 parts_len = lxc_array_len((void **)parts);
1705 if (parts_len > 0)
1706 parts_len--;
1707
1708 cgroup = must_make_path(h->mountpoint, h->base_cgroup, NULL);
1709 for (i = 0; i < parts_len; i++) {
1710 int ret;
1711 char *target;
1712
1713 cgroup = must_append_path(cgroup, parts[i], NULL);
1714 target = must_make_path(cgroup, "cgroup.subtree_control", NULL);
1715 ret = lxc_write_to_file(target, add_controllers, full_len, false);
1716 free(target);
1717 if (ret < 0) {
1718 SYSERROR("Could not enable \"%s\" controllers in the "
1719 "unified cgroup \"%s\"", add_controllers, cgroup);
1720 goto on_error;
1721 }
1722 }
1723
1724 bret = true;
1725
1726 on_error:
1727 lxc_free_array((void **)parts, free);
1728 free(add_controllers);
1729 free(cgroup);
1730 return bret;
1731 }
1732
1733 static bool create_path_for_hierarchy(struct hierarchy *h, char *cgname)
1734 {
1735 int ret;
1736
1737 h->fullcgpath = must_make_path(h->mountpoint, h->base_cgroup, cgname, NULL);
1738 if (dir_exists(h->fullcgpath)) {
1739 ERROR("The cgroup \"%s\" already existed", h->fullcgpath);
1740 return false;
1741 }
1742
1743 if (!cg_legacy_handle_cpuset_hierarchy(h, cgname)) {
1744 ERROR("Failed to handle legacy cpuset controller");
1745 return false;
1746 }
1747
1748 ret = mkdir_p(h->fullcgpath, 0755);
1749 if (ret < 0) {
1750 ERROR("Failed to create cgroup \"%s\"", h->fullcgpath);
1751 return false;
1752 }
1753
1754 return cg_unified_create_cgroup(h, cgname);
1755 }
1756
1757 static void remove_path_for_hierarchy(struct hierarchy *h, char *cgname)
1758 {
1759 int ret;
1760
1761 ret = rmdir(h->fullcgpath);
1762 if (ret < 0)
1763 SYSERROR("Failed to rmdir(\"%s\") from failed creation attempt", h->fullcgpath);
1764
1765 free(h->fullcgpath);
1766 h->fullcgpath = NULL;
1767 }
1768
1769 /* Try to create the same cgroup in all hierarchies. Start with cgroup_pattern;
1770 * next cgroup_pattern-1, -2, ..., -999.
1771 */
1772 static inline bool cgfsng_create(void *hdata)
1773 {
1774 int i;
1775 size_t len;
1776 char *container_cgroup, *offset, *tmp;
1777 int idx = 0;
1778 struct cgfsng_handler_data *d = hdata;
1779
1780 if (!d)
1781 return false;
1782
1783 if (d->container_cgroup) {
1784 WARN("cgfsng_create called a second time");
1785 return false;
1786 }
1787
1788 if (d->cgroup_meta.dir)
1789 tmp = lxc_string_join("/", (const char *[]){d->cgroup_meta.dir, d->name, NULL}, false);
1790 else
1791 tmp = lxc_string_replace("%n", d->name, d->cgroup_pattern);
1792 if (!tmp) {
1793 ERROR("Failed expanding cgroup name pattern");
1794 return false;
1795 }
1796 len = strlen(tmp) + 5; /* leave room for -NNN\0 */
1797 container_cgroup = must_alloc(len);
1798 strcpy(container_cgroup, tmp);
1799 free(tmp);
1800 offset = container_cgroup + len - 5;
1801
1802 again:
1803 if (idx == 1000) {
1804 ERROR("Too many conflicting cgroup names");
1805 goto out_free;
1806 }
1807
1808 if (idx) {
1809 int ret;
1810
1811 ret = snprintf(offset, 5, "-%d", idx);
1812 if (ret < 0 || (size_t)ret >= 5) {
1813 FILE *f = fopen("/dev/null", "w");
1814 if (f) {
1815 fprintf(f, "Workaround for GCC7 bug: "
1816 "https://gcc.gnu.org/bugzilla/"
1817 "show_bug.cgi?id=78969");
1818 fclose(f);
1819 }
1820 }
1821 }
1822
1823 for (i = 0; hierarchies[i]; i++) {
1824 if (!create_path_for_hierarchy(hierarchies[i], container_cgroup)) {
1825 int j;
1826 ERROR("Failed to create cgroup \"%s\"", hierarchies[i]->fullcgpath);
1827 free(hierarchies[i]->fullcgpath);
1828 hierarchies[i]->fullcgpath = NULL;
1829 for (j = 0; j < i; j++)
1830 remove_path_for_hierarchy(hierarchies[j], container_cgroup);
1831 idx++;
1832 goto again;
1833 }
1834 }
1835
1836 d->container_cgroup = container_cgroup;
1837
1838 return true;
1839
1840 out_free:
1841 free(container_cgroup);
1842
1843 return false;
1844 }
1845
1846 static bool cgfsng_enter(void *hdata, pid_t pid)
1847 {
1848 int i, len;
1849 char pidstr[25];
1850
1851 len = snprintf(pidstr, 25, "%d", pid);
1852 if (len < 0 || len >= 25)
1853 return false;
1854
1855 for (i = 0; hierarchies[i]; i++) {
1856 int ret;
1857 char *fullpath;
1858
1859 fullpath = must_make_path(hierarchies[i]->fullcgpath,
1860 "cgroup.procs", NULL);
1861 ret = lxc_write_to_file(fullpath, pidstr, len, false);
1862 if (ret != 0) {
1863 SYSERROR("Failed to enter cgroup \"%s\"", fullpath);
1864 free(fullpath);
1865 return false;
1866 }
1867 free(fullpath);
1868 }
1869
1870 return true;
1871 }
1872
1873 static int chowmod(char *path, uid_t chown_uid, gid_t chown_gid,
1874 mode_t chmod_mode)
1875 {
1876 int ret;
1877
1878 ret = chown(path, chown_uid, chown_gid);
1879 if (ret < 0) {
1880 WARN("%s - Failed to chown(%s, %d, %d)", strerror(errno), path,
1881 (int)chown_uid, (int)chown_gid);
1882 return -1;
1883 }
1884
1885 ret = chmod(path, chmod_mode);
1886 if (ret < 0) {
1887 WARN("%s - Failed to chmod(%s, %d)", strerror(errno), path,
1888 (int)chmod_mode);
1889 return -1;
1890 }
1891
1892 return 0;
1893 }
1894
1895 /* chgrp the container cgroups to container group. We leave
1896 * the container owner as cgroup owner. So we must make the
1897 * directories 775 so that the container can create sub-cgroups.
1898 *
1899 * Also chown the tasks and cgroup.procs files. Those may not
1900 * exist depending on kernel version.
1901 */
1902 static int chown_cgroup_wrapper(void *data)
1903 {
1904 int i, ret;
1905 uid_t destuid;
1906 struct generic_userns_exec_data *arg = data;
1907 uid_t nsuid = (arg->conf->root_nsuid_map != NULL) ? 0 : arg->conf->init_uid;
1908 gid_t nsgid = (arg->conf->root_nsgid_map != NULL) ? 0 : arg->conf->init_gid;
1909
1910 ret = setresgid(nsgid, nsgid, nsgid);
1911 if (ret < 0) {
1912 SYSERROR("Failed to setresgid(%d, %d, %d)",
1913 (int)nsgid, (int)nsgid, (int)nsgid);
1914 return -1;
1915 }
1916
1917 ret = setresuid(nsuid, nsuid, nsuid);
1918 if (ret < 0) {
1919 SYSERROR("Failed to setresuid(%d, %d, %d)",
1920 (int)nsuid, (int)nsuid, (int)nsuid);
1921 return -1;
1922 }
1923
1924 ret = setgroups(0, NULL);
1925 if (ret < 0 && errno != EPERM) {
1926 SYSERROR("Failed to setgroups(0, NULL)");
1927 return -1;
1928 }
1929
1930 destuid = get_ns_uid(arg->origuid);
1931
1932 for (i = 0; hierarchies[i]; i++) {
1933 char *fullpath;
1934 char *path = hierarchies[i]->fullcgpath;
1935
1936 ret = chowmod(path, destuid, nsgid, 0775);
1937 if (ret < 0)
1938 return -1;
1939
1940 /* Failures to chown() these are inconvenient but not
1941 * detrimental We leave these owned by the container launcher,
1942 * so that container root can write to the files to attach. We
1943 * chmod() them 664 so that container systemd can write to the
1944 * files (which systemd in wily insists on doing).
1945 */
1946
1947 if (hierarchies[i]->version == CGROUP_SUPER_MAGIC) {
1948 fullpath = must_make_path(path, "tasks", NULL);
1949 (void)chowmod(fullpath, destuid, nsgid, 0664);
1950 free(fullpath);
1951 }
1952
1953 fullpath = must_make_path(path, "cgroup.procs", NULL);
1954 (void)chowmod(fullpath, destuid, 0, 0664);
1955 free(fullpath);
1956
1957 if (hierarchies[i]->version != CGROUP2_SUPER_MAGIC)
1958 continue;
1959
1960 fullpath = must_make_path(path, "cgroup.subtree_control", NULL);
1961 (void)chowmod(fullpath, destuid, nsgid, 0664);
1962 free(fullpath);
1963
1964 fullpath = must_make_path(path, "cgroup.threads", NULL);
1965 (void)chowmod(fullpath, destuid, nsgid, 0664);
1966 free(fullpath);
1967 }
1968
1969 return 0;
1970 }
1971
1972 static bool cgfsng_chown(void *hdata, struct lxc_conf *conf)
1973 {
1974 struct cgfsng_handler_data *d = hdata;
1975 struct generic_userns_exec_data wrap;
1976
1977 if (!d)
1978 return false;
1979
1980 if (lxc_list_empty(&conf->id_map))
1981 return true;
1982
1983 wrap.origuid = geteuid();
1984 wrap.path = NULL;
1985 wrap.d = d;
1986 wrap.conf = conf;
1987
1988 if (userns_exec_1(conf, chown_cgroup_wrapper, &wrap,
1989 "chown_cgroup_wrapper") < 0) {
1990 ERROR("Error requesting cgroup chown in new user namespace");
1991 return false;
1992 }
1993
1994 return true;
1995 }
1996
1997 /* cgroup-full:* is done, no need to create subdirs */
1998 static bool cg_mount_needs_subdirs(int type)
1999 {
2000 if (type >= LXC_AUTO_CGROUP_FULL_RO)
2001 return false;
2002
2003 return true;
2004 }
2005
2006 /* After $rootfs/sys/fs/container/controller/the/cg/path has been created,
2007 * remount controller ro if needed and bindmount the cgroupfs onto
2008 * controll/the/cg/path.
2009 */
2010 static int cg_legacy_mount_controllers(int type, struct hierarchy *h,
2011 char *controllerpath, char *cgpath,
2012 const char *container_cgroup)
2013 {
2014 int ret, remount_flags;
2015 char *sourcepath;
2016 int flags = MS_BIND;
2017
2018 if (type == LXC_AUTO_CGROUP_RO || type == LXC_AUTO_CGROUP_MIXED) {
2019 ret = mount(controllerpath, controllerpath, "cgroup", MS_BIND, NULL);
2020 if (ret < 0) {
2021 SYSERROR("Failed to bind mount \"%s\" onto \"%s\"",
2022 controllerpath, controllerpath);
2023 return -1;
2024 }
2025
2026 remount_flags = add_required_remount_flags(controllerpath,
2027 controllerpath,
2028 flags | MS_REMOUNT);
2029 ret = mount(controllerpath, controllerpath, "cgroup",
2030 MS_REMOUNT | MS_BIND | MS_RDONLY, NULL);
2031 if (ret < 0) {
2032 SYSERROR("Failed to remount \"%s\" ro", controllerpath);
2033 return -1;
2034 }
2035
2036 INFO("Remounted %s read-only", controllerpath);
2037 }
2038
2039 sourcepath = must_make_path(h->mountpoint, h->base_cgroup,
2040 container_cgroup, NULL);
2041 if (type == LXC_AUTO_CGROUP_RO)
2042 flags |= MS_RDONLY;
2043
2044 ret = mount(sourcepath, cgpath, "cgroup", flags, NULL);
2045 if (ret < 0) {
2046 SYSERROR("Failed to mount \"%s\" onto \"%s\"", h->controllers[0], cgpath);
2047 free(sourcepath);
2048 return -1;
2049 }
2050 INFO("Mounted \"%s\" onto \"%s\"", h->controllers[0], cgpath);
2051
2052 if (flags & MS_RDONLY) {
2053 remount_flags = add_required_remount_flags(sourcepath, cgpath,
2054 flags | MS_REMOUNT);
2055 ret = mount(sourcepath, cgpath, "cgroup", remount_flags, NULL);
2056 if (ret < 0) {
2057 SYSERROR("Failed to remount \"%s\" ro", cgpath);
2058 free(sourcepath);
2059 return -1;
2060 }
2061 INFO("Remounted %s read-only", cgpath);
2062 }
2063
2064 free(sourcepath);
2065 INFO("Completed second stage cgroup automounts for \"%s\"", cgpath);
2066 return 0;
2067 }
2068
2069 /* __cg_mount_direct
2070 *
2071 * Mount cgroup hierarchies directly without using bind-mounts. The main
2072 * uses-cases are mounting cgroup hierarchies in cgroup namespaces and mounting
2073 * cgroups for the LXC_AUTO_CGROUP_FULL option.
2074 */
2075 static int __cg_mount_direct(int type, struct hierarchy *h,
2076 const char *controllerpath)
2077 {
2078 int ret;
2079 char *controllers = NULL;
2080 char *fstype = "cgroup2";
2081 unsigned long flags = 0;
2082
2083 flags |= MS_NOSUID;
2084 flags |= MS_NOEXEC;
2085 flags |= MS_NODEV;
2086 flags |= MS_RELATIME;
2087
2088 if (type == LXC_AUTO_CGROUP_RO || type == LXC_AUTO_CGROUP_FULL_RO)
2089 flags |= MS_RDONLY;
2090
2091 if (h->version != CGROUP2_SUPER_MAGIC) {
2092 controllers = lxc_string_join(",", (const char **)h->controllers, false);
2093 if (!controllers)
2094 return -ENOMEM;
2095 fstype = "cgroup";
2096 }
2097
2098 ret = mount("cgroup", controllerpath, fstype, flags, controllers);
2099 free(controllers);
2100 if (ret < 0) {
2101 SYSERROR("Failed to mount \"%s\" with cgroup filesystem type %s", controllerpath, fstype);
2102 return -1;
2103 }
2104
2105 DEBUG("Mounted \"%s\" with cgroup filesystem type %s", controllerpath, fstype);
2106 return 0;
2107 }
2108
2109 static inline int cg_mount_in_cgroup_namespace(int type, struct hierarchy *h,
2110 const char *controllerpath)
2111 {
2112 return __cg_mount_direct(type, h, controllerpath);
2113 }
2114
2115 static inline int cg_mount_cgroup_full(int type, struct hierarchy *h,
2116 const char *controllerpath)
2117 {
2118 if (type < LXC_AUTO_CGROUP_FULL_RO || type > LXC_AUTO_CGROUP_FULL_MIXED)
2119 return 0;
2120
2121 return __cg_mount_direct(type, h, controllerpath);
2122 }
2123
2124 static bool cgfsng_mount(void *hdata, const char *root, int type)
2125 {
2126 int i, ret;
2127 char *tmpfspath = NULL;
2128 bool has_cgns = false, retval = false, wants_force_mount = false;
2129 struct lxc_handler *handler = hdata;
2130 struct cgfsng_handler_data *d = handler->cgroup_data;
2131
2132 if ((type & LXC_AUTO_CGROUP_MASK) == 0)
2133 return true;
2134
2135 if (type & LXC_AUTO_CGROUP_FORCE) {
2136 type &= ~LXC_AUTO_CGROUP_FORCE;
2137 wants_force_mount = true;
2138 }
2139
2140 if (!wants_force_mount){
2141 if (!lxc_list_empty(&handler->conf->keepcaps))
2142 wants_force_mount = !in_caplist(CAP_SYS_ADMIN, &handler->conf->keepcaps);
2143 else
2144 wants_force_mount = in_caplist(CAP_SYS_ADMIN, &handler->conf->caps);
2145 }
2146
2147 has_cgns = cgns_supported();
2148 if (has_cgns && !wants_force_mount)
2149 return true;
2150
2151 if (type == LXC_AUTO_CGROUP_NOSPEC)
2152 type = LXC_AUTO_CGROUP_MIXED;
2153 else if (type == LXC_AUTO_CGROUP_FULL_NOSPEC)
2154 type = LXC_AUTO_CGROUP_FULL_MIXED;
2155
2156 /* Mount tmpfs */
2157 tmpfspath = must_make_path(root, "/sys/fs/cgroup", NULL);
2158 ret = safe_mount(NULL, tmpfspath, "tmpfs",
2159 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_RELATIME,
2160 "size=10240k,mode=755", root);
2161 if (ret < 0)
2162 goto on_error;
2163
2164 for (i = 0; hierarchies[i]; i++) {
2165 char *controllerpath, *path2;
2166 struct hierarchy *h = hierarchies[i];
2167 char *controller = strrchr(h->mountpoint, '/');
2168
2169 if (!controller)
2170 continue;
2171 controller++;
2172
2173 controllerpath = must_make_path(tmpfspath, controller, NULL);
2174 if (dir_exists(controllerpath)) {
2175 free(controllerpath);
2176 continue;
2177 }
2178
2179 ret = mkdir(controllerpath, 0755);
2180 if (ret < 0) {
2181 SYSERROR("Error creating cgroup path: %s", controllerpath);
2182 free(controllerpath);
2183 goto on_error;
2184 }
2185
2186 if (has_cgns && wants_force_mount) {
2187 /* If cgroup namespaces are supported but the container
2188 * will not have CAP_SYS_ADMIN after it has started we
2189 * need to mount the cgroups manually.
2190 */
2191 ret = cg_mount_in_cgroup_namespace(type, h, controllerpath);
2192 free(controllerpath);
2193 if (ret < 0)
2194 goto on_error;
2195
2196 continue;
2197 }
2198
2199 ret = cg_mount_cgroup_full(type, h, controllerpath);
2200 if (ret < 0) {
2201 free(controllerpath);
2202 goto on_error;
2203 }
2204
2205 if (!cg_mount_needs_subdirs(type)) {
2206 free(controllerpath);
2207 continue;
2208 }
2209
2210 path2 = must_make_path(controllerpath, h->base_cgroup,
2211 d->container_cgroup, NULL);
2212 ret = mkdir_p(path2, 0755);
2213 if (ret < 0) {
2214 free(controllerpath);
2215 free(path2);
2216 goto on_error;
2217 }
2218
2219 ret = cg_legacy_mount_controllers(type, h, controllerpath,
2220 path2, d->container_cgroup);
2221 free(controllerpath);
2222 free(path2);
2223 if (ret < 0)
2224 goto on_error;
2225 }
2226 retval = true;
2227
2228 on_error:
2229 free(tmpfspath);
2230 return retval;
2231 }
2232
2233 static int recursive_count_nrtasks(char *dirname)
2234 {
2235 struct dirent *direntp;
2236 DIR *dir;
2237 int count = 0, ret;
2238 char *path;
2239
2240 dir = opendir(dirname);
2241 if (!dir)
2242 return 0;
2243
2244 while ((direntp = readdir(dir))) {
2245 struct stat mystat;
2246
2247 if (!direntp)
2248 break;
2249
2250 if (!strcmp(direntp->d_name, ".") ||
2251 !strcmp(direntp->d_name, ".."))
2252 continue;
2253
2254 path = must_make_path(dirname, direntp->d_name, NULL);
2255
2256 if (lstat(path, &mystat))
2257 goto next;
2258
2259 if (!S_ISDIR(mystat.st_mode))
2260 goto next;
2261
2262 count += recursive_count_nrtasks(path);
2263 next:
2264 free(path);
2265 }
2266
2267 path = must_make_path(dirname, "cgroup.procs", NULL);
2268 ret = lxc_count_file_lines(path);
2269 if (ret != -1)
2270 count += ret;
2271 free(path);
2272
2273 (void)closedir(dir);
2274
2275 return count;
2276 }
2277
2278 static int cgfsng_nrtasks(void *hdata)
2279 {
2280 int count;
2281 char *path;
2282 struct cgfsng_handler_data *d = hdata;
2283
2284 if (!d || !d->container_cgroup || !hierarchies)
2285 return -1;
2286
2287 path = must_make_path(hierarchies[0]->fullcgpath, NULL);
2288 count = recursive_count_nrtasks(path);
2289 free(path);
2290 return count;
2291 }
2292
2293 /* Only root needs to escape to the cgroup of its init. */
2294 static bool cgfsng_escape()
2295 {
2296 int i;
2297
2298 if (geteuid())
2299 return true;
2300
2301 for (i = 0; hierarchies[i]; i++) {
2302 int ret;
2303 char *fullpath;
2304
2305 fullpath = must_make_path(hierarchies[i]->mountpoint,
2306 hierarchies[i]->base_cgroup,
2307 "cgroup.procs", NULL);
2308 ret = lxc_write_to_file(fullpath, "0", 2, false);
2309 if (ret != 0) {
2310 SYSERROR("Failed to escape to cgroup \"%s\"", fullpath);
2311 free(fullpath);
2312 return false;
2313 }
2314 free(fullpath);
2315 }
2316
2317 return true;
2318 }
2319
2320 static int cgfsng_num_hierarchies(void)
2321 {
2322 int i;
2323
2324 for (i = 0; hierarchies[i]; i++)
2325 ;
2326
2327 return i;
2328 }
2329
2330 static bool cgfsng_get_hierarchies(int n, char ***out)
2331 {
2332 int i;
2333
2334 /* sanity check n */
2335 for (i = 0; i < n; i++)
2336 if (!hierarchies[i])
2337 return false;
2338
2339 *out = hierarchies[i]->controllers;
2340
2341 return true;
2342 }
2343
2344 #define THAWED "THAWED"
2345 #define THAWED_LEN (strlen(THAWED))
2346
2347 /* TODO: If the unified cgroup hierarchy grows a freezer controller this needs
2348 * to be adapted.
2349 */
2350 static bool cgfsng_unfreeze(void *hdata)
2351 {
2352 int ret;
2353 char *fullpath;
2354 struct hierarchy *h;
2355
2356 h = get_hierarchy("freezer");
2357 if (!h)
2358 return false;
2359
2360 fullpath = must_make_path(h->fullcgpath, "freezer.state", NULL);
2361 ret = lxc_write_to_file(fullpath, THAWED, THAWED_LEN, false);
2362 free(fullpath);
2363 if (ret < 0)
2364 return false;
2365
2366 return true;
2367 }
2368
2369 static const char *cgfsng_get_cgroup(void *hdata, const char *controller)
2370 {
2371 struct hierarchy *h;
2372
2373 h = get_hierarchy(controller);
2374 if (!h) {
2375 SYSERROR("Failed to find hierarchy for controller \"%s\"",
2376 controller ? controller : "(null)");
2377 return NULL;
2378 }
2379
2380 return h->fullcgpath ? h->fullcgpath + strlen(h->mountpoint) : NULL;
2381 }
2382
2383 /* Given a cgroup path returned from lxc_cmd_get_cgroup_path, build a full path,
2384 * which must be freed by the caller.
2385 */
2386 static inline char *build_full_cgpath_from_monitorpath(struct hierarchy *h,
2387 const char *inpath,
2388 const char *filename)
2389 {
2390 return must_make_path(h->mountpoint, inpath, filename, NULL);
2391 }
2392
2393 /* Technically, we're always at a delegation boundary here (This is especially
2394 * true when cgroup namespaces are available.). The reasoning is that in order
2395 * for us to have been able to start a container in the first place the root
2396 * cgroup must have been a leaf node. Now, either the container's init system
2397 * has populated the cgroup and kept it as a leaf node or it has created
2398 * subtrees. In the former case we will simply attach to the leaf node we
2399 * created when we started the container in the latter case we create our own
2400 * cgroup for the attaching process.
2401 */
2402 static int __cg_unified_attach(const struct hierarchy *h, const char *name,
2403 const char *lxcpath, const char *pidstr,
2404 size_t pidstr_len, const char *controller)
2405 {
2406 int ret;
2407 size_t len;
2408 int fret = -1, idx = 0;
2409 char *base_path = NULL, *container_cgroup = NULL, *full_path = NULL;
2410
2411 container_cgroup = lxc_cmd_get_cgroup_path(name, lxcpath, controller);
2412 /* not running */
2413 if (!container_cgroup)
2414 return 0;
2415
2416 base_path = must_make_path(h->mountpoint, container_cgroup, NULL);
2417 full_path = must_make_path(base_path, "cgroup.procs", NULL);
2418 /* cgroup is populated */
2419 ret = lxc_write_to_file(full_path, pidstr, pidstr_len, false);
2420 if (ret < 0 && errno != EBUSY)
2421 goto on_error;
2422
2423 if (ret == 0)
2424 goto on_success;
2425
2426 free(full_path);
2427
2428 len = strlen(base_path) + sizeof("/lxc-1000") - 1 +
2429 sizeof("/cgroup-procs") - 1;
2430 full_path = must_alloc(len + 1);
2431 do {
2432 if (idx)
2433 ret = snprintf(full_path, len + 1, "%s/lxc-%d",
2434 base_path, idx);
2435 else
2436 ret = snprintf(full_path, len + 1, "%s/lxc", base_path);
2437 if (ret < 0 || (size_t)ret >= len + 1)
2438 goto on_error;
2439
2440 ret = mkdir_p(full_path, 0755);
2441 if (ret < 0 && errno != EEXIST)
2442 goto on_error;
2443
2444 strcat(full_path, "/cgroup.procs");
2445 ret = lxc_write_to_file(full_path, pidstr, len, false);
2446 if (ret == 0)
2447 goto on_success;
2448
2449 /* this is a non-leaf node */
2450 if (errno != EBUSY)
2451 goto on_error;
2452
2453 } while (++idx > 0 && idx < 1000);
2454
2455 on_success:
2456 if (idx < 1000)
2457 fret = 0;
2458
2459 on_error:
2460 free(base_path);
2461 free(container_cgroup);
2462 free(full_path);
2463
2464 return fret;
2465 }
2466
2467 static bool cgfsng_attach(const char *name, const char *lxcpath, pid_t pid)
2468 {
2469 int i, len, ret;
2470 char pidstr[25];
2471
2472 len = snprintf(pidstr, 25, "%d", pid);
2473 if (len < 0 || len >= 25)
2474 return false;
2475
2476 for (i = 0; hierarchies[i]; i++) {
2477 char *path;
2478 char *fullpath = NULL;
2479 struct hierarchy *h = hierarchies[i];
2480
2481 if (h->version == CGROUP2_SUPER_MAGIC) {
2482 ret = __cg_unified_attach(h, name, lxcpath, pidstr, len,
2483 h->controllers[0]);
2484 if (ret < 0)
2485 return false;
2486
2487 continue;
2488 }
2489
2490 path = lxc_cmd_get_cgroup_path(name, lxcpath, h->controllers[0]);
2491 /* not running */
2492 if (!path)
2493 continue;
2494
2495 fullpath = build_full_cgpath_from_monitorpath(h, path, "cgroup.procs");
2496 ret = lxc_write_to_file(fullpath, pidstr, len, false);
2497 if (ret < 0) {
2498 SYSERROR("Failed to attach %d to %s", (int)pid, fullpath);
2499 free(fullpath);
2500 return false;
2501 }
2502 free(fullpath);
2503 }
2504
2505 return true;
2506 }
2507
2508 /* Called externally (i.e. from 'lxc-cgroup') to query cgroup limits. Here we
2509 * don't have a cgroup_data set up, so we ask the running container through the
2510 * commands API for the cgroup path.
2511 */
2512 static int cgfsng_get(const char *filename, char *value, size_t len,
2513 const char *name, const char *lxcpath)
2514 {
2515 int ret = -1;
2516 size_t controller_len;
2517 char *controller, *p, *path;
2518 struct hierarchy *h;
2519
2520 controller_len = strlen(filename);
2521 controller = alloca(controller_len + 1);
2522 strcpy(controller, filename);
2523 p = strchr(controller, '.');
2524 if (p)
2525 *p = '\0';
2526
2527 path = lxc_cmd_get_cgroup_path(name, lxcpath, controller);
2528 /* not running */
2529 if (!path)
2530 return -1;
2531
2532 h = get_hierarchy(controller);
2533 if (h) {
2534 char *fullpath;
2535
2536 fullpath = build_full_cgpath_from_monitorpath(h, path, filename);
2537 ret = lxc_read_from_file(fullpath, value, len);
2538 free(fullpath);
2539 }
2540 free(path);
2541
2542 return ret;
2543 }
2544
2545 /* Called externally (i.e. from 'lxc-cgroup') to set new cgroup limits. Here we
2546 * don't have a cgroup_data set up, so we ask the running container through the
2547 * commands API for the cgroup path.
2548 */
2549 static int cgfsng_set(const char *filename, const char *value, const char *name,
2550 const char *lxcpath)
2551 {
2552 int ret = -1;
2553 size_t controller_len;
2554 char *controller, *p, *path;
2555 struct hierarchy *h;
2556
2557 controller_len = strlen(filename);
2558 controller = alloca(controller_len + 1);
2559 strcpy(controller, filename);
2560 p = strchr(controller, '.');
2561 if (p)
2562 *p = '\0';
2563
2564 path = lxc_cmd_get_cgroup_path(name, lxcpath, controller);
2565 /* not running */
2566 if (!path)
2567 return -1;
2568
2569 h = get_hierarchy(controller);
2570 if (h) {
2571 char *fullpath;
2572
2573 fullpath = build_full_cgpath_from_monitorpath(h, path, filename);
2574 ret = lxc_write_to_file(fullpath, value, strlen(value), false);
2575 free(fullpath);
2576 }
2577 free(path);
2578
2579 return ret;
2580 }
2581
2582 /* take devices cgroup line
2583 * /dev/foo rwx
2584 * and convert it to a valid
2585 * type major:minor mode
2586 * line. Return <0 on error. Dest is a preallocated buffer long enough to hold
2587 * the output.
2588 */
2589 static int convert_devpath(const char *invalue, char *dest)
2590 {
2591 int n_parts;
2592 char *p, *path, type;
2593 unsigned long minor, major;
2594 struct stat sb;
2595 int ret = -EINVAL;
2596 char *mode = NULL;
2597
2598 path = must_copy_string(invalue);
2599
2600 /* Read path followed by mode. Ignore any trailing text.
2601 * A ' # comment' would be legal. Technically other text is not
2602 * legal, we could check for that if we cared to.
2603 */
2604 for (n_parts = 1, p = path; *p && n_parts < 3; p++) {
2605 if (*p != ' ')
2606 continue;
2607 *p = '\0';
2608
2609 if (n_parts != 1)
2610 break;
2611 p++;
2612 n_parts++;
2613
2614 while (*p == ' ')
2615 p++;
2616
2617 mode = p;
2618
2619 if (*p == '\0')
2620 goto out;
2621 }
2622
2623 if (n_parts == 1)
2624 goto out;
2625
2626 ret = stat(path, &sb);
2627 if (ret < 0)
2628 goto out;
2629
2630 mode_t m = sb.st_mode & S_IFMT;
2631 switch (m) {
2632 case S_IFBLK:
2633 type = 'b';
2634 break;
2635 case S_IFCHR:
2636 type = 'c';
2637 break;
2638 default:
2639 ERROR("Unsupported device type %i for \"%s\"", m, path);
2640 ret = -EINVAL;
2641 goto out;
2642 }
2643
2644 major = MAJOR(sb.st_rdev);
2645 minor = MINOR(sb.st_rdev);
2646 ret = snprintf(dest, 50, "%c %lu:%lu %s", type, major, minor, mode);
2647 if (ret < 0 || ret >= 50) {
2648 ERROR("Error on configuration value \"%c %lu:%lu %s\" (max 50 "
2649 "chars)", type, major, minor, mode);
2650 ret = -ENAMETOOLONG;
2651 goto out;
2652 }
2653 ret = 0;
2654
2655 out:
2656 free(path);
2657 return ret;
2658 }
2659
2660 /* Called from setup_limits - here we have the container's cgroup_data because
2661 * we created the cgroups.
2662 */
2663 static int cg_legacy_set_data(const char *filename, const char *value,
2664 struct cgfsng_handler_data *d)
2665 {
2666 size_t len;
2667 char *fullpath, *p;
2668 /* "b|c <2^64-1>:<2^64-1> r|w|m" = 47 chars max */
2669 char converted_value[50];
2670 struct hierarchy *h;
2671 int ret = 0;
2672 char *controller = NULL;
2673
2674 len = strlen(filename);
2675 controller = alloca(len + 1);
2676 strcpy(controller, filename);
2677 p = strchr(controller, '.');
2678 if (p)
2679 *p = '\0';
2680
2681 if (strcmp("devices.allow", filename) == 0 && value[0] == '/') {
2682 ret = convert_devpath(value, converted_value);
2683 if (ret < 0)
2684 return ret;
2685 value = converted_value;
2686 }
2687
2688 h = get_hierarchy(controller);
2689 if (!h) {
2690 ERROR("Failed to setup limits for the \"%s\" controller. "
2691 "The controller seems to be unused by \"cgfsng\" cgroup "
2692 "driver or not enabled on the cgroup hierarchy",
2693 controller);
2694 errno = ENOENT;
2695 return -ENOENT;
2696 }
2697
2698 fullpath = must_make_path(h->fullcgpath, filename, NULL);
2699 ret = lxc_write_to_file(fullpath, value, strlen(value), false);
2700 free(fullpath);
2701 return ret;
2702 }
2703
2704 static bool __cg_legacy_setup_limits(void *hdata,
2705 struct lxc_list *cgroup_settings,
2706 bool do_devices)
2707 {
2708 struct lxc_list *iterator, *next, *sorted_cgroup_settings;
2709 struct lxc_cgroup *cg;
2710 struct cgfsng_handler_data *d = hdata;
2711 bool ret = false;
2712
2713 if (lxc_list_empty(cgroup_settings))
2714 return true;
2715
2716 sorted_cgroup_settings = sort_cgroup_settings(cgroup_settings);
2717 if (!sorted_cgroup_settings)
2718 return false;
2719
2720 lxc_list_for_each(iterator, sorted_cgroup_settings) {
2721 cg = iterator->elem;
2722
2723 if (do_devices == !strncmp("devices", cg->subsystem, 7)) {
2724 if (cg_legacy_set_data(cg->subsystem, cg->value, d)) {
2725 if (do_devices && (errno == EACCES || errno == EPERM)) {
2726 WARN("Failed to set \"%s\" to \"%s\"",
2727 cg->subsystem, cg->value);
2728 continue;
2729 }
2730 WARN("Failed to set \"%s\" to \"%s\"",
2731 cg->subsystem, cg->value);
2732 goto out;
2733 }
2734 DEBUG("Set controller \"%s\" set to \"%s\"",
2735 cg->subsystem, cg->value);
2736 }
2737 }
2738
2739 ret = true;
2740 INFO("Limits for the legacy cgroup hierarchies have been setup");
2741 out:
2742 lxc_list_for_each_safe(iterator, sorted_cgroup_settings, next) {
2743 lxc_list_del(iterator);
2744 free(iterator);
2745 }
2746 free(sorted_cgroup_settings);
2747 return ret;
2748 }
2749
2750 static bool __cg_unified_setup_limits(void *hdata,
2751 struct lxc_list *cgroup_settings)
2752 {
2753 struct lxc_list *iterator;
2754 struct hierarchy *h = unified;
2755
2756 if (lxc_list_empty(cgroup_settings))
2757 return true;
2758
2759 if (!h)
2760 return false;
2761
2762 lxc_list_for_each(iterator, cgroup_settings) {
2763 int ret;
2764 char *fullpath;
2765 struct lxc_cgroup *cg = iterator->elem;
2766
2767 fullpath = must_make_path(h->fullcgpath, cg->subsystem, NULL);
2768 ret = lxc_write_to_file(fullpath, cg->value, strlen(cg->value), false);
2769 free(fullpath);
2770 if (ret < 0) {
2771 SYSERROR("Failed to set \"%s\" to \"%s\"",
2772 cg->subsystem, cg->value);
2773 return false;
2774 }
2775 TRACE("Set \"%s\" to \"%s\"", cg->subsystem, cg->value);
2776 }
2777
2778 INFO("Limits for the unified cgroup hierarchy have been setup");
2779 return true;
2780 }
2781
2782 static bool cgfsng_setup_limits(void *hdata, struct lxc_conf *conf,
2783 bool do_devices)
2784 {
2785 bool bret;
2786
2787 bret = __cg_legacy_setup_limits(hdata, &conf->cgroup, do_devices);
2788 if (!bret)
2789 return false;
2790
2791 return __cg_unified_setup_limits(hdata, &conf->cgroup2);
2792 }
2793
2794 static struct cgroup_ops cgfsng_ops = {
2795 .init = cgfsng_init,
2796 .destroy = cgfsng_destroy,
2797 .create = cgfsng_create,
2798 .enter = cgfsng_enter,
2799 .escape = cgfsng_escape,
2800 .num_hierarchies = cgfsng_num_hierarchies,
2801 .get_hierarchies = cgfsng_get_hierarchies,
2802 .get_cgroup = cgfsng_get_cgroup,
2803 .get = cgfsng_get,
2804 .set = cgfsng_set,
2805 .unfreeze = cgfsng_unfreeze,
2806 .setup_limits = cgfsng_setup_limits,
2807 .driver = "cgfsng",
2808 .version = "1.0.0",
2809 .attach = cgfsng_attach,
2810 .chown = cgfsng_chown,
2811 .mount_cgroup = cgfsng_mount,
2812 .nrtasks = cgfsng_nrtasks,
2813 };