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