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