3 * Copyright © 2014,2015 Canonical, Inc
4 * Author: Serge Hallyn <serge.hallyn@ubuntu.com>
6 * See COPYING file for details.
9 #define FUSE_USE_VERSION 26
23 #include <linux/sched.h>
24 #include <sys/socket.h>
25 #include <sys/mount.h>
26 #include <sys/epoll.h>
30 #define GLIB_DISABLE_DEPRECATION_WARNINGS
31 #include <glib-object.h>
35 #include "config.h" // for VERSION
40 LXC_TYPE_PROC_MEMINFO
,
41 LXC_TYPE_PROC_CPUINFO
,
44 LXC_TYPE_PROC_DISKSTATS
,
52 char *buf
; // unused as of yet
54 int size
; //actual data size
58 /* reserve buffer size, for cpuall in /proc/stat */
59 #define BUF_RESERVE_SIZE 256
63 * src: a pointer to a char* in which ot append the pid.
64 * sz: the number of characters printed so far, minus trailing \0.
65 * asz: the allocated size so far
66 * pid: the pid to append
68 static void must_strcat_pid(char **src
, size_t *sz
, size_t *asz
, pid_t pid
)
72 int tmplen
= sprintf(tmp
, "%d\n", (int)pid
);
74 if (!*src
|| tmplen
+ *sz
+ 1 >= *asz
) {
77 tmp
= realloc(*src
, *asz
+ BUF_RESERVE_SIZE
);
80 *asz
+= BUF_RESERVE_SIZE
;
82 memcpy((*src
) +*sz
, tmp
, tmplen
);
87 static pid_t
get_init_pid_for_task(pid_t task
);
89 static int wait_for_pid(pid_t pid
)
94 ret
= waitpid(pid
, &status
, 0);
102 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
108 * Given a open file * to /proc/pid/{u,g}id_map, and an id
109 * valid in the caller's namespace, return the id mapped into
111 * Returns the mapped id, or -1 on error.
114 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
116 unsigned int nsuid
, // base id for a range in the idfile's namespace
117 hostuid
, // base id for a range in the caller's namespace
118 count
; // number of ids in this range
122 fseek(idfile
, 0L, SEEK_SET
);
123 while (fgets(line
, 400, idfile
)) {
124 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
127 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
129 * uids wrapped around - unexpected as this is a procfile,
132 fprintf(stderr
, "pid wrapparound at entry %u %u %u in %s\n",
133 nsuid
, hostuid
, count
, line
);
136 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
138 * now since hostuid <= in_id < hostuid+count, and
139 * hostuid+count and nsuid+count do not wrap around,
140 * we know that nsuid+(in_id-hostuid) which must be
141 * less that nsuid+(count) must not wrap around
143 return (in_id
- hostuid
) + nsuid
;
152 * for is_privileged_over,
153 * specify whether we require the calling uid to be root in his
156 #define NS_ROOT_REQD true
157 #define NS_ROOT_OPT false
161 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
168 if (victim
== -1 || uid
== -1)
172 * If the request is one not requiring root in the namespace,
173 * then having the same uid suffices. (i.e. uid 1000 has write
174 * access to files owned by uid 1000
176 if (!req_ns_root
&& uid
== victim
)
179 ret
= snprintf(fpath
, PROCLEN
, "/proc/%d/uid_map", pid
);
180 if (ret
< 0 || ret
>= PROCLEN
)
182 FILE *f
= fopen(fpath
, "r");
186 /* if caller's not root in his namespace, reject */
187 nsuid
= convert_id_to_ns(f
, uid
);
192 * If victim is not mapped into caller's ns, reject.
193 * XXX I'm not sure this check is needed given that fuse
194 * will be sending requests where the vfs has converted
196 nsuid
= convert_id_to_ns(f
, victim
);
207 static bool perms_include(int fmode
, mode_t req_mode
)
211 switch (req_mode
& O_ACCMODE
) {
219 r
= S_IROTH
| S_IWOTH
;
224 return ((fmode
& r
) == r
);
230 * querycg is /a/b/c/d/e
233 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
237 if (strlen(taskcg
) <= strlen(querycg
)) {
238 fprintf(stderr
, "%s: I was fed bad input\n", __func__
);
242 if (strcmp(querycg
, "/") == 0)
243 start
= strdup(taskcg
+ 1);
245 start
= strdup(taskcg
+ strlen(querycg
) + 1);
248 end
= strchr(start
, '/');
254 static void stripnewline(char *x
)
256 size_t l
= strlen(x
);
257 if (l
&& x
[l
-1] == '\n')
261 static char *get_pid_cgroup(pid_t pid
, const char *contrl
)
269 const char *h
= find_mounted_controller(contrl
);
273 ret
= snprintf(fnam
, PROCLEN
, "/proc/%d/cgroup", pid
);
274 if (ret
< 0 || ret
>= PROCLEN
)
276 if (!(f
= fopen(fnam
, "r")))
279 while (getline(&line
, &len
, f
) != -1) {
283 c1
= strchr(line
, ':');
287 c2
= strchr(c1
, ':');
291 if (strcmp(c1
, h
) != 0)
308 * check whether a fuse context may access a cgroup dir or file
310 * If file is not null, it is a cgroup file to check under cg.
311 * If file is null, then we are checking perms on cg itself.
313 * For files we can check the mode of the list_keys result.
314 * For cgroups, we must make assumptions based on the files under the
315 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
318 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
320 struct cgfs_files
*k
= NULL
;
323 k
= cgfs_get_key(contrl
, cg
, file
);
327 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
328 if (perms_include(k
->mode
>> 6, mode
)) {
333 if (fc
->gid
== k
->gid
) {
334 if (perms_include(k
->mode
>> 3, mode
)) {
339 ret
= perms_include(k
->mode
, mode
);
346 #define INITSCOPE "/init.scope"
347 static void prune_init_slice(char *cg
)
350 point
= cg
+ strlen(cg
) - strlen(INITSCOPE
);
353 if (strcmp(point
, INITSCOPE
) == 0) {
362 * If caller is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
363 * If caller is in /a, he may act on /a/b, but not on /b.
364 * if the answer is false and nextcg is not NULL, then *nextcg will point
365 * to a string containing the next cgroup directory under cg, which must be
366 * freed by the caller.
368 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
371 char *c2
= get_pid_cgroup(pid
, contrl
);
376 prune_init_slice(c2
);
379 * callers pass in '/' for root cgroup, otherwise they pass
380 * in a cgroup without leading '/'
382 linecmp
= *cg
== '/' ? c2
: c2
+1;
383 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
385 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
397 * If caller is in /a/b/c, he may see that /a exists, but not /b or /a/c.
399 static bool caller_may_see_dir(pid_t pid
, const char *contrl
, const char *cg
)
403 size_t target_len
, task_len
;
405 if (strcmp(cg
, "/") == 0)
408 c2
= get_pid_cgroup(pid
, contrl
);
411 prune_init_slice(c2
);
414 target_len
= strlen(cg
);
415 task_len
= strlen(task_cg
);
417 /* Task is in the root cg, it can see everything. This case is
418 * not handled by the strmcps below, since they test for the
419 * last /, but that is the first / that we've chopped off
425 if (strcmp(cg
, task_cg
) == 0) {
429 if (target_len
< task_len
) {
430 /* looking up a parent dir */
431 if (strncmp(task_cg
, cg
, target_len
) == 0 && task_cg
[target_len
] == '/')
435 if (target_len
> task_len
) {
436 /* looking up a child dir */
437 if (strncmp(task_cg
, cg
, task_len
) == 0 && cg
[task_len
] == '/')
448 * given /cgroup/freezer/a/b, return "freezer".
449 * the returned char* should NOT be freed.
451 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
456 if (strlen(path
) < 9)
458 if (*(path
+7) != '/')
464 slash
= strstr(contr
, "/");
469 for (i
= 0; i
< num_hierarchies
; i
++) {
470 if (hierarchies
[i
] && strcmp(hierarchies
[i
], contr
) == 0)
471 return hierarchies
[i
];
477 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
478 * Note that the returned value may include files (keynames) etc
480 static const char *find_cgroup_in_path(const char *path
)
484 if (strlen(path
) < 9)
486 p1
= strstr(path
+8, "/");
493 * split the last path element from the path in @cg.
494 * @dir is newly allocated and should be freed, @last not
496 static void get_cgdir_and_path(const char *cg
, char **dir
, char **last
)
503 *last
= strrchr(cg
, '/');
508 p
= strrchr(*dir
, '/');
513 * FUSE ops for /cgroup
516 static int cg_getattr(const char *path
, struct stat
*sb
)
519 struct fuse_context
*fc
= fuse_get_context();
521 char *last
= NULL
, *path1
, *path2
;
522 struct cgfs_files
*k
= NULL
;
524 const char *controller
= NULL
;
531 memset(sb
, 0, sizeof(struct stat
));
533 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
536 sb
->st_uid
= sb
->st_gid
= 0;
537 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
540 if (strcmp(path
, "/cgroup") == 0) {
541 sb
->st_mode
= S_IFDIR
| 00755;
546 controller
= pick_controller_from_path(fc
, path
);
549 cgroup
= find_cgroup_in_path(path
);
551 /* this is just /cgroup/controller, return it as a dir */
552 sb
->st_mode
= S_IFDIR
| 00755;
557 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
567 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
568 * Then check that caller's cgroup is under path if last is a child
569 * cgroup, or cgdir if last is a file */
571 if (is_child_cgroup(controller
, path1
, path2
)) {
572 if (!caller_may_see_dir(fc
->pid
, controller
, cgroup
)) {
576 if (!caller_is_in_ancestor(fc
->pid
, controller
, cgroup
, NULL
)) {
577 /* this is just /cgroup/controller, return it as a dir */
578 sb
->st_mode
= S_IFDIR
| 00555;
583 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
)) {
588 // get uid, gid, from '/tasks' file and make up a mode
589 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
590 sb
->st_mode
= S_IFDIR
| 00755;
591 k
= cgfs_get_key(controller
, cgroup
, NULL
);
593 sb
->st_uid
= sb
->st_gid
= 0;
604 if ((k
= cgfs_get_key(controller
, path1
, path2
)) != NULL
) {
605 sb
->st_mode
= S_IFREG
| k
->mode
;
611 if (!caller_is_in_ancestor(fc
->pid
, controller
, path1
, NULL
)) {
615 if (!fc_may_access(fc
, controller
, path1
, path2
, O_RDONLY
)) {
628 static int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
630 struct fuse_context
*fc
= fuse_get_context();
632 struct file_info
*dir_info
;
633 char *controller
= NULL
;
638 if (strcmp(path
, "/cgroup") == 0) {
642 // return list of keys for the controller, and list of child cgroups
643 controller
= pick_controller_from_path(fc
, path
);
647 cgroup
= find_cgroup_in_path(path
);
649 /* this is just /cgroup/controller, return its contents */
655 if (!caller_may_see_dir(fc
->pid
, controller
, cgroup
))
657 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
661 /* we'll free this at cg_releasedir */
662 dir_info
= malloc(sizeof(*dir_info
));
665 dir_info
->controller
= must_copy_string(controller
);
666 dir_info
->cgroup
= must_copy_string(cgroup
);
667 dir_info
->type
= LXC_TYPE_CGDIR
;
668 dir_info
->buf
= NULL
;
669 dir_info
->file
= NULL
;
670 dir_info
->buflen
= 0;
672 fi
->fh
= (unsigned long)dir_info
;
676 static int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
677 struct fuse_file_info
*fi
)
679 struct file_info
*d
= (struct file_info
*)fi
->fh
;
680 struct cgfs_files
**list
= NULL
;
683 struct fuse_context
*fc
= fuse_get_context();
686 if (d
->type
!= LXC_TYPE_CGDIR
) {
687 fprintf(stderr
, "Internal error: file cache info used in readdir\n");
690 if (!d
->cgroup
&& !d
->controller
) {
691 // ls /var/lib/lxcfs/cgroup - just show list of controllers
694 for (i
= 0; i
< num_hierarchies
; i
++) {
695 if (hierarchies
[i
] && filler(buf
, hierarchies
[i
], NULL
, 0) != 0) {
702 if (!cgfs_list_keys(d
->controller
, d
->cgroup
, &list
)) {
703 // not a valid cgroup
708 if (!caller_is_in_ancestor(fc
->pid
, d
->controller
, d
->cgroup
, &nextcg
)) {
711 ret
= filler(buf
, nextcg
, NULL
, 0);
722 for (i
= 0; list
[i
]; i
++) {
723 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
729 // now get the list of child cgroups
731 if (!cgfs_list_children(d
->controller
, d
->cgroup
, &clist
)) {
735 for (i
= 0; clist
[i
]; i
++) {
736 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
746 for (i
= 0; clist
[i
]; i
++)
753 static void do_release_file_info(struct file_info
*f
)
764 static int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
766 struct file_info
*d
= (struct file_info
*)fi
->fh
;
768 do_release_file_info(d
);
772 static int cg_open(const char *path
, struct fuse_file_info
*fi
)
775 char *last
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
776 struct cgfs_files
*k
= NULL
;
777 struct file_info
*file_info
;
778 struct fuse_context
*fc
= fuse_get_context();
784 controller
= pick_controller_from_path(fc
, path
);
787 cgroup
= find_cgroup_in_path(path
);
791 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
800 k
= cgfs_get_key(controller
, path1
, path2
);
807 if (!caller_may_see_dir(fc
->pid
, controller
, path1
)) {
811 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
)) {
812 // should never get here
817 /* we'll free this at cg_release */
818 file_info
= malloc(sizeof(*file_info
));
823 file_info
->controller
= must_copy_string(controller
);
824 file_info
->cgroup
= must_copy_string(path1
);
825 file_info
->file
= must_copy_string(path2
);
826 file_info
->type
= LXC_TYPE_CGFILE
;
827 file_info
->buf
= NULL
;
828 file_info
->buflen
= 0;
830 fi
->fh
= (unsigned long)file_info
;
838 static int cg_release(const char *path
, struct fuse_file_info
*fi
)
840 struct file_info
*f
= (struct file_info
*)fi
->fh
;
842 do_release_file_info(f
);
846 #define POLLIN_SET ( EPOLLIN | EPOLLHUP | EPOLLRDHUP )
848 static bool wait_for_sock(int sock
, int timeout
)
850 struct epoll_event ev
;
853 epfd
= epoll_create(1);
855 fprintf(stderr
, "Failed to create epoll socket: %m\n");
859 ev
.events
= POLLIN_SET
;
861 if (epoll_ctl(epfd
, EPOLL_CTL_ADD
, sock
, &ev
) < 0) {
862 fprintf(stderr
, "Failed adding socket to epoll: %m\n");
867 ret
= epoll_wait(epfd
, &ev
, 1, timeout
);
873 fprintf(stderr
, "Failure during epoll_wait: %m\n");
879 static int msgrecv(int sockfd
, void *buf
, size_t len
)
881 if (!wait_for_sock(sockfd
, 2))
883 return recv(sockfd
, buf
, len
, MSG_DONTWAIT
);
886 #define SEND_CREDS_OK 0
887 #define SEND_CREDS_NOTSK 1
888 #define SEND_CREDS_FAIL 2
889 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
)
891 struct msghdr msg
= { 0 };
893 struct cmsghdr
*cmsg
;
894 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
899 if (msgrecv(sock
, buf
, 1) != 1) {
900 fprintf(stderr
, "%s: Error getting reply from server over socketpair\n",
902 return SEND_CREDS_FAIL
;
906 msg
.msg_control
= cmsgbuf
;
907 msg
.msg_controllen
= sizeof(cmsgbuf
);
909 cmsg
= CMSG_FIRSTHDR(&msg
);
910 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
911 cmsg
->cmsg_level
= SOL_SOCKET
;
912 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
913 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
920 iov
.iov_len
= sizeof(buf
);
924 if (sendmsg(sock
, &msg
, 0) < 0) {
925 fprintf(stderr
, "%s: failed at sendmsg: %s\n", __func__
,
928 return SEND_CREDS_NOTSK
;
929 return SEND_CREDS_FAIL
;
932 return SEND_CREDS_OK
;
935 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
937 struct msghdr msg
= { 0 };
939 struct cmsghdr
*cmsg
;
940 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
951 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
952 fprintf(stderr
, "Failed to set passcred: %s\n", strerror(errno
));
956 if (write(sock
, buf
, 1) != 1) {
957 fprintf(stderr
, "Failed to start write on scm fd: %s\n", strerror(errno
));
963 msg
.msg_control
= cmsgbuf
;
964 msg
.msg_controllen
= sizeof(cmsgbuf
);
967 iov
.iov_len
= sizeof(buf
);
971 if (!wait_for_sock(sock
, 2)) {
972 fprintf(stderr
, "Timed out waiting for scm_cred: %s\n",
976 ret
= recvmsg(sock
, &msg
, MSG_DONTWAIT
);
978 fprintf(stderr
, "Failed to receive scm_cred: %s\n",
983 cmsg
= CMSG_FIRSTHDR(&msg
);
985 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
986 cmsg
->cmsg_level
== SOL_SOCKET
&&
987 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
988 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
997 * pid_to_ns - reads pids from a ucred over a socket, then writes the
998 * int value back over the socket. This shifts the pid from the
999 * sender's pidns into tpid's pidns.
1001 static void pid_to_ns(int sock
, pid_t tpid
)
1006 while (recv_creds(sock
, &cred
, &v
)) {
1009 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
1016 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
1017 * in your old pidns. Only children which you fork will be in the target
1018 * pidns. So the pid_to_ns_wrapper does the setns, then forks a child to
1019 * actually convert pids
1021 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
1023 int newnsfd
= -1, ret
, cpipe
[2];
1028 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
1029 if (ret
< 0 || ret
>= sizeof(fnam
))
1031 newnsfd
= open(fnam
, O_RDONLY
);
1034 if (setns(newnsfd
, 0) < 0)
1038 if (pipe(cpipe
) < 0)
1048 if (write(cpipe
[1], &b
, sizeof(char)) < 0) {
1049 fprintf(stderr
, "%s (child): erorr on write: %s\n",
1050 __func__
, strerror(errno
));
1053 pid_to_ns(sock
, tpid
);
1054 _exit(1); // not reached
1056 // give the child 1 second to be done forking and
1058 if (!wait_for_sock(cpipe
[0], 1))
1060 ret
= read(cpipe
[0], &v
, 1);
1061 if (ret
!= sizeof(char) || v
!= '1')
1064 if (!wait_for_pid(cpid
))
1070 * To read cgroup files with a particular pid, we will setns into the child
1071 * pidns, open a pipe, fork a child - which will be the first to really be in
1072 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
1074 static bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
1076 int sock
[2] = {-1, -1};
1077 char *tmpdata
= NULL
;
1079 pid_t qpid
, cpid
= -1;
1080 bool answer
= false;
1083 size_t sz
= 0, asz
= 0;
1085 if (!cgfs_get_value(contrl
, cg
, file
, &tmpdata
))
1089 * Now we read the pids from returned data one by one, pass
1090 * them into a child in the target namespace, read back the
1091 * translated pids, and put them into our to-return data
1094 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1095 perror("socketpair");
1104 if (!cpid
) // child - exits when done
1105 pid_to_ns_wrapper(sock
[1], tpid
);
1107 char *ptr
= tmpdata
;
1110 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
1112 ret
= send_creds(sock
[0], &cred
, v
, true);
1114 if (ret
== SEND_CREDS_NOTSK
)
1116 if (ret
== SEND_CREDS_FAIL
)
1119 // read converted results
1120 if (!wait_for_sock(sock
[0], 2)) {
1121 fprintf(stderr
, "%s: timed out waiting for pid from child: %s\n",
1122 __func__
, strerror(errno
));
1125 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
1126 fprintf(stderr
, "%s: error reading pid from child: %s\n",
1127 __func__
, strerror(errno
));
1130 must_strcat_pid(d
, &sz
, &asz
, qpid
);
1132 ptr
= strchr(ptr
, '\n');
1138 cred
.pid
= getpid();
1140 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
1141 // failed to ask child to exit
1142 fprintf(stderr
, "%s: failed to ask child to exit: %s\n",
1143 __func__
, strerror(errno
));
1153 if (sock
[0] != -1) {
1160 static int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
1161 struct fuse_file_info
*fi
)
1163 struct fuse_context
*fc
= fuse_get_context();
1164 struct file_info
*f
= (struct file_info
*)fi
->fh
;
1165 struct cgfs_files
*k
= NULL
;
1170 if (f
->type
!= LXC_TYPE_CGFILE
) {
1171 fprintf(stderr
, "Internal error: directory cache info used in cg_read\n");
1184 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
1190 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_RDONLY
)) { // should never get here
1195 if (strcmp(f
->file
, "tasks") == 0 ||
1196 strcmp(f
->file
, "/tasks") == 0 ||
1197 strcmp(f
->file
, "/cgroup.procs") == 0 ||
1198 strcmp(f
->file
, "cgroup.procs") == 0)
1199 // special case - we have to translate the pids
1200 r
= do_read_pids(fc
->pid
, f
->controller
, f
->cgroup
, f
->file
, &data
);
1202 r
= cgfs_get_value(f
->controller
, f
->cgroup
, f
->file
, &data
);
1216 memcpy(buf
, data
, s
);
1217 if (s
> 0 && s
< size
&& data
[s
-1] != '\n')
1227 static void pid_from_ns(int sock
, pid_t tpid
)
1237 if (!wait_for_sock(sock
, 2)) {
1238 fprintf(stderr
, "%s: timeout reading from parent\n", __func__
);
1241 if ((ret
= read(sock
, &vpid
, sizeof(pid_t
))) != sizeof(pid_t
)) {
1242 fprintf(stderr
, "%s: bad read from parent: %s\n",
1243 __func__
, strerror(errno
));
1246 if (vpid
== -1) // done
1250 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
1252 cred
.pid
= getpid();
1253 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
1260 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
1262 int newnsfd
= -1, ret
, cpipe
[2];
1267 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
1268 if (ret
< 0 || ret
>= sizeof(fnam
))
1270 newnsfd
= open(fnam
, O_RDONLY
);
1273 if (setns(newnsfd
, 0) < 0)
1277 if (pipe(cpipe
) < 0)
1289 if (write(cpipe
[1], &b
, sizeof(char)) < 0) {
1290 fprintf(stderr
, "%s (child): erorr on write: %s\n",
1291 __func__
, strerror(errno
));
1294 pid_from_ns(sock
, tpid
);
1297 // give the child 1 second to be done forking and
1299 if (!wait_for_sock(cpipe
[0], 1))
1301 ret
= read(cpipe
[0], &v
, 1);
1302 if (ret
!= sizeof(char) || v
!= '1') {
1306 if (!wait_for_pid(cpid
))
1311 kill(cpid
, SIGKILL
);
1317 * Given host @uid, return the uid to which it maps in
1318 * @pid's user namespace, or -1 if none.
1320 bool hostuid_to_ns(uid_t uid
, pid_t pid
, uid_t
*answer
)
1325 sprintf(line
, "/proc/%d/uid_map", pid
);
1326 if ((f
= fopen(line
, "r")) == NULL
) {
1330 *answer
= convert_id_to_ns(f
, uid
);
1339 * get_pid_creds: get the real uid and gid of @pid from
1341 * (XXX should we use euid here?)
1343 void get_pid_creds(pid_t pid
, uid_t
*uid
, gid_t
*gid
)
1352 sprintf(line
, "/proc/%d/status", pid
);
1353 if ((f
= fopen(line
, "r")) == NULL
) {
1354 fprintf(stderr
, "Error opening %s: %s\n", line
, strerror(errno
));
1357 while (fgets(line
, 400, f
)) {
1358 if (strncmp(line
, "Uid:", 4) == 0) {
1359 if (sscanf(line
+4, "%u", &u
) != 1) {
1360 fprintf(stderr
, "bad uid line for pid %u\n", pid
);
1365 } else if (strncmp(line
, "Gid:", 4) == 0) {
1366 if (sscanf(line
+4, "%u", &g
) != 1) {
1367 fprintf(stderr
, "bad gid line for pid %u\n", pid
);
1378 * May the requestor @r move victim @v to a new cgroup?
1379 * This is allowed if
1380 * . they are the same task
1381 * . they are ownedy by the same uid
1382 * . @r is root on the host, or
1383 * . @v's uid is mapped into @r's where @r is root.
1385 bool may_move_pid(pid_t r
, uid_t r_uid
, pid_t v
)
1387 uid_t v_uid
, tmpuid
;
1394 get_pid_creds(v
, &v_uid
, &v_gid
);
1397 if (hostuid_to_ns(r_uid
, r
, &tmpuid
) && tmpuid
== 0
1398 && hostuid_to_ns(v_uid
, r
, &tmpuid
))
1403 static bool do_write_pids(pid_t tpid
, uid_t tuid
, const char *contrl
, const char *cg
,
1404 const char *file
, const char *buf
)
1406 int sock
[2] = {-1, -1};
1407 pid_t qpid
, cpid
= -1;
1408 FILE *pids_file
= NULL
;
1409 bool answer
= false, fail
= false;
1411 pids_file
= open_pids_file(contrl
, cg
);
1416 * write the pids to a socket, have helper in writer's pidns
1417 * call movepid for us
1419 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1420 perror("socketpair");
1428 if (!cpid
) { // child
1430 pid_from_ns_wrapper(sock
[1], tpid
);
1433 const char *ptr
= buf
;
1434 while (sscanf(ptr
, "%d", &qpid
) == 1) {
1438 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
1439 fprintf(stderr
, "%s: error writing pid to child: %s\n",
1440 __func__
, strerror(errno
));
1444 if (recv_creds(sock
[0], &cred
, &v
)) {
1446 if (!may_move_pid(tpid
, tuid
, cred
.pid
)) {
1450 if (fprintf(pids_file
, "%d", (int) cred
.pid
) < 0)
1455 ptr
= strchr(ptr
, '\n');
1461 /* All good, write the value */
1463 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
1464 fprintf(stderr
, "Warning: failed to ask child to exit\n");
1472 if (sock
[0] != -1) {
1477 if (fclose(pids_file
) != 0)
1483 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
1484 struct fuse_file_info
*fi
)
1486 struct fuse_context
*fc
= fuse_get_context();
1487 char *localbuf
= NULL
;
1488 struct cgfs_files
*k
= NULL
;
1489 struct file_info
*f
= (struct file_info
*)fi
->fh
;
1492 if (f
->type
!= LXC_TYPE_CGFILE
) {
1493 fprintf(stderr
, "Internal error: directory cache info used in cg_write\n");
1503 localbuf
= alloca(size
+1);
1504 localbuf
[size
] = '\0';
1505 memcpy(localbuf
, buf
, size
);
1507 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
1512 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_WRONLY
)) {
1517 if (strcmp(f
->file
, "tasks") == 0 ||
1518 strcmp(f
->file
, "/tasks") == 0 ||
1519 strcmp(f
->file
, "/cgroup.procs") == 0 ||
1520 strcmp(f
->file
, "cgroup.procs") == 0)
1521 // special case - we have to translate the pids
1522 r
= do_write_pids(fc
->pid
, fc
->uid
, f
->controller
, f
->cgroup
, f
->file
, localbuf
);
1524 r
= cgfs_set_value(f
->controller
, f
->cgroup
, f
->file
, localbuf
);
1534 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
1536 struct fuse_context
*fc
= fuse_get_context();
1537 char *cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
1538 struct cgfs_files
*k
= NULL
;
1545 if (strcmp(path
, "/cgroup") == 0)
1548 controller
= pick_controller_from_path(fc
, path
);
1551 cgroup
= find_cgroup_in_path(path
);
1553 /* this is just /cgroup/controller */
1556 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1566 if (is_child_cgroup(controller
, path1
, path2
)) {
1567 // get uid, gid, from '/tasks' file and make up a mode
1568 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1569 k
= cgfs_get_key(controller
, cgroup
, "tasks");
1572 k
= cgfs_get_key(controller
, path1
, path2
);
1580 * This being a fuse request, the uid and gid must be valid
1581 * in the caller's namespace. So we can just check to make
1582 * sure that the caller is root in his uid, and privileged
1583 * over the file's current owner.
1585 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
)) {
1590 ret
= cgfs_chown_file(controller
, cgroup
, uid
, gid
);
1599 int cg_chmod(const char *path
, mode_t mode
)
1601 struct fuse_context
*fc
= fuse_get_context();
1602 char * cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
1603 struct cgfs_files
*k
= NULL
;
1610 if (strcmp(path
, "/cgroup") == 0)
1613 controller
= pick_controller_from_path(fc
, path
);
1616 cgroup
= find_cgroup_in_path(path
);
1618 /* this is just /cgroup/controller */
1621 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1631 if (is_child_cgroup(controller
, path1
, path2
)) {
1632 // get uid, gid, from '/tasks' file and make up a mode
1633 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1634 k
= cgfs_get_key(controller
, cgroup
, "tasks");
1637 k
= cgfs_get_key(controller
, path1
, path2
);
1645 * This being a fuse request, the uid and gid must be valid
1646 * in the caller's namespace. So we can just check to make
1647 * sure that the caller is root in his uid, and privileged
1648 * over the file's current owner.
1650 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
1655 if (!cgfs_chmod_file(controller
, cgroup
, mode
)) {
1667 int cg_mkdir(const char *path
, mode_t mode
)
1669 struct fuse_context
*fc
= fuse_get_context();
1670 char *last
= NULL
, *path1
, *cgdir
= NULL
, *controller
, *next
= NULL
;
1678 controller
= pick_controller_from_path(fc
, path
);
1682 cgroup
= find_cgroup_in_path(path
);
1686 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1692 if (!caller_is_in_ancestor(fc
->pid
, controller
, path1
, &next
)) {
1693 if (last
&& strcmp(next
, last
) == 0)
1700 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
)) {
1704 if (!caller_is_in_ancestor(fc
->pid
, controller
, path1
, NULL
)) {
1709 ret
= cgfs_create(controller
, cgroup
, fc
->uid
, fc
->gid
);
1717 static int cg_rmdir(const char *path
)
1719 struct fuse_context
*fc
= fuse_get_context();
1720 char *last
= NULL
, *cgdir
= NULL
, *controller
, *next
= NULL
;
1727 controller
= pick_controller_from_path(fc
, path
);
1731 cgroup
= find_cgroup_in_path(path
);
1735 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1741 if (!caller_is_in_ancestor(fc
->pid
, controller
, cgroup
, &next
)) {
1742 if (!last
|| strcmp(next
, last
) == 0)
1749 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
)) {
1753 if (!caller_is_in_ancestor(fc
->pid
, controller
, cgroup
, NULL
)) {
1758 if (!cgfs_remove(controller
, cgroup
)) {
1771 static bool startswith(const char *line
, const char *pref
)
1773 if (strncmp(line
, pref
, strlen(pref
)) == 0)
1778 static void get_mem_cached(char *memstat
, unsigned long *v
)
1784 if (startswith(memstat
, "total_cache")) {
1785 sscanf(memstat
+ 11, "%lu", v
);
1789 eol
= strchr(memstat
, '\n');
1796 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
1802 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
1804 size_t len
= strlen(key
);
1808 if (startswith(str
, key
)) {
1809 sscanf(str
+ len
, "%lu", v
);
1812 eol
= strchr(str
, '\n');
1819 static int read_file(const char *path
, char *buf
, size_t size
,
1820 struct file_info
*d
)
1822 size_t linelen
= 0, total_len
= 0, rv
= 0;
1824 char *cache
= d
->buf
;
1825 size_t cache_size
= d
->buflen
;
1826 FILE *f
= fopen(path
, "r");
1830 while (getline(&line
, &linelen
, f
) != -1) {
1831 size_t l
= snprintf(cache
, cache_size
, "%s", line
);
1833 perror("Error writing to cache");
1837 if (l
>= cache_size
) {
1838 fprintf(stderr
, "Internal error: truncated write to cache\n");
1842 if (l
< cache_size
) {
1847 cache
+= cache_size
;
1848 total_len
+= cache_size
;
1854 d
->size
= total_len
;
1855 if (total_len
> size
) total_len
= size
;
1857 /* read from off 0 */
1858 memcpy(buf
, d
->buf
, total_len
);
1867 * FUSE ops for /proc
1870 static unsigned long get_memlimit(const char *cgroup
)
1872 char *memlimit_str
= NULL
;
1873 unsigned long memlimit
= -1;
1875 if (cgfs_get_value("memory", cgroup
, "memory.limit_in_bytes", &memlimit_str
))
1876 memlimit
= strtoul(memlimit_str
, NULL
, 10);
1883 static unsigned long get_min_memlimit(const char *cgroup
)
1885 char *copy
= strdupa(cgroup
);
1886 unsigned long memlimit
= 0, retlimit
;
1888 retlimit
= get_memlimit(copy
);
1890 while (strcmp(copy
, "/") != 0) {
1891 copy
= dirname(copy
);
1892 memlimit
= get_memlimit(copy
);
1893 if (memlimit
!= -1 && memlimit
< retlimit
)
1894 retlimit
= memlimit
;
1900 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
1901 struct fuse_file_info
*fi
)
1903 struct fuse_context
*fc
= fuse_get_context();
1904 struct file_info
*d
= (struct file_info
*)fi
->fh
;
1906 char *memusage_str
= NULL
, *memstat_str
= NULL
,
1907 *memswlimit_str
= NULL
, *memswusage_str
= NULL
,
1908 *memswlimit_default_str
= NULL
, *memswusage_default_str
= NULL
;
1909 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0, memswusage
= 0,
1910 cached
= 0, hosttotal
= 0;
1912 size_t linelen
= 0, total_len
= 0, rv
= 0;
1913 char *cache
= d
->buf
;
1914 size_t cache_size
= d
->buflen
;
1918 if (offset
> d
->size
)
1922 int left
= d
->size
- offset
;
1923 total_len
= left
> size
? size
: left
;
1924 memcpy(buf
, cache
+ offset
, total_len
);
1928 cg
= get_pid_cgroup(fc
->pid
, "memory");
1930 return read_file("/proc/meminfo", buf
, size
, d
);
1932 memlimit
= get_min_memlimit(cg
);
1933 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
1935 if (!cgfs_get_value("memory", cg
, "memory.stat", &memstat_str
))
1938 // Following values are allowed to fail, because swapaccount might be turned
1939 // off for current kernel
1940 if(cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
) &&
1941 cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
))
1943 /* If swapaccounting is turned on, then default value is assumed to be that of cgroup / */
1944 if (!cgfs_get_value("memory", "/", "memory.memsw.limit_in_bytes", &memswlimit_default_str
))
1946 if (!cgfs_get_value("memory", "/", "memory.memsw.usage_in_bytes", &memswusage_default_str
))
1949 memswlimit
= strtoul(memswlimit_str
, NULL
, 10);
1950 memswusage
= strtoul(memswusage_str
, NULL
, 10);
1952 if (!strcmp(memswlimit_str
, memswlimit_default_str
))
1954 if (!strcmp(memswusage_str
, memswusage_default_str
))
1957 memswlimit
= memswlimit
/ 1024;
1958 memswusage
= memswusage
/ 1024;
1961 memusage
= strtoul(memusage_str
, NULL
, 10);
1965 get_mem_cached(memstat_str
, &cached
);
1967 f
= fopen("/proc/meminfo", "r");
1971 while (getline(&line
, &linelen
, f
) != -1) {
1973 char *printme
, lbuf
[100];
1975 memset(lbuf
, 0, 100);
1976 if (startswith(line
, "MemTotal:")) {
1977 sscanf(line
+14, "%lu", &hosttotal
);
1978 if (hosttotal
< memlimit
)
1979 memlimit
= hosttotal
;
1980 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
1982 } else if (startswith(line
, "MemFree:")) {
1983 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
1985 } else if (startswith(line
, "MemAvailable:")) {
1986 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
);
1988 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0) {
1989 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
- memlimit
);
1991 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 && memswusage
> 0) {
1992 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n",
1993 (memswlimit
- memlimit
) - (memswusage
- memusage
));
1995 } else if (startswith(line
, "Buffers:")) {
1996 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
1998 } else if (startswith(line
, "Cached:")) {
1999 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
2001 } else if (startswith(line
, "SwapCached:")) {
2002 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
2007 l
= snprintf(cache
, cache_size
, "%s", printme
);
2009 perror("Error writing to cache");
2014 if (l
>= cache_size
) {
2015 fprintf(stderr
, "Internal error: truncated write to cache\n");
2026 d
->size
= total_len
;
2027 if (total_len
> size
) total_len
= size
;
2028 memcpy(buf
, d
->buf
, total_len
);
2037 free(memswlimit_str
);
2038 free(memswusage_str
);
2040 free(memswlimit_default_str
);
2041 free(memswusage_default_str
);
2046 * Read the cpuset.cpus for cg
2047 * Return the answer in a newly allocated string which must be freed
2049 static char *get_cpuset(const char *cg
)
2053 if (!cgfs_get_value("cpuset", cg
, "cpuset.cpus", &answer
))
2058 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
2060 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
2064 if (sscanf(line
, "processor : %d", &cpu
) != 1)
2066 return cpu_in_cpuset(cpu
, cpuset
);
2070 * check whether this is a '^processor" line in /proc/cpuinfo
2072 static bool is_processor_line(const char *line
)
2076 if (sscanf(line
, "processor : %d", &cpu
) == 1)
2081 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
2082 struct fuse_file_info
*fi
)
2084 struct fuse_context
*fc
= fuse_get_context();
2085 struct file_info
*d
= (struct file_info
*)fi
->fh
;
2087 char *cpuset
= NULL
;
2089 size_t linelen
= 0, total_len
= 0, rv
= 0;
2090 bool am_printing
= false;
2092 char *cache
= d
->buf
;
2093 size_t cache_size
= d
->buflen
;
2097 if (offset
> d
->size
)
2101 int left
= d
->size
- offset
;
2102 total_len
= left
> size
? size
: left
;
2103 memcpy(buf
, cache
+ offset
, total_len
);
2107 cg
= get_pid_cgroup(fc
->pid
, "cpuset");
2109 return read_file("proc/cpuinfo", buf
, size
, d
);
2111 cpuset
= get_cpuset(cg
);
2115 f
= fopen("/proc/cpuinfo", "r");
2119 while (getline(&line
, &linelen
, f
) != -1) {
2121 if (is_processor_line(line
)) {
2122 am_printing
= cpuline_in_cpuset(line
, cpuset
);
2125 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
2127 perror("Error writing to cache");
2131 if (l
>= cache_size
) {
2132 fprintf(stderr
, "Internal error: truncated write to cache\n");
2136 if (l
< cache_size
){
2141 cache
+= cache_size
;
2142 total_len
+= cache_size
;
2150 l
= snprintf(cache
, cache_size
, "%s", line
);
2152 perror("Error writing to cache");
2156 if (l
>= cache_size
) {
2157 fprintf(stderr
, "Internal error: truncated write to cache\n");
2161 if (l
< cache_size
) {
2166 cache
+= cache_size
;
2167 total_len
+= cache_size
;
2175 d
->size
= total_len
;
2176 if (total_len
> size
) total_len
= size
;
2178 /* read from off 0 */
2179 memcpy(buf
, d
->buf
, total_len
);
2190 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
2191 struct fuse_file_info
*fi
)
2193 struct fuse_context
*fc
= fuse_get_context();
2194 struct file_info
*d
= (struct file_info
*)fi
->fh
;
2196 char *cpuset
= NULL
;
2198 size_t linelen
= 0, total_len
= 0, rv
= 0;
2199 int curcpu
= -1; /* cpu numbering starts at 0 */
2200 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0;
2201 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0, iowait_sum
= 0,
2202 irq_sum
= 0, softirq_sum
= 0, steal_sum
= 0, guest_sum
= 0;
2203 #define CPUALL_MAX_SIZE BUF_RESERVE_SIZE
2204 char cpuall
[CPUALL_MAX_SIZE
];
2205 /* reserve for cpu all */
2206 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
2207 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
2211 if (offset
> d
->size
)
2215 int left
= d
->size
- offset
;
2216 total_len
= left
> size
? size
: left
;
2217 memcpy(buf
, d
->buf
+ offset
, total_len
);
2221 cg
= get_pid_cgroup(fc
->pid
, "cpuset");
2223 return read_file("/proc/stat", buf
, size
, d
);
2225 cpuset
= get_cpuset(cg
);
2229 f
= fopen("/proc/stat", "r");
2234 if (getline(&line
, &linelen
, f
) < 0) {
2235 fprintf(stderr
, "proc_stat_read read first line failed\n");
2239 while (getline(&line
, &linelen
, f
) != -1) {
2242 char cpu_char
[10]; /* That's a lot of cores */
2245 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
2246 /* not a ^cpuN line containing a number N, just print it */
2247 l
= snprintf(cache
, cache_size
, "%s", line
);
2249 perror("Error writing to cache");
2253 if (l
>= cache_size
) {
2254 fprintf(stderr
, "Internal error: truncated write to cache\n");
2258 if (l
< cache_size
) {
2264 //no more space, break it
2265 cache
+= cache_size
;
2266 total_len
+= cache_size
;
2272 if (sscanf(cpu_char
, "%d", &cpu
) != 1)
2274 if (!cpu_in_cpuset(cpu
, cpuset
))
2278 c
= strchr(line
, ' ');
2281 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
2283 perror("Error writing to cache");
2288 if (l
>= cache_size
) {
2289 fprintf(stderr
, "Internal error: truncated write to cache\n");
2298 if (sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu", &user
, &nice
, &system
, &idle
, &iowait
, &irq
,
2299 &softirq
, &steal
, &guest
) != 9)
2303 system_sum
+= system
;
2305 iowait_sum
+= iowait
;
2307 softirq_sum
+= softirq
;
2314 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
2315 "cpu ", user_sum
, nice_sum
, system_sum
, idle_sum
, iowait_sum
, irq_sum
, softirq_sum
, steal_sum
, guest_sum
);
2316 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
){
2317 memcpy(cache
, cpuall
, cpuall_len
);
2318 cache
+= cpuall_len
;
2320 /* shouldn't happen */
2321 fprintf(stderr
, "proc_stat_read copy cpuall failed, cpuall_len=%d\n", cpuall_len
);
2325 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
2326 total_len
+= cpuall_len
;
2328 d
->size
= total_len
;
2329 if (total_len
> size
) total_len
= size
;
2331 memcpy(buf
, d
->buf
, total_len
);
2343 static long int getreaperage(pid_t pid
)
2350 qpid
= get_init_pid_for_task(pid
);
2354 ret
= snprintf(fnam
, 100, "/proc/%d", qpid
);
2355 if (ret
< 0 || ret
>= 100)
2358 if (lstat(fnam
, &sb
) < 0)
2361 return time(NULL
) - sb
.st_ctime
;
2365 * fork a task which switches to @task's namespace and writes '1'.
2366 * over a unix sock so we can read the task's reaper's pid in our
2369 void write_task_init_pid_exit(int sock
, pid_t target
)
2377 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
2378 if (ret
< 0 || ret
>= sizeof(fnam
))
2381 fd
= open(fnam
, O_RDONLY
);
2383 perror("write_task_init_pid_exit open of ns/pid");
2387 perror("write_task_init_pid_exit setns 1");
2399 /* we are the child */
2404 send_creds(sock
, &cred
, v
, true);
2408 static pid_t
get_init_pid_for_task(pid_t task
)
2416 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2417 perror("socketpair");
2426 write_task_init_pid_exit(sock
[0], task
);
2429 if (!recv_creds(sock
[1], &cred
, &v
))
2440 static unsigned long get_reaper_busy(pid_t task
)
2442 pid_t init
= get_init_pid_for_task(task
);
2443 char *cgroup
= NULL
, *usage_str
= NULL
;
2444 unsigned long usage
= 0;
2449 cgroup
= get_pid_cgroup(init
, "cpuacct");
2452 if (!cgfs_get_value("cpuacct", cgroup
, "cpuacct.usage", &usage_str
))
2454 usage
= strtoul(usage_str
, NULL
, 10);
2455 usage
/= 1000000000;
2464 * We read /proc/uptime and reuse its second field.
2465 * For the first field, we use the mtime for the reaper for
2466 * the calling pid as returned by getreaperage
2468 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
2469 struct fuse_file_info
*fi
)
2471 struct fuse_context
*fc
= fuse_get_context();
2472 struct file_info
*d
= (struct file_info
*)fi
->fh
;
2473 long int reaperage
= getreaperage(fc
->pid
);
2474 unsigned long int busytime
= get_reaper_busy(fc
->pid
), idletime
;
2475 char *cache
= d
->buf
;
2476 size_t total_len
= 0;
2479 if (offset
> d
->size
)
2483 int left
= d
->size
- offset
;
2484 total_len
= left
> size
? size
: left
;
2485 memcpy(buf
, cache
+ offset
, total_len
);
2489 idletime
= reaperage
- busytime
;
2490 if (idletime
> reaperage
)
2491 idletime
= reaperage
;
2493 total_len
= snprintf(d
->buf
, d
->size
, "%ld.0 %lu.0\n", reaperage
, idletime
);
2495 perror("Error writing to cache");
2499 d
->size
= (int)total_len
;
2502 if (total_len
> size
) total_len
= size
;
2504 memcpy(buf
, d
->buf
, total_len
);
2508 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
2509 struct fuse_file_info
*fi
)
2512 struct fuse_context
*fc
= fuse_get_context();
2513 struct file_info
*d
= (struct file_info
*)fi
->fh
;
2515 char *io_serviced_str
= NULL
, *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
2516 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
;
2517 unsigned long read
= 0, write
= 0;
2518 unsigned long read_merged
= 0, write_merged
= 0;
2519 unsigned long read_sectors
= 0, write_sectors
= 0;
2520 unsigned long read_ticks
= 0, write_ticks
= 0;
2521 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
2522 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
2523 char *cache
= d
->buf
;
2524 size_t cache_size
= d
->buflen
;
2526 size_t linelen
= 0, total_len
= 0, rv
= 0;
2527 unsigned int major
= 0, minor
= 0;
2532 if (offset
> d
->size
)
2536 int left
= d
->size
- offset
;
2537 total_len
= left
> size
? size
: left
;
2538 memcpy(buf
, cache
+ offset
, total_len
);
2542 cg
= get_pid_cgroup(fc
->pid
, "blkio");
2544 return read_file("/proc/diskstats", buf
, size
, d
);
2546 if (!cgfs_get_value("blkio", cg
, "blkio.io_serviced", &io_serviced_str
))
2548 if (!cgfs_get_value("blkio", cg
, "blkio.io_merged", &io_merged_str
))
2550 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_bytes", &io_service_bytes_str
))
2552 if (!cgfs_get_value("blkio", cg
, "blkio.io_wait_time", &io_wait_time_str
))
2554 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_time", &io_service_time_str
))
2558 f
= fopen("/proc/diskstats", "r");
2562 while (getline(&line
, &linelen
, f
) != -1) {
2564 char *printme
, lbuf
[256];
2566 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
2568 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
2569 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
2570 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
2571 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
2572 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
2573 read_sectors
= read_sectors
/512;
2574 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
2575 write_sectors
= write_sectors
/512;
2577 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
2578 rd_svctm
= rd_svctm
/1000000;
2579 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
2580 rd_wait
= rd_wait
/1000000;
2581 read_ticks
= rd_svctm
+ rd_wait
;
2583 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
2584 wr_svctm
= wr_svctm
/1000000;
2585 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
2586 wr_wait
= wr_wait
/1000000;
2587 write_ticks
= wr_svctm
+ wr_wait
;
2589 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
2590 tot_ticks
= tot_ticks
/1000000;
2595 memset(lbuf
, 0, 256);
2596 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
) {
2597 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
2598 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
2599 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
2604 l
= snprintf(cache
, cache_size
, "%s", printme
);
2606 perror("Error writing to fuse buf");
2610 if (l
>= cache_size
) {
2611 fprintf(stderr
, "Internal error: truncated write to cache\n");
2621 d
->size
= total_len
;
2622 if (total_len
> size
) total_len
= size
;
2623 memcpy(buf
, d
->buf
, total_len
);
2631 free(io_serviced_str
);
2632 free(io_merged_str
);
2633 free(io_service_bytes_str
);
2634 free(io_wait_time_str
);
2635 free(io_service_time_str
);
2639 static off_t
get_procfile_size(const char *which
)
2641 FILE *f
= fopen(which
, "r");
2644 ssize_t sz
, answer
= 0;
2648 while ((sz
= getline(&line
, &len
, f
)) != -1)
2656 static int proc_getattr(const char *path
, struct stat
*sb
)
2658 struct timespec now
;
2660 memset(sb
, 0, sizeof(struct stat
));
2661 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
2663 sb
->st_uid
= sb
->st_gid
= 0;
2664 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
2665 if (strcmp(path
, "/proc") == 0) {
2666 sb
->st_mode
= S_IFDIR
| 00555;
2670 if (strcmp(path
, "/proc/meminfo") == 0 ||
2671 strcmp(path
, "/proc/cpuinfo") == 0 ||
2672 strcmp(path
, "/proc/uptime") == 0 ||
2673 strcmp(path
, "/proc/stat") == 0 ||
2674 strcmp(path
, "/proc/diskstats") == 0) {
2676 sb
->st_mode
= S_IFREG
| 00444;
2684 static int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
2685 struct fuse_file_info
*fi
)
2687 if (filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
2688 filler(buf
, "meminfo", NULL
, 0) != 0 ||
2689 filler(buf
, "stat", NULL
, 0) != 0 ||
2690 filler(buf
, "uptime", NULL
, 0) != 0 ||
2691 filler(buf
, "diskstats", NULL
, 0) != 0)
2696 static int proc_open(const char *path
, struct fuse_file_info
*fi
)
2699 struct file_info
*info
;
2701 if (strcmp(path
, "/proc/meminfo") == 0)
2702 type
= LXC_TYPE_PROC_MEMINFO
;
2703 else if (strcmp(path
, "/proc/cpuinfo") == 0)
2704 type
= LXC_TYPE_PROC_CPUINFO
;
2705 else if (strcmp(path
, "/proc/uptime") == 0)
2706 type
= LXC_TYPE_PROC_UPTIME
;
2707 else if (strcmp(path
, "/proc/stat") == 0)
2708 type
= LXC_TYPE_PROC_STAT
;
2709 else if (strcmp(path
, "/proc/diskstats") == 0)
2710 type
= LXC_TYPE_PROC_DISKSTATS
;
2714 info
= malloc(sizeof(*info
));
2718 memset(info
, 0, sizeof(*info
));
2721 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
2723 info
->buf
= malloc(info
->buflen
);
2724 } while (!info
->buf
);
2725 memset(info
->buf
, 0, info
->buflen
);
2726 /* set actual size to buffer size */
2727 info
->size
= info
->buflen
;
2729 fi
->fh
= (unsigned long)info
;
2733 static int proc_release(const char *path
, struct fuse_file_info
*fi
)
2735 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2737 do_release_file_info(f
);
2741 static int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2742 struct fuse_file_info
*fi
)
2744 struct file_info
*f
= (struct file_info
*) fi
->fh
;
2747 case LXC_TYPE_PROC_MEMINFO
:
2748 return proc_meminfo_read(buf
, size
, offset
, fi
);
2749 case LXC_TYPE_PROC_CPUINFO
:
2750 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
2751 case LXC_TYPE_PROC_UPTIME
:
2752 return proc_uptime_read(buf
, size
, offset
, fi
);
2753 case LXC_TYPE_PROC_STAT
:
2754 return proc_stat_read(buf
, size
, offset
, fi
);
2755 case LXC_TYPE_PROC_DISKSTATS
:
2756 return proc_diskstats_read(buf
, size
, offset
, fi
);
2764 * these just delegate to the /proc and /cgroup ops as
2768 static int lxcfs_getattr(const char *path
, struct stat
*sb
)
2770 if (strcmp(path
, "/") == 0) {
2771 sb
->st_mode
= S_IFDIR
| 00755;
2775 if (strncmp(path
, "/cgroup", 7) == 0) {
2776 return cg_getattr(path
, sb
);
2778 if (strncmp(path
, "/proc", 5) == 0) {
2779 return proc_getattr(path
, sb
);
2784 static int lxcfs_opendir(const char *path
, struct fuse_file_info
*fi
)
2786 if (strcmp(path
, "/") == 0)
2789 if (strncmp(path
, "/cgroup", 7) == 0) {
2790 return cg_opendir(path
, fi
);
2792 if (strcmp(path
, "/proc") == 0)
2797 static int lxcfs_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
2798 struct fuse_file_info
*fi
)
2800 if (strcmp(path
, "/") == 0) {
2801 if (filler(buf
, "proc", NULL
, 0) != 0 ||
2802 filler(buf
, "cgroup", NULL
, 0) != 0)
2806 if (strncmp(path
, "/cgroup", 7) == 0)
2807 return cg_readdir(path
, buf
, filler
, offset
, fi
);
2808 if (strcmp(path
, "/proc") == 0)
2809 return proc_readdir(path
, buf
, filler
, offset
, fi
);
2813 static int lxcfs_releasedir(const char *path
, struct fuse_file_info
*fi
)
2815 if (strcmp(path
, "/") == 0)
2817 if (strncmp(path
, "/cgroup", 7) == 0) {
2818 return cg_releasedir(path
, fi
);
2820 if (strcmp(path
, "/proc") == 0)
2825 static int lxcfs_open(const char *path
, struct fuse_file_info
*fi
)
2827 if (strncmp(path
, "/cgroup", 7) == 0)
2828 return cg_open(path
, fi
);
2829 if (strncmp(path
, "/proc", 5) == 0)
2830 return proc_open(path
, fi
);
2835 static int lxcfs_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2836 struct fuse_file_info
*fi
)
2838 if (strncmp(path
, "/cgroup", 7) == 0)
2839 return cg_read(path
, buf
, size
, offset
, fi
);
2840 if (strncmp(path
, "/proc", 5) == 0)
2841 return proc_read(path
, buf
, size
, offset
, fi
);
2846 int lxcfs_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
2847 struct fuse_file_info
*fi
)
2849 if (strncmp(path
, "/cgroup", 7) == 0) {
2850 return cg_write(path
, buf
, size
, offset
, fi
);
2856 static int lxcfs_flush(const char *path
, struct fuse_file_info
*fi
)
2861 static int lxcfs_release(const char *path
, struct fuse_file_info
*fi
)
2863 if (strncmp(path
, "/cgroup", 7) == 0)
2864 return cg_release(path
, fi
);
2865 if (strncmp(path
, "/proc", 5) == 0)
2866 return proc_release(path
, fi
);
2871 static int lxcfs_fsync(const char *path
, int datasync
, struct fuse_file_info
*fi
)
2876 int lxcfs_mkdir(const char *path
, mode_t mode
)
2878 if (strncmp(path
, "/cgroup", 7) == 0)
2879 return cg_mkdir(path
, mode
);
2884 int lxcfs_chown(const char *path
, uid_t uid
, gid_t gid
)
2886 if (strncmp(path
, "/cgroup", 7) == 0)
2887 return cg_chown(path
, uid
, gid
);
2893 * cat first does a truncate before doing ops->write. This doesn't
2894 * really make sense for cgroups. So just return 0 always but do
2897 int lxcfs_truncate(const char *path
, off_t newsize
)
2899 if (strncmp(path
, "/cgroup", 7) == 0)
2904 int lxcfs_rmdir(const char *path
)
2906 if (strncmp(path
, "/cgroup", 7) == 0)
2907 return cg_rmdir(path
);
2911 int lxcfs_chmod(const char *path
, mode_t mode
)
2913 if (strncmp(path
, "/cgroup", 7) == 0)
2914 return cg_chmod(path
, mode
);
2918 const struct fuse_operations lxcfs_ops
= {
2919 .getattr
= lxcfs_getattr
,
2923 .mkdir
= lxcfs_mkdir
,
2925 .rmdir
= lxcfs_rmdir
,
2929 .chmod
= lxcfs_chmod
,
2930 .chown
= lxcfs_chown
,
2931 .truncate
= lxcfs_truncate
,
2936 .release
= lxcfs_release
,
2937 .write
= lxcfs_write
,
2940 .flush
= lxcfs_flush
,
2941 .fsync
= lxcfs_fsync
,
2946 .removexattr
= NULL
,
2948 .opendir
= lxcfs_opendir
,
2949 .readdir
= lxcfs_readdir
,
2950 .releasedir
= lxcfs_releasedir
,
2961 static void usage(const char *me
)
2963 fprintf(stderr
, "Usage:\n");
2964 fprintf(stderr
, "\n");
2965 fprintf(stderr
, "%s mountpoint\n", me
);
2966 fprintf(stderr
, "%s -h\n", me
);
2970 static bool is_help(char *w
)
2972 if (strcmp(w
, "-h") == 0 ||
2973 strcmp(w
, "--help") == 0 ||
2974 strcmp(w
, "-help") == 0 ||
2975 strcmp(w
, "help") == 0)
2980 void swallow_arg(int *argcp
, char *argv
[], char *which
)
2984 for (i
= 1; argv
[i
]; i
++) {
2985 if (strcmp(argv
[i
], which
) != 0)
2987 for (; argv
[i
]; i
++) {
2988 argv
[i
] = argv
[i
+1];
2995 void swallow_option(int *argcp
, char *argv
[], char *opt
, char *v
)
2999 for (i
= 1; argv
[i
]; i
++) {
3002 if (strcmp(argv
[i
], opt
) != 0)
3004 if (strcmp(argv
[i
+1], v
) != 0) {
3005 fprintf(stderr
, "Warning: unexpected fuse option %s\n", v
);
3008 for (; argv
[i
+1]; i
++) {
3009 argv
[i
] = argv
[i
+2];
3016 int main(int argc
, char *argv
[])
3020 * what we pass to fuse_main is:
3021 * argv[0] -s -f -o allow_other,directio argv[1] NULL
3023 int nargs
= 5, cnt
= 0;
3027 /* for travis which runs on 12.04 */
3028 if (glib_check_version (2, 36, 0) != NULL
)
3032 /* accomodate older init scripts */
3033 swallow_arg(&argc
, argv
, "-s");
3034 swallow_arg(&argc
, argv
, "-f");
3035 swallow_option(&argc
, argv
, "-o", "allow_other");
3037 if (argc
== 2 && strcmp(argv
[1], "--version") == 0) {
3038 fprintf(stderr
, "%s\n", VERSION
);
3041 if (argc
!= 2 || is_help(argv
[1]))
3044 newargv
[cnt
++] = argv
[0];
3045 newargv
[cnt
++] = "-f";
3046 newargv
[cnt
++] = "-o";
3047 newargv
[cnt
++] = "allow_other,direct_io,entry_timeout=0.5,attr_timeout=0.5";
3048 newargv
[cnt
++] = argv
[1];
3049 newargv
[cnt
++] = NULL
;
3051 if (!cgfs_setup_controllers())
3054 ret
= fuse_main(nargs
, newargv
, &lxcfs_ops
, NULL
);