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