]> git.proxmox.com Git - mirror_lxcfs.git/blame - bindings.c
bindings: revert cgroup check
[mirror_lxcfs.git] / bindings.c
CommitLineData
237e200e
SH
1/* lxcfs
2 *
3 * Copyright © 2014-2016 Canonical, Inc
4 * Author: Serge Hallyn <serge.hallyn@ubuntu.com>
5 *
6 * See COPYING file for details.
7 */
8
9#define FUSE_USE_VERSION 26
10
237e200e 11#include <dirent.h>
29a73c2f 12#include <errno.h>
237e200e
SH
13#include <fcntl.h>
14#include <fuse.h>
237e200e 15#include <libgen.h>
237e200e 16#include <pthread.h>
29a73c2f
CB
17#include <sched.h>
18#include <stdbool.h>
19#include <stdio.h>
20#include <stdlib.h>
21#include <string.h>
22#include <time.h>
23#include <unistd.h>
24#include <wait.h>
237e200e 25#include <linux/sched.h>
29a73c2f
CB
26#include <sys/epoll.h>
27#include <sys/mman.h>
28#include <sys/mount.h>
237e200e
SH
29#include <sys/param.h>
30#include <sys/socket.h>
29a73c2f 31#include <sys/syscall.h>
237e200e 32
237e200e 33#include "bindings.h"
237e200e
SH
34#include "config.h" // for VERSION
35
29a73c2f
CB
36/* Define pivot_root() if missing from the C library */
37#ifndef HAVE_PIVOT_ROOT
38static int pivot_root(const char * new_root, const char * put_old)
39{
40#ifdef __NR_pivot_root
41return syscall(__NR_pivot_root, new_root, put_old);
42#else
43errno = ENOSYS;
44return -1;
45#endif
46}
47#else
48extern int pivot_root(const char * new_root, const char * put_old);
49#endif
50
7dd6560a
CB
51#ifdef DEBUG
52#define lxcfs_debug(format, ...) \
53 do { \
54 fprintf(stderr, "%s: %d: %s: " format, __FILE__, __LINE__, \
55 __func__, __VA_ARGS__); \
56 } while (false)
57#else
58#define lxcfs_debug(format, ...)
59#endif /* DEBUG */
60
237e200e
SH
61enum {
62 LXC_TYPE_CGDIR,
63 LXC_TYPE_CGFILE,
64 LXC_TYPE_PROC_MEMINFO,
65 LXC_TYPE_PROC_CPUINFO,
66 LXC_TYPE_PROC_UPTIME,
67 LXC_TYPE_PROC_STAT,
68 LXC_TYPE_PROC_DISKSTATS,
70dcc12e 69 LXC_TYPE_PROC_SWAPS,
237e200e
SH
70};
71
72struct file_info {
73 char *controller;
74 char *cgroup;
75 char *file;
76 int type;
77 char *buf; // unused as of yet
78 int buflen;
79 int size; //actual data size
80 int cached;
81};
82
83/* reserve buffer size, for cpuall in /proc/stat */
84#define BUF_RESERVE_SIZE 256
85
86/*
87 * A table caching which pid is init for a pid namespace.
88 * When looking up which pid is init for $qpid, we first
89 * 1. Stat /proc/$qpid/ns/pid.
90 * 2. Check whether the ino_t is in our store.
91 * a. if not, fork a child in qpid's ns to send us
92 * ucred.pid = 1, and read the initpid. Cache
93 * initpid and creation time for /proc/initpid
94 * in a new store entry.
95 * b. if so, verify that /proc/initpid still matches
96 * what we have saved. If not, clear the store
97 * entry and go back to a. If so, return the
98 * cached initpid.
99 */
100struct pidns_init_store {
101 ino_t ino; // inode number for /proc/$pid/ns/pid
102 pid_t initpid; // the pid of nit in that ns
103 long int ctime; // the time at which /proc/$initpid was created
104 struct pidns_init_store *next;
105 long int lastcheck;
106};
107
108/* lol - look at how they are allocated in the kernel */
109#define PIDNS_HASH_SIZE 4096
110#define HASH(x) ((x) % PIDNS_HASH_SIZE)
111
112static struct pidns_init_store *pidns_hash_table[PIDNS_HASH_SIZE];
113static pthread_mutex_t pidns_store_mutex = PTHREAD_MUTEX_INITIALIZER;
114static void lock_mutex(pthread_mutex_t *l)
115{
116 int ret;
117
118 if ((ret = pthread_mutex_lock(l)) != 0) {
119 fprintf(stderr, "pthread_mutex_lock returned:%d %s\n", ret, strerror(ret));
120 exit(1);
121 }
122}
123
29a73c2f
CB
124/* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
125 * Number of hierarchies mounted. */
126static int num_hierarchies;
127
128/* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
129 * Hierachies mounted {cpuset, blkio, ...}:
130 * Initialized via __constructor__ collect_and_mount_subsystems(). */
131static char **hierarchies;
132
133/* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
134 * Open file descriptors:
135 * @fd_hierarchies[i] refers to cgroup @hierarchies[i]. They are mounted in a
136 * private mount namespace.
137 * Initialized via __constructor__ collect_and_mount_subsystems().
138 * @fd_hierarchies[i] can be used to perform file operations on the cgroup
139 * mounts and respective files in the private namespace even when located in
140 * another namespace using the *at() family of functions
141 * {openat(), fchownat(), ...}. */
142static int *fd_hierarchies;
143
237e200e
SH
144static void unlock_mutex(pthread_mutex_t *l)
145{
146 int ret;
147
148 if ((ret = pthread_mutex_unlock(l)) != 0) {
149 fprintf(stderr, "pthread_mutex_unlock returned:%d %s\n", ret, strerror(ret));
150 exit(1);
151 }
152}
153
154static void store_lock(void)
155{
156 lock_mutex(&pidns_store_mutex);
157}
158
159static void store_unlock(void)
160{
161 unlock_mutex(&pidns_store_mutex);
162}
163
164/* Must be called under store_lock */
165static bool initpid_still_valid(struct pidns_init_store *e, struct stat *nsfdsb)
166{
167 struct stat initsb;
168 char fnam[100];
169
170 snprintf(fnam, 100, "/proc/%d", e->initpid);
171 if (stat(fnam, &initsb) < 0)
172 return false;
7dd6560a
CB
173
174 lxcfs_debug("Comparing ctime %ld == %ld for pid %d.\n", e->ctime,
175 initsb.st_ctime, e->initpid);
176
237e200e
SH
177 if (e->ctime != initsb.st_ctime)
178 return false;
179 return true;
180}
181
182/* Must be called under store_lock */
183static void remove_initpid(struct pidns_init_store *e)
184{
185 struct pidns_init_store *tmp;
186 int h;
187
7dd6560a
CB
188 lxcfs_debug("Remove_initpid: removing entry for %d.\n", e->initpid);
189
237e200e
SH
190 h = HASH(e->ino);
191 if (pidns_hash_table[h] == e) {
192 pidns_hash_table[h] = e->next;
193 free(e);
194 return;
195 }
196
197 tmp = pidns_hash_table[h];
198 while (tmp) {
199 if (tmp->next == e) {
200 tmp->next = e->next;
201 free(e);
202 return;
203 }
204 tmp = tmp->next;
205 }
206}
207
208#define PURGE_SECS 5
209/* Must be called under store_lock */
210static void prune_initpid_store(void)
211{
212 static long int last_prune = 0;
213 struct pidns_init_store *e, *prev, *delme;
214 long int now, threshold;
215 int i;
216
217 if (!last_prune) {
218 last_prune = time(NULL);
219 return;
220 }
221 now = time(NULL);
222 if (now < last_prune + PURGE_SECS)
223 return;
7dd6560a
CB
224
225 lxcfs_debug("%s\n", "Pruning.");
226
237e200e
SH
227 last_prune = now;
228 threshold = now - 2 * PURGE_SECS;
229
230 for (i = 0; i < PIDNS_HASH_SIZE; i++) {
231 for (prev = NULL, e = pidns_hash_table[i]; e; ) {
232 if (e->lastcheck < threshold) {
7dd6560a
CB
233
234 lxcfs_debug("Removing cached entry for %d.\n", e->initpid);
235
237e200e
SH
236 delme = e;
237 if (prev)
238 prev->next = e->next;
239 else
240 pidns_hash_table[i] = e->next;
241 e = e->next;
242 free(delme);
243 } else {
244 prev = e;
245 e = e->next;
246 }
247 }
248 }
249}
250
251/* Must be called under store_lock */
252static void save_initpid(struct stat *sb, pid_t pid)
253{
254 struct pidns_init_store *e;
255 char fpath[100];
256 struct stat procsb;
257 int h;
258
7dd6560a
CB
259 lxcfs_debug("Save_initpid: adding entry for %d.\n", pid);
260
237e200e
SH
261 snprintf(fpath, 100, "/proc/%d", pid);
262 if (stat(fpath, &procsb) < 0)
263 return;
264 do {
265 e = malloc(sizeof(*e));
266 } while (!e);
267 e->ino = sb->st_ino;
268 e->initpid = pid;
269 e->ctime = procsb.st_ctime;
270 h = HASH(e->ino);
271 e->next = pidns_hash_table[h];
272 e->lastcheck = time(NULL);
273 pidns_hash_table[h] = e;
274}
275
276/*
277 * Given the stat(2) info for a nsfd pid inode, lookup the init_pid_store
278 * entry for the inode number and creation time. Verify that the init pid
279 * is still valid. If not, remove it. Return the entry if valid, NULL
280 * otherwise.
281 * Must be called under store_lock
282 */
283static struct pidns_init_store *lookup_verify_initpid(struct stat *sb)
284{
285 int h = HASH(sb->st_ino);
286 struct pidns_init_store *e = pidns_hash_table[h];
287
288 while (e) {
289 if (e->ino == sb->st_ino) {
290 if (initpid_still_valid(e, sb)) {
291 e->lastcheck = time(NULL);
292 return e;
293 }
294 remove_initpid(e);
295 return NULL;
296 }
297 e = e->next;
298 }
299
300 return NULL;
301}
302
0f657ce3 303static int is_dir(const char *path, int fd)
237e200e
SH
304{
305 struct stat statbuf;
0f657ce3 306 int ret = fstatat(fd, path, &statbuf, fd);
237e200e
SH
307 if (ret == 0 && S_ISDIR(statbuf.st_mode))
308 return 1;
309 return 0;
310}
311
312static char *must_copy_string(const char *str)
313{
314 char *dup = NULL;
315 if (!str)
316 return NULL;
317 do {
318 dup = strdup(str);
319 } while (!dup);
320
321 return dup;
322}
323
324static inline void drop_trailing_newlines(char *s)
325{
326 int l;
327
328 for (l=strlen(s); l>0 && s[l-1] == '\n'; l--)
329 s[l-1] = '\0';
330}
331
332#define BATCH_SIZE 50
333static void dorealloc(char **mem, size_t oldlen, size_t newlen)
334{
335 int newbatches = (newlen / BATCH_SIZE) + 1;
336 int oldbatches = (oldlen / BATCH_SIZE) + 1;
337
338 if (!*mem || newbatches > oldbatches) {
339 char *tmp;
340 do {
341 tmp = realloc(*mem, newbatches * BATCH_SIZE);
342 } while (!tmp);
343 *mem = tmp;
344 }
345}
346static void append_line(char **contents, size_t *len, char *line, ssize_t linelen)
347{
348 size_t newlen = *len + linelen;
349 dorealloc(contents, *len, newlen + 1);
350 memcpy(*contents + *len, line, linelen+1);
351 *len = newlen;
352}
353
60f2ae53 354static char *slurp_file(const char *from, int fd)
237e200e
SH
355{
356 char *line = NULL;
357 char *contents = NULL;
60f2ae53 358 FILE *f = fdopen(fd, "r");
237e200e
SH
359 size_t len = 0, fulllen = 0;
360 ssize_t linelen;
361
362 if (!f)
363 return NULL;
364
365 while ((linelen = getline(&line, &len, f)) != -1) {
366 append_line(&contents, &fulllen, line, linelen);
367 }
368 fclose(f);
369
370 if (contents)
371 drop_trailing_newlines(contents);
372 free(line);
373 return contents;
374}
375
ba59ea09 376static bool write_string(const char *fnam, const char *string, int fd)
237e200e
SH
377{
378 FILE *f;
379 size_t len, ret;
380
ba59ea09 381 if (!(f = fdopen(fd, "w")))
237e200e
SH
382 return false;
383 len = strlen(string);
384 ret = fwrite(string, 1, len, f);
385 if (ret != len) {
386 fprintf(stderr, "Error writing to file: %s\n", strerror(errno));
387 fclose(f);
388 return false;
389 }
390 if (fclose(f) < 0) {
391 fprintf(stderr, "Error writing to file: %s\n", strerror(errno));
392 return false;
393 }
394 return true;
395}
396
237e200e
SH
397struct cgfs_files {
398 char *name;
399 uint32_t uid, gid;
400 uint32_t mode;
401};
402
0619767c 403#define ALLOC_NUM 20
237e200e
SH
404static bool store_hierarchy(char *stridx, char *h)
405{
0619767c
SH
406 if (num_hierarchies % ALLOC_NUM == 0) {
407 size_t n = (num_hierarchies / ALLOC_NUM) + 1;
408 n *= ALLOC_NUM;
409 char **tmp = realloc(hierarchies, n * sizeof(char *));
0619767c
SH
410 if (!tmp) {
411 fprintf(stderr, "Out of memory\n");
412 exit(1);
413 }
237e200e 414 hierarchies = tmp;
237e200e 415 }
f676eb79 416
0619767c 417 hierarchies[num_hierarchies++] = must_copy_string(h);
237e200e
SH
418 return true;
419}
420
421static void print_subsystems(void)
422{
423 int i;
424
cc97d34c 425 fprintf(stderr, "hierarchies:\n");
237e200e
SH
426 for (i = 0; i < num_hierarchies; i++) {
427 if (hierarchies[i])
428 fprintf(stderr, " %d: %s\n", i, hierarchies[i]);
429 }
430}
431
432static bool in_comma_list(const char *needle, const char *haystack)
433{
434 const char *s = haystack, *e;
435 size_t nlen = strlen(needle);
436
06081b29 437 while (*s && (e = strchr(s, ','))) {
237e200e
SH
438 if (nlen != e - s) {
439 s = e + 1;
440 continue;
441 }
442 if (strncmp(needle, s, nlen) == 0)
443 return true;
444 s = e + 1;
445 }
446 if (strcmp(needle, s) == 0)
447 return true;
448 return false;
449}
450
451/* do we need to do any massaging here? I'm not sure... */
5dd3e6fd
CB
452/* Return the mounted controller and store the corresponding open file descriptor
453 * referring to the controller mountpoint in the private lxcfs namespace in
454 * @cfd.
455 */
456static char *find_mounted_controller(const char *controller, int *cfd)
237e200e
SH
457{
458 int i;
459
460 for (i = 0; i < num_hierarchies; i++) {
461 if (!hierarchies[i])
462 continue;
5dd3e6fd
CB
463 if (strcmp(hierarchies[i], controller) == 0) {
464 *cfd = fd_hierarchies[i];
237e200e 465 return hierarchies[i];
5dd3e6fd
CB
466 }
467 if (in_comma_list(controller, hierarchies[i])) {
468 *cfd = fd_hierarchies[i];
237e200e 469 return hierarchies[i];
5dd3e6fd 470 }
237e200e
SH
471 }
472
473 return NULL;
474}
475
476bool cgfs_set_value(const char *controller, const char *cgroup, const char *file,
477 const char *value)
478{
ba59ea09 479 int ret, fd, cfd;
237e200e 480 size_t len;
f5a6d92e 481 char *fnam, *tmpc;
237e200e 482
f5a6d92e 483 tmpc = find_mounted_controller(controller, &cfd);
237e200e
SH
484 if (!tmpc)
485 return false;
f5a6d92e
CB
486
487 /* Make sure we pass a relative path to *at() family of functions.
488 * . + /cgroup + / + file + \0
489 */
ba59ea09 490 len = strlen(cgroup) + strlen(file) + 3;
237e200e 491 fnam = alloca(len);
ba59ea09
CB
492 ret = snprintf(fnam, len, "%s%s/%s", *cgroup == '/' ? "." : "", cgroup, file);
493 if (ret < 0 || (size_t)ret >= len)
494 return false;
495
496 fd = openat(cfd, fnam, O_WRONLY);
497 if (fd < 0)
498 return false;
f676eb79 499
ba59ea09 500 return write_string(fnam, value, fd);
237e200e
SH
501}
502
503// Chown all the files in the cgroup directory. We do this when we create
504// a cgroup on behalf of a user.
f23fe717 505static void chown_all_cgroup_files(const char *dirname, uid_t uid, gid_t gid, int fd)
237e200e 506{
f23fe717 507 struct dirent *direntp;
237e200e
SH
508 char path[MAXPATHLEN];
509 size_t len;
510 DIR *d;
f23fe717 511 int fd1, ret;
237e200e
SH
512
513 len = strlen(dirname);
514 if (len >= MAXPATHLEN) {
515 fprintf(stderr, "chown_all_cgroup_files: pathname too long: %s\n", dirname);
516 return;
517 }
518
f23fe717
CB
519 fd1 = openat(fd, dirname, O_DIRECTORY);
520 if (fd1 < 0)
521 return;
522
523 d = fdopendir(fd1);
237e200e
SH
524 if (!d) {
525 fprintf(stderr, "chown_all_cgroup_files: failed to open %s\n", dirname);
526 return;
527 }
528
f23fe717 529 while ((direntp = readdir(d))) {
237e200e
SH
530 if (!strcmp(direntp->d_name, ".") || !strcmp(direntp->d_name, ".."))
531 continue;
532 ret = snprintf(path, MAXPATHLEN, "%s/%s", dirname, direntp->d_name);
533 if (ret < 0 || ret >= MAXPATHLEN) {
534 fprintf(stderr, "chown_all_cgroup_files: pathname too long under %s\n", dirname);
535 continue;
536 }
f23fe717 537 if (fchownat(fd, path, uid, gid, 0) < 0)
237e200e
SH
538 fprintf(stderr, "Failed to chown file %s to %u:%u", path, uid, gid);
539 }
540 closedir(d);
541}
542
543int cgfs_create(const char *controller, const char *cg, uid_t uid, gid_t gid)
544{
5dd3e6fd 545 int cfd;
237e200e 546 size_t len;
f5a6d92e 547 char *dirnam, *tmpc;
237e200e 548
f5a6d92e 549 tmpc = find_mounted_controller(controller, &cfd);
237e200e
SH
550 if (!tmpc)
551 return -EINVAL;
f5a6d92e
CB
552
553 /* Make sure we pass a relative path to *at() family of functions.
554 * . + /cg + \0
555 */
f23fe717 556 len = strlen(cg) + 2;
237e200e 557 dirnam = alloca(len);
f23fe717 558 snprintf(dirnam, len, "%s%s", *cg == '/' ? "." : "", cg);
237e200e 559
f23fe717 560 if (mkdirat(cfd, dirnam, 0755) < 0)
237e200e
SH
561 return -errno;
562
563 if (uid == 0 && gid == 0)
564 return 0;
565
f23fe717 566 if (fchownat(cfd, dirnam, uid, gid, 0) < 0)
237e200e
SH
567 return -errno;
568
f23fe717 569 chown_all_cgroup_files(dirnam, uid, gid, cfd);
237e200e
SH
570
571 return 0;
572}
573
7213ec5c 574static bool recursive_rmdir(const char *dirname, int fd, const int cfd)
237e200e 575{
b7672ded 576 struct dirent *direntp;
237e200e
SH
577 DIR *dir;
578 bool ret = false;
579 char pathname[MAXPATHLEN];
b7672ded
CB
580 int dupfd;
581
582 dupfd = dup(fd); // fdopendir() does bad things once it uses an fd.
583 if (dupfd < 0)
584 return false;
237e200e 585
b7672ded 586 dir = fdopendir(dupfd);
237e200e 587 if (!dir) {
7dd6560a 588 lxcfs_debug("Failed to open %s: %s.\n", dirname, strerror(errno));
7213ec5c 589 close(dupfd);
237e200e
SH
590 return false;
591 }
592
b7672ded 593 while ((direntp = readdir(dir))) {
237e200e
SH
594 struct stat mystat;
595 int rc;
596
237e200e
SH
597 if (!strcmp(direntp->d_name, ".") ||
598 !strcmp(direntp->d_name, ".."))
599 continue;
600
601 rc = snprintf(pathname, MAXPATHLEN, "%s/%s", dirname, direntp->d_name);
602 if (rc < 0 || rc >= MAXPATHLEN) {
603 fprintf(stderr, "pathname too long\n");
604 continue;
605 }
606
2e81a5e3
CB
607 rc = fstatat(cfd, pathname, &mystat, AT_SYMLINK_NOFOLLOW);
608 if (rc) {
7dd6560a 609 lxcfs_debug("Failed to stat %s: %s.\n", pathname, strerror(errno));
237e200e
SH
610 continue;
611 }
7dd6560a 612 if (S_ISDIR(mystat.st_mode))
2e81a5e3 613 if (!recursive_rmdir(pathname, fd, cfd))
7dd6560a 614 lxcfs_debug("Error removing %s.\n", pathname);
237e200e
SH
615 }
616
617 ret = true;
618 if (closedir(dir) < 0) {
619 fprintf(stderr, "%s: failed to close directory %s: %s\n", __func__, dirname, strerror(errno));
620 ret = false;
621 }
622
2e81a5e3 623 if (unlinkat(cfd, dirname, AT_REMOVEDIR) < 0) {
7dd6560a 624 lxcfs_debug("Failed to delete %s: %s.\n", dirname, strerror(errno));
237e200e
SH
625 ret = false;
626 }
7213ec5c
CB
627
628 close(dupfd);
237e200e
SH
629
630 return ret;
631}
632
633bool cgfs_remove(const char *controller, const char *cg)
634{
b7672ded 635 int fd, cfd;
237e200e 636 size_t len;
f5a6d92e 637 char *dirnam, *tmpc;
7213ec5c 638 bool bret;
237e200e 639
f5a6d92e 640 tmpc = find_mounted_controller(controller, &cfd);
237e200e
SH
641 if (!tmpc)
642 return false;
f5a6d92e
CB
643
644 /* Make sure we pass a relative path to *at() family of functions.
645 * . + /cg + \0
646 */
b7672ded 647 len = strlen(cg) + 2;
237e200e 648 dirnam = alloca(len);
b7672ded
CB
649 snprintf(dirnam, len, "%s%s", *cg == '/' ? "." : "", cg);
650
651 fd = openat(cfd, dirnam, O_DIRECTORY);
652 if (fd < 0)
653 return false;
654
7213ec5c
CB
655 bret = recursive_rmdir(dirnam, fd, cfd);
656 close(fd);
657 return bret;
237e200e
SH
658}
659
660bool cgfs_chmod_file(const char *controller, const char *file, mode_t mode)
661{
5dd3e6fd 662 int cfd;
237e200e 663 size_t len;
f5a6d92e 664 char *pathname, *tmpc;
237e200e 665
f5a6d92e 666 tmpc = find_mounted_controller(controller, &cfd);
237e200e
SH
667 if (!tmpc)
668 return false;
f5a6d92e
CB
669
670 /* Make sure we pass a relative path to *at() family of functions.
671 * . + /file + \0
672 */
534690b4 673 len = strlen(file) + 2;
237e200e 674 pathname = alloca(len);
534690b4
CB
675 snprintf(pathname, len, "%s%s", *file == '/' ? "." : "", file);
676 if (fchmodat(cfd, pathname, mode, 0) < 0)
237e200e
SH
677 return false;
678 return true;
679}
680
0f657ce3 681static int chown_tasks_files(const char *dirname, uid_t uid, gid_t gid, int fd)
237e200e
SH
682{
683 size_t len;
684 char *fname;
685
686 len = strlen(dirname) + strlen("/cgroup.procs") + 1;
687 fname = alloca(len);
688 snprintf(fname, len, "%s/tasks", dirname);
0f657ce3 689 if (fchownat(fd, fname, uid, gid, 0) != 0)
237e200e
SH
690 return -errno;
691 snprintf(fname, len, "%s/cgroup.procs", dirname);
0f657ce3 692 if (fchownat(fd, fname, uid, gid, 0) != 0)
237e200e
SH
693 return -errno;
694 return 0;
695}
696
697int cgfs_chown_file(const char *controller, const char *file, uid_t uid, gid_t gid)
698{
5dd3e6fd 699 int cfd;
237e200e 700 size_t len;
f5a6d92e 701 char *pathname, *tmpc;
237e200e 702
f5a6d92e 703 tmpc = find_mounted_controller(controller, &cfd);
237e200e
SH
704 if (!tmpc)
705 return -EINVAL;
f5a6d92e
CB
706
707 /* Make sure we pass a relative path to *at() family of functions.
708 * . + /file + \0
709 */
0f657ce3 710 len = strlen(file) + 2;
237e200e 711 pathname = alloca(len);
0f657ce3
CB
712 snprintf(pathname, len, "%s%s", *file == '/' ? "." : "", file);
713 if (fchownat(cfd, pathname, uid, gid, 0) < 0)
237e200e
SH
714 return -errno;
715
0f657ce3 716 if (is_dir(pathname, cfd))
237e200e 717 // like cgmanager did, we want to chown the tasks file as well
0f657ce3 718 return chown_tasks_files(pathname, uid, gid, cfd);
237e200e
SH
719
720 return 0;
721}
722
723FILE *open_pids_file(const char *controller, const char *cgroup)
724{
3ffd08ee 725 int fd, cfd;
237e200e 726 size_t len;
f5a6d92e 727 char *pathname, *tmpc;
237e200e 728
f5a6d92e 729 tmpc = find_mounted_controller(controller, &cfd);
237e200e
SH
730 if (!tmpc)
731 return NULL;
f5a6d92e
CB
732
733 /* Make sure we pass a relative path to *at() family of functions.
734 * . + /cgroup + / "cgroup.procs" + \0
735 */
3ffd08ee 736 len = strlen(cgroup) + strlen("cgroup.procs") + 3;
237e200e 737 pathname = alloca(len);
3ffd08ee
CB
738 snprintf(pathname, len, "%s%s/cgroup.procs", *cgroup == '/' ? "." : "", cgroup);
739
740 fd = openat(cfd, pathname, O_WRONLY);
741 if (fd < 0)
742 return NULL;
743
744 return fdopen(fd, "w");
237e200e
SH
745}
746
f366da65
WB
747static bool cgfs_iterate_cgroup(const char *controller, const char *cgroup, bool directories,
748 void ***list, size_t typesize,
749 void* (*iterator)(const char*, const char*, const char*))
237e200e 750{
4ea38a4c 751 int cfd, fd, ret;
237e200e 752 size_t len;
4ea38a4c 753 char *cg, *tmpc;
237e200e 754 char pathname[MAXPATHLEN];
f366da65 755 size_t sz = 0, asz = 0;
4ea38a4c 756 struct dirent *dirent;
237e200e 757 DIR *dir;
237e200e 758
4ea38a4c 759 tmpc = find_mounted_controller(controller, &cfd);
f366da65 760 *list = NULL;
237e200e 761 if (!tmpc)
e97c834b 762 return false;
237e200e 763
f5a6d92e 764 /* Make sure we pass a relative path to *at() family of functions. */
4ea38a4c
CB
765 len = strlen(cgroup) + 1 /* . */ + 1 /* \0 */;
766 cg = alloca(len);
767 ret = snprintf(cg, len, "%s%s", *cgroup == '/' ? "." : "", cgroup);
768 if (ret < 0 || (size_t)ret >= len) {
769 fprintf(stderr, "%s: pathname too long under %s\n", __func__, cgroup);
770 return false;
771 }
237e200e 772
4ea38a4c
CB
773 fd = openat(cfd, cg, O_DIRECTORY);
774 if (fd < 0)
775 return false;
776
777 dir = fdopendir(fd);
237e200e
SH
778 if (!dir)
779 return false;
780
4ea38a4c 781 while ((dirent = readdir(dir))) {
237e200e 782 struct stat mystat;
237e200e 783
4ea38a4c
CB
784 if (!strcmp(dirent->d_name, ".") ||
785 !strcmp(dirent->d_name, ".."))
237e200e
SH
786 continue;
787
4ea38a4c
CB
788 ret = snprintf(pathname, MAXPATHLEN, "%s/%s", cg, dirent->d_name);
789 if (ret < 0 || ret >= MAXPATHLEN) {
790 fprintf(stderr, "%s: pathname too long under %s\n", __func__, cg);
237e200e
SH
791 continue;
792 }
793
4ea38a4c 794 ret = fstatat(cfd, pathname, &mystat, AT_SYMLINK_NOFOLLOW);
237e200e
SH
795 if (ret) {
796 fprintf(stderr, "%s: failed to stat %s: %s\n", __func__, pathname, strerror(errno));
797 continue;
798 }
f366da65
WB
799 if ((!directories && !S_ISREG(mystat.st_mode)) ||
800 (directories && !S_ISDIR(mystat.st_mode)))
237e200e
SH
801 continue;
802
803 if (sz+2 >= asz) {
f366da65 804 void **tmp;
237e200e
SH
805 asz += BATCH_SIZE;
806 do {
f366da65 807 tmp = realloc(*list, asz * typesize);
237e200e
SH
808 } while (!tmp);
809 *list = tmp;
810 }
4ea38a4c 811 (*list)[sz] = (*iterator)(controller, cg, dirent->d_name);
237e200e
SH
812 (*list)[sz+1] = NULL;
813 sz++;
814 }
815 if (closedir(dir) < 0) {
4ea38a4c 816 fprintf(stderr, "%s: failed closedir for %s: %s\n", __func__, cgroup, strerror(errno));
237e200e
SH
817 return false;
818 }
819 return true;
820}
821
f366da65
WB
822static void *make_children_list_entry(const char *controller, const char *cgroup, const char *dir_entry)
823{
824 char *dup;
825 do {
826 dup = strdup(dir_entry);
827 } while (!dup);
828 return dup;
829}
830
831bool cgfs_list_children(const char *controller, const char *cgroup, char ***list)
832{
833 return cgfs_iterate_cgroup(controller, cgroup, true, (void***)list, sizeof(*list), &make_children_list_entry);
834}
835
237e200e
SH
836void free_key(struct cgfs_files *k)
837{
838 if (!k)
839 return;
840 free(k->name);
841 free(k);
842}
843
844void free_keys(struct cgfs_files **keys)
845{
846 int i;
847
848 if (!keys)
849 return;
850 for (i = 0; keys[i]; i++) {
851 free_key(keys[i]);
852 }
853 free(keys);
854}
855
856bool cgfs_get_value(const char *controller, const char *cgroup, const char *file, char **value)
857{
60f2ae53 858 int ret, fd, cfd;
237e200e 859 size_t len;
f5a6d92e 860 char *fnam, *tmpc;
237e200e 861
f5a6d92e 862 tmpc = find_mounted_controller(controller, &cfd);
237e200e
SH
863 if (!tmpc)
864 return false;
f5a6d92e
CB
865
866 /* Make sure we pass a relative path to *at() family of functions.
867 * . + /cgroup + / + file + \0
868 */
60f2ae53 869 len = strlen(cgroup) + strlen(file) + 3;
237e200e 870 fnam = alloca(len);
60f2ae53
CB
871 ret = snprintf(fnam, len, "%s%s/%s", *cgroup == '/' ? "." : "", cgroup, file);
872 if (ret < 0 || (size_t)ret >= len)
873 return NULL;
874
875 fd = openat(cfd, fnam, O_RDONLY);
876 if (fd < 0)
877 return NULL;
237e200e 878
60f2ae53 879 *value = slurp_file(fnam, fd);
237e200e
SH
880 return *value != NULL;
881}
882
883struct cgfs_files *cgfs_get_key(const char *controller, const char *cgroup, const char *file)
884{
4ea38a4c 885 int ret, cfd;
237e200e 886 size_t len;
f5a6d92e 887 char *fnam, *tmpc;
237e200e
SH
888 struct stat sb;
889 struct cgfs_files *newkey;
237e200e 890
f5a6d92e 891 tmpc = find_mounted_controller(controller, &cfd);
237e200e
SH
892 if (!tmpc)
893 return false;
894
895 if (file && *file == '/')
896 file++;
897
06081b29 898 if (file && strchr(file, '/'))
237e200e
SH
899 return NULL;
900
f5a6d92e
CB
901 /* Make sure we pass a relative path to *at() family of functions.
902 * . + /cgroup + / + file + \0
903 */
4ea38a4c 904 len = strlen(cgroup) + 3;
237e200e
SH
905 if (file)
906 len += strlen(file) + 1;
907 fnam = alloca(len);
4ea38a4c
CB
908 snprintf(fnam, len, "%s%s%s%s", *cgroup == '/' ? "." : "", cgroup,
909 file ? "/" : "", file ? file : "");
237e200e 910
4ea38a4c 911 ret = fstatat(cfd, fnam, &sb, 0);
237e200e
SH
912 if (ret < 0)
913 return NULL;
914
915 do {
916 newkey = malloc(sizeof(struct cgfs_files));
917 } while (!newkey);
918 if (file)
919 newkey->name = must_copy_string(file);
06081b29
CB
920 else if (strrchr(cgroup, '/'))
921 newkey->name = must_copy_string(strrchr(cgroup, '/'));
237e200e
SH
922 else
923 newkey->name = must_copy_string(cgroup);
924 newkey->uid = sb.st_uid;
925 newkey->gid = sb.st_gid;
926 newkey->mode = sb.st_mode;
927
928 return newkey;
929}
930
f366da65 931static void *make_key_list_entry(const char *controller, const char *cgroup, const char *dir_entry)
237e200e 932{
f366da65
WB
933 struct cgfs_files *entry = cgfs_get_key(controller, cgroup, dir_entry);
934 if (!entry) {
935 fprintf(stderr, "%s: Error getting files under %s:%s\n",
936 __func__, controller, cgroup);
237e200e 937 }
f366da65
WB
938 return entry;
939}
940
941bool cgfs_list_keys(const char *controller, const char *cgroup, struct cgfs_files ***keys)
942{
943 return cgfs_iterate_cgroup(controller, cgroup, false, (void***)keys, sizeof(*keys), &make_key_list_entry);
237e200e
SH
944}
945
946bool is_child_cgroup(const char *controller, const char *cgroup, const char *f)
5dd3e6fd
CB
947{
948 int cfd;
949 size_t len;
f5a6d92e 950 char *fnam, *tmpc;
237e200e
SH
951 int ret;
952 struct stat sb;
953
f5a6d92e 954 tmpc = find_mounted_controller(controller, &cfd);
237e200e
SH
955 if (!tmpc)
956 return false;
f5a6d92e
CB
957
958 /* Make sure we pass a relative path to *at() family of functions.
959 * . + /cgroup + / + f + \0
960 */
d04232f2 961 len = strlen(cgroup) + strlen(f) + 3;
237e200e 962 fnam = alloca(len);
d04232f2
CB
963 ret = snprintf(fnam, len, "%s%s/%s", *cgroup == '/' ? "." : "", cgroup, f);
964 if (ret < 0 || (size_t)ret >= len)
965 return false;
237e200e 966
d04232f2 967 ret = fstatat(cfd, fnam, &sb, 0);
237e200e
SH
968 if (ret < 0 || !S_ISDIR(sb.st_mode))
969 return false;
f5a6d92e 970
237e200e
SH
971 return true;
972}
973
974#define SEND_CREDS_OK 0
975#define SEND_CREDS_NOTSK 1
976#define SEND_CREDS_FAIL 2
977static bool recv_creds(int sock, struct ucred *cred, char *v);
978static int wait_for_pid(pid_t pid);
979static int send_creds(int sock, struct ucred *cred, char v, bool pingfirst);
b10bdd6c 980static int send_creds_clone_wrapper(void *arg);
237e200e
SH
981
982/*
b10bdd6c 983 * clone a task which switches to @task's namespace and writes '1'.
237e200e
SH
984 * over a unix sock so we can read the task's reaper's pid in our
985 * namespace
b10bdd6c
FG
986 *
987 * Note: glibc's fork() does not respect pidns, which can lead to failed
988 * assertions inside glibc (and thus failed forks) if the child's pid in
989 * the pidns and the parent pid outside are identical. Using clone prevents
990 * this issue.
237e200e
SH
991 */
992static void write_task_init_pid_exit(int sock, pid_t target)
993{
237e200e
SH
994 char fnam[100];
995 pid_t pid;
237e200e 996 int fd, ret;
b10bdd6c
FG
997 size_t stack_size = sysconf(_SC_PAGESIZE);
998 void *stack = alloca(stack_size);
237e200e
SH
999
1000 ret = snprintf(fnam, sizeof(fnam), "/proc/%d/ns/pid", (int)target);
1001 if (ret < 0 || ret >= sizeof(fnam))
1002 _exit(1);
1003
1004 fd = open(fnam, O_RDONLY);
1005 if (fd < 0) {
1006 perror("write_task_init_pid_exit open of ns/pid");
1007 _exit(1);
1008 }
1009 if (setns(fd, 0)) {
1010 perror("write_task_init_pid_exit setns 1");
1011 close(fd);
1012 _exit(1);
1013 }
b10bdd6c 1014 pid = clone(send_creds_clone_wrapper, stack + stack_size, SIGCHLD, &sock);
237e200e
SH
1015 if (pid < 0)
1016 _exit(1);
1017 if (pid != 0) {
1018 if (!wait_for_pid(pid))
1019 _exit(1);
1020 _exit(0);
1021 }
b10bdd6c
FG
1022}
1023
1024static int send_creds_clone_wrapper(void *arg) {
1025 struct ucred cred;
1026 char v;
1027 int sock = *(int *)arg;
237e200e
SH
1028
1029 /* we are the child */
1030 cred.uid = 0;
1031 cred.gid = 0;
1032 cred.pid = 1;
1033 v = '1';
1034 if (send_creds(sock, &cred, v, true) != SEND_CREDS_OK)
b10bdd6c
FG
1035 return 1;
1036 return 0;
237e200e
SH
1037}
1038
1039static pid_t get_init_pid_for_task(pid_t task)
1040{
1041 int sock[2];
1042 pid_t pid;
1043 pid_t ret = -1;
1044 char v = '0';
1045 struct ucred cred;
1046
1047 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, sock) < 0) {
1048 perror("socketpair");
1049 return -1;
1050 }
1051
1052 pid = fork();
1053 if (pid < 0)
1054 goto out;
1055 if (!pid) {
1056 close(sock[1]);
1057 write_task_init_pid_exit(sock[0], task);
1058 _exit(0);
1059 }
1060
1061 if (!recv_creds(sock[1], &cred, &v))
1062 goto out;
1063 ret = cred.pid;
1064
1065out:
1066 close(sock[0]);
1067 close(sock[1]);
1068 if (pid > 0)
1069 wait_for_pid(pid);
1070 return ret;
1071}
1072
1073static pid_t lookup_initpid_in_store(pid_t qpid)
1074{
1075 pid_t answer = 0;
1076 struct stat sb;
1077 struct pidns_init_store *e;
1078 char fnam[100];
1079
1080 snprintf(fnam, 100, "/proc/%d/ns/pid", qpid);
1081 store_lock();
1082 if (stat(fnam, &sb) < 0)
1083 goto out;
1084 e = lookup_verify_initpid(&sb);
1085 if (e) {
1086 answer = e->initpid;
1087 goto out;
1088 }
1089 answer = get_init_pid_for_task(qpid);
1090 if (answer > 0)
1091 save_initpid(&sb, answer);
1092
1093out:
1094 /* we prune at end in case we are returning
1095 * the value we were about to return */
1096 prune_initpid_store();
1097 store_unlock();
1098 return answer;
1099}
1100
1101static int wait_for_pid(pid_t pid)
1102{
1103 int status, ret;
1104
1105 if (pid <= 0)
1106 return -1;
1107
1108again:
1109 ret = waitpid(pid, &status, 0);
1110 if (ret == -1) {
1111 if (errno == EINTR)
1112 goto again;
1113 return -1;
1114 }
1115 if (ret != pid)
1116 goto again;
1117 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
1118 return -1;
1119 return 0;
1120}
1121
1122
1123/*
1124 * append pid to *src.
1125 * src: a pointer to a char* in which ot append the pid.
1126 * sz: the number of characters printed so far, minus trailing \0.
1127 * asz: the allocated size so far
1128 * pid: the pid to append
1129 */
1130static void must_strcat_pid(char **src, size_t *sz, size_t *asz, pid_t pid)
1131{
1132 char tmp[30];
1133
1134 int tmplen = sprintf(tmp, "%d\n", (int)pid);
1135
1136 if (!*src || tmplen + *sz + 1 >= *asz) {
1137 char *tmp;
1138 do {
1139 tmp = realloc(*src, *asz + BUF_RESERVE_SIZE);
1140 } while (!tmp);
1141 *src = tmp;
1142 *asz += BUF_RESERVE_SIZE;
1143 }
bbfd0e33 1144 memcpy((*src) +*sz , tmp, tmplen+1); /* include the \0 */
237e200e 1145 *sz += tmplen;
237e200e
SH
1146}
1147
1148/*
1149 * Given a open file * to /proc/pid/{u,g}id_map, and an id
1150 * valid in the caller's namespace, return the id mapped into
1151 * pid's namespace.
1152 * Returns the mapped id, or -1 on error.
1153 */
1154unsigned int
1155convert_id_to_ns(FILE *idfile, unsigned int in_id)
1156{
1157 unsigned int nsuid, // base id for a range in the idfile's namespace
1158 hostuid, // base id for a range in the caller's namespace
1159 count; // number of ids in this range
1160 char line[400];
1161 int ret;
1162
1163 fseek(idfile, 0L, SEEK_SET);
1164 while (fgets(line, 400, idfile)) {
1165 ret = sscanf(line, "%u %u %u\n", &nsuid, &hostuid, &count);
1166 if (ret != 3)
1167 continue;
1168 if (hostuid + count < hostuid || nsuid + count < nsuid) {
1169 /*
1170 * uids wrapped around - unexpected as this is a procfile,
1171 * so just bail.
1172 */
1173 fprintf(stderr, "pid wrapparound at entry %u %u %u in %s\n",
1174 nsuid, hostuid, count, line);
1175 return -1;
1176 }
1177 if (hostuid <= in_id && hostuid+count > in_id) {
1178 /*
1179 * now since hostuid <= in_id < hostuid+count, and
1180 * hostuid+count and nsuid+count do not wrap around,
1181 * we know that nsuid+(in_id-hostuid) which must be
1182 * less that nsuid+(count) must not wrap around
1183 */
1184 return (in_id - hostuid) + nsuid;
1185 }
1186 }
1187
1188 // no answer found
1189 return -1;
1190}
1191
1192/*
1193 * for is_privileged_over,
1194 * specify whether we require the calling uid to be root in his
1195 * namespace
1196 */
1197#define NS_ROOT_REQD true
1198#define NS_ROOT_OPT false
1199
1200#define PROCLEN 100
1201
1202static bool is_privileged_over(pid_t pid, uid_t uid, uid_t victim, bool req_ns_root)
1203{
1204 char fpath[PROCLEN];
1205 int ret;
1206 bool answer = false;
1207 uid_t nsuid;
1208
1209 if (victim == -1 || uid == -1)
1210 return false;
1211
1212 /*
1213 * If the request is one not requiring root in the namespace,
1214 * then having the same uid suffices. (i.e. uid 1000 has write
1215 * access to files owned by uid 1000
1216 */
1217 if (!req_ns_root && uid == victim)
1218 return true;
1219
1220 ret = snprintf(fpath, PROCLEN, "/proc/%d/uid_map", pid);
1221 if (ret < 0 || ret >= PROCLEN)
1222 return false;
1223 FILE *f = fopen(fpath, "r");
1224 if (!f)
1225 return false;
1226
1227 /* if caller's not root in his namespace, reject */
1228 nsuid = convert_id_to_ns(f, uid);
1229 if (nsuid)
1230 goto out;
1231
1232 /*
1233 * If victim is not mapped into caller's ns, reject.
1234 * XXX I'm not sure this check is needed given that fuse
1235 * will be sending requests where the vfs has converted
1236 */
1237 nsuid = convert_id_to_ns(f, victim);
1238 if (nsuid == -1)
1239 goto out;
1240
1241 answer = true;
1242
1243out:
1244 fclose(f);
1245 return answer;
1246}
1247
1248static bool perms_include(int fmode, mode_t req_mode)
1249{
1250 mode_t r;
1251
1252 switch (req_mode & O_ACCMODE) {
1253 case O_RDONLY:
1254 r = S_IROTH;
1255 break;
1256 case O_WRONLY:
1257 r = S_IWOTH;
1258 break;
1259 case O_RDWR:
1260 r = S_IROTH | S_IWOTH;
1261 break;
1262 default:
1263 return false;
1264 }
1265 return ((fmode & r) == r);
1266}
1267
1268
1269/*
1270 * taskcg is a/b/c
1271 * querycg is /a/b/c/d/e
1272 * we return 'd'
1273 */
1274static char *get_next_cgroup_dir(const char *taskcg, const char *querycg)
1275{
1276 char *start, *end;
1277
1278 if (strlen(taskcg) <= strlen(querycg)) {
1279 fprintf(stderr, "%s: I was fed bad input\n", __func__);
1280 return NULL;
1281 }
1282
06081b29 1283 if ((strcmp(querycg, "/") == 0) || (strcmp(querycg, "./") == 0))
237e200e
SH
1284 start = strdup(taskcg + 1);
1285 else
1286 start = strdup(taskcg + strlen(querycg) + 1);
1287 if (!start)
1288 return NULL;
1289 end = strchr(start, '/');
1290 if (end)
1291 *end = '\0';
1292 return start;
1293}
1294
1295static void stripnewline(char *x)
1296{
1297 size_t l = strlen(x);
1298 if (l && x[l-1] == '\n')
1299 x[l-1] = '\0';
1300}
1301
1302static char *get_pid_cgroup(pid_t pid, const char *contrl)
1303{
5dd3e6fd 1304 int cfd;
237e200e
SH
1305 char fnam[PROCLEN];
1306 FILE *f;
1307 char *answer = NULL;
1308 char *line = NULL;
1309 size_t len = 0;
1310 int ret;
5dd3e6fd 1311 const char *h = find_mounted_controller(contrl, &cfd);
237e200e
SH
1312 if (!h)
1313 return NULL;
1314
1315 ret = snprintf(fnam, PROCLEN, "/proc/%d/cgroup", pid);
1316 if (ret < 0 || ret >= PROCLEN)
1317 return NULL;
1318 if (!(f = fopen(fnam, "r")))
1319 return NULL;
1320
1321 while (getline(&line, &len, f) != -1) {
1322 char *c1, *c2;
1323 if (!line[0])
1324 continue;
1325 c1 = strchr(line, ':');
1326 if (!c1)
1327 goto out;
1328 c1++;
1329 c2 = strchr(c1, ':');
1330 if (!c2)
1331 goto out;
1332 *c2 = '\0';
1333 if (strcmp(c1, h) != 0)
1334 continue;
1335 c2++;
1336 stripnewline(c2);
1337 do {
1338 answer = strdup(c2);
1339 } while (!answer);
1340 break;
1341 }
1342
1343out:
1344 fclose(f);
1345 free(line);
1346 return answer;
1347}
1348
1349/*
1350 * check whether a fuse context may access a cgroup dir or file
1351 *
1352 * If file is not null, it is a cgroup file to check under cg.
1353 * If file is null, then we are checking perms on cg itself.
1354 *
1355 * For files we can check the mode of the list_keys result.
1356 * For cgroups, we must make assumptions based on the files under the
1357 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
1358 * yet.
1359 */
1360static bool fc_may_access(struct fuse_context *fc, const char *contrl, const char *cg, const char *file, mode_t mode)
1361{
1362 struct cgfs_files *k = NULL;
1363 bool ret = false;
1364
1365 k = cgfs_get_key(contrl, cg, file);
1366 if (!k)
1367 return false;
1368
1369 if (is_privileged_over(fc->pid, fc->uid, k->uid, NS_ROOT_OPT)) {
1370 if (perms_include(k->mode >> 6, mode)) {
1371 ret = true;
1372 goto out;
1373 }
1374 }
1375 if (fc->gid == k->gid) {
1376 if (perms_include(k->mode >> 3, mode)) {
1377 ret = true;
1378 goto out;
1379 }
1380 }
1381 ret = perms_include(k->mode, mode);
1382
1383out:
1384 free_key(k);
1385 return ret;
1386}
1387
1388#define INITSCOPE "/init.scope"
1389static void prune_init_slice(char *cg)
1390{
1391 char *point;
1392 size_t cg_len = strlen(cg), initscope_len = strlen(INITSCOPE);
1393
1394 if (cg_len < initscope_len)
1395 return;
1396
1397 point = cg + cg_len - initscope_len;
1398 if (strcmp(point, INITSCOPE) == 0) {
1399 if (point == cg)
1400 *(point+1) = '\0';
1401 else
1402 *point = '\0';
1403 }
1404}
1405
1406/*
1407 * If pid is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
1408 * If pid is in /a, he may act on /a/b, but not on /b.
1409 * if the answer is false and nextcg is not NULL, then *nextcg will point
1410 * to a string containing the next cgroup directory under cg, which must be
1411 * freed by the caller.
1412 */
1413static bool caller_is_in_ancestor(pid_t pid, const char *contrl, const char *cg, char **nextcg)
1414{
1415 bool answer = false;
1416 char *c2 = get_pid_cgroup(pid, contrl);
1417 char *linecmp;
1418
1419 if (!c2)
1420 return false;
1421 prune_init_slice(c2);
1422
1423 /*
12c31268
CB
1424 * callers pass in '/' or './' (openat()) for root cgroup, otherwise
1425 * they pass in a cgroup without leading '/'
1426 *
1427 * The original line here was:
1428 * linecmp = *cg == '/' ? c2 : c2+1;
1429 * TODO: I'm not sure why you'd want to increment when *cg != '/'?
1430 * Serge, do you know?
237e200e 1431 */
12c31268
CB
1432 if (*cg == '/' || !strncmp(cg, "./", 2))
1433 linecmp = c2;
1434 else
1435 linecmp = c2 + 1;
237e200e
SH
1436 if (strncmp(linecmp, cg, strlen(linecmp)) != 0) {
1437 if (nextcg) {
1438 *nextcg = get_next_cgroup_dir(linecmp, cg);
1439 }
1440 goto out;
1441 }
1442 answer = true;
1443
1444out:
1445 free(c2);
1446 return answer;
1447}
1448
1449/*
1450 * If pid is in /a/b/c, he may see that /a exists, but not /b or /a/c.
1451 */
1452static bool caller_may_see_dir(pid_t pid, const char *contrl, const char *cg)
1453{
1454 bool answer = false;
1455 char *c2, *task_cg;
1456 size_t target_len, task_len;
1457
f7bff426 1458 if (strcmp(cg, "/") == 0 || strcmp(cg, "./") == 0)
237e200e
SH
1459 return true;
1460
1461 c2 = get_pid_cgroup(pid, contrl);
1462 if (!c2)
1463 return false;
1464 prune_init_slice(c2);
1465
1466 task_cg = c2 + 1;
1467 target_len = strlen(cg);
1468 task_len = strlen(task_cg);
1469 if (task_len == 0) {
1470 /* Task is in the root cg, it can see everything. This case is
1471 * not handled by the strmcps below, since they test for the
1472 * last /, but that is the first / that we've chopped off
1473 * above.
1474 */
1475 answer = true;
1476 goto out;
1477 }
1478 if (strcmp(cg, task_cg) == 0) {
1479 answer = true;
1480 goto out;
1481 }
1482 if (target_len < task_len) {
1483 /* looking up a parent dir */
1484 if (strncmp(task_cg, cg, target_len) == 0 && task_cg[target_len] == '/')
1485 answer = true;
1486 goto out;
1487 }
1488 if (target_len > task_len) {
1489 /* looking up a child dir */
1490 if (strncmp(task_cg, cg, task_len) == 0 && cg[task_len] == '/')
1491 answer = true;
1492 goto out;
1493 }
1494
1495out:
1496 free(c2);
1497 return answer;
1498}
1499
1500/*
1501 * given /cgroup/freezer/a/b, return "freezer".
1502 * the returned char* should NOT be freed.
1503 */
1504static char *pick_controller_from_path(struct fuse_context *fc, const char *path)
1505{
1506 const char *p1;
1507 char *contr, *slash;
1508
99142521
CB
1509 if (strlen(path) < 9) {
1510 errno = EINVAL;
237e200e 1511 return NULL;
99142521
CB
1512 }
1513 if (*(path + 7) != '/') {
1514 errno = EINVAL;
237e200e 1515 return NULL;
99142521 1516 }
3adc421c 1517 p1 = path + 8;
237e200e 1518 contr = strdupa(p1);
99142521
CB
1519 if (!contr) {
1520 errno = ENOMEM;
237e200e 1521 return NULL;
99142521 1522 }
237e200e
SH
1523 slash = strstr(contr, "/");
1524 if (slash)
1525 *slash = '\0';
1526
1527 int i;
3adc421c 1528 for (i = 0; i < num_hierarchies; i++) {
237e200e
SH
1529 if (hierarchies[i] && strcmp(hierarchies[i], contr) == 0)
1530 return hierarchies[i];
1531 }
99142521 1532 errno = ENOENT;
237e200e
SH
1533 return NULL;
1534}
1535
1536/*
1537 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
1538 * Note that the returned value may include files (keynames) etc
1539 */
1540static const char *find_cgroup_in_path(const char *path)
1541{
1542 const char *p1;
1543
1544 if (strlen(path) < 9)
1545 return NULL;
1546 p1 = strstr(path+8, "/");
1547 if (!p1)
1548 return NULL;
1549 return p1+1;
1550}
1551
1552/*
1553 * split the last path element from the path in @cg.
1554 * @dir is newly allocated and should be freed, @last not
1555*/
1556static void get_cgdir_and_path(const char *cg, char **dir, char **last)
1557{
1558 char *p;
1559
1560 do {
1561 *dir = strdup(cg);
1562 } while (!*dir);
1563 *last = strrchr(cg, '/');
1564 if (!*last) {
1565 *last = NULL;
1566 return;
1567 }
1568 p = strrchr(*dir, '/');
1569 *p = '\0';
1570}
1571
1572/*
1573 * FUSE ops for /cgroup
1574 */
1575
1576int cg_getattr(const char *path, struct stat *sb)
1577{
1578 struct timespec now;
1579 struct fuse_context *fc = fuse_get_context();
1580 char * cgdir = NULL;
1581 char *last = NULL, *path1, *path2;
1582 struct cgfs_files *k = NULL;
1583 const char *cgroup;
1584 const char *controller = NULL;
1585 int ret = -ENOENT;
1586
1587
1588 if (!fc)
1589 return -EIO;
1590
1591 memset(sb, 0, sizeof(struct stat));
1592
1593 if (clock_gettime(CLOCK_REALTIME, &now) < 0)
1594 return -EINVAL;
1595
1596 sb->st_uid = sb->st_gid = 0;
1597 sb->st_atim = sb->st_mtim = sb->st_ctim = now;
1598 sb->st_size = 0;
1599
1600 if (strcmp(path, "/cgroup") == 0) {
1601 sb->st_mode = S_IFDIR | 00755;
1602 sb->st_nlink = 2;
1603 return 0;
1604 }
1605
1606 controller = pick_controller_from_path(fc, path);
1607 if (!controller)
2f7036d0 1608 return -errno;
237e200e
SH
1609 cgroup = find_cgroup_in_path(path);
1610 if (!cgroup) {
1611 /* this is just /cgroup/controller, return it as a dir */
1612 sb->st_mode = S_IFDIR | 00755;
1613 sb->st_nlink = 2;
1614 return 0;
1615 }
1616
1617 get_cgdir_and_path(cgroup, &cgdir, &last);
1618
1619 if (!last) {
1620 path1 = "/";
1621 path2 = cgdir;
1622 } else {
1623 path1 = cgdir;
1624 path2 = last;
1625 }
1626
1627 pid_t initpid = lookup_initpid_in_store(fc->pid);
1628 if (initpid <= 0)
1629 initpid = fc->pid;
1630 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
1631 * Then check that caller's cgroup is under path if last is a child
1632 * cgroup, or cgdir if last is a file */
1633
1634 if (is_child_cgroup(controller, path1, path2)) {
1635 if (!caller_may_see_dir(initpid, controller, cgroup)) {
1636 ret = -ENOENT;
1637 goto out;
1638 }
1639 if (!caller_is_in_ancestor(initpid, controller, cgroup, NULL)) {
1640 /* this is just /cgroup/controller, return it as a dir */
1641 sb->st_mode = S_IFDIR | 00555;
1642 sb->st_nlink = 2;
1643 ret = 0;
1644 goto out;
1645 }
1646 if (!fc_may_access(fc, controller, cgroup, NULL, O_RDONLY)) {
1647 ret = -EACCES;
1648 goto out;
1649 }
1650
1651 // get uid, gid, from '/tasks' file and make up a mode
1652 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1653 sb->st_mode = S_IFDIR | 00755;
1654 k = cgfs_get_key(controller, cgroup, NULL);
1655 if (!k) {
1656 sb->st_uid = sb->st_gid = 0;
1657 } else {
1658 sb->st_uid = k->uid;
1659 sb->st_gid = k->gid;
1660 }
1661 free_key(k);
1662 sb->st_nlink = 2;
1663 ret = 0;
1664 goto out;
1665 }
1666
1667 if ((k = cgfs_get_key(controller, path1, path2)) != NULL) {
1668 sb->st_mode = S_IFREG | k->mode;
1669 sb->st_nlink = 1;
1670 sb->st_uid = k->uid;
1671 sb->st_gid = k->gid;
1672 sb->st_size = 0;
1673 free_key(k);
1674 if (!caller_is_in_ancestor(initpid, controller, path1, NULL)) {
1675 ret = -ENOENT;
1676 goto out;
1677 }
1678 if (!fc_may_access(fc, controller, path1, path2, O_RDONLY)) {
1679 ret = -EACCES;
1680 goto out;
1681 }
1682
1683 ret = 0;
1684 }
1685
1686out:
1687 free(cgdir);
1688 return ret;
1689}
1690
1691int cg_opendir(const char *path, struct fuse_file_info *fi)
1692{
1693 struct fuse_context *fc = fuse_get_context();
1694 const char *cgroup;
1695 struct file_info *dir_info;
1696 char *controller = NULL;
1697
1698 if (!fc)
1699 return -EIO;
1700
1701 if (strcmp(path, "/cgroup") == 0) {
1702 cgroup = NULL;
1703 controller = NULL;
1704 } else {
1705 // return list of keys for the controller, and list of child cgroups
1706 controller = pick_controller_from_path(fc, path);
1707 if (!controller)
2f7036d0 1708 return -errno;
237e200e
SH
1709
1710 cgroup = find_cgroup_in_path(path);
1711 if (!cgroup) {
1712 /* this is just /cgroup/controller, return its contents */
1713 cgroup = "/";
1714 }
1715 }
1716
1717 pid_t initpid = lookup_initpid_in_store(fc->pid);
1718 if (initpid <= 0)
1719 initpid = fc->pid;
1720 if (cgroup) {
1721 if (!caller_may_see_dir(initpid, controller, cgroup))
1722 return -ENOENT;
1723 if (!fc_may_access(fc, controller, cgroup, NULL, O_RDONLY))
1724 return -EACCES;
1725 }
1726
1727 /* we'll free this at cg_releasedir */
1728 dir_info = malloc(sizeof(*dir_info));
1729 if (!dir_info)
1730 return -ENOMEM;
1731 dir_info->controller = must_copy_string(controller);
1732 dir_info->cgroup = must_copy_string(cgroup);
1733 dir_info->type = LXC_TYPE_CGDIR;
1734 dir_info->buf = NULL;
1735 dir_info->file = NULL;
1736 dir_info->buflen = 0;
1737
1738 fi->fh = (unsigned long)dir_info;
1739 return 0;
1740}
1741
1742int cg_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset,
1743 struct fuse_file_info *fi)
1744{
1745 struct file_info *d = (struct file_info *)fi->fh;
1746 struct cgfs_files **list = NULL;
1747 int i, ret;
1748 char *nextcg = NULL;
1749 struct fuse_context *fc = fuse_get_context();
1750 char **clist = NULL;
1751
d639f863
CB
1752 if (filler(buf, ".", NULL, 0) != 0 || filler(buf, "..", NULL, 0) != 0)
1753 return -EIO;
1754
237e200e
SH
1755 if (d->type != LXC_TYPE_CGDIR) {
1756 fprintf(stderr, "Internal error: file cache info used in readdir\n");
1757 return -EIO;
1758 }
1759 if (!d->cgroup && !d->controller) {
1760 // ls /var/lib/lxcfs/cgroup - just show list of controllers
1761 int i;
1762
1763 for (i = 0; i < num_hierarchies; i++) {
1764 if (hierarchies[i] && filler(buf, hierarchies[i], NULL, 0) != 0) {
1765 return -EIO;
1766 }
1767 }
1768 return 0;
1769 }
1770
1771 if (!cgfs_list_keys(d->controller, d->cgroup, &list)) {
1772 // not a valid cgroup
1773 ret = -EINVAL;
1774 goto out;
1775 }
1776
1777 pid_t initpid = lookup_initpid_in_store(fc->pid);
1778 if (initpid <= 0)
1779 initpid = fc->pid;
1780 if (!caller_is_in_ancestor(initpid, d->controller, d->cgroup, &nextcg)) {
1781 if (nextcg) {
1782 ret = filler(buf, nextcg, NULL, 0);
1783 free(nextcg);
1784 if (ret != 0) {
1785 ret = -EIO;
1786 goto out;
1787 }
1788 }
1789 ret = 0;
1790 goto out;
1791 }
1792
1793 for (i = 0; list[i]; i++) {
1794 if (filler(buf, list[i]->name, NULL, 0) != 0) {
1795 ret = -EIO;
1796 goto out;
1797 }
1798 }
1799
1800 // now get the list of child cgroups
1801
1802 if (!cgfs_list_children(d->controller, d->cgroup, &clist)) {
1803 ret = 0;
1804 goto out;
1805 }
f366da65
WB
1806 if (clist) {
1807 for (i = 0; clist[i]; i++) {
1808 if (filler(buf, clist[i], NULL, 0) != 0) {
1809 ret = -EIO;
1810 goto out;
1811 }
237e200e
SH
1812 }
1813 }
1814 ret = 0;
1815
1816out:
1817 free_keys(list);
1818 if (clist) {
1819 for (i = 0; clist[i]; i++)
1820 free(clist[i]);
1821 free(clist);
1822 }
1823 return ret;
1824}
1825
43215927 1826static void do_release_file_info(struct fuse_file_info *fi)
237e200e 1827{
43215927
SH
1828 struct file_info *f = (struct file_info *)fi->fh;
1829
237e200e
SH
1830 if (!f)
1831 return;
43215927
SH
1832
1833 fi->fh = 0;
1834
237e200e 1835 free(f->controller);
43215927 1836 f->controller = NULL;
237e200e 1837 free(f->cgroup);
43215927 1838 f->cgroup = NULL;
237e200e 1839 free(f->file);
43215927 1840 f->file = NULL;
237e200e 1841 free(f->buf);
43215927 1842 f->buf = NULL;
237e200e
SH
1843 free(f);
1844}
1845
1846int cg_releasedir(const char *path, struct fuse_file_info *fi)
1847{
43215927 1848 do_release_file_info(fi);
237e200e
SH
1849 return 0;
1850}
1851
1852int cg_open(const char *path, struct fuse_file_info *fi)
1853{
1854 const char *cgroup;
1855 char *last = NULL, *path1, *path2, * cgdir = NULL, *controller;
1856 struct cgfs_files *k = NULL;
1857 struct file_info *file_info;
1858 struct fuse_context *fc = fuse_get_context();
1859 int ret;
1860
1861 if (!fc)
1862 return -EIO;
1863
1864 controller = pick_controller_from_path(fc, path);
1865 if (!controller)
2f7036d0 1866 return -errno;
237e200e
SH
1867 cgroup = find_cgroup_in_path(path);
1868 if (!cgroup)
1869 return -EINVAL;
1870
1871 get_cgdir_and_path(cgroup, &cgdir, &last);
1872 if (!last) {
1873 path1 = "/";
1874 path2 = cgdir;
1875 } else {
1876 path1 = cgdir;
1877 path2 = last;
1878 }
1879
1880 k = cgfs_get_key(controller, path1, path2);
1881 if (!k) {
1882 ret = -EINVAL;
1883 goto out;
1884 }
1885 free_key(k);
1886
1887 pid_t initpid = lookup_initpid_in_store(fc->pid);
1888 if (initpid <= 0)
1889 initpid = fc->pid;
1890 if (!caller_may_see_dir(initpid, controller, path1)) {
1891 ret = -ENOENT;
1892 goto out;
1893 }
1894 if (!fc_may_access(fc, controller, path1, path2, fi->flags)) {
237e200e
SH
1895 ret = -EACCES;
1896 goto out;
1897 }
1898
1899 /* we'll free this at cg_release */
1900 file_info = malloc(sizeof(*file_info));
1901 if (!file_info) {
1902 ret = -ENOMEM;
1903 goto out;
1904 }
1905 file_info->controller = must_copy_string(controller);
1906 file_info->cgroup = must_copy_string(path1);
1907 file_info->file = must_copy_string(path2);
1908 file_info->type = LXC_TYPE_CGFILE;
1909 file_info->buf = NULL;
1910 file_info->buflen = 0;
1911
1912 fi->fh = (unsigned long)file_info;
1913 ret = 0;
1914
1915out:
1916 free(cgdir);
1917 return ret;
1918}
1919
bddbb106
SH
1920int cg_access(const char *path, int mode)
1921{
6f0f6b83 1922 int ret;
bddbb106 1923 const char *cgroup;
6f0f6b83
CB
1924 char *path1, *path2, *controller;
1925 char *last = NULL, *cgdir = NULL;
bddbb106
SH
1926 struct cgfs_files *k = NULL;
1927 struct fuse_context *fc = fuse_get_context();
6f0f6b83 1928
9873c5e8 1929 if (strcmp(path, "/cgroup") == 0)
6f0f6b83 1930 return 0;
bddbb106
SH
1931
1932 if (!fc)
1933 return -EIO;
1934
1935 controller = pick_controller_from_path(fc, path);
1936 if (!controller)
2f7036d0 1937 return -errno;
bddbb106 1938 cgroup = find_cgroup_in_path(path);
575316c4
SH
1939 if (!cgroup) {
1940 // access("/sys/fs/cgroup/systemd", mode) - rx allowed, w not
3f441bc7
SH
1941 if ((mode & W_OK) == 0)
1942 return 0;
1943 return -EACCES;
575316c4 1944 }
bddbb106
SH
1945
1946 get_cgdir_and_path(cgroup, &cgdir, &last);
1947 if (!last) {
1948 path1 = "/";
1949 path2 = cgdir;
1950 } else {
1951 path1 = cgdir;
1952 path2 = last;
1953 }
1954
1955 k = cgfs_get_key(controller, path1, path2);
1956 if (!k) {
3f441bc7
SH
1957 if ((mode & W_OK) == 0)
1958 ret = 0;
1959 else
1960 ret = -EACCES;
bddbb106
SH
1961 goto out;
1962 }
1963 free_key(k);
1964
1965 pid_t initpid = lookup_initpid_in_store(fc->pid);
1966 if (initpid <= 0)
1967 initpid = fc->pid;
1968 if (!caller_may_see_dir(initpid, controller, path1)) {
1969 ret = -ENOENT;
1970 goto out;
1971 }
1972 if (!fc_may_access(fc, controller, path1, path2, mode)) {
1973 ret = -EACCES;
1974 goto out;
1975 }
1976
1977 ret = 0;
1978
1979out:
1980 free(cgdir);
1981 return ret;
1982}
1983
237e200e
SH
1984int cg_release(const char *path, struct fuse_file_info *fi)
1985{
43215927 1986 do_release_file_info(fi);
237e200e
SH
1987 return 0;
1988}
1989
1990#define POLLIN_SET ( EPOLLIN | EPOLLHUP | EPOLLRDHUP )
1991
1992static bool wait_for_sock(int sock, int timeout)
1993{
1994 struct epoll_event ev;
1995 int epfd, ret, now, starttime, deltatime, saved_errno;
1996
1997 if ((starttime = time(NULL)) < 0)
1998 return false;
1999
2000 if ((epfd = epoll_create(1)) < 0) {
2001 fprintf(stderr, "Failed to create epoll socket: %m\n");
2002 return false;
2003 }
2004
2005 ev.events = POLLIN_SET;
2006 ev.data.fd = sock;
2007 if (epoll_ctl(epfd, EPOLL_CTL_ADD, sock, &ev) < 0) {
2008 fprintf(stderr, "Failed adding socket to epoll: %m\n");
2009 close(epfd);
2010 return false;
2011 }
2012
2013again:
2014 if ((now = time(NULL)) < 0) {
2015 close(epfd);
2016 return false;
2017 }
2018
2019 deltatime = (starttime + timeout) - now;
2020 if (deltatime < 0) { // timeout
2021 errno = 0;
2022 close(epfd);
2023 return false;
2024 }
2025 ret = epoll_wait(epfd, &ev, 1, 1000*deltatime + 1);
2026 if (ret < 0 && errno == EINTR)
2027 goto again;
2028 saved_errno = errno;
2029 close(epfd);
2030
2031 if (ret <= 0) {
2032 errno = saved_errno;
2033 return false;
2034 }
2035 return true;
2036}
2037
2038static int msgrecv(int sockfd, void *buf, size_t len)
2039{
2040 if (!wait_for_sock(sockfd, 2))
2041 return -1;
2042 return recv(sockfd, buf, len, MSG_DONTWAIT);
2043}
2044
2045static int send_creds(int sock, struct ucred *cred, char v, bool pingfirst)
2046{
2047 struct msghdr msg = { 0 };
2048 struct iovec iov;
2049 struct cmsghdr *cmsg;
2050 char cmsgbuf[CMSG_SPACE(sizeof(*cred))];
2051 char buf[1];
2052 buf[0] = 'p';
2053
2054 if (pingfirst) {
2055 if (msgrecv(sock, buf, 1) != 1) {
2056 fprintf(stderr, "%s: Error getting reply from server over socketpair\n",
2057 __func__);
2058 return SEND_CREDS_FAIL;
2059 }
2060 }
2061
2062 msg.msg_control = cmsgbuf;
2063 msg.msg_controllen = sizeof(cmsgbuf);
2064
2065 cmsg = CMSG_FIRSTHDR(&msg);
2066 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
2067 cmsg->cmsg_level = SOL_SOCKET;
2068 cmsg->cmsg_type = SCM_CREDENTIALS;
2069 memcpy(CMSG_DATA(cmsg), cred, sizeof(*cred));
2070
2071 msg.msg_name = NULL;
2072 msg.msg_namelen = 0;
2073
2074 buf[0] = v;
2075 iov.iov_base = buf;
2076 iov.iov_len = sizeof(buf);
2077 msg.msg_iov = &iov;
2078 msg.msg_iovlen = 1;
2079
2080 if (sendmsg(sock, &msg, 0) < 0) {
2081 fprintf(stderr, "%s: failed at sendmsg: %s\n", __func__,
2082 strerror(errno));
2083 if (errno == 3)
2084 return SEND_CREDS_NOTSK;
2085 return SEND_CREDS_FAIL;
2086 }
2087
2088 return SEND_CREDS_OK;
2089}
2090
2091static bool recv_creds(int sock, struct ucred *cred, char *v)
2092{
2093 struct msghdr msg = { 0 };
2094 struct iovec iov;
2095 struct cmsghdr *cmsg;
2096 char cmsgbuf[CMSG_SPACE(sizeof(*cred))];
2097 char buf[1];
2098 int ret;
2099 int optval = 1;
2100
2101 *v = '1';
2102
2103 cred->pid = -1;
2104 cred->uid = -1;
2105 cred->gid = -1;
2106
2107 if (setsockopt(sock, SOL_SOCKET, SO_PASSCRED, &optval, sizeof(optval)) == -1) {
2108 fprintf(stderr, "Failed to set passcred: %s\n", strerror(errno));
2109 return false;
2110 }
2111 buf[0] = '1';
2112 if (write(sock, buf, 1) != 1) {
2113 fprintf(stderr, "Failed to start write on scm fd: %s\n", strerror(errno));
2114 return false;
2115 }
2116
2117 msg.msg_name = NULL;
2118 msg.msg_namelen = 0;
2119 msg.msg_control = cmsgbuf;
2120 msg.msg_controllen = sizeof(cmsgbuf);
2121
2122 iov.iov_base = buf;
2123 iov.iov_len = sizeof(buf);
2124 msg.msg_iov = &iov;
2125 msg.msg_iovlen = 1;
2126
2127 if (!wait_for_sock(sock, 2)) {
2128 fprintf(stderr, "Timed out waiting for scm_cred: %s\n",
2129 strerror(errno));
2130 return false;
2131 }
2132 ret = recvmsg(sock, &msg, MSG_DONTWAIT);
2133 if (ret < 0) {
2134 fprintf(stderr, "Failed to receive scm_cred: %s\n",
2135 strerror(errno));
2136 return false;
2137 }
2138
2139 cmsg = CMSG_FIRSTHDR(&msg);
2140
2141 if (cmsg && cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)) &&
2142 cmsg->cmsg_level == SOL_SOCKET &&
2143 cmsg->cmsg_type == SCM_CREDENTIALS) {
2144 memcpy(cred, CMSG_DATA(cmsg), sizeof(*cred));
2145 }
2146 *v = buf[0];
2147
2148 return true;
2149}
2150
35174b0f
FG
2151struct pid_ns_clone_args {
2152 int *cpipe;
2153 int sock;
2154 pid_t tpid;
2155 int (*wrapped) (int, pid_t); // pid_from_ns or pid_to_ns
2156};
2157
2158/*
2159 * pid_ns_clone_wrapper - wraps pid_to_ns or pid_from_ns for usage
2160 * with clone(). This simply writes '1' as ACK back to the parent
2161 * before calling the actual wrapped function.
2162 */
2163static int pid_ns_clone_wrapper(void *arg) {
2164 struct pid_ns_clone_args* args = (struct pid_ns_clone_args *) arg;
2165 char b = '1';
2166
2167 close(args->cpipe[0]);
2168 if (write(args->cpipe[1], &b, sizeof(char)) < 0) {
2169 fprintf(stderr, "%s (child): error on write: %s\n",
2170 __func__, strerror(errno));
2171 }
2172 close(args->cpipe[1]);
2173 return args->wrapped(args->sock, args->tpid);
2174}
237e200e
SH
2175
2176/*
2177 * pid_to_ns - reads pids from a ucred over a socket, then writes the
2178 * int value back over the socket. This shifts the pid from the
2179 * sender's pidns into tpid's pidns.
2180 */
35174b0f 2181static int pid_to_ns(int sock, pid_t tpid)
237e200e
SH
2182{
2183 char v = '0';
2184 struct ucred cred;
2185
2186 while (recv_creds(sock, &cred, &v)) {
2187 if (v == '1')
35174b0f 2188 return 0;
237e200e 2189 if (write(sock, &cred.pid, sizeof(pid_t)) != sizeof(pid_t))
35174b0f 2190 return 1;
237e200e 2191 }
35174b0f 2192 return 0;
237e200e
SH
2193}
2194
35174b0f 2195
237e200e
SH
2196/*
2197 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
35174b0f
FG
2198 * in your old pidns. Only children which you clone will be in the target
2199 * pidns. So the pid_to_ns_wrapper does the setns, then clones a child to
2200 * actually convert pids.
2201 *
2202 * Note: glibc's fork() does not respect pidns, which can lead to failed
2203 * assertions inside glibc (and thus failed forks) if the child's pid in
2204 * the pidns and the parent pid outside are identical. Using clone prevents
2205 * this issue.
237e200e
SH
2206 */
2207static void pid_to_ns_wrapper(int sock, pid_t tpid)
2208{
2209 int newnsfd = -1, ret, cpipe[2];
2210 char fnam[100];
2211 pid_t cpid;
2212 char v;
2213
2214 ret = snprintf(fnam, sizeof(fnam), "/proc/%d/ns/pid", tpid);
2215 if (ret < 0 || ret >= sizeof(fnam))
2216 _exit(1);
2217 newnsfd = open(fnam, O_RDONLY);
2218 if (newnsfd < 0)
2219 _exit(1);
2220 if (setns(newnsfd, 0) < 0)
2221 _exit(1);
2222 close(newnsfd);
2223
2224 if (pipe(cpipe) < 0)
2225 _exit(1);
2226
35174b0f
FG
2227 struct pid_ns_clone_args args = {
2228 .cpipe = cpipe,
2229 .sock = sock,
2230 .tpid = tpid,
2231 .wrapped = &pid_to_ns
2232 };
2233 size_t stack_size = sysconf(_SC_PAGESIZE);
2234 void *stack = alloca(stack_size);
2235
2236 cpid = clone(pid_ns_clone_wrapper, stack + stack_size, SIGCHLD, &args);
237e200e
SH
2237 if (cpid < 0)
2238 _exit(1);
2239
237e200e
SH
2240 // give the child 1 second to be done forking and
2241 // write its ack
2242 if (!wait_for_sock(cpipe[0], 1))
2243 _exit(1);
2244 ret = read(cpipe[0], &v, 1);
2245 if (ret != sizeof(char) || v != '1')
2246 _exit(1);
2247
2248 if (!wait_for_pid(cpid))
2249 _exit(1);
2250 _exit(0);
2251}
2252
2253/*
2254 * To read cgroup files with a particular pid, we will setns into the child
2255 * pidns, open a pipe, fork a child - which will be the first to really be in
2256 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
2257 */
2258bool do_read_pids(pid_t tpid, const char *contrl, const char *cg, const char *file, char **d)
2259{
2260 int sock[2] = {-1, -1};
2261 char *tmpdata = NULL;
2262 int ret;
2263 pid_t qpid, cpid = -1;
2264 bool answer = false;
2265 char v = '0';
2266 struct ucred cred;
2267 size_t sz = 0, asz = 0;
2268
2269 if (!cgfs_get_value(contrl, cg, file, &tmpdata))
2270 return false;
2271
2272 /*
2273 * Now we read the pids from returned data one by one, pass
2274 * them into a child in the target namespace, read back the
2275 * translated pids, and put them into our to-return data
2276 */
2277
2278 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, sock) < 0) {
2279 perror("socketpair");
2280 free(tmpdata);
2281 return false;
2282 }
2283
2284 cpid = fork();
2285 if (cpid == -1)
2286 goto out;
2287
2288 if (!cpid) // child - exits when done
2289 pid_to_ns_wrapper(sock[1], tpid);
2290
2291 char *ptr = tmpdata;
2292 cred.uid = 0;
2293 cred.gid = 0;
2294 while (sscanf(ptr, "%d\n", &qpid) == 1) {
2295 cred.pid = qpid;
2296 ret = send_creds(sock[0], &cred, v, true);
2297
2298 if (ret == SEND_CREDS_NOTSK)
2299 goto next;
2300 if (ret == SEND_CREDS_FAIL)
2301 goto out;
2302
2303 // read converted results
2304 if (!wait_for_sock(sock[0], 2)) {
2305 fprintf(stderr, "%s: timed out waiting for pid from child: %s\n",
2306 __func__, strerror(errno));
2307 goto out;
2308 }
2309 if (read(sock[0], &qpid, sizeof(qpid)) != sizeof(qpid)) {
2310 fprintf(stderr, "%s: error reading pid from child: %s\n",
2311 __func__, strerror(errno));
2312 goto out;
2313 }
2314 must_strcat_pid(d, &sz, &asz, qpid);
2315next:
2316 ptr = strchr(ptr, '\n');
2317 if (!ptr)
2318 break;
2319 ptr++;
2320 }
2321
2322 cred.pid = getpid();
2323 v = '1';
2324 if (send_creds(sock[0], &cred, v, true) != SEND_CREDS_OK) {
2325 // failed to ask child to exit
2326 fprintf(stderr, "%s: failed to ask child to exit: %s\n",
2327 __func__, strerror(errno));
2328 goto out;
2329 }
2330
2331 answer = true;
2332
2333out:
2334 free(tmpdata);
2335 if (cpid != -1)
2336 wait_for_pid(cpid);
2337 if (sock[0] != -1) {
2338 close(sock[0]);
2339 close(sock[1]);
2340 }
2341 return answer;
2342}
2343
2344int cg_read(const char *path, char *buf, size_t size, off_t offset,
2345 struct fuse_file_info *fi)
2346{
2347 struct fuse_context *fc = fuse_get_context();
2348 struct file_info *f = (struct file_info *)fi->fh;
2349 struct cgfs_files *k = NULL;
2350 char *data = NULL;
2351 int ret, s;
2352 bool r;
2353
2354 if (f->type != LXC_TYPE_CGFILE) {
2355 fprintf(stderr, "Internal error: directory cache info used in cg_read\n");
2356 return -EIO;
2357 }
2358
2359 if (offset)
2360 return 0;
2361
2362 if (!fc)
2363 return -EIO;
2364
2365 if (!f->controller)
2366 return -EINVAL;
2367
2368 if ((k = cgfs_get_key(f->controller, f->cgroup, f->file)) == NULL) {
2369 return -EINVAL;
2370 }
2371 free_key(k);
2372
2373
888f8f3c 2374 if (!fc_may_access(fc, f->controller, f->cgroup, f->file, O_RDONLY)) {
237e200e
SH
2375 ret = -EACCES;
2376 goto out;
2377 }
2378
2379 if (strcmp(f->file, "tasks") == 0 ||
2380 strcmp(f->file, "/tasks") == 0 ||
2381 strcmp(f->file, "/cgroup.procs") == 0 ||
2382 strcmp(f->file, "cgroup.procs") == 0)
2383 // special case - we have to translate the pids
2384 r = do_read_pids(fc->pid, f->controller, f->cgroup, f->file, &data);
2385 else
2386 r = cgfs_get_value(f->controller, f->cgroup, f->file, &data);
2387
2388 if (!r) {
2389 ret = -EINVAL;
2390 goto out;
2391 }
2392
2393 if (!data) {
2394 ret = 0;
2395 goto out;
2396 }
2397 s = strlen(data);
2398 if (s > size)
2399 s = size;
2400 memcpy(buf, data, s);
2401 if (s > 0 && s < size && data[s-1] != '\n')
2402 buf[s++] = '\n';
2403
2404 ret = s;
2405
2406out:
2407 free(data);
2408 return ret;
2409}
2410
35174b0f 2411static int pid_from_ns(int sock, pid_t tpid)
237e200e
SH
2412{
2413 pid_t vpid;
2414 struct ucred cred;
2415 char v;
2416 int ret;
2417
2418 cred.uid = 0;
2419 cred.gid = 0;
2420 while (1) {
2421 if (!wait_for_sock(sock, 2)) {
2422 fprintf(stderr, "%s: timeout reading from parent\n", __func__);
35174b0f 2423 return 1;
237e200e
SH
2424 }
2425 if ((ret = read(sock, &vpid, sizeof(pid_t))) != sizeof(pid_t)) {
2426 fprintf(stderr, "%s: bad read from parent: %s\n",
2427 __func__, strerror(errno));
35174b0f 2428 return 1;
237e200e
SH
2429 }
2430 if (vpid == -1) // done
2431 break;
2432 v = '0';
2433 cred.pid = vpid;
2434 if (send_creds(sock, &cred, v, true) != SEND_CREDS_OK) {
2435 v = '1';
2436 cred.pid = getpid();
2437 if (send_creds(sock, &cred, v, false) != SEND_CREDS_OK)
35174b0f 2438 return 1;
237e200e
SH
2439 }
2440 }
35174b0f 2441 return 0;
237e200e
SH
2442}
2443
2444static void pid_from_ns_wrapper(int sock, pid_t tpid)
2445{
2446 int newnsfd = -1, ret, cpipe[2];
2447 char fnam[100];
2448 pid_t cpid;
2449 char v;
2450
2451 ret = snprintf(fnam, sizeof(fnam), "/proc/%d/ns/pid", tpid);
2452 if (ret < 0 || ret >= sizeof(fnam))
2453 _exit(1);
2454 newnsfd = open(fnam, O_RDONLY);
2455 if (newnsfd < 0)
2456 _exit(1);
2457 if (setns(newnsfd, 0) < 0)
2458 _exit(1);
2459 close(newnsfd);
2460
2461 if (pipe(cpipe) < 0)
2462 _exit(1);
2463
35174b0f
FG
2464 struct pid_ns_clone_args args = {
2465 .cpipe = cpipe,
2466 .sock = sock,
2467 .tpid = tpid,
2468 .wrapped = &pid_from_ns
2469 };
f0f8b851
SH
2470 size_t stack_size = sysconf(_SC_PAGESIZE);
2471 void *stack = alloca(stack_size);
35174b0f
FG
2472
2473 cpid = clone(pid_ns_clone_wrapper, stack + stack_size, SIGCHLD, &args);
237e200e
SH
2474 if (cpid < 0)
2475 _exit(1);
2476
237e200e
SH
2477 // give the child 1 second to be done forking and
2478 // write its ack
2479 if (!wait_for_sock(cpipe[0], 1))
f0f8b851 2480 _exit(1);
237e200e 2481 ret = read(cpipe[0], &v, 1);
f0f8b851
SH
2482 if (ret != sizeof(char) || v != '1')
2483 _exit(1);
237e200e
SH
2484
2485 if (!wait_for_pid(cpid))
2486 _exit(1);
2487 _exit(0);
237e200e
SH
2488}
2489
2490/*
2491 * Given host @uid, return the uid to which it maps in
2492 * @pid's user namespace, or -1 if none.
2493 */
2494bool hostuid_to_ns(uid_t uid, pid_t pid, uid_t *answer)
2495{
2496 FILE *f;
2497 char line[400];
2498
2499 sprintf(line, "/proc/%d/uid_map", pid);
2500 if ((f = fopen(line, "r")) == NULL) {
2501 return false;
2502 }
2503
2504 *answer = convert_id_to_ns(f, uid);
2505 fclose(f);
2506
2507 if (*answer == -1)
2508 return false;
2509 return true;
2510}
2511
2512/*
2513 * get_pid_creds: get the real uid and gid of @pid from
2514 * /proc/$$/status
2515 * (XXX should we use euid here?)
2516 */
2517void get_pid_creds(pid_t pid, uid_t *uid, gid_t *gid)
2518{
2519 char line[400];
2520 uid_t u;
2521 gid_t g;
2522 FILE *f;
2523
2524 *uid = -1;
2525 *gid = -1;
2526 sprintf(line, "/proc/%d/status", pid);
2527 if ((f = fopen(line, "r")) == NULL) {
2528 fprintf(stderr, "Error opening %s: %s\n", line, strerror(errno));
2529 return;
2530 }
2531 while (fgets(line, 400, f)) {
2532 if (strncmp(line, "Uid:", 4) == 0) {
2533 if (sscanf(line+4, "%u", &u) != 1) {
2534 fprintf(stderr, "bad uid line for pid %u\n", pid);
2535 fclose(f);
2536 return;
2537 }
2538 *uid = u;
2539 } else if (strncmp(line, "Gid:", 4) == 0) {
2540 if (sscanf(line+4, "%u", &g) != 1) {
2541 fprintf(stderr, "bad gid line for pid %u\n", pid);
2542 fclose(f);
2543 return;
2544 }
2545 *gid = g;
2546 }
2547 }
2548 fclose(f);
2549}
2550
2551/*
2552 * May the requestor @r move victim @v to a new cgroup?
2553 * This is allowed if
2554 * . they are the same task
2555 * . they are ownedy by the same uid
2556 * . @r is root on the host, or
2557 * . @v's uid is mapped into @r's where @r is root.
2558 */
2559bool may_move_pid(pid_t r, uid_t r_uid, pid_t v)
2560{
2561 uid_t v_uid, tmpuid;
2562 gid_t v_gid;
2563
2564 if (r == v)
2565 return true;
2566 if (r_uid == 0)
2567 return true;
2568 get_pid_creds(v, &v_uid, &v_gid);
2569 if (r_uid == v_uid)
2570 return true;
2571 if (hostuid_to_ns(r_uid, r, &tmpuid) && tmpuid == 0
2572 && hostuid_to_ns(v_uid, r, &tmpuid))
2573 return true;
2574 return false;
2575}
2576
2577static bool do_write_pids(pid_t tpid, uid_t tuid, const char *contrl, const char *cg,
2578 const char *file, const char *buf)
2579{
2580 int sock[2] = {-1, -1};
2581 pid_t qpid, cpid = -1;
2582 FILE *pids_file = NULL;
2583 bool answer = false, fail = false;
2584
2585 pids_file = open_pids_file(contrl, cg);
2586 if (!pids_file)
2587 return false;
2588
2589 /*
2590 * write the pids to a socket, have helper in writer's pidns
2591 * call movepid for us
2592 */
2593 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, sock) < 0) {
2594 perror("socketpair");
2595 goto out;
2596 }
2597
2598 cpid = fork();
2599 if (cpid == -1)
2600 goto out;
2601
2602 if (!cpid) { // child
2603 fclose(pids_file);
2604 pid_from_ns_wrapper(sock[1], tpid);
2605 }
2606
2607 const char *ptr = buf;
2608 while (sscanf(ptr, "%d", &qpid) == 1) {
2609 struct ucred cred;
2610 char v;
2611
2612 if (write(sock[0], &qpid, sizeof(qpid)) != sizeof(qpid)) {
2613 fprintf(stderr, "%s: error writing pid to child: %s\n",
2614 __func__, strerror(errno));
2615 goto out;
2616 }
2617
2618 if (recv_creds(sock[0], &cred, &v)) {
2619 if (v == '0') {
2620 if (!may_move_pid(tpid, tuid, cred.pid)) {
2621 fail = true;
2622 break;
2623 }
2624 if (fprintf(pids_file, "%d", (int) cred.pid) < 0)
2625 fail = true;
2626 }
2627 }
2628
2629 ptr = strchr(ptr, '\n');
2630 if (!ptr)
2631 break;
2632 ptr++;
2633 }
2634
2635 /* All good, write the value */
2636 qpid = -1;
2637 if (write(sock[0], &qpid ,sizeof(qpid)) != sizeof(qpid))
2638 fprintf(stderr, "Warning: failed to ask child to exit\n");
2639
2640 if (!fail)
2641 answer = true;
2642
2643out:
2644 if (cpid != -1)
2645 wait_for_pid(cpid);
2646 if (sock[0] != -1) {
2647 close(sock[0]);
2648 close(sock[1]);
2649 }
2650 if (pids_file) {
2651 if (fclose(pids_file) != 0)
2652 answer = false;
2653 }
2654 return answer;
2655}
2656
2657int cg_write(const char *path, const char *buf, size_t size, off_t offset,
2658 struct fuse_file_info *fi)
2659{
2660 struct fuse_context *fc = fuse_get_context();
2661 char *localbuf = NULL;
2662 struct cgfs_files *k = NULL;
2663 struct file_info *f = (struct file_info *)fi->fh;
2664 bool r;
2665
2666 if (f->type != LXC_TYPE_CGFILE) {
2667 fprintf(stderr, "Internal error: directory cache info used in cg_write\n");
2668 return -EIO;
2669 }
2670
2671 if (offset)
2672 return 0;
2673
2674 if (!fc)
2675 return -EIO;
2676
2677 localbuf = alloca(size+1);
2678 localbuf[size] = '\0';
2679 memcpy(localbuf, buf, size);
2680
2681 if ((k = cgfs_get_key(f->controller, f->cgroup, f->file)) == NULL) {
2682 size = -EINVAL;
2683 goto out;
2684 }
2685
2686 if (!fc_may_access(fc, f->controller, f->cgroup, f->file, O_WRONLY)) {
2687 size = -EACCES;
2688 goto out;
2689 }
2690
2691 if (strcmp(f->file, "tasks") == 0 ||
2692 strcmp(f->file, "/tasks") == 0 ||
2693 strcmp(f->file, "/cgroup.procs") == 0 ||
2694 strcmp(f->file, "cgroup.procs") == 0)
2695 // special case - we have to translate the pids
2696 r = do_write_pids(fc->pid, fc->uid, f->controller, f->cgroup, f->file, localbuf);
2697 else
2698 r = cgfs_set_value(f->controller, f->cgroup, f->file, localbuf);
2699
2700 if (!r)
2701 size = -EINVAL;
2702
2703out:
2704 free_key(k);
2705 return size;
2706}
2707
2708int cg_chown(const char *path, uid_t uid, gid_t gid)
2709{
2710 struct fuse_context *fc = fuse_get_context();
2711 char *cgdir = NULL, *last = NULL, *path1, *path2, *controller;
2712 struct cgfs_files *k = NULL;
2713 const char *cgroup;
2714 int ret;
2715
2716 if (!fc)
2717 return -EIO;
2718
2719 if (strcmp(path, "/cgroup") == 0)
2720 return -EINVAL;
2721
2722 controller = pick_controller_from_path(fc, path);
2723 if (!controller)
2f7036d0 2724 return -errno;
237e200e
SH
2725 cgroup = find_cgroup_in_path(path);
2726 if (!cgroup)
2727 /* this is just /cgroup/controller */
2728 return -EINVAL;
2729
2730 get_cgdir_and_path(cgroup, &cgdir, &last);
2731
2732 if (!last) {
2733 path1 = "/";
2734 path2 = cgdir;
2735 } else {
2736 path1 = cgdir;
2737 path2 = last;
2738 }
2739
2740 if (is_child_cgroup(controller, path1, path2)) {
2741 // get uid, gid, from '/tasks' file and make up a mode
2742 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2743 k = cgfs_get_key(controller, cgroup, "tasks");
2744
2745 } else
2746 k = cgfs_get_key(controller, path1, path2);
2747
2748 if (!k) {
2749 ret = -EINVAL;
2750 goto out;
2751 }
2752
2753 /*
2754 * This being a fuse request, the uid and gid must be valid
2755 * in the caller's namespace. So we can just check to make
2756 * sure that the caller is root in his uid, and privileged
2757 * over the file's current owner.
2758 */
2759 if (!is_privileged_over(fc->pid, fc->uid, k->uid, NS_ROOT_REQD)) {
2760 ret = -EACCES;
2761 goto out;
2762 }
2763
2764 ret = cgfs_chown_file(controller, cgroup, uid, gid);
2765
2766out:
2767 free_key(k);
2768 free(cgdir);
2769
2770 return ret;
2771}
2772
2773int cg_chmod(const char *path, mode_t mode)
2774{
2775 struct fuse_context *fc = fuse_get_context();
2776 char * cgdir = NULL, *last = NULL, *path1, *path2, *controller;
2777 struct cgfs_files *k = NULL;
2778 const char *cgroup;
2779 int ret;
2780
2781 if (!fc)
2782 return -EIO;
2783
2784 if (strcmp(path, "/cgroup") == 0)
2785 return -EINVAL;
2786
2787 controller = pick_controller_from_path(fc, path);
2788 if (!controller)
2f7036d0 2789 return -errno;
237e200e
SH
2790 cgroup = find_cgroup_in_path(path);
2791 if (!cgroup)
2792 /* this is just /cgroup/controller */
2793 return -EINVAL;
2794
2795 get_cgdir_and_path(cgroup, &cgdir, &last);
2796
2797 if (!last) {
2798 path1 = "/";
2799 path2 = cgdir;
2800 } else {
2801 path1 = cgdir;
2802 path2 = last;
2803 }
2804
2805 if (is_child_cgroup(controller, path1, path2)) {
2806 // get uid, gid, from '/tasks' file and make up a mode
2807 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2808 k = cgfs_get_key(controller, cgroup, "tasks");
2809
2810 } else
2811 k = cgfs_get_key(controller, path1, path2);
2812
2813 if (!k) {
2814 ret = -EINVAL;
2815 goto out;
2816 }
2817
2818 /*
2819 * This being a fuse request, the uid and gid must be valid
2820 * in the caller's namespace. So we can just check to make
2821 * sure that the caller is root in his uid, and privileged
2822 * over the file's current owner.
2823 */
2824 if (!is_privileged_over(fc->pid, fc->uid, k->uid, NS_ROOT_OPT)) {
2825 ret = -EPERM;
2826 goto out;
2827 }
2828
2829 if (!cgfs_chmod_file(controller, cgroup, mode)) {
2830 ret = -EINVAL;
2831 goto out;
2832 }
2833
2834 ret = 0;
2835out:
2836 free_key(k);
2837 free(cgdir);
2838 return ret;
2839}
2840
2841int cg_mkdir(const char *path, mode_t mode)
2842{
2843 struct fuse_context *fc = fuse_get_context();
2844 char *last = NULL, *path1, *cgdir = NULL, *controller, *next = NULL;
2845 const char *cgroup;
2846 int ret;
2847
2848 if (!fc)
2849 return -EIO;
2850
2851
2852 controller = pick_controller_from_path(fc, path);
2853 if (!controller)
2f7036d0 2854 return errno == ENOENT ? -EPERM : -errno;
237e200e
SH
2855
2856 cgroup = find_cgroup_in_path(path);
2857 if (!cgroup)
2858 return -EINVAL;
2859
2860 get_cgdir_and_path(cgroup, &cgdir, &last);
2861 if (!last)
2862 path1 = "/";
2863 else
2864 path1 = cgdir;
2865
2866 pid_t initpid = lookup_initpid_in_store(fc->pid);
2867 if (initpid <= 0)
2868 initpid = fc->pid;
2869 if (!caller_is_in_ancestor(initpid, controller, path1, &next)) {
2870 if (!next)
2871 ret = -EINVAL;
2872 else if (last && strcmp(next, last) == 0)
2873 ret = -EEXIST;
2874 else
2f7036d0 2875 ret = -EPERM;
237e200e
SH
2876 goto out;
2877 }
2878
2879 if (!fc_may_access(fc, controller, path1, NULL, O_RDWR)) {
2880 ret = -EACCES;
2881 goto out;
2882 }
2883 if (!caller_is_in_ancestor(initpid, controller, path1, NULL)) {
2884 ret = -EACCES;
2885 goto out;
2886 }
2887
2888 ret = cgfs_create(controller, cgroup, fc->uid, fc->gid);
2889
2890out:
2891 free(cgdir);
2892 free(next);
2893 return ret;
2894}
2895
2896int cg_rmdir(const char *path)
2897{
2898 struct fuse_context *fc = fuse_get_context();
2899 char *last = NULL, *cgdir = NULL, *controller, *next = NULL;
2900 const char *cgroup;
2901 int ret;
2902
2903 if (!fc)
2904 return -EIO;
2905
2906 controller = pick_controller_from_path(fc, path);
2907 if (!controller)
2f7036d0 2908 return -errno;
237e200e
SH
2909
2910 cgroup = find_cgroup_in_path(path);
2911 if (!cgroup)
2912 return -EINVAL;
2913
2914 get_cgdir_and_path(cgroup, &cgdir, &last);
2915 if (!last) {
2916 ret = -EINVAL;
2917 goto out;
2918 }
2919
2920 pid_t initpid = lookup_initpid_in_store(fc->pid);
2921 if (initpid <= 0)
2922 initpid = fc->pid;
2923 if (!caller_is_in_ancestor(initpid, controller, cgroup, &next)) {
2924 if (!last || strcmp(next, last) == 0)
2925 ret = -EBUSY;
2926 else
2927 ret = -ENOENT;
2928 goto out;
2929 }
2930
2931 if (!fc_may_access(fc, controller, cgdir, NULL, O_WRONLY)) {
2932 ret = -EACCES;
2933 goto out;
2934 }
2935 if (!caller_is_in_ancestor(initpid, controller, cgroup, NULL)) {
2936 ret = -EACCES;
2937 goto out;
2938 }
2939
2940 if (!cgfs_remove(controller, cgroup)) {
2941 ret = -EINVAL;
2942 goto out;
2943 }
2944
2945 ret = 0;
2946
2947out:
2948 free(cgdir);
2949 free(next);
2950 return ret;
2951}
2952
2953static bool startswith(const char *line, const char *pref)
2954{
2955 if (strncmp(line, pref, strlen(pref)) == 0)
2956 return true;
2957 return false;
2958}
2959
c6095b08
SH
2960static void parse_memstat(char *memstat, unsigned long *cached,
2961 unsigned long *active_anon, unsigned long *inactive_anon,
2962 unsigned long *active_file, unsigned long *inactive_file,
2963 unsigned long *unevictable)
237e200e
SH
2964{
2965 char *eol;
2966
237e200e 2967 while (*memstat) {
c6095b08
SH
2968 if (startswith(memstat, "cache")) {
2969 sscanf(memstat + 11, "%lu", cached);
2970 *cached /= 1024;
2971 } else if (startswith(memstat, "active_anon")) {
2972 sscanf(memstat + 11, "%lu", active_anon);
2973 *active_anon /= 1024;
2974 } else if (startswith(memstat, "inactive_anon")) {
2975 sscanf(memstat + 11, "%lu", inactive_anon);
2976 *inactive_anon /= 1024;
2977 } else if (startswith(memstat, "active_file")) {
2978 sscanf(memstat + 11, "%lu", active_file);
2979 *active_file /= 1024;
2980 } else if (startswith(memstat, "inactive_file")) {
2981 sscanf(memstat + 11, "%lu", inactive_file);
2982 *inactive_file /= 1024;
2983 } else if (startswith(memstat, "unevictable")) {
2984 sscanf(memstat + 11, "%lu", unevictable);
2985 *unevictable /= 1024;
237e200e
SH
2986 }
2987 eol = strchr(memstat, '\n');
2988 if (!eol)
2989 return;
2990 memstat = eol+1;
2991 }
2992}
2993
2994static void get_blkio_io_value(char *str, unsigned major, unsigned minor, char *iotype, unsigned long *v)
2995{
2996 char *eol;
2997 char key[32];
2998
2999 memset(key, 0, 32);
3000 snprintf(key, 32, "%u:%u %s", major, minor, iotype);
3001
3002 size_t len = strlen(key);
3003 *v = 0;
3004
3005 while (*str) {
3006 if (startswith(str, key)) {
3007 sscanf(str + len, "%lu", v);
3008 return;
3009 }
3010 eol = strchr(str, '\n');
3011 if (!eol)
3012 return;
3013 str = eol+1;
3014 }
3015}
3016
3017static int read_file(const char *path, char *buf, size_t size,
3018 struct file_info *d)
3019{
3020 size_t linelen = 0, total_len = 0, rv = 0;
3021 char *line = NULL;
3022 char *cache = d->buf;
3023 size_t cache_size = d->buflen;
3024 FILE *f = fopen(path, "r");
3025 if (!f)
3026 return 0;
3027
3028 while (getline(&line, &linelen, f) != -1) {
a262ddb7 3029 ssize_t l = snprintf(cache, cache_size, "%s", line);
237e200e
SH
3030 if (l < 0) {
3031 perror("Error writing to cache");
3032 rv = 0;
3033 goto err;
3034 }
3035 if (l >= cache_size) {
3036 fprintf(stderr, "Internal error: truncated write to cache\n");
3037 rv = 0;
3038 goto err;
3039 }
3040 cache += l;
3041 cache_size -= l;
3042 total_len += l;
3043 }
3044
3045 d->size = total_len;
a262ddb7
CB
3046 if (total_len > size)
3047 total_len = size;
237e200e
SH
3048
3049 /* read from off 0 */
3050 memcpy(buf, d->buf, total_len);
3051 rv = total_len;
3052 err:
3053 fclose(f);
3054 free(line);
3055 return rv;
3056}
3057
3058/*
3059 * FUSE ops for /proc
3060 */
3061
3062static unsigned long get_memlimit(const char *cgroup)
3063{
3064 char *memlimit_str = NULL;
3065 unsigned long memlimit = -1;
3066
3067 if (cgfs_get_value("memory", cgroup, "memory.limit_in_bytes", &memlimit_str))
3068 memlimit = strtoul(memlimit_str, NULL, 10);
3069
3070 free(memlimit_str);
3071
3072 return memlimit;
3073}
3074
3075static unsigned long get_min_memlimit(const char *cgroup)
3076{
3077 char *copy = strdupa(cgroup);
3078 unsigned long memlimit = 0, retlimit;
3079
3080 retlimit = get_memlimit(copy);
3081
3082 while (strcmp(copy, "/") != 0) {
3083 copy = dirname(copy);
3084 memlimit = get_memlimit(copy);
3085 if (memlimit != -1 && memlimit < retlimit)
3086 retlimit = memlimit;
3087 };
3088
3089 return retlimit;
3090}
3091
3092static int proc_meminfo_read(char *buf, size_t size, off_t offset,
3093 struct fuse_file_info *fi)
3094{
3095 struct fuse_context *fc = fuse_get_context();
3096 struct file_info *d = (struct file_info *)fi->fh;
3097 char *cg;
3098 char *memusage_str = NULL, *memstat_str = NULL,
3099 *memswlimit_str = NULL, *memswusage_str = NULL,
3100 *memswlimit_default_str = NULL, *memswusage_default_str = NULL;
3101 unsigned long memlimit = 0, memusage = 0, memswlimit = 0, memswusage = 0,
c6095b08
SH
3102 cached = 0, hosttotal = 0, active_anon = 0, inactive_anon = 0,
3103 active_file = 0, inactive_file = 0, unevictable = 0;
237e200e
SH
3104 char *line = NULL;
3105 size_t linelen = 0, total_len = 0, rv = 0;
3106 char *cache = d->buf;
3107 size_t cache_size = d->buflen;
3108 FILE *f = NULL;
3109
3110 if (offset){
3111 if (offset > d->size)
3112 return -EINVAL;
3113 if (!d->cached)
3114 return 0;
3115 int left = d->size - offset;
3116 total_len = left > size ? size: left;
3117 memcpy(buf, cache + offset, total_len);
3118 return total_len;
3119 }
3120
3121 pid_t initpid = lookup_initpid_in_store(fc->pid);
3122 if (initpid <= 0)
3123 initpid = fc->pid;
3124 cg = get_pid_cgroup(initpid, "memory");
3125 if (!cg)
3126 return read_file("/proc/meminfo", buf, size, d);
6d2f6996 3127 prune_init_slice(cg);
237e200e
SH
3128
3129 memlimit = get_min_memlimit(cg);
3130 if (!cgfs_get_value("memory", cg, "memory.usage_in_bytes", &memusage_str))
3131 goto err;
3132 if (!cgfs_get_value("memory", cg, "memory.stat", &memstat_str))
3133 goto err;
3134
3135 // Following values are allowed to fail, because swapaccount might be turned
3136 // off for current kernel
3137 if(cgfs_get_value("memory", cg, "memory.memsw.limit_in_bytes", &memswlimit_str) &&
3138 cgfs_get_value("memory", cg, "memory.memsw.usage_in_bytes", &memswusage_str))
3139 {
3140 /* If swapaccounting is turned on, then default value is assumed to be that of cgroup / */
3141 if (!cgfs_get_value("memory", "/", "memory.memsw.limit_in_bytes", &memswlimit_default_str))
3142 goto err;
3143 if (!cgfs_get_value("memory", "/", "memory.memsw.usage_in_bytes", &memswusage_default_str))
3144 goto err;
3145
3146 memswlimit = strtoul(memswlimit_str, NULL, 10);
3147 memswusage = strtoul(memswusage_str, NULL, 10);
3148
3149 if (!strcmp(memswlimit_str, memswlimit_default_str))
3150 memswlimit = 0;
3151 if (!strcmp(memswusage_str, memswusage_default_str))
3152 memswusage = 0;
3153
3154 memswlimit = memswlimit / 1024;
3155 memswusage = memswusage / 1024;
3156 }
3157
3158 memusage = strtoul(memusage_str, NULL, 10);
3159 memlimit /= 1024;
3160 memusage /= 1024;
3161
c6095b08
SH
3162 parse_memstat(memstat_str, &cached, &active_anon,
3163 &inactive_anon, &active_file, &inactive_file,
3164 &unevictable);
237e200e
SH
3165
3166 f = fopen("/proc/meminfo", "r");
3167 if (!f)
3168 goto err;
3169
3170 while (getline(&line, &linelen, f) != -1) {
a262ddb7 3171 ssize_t l;
237e200e
SH
3172 char *printme, lbuf[100];
3173
3174 memset(lbuf, 0, 100);
3175 if (startswith(line, "MemTotal:")) {
3176 sscanf(line+14, "%lu", &hosttotal);
3177 if (hosttotal < memlimit)
3178 memlimit = hosttotal;
3179 snprintf(lbuf, 100, "MemTotal: %8lu kB\n", memlimit);
3180 printme = lbuf;
3181 } else if (startswith(line, "MemFree:")) {
3182 snprintf(lbuf, 100, "MemFree: %8lu kB\n", memlimit - memusage);
3183 printme = lbuf;
3184 } else if (startswith(line, "MemAvailable:")) {
3185 snprintf(lbuf, 100, "MemAvailable: %8lu kB\n", memlimit - memusage);
3186 printme = lbuf;
3187 } else if (startswith(line, "SwapTotal:") && memswlimit > 0) {
3188 snprintf(lbuf, 100, "SwapTotal: %8lu kB\n", memswlimit - memlimit);
3189 printme = lbuf;
3190 } else if (startswith(line, "SwapFree:") && memswlimit > 0 && memswusage > 0) {
b4665ce0
SH
3191 unsigned long swaptotal = memswlimit - memlimit,
3192 swapusage = memswusage - memusage,
3193 swapfree = swapusage < swaptotal ? swaptotal - swapusage : 0;
3194 snprintf(lbuf, 100, "SwapFree: %8lu kB\n", swapfree);
237e200e 3195 printme = lbuf;
da35d72a
SH
3196 } else if (startswith(line, "Slab:")) {
3197 snprintf(lbuf, 100, "Slab: %8lu kB\n", 0UL);
3198 printme = lbuf;
237e200e
SH
3199 } else if (startswith(line, "Buffers:")) {
3200 snprintf(lbuf, 100, "Buffers: %8lu kB\n", 0UL);
3201 printme = lbuf;
3202 } else if (startswith(line, "Cached:")) {
3203 snprintf(lbuf, 100, "Cached: %8lu kB\n", cached);
3204 printme = lbuf;
3205 } else if (startswith(line, "SwapCached:")) {
3206 snprintf(lbuf, 100, "SwapCached: %8lu kB\n", 0UL);
3207 printme = lbuf;
c6095b08
SH
3208 } else if (startswith(line, "Active")) {
3209 snprintf(lbuf, 100, "Active: %8lu kB\n",
3210 active_anon + active_file);
3211 printme = lbuf;
3212 } else if (startswith(line, "Inactive")) {
3213 snprintf(lbuf, 100, "Inactive: %8lu kB\n",
3214 inactive_anon + inactive_file);
3215 printme = lbuf;
3216 } else if (startswith(line, "Active(anon)")) {
3217 snprintf(lbuf, 100, "Active(anon): %8lu kB\n", active_anon);
3218 printme = lbuf;
3219 } else if (startswith(line, "Inactive(anon)")) {
3220 snprintf(lbuf, 100, "Inactive(anon): %8lu kB\n", inactive_anon);
3221 printme = lbuf;
3222 } else if (startswith(line, "Active(file)")) {
3223 snprintf(lbuf, 100, "Active(file): %8lu kB\n", active_file);
3224 printme = lbuf;
3225 } else if (startswith(line, "Inactive(file)")) {
3226 snprintf(lbuf, 100, "Inactive(file): %8lu kB\n", inactive_file);
3227 printme = lbuf;
3228 } else if (startswith(line, "Unevictable")) {
3229 snprintf(lbuf, 100, "Unevictable: %8lu kB\n", unevictable);
3230 printme = lbuf;
3231 } else if (startswith(line, "SReclaimable")) {
3232 snprintf(lbuf, 100, "SReclaimable: %8lu kB\n", 0UL);
3233 printme = lbuf;
3234 } else if (startswith(line, "SUnreclaim")) {
3235 snprintf(lbuf, 100, "SUnreclaim: %8lu kB\n", 0UL);
3236 printme = lbuf;
237e200e
SH
3237 } else
3238 printme = line;
3239
3240 l = snprintf(cache, cache_size, "%s", printme);
3241 if (l < 0) {
3242 perror("Error writing to cache");
3243 rv = 0;
3244 goto err;
3245
3246 }
3247 if (l >= cache_size) {
3248 fprintf(stderr, "Internal error: truncated write to cache\n");
3249 rv = 0;
3250 goto err;
3251 }
3252
3253 cache += l;
3254 cache_size -= l;
3255 total_len += l;
3256 }
3257
3258 d->cached = 1;
3259 d->size = total_len;
3260 if (total_len > size ) total_len = size;
3261 memcpy(buf, d->buf, total_len);
3262
3263 rv = total_len;
3264err:
3265 if (f)
3266 fclose(f);
3267 free(line);
3268 free(cg);
3269 free(memusage_str);
3270 free(memswlimit_str);
3271 free(memswusage_str);
3272 free(memstat_str);
3273 free(memswlimit_default_str);
3274 free(memswusage_default_str);
3275 return rv;
3276}
3277
3278/*
3279 * Read the cpuset.cpus for cg
3280 * Return the answer in a newly allocated string which must be freed
3281 */
3282static char *get_cpuset(const char *cg)
3283{
3284 char *answer;
3285
3286 if (!cgfs_get_value("cpuset", cg, "cpuset.cpus", &answer))
3287 return NULL;
3288 return answer;
3289}
3290
3291bool cpu_in_cpuset(int cpu, const char *cpuset);
3292
3293static bool cpuline_in_cpuset(const char *line, const char *cpuset)
3294{
3295 int cpu;
3296
3297 if (sscanf(line, "processor : %d", &cpu) != 1)
3298 return false;
3299 return cpu_in_cpuset(cpu, cpuset);
3300}
3301
3302/*
3303 * check whether this is a '^processor" line in /proc/cpuinfo
3304 */
3305static bool is_processor_line(const char *line)
3306{
3307 int cpu;
3308
3309 if (sscanf(line, "processor : %d", &cpu) == 1)
3310 return true;
3311 return false;
3312}
3313
3314static int proc_cpuinfo_read(char *buf, size_t size, off_t offset,
3315 struct fuse_file_info *fi)
3316{
3317 struct fuse_context *fc = fuse_get_context();
3318 struct file_info *d = (struct file_info *)fi->fh;
3319 char *cg;
3320 char *cpuset = NULL;
3321 char *line = NULL;
3322 size_t linelen = 0, total_len = 0, rv = 0;
f676eb79
SH
3323 bool am_printing = false, firstline = true, is_s390x = false;
3324 int curcpu = -1, cpu;
237e200e
SH
3325 char *cache = d->buf;
3326 size_t cache_size = d->buflen;
3327 FILE *f = NULL;
3328
3329 if (offset){
3330 if (offset > d->size)
3331 return -EINVAL;
3332 if (!d->cached)
3333 return 0;
3334 int left = d->size - offset;
3335 total_len = left > size ? size: left;
3336 memcpy(buf, cache + offset, total_len);
3337 return total_len;
3338 }
3339
3340 pid_t initpid = lookup_initpid_in_store(fc->pid);
3341 if (initpid <= 0)
3342 initpid = fc->pid;
3343 cg = get_pid_cgroup(initpid, "cpuset");
3344 if (!cg)
3345 return read_file("proc/cpuinfo", buf, size, d);
6d2f6996 3346 prune_init_slice(cg);
237e200e
SH
3347
3348 cpuset = get_cpuset(cg);
3349 if (!cpuset)
3350 goto err;
3351
3352 f = fopen("/proc/cpuinfo", "r");
3353 if (!f)
3354 goto err;
3355
3356 while (getline(&line, &linelen, f) != -1) {
a262ddb7 3357 ssize_t l;
f676eb79
SH
3358 if (firstline) {
3359 firstline = false;
3360 if (strstr(line, "IBM/S390") != NULL) {
3361 is_s390x = true;
3362 am_printing = true;
5ed9d4e2 3363 continue;
f676eb79
SH
3364 }
3365 }
5ed9d4e2
SH
3366 if (strncmp(line, "# processors:", 12) == 0)
3367 continue;
237e200e
SH
3368 if (is_processor_line(line)) {
3369 am_printing = cpuline_in_cpuset(line, cpuset);
3370 if (am_printing) {
3371 curcpu ++;
3372 l = snprintf(cache, cache_size, "processor : %d\n", curcpu);
3373 if (l < 0) {
3374 perror("Error writing to cache");
3375 rv = 0;
3376 goto err;
3377 }
3378 if (l >= cache_size) {
3379 fprintf(stderr, "Internal error: truncated write to cache\n");
3380 rv = 0;
3381 goto err;
3382 }
3383 cache += l;
3384 cache_size -= l;
3385 total_len += l;
3386 }
3387 continue;
f676eb79
SH
3388 } else if (is_s390x && sscanf(line, "processor %d:", &cpu) == 1) {
3389 char *p;
3390 if (!cpu_in_cpuset(cpu, cpuset))
3391 continue;
3392 curcpu ++;
3393 p = strchr(line, ':');
3394 if (!p || !*p)
3395 goto err;
3396 p++;
5ed9d4e2 3397 l = snprintf(cache, cache_size, "processor %d:%s", curcpu, p);
f676eb79
SH
3398 if (l < 0) {
3399 perror("Error writing to cache");
3400 rv = 0;
3401 goto err;
3402 }
3403 if (l >= cache_size) {
3404 fprintf(stderr, "Internal error: truncated write to cache\n");
3405 rv = 0;
3406 goto err;
3407 }
3408 cache += l;
3409 cache_size -= l;
3410 total_len += l;
3411 continue;
3412
237e200e
SH
3413 }
3414 if (am_printing) {
3415 l = snprintf(cache, cache_size, "%s", line);
3416 if (l < 0) {
3417 perror("Error writing to cache");
3418 rv = 0;
3419 goto err;
3420 }
3421 if (l >= cache_size) {
3422 fprintf(stderr, "Internal error: truncated write to cache\n");
3423 rv = 0;
3424 goto err;
3425 }
3426 cache += l;
3427 cache_size -= l;
3428 total_len += l;
3429 }
3430 }
3431
5ed9d4e2
SH
3432 if (is_s390x) {
3433 char *origcache = d->buf;
a262ddb7 3434 ssize_t l;
5ed9d4e2
SH
3435 do {
3436 d->buf = malloc(d->buflen);
3437 } while (!d->buf);
3438 cache = d->buf;
3439 cache_size = d->buflen;
3440 total_len = 0;
3441 l = snprintf(cache, cache_size, "vendor_id : IBM/S390\n");
3442 if (l < 0 || l >= cache_size) {
3443 free(origcache);
3444 goto err;
3445 }
3446 cache_size -= l;
3447 cache += l;
3448 total_len += l;
3449 l = snprintf(cache, cache_size, "# processors : %d\n", curcpu + 1);
3450 if (l < 0 || l >= cache_size) {
3451 free(origcache);
3452 goto err;
3453 }
3454 cache_size -= l;
3455 cache += l;
3456 total_len += l;
3457 l = snprintf(cache, cache_size, "%s", origcache);
3458 free(origcache);
3459 if (l < 0 || l >= cache_size)
3460 goto err;
3461 total_len += l;
3462 }
3463
237e200e
SH
3464 d->cached = 1;
3465 d->size = total_len;
3466 if (total_len > size ) total_len = size;
3467
3468 /* read from off 0 */
3469 memcpy(buf, d->buf, total_len);
3470 rv = total_len;
3471err:
3472 if (f)
3473 fclose(f);
3474 free(line);
3475 free(cpuset);
3476 free(cg);
3477 return rv;
3478}
3479
3480static int proc_stat_read(char *buf, size_t size, off_t offset,
3481 struct fuse_file_info *fi)
3482{
3483 struct fuse_context *fc = fuse_get_context();
3484 struct file_info *d = (struct file_info *)fi->fh;
3485 char *cg;
3486 char *cpuset = NULL;
3487 char *line = NULL;
3488 size_t linelen = 0, total_len = 0, rv = 0;
3489 int curcpu = -1; /* cpu numbering starts at 0 */
3490 unsigned long user = 0, nice = 0, system = 0, idle = 0, iowait = 0, irq = 0, softirq = 0, steal = 0, guest = 0;
3491 unsigned long user_sum = 0, nice_sum = 0, system_sum = 0, idle_sum = 0, iowait_sum = 0,
3492 irq_sum = 0, softirq_sum = 0, steal_sum = 0, guest_sum = 0;
3493#define CPUALL_MAX_SIZE BUF_RESERVE_SIZE
3494 char cpuall[CPUALL_MAX_SIZE];
3495 /* reserve for cpu all */
3496 char *cache = d->buf + CPUALL_MAX_SIZE;
3497 size_t cache_size = d->buflen - CPUALL_MAX_SIZE;
3498 FILE *f = NULL;
3499
3500 if (offset){
3501 if (offset > d->size)
3502 return -EINVAL;
3503 if (!d->cached)
3504 return 0;
3505 int left = d->size - offset;
3506 total_len = left > size ? size: left;
3507 memcpy(buf, d->buf + offset, total_len);
3508 return total_len;
3509 }
3510
3511 pid_t initpid = lookup_initpid_in_store(fc->pid);
3512 if (initpid <= 0)
3513 initpid = fc->pid;
3514 cg = get_pid_cgroup(initpid, "cpuset");
3515 if (!cg)
3516 return read_file("/proc/stat", buf, size, d);
6d2f6996 3517 prune_init_slice(cg);
237e200e
SH
3518
3519 cpuset = get_cpuset(cg);
3520 if (!cpuset)
3521 goto err;
3522
3523 f = fopen("/proc/stat", "r");
3524 if (!f)
3525 goto err;
3526
3527 //skip first line
3528 if (getline(&line, &linelen, f) < 0) {
3529 fprintf(stderr, "proc_stat_read read first line failed\n");
3530 goto err;
3531 }
3532
3533 while (getline(&line, &linelen, f) != -1) {
a262ddb7 3534 ssize_t l;
237e200e
SH
3535 int cpu;
3536 char cpu_char[10]; /* That's a lot of cores */
3537 char *c;
3538
b4665ce0
SH
3539 if (strlen(line) == 0)
3540 continue;
237e200e
SH
3541 if (sscanf(line, "cpu%9[^ ]", cpu_char) != 1) {
3542 /* not a ^cpuN line containing a number N, just print it */
3543 l = snprintf(cache, cache_size, "%s", line);
3544 if (l < 0) {
3545 perror("Error writing to cache");
3546 rv = 0;
3547 goto err;
3548 }
3549 if (l >= cache_size) {
3550 fprintf(stderr, "Internal error: truncated write to cache\n");
3551 rv = 0;
3552 goto err;
3553 }
3554 cache += l;
3555 cache_size -= l;
3556 total_len += l;
3557 continue;
3558 }
3559
3560 if (sscanf(cpu_char, "%d", &cpu) != 1)
3561 continue;
3562 if (!cpu_in_cpuset(cpu, cpuset))
3563 continue;
3564 curcpu ++;
3565
3566 c = strchr(line, ' ');
3567 if (!c)
3568 continue;
3569 l = snprintf(cache, cache_size, "cpu%d%s", curcpu, c);
3570 if (l < 0) {
3571 perror("Error writing to cache");
3572 rv = 0;
3573 goto err;
3574
3575 }
3576 if (l >= cache_size) {
3577 fprintf(stderr, "Internal error: truncated write to cache\n");
3578 rv = 0;
3579 goto err;
3580 }
3581
3582 cache += l;
3583 cache_size -= l;
3584 total_len += l;
3585
3586 if (sscanf(line, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu", &user, &nice, &system, &idle, &iowait, &irq,
3587 &softirq, &steal, &guest) != 9)
3588 continue;
3589 user_sum += user;
3590 nice_sum += nice;
3591 system_sum += system;
3592 idle_sum += idle;
3593 iowait_sum += iowait;
3594 irq_sum += irq;
3595 softirq_sum += softirq;
3596 steal_sum += steal;
3597 guest_sum += guest;
3598 }
3599
3600 cache = d->buf;
3601
3602 int cpuall_len = snprintf(cpuall, CPUALL_MAX_SIZE, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
3603 "cpu ", user_sum, nice_sum, system_sum, idle_sum, iowait_sum, irq_sum, softirq_sum, steal_sum, guest_sum);
3604 if (cpuall_len > 0 && cpuall_len < CPUALL_MAX_SIZE){
3605 memcpy(cache, cpuall, cpuall_len);
3606 cache += cpuall_len;
3607 } else{
3608 /* shouldn't happen */
3609 fprintf(stderr, "proc_stat_read copy cpuall failed, cpuall_len=%d\n", cpuall_len);
3610 cpuall_len = 0;
3611 }
3612
3613 memmove(cache, d->buf + CPUALL_MAX_SIZE, total_len);
3614 total_len += cpuall_len;
3615 d->cached = 1;
3616 d->size = total_len;
3617 if (total_len > size ) total_len = size;
3618
3619 memcpy(buf, d->buf, total_len);
3620 rv = total_len;
3621
3622err:
3623 if (f)
3624 fclose(f);
3625 free(line);
3626 free(cpuset);
3627 free(cg);
3628 return rv;
3629}
3630
3631static long int getreaperage(pid_t pid)
3632{
3633 char fnam[100];
3634 struct stat sb;
3635 int ret;
3636 pid_t qpid;
3637
3638 qpid = lookup_initpid_in_store(pid);
3639 if (qpid <= 0)
3640 return 0;
3641
3642 ret = snprintf(fnam, 100, "/proc/%d", qpid);
3643 if (ret < 0 || ret >= 100)
3644 return 0;
3645
3646 if (lstat(fnam, &sb) < 0)
3647 return 0;
3648
3649 return time(NULL) - sb.st_ctime;
3650}
3651
3652static unsigned long get_reaper_busy(pid_t task)
3653{
3654 pid_t initpid = lookup_initpid_in_store(task);
3655 char *cgroup = NULL, *usage_str = NULL;
3656 unsigned long usage = 0;
3657
3658 if (initpid <= 0)
3659 return 0;
3660
3661 cgroup = get_pid_cgroup(initpid, "cpuacct");
3662 if (!cgroup)
3663 goto out;
6d2f6996 3664 prune_init_slice(cgroup);
237e200e
SH
3665 if (!cgfs_get_value("cpuacct", cgroup, "cpuacct.usage", &usage_str))
3666 goto out;
3667 usage = strtoul(usage_str, NULL, 10);
3668 usage /= 1000000000;
3669
3670out:
3671 free(cgroup);
3672 free(usage_str);
3673 return usage;
3674}
3675
3676#if RELOADTEST
3677void iwashere(void)
3678{
237e200e
SH
3679 int fd;
3680
ec2b5e7c 3681 fd = creat("/tmp/lxcfs-iwashere", 0644);
237e200e
SH
3682 if (fd >= 0)
3683 close(fd);
3684}
3685#endif
3686
3687/*
3688 * We read /proc/uptime and reuse its second field.
3689 * For the first field, we use the mtime for the reaper for
3690 * the calling pid as returned by getreaperage
3691 */
3692static int proc_uptime_read(char *buf, size_t size, off_t offset,
3693 struct fuse_file_info *fi)
3694{
3695 struct fuse_context *fc = fuse_get_context();
3696 struct file_info *d = (struct file_info *)fi->fh;
3697 long int reaperage = getreaperage(fc->pid);
3698 unsigned long int busytime = get_reaper_busy(fc->pid), idletime;
3699 char *cache = d->buf;
a262ddb7 3700 ssize_t total_len = 0;
237e200e
SH
3701
3702#if RELOADTEST
3703 iwashere();
3704#endif
3705
3706 if (offset){
3707 if (offset > d->size)
3708 return -EINVAL;
3709 if (!d->cached)
3710 return 0;
3711 int left = d->size - offset;
3712 total_len = left > size ? size: left;
3713 memcpy(buf, cache + offset, total_len);
3714 return total_len;
3715 }
3716
3717 idletime = reaperage - busytime;
3718 if (idletime > reaperage)
3719 idletime = reaperage;
3720
3721 total_len = snprintf(d->buf, d->size, "%ld.0 %lu.0\n", reaperage, idletime);
3722 if (total_len < 0){
3723 perror("Error writing to cache");
3724 return 0;
3725 }
3726
3727 d->size = (int)total_len;
3728 d->cached = 1;
3729
3730 if (total_len > size) total_len = size;
3731
3732 memcpy(buf, d->buf, total_len);
3733 return total_len;
3734}
3735
3736static int proc_diskstats_read(char *buf, size_t size, off_t offset,
3737 struct fuse_file_info *fi)
3738{
3739 char dev_name[72];
3740 struct fuse_context *fc = fuse_get_context();
3741 struct file_info *d = (struct file_info *)fi->fh;
3742 char *cg;
3743 char *io_serviced_str = NULL, *io_merged_str = NULL, *io_service_bytes_str = NULL,
3744 *io_wait_time_str = NULL, *io_service_time_str = NULL;
3745 unsigned long read = 0, write = 0;
3746 unsigned long read_merged = 0, write_merged = 0;
3747 unsigned long read_sectors = 0, write_sectors = 0;
3748 unsigned long read_ticks = 0, write_ticks = 0;
3749 unsigned long ios_pgr = 0, tot_ticks = 0, rq_ticks = 0;
3750 unsigned long rd_svctm = 0, wr_svctm = 0, rd_wait = 0, wr_wait = 0;
3751 char *cache = d->buf;
3752 size_t cache_size = d->buflen;
3753 char *line = NULL;
3754 size_t linelen = 0, total_len = 0, rv = 0;
3755 unsigned int major = 0, minor = 0;
3756 int i = 0;
3757 FILE *f = NULL;
3758
3759 if (offset){
3760 if (offset > d->size)
3761 return -EINVAL;
3762 if (!d->cached)
3763 return 0;
3764 int left = d->size - offset;
3765 total_len = left > size ? size: left;
3766 memcpy(buf, cache + offset, total_len);
3767 return total_len;
3768 }
3769
3770 pid_t initpid = lookup_initpid_in_store(fc->pid);
3771 if (initpid <= 0)
3772 initpid = fc->pid;
3773 cg = get_pid_cgroup(initpid, "blkio");
3774 if (!cg)
3775 return read_file("/proc/diskstats", buf, size, d);
6d2f6996 3776 prune_init_slice(cg);
237e200e 3777
2209fe50 3778 if (!cgfs_get_value("blkio", cg, "blkio.io_serviced_recursive", &io_serviced_str))
237e200e 3779 goto err;
2209fe50 3780 if (!cgfs_get_value("blkio", cg, "blkio.io_merged_recursive", &io_merged_str))
237e200e 3781 goto err;
2209fe50 3782 if (!cgfs_get_value("blkio", cg, "blkio.io_service_bytes_recursive", &io_service_bytes_str))
237e200e 3783 goto err;
2209fe50 3784 if (!cgfs_get_value("blkio", cg, "blkio.io_wait_time_recursive", &io_wait_time_str))
237e200e 3785 goto err;
2209fe50 3786 if (!cgfs_get_value("blkio", cg, "blkio.io_service_time_recursive", &io_service_time_str))
237e200e
SH
3787 goto err;
3788
3789
3790 f = fopen("/proc/diskstats", "r");
3791 if (!f)
3792 goto err;
3793
3794 while (getline(&line, &linelen, f) != -1) {
a262ddb7 3795 ssize_t l;
2209fe50 3796 char lbuf[256];
237e200e
SH
3797
3798 i = sscanf(line, "%u %u %71s", &major, &minor, dev_name);
2209fe50 3799 if (i != 3)
237e200e 3800 continue;
2209fe50
SH
3801
3802 get_blkio_io_value(io_serviced_str, major, minor, "Read", &read);
3803 get_blkio_io_value(io_serviced_str, major, minor, "Write", &write);
3804 get_blkio_io_value(io_merged_str, major, minor, "Read", &read_merged);
3805 get_blkio_io_value(io_merged_str, major, minor, "Write", &write_merged);
3806 get_blkio_io_value(io_service_bytes_str, major, minor, "Read", &read_sectors);
3807 read_sectors = read_sectors/512;
3808 get_blkio_io_value(io_service_bytes_str, major, minor, "Write", &write_sectors);
3809 write_sectors = write_sectors/512;
3810
3811 get_blkio_io_value(io_service_time_str, major, minor, "Read", &rd_svctm);
3812 rd_svctm = rd_svctm/1000000;
3813 get_blkio_io_value(io_wait_time_str, major, minor, "Read", &rd_wait);
3814 rd_wait = rd_wait/1000000;
3815 read_ticks = rd_svctm + rd_wait;
3816
3817 get_blkio_io_value(io_service_time_str, major, minor, "Write", &wr_svctm);
3818 wr_svctm = wr_svctm/1000000;
3819 get_blkio_io_value(io_wait_time_str, major, minor, "Write", &wr_wait);
3820 wr_wait = wr_wait/1000000;
3821 write_ticks = wr_svctm + wr_wait;
3822
3823 get_blkio_io_value(io_service_time_str, major, minor, "Total", &tot_ticks);
3824 tot_ticks = tot_ticks/1000000;
237e200e
SH
3825
3826 memset(lbuf, 0, 256);
2db31eb6
SH
3827 if (read || write || read_merged || write_merged || read_sectors || write_sectors || read_ticks || write_ticks)
3828 snprintf(lbuf, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
3829 major, minor, dev_name, read, read_merged, read_sectors, read_ticks,
3830 write, write_merged, write_sectors, write_ticks, ios_pgr, tot_ticks, rq_ticks);
3831 else
3832 continue;
237e200e 3833
2209fe50 3834 l = snprintf(cache, cache_size, "%s", lbuf);
237e200e
SH
3835 if (l < 0) {
3836 perror("Error writing to fuse buf");
3837 rv = 0;
3838 goto err;
3839 }
3840 if (l >= cache_size) {
3841 fprintf(stderr, "Internal error: truncated write to cache\n");
3842 rv = 0;
3843 goto err;
3844 }
3845 cache += l;
3846 cache_size -= l;
3847 total_len += l;
3848 }
3849
3850 d->cached = 1;
3851 d->size = total_len;
3852 if (total_len > size ) total_len = size;
3853 memcpy(buf, d->buf, total_len);
3854
3855 rv = total_len;
3856err:
3857 free(cg);
3858 if (f)
3859 fclose(f);
3860 free(line);
3861 free(io_serviced_str);
3862 free(io_merged_str);
3863 free(io_service_bytes_str);
3864 free(io_wait_time_str);
3865 free(io_service_time_str);
3866 return rv;
3867}
3868
70dcc12e
SH
3869static int proc_swaps_read(char *buf, size_t size, off_t offset,
3870 struct fuse_file_info *fi)
3871{
3872 struct fuse_context *fc = fuse_get_context();
3873 struct file_info *d = (struct file_info *)fi->fh;
3874 char *cg = NULL;
3875 char *memswlimit_str = NULL, *memlimit_str = NULL, *memusage_str = NULL, *memswusage_str = NULL,
3876 *memswlimit_default_str = NULL, *memswusage_default_str = NULL;
3877 unsigned long memswlimit = 0, memlimit = 0, memusage = 0, memswusage = 0, swap_total = 0, swap_free = 0;
a262ddb7
CB
3878 ssize_t total_len = 0, rv = 0;
3879 ssize_t l = 0;
70dcc12e
SH
3880 char *cache = d->buf;
3881
3882 if (offset) {
3883 if (offset > d->size)
3884 return -EINVAL;
3885 if (!d->cached)
3886 return 0;
3887 int left = d->size - offset;
3888 total_len = left > size ? size: left;
3889 memcpy(buf, cache + offset, total_len);
3890 return total_len;
3891 }
3892
3893 pid_t initpid = lookup_initpid_in_store(fc->pid);
3894 if (initpid <= 0)
3895 initpid = fc->pid;
3896 cg = get_pid_cgroup(initpid, "memory");
3897 if (!cg)
3898 return read_file("/proc/swaps", buf, size, d);
6d2f6996 3899 prune_init_slice(cg);
70dcc12e
SH
3900
3901 if (!cgfs_get_value("memory", cg, "memory.limit_in_bytes", &memlimit_str))
3902 goto err;
3903
3904 if (!cgfs_get_value("memory", cg, "memory.usage_in_bytes", &memusage_str))
3905 goto err;
3906
3907 memlimit = strtoul(memlimit_str, NULL, 10);
3908 memusage = strtoul(memusage_str, NULL, 10);
3909
3910 if (cgfs_get_value("memory", cg, "memory.memsw.usage_in_bytes", &memswusage_str) &&
3911 cgfs_get_value("memory", cg, "memory.memsw.limit_in_bytes", &memswlimit_str)) {
3912
3913 /* If swap accounting is turned on, then default value is assumed to be that of cgroup / */
3914 if (!cgfs_get_value("memory", "/", "memory.memsw.limit_in_bytes", &memswlimit_default_str))
3915 goto err;
3916 if (!cgfs_get_value("memory", "/", "memory.memsw.usage_in_bytes", &memswusage_default_str))
3917 goto err;
3918
3919 memswlimit = strtoul(memswlimit_str, NULL, 10);
3920 memswusage = strtoul(memswusage_str, NULL, 10);
3921
3922 if (!strcmp(memswlimit_str, memswlimit_default_str))
3923 memswlimit = 0;
3924 if (!strcmp(memswusage_str, memswusage_default_str))
3925 memswusage = 0;
3926
3927 swap_total = (memswlimit - memlimit) / 1024;
3928 swap_free = (memswusage - memusage) / 1024;
3929 }
3930
3931 total_len = snprintf(d->buf, d->size, "Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
3932
3933 /* When no mem + swap limit is specified or swapaccount=0*/
3934 if (!memswlimit) {
3935 char *line = NULL;
3936 size_t linelen = 0;
3937 FILE *f = fopen("/proc/meminfo", "r");
3938
3939 if (!f)
3940 goto err;
3941
3942 while (getline(&line, &linelen, f) != -1) {
3943 if (startswith(line, "SwapTotal:")) {
3944 sscanf(line, "SwapTotal: %8lu kB", &swap_total);
3945 } else if (startswith(line, "SwapFree:")) {
3946 sscanf(line, "SwapFree: %8lu kB", &swap_free);
3947 }
3948 }
3949
3950 free(line);
3951 fclose(f);
3952 }
3953
3954 if (swap_total > 0) {
a262ddb7
CB
3955 l = snprintf(d->buf + total_len, d->size - total_len,
3956 "none%*svirtual\t\t%lu\t%lu\t0\n", 36, " ",
3957 swap_total, swap_free);
3958 total_len += l;
70dcc12e
SH
3959 }
3960
a262ddb7 3961 if (total_len < 0 || l < 0) {
70dcc12e
SH
3962 perror("Error writing to cache");
3963 rv = 0;
3964 goto err;
3965 }
3966
3967 d->cached = 1;
3968 d->size = (int)total_len;
3969
3970 if (total_len > size) total_len = size;
3971 memcpy(buf, d->buf, total_len);
3972 rv = total_len;
3973
3974err:
3975 free(cg);
3976 free(memswlimit_str);
3977 free(memlimit_str);
3978 free(memusage_str);
3979 free(memswusage_str);
3980 free(memswusage_default_str);
3981 free(memswlimit_default_str);
3982 return rv;
3983}
3984
237e200e
SH
3985static off_t get_procfile_size(const char *which)
3986{
3987 FILE *f = fopen(which, "r");
3988 char *line = NULL;
3989 size_t len = 0;
3990 ssize_t sz, answer = 0;
3991 if (!f)
3992 return 0;
3993
3994 while ((sz = getline(&line, &len, f)) != -1)
3995 answer += sz;
3996 fclose (f);
3997 free(line);
3998
3999 return answer;
4000}
4001
4002int proc_getattr(const char *path, struct stat *sb)
4003{
4004 struct timespec now;
4005
4006 memset(sb, 0, sizeof(struct stat));
4007 if (clock_gettime(CLOCK_REALTIME, &now) < 0)
4008 return -EINVAL;
4009 sb->st_uid = sb->st_gid = 0;
4010 sb->st_atim = sb->st_mtim = sb->st_ctim = now;
4011 if (strcmp(path, "/proc") == 0) {
4012 sb->st_mode = S_IFDIR | 00555;
4013 sb->st_nlink = 2;
4014 return 0;
4015 }
4016 if (strcmp(path, "/proc/meminfo") == 0 ||
4017 strcmp(path, "/proc/cpuinfo") == 0 ||
4018 strcmp(path, "/proc/uptime") == 0 ||
4019 strcmp(path, "/proc/stat") == 0 ||
70dcc12e
SH
4020 strcmp(path, "/proc/diskstats") == 0 ||
4021 strcmp(path, "/proc/swaps") == 0) {
237e200e
SH
4022 sb->st_size = 0;
4023 sb->st_mode = S_IFREG | 00444;
4024 sb->st_nlink = 1;
4025 return 0;
4026 }
4027
4028 return -ENOENT;
4029}
4030
4031int proc_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset,
4032 struct fuse_file_info *fi)
4033{
d639f863
CB
4034 if (filler(buf, ".", NULL, 0) != 0 ||
4035 filler(buf, "..", NULL, 0) != 0 ||
4036 filler(buf, "cpuinfo", NULL, 0) != 0 ||
4037 filler(buf, "meminfo", NULL, 0) != 0 ||
4038 filler(buf, "stat", NULL, 0) != 0 ||
4039 filler(buf, "uptime", NULL, 0) != 0 ||
4040 filler(buf, "diskstats", NULL, 0) != 0 ||
4041 filler(buf, "swaps", NULL, 0) != 0)
237e200e
SH
4042 return -EINVAL;
4043 return 0;
4044}
4045
4046int proc_open(const char *path, struct fuse_file_info *fi)
4047{
4048 int type = -1;
4049 struct file_info *info;
4050
4051 if (strcmp(path, "/proc/meminfo") == 0)
4052 type = LXC_TYPE_PROC_MEMINFO;
4053 else if (strcmp(path, "/proc/cpuinfo") == 0)
4054 type = LXC_TYPE_PROC_CPUINFO;
4055 else if (strcmp(path, "/proc/uptime") == 0)
4056 type = LXC_TYPE_PROC_UPTIME;
4057 else if (strcmp(path, "/proc/stat") == 0)
4058 type = LXC_TYPE_PROC_STAT;
4059 else if (strcmp(path, "/proc/diskstats") == 0)
4060 type = LXC_TYPE_PROC_DISKSTATS;
70dcc12e
SH
4061 else if (strcmp(path, "/proc/swaps") == 0)
4062 type = LXC_TYPE_PROC_SWAPS;
237e200e
SH
4063 if (type == -1)
4064 return -ENOENT;
4065
4066 info = malloc(sizeof(*info));
4067 if (!info)
4068 return -ENOMEM;
4069
4070 memset(info, 0, sizeof(*info));
4071 info->type = type;
4072
4073 info->buflen = get_procfile_size(path) + BUF_RESERVE_SIZE;
4074 do {
4075 info->buf = malloc(info->buflen);
4076 } while (!info->buf);
4077 memset(info->buf, 0, info->buflen);
4078 /* set actual size to buffer size */
4079 info->size = info->buflen;
4080
4081 fi->fh = (unsigned long)info;
4082 return 0;
4083}
4084
bddbb106
SH
4085int proc_access(const char *path, int mask)
4086{
e7849aa3
CB
4087 if (strcmp(path, "/proc") == 0 && access(path, R_OK) == 0)
4088 return 0;
4089
bddbb106
SH
4090 /* these are all read-only */
4091 if ((mask & ~R_OK) != 0)
1b060d0a 4092 return -EACCES;
bddbb106
SH
4093 return 0;
4094}
4095
237e200e
SH
4096int proc_release(const char *path, struct fuse_file_info *fi)
4097{
43215927 4098 do_release_file_info(fi);
237e200e
SH
4099 return 0;
4100}
4101
4102int proc_read(const char *path, char *buf, size_t size, off_t offset,
4103 struct fuse_file_info *fi)
4104{
4105 struct file_info *f = (struct file_info *) fi->fh;
4106
4107 switch (f->type) {
4108 case LXC_TYPE_PROC_MEMINFO:
4109 return proc_meminfo_read(buf, size, offset, fi);
4110 case LXC_TYPE_PROC_CPUINFO:
4111 return proc_cpuinfo_read(buf, size, offset, fi);
4112 case LXC_TYPE_PROC_UPTIME:
4113 return proc_uptime_read(buf, size, offset, fi);
4114 case LXC_TYPE_PROC_STAT:
4115 return proc_stat_read(buf, size, offset, fi);
4116 case LXC_TYPE_PROC_DISKSTATS:
4117 return proc_diskstats_read(buf, size, offset, fi);
70dcc12e
SH
4118 case LXC_TYPE_PROC_SWAPS:
4119 return proc_swaps_read(buf, size, offset, fi);
237e200e
SH
4120 default:
4121 return -EINVAL;
4122 }
4123}
4124
29a73c2f
CB
4125/*
4126 * Functions needed to setup cgroups in the __constructor__.
29a73c2f
CB
4127 */
4128
4129static bool mkdir_p(const char *dir, mode_t mode)
4130{
4131 const char *tmp = dir;
4132 const char *orig = dir;
4133 char *makeme;
4134
4135 do {
4136 dir = tmp + strspn(tmp, "/");
4137 tmp = dir + strcspn(dir, "/");
4138 makeme = strndup(orig, dir - orig);
4139 if (!makeme)
4140 return false;
4141 if (mkdir(makeme, mode) && errno != EEXIST) {
4142 fprintf(stderr, "failed to create directory '%s': %s",
4143 makeme, strerror(errno));
4144 free(makeme);
4145 return false;
4146 }
4147 free(makeme);
4148 } while(tmp != dir);
4149
4150 return true;
4151}
4152
4153static bool umount_if_mounted(void)
4154{
4155 if (umount2(BASEDIR, MNT_DETACH) < 0 && errno != EINVAL) {
480262c9 4156 fprintf(stderr, "failed to unmount %s: %s.\n", BASEDIR, strerror(errno));
29a73c2f
CB
4157 return false;
4158 }
4159 return true;
4160}
4161
4162static int pivot_enter(void)
4163{
4164 int ret = -1, oldroot = -1, newroot = -1;
4165
4166 oldroot = open("/", O_DIRECTORY | O_RDONLY);
4167 if (oldroot < 0) {
4168 fprintf(stderr, "%s: Failed to open old root for fchdir.\n", __func__);
4169 return ret;
4170 }
4171
4172 newroot = open(ROOTDIR, O_DIRECTORY | O_RDONLY);
4173 if (newroot < 0) {
4174 fprintf(stderr, "%s: Failed to open new root for fchdir.\n", __func__);
4175 goto err;
4176 }
4177
4178 /* change into new root fs */
4179 if (fchdir(newroot) < 0) {
4180 fprintf(stderr, "%s: Failed to change directory to new rootfs: %s.\n", __func__, ROOTDIR);
4181 goto err;
4182 }
4183
4184 /* pivot_root into our new root fs */
4185 if (pivot_root(".", ".") < 0) {
4186 fprintf(stderr, "%s: pivot_root() syscall failed: %s.\n", __func__, strerror(errno));
4187 goto err;
4188 }
4189
4190 /*
4191 * At this point the old-root is mounted on top of our new-root.
4192 * To unmounted it we must not be chdir'd into it, so escape back
4193 * to the old-root.
4194 */
4195 if (fchdir(oldroot) < 0) {
4196 fprintf(stderr, "%s: Failed to enter old root.\n", __func__);
4197 goto err;
4198 }
4199 if (umount2(".", MNT_DETACH) < 0) {
4200 fprintf(stderr, "%s: Failed to detach old root.\n", __func__);
4201 goto err;
4202 }
4203
4204 if (fchdir(newroot) < 0) {
4205 fprintf(stderr, "%s: Failed to re-enter new root.\n", __func__);
4206 goto err;
4207 }
4208
4209 ret = 0;
4210
4211err:
4212 if (oldroot > 0)
4213 close(oldroot);
4214 if (newroot > 0)
4215 close(newroot);
4216 return ret;
4217}
4218
4219/* Prepare our new clean root. */
4220static int pivot_prepare(void)
4221{
4222 if (mkdir(ROOTDIR, 0700) < 0 && errno != EEXIST) {
4223 fprintf(stderr, "%s: Failed to create directory for new root.\n", __func__);
4224 return -1;
4225 }
4226
4227 if (mount("/", ROOTDIR, NULL, MS_BIND, 0) < 0) {
4228 fprintf(stderr, "%s: Failed to bind-mount / for new root: %s.\n", __func__, strerror(errno));
4229 return -1;
4230 }
4231
4232 if (mount(RUNTIME_PATH, ROOTDIR RUNTIME_PATH, NULL, MS_BIND, 0) < 0) {
4233 fprintf(stderr, "%s: Failed to bind-mount /run into new root: %s.\n", __func__, strerror(errno));
4234 return -1;
4235 }
4236
4237 if (mount(BASEDIR, ROOTDIR BASEDIR, NULL, MS_REC | MS_MOVE, 0) < 0) {
4238 printf("%s: failed to move " BASEDIR " into new root: %s.\n", __func__, strerror(errno));
4239 return -1;
4240 }
4241
4242 return 0;
4243}
4244
4245static bool pivot_new_root(void)
4246{
4247 /* Prepare new root. */
4248 if (pivot_prepare() < 0)
4249 return false;
4250
4251 /* Pivot into new root. */
4252 if (pivot_enter() < 0)
4253 return false;
4254
4255 return true;
4256}
4257
4258static bool setup_cgfs_dir(void)
4259{
4260 if (!mkdir_p(BASEDIR, 0700)) {
480262c9 4261 fprintf(stderr, "Failed to create lxcfs cgroup mountpoint.\n");
29a73c2f
CB
4262 return false;
4263 }
480262c9 4264
29a73c2f 4265 if (!umount_if_mounted()) {
480262c9
CB
4266 fprintf(stderr, "Failed to clean up old lxcfs cgroup mountpoint.\n");
4267 return false;
4268 }
4269
4270 if (unshare(CLONE_NEWNS) < 0) {
4271 fprintf(stderr, "%s: Failed to unshare mount namespace: %s.\n", __func__, strerror(errno));
4272 return false;
4273 }
4274
4275 if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, 0) < 0) {
4276 fprintf(stderr, "%s: Failed to remount / private: %s.\n", __func__, strerror(errno));
29a73c2f
CB
4277 return false;
4278 }
480262c9 4279
29a73c2f 4280 if (mount("tmpfs", BASEDIR, "tmpfs", 0, "size=100000,mode=700") < 0) {
480262c9 4281 fprintf(stderr, "Failed to mount tmpfs over lxcfs cgroup mountpoint.\n");
29a73c2f
CB
4282 return false;
4283 }
480262c9 4284
29a73c2f
CB
4285 return true;
4286}
4287
4288static bool do_mount_cgroups(void)
4289{
4290 char *target;
4291 size_t clen, len;
4292 int i, ret;
4293
4294 for (i = 0; i < num_hierarchies; i++) {
4295 char *controller = hierarchies[i];
4296 clen = strlen(controller);
4297 len = strlen(BASEDIR) + clen + 2;
4298 target = malloc(len);
4299 if (!target)
4300 return false;
4301 ret = snprintf(target, len, "%s/%s", BASEDIR, controller);
4302 if (ret < 0 || ret >= len) {
4303 free(target);
4304 return false;
4305 }
4306 if (mkdir(target, 0755) < 0 && errno != EEXIST) {
4307 free(target);
4308 return false;
4309 }
4310 if (mount(controller, target, "cgroup", 0, controller) < 0) {
4311 fprintf(stderr, "Failed mounting cgroup %s\n", controller);
4312 free(target);
4313 return false;
4314 }
4315
4316 fd_hierarchies[i] = open(target, O_DIRECTORY);
4317 if (fd_hierarchies[i] < 0) {
4318 free(target);
4319 return false;
4320 }
4321 free(target);
4322 }
4323 return true;
4324}
4325
480262c9 4326static bool cgfs_setup_controllers(void)
29a73c2f 4327{
480262c9 4328 if (!setup_cgfs_dir())
29a73c2f 4329 return false;
29a73c2f
CB
4330
4331 if (!do_mount_cgroups()) {
480262c9 4332 fprintf(stderr, "Failed to set up private lxcfs cgroup mounts.\n");
29a73c2f
CB
4333 return false;
4334 }
4335
4336 if (!pivot_new_root())
4337 return false;
4338
4339 return true;
4340}
4341
480262c9
CB
4342static int preserve_ns(int pid)
4343{
4344 int ret;
4345 size_t len = 5 /* /proc */ + 21 /* /int_as_str */ + 7 /* /ns/mnt */ + 1 /* \0 */;
4346 char path[len];
4347
4348 ret = snprintf(path, len, "/proc/%d/ns/mnt", pid);
4349 if (ret < 0 || (size_t)ret >= len)
4350 return -1;
4351
4352 return open(path, O_RDONLY | O_CLOEXEC);
4353}
4354
29a73c2f 4355static void __attribute__((constructor)) collect_and_mount_subsystems(void)
237e200e
SH
4356{
4357 FILE *f;
4358 char *line = NULL;
4359 size_t len = 0;
480262c9 4360 int i, init_ns = -1;
237e200e
SH
4361
4362 if ((f = fopen("/proc/self/cgroup", "r")) == NULL) {
4363 fprintf(stderr, "Error opening /proc/self/cgroup: %s\n", strerror(errno));
4364 return;
4365 }
4366 while (getline(&line, &len, f) != -1) {
4367 char *p, *p2;
4368
4369 p = strchr(line, ':');
4370 if (!p)
4371 goto out;
4372 *(p++) = '\0';
4373
4374 p2 = strrchr(p, ':');
4375 if (!p2)
4376 goto out;
4377 *p2 = '\0';
4378
a67719f6
CB
4379 /* With cgroupv2 /proc/self/cgroup can contain entries of the
4380 * form: 0::/ This will cause lxcfs to fail the cgroup mounts
4381 * because it parses out the empty string "" and later on passes
4382 * it to mount(). Let's skip such entries.
4383 */
4384 if (!strcmp(p, ""))
4385 continue;
4386
237e200e
SH
4387 if (!store_hierarchy(line, p))
4388 goto out;
4389 }
4390
480262c9
CB
4391 /* Preserve initial namespace. */
4392 init_ns = preserve_ns(getpid());
4393 if (init_ns < 0)
4394 goto out;
4395
4396 fd_hierarchies = malloc(sizeof(int *) * num_hierarchies);
29a73c2f
CB
4397 if (!fd_hierarchies)
4398 goto out;
4399
480262c9
CB
4400 for (i = 0; i < num_hierarchies; i++)
4401 fd_hierarchies[i] = -1;
4402
4403 /* This function calls unshare(CLONE_NEWNS) our initial mount namespace
4404 * to privately mount lxcfs cgroups. */
4405 if (!cgfs_setup_controllers())
29a73c2f 4406 goto out;
480262c9
CB
4407
4408 if (setns(init_ns, 0) < 0)
29a73c2f 4409 goto out;
29a73c2f 4410
237e200e
SH
4411 print_subsystems();
4412
4413out:
4414 free(line);
4415 fclose(f);
480262c9
CB
4416 if (init_ns >= 0)
4417 close(init_ns);
237e200e
SH
4418}
4419
4420static void __attribute__((destructor)) free_subsystems(void)
4421{
4422 int i;
4423
29a73c2f 4424 for (i = 0; i < num_hierarchies; i++) {
237e200e
SH
4425 if (hierarchies[i])
4426 free(hierarchies[i]);
480262c9 4427 if (fd_hierarchies && fd_hierarchies[i] >= 0)
29a73c2f
CB
4428 close(fd_hierarchies[i]);
4429 }
237e200e 4430 free(hierarchies);
480262c9 4431 free(fd_hierarchies);
237e200e 4432}