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