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