]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/cgroups/cgfsng.c
cgroups: ignore legacy limits on pure cgroup2 systems
[mirror_lxc.git] / src / lxc / cgroups / cgfsng.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 /*
4 * cgfs-ng.c: this is a new, simplified implementation of a filesystem
5 * cgroup backend. The original cgfs.c was designed to be as flexible
6 * as possible. It would try to find cgroup filesystems no matter where
7 * or how you had them mounted, and deduce the most usable mount for
8 * each controller.
9 *
10 * This new implementation assumes that cgroup filesystems are mounted
11 * under /sys/fs/cgroup/clist where clist is either the controller, or
12 * a comma-separated list of controllers.
13 */
14
15 #ifndef _GNU_SOURCE
16 #define _GNU_SOURCE 1
17 #endif
18 #include <ctype.h>
19 #include <dirent.h>
20 #include <errno.h>
21 #include <grp.h>
22 #include <linux/kdev_t.h>
23 #include <linux/types.h>
24 #include <poll.h>
25 #include <signal.h>
26 #include <stdint.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/types.h>
31 #include <unistd.h>
32
33 #include "af_unix.h"
34 #include "caps.h"
35 #include "cgroup.h"
36 #include "cgroup2_devices.h"
37 #include "cgroup_utils.h"
38 #include "commands.h"
39 #include "conf.h"
40 #include "config.h"
41 #include "log.h"
42 #include "macro.h"
43 #include "mainloop.h"
44 #include "memory_utils.h"
45 #include "storage/storage.h"
46 #include "utils.h"
47
48 #ifndef HAVE_STRLCPY
49 #include "include/strlcpy.h"
50 #endif
51
52 #ifndef HAVE_STRLCAT
53 #include "include/strlcat.h"
54 #endif
55
56 lxc_log_define(cgfsng, cgroup);
57
58 /* Given a pointer to a null-terminated array of pointers, realloc to add one
59 * entry, and point the new entry to NULL. Do not fail. Return the index to the
60 * second-to-last entry - that is, the one which is now available for use
61 * (keeping the list null-terminated).
62 */
63 static int append_null_to_list(void ***list)
64 {
65 int newentry = 0;
66
67 if (*list)
68 for (; (*list)[newentry]; newentry++)
69 ;
70
71 *list = must_realloc(*list, (newentry + 2) * sizeof(void **));
72 (*list)[newentry + 1] = NULL;
73 return newentry;
74 }
75
76 /* Given a null-terminated array of strings, check whether @entry is one of the
77 * strings.
78 */
79 static bool string_in_list(char **list, const char *entry)
80 {
81 if (!list)
82 return false;
83
84 for (int i = 0; list[i]; i++)
85 if (strcmp(list[i], entry) == 0)
86 return true;
87
88 return false;
89 }
90
91 /* Return a copy of @entry prepending "name=", i.e. turn "systemd" into
92 * "name=systemd". Do not fail.
93 */
94 static char *cg_legacy_must_prefix_named(char *entry)
95 {
96 size_t len;
97 char *prefixed;
98
99 len = strlen(entry);
100 prefixed = must_realloc(NULL, len + 6);
101
102 memcpy(prefixed, "name=", STRLITERALLEN("name="));
103 memcpy(prefixed + STRLITERALLEN("name="), entry, len);
104 prefixed[len + 5] = '\0';
105
106 return prefixed;
107 }
108
109 /* Append an entry to the clist. Do not fail. @clist must be NULL the first time
110 * we are called.
111 *
112 * We also handle named subsystems here. Any controller which is not a kernel
113 * subsystem, we prefix "name=". Any which is both a kernel and named subsystem,
114 * we refuse to use because we're not sure which we have here.
115 * (TODO: We could work around this in some cases by just remounting to be
116 * unambiguous, or by comparing mountpoint contents with current cgroup.)
117 *
118 * The last entry will always be NULL.
119 */
120 static void must_append_controller(char **klist, char **nlist, char ***clist,
121 char *entry)
122 {
123 int newentry;
124 char *copy;
125
126 if (string_in_list(klist, entry) && string_in_list(nlist, entry)) {
127 ERROR("Refusing to use ambiguous controller \"%s\"", entry);
128 ERROR("It is both a named and kernel subsystem");
129 return;
130 }
131
132 newentry = append_null_to_list((void ***)clist);
133
134 if (strncmp(entry, "name=", 5) == 0)
135 copy = must_copy_string(entry);
136 else if (string_in_list(klist, entry))
137 copy = must_copy_string(entry);
138 else
139 copy = cg_legacy_must_prefix_named(entry);
140
141 (*clist)[newentry] = copy;
142 }
143
144 /* Given a handler's cgroup data, return the struct hierarchy for the controller
145 * @c, or NULL if there is none.
146 */
147 struct hierarchy *get_hierarchy(struct cgroup_ops *ops, const char *controller)
148 {
149 if (!ops->hierarchies)
150 return log_trace_errno(NULL, errno, "There are no useable cgroup controllers");
151
152 for (int i = 0; ops->hierarchies[i]; i++) {
153 if (!controller) {
154 /* This is the empty unified hierarchy. */
155 if (ops->hierarchies[i]->controllers &&
156 !ops->hierarchies[i]->controllers[0])
157 return ops->hierarchies[i];
158 continue;
159 } else if (pure_unified_layout(ops) &&
160 strcmp(controller, "devices") == 0) {
161 if (ops->unified->bpf_device_controller)
162 return ops->unified;
163 break;
164 }
165
166 if (string_in_list(ops->hierarchies[i]->controllers, controller))
167 return ops->hierarchies[i];
168 }
169
170 if (controller)
171 WARN("There is no useable %s controller", controller);
172 else
173 WARN("There is no empty unified cgroup hierarchy");
174
175 return ret_set_errno(NULL, ENOENT);
176 }
177
178 #define BATCH_SIZE 50
179 static void batch_realloc(char **mem, size_t oldlen, size_t newlen)
180 {
181 int newbatches = (newlen / BATCH_SIZE) + 1;
182 int oldbatches = (oldlen / BATCH_SIZE) + 1;
183
184 if (!*mem || newbatches > oldbatches)
185 *mem = must_realloc(*mem, newbatches * BATCH_SIZE);
186 }
187
188 static void append_line(char **dest, size_t oldlen, char *new, size_t newlen)
189 {
190 size_t full = oldlen + newlen;
191
192 batch_realloc(dest, oldlen, full + 1);
193
194 memcpy(*dest + oldlen, new, newlen + 1);
195 }
196
197 /* Slurp in a whole file */
198 static char *read_file(const char *fnam)
199 {
200 __do_free char *buf = NULL, *line = NULL;
201 __do_fclose FILE *f = NULL;
202 size_t len = 0, fulllen = 0;
203 int linelen;
204
205 f = fopen(fnam, "re");
206 if (!f)
207 return NULL;
208
209 while ((linelen = getline(&line, &len, f)) != -1) {
210 append_line(&buf, fulllen, line, linelen);
211 fulllen += linelen;
212 }
213
214 return move_ptr(buf);
215 }
216
217 /* Taken over modified from the kernel sources. */
218 #define NBITS 32 /* bits in uint32_t */
219 #define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
220 #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, NBITS)
221
222 static void set_bit(unsigned bit, uint32_t *bitarr)
223 {
224 bitarr[bit / NBITS] |= (1 << (bit % NBITS));
225 }
226
227 static void clear_bit(unsigned bit, uint32_t *bitarr)
228 {
229 bitarr[bit / NBITS] &= ~(1 << (bit % NBITS));
230 }
231
232 static bool is_set(unsigned bit, uint32_t *bitarr)
233 {
234 return (bitarr[bit / NBITS] & (1 << (bit % NBITS))) != 0;
235 }
236
237 /* Create cpumask from cpulist aka turn:
238 *
239 * 0,2-3
240 *
241 * into bit array
242 *
243 * 1 0 1 1
244 */
245 static uint32_t *lxc_cpumask(char *buf, size_t nbits)
246 {
247 __do_free uint32_t *bitarr = NULL;
248 char *token;
249 size_t arrlen;
250
251 arrlen = BITS_TO_LONGS(nbits);
252 bitarr = calloc(arrlen, sizeof(uint32_t));
253 if (!bitarr)
254 return ret_set_errno(NULL, ENOMEM);
255
256 lxc_iterate_parts(token, buf, ",") {
257 errno = 0;
258 unsigned end, start;
259 char *range;
260
261 start = strtoul(token, NULL, 0);
262 end = start;
263 range = strchr(token, '-');
264 if (range)
265 end = strtoul(range + 1, NULL, 0);
266
267 if (!(start <= end))
268 return ret_set_errno(NULL, EINVAL);
269
270 if (end >= nbits)
271 return ret_set_errno(NULL, EINVAL);
272
273 while (start <= end)
274 set_bit(start++, bitarr);
275 }
276
277 return move_ptr(bitarr);
278 }
279
280 /* Turn cpumask into simple, comma-separated cpulist. */
281 static char *lxc_cpumask_to_cpulist(uint32_t *bitarr, size_t nbits)
282 {
283 __do_free_string_list char **cpulist = NULL;
284 char numstr[INTTYPE_TO_STRLEN(size_t)] = {0};
285 int ret;
286
287 for (size_t i = 0; i <= nbits; i++) {
288 if (!is_set(i, bitarr))
289 continue;
290
291 ret = snprintf(numstr, sizeof(numstr), "%zu", i);
292 if (ret < 0 || (size_t)ret >= sizeof(numstr))
293 return NULL;
294
295 ret = lxc_append_string(&cpulist, numstr);
296 if (ret < 0)
297 return ret_set_errno(NULL, ENOMEM);
298 }
299
300 if (!cpulist)
301 return ret_set_errno(NULL, ENOMEM);
302
303 return lxc_string_join(",", (const char **)cpulist, false);
304 }
305
306 static ssize_t get_max_cpus(char *cpulist)
307 {
308 char *c1, *c2;
309 char *maxcpus = cpulist;
310 size_t cpus = 0;
311
312 c1 = strrchr(maxcpus, ',');
313 if (c1)
314 c1++;
315
316 c2 = strrchr(maxcpus, '-');
317 if (c2)
318 c2++;
319
320 if (!c1 && !c2)
321 c1 = maxcpus;
322 else if (c1 > c2)
323 c2 = c1;
324 else if (c1 < c2)
325 c1 = c2;
326 else if (!c1 && c2)
327 c1 = c2;
328
329 errno = 0;
330 cpus = strtoul(c1, NULL, 0);
331 if (errno != 0)
332 return -1;
333
334 return cpus;
335 }
336
337 #define __ISOL_CPUS "/sys/devices/system/cpu/isolated"
338 #define __OFFLINE_CPUS "/sys/devices/system/cpu/offline"
339 static bool cg_legacy_filter_and_set_cpus(const char *parent_cgroup,
340 char *child_cgroup, bool am_initialized)
341 {
342 __do_free char *cpulist = NULL, *fpath = NULL, *isolcpus = NULL,
343 *offlinecpus = NULL, *posscpus = NULL;
344 __do_free uint32_t *isolmask = NULL, *offlinemask = NULL,
345 *possmask = NULL;
346 int ret;
347 ssize_t i;
348 ssize_t maxisol = 0, maxoffline = 0, maxposs = 0;
349 bool flipped_bit = false;
350
351 fpath = must_make_path(parent_cgroup, "cpuset.cpus", NULL);
352 posscpus = read_file(fpath);
353 if (!posscpus)
354 return log_error_errno(false, errno, "Failed to read file \"%s\"", fpath);
355
356 /* Get maximum number of cpus found in possible cpuset. */
357 maxposs = get_max_cpus(posscpus);
358 if (maxposs < 0 || maxposs >= INT_MAX - 1)
359 return false;
360
361 if (file_exists(__ISOL_CPUS)) {
362 isolcpus = read_file(__ISOL_CPUS);
363 if (!isolcpus)
364 return log_error_errno(false, errno, "Failed to read file \"%s\"", __ISOL_CPUS);
365
366 if (isdigit(isolcpus[0])) {
367 /* Get maximum number of cpus found in isolated cpuset. */
368 maxisol = get_max_cpus(isolcpus);
369 if (maxisol < 0 || maxisol >= INT_MAX - 1)
370 return false;
371 }
372
373 if (maxposs < maxisol)
374 maxposs = maxisol;
375 maxposs++;
376 } else {
377 TRACE("The path \""__ISOL_CPUS"\" to read isolated cpus from does not exist");
378 }
379
380 if (file_exists(__OFFLINE_CPUS)) {
381 offlinecpus = read_file(__OFFLINE_CPUS);
382 if (!offlinecpus)
383 return log_error_errno(false, errno, "Failed to read file \"%s\"", __OFFLINE_CPUS);
384
385 if (isdigit(offlinecpus[0])) {
386 /* Get maximum number of cpus found in offline cpuset. */
387 maxoffline = get_max_cpus(offlinecpus);
388 if (maxoffline < 0 || maxoffline >= INT_MAX - 1)
389 return false;
390 }
391
392 if (maxposs < maxoffline)
393 maxposs = maxoffline;
394 maxposs++;
395 } else {
396 TRACE("The path \""__OFFLINE_CPUS"\" to read offline cpus from does not exist");
397 }
398
399 if ((maxisol == 0) && (maxoffline == 0)) {
400 cpulist = move_ptr(posscpus);
401 goto copy_parent;
402 }
403
404 possmask = lxc_cpumask(posscpus, maxposs);
405 if (!possmask)
406 return log_error_errno(false, errno, "Failed to create cpumask for possible cpus");
407
408 if (maxisol > 0) {
409 isolmask = lxc_cpumask(isolcpus, maxposs);
410 if (!isolmask)
411 return log_error_errno(false, errno, "Failed to create cpumask for isolated cpus");
412 }
413
414 if (maxoffline > 0) {
415 offlinemask = lxc_cpumask(offlinecpus, maxposs);
416 if (!offlinemask)
417 return log_error_errno(false, errno, "Failed to create cpumask for offline cpus");
418 }
419
420 for (i = 0; i <= maxposs; i++) {
421 if ((isolmask && !is_set(i, isolmask)) ||
422 (offlinemask && !is_set(i, offlinemask)) ||
423 !is_set(i, possmask))
424 continue;
425
426 flipped_bit = true;
427 clear_bit(i, possmask);
428 }
429
430 if (!flipped_bit) {
431 cpulist = lxc_cpumask_to_cpulist(possmask, maxposs);
432 TRACE("No isolated or offline cpus present in cpuset");
433 } else {
434 cpulist = move_ptr(posscpus);
435 TRACE("Removed isolated or offline cpus from cpuset");
436 }
437 if (!cpulist)
438 return log_error_errno(false, errno, "Failed to create cpu list");
439
440 copy_parent:
441 if (!am_initialized) {
442 ret = lxc_write_openat(child_cgroup, "cpuset.cpus", cpulist, strlen(cpulist));
443 if (ret < 0)
444 return log_error_errno(false,
445 errno, "Failed to write cpu list to \"%s/cpuset.cpus\"",
446 child_cgroup);
447
448 TRACE("Copied cpu settings of parent cgroup");
449 }
450
451 return true;
452 }
453
454 /* Copy contents of parent(@path)/@file to @path/@file */
455 static bool copy_parent_file(const char *parent_cgroup,
456 const char *child_cgroup, const char *file)
457 {
458 __do_free char *parent_file = NULL, *value = NULL;
459 int len = 0;
460 int ret;
461
462 parent_file = must_make_path(parent_cgroup, file, NULL);
463 len = lxc_read_from_file(parent_file, NULL, 0);
464 if (len <= 0)
465 return log_error_errno(false, errno, "Failed to determine buffer size");
466
467 value = must_realloc(NULL, len + 1);
468 value[len] = '\0';
469 ret = lxc_read_from_file(parent_file, value, len);
470 if (ret != len)
471 return log_error_errno(false, errno, "Failed to read from parent file \"%s\"", parent_file);
472
473 ret = lxc_write_openat(child_cgroup, file, value, len);
474 if (ret < 0 && errno != EACCES)
475 return log_error_errno(false, errno, "Failed to write \"%s\" to file \"%s/%s\"",
476 value, child_cgroup, file);
477 return true;
478 }
479
480 static inline bool is_unified_hierarchy(const struct hierarchy *h)
481 {
482 return h->version == CGROUP2_SUPER_MAGIC;
483 }
484
485 /*
486 * Initialize the cpuset hierarchy in first directory of @cgroup_leaf and set
487 * cgroup.clone_children so that children inherit settings. Since the
488 * h->base_path is populated by init or ourselves, we know it is already
489 * initialized.
490 *
491 * returns -1 on error, 0 when we didn't created a cgroup, 1 if we created a
492 * cgroup.
493 */
494 static int cg_legacy_handle_cpuset_hierarchy(struct hierarchy *h,
495 const char *cgroup_leaf)
496 {
497 __do_free char *parent_cgroup = NULL, *child_cgroup = NULL, *dup = NULL;
498 __do_close int cgroup_fd = -EBADF;
499 int fret = -1;
500 int ret;
501 char v;
502 char *leaf, *slash;
503
504 if (is_unified_hierarchy(h))
505 return 0;
506
507 if (!string_in_list(h->controllers, "cpuset"))
508 return 0;
509
510 if (!cgroup_leaf)
511 return ret_set_errno(-1, EINVAL);
512
513 dup = strdup(cgroup_leaf);
514 if (!dup)
515 return ret_set_errno(-1, ENOMEM);
516
517 parent_cgroup = must_make_path(h->mountpoint, h->container_base_path, NULL);
518
519 leaf = dup;
520 leaf += strspn(leaf, "/");
521 slash = strchr(leaf, '/');
522 if (slash)
523 *slash = '\0';
524 child_cgroup = must_make_path(parent_cgroup, leaf, NULL);
525 if (slash)
526 *slash = '/';
527
528 fret = 1;
529 ret = mkdir(child_cgroup, 0755);
530 if (ret < 0) {
531 if (errno != EEXIST)
532 return log_error_errno(-1, errno, "Failed to create directory \"%s\"", child_cgroup);
533
534 fret = 0;
535 }
536
537 cgroup_fd = lxc_open_dirfd(child_cgroup);
538 if (cgroup_fd < 0)
539 return -1;
540
541 ret = lxc_readat(cgroup_fd, "cgroup.clone_children", &v, 1);
542 if (ret < 0)
543 return log_error_errno(-1, errno, "Failed to read file \"%s/cgroup.clone_children\"", child_cgroup);
544
545 /* Make sure any isolated cpus are removed from cpuset.cpus. */
546 if (!cg_legacy_filter_and_set_cpus(parent_cgroup, child_cgroup, v == '1'))
547 return log_error_errno(-1, errno, "Failed to remove isolated cpus");
548
549 /* Already set for us by someone else. */
550 if (v == '1')
551 TRACE("\"cgroup.clone_children\" was already set to \"1\"");
552
553 /* copy parent's settings */
554 if (!copy_parent_file(parent_cgroup, child_cgroup, "cpuset.mems"))
555 return log_error_errno(-1, errno, "Failed to copy \"cpuset.mems\" settings");
556
557 /* Set clone_children so children inherit our settings */
558 ret = lxc_writeat(cgroup_fd, "cgroup.clone_children", "1", 1);
559 if (ret < 0)
560 return log_error_errno(-1, errno, "Failed to write 1 to \"%s/cgroup.clone_children\"", child_cgroup);
561
562 return fret;
563 }
564
565 /* Given two null-terminated lists of strings, return true if any string is in
566 * both.
567 */
568 static bool controller_lists_intersect(char **l1, char **l2)
569 {
570 if (!l1 || !l2)
571 return false;
572
573 for (int i = 0; l1[i]; i++)
574 if (string_in_list(l2, l1[i]))
575 return true;
576
577 return false;
578 }
579
580 /* For a null-terminated list of controllers @clist, return true if any of those
581 * controllers is already listed the null-terminated list of hierarchies @hlist.
582 * Realistically, if one is present, all must be present.
583 */
584 static bool controller_list_is_dup(struct hierarchy **hlist, char **clist)
585 {
586 if (!hlist)
587 return false;
588
589 for (int i = 0; hlist[i]; i++)
590 if (controller_lists_intersect(hlist[i]->controllers, clist))
591 return true;
592
593 return false;
594 }
595
596 /* Return true if the controller @entry is found in the null-terminated list of
597 * hierarchies @hlist.
598 */
599 static bool controller_found(struct hierarchy **hlist, char *entry)
600 {
601 if (!hlist)
602 return false;
603
604 for (int i = 0; hlist[i]; i++)
605 if (string_in_list(hlist[i]->controllers, entry))
606 return true;
607
608 return false;
609 }
610
611 /* Return true if all of the controllers which we require have been found. The
612 * required list is freezer and anything in lxc.cgroup.use.
613 */
614 static bool all_controllers_found(struct cgroup_ops *ops)
615 {
616 struct hierarchy **hlist;
617
618 if (!ops->cgroup_use)
619 return true;
620
621 hlist = ops->hierarchies;
622 for (char **cur = ops->cgroup_use; cur && *cur; cur++)
623 if (!controller_found(hlist, *cur))
624 return log_error(false, "No %s controller mountpoint found", *cur);
625
626 return true;
627 }
628
629 /* Get the controllers from a mountinfo line There are other ways we could get
630 * this info. For lxcfs, field 3 is /cgroup/controller-list. For cgroupfs, we
631 * could parse the mount options. But we simply assume that the mountpoint must
632 * be /sys/fs/cgroup/controller-list
633 */
634 static char **cg_hybrid_get_controllers(char **klist, char **nlist, char *line,
635 int type)
636 {
637 /* The fourth field is /sys/fs/cgroup/comma-delimited-controller-list
638 * for legacy hierarchies.
639 */
640 __do_free_string_list char **aret = NULL;
641 int i;
642 char *p2, *tok;
643 char *p = line, *sep = ",";
644
645 for (i = 0; i < 4; i++) {
646 p = strchr(p, ' ');
647 if (!p)
648 return NULL;
649 p++;
650 }
651
652 /* Note, if we change how mountinfo works, then our caller will need to
653 * verify /sys/fs/cgroup/ in this field.
654 */
655 if (strncmp(p, DEFAULT_CGROUP_MOUNTPOINT "/", 15) != 0)
656 return log_error(NULL, "Found hierarchy not under " DEFAULT_CGROUP_MOUNTPOINT ": \"%s\"", p);
657
658 p += 15;
659 p2 = strchr(p, ' ');
660 if (!p2)
661 return log_error(NULL, "Corrupt mountinfo");
662 *p2 = '\0';
663
664 if (type == CGROUP_SUPER_MAGIC) {
665 __do_free char *dup = NULL;
666
667 /* strdup() here for v1 hierarchies. Otherwise
668 * lxc_iterate_parts() will destroy mountpoints such as
669 * "/sys/fs/cgroup/cpu,cpuacct".
670 */
671 dup = must_copy_string(p);
672 if (!dup)
673 return NULL;
674
675 lxc_iterate_parts(tok, dup, sep)
676 must_append_controller(klist, nlist, &aret, tok);
677 }
678 *p2 = ' ';
679
680 return move_ptr(aret);
681 }
682
683 static char **cg_unified_make_empty_controller(void)
684 {
685 __do_free_string_list char **aret = NULL;
686 int newentry;
687
688 newentry = append_null_to_list((void ***)&aret);
689 aret[newentry] = NULL;
690 return move_ptr(aret);
691 }
692
693 static char **cg_unified_get_controllers(const char *file)
694 {
695 __do_free char *buf = NULL;
696 __do_free_string_list char **aret = NULL;
697 char *sep = " \t\n";
698 char *tok;
699
700 buf = read_file(file);
701 if (!buf)
702 return NULL;
703
704 lxc_iterate_parts(tok, buf, sep) {
705 int newentry;
706 char *copy;
707
708 newentry = append_null_to_list((void ***)&aret);
709 copy = must_copy_string(tok);
710 aret[newentry] = copy;
711 }
712
713 return move_ptr(aret);
714 }
715
716 static struct hierarchy *add_hierarchy(struct hierarchy ***h, char **clist, char *mountpoint,
717 char *container_base_path, int type)
718 {
719 struct hierarchy *new;
720 int newentry;
721
722 new = zalloc(sizeof(*new));
723 new->controllers = clist;
724 new->mountpoint = mountpoint;
725 new->container_base_path = container_base_path;
726 new->version = type;
727 new->cgfd_con = -EBADF;
728 new->cgfd_limit = -EBADF;
729 new->cgfd_mon = -EBADF;
730
731 newentry = append_null_to_list((void ***)h);
732 (*h)[newentry] = new;
733 return new;
734 }
735
736 /* Get a copy of the mountpoint from @line, which is a line from
737 * /proc/self/mountinfo.
738 */
739 static char *cg_hybrid_get_mountpoint(char *line)
740 {
741 char *p = line, *sret = NULL;
742 size_t len;
743 char *p2;
744
745 for (int i = 0; i < 4; i++) {
746 p = strchr(p, ' ');
747 if (!p)
748 return NULL;
749 p++;
750 }
751
752 if (strncmp(p, DEFAULT_CGROUP_MOUNTPOINT "/", 15) != 0)
753 return NULL;
754
755 p2 = strchr(p + 15, ' ');
756 if (!p2)
757 return NULL;
758 *p2 = '\0';
759
760 len = strlen(p);
761 sret = must_realloc(NULL, len + 1);
762 memcpy(sret, p, len);
763 sret[len] = '\0';
764
765 return sret;
766 }
767
768 /* Given a multi-line string, return a null-terminated copy of the current line. */
769 static char *copy_to_eol(char *p)
770 {
771 char *p2, *sret;
772 size_t len;
773
774 p2 = strchr(p, '\n');
775 if (!p2)
776 return NULL;
777
778 len = p2 - p;
779 sret = must_realloc(NULL, len + 1);
780 memcpy(sret, p, len);
781 sret[len] = '\0';
782
783 return sret;
784 }
785
786 /* cgline: pointer to character after the first ':' in a line in a \n-terminated
787 * /proc/self/cgroup file. Check whether controller c is present.
788 */
789 static bool controller_in_clist(char *cgline, char *c)
790 {
791 __do_free char *tmp = NULL;
792 char *tok, *eol;
793 size_t len;
794
795 eol = strchr(cgline, ':');
796 if (!eol)
797 return false;
798
799 len = eol - cgline;
800 tmp = must_realloc(NULL, len + 1);
801 memcpy(tmp, cgline, len);
802 tmp[len] = '\0';
803
804 lxc_iterate_parts(tok, tmp, ",")
805 if (strcmp(tok, c) == 0)
806 return true;
807
808 return false;
809 }
810
811 /* @basecginfo is a copy of /proc/$$/cgroup. Return the current cgroup for
812 * @controller.
813 */
814 static char *cg_hybrid_get_current_cgroup(char *basecginfo, char *controller,
815 int type)
816 {
817 char *p = basecginfo;
818
819 for (;;) {
820 bool is_cgv2_base_cgroup = false;
821
822 /* cgroup v2 entry in "/proc/<pid>/cgroup": "0::/some/path" */
823 if ((type == CGROUP2_SUPER_MAGIC) && (*p == '0'))
824 is_cgv2_base_cgroup = true;
825
826 p = strchr(p, ':');
827 if (!p)
828 return NULL;
829 p++;
830
831 if (is_cgv2_base_cgroup || (controller && controller_in_clist(p, controller))) {
832 p = strchr(p, ':');
833 if (!p)
834 return NULL;
835 p++;
836 return copy_to_eol(p);
837 }
838
839 p = strchr(p, '\n');
840 if (!p)
841 return NULL;
842 p++;
843 }
844 }
845
846 static void must_append_string(char ***list, char *entry)
847 {
848 int newentry;
849 char *copy;
850
851 newentry = append_null_to_list((void ***)list);
852 copy = must_copy_string(entry);
853 (*list)[newentry] = copy;
854 }
855
856 static int get_existing_subsystems(char ***klist, char ***nlist)
857 {
858 __do_free char *line = NULL;
859 __do_fclose FILE *f = NULL;
860 size_t len = 0;
861
862 f = fopen("/proc/self/cgroup", "re");
863 if (!f)
864 return -1;
865
866 while (getline(&line, &len, f) != -1) {
867 char *p, *p2, *tok;
868 p = strchr(line, ':');
869 if (!p)
870 continue;
871 p++;
872 p2 = strchr(p, ':');
873 if (!p2)
874 continue;
875 *p2 = '\0';
876
877 /* If the kernel has cgroup v2 support, then /proc/self/cgroup
878 * contains an entry of the form:
879 *
880 * 0::/some/path
881 *
882 * In this case we use "cgroup2" as controller name.
883 */
884 if ((p2 - p) == 0) {
885 must_append_string(klist, "cgroup2");
886 continue;
887 }
888
889 lxc_iterate_parts(tok, p, ",") {
890 if (strncmp(tok, "name=", 5) == 0)
891 must_append_string(nlist, tok);
892 else
893 must_append_string(klist, tok);
894 }
895 }
896
897 return 0;
898 }
899
900 static char *trim(char *s)
901 {
902 size_t len;
903
904 len = strlen(s);
905 while ((len > 1) && (s[len - 1] == '\n'))
906 s[--len] = '\0';
907
908 return s;
909 }
910
911 static void lxc_cgfsng_print_hierarchies(struct cgroup_ops *ops)
912 {
913 int i;
914 struct hierarchy **it;
915
916 if (!ops->hierarchies) {
917 TRACE(" No hierarchies found");
918 return;
919 }
920
921 TRACE(" Hierarchies:");
922 for (i = 0, it = ops->hierarchies; it && *it; it++, i++) {
923 int j;
924 char **cit;
925
926 TRACE(" %d: base_cgroup: %s", i, (*it)->container_base_path ? (*it)->container_base_path : "(null)");
927 TRACE(" mountpoint: %s", (*it)->mountpoint ? (*it)->mountpoint : "(null)");
928 TRACE(" controllers:");
929 for (j = 0, cit = (*it)->controllers; cit && *cit; cit++, j++)
930 TRACE(" %d: %s", j, *cit);
931 }
932 }
933
934 static void lxc_cgfsng_print_basecg_debuginfo(char *basecginfo, char **klist,
935 char **nlist)
936 {
937 int k;
938 char **it;
939
940 TRACE("basecginfo is:");
941 TRACE("%s", basecginfo);
942
943 for (k = 0, it = klist; it && *it; it++, k++)
944 TRACE("kernel subsystem %d: %s", k, *it);
945
946 for (k = 0, it = nlist; it && *it; it++, k++)
947 TRACE("named subsystem %d: %s", k, *it);
948 }
949
950 static int cgroup_tree_remove(struct hierarchy **hierarchies,
951 const char *container_cgroup)
952 {
953 if (!container_cgroup || !hierarchies)
954 return 0;
955
956 for (int i = 0; hierarchies[i]; i++) {
957 struct hierarchy *h = hierarchies[i];
958 int ret;
959
960 if (!h->container_limit_path)
961 continue;
962
963 ret = lxc_rm_rf(h->container_limit_path);
964 if (ret < 0)
965 WARN("Failed to destroy \"%s\"", h->container_limit_path);
966
967 if (h->container_limit_path != h->container_full_path)
968 free_disarm(h->container_limit_path);
969 free_disarm(h->container_full_path);
970 }
971
972 return 0;
973 }
974
975 struct generic_userns_exec_data {
976 struct hierarchy **hierarchies;
977 const char *container_cgroup;
978 struct lxc_conf *conf;
979 uid_t origuid; /* target uid in parent namespace */
980 char *path;
981 };
982
983 static int cgroup_tree_remove_wrapper(void *data)
984 {
985 struct generic_userns_exec_data *arg = data;
986 uid_t nsuid = (arg->conf->root_nsuid_map != NULL) ? 0 : arg->conf->init_uid;
987 gid_t nsgid = (arg->conf->root_nsgid_map != NULL) ? 0 : arg->conf->init_gid;
988 int ret;
989
990 if (!lxc_setgroups(0, NULL) && errno != EPERM)
991 return log_error_errno(-1, errno, "Failed to setgroups(0, NULL)");
992
993 ret = setresgid(nsgid, nsgid, nsgid);
994 if (ret < 0)
995 return log_error_errno(-1, errno, "Failed to setresgid(%d, %d, %d)",
996 (int)nsgid, (int)nsgid, (int)nsgid);
997
998 ret = setresuid(nsuid, nsuid, nsuid);
999 if (ret < 0)
1000 return log_error_errno(-1, errno, "Failed to setresuid(%d, %d, %d)",
1001 (int)nsuid, (int)nsuid, (int)nsuid);
1002
1003 return cgroup_tree_remove(arg->hierarchies, arg->container_cgroup);
1004 }
1005
1006 __cgfsng_ops static void cgfsng_payload_destroy(struct cgroup_ops *ops,
1007 struct lxc_handler *handler)
1008 {
1009 int ret;
1010
1011 if (!ops) {
1012 ERROR("Called with uninitialized cgroup operations");
1013 return;
1014 }
1015
1016 if (!ops->hierarchies)
1017 return;
1018
1019 if (!handler) {
1020 ERROR("Called with uninitialized handler");
1021 return;
1022 }
1023
1024 if (!handler->conf) {
1025 ERROR("Called with uninitialized conf");
1026 return;
1027 }
1028
1029 #ifdef HAVE_STRUCT_BPF_CGROUP_DEV_CTX
1030 ret = bpf_program_cgroup_detach(handler->conf->cgroup2_devices);
1031 if (ret < 0)
1032 WARN("Failed to detach bpf program from cgroup");
1033 #endif
1034
1035 if (handler->conf && !lxc_list_empty(&handler->conf->id_map)) {
1036 struct generic_userns_exec_data wrap = {
1037 .conf = handler->conf,
1038 .container_cgroup = ops->container_cgroup,
1039 .hierarchies = ops->hierarchies,
1040 .origuid = 0,
1041 };
1042 ret = userns_exec_1(handler->conf, cgroup_tree_remove_wrapper,
1043 &wrap, "cgroup_tree_remove_wrapper");
1044 } else {
1045 ret = cgroup_tree_remove(ops->hierarchies, ops->container_cgroup);
1046 }
1047 if (ret < 0)
1048 SYSWARN("Failed to destroy cgroups");
1049 }
1050
1051 __cgfsng_ops static void cgfsng_monitor_destroy(struct cgroup_ops *ops,
1052 struct lxc_handler *handler)
1053 {
1054 int len;
1055 char pidstr[INTTYPE_TO_STRLEN(pid_t)];
1056 const struct lxc_conf *conf;
1057
1058 if (!ops) {
1059 ERROR("Called with uninitialized cgroup operations");
1060 return;
1061 }
1062
1063 if (!ops->hierarchies)
1064 return;
1065
1066 if (!handler) {
1067 ERROR("Called with uninitialized handler");
1068 return;
1069 }
1070
1071 if (!handler->conf) {
1072 ERROR("Called with uninitialized conf");
1073 return;
1074 }
1075 conf = handler->conf;
1076
1077 len = snprintf(pidstr, sizeof(pidstr), "%d", handler->monitor_pid);
1078 if (len < 0 || (size_t)len >= sizeof(pidstr))
1079 return;
1080
1081 for (int i = 0; ops->hierarchies[i]; i++) {
1082 __do_free char *pivot_path = NULL;
1083 struct hierarchy *h = ops->hierarchies[i];
1084 int ret;
1085
1086 if (!h->monitor_full_path)
1087 continue;
1088
1089 /* Monitor might have died before we entered the cgroup. */
1090 if (handler->monitor_pid <= 0) {
1091 WARN("No valid monitor process found while destroying cgroups");
1092 goto try_lxc_rm_rf;
1093 }
1094
1095 if (conf && conf->cgroup_meta.monitor_dir)
1096 pivot_path = must_make_path(h->mountpoint,
1097 h->container_base_path,
1098 conf->cgroup_meta.monitor_dir,
1099 CGROUP_PIVOT, NULL);
1100 else if (conf && conf->cgroup_meta.dir)
1101 pivot_path = must_make_path(h->mountpoint,
1102 h->container_base_path,
1103 conf->cgroup_meta.dir,
1104 CGROUP_PIVOT, NULL);
1105 else
1106 pivot_path = must_make_path(h->mountpoint,
1107 h->container_base_path,
1108 CGROUP_PIVOT, NULL);
1109
1110 ret = mkdir_p(pivot_path, 0755);
1111 if (ret < 0 && errno != EEXIST) {
1112 ERROR("Failed to create %s", pivot_path);
1113 goto try_lxc_rm_rf;
1114 }
1115
1116 ret = lxc_write_openat(pivot_path, "cgroup.procs", pidstr, len);
1117 if (ret != 0) {
1118 SYSWARN("Failed to move monitor %s to \"%s\"", pidstr, pivot_path);
1119 continue;
1120 }
1121
1122 try_lxc_rm_rf:
1123 ret = lxc_rm_rf(h->monitor_full_path);
1124 if (ret < 0)
1125 WARN("Failed to destroy \"%s\"", h->monitor_full_path);
1126 }
1127 }
1128
1129 static int mkdir_eexist_on_last(const char *dir, mode_t mode)
1130 {
1131 const char *tmp = dir;
1132 const char *orig = dir;
1133 size_t orig_len;
1134
1135 orig_len = strlen(dir);
1136 do {
1137 __do_free char *makeme = NULL;
1138 int ret;
1139 size_t cur_len;
1140
1141 dir = tmp + strspn(tmp, "/");
1142 tmp = dir + strcspn(dir, "/");
1143
1144 cur_len = dir - orig;
1145 makeme = strndup(orig, cur_len);
1146 if (!makeme)
1147 return ret_set_errno(-1, ENOMEM);
1148
1149 ret = mkdir(makeme, mode);
1150 if (ret < 0 && ((errno != EEXIST) || (orig_len == cur_len)))
1151 return log_error_errno(-1, errno, "Failed to create directory \"%s\"", makeme);
1152 } while (tmp != dir);
1153
1154 return 0;
1155 }
1156
1157 static bool cgroup_tree_create(struct cgroup_ops *ops, struct lxc_conf *conf,
1158 struct hierarchy *h, const char *cgroup_tree,
1159 const char *cgroup_leaf, bool payload,
1160 const char *cgroup_limit_dir)
1161 {
1162 __do_free char *path = NULL, *limit_path = NULL;
1163 int ret, ret_cpuset;
1164
1165 path = must_make_path(h->mountpoint, h->container_base_path, cgroup_leaf, NULL);
1166 if (dir_exists(path))
1167 return log_warn_errno(false, errno, "The %s cgroup already existed", path);
1168
1169 ret_cpuset = cg_legacy_handle_cpuset_hierarchy(h, cgroup_leaf);
1170 if (ret_cpuset < 0)
1171 return log_error_errno(false, errno, "Failed to handle legacy cpuset controller");
1172
1173 if (payload && cgroup_limit_dir) {
1174 /* with isolation both parts need to not already exist */
1175 limit_path = must_make_path(h->mountpoint,
1176 h->container_base_path,
1177 cgroup_limit_dir, NULL);
1178
1179 ret = mkdir_eexist_on_last(limit_path, 0755);
1180 if (ret < 0)
1181 return log_error_errno(false, errno,
1182 "Failed to create %s limiting cgroup",
1183 limit_path);
1184
1185 h->cgfd_limit = lxc_open_dirfd(limit_path);
1186 if (h->cgfd_limit < 0)
1187 return log_error_errno(false, errno,
1188 "Failed to open %s", path);
1189 h->container_limit_path = move_ptr(limit_path);
1190
1191 /*
1192 * With isolation the devices legacy cgroup needs to be
1193 * iinitialized early, as it typically contains an 'a' (all)
1194 * line, which is not possible once a subdirectory has been
1195 * created.
1196 */
1197 if (string_in_list(h->controllers, "devices")) {
1198 ret = ops->setup_limits_legacy(ops, conf, true);
1199 if (ret < 0)
1200 return ret;
1201 }
1202 }
1203
1204 ret = mkdir_eexist_on_last(path, 0755);
1205 if (ret < 0) {
1206 /*
1207 * This is the cpuset controller and
1208 * cg_legacy_handle_cpuset_hierarchy() has created our target
1209 * directory for us to ensure correct initialization.
1210 */
1211 if (ret_cpuset != 1 || cgroup_tree)
1212 return log_error_errno(false, errno, "Failed to create %s cgroup", path);
1213 }
1214
1215 if (payload) {
1216 h->cgfd_con = lxc_open_dirfd(path);
1217 if (h->cgfd_con < 0)
1218 return log_error_errno(false, errno, "Failed to open %s", path);
1219 h->container_full_path = move_ptr(path);
1220 if (h->cgfd_limit < 0)
1221 h->cgfd_limit = h->cgfd_con;
1222 if (!h->container_limit_path)
1223 h->container_limit_path = h->container_full_path;
1224 } else {
1225 h->cgfd_mon = lxc_open_dirfd(path);
1226 if (h->cgfd_mon < 0)
1227 return log_error_errno(false, errno, "Failed to open %s", path);
1228 h->monitor_full_path = move_ptr(path);
1229 }
1230
1231 return true;
1232 }
1233
1234 static void cgroup_tree_leaf_remove(struct hierarchy *h, bool payload)
1235 {
1236 __do_free char *full_path = NULL, *__limit_path = NULL;
1237 char *limit_path = NULL;
1238
1239 if (payload) {
1240 __lxc_unused __do_close int fd = move_fd(h->cgfd_con);
1241 full_path = move_ptr(h->container_full_path);
1242 limit_path = move_ptr(h->container_limit_path);
1243 if (limit_path != full_path)
1244 __limit_path = limit_path;
1245 } else {
1246 __lxc_unused __do_close int fd = move_fd(h->cgfd_mon);
1247 full_path = move_ptr(h->monitor_full_path);
1248 }
1249
1250 if (full_path && rmdir(full_path))
1251 SYSWARN("Failed to rmdir(\"%s\") cgroup", full_path);
1252 if (limit_path && rmdir(limit_path))
1253 SYSWARN("Failed to rmdir(\"%s\") cgroup", limit_path);
1254 }
1255
1256 /*
1257 * Check we have no lxc.cgroup.dir, and that lxc.cgroup.dir.limit_prefix is a
1258 * proper prefix directory of lxc.cgroup.dir.payload.
1259 *
1260 * Returns the prefix length if it is set, otherwise zero on success.
1261 */
1262 static bool check_cgroup_dir_config(struct lxc_conf *conf)
1263 {
1264 const char *monitor_dir = conf->cgroup_meta.monitor_dir,
1265 *container_dir = conf->cgroup_meta.container_dir,
1266 *namespace_dir = conf->cgroup_meta.namespace_dir;
1267
1268 /* none of the new options are set, all is fine */
1269 if (!monitor_dir && !container_dir && !namespace_dir)
1270 return true;
1271
1272 /* some are set, make sure lxc.cgroup.dir is not also set*/
1273 if (conf->cgroup_meta.dir)
1274 return log_error_errno(false, EINVAL,
1275 "lxc.cgroup.dir conflicts with lxc.cgroup.dir.payload/monitor");
1276
1277 /* make sure both monitor and payload are set */
1278 if (!monitor_dir || !container_dir)
1279 return log_error_errno(false, EINVAL,
1280 "lxc.cgroup.dir.payload and lxc.cgroup.dir.monitor must both be set");
1281
1282 /* namespace_dir may be empty */
1283 return true;
1284 }
1285
1286 __cgfsng_ops static inline bool cgfsng_monitor_create(struct cgroup_ops *ops,
1287 struct lxc_handler *handler)
1288 {
1289 __do_free char *monitor_cgroup = NULL, *__cgroup_tree = NULL;
1290 const char *cgroup_tree;
1291 int idx = 0;
1292 int i;
1293 size_t len;
1294 char *suffix = NULL;
1295 struct lxc_conf *conf;
1296
1297 if (!ops)
1298 return ret_set_errno(false, ENOENT);
1299
1300 if (!ops->hierarchies)
1301 return true;
1302
1303 if (ops->monitor_cgroup)
1304 return ret_set_errno(false, EEXIST);
1305
1306 if (!handler || !handler->conf)
1307 return ret_set_errno(false, EINVAL);
1308
1309 conf = handler->conf;
1310
1311 if (!check_cgroup_dir_config(conf))
1312 return false;
1313
1314 if (conf->cgroup_meta.monitor_dir) {
1315 cgroup_tree = NULL;
1316 monitor_cgroup = strdup(conf->cgroup_meta.monitor_dir);
1317 } else if (conf->cgroup_meta.dir) {
1318 cgroup_tree = conf->cgroup_meta.dir;
1319 monitor_cgroup = must_concat(&len, conf->cgroup_meta.dir, "/",
1320 DEFAULT_MONITOR_CGROUP_PREFIX,
1321 handler->name,
1322 CGROUP_CREATE_RETRY, NULL);
1323 } else if (ops->cgroup_pattern) {
1324 __cgroup_tree = lxc_string_replace("%n", handler->name, ops->cgroup_pattern);
1325 if (!__cgroup_tree)
1326 return ret_set_errno(false, ENOMEM);
1327
1328 cgroup_tree = __cgroup_tree;
1329 monitor_cgroup = must_concat(&len, cgroup_tree, "/",
1330 DEFAULT_MONITOR_CGROUP,
1331 CGROUP_CREATE_RETRY, NULL);
1332 } else {
1333 cgroup_tree = NULL;
1334 monitor_cgroup = must_concat(&len, DEFAULT_MONITOR_CGROUP_PREFIX,
1335 handler->name,
1336 CGROUP_CREATE_RETRY, NULL);
1337 }
1338 if (!monitor_cgroup)
1339 return ret_set_errno(false, ENOMEM);
1340
1341 if (!conf->cgroup_meta.monitor_dir) {
1342 suffix = monitor_cgroup + len - CGROUP_CREATE_RETRY_LEN;
1343 *suffix = '\0';
1344 }
1345 do {
1346 if (idx && suffix)
1347 sprintf(suffix, "-%d", idx);
1348
1349 for (i = 0; ops->hierarchies[i]; i++) {
1350 if (cgroup_tree_create(ops, handler->conf,
1351 ops->hierarchies[i], cgroup_tree,
1352 monitor_cgroup, false, NULL))
1353 continue;
1354
1355 ERROR("Failed to create cgroup \"%s\"", ops->hierarchies[i]->monitor_full_path ?: "(null)");
1356 for (int j = 0; j < i; j++)
1357 cgroup_tree_leaf_remove(ops->hierarchies[j], false);
1358
1359 idx++;
1360 break;
1361 }
1362 } while (ops->hierarchies[i] && idx > 0 && idx < 1000 && suffix);
1363
1364 if (idx == 1000 || (!suffix && idx != 0))
1365 return ret_set_errno(false, ERANGE);
1366
1367 ops->monitor_cgroup = move_ptr(monitor_cgroup);
1368 return log_info(true, "The monitor process uses \"%s\" as cgroup", ops->monitor_cgroup);
1369 }
1370
1371 /*
1372 * Try to create the same cgroup in all hierarchies. Start with cgroup_pattern;
1373 * next cgroup_pattern-1, -2, ..., -999.
1374 */
1375 __cgfsng_ops static inline bool cgfsng_payload_create(struct cgroup_ops *ops,
1376 struct lxc_handler *handler)
1377 {
1378 __do_free char *container_cgroup = NULL,
1379 *__cgroup_tree = NULL,
1380 *limiting_cgroup = NULL;
1381 const char *cgroup_tree;
1382 int idx = 0;
1383 int i;
1384 size_t len;
1385 char *suffix = NULL;
1386 struct lxc_conf *conf;
1387
1388 if (!ops)
1389 return ret_set_errno(false, ENOENT);
1390
1391 if (!ops->hierarchies)
1392 return true;
1393
1394 if (ops->container_cgroup)
1395 return ret_set_errno(false, EEXIST);
1396
1397 if (!handler || !handler->conf)
1398 return ret_set_errno(false, EINVAL);
1399
1400 conf = handler->conf;
1401
1402 if (!check_cgroup_dir_config(conf))
1403 return false;
1404
1405 if (conf->cgroup_meta.container_dir) {
1406 cgroup_tree = NULL;
1407
1408 limiting_cgroup = strdup(conf->cgroup_meta.container_dir);
1409 if (!limiting_cgroup)
1410 return ret_set_errno(false, ENOMEM);
1411
1412 if (conf->cgroup_meta.namespace_dir) {
1413 container_cgroup = must_make_path(limiting_cgroup,
1414 conf->cgroup_meta.namespace_dir,
1415 NULL);
1416 } else {
1417 /* explicit paths but without isolation */
1418 container_cgroup = move_ptr(limiting_cgroup);
1419 }
1420 } else if (conf->cgroup_meta.dir) {
1421 cgroup_tree = conf->cgroup_meta.dir;
1422 container_cgroup = must_concat(&len, cgroup_tree, "/",
1423 DEFAULT_PAYLOAD_CGROUP_PREFIX,
1424 handler->name,
1425 CGROUP_CREATE_RETRY, NULL);
1426 } else if (ops->cgroup_pattern) {
1427 __cgroup_tree = lxc_string_replace("%n", handler->name, ops->cgroup_pattern);
1428 if (!__cgroup_tree)
1429 return ret_set_errno(false, ENOMEM);
1430
1431 cgroup_tree = __cgroup_tree;
1432 container_cgroup = must_concat(&len, cgroup_tree, "/",
1433 DEFAULT_PAYLOAD_CGROUP,
1434 CGROUP_CREATE_RETRY, NULL);
1435 } else {
1436 cgroup_tree = NULL;
1437 container_cgroup = must_concat(&len, DEFAULT_PAYLOAD_CGROUP_PREFIX,
1438 handler->name,
1439 CGROUP_CREATE_RETRY, NULL);
1440 }
1441 if (!container_cgroup)
1442 return ret_set_errno(false, ENOMEM);
1443
1444 if (!conf->cgroup_meta.container_dir) {
1445 suffix = container_cgroup + len - CGROUP_CREATE_RETRY_LEN;
1446 *suffix = '\0';
1447 }
1448 do {
1449 if (idx && suffix)
1450 sprintf(suffix, "-%d", idx);
1451
1452 for (i = 0; ops->hierarchies[i]; i++) {
1453 if (cgroup_tree_create(ops, handler->conf,
1454 ops->hierarchies[i], cgroup_tree,
1455 container_cgroup, true,
1456 limiting_cgroup))
1457 continue;
1458
1459 ERROR("Failed to create cgroup \"%s\"", ops->hierarchies[i]->container_full_path ?: "(null)");
1460 for (int j = 0; j < i; j++)
1461 cgroup_tree_leaf_remove(ops->hierarchies[j], true);
1462
1463 idx++;
1464 break;
1465 }
1466 } while (ops->hierarchies[i] && idx > 0 && idx < 1000 && suffix);
1467
1468 if (idx == 1000 || (!suffix && idx != 0))
1469 return ret_set_errno(false, ERANGE);
1470
1471 ops->container_cgroup = move_ptr(container_cgroup);
1472 INFO("The container process uses \"%s\" as cgroup", ops->container_cgroup);
1473 return true;
1474 }
1475
1476 __cgfsng_ops static bool cgfsng_monitor_enter(struct cgroup_ops *ops,
1477 struct lxc_handler *handler)
1478 {
1479 int monitor_len, transient_len = 0;
1480 char monitor[INTTYPE_TO_STRLEN(pid_t)],
1481 transient[INTTYPE_TO_STRLEN(pid_t)];
1482
1483 if (!ops)
1484 return ret_set_errno(false, ENOENT);
1485
1486 if (!ops->hierarchies)
1487 return true;
1488
1489 if (!ops->monitor_cgroup)
1490 return ret_set_errno(false, ENOENT);
1491
1492 if (!handler || !handler->conf)
1493 return ret_set_errno(false, EINVAL);
1494
1495 monitor_len = snprintf(monitor, sizeof(monitor), "%d", handler->monitor_pid);
1496 if (handler->transient_pid > 0)
1497 transient_len = snprintf(transient, sizeof(transient), "%d", handler->transient_pid);
1498
1499 for (int i = 0; ops->hierarchies[i]; i++) {
1500 struct hierarchy *h = ops->hierarchies[i];
1501 int ret;
1502
1503 ret = lxc_writeat(h->cgfd_mon, "cgroup.procs", monitor, monitor_len);
1504 if (ret)
1505 return log_error_errno(false, errno, "Failed to enter cgroup \"%s\"", h->monitor_full_path);
1506
1507 if (handler->transient_pid <= 0)
1508 return true;
1509
1510 ret = lxc_writeat(h->cgfd_mon, "cgroup.procs", transient, transient_len);
1511 if (ret)
1512 return log_error_errno(false, errno, "Failed to enter cgroup \"%s\"", h->monitor_full_path);
1513
1514 /*
1515 * we don't keep the fds for non-unified hierarchies around
1516 * mainly because we don't make use of them anymore after the
1517 * core cgroup setup is done but also because there are quite a
1518 * lot of them.
1519 */
1520 if (!is_unified_hierarchy(h))
1521 close_prot_errno_disarm(h->cgfd_mon);
1522 }
1523 handler->transient_pid = -1;
1524
1525 return true;
1526 }
1527
1528 __cgfsng_ops static bool cgfsng_payload_enter(struct cgroup_ops *ops,
1529 struct lxc_handler *handler)
1530 {
1531 int len;
1532 char pidstr[INTTYPE_TO_STRLEN(pid_t)];
1533
1534 if (!ops)
1535 return ret_set_errno(false, ENOENT);
1536
1537 if (!ops->hierarchies)
1538 return true;
1539
1540 if (!ops->container_cgroup)
1541 return ret_set_errno(false, ENOENT);
1542
1543 if (!handler || !handler->conf)
1544 return ret_set_errno(false, EINVAL);
1545
1546 len = snprintf(pidstr, sizeof(pidstr), "%d", handler->pid);
1547
1548 for (int i = 0; ops->hierarchies[i]; i++) {
1549 struct hierarchy *h = ops->hierarchies[i];
1550 int ret;
1551
1552 ret = lxc_writeat(h->cgfd_con, "cgroup.procs", pidstr, len);
1553 if (ret != 0)
1554 return log_error_errno(false, errno, "Failed to enter cgroup \"%s\"", h->container_full_path);
1555 }
1556
1557 return true;
1558 }
1559
1560 static int fchowmodat(int dirfd, const char *path, uid_t chown_uid,
1561 gid_t chown_gid, mode_t chmod_mode)
1562 {
1563 int ret;
1564
1565 ret = fchownat(dirfd, path, chown_uid, chown_gid,
1566 AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW);
1567 if (ret < 0)
1568 return log_warn_errno(-1,
1569 errno, "Failed to fchownat(%d, %s, %d, %d, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW )",
1570 dirfd, path, (int)chown_uid,
1571 (int)chown_gid);
1572
1573 ret = fchmodat(dirfd, (*path != '\0') ? path : ".", chmod_mode, 0);
1574 if (ret < 0)
1575 return log_warn_errno(-1, errno, "Failed to fchmodat(%d, %s, %d, AT_SYMLINK_NOFOLLOW)",
1576 dirfd, path, (int)chmod_mode);
1577
1578 return 0;
1579 }
1580
1581 /* chgrp the container cgroups to container group. We leave
1582 * the container owner as cgroup owner. So we must make the
1583 * directories 775 so that the container can create sub-cgroups.
1584 *
1585 * Also chown the tasks and cgroup.procs files. Those may not
1586 * exist depending on kernel version.
1587 */
1588 static int chown_cgroup_wrapper(void *data)
1589 {
1590 int ret;
1591 uid_t destuid;
1592 struct generic_userns_exec_data *arg = data;
1593 uid_t nsuid = (arg->conf->root_nsuid_map != NULL) ? 0 : arg->conf->init_uid;
1594 gid_t nsgid = (arg->conf->root_nsgid_map != NULL) ? 0 : arg->conf->init_gid;
1595
1596 if (!lxc_setgroups(0, NULL) && errno != EPERM)
1597 return log_error_errno(-1, errno, "Failed to setgroups(0, NULL)");
1598
1599 ret = setresgid(nsgid, nsgid, nsgid);
1600 if (ret < 0)
1601 return log_error_errno(-1, errno, "Failed to setresgid(%d, %d, %d)",
1602 (int)nsgid, (int)nsgid, (int)nsgid);
1603
1604 ret = setresuid(nsuid, nsuid, nsuid);
1605 if (ret < 0)
1606 return log_error_errno(-1, errno, "Failed to setresuid(%d, %d, %d)",
1607 (int)nsuid, (int)nsuid, (int)nsuid);
1608
1609 destuid = get_ns_uid(arg->origuid);
1610 if (destuid == LXC_INVALID_UID)
1611 destuid = 0;
1612
1613 for (int i = 0; arg->hierarchies[i]; i++) {
1614 int dirfd = arg->hierarchies[i]->cgfd_con;
1615
1616 (void)fchowmodat(dirfd, "", destuid, nsgid, 0775);
1617
1618 /*
1619 * Failures to chown() these are inconvenient but not
1620 * detrimental We leave these owned by the container launcher,
1621 * so that container root can write to the files to attach. We
1622 * chmod() them 664 so that container systemd can write to the
1623 * files (which systemd in wily insists on doing).
1624 */
1625
1626 if (arg->hierarchies[i]->version == CGROUP_SUPER_MAGIC)
1627 (void)fchowmodat(dirfd, "tasks", destuid, nsgid, 0664);
1628
1629 (void)fchowmodat(dirfd, "cgroup.procs", destuid, nsgid, 0664);
1630
1631 if (arg->hierarchies[i]->version != CGROUP2_SUPER_MAGIC)
1632 continue;
1633
1634 for (char **p = arg->hierarchies[i]->cgroup2_chown; p && *p; p++)
1635 (void)fchowmodat(dirfd, *p, destuid, nsgid, 0664);
1636 }
1637
1638 return 0;
1639 }
1640
1641 __cgfsng_ops static bool cgfsng_chown(struct cgroup_ops *ops,
1642 struct lxc_conf *conf)
1643 {
1644 struct generic_userns_exec_data wrap;
1645
1646 if (!ops)
1647 return ret_set_errno(false, ENOENT);
1648
1649 if (!ops->hierarchies)
1650 return true;
1651
1652 if (!ops->container_cgroup)
1653 return ret_set_errno(false, ENOENT);
1654
1655 if (!conf)
1656 return ret_set_errno(false, EINVAL);
1657
1658 if (lxc_list_empty(&conf->id_map))
1659 return true;
1660
1661 wrap.origuid = geteuid();
1662 wrap.path = NULL;
1663 wrap.hierarchies = ops->hierarchies;
1664 wrap.conf = conf;
1665
1666 if (userns_exec_1(conf, chown_cgroup_wrapper, &wrap, "chown_cgroup_wrapper") < 0)
1667 return log_error_errno(false, errno, "Error requesting cgroup chown in new user namespace");
1668
1669 return true;
1670 }
1671
1672 __cgfsng_ops void cgfsng_payload_finalize(struct cgroup_ops *ops)
1673 {
1674 if (!ops)
1675 return;
1676
1677 if (!ops->hierarchies)
1678 return;
1679
1680 for (int i = 0; ops->hierarchies[i]; i++) {
1681 struct hierarchy *h = ops->hierarchies[i];
1682 /*
1683 * we don't keep the fds for non-unified hierarchies around
1684 * mainly because we don't make use of them anymore after the
1685 * core cgroup setup is done but also because there are quite a
1686 * lot of them.
1687 */
1688 if (!is_unified_hierarchy(h))
1689 close_prot_errno_disarm(h->cgfd_con);
1690 }
1691 }
1692
1693 /* cgroup-full:* is done, no need to create subdirs */
1694 static inline bool cg_mount_needs_subdirs(int type)
1695 {
1696 return !(type >= LXC_AUTO_CGROUP_FULL_RO);
1697 }
1698
1699 /* After $rootfs/sys/fs/container/controller/the/cg/path has been created,
1700 * remount controller ro if needed and bindmount the cgroupfs onto
1701 * control/the/cg/path.
1702 */
1703 static int cg_legacy_mount_controllers(int type, struct hierarchy *h,
1704 char *controllerpath, char *cgpath,
1705 const char *container_cgroup)
1706 {
1707 __do_free char *sourcepath = NULL;
1708 int ret, remount_flags;
1709 int flags = MS_BIND;
1710
1711 if (type == LXC_AUTO_CGROUP_RO || type == LXC_AUTO_CGROUP_MIXED) {
1712 ret = mount(controllerpath, controllerpath, "cgroup", MS_BIND, NULL);
1713 if (ret < 0)
1714 return log_error_errno(-1, errno, "Failed to bind mount \"%s\" onto \"%s\"",
1715 controllerpath, controllerpath);
1716
1717 remount_flags = add_required_remount_flags(controllerpath,
1718 controllerpath,
1719 flags | MS_REMOUNT);
1720 ret = mount(controllerpath, controllerpath, "cgroup",
1721 remount_flags | MS_REMOUNT | MS_BIND | MS_RDONLY,
1722 NULL);
1723 if (ret < 0)
1724 return log_error_errno(-1, errno, "Failed to remount \"%s\" ro", controllerpath);
1725
1726 INFO("Remounted %s read-only", controllerpath);
1727 }
1728
1729 sourcepath = must_make_path(h->mountpoint, h->container_base_path,
1730 container_cgroup, NULL);
1731 if (type == LXC_AUTO_CGROUP_RO)
1732 flags |= MS_RDONLY;
1733
1734 ret = mount(sourcepath, cgpath, "cgroup", flags, NULL);
1735 if (ret < 0)
1736 return log_error_errno(-1, errno, "Failed to mount \"%s\" onto \"%s\"",
1737 h->controllers[0], cgpath);
1738 INFO("Mounted \"%s\" onto \"%s\"", h->controllers[0], cgpath);
1739
1740 if (flags & MS_RDONLY) {
1741 remount_flags = add_required_remount_flags(sourcepath, cgpath,
1742 flags | MS_REMOUNT);
1743 ret = mount(sourcepath, cgpath, "cgroup", remount_flags, NULL);
1744 if (ret < 0)
1745 return log_error_errno(-1, errno, "Failed to remount \"%s\" ro", cgpath);
1746 INFO("Remounted %s read-only", cgpath);
1747 }
1748
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 __do_free char *controllers = NULL;
1763 char *fstype = "cgroup2";
1764 unsigned long flags = 0;
1765 int ret;
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 if (ret < 0)
1784 return log_error_errno(-1, errno, "Failed to mount \"%s\" with cgroup filesystem type %s",
1785 controllerpath, fstype);
1786
1787 DEBUG("Mounted \"%s\" with cgroup filesystem type %s", controllerpath, fstype);
1788 return 0;
1789 }
1790
1791 static inline int cg_mount_in_cgroup_namespace(int type, struct hierarchy *h,
1792 const char *controllerpath)
1793 {
1794 return __cg_mount_direct(type, h, controllerpath);
1795 }
1796
1797 static inline int cg_mount_cgroup_full(int type, struct hierarchy *h,
1798 const char *controllerpath)
1799 {
1800 if (type < LXC_AUTO_CGROUP_FULL_RO || type > LXC_AUTO_CGROUP_FULL_MIXED)
1801 return 0;
1802
1803 return __cg_mount_direct(type, h, controllerpath);
1804 }
1805
1806 __cgfsng_ops static bool cgfsng_mount(struct cgroup_ops *ops,
1807 struct lxc_handler *handler,
1808 const char *root, int type)
1809 {
1810 __do_free char *cgroup_root = NULL;
1811 bool has_cgns = false, wants_force_mount = false;
1812 int ret;
1813
1814 if (!ops)
1815 return ret_set_errno(false, ENOENT);
1816
1817 if (!ops->hierarchies)
1818 return true;
1819
1820 if (!handler || !handler->conf)
1821 return ret_set_errno(false, EINVAL);
1822
1823 if ((type & LXC_AUTO_CGROUP_MASK) == 0)
1824 return true;
1825
1826 if (type & LXC_AUTO_CGROUP_FORCE) {
1827 type &= ~LXC_AUTO_CGROUP_FORCE;
1828 wants_force_mount = true;
1829 }
1830
1831 if (!wants_force_mount){
1832 if (!lxc_list_empty(&handler->conf->keepcaps))
1833 wants_force_mount = !in_caplist(CAP_SYS_ADMIN, &handler->conf->keepcaps);
1834 else
1835 wants_force_mount = in_caplist(CAP_SYS_ADMIN, &handler->conf->caps);
1836 }
1837
1838 has_cgns = cgns_supported();
1839 if (has_cgns && !wants_force_mount)
1840 return true;
1841
1842 if (type == LXC_AUTO_CGROUP_NOSPEC)
1843 type = LXC_AUTO_CGROUP_MIXED;
1844 else if (type == LXC_AUTO_CGROUP_FULL_NOSPEC)
1845 type = LXC_AUTO_CGROUP_FULL_MIXED;
1846
1847 cgroup_root = must_make_path(root, DEFAULT_CGROUP_MOUNTPOINT, NULL);
1848 if (ops->cgroup_layout == CGROUP_LAYOUT_UNIFIED) {
1849 if (has_cgns && wants_force_mount) {
1850 /*
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 return cg_mount_in_cgroup_namespace(type, ops->unified, cgroup_root) == 0;
1856 }
1857
1858 return cg_mount_cgroup_full(type, ops->unified, cgroup_root) == 0;
1859 }
1860
1861 /* mount tmpfs */
1862 ret = safe_mount(NULL, cgroup_root, "tmpfs",
1863 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_RELATIME,
1864 "size=10240k,mode=755", root);
1865 if (ret < 0)
1866 return false;
1867
1868 for (int i = 0; ops->hierarchies[i]; i++) {
1869 __do_free char *controllerpath = NULL, *path2 = NULL;
1870 struct hierarchy *h = ops->hierarchies[i];
1871 char *controller = strrchr(h->mountpoint, '/');
1872
1873 if (!controller)
1874 continue;
1875 controller++;
1876
1877 controllerpath = must_make_path(cgroup_root, controller, NULL);
1878 if (dir_exists(controllerpath))
1879 continue;
1880
1881 ret = mkdir(controllerpath, 0755);
1882 if (ret < 0)
1883 return log_error_errno(false, errno, "Error creating cgroup path: %s", controllerpath);
1884
1885 if (has_cgns && wants_force_mount) {
1886 /* If cgroup namespaces are supported but the container
1887 * will not have CAP_SYS_ADMIN after it has started we
1888 * need to mount the cgroups manually.
1889 */
1890 ret = cg_mount_in_cgroup_namespace(type, h, controllerpath);
1891 if (ret < 0)
1892 return false;
1893
1894 continue;
1895 }
1896
1897 ret = cg_mount_cgroup_full(type, h, controllerpath);
1898 if (ret < 0)
1899 return false;
1900
1901 if (!cg_mount_needs_subdirs(type))
1902 continue;
1903
1904 path2 = must_make_path(controllerpath, h->container_base_path,
1905 ops->container_cgroup, NULL);
1906 ret = mkdir_p(path2, 0755);
1907 if (ret < 0)
1908 return false;
1909
1910 ret = cg_legacy_mount_controllers(type, h, controllerpath,
1911 path2, ops->container_cgroup);
1912 if (ret < 0)
1913 return false;
1914 }
1915
1916 return true;
1917 }
1918
1919 /* Only root needs to escape to the cgroup of its init. */
1920 __cgfsng_ops static bool cgfsng_escape(const struct cgroup_ops *ops,
1921 struct lxc_conf *conf)
1922 {
1923 if (!ops)
1924 return ret_set_errno(false, ENOENT);
1925
1926 if (!ops->hierarchies)
1927 return true;
1928
1929 if (!conf)
1930 return ret_set_errno(false, EINVAL);
1931
1932 if (conf->cgroup_meta.relative || geteuid())
1933 return true;
1934
1935 for (int i = 0; ops->hierarchies[i]; i++) {
1936 __do_free char *fullpath = NULL;
1937 int ret;
1938
1939 fullpath =
1940 must_make_path(ops->hierarchies[i]->mountpoint,
1941 ops->hierarchies[i]->container_base_path,
1942 "cgroup.procs", NULL);
1943 ret = lxc_write_to_file(fullpath, "0", 2, false, 0666);
1944 if (ret != 0)
1945 return log_error_errno(false, errno, "Failed to escape to cgroup \"%s\"", fullpath);
1946 }
1947
1948 return true;
1949 }
1950
1951 __cgfsng_ops static int cgfsng_num_hierarchies(struct cgroup_ops *ops)
1952 {
1953 int i = 0;
1954
1955 if (!ops)
1956 return ret_set_errno(-1, ENOENT);
1957
1958 if (!ops->hierarchies)
1959 return 0;
1960
1961 for (; ops->hierarchies[i]; i++)
1962 ;
1963
1964 return i;
1965 }
1966
1967 __cgfsng_ops static bool cgfsng_get_hierarchies(struct cgroup_ops *ops, int n,
1968 char ***out)
1969 {
1970 int i;
1971
1972 if (!ops)
1973 return ret_set_errno(false, ENOENT);
1974
1975 if (!ops->hierarchies)
1976 return ret_set_errno(false, ENOENT);
1977
1978 /* sanity check n */
1979 for (i = 0; i < n; i++)
1980 if (!ops->hierarchies[i])
1981 return ret_set_errno(false, ENOENT);
1982
1983 *out = ops->hierarchies[i]->controllers;
1984
1985 return true;
1986 }
1987
1988 static bool cg_legacy_freeze(struct cgroup_ops *ops)
1989 {
1990 struct hierarchy *h;
1991
1992 h = get_hierarchy(ops, "freezer");
1993 if (!h)
1994 return ret_set_errno(-1, ENOENT);
1995
1996 return lxc_write_openat(h->container_full_path, "freezer.state",
1997 "FROZEN", STRLITERALLEN("FROZEN"));
1998 }
1999
2000 static int freezer_cgroup_events_cb(int fd, uint32_t events, void *cbdata,
2001 struct lxc_epoll_descr *descr)
2002 {
2003 __do_close int duped_fd = -EBADF;
2004 __do_free char *line = NULL;
2005 __do_fclose FILE *f = NULL;
2006 int state = PTR_TO_INT(cbdata);
2007 size_t len;
2008 const char *state_string;
2009
2010 duped_fd = dup(fd);
2011 if (duped_fd < 0)
2012 return LXC_MAINLOOP_ERROR;
2013
2014 if (lseek(duped_fd, 0, SEEK_SET) < (off_t)-1)
2015 return LXC_MAINLOOP_ERROR;
2016
2017 f = fdopen(duped_fd, "re");
2018 if (!f)
2019 return LXC_MAINLOOP_ERROR;
2020 move_fd(duped_fd);
2021
2022 if (state == 1)
2023 state_string = "frozen 1";
2024 else
2025 state_string = "frozen 0";
2026
2027 while (getline(&line, &len, f) != -1)
2028 if (strncmp(line, state_string, STRLITERALLEN("frozen") + 2) == 0)
2029 return LXC_MAINLOOP_CLOSE;
2030
2031 return LXC_MAINLOOP_CONTINUE;
2032 }
2033
2034 static int cg_unified_freeze(struct cgroup_ops *ops, int timeout)
2035 {
2036 __do_close int fd = -EBADF;
2037 call_cleaner(lxc_mainloop_close) struct lxc_epoll_descr *descr_ptr = NULL;
2038 int ret;
2039 struct lxc_epoll_descr descr;
2040 struct hierarchy *h;
2041
2042 h = ops->unified;
2043 if (!h)
2044 return ret_set_errno(-1, ENOENT);
2045
2046 if (!h->container_full_path)
2047 return ret_set_errno(-1, EEXIST);
2048
2049 if (timeout != 0) {
2050 __do_free char *events_file = NULL;
2051
2052 events_file = must_make_path(h->container_full_path, "cgroup.events", NULL);
2053 fd = open(events_file, O_RDONLY | O_CLOEXEC);
2054 if (fd < 0)
2055 return log_error_errno(-1, errno, "Failed to open cgroup.events file");
2056
2057 ret = lxc_mainloop_open(&descr);
2058 if (ret)
2059 return log_error_errno(-1, errno, "Failed to create epoll instance to wait for container freeze");
2060
2061 /* automatically cleaned up now */
2062 descr_ptr = &descr;
2063
2064 ret = lxc_mainloop_add_handler(&descr, fd, freezer_cgroup_events_cb, INT_TO_PTR((int){1}));
2065 if (ret < 0)
2066 return log_error_errno(-1, errno, "Failed to add cgroup.events fd handler to mainloop");
2067 }
2068
2069 ret = lxc_write_openat(h->container_full_path, "cgroup.freeze", "1", 1);
2070 if (ret < 0)
2071 return log_error_errno(-1, errno, "Failed to open cgroup.freeze file");
2072
2073 if (timeout != 0 && lxc_mainloop(&descr, timeout))
2074 return log_error_errno(-1, errno, "Failed to wait for container to be frozen");
2075
2076 return 0;
2077 }
2078
2079 __cgfsng_ops static int cgfsng_freeze(struct cgroup_ops *ops, int timeout)
2080 {
2081 if (!ops->hierarchies)
2082 return ret_set_errno(-1, ENOENT);
2083
2084 if (ops->cgroup_layout != CGROUP_LAYOUT_UNIFIED)
2085 return cg_legacy_freeze(ops);
2086
2087 return cg_unified_freeze(ops, timeout);
2088 }
2089
2090 static int cg_legacy_unfreeze(struct cgroup_ops *ops)
2091 {
2092 struct hierarchy *h;
2093
2094 h = get_hierarchy(ops, "freezer");
2095 if (!h)
2096 return ret_set_errno(-1, ENOENT);
2097
2098 return lxc_write_openat(h->container_full_path, "freezer.state",
2099 "THAWED", STRLITERALLEN("THAWED"));
2100 }
2101
2102 static int cg_unified_unfreeze(struct cgroup_ops *ops, int timeout)
2103 {
2104 __do_close int fd = -EBADF;
2105 call_cleaner(lxc_mainloop_close)struct lxc_epoll_descr *descr_ptr = NULL;
2106 int ret;
2107 struct lxc_epoll_descr descr;
2108 struct hierarchy *h;
2109
2110 h = ops->unified;
2111 if (!h)
2112 return ret_set_errno(-1, ENOENT);
2113
2114 if (!h->container_full_path)
2115 return ret_set_errno(-1, EEXIST);
2116
2117 if (timeout != 0) {
2118 __do_free char *events_file = NULL;
2119
2120 events_file = must_make_path(h->container_full_path, "cgroup.events", NULL);
2121 fd = open(events_file, O_RDONLY | O_CLOEXEC);
2122 if (fd < 0)
2123 return log_error_errno(-1, errno, "Failed to open cgroup.events file");
2124
2125 ret = lxc_mainloop_open(&descr);
2126 if (ret)
2127 return log_error_errno(-1, errno, "Failed to create epoll instance to wait for container unfreeze");
2128
2129 /* automatically cleaned up now */
2130 descr_ptr = &descr;
2131
2132 ret = lxc_mainloop_add_handler(&descr, fd, freezer_cgroup_events_cb, INT_TO_PTR((int){0}));
2133 if (ret < 0)
2134 return log_error_errno(-1, errno, "Failed to add cgroup.events fd handler to mainloop");
2135 }
2136
2137 ret = lxc_write_openat(h->container_full_path, "cgroup.freeze", "0", 1);
2138 if (ret < 0)
2139 return log_error_errno(-1, errno, "Failed to open cgroup.freeze file");
2140
2141 if (timeout != 0 && lxc_mainloop(&descr, timeout))
2142 return log_error_errno(-1, errno, "Failed to wait for container to be unfrozen");
2143
2144 return 0;
2145 }
2146
2147 __cgfsng_ops static int cgfsng_unfreeze(struct cgroup_ops *ops, int timeout)
2148 {
2149 if (!ops->hierarchies)
2150 return ret_set_errno(-1, ENOENT);
2151
2152 if (ops->cgroup_layout != CGROUP_LAYOUT_UNIFIED)
2153 return cg_legacy_unfreeze(ops);
2154
2155 return cg_unified_unfreeze(ops, timeout);
2156 }
2157
2158 static const char *cgfsng_get_cgroup_do(struct cgroup_ops *ops,
2159 const char *controller, bool limiting)
2160 {
2161 struct hierarchy *h;
2162
2163 h = get_hierarchy(ops, controller);
2164 if (!h)
2165 return log_warn_errno(NULL, ENOENT, "Failed to find hierarchy for controller \"%s\"",
2166 controller ? controller : "(null)");
2167
2168 if (limiting)
2169 return h->container_limit_path
2170 ? h->container_limit_path + strlen(h->mountpoint)
2171 : NULL;
2172
2173 return h->container_full_path
2174 ? h->container_full_path + strlen(h->mountpoint)
2175 : NULL;
2176 }
2177
2178 __cgfsng_ops static const char *cgfsng_get_cgroup(struct cgroup_ops *ops,
2179 const char *controller)
2180 {
2181 return cgfsng_get_cgroup_do(ops, controller, false);
2182 }
2183
2184 __cgfsng_ops static const char *cgfsng_get_limiting_cgroup(struct cgroup_ops *ops,
2185 const char *controller)
2186 {
2187 return cgfsng_get_cgroup_do(ops, controller, true);
2188 }
2189
2190 /* Given a cgroup path returned from lxc_cmd_get_cgroup_path, build a full path,
2191 * which must be freed by the caller.
2192 */
2193 static inline char *build_full_cgpath_from_monitorpath(struct hierarchy *h,
2194 const char *inpath,
2195 const char *filename)
2196 {
2197 return must_make_path(h->mountpoint, inpath, filename, NULL);
2198 }
2199
2200 static int cgroup_attach_leaf(const struct lxc_conf *conf, int unified_fd, pid_t pid)
2201 {
2202 int idx = 1;
2203 int ret;
2204 char pidstr[INTTYPE_TO_STRLEN(int64_t) + 1];
2205 size_t pidstr_len;
2206
2207 /* Create leaf cgroup. */
2208 ret = mkdirat(unified_fd, ".lxc", 0755);
2209 if (ret < 0 && errno != EEXIST)
2210 return log_error_errno(-1, errno, "Failed to create leaf cgroup \".lxc\"");
2211
2212 pidstr_len = sprintf(pidstr, INT64_FMT, (int64_t)pid);
2213 ret = lxc_writeat(unified_fd, ".lxc/cgroup.procs", pidstr, pidstr_len);
2214 if (ret < 0)
2215 ret = lxc_writeat(unified_fd, "cgroup.procs", pidstr, pidstr_len);
2216 if (ret == 0)
2217 return 0;
2218
2219 /* this is a non-leaf node */
2220 if (errno != EBUSY)
2221 return log_error_errno(-1, errno, "Failed to attach to unified cgroup");
2222
2223 do {
2224 bool rm = false;
2225 char attach_cgroup[STRLITERALLEN(".lxc-1000/cgroup.procs") + 1];
2226 char *slash;
2227
2228 ret = snprintf(attach_cgroup, sizeof(attach_cgroup), ".lxc-%d/cgroup.procs", idx);
2229 if (ret < 0 || (size_t)ret >= sizeof(attach_cgroup))
2230 return ret_errno(EIO);
2231
2232 slash = &attach_cgroup[ret] - STRLITERALLEN("/cgroup.procs");
2233 *slash = '\0';
2234
2235 ret = mkdirat(unified_fd, attach_cgroup, 0755);
2236 if (ret < 0 && errno != EEXIST)
2237 return log_error_errno(-1, errno, "Failed to create cgroup %s", attach_cgroup);
2238 if (ret == 0)
2239 rm = true;
2240
2241 *slash = '/';
2242
2243 ret = lxc_writeat(unified_fd, attach_cgroup, pidstr, pidstr_len);
2244 if (ret == 0)
2245 return 0;
2246
2247 if (rm && unlinkat(unified_fd, attach_cgroup, AT_REMOVEDIR))
2248 SYSERROR("Failed to remove cgroup \"%d(%s)\"", unified_fd, attach_cgroup);
2249
2250 /* this is a non-leaf node */
2251 if (errno != EBUSY)
2252 return log_error_errno(-1, errno, "Failed to attach to unified cgroup");
2253
2254 idx++;
2255 } while (idx < 1000);
2256
2257 return log_error_errno(-1, errno, "Failed to attach to unified cgroup");
2258 }
2259
2260 static int cgroup_attach_create_leaf(const struct lxc_conf *conf,
2261 int unified_fd, int *sk_fd)
2262 {
2263 __do_close int sk = *sk_fd, target_fd0 = -EBADF, target_fd1 = -EBADF;
2264 int target_fds[2];
2265 ssize_t ret;
2266
2267 /* Create leaf cgroup. */
2268 ret = mkdirat(unified_fd, ".lxc", 0755);
2269 if (ret < 0 && errno != EEXIST)
2270 return log_error_errno(-1, errno, "Failed to create leaf cgroup \".lxc\"");
2271
2272 target_fd0 = openat(unified_fd, ".lxc/cgroup.procs", O_WRONLY | O_CLOEXEC | O_NOFOLLOW);
2273 if (target_fd0 < 0)
2274 return log_error_errno(-errno, errno, "Failed to open \".lxc/cgroup.procs\"");
2275 target_fds[0] = target_fd0;
2276
2277 target_fd1 = openat(unified_fd, "cgroup.procs", O_WRONLY | O_CLOEXEC | O_NOFOLLOW);
2278 if (target_fd1 < 0)
2279 return log_error_errno(-errno, errno, "Failed to open \".lxc/cgroup.procs\"");
2280 target_fds[1] = target_fd1;
2281
2282 ret = lxc_abstract_unix_send_fds(sk, target_fds, 2, NULL, 0);
2283 if (ret <= 0)
2284 return log_error_errno(-errno, errno, "Failed to send \".lxc/cgroup.procs\" fds %d and %d",
2285 target_fd0, target_fd1);
2286
2287 return log_debug(0, "Sent target cgroup fds %d and %d", target_fd0, target_fd1);
2288 }
2289
2290 static int cgroup_attach_move_into_leaf(const struct lxc_conf *conf,
2291 int *sk_fd, pid_t pid)
2292 {
2293 __do_close int sk = *sk_fd, target_fd0 = -EBADF, target_fd1 = -EBADF;
2294 int target_fds[2];
2295 char pidstr[INTTYPE_TO_STRLEN(int64_t) + 1];
2296 size_t pidstr_len;
2297 ssize_t ret;
2298
2299 ret = lxc_abstract_unix_recv_fds(sk, target_fds, 2, NULL, 0);
2300 if (ret <= 0)
2301 return log_error_errno(-1, errno, "Failed to receive target cgroup fd");
2302 target_fd0 = target_fds[0];
2303 target_fd1 = target_fds[1];
2304
2305 pidstr_len = sprintf(pidstr, INT64_FMT, (int64_t)pid);
2306
2307 ret = lxc_write_nointr(target_fd0, pidstr, pidstr_len);
2308 if (ret > 0 && ret == pidstr_len)
2309 return log_debug(0, "Moved process into target cgroup via fd %d", target_fd0);
2310
2311 ret = lxc_write_nointr(target_fd1, pidstr, pidstr_len);
2312 if (ret > 0 && ret == pidstr_len)
2313 return log_debug(0, "Moved process into target cgroup via fd %d", target_fd1);
2314
2315 return log_debug_errno(-1, errno, "Failed to move process into target cgroup via fd %d and %d",
2316 target_fd0, target_fd1);
2317 }
2318
2319 struct userns_exec_unified_attach_data {
2320 const struct lxc_conf *conf;
2321 int unified_fd;
2322 int sk_pair[2];
2323 pid_t pid;
2324 };
2325
2326 static int cgroup_unified_attach_child_wrapper(void *data)
2327 {
2328 struct userns_exec_unified_attach_data *args = data;
2329
2330 if (!args->conf || args->unified_fd < 0 || args->pid <= 0 ||
2331 args->sk_pair[0] < 0 || args->sk_pair[1] < 0)
2332 return ret_errno(EINVAL);
2333
2334 close_prot_errno_disarm(args->sk_pair[0]);
2335 return cgroup_attach_create_leaf(args->conf, args->unified_fd,
2336 &args->sk_pair[1]);
2337 }
2338
2339 static int cgroup_unified_attach_parent_wrapper(void *data)
2340 {
2341 struct userns_exec_unified_attach_data *args = data;
2342
2343 if (!args->conf || args->unified_fd < 0 || args->pid <= 0 ||
2344 args->sk_pair[0] < 0 || args->sk_pair[1] < 0)
2345 return ret_errno(EINVAL);
2346
2347 close_prot_errno_disarm(args->sk_pair[1]);
2348 return cgroup_attach_move_into_leaf(args->conf, &args->sk_pair[0],
2349 args->pid);
2350 }
2351
2352 int cgroup_attach(const struct lxc_conf *conf, const char *name,
2353 const char *lxcpath, pid_t pid)
2354 {
2355 __do_close int unified_fd = -EBADF;
2356 int ret;
2357
2358 if (!conf || !name || !lxcpath || pid <= 0)
2359 return ret_errno(EINVAL);
2360
2361 unified_fd = lxc_cmd_get_cgroup2_fd(name, lxcpath);
2362 if (unified_fd < 0)
2363 return ret_errno(EBADF);
2364
2365 if (!lxc_list_empty(&conf->id_map)) {
2366 struct userns_exec_unified_attach_data args = {
2367 .conf = conf,
2368 .unified_fd = unified_fd,
2369 .pid = pid,
2370 };
2371
2372 ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, args.sk_pair);
2373 if (ret < 0)
2374 return -errno;
2375
2376 ret = userns_exec_minimal(conf,
2377 cgroup_unified_attach_parent_wrapper,
2378 &args,
2379 cgroup_unified_attach_child_wrapper,
2380 &args);
2381 } else {
2382 ret = cgroup_attach_leaf(conf, unified_fd, pid);
2383 }
2384
2385 return ret;
2386 }
2387
2388 /* Technically, we're always at a delegation boundary here (This is especially
2389 * true when cgroup namespaces are available.). The reasoning is that in order
2390 * for us to have been able to start a container in the first place the root
2391 * cgroup must have been a leaf node. Now, either the container's init system
2392 * has populated the cgroup and kept it as a leaf node or it has created
2393 * subtrees. In the former case we will simply attach to the leaf node we
2394 * created when we started the container in the latter case we create our own
2395 * cgroup for the attaching process.
2396 */
2397 static int __cg_unified_attach(const struct hierarchy *h,
2398 const struct lxc_conf *conf, const char *name,
2399 const char *lxcpath, pid_t pid,
2400 const char *controller)
2401 {
2402 __do_close int unified_fd = -EBADF;
2403 __do_free char *path = NULL, *cgroup = NULL;
2404 int ret;
2405
2406 if (!conf || !name || !lxcpath || pid <= 0)
2407 return ret_errno(EINVAL);
2408
2409 ret = cgroup_attach(conf, name, lxcpath, pid);
2410 if (ret == 0)
2411 return log_trace(0, "Attached to unified cgroup via command handler");
2412 if (ret != -EBADF)
2413 return log_error_errno(ret, errno, "Failed to attach to unified cgroup");
2414
2415 /* Fall back to retrieving the path for the unified cgroup. */
2416 cgroup = lxc_cmd_get_cgroup_path(name, lxcpath, controller);
2417 /* not running */
2418 if (!cgroup)
2419 return 0;
2420
2421 path = must_make_path(h->mountpoint, cgroup, NULL);
2422
2423 unified_fd = open(path, O_PATH | O_DIRECTORY | O_CLOEXEC);
2424 if (unified_fd < 0)
2425 return ret_errno(EBADF);
2426
2427 if (!lxc_list_empty(&conf->id_map)) {
2428 struct userns_exec_unified_attach_data args = {
2429 .conf = conf,
2430 .unified_fd = unified_fd,
2431 .pid = pid,
2432 };
2433
2434 ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, args.sk_pair);
2435 if (ret < 0)
2436 return -errno;
2437
2438 ret = userns_exec_minimal(conf,
2439 cgroup_unified_attach_parent_wrapper,
2440 &args,
2441 cgroup_unified_attach_child_wrapper,
2442 &args);
2443 } else {
2444 ret = cgroup_attach_leaf(conf, unified_fd, pid);
2445 }
2446
2447 return ret;
2448 }
2449
2450 __cgfsng_ops static bool cgfsng_attach(struct cgroup_ops *ops,
2451 const struct lxc_conf *conf,
2452 const char *name, const char *lxcpath,
2453 pid_t pid)
2454 {
2455 int len, ret;
2456 char pidstr[INTTYPE_TO_STRLEN(pid_t)];
2457
2458 if (!ops)
2459 return ret_set_errno(false, ENOENT);
2460
2461 if (!ops->hierarchies)
2462 return true;
2463
2464 len = snprintf(pidstr, sizeof(pidstr), "%d", pid);
2465 if (len < 0 || (size_t)len >= sizeof(pidstr))
2466 return false;
2467
2468 for (int i = 0; ops->hierarchies[i]; i++) {
2469 __do_free char *fullpath = NULL, *path = NULL;
2470 struct hierarchy *h = ops->hierarchies[i];
2471
2472 if (h->version == CGROUP2_SUPER_MAGIC) {
2473 ret = __cg_unified_attach(h, conf, name, lxcpath, pid,
2474 h->controllers[0]);
2475 if (ret < 0)
2476 return false;
2477
2478 continue;
2479 }
2480
2481 path = lxc_cmd_get_cgroup_path(name, lxcpath, h->controllers[0]);
2482 /* not running */
2483 if (!path)
2484 return false;
2485
2486 fullpath = build_full_cgpath_from_monitorpath(h, path, "cgroup.procs");
2487 ret = lxc_write_to_file(fullpath, pidstr, len, false, 0666);
2488 if (ret < 0)
2489 return log_error_errno(false, errno, "Failed to attach %d to %s",
2490 (int)pid, fullpath);
2491 }
2492
2493 return true;
2494 }
2495
2496 /* Called externally (i.e. from 'lxc-cgroup') to query cgroup limits. Here we
2497 * don't have a cgroup_data set up, so we ask the running container through the
2498 * commands API for the cgroup path.
2499 */
2500 __cgfsng_ops static int cgfsng_get(struct cgroup_ops *ops, const char *filename,
2501 char *value, size_t len, const char *name,
2502 const char *lxcpath)
2503 {
2504 __do_free char *path = NULL;
2505 __do_free char *controller = NULL;
2506 char *p;
2507 struct hierarchy *h;
2508 int ret = -1;
2509
2510 if (!ops)
2511 return ret_set_errno(-1, ENOENT);
2512
2513 controller = must_copy_string(filename);
2514 p = strchr(controller, '.');
2515 if (p)
2516 *p = '\0';
2517
2518 path = lxc_cmd_get_limiting_cgroup_path(name, lxcpath, controller);
2519 /* not running */
2520 if (!path)
2521 return -1;
2522
2523 h = get_hierarchy(ops, controller);
2524 if (h) {
2525 __do_free char *fullpath = NULL;
2526
2527 fullpath = build_full_cgpath_from_monitorpath(h, path, filename);
2528 ret = lxc_read_from_file(fullpath, value, len);
2529 }
2530
2531 return ret;
2532 }
2533
2534 static int device_cgroup_parse_access(struct device_item *device, const char *val)
2535 {
2536 for (int count = 0; count < 3; count++, val++) {
2537 switch (*val) {
2538 case 'r':
2539 device->access[count] = *val;
2540 break;
2541 case 'w':
2542 device->access[count] = *val;
2543 break;
2544 case 'm':
2545 device->access[count] = *val;
2546 break;
2547 case '\n':
2548 case '\0':
2549 count = 3;
2550 break;
2551 default:
2552 return ret_errno(EINVAL);
2553 }
2554 }
2555
2556 return 0;
2557 }
2558
2559 static int device_cgroup_rule_parse(struct device_item *device, const char *key,
2560 const char *val)
2561 {
2562 int count, ret;
2563 char temp[50];
2564
2565 if (strcmp("devices.allow", key) == 0)
2566 device->allow = 1;
2567 else
2568 device->allow = 0;
2569
2570 if (strcmp(val, "a") == 0) {
2571 /* global rule */
2572 device->type = 'a';
2573 device->major = -1;
2574 device->minor = -1;
2575 device->global_rule = device->allow
2576 ? LXC_BPF_DEVICE_CGROUP_BLACKLIST
2577 : LXC_BPF_DEVICE_CGROUP_WHITELIST;
2578 device->allow = -1;
2579 return 0;
2580 }
2581
2582 /* local rule */
2583 device->global_rule = LXC_BPF_DEVICE_CGROUP_LOCAL_RULE;
2584
2585 switch (*val) {
2586 case 'a':
2587 __fallthrough;
2588 case 'b':
2589 __fallthrough;
2590 case 'c':
2591 device->type = *val;
2592 break;
2593 default:
2594 return -1;
2595 }
2596
2597 val++;
2598 if (!isspace(*val))
2599 return -1;
2600 val++;
2601 if (*val == '*') {
2602 device->major = -1;
2603 val++;
2604 } else if (isdigit(*val)) {
2605 memset(temp, 0, sizeof(temp));
2606 for (count = 0; count < sizeof(temp) - 1; count++) {
2607 temp[count] = *val;
2608 val++;
2609 if (!isdigit(*val))
2610 break;
2611 }
2612 ret = lxc_safe_int(temp, &device->major);
2613 if (ret)
2614 return -1;
2615 } else {
2616 return -1;
2617 }
2618 if (*val != ':')
2619 return -1;
2620 val++;
2621
2622 /* read minor */
2623 if (*val == '*') {
2624 device->minor = -1;
2625 val++;
2626 } else if (isdigit(*val)) {
2627 memset(temp, 0, sizeof(temp));
2628 for (count = 0; count < sizeof(temp) - 1; count++) {
2629 temp[count] = *val;
2630 val++;
2631 if (!isdigit(*val))
2632 break;
2633 }
2634 ret = lxc_safe_int(temp, &device->minor);
2635 if (ret)
2636 return -1;
2637 } else {
2638 return -1;
2639 }
2640 if (!isspace(*val))
2641 return -1;
2642
2643 return device_cgroup_parse_access(device, ++val);
2644 }
2645
2646 /* Called externally (i.e. from 'lxc-cgroup') to set new cgroup limits. Here we
2647 * don't have a cgroup_data set up, so we ask the running container through the
2648 * commands API for the cgroup path.
2649 */
2650 __cgfsng_ops static int cgfsng_set(struct cgroup_ops *ops,
2651 const char *key, const char *value,
2652 const char *name, const char *lxcpath)
2653 {
2654 __do_free char *path = NULL;
2655 __do_free char *controller = NULL;
2656 char *p;
2657 struct hierarchy *h;
2658 int ret = -1;
2659
2660 if (!ops)
2661 return ret_set_errno(-1, ENOENT);
2662
2663 controller = must_copy_string(key);
2664 p = strchr(controller, '.');
2665 if (p)
2666 *p = '\0';
2667
2668 if (pure_unified_layout(ops) && strcmp(controller, "devices") == 0) {
2669 struct device_item device = {0};
2670
2671 ret = device_cgroup_rule_parse(&device, key, value);
2672 if (ret < 0)
2673 return log_error_errno(-1, EINVAL, "Failed to parse device string %s=%s",
2674 key, value);
2675
2676 ret = lxc_cmd_add_bpf_device_cgroup(name, lxcpath, &device);
2677 if (ret < 0)
2678 return -1;
2679
2680 return 0;
2681 }
2682
2683 path = lxc_cmd_get_limiting_cgroup_path(name, lxcpath, controller);
2684 /* not running */
2685 if (!path)
2686 return -1;
2687
2688 h = get_hierarchy(ops, controller);
2689 if (h) {
2690 __do_free char *fullpath = NULL;
2691
2692 fullpath = build_full_cgpath_from_monitorpath(h, path, key);
2693 ret = lxc_write_to_file(fullpath, value, strlen(value), false, 0666);
2694 }
2695
2696 return ret;
2697 }
2698
2699 /* take devices cgroup line
2700 * /dev/foo rwx
2701 * and convert it to a valid
2702 * type major:minor mode
2703 * line. Return <0 on error. Dest is a preallocated buffer long enough to hold
2704 * the output.
2705 */
2706 static int device_cgroup_rule_parse_devpath(struct device_item *device,
2707 const char *devpath)
2708 {
2709 __do_free char *path = NULL;
2710 char *mode = NULL;
2711 int n_parts, ret;
2712 char *p;
2713 struct stat sb;
2714
2715 path = must_copy_string(devpath);
2716
2717 /*
2718 * Read path followed by mode. Ignore any trailing text.
2719 * A ' # comment' would be legal. Technically other text is not
2720 * legal, we could check for that if we cared to.
2721 */
2722 for (n_parts = 1, p = path; *p; p++) {
2723 if (*p != ' ')
2724 continue;
2725 *p = '\0';
2726
2727 if (n_parts != 1)
2728 break;
2729 p++;
2730 n_parts++;
2731
2732 while (*p == ' ')
2733 p++;
2734
2735 mode = p;
2736
2737 if (*p == '\0')
2738 return ret_set_errno(-1, EINVAL);
2739 }
2740
2741 if (device_cgroup_parse_access(device, mode) < 0)
2742 return -1;
2743
2744 if (n_parts == 1)
2745 return ret_set_errno(-1, EINVAL);
2746
2747 ret = stat(path, &sb);
2748 if (ret < 0)
2749 return ret_set_errno(-1, errno);
2750
2751 mode_t m = sb.st_mode & S_IFMT;
2752 switch (m) {
2753 case S_IFBLK:
2754 device->type = 'b';
2755 break;
2756 case S_IFCHR:
2757 device->type = 'c';
2758 break;
2759 default:
2760 return log_error_errno(-1, EINVAL, "Unsupported device type %i for \"%s\"", m, path);
2761 }
2762
2763 device->major = MAJOR(sb.st_rdev);
2764 device->minor = MINOR(sb.st_rdev);
2765 device->allow = 1;
2766 device->global_rule = LXC_BPF_DEVICE_CGROUP_LOCAL_RULE;
2767
2768 return 0;
2769 }
2770
2771 static int convert_devpath(const char *invalue, char *dest)
2772 {
2773 struct device_item device = {0};
2774 int ret;
2775
2776 ret = device_cgroup_rule_parse_devpath(&device, invalue);
2777 if (ret < 0)
2778 return -1;
2779
2780 ret = snprintf(dest, 50, "%c %d:%d %s", device.type, device.major,
2781 device.minor, device.access);
2782 if (ret < 0 || ret >= 50)
2783 return log_error_errno(-1, ENAMETOOLONG, "Error on configuration value \"%c %d:%d %s\" (max 50 chars)",
2784 device.type, device.major, device.minor, device.access);
2785
2786 return 0;
2787 }
2788
2789 /* Called from setup_limits - here we have the container's cgroup_data because
2790 * we created the cgroups.
2791 */
2792 static int cg_legacy_set_data(struct cgroup_ops *ops, const char *filename,
2793 const char *value, bool is_cpuset)
2794 {
2795 __do_free char *controller = NULL;
2796 char *p;
2797 /* "b|c <2^64-1>:<2^64-1> r|w|m" = 47 chars max */
2798 char converted_value[50];
2799 struct hierarchy *h;
2800
2801 controller = must_copy_string(filename);
2802 p = strchr(controller, '.');
2803 if (p)
2804 *p = '\0';
2805
2806 if (strcmp("devices.allow", filename) == 0 && value[0] == '/') {
2807 int ret;
2808
2809 ret = convert_devpath(value, converted_value);
2810 if (ret < 0)
2811 return ret;
2812 value = converted_value;
2813 }
2814
2815 h = get_hierarchy(ops, controller);
2816 if (!h)
2817 return log_error_errno(-ENOENT, ENOENT, "Failed to setup limits for the \"%s\" controller. The controller seems to be unused by \"cgfsng\" cgroup driver or not enabled on the cgroup hierarchy", controller);
2818
2819 if (is_cpuset) {
2820 int ret = lxc_write_openat(h->container_full_path, filename, value, strlen(value));
2821 if (ret)
2822 return ret;
2823 }
2824 return lxc_write_openat(h->container_limit_path, filename, value, strlen(value));
2825 }
2826
2827 __cgfsng_ops static bool cgfsng_setup_limits_legacy(struct cgroup_ops *ops,
2828 struct lxc_conf *conf,
2829 bool do_devices)
2830 {
2831 __do_free struct lxc_list *sorted_cgroup_settings = NULL;
2832 struct lxc_list *cgroup_settings = &conf->cgroup;
2833 struct lxc_list *iterator, *next;
2834 struct lxc_cgroup *cg;
2835 bool ret = false;
2836
2837 if (!ops)
2838 return ret_set_errno(false, ENOENT);
2839
2840 if (!conf)
2841 return ret_set_errno(false, EINVAL);
2842
2843 cgroup_settings = &conf->cgroup;
2844 if (lxc_list_empty(cgroup_settings))
2845 return true;
2846
2847 if (!ops->hierarchies)
2848 return ret_set_errno(false, EINVAL);
2849
2850 if (!pure_unified_layout(ops))
2851 return log_warn_errno(true, EINVAL, "Ignoring legacy cgroup limits on pure cgroup2 system");
2852
2853 sorted_cgroup_settings = sort_cgroup_settings(cgroup_settings);
2854 if (!sorted_cgroup_settings)
2855 return false;
2856
2857 lxc_list_for_each(iterator, sorted_cgroup_settings) {
2858 cg = iterator->elem;
2859
2860 if (do_devices == !strncmp("devices", cg->subsystem, 7)) {
2861 if (cg_legacy_set_data(ops, cg->subsystem, cg->value, strncmp("cpuset", cg->subsystem, 6) == 0)) {
2862 if (do_devices && (errno == EACCES || errno == EPERM)) {
2863 SYSWARN("Failed to set \"%s\" to \"%s\"", cg->subsystem, cg->value);
2864 continue;
2865 }
2866 SYSERROR("Failed to set \"%s\" to \"%s\"", cg->subsystem, cg->value);
2867 goto out;
2868 }
2869 DEBUG("Set controller \"%s\" set to \"%s\"", cg->subsystem, cg->value);
2870 }
2871 }
2872
2873 ret = true;
2874 INFO("Limits for the legacy cgroup hierarchies have been setup");
2875 out:
2876 lxc_list_for_each_safe(iterator, sorted_cgroup_settings, next) {
2877 lxc_list_del(iterator);
2878 free(iterator);
2879 }
2880
2881 return ret;
2882 }
2883
2884 /*
2885 * Some of the parsing logic comes from the original cgroup device v1
2886 * implementation in the kernel.
2887 */
2888 static int bpf_device_cgroup_prepare(struct cgroup_ops *ops,
2889 struct lxc_conf *conf, const char *key,
2890 const char *val)
2891 {
2892 #ifdef HAVE_STRUCT_BPF_CGROUP_DEV_CTX
2893 struct device_item device_item = {0};
2894 int ret;
2895
2896 if (strcmp("devices.allow", key) == 0 && *val == '/')
2897 ret = device_cgroup_rule_parse_devpath(&device_item, val);
2898 else
2899 ret = device_cgroup_rule_parse(&device_item, key, val);
2900 if (ret < 0)
2901 return log_error_errno(-1, EINVAL, "Failed to parse device string %s=%s", key, val);
2902
2903 ret = bpf_list_add_device(conf, &device_item);
2904 if (ret < 0)
2905 return -1;
2906 #endif
2907 return 0;
2908 }
2909
2910 __cgfsng_ops static bool cgfsng_setup_limits(struct cgroup_ops *ops,
2911 struct lxc_handler *handler)
2912 {
2913 struct lxc_list *cgroup_settings, *iterator;
2914 struct hierarchy *h;
2915 struct lxc_conf *conf;
2916
2917 if (!ops)
2918 return ret_set_errno(false, ENOENT);
2919
2920 if (!ops->hierarchies)
2921 return true;
2922
2923 if (!ops->container_cgroup)
2924 return ret_set_errno(false, EINVAL);
2925
2926 if (!handler || !handler->conf)
2927 return ret_set_errno(false, EINVAL);
2928 conf = handler->conf;
2929
2930 if (lxc_list_empty(&conf->cgroup2))
2931 return true;
2932 cgroup_settings = &conf->cgroup2;
2933
2934 if (!ops->unified)
2935 return false;
2936 h = ops->unified;
2937
2938 lxc_list_for_each (iterator, cgroup_settings) {
2939 struct lxc_cgroup *cg = iterator->elem;
2940 int ret;
2941
2942 if (strncmp("devices", cg->subsystem, 7) == 0) {
2943 ret = bpf_device_cgroup_prepare(ops, conf, cg->subsystem,
2944 cg->value);
2945 } else {
2946 ret = lxc_write_openat(h->container_limit_path,
2947 cg->subsystem, cg->value,
2948 strlen(cg->value));
2949 if (ret < 0)
2950 return log_error_errno(false, errno, "Failed to set \"%s\" to \"%s\"",
2951 cg->subsystem, cg->value);
2952 }
2953 TRACE("Set \"%s\" to \"%s\"", cg->subsystem, cg->value);
2954 }
2955
2956 return log_info(true, "Limits for the unified cgroup hierarchy have been setup");
2957 }
2958
2959 __cgfsng_ops bool cgfsng_devices_activate(struct cgroup_ops *ops,
2960 struct lxc_handler *handler)
2961 {
2962 #ifdef HAVE_STRUCT_BPF_CGROUP_DEV_CTX
2963 __do_bpf_program_free struct bpf_program *devices = NULL;
2964 int ret;
2965 struct lxc_conf *conf;
2966 struct hierarchy *unified;
2967 struct lxc_list *it;
2968 struct bpf_program *devices_old;
2969
2970 if (!ops)
2971 return ret_set_errno(false, ENOENT);
2972
2973 if (!ops->hierarchies)
2974 return true;
2975
2976 if (!ops->container_cgroup)
2977 return ret_set_errno(false, EEXIST);
2978
2979 if (!handler || !handler->conf)
2980 return ret_set_errno(false, EINVAL);
2981 conf = handler->conf;
2982
2983 unified = ops->unified;
2984 if (!unified || !unified->bpf_device_controller ||
2985 !unified->container_full_path || lxc_list_empty(&conf->devices))
2986 return true;
2987
2988 devices = bpf_program_new(BPF_PROG_TYPE_CGROUP_DEVICE);
2989 if (!devices)
2990 return log_error_errno(false, ENOMEM, "Failed to create new bpf program");
2991
2992 ret = bpf_program_init(devices);
2993 if (ret)
2994 return log_error_errno(false, ENOMEM, "Failed to initialize bpf program");
2995
2996 lxc_list_for_each(it, &conf->devices) {
2997 struct device_item *cur = it->elem;
2998
2999 ret = bpf_program_append_device(devices, cur);
3000 if (ret)
3001 return log_error_errno(false, ENOMEM, "Failed to add new rule to bpf device program: type %c, major %d, minor %d, access %s, allow %d, global_rule %d",
3002 cur->type,
3003 cur->major,
3004 cur->minor,
3005 cur->access,
3006 cur->allow,
3007 cur->global_rule);
3008 TRACE("Added rule to bpf device program: type %c, major %d, minor %d, access %s, allow %d, global_rule %d",
3009 cur->type,
3010 cur->major,
3011 cur->minor,
3012 cur->access,
3013 cur->allow,
3014 cur->global_rule);
3015 }
3016
3017 ret = bpf_program_finalize(devices);
3018 if (ret)
3019 return log_error_errno(false, ENOMEM, "Failed to finalize bpf program");
3020
3021 ret = bpf_program_cgroup_attach(devices, BPF_CGROUP_DEVICE,
3022 unified->container_limit_path,
3023 BPF_F_ALLOW_MULTI);
3024 if (ret)
3025 return log_error_errno(false, ENOMEM, "Failed to attach bpf program");
3026
3027 /* Replace old bpf program. */
3028 devices_old = move_ptr(conf->cgroup2_devices);
3029 conf->cgroup2_devices = move_ptr(devices);
3030 devices = move_ptr(devices_old);
3031 #endif
3032 return true;
3033 }
3034
3035 bool __cgfsng_delegate_controllers(struct cgroup_ops *ops, const char *cgroup)
3036 {
3037 __do_free char *add_controllers = NULL, *base_path = NULL;
3038 __do_free_string_list char **parts = NULL;
3039 struct hierarchy *unified = ops->unified;
3040 ssize_t parts_len;
3041 char **it;
3042 size_t full_len = 0;
3043
3044 if (!ops->hierarchies || !pure_unified_layout(ops) ||
3045 !unified->controllers[0])
3046 return true;
3047
3048 /* For now we simply enable all controllers that we have detected by
3049 * creating a string like "+memory +pids +cpu +io".
3050 * TODO: In the near future we might want to support "-<controller>"
3051 * etc. but whether supporting semantics like this make sense will need
3052 * some thinking.
3053 */
3054 for (it = unified->controllers; it && *it; it++) {
3055 full_len += strlen(*it) + 2;
3056 add_controllers = must_realloc(add_controllers, full_len + 1);
3057
3058 if (unified->controllers[0] == *it)
3059 add_controllers[0] = '\0';
3060
3061 (void)strlcat(add_controllers, "+", full_len + 1);
3062 (void)strlcat(add_controllers, *it, full_len + 1);
3063
3064 if ((it + 1) && *(it + 1))
3065 (void)strlcat(add_controllers, " ", full_len + 1);
3066 }
3067
3068 parts = lxc_string_split(cgroup, '/');
3069 if (!parts)
3070 return false;
3071
3072 parts_len = lxc_array_len((void **)parts);
3073 if (parts_len > 0)
3074 parts_len--;
3075
3076 base_path = must_make_path(unified->mountpoint, unified->container_base_path, NULL);
3077 for (ssize_t i = -1; i < parts_len; i++) {
3078 int ret;
3079 __do_free char *target = NULL;
3080
3081 if (i >= 0)
3082 base_path = must_append_path(base_path, parts[i], NULL);
3083 target = must_make_path(base_path, "cgroup.subtree_control", NULL);
3084 ret = lxc_writeat(-1, target, add_controllers, full_len);
3085 if (ret < 0)
3086 return log_error_errno(false, errno, "Could not enable \"%s\" controllers in the unified cgroup \"%s\"",
3087 add_controllers, target);
3088 TRACE("Enable \"%s\" controllers in the unified cgroup \"%s\"", add_controllers, target);
3089 }
3090
3091 return true;
3092 }
3093
3094 __cgfsng_ops bool cgfsng_monitor_delegate_controllers(struct cgroup_ops *ops)
3095 {
3096 if (!ops)
3097 return ret_set_errno(false, ENOENT);
3098
3099 return __cgfsng_delegate_controllers(ops, ops->monitor_cgroup);
3100 }
3101
3102 __cgfsng_ops bool cgfsng_payload_delegate_controllers(struct cgroup_ops *ops)
3103 {
3104 if (!ops)
3105 return ret_set_errno(false, ENOENT);
3106
3107 return __cgfsng_delegate_controllers(ops, ops->container_cgroup);
3108 }
3109
3110 static bool cgroup_use_wants_controllers(const struct cgroup_ops *ops,
3111 char **controllers)
3112 {
3113 if (!ops->cgroup_use)
3114 return true;
3115
3116 for (char **cur_ctrl = controllers; cur_ctrl && *cur_ctrl; cur_ctrl++) {
3117 bool found = false;
3118
3119 for (char **cur_use = ops->cgroup_use; cur_use && *cur_use; cur_use++) {
3120 if (strcmp(*cur_use, *cur_ctrl) != 0)
3121 continue;
3122
3123 found = true;
3124 break;
3125 }
3126
3127 if (found)
3128 continue;
3129
3130 return false;
3131 }
3132
3133 return true;
3134 }
3135
3136 static void cg_unified_delegate(char ***delegate)
3137 {
3138 __do_free char *buf = NULL;
3139 char *standard[] = {"cgroup.subtree_control", "cgroup.threads", NULL};
3140 char *token;
3141 int idx;
3142
3143 buf = read_file("/sys/kernel/cgroup/delegate");
3144 if (!buf) {
3145 for (char **p = standard; p && *p; p++) {
3146 idx = append_null_to_list((void ***)delegate);
3147 (*delegate)[idx] = must_copy_string(*p);
3148 }
3149 SYSWARN("Failed to read /sys/kernel/cgroup/delegate");
3150 return;
3151 }
3152
3153 lxc_iterate_parts(token, buf, " \t\n") {
3154 /*
3155 * We always need to chown this for both cgroup and
3156 * cgroup2.
3157 */
3158 if (strcmp(token, "cgroup.procs") == 0)
3159 continue;
3160
3161 idx = append_null_to_list((void ***)delegate);
3162 (*delegate)[idx] = must_copy_string(token);
3163 }
3164 }
3165
3166 /* At startup, parse_hierarchies finds all the info we need about cgroup
3167 * mountpoints and current cgroups, and stores it in @d.
3168 */
3169 static int cg_hybrid_init(struct cgroup_ops *ops, bool relative, bool unprivileged)
3170 {
3171 __do_free char *basecginfo = NULL, *line = NULL;
3172 __do_free_string_list char **klist = NULL, **nlist = NULL;
3173 __do_fclose FILE *f = NULL;
3174 int ret;
3175 size_t len = 0;
3176
3177 /* Root spawned containers escape the current cgroup, so use init's
3178 * cgroups as our base in that case.
3179 */
3180 if (!relative && (geteuid() == 0))
3181 basecginfo = read_file("/proc/1/cgroup");
3182 else
3183 basecginfo = read_file("/proc/self/cgroup");
3184 if (!basecginfo)
3185 return ret_set_errno(-1, ENOMEM);
3186
3187 ret = get_existing_subsystems(&klist, &nlist);
3188 if (ret < 0)
3189 return log_error_errno(-1, errno, "Failed to retrieve available legacy cgroup controllers");
3190
3191 f = fopen("/proc/self/mountinfo", "re");
3192 if (!f)
3193 return log_error_errno(-1, errno, "Failed to open \"/proc/self/mountinfo\"");
3194
3195 lxc_cgfsng_print_basecg_debuginfo(basecginfo, klist, nlist);
3196
3197 while (getline(&line, &len, f) != -1) {
3198 __do_free char *base_cgroup = NULL, *mountpoint = NULL;
3199 __do_free_string_list char **controller_list = NULL;
3200 int type;
3201 bool writeable;
3202 struct hierarchy *new;
3203
3204 type = get_cgroup_version(line);
3205 if (type == 0)
3206 continue;
3207
3208 if (type == CGROUP2_SUPER_MAGIC && ops->unified)
3209 continue;
3210
3211 if (ops->cgroup_layout == CGROUP_LAYOUT_UNKNOWN) {
3212 if (type == CGROUP2_SUPER_MAGIC)
3213 ops->cgroup_layout = CGROUP_LAYOUT_UNIFIED;
3214 else if (type == CGROUP_SUPER_MAGIC)
3215 ops->cgroup_layout = CGROUP_LAYOUT_LEGACY;
3216 } else if (ops->cgroup_layout == CGROUP_LAYOUT_UNIFIED) {
3217 if (type == CGROUP_SUPER_MAGIC)
3218 ops->cgroup_layout = CGROUP_LAYOUT_HYBRID;
3219 } else if (ops->cgroup_layout == CGROUP_LAYOUT_LEGACY) {
3220 if (type == CGROUP2_SUPER_MAGIC)
3221 ops->cgroup_layout = CGROUP_LAYOUT_HYBRID;
3222 }
3223
3224 controller_list = cg_hybrid_get_controllers(klist, nlist, line, type);
3225 if (!controller_list && type == CGROUP_SUPER_MAGIC)
3226 continue;
3227
3228 if (type == CGROUP_SUPER_MAGIC)
3229 if (controller_list_is_dup(ops->hierarchies, controller_list)) {
3230 TRACE("Skipping duplicating controller");
3231 continue;
3232 }
3233
3234 mountpoint = cg_hybrid_get_mountpoint(line);
3235 if (!mountpoint) {
3236 ERROR("Failed parsing mountpoint from \"%s\"", line);
3237 continue;
3238 }
3239
3240 if (type == CGROUP_SUPER_MAGIC)
3241 base_cgroup = cg_hybrid_get_current_cgroup(basecginfo, controller_list[0], CGROUP_SUPER_MAGIC);
3242 else
3243 base_cgroup = cg_hybrid_get_current_cgroup(basecginfo, NULL, CGROUP2_SUPER_MAGIC);
3244 if (!base_cgroup) {
3245 ERROR("Failed to find current cgroup");
3246 continue;
3247 }
3248
3249 trim(base_cgroup);
3250 prune_init_scope(base_cgroup);
3251 if (type == CGROUP2_SUPER_MAGIC)
3252 writeable = test_writeable_v2(mountpoint, base_cgroup);
3253 else
3254 writeable = test_writeable_v1(mountpoint, base_cgroup);
3255 if (!writeable) {
3256 TRACE("The %s group is not writeable", base_cgroup);
3257 continue;
3258 }
3259
3260 if (type == CGROUP2_SUPER_MAGIC) {
3261 char *cgv2_ctrl_path;
3262
3263 cgv2_ctrl_path = must_make_path(mountpoint, base_cgroup,
3264 "cgroup.controllers",
3265 NULL);
3266
3267 controller_list = cg_unified_get_controllers(cgv2_ctrl_path);
3268 free(cgv2_ctrl_path);
3269 if (!controller_list) {
3270 controller_list = cg_unified_make_empty_controller();
3271 TRACE("No controllers are enabled for "
3272 "delegation in the unified hierarchy");
3273 }
3274 }
3275
3276 /* Exclude all controllers that cgroup use does not want. */
3277 if (!cgroup_use_wants_controllers(ops, controller_list)) {
3278 TRACE("Skipping controller");
3279 continue;
3280 }
3281
3282 new = add_hierarchy(&ops->hierarchies, move_ptr(controller_list), move_ptr(mountpoint), move_ptr(base_cgroup), type);
3283 if (type == CGROUP2_SUPER_MAGIC && !ops->unified) {
3284 if (unprivileged)
3285 cg_unified_delegate(&new->cgroup2_chown);
3286 ops->unified = new;
3287 }
3288 }
3289
3290 TRACE("Writable cgroup hierarchies:");
3291 lxc_cgfsng_print_hierarchies(ops);
3292
3293 /* verify that all controllers in cgroup.use and all crucial
3294 * controllers are accounted for
3295 */
3296 if (!all_controllers_found(ops))
3297 return log_error_errno(-1, ENOENT, "Failed to find all required controllers");
3298
3299 return 0;
3300 }
3301
3302 /* Get current cgroup from /proc/self/cgroup for the cgroupfs v2 hierarchy. */
3303 static char *cg_unified_get_current_cgroup(bool relative)
3304 {
3305 __do_free char *basecginfo = NULL;
3306 char *copy;
3307 char *base_cgroup;
3308
3309 if (!relative && (geteuid() == 0))
3310 basecginfo = read_file("/proc/1/cgroup");
3311 else
3312 basecginfo = read_file("/proc/self/cgroup");
3313 if (!basecginfo)
3314 return NULL;
3315
3316 base_cgroup = strstr(basecginfo, "0::/");
3317 if (!base_cgroup)
3318 return NULL;
3319
3320 base_cgroup = base_cgroup + 3;
3321 copy = copy_to_eol(base_cgroup);
3322 if (!copy)
3323 return NULL;
3324
3325 return trim(copy);
3326 }
3327
3328 static int cg_unified_init(struct cgroup_ops *ops, bool relative,
3329 bool unprivileged)
3330 {
3331 __do_free char *subtree_path = NULL;
3332 int ret;
3333 char *mountpoint;
3334 char **delegatable;
3335 struct hierarchy *new;
3336 char *base_cgroup = NULL;
3337
3338 ret = unified_cgroup_hierarchy();
3339 if (ret == -ENOMEDIUM)
3340 return ret_errno(ENOMEDIUM);
3341
3342 if (ret != CGROUP2_SUPER_MAGIC)
3343 return 0;
3344
3345 base_cgroup = cg_unified_get_current_cgroup(relative);
3346 if (!base_cgroup)
3347 return ret_errno(EINVAL);
3348 if (!relative)
3349 prune_init_scope(base_cgroup);
3350
3351 /*
3352 * We assume that the cgroup we're currently in has been delegated to
3353 * us and we are free to further delege all of the controllers listed
3354 * in cgroup.controllers further down the hierarchy.
3355 */
3356 mountpoint = must_copy_string(DEFAULT_CGROUP_MOUNTPOINT);
3357 subtree_path = must_make_path(mountpoint, base_cgroup, "cgroup.controllers", NULL);
3358 delegatable = cg_unified_get_controllers(subtree_path);
3359 if (!delegatable)
3360 delegatable = cg_unified_make_empty_controller();
3361 if (!delegatable[0])
3362 TRACE("No controllers are enabled for delegation");
3363
3364 /* TODO: If the user requested specific controllers via lxc.cgroup.use
3365 * we should verify here. The reason I'm not doing it right is that I'm
3366 * not convinced that lxc.cgroup.use will be the future since it is a
3367 * global property. I much rather have an option that lets you request
3368 * controllers per container.
3369 */
3370
3371 new = add_hierarchy(&ops->hierarchies, delegatable, mountpoint, base_cgroup, CGROUP2_SUPER_MAGIC);
3372 if (unprivileged)
3373 cg_unified_delegate(&new->cgroup2_chown);
3374
3375 if (bpf_devices_cgroup_supported())
3376 new->bpf_device_controller = 1;
3377
3378 ops->cgroup_layout = CGROUP_LAYOUT_UNIFIED;
3379 ops->unified = new;
3380
3381 return CGROUP2_SUPER_MAGIC;
3382 }
3383
3384 static int cg_init(struct cgroup_ops *ops, struct lxc_conf *conf)
3385 {
3386 int ret;
3387 const char *tmp;
3388 bool relative = conf->cgroup_meta.relative;
3389
3390 tmp = lxc_global_config_value("lxc.cgroup.use");
3391 if (tmp) {
3392 __do_free char *pin = NULL;
3393 char *chop, *cur;
3394
3395 pin = must_copy_string(tmp);
3396 chop = pin;
3397
3398 lxc_iterate_parts(cur, chop, ",")
3399 must_append_string(&ops->cgroup_use, cur);
3400 }
3401
3402 ret = cg_unified_init(ops, relative, !lxc_list_empty(&conf->id_map));
3403 if (ret < 0)
3404 return -1;
3405
3406 if (ret == CGROUP2_SUPER_MAGIC)
3407 return 0;
3408
3409 return cg_hybrid_init(ops, relative, !lxc_list_empty(&conf->id_map));
3410 }
3411
3412 __cgfsng_ops static int cgfsng_data_init(struct cgroup_ops *ops)
3413 {
3414 const char *cgroup_pattern;
3415
3416 if (!ops)
3417 return ret_set_errno(-1, ENOENT);
3418
3419 /* copy system-wide cgroup information */
3420 cgroup_pattern = lxc_global_config_value("lxc.cgroup.pattern");
3421 if (cgroup_pattern && strcmp(cgroup_pattern, "") != 0)
3422 ops->cgroup_pattern = must_copy_string(cgroup_pattern);
3423
3424 return 0;
3425 }
3426
3427 struct cgroup_ops *cgfsng_ops_init(struct lxc_conf *conf)
3428 {
3429 __do_free struct cgroup_ops *cgfsng_ops = NULL;
3430
3431 cgfsng_ops = malloc(sizeof(struct cgroup_ops));
3432 if (!cgfsng_ops)
3433 return ret_set_errno(NULL, ENOMEM);
3434
3435 memset(cgfsng_ops, 0, sizeof(struct cgroup_ops));
3436 cgfsng_ops->cgroup_layout = CGROUP_LAYOUT_UNKNOWN;
3437
3438 if (cg_init(cgfsng_ops, conf))
3439 return NULL;
3440
3441 cgfsng_ops->data_init = cgfsng_data_init;
3442 cgfsng_ops->payload_destroy = cgfsng_payload_destroy;
3443 cgfsng_ops->monitor_destroy = cgfsng_monitor_destroy;
3444 cgfsng_ops->monitor_create = cgfsng_monitor_create;
3445 cgfsng_ops->monitor_enter = cgfsng_monitor_enter;
3446 cgfsng_ops->monitor_delegate_controllers = cgfsng_monitor_delegate_controllers;
3447 cgfsng_ops->payload_delegate_controllers = cgfsng_payload_delegate_controllers;
3448 cgfsng_ops->payload_create = cgfsng_payload_create;
3449 cgfsng_ops->payload_enter = cgfsng_payload_enter;
3450 cgfsng_ops->payload_finalize = cgfsng_payload_finalize;
3451 cgfsng_ops->escape = cgfsng_escape;
3452 cgfsng_ops->num_hierarchies = cgfsng_num_hierarchies;
3453 cgfsng_ops->get_hierarchies = cgfsng_get_hierarchies;
3454 cgfsng_ops->get_cgroup = cgfsng_get_cgroup;
3455 cgfsng_ops->get = cgfsng_get;
3456 cgfsng_ops->set = cgfsng_set;
3457 cgfsng_ops->freeze = cgfsng_freeze;
3458 cgfsng_ops->unfreeze = cgfsng_unfreeze;
3459 cgfsng_ops->setup_limits_legacy = cgfsng_setup_limits_legacy;
3460 cgfsng_ops->setup_limits = cgfsng_setup_limits;
3461 cgfsng_ops->driver = "cgfsng";
3462 cgfsng_ops->version = "1.0.0";
3463 cgfsng_ops->attach = cgfsng_attach;
3464 cgfsng_ops->chown = cgfsng_chown;
3465 cgfsng_ops->mount = cgfsng_mount;
3466 cgfsng_ops->devices_activate = cgfsng_devices_activate;
3467 cgfsng_ops->get_limiting_cgroup = cgfsng_get_limiting_cgroup;
3468
3469 return move_ptr(cgfsng_ops);
3470 }