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