]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/cgroups/cgfsng.c
31ad219c1d8193ce826dbef3d35451feee358e0a
[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 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,
952 const char *container_cgroup)
953 {
954 if (!container_cgroup || !hierarchies)
955 return 0;
956
957 for (int i = 0; hierarchies[i]; i++) {
958 struct hierarchy *h = hierarchies[i];
959 int ret;
960
961 if (!h->container_limit_path)
962 continue;
963
964 ret = lxc_rm_rf(h->container_limit_path);
965 if (ret < 0)
966 WARN("Failed to destroy \"%s\"", h->container_limit_path);
967
968 if (h->container_limit_path != h->container_full_path)
969 free_disarm(h->container_limit_path);
970 free_disarm(h->container_full_path);
971 }
972
973 return 0;
974 }
975
976 struct generic_userns_exec_data {
977 struct hierarchy **hierarchies;
978 const char *container_cgroup;
979 struct lxc_conf *conf;
980 uid_t origuid; /* target uid in parent namespace */
981 char *path;
982 };
983
984 static int cgroup_tree_remove_wrapper(void *data)
985 {
986 struct generic_userns_exec_data *arg = data;
987 uid_t nsuid = (arg->conf->root_nsuid_map != NULL) ? 0 : arg->conf->init_uid;
988 gid_t nsgid = (arg->conf->root_nsgid_map != NULL) ? 0 : arg->conf->init_gid;
989 int ret;
990
991 if (!lxc_setgroups(0, NULL) && errno != EPERM)
992 return log_error_errno(-1, errno, "Failed to setgroups(0, NULL)");
993
994 ret = setresgid(nsgid, nsgid, nsgid);
995 if (ret < 0)
996 return log_error_errno(-1, errno, "Failed to setresgid(%d, %d, %d)",
997 (int)nsgid, (int)nsgid, (int)nsgid);
998
999 ret = setresuid(nsuid, nsuid, nsuid);
1000 if (ret < 0)
1001 return log_error_errno(-1, errno, "Failed to setresuid(%d, %d, %d)",
1002 (int)nsuid, (int)nsuid, (int)nsuid);
1003
1004 return cgroup_tree_remove(arg->hierarchies, arg->container_cgroup);
1005 }
1006
1007 __cgfsng_ops static void cgfsng_payload_destroy(struct cgroup_ops *ops,
1008 struct lxc_handler *handler)
1009 {
1010 int ret;
1011
1012 if (!ops) {
1013 ERROR("Called with uninitialized cgroup operations");
1014 return;
1015 }
1016
1017 if (!ops->hierarchies)
1018 return;
1019
1020 if (!handler) {
1021 ERROR("Called with uninitialized handler");
1022 return;
1023 }
1024
1025 if (!handler->conf) {
1026 ERROR("Called with uninitialized conf");
1027 return;
1028 }
1029
1030 #ifdef HAVE_STRUCT_BPF_CGROUP_DEV_CTX
1031 ret = bpf_program_cgroup_detach(handler->conf->cgroup2_devices);
1032 if (ret < 0)
1033 WARN("Failed to detach bpf program from cgroup");
1034 #endif
1035
1036 if (handler->conf && !lxc_list_empty(&handler->conf->id_map)) {
1037 struct generic_userns_exec_data wrap = {
1038 .conf = handler->conf,
1039 .container_cgroup = ops->container_cgroup,
1040 .hierarchies = ops->hierarchies,
1041 .origuid = 0,
1042 };
1043 ret = userns_exec_1(handler->conf, cgroup_tree_remove_wrapper,
1044 &wrap, "cgroup_tree_remove_wrapper");
1045 } else {
1046 ret = cgroup_tree_remove(ops->hierarchies, ops->container_cgroup);
1047 }
1048 if (ret < 0)
1049 SYSWARN("Failed to destroy cgroups");
1050 }
1051
1052 __cgfsng_ops static void cgfsng_monitor_destroy(struct cgroup_ops *ops,
1053 struct lxc_handler *handler)
1054 {
1055 int len;
1056 char pidstr[INTTYPE_TO_STRLEN(pid_t)];
1057 const struct lxc_conf *conf;
1058
1059 if (!ops) {
1060 ERROR("Called with uninitialized cgroup operations");
1061 return;
1062 }
1063
1064 if (!ops->hierarchies)
1065 return;
1066
1067 if (!handler) {
1068 ERROR("Called with uninitialized handler");
1069 return;
1070 }
1071
1072 if (!handler->conf) {
1073 ERROR("Called with uninitialized conf");
1074 return;
1075 }
1076 conf = handler->conf;
1077
1078 len = snprintf(pidstr, sizeof(pidstr), "%d", handler->monitor_pid);
1079 if (len < 0 || (size_t)len >= sizeof(pidstr))
1080 return;
1081
1082 for (int i = 0; ops->hierarchies[i]; i++) {
1083 __do_free char *pivot_path = NULL;
1084 struct hierarchy *h = ops->hierarchies[i];
1085 size_t offset;
1086 int ret;
1087
1088 if (!h->monitor_full_path)
1089 continue;
1090
1091 /* Monitor might have died before we entered the cgroup. */
1092 if (handler->monitor_pid <= 0) {
1093 WARN("No valid monitor process found while destroying cgroups");
1094 goto try_lxc_rm_rf;
1095 }
1096
1097 if (conf && conf->cgroup_meta.monitor_dir)
1098 pivot_path = must_make_path(h->mountpoint, h->container_base_path,
1099 conf->cgroup_meta.monitor_dir, CGROUP_PIVOT, NULL);
1100 else if (conf && conf->cgroup_meta.dir)
1101 pivot_path = must_make_path(h->mountpoint, h->container_base_path,
1102 conf->cgroup_meta.dir, CGROUP_PIVOT, NULL);
1103 else
1104 pivot_path = must_make_path(h->mountpoint, h->container_base_path,
1105 CGROUP_PIVOT, NULL);
1106
1107 offset = strlen(h->mountpoint) + strlen(h->container_base_path);
1108
1109 if (cg_legacy_handle_cpuset_hierarchy(h, pivot_path + offset))
1110 SYSWARN("Failed to initialize cpuset %s/" CGROUP_PIVOT, pivot_path);
1111
1112 ret = mkdir_p(pivot_path, 0755);
1113 if (ret < 0 && errno != EEXIST) {
1114 ERROR("Failed to create %s", pivot_path);
1115 goto try_lxc_rm_rf;
1116 }
1117
1118 ret = lxc_write_openat(pivot_path, "cgroup.procs", pidstr, len);
1119 if (ret != 0) {
1120 SYSWARN("Failed to move monitor %s to \"%s\"", pidstr, pivot_path);
1121 continue;
1122 }
1123
1124 try_lxc_rm_rf:
1125 ret = lxc_rm_rf(h->monitor_full_path);
1126 if (ret < 0)
1127 WARN("Failed to destroy \"%s\"", h->monitor_full_path);
1128 }
1129 }
1130
1131 static int mkdir_eexist_on_last(const char *dir, mode_t mode)
1132 {
1133 const char *tmp = dir;
1134 const char *orig = dir;
1135 size_t orig_len;
1136
1137 orig_len = strlen(dir);
1138 do {
1139 __do_free char *makeme = NULL;
1140 int ret;
1141 size_t cur_len;
1142
1143 dir = tmp + strspn(tmp, "/");
1144 tmp = dir + strcspn(dir, "/");
1145
1146 cur_len = dir - orig;
1147 makeme = strndup(orig, cur_len);
1148 if (!makeme)
1149 return ret_set_errno(-1, ENOMEM);
1150
1151 ret = mkdir(makeme, mode);
1152 if (ret < 0 && ((errno != EEXIST) || (orig_len == cur_len)))
1153 return log_warn_errno(-1, errno, "Failed to create directory \"%s\"", makeme);
1154 } while (tmp != dir);
1155
1156 return 0;
1157 }
1158
1159 static bool cgroup_tree_create(struct cgroup_ops *ops, struct lxc_conf *conf,
1160 struct hierarchy *h, const char *cgroup_tree,
1161 const char *cgroup_leaf, bool payload,
1162 const char *cgroup_limit_dir)
1163 {
1164 __do_free char *path = NULL, *limit_path = NULL;
1165 int ret, ret_cpuset;
1166
1167 path = must_make_path(h->mountpoint, h->container_base_path, cgroup_leaf, NULL);
1168 if (dir_exists(path))
1169 return log_warn_errno(false, errno, "The %s cgroup already existed", path);
1170
1171 ret_cpuset = cg_legacy_handle_cpuset_hierarchy(h, cgroup_leaf);
1172 if (ret_cpuset < 0)
1173 return log_error_errno(false, errno, "Failed to handle legacy cpuset controller");
1174
1175 if (payload && cgroup_limit_dir) {
1176 /* with isolation both parts need to not already exist */
1177 limit_path = must_make_path(h->mountpoint,
1178 h->container_base_path,
1179 cgroup_limit_dir, NULL);
1180
1181 ret = mkdir_eexist_on_last(limit_path, 0755);
1182 if (ret < 0)
1183 return log_debug_errno(false,
1184 errno, "Failed to create %s limiting cgroup",
1185 limit_path);
1186
1187 h->cgfd_limit = lxc_open_dirfd(limit_path);
1188 if (h->cgfd_limit < 0)
1189 return log_error_errno(false, errno,
1190 "Failed to open %s", path);
1191 h->container_limit_path = move_ptr(limit_path);
1192
1193 /*
1194 * With isolation the devices legacy cgroup needs to be
1195 * iinitialized early, as it typically contains an 'a' (all)
1196 * line, which is not possible once a subdirectory has been
1197 * created.
1198 */
1199 if (string_in_list(h->controllers, "devices") &&
1200 !ops->setup_limits_legacy(ops, conf, true))
1201 return log_error(false, "Failed to setup legacy device limits");
1202 }
1203
1204 ret = mkdir_eexist_on_last(path, 0755);
1205 if (ret < 0) {
1206 /*
1207 * This is the cpuset controller and
1208 * cg_legacy_handle_cpuset_hierarchy() has created our target
1209 * directory for us to ensure correct initialization.
1210 */
1211 if (ret_cpuset != 1 || cgroup_tree)
1212 return log_debug_errno(false, errno, "Failed to create %s cgroup", path);
1213 }
1214
1215 if (payload) {
1216 h->cgfd_con = lxc_open_dirfd(path);
1217 if (h->cgfd_con < 0)
1218 return log_error_errno(false, errno, "Failed to open %s", path);
1219 h->container_full_path = move_ptr(path);
1220 if (h->cgfd_limit < 0)
1221 h->cgfd_limit = h->cgfd_con;
1222 if (!h->container_limit_path)
1223 h->container_limit_path = h->container_full_path;
1224 } else {
1225 h->cgfd_mon = lxc_open_dirfd(path);
1226 if (h->cgfd_mon < 0)
1227 return log_error_errno(false, errno, "Failed to open %s", path);
1228 h->monitor_full_path = move_ptr(path);
1229 }
1230
1231 return true;
1232 }
1233
1234 static void cgroup_tree_leaf_remove(struct hierarchy *h, bool payload)
1235 {
1236 __do_free char *full_path = NULL, *__limit_path = NULL;
1237 char *limit_path = NULL;
1238
1239 if (payload) {
1240 __lxc_unused __do_close int fd = move_fd(h->cgfd_con);
1241 full_path = move_ptr(h->container_full_path);
1242 limit_path = move_ptr(h->container_limit_path);
1243 if (limit_path != full_path)
1244 __limit_path = limit_path;
1245 } else {
1246 __lxc_unused __do_close int fd = move_fd(h->cgfd_mon);
1247 full_path = move_ptr(h->monitor_full_path);
1248 }
1249
1250 if (full_path && rmdir(full_path))
1251 SYSWARN("Failed to rmdir(\"%s\") cgroup", full_path);
1252 if (limit_path && rmdir(limit_path))
1253 SYSWARN("Failed to rmdir(\"%s\") cgroup", limit_path);
1254 }
1255
1256 /*
1257 * Check we have no lxc.cgroup.dir, and that lxc.cgroup.dir.limit_prefix is a
1258 * proper prefix directory of lxc.cgroup.dir.payload.
1259 *
1260 * Returns the prefix length if it is set, otherwise zero on success.
1261 */
1262 static bool check_cgroup_dir_config(struct lxc_conf *conf)
1263 {
1264 const char *monitor_dir = conf->cgroup_meta.monitor_dir,
1265 *container_dir = conf->cgroup_meta.container_dir,
1266 *namespace_dir = conf->cgroup_meta.namespace_dir;
1267
1268 /* none of the new options are set, all is fine */
1269 if (!monitor_dir && !container_dir && !namespace_dir)
1270 return true;
1271
1272 /* some are set, make sure lxc.cgroup.dir is not also set*/
1273 if (conf->cgroup_meta.dir)
1274 return log_error_errno(false, EINVAL,
1275 "lxc.cgroup.dir conflicts with lxc.cgroup.dir.payload/monitor");
1276
1277 /* make sure both monitor and payload are set */
1278 if (!monitor_dir || !container_dir)
1279 return log_error_errno(false, EINVAL,
1280 "lxc.cgroup.dir.payload and lxc.cgroup.dir.monitor must both be set");
1281
1282 /* namespace_dir may be empty */
1283 return true;
1284 }
1285
1286 __cgfsng_ops static inline bool cgfsng_monitor_create(struct cgroup_ops *ops,
1287 struct lxc_handler *handler)
1288 {
1289 __do_free char *monitor_cgroup = NULL, *__cgroup_tree = NULL;
1290 const char *cgroup_tree;
1291 int idx = 0;
1292 int i;
1293 size_t len;
1294 char *suffix = NULL;
1295 struct lxc_conf *conf;
1296
1297 if (!ops)
1298 return ret_set_errno(false, ENOENT);
1299
1300 if (!ops->hierarchies)
1301 return true;
1302
1303 if (ops->monitor_cgroup)
1304 return ret_set_errno(false, EEXIST);
1305
1306 if (!handler || !handler->conf)
1307 return ret_set_errno(false, EINVAL);
1308
1309 conf = handler->conf;
1310
1311 if (!check_cgroup_dir_config(conf))
1312 return false;
1313
1314 if (conf->cgroup_meta.monitor_dir) {
1315 cgroup_tree = NULL;
1316 monitor_cgroup = strdup(conf->cgroup_meta.monitor_dir);
1317 } else if (conf->cgroup_meta.dir) {
1318 cgroup_tree = conf->cgroup_meta.dir;
1319 monitor_cgroup = must_concat(&len, conf->cgroup_meta.dir, "/",
1320 DEFAULT_MONITOR_CGROUP_PREFIX,
1321 handler->name,
1322 CGROUP_CREATE_RETRY, NULL);
1323 } else if (ops->cgroup_pattern) {
1324 __cgroup_tree = lxc_string_replace("%n", handler->name, ops->cgroup_pattern);
1325 if (!__cgroup_tree)
1326 return ret_set_errno(false, ENOMEM);
1327
1328 cgroup_tree = __cgroup_tree;
1329 monitor_cgroup = must_concat(&len, cgroup_tree, "/",
1330 DEFAULT_MONITOR_CGROUP,
1331 CGROUP_CREATE_RETRY, NULL);
1332 } else {
1333 cgroup_tree = NULL;
1334 monitor_cgroup = must_concat(&len, DEFAULT_MONITOR_CGROUP_PREFIX,
1335 handler->name,
1336 CGROUP_CREATE_RETRY, NULL);
1337 }
1338 if (!monitor_cgroup)
1339 return ret_set_errno(false, ENOMEM);
1340
1341 if (!conf->cgroup_meta.monitor_dir) {
1342 suffix = monitor_cgroup + len - CGROUP_CREATE_RETRY_LEN;
1343 *suffix = '\0';
1344 }
1345 do {
1346 if (idx && suffix)
1347 sprintf(suffix, "-%d", idx);
1348
1349 for (i = 0; ops->hierarchies[i]; i++) {
1350 if (cgroup_tree_create(ops, handler->conf,
1351 ops->hierarchies[i], cgroup_tree,
1352 monitor_cgroup, false, NULL))
1353 continue;
1354
1355 DEBUG("Failed to create cgroup \"%s\"", ops->hierarchies[i]->monitor_full_path ?: "(null)");
1356 for (int j = 0; j < i; j++)
1357 cgroup_tree_leaf_remove(ops->hierarchies[j], false);
1358
1359 idx++;
1360 break;
1361 }
1362 } while (ops->hierarchies[i] && idx > 0 && idx < 1000 && suffix);
1363
1364 if (idx == 1000 || (!suffix && idx != 0))
1365 return log_error_errno(false, ERANGE, "Failed to create monitor cgroup");
1366
1367 ops->monitor_cgroup = move_ptr(monitor_cgroup);
1368 return log_info(true, "The monitor process uses \"%s\" as cgroup", ops->monitor_cgroup);
1369 }
1370
1371 /*
1372 * Try to create the same cgroup in all hierarchies. Start with cgroup_pattern;
1373 * next cgroup_pattern-1, -2, ..., -999.
1374 */
1375 __cgfsng_ops static inline bool cgfsng_payload_create(struct cgroup_ops *ops,
1376 struct lxc_handler *handler)
1377 {
1378 __do_free char *container_cgroup = NULL,
1379 *__cgroup_tree = NULL,
1380 *limiting_cgroup = NULL;
1381 const char *cgroup_tree;
1382 int idx = 0;
1383 int i;
1384 size_t len;
1385 char *suffix = NULL;
1386 struct lxc_conf *conf;
1387
1388 if (!ops)
1389 return ret_set_errno(false, ENOENT);
1390
1391 if (!ops->hierarchies)
1392 return true;
1393
1394 if (ops->container_cgroup)
1395 return ret_set_errno(false, EEXIST);
1396
1397 if (!handler || !handler->conf)
1398 return ret_set_errno(false, EINVAL);
1399
1400 conf = handler->conf;
1401
1402 if (!check_cgroup_dir_config(conf))
1403 return false;
1404
1405 if (conf->cgroup_meta.container_dir) {
1406 cgroup_tree = NULL;
1407
1408 limiting_cgroup = strdup(conf->cgroup_meta.container_dir);
1409 if (!limiting_cgroup)
1410 return ret_set_errno(false, ENOMEM);
1411
1412 if (conf->cgroup_meta.namespace_dir) {
1413 container_cgroup = must_make_path(limiting_cgroup,
1414 conf->cgroup_meta.namespace_dir,
1415 NULL);
1416 } else {
1417 /* explicit paths but without isolation */
1418 container_cgroup = move_ptr(limiting_cgroup);
1419 }
1420 } else if (conf->cgroup_meta.dir) {
1421 cgroup_tree = conf->cgroup_meta.dir;
1422 container_cgroup = must_concat(&len, cgroup_tree, "/",
1423 DEFAULT_PAYLOAD_CGROUP_PREFIX,
1424 handler->name,
1425 CGROUP_CREATE_RETRY, NULL);
1426 } else if (ops->cgroup_pattern) {
1427 __cgroup_tree = lxc_string_replace("%n", handler->name, ops->cgroup_pattern);
1428 if (!__cgroup_tree)
1429 return ret_set_errno(false, ENOMEM);
1430
1431 cgroup_tree = __cgroup_tree;
1432 container_cgroup = must_concat(&len, cgroup_tree, "/",
1433 DEFAULT_PAYLOAD_CGROUP,
1434 CGROUP_CREATE_RETRY, NULL);
1435 } else {
1436 cgroup_tree = NULL;
1437 container_cgroup = must_concat(&len, DEFAULT_PAYLOAD_CGROUP_PREFIX,
1438 handler->name,
1439 CGROUP_CREATE_RETRY, NULL);
1440 }
1441 if (!container_cgroup)
1442 return ret_set_errno(false, ENOMEM);
1443
1444 if (!conf->cgroup_meta.container_dir) {
1445 suffix = container_cgroup + len - CGROUP_CREATE_RETRY_LEN;
1446 *suffix = '\0';
1447 }
1448 do {
1449 if (idx && suffix)
1450 sprintf(suffix, "-%d", idx);
1451
1452 for (i = 0; ops->hierarchies[i]; i++) {
1453 if (cgroup_tree_create(ops, handler->conf,
1454 ops->hierarchies[i], cgroup_tree,
1455 container_cgroup, true,
1456 limiting_cgroup))
1457 continue;
1458
1459 DEBUG("Failed to create cgroup \"%s\"", ops->hierarchies[i]->container_full_path ?: "(null)");
1460 for (int j = 0; j < i; j++)
1461 cgroup_tree_leaf_remove(ops->hierarchies[j], true);
1462
1463 idx++;
1464 break;
1465 }
1466 } while (ops->hierarchies[i] && idx > 0 && idx < 1000 && suffix);
1467
1468 if (idx == 1000 || (!suffix && idx != 0))
1469 return log_error_errno(false, ERANGE, "Failed to create container cgroup");
1470
1471 ops->container_cgroup = move_ptr(container_cgroup);
1472 INFO("The container process uses \"%s\" as cgroup", ops->container_cgroup);
1473 return true;
1474 }
1475
1476 __cgfsng_ops static bool cgfsng_monitor_enter(struct cgroup_ops *ops,
1477 struct lxc_handler *handler)
1478 {
1479 int monitor_len, transient_len = 0;
1480 char monitor[INTTYPE_TO_STRLEN(pid_t)],
1481 transient[INTTYPE_TO_STRLEN(pid_t)];
1482
1483 if (!ops)
1484 return ret_set_errno(false, ENOENT);
1485
1486 if (!ops->hierarchies)
1487 return true;
1488
1489 if (!ops->monitor_cgroup)
1490 return ret_set_errno(false, ENOENT);
1491
1492 if (!handler || !handler->conf)
1493 return ret_set_errno(false, EINVAL);
1494
1495 monitor_len = snprintf(monitor, sizeof(monitor), "%d", handler->monitor_pid);
1496 if (handler->transient_pid > 0)
1497 transient_len = snprintf(transient, sizeof(transient), "%d", handler->transient_pid);
1498
1499 for (int i = 0; ops->hierarchies[i]; i++) {
1500 struct hierarchy *h = ops->hierarchies[i];
1501 int ret;
1502
1503 ret = lxc_writeat(h->cgfd_mon, "cgroup.procs", monitor, monitor_len);
1504 if (ret)
1505 return log_error_errno(false, errno, "Failed to enter cgroup \"%s\"", h->monitor_full_path);
1506
1507 if (handler->transient_pid <= 0)
1508 return true;
1509
1510 ret = lxc_writeat(h->cgfd_mon, "cgroup.procs", transient, transient_len);
1511 if (ret)
1512 return log_error_errno(false, errno, "Failed to enter cgroup \"%s\"", h->monitor_full_path);
1513
1514 /*
1515 * we don't keep the fds for non-unified hierarchies around
1516 * mainly because we don't make use of them anymore after the
1517 * core cgroup setup is done but also because there are quite a
1518 * lot of them.
1519 */
1520 if (!is_unified_hierarchy(h))
1521 close_prot_errno_disarm(h->cgfd_mon);
1522 }
1523 handler->transient_pid = -1;
1524
1525 return true;
1526 }
1527
1528 __cgfsng_ops static bool cgfsng_payload_enter(struct cgroup_ops *ops,
1529 struct lxc_handler *handler)
1530 {
1531 int len;
1532 char pidstr[INTTYPE_TO_STRLEN(pid_t)];
1533
1534 if (!ops)
1535 return ret_set_errno(false, ENOENT);
1536
1537 if (!ops->hierarchies)
1538 return true;
1539
1540 if (!ops->container_cgroup)
1541 return ret_set_errno(false, ENOENT);
1542
1543 if (!handler || !handler->conf)
1544 return ret_set_errno(false, EINVAL);
1545
1546 len = snprintf(pidstr, sizeof(pidstr), "%d", handler->pid);
1547
1548 for (int i = 0; ops->hierarchies[i]; i++) {
1549 struct hierarchy *h = ops->hierarchies[i];
1550 int ret;
1551
1552 if (is_unified_hierarchy(h) && handler->clone_flags & CLONE_INTO_CGROUP)
1553 continue;
1554
1555 ret = lxc_writeat(h->cgfd_con, "cgroup.procs", pidstr, len);
1556 if (ret != 0)
1557 return log_error_errno(false, errno, "Failed to enter cgroup \"%s\"", h->container_full_path);
1558 }
1559
1560 return true;
1561 }
1562
1563 static int fchowmodat(int dirfd, const char *path, uid_t chown_uid,
1564 gid_t chown_gid, mode_t chmod_mode)
1565 {
1566 int ret;
1567
1568 ret = fchownat(dirfd, path, chown_uid, chown_gid,
1569 AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW);
1570 if (ret < 0)
1571 return log_warn_errno(-1,
1572 errno, "Failed to fchownat(%d, %s, %d, %d, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW )",
1573 dirfd, path, (int)chown_uid,
1574 (int)chown_gid);
1575
1576 ret = fchmodat(dirfd, (*path != '\0') ? path : ".", chmod_mode, 0);
1577 if (ret < 0)
1578 return log_warn_errno(-1, errno, "Failed to fchmodat(%d, %s, %d, AT_SYMLINK_NOFOLLOW)",
1579 dirfd, path, (int)chmod_mode);
1580
1581 return 0;
1582 }
1583
1584 /* chgrp the container cgroups to container group. We leave
1585 * the container owner as cgroup owner. So we must make the
1586 * directories 775 so that the container can create sub-cgroups.
1587 *
1588 * Also chown the tasks and cgroup.procs files. Those may not
1589 * exist depending on kernel version.
1590 */
1591 static int chown_cgroup_wrapper(void *data)
1592 {
1593 int ret;
1594 uid_t destuid;
1595 struct generic_userns_exec_data *arg = data;
1596 uid_t nsuid = (arg->conf->root_nsuid_map != NULL) ? 0 : arg->conf->init_uid;
1597 gid_t nsgid = (arg->conf->root_nsgid_map != NULL) ? 0 : arg->conf->init_gid;
1598
1599 if (!lxc_setgroups(0, NULL) && errno != EPERM)
1600 return log_error_errno(-1, errno, "Failed to setgroups(0, NULL)");
1601
1602 ret = setresgid(nsgid, nsgid, nsgid);
1603 if (ret < 0)
1604 return log_error_errno(-1, errno, "Failed to setresgid(%d, %d, %d)",
1605 (int)nsgid, (int)nsgid, (int)nsgid);
1606
1607 ret = setresuid(nsuid, nsuid, nsuid);
1608 if (ret < 0)
1609 return log_error_errno(-1, errno, "Failed to setresuid(%d, %d, %d)",
1610 (int)nsuid, (int)nsuid, (int)nsuid);
1611
1612 destuid = get_ns_uid(arg->origuid);
1613 if (destuid == LXC_INVALID_UID)
1614 destuid = 0;
1615
1616 for (int i = 0; arg->hierarchies[i]; i++) {
1617 int dirfd = arg->hierarchies[i]->cgfd_con;
1618
1619 (void)fchowmodat(dirfd, "", destuid, nsgid, 0775);
1620
1621 /*
1622 * Failures to chown() these are inconvenient but not
1623 * detrimental We leave these owned by the container launcher,
1624 * so that container root can write to the files to attach. We
1625 * chmod() them 664 so that container systemd can write to the
1626 * files (which systemd in wily insists on doing).
1627 */
1628
1629 if (arg->hierarchies[i]->version == CGROUP_SUPER_MAGIC)
1630 (void)fchowmodat(dirfd, "tasks", destuid, nsgid, 0664);
1631
1632 (void)fchowmodat(dirfd, "cgroup.procs", destuid, nsgid, 0664);
1633
1634 if (arg->hierarchies[i]->version != CGROUP2_SUPER_MAGIC)
1635 continue;
1636
1637 for (char **p = arg->hierarchies[i]->cgroup2_chown; p && *p; p++)
1638 (void)fchowmodat(dirfd, *p, destuid, nsgid, 0664);
1639 }
1640
1641 return 0;
1642 }
1643
1644 __cgfsng_ops static bool cgfsng_chown(struct cgroup_ops *ops,
1645 struct lxc_conf *conf)
1646 {
1647 struct generic_userns_exec_data wrap;
1648
1649 if (!ops)
1650 return ret_set_errno(false, ENOENT);
1651
1652 if (!ops->hierarchies)
1653 return true;
1654
1655 if (!ops->container_cgroup)
1656 return ret_set_errno(false, ENOENT);
1657
1658 if (!conf)
1659 return ret_set_errno(false, EINVAL);
1660
1661 if (lxc_list_empty(&conf->id_map))
1662 return true;
1663
1664 wrap.origuid = geteuid();
1665 wrap.path = NULL;
1666 wrap.hierarchies = ops->hierarchies;
1667 wrap.conf = conf;
1668
1669 if (userns_exec_1(conf, chown_cgroup_wrapper, &wrap, "chown_cgroup_wrapper") < 0)
1670 return log_error_errno(false, errno, "Error requesting cgroup chown in new user namespace");
1671
1672 return true;
1673 }
1674
1675 __cgfsng_ops void cgfsng_payload_finalize(struct cgroup_ops *ops)
1676 {
1677 if (!ops)
1678 return;
1679
1680 if (!ops->hierarchies)
1681 return;
1682
1683 for (int i = 0; ops->hierarchies[i]; i++) {
1684 struct hierarchy *h = ops->hierarchies[i];
1685 /*
1686 * we don't keep the fds for non-unified hierarchies around
1687 * mainly because we don't make use of them anymore after the
1688 * core cgroup setup is done but also because there are quite a
1689 * lot of them.
1690 */
1691 if (!is_unified_hierarchy(h))
1692 close_prot_errno_disarm(h->cgfd_con);
1693 }
1694 }
1695
1696 /* cgroup-full:* is done, no need to create subdirs */
1697 static inline bool cg_mount_needs_subdirs(int type)
1698 {
1699 return !(type >= LXC_AUTO_CGROUP_FULL_RO);
1700 }
1701
1702 /* After $rootfs/sys/fs/container/controller/the/cg/path has been created,
1703 * remount controller ro if needed and bindmount the cgroupfs onto
1704 * control/the/cg/path.
1705 */
1706 static int cg_legacy_mount_controllers(int type, struct hierarchy *h,
1707 char *controllerpath, char *cgpath,
1708 const char *container_cgroup)
1709 {
1710 __do_free char *sourcepath = NULL;
1711 int ret, remount_flags;
1712 int flags = MS_BIND;
1713
1714 if (type == LXC_AUTO_CGROUP_RO || type == LXC_AUTO_CGROUP_MIXED) {
1715 ret = mount(controllerpath, controllerpath, "cgroup", MS_BIND, NULL);
1716 if (ret < 0)
1717 return log_error_errno(-1, errno, "Failed to bind mount \"%s\" onto \"%s\"",
1718 controllerpath, controllerpath);
1719
1720 remount_flags = add_required_remount_flags(controllerpath,
1721 controllerpath,
1722 flags | MS_REMOUNT);
1723 ret = mount(controllerpath, controllerpath, "cgroup",
1724 remount_flags | MS_REMOUNT | MS_BIND | MS_RDONLY,
1725 NULL);
1726 if (ret < 0)
1727 return log_error_errno(-1, errno, "Failed to remount \"%s\" ro", controllerpath);
1728
1729 INFO("Remounted %s read-only", controllerpath);
1730 }
1731
1732 sourcepath = must_make_path(h->mountpoint, h->container_base_path,
1733 container_cgroup, NULL);
1734 if (type == LXC_AUTO_CGROUP_RO)
1735 flags |= MS_RDONLY;
1736
1737 ret = mount(sourcepath, cgpath, "cgroup", flags, NULL);
1738 if (ret < 0)
1739 return log_error_errno(-1, errno, "Failed to mount \"%s\" onto \"%s\"",
1740 h->controllers[0], cgpath);
1741 INFO("Mounted \"%s\" onto \"%s\"", h->controllers[0], cgpath);
1742
1743 if (flags & MS_RDONLY) {
1744 remount_flags = add_required_remount_flags(sourcepath, cgpath,
1745 flags | MS_REMOUNT);
1746 ret = mount(sourcepath, cgpath, "cgroup", remount_flags, NULL);
1747 if (ret < 0)
1748 return log_error_errno(-1, errno, "Failed to remount \"%s\" ro", cgpath);
1749 INFO("Remounted %s read-only", cgpath);
1750 }
1751
1752 INFO("Completed second stage cgroup automounts for \"%s\"", cgpath);
1753 return 0;
1754 }
1755
1756 /* __cg_mount_direct
1757 *
1758 * Mount cgroup hierarchies directly without using bind-mounts. The main
1759 * uses-cases are mounting cgroup hierarchies in cgroup namespaces and mounting
1760 * cgroups for the LXC_AUTO_CGROUP_FULL option.
1761 */
1762 static int __cg_mount_direct(int type, struct hierarchy *h,
1763 const char *controllerpath)
1764 {
1765 __do_free char *controllers = NULL;
1766 char *fstype = "cgroup2";
1767 unsigned long flags = 0;
1768 int ret;
1769
1770 flags |= MS_NOSUID;
1771 flags |= MS_NOEXEC;
1772 flags |= MS_NODEV;
1773 flags |= MS_RELATIME;
1774
1775 if (type == LXC_AUTO_CGROUP_RO || type == LXC_AUTO_CGROUP_FULL_RO)
1776 flags |= MS_RDONLY;
1777
1778 if (h->version != CGROUP2_SUPER_MAGIC) {
1779 controllers = lxc_string_join(",", (const char **)h->controllers, false);
1780 if (!controllers)
1781 return -ENOMEM;
1782 fstype = "cgroup";
1783 }
1784
1785 ret = mount("cgroup", controllerpath, fstype, flags, controllers);
1786 if (ret < 0)
1787 return log_error_errno(-1, errno, "Failed to mount \"%s\" with cgroup filesystem type %s",
1788 controllerpath, fstype);
1789
1790 DEBUG("Mounted \"%s\" with cgroup filesystem type %s", controllerpath, fstype);
1791 return 0;
1792 }
1793
1794 static inline int cg_mount_in_cgroup_namespace(int type, struct hierarchy *h,
1795 const char *controllerpath)
1796 {
1797 return __cg_mount_direct(type, h, controllerpath);
1798 }
1799
1800 static inline int cg_mount_cgroup_full(int type, struct hierarchy *h,
1801 const char *controllerpath)
1802 {
1803 if (type < LXC_AUTO_CGROUP_FULL_RO || type > LXC_AUTO_CGROUP_FULL_MIXED)
1804 return 0;
1805
1806 return __cg_mount_direct(type, h, controllerpath);
1807 }
1808
1809 __cgfsng_ops static bool cgfsng_mount(struct cgroup_ops *ops,
1810 struct lxc_handler *handler,
1811 const char *root, int type)
1812 {
1813 __do_free char *cgroup_root = NULL;
1814 bool has_cgns = false, wants_force_mount = false;
1815 int ret;
1816
1817 if (!ops)
1818 return ret_set_errno(false, ENOENT);
1819
1820 if (!ops->hierarchies)
1821 return true;
1822
1823 if (!handler || !handler->conf)
1824 return ret_set_errno(false, EINVAL);
1825
1826 if ((type & LXC_AUTO_CGROUP_MASK) == 0)
1827 return true;
1828
1829 if (type & LXC_AUTO_CGROUP_FORCE) {
1830 type &= ~LXC_AUTO_CGROUP_FORCE;
1831 wants_force_mount = true;
1832 }
1833
1834 if (!wants_force_mount) {
1835 if (!lxc_list_empty(&handler->conf->keepcaps))
1836 wants_force_mount = !in_caplist(CAP_SYS_ADMIN, &handler->conf->keepcaps);
1837 else
1838 wants_force_mount = in_caplist(CAP_SYS_ADMIN, &handler->conf->caps);
1839
1840 /*
1841 * Most recent distro versions currently have init system that
1842 * do support cgroup2 but do not mount it by default unless
1843 * explicitly told so even if the host is cgroup2 only. That
1844 * means they often will fail to boot. Fix this by pre-mounting
1845 * cgroup2 by default. We will likely need to be doing this a
1846 * few years until all distros have switched over to cgroup2 at
1847 * which point we can safely assume that their init systems
1848 * will mount it themselves.
1849 */
1850 if (pure_unified_layout(ops))
1851 wants_force_mount = true;
1852 }
1853
1854 has_cgns = cgns_supported();
1855 if (has_cgns && !wants_force_mount)
1856 return true;
1857
1858 if (type == LXC_AUTO_CGROUP_NOSPEC)
1859 type = LXC_AUTO_CGROUP_MIXED;
1860 else if (type == LXC_AUTO_CGROUP_FULL_NOSPEC)
1861 type = LXC_AUTO_CGROUP_FULL_MIXED;
1862
1863 cgroup_root = must_make_path(root, DEFAULT_CGROUP_MOUNTPOINT, NULL);
1864 if (ops->cgroup_layout == CGROUP_LAYOUT_UNIFIED) {
1865 if (has_cgns && wants_force_mount) {
1866 /*
1867 * If cgroup namespaces are supported but the container
1868 * will not have CAP_SYS_ADMIN after it has started we
1869 * need to mount the cgroups manually.
1870 */
1871 return cg_mount_in_cgroup_namespace(type, ops->unified, cgroup_root) == 0;
1872 }
1873
1874 return cg_mount_cgroup_full(type, ops->unified, cgroup_root) == 0;
1875 }
1876
1877 /* mount tmpfs */
1878 ret = safe_mount(NULL, cgroup_root, "tmpfs",
1879 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_RELATIME,
1880 "size=10240k,mode=755", root);
1881 if (ret < 0)
1882 return false;
1883
1884 for (int i = 0; ops->hierarchies[i]; i++) {
1885 __do_free char *controllerpath = NULL, *path2 = NULL;
1886 struct hierarchy *h = ops->hierarchies[i];
1887 char *controller = strrchr(h->mountpoint, '/');
1888
1889 if (!controller)
1890 continue;
1891 controller++;
1892
1893 controllerpath = must_make_path(cgroup_root, controller, NULL);
1894 if (dir_exists(controllerpath))
1895 continue;
1896
1897 ret = mkdir(controllerpath, 0755);
1898 if (ret < 0)
1899 return log_error_errno(false, errno, "Error creating cgroup path: %s", controllerpath);
1900
1901 if (has_cgns && wants_force_mount) {
1902 /* If cgroup namespaces are supported but the container
1903 * will not have CAP_SYS_ADMIN after it has started we
1904 * need to mount the cgroups manually.
1905 */
1906 ret = cg_mount_in_cgroup_namespace(type, h, controllerpath);
1907 if (ret < 0)
1908 return false;
1909
1910 continue;
1911 }
1912
1913 ret = cg_mount_cgroup_full(type, h, controllerpath);
1914 if (ret < 0)
1915 return false;
1916
1917 if (!cg_mount_needs_subdirs(type))
1918 continue;
1919
1920 path2 = must_make_path(controllerpath, h->container_base_path,
1921 ops->container_cgroup, NULL);
1922 ret = mkdir_p(path2, 0755);
1923 if (ret < 0)
1924 return false;
1925
1926 ret = cg_legacy_mount_controllers(type, h, controllerpath,
1927 path2, ops->container_cgroup);
1928 if (ret < 0)
1929 return false;
1930 }
1931
1932 return true;
1933 }
1934
1935 /* Only root needs to escape to the cgroup of its init. */
1936 __cgfsng_ops static bool cgfsng_escape(const struct cgroup_ops *ops,
1937 struct lxc_conf *conf)
1938 {
1939 if (!ops)
1940 return ret_set_errno(false, ENOENT);
1941
1942 if (!ops->hierarchies)
1943 return true;
1944
1945 if (!conf)
1946 return ret_set_errno(false, EINVAL);
1947
1948 if (conf->cgroup_meta.relative || geteuid())
1949 return true;
1950
1951 for (int i = 0; ops->hierarchies[i]; i++) {
1952 __do_free char *fullpath = NULL;
1953 int ret;
1954
1955 fullpath =
1956 must_make_path(ops->hierarchies[i]->mountpoint,
1957 ops->hierarchies[i]->container_base_path,
1958 "cgroup.procs", NULL);
1959 ret = lxc_write_to_file(fullpath, "0", 2, false, 0666);
1960 if (ret != 0)
1961 return log_error_errno(false, errno, "Failed to escape to cgroup \"%s\"", fullpath);
1962 }
1963
1964 return true;
1965 }
1966
1967 __cgfsng_ops static int cgfsng_num_hierarchies(struct cgroup_ops *ops)
1968 {
1969 int i = 0;
1970
1971 if (!ops)
1972 return ret_set_errno(-1, ENOENT);
1973
1974 if (!ops->hierarchies)
1975 return 0;
1976
1977 for (; ops->hierarchies[i]; i++)
1978 ;
1979
1980 return i;
1981 }
1982
1983 __cgfsng_ops static bool cgfsng_get_hierarchies(struct cgroup_ops *ops, int n,
1984 char ***out)
1985 {
1986 int i;
1987
1988 if (!ops)
1989 return ret_set_errno(false, ENOENT);
1990
1991 if (!ops->hierarchies)
1992 return ret_set_errno(false, ENOENT);
1993
1994 /* sanity check n */
1995 for (i = 0; i < n; i++)
1996 if (!ops->hierarchies[i])
1997 return ret_set_errno(false, ENOENT);
1998
1999 *out = ops->hierarchies[i]->controllers;
2000
2001 return true;
2002 }
2003
2004 static bool cg_legacy_freeze(struct cgroup_ops *ops)
2005 {
2006 struct hierarchy *h;
2007
2008 h = get_hierarchy(ops, "freezer");
2009 if (!h)
2010 return ret_set_errno(-1, ENOENT);
2011
2012 return lxc_write_openat(h->container_full_path, "freezer.state",
2013 "FROZEN", STRLITERALLEN("FROZEN"));
2014 }
2015
2016 static int freezer_cgroup_events_cb(int fd, uint32_t events, void *cbdata,
2017 struct lxc_epoll_descr *descr)
2018 {
2019 __do_close int duped_fd = -EBADF;
2020 __do_free char *line = NULL;
2021 __do_fclose FILE *f = NULL;
2022 int state = PTR_TO_INT(cbdata);
2023 size_t len;
2024 const char *state_string;
2025
2026 duped_fd = dup(fd);
2027 if (duped_fd < 0)
2028 return LXC_MAINLOOP_ERROR;
2029
2030 if (lseek(duped_fd, 0, SEEK_SET) < (off_t)-1)
2031 return LXC_MAINLOOP_ERROR;
2032
2033 f = fdopen(duped_fd, "re");
2034 if (!f)
2035 return LXC_MAINLOOP_ERROR;
2036 move_fd(duped_fd);
2037
2038 if (state == 1)
2039 state_string = "frozen 1";
2040 else
2041 state_string = "frozen 0";
2042
2043 while (getline(&line, &len, f) != -1)
2044 if (strncmp(line, state_string, STRLITERALLEN("frozen") + 2) == 0)
2045 return LXC_MAINLOOP_CLOSE;
2046
2047 return LXC_MAINLOOP_CONTINUE;
2048 }
2049
2050 static int cg_unified_freeze_do(struct cgroup_ops *ops, int timeout,
2051 const char *state_string,
2052 int state_num,
2053 const char *epoll_error,
2054 const char *wait_error)
2055 {
2056 __do_close int fd = -EBADF;
2057 call_cleaner(lxc_mainloop_close) struct lxc_epoll_descr *descr_ptr = NULL;
2058 int ret;
2059 struct lxc_epoll_descr descr;
2060 struct hierarchy *h;
2061
2062 h = ops->unified;
2063 if (!h)
2064 return ret_set_errno(-1, ENOENT);
2065
2066 if (!h->container_full_path)
2067 return ret_set_errno(-1, EEXIST);
2068
2069 if (timeout != 0) {
2070 __do_free char *events_file = NULL;
2071
2072 events_file = must_make_path(h->container_full_path, "cgroup.events", NULL);
2073 fd = open(events_file, O_RDONLY | O_CLOEXEC);
2074 if (fd < 0)
2075 return log_error_errno(-1, errno, "Failed to open cgroup.events file");
2076
2077 ret = lxc_mainloop_open(&descr);
2078 if (ret)
2079 return log_error_errno(-1, errno, "%s", epoll_error);
2080
2081 /* automatically cleaned up now */
2082 descr_ptr = &descr;
2083
2084 ret = lxc_mainloop_add_handler_events(&descr, fd, EPOLLPRI, freezer_cgroup_events_cb, INT_TO_PTR(state_num));
2085 if (ret < 0)
2086 return log_error_errno(-1, errno, "Failed to add cgroup.events fd handler to mainloop");
2087 }
2088
2089 ret = lxc_write_openat(h->container_full_path, "cgroup.freeze", state_string, 1);
2090 if (ret < 0)
2091 return log_error_errno(-1, errno, "Failed to open cgroup.freeze file");
2092
2093 if (timeout != 0 && lxc_mainloop(&descr, timeout))
2094 return log_error_errno(-1, errno, "%s", wait_error);
2095
2096 return 0;
2097 }
2098
2099 static int cg_unified_freeze(struct cgroup_ops *ops, int timeout)
2100 {
2101 return cg_unified_freeze_do(ops, timeout, "1", 1,
2102 "Failed to create epoll instance to wait for container freeze",
2103 "Failed to wait for container to be frozen");
2104 }
2105
2106 __cgfsng_ops static int cgfsng_freeze(struct cgroup_ops *ops, int timeout)
2107 {
2108 if (!ops->hierarchies)
2109 return ret_set_errno(-1, ENOENT);
2110
2111 if (ops->cgroup_layout != CGROUP_LAYOUT_UNIFIED)
2112 return cg_legacy_freeze(ops);
2113
2114 return cg_unified_freeze(ops, timeout);
2115 }
2116
2117 static int cg_legacy_unfreeze(struct cgroup_ops *ops)
2118 {
2119 struct hierarchy *h;
2120
2121 h = get_hierarchy(ops, "freezer");
2122 if (!h)
2123 return ret_set_errno(-1, ENOENT);
2124
2125 return lxc_write_openat(h->container_full_path, "freezer.state",
2126 "THAWED", STRLITERALLEN("THAWED"));
2127 }
2128
2129 static int cg_unified_unfreeze(struct cgroup_ops *ops, int timeout)
2130 {
2131 return cg_unified_freeze_do(ops, timeout, "0", 0,
2132 "Failed to create epoll instance to wait for container unfreeze",
2133 "Failed to wait for container to be unfrozen");
2134 }
2135
2136 __cgfsng_ops static int cgfsng_unfreeze(struct cgroup_ops *ops, int timeout)
2137 {
2138 if (!ops->hierarchies)
2139 return ret_set_errno(-1, ENOENT);
2140
2141 if (ops->cgroup_layout != CGROUP_LAYOUT_UNIFIED)
2142 return cg_legacy_unfreeze(ops);
2143
2144 return cg_unified_unfreeze(ops, timeout);
2145 }
2146
2147 static const char *cgfsng_get_cgroup_do(struct cgroup_ops *ops,
2148 const char *controller, bool limiting)
2149 {
2150 struct hierarchy *h;
2151
2152 h = get_hierarchy(ops, controller);
2153 if (!h)
2154 return log_warn_errno(NULL, ENOENT, "Failed to find hierarchy for controller \"%s\"",
2155 controller ? controller : "(null)");
2156
2157 if (limiting)
2158 return h->container_limit_path
2159 ? h->container_limit_path + strlen(h->mountpoint)
2160 : NULL;
2161
2162 return h->container_full_path
2163 ? h->container_full_path + strlen(h->mountpoint)
2164 : NULL;
2165 }
2166
2167 __cgfsng_ops static const char *cgfsng_get_cgroup(struct cgroup_ops *ops,
2168 const char *controller)
2169 {
2170 return cgfsng_get_cgroup_do(ops, controller, false);
2171 }
2172
2173 __cgfsng_ops static const char *cgfsng_get_limiting_cgroup(struct cgroup_ops *ops,
2174 const char *controller)
2175 {
2176 return cgfsng_get_cgroup_do(ops, controller, true);
2177 }
2178
2179 /* Given a cgroup path returned from lxc_cmd_get_cgroup_path, build a full path,
2180 * which must be freed by the caller.
2181 */
2182 static inline char *build_full_cgpath_from_monitorpath(struct hierarchy *h,
2183 const char *inpath,
2184 const char *filename)
2185 {
2186 return must_make_path(h->mountpoint, inpath, filename, NULL);
2187 }
2188
2189 static int cgroup_attach_leaf(const struct lxc_conf *conf, int unified_fd, pid_t pid)
2190 {
2191 int idx = 1;
2192 int ret;
2193 char pidstr[INTTYPE_TO_STRLEN(int64_t) + 1];
2194 size_t pidstr_len;
2195
2196 /* Create leaf cgroup. */
2197 ret = mkdirat(unified_fd, ".lxc", 0755);
2198 if (ret < 0 && errno != EEXIST)
2199 return log_error_errno(-1, errno, "Failed to create leaf cgroup \".lxc\"");
2200
2201 pidstr_len = sprintf(pidstr, INT64_FMT, (int64_t)pid);
2202 ret = lxc_writeat(unified_fd, ".lxc/cgroup.procs", pidstr, pidstr_len);
2203 if (ret < 0)
2204 ret = lxc_writeat(unified_fd, "cgroup.procs", pidstr, pidstr_len);
2205 if (ret == 0)
2206 return 0;
2207
2208 /* this is a non-leaf node */
2209 if (errno != EBUSY)
2210 return log_error_errno(-1, errno, "Failed to attach to unified cgroup");
2211
2212 do {
2213 bool rm = false;
2214 char attach_cgroup[STRLITERALLEN(".lxc-1000/cgroup.procs") + 1];
2215 char *slash;
2216
2217 ret = snprintf(attach_cgroup, sizeof(attach_cgroup), ".lxc-%d/cgroup.procs", idx);
2218 if (ret < 0 || (size_t)ret >= sizeof(attach_cgroup))
2219 return ret_errno(EIO);
2220
2221 slash = &attach_cgroup[ret] - STRLITERALLEN("/cgroup.procs");
2222 *slash = '\0';
2223
2224 ret = mkdirat(unified_fd, attach_cgroup, 0755);
2225 if (ret < 0 && errno != EEXIST)
2226 return log_error_errno(-1, errno, "Failed to create cgroup %s", attach_cgroup);
2227 if (ret == 0)
2228 rm = true;
2229
2230 *slash = '/';
2231
2232 ret = lxc_writeat(unified_fd, attach_cgroup, pidstr, pidstr_len);
2233 if (ret == 0)
2234 return 0;
2235
2236 if (rm && unlinkat(unified_fd, attach_cgroup, AT_REMOVEDIR))
2237 SYSERROR("Failed to remove cgroup \"%d(%s)\"", unified_fd, attach_cgroup);
2238
2239 /* this is a non-leaf node */
2240 if (errno != EBUSY)
2241 return log_error_errno(-1, errno, "Failed to attach to unified cgroup");
2242
2243 idx++;
2244 } while (idx < 1000);
2245
2246 return log_error_errno(-1, errno, "Failed to attach to unified cgroup");
2247 }
2248
2249 static int cgroup_attach_create_leaf(const struct lxc_conf *conf,
2250 int unified_fd, int *sk_fd)
2251 {
2252 __do_close int sk = *sk_fd, target_fd0 = -EBADF, target_fd1 = -EBADF;
2253 int target_fds[2];
2254 ssize_t ret;
2255
2256 /* Create leaf cgroup. */
2257 ret = mkdirat(unified_fd, ".lxc", 0755);
2258 if (ret < 0 && errno != EEXIST)
2259 return log_error_errno(-1, errno, "Failed to create leaf cgroup \".lxc\"");
2260
2261 target_fd0 = openat(unified_fd, ".lxc/cgroup.procs", O_WRONLY | O_CLOEXEC | O_NOFOLLOW);
2262 if (target_fd0 < 0)
2263 return log_error_errno(-errno, errno, "Failed to open \".lxc/cgroup.procs\"");
2264 target_fds[0] = target_fd0;
2265
2266 target_fd1 = openat(unified_fd, "cgroup.procs", O_WRONLY | O_CLOEXEC | O_NOFOLLOW);
2267 if (target_fd1 < 0)
2268 return log_error_errno(-errno, errno, "Failed to open \".lxc/cgroup.procs\"");
2269 target_fds[1] = target_fd1;
2270
2271 ret = lxc_abstract_unix_send_fds(sk, target_fds, 2, NULL, 0);
2272 if (ret <= 0)
2273 return log_error_errno(-errno, errno, "Failed to send \".lxc/cgroup.procs\" fds %d and %d",
2274 target_fd0, target_fd1);
2275
2276 return log_debug(0, "Sent target cgroup fds %d and %d", target_fd0, target_fd1);
2277 }
2278
2279 static int cgroup_attach_move_into_leaf(const struct lxc_conf *conf,
2280 int *sk_fd, pid_t pid)
2281 {
2282 __do_close int sk = *sk_fd, target_fd0 = -EBADF, target_fd1 = -EBADF;
2283 int target_fds[2];
2284 char pidstr[INTTYPE_TO_STRLEN(int64_t) + 1];
2285 size_t pidstr_len;
2286 ssize_t ret;
2287
2288 ret = lxc_abstract_unix_recv_fds(sk, target_fds, 2, NULL, 0);
2289 if (ret <= 0)
2290 return log_error_errno(-1, errno, "Failed to receive target cgroup fd");
2291 target_fd0 = target_fds[0];
2292 target_fd1 = target_fds[1];
2293
2294 pidstr_len = sprintf(pidstr, INT64_FMT, (int64_t)pid);
2295
2296 ret = lxc_write_nointr(target_fd0, pidstr, pidstr_len);
2297 if (ret > 0 && ret == pidstr_len)
2298 return log_debug(0, "Moved process into target cgroup via fd %d", target_fd0);
2299
2300 ret = lxc_write_nointr(target_fd1, pidstr, pidstr_len);
2301 if (ret > 0 && ret == pidstr_len)
2302 return log_debug(0, "Moved process into target cgroup via fd %d", target_fd1);
2303
2304 return log_debug_errno(-1, errno, "Failed to move process into target cgroup via fd %d and %d",
2305 target_fd0, target_fd1);
2306 }
2307
2308 struct userns_exec_unified_attach_data {
2309 const struct lxc_conf *conf;
2310 int unified_fd;
2311 int sk_pair[2];
2312 pid_t pid;
2313 };
2314
2315 static int cgroup_unified_attach_child_wrapper(void *data)
2316 {
2317 struct userns_exec_unified_attach_data *args = data;
2318
2319 if (!args->conf || args->unified_fd < 0 || args->pid <= 0 ||
2320 args->sk_pair[0] < 0 || args->sk_pair[1] < 0)
2321 return ret_errno(EINVAL);
2322
2323 close_prot_errno_disarm(args->sk_pair[0]);
2324 return cgroup_attach_create_leaf(args->conf, args->unified_fd,
2325 &args->sk_pair[1]);
2326 }
2327
2328 static int cgroup_unified_attach_parent_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[1]);
2337 return cgroup_attach_move_into_leaf(args->conf, &args->sk_pair[0],
2338 args->pid);
2339 }
2340
2341 int cgroup_attach(const struct lxc_conf *conf, const char *name,
2342 const char *lxcpath, pid_t pid)
2343 {
2344 __do_close int unified_fd = -EBADF;
2345 int ret;
2346
2347 if (!conf || !name || !lxcpath || pid <= 0)
2348 return ret_errno(EINVAL);
2349
2350 unified_fd = lxc_cmd_get_cgroup2_fd(name, lxcpath);
2351 if (unified_fd < 0)
2352 return ret_errno(EBADF);
2353
2354 if (!lxc_list_empty(&conf->id_map)) {
2355 struct userns_exec_unified_attach_data args = {
2356 .conf = conf,
2357 .unified_fd = unified_fd,
2358 .pid = pid,
2359 };
2360
2361 ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, args.sk_pair);
2362 if (ret < 0)
2363 return -errno;
2364
2365 ret = userns_exec_minimal(conf,
2366 cgroup_unified_attach_parent_wrapper,
2367 &args,
2368 cgroup_unified_attach_child_wrapper,
2369 &args);
2370 } else {
2371 ret = cgroup_attach_leaf(conf, unified_fd, pid);
2372 }
2373
2374 return ret;
2375 }
2376
2377 /* Technically, we're always at a delegation boundary here (This is especially
2378 * true when cgroup namespaces are available.). The reasoning is that in order
2379 * for us to have been able to start a container in the first place the root
2380 * cgroup must have been a leaf node. Now, either the container's init system
2381 * has populated the cgroup and kept it as a leaf node or it has created
2382 * subtrees. In the former case we will simply attach to the leaf node we
2383 * created when we started the container in the latter case we create our own
2384 * cgroup for the attaching process.
2385 */
2386 static int __cg_unified_attach(const struct hierarchy *h,
2387 const struct lxc_conf *conf, const char *name,
2388 const char *lxcpath, pid_t pid,
2389 const char *controller)
2390 {
2391 __do_close int unified_fd = -EBADF;
2392 __do_free char *path = NULL, *cgroup = NULL;
2393 int ret;
2394
2395 if (!conf || !name || !lxcpath || pid <= 0)
2396 return ret_errno(EINVAL);
2397
2398 ret = cgroup_attach(conf, name, lxcpath, pid);
2399 if (ret == 0)
2400 return log_trace(0, "Attached to unified cgroup via command handler");
2401 if (ret != -EBADF)
2402 return log_error_errno(ret, errno, "Failed to attach to unified cgroup");
2403
2404 /* Fall back to retrieving the path for the unified cgroup. */
2405 cgroup = lxc_cmd_get_cgroup_path(name, lxcpath, controller);
2406 /* not running */
2407 if (!cgroup)
2408 return 0;
2409
2410 path = must_make_path(h->mountpoint, cgroup, NULL);
2411
2412 unified_fd = open(path, O_PATH | O_DIRECTORY | O_CLOEXEC);
2413 if (unified_fd < 0)
2414 return ret_errno(EBADF);
2415
2416 if (!lxc_list_empty(&conf->id_map)) {
2417 struct userns_exec_unified_attach_data args = {
2418 .conf = conf,
2419 .unified_fd = unified_fd,
2420 .pid = pid,
2421 };
2422
2423 ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, args.sk_pair);
2424 if (ret < 0)
2425 return -errno;
2426
2427 ret = userns_exec_minimal(conf,
2428 cgroup_unified_attach_parent_wrapper,
2429 &args,
2430 cgroup_unified_attach_child_wrapper,
2431 &args);
2432 } else {
2433 ret = cgroup_attach_leaf(conf, unified_fd, pid);
2434 }
2435
2436 return ret;
2437 }
2438
2439 __cgfsng_ops static bool cgfsng_attach(struct cgroup_ops *ops,
2440 const struct lxc_conf *conf,
2441 const char *name, const char *lxcpath,
2442 pid_t pid)
2443 {
2444 int len, ret;
2445 char pidstr[INTTYPE_TO_STRLEN(pid_t)];
2446
2447 if (!ops)
2448 return ret_set_errno(false, ENOENT);
2449
2450 if (!ops->hierarchies)
2451 return true;
2452
2453 len = snprintf(pidstr, sizeof(pidstr), "%d", pid);
2454 if (len < 0 || (size_t)len >= sizeof(pidstr))
2455 return false;
2456
2457 for (int i = 0; ops->hierarchies[i]; i++) {
2458 __do_free char *fullpath = NULL, *path = NULL;
2459 struct hierarchy *h = ops->hierarchies[i];
2460
2461 if (h->version == CGROUP2_SUPER_MAGIC) {
2462 ret = __cg_unified_attach(h, conf, name, lxcpath, pid,
2463 h->controllers[0]);
2464 if (ret < 0)
2465 return false;
2466
2467 continue;
2468 }
2469
2470 path = lxc_cmd_get_cgroup_path(name, lxcpath, h->controllers[0]);
2471 /* not running */
2472 if (!path)
2473 return false;
2474
2475 fullpath = build_full_cgpath_from_monitorpath(h, path, "cgroup.procs");
2476 ret = lxc_write_to_file(fullpath, pidstr, len, false, 0666);
2477 if (ret < 0)
2478 return log_error_errno(false, errno, "Failed to attach %d to %s",
2479 (int)pid, fullpath);
2480 }
2481
2482 return true;
2483 }
2484
2485 /* Called externally (i.e. from 'lxc-cgroup') to query cgroup limits. Here we
2486 * don't have a cgroup_data set up, so we ask the running container through the
2487 * commands API for the cgroup path.
2488 */
2489 __cgfsng_ops static int cgfsng_get(struct cgroup_ops *ops, const char *filename,
2490 char *value, size_t len, const char *name,
2491 const char *lxcpath)
2492 {
2493 __do_free char *path = NULL;
2494 __do_free char *controller = NULL;
2495 char *p;
2496 struct hierarchy *h;
2497 int ret = -1;
2498
2499 if (!ops)
2500 return ret_set_errno(-1, ENOENT);
2501
2502 controller = must_copy_string(filename);
2503 p = strchr(controller, '.');
2504 if (p)
2505 *p = '\0';
2506
2507 path = lxc_cmd_get_limiting_cgroup_path(name, lxcpath, controller);
2508 /* not running */
2509 if (!path)
2510 return -1;
2511
2512 h = get_hierarchy(ops, controller);
2513 if (h) {
2514 __do_free char *fullpath = NULL;
2515
2516 fullpath = build_full_cgpath_from_monitorpath(h, path, filename);
2517 ret = lxc_read_from_file(fullpath, value, len);
2518 }
2519
2520 return ret;
2521 }
2522
2523 static int device_cgroup_parse_access(struct device_item *device, const char *val)
2524 {
2525 for (int count = 0; count < 3; count++, val++) {
2526 switch (*val) {
2527 case 'r':
2528 device->access[count] = *val;
2529 break;
2530 case 'w':
2531 device->access[count] = *val;
2532 break;
2533 case 'm':
2534 device->access[count] = *val;
2535 break;
2536 case '\n':
2537 case '\0':
2538 count = 3;
2539 break;
2540 default:
2541 return ret_errno(EINVAL);
2542 }
2543 }
2544
2545 return 0;
2546 }
2547
2548 static int device_cgroup_rule_parse(struct device_item *device, const char *key,
2549 const char *val)
2550 {
2551 int count, ret;
2552 char temp[50];
2553
2554 if (strcmp("devices.allow", key) == 0)
2555 device->allow = 1;
2556 else
2557 device->allow = 0;
2558
2559 if (strcmp(val, "a") == 0) {
2560 /* global rule */
2561 device->type = 'a';
2562 device->major = -1;
2563 device->minor = -1;
2564 device->global_rule = device->allow
2565 ? LXC_BPF_DEVICE_CGROUP_DENYLIST
2566 : LXC_BPF_DEVICE_CGROUP_ALLOWLIST;
2567 device->allow = -1;
2568 return 0;
2569 }
2570
2571 /* local rule */
2572 device->global_rule = LXC_BPF_DEVICE_CGROUP_LOCAL_RULE;
2573
2574 switch (*val) {
2575 case 'a':
2576 __fallthrough;
2577 case 'b':
2578 __fallthrough;
2579 case 'c':
2580 device->type = *val;
2581 break;
2582 default:
2583 return -1;
2584 }
2585
2586 val++;
2587 if (!isspace(*val))
2588 return -1;
2589 val++;
2590 if (*val == '*') {
2591 device->major = -1;
2592 val++;
2593 } else if (isdigit(*val)) {
2594 memset(temp, 0, sizeof(temp));
2595 for (count = 0; count < sizeof(temp) - 1; count++) {
2596 temp[count] = *val;
2597 val++;
2598 if (!isdigit(*val))
2599 break;
2600 }
2601 ret = lxc_safe_int(temp, &device->major);
2602 if (ret)
2603 return -1;
2604 } else {
2605 return -1;
2606 }
2607 if (*val != ':')
2608 return -1;
2609 val++;
2610
2611 /* read minor */
2612 if (*val == '*') {
2613 device->minor = -1;
2614 val++;
2615 } else if (isdigit(*val)) {
2616 memset(temp, 0, sizeof(temp));
2617 for (count = 0; count < sizeof(temp) - 1; count++) {
2618 temp[count] = *val;
2619 val++;
2620 if (!isdigit(*val))
2621 break;
2622 }
2623 ret = lxc_safe_int(temp, &device->minor);
2624 if (ret)
2625 return -1;
2626 } else {
2627 return -1;
2628 }
2629 if (!isspace(*val))
2630 return -1;
2631
2632 return device_cgroup_parse_access(device, ++val);
2633 }
2634
2635 /* Called externally (i.e. from 'lxc-cgroup') to set new cgroup limits. Here we
2636 * don't have a cgroup_data set up, so we ask the running container through the
2637 * commands API for the cgroup path.
2638 */
2639 __cgfsng_ops static int cgfsng_set(struct cgroup_ops *ops,
2640 const char *key, const char *value,
2641 const char *name, const char *lxcpath)
2642 {
2643 __do_free char *path = NULL;
2644 __do_free char *controller = NULL;
2645 char *p;
2646 struct hierarchy *h;
2647 int ret = -1;
2648
2649 if (!ops)
2650 return ret_set_errno(-1, ENOENT);
2651
2652 controller = must_copy_string(key);
2653 p = strchr(controller, '.');
2654 if (p)
2655 *p = '\0';
2656
2657 if (pure_unified_layout(ops) && strcmp(controller, "devices") == 0) {
2658 struct device_item device = {0};
2659
2660 ret = device_cgroup_rule_parse(&device, key, value);
2661 if (ret < 0)
2662 return log_error_errno(-1, EINVAL, "Failed to parse device string %s=%s",
2663 key, value);
2664
2665 ret = lxc_cmd_add_bpf_device_cgroup(name, lxcpath, &device);
2666 if (ret < 0)
2667 return -1;
2668
2669 return 0;
2670 }
2671
2672 path = lxc_cmd_get_limiting_cgroup_path(name, lxcpath, controller);
2673 /* not running */
2674 if (!path)
2675 return -1;
2676
2677 h = get_hierarchy(ops, controller);
2678 if (h) {
2679 __do_free char *fullpath = NULL;
2680
2681 fullpath = build_full_cgpath_from_monitorpath(h, path, key);
2682 ret = lxc_write_to_file(fullpath, value, strlen(value), false, 0666);
2683 }
2684
2685 return ret;
2686 }
2687
2688 /* take devices cgroup line
2689 * /dev/foo rwx
2690 * and convert it to a valid
2691 * type major:minor mode
2692 * line. Return <0 on error. Dest is a preallocated buffer long enough to hold
2693 * the output.
2694 */
2695 static int device_cgroup_rule_parse_devpath(struct device_item *device,
2696 const char *devpath)
2697 {
2698 __do_free char *path = NULL;
2699 char *mode = NULL;
2700 int n_parts, ret;
2701 char *p;
2702 struct stat sb;
2703
2704 path = must_copy_string(devpath);
2705
2706 /*
2707 * Read path followed by mode. Ignore any trailing text.
2708 * A ' # comment' would be legal. Technically other text is not
2709 * legal, we could check for that if we cared to.
2710 */
2711 for (n_parts = 1, p = path; *p; p++) {
2712 if (*p != ' ')
2713 continue;
2714 *p = '\0';
2715
2716 if (n_parts != 1)
2717 break;
2718 p++;
2719 n_parts++;
2720
2721 while (*p == ' ')
2722 p++;
2723
2724 mode = p;
2725
2726 if (*p == '\0')
2727 return ret_set_errno(-1, EINVAL);
2728 }
2729
2730 if (!mode)
2731 return ret_errno(EINVAL);
2732
2733 if (device_cgroup_parse_access(device, mode) < 0)
2734 return -1;
2735
2736 if (n_parts == 1)
2737 return ret_set_errno(-1, EINVAL);
2738
2739 ret = stat(path, &sb);
2740 if (ret < 0)
2741 return ret_set_errno(-1, errno);
2742
2743 mode_t m = sb.st_mode & S_IFMT;
2744 switch (m) {
2745 case S_IFBLK:
2746 device->type = 'b';
2747 break;
2748 case S_IFCHR:
2749 device->type = 'c';
2750 break;
2751 default:
2752 return log_error_errno(-1, EINVAL, "Unsupported device type %i for \"%s\"", m, path);
2753 }
2754
2755 device->major = MAJOR(sb.st_rdev);
2756 device->minor = MINOR(sb.st_rdev);
2757 device->allow = 1;
2758 device->global_rule = LXC_BPF_DEVICE_CGROUP_LOCAL_RULE;
2759
2760 return 0;
2761 }
2762
2763 static int convert_devpath(const char *invalue, char *dest)
2764 {
2765 struct device_item device = {0};
2766 int ret;
2767
2768 ret = device_cgroup_rule_parse_devpath(&device, invalue);
2769 if (ret < 0)
2770 return -1;
2771
2772 ret = snprintf(dest, 50, "%c %d:%d %s", device.type, device.major,
2773 device.minor, device.access);
2774 if (ret < 0 || ret >= 50)
2775 return log_error_errno(-1, ENAMETOOLONG, "Error on configuration value \"%c %d:%d %s\" (max 50 chars)",
2776 device.type, device.major, device.minor, device.access);
2777
2778 return 0;
2779 }
2780
2781 /* Called from setup_limits - here we have the container's cgroup_data because
2782 * we created the cgroups.
2783 */
2784 static int cg_legacy_set_data(struct cgroup_ops *ops, const char *filename,
2785 const char *value, bool is_cpuset)
2786 {
2787 __do_free char *controller = NULL;
2788 char *p;
2789 /* "b|c <2^64-1>:<2^64-1> r|w|m" = 47 chars max */
2790 char converted_value[50];
2791 struct hierarchy *h;
2792
2793 controller = must_copy_string(filename);
2794 p = strchr(controller, '.');
2795 if (p)
2796 *p = '\0';
2797
2798 if (strcmp("devices.allow", filename) == 0 && value[0] == '/') {
2799 int ret;
2800
2801 ret = convert_devpath(value, converted_value);
2802 if (ret < 0)
2803 return ret;
2804 value = converted_value;
2805 }
2806
2807 h = get_hierarchy(ops, controller);
2808 if (!h)
2809 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);
2810
2811 if (is_cpuset) {
2812 int ret = lxc_write_openat(h->container_full_path, filename, value, strlen(value));
2813 if (ret)
2814 return ret;
2815 }
2816 return lxc_write_openat(h->container_limit_path, filename, value, strlen(value));
2817 }
2818
2819 __cgfsng_ops static bool cgfsng_setup_limits_legacy(struct cgroup_ops *ops,
2820 struct lxc_conf *conf,
2821 bool do_devices)
2822 {
2823 __do_free struct lxc_list *sorted_cgroup_settings = NULL;
2824 struct lxc_list *cgroup_settings = &conf->cgroup;
2825 struct lxc_list *iterator, *next;
2826 struct lxc_cgroup *cg;
2827 bool ret = false;
2828
2829 if (!ops)
2830 return ret_set_errno(false, ENOENT);
2831
2832 if (!conf)
2833 return ret_set_errno(false, EINVAL);
2834
2835 cgroup_settings = &conf->cgroup;
2836 if (lxc_list_empty(cgroup_settings))
2837 return true;
2838
2839 if (!ops->hierarchies)
2840 return ret_set_errno(false, EINVAL);
2841
2842 if (pure_unified_layout(ops))
2843 return log_warn_errno(true, EINVAL, "Ignoring legacy cgroup limits on pure cgroup2 system");
2844
2845 sorted_cgroup_settings = sort_cgroup_settings(cgroup_settings);
2846 if (!sorted_cgroup_settings)
2847 return false;
2848
2849 lxc_list_for_each(iterator, sorted_cgroup_settings) {
2850 cg = iterator->elem;
2851
2852 if (do_devices == !strncmp("devices", cg->subsystem, 7)) {
2853 if (cg_legacy_set_data(ops, cg->subsystem, cg->value, strncmp("cpuset", cg->subsystem, 6) == 0)) {
2854 if (do_devices && (errno == EACCES || errno == EPERM)) {
2855 SYSWARN("Failed to set \"%s\" to \"%s\"", cg->subsystem, cg->value);
2856 continue;
2857 }
2858 SYSERROR("Failed to set \"%s\" to \"%s\"", cg->subsystem, cg->value);
2859 goto out;
2860 }
2861 DEBUG("Set controller \"%s\" set to \"%s\"", cg->subsystem, cg->value);
2862 }
2863 }
2864
2865 ret = true;
2866 INFO("Limits for the legacy cgroup hierarchies have been setup");
2867 out:
2868 lxc_list_for_each_safe(iterator, sorted_cgroup_settings, next) {
2869 lxc_list_del(iterator);
2870 free(iterator);
2871 }
2872
2873 return ret;
2874 }
2875
2876 /*
2877 * Some of the parsing logic comes from the original cgroup device v1
2878 * implementation in the kernel.
2879 */
2880 static int bpf_device_cgroup_prepare(struct cgroup_ops *ops,
2881 struct lxc_conf *conf, const char *key,
2882 const char *val)
2883 {
2884 #ifdef HAVE_STRUCT_BPF_CGROUP_DEV_CTX
2885 struct device_item device_item = {0};
2886 int ret;
2887
2888 if (strcmp("devices.allow", key) == 0 && *val == '/')
2889 ret = device_cgroup_rule_parse_devpath(&device_item, val);
2890 else
2891 ret = device_cgroup_rule_parse(&device_item, key, val);
2892 if (ret < 0)
2893 return log_error_errno(-1, EINVAL, "Failed to parse device string %s=%s", key, val);
2894
2895 ret = bpf_list_add_device(conf, &device_item);
2896 if (ret < 0)
2897 return -1;
2898 #endif
2899 return 0;
2900 }
2901
2902 __cgfsng_ops static bool cgfsng_setup_limits(struct cgroup_ops *ops,
2903 struct lxc_handler *handler)
2904 {
2905 struct lxc_list *cgroup_settings, *iterator;
2906 struct hierarchy *h;
2907 struct lxc_conf *conf;
2908
2909 if (!ops)
2910 return ret_set_errno(false, ENOENT);
2911
2912 if (!ops->hierarchies)
2913 return true;
2914
2915 if (!ops->container_cgroup)
2916 return ret_set_errno(false, EINVAL);
2917
2918 if (!handler || !handler->conf)
2919 return ret_set_errno(false, EINVAL);
2920 conf = handler->conf;
2921
2922 cgroup_settings = &conf->cgroup2;
2923 if (lxc_list_empty(cgroup_settings))
2924 return true;
2925
2926 if (!pure_unified_layout(ops))
2927 return log_warn_errno(true, EINVAL, "Ignoring cgroup2 limits on legacy cgroup system");
2928
2929 if (!ops->unified)
2930 return false;
2931 h = ops->unified;
2932
2933 lxc_list_for_each (iterator, cgroup_settings) {
2934 struct lxc_cgroup *cg = iterator->elem;
2935 int ret;
2936
2937 if (strncmp("devices", cg->subsystem, 7) == 0) {
2938 ret = bpf_device_cgroup_prepare(ops, conf, cg->subsystem,
2939 cg->value);
2940 } else {
2941 ret = lxc_write_openat(h->container_limit_path,
2942 cg->subsystem, cg->value,
2943 strlen(cg->value));
2944 if (ret < 0)
2945 return log_error_errno(false, errno, "Failed to set \"%s\" to \"%s\"",
2946 cg->subsystem, cg->value);
2947 }
2948 TRACE("Set \"%s\" to \"%s\"", cg->subsystem, cg->value);
2949 }
2950
2951 return log_info(true, "Limits for the unified cgroup hierarchy have been setup");
2952 }
2953
2954 __cgfsng_ops bool cgfsng_devices_activate(struct cgroup_ops *ops,
2955 struct lxc_handler *handler)
2956 {
2957 #ifdef HAVE_STRUCT_BPF_CGROUP_DEV_CTX
2958 __do_bpf_program_free struct bpf_program *devices = NULL;
2959 int ret;
2960 struct lxc_conf *conf;
2961 struct hierarchy *unified;
2962 struct lxc_list *it;
2963 struct bpf_program *devices_old;
2964
2965 if (!ops)
2966 return ret_set_errno(false, ENOENT);
2967
2968 if (!ops->hierarchies)
2969 return true;
2970
2971 if (!ops->container_cgroup)
2972 return ret_set_errno(false, EEXIST);
2973
2974 if (!handler || !handler->conf)
2975 return ret_set_errno(false, EINVAL);
2976 conf = handler->conf;
2977
2978 unified = ops->unified;
2979 if (!unified || !unified->bpf_device_controller ||
2980 !unified->container_full_path || lxc_list_empty(&conf->devices))
2981 return true;
2982
2983 devices = bpf_program_new(BPF_PROG_TYPE_CGROUP_DEVICE);
2984 if (!devices)
2985 return log_error_errno(false, ENOMEM, "Failed to create new bpf program");
2986
2987 ret = bpf_program_init(devices);
2988 if (ret)
2989 return log_error_errno(false, ENOMEM, "Failed to initialize bpf program");
2990
2991 lxc_list_for_each(it, &conf->devices) {
2992 struct device_item *cur = it->elem;
2993
2994 ret = bpf_program_append_device(devices, cur);
2995 if (ret)
2996 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",
2997 cur->type,
2998 cur->major,
2999 cur->minor,
3000 cur->access,
3001 cur->allow,
3002 cur->global_rule);
3003 TRACE("Added rule to bpf device program: type %c, major %d, minor %d, access %s, allow %d, global_rule %d",
3004 cur->type,
3005 cur->major,
3006 cur->minor,
3007 cur->access,
3008 cur->allow,
3009 cur->global_rule);
3010 }
3011
3012 ret = bpf_program_finalize(devices);
3013 if (ret)
3014 return log_error_errno(false, ENOMEM, "Failed to finalize bpf program");
3015
3016 ret = bpf_program_cgroup_attach(devices, BPF_CGROUP_DEVICE,
3017 unified->container_limit_path,
3018 BPF_F_ALLOW_MULTI);
3019 if (ret)
3020 return log_error_errno(false, ENOMEM, "Failed to attach bpf program");
3021
3022 /* Replace old bpf program. */
3023 devices_old = move_ptr(conf->cgroup2_devices);
3024 conf->cgroup2_devices = move_ptr(devices);
3025 devices = move_ptr(devices_old);
3026 #endif
3027 return true;
3028 }
3029
3030 bool __cgfsng_delegate_controllers(struct cgroup_ops *ops, const char *cgroup)
3031 {
3032 __do_free char *add_controllers = NULL, *base_path = NULL;
3033 __do_free_string_list char **parts = NULL;
3034 struct hierarchy *unified = ops->unified;
3035 ssize_t parts_len;
3036 char **it;
3037 size_t full_len = 0;
3038
3039 if (!ops->hierarchies || !pure_unified_layout(ops) ||
3040 !unified->controllers[0])
3041 return true;
3042
3043 /* For now we simply enable all controllers that we have detected by
3044 * creating a string like "+memory +pids +cpu +io".
3045 * TODO: In the near future we might want to support "-<controller>"
3046 * etc. but whether supporting semantics like this make sense will need
3047 * some thinking.
3048 */
3049 for (it = unified->controllers; it && *it; it++) {
3050 full_len += strlen(*it) + 2;
3051 add_controllers = must_realloc(add_controllers, full_len + 1);
3052
3053 if (unified->controllers[0] == *it)
3054 add_controllers[0] = '\0';
3055
3056 (void)strlcat(add_controllers, "+", full_len + 1);
3057 (void)strlcat(add_controllers, *it, full_len + 1);
3058
3059 if ((it + 1) && *(it + 1))
3060 (void)strlcat(add_controllers, " ", full_len + 1);
3061 }
3062
3063 parts = lxc_string_split(cgroup, '/');
3064 if (!parts)
3065 return false;
3066
3067 parts_len = lxc_array_len((void **)parts);
3068 if (parts_len > 0)
3069 parts_len--;
3070
3071 base_path = must_make_path(unified->mountpoint, unified->container_base_path, NULL);
3072 for (ssize_t i = -1; i < parts_len; i++) {
3073 int ret;
3074 __do_free char *target = NULL;
3075
3076 if (i >= 0)
3077 base_path = must_append_path(base_path, parts[i], NULL);
3078 target = must_make_path(base_path, "cgroup.subtree_control", NULL);
3079 ret = lxc_writeat(-1, target, add_controllers, full_len);
3080 if (ret < 0)
3081 return log_error_errno(false, errno, "Could not enable \"%s\" controllers in the unified cgroup \"%s\"",
3082 add_controllers, target);
3083 TRACE("Enable \"%s\" controllers in the unified cgroup \"%s\"", add_controllers, target);
3084 }
3085
3086 return true;
3087 }
3088
3089 __cgfsng_ops bool cgfsng_monitor_delegate_controllers(struct cgroup_ops *ops)
3090 {
3091 if (!ops)
3092 return ret_set_errno(false, ENOENT);
3093
3094 return __cgfsng_delegate_controllers(ops, ops->monitor_cgroup);
3095 }
3096
3097 __cgfsng_ops bool cgfsng_payload_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->container_cgroup);
3103 }
3104
3105 static bool cgroup_use_wants_controllers(const struct cgroup_ops *ops,
3106 char **controllers)
3107 {
3108 if (!ops->cgroup_use)
3109 return true;
3110
3111 for (char **cur_ctrl = controllers; cur_ctrl && *cur_ctrl; cur_ctrl++) {
3112 bool found = false;
3113
3114 for (char **cur_use = ops->cgroup_use; cur_use && *cur_use; cur_use++) {
3115 if (strcmp(*cur_use, *cur_ctrl) != 0)
3116 continue;
3117
3118 found = true;
3119 break;
3120 }
3121
3122 if (found)
3123 continue;
3124
3125 return false;
3126 }
3127
3128 return true;
3129 }
3130
3131 static void cg_unified_delegate(char ***delegate)
3132 {
3133 __do_free char *buf = NULL;
3134 char *standard[] = {"cgroup.subtree_control", "cgroup.threads", NULL};
3135 char *token;
3136 int idx;
3137
3138 buf = read_file("/sys/kernel/cgroup/delegate");
3139 if (!buf) {
3140 for (char **p = standard; p && *p; p++) {
3141 idx = append_null_to_list((void ***)delegate);
3142 (*delegate)[idx] = must_copy_string(*p);
3143 }
3144 SYSWARN("Failed to read /sys/kernel/cgroup/delegate");
3145 return;
3146 }
3147
3148 lxc_iterate_parts(token, buf, " \t\n") {
3149 /*
3150 * We always need to chown this for both cgroup and
3151 * cgroup2.
3152 */
3153 if (strcmp(token, "cgroup.procs") == 0)
3154 continue;
3155
3156 idx = append_null_to_list((void ***)delegate);
3157 (*delegate)[idx] = must_copy_string(token);
3158 }
3159 }
3160
3161 /* At startup, parse_hierarchies finds all the info we need about cgroup
3162 * mountpoints and current cgroups, and stores it in @d.
3163 */
3164 static int cg_hybrid_init(struct cgroup_ops *ops, bool relative, bool unprivileged)
3165 {
3166 __do_free char *basecginfo = NULL, *line = NULL;
3167 __do_free_string_list char **klist = NULL, **nlist = NULL;
3168 __do_fclose FILE *f = NULL;
3169 int ret;
3170 size_t len = 0;
3171
3172 /* Root spawned containers escape the current cgroup, so use init's
3173 * cgroups as our base in that case.
3174 */
3175 if (!relative && (geteuid() == 0))
3176 basecginfo = read_file("/proc/1/cgroup");
3177 else
3178 basecginfo = read_file("/proc/self/cgroup");
3179 if (!basecginfo)
3180 return ret_set_errno(-1, ENOMEM);
3181
3182 ret = get_existing_subsystems(&klist, &nlist);
3183 if (ret < 0)
3184 return log_error_errno(-1, errno, "Failed to retrieve available legacy cgroup controllers");
3185
3186 f = fopen("/proc/self/mountinfo", "re");
3187 if (!f)
3188 return log_error_errno(-1, errno, "Failed to open \"/proc/self/mountinfo\"");
3189
3190 lxc_cgfsng_print_basecg_debuginfo(basecginfo, klist, nlist);
3191
3192 while (getline(&line, &len, f) != -1) {
3193 __do_free char *base_cgroup = NULL, *mountpoint = NULL;
3194 __do_free_string_list char **controller_list = NULL;
3195 int type;
3196 bool writeable;
3197 struct hierarchy *new;
3198
3199 type = get_cgroup_version(line);
3200 if (type == 0)
3201 continue;
3202
3203 if (type == CGROUP2_SUPER_MAGIC && ops->unified)
3204 continue;
3205
3206 if (ops->cgroup_layout == CGROUP_LAYOUT_UNKNOWN) {
3207 if (type == CGROUP2_SUPER_MAGIC)
3208 ops->cgroup_layout = CGROUP_LAYOUT_UNIFIED;
3209 else if (type == CGROUP_SUPER_MAGIC)
3210 ops->cgroup_layout = CGROUP_LAYOUT_LEGACY;
3211 } else if (ops->cgroup_layout == CGROUP_LAYOUT_UNIFIED) {
3212 if (type == CGROUP_SUPER_MAGIC)
3213 ops->cgroup_layout = CGROUP_LAYOUT_HYBRID;
3214 } else if (ops->cgroup_layout == CGROUP_LAYOUT_LEGACY) {
3215 if (type == CGROUP2_SUPER_MAGIC)
3216 ops->cgroup_layout = CGROUP_LAYOUT_HYBRID;
3217 }
3218
3219 controller_list = cg_hybrid_get_controllers(klist, nlist, line, type);
3220 if (!controller_list && type == CGROUP_SUPER_MAGIC)
3221 continue;
3222
3223 if (type == CGROUP_SUPER_MAGIC)
3224 if (controller_list_is_dup(ops->hierarchies, controller_list)) {
3225 TRACE("Skipping duplicating controller");
3226 continue;
3227 }
3228
3229 mountpoint = cg_hybrid_get_mountpoint(line);
3230 if (!mountpoint) {
3231 ERROR("Failed parsing mountpoint from \"%s\"", line);
3232 continue;
3233 }
3234
3235 if (type == CGROUP_SUPER_MAGIC)
3236 base_cgroup = cg_hybrid_get_current_cgroup(basecginfo, controller_list[0], CGROUP_SUPER_MAGIC);
3237 else
3238 base_cgroup = cg_hybrid_get_current_cgroup(basecginfo, NULL, CGROUP2_SUPER_MAGIC);
3239 if (!base_cgroup) {
3240 ERROR("Failed to find current cgroup");
3241 continue;
3242 }
3243
3244 trim(base_cgroup);
3245 prune_init_scope(base_cgroup);
3246 if (type == CGROUP2_SUPER_MAGIC)
3247 writeable = test_writeable_v2(mountpoint, base_cgroup);
3248 else
3249 writeable = test_writeable_v1(mountpoint, base_cgroup);
3250 if (!writeable) {
3251 TRACE("The %s group is not writeable", base_cgroup);
3252 continue;
3253 }
3254
3255 if (type == CGROUP2_SUPER_MAGIC) {
3256 char *cgv2_ctrl_path;
3257
3258 cgv2_ctrl_path = must_make_path(mountpoint, base_cgroup,
3259 "cgroup.controllers",
3260 NULL);
3261
3262 controller_list = cg_unified_get_controllers(cgv2_ctrl_path);
3263 free(cgv2_ctrl_path);
3264 if (!controller_list) {
3265 controller_list = cg_unified_make_empty_controller();
3266 TRACE("No controllers are enabled for "
3267 "delegation in the unified hierarchy");
3268 }
3269 }
3270
3271 /* Exclude all controllers that cgroup use does not want. */
3272 if (!cgroup_use_wants_controllers(ops, controller_list)) {
3273 TRACE("Skipping controller");
3274 continue;
3275 }
3276
3277 new = add_hierarchy(&ops->hierarchies, move_ptr(controller_list), move_ptr(mountpoint), move_ptr(base_cgroup), type);
3278 if (type == CGROUP2_SUPER_MAGIC && !ops->unified) {
3279 if (unprivileged)
3280 cg_unified_delegate(&new->cgroup2_chown);
3281 ops->unified = new;
3282 }
3283 }
3284
3285 TRACE("Writable cgroup hierarchies:");
3286 lxc_cgfsng_print_hierarchies(ops);
3287
3288 /* verify that all controllers in cgroup.use and all crucial
3289 * controllers are accounted for
3290 */
3291 if (!all_controllers_found(ops))
3292 return log_error_errno(-1, ENOENT, "Failed to find all required controllers");
3293
3294 return 0;
3295 }
3296
3297 /* Get current cgroup from /proc/self/cgroup for the cgroupfs v2 hierarchy. */
3298 static char *cg_unified_get_current_cgroup(bool relative)
3299 {
3300 __do_free char *basecginfo = NULL;
3301 char *copy;
3302 char *base_cgroup;
3303
3304 if (!relative && (geteuid() == 0))
3305 basecginfo = read_file("/proc/1/cgroup");
3306 else
3307 basecginfo = read_file("/proc/self/cgroup");
3308 if (!basecginfo)
3309 return NULL;
3310
3311 base_cgroup = strstr(basecginfo, "0::/");
3312 if (!base_cgroup)
3313 return NULL;
3314
3315 base_cgroup = base_cgroup + 3;
3316 copy = copy_to_eol(base_cgroup);
3317 if (!copy)
3318 return NULL;
3319
3320 return trim(copy);
3321 }
3322
3323 static int cg_unified_init(struct cgroup_ops *ops, bool relative,
3324 bool unprivileged)
3325 {
3326 __do_free char *subtree_path = NULL;
3327 int ret;
3328 char *mountpoint;
3329 char **delegatable;
3330 struct hierarchy *new;
3331 char *base_cgroup = NULL;
3332
3333 ret = unified_cgroup_hierarchy();
3334 if (ret == -ENOMEDIUM)
3335 return ret_errno(ENOMEDIUM);
3336
3337 if (ret != CGROUP2_SUPER_MAGIC)
3338 return 0;
3339
3340 base_cgroup = cg_unified_get_current_cgroup(relative);
3341 if (!base_cgroup)
3342 return ret_errno(EINVAL);
3343 if (!relative)
3344 prune_init_scope(base_cgroup);
3345
3346 /*
3347 * We assume that the cgroup we're currently in has been delegated to
3348 * us and we are free to further delege all of the controllers listed
3349 * in cgroup.controllers further down the hierarchy.
3350 */
3351 mountpoint = must_copy_string(DEFAULT_CGROUP_MOUNTPOINT);
3352 subtree_path = must_make_path(mountpoint, base_cgroup, "cgroup.controllers", NULL);
3353 delegatable = cg_unified_get_controllers(subtree_path);
3354 if (!delegatable)
3355 delegatable = cg_unified_make_empty_controller();
3356 if (!delegatable[0])
3357 TRACE("No controllers are enabled for delegation");
3358
3359 /* TODO: If the user requested specific controllers via lxc.cgroup.use
3360 * we should verify here. The reason I'm not doing it right is that I'm
3361 * not convinced that lxc.cgroup.use will be the future since it is a
3362 * global property. I much rather have an option that lets you request
3363 * controllers per container.
3364 */
3365
3366 new = add_hierarchy(&ops->hierarchies, delegatable, mountpoint, base_cgroup, CGROUP2_SUPER_MAGIC);
3367 if (unprivileged)
3368 cg_unified_delegate(&new->cgroup2_chown);
3369
3370 if (bpf_devices_cgroup_supported())
3371 new->bpf_device_controller = 1;
3372
3373 ops->cgroup_layout = CGROUP_LAYOUT_UNIFIED;
3374 ops->unified = new;
3375
3376 return CGROUP2_SUPER_MAGIC;
3377 }
3378
3379 static int cg_init(struct cgroup_ops *ops, struct lxc_conf *conf)
3380 {
3381 int ret;
3382 const char *tmp;
3383 bool relative = conf->cgroup_meta.relative;
3384
3385 tmp = lxc_global_config_value("lxc.cgroup.use");
3386 if (tmp) {
3387 __do_free char *pin = NULL;
3388 char *chop, *cur;
3389
3390 pin = must_copy_string(tmp);
3391 chop = pin;
3392
3393 lxc_iterate_parts(cur, chop, ",")
3394 must_append_string(&ops->cgroup_use, cur);
3395 }
3396
3397 ret = cg_unified_init(ops, relative, !lxc_list_empty(&conf->id_map));
3398 if (ret < 0)
3399 return -1;
3400
3401 if (ret == CGROUP2_SUPER_MAGIC)
3402 return 0;
3403
3404 return cg_hybrid_init(ops, relative, !lxc_list_empty(&conf->id_map));
3405 }
3406
3407 __cgfsng_ops static int cgfsng_data_init(struct cgroup_ops *ops)
3408 {
3409 const char *cgroup_pattern;
3410
3411 if (!ops)
3412 return ret_set_errno(-1, ENOENT);
3413
3414 /* copy system-wide cgroup information */
3415 cgroup_pattern = lxc_global_config_value("lxc.cgroup.pattern");
3416 if (cgroup_pattern && strcmp(cgroup_pattern, "") != 0)
3417 ops->cgroup_pattern = must_copy_string(cgroup_pattern);
3418
3419 return 0;
3420 }
3421
3422 struct cgroup_ops *cgfsng_ops_init(struct lxc_conf *conf)
3423 {
3424 __do_free struct cgroup_ops *cgfsng_ops = NULL;
3425
3426 cgfsng_ops = malloc(sizeof(struct cgroup_ops));
3427 if (!cgfsng_ops)
3428 return ret_set_errno(NULL, ENOMEM);
3429
3430 memset(cgfsng_ops, 0, sizeof(struct cgroup_ops));
3431 cgfsng_ops->cgroup_layout = CGROUP_LAYOUT_UNKNOWN;
3432
3433 if (cg_init(cgfsng_ops, conf))
3434 return NULL;
3435
3436 cgfsng_ops->data_init = cgfsng_data_init;
3437 cgfsng_ops->payload_destroy = cgfsng_payload_destroy;
3438 cgfsng_ops->monitor_destroy = cgfsng_monitor_destroy;
3439 cgfsng_ops->monitor_create = cgfsng_monitor_create;
3440 cgfsng_ops->monitor_enter = cgfsng_monitor_enter;
3441 cgfsng_ops->monitor_delegate_controllers = cgfsng_monitor_delegate_controllers;
3442 cgfsng_ops->payload_delegate_controllers = cgfsng_payload_delegate_controllers;
3443 cgfsng_ops->payload_create = cgfsng_payload_create;
3444 cgfsng_ops->payload_enter = cgfsng_payload_enter;
3445 cgfsng_ops->payload_finalize = cgfsng_payload_finalize;
3446 cgfsng_ops->escape = cgfsng_escape;
3447 cgfsng_ops->num_hierarchies = cgfsng_num_hierarchies;
3448 cgfsng_ops->get_hierarchies = cgfsng_get_hierarchies;
3449 cgfsng_ops->get_cgroup = cgfsng_get_cgroup;
3450 cgfsng_ops->get = cgfsng_get;
3451 cgfsng_ops->set = cgfsng_set;
3452 cgfsng_ops->freeze = cgfsng_freeze;
3453 cgfsng_ops->unfreeze = cgfsng_unfreeze;
3454 cgfsng_ops->setup_limits_legacy = cgfsng_setup_limits_legacy;
3455 cgfsng_ops->setup_limits = cgfsng_setup_limits;
3456 cgfsng_ops->driver = "cgfsng";
3457 cgfsng_ops->version = "1.0.0";
3458 cgfsng_ops->attach = cgfsng_attach;
3459 cgfsng_ops->chown = cgfsng_chown;
3460 cgfsng_ops->mount = cgfsng_mount;
3461 cgfsng_ops->devices_activate = cgfsng_devices_activate;
3462 cgfsng_ops->get_limiting_cgroup = cgfsng_get_limiting_cgroup;
3463
3464 return move_ptr(cgfsng_ops);
3465 }