]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/cgfs.c
Merge pull request #826 from brauner/2016-02-19/exec_cast_null
[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;
3939a22a 1665 prune_init_scope(entry->cgroup_path);
d08ba6ec 1666
33ad9f1a
CS
1667 *cptr = entry;
1668 cptr = &entry->next;
1669 entry = NULL;
b98f7d6e 1670 }
b98f7d6e 1671
33ad9f1a
CS
1672 fclose(proc_pid_cgroup);
1673 free(line);
1674 return result;
1675
1676out_error:
1677 saved_errno = errno;
1678 if (proc_pid_cgroup)
1679 fclose(proc_pid_cgroup);
1680 lxc_cgroup_process_info_free(result);
1681 lxc_cgroup_process_info_free(entry);
1682 free(line);
1683 errno = saved_errno;
ae5c8b8e 1684 return NULL;
36b86299
DL
1685}
1686
574c4428
QH
1687static char **subsystems_from_mount_options(const char *mount_options,
1688 char **kernel_list)
36b86299 1689{
33ad9f1a
CS
1690 char *token, *str, *saveptr = NULL;
1691 char **result = NULL;
1692 size_t result_capacity = 0;
8900b9eb 1693 size_t result_count = 0;
33ad9f1a
CS
1694 int saved_errno;
1695 int r;
ef342abb 1696
33ad9f1a
CS
1697 str = alloca(strlen(mount_options)+1);
1698 strcpy(str, mount_options);
1699 for (; (token = strtok_r(str, ",", &saveptr)); str = NULL) {
1700 /* we have a subsystem if it's either in the list of
1701 * subsystems provided by the kernel OR if it starts
1702 * with name= for named hierarchies
1703 */
1704 if (!strncmp(token, "name=", 5) || lxc_string_in_array(token, (const char **)kernel_list)) {
1705 r = lxc_grow_array((void ***)&result, &result_capacity, result_count + 1, 12);
1706 if (r < 0)
1707 goto out_free;
1708 result[result_count + 1] = NULL;
1709 result[result_count] = strdup(token);
1710 if (!result[result_count])
1711 goto out_free;
1712 result_count++;
1713 }
ae5c8b8e 1714 }
f0e64b8b 1715
33ad9f1a
CS
1716 return result;
1717
1718out_free:
1719 saved_errno = errno;
1720 lxc_free_array((void**)result, free);
1721 errno = saved_errno;
1722 return NULL;
b98f7d6e
SH
1723}
1724
574c4428 1725static void lxc_cgroup_mount_point_free(struct cgroup_mount_point *mp)
b98f7d6e 1726{
33ad9f1a
CS
1727 if (!mp)
1728 return;
1729 free(mp->mount_point);
1730 free(mp->mount_prefix);
1731 free(mp);
bcbd102c
SH
1732}
1733
574c4428 1734static void lxc_cgroup_hierarchy_free(struct cgroup_hierarchy *h)
341a9bd8 1735{
33ad9f1a
CS
1736 if (!h)
1737 return;
1738 lxc_free_array((void **)h->subsystems, free);
8bfcb981 1739 free(h->all_mount_points);
33ad9f1a
CS
1740 free(h);
1741}
341a9bd8 1742
574c4428 1743static bool is_valid_cgroup(const char *name)
33ad9f1a
CS
1744{
1745 const char *p;
1746 for (p = name; *p; p++) {
28bb9321
QH
1747 /* Use the ASCII printable characters range(32 - 127)
1748 * is reasonable, we kick out 32(SPACE) because it'll
1749 * break legacy lxc-ls
1750 */
1751 if (*p <= 32 || *p >= 127 || *p == '/')
33ad9f1a 1752 return false;
341a9bd8 1753 }
33ad9f1a
CS
1754 return strcmp(name, ".") != 0 && strcmp(name, "..") != 0;
1755}
341a9bd8 1756
574c4428
QH
1757static int create_or_remove_cgroup(bool do_remove,
1758 struct cgroup_mount_point *mp, const char *path, int recurse)
33ad9f1a
CS
1759{
1760 int r, saved_errno = 0;
1761 char *buf = cgroup_to_absolute_path(mp, path, NULL);
1762 if (!buf)
1763 return -1;
341a9bd8 1764
33ad9f1a 1765 /* create or remove directory */
603c64c2
SH
1766 if (do_remove) {
1767 if (recurse)
1768 r = cgroup_rmdir(buf);
1769 else
1770 r = rmdir(buf);
1771 } else
1772 r = mkdir(buf, 0777);
33ad9f1a
CS
1773 saved_errno = errno;
1774 free(buf);
1775 errno = saved_errno;
1776 return r;
341a9bd8 1777}
bcbd102c 1778
574c4428 1779static int create_cgroup(struct cgroup_mount_point *mp, const char *path)
a6ddef61 1780{
603c64c2 1781 return create_or_remove_cgroup(false, mp, path, false);
a6ddef61
MN
1782}
1783
574c4428
QH
1784static int remove_cgroup(struct cgroup_mount_point *mp,
1785 const char *path, bool recurse)
576f946d 1786{
603c64c2 1787 return create_or_remove_cgroup(true, mp, path, recurse);
33ad9f1a 1788}
576f946d 1789
574c4428
QH
1790static char *cgroup_to_absolute_path(struct cgroup_mount_point *mp,
1791 const char *path, const char *suffix)
33ad9f1a
CS
1792{
1793 /* first we have to make sure we subtract the mount point's prefix */
1794 char *prefix = mp->mount_prefix;
1795 char *buf;
1796 ssize_t len, rv;
1797
1798 /* we want to make sure only absolute paths to cgroups are passed to us */
1799 if (path[0] != '/') {
1800 errno = EINVAL;
1801 return NULL;
1802 }
b98f7d6e 1803
33ad9f1a
CS
1804 if (prefix && !strcmp(prefix, "/"))
1805 prefix = NULL;
b98f7d6e 1806
33ad9f1a
CS
1807 /* prefix doesn't match */
1808 if (prefix && strncmp(prefix, path, strlen(prefix)) != 0) {
1809 errno = EINVAL;
1810 return NULL;
1811 }
1812 /* if prefix is /foo and path is /foobar */
1813 if (prefix && path[strlen(prefix)] != '/' && path[strlen(prefix)] != '\0') {
1814 errno = EINVAL;
1815 return NULL;
1816 }
b98f7d6e 1817
33ad9f1a
CS
1818 /* remove prefix from path */
1819 path += prefix ? strlen(prefix) : 0;
b98f7d6e 1820
33ad9f1a
CS
1821 len = strlen(mp->mount_point) + strlen(path) + (suffix ? strlen(suffix) : 0);
1822 buf = calloc(len + 1, 1);
50266dc6
DE
1823 if (!buf)
1824 return NULL;
33ad9f1a 1825 rv = snprintf(buf, len + 1, "%s%s%s", mp->mount_point, path, suffix ? suffix : "");
8900b9eb 1826 if (rv > len) {
33ad9f1a
CS
1827 free(buf);
1828 errno = ENOMEM;
8900b9eb 1829 return NULL;
8b92dc3a 1830 }
576f946d 1831
33ad9f1a 1832 return buf;
e0f888d9 1833}
283678ed 1834
574c4428
QH
1835static struct cgroup_process_info *
1836find_info_for_subsystem(struct cgroup_process_info *info, const char *subsystem)
283678ed 1837{
33ad9f1a
CS
1838 struct cgroup_process_info *info_ptr;
1839 for (info_ptr = info; info_ptr; info_ptr = info_ptr->next) {
1840 struct cgroup_hierarchy *h = info_ptr->hierarchy;
1841 if (lxc_string_in_array(subsystem, (const char **)h->subsystems))
1842 return info_ptr;
b98f7d6e 1843 }
33ad9f1a
CS
1844 errno = ENOENT;
1845 return NULL;
1846}
283678ed 1847
574c4428
QH
1848static int do_cgroup_get(const char *cgroup_path, const char *sub_filename,
1849 char *value, size_t len)
33ad9f1a
CS
1850{
1851 const char *parts[3] = {
1852 cgroup_path,
1853 sub_filename,
1854 NULL
1855 };
1856 char *filename;
1857 int ret, saved_errno;
1858
1859 filename = lxc_string_join("/", parts, false);
1860 if (!filename)
1861 return -1;
1862
1863 ret = lxc_read_from_file(filename, value, len);
1864 saved_errno = errno;
1865 free(filename);
1866 errno = saved_errno;
1867 return ret;
283678ed 1868}
b113383b 1869
574c4428
QH
1870static int do_cgroup_set(const char *cgroup_path, const char *sub_filename,
1871 const char *value)
b113383b 1872{
33ad9f1a
CS
1873 const char *parts[3] = {
1874 cgroup_path,
1875 sub_filename,
1876 NULL
1877 };
1878 char *filename;
1879 int ret, saved_errno;
b113383b 1880
33ad9f1a
CS
1881 filename = lxc_string_join("/", parts, false);
1882 if (!filename)
1883 return -1;
b113383b 1884
33ad9f1a
CS
1885 ret = lxc_write_to_file(filename, value, strlen(value), false);
1886 saved_errno = errno;
1887 free(filename);
1888 errno = saved_errno;
1889 return ret;
b98f7d6e
SH
1890}
1891
4fb3cba5 1892static int do_setup_cgroup_limits(struct cgfs_data *d,
574c4428 1893 struct lxc_list *cgroup_settings, bool do_devices)
b98f7d6e 1894{
365d180a 1895 struct lxc_list *iterator, *sorted_cgroup_settings, *next;
b98f7d6e
SH
1896 struct lxc_cgroup *cg;
1897 int ret = -1;
1898
33ad9f1a 1899 if (lxc_list_empty(cgroup_settings))
b98f7d6e
SH
1900 return 0;
1901
aaf26830 1902 sorted_cgroup_settings = sort_cgroup_settings(cgroup_settings);
fac7c663
KT
1903 if (!sorted_cgroup_settings) {
1904 return -1;
1905 }
aaf26830
KT
1906
1907 lxc_list_for_each(iterator, sorted_cgroup_settings) {
b98f7d6e
SH
1908 cg = iterator->elem;
1909
33ad9f1a 1910 if (do_devices == !strncmp("devices", cg->subsystem, 7)) {
b98f7d6e 1911 if (strcmp(cg->subsystem, "devices.deny") == 0 &&
4fb3cba5 1912 cgroup_devices_has_allow_or_deny(d, cg->value, false))
b98f7d6e
SH
1913 continue;
1914 if (strcmp(cg->subsystem, "devices.allow") == 0 &&
4fb3cba5 1915 cgroup_devices_has_allow_or_deny(d, cg->value, true))
b98f7d6e 1916 continue;
4fb3cba5 1917 if (lxc_cgroup_set_data(cg->subsystem, cg->value, d)) {
959aee9c 1918 ERROR("Error setting %s to %s for %s",
4fb3cba5 1919 cg->subsystem, cg->value, d->name);
b98f7d6e
SH
1920 goto out;
1921 }
b113383b 1922 }
b98f7d6e
SH
1923
1924 DEBUG("cgroup '%s' set to '%s'", cg->subsystem, cg->value);
b113383b
SH
1925 }
1926
b98f7d6e
SH
1927 ret = 0;
1928 INFO("cgroup has been setup");
1929out:
365d180a 1930 lxc_list_for_each_safe(iterator, sorted_cgroup_settings, next) {
aaf26830
KT
1931 lxc_list_del(iterator);
1932 free(iterator);
1933 }
365d180a 1934 free(sorted_cgroup_settings);
b113383b
SH
1935 return ret;
1936}
b98f7d6e 1937
4fb3cba5 1938static bool cgroup_devices_has_allow_or_deny(struct cgfs_data *d,
574c4428 1939 char *v, bool for_allow)
33ad9f1a
CS
1940{
1941 char *path;
1942 FILE *devices_list;
8900b9eb 1943 char *line = NULL;
33ad9f1a
CS
1944 size_t sz = 0;
1945 bool ret = !for_allow;
1946 const char *parts[3] = {
1947 NULL,
1948 "devices.list",
1949 NULL
1950 };
1951
1952 // XXX FIXME if users could use something other than 'lxc.devices.deny = a'.
1953 // not sure they ever do, but they *could*
1954 // right now, I'm assuming they do NOT
1955 if (!for_allow && strcmp(v, "a") != 0 && strcmp(v, "a *:* rwm") != 0)
1956 return false;
1957
4fb3cba5 1958 parts[0] = (const char *)lxc_cgroup_get_hierarchy_abs_path_data("devices", d);
33ad9f1a
CS
1959 if (!parts[0])
1960 return false;
1961 path = lxc_string_join("/", parts, false);
1962 if (!path) {
1963 free((void *)parts[0]);
1964 return false;
1965 }
1966
1967 devices_list = fopen_cloexec(path, "r");
1968 if (!devices_list) {
1969 free(path);
1970 return false;
1971 }
1972
1973 while (getline(&line, &sz, devices_list) != -1) {
1974 size_t len = strlen(line);
1975 if (len > 0 && line[len-1] == '\n')
1976 line[len-1] = '\0';
1977 if (strcmp(line, "a *:* rwm") == 0) {
1978 ret = for_allow;
1979 goto out;
1980 } else if (for_allow && strcmp(line, v) == 0) {
1981 ret = true;
8900b9eb 1982 goto out;
33ad9f1a
CS
1983 }
1984 }
1985
1986out:
1987 fclose(devices_list);
1988 free(line);
1989 free(path);
1990 return ret;
1991}
1992
574c4428 1993static int cgroup_recursive_task_count(const char *cgroup_path)
b98f7d6e 1994{
33ad9f1a
CS
1995 DIR *d;
1996 struct dirent *dent_buf;
1997 struct dirent *dent;
8900b9eb 1998 ssize_t name_max;
33ad9f1a
CS
1999 int n = 0, r;
2000
2001 /* see man readdir_r(3) */
2002 name_max = pathconf(cgroup_path, _PC_NAME_MAX);
2003 if (name_max <= 0)
2004 name_max = 255;
2005 dent_buf = malloc(offsetof(struct dirent, d_name) + name_max + 1);
2006 if (!dent_buf)
2007 return -1;
2008
2009 d = opendir(cgroup_path);
034ef75d
SH
2010 if (!d) {
2011 free(dent_buf);
33ad9f1a 2012 return 0;
034ef75d 2013 }
33ad9f1a
CS
2014
2015 while (readdir_r(d, dent_buf, &dent) == 0 && dent) {
2016 const char *parts[3] = {
2017 cgroup_path,
2018 dent->d_name,
2019 NULL
2020 };
2021 char *sub_path;
2022 struct stat st;
2023
2024 if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
2025 continue;
2026 sub_path = lxc_string_join("/", parts, false);
2027 if (!sub_path) {
2028 closedir(d);
2029 free(dent_buf);
2030 return -1;
2031 }
2032 r = stat(sub_path, &st);
2033 if (r < 0) {
2034 closedir(d);
2035 free(dent_buf);
2036 free(sub_path);
2037 return -1;
2038 }
2039 if (S_ISDIR(st.st_mode)) {
2040 r = cgroup_recursive_task_count(sub_path);
2041 if (r >= 0)
2042 n += r;
2043 } else if (!strcmp(dent->d_name, "tasks")) {
2044 r = count_lines(sub_path);
2045 if (r >= 0)
2046 n += r;
2047 }
2048 free(sub_path);
2049 }
2050 closedir(d);
2051 free(dent_buf);
2052
2053 return n;
2054}
2055
574c4428 2056static int count_lines(const char *fn)
33ad9f1a
CS
2057{
2058 FILE *f;
2059 char *line = NULL;
2060 size_t sz = 0;
2061 int n = 0;
2062
2063 f = fopen_cloexec(fn, "r");
2064 if (!f)
2065 return -1;
2066
2067 while (getline(&line, &sz, f) != -1) {
2068 n++;
2069 }
2070 free(line);
2071 fclose(f);
2072 return n;
b98f7d6e
SH
2073}
2074
574c4428
QH
2075static int handle_cgroup_settings(struct cgroup_mount_point *mp,
2076 char *cgroup_path)
b98f7d6e 2077{
33ad9f1a 2078 int r, saved_errno = 0;
7e7243e1 2079 char buf[2];
1ea59ad2 2080
934b1673
SH
2081 mp->need_cpuset_init = false;
2082
1ea59ad2
SH
2083 /* If this is the memory cgroup, we want to enforce hierarchy.
2084 * But don't fail if for some reason we can't.
2085 */
2edb53c7
SH
2086 if (lxc_string_in_array("memory", (const char **)mp->hierarchy->subsystems)) {
2087 char *cc_path = cgroup_to_absolute_path(mp, cgroup_path, "/memory.use_hierarchy");
2088 if (cc_path) {
2089 r = lxc_read_from_file(cc_path, buf, 1);
2090 if (r < 1 || buf[0] != '1') {
2091 r = lxc_write_to_file(cc_path, "1", 1, false);
2092 if (r < 0)
a8916143 2093 SYSERROR("failed to set memory.use_hierarchy to 1; continuing");
2edb53c7 2094 }
1ea59ad2
SH
2095 free(cc_path);
2096 }
2edb53c7 2097 }
1ea59ad2 2098
33ad9f1a
CS
2099 /* if this is a cpuset hierarchy, we have to set cgroup.clone_children in
2100 * the base cgroup, otherwise containers will start with an empty cpuset.mems
2101 * and cpuset.cpus and then
2102 */
2edb53c7
SH
2103 if (lxc_string_in_array("cpuset", (const char **)mp->hierarchy->subsystems)) {
2104 char *cc_path = cgroup_to_absolute_path(mp, cgroup_path, "/cgroup.clone_children");
d703c2b1
RV
2105 struct stat sb;
2106
33ad9f1a 2107 if (!cc_path)
2edb53c7 2108 return -1;
d703c2b1
RV
2109 /* cgroup.clone_children is not available when running under
2110 * older kernel versions; in this case, we'll initialize
2111 * cpuset.cpus and cpuset.mems later, after the new cgroup
2112 * was created
2113 */
2114 if (stat(cc_path, &sb) != 0 && errno == ENOENT) {
934b1673 2115 mp->need_cpuset_init = true;
d703c2b1
RV
2116 free(cc_path);
2117 return 0;
2118 }
7e7243e1
SH
2119 r = lxc_read_from_file(cc_path, buf, 1);
2120 if (r == 1 && buf[0] == '1') {
2121 free(cc_path);
2edb53c7 2122 return 0;
7e7243e1 2123 }
33ad9f1a 2124 r = lxc_write_to_file(cc_path, "1", 1, false);
2edb53c7
SH
2125 saved_errno = errno;
2126 free(cc_path);
2127 errno = saved_errno;
2128 return r < 0 ? -1 : 0;
33ad9f1a
CS
2129 }
2130 return 0;
b98f7d6e 2131}
484ed030 2132
934b1673 2133static int cgroup_read_from_file(const char *fn, char buf[], size_t bufsize)
d703c2b1
RV
2134{
2135 int ret = lxc_read_from_file(fn, buf, bufsize);
2136 if (ret < 0) {
2137 SYSERROR("failed to read %s", fn);
934b1673 2138 return ret;
d703c2b1
RV
2139 }
2140 if (ret == bufsize) {
934b1673
SH
2141 if (bufsize > 0) {
2142 /* obviously this wasn't empty */
2143 buf[bufsize-1] = '\0';
2144 return ret;
2145 }
2146 /* Callers don't do this, but regression/sanity check */
2147 ERROR("%s: was not expecting 0 bufsize", __func__);
2148 return -1;
d703c2b1
RV
2149 }
2150 buf[ret] = '\0';
934b1673 2151 return ret;
d703c2b1
RV
2152}
2153
2154static bool do_init_cpuset_file(struct cgroup_mount_point *mp,
2155 const char *path, const char *name)
2156{
934b1673
SH
2157 char value[1024];
2158 char *childfile, *parentfile = NULL, *tmp;
2159 int ret;
2160 bool ok = false;
2161
d703c2b1
RV
2162 childfile = cgroup_to_absolute_path(mp, path, name);
2163 if (!childfile)
2164 return false;
2165
2166 /* don't overwrite a non-empty value in the file */
934b1673
SH
2167 ret = cgroup_read_from_file(childfile, value, sizeof(value));
2168 if (ret < 0)
2169 goto out;
d703c2b1 2170 if (value[0] != '\0' && value[0] != '\n') {
934b1673
SH
2171 ok = true;
2172 goto out;
d703c2b1
RV
2173 }
2174
2175 /* path to the same name in the parent cgroup */
2176 parentfile = strdup(path);
2177 if (!parentfile)
934b1673
SH
2178 goto out;
2179
d703c2b1 2180 tmp = strrchr(parentfile, '/');
934b1673
SH
2181 if (!tmp)
2182 goto out;
d703c2b1
RV
2183 if (tmp == parentfile)
2184 tmp++; /* keep the '/' at the start */
2185 *tmp = '\0';
2186 tmp = parentfile;
2187 parentfile = cgroup_to_absolute_path(mp, tmp, name);
2188 free(tmp);
934b1673
SH
2189 if (!parentfile)
2190 goto out;
d703c2b1
RV
2191
2192 /* copy from parent to child cgroup */
934b1673
SH
2193 ret = cgroup_read_from_file(parentfile, value, sizeof(value));
2194 if (ret < 0)
2195 goto out;
2196 if (ret == sizeof(value)) {
2197 /* If anyone actually sees this error, we can address it */
2198 ERROR("parent cpuset value too long");
2199 goto out;
d703c2b1
RV
2200 }
2201 ok = (lxc_write_to_file(childfile, value, strlen(value), false) >= 0);
2202 if (!ok)
2203 SYSERROR("failed writing %s", childfile);
b1dad6f6
RV
2204
2205out:
f10fad2f 2206 free(parentfile);
d703c2b1 2207 free(childfile);
d703c2b1
RV
2208 return ok;
2209}
2210
2211static bool init_cpuset_if_needed(struct cgroup_mount_point *mp,
2212 const char *path)
2213{
2214 /* the files we have to handle here are only in cpuset hierarchies */
2215 if (!lxc_string_in_array("cpuset",
2216 (const char **)mp->hierarchy->subsystems))
2217 return true;
2218
b1dad6f6
RV
2219 if (!mp->need_cpuset_init)
2220 return true;
2221
d703c2b1
RV
2222 return (do_init_cpuset_file(mp, path, "/cpuset.cpus") &&
2223 do_init_cpuset_file(mp, path, "/cpuset.mems") );
2224}
2225
4fb3cba5 2226struct cgroup_ops *cgfs_ops_init(void)
484ed030 2227{
4fb3cba5 2228 return &cgfs_ops;
d4ef7c50 2229}
484ed030 2230
4fb3cba5 2231static void *cgfs_init(const char *name)
d4ef7c50 2232{
4fb3cba5 2233 struct cgfs_data *d;
484ed030 2234
4fb3cba5
DE
2235 d = malloc(sizeof(*d));
2236 if (!d)
2237 return NULL;
484ed030 2238
4fb3cba5
DE
2239 memset(d, 0, sizeof(*d));
2240 d->name = strdup(name);
2241 if (!d->name)
2242 goto err1;
2243
5e1c5795 2244 d->cgroup_pattern = lxc_global_config_value("lxc.cgroup.pattern");
4fb3cba5
DE
2245
2246 d->meta = lxc_cgroup_load_meta();
2247 if (!d->meta) {
2248 ERROR("cgroupfs failed to detect cgroup metadata");
2249 goto err2;
2250 }
2251 return d;
2252
2253err2:
2254 free(d->name);
2255err1:
2256 free(d);
2257 return NULL;
d4ef7c50 2258}
484ed030 2259
4fb3cba5 2260static void cgfs_destroy(void *hdata)
d4ef7c50 2261{
4fb3cba5
DE
2262 struct cgfs_data *d = hdata;
2263
d4ef7c50
SH
2264 if (!d)
2265 return;
f10fad2f 2266 free(d->name);
c55d4505
ME
2267 lxc_cgroup_process_info_free_and_remove(d->info);
2268 lxc_cgroup_put_meta(d->meta);
d4ef7c50 2269 free(d);
d4ef7c50 2270}
484ed030 2271
4fb3cba5 2272static inline bool cgfs_create(void *hdata)
d4ef7c50 2273{
4fb3cba5
DE
2274 struct cgfs_data *d = hdata;
2275 struct cgroup_process_info *i;
2276 struct cgroup_meta_data *md;
484ed030 2277
4fb3cba5 2278 if (!d)
d4ef7c50 2279 return false;
4fb3cba5
DE
2280 md = d->meta;
2281 i = lxc_cgroupfs_create(d->name, d->cgroup_pattern, md, NULL);
d4ef7c50
SH
2282 if (!i)
2283 return false;
2284 d->info = i;
2285 return true;
2286}
484ed030 2287
4fb3cba5 2288static inline bool cgfs_enter(void *hdata, pid_t pid)
d4ef7c50 2289{
4fb3cba5
DE
2290 struct cgfs_data *d = hdata;
2291 struct cgroup_process_info *i;
d4ef7c50 2292 int ret;
4fb3cba5
DE
2293
2294 if (!d)
2295 return false;
2296 i = d->info;
2297 ret = lxc_cgroupfs_enter(i, pid, false);
484ed030 2298
d4ef7c50
SH
2299 return ret == 0;
2300}
2301
4fb3cba5 2302static inline bool cgfs_create_legacy(void *hdata, pid_t pid)
d4ef7c50 2303{
4fb3cba5
DE
2304 struct cgfs_data *d = hdata;
2305 struct cgroup_process_info *i;
2306
2307 if (!d)
2308 return false;
2309 i = d->info;
2310 if (lxc_cgroup_create_legacy(i, d->name, pid) < 0) {
2311 ERROR("failed to create legacy ns cgroups for '%s'", d->name);
d4ef7c50 2312 return false;
484ed030 2313 }
d4ef7c50
SH
2314 return true;
2315}
484ed030 2316
4fb3cba5 2317static const char *cgfs_get_cgroup(void *hdata, const char *subsystem)
d4ef7c50 2318{
4fb3cba5
DE
2319 struct cgfs_data *d = hdata;
2320
2321 if (!d)
2322 return NULL;
2323 return lxc_cgroup_get_hierarchy_path_data(subsystem, d);
484ed030
SH
2324}
2325
2ba7a429
TA
2326static const char *cgfs_canonical_path(void *hdata)
2327{
2328 struct cgfs_data *d = hdata;
2329 struct cgroup_process_info *info_ptr;
2330 char *path = NULL;
2331
2332 if (!d)
2333 return NULL;
2334
2335 for (info_ptr = d->info; info_ptr; info_ptr = info_ptr->next) {
2336 if (!path)
2337 path = info_ptr->cgroup_path;
2338 else if (strcmp(path, info_ptr->cgroup_path) != 0) {
2339 ERROR("not all paths match %s, %s has path %s", path,
2340 info_ptr->hierarchy->subsystems[0], info_ptr->cgroup_path);
2341 return NULL;
2342 }
2343 }
2344
2345 return path;
2346}
2347
06078509
TA
2348static bool cgfs_escape(void)
2349{
2350 struct cgroup_meta_data *md;
2351 int i;
2352 bool ret = false;
2353
2354 md = lxc_cgroup_load_meta();
2355 if (!md)
2356 return false;
2357
2358 for (i = 1; i <= md->maximum_hierarchy; i++) {
2359 struct cgroup_hierarchy *h = md->hierarchies[i];
2360 struct cgroup_mount_point *mp;
2361 char *tasks;
2362 FILE *f;
2363 int written;
2364
2365 if (!h) {
2366 WARN("not escaping hierarchy %d", i);
2367 continue;
2368 }
2369
2370 mp = lxc_cgroup_find_mount_point(h, "/", true);
2371 if (!mp)
2372 goto out;
2373
2374 tasks = cgroup_to_absolute_path(mp, "/", "tasks");
2375 if (!tasks)
2376 goto out;
2377
2378 f = fopen(tasks, "a");
2379 free(tasks);
2380 if (!f)
2381 goto out;
2382
2383 written = fprintf(f, "%d\n", getpid());
2384 fclose(f);
2385 if (written < 0) {
2386 SYSERROR("writing tasks failed\n");
2387 goto out;
2388 }
2389 }
2390
2391 ret = true;
2392out:
2393 lxc_cgroup_put_meta(md);
2394 return ret;
2395}
2396
4fb3cba5 2397static bool cgfs_unfreeze(void *hdata)
0086f499 2398{
4fb3cba5 2399 struct cgfs_data *d = hdata;
0086f499
SH
2400 char *cgabspath, *cgrelpath;
2401 int ret;
2402
4fb3cba5
DE
2403 if (!d)
2404 return false;
2405
2406 cgrelpath = lxc_cgroup_get_hierarchy_path_data("freezer", d);
0086f499
SH
2407 cgabspath = lxc_cgroup_find_abs_path("freezer", cgrelpath, true, NULL);
2408 if (!cgabspath)
ecfcb3f0 2409 return false;
0086f499
SH
2410
2411 ret = do_cgroup_set(cgabspath, "freezer.state", "THAWED");
2412 free(cgabspath);
ecfcb3f0 2413 return ret == 0;
0086f499
SH
2414}
2415
4fb3cba5
DE
2416static bool cgroupfs_setup_limits(void *hdata, struct lxc_list *cgroup_conf,
2417 bool with_devices)
9daf6f5d 2418{
4fb3cba5
DE
2419 struct cgfs_data *d = hdata;
2420
2421 if (!d)
2422 return false;
2423 return do_setup_cgroup_limits(d, cgroup_conf, with_devices) == 0;
9daf6f5d
SH
2424}
2425
4fb3cba5 2426static bool lxc_cgroupfs_attach(const char *name, const char *lxcpath, pid_t pid)
5d897655
SH
2427{
2428 struct cgroup_meta_data *meta_data;
2429 struct cgroup_process_info *container_info;
2430 int ret;
2431
2432 meta_data = lxc_cgroup_load_meta();
2433 if (!meta_data) {
2434 ERROR("could not move attached process %d to cgroup of container", pid);
2435 return false;
2436 }
2437
2438 container_info = lxc_cgroup_get_container_info(name, lxcpath, meta_data);
2439 lxc_cgroup_put_meta(meta_data);
2440 if (!container_info) {
2441 ERROR("could not move attached process %d to cgroup of container", pid);
2442 return false;
2443 }
2444
2445 ret = lxc_cgroupfs_enter(container_info, pid, false);
2446 lxc_cgroup_process_info_free(container_info);
2447 if (ret < 0) {
2448 ERROR("could not move attached process %d to cgroup of container", pid);
2449 return false;
2450 }
2451 return true;
2452}
2453
8b276860
SH
2454struct chown_data {
2455 const char *cgroup_path;
2456 uid_t origuid;
2457};
2458
2459/*
2460 * TODO - someone should refactor this to unshare once passing all the paths
2461 * to be chowned in one go
2462 */
2463static int chown_cgroup_wrapper(void *data)
2464{
2465 struct chown_data *arg = data;
2466 uid_t destuid;
2467 char *fpath;
2468
2469
2470 if (setresgid(0,0,0) < 0)
2471 SYSERROR("Failed to setgid to 0");
2472 if (setresuid(0,0,0) < 0)
2473 SYSERROR("Failed to setuid to 0");
2474 if (setgroups(0, NULL) < 0)
2475 SYSERROR("Failed to clear groups");
2476 destuid = get_ns_uid(arg->origuid);
2477
2478 if (chown(arg->cgroup_path, destuid, 0) < 0)
2479 SYSERROR("Failed chowning %s to %d", arg->cgroup_path, (int)destuid);
2480
2481 fpath = lxc_append_paths(arg->cgroup_path, "tasks");
2482 if (!fpath)
2483 return -1;
2484 if (chown(fpath, destuid, 0) < 0)
2485 SYSERROR("Error chowning %s\n", fpath);
2486 free(fpath);
2487 fpath = lxc_append_paths(arg->cgroup_path, "cgroup.procs");
2488 if (!fpath)
2489 return -1;
2490 if (chown(fpath, destuid, 0) < 0)
2491 SYSERROR("Error chowning %s", fpath);
2492 free(fpath);
2493
2494 return 0;
2495}
2496
2497static bool do_cgfs_chown(char *cgroup_path, struct lxc_conf *conf)
2498{
2499 struct chown_data data;
2500 char *fpath;
2501
2502 if (lxc_list_empty(&conf->id_map))
2503 /* If there's no mapping then we don't need to chown */
2504 return true;
2505
2506 data.cgroup_path = cgroup_path;
2507 data.origuid = geteuid();
2508
2509 /* Unpriv users can't chown it themselves, so chown from
2510 * a child namespace mapping both our own and the target uid
2511 */
2512 if (userns_exec_1(conf, chown_cgroup_wrapper, &data) < 0) {
2513 ERROR("Error requesting cgroup chown in new namespace");
2514 return false;
2515 }
2516
2517 /*
2518 * Now chmod 775 the directory else the container cannot create cgroups.
2519 * This can't be done in the child namespace because it only group-owns
2520 * the cgroup
2521 */
2522 if (chmod(cgroup_path, 0775) < 0) {
2523 SYSERROR("Error chmoding %s\n", cgroup_path);
2524 return false;
2525 }
2526 fpath = lxc_append_paths(cgroup_path, "tasks");
2527 if (!fpath)
2528 return false;
2529 if (chmod(fpath, 0664) < 0)
2530 SYSERROR("Error chmoding %s\n", fpath);
2531 free(fpath);
2532 fpath = lxc_append_paths(cgroup_path, "cgroup.procs");
2533 if (!fpath)
2534 return false;
2535 if (chmod(fpath, 0664) < 0)
2536 SYSERROR("Error chmoding %s\n", fpath);
2537 free(fpath);
2538
2539 return true;
2540}
2541
2542static bool cgfs_chown(void *hdata, struct lxc_conf *conf)
2543{
2544 struct cgfs_data *d = hdata;
2545 struct cgroup_process_info *info_ptr;
2546 char *cgpath;
2547 bool r = true;
2548
2549 if (!d)
2550 return false;
2551
2552 for (info_ptr = d->info; info_ptr; info_ptr = info_ptr->next) {
2553 if (!info_ptr->designated_mount_point) {
2554 info_ptr->designated_mount_point = lxc_cgroup_find_mount_point(info_ptr->hierarchy, info_ptr->cgroup_path, true);
2555 if (!info_ptr->designated_mount_point) {
2556 SYSERROR("Could not chown cgroup %s: internal error (couldn't find any writable mountpoint to cgroup filesystem)", info_ptr->cgroup_path);
2557 return false;
2558 }
2559 }
2560
2561 cgpath = cgroup_to_absolute_path(info_ptr->designated_mount_point, info_ptr->cgroup_path, NULL);
2562 if (!cgpath) {
2563 SYSERROR("Could not chown cgroup %s: internal error", info_ptr->cgroup_path);
2564 continue;
2565 }
2566 r = do_cgfs_chown(cgpath, conf);
2567 if (!r) {
2568 ERROR("Failed chowning %s\n", cgpath);
2569 free(cgpath);
2570 return false;
2571 }
2572 free(cgpath);
2573 }
2574
2575 return true;
2576}
2577
d4ef7c50 2578static struct cgroup_ops cgfs_ops = {
d4ef7c50 2579 .init = cgfs_init,
4fb3cba5 2580 .destroy = cgfs_destroy,
d4ef7c50
SH
2581 .create = cgfs_create,
2582 .enter = cgfs_enter,
2583 .create_legacy = cgfs_create_legacy,
2584 .get_cgroup = cgfs_get_cgroup,
2ba7a429 2585 .canonical_path = cgfs_canonical_path,
06078509 2586 .escape = cgfs_escape,
d4ef7c50
SH
2587 .get = lxc_cgroupfs_get,
2588 .set = lxc_cgroupfs_set,
4fb3cba5 2589 .unfreeze = cgfs_unfreeze,
9daf6f5d 2590 .setup_limits = cgroupfs_setup_limits,
d4ef7c50 2591 .name = "cgroupfs",
5d897655 2592 .attach = lxc_cgroupfs_attach,
8b276860 2593 .chown = cgfs_chown,
c476bdce 2594 .mount_cgroup = cgroupfs_mount_cgroup,
4fb3cba5 2595 .nrtasks = cgfs_nrtasks,
23befb18 2596 .driver = CGFS,
d4ef7c50 2597};