]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/cgfs.c
cgfs: always handle named subsystems by default
[mirror_lxc.git] / src / lxc / cgfs.c
CommitLineData
576f946d 1/*
2 * lxc: linux Container library
3 *
4 * (C) Copyright IBM Corp. 2007, 2008
5 *
6 * Authors:
9afe19d6 7 * Daniel Lezcano <daniel.lezcano at free.fr>
576f946d 8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
250b1eec 21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
576f946d 22 */
d06245b8
NC
23#include "config.h"
24
576f946d 25#include <stdio.h>
576f946d 26#include <stdlib.h>
27#include <errno.h>
576f946d 28#include <unistd.h>
29#include <string.h>
341a9bd8 30#include <dirent.h>
576f946d 31#include <fcntl.h>
8b276860 32#include <grp.h>
b98f7d6e 33#include <ctype.h>
576f946d 34#include <sys/types.h>
35#include <sys/stat.h>
36#include <sys/param.h>
37#include <sys/inotify.h>
aae1f3c4 38#include <sys/mount.h>
576f946d 39#include <netinet/in.h>
40#include <net/if.h>
41
e2bcd7db 42#include "error.h"
ae5c8b8e 43#include "commands.h"
b98f7d6e
SH
44#include "list.h"
45#include "conf.h"
33ad9f1a 46#include "utils.h"
4ec31c52 47#include "bdev/bdev.h"
f2363e38
ÇO
48#include "log.h"
49#include "cgroup.h"
50#include "start.h"
484ed030 51#include "state.h"
36eb9bde 52
edaf8b1b
SG
53#if IS_BIONIC
54#include <../include/lxcmntent.h>
55#else
56#include <mntent.h>
57#endif
58
4fb3cba5
DE
59struct cgroup_hierarchy;
60struct cgroup_meta_data;
61struct cgroup_mount_point;
62
63/*
64 * cgroup_meta_data: the metadata about the cgroup infrastructure on this
65 * host
66 */
67struct cgroup_meta_data {
68 ptrdiff_t ref; /* simple refcount */
69 struct cgroup_hierarchy **hierarchies;
70 struct cgroup_mount_point **mount_points;
71 int maximum_hierarchy;
72};
73
74/*
75 * cgroup_hierarchy: describes a single cgroup hierarchy
76 * (may have multiple mount points)
77 */
78struct cgroup_hierarchy {
79 int index;
80 bool used; /* false if the hierarchy should be ignored by lxc */
81 char **subsystems;
82 struct cgroup_mount_point *rw_absolute_mount_point;
83 struct cgroup_mount_point *ro_absolute_mount_point;
84 struct cgroup_mount_point **all_mount_points;
85 size_t all_mount_point_capacity;
86};
87
88/*
89 * cgroup_mount_point: a mount point to where a hierarchy
90 * is mounted to
91 */
92struct cgroup_mount_point {
93 struct cgroup_hierarchy *hierarchy;
94 char *mount_point;
95 char *mount_prefix;
96 bool read_only;
97 bool need_cpuset_init;
98};
99
100/*
101 * cgroup_process_info: describes the membership of a
102 * process to the different cgroup
103 * hierarchies
104 *
105 * Note this is the per-process info tracked by the cgfs_ops.
106 * This is not used with cgmanager.
107 */
108struct cgroup_process_info {
109 struct cgroup_process_info *next;
110 struct cgroup_meta_data *meta_ref;
111 struct cgroup_hierarchy *hierarchy;
112 char *cgroup_path;
113 char *cgroup_path_sub;
114 char **created_paths;
115 size_t created_paths_capacity;
116 size_t created_paths_count;
117 struct cgroup_mount_point *designated_mount_point;
118};
119
120struct cgfs_data {
121 char *name;
122 const char *cgroup_pattern;
123 struct cgroup_meta_data *meta;
124 struct cgroup_process_info *info;
125};
126
127lxc_log_define(lxc_cgfs, lxc);
576f946d 128
33ad9f1a
CS
129static struct cgroup_process_info *lxc_cgroup_process_info_getx(const char *proc_pid_cgroup_str, struct cgroup_meta_data *meta);
130static char **subsystems_from_mount_options(const char *mount_options, char **kernel_list);
131static void lxc_cgroup_mount_point_free(struct cgroup_mount_point *mp);
132static void lxc_cgroup_hierarchy_free(struct cgroup_hierarchy *h);
133static bool is_valid_cgroup(const char *name);
33ad9f1a 134static int create_cgroup(struct cgroup_mount_point *mp, const char *path);
603c64c2 135static int remove_cgroup(struct cgroup_mount_point *mp, const char *path, bool recurse);
33ad9f1a
CS
136static char *cgroup_to_absolute_path(struct cgroup_mount_point *mp, const char *path, const char *suffix);
137static struct cgroup_process_info *find_info_for_subsystem(struct cgroup_process_info *info, const char *subsystem);
138static int do_cgroup_get(const char *cgroup_path, const char *sub_filename, char *value, size_t len);
139static int do_cgroup_set(const char *cgroup_path, const char *sub_filename, const char *value);
4fb3cba5
DE
140static bool cgroup_devices_has_allow_or_deny(struct cgfs_data *d, char *v, bool for_allow);
141static int do_setup_cgroup_limits(struct cgfs_data *d, struct lxc_list *cgroup_settings, bool do_devices);
33ad9f1a
CS
142static int cgroup_recursive_task_count(const char *cgroup_path);
143static int count_lines(const char *fn);
1ea59ad2 144static int handle_cgroup_settings(struct cgroup_mount_point *mp, char *cgroup_path);
d703c2b1 145static bool init_cpuset_if_needed(struct cgroup_mount_point *mp, const char *path);
33ad9f1a 146
4fb3cba5
DE
147static struct cgroup_meta_data *lxc_cgroup_load_meta2(const char **subsystem_whitelist);
148static struct cgroup_meta_data *lxc_cgroup_get_meta(struct cgroup_meta_data *meta_data);
149static struct cgroup_meta_data *lxc_cgroup_put_meta(struct cgroup_meta_data *meta_data);
150
151/* free process membership information */
152static void lxc_cgroup_process_info_free(struct cgroup_process_info *info);
153static void lxc_cgroup_process_info_free_and_remove(struct cgroup_process_info *info);
154
d4ef7c50 155static struct cgroup_ops cgfs_ops;
d4ef7c50 156
603c64c2
SH
157static int cgroup_rmdir(char *dirname)
158{
159 struct dirent dirent, *direntp;
160 int saved_errno = 0;
161 DIR *dir;
162 int ret, failed=0;
163 char pathname[MAXPATHLEN];
164
165 dir = opendir(dirname);
166 if (!dir) {
167 ERROR("%s: failed to open %s", __func__, dirname);
168 return -1;
169 }
170
171 while (!readdir_r(dir, &dirent, &direntp)) {
172 struct stat mystat;
173 int rc;
174
175 if (!direntp)
176 break;
177
178 if (!strcmp(direntp->d_name, ".") ||
179 !strcmp(direntp->d_name, ".."))
180 continue;
181
182 rc = snprintf(pathname, MAXPATHLEN, "%s/%s", dirname, direntp->d_name);
183 if (rc < 0 || rc >= MAXPATHLEN) {
184 ERROR("pathname too long");
185 failed=1;
186 if (!saved_errno)
187 saved_errno = -ENOMEM;
188 continue;
189 }
190 ret = lstat(pathname, &mystat);
191 if (ret) {
192 SYSERROR("%s: failed to stat %s", __func__, pathname);
193 failed=1;
194 if (!saved_errno)
195 saved_errno = errno;
196 continue;
197 }
198 if (S_ISDIR(mystat.st_mode)) {
199 if (cgroup_rmdir(pathname) < 0) {
200 if (!saved_errno)
201 saved_errno = errno;
202 failed=1;
203 }
204 }
205 }
206
207 if (rmdir(dirname) < 0) {
208 SYSERROR("%s: failed to delete %s", __func__, dirname);
209 if (!saved_errno)
210 saved_errno = errno;
211 failed=1;
212 }
213
214 ret = closedir(dir);
215 if (ret) {
216 SYSERROR("%s: failed to close directory %s", __func__, dirname);
217 if (!saved_errno)
218 saved_errno = errno;
219 failed=1;
220 }
221
222 errno = saved_errno;
223 return failed ? -1 : 0;
224}
225
4fb3cba5 226static struct cgroup_meta_data *lxc_cgroup_load_meta()
33ad9f1a
CS
227{
228 const char *cgroup_use = NULL;
229 char **cgroup_use_list = NULL;
230 struct cgroup_meta_data *md = NULL;
231 int saved_errno;
232
233 errno = 0;
593e8478 234 cgroup_use = lxc_global_config_value("lxc.cgroup.use");
33ad9f1a
CS
235 if (!cgroup_use && errno != 0)
236 return NULL;
237 if (cgroup_use) {
238 cgroup_use_list = lxc_string_split_and_trim(cgroup_use, ',');
239 if (!cgroup_use_list)
240 return NULL;
241 }
576f946d 242
33ad9f1a
CS
243 md = lxc_cgroup_load_meta2((const char **)cgroup_use_list);
244 saved_errno = errno;
245 lxc_free_array((void **)cgroup_use_list, free);
246 errno = saved_errno;
247 return md;
248}
fd37327f 249
b653309a 250/* Step 1: determine all kernel subsystems */
4fb3cba5 251static bool find_cgroup_subsystems(char ***kernel_subsystems)
1d39a065 252{
b653309a
SH
253 FILE *proc_cgroups;
254 bool bret = false;
33ad9f1a
CS
255 char *line = NULL;
256 size_t sz = 0;
b653309a
SH
257 size_t kernel_subsystems_count = 0;
258 size_t kernel_subsystems_capacity = 0;
259 int r;
1d39a065 260
33ad9f1a
CS
261 proc_cgroups = fopen_cloexec("/proc/cgroups", "r");
262 if (!proc_cgroups)
b653309a 263 return false;
1d39a065 264
33ad9f1a
CS
265 while (getline(&line, &sz, proc_cgroups) != -1) {
266 char *tab1;
267 char *tab2;
268 int hierarchy_number;
1d39a065 269
33ad9f1a
CS
270 if (line[0] == '#')
271 continue;
272 if (!line[0])
273 continue;
1d39a065 274
33ad9f1a
CS
275 tab1 = strchr(line, '\t');
276 if (!tab1)
8900b9eb 277 continue;
33ad9f1a
CS
278 *tab1++ = '\0';
279 tab2 = strchr(tab1, '\t');
280 if (!tab2)
281 continue;
282 *tab2 = '\0';
fd37327f 283
33ad9f1a
CS
284 tab2 = NULL;
285 hierarchy_number = strtoul(tab1, &tab2, 10);
286 if (!tab2 || *tab2)
287 continue;
288 (void)hierarchy_number;
289
b653309a 290 r = lxc_grow_array((void ***)kernel_subsystems, &kernel_subsystems_capacity, kernel_subsystems_count + 1, 12);
33ad9f1a 291 if (r < 0)
b653309a
SH
292 goto out;
293 (*kernel_subsystems)[kernel_subsystems_count] = strdup(line);
294 if (!(*kernel_subsystems)[kernel_subsystems_count])
295 goto out;
33ad9f1a 296 kernel_subsystems_count++;
bcbd102c 297 }
b653309a 298 bret = true;
0d9f8e18 299
b653309a 300out:
33ad9f1a 301 fclose(proc_cgroups);
0ccf7c2a 302 free(line);
b653309a
SH
303 return bret;
304}
305
306/* Step 2: determine all hierarchies (by reading /proc/self/cgroup),
307 * since mount points don't specify hierarchy number and
308 * /proc/cgroups does not contain named hierarchies
309 */
310static bool find_cgroup_hierarchies(struct cgroup_meta_data *meta_data,
311 bool all_kernel_subsystems, bool all_named_subsystems,
312 const char **subsystem_whitelist)
313{
314 FILE *proc_self_cgroup;
315 char *line = NULL;
316 size_t sz = 0;
317 int r;
318 bool bret = false;
319 size_t hierarchy_capacity = 0;
ef6e34ee 320
33ad9f1a
CS
321 proc_self_cgroup = fopen_cloexec("/proc/self/cgroup", "r");
322 /* if for some reason (because of setns() and pid namespace for example),
323 * /proc/self is not valid, we try /proc/1/cgroup... */
324 if (!proc_self_cgroup)
325 proc_self_cgroup = fopen_cloexec("/proc/1/cgroup", "r");
326 if (!proc_self_cgroup)
b653309a 327 return false;
33ad9f1a
CS
328
329 while (getline(&line, &sz, proc_self_cgroup) != -1) {
330 /* file format: hierarchy:subsystems:group,
331 * we only extract hierarchy and subsystems
332 * here */
333 char *colon1;
334 char *colon2;
335 int hierarchy_number;
336 struct cgroup_hierarchy *h = NULL;
337 char **p;
338
339 if (!line[0])
340 continue;
ad08bbb7 341
33ad9f1a
CS
342 colon1 = strchr(line, ':');
343 if (!colon1)
8900b9eb 344 continue;
33ad9f1a
CS
345 *colon1++ = '\0';
346 colon2 = strchr(colon1, ':');
347 if (!colon2)
348 continue;
349 *colon2 = '\0';
ad08bbb7 350
33ad9f1a
CS
351 colon2 = NULL;
352 hierarchy_number = strtoul(line, &colon2, 10);
353 if (!colon2 || *colon2)
354 continue;
576f946d 355
33ad9f1a
CS
356 if (hierarchy_number > meta_data->maximum_hierarchy) {
357 /* lxc_grow_array will never shrink, so even if we find a lower
358 * hierarchy number here, the array will never be smaller
359 */
360 r = lxc_grow_array((void ***)&meta_data->hierarchies, &hierarchy_capacity, hierarchy_number + 1, 12);
361 if (r < 0)
b653309a 362 goto out;
5193cc3d 363
33ad9f1a
CS
364 meta_data->maximum_hierarchy = hierarchy_number;
365 }
fd37327f 366
33ad9f1a
CS
367 /* this shouldn't happen, we had this already */
368 if (meta_data->hierarchies[hierarchy_number])
b653309a 369 goto out;
33ad9f1a
CS
370
371 h = calloc(1, sizeof(struct cgroup_hierarchy));
372 if (!h)
b653309a 373 goto out;
33ad9f1a
CS
374
375 meta_data->hierarchies[hierarchy_number] = h;
376
377 h->index = hierarchy_number;
378 h->subsystems = lxc_string_split_and_trim(colon1, ',');
379 if (!h->subsystems)
b653309a 380 goto out;
33ad9f1a
CS
381 /* see if this hierarchy should be considered */
382 if (!all_kernel_subsystems || !all_named_subsystems) {
383 for (p = h->subsystems; *p; p++) {
384 if (!strncmp(*p, "name=", 5)) {
385 if (all_named_subsystems || (subsystem_whitelist && lxc_string_in_array(*p, subsystem_whitelist))) {
386 h->used = true;
387 break;
388 }
389 } else {
390 if (all_kernel_subsystems || (subsystem_whitelist && lxc_string_in_array(*p, subsystem_whitelist))) {
391 h->used = true;
392 break;
393 }
394 }
395 }
396 } else {
397 /* we want all hierarchy anyway */
398 h->used = true;
ae5c8b8e 399 }
ae5c8b8e 400 }
b653309a 401 bret = true;
0b9c21ab 402
b653309a 403out:
33ad9f1a 404 fclose(proc_self_cgroup);
0ccf7c2a 405 free(line);
b653309a
SH
406 return bret;
407}
408
409/* Step 3: determine all mount points of each hierarchy */
410static bool find_hierarchy_mountpts( struct cgroup_meta_data *meta_data, char **kernel_subsystems)
411{
412 bool bret = false;
413 FILE *proc_self_mountinfo;
414 char *line = NULL;
415 size_t sz = 0;
416 char **tokens = NULL;
417 size_t mount_point_count = 0;
418 size_t mount_point_capacity = 0;
419 size_t token_capacity = 0;
420 int r;
421
33ad9f1a
CS
422 proc_self_mountinfo = fopen_cloexec("/proc/self/mountinfo", "r");
423 /* if for some reason (because of setns() and pid namespace for example),
424 * /proc/self is not valid, we try /proc/1/cgroup... */
425 if (!proc_self_mountinfo)
426 proc_self_mountinfo = fopen_cloexec("/proc/1/mountinfo", "r");
427 if (!proc_self_mountinfo)
b653309a 428 return false;
33ad9f1a
CS
429
430 while (getline(&line, &sz, proc_self_mountinfo) != -1) {
178938fe 431 char *token, *line_tok, *saveptr = NULL;
33ad9f1a
CS
432 size_t i, j, k;
433 struct cgroup_mount_point *mount_point;
434 struct cgroup_hierarchy *h;
435 char **subsystems;
436
437 if (line[0] && line[strlen(line) - 1] == '\n')
438 line[strlen(line) - 1] = '\0';
439
178938fe 440 for (i = 0, line_tok = line; (token = strtok_r(line_tok, " ", &saveptr)); line_tok = NULL) {
33ad9f1a
CS
441 r = lxc_grow_array((void ***)&tokens, &token_capacity, i + 1, 64);
442 if (r < 0)
b653309a 443 goto out;
33ad9f1a
CS
444 tokens[i++] = token;
445 }
b98f7d6e 446
33ad9f1a
CS
447 /* layout of /proc/self/mountinfo:
448 * 0: id
449 * 1: parent id
450 * 2: device major:minor
451 * 3: mount prefix
8900b9eb 452 * 4: mount point
33ad9f1a
CS
453 * 5: per-mount options
454 * [optional X]: additional data
455 * X+7: "-"
456 * X+8: type
457 * X+9: source
458 * X+10: per-superblock options
459 */
460 for (j = 6; j < i && tokens[j]; j++)
461 if (!strcmp(tokens[j], "-"))
462 break;
fd4f5a56 463
33ad9f1a
CS
464 /* could not find separator */
465 if (j >= i || !tokens[j])
466 continue;
467 /* there should be exactly three fields after
468 * the separator
469 */
470 if (i != j + 4)
471 continue;
fd4f5a56 472
33ad9f1a
CS
473 /* not a cgroup filesystem */
474 if (strcmp(tokens[j + 1], "cgroup") != 0)
475 continue;
b98f7d6e 476
33ad9f1a
CS
477 subsystems = subsystems_from_mount_options(tokens[j + 3], kernel_subsystems);
478 if (!subsystems)
b653309a 479 goto out;
33ad9f1a
CS
480
481 h = NULL;
482 for (k = 1; k <= meta_data->maximum_hierarchy; k++) {
483 if (meta_data->hierarchies[k] &&
484 meta_data->hierarchies[k]->subsystems[0] &&
485 lxc_string_in_array(meta_data->hierarchies[k]->subsystems[0], (const char **)subsystems)) {
486 /* TODO: we could also check if the lists really match completely,
487 * just to have an additional sanity check */
488 h = meta_data->hierarchies[k];
b98f7d6e 489 break;
33ad9f1a 490 }
b98f7d6e 491 }
33ad9f1a
CS
492 lxc_free_array((void **)subsystems, free);
493
494 r = lxc_grow_array((void ***)&meta_data->mount_points, &mount_point_capacity, mount_point_count + 1, 12);
495 if (r < 0)
b653309a 496 goto out;
33ad9f1a
CS
497
498 /* create mount point object */
499 mount_point = calloc(1, sizeof(*mount_point));
500 if (!mount_point)
b653309a 501 goto out;
33ad9f1a
CS
502
503 meta_data->mount_points[mount_point_count++] = mount_point;
504
505 mount_point->hierarchy = h;
506 mount_point->mount_point = strdup(tokens[4]);
507 mount_point->mount_prefix = strdup(tokens[3]);
508 if (!mount_point->mount_point || !mount_point->mount_prefix)
b653309a 509 goto out;
33ad9f1a
CS
510 mount_point->read_only = !lxc_string_in_list("rw", tokens[5], ',');
511
512 if (!strcmp(mount_point->mount_prefix, "/")) {
513 if (mount_point->read_only) {
514 if (!h->ro_absolute_mount_point)
515 h->ro_absolute_mount_point = mount_point;
516 } else {
517 if (!h->rw_absolute_mount_point)
518 h->rw_absolute_mount_point = mount_point;
519 }
b98f7d6e 520 }
ae5c8b8e 521
33ad9f1a
CS
522 k = lxc_array_len((void **)h->all_mount_points);
523 r = lxc_grow_array((void ***)&h->all_mount_points, &h->all_mount_point_capacity, k + 1, 4);
524 if (r < 0)
b653309a 525 goto out;
33ad9f1a 526 h->all_mount_points[k] = mount_point;
fd4f5a56 527 }
b653309a
SH
528 bret = true;
529
530out:
b653309a 531 fclose(proc_self_mountinfo);
b653309a 532 free(tokens);
2cdafc54 533 free(line);
b653309a
SH
534 return bret;
535}
536
4fb3cba5 537static struct cgroup_meta_data *lxc_cgroup_load_meta2(const char **subsystem_whitelist)
b653309a
SH
538{
539 bool all_kernel_subsystems = true;
540 bool all_named_subsystems = false;
541 struct cgroup_meta_data *meta_data = NULL;
542 char **kernel_subsystems = NULL;
543 int saved_errno = 0;
544
545 /* if the subsystem whitelist is not specified, include all
546 * hierarchies that contain kernel subsystems by default but
547 * no hierarchies that only contain named subsystems
548 *
549 * if it is specified, the specifier @all will select all
550 * hierarchies, @kernel will select all hierarchies with
551 * kernel subsystems and @named will select all named
552 * hierarchies
553 */
554 all_kernel_subsystems = subsystem_whitelist ?
555 (lxc_string_in_array("@kernel", subsystem_whitelist) || lxc_string_in_array("@all", subsystem_whitelist)) :
556 true;
557 all_named_subsystems = subsystem_whitelist ?
558 (lxc_string_in_array("@named", subsystem_whitelist) || lxc_string_in_array("@all", subsystem_whitelist)) :
79c59e6b 559 true;
b653309a
SH
560
561 meta_data = calloc(1, sizeof(struct cgroup_meta_data));
562 if (!meta_data)
563 return NULL;
564 meta_data->ref = 1;
565
566 if (!find_cgroup_subsystems(&kernel_subsystems))
567 goto out_error;
568
569 if (!find_cgroup_hierarchies(meta_data, all_kernel_subsystems,
570 all_named_subsystems, subsystem_whitelist))
571 goto out_error;
572
573 if (!find_hierarchy_mountpts(meta_data, kernel_subsystems))
574 goto out_error;
fd4f5a56 575
33ad9f1a
CS
576 /* oops, we couldn't find anything */
577 if (!meta_data->hierarchies || !meta_data->mount_points) {
578 errno = EINVAL;
579 goto out_error;
ae5c8b8e 580 }
fd4f5a56 581
3a0abb3a 582 lxc_free_array((void **)kernel_subsystems, free);
33ad9f1a
CS
583 return meta_data;
584
585out_error:
586 saved_errno = errno;
33ad9f1a
CS
587 lxc_free_array((void **)kernel_subsystems, free);
588 lxc_cgroup_put_meta(meta_data);
589 errno = saved_errno;
590 return NULL;
fd4f5a56
DL
591}
592
4fb3cba5 593static struct cgroup_meta_data *lxc_cgroup_get_meta(struct cgroup_meta_data *meta_data)
e14f67a7 594{
33ad9f1a
CS
595 meta_data->ref++;
596 return meta_data;
597}
e14f67a7 598
4fb3cba5 599static struct cgroup_meta_data *lxc_cgroup_put_meta(struct cgroup_meta_data *meta_data)
33ad9f1a
CS
600{
601 size_t i;
602 if (!meta_data)
603 return NULL;
604 if (--meta_data->ref > 0)
605 return meta_data;
606 lxc_free_array((void **)meta_data->mount_points, (lxc_free_fn)lxc_cgroup_mount_point_free);
607 if (meta_data->hierarchies) {
608 for (i = 0; i <= meta_data->maximum_hierarchy; i++)
609 lxc_cgroup_hierarchy_free(meta_data->hierarchies[i]);
e14f67a7 610 }
33ad9f1a 611 free(meta_data->hierarchies);
178938fe 612 free(meta_data);
33ad9f1a 613 return NULL;
e14f67a7
U
614}
615
4fb3cba5 616static struct cgroup_hierarchy *lxc_cgroup_find_hierarchy(struct cgroup_meta_data *meta_data, const char *subsystem)
e14f67a7 617{
33ad9f1a
CS
618 size_t i;
619 for (i = 0; i <= meta_data->maximum_hierarchy; i++) {
620 struct cgroup_hierarchy *h = meta_data->hierarchies[i];
621 if (h && lxc_string_in_array(subsystem, (const char **)h->subsystems))
622 return h;
e14f67a7 623 }
e14f67a7
U
624 return NULL;
625}
626
4fb3cba5 627static struct cgroup_mount_point *lxc_cgroup_find_mount_point(struct cgroup_hierarchy *hierarchy, const char *group, bool should_be_writable)
b98f7d6e 628{
33ad9f1a
CS
629 struct cgroup_mount_point **mps;
630 struct cgroup_mount_point *current_result = NULL;
631 ssize_t quality = -1;
b98f7d6e 632
33ad9f1a
CS
633 /* trivial case */
634 if (hierarchy->rw_absolute_mount_point)
635 return hierarchy->rw_absolute_mount_point;
636 if (!should_be_writable && hierarchy->ro_absolute_mount_point)
637 return hierarchy->ro_absolute_mount_point;
b98f7d6e 638
33ad9f1a
CS
639 for (mps = hierarchy->all_mount_points; mps && *mps; mps++) {
640 struct cgroup_mount_point *mp = *mps;
641 size_t prefix_len = mp->mount_prefix ? strlen(mp->mount_prefix) : 0;
b98f7d6e 642
33ad9f1a
CS
643 if (prefix_len == 1 && mp->mount_prefix[0] == '/')
644 prefix_len = 0;
b98f7d6e 645
33ad9f1a
CS
646 if (should_be_writable && mp->read_only)
647 continue;
648
649 if (!prefix_len ||
650 (strncmp(group, mp->mount_prefix, prefix_len) == 0 &&
651 (group[prefix_len] == '\0' || group[prefix_len] == '/'))) {
652 /* search for the best quality match, i.e. the match with the
653 * shortest prefix where this group is still contained
654 */
655 if (quality == -1 || prefix_len < quality) {
656 current_result = mp;
657 quality = prefix_len;
658 }
b98f7d6e
SH
659 }
660 }
661
33ad9f1a
CS
662 if (!current_result)
663 errno = ENOENT;
664 return current_result;
b98f7d6e
SH
665}
666
4fb3cba5 667static char *lxc_cgroup_find_abs_path(const char *subsystem, const char *group, bool should_be_writable, const char *suffix)
b98f7d6e 668{
33ad9f1a
CS
669 struct cgroup_meta_data *meta_data;
670 struct cgroup_hierarchy *h;
671 struct cgroup_mount_point *mp;
672 char *result;
673 int saved_errno;
674
675 meta_data = lxc_cgroup_load_meta();
676 if (!meta_data)
677 return NULL;
b98f7d6e 678
33ad9f1a
CS
679 h = lxc_cgroup_find_hierarchy(meta_data, subsystem);
680 if (!h)
681 goto out_error;
b98f7d6e 682
33ad9f1a
CS
683 mp = lxc_cgroup_find_mount_point(h, group, should_be_writable);
684 if (!mp)
685 goto out_error;
b98f7d6e 686
33ad9f1a
CS
687 result = cgroup_to_absolute_path(mp, group, suffix);
688 if (!result)
689 goto out_error;
b98f7d6e 690
33ad9f1a
CS
691 lxc_cgroup_put_meta(meta_data);
692 return result;
b98f7d6e 693
33ad9f1a
CS
694out_error:
695 saved_errno = errno;
696 lxc_cgroup_put_meta(meta_data);
697 errno = saved_errno;
698 return NULL;
b98f7d6e
SH
699}
700
4fb3cba5 701static struct cgroup_process_info *lxc_cgroup_process_info_get(pid_t pid, struct cgroup_meta_data *meta)
fd4f5a56 702{
33ad9f1a
CS
703 char pid_buf[32];
704 snprintf(pid_buf, 32, "/proc/%lu/cgroup", (unsigned long)pid);
705 return lxc_cgroup_process_info_getx(pid_buf, meta);
c8f7c563
CS
706}
707
4fb3cba5 708static struct cgroup_process_info *lxc_cgroup_process_info_get_init(struct cgroup_meta_data *meta)
c8f7c563 709{
33ad9f1a
CS
710 return lxc_cgroup_process_info_get(1, meta);
711}
b98f7d6e 712
4fb3cba5 713static struct cgroup_process_info *lxc_cgroup_process_info_get_self(struct cgroup_meta_data *meta)
33ad9f1a
CS
714{
715 struct cgroup_process_info *i;
716 i = lxc_cgroup_process_info_getx("/proc/self/cgroup", meta);
717 if (!i)
718 i = lxc_cgroup_process_info_get(getpid(), meta);
719 return i;
720}
ae5c8b8e 721
692ba18f
SH
722/*
723 * If a controller has ns cgroup mounted, then in that cgroup the handler->pid
724 * is already in a new cgroup named after the pid. 'mnt' is passed in as
725 * the full current cgroup. Say that is /sys/fs/cgroup/lxc/2975 and the container
726 * name is c1. . We want to rename the cgroup directory to /sys/fs/cgroup/lxc/c1,
727 * and return the string /sys/fs/cgroup/lxc/c1.
728 */
cea0552e 729static char *cgroup_rename_nsgroup(const char *mountpath, const char *oldname, pid_t pid, const char *name)
692ba18f
SH
730{
731 char *dir, *fulloldpath;
732 char *newname, *fullnewpath;
cea0552e 733 int len, newlen, ret;
692ba18f
SH
734
735 /*
736 * if cgroup is mounted at /cgroup and task is in cgroup /ab/, pid 2375 and
737 * name is c1,
738 * dir: /ab
739 * fulloldpath = /cgroup/ab/2375
740 * fullnewpath = /cgroup/ab/c1
741 * newname = /ab/c1
742 */
743 dir = alloca(strlen(oldname) + 1);
744 strcpy(dir, oldname);
745
cea0552e
SH
746 len = strlen(oldname) + strlen(mountpath) + 22;
747 fulloldpath = alloca(len);
748 ret = snprintf(fulloldpath, len, "%s/%s/%ld", mountpath, oldname, (unsigned long)pid);
749 if (ret < 0 || ret >= len)
750 return NULL;
692ba18f
SH
751
752 len = strlen(dir) + strlen(name) + 2;
753 newname = malloc(len);
754 if (!newname) {
755 SYSERROR("Out of memory");
756 return NULL;
757 }
cea0552e
SH
758 ret = snprintf(newname, len, "%s/%s", dir, name);
759 if (ret < 0 || ret >= len) {
760 free(newname);
761 return NULL;
762 }
692ba18f 763
cea0552e
SH
764 newlen = strlen(mountpath) + len + 2;
765 fullnewpath = alloca(newlen);
766 ret = snprintf(fullnewpath, newlen, "%s/%s", mountpath, newname);
767 if (ret < 0 || ret >= newlen) {
768 free(newname);
769 return NULL;
770 }
692ba18f
SH
771
772 if (access(fullnewpath, F_OK) == 0) {
773 if (rmdir(fullnewpath) != 0) {
774 SYSERROR("container cgroup %s already exists.", fullnewpath);
775 free(newname);
776 return NULL;
777 }
778 }
779 if (rename(fulloldpath, fullnewpath)) {
780 SYSERROR("failed to rename cgroup %s->%s", fulloldpath, fullnewpath);
781 free(newname);
782 return NULL;
783 }
784
785 DEBUG("'%s' renamed to '%s'", oldname, newname);
786
787 return newname;
788}
789
33ad9f1a 790/* create a new cgroup */
4fb3cba5 791static struct cgroup_process_info *lxc_cgroupfs_create(const char *name, const char *path_pattern, struct cgroup_meta_data *meta_data, const char *sub_pattern)
33ad9f1a 792{
001b026e 793 char **cgroup_path_components = NULL;
33ad9f1a
CS
794 char **p = NULL;
795 char *path_so_far = NULL;
796 char **new_cgroup_paths = NULL;
797 char **new_cgroup_paths_sub = NULL;
798 struct cgroup_mount_point *mp;
799 struct cgroup_hierarchy *h;
800 struct cgroup_process_info *base_info = NULL;
801 struct cgroup_process_info *info_ptr;
802 int saved_errno;
803 int r;
804 unsigned suffix = 0;
805 bool had_sub_pattern = false;
806 size_t i;
ae5c8b8e 807
33ad9f1a
CS
808 if (!is_valid_cgroup(name)) {
809 ERROR("Invalid cgroup name: '%s'", name);
810 errno = EINVAL;
811 return NULL;
ae5c8b8e
SH
812 }
813
33ad9f1a
CS
814 if (!strstr(path_pattern, "%n")) {
815 ERROR("Invalid cgroup path pattern: '%s'; contains no %%n for specifying container name", path_pattern);
816 errno = EINVAL;
817 return NULL;
818 }
fd37327f 819
33ad9f1a
CS
820 /* we will modify the result of this operation directly,
821 * so we don't have to copy the data structure
822 */
823 base_info = (path_pattern[0] == '/') ?
824 lxc_cgroup_process_info_get_init(meta_data) :
825 lxc_cgroup_process_info_get_self(meta_data);
826 if (!base_info)
827 return NULL;
c8f7c563 828
33ad9f1a
CS
829 new_cgroup_paths = calloc(meta_data->maximum_hierarchy + 1, sizeof(char *));
830 if (!new_cgroup_paths)
831 goto out_initial_error;
832
833 new_cgroup_paths_sub = calloc(meta_data->maximum_hierarchy + 1, sizeof(char *));
834 if (!new_cgroup_paths_sub)
835 goto out_initial_error;
836
837 /* find mount points we can use */
838 for (info_ptr = base_info; info_ptr; info_ptr = info_ptr->next) {
839 h = info_ptr->hierarchy;
840 mp = lxc_cgroup_find_mount_point(h, info_ptr->cgroup_path, true);
841 if (!mp) {
842 ERROR("Could not find writable mount point for cgroup hierarchy %d while trying to create cgroup.", h->index);
843 goto out_initial_error;
844 }
845 info_ptr->designated_mount_point = mp;
460a1cf0 846
692ba18f
SH
847 if (lxc_string_in_array("ns", (const char **)h->subsystems))
848 continue;
2edb53c7
SH
849 if (handle_cgroup_settings(mp, info_ptr->cgroup_path) < 0) {
850 ERROR("Could not set clone_children to 1 for cpuset hierarchy in parent cgroup.");
33ad9f1a 851 goto out_initial_error;
2edb53c7 852 }
33ad9f1a 853 }
b98f7d6e 854
33ad9f1a
CS
855 /* normalize the path */
856 cgroup_path_components = lxc_normalize_path(path_pattern);
857 if (!cgroup_path_components)
858 goto out_initial_error;
859
860 /* go through the path components to see if we can create them */
861 for (p = cgroup_path_components; *p || (sub_pattern && !had_sub_pattern); p++) {
862 /* we only want to create the same component with -1, -2, etc.
863 * if the component contains the container name itself, otherwise
864 * it's not an error if it already exists
865 */
866 char *p_eff = *p ? *p : (char *)sub_pattern;
867 bool contains_name = strstr(p_eff, "%n");
868 char *current_component = NULL;
869 char *current_subpath = NULL;
870 char *current_entire_path = NULL;
871 char *parts[3];
872 size_t j = 0;
873 i = 0;
874
875 /* if we are processing the subpattern, we want to make sure
876 * loop is ended the next time around
877 */
878 if (!*p) {
879 had_sub_pattern = true;
880 p--;
881 }
b98f7d6e 882
33ad9f1a 883 goto find_name_on_this_level;
4fb3cba5 884
33ad9f1a
CS
885 cleanup_name_on_this_level:
886 /* This is reached if we found a name clash.
887 * In that case, remove the cgroup from all previous hierarchies
888 */
889 for (j = 0, info_ptr = base_info; j < i && info_ptr; info_ptr = info_ptr->next, j++) {
603c64c2 890 r = remove_cgroup(info_ptr->designated_mount_point, info_ptr->created_paths[info_ptr->created_paths_count - 1], false);
33ad9f1a
CS
891 if (r < 0)
892 WARN("could not clean up cgroup we created when trying to create container");
893 free(info_ptr->created_paths[info_ptr->created_paths_count - 1]);
894 info_ptr->created_paths[--info_ptr->created_paths_count] = NULL;
895 }
896 if (current_component != current_subpath)
897 free(current_subpath);
898 if (current_component != p_eff)
899 free(current_component);
900 current_component = current_subpath = NULL;
901 /* try again with another suffix */
902 ++suffix;
4fb3cba5 903
33ad9f1a
CS
904 find_name_on_this_level:
905 /* determine name of the path component we should create */
906 if (contains_name && suffix > 0) {
907 char *buf = calloc(strlen(name) + 32, 1);
908 if (!buf)
909 goto out_initial_error;
910 snprintf(buf, strlen(name) + 32, "%s-%u", name, suffix);
911 current_component = lxc_string_replace("%n", buf, p_eff);
912 free(buf);
913 } else {
914 current_component = contains_name ? lxc_string_replace("%n", name, p_eff) : p_eff;
915 }
916 parts[0] = path_so_far;
917 parts[1] = current_component;
918 parts[2] = NULL;
919 current_subpath = path_so_far ? lxc_string_join("/", (const char **)parts, false) : current_component;
920
921 /* Now go through each hierarchy and try to create the
922 * corresponding cgroup
923 */
924 for (i = 0, info_ptr = base_info; info_ptr; info_ptr = info_ptr->next, i++) {
925 char *parts2[3];
692ba18f
SH
926
927 if (lxc_string_in_array("ns", (const char **)info_ptr->hierarchy->subsystems))
928 continue;
33ad9f1a
CS
929 current_entire_path = NULL;
930
931 parts2[0] = !strcmp(info_ptr->cgroup_path, "/") ? "" : info_ptr->cgroup_path;
932 parts2[1] = current_subpath;
933 parts2[2] = NULL;
934 current_entire_path = lxc_string_join("/", (const char **)parts2, false);
935
936 if (!*p) {
937 /* we are processing the subpath, so only update that one */
938 free(new_cgroup_paths_sub[i]);
939 new_cgroup_paths_sub[i] = strdup(current_entire_path);
940 if (!new_cgroup_paths_sub[i])
941 goto cleanup_from_error;
942 } else {
943 /* remember which path was used on this controller */
944 free(new_cgroup_paths[i]);
945 new_cgroup_paths[i] = strdup(current_entire_path);
946 if (!new_cgroup_paths[i])
947 goto cleanup_from_error;
948 }
fd4f5a56 949
33ad9f1a
CS
950 r = create_cgroup(info_ptr->designated_mount_point, current_entire_path);
951 if (r < 0 && errno == EEXIST && contains_name) {
952 /* name clash => try new name with new suffix */
953 free(current_entire_path);
954 current_entire_path = NULL;
955 goto cleanup_name_on_this_level;
956 } else if (r < 0 && errno != EEXIST) {
b38b62a6 957 SYSERROR("Could not create cgroup '%s' in '%s'.", current_entire_path, info_ptr->designated_mount_point->mount_point);
33ad9f1a
CS
958 goto cleanup_from_error;
959 } else if (r == 0) {
960 /* successfully created */
961 r = lxc_grow_array((void ***)&info_ptr->created_paths, &info_ptr->created_paths_capacity, info_ptr->created_paths_count + 1, 8);
962 if (r < 0)
963 goto cleanup_from_error;
d703c2b1 964 if (!init_cpuset_if_needed(info_ptr->designated_mount_point, current_entire_path)) {
b38b62a6 965 ERROR("Failed to initialize cpuset for '%s' in '%s'.", current_entire_path, info_ptr->designated_mount_point->mount_point);
d703c2b1
RV
966 goto cleanup_from_error;
967 }
33ad9f1a
CS
968 info_ptr->created_paths[info_ptr->created_paths_count++] = current_entire_path;
969 } else {
970 /* if we didn't create the cgroup, then we have to make sure that
971 * further cgroups will be created properly
972 */
d703c2b1 973 if (handle_cgroup_settings(info_ptr->designated_mount_point, info_ptr->cgroup_path) < 0) {
f6ac3b9e 974 ERROR("Could not set clone_children to 1 for cpuset hierarchy in pre-existing cgroup.");
33ad9f1a 975 goto cleanup_from_error;
f6ac3b9e 976 }
d703c2b1
RV
977 if (!init_cpuset_if_needed(info_ptr->designated_mount_point, info_ptr->cgroup_path)) {
978 ERROR("Failed to initialize cpuset in pre-existing '%s'.", info_ptr->cgroup_path);
979 goto cleanup_from_error;
980 }
33ad9f1a
CS
981
982 /* already existed but path component of pattern didn't contain '%n',
983 * so this is not an error; but then we don't need current_entire_path
984 * anymore...
985 */
986 free(current_entire_path);
987 current_entire_path = NULL;
988 }
989 }
fd4f5a56 990
33ad9f1a
CS
991 /* save path so far */
992 free(path_so_far);
993 path_so_far = strdup(current_subpath);
994 if (!path_so_far)
995 goto cleanup_from_error;
996
997 /* cleanup */
998 if (current_component != current_subpath)
999 free(current_subpath);
1000 if (current_component != p_eff)
1001 free(current_component);
1002 current_component = current_subpath = NULL;
1003 continue;
4fb3cba5 1004
33ad9f1a 1005 cleanup_from_error:
ec64264d 1006 /* called if an error occurred in the loop, so we
33ad9f1a
CS
1007 * do some additional cleanup here
1008 */
1009 saved_errno = errno;
1010 if (current_component != current_subpath)
1011 free(current_subpath);
1012 if (current_component != p_eff)
1013 free(current_component);
1014 free(current_entire_path);
1015 errno = saved_errno;
1016 goto out_initial_error;
fd4f5a56
DL
1017 }
1018
33ad9f1a
CS
1019 /* we're done, now update the paths */
1020 for (i = 0, info_ptr = base_info; info_ptr; info_ptr = info_ptr->next, i++) {
47d8fb3b
CS
1021 /* ignore legacy 'ns' subsystem here, lxc_cgroup_create_legacy
1022 * will take care of it
1023 * Since we do a continue in above loop, new_cgroup_paths[i] is
1024 * unset anyway, as is new_cgroup_paths_sub[i]
692ba18f 1025 */
47d8fb3b
CS
1026 if (lxc_string_in_array("ns", (const char **)info_ptr->hierarchy->subsystems))
1027 continue;
1028 free(info_ptr->cgroup_path);
1029 info_ptr->cgroup_path = new_cgroup_paths[i];
1030 info_ptr->cgroup_path_sub = new_cgroup_paths_sub[i];
fd4f5a56 1031 }
33ad9f1a
CS
1032 /* don't use lxc_free_array since we used the array members
1033 * to store them in our result...
1034 */
1035 free(new_cgroup_paths);
1036 free(new_cgroup_paths_sub);
1037 free(path_so_far);
1038 lxc_free_array((void **)cgroup_path_components, free);
1039 return base_info;
1040
1041out_initial_error:
1042 saved_errno = errno;
1043 free(path_so_far);
1044 lxc_cgroup_process_info_free_and_remove(base_info);
1045 lxc_free_array((void **)new_cgroup_paths, free);
1046 lxc_free_array((void **)new_cgroup_paths_sub, free);
1047 lxc_free_array((void **)cgroup_path_components, free);
1048 errno = saved_errno;
1049 return NULL;
c8f7c563
CS
1050}
1051
4fb3cba5 1052static int lxc_cgroup_create_legacy(struct cgroup_process_info *base_info, const char *name, pid_t pid)
47d8fb3b
CS
1053{
1054 struct cgroup_process_info *info_ptr;
1055 int r;
1056
1057 for (info_ptr = base_info; info_ptr; info_ptr = info_ptr->next) {
1058 if (!lxc_string_in_array("ns", (const char **)info_ptr->hierarchy->subsystems))
1059 continue;
1060 /*
1061 * For any path which has ns cgroup mounted, handler->pid is already
1062 * moved into a container called '%d % (handler->pid)'. Rename it to
1063 * the cgroup name and record that.
1064 */
1065 char *tmp = cgroup_rename_nsgroup((const char *)info_ptr->designated_mount_point->mount_point,
1066 info_ptr->cgroup_path, pid, name);
1067 if (!tmp)
1068 return -1;
1069 free(info_ptr->cgroup_path);
1070 info_ptr->cgroup_path = tmp;
1071 r = lxc_grow_array((void ***)&info_ptr->created_paths, &info_ptr->created_paths_capacity, info_ptr->created_paths_count + 1, 8);
1072 if (r < 0)
1073 return -1;
1074 tmp = strdup(tmp);
1075 if (!tmp)
1076 return -1;
1077 info_ptr->created_paths[info_ptr->created_paths_count++] = tmp;
1078 }
1079 return 0;
1080}
1081
33ad9f1a 1082/* get the cgroup membership of a given container */
4fb3cba5 1083static struct cgroup_process_info *lxc_cgroup_get_container_info(const char *name, const char *lxcpath, struct cgroup_meta_data *meta_data)
c8f7c563 1084{
33ad9f1a
CS
1085 struct cgroup_process_info *result = NULL;
1086 int saved_errno = 0;
1087 size_t i;
1088 struct cgroup_process_info **cptr = &result;
1089 struct cgroup_process_info *entry = NULL;
1090 char *path = NULL;
1091
1092 for (i = 0; i <= meta_data->maximum_hierarchy; i++) {
1093 struct cgroup_hierarchy *h = meta_data->hierarchies[i];
1094 if (!h || !h->used)
1095 continue;
c8f7c563 1096
33ad9f1a
CS
1097 /* use the command interface to look for the cgroup */
1098 path = lxc_cmd_get_cgroup_path(name, lxcpath, h->subsystems[0]);
c661b0a8
DE
1099 if (!path) {
1100 h->used = false;
1101 WARN("Not attaching to cgroup %s unknown to %s %s", h->subsystems[0], lxcpath, name);
1102 continue;
1103 }
33ad9f1a
CS
1104
1105 entry = calloc(1, sizeof(struct cgroup_process_info));
1106 if (!entry)
1107 goto out_error;
1108 entry->meta_ref = lxc_cgroup_get_meta(meta_data);
1109 entry->hierarchy = h;
1110 entry->cgroup_path = path;
1111 path = NULL;
1112
1113 /* it is not an error if we don't find anything here,
1114 * it is up to the caller to decide what to do in that
1115 * case */
1116 entry->designated_mount_point = lxc_cgroup_find_mount_point(h, entry->cgroup_path, true);
1117
1118 *cptr = entry;
1119 cptr = &entry->next;
1120 entry = NULL;
c8f7c563
CS
1121 }
1122
33ad9f1a
CS
1123 return result;
1124out_error:
1125 saved_errno = errno;
1126 free(path);
1127 lxc_cgroup_process_info_free(result);
1128 lxc_cgroup_process_info_free(entry);
1129 errno = saved_errno;
1130 return NULL;
fd4f5a56
DL
1131}
1132
33ad9f1a 1133/* move a processs to the cgroups specified by the membership */
4fb3cba5 1134static int lxc_cgroupfs_enter(struct cgroup_process_info *info, pid_t pid, bool enter_sub)
4f17323e 1135{
33ad9f1a
CS
1136 char pid_buf[32];
1137 char *cgroup_tasks_fn;
1138 int r;
1139 struct cgroup_process_info *info_ptr;
1140
1141 snprintf(pid_buf, 32, "%lu", (unsigned long)pid);
1142 for (info_ptr = info; info_ptr; info_ptr = info_ptr->next) {
1143 char *cgroup_path = (enter_sub && info_ptr->cgroup_path_sub) ?
1144 info_ptr->cgroup_path_sub :
1145 info_ptr->cgroup_path;
1146
1147 if (!info_ptr->designated_mount_point) {
1148 info_ptr->designated_mount_point = lxc_cgroup_find_mount_point(info_ptr->hierarchy, cgroup_path, true);
1149 if (!info_ptr->designated_mount_point) {
1150 SYSERROR("Could not add pid %lu to cgroup %s: internal error (couldn't find any writable mountpoint to cgroup filesystem)", (unsigned long)pid, cgroup_path);
1151 return -1;
1152 }
1153 }
4f17323e 1154
33ad9f1a
CS
1155 cgroup_tasks_fn = cgroup_to_absolute_path(info_ptr->designated_mount_point, cgroup_path, "/tasks");
1156 if (!cgroup_tasks_fn) {
1157 SYSERROR("Could not add pid %lu to cgroup %s: internal error", (unsigned long)pid, cgroup_path);
1158 return -1;
1159 }
4f17323e 1160
33ad9f1a 1161 r = lxc_write_to_file(cgroup_tasks_fn, pid_buf, strlen(pid_buf), false);
5903da82 1162 free(cgroup_tasks_fn);
33ad9f1a
CS
1163 if (r < 0) {
1164 SYSERROR("Could not add pid %lu to cgroup %s: internal error", (unsigned long)pid, cgroup_path);
1165 return -1;
1166 }
4f17323e
CS
1167 }
1168
33ad9f1a 1169 return 0;
4f17323e
CS
1170}
1171
33ad9f1a
CS
1172/* free process membership information */
1173void lxc_cgroup_process_info_free(struct cgroup_process_info *info)
fc7de561 1174{
33ad9f1a
CS
1175 struct cgroup_process_info *next;
1176 if (!info)
b98f7d6e 1177 return;
33ad9f1a
CS
1178 next = info->next;
1179 lxc_cgroup_put_meta(info->meta_ref);
1180 free(info->cgroup_path);
1181 free(info->cgroup_path_sub);
1182 lxc_free_array((void **)info->created_paths, free);
1183 free(info);
1184 lxc_cgroup_process_info_free(next);
fc7de561
SH
1185}
1186
33ad9f1a
CS
1187/* free process membership information and remove cgroups that were created */
1188void lxc_cgroup_process_info_free_and_remove(struct cgroup_process_info *info)
b98f7d6e 1189{
33ad9f1a
CS
1190 struct cgroup_process_info *next;
1191 char **pp;
1192 if (!info)
1193 return;
1194 next = info->next;
603c64c2 1195 {
33ad9f1a
CS
1196 struct cgroup_mount_point *mp = info->designated_mount_point;
1197 if (!mp)
1198 mp = lxc_cgroup_find_mount_point(info->hierarchy, info->cgroup_path, true);
1199 if (mp)
1200 /* ignore return value here, perhaps we created the
1201 * '/lxc' cgroup in this container but another container
1202 * is still running (for example)
1203 */
603c64c2
SH
1204 (void)remove_cgroup(mp, info->cgroup_path, true);
1205 }
1206 for (pp = info->created_paths; pp && *pp; pp++);
1207 for ((void)(pp && --pp); info->created_paths && pp >= info->created_paths; --pp) {
33ad9f1a 1208 free(*pp);
b98f7d6e 1209 }
33ad9f1a
CS
1210 free(info->created_paths);
1211 lxc_cgroup_put_meta(info->meta_ref);
1212 free(info->cgroup_path);
1213 free(info->cgroup_path_sub);
1214 free(info);
9431aa65 1215 lxc_cgroup_process_info_free_and_remove(next);
33ad9f1a 1216}
b98f7d6e 1217
4fb3cba5 1218static char *lxc_cgroup_get_hierarchy_path_data(const char *subsystem, struct cgfs_data *d)
33ad9f1a 1219{
d4ef7c50
SH
1220 struct cgroup_process_info *info = d->info;
1221 info = find_info_for_subsystem(info, subsystem);
33ad9f1a
CS
1222 if (!info)
1223 return NULL;
f348e47c 1224 prune_init_scope(info->cgroup_path);
33ad9f1a 1225 return info->cgroup_path;
b98f7d6e
SH
1226}
1227
4fb3cba5 1228static char *lxc_cgroup_get_hierarchy_abs_path_data(const char *subsystem, struct cgfs_data *d)
b98f7d6e 1229{
d4ef7c50 1230 struct cgroup_process_info *info = d->info;
33ad9f1a 1231 struct cgroup_mount_point *mp = NULL;
d4ef7c50
SH
1232
1233 info = find_info_for_subsystem(info, subsystem);
33ad9f1a
CS
1234 if (!info)
1235 return NULL;
1236 if (info->designated_mount_point) {
8900b9eb 1237 mp = info->designated_mount_point;
33ad9f1a
CS
1238 } else {
1239 mp = lxc_cgroup_find_mount_point(info->hierarchy, info->cgroup_path, true);
1240 if (!mp)
1241 return NULL;
b98f7d6e 1242 }
33ad9f1a 1243 return cgroup_to_absolute_path(mp, info->cgroup_path, NULL);
b98f7d6e 1244}
55c76589 1245
4fb3cba5 1246static char *lxc_cgroup_get_hierarchy_abs_path(const char *subsystem, const char *name, const char *lxcpath)
9a93d992 1247{
33ad9f1a
CS
1248 struct cgroup_meta_data *meta;
1249 struct cgroup_process_info *base_info, *info;
1250 struct cgroup_mount_point *mp;
1251 char *result = NULL;
33ad9f1a
CS
1252
1253 meta = lxc_cgroup_load_meta();
1254 if (!meta)
9a93d992 1255 return NULL;
33ad9f1a
CS
1256 base_info = lxc_cgroup_get_container_info(name, lxcpath, meta);
1257 if (!base_info)
178938fe 1258 goto out1;
33ad9f1a
CS
1259 info = find_info_for_subsystem(base_info, subsystem);
1260 if (!info)
178938fe 1261 goto out2;
33ad9f1a 1262 if (info->designated_mount_point) {
8900b9eb 1263 mp = info->designated_mount_point;
33ad9f1a
CS
1264 } else {
1265 mp = lxc_cgroup_find_mount_point(info->hierarchy, info->cgroup_path, true);
1266 if (!mp)
178938fe 1267 goto out3;
33ad9f1a
CS
1268 }
1269 result = cgroup_to_absolute_path(mp, info->cgroup_path, NULL);
178938fe 1270out3:
178938fe 1271out2:
33ad9f1a 1272 lxc_cgroup_process_info_free(base_info);
178938fe 1273out1:
33ad9f1a 1274 lxc_cgroup_put_meta(meta);
33ad9f1a
CS
1275 return result;
1276}
9a93d992 1277
4fb3cba5 1278static int lxc_cgroup_set_data(const char *filename, const char *value, struct cgfs_data *d)
33ad9f1a
CS
1279{
1280 char *subsystem = NULL, *p, *path;
1281 int ret = -1;
9a93d992 1282
33ad9f1a
CS
1283 subsystem = alloca(strlen(filename) + 1);
1284 strcpy(subsystem, filename);
46cd2845 1285 if ((p = strchr(subsystem, '.')) != NULL)
33ad9f1a 1286 *p = '\0';
9a93d992 1287
4fb3cba5 1288 path = lxc_cgroup_get_hierarchy_abs_path_data(subsystem, d);
33ad9f1a
CS
1289 if (path) {
1290 ret = do_cgroup_set(path, filename, value);
1291 free(path);
9a93d992 1292 }
33ad9f1a
CS
1293 return ret;
1294}
9a93d992 1295
4fb3cba5 1296static int lxc_cgroupfs_set(const char *filename, const char *value, const char *name, const char *lxcpath)
9a93d992 1297{
33ad9f1a
CS
1298 char *subsystem = NULL, *p, *path;
1299 int ret = -1;
9a93d992 1300
33ad9f1a
CS
1301 subsystem = alloca(strlen(filename) + 1);
1302 strcpy(subsystem, filename);
46cd2845 1303 if ((p = strchr(subsystem, '.')) != NULL)
33ad9f1a 1304 *p = '\0';
9a93d992 1305
33ad9f1a
CS
1306 path = lxc_cgroup_get_hierarchy_abs_path(subsystem, name, lxcpath);
1307 if (path) {
1308 ret = do_cgroup_set(path, filename, value);
1309 free(path);
1310 }
b98f7d6e 1311 return ret;
9a93d992
SH
1312}
1313
4fb3cba5 1314static int lxc_cgroupfs_get(const char *filename, char *value, size_t len, const char *name, const char *lxcpath)
9a93d992 1315{
33ad9f1a
CS
1316 char *subsystem = NULL, *p, *path;
1317 int ret = -1;
1318
1319 subsystem = alloca(strlen(filename) + 1);
1320 strcpy(subsystem, filename);
46cd2845 1321 if ((p = strchr(subsystem, '.')) != NULL)
33ad9f1a
CS
1322 *p = '\0';
1323
1324 path = lxc_cgroup_get_hierarchy_abs_path(subsystem, name, lxcpath);
1325 if (path) {
1326 ret = do_cgroup_get(path, filename, value, len);
1327 free(path);
9a93d992 1328 }
33ad9f1a 1329 return ret;
9a93d992
SH
1330}
1331
4fb3cba5 1332static bool cgroupfs_mount_cgroup(void *hdata, const char *root, int type)
aae1f3c4
CS
1333{
1334 size_t bufsz = strlen(root) + sizeof("/sys/fs/cgroup");
1335 char *path = NULL;
1336 char **parts = NULL;
1337 char *dirname = NULL;
1338 char *abs_path = NULL;
1339 char *abs_path2 = NULL;
d4ef7c50
SH
1340 struct cgfs_data *cgfs_d;
1341 struct cgroup_process_info *info, *base_info;
aae1f3c4
CS
1342 int r, saved_errno = 0;
1343
4fb3cba5
DE
1344 cgfs_d = hdata;
1345 if (!cgfs_d)
1346 return false;
d4ef7c50
SH
1347 base_info = cgfs_d->info;
1348
0769b82a
CS
1349 /* If we get passed the _NOSPEC types, we default to _MIXED, since we don't
1350 * have access to the lxc_conf object at this point. It really should be up
1351 * to the caller to fix this, but this doesn't really hurt.
1352 */
1353 if (type == LXC_AUTO_CGROUP_FULL_NOSPEC)
1354 type = LXC_AUTO_CGROUP_FULL_MIXED;
1355 else if (type == LXC_AUTO_CGROUP_NOSPEC)
1356 type = LXC_AUTO_CGROUP_MIXED;
1357
7997d7da
CS
1358 if (type < LXC_AUTO_CGROUP_RO || type > LXC_AUTO_CGROUP_FULL_MIXED) {
1359 ERROR("could not mount cgroups into container: invalid type specified internally");
1360 errno = EINVAL;
c476bdce 1361 return false;
7997d7da
CS
1362 }
1363
aae1f3c4
CS
1364 path = calloc(1, bufsz);
1365 if (!path)
c476bdce 1366 return false;
aae1f3c4 1367 snprintf(path, bufsz, "%s/sys/fs/cgroup", root);
592fd47a
SH
1368 r = safe_mount("cgroup_root", path, "tmpfs",
1369 MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_RELATIME,
1370 "size=10240k,mode=755",
1371 root);
aae1f3c4
CS
1372 if (r < 0) {
1373 SYSERROR("could not mount tmpfs to /sys/fs/cgroup in the container");
c476bdce 1374 return false;
aae1f3c4
CS
1375 }
1376
1377 /* now mount all the hierarchies we care about */
1378 for (info = base_info; info; info = info->next) {
1379 size_t subsystem_count, i;
1380 struct cgroup_mount_point *mp = info->designated_mount_point;
1381 if (!mp)
1382 mp = lxc_cgroup_find_mount_point(info->hierarchy, info->cgroup_path, true);
1383 if (!mp) {
1384 SYSERROR("could not find original mount point for cgroup hierarchy while trying to mount cgroup filesystem");
1385 goto out_error;
1386 }
1387
1388 subsystem_count = lxc_array_len((void **)info->hierarchy->subsystems);
1389 parts = calloc(subsystem_count + 1, sizeof(char *));
1390 if (!parts)
1391 goto out_error;
1392
1393 for (i = 0; i < subsystem_count; i++) {
1394 if (!strncmp(info->hierarchy->subsystems[i], "name=", 5))
1395 parts[i] = info->hierarchy->subsystems[i] + 5;
1396 else
1397 parts[i] = info->hierarchy->subsystems[i];
1398 }
1399 dirname = lxc_string_join(",", (const char **)parts, false);
1400 if (!dirname)
1401 goto out_error;
1402
1403 /* create subsystem directory */
1404 abs_path = lxc_append_paths(path, dirname);
1405 if (!abs_path)
1406 goto out_error;
1407 r = mkdir_p(abs_path, 0755);
1408 if (r < 0 && errno != EEXIST) {
1409 SYSERROR("could not create cgroup subsystem directory /sys/fs/cgroup/%s", dirname);
1410 goto out_error;
1411 }
1412
aae1f3c4
CS
1413 abs_path2 = lxc_append_paths(abs_path, info->cgroup_path);
1414 if (!abs_path2)
1415 goto out_error;
aae1f3c4 1416
7997d7da
CS
1417 if (type == LXC_AUTO_CGROUP_FULL_RO || type == LXC_AUTO_CGROUP_FULL_RW || type == LXC_AUTO_CGROUP_FULL_MIXED) {
1418 /* bind-mount the cgroup entire filesystem there */
1419 if (strcmp(mp->mount_prefix, "/") != 0) {
1420 /* FIXME: maybe we should just try to remount the entire hierarchy
1421 * with a regular mount command? may that works? */
1422 ERROR("could not automatically mount cgroup-full to /sys/fs/cgroup/%s: host has no mount point for this cgroup filesystem that has access to the root cgroup", dirname);
1423 goto out_error;
1424 }
1425 r = mount(mp->mount_point, abs_path, "none", MS_BIND, 0);
1426 if (r < 0) {
1427 SYSERROR("error bind-mounting %s to %s", mp->mount_point, abs_path);
1428 goto out_error;
1429 }
f8f3c3c0
SG
1430 /* main cgroup path should be read-only */
1431 if (type == LXC_AUTO_CGROUP_FULL_RO || type == LXC_AUTO_CGROUP_FULL_MIXED) {
1432 r = mount(NULL, abs_path, NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL);
1433 if (r < 0) {
1434 SYSERROR("error re-mounting %s readonly", abs_path);
1435 goto out_error;
1436 }
1437 }
7997d7da
CS
1438 /* own cgroup should be read-write */
1439 if (type == LXC_AUTO_CGROUP_FULL_MIXED) {
1440 r = mount(abs_path2, abs_path2, NULL, MS_BIND, NULL);
1441 if (r < 0) {
1442 SYSERROR("error bind-mounting %s onto itself", abs_path2);
1443 goto out_error;
1444 }
1445 r = mount(NULL, abs_path2, NULL, MS_REMOUNT|MS_BIND, NULL);
1446 if (r < 0) {
1447 SYSERROR("error re-mounting %s readwrite", abs_path2);
1448 goto out_error;
1449 }
1450 }
1451 } else {
1452 /* create path for container's cgroup */
1453 r = mkdir_p(abs_path2, 0755);
1454 if (r < 0 && errno != EEXIST) {
1455 SYSERROR("could not create cgroup directory /sys/fs/cgroup/%s%s", dirname, info->cgroup_path);
1456 goto out_error;
1457 }
aae1f3c4 1458
b46f0553
CS
1459 /* for read-only and mixed cases, we have to bind-mount the tmpfs directory
1460 * that points to the hierarchy itself (i.e. /sys/fs/cgroup/cpu etc.) onto
1461 * itself and then bind-mount it read-only, since we keep the tmpfs itself
1462 * read-write (see comment below)
1463 */
1464 if (type == LXC_AUTO_CGROUP_MIXED || type == LXC_AUTO_CGROUP_RO) {
1465 r = mount(abs_path, abs_path, NULL, MS_BIND, NULL);
1466 if (r < 0) {
1467 SYSERROR("error bind-mounting %s onto itself", abs_path);
1468 goto out_error;
1469 }
1470 r = mount(NULL, abs_path, NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL);
1471 if (r < 0) {
1472 SYSERROR("error re-mounting %s readonly", abs_path);
1473 goto out_error;
1474 }
1475 }
1476
7997d7da
CS
1477 free(abs_path);
1478 abs_path = NULL;
1479
1480 /* bind-mount container's cgroup to that directory */
1481 abs_path = cgroup_to_absolute_path(mp, info->cgroup_path, NULL);
1482 if (!abs_path)
1483 goto out_error;
1484 r = mount(abs_path, abs_path2, "none", MS_BIND, 0);
1485 if (r < 0) {
1486 SYSERROR("error bind-mounting %s to %s", abs_path, abs_path2);
1487 goto out_error;
1488 }
1489 if (type == LXC_AUTO_CGROUP_RO) {
1490 r = mount(NULL, abs_path2, NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL);
1491 if (r < 0) {
1492 SYSERROR("error re-mounting %s readonly", abs_path2);
1493 goto out_error;
1494 }
1495 }
aae1f3c4
CS
1496 }
1497
1498 free(abs_path);
1499 free(abs_path2);
1500 abs_path = NULL;
1501 abs_path2 = NULL;
1502
1503 /* add symlinks for every single subsystem */
1504 if (subsystem_count > 1) {
1505 for (i = 0; i < subsystem_count; i++) {
1506 abs_path = lxc_append_paths(path, parts[i]);
1507 if (!abs_path)
1508 goto out_error;
1509 r = symlink(dirname, abs_path);
1510 if (r < 0)
1511 WARN("could not create symlink %s -> %s in /sys/fs/cgroup of container", parts[i], dirname);
1512 free(abs_path);
1513 abs_path = NULL;
1514 }
1515 }
1516 free(dirname);
1517 free(parts);
1518 dirname = NULL;
1519 parts = NULL;
1520 }
1521
b46f0553
CS
1522 /* We used to remount the entire tmpfs readonly if any :ro or
1523 * :mixed mode was specified. However, Ubuntu's mountall has the
1524 * unfortunate behavior to block bootup if /sys/fs/cgroup is
1525 * mounted read-only and cannot be remounted read-write.
1526 * (mountall reads /lib/init/fstab and tries to (re-)mount all of
1527 * these if they are not already mounted with the right options;
1528 * it contains an entry for /sys/fs/cgroup. In case it can't do
1529 * that, it prompts for the user to either manually fix it or
1530 * boot anyway. But without user input, booting of the container
1531 * hangs.)
1532 *
1533 * Instead of remounting the entire tmpfs readonly, we only
1534 * remount the paths readonly that are part of the cgroup
1535 * hierarchy.
f8f3c3c0 1536 */
f8f3c3c0 1537
aae1f3c4
CS
1538 free(path);
1539
c476bdce 1540 return true;
aae1f3c4
CS
1541
1542out_error:
1543 saved_errno = errno;
1544 free(path);
1545 free(dirname);
1546 free(parts);
1547 free(abs_path);
1548 free(abs_path2);
1549 errno = saved_errno;
c476bdce 1550 return false;
aae1f3c4
CS
1551}
1552
4fb3cba5 1553static int cgfs_nrtasks(void *hdata)
33ad9f1a 1554{
4fb3cba5
DE
1555 struct cgfs_data *d = hdata;
1556 struct cgroup_process_info *info;
33ad9f1a
CS
1557 struct cgroup_mount_point *mp = NULL;
1558 char *abs_path = NULL;
1559 int ret;
460a1cf0 1560
4fb3cba5
DE
1561 if (!d) {
1562 errno = ENOENT;
1563 return -1;
1564 }
1565
1566 info = d->info;
33ad9f1a
CS
1567 if (!info) {
1568 errno = ENOENT;
1569 return -1;
b98f7d6e 1570 }
c8f7c563 1571
33ad9f1a 1572 if (info->designated_mount_point) {
8900b9eb 1573 mp = info->designated_mount_point;
33ad9f1a
CS
1574 } else {
1575 mp = lxc_cgroup_find_mount_point(info->hierarchy, info->cgroup_path, false);
1576 if (!mp)
1577 return -1;
c8f7c563
CS
1578 }
1579
33ad9f1a
CS
1580 abs_path = cgroup_to_absolute_path(mp, info->cgroup_path, NULL);
1581 if (!abs_path)
1582 return -1;
1583
1584 ret = cgroup_recursive_task_count(abs_path);
1585 free(abs_path);
1586 return ret;
c8f7c563
CS
1587}
1588
574c4428
QH
1589static struct cgroup_process_info *
1590lxc_cgroup_process_info_getx(const char *proc_pid_cgroup_str,
1591 struct cgroup_meta_data *meta)
d08ba6ec 1592{
33ad9f1a
CS
1593 struct cgroup_process_info *result = NULL;
1594 FILE *proc_pid_cgroup = NULL;
1595 char *line = NULL;
1596 size_t sz = 0;
1597 int saved_errno = 0;
1598 struct cgroup_process_info **cptr = &result;
1599 struct cgroup_process_info *entry = NULL;
1600
1601 proc_pid_cgroup = fopen_cloexec(proc_pid_cgroup_str, "r");
1602 if (!proc_pid_cgroup)
b98f7d6e 1603 return NULL;
1ac470c0 1604
33ad9f1a
CS
1605 while (getline(&line, &sz, proc_pid_cgroup) != -1) {
1606 /* file format: hierarchy:subsystems:group */
1607 char *colon1;
1608 char *colon2;
1609 char *endptr;
1610 int hierarchy_number;
1611 struct cgroup_hierarchy *h = NULL;
fd4f5a56 1612
33ad9f1a 1613 if (!line[0])
ae5c8b8e 1614 continue;
b98f7d6e 1615
33ad9f1a
CS
1616 if (line[strlen(line) - 1] == '\n')
1617 line[strlen(line) - 1] = '\0';
1618
1619 colon1 = strchr(line, ':');
1620 if (!colon1)
8900b9eb 1621 continue;
33ad9f1a
CS
1622 *colon1++ = '\0';
1623 colon2 = strchr(colon1, ':');
1624 if (!colon2)
ae5c8b8e 1625 continue;
33ad9f1a 1626 *colon2++ = '\0';
e4659536 1627
33ad9f1a
CS
1628 endptr = NULL;
1629 hierarchy_number = strtoul(line, &endptr, 10);
1630 if (!endptr || *endptr)
9a93d992 1631 continue;
9a93d992 1632
33ad9f1a
CS
1633 if (hierarchy_number > meta->maximum_hierarchy) {
1634 /* we encountered a hierarchy we didn't have before,
1635 * so probably somebody remounted some stuff in the
1636 * mean time...
1637 */
1638 errno = EAGAIN;
1639 goto out_error;
b98f7d6e 1640 }
33ad9f1a
CS
1641
1642 h = meta->hierarchies[hierarchy_number];
1643 if (!h) {
1644 /* we encountered a hierarchy that was thought to be
1645 * dead before, so probably somebody remounted some
1646 * stuff in the mean time...
1647 */
1648 errno = EAGAIN;
1649 goto out_error;
b98f7d6e 1650 }
33ad9f1a
CS
1651
1652 /* we are told that we should ignore this hierarchy */
1653 if (!h->used)
b98f7d6e 1654 continue;
5193cc3d 1655
33ad9f1a
CS
1656 entry = calloc(1, sizeof(struct cgroup_process_info));
1657 if (!entry)
1658 goto out_error;
fd4f5a56 1659
33ad9f1a
CS
1660 entry->meta_ref = lxc_cgroup_get_meta(meta);
1661 entry->hierarchy = h;
1662 entry->cgroup_path = strdup(colon2);
1663 if (!entry->cgroup_path)
1664 goto out_error;
d08ba6ec 1665
33ad9f1a
CS
1666 *cptr = entry;
1667 cptr = &entry->next;
1668 entry = NULL;
b98f7d6e 1669 }
b98f7d6e 1670
33ad9f1a
CS
1671 fclose(proc_pid_cgroup);
1672 free(line);
1673 return result;
1674
1675out_error:
1676 saved_errno = errno;
1677 if (proc_pid_cgroup)
1678 fclose(proc_pid_cgroup);
1679 lxc_cgroup_process_info_free(result);
1680 lxc_cgroup_process_info_free(entry);
1681 free(line);
1682 errno = saved_errno;
ae5c8b8e 1683 return NULL;
36b86299
DL
1684}
1685
574c4428
QH
1686static char **subsystems_from_mount_options(const char *mount_options,
1687 char **kernel_list)
36b86299 1688{
33ad9f1a
CS
1689 char *token, *str, *saveptr = NULL;
1690 char **result = NULL;
1691 size_t result_capacity = 0;
8900b9eb 1692 size_t result_count = 0;
33ad9f1a
CS
1693 int saved_errno;
1694 int r;
ef342abb 1695
33ad9f1a
CS
1696 str = alloca(strlen(mount_options)+1);
1697 strcpy(str, mount_options);
1698 for (; (token = strtok_r(str, ",", &saveptr)); str = NULL) {
1699 /* we have a subsystem if it's either in the list of
1700 * subsystems provided by the kernel OR if it starts
1701 * with name= for named hierarchies
1702 */
1703 if (!strncmp(token, "name=", 5) || lxc_string_in_array(token, (const char **)kernel_list)) {
1704 r = lxc_grow_array((void ***)&result, &result_capacity, result_count + 1, 12);
1705 if (r < 0)
1706 goto out_free;
1707 result[result_count + 1] = NULL;
1708 result[result_count] = strdup(token);
1709 if (!result[result_count])
1710 goto out_free;
1711 result_count++;
1712 }
ae5c8b8e 1713 }
f0e64b8b 1714
33ad9f1a
CS
1715 return result;
1716
1717out_free:
1718 saved_errno = errno;
1719 lxc_free_array((void**)result, free);
1720 errno = saved_errno;
1721 return NULL;
b98f7d6e
SH
1722}
1723
574c4428 1724static void lxc_cgroup_mount_point_free(struct cgroup_mount_point *mp)
b98f7d6e 1725{
33ad9f1a
CS
1726 if (!mp)
1727 return;
1728 free(mp->mount_point);
1729 free(mp->mount_prefix);
1730 free(mp);
bcbd102c
SH
1731}
1732
574c4428 1733static void lxc_cgroup_hierarchy_free(struct cgroup_hierarchy *h)
341a9bd8 1734{
33ad9f1a
CS
1735 if (!h)
1736 return;
1737 lxc_free_array((void **)h->subsystems, free);
8bfcb981 1738 free(h->all_mount_points);
33ad9f1a
CS
1739 free(h);
1740}
341a9bd8 1741
574c4428 1742static bool is_valid_cgroup(const char *name)
33ad9f1a
CS
1743{
1744 const char *p;
1745 for (p = name; *p; p++) {
28bb9321
QH
1746 /* Use the ASCII printable characters range(32 - 127)
1747 * is reasonable, we kick out 32(SPACE) because it'll
1748 * break legacy lxc-ls
1749 */
1750 if (*p <= 32 || *p >= 127 || *p == '/')
33ad9f1a 1751 return false;
341a9bd8 1752 }
33ad9f1a
CS
1753 return strcmp(name, ".") != 0 && strcmp(name, "..") != 0;
1754}
341a9bd8 1755
574c4428
QH
1756static int create_or_remove_cgroup(bool do_remove,
1757 struct cgroup_mount_point *mp, const char *path, int recurse)
33ad9f1a
CS
1758{
1759 int r, saved_errno = 0;
1760 char *buf = cgroup_to_absolute_path(mp, path, NULL);
1761 if (!buf)
1762 return -1;
341a9bd8 1763
33ad9f1a 1764 /* create or remove directory */
603c64c2
SH
1765 if (do_remove) {
1766 if (recurse)
1767 r = cgroup_rmdir(buf);
1768 else
1769 r = rmdir(buf);
1770 } else
1771 r = mkdir(buf, 0777);
33ad9f1a
CS
1772 saved_errno = errno;
1773 free(buf);
1774 errno = saved_errno;
1775 return r;
341a9bd8 1776}
bcbd102c 1777
574c4428 1778static int create_cgroup(struct cgroup_mount_point *mp, const char *path)
a6ddef61 1779{
603c64c2 1780 return create_or_remove_cgroup(false, mp, path, false);
a6ddef61
MN
1781}
1782
574c4428
QH
1783static int remove_cgroup(struct cgroup_mount_point *mp,
1784 const char *path, bool recurse)
576f946d 1785{
603c64c2 1786 return create_or_remove_cgroup(true, mp, path, recurse);
33ad9f1a 1787}
576f946d 1788
574c4428
QH
1789static char *cgroup_to_absolute_path(struct cgroup_mount_point *mp,
1790 const char *path, const char *suffix)
33ad9f1a
CS
1791{
1792 /* first we have to make sure we subtract the mount point's prefix */
1793 char *prefix = mp->mount_prefix;
1794 char *buf;
1795 ssize_t len, rv;
1796
1797 /* we want to make sure only absolute paths to cgroups are passed to us */
1798 if (path[0] != '/') {
1799 errno = EINVAL;
1800 return NULL;
1801 }
b98f7d6e 1802
33ad9f1a
CS
1803 if (prefix && !strcmp(prefix, "/"))
1804 prefix = NULL;
b98f7d6e 1805
33ad9f1a
CS
1806 /* prefix doesn't match */
1807 if (prefix && strncmp(prefix, path, strlen(prefix)) != 0) {
1808 errno = EINVAL;
1809 return NULL;
1810 }
1811 /* if prefix is /foo and path is /foobar */
1812 if (prefix && path[strlen(prefix)] != '/' && path[strlen(prefix)] != '\0') {
1813 errno = EINVAL;
1814 return NULL;
1815 }
b98f7d6e 1816
33ad9f1a
CS
1817 /* remove prefix from path */
1818 path += prefix ? strlen(prefix) : 0;
b98f7d6e 1819
33ad9f1a
CS
1820 len = strlen(mp->mount_point) + strlen(path) + (suffix ? strlen(suffix) : 0);
1821 buf = calloc(len + 1, 1);
50266dc6
DE
1822 if (!buf)
1823 return NULL;
33ad9f1a 1824 rv = snprintf(buf, len + 1, "%s%s%s", mp->mount_point, path, suffix ? suffix : "");
8900b9eb 1825 if (rv > len) {
33ad9f1a
CS
1826 free(buf);
1827 errno = ENOMEM;
8900b9eb 1828 return NULL;
8b92dc3a 1829 }
576f946d 1830
33ad9f1a 1831 return buf;
e0f888d9 1832}
283678ed 1833
574c4428
QH
1834static struct cgroup_process_info *
1835find_info_for_subsystem(struct cgroup_process_info *info, const char *subsystem)
283678ed 1836{
33ad9f1a
CS
1837 struct cgroup_process_info *info_ptr;
1838 for (info_ptr = info; info_ptr; info_ptr = info_ptr->next) {
1839 struct cgroup_hierarchy *h = info_ptr->hierarchy;
1840 if (lxc_string_in_array(subsystem, (const char **)h->subsystems))
1841 return info_ptr;
b98f7d6e 1842 }
33ad9f1a
CS
1843 errno = ENOENT;
1844 return NULL;
1845}
283678ed 1846
574c4428
QH
1847static int do_cgroup_get(const char *cgroup_path, const char *sub_filename,
1848 char *value, size_t len)
33ad9f1a
CS
1849{
1850 const char *parts[3] = {
1851 cgroup_path,
1852 sub_filename,
1853 NULL
1854 };
1855 char *filename;
1856 int ret, saved_errno;
1857
1858 filename = lxc_string_join("/", parts, false);
1859 if (!filename)
1860 return -1;
1861
1862 ret = lxc_read_from_file(filename, value, len);
1863 saved_errno = errno;
1864 free(filename);
1865 errno = saved_errno;
1866 return ret;
283678ed 1867}
b113383b 1868
574c4428
QH
1869static int do_cgroup_set(const char *cgroup_path, const char *sub_filename,
1870 const char *value)
b113383b 1871{
33ad9f1a
CS
1872 const char *parts[3] = {
1873 cgroup_path,
1874 sub_filename,
1875 NULL
1876 };
1877 char *filename;
1878 int ret, saved_errno;
b113383b 1879
33ad9f1a
CS
1880 filename = lxc_string_join("/", parts, false);
1881 if (!filename)
1882 return -1;
b113383b 1883
33ad9f1a
CS
1884 ret = lxc_write_to_file(filename, value, strlen(value), false);
1885 saved_errno = errno;
1886 free(filename);
1887 errno = saved_errno;
1888 return ret;
b98f7d6e
SH
1889}
1890
4fb3cba5 1891static int do_setup_cgroup_limits(struct cgfs_data *d,
574c4428 1892 struct lxc_list *cgroup_settings, bool do_devices)
b98f7d6e 1893{
365d180a 1894 struct lxc_list *iterator, *sorted_cgroup_settings, *next;
b98f7d6e
SH
1895 struct lxc_cgroup *cg;
1896 int ret = -1;
1897
33ad9f1a 1898 if (lxc_list_empty(cgroup_settings))
b98f7d6e
SH
1899 return 0;
1900
aaf26830 1901 sorted_cgroup_settings = sort_cgroup_settings(cgroup_settings);
fac7c663
KT
1902 if (!sorted_cgroup_settings) {
1903 return -1;
1904 }
aaf26830
KT
1905
1906 lxc_list_for_each(iterator, sorted_cgroup_settings) {
b98f7d6e
SH
1907 cg = iterator->elem;
1908
33ad9f1a 1909 if (do_devices == !strncmp("devices", cg->subsystem, 7)) {
b98f7d6e 1910 if (strcmp(cg->subsystem, "devices.deny") == 0 &&
4fb3cba5 1911 cgroup_devices_has_allow_or_deny(d, cg->value, false))
b98f7d6e
SH
1912 continue;
1913 if (strcmp(cg->subsystem, "devices.allow") == 0 &&
4fb3cba5 1914 cgroup_devices_has_allow_or_deny(d, cg->value, true))
b98f7d6e 1915 continue;
4fb3cba5 1916 if (lxc_cgroup_set_data(cg->subsystem, cg->value, d)) {
959aee9c 1917 ERROR("Error setting %s to %s for %s",
4fb3cba5 1918 cg->subsystem, cg->value, d->name);
b98f7d6e
SH
1919 goto out;
1920 }
b113383b 1921 }
b98f7d6e
SH
1922
1923 DEBUG("cgroup '%s' set to '%s'", cg->subsystem, cg->value);
b113383b
SH
1924 }
1925
b98f7d6e
SH
1926 ret = 0;
1927 INFO("cgroup has been setup");
1928out:
365d180a 1929 lxc_list_for_each_safe(iterator, sorted_cgroup_settings, next) {
aaf26830
KT
1930 lxc_list_del(iterator);
1931 free(iterator);
1932 }
365d180a 1933 free(sorted_cgroup_settings);
b113383b
SH
1934 return ret;
1935}
b98f7d6e 1936
4fb3cba5 1937static bool cgroup_devices_has_allow_or_deny(struct cgfs_data *d,
574c4428 1938 char *v, bool for_allow)
33ad9f1a
CS
1939{
1940 char *path;
1941 FILE *devices_list;
8900b9eb 1942 char *line = NULL;
33ad9f1a
CS
1943 size_t sz = 0;
1944 bool ret = !for_allow;
1945 const char *parts[3] = {
1946 NULL,
1947 "devices.list",
1948 NULL
1949 };
1950
1951 // XXX FIXME if users could use something other than 'lxc.devices.deny = a'.
1952 // not sure they ever do, but they *could*
1953 // right now, I'm assuming they do NOT
1954 if (!for_allow && strcmp(v, "a") != 0 && strcmp(v, "a *:* rwm") != 0)
1955 return false;
1956
4fb3cba5 1957 parts[0] = (const char *)lxc_cgroup_get_hierarchy_abs_path_data("devices", d);
33ad9f1a
CS
1958 if (!parts[0])
1959 return false;
1960 path = lxc_string_join("/", parts, false);
1961 if (!path) {
1962 free((void *)parts[0]);
1963 return false;
1964 }
1965
1966 devices_list = fopen_cloexec(path, "r");
1967 if (!devices_list) {
1968 free(path);
1969 return false;
1970 }
1971
1972 while (getline(&line, &sz, devices_list) != -1) {
1973 size_t len = strlen(line);
1974 if (len > 0 && line[len-1] == '\n')
1975 line[len-1] = '\0';
1976 if (strcmp(line, "a *:* rwm") == 0) {
1977 ret = for_allow;
1978 goto out;
1979 } else if (for_allow && strcmp(line, v) == 0) {
1980 ret = true;
8900b9eb 1981 goto out;
33ad9f1a
CS
1982 }
1983 }
1984
1985out:
1986 fclose(devices_list);
1987 free(line);
1988 free(path);
1989 return ret;
1990}
1991
574c4428 1992static int cgroup_recursive_task_count(const char *cgroup_path)
b98f7d6e 1993{
33ad9f1a
CS
1994 DIR *d;
1995 struct dirent *dent_buf;
1996 struct dirent *dent;
8900b9eb 1997 ssize_t name_max;
33ad9f1a
CS
1998 int n = 0, r;
1999
2000 /* see man readdir_r(3) */
2001 name_max = pathconf(cgroup_path, _PC_NAME_MAX);
2002 if (name_max <= 0)
2003 name_max = 255;
2004 dent_buf = malloc(offsetof(struct dirent, d_name) + name_max + 1);
2005 if (!dent_buf)
2006 return -1;
2007
2008 d = opendir(cgroup_path);
034ef75d
SH
2009 if (!d) {
2010 free(dent_buf);
33ad9f1a 2011 return 0;
034ef75d 2012 }
33ad9f1a
CS
2013
2014 while (readdir_r(d, dent_buf, &dent) == 0 && dent) {
2015 const char *parts[3] = {
2016 cgroup_path,
2017 dent->d_name,
2018 NULL
2019 };
2020 char *sub_path;
2021 struct stat st;
2022
2023 if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
2024 continue;
2025 sub_path = lxc_string_join("/", parts, false);
2026 if (!sub_path) {
2027 closedir(d);
2028 free(dent_buf);
2029 return -1;
2030 }
2031 r = stat(sub_path, &st);
2032 if (r < 0) {
2033 closedir(d);
2034 free(dent_buf);
2035 free(sub_path);
2036 return -1;
2037 }
2038 if (S_ISDIR(st.st_mode)) {
2039 r = cgroup_recursive_task_count(sub_path);
2040 if (r >= 0)
2041 n += r;
2042 } else if (!strcmp(dent->d_name, "tasks")) {
2043 r = count_lines(sub_path);
2044 if (r >= 0)
2045 n += r;
2046 }
2047 free(sub_path);
2048 }
2049 closedir(d);
2050 free(dent_buf);
2051
2052 return n;
2053}
2054
574c4428 2055static int count_lines(const char *fn)
33ad9f1a
CS
2056{
2057 FILE *f;
2058 char *line = NULL;
2059 size_t sz = 0;
2060 int n = 0;
2061
2062 f = fopen_cloexec(fn, "r");
2063 if (!f)
2064 return -1;
2065
2066 while (getline(&line, &sz, f) != -1) {
2067 n++;
2068 }
2069 free(line);
2070 fclose(f);
2071 return n;
b98f7d6e
SH
2072}
2073
574c4428
QH
2074static int handle_cgroup_settings(struct cgroup_mount_point *mp,
2075 char *cgroup_path)
b98f7d6e 2076{
33ad9f1a 2077 int r, saved_errno = 0;
7e7243e1 2078 char buf[2];
1ea59ad2 2079
934b1673
SH
2080 mp->need_cpuset_init = false;
2081
1ea59ad2
SH
2082 /* If this is the memory cgroup, we want to enforce hierarchy.
2083 * But don't fail if for some reason we can't.
2084 */
2edb53c7
SH
2085 if (lxc_string_in_array("memory", (const char **)mp->hierarchy->subsystems)) {
2086 char *cc_path = cgroup_to_absolute_path(mp, cgroup_path, "/memory.use_hierarchy");
2087 if (cc_path) {
2088 r = lxc_read_from_file(cc_path, buf, 1);
2089 if (r < 1 || buf[0] != '1') {
2090 r = lxc_write_to_file(cc_path, "1", 1, false);
2091 if (r < 0)
a8916143 2092 SYSERROR("failed to set memory.use_hierarchy to 1; continuing");
2edb53c7 2093 }
1ea59ad2
SH
2094 free(cc_path);
2095 }
2edb53c7 2096 }
1ea59ad2 2097
33ad9f1a
CS
2098 /* if this is a cpuset hierarchy, we have to set cgroup.clone_children in
2099 * the base cgroup, otherwise containers will start with an empty cpuset.mems
2100 * and cpuset.cpus and then
2101 */
2edb53c7
SH
2102 if (lxc_string_in_array("cpuset", (const char **)mp->hierarchy->subsystems)) {
2103 char *cc_path = cgroup_to_absolute_path(mp, cgroup_path, "/cgroup.clone_children");
d703c2b1
RV
2104 struct stat sb;
2105
33ad9f1a 2106 if (!cc_path)
2edb53c7 2107 return -1;
d703c2b1
RV
2108 /* cgroup.clone_children is not available when running under
2109 * older kernel versions; in this case, we'll initialize
2110 * cpuset.cpus and cpuset.mems later, after the new cgroup
2111 * was created
2112 */
2113 if (stat(cc_path, &sb) != 0 && errno == ENOENT) {
934b1673 2114 mp->need_cpuset_init = true;
d703c2b1
RV
2115 free(cc_path);
2116 return 0;
2117 }
7e7243e1
SH
2118 r = lxc_read_from_file(cc_path, buf, 1);
2119 if (r == 1 && buf[0] == '1') {
2120 free(cc_path);
2edb53c7 2121 return 0;
7e7243e1 2122 }
33ad9f1a 2123 r = lxc_write_to_file(cc_path, "1", 1, false);
2edb53c7
SH
2124 saved_errno = errno;
2125 free(cc_path);
2126 errno = saved_errno;
2127 return r < 0 ? -1 : 0;
33ad9f1a
CS
2128 }
2129 return 0;
b98f7d6e 2130}
484ed030 2131
934b1673 2132static int cgroup_read_from_file(const char *fn, char buf[], size_t bufsize)
d703c2b1
RV
2133{
2134 int ret = lxc_read_from_file(fn, buf, bufsize);
2135 if (ret < 0) {
2136 SYSERROR("failed to read %s", fn);
934b1673 2137 return ret;
d703c2b1
RV
2138 }
2139 if (ret == bufsize) {
934b1673
SH
2140 if (bufsize > 0) {
2141 /* obviously this wasn't empty */
2142 buf[bufsize-1] = '\0';
2143 return ret;
2144 }
2145 /* Callers don't do this, but regression/sanity check */
2146 ERROR("%s: was not expecting 0 bufsize", __func__);
2147 return -1;
d703c2b1
RV
2148 }
2149 buf[ret] = '\0';
934b1673 2150 return ret;
d703c2b1
RV
2151}
2152
2153static bool do_init_cpuset_file(struct cgroup_mount_point *mp,
2154 const char *path, const char *name)
2155{
934b1673
SH
2156 char value[1024];
2157 char *childfile, *parentfile = NULL, *tmp;
2158 int ret;
2159 bool ok = false;
2160
d703c2b1
RV
2161 childfile = cgroup_to_absolute_path(mp, path, name);
2162 if (!childfile)
2163 return false;
2164
2165 /* don't overwrite a non-empty value in the file */
934b1673
SH
2166 ret = cgroup_read_from_file(childfile, value, sizeof(value));
2167 if (ret < 0)
2168 goto out;
d703c2b1 2169 if (value[0] != '\0' && value[0] != '\n') {
934b1673
SH
2170 ok = true;
2171 goto out;
d703c2b1
RV
2172 }
2173
2174 /* path to the same name in the parent cgroup */
2175 parentfile = strdup(path);
2176 if (!parentfile)
934b1673
SH
2177 goto out;
2178
d703c2b1 2179 tmp = strrchr(parentfile, '/');
934b1673
SH
2180 if (!tmp)
2181 goto out;
d703c2b1
RV
2182 if (tmp == parentfile)
2183 tmp++; /* keep the '/' at the start */
2184 *tmp = '\0';
2185 tmp = parentfile;
2186 parentfile = cgroup_to_absolute_path(mp, tmp, name);
2187 free(tmp);
934b1673
SH
2188 if (!parentfile)
2189 goto out;
d703c2b1
RV
2190
2191 /* copy from parent to child cgroup */
934b1673
SH
2192 ret = cgroup_read_from_file(parentfile, value, sizeof(value));
2193 if (ret < 0)
2194 goto out;
2195 if (ret == sizeof(value)) {
2196 /* If anyone actually sees this error, we can address it */
2197 ERROR("parent cpuset value too long");
2198 goto out;
d703c2b1
RV
2199 }
2200 ok = (lxc_write_to_file(childfile, value, strlen(value), false) >= 0);
2201 if (!ok)
2202 SYSERROR("failed writing %s", childfile);
b1dad6f6
RV
2203
2204out:
f10fad2f 2205 free(parentfile);
d703c2b1 2206 free(childfile);
d703c2b1
RV
2207 return ok;
2208}
2209
2210static bool init_cpuset_if_needed(struct cgroup_mount_point *mp,
2211 const char *path)
2212{
2213 /* the files we have to handle here are only in cpuset hierarchies */
2214 if (!lxc_string_in_array("cpuset",
2215 (const char **)mp->hierarchy->subsystems))
2216 return true;
2217
b1dad6f6
RV
2218 if (!mp->need_cpuset_init)
2219 return true;
2220
d703c2b1
RV
2221 return (do_init_cpuset_file(mp, path, "/cpuset.cpus") &&
2222 do_init_cpuset_file(mp, path, "/cpuset.mems") );
2223}
2224
4fb3cba5 2225struct cgroup_ops *cgfs_ops_init(void)
484ed030 2226{
4fb3cba5 2227 return &cgfs_ops;
d4ef7c50 2228}
484ed030 2229
4fb3cba5 2230static void *cgfs_init(const char *name)
d4ef7c50 2231{
4fb3cba5 2232 struct cgfs_data *d;
484ed030 2233
4fb3cba5
DE
2234 d = malloc(sizeof(*d));
2235 if (!d)
2236 return NULL;
484ed030 2237
4fb3cba5
DE
2238 memset(d, 0, sizeof(*d));
2239 d->name = strdup(name);
2240 if (!d->name)
2241 goto err1;
2242
5e1c5795 2243 d->cgroup_pattern = lxc_global_config_value("lxc.cgroup.pattern");
4fb3cba5
DE
2244
2245 d->meta = lxc_cgroup_load_meta();
2246 if (!d->meta) {
2247 ERROR("cgroupfs failed to detect cgroup metadata");
2248 goto err2;
2249 }
2250 return d;
2251
2252err2:
2253 free(d->name);
2254err1:
2255 free(d);
2256 return NULL;
d4ef7c50 2257}
484ed030 2258
4fb3cba5 2259static void cgfs_destroy(void *hdata)
d4ef7c50 2260{
4fb3cba5
DE
2261 struct cgfs_data *d = hdata;
2262
d4ef7c50
SH
2263 if (!d)
2264 return;
f10fad2f 2265 free(d->name);
c55d4505
ME
2266 lxc_cgroup_process_info_free_and_remove(d->info);
2267 lxc_cgroup_put_meta(d->meta);
d4ef7c50 2268 free(d);
d4ef7c50 2269}
484ed030 2270
4fb3cba5 2271static inline bool cgfs_create(void *hdata)
d4ef7c50 2272{
4fb3cba5
DE
2273 struct cgfs_data *d = hdata;
2274 struct cgroup_process_info *i;
2275 struct cgroup_meta_data *md;
484ed030 2276
4fb3cba5 2277 if (!d)
d4ef7c50 2278 return false;
4fb3cba5
DE
2279 md = d->meta;
2280 i = lxc_cgroupfs_create(d->name, d->cgroup_pattern, md, NULL);
d4ef7c50
SH
2281 if (!i)
2282 return false;
2283 d->info = i;
2284 return true;
2285}
484ed030 2286
4fb3cba5 2287static inline bool cgfs_enter(void *hdata, pid_t pid)
d4ef7c50 2288{
4fb3cba5
DE
2289 struct cgfs_data *d = hdata;
2290 struct cgroup_process_info *i;
d4ef7c50 2291 int ret;
4fb3cba5
DE
2292
2293 if (!d)
2294 return false;
2295 i = d->info;
2296 ret = lxc_cgroupfs_enter(i, pid, false);
484ed030 2297
d4ef7c50
SH
2298 return ret == 0;
2299}
2300
4fb3cba5 2301static inline bool cgfs_create_legacy(void *hdata, pid_t pid)
d4ef7c50 2302{
4fb3cba5
DE
2303 struct cgfs_data *d = hdata;
2304 struct cgroup_process_info *i;
2305
2306 if (!d)
2307 return false;
2308 i = d->info;
2309 if (lxc_cgroup_create_legacy(i, d->name, pid) < 0) {
2310 ERROR("failed to create legacy ns cgroups for '%s'", d->name);
d4ef7c50 2311 return false;
484ed030 2312 }
d4ef7c50
SH
2313 return true;
2314}
484ed030 2315
4fb3cba5 2316static const char *cgfs_get_cgroup(void *hdata, const char *subsystem)
d4ef7c50 2317{
4fb3cba5
DE
2318 struct cgfs_data *d = hdata;
2319
2320 if (!d)
2321 return NULL;
2322 return lxc_cgroup_get_hierarchy_path_data(subsystem, d);
484ed030
SH
2323}
2324
2ba7a429
TA
2325static const char *cgfs_canonical_path(void *hdata)
2326{
2327 struct cgfs_data *d = hdata;
2328 struct cgroup_process_info *info_ptr;
2329 char *path = NULL;
2330
2331 if (!d)
2332 return NULL;
2333
2334 for (info_ptr = d->info; info_ptr; info_ptr = info_ptr->next) {
2335 if (!path)
2336 path = info_ptr->cgroup_path;
2337 else if (strcmp(path, info_ptr->cgroup_path) != 0) {
2338 ERROR("not all paths match %s, %s has path %s", path,
2339 info_ptr->hierarchy->subsystems[0], info_ptr->cgroup_path);
2340 return NULL;
2341 }
2342 }
2343
2344 return path;
2345}
2346
06078509
TA
2347static bool cgfs_escape(void)
2348{
2349 struct cgroup_meta_data *md;
2350 int i;
2351 bool ret = false;
2352
2353 md = lxc_cgroup_load_meta();
2354 if (!md)
2355 return false;
2356
2357 for (i = 1; i <= md->maximum_hierarchy; i++) {
2358 struct cgroup_hierarchy *h = md->hierarchies[i];
2359 struct cgroup_mount_point *mp;
2360 char *tasks;
2361 FILE *f;
2362 int written;
2363
2364 if (!h) {
2365 WARN("not escaping hierarchy %d", i);
2366 continue;
2367 }
2368
2369 mp = lxc_cgroup_find_mount_point(h, "/", true);
2370 if (!mp)
2371 goto out;
2372
2373 tasks = cgroup_to_absolute_path(mp, "/", "tasks");
2374 if (!tasks)
2375 goto out;
2376
2377 f = fopen(tasks, "a");
2378 free(tasks);
2379 if (!f)
2380 goto out;
2381
2382 written = fprintf(f, "%d\n", getpid());
2383 fclose(f);
2384 if (written < 0) {
2385 SYSERROR("writing tasks failed\n");
2386 goto out;
2387 }
2388 }
2389
2390 ret = true;
2391out:
2392 lxc_cgroup_put_meta(md);
2393 return ret;
2394}
2395
4fb3cba5 2396static bool cgfs_unfreeze(void *hdata)
0086f499 2397{
4fb3cba5 2398 struct cgfs_data *d = hdata;
0086f499
SH
2399 char *cgabspath, *cgrelpath;
2400 int ret;
2401
4fb3cba5
DE
2402 if (!d)
2403 return false;
2404
2405 cgrelpath = lxc_cgroup_get_hierarchy_path_data("freezer", d);
0086f499
SH
2406 cgabspath = lxc_cgroup_find_abs_path("freezer", cgrelpath, true, NULL);
2407 if (!cgabspath)
ecfcb3f0 2408 return false;
0086f499
SH
2409
2410 ret = do_cgroup_set(cgabspath, "freezer.state", "THAWED");
2411 free(cgabspath);
ecfcb3f0 2412 return ret == 0;
0086f499
SH
2413}
2414
4fb3cba5
DE
2415static bool cgroupfs_setup_limits(void *hdata, struct lxc_list *cgroup_conf,
2416 bool with_devices)
9daf6f5d 2417{
4fb3cba5
DE
2418 struct cgfs_data *d = hdata;
2419
2420 if (!d)
2421 return false;
2422 return do_setup_cgroup_limits(d, cgroup_conf, with_devices) == 0;
9daf6f5d
SH
2423}
2424
4fb3cba5 2425static bool lxc_cgroupfs_attach(const char *name, const char *lxcpath, pid_t pid)
5d897655
SH
2426{
2427 struct cgroup_meta_data *meta_data;
2428 struct cgroup_process_info *container_info;
2429 int ret;
2430
2431 meta_data = lxc_cgroup_load_meta();
2432 if (!meta_data) {
2433 ERROR("could not move attached process %d to cgroup of container", pid);
2434 return false;
2435 }
2436
2437 container_info = lxc_cgroup_get_container_info(name, lxcpath, meta_data);
2438 lxc_cgroup_put_meta(meta_data);
2439 if (!container_info) {
2440 ERROR("could not move attached process %d to cgroup of container", pid);
2441 return false;
2442 }
2443
2444 ret = lxc_cgroupfs_enter(container_info, pid, false);
2445 lxc_cgroup_process_info_free(container_info);
2446 if (ret < 0) {
2447 ERROR("could not move attached process %d to cgroup of container", pid);
2448 return false;
2449 }
2450 return true;
2451}
2452
8b276860
SH
2453struct chown_data {
2454 const char *cgroup_path;
2455 uid_t origuid;
2456};
2457
2458/*
2459 * TODO - someone should refactor this to unshare once passing all the paths
2460 * to be chowned in one go
2461 */
2462static int chown_cgroup_wrapper(void *data)
2463{
2464 struct chown_data *arg = data;
2465 uid_t destuid;
2466 char *fpath;
2467
2468
2469 if (setresgid(0,0,0) < 0)
2470 SYSERROR("Failed to setgid to 0");
2471 if (setresuid(0,0,0) < 0)
2472 SYSERROR("Failed to setuid to 0");
2473 if (setgroups(0, NULL) < 0)
2474 SYSERROR("Failed to clear groups");
2475 destuid = get_ns_uid(arg->origuid);
2476
2477 if (chown(arg->cgroup_path, destuid, 0) < 0)
2478 SYSERROR("Failed chowning %s to %d", arg->cgroup_path, (int)destuid);
2479
2480 fpath = lxc_append_paths(arg->cgroup_path, "tasks");
2481 if (!fpath)
2482 return -1;
2483 if (chown(fpath, destuid, 0) < 0)
2484 SYSERROR("Error chowning %s\n", fpath);
2485 free(fpath);
2486 fpath = lxc_append_paths(arg->cgroup_path, "cgroup.procs");
2487 if (!fpath)
2488 return -1;
2489 if (chown(fpath, destuid, 0) < 0)
2490 SYSERROR("Error chowning %s", fpath);
2491 free(fpath);
2492
2493 return 0;
2494}
2495
2496static bool do_cgfs_chown(char *cgroup_path, struct lxc_conf *conf)
2497{
2498 struct chown_data data;
2499 char *fpath;
2500
2501 if (lxc_list_empty(&conf->id_map))
2502 /* If there's no mapping then we don't need to chown */
2503 return true;
2504
2505 data.cgroup_path = cgroup_path;
2506 data.origuid = geteuid();
2507
2508 /* Unpriv users can't chown it themselves, so chown from
2509 * a child namespace mapping both our own and the target uid
2510 */
2511 if (userns_exec_1(conf, chown_cgroup_wrapper, &data) < 0) {
2512 ERROR("Error requesting cgroup chown in new namespace");
2513 return false;
2514 }
2515
2516 /*
2517 * Now chmod 775 the directory else the container cannot create cgroups.
2518 * This can't be done in the child namespace because it only group-owns
2519 * the cgroup
2520 */
2521 if (chmod(cgroup_path, 0775) < 0) {
2522 SYSERROR("Error chmoding %s\n", cgroup_path);
2523 return false;
2524 }
2525 fpath = lxc_append_paths(cgroup_path, "tasks");
2526 if (!fpath)
2527 return false;
2528 if (chmod(fpath, 0664) < 0)
2529 SYSERROR("Error chmoding %s\n", fpath);
2530 free(fpath);
2531 fpath = lxc_append_paths(cgroup_path, "cgroup.procs");
2532 if (!fpath)
2533 return false;
2534 if (chmod(fpath, 0664) < 0)
2535 SYSERROR("Error chmoding %s\n", fpath);
2536 free(fpath);
2537
2538 return true;
2539}
2540
2541static bool cgfs_chown(void *hdata, struct lxc_conf *conf)
2542{
2543 struct cgfs_data *d = hdata;
2544 struct cgroup_process_info *info_ptr;
2545 char *cgpath;
2546 bool r = true;
2547
2548 if (!d)
2549 return false;
2550
2551 for (info_ptr = d->info; info_ptr; info_ptr = info_ptr->next) {
2552 if (!info_ptr->designated_mount_point) {
2553 info_ptr->designated_mount_point = lxc_cgroup_find_mount_point(info_ptr->hierarchy, info_ptr->cgroup_path, true);
2554 if (!info_ptr->designated_mount_point) {
2555 SYSERROR("Could not chown cgroup %s: internal error (couldn't find any writable mountpoint to cgroup filesystem)", info_ptr->cgroup_path);
2556 return false;
2557 }
2558 }
2559
2560 cgpath = cgroup_to_absolute_path(info_ptr->designated_mount_point, info_ptr->cgroup_path, NULL);
2561 if (!cgpath) {
2562 SYSERROR("Could not chown cgroup %s: internal error", info_ptr->cgroup_path);
2563 continue;
2564 }
2565 r = do_cgfs_chown(cgpath, conf);
2566 if (!r) {
2567 ERROR("Failed chowning %s\n", cgpath);
2568 free(cgpath);
2569 return false;
2570 }
2571 free(cgpath);
2572 }
2573
2574 return true;
2575}
2576
d4ef7c50 2577static struct cgroup_ops cgfs_ops = {
d4ef7c50 2578 .init = cgfs_init,
4fb3cba5 2579 .destroy = cgfs_destroy,
d4ef7c50
SH
2580 .create = cgfs_create,
2581 .enter = cgfs_enter,
2582 .create_legacy = cgfs_create_legacy,
2583 .get_cgroup = cgfs_get_cgroup,
2ba7a429 2584 .canonical_path = cgfs_canonical_path,
06078509 2585 .escape = cgfs_escape,
d4ef7c50
SH
2586 .get = lxc_cgroupfs_get,
2587 .set = lxc_cgroupfs_set,
4fb3cba5 2588 .unfreeze = cgfs_unfreeze,
9daf6f5d 2589 .setup_limits = cgroupfs_setup_limits,
d4ef7c50 2590 .name = "cgroupfs",
5d897655 2591 .attach = lxc_cgroupfs_attach,
8b276860 2592 .chown = cgfs_chown,
c476bdce 2593 .mount_cgroup = cgroupfs_mount_cgroup,
4fb3cba5 2594 .nrtasks = cgfs_nrtasks,
23befb18 2595 .driver = CGFS,
d4ef7c50 2596};