3 * Copyright © 2014,2015 Canonical, Inc
4 * Author: Serge Hallyn <serge.hallyn@ubuntu.com>
6 * See COPYING file for details.
11 * sanitize paths for '..', cgmanager's not doing that for us any more
13 * Surely there are more paths we'll need to sanitize - look back through
14 * cgmanager's sources.
17 #define FUSE_USE_VERSION 26
31 #include <linux/sched.h>
32 #include <sys/socket.h>
33 #include <sys/mount.h>
37 #define GLIB_DISABLE_DEPRECATION_WARNINGS
38 #include <glib-object.h>
42 #include "config.h" // for VERSION
47 LXC_TYPE_PROC_MEMINFO
,
48 LXC_TYPE_PROC_CPUINFO
,
51 LXC_TYPE_PROC_DISKSTATS
,
59 char *buf
; // unused as of yet
61 int size
; //actual data size
65 /* reserve buffer size, for cpuall in /proc/stat */
66 #define BUF_RESERVE_SIZE 256
70 * src: a pointer to a char* in which ot append the pid.
71 * sz: the number of characters printed so far, minus trailing \0.
72 * asz: the allocated size so far
73 * pid: the pid to append
75 static void must_strcat_pid(char **src
, size_t *sz
, size_t *asz
, pid_t pid
)
80 sprintf(tmp
, "%d\n", (int)pid
);
84 d
= malloc(BUF_RESERVE_SIZE
);
87 *asz
= BUF_RESERVE_SIZE
;
88 } else if (strlen(tmp
) + sz
+ 1 >= asz
) {
90 d
= realloc(d
, *asz
+ BUF_RESERVE_SIZE
);
93 *asz
+= BUF_RESERVE_SIZE
;
95 memcpy(d
+*sz
, tmp
, strlen(tmp
));
100 static int wait_for_pid(pid_t pid
)
105 ret
= waitpid(pid
, &status
, 0);
113 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
119 * Given a open file * to /proc/pid/{u,g}id_map, and an id
120 * valid in the caller's namespace, return the id mapped into
122 * Returns the mapped id, or -1 on error.
125 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
127 unsigned int nsuid
, // base id for a range in the idfile's namespace
128 hostuid
, // base id for a range in the caller's namespace
129 count
; // number of ids in this range
133 fseek(idfile
, 0L, SEEK_SET
);
134 while (fgets(line
, 400, idfile
)) {
135 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
138 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
140 * uids wrapped around - unexpected as this is a procfile,
143 fprintf(stderr
, "pid wrapparound at entry %u %u %u in %s\n",
144 nsuid
, hostuid
, count
, line
);
147 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
149 * now since hostuid <= in_id < hostuid+count, and
150 * hostuid+count and nsuid+count do not wrap around,
151 * we know that nsuid+(in_id-hostuid) which must be
152 * less that nsuid+(count) must not wrap around
154 return (in_id
- hostuid
) + nsuid
;
163 * for is_privileged_over,
164 * specify whether we require the calling uid to be root in his
167 #define NS_ROOT_REQD true
168 #define NS_ROOT_OPT false
172 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
179 if (victim
== -1 || uid
== -1)
183 * If the request is one not requiring root in the namespace,
184 * then having the same uid suffices. (i.e. uid 1000 has write
185 * access to files owned by uid 1000
187 if (!req_ns_root
&& uid
== victim
)
190 ret
= snprintf(fpath
, PROCLEN
, "/proc/%d/uid_map", pid
);
191 if (ret
< 0 || ret
>= PROCLEN
)
193 FILE *f
= fopen(fpath
, "r");
197 /* if caller's not root in his namespace, reject */
198 nsuid
= convert_id_to_ns(f
, uid
);
203 * If victim is not mapped into caller's ns, reject.
204 * XXX I'm not sure this check is needed given that fuse
205 * will be sending requests where the vfs has converted
207 nsuid
= convert_id_to_ns(f
, victim
);
218 static bool perms_include(int fmode
, mode_t req_mode
)
222 switch (req_mode
& O_ACCMODE
) {
230 r
= S_IROTH
| S_IWOTH
;
235 return ((fmode
& r
) == r
);
241 * querycg is /a/b/c/d/e
244 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
248 if (strlen(taskcg
) <= strlen(querycg
)) {
249 fprintf(stderr
, "%s: I was fed bad input\n", __func__
);
253 if (strcmp(querycg
, "/") == 0)
254 start
= strdup(taskcg
+ 1);
256 start
= strdup(taskcg
+ strlen(querycg
) + 1);
259 end
= strchr(start
, '/');
265 static void stripnewline(char *x
)
267 size_t l
= strlen(x
);
268 if (l
&& x
[l
-1] == '\n')
272 static char *get_pid_cgroup(pid_t pid
, const char *contrl
)
280 const char *h
= find_mounted_controller(contrl
);
284 ret
= snprintf(fnam
, PROCLEN
, "/proc/%d/cgroup", pid
);
285 if (ret
< 0 || ret
>= PROCLEN
)
287 if (!(f
= fopen(fnam
, "r")))
290 while (getline(&line
, &len
, f
) != -1) {
294 c1
= strchr(line
, ':');
298 c2
= strchr(c1
, ':');
302 if (strcmp(c1
, h
) != 0)
319 * check whether a fuse context may access a cgroup dir or file
321 * If file is not null, it is a cgroup file to check under cg.
322 * If file is null, then we are checking perms on cg itself.
324 * For files we can check the mode of the list_keys result.
325 * For cgroups, we must make assumptions based on the files under the
326 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
329 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
331 struct cgfs_files
*k
= NULL
;
340 k
= cgfs_get_key(contrl
, cg
, file
);
344 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
345 if (perms_include(k
->mode
>> 6, mode
)) {
350 if (fc
->gid
== k
->gid
) {
351 if (perms_include(k
->mode
>> 3, mode
)) {
356 ret
= perms_include(k
->mode
, mode
);
363 #define INITSCOPE "/init.scope"
364 static void prune_init_slice(char *cg
)
367 point
= cg
+ strlen(cg
) - strlen(INITSCOPE
);
370 if (strcmp(point
, INITSCOPE
) == 0) {
379 * If caller is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
380 * If caller is in /a, he may act on /a/b, but not on /b.
381 * if the answer is false and nextcg is not NULL, then *nextcg will point
382 * to a string containing the next cgroup directory under cg, which must be
383 * freed by the caller.
385 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
388 char *c2
= get_pid_cgroup(pid
, contrl
);
393 prune_init_slice(c2
);
396 * callers pass in '/' for root cgroup, otherwise they pass
397 * in a cgroup without leading '/'
399 linecmp
= *cg
== '/' ? c2
: c2
+1;
400 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
402 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
414 * If caller is in /a/b/c, he may see that /a exists, but not /b or /a/c.
416 static bool caller_may_see_dir(pid_t pid
, const char *contrl
, const char *cg
)
420 size_t target_len
, task_len
;
422 if (strcmp(cg
, "/") == 0)
425 c2
= get_pid_cgroup(pid
, contrl
);
428 prune_init_slice(c2
);
431 target_len
= strlen(cg
);
432 task_len
= strlen(task_cg
);
433 if (strcmp(cg
, task_cg
) == 0) {
437 if (target_len
< task_len
) {
438 /* looking up a parent dir */
439 if (strncmp(task_cg
, cg
, target_len
) == 0 && task_cg
[target_len
] == '/')
443 if (target_len
> task_len
) {
444 /* looking up a child dir */
445 if (strncmp(task_cg
, cg
, task_len
) == 0 && cg
[task_len
] == '/')
456 * given /cgroup/freezer/a/b, return "freezer".
457 * the returned char* should NOT be freed.
459 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
464 if (strlen(path
) < 9)
466 if (*(path
+7) != '/')
472 slash
= strstr(contr
, "/");
477 for (i
= 0; i
< num_hierarchies
; i
++) {
478 if (hierarchies
[i
] && strcmp(hierarchies
[i
], contr
) == 0)
479 return hierarchies
[i
];
485 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
486 * Note that the returned value may include files (keynames) etc
488 static const char *find_cgroup_in_path(const char *path
)
492 if (strlen(path
) < 9)
494 p1
= strstr(path
+8, "/");
501 * dir should be freed, file not
503 static void get_cgdir_and_path(const char *cg
, char **dir
, char **file
)
510 *file
= strrchr(cg
, '/');
515 p
= strrchr(*dir
, '/');
520 * FUSE ops for /cgroup
523 static int cg_getattr(const char *path
, struct stat
*sb
)
526 struct fuse_context
*fc
= fuse_get_context();
528 char *fpath
= NULL
, *path1
, *path2
;
529 struct cgfs_files
*k
= NULL
;
531 const char *controller
= NULL
;
538 memset(sb
, 0, sizeof(struct stat
));
540 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
543 sb
->st_uid
= sb
->st_gid
= 0;
544 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
547 if (strcmp(path
, "/cgroup") == 0) {
548 sb
->st_mode
= S_IFDIR
| 00755;
553 controller
= pick_controller_from_path(fc
, path
);
556 cgroup
= find_cgroup_in_path(path
);
558 /* this is just /cgroup/controller, return it as a dir */
559 sb
->st_mode
= S_IFDIR
| 00755;
564 get_cgdir_and_path(cgroup
, &cgdir
, &fpath
);
574 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
575 * Then check that caller's cgroup is under path if fpath is a child
576 * cgroup, or cgdir if fpath is a file */
578 if (is_child_cgroup(controller
, path1
, path2
)) {
579 if (!caller_may_see_dir(fc
->pid
, controller
, cgroup
)) {
583 if (!caller_is_in_ancestor(fc
->pid
, controller
, cgroup
, NULL
)) {
584 /* this is just /cgroup/controller, return it as a dir */
585 sb
->st_mode
= S_IFDIR
| 00555;
590 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
)) {
595 // get uid, gid, from '/tasks' file and make up a mode
596 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
597 sb
->st_mode
= S_IFDIR
| 00755;
598 k
= cgfs_get_key(controller
, cgroup
, "tasks");
600 sb
->st_uid
= sb
->st_gid
= 0;
611 if ((k
= cgfs_get_key(controller
, path1
, path2
)) != NULL
) {
612 sb
->st_mode
= S_IFREG
| k
->mode
;
618 if (!caller_is_in_ancestor(fc
->pid
, controller
, path1
, NULL
)) {
622 if (!fc_may_access(fc
, controller
, path1
, path2
, O_RDONLY
)) {
635 static int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
637 struct fuse_context
*fc
= fuse_get_context();
639 struct file_info
*dir_info
;
640 char *controller
= NULL
;
645 if (strcmp(path
, "/cgroup") == 0) {
649 // return list of keys for the controller, and list of child cgroups
650 controller
= pick_controller_from_path(fc
, path
);
654 cgroup
= find_cgroup_in_path(path
);
656 /* this is just /cgroup/controller, return its contents */
662 if (!caller_may_see_dir(fc
->pid
, controller
, cgroup
))
664 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
668 /* we'll free this at cg_releasedir */
669 dir_info
= malloc(sizeof(*dir_info
));
672 dir_info
->controller
= must_copy_string(controller
);
673 dir_info
->cgroup
= must_copy_string(cgroup
);
674 dir_info
->type
= LXC_TYPE_CGDIR
;
675 dir_info
->buf
= NULL
;
676 dir_info
->file
= NULL
;
677 dir_info
->buflen
= 0;
679 fi
->fh
= (unsigned long)dir_info
;
683 static int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
684 struct fuse_file_info
*fi
)
686 struct file_info
*d
= (struct file_info
*)fi
->fh
;
687 struct cgfs_files
**list
= NULL
;
690 struct fuse_context
*fc
= fuse_get_context();
693 if (d
->type
!= LXC_TYPE_CGDIR
) {
694 fprintf(stderr
, "Internal error: file cache info used in readdir\n");
697 if (!d
->cgroup
&& !d
->controller
) {
698 // ls /var/lib/lxcfs/cgroup - just show list of controllers
701 for (i
= 0; i
< num_hierarchies
; i
++) {
702 if (hierarchies
[i
] && filler(buf
, hierarchies
[i
], NULL
, 0) != 0) {
709 if (!cgfs_list_keys(d
->controller
, d
->cgroup
, &list
)) {
710 // not a valid cgroup
715 if (!caller_is_in_ancestor(fc
->pid
, d
->controller
, d
->cgroup
, &nextcg
)) {
718 ret
= filler(buf
, nextcg
, NULL
, 0);
729 for (i
= 0; list
[i
]; i
++) {
730 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
736 // now get the list of child cgroups
738 if (!cgfs_list_children(d
->controller
, d
->cgroup
, &clist
)) {
742 for (i
= 0; clist
[i
]; i
++) {
743 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
753 for (i
= 0; clist
[i
]; i
++)
760 static void do_release_file_info(struct file_info
*f
)
771 static int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
773 struct file_info
*d
= (struct file_info
*)fi
->fh
;
775 do_release_file_info(d
);
779 static int cg_open(const char *path
, struct fuse_file_info
*fi
)
782 char *fpath
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
783 struct cgfs_files
*k
= NULL
;
784 struct file_info
*file_info
;
785 struct fuse_context
*fc
= fuse_get_context();
791 controller
= pick_controller_from_path(fc
, path
);
794 cgroup
= find_cgroup_in_path(path
);
798 get_cgdir_and_path(cgroup
, &cgdir
, &fpath
);
807 k
= cgfs_get_key(controller
, path1
, path2
);
814 if (!caller_may_see_dir(fc
->pid
, controller
, path1
)) {
818 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
)) {
819 // should never get here
824 /* we'll free this at cg_release */
825 file_info
= malloc(sizeof(*file_info
));
830 file_info
->controller
= must_copy_string(controller
);
831 file_info
->cgroup
= must_copy_string(path1
);
832 file_info
->file
= must_copy_string(path2
);
833 file_info
->type
= LXC_TYPE_CGFILE
;
834 file_info
->buf
= NULL
;
835 file_info
->buflen
= 0;
837 fi
->fh
= (unsigned long)file_info
;
845 static int cg_release(const char *path
, struct fuse_file_info
*fi
)
847 struct file_info
*f
= (struct file_info
*)fi
->fh
;
849 do_release_file_info(f
);
853 static int msgrecv(int sockfd
, void *buf
, size_t len
)
859 FD_SET(sockfd
, &rfds
);
863 if (select(sockfd
+1, &rfds
, NULL
, NULL
, &tv
) <= 0)
865 return recv(sockfd
, buf
, len
, MSG_DONTWAIT
);
868 #define SEND_CREDS_OK 0
869 #define SEND_CREDS_NOTSK 1
870 #define SEND_CREDS_FAIL 2
871 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
)
873 struct msghdr msg
= { 0 };
875 struct cmsghdr
*cmsg
;
876 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
881 if (msgrecv(sock
, buf
, 1) != 1) {
882 fprintf(stderr
, "%s: Error getting reply from server over socketpair\n",
884 return SEND_CREDS_FAIL
;
888 msg
.msg_control
= cmsgbuf
;
889 msg
.msg_controllen
= sizeof(cmsgbuf
);
891 cmsg
= CMSG_FIRSTHDR(&msg
);
892 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
893 cmsg
->cmsg_level
= SOL_SOCKET
;
894 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
895 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
902 iov
.iov_len
= sizeof(buf
);
906 if (sendmsg(sock
, &msg
, 0) < 0) {
907 fprintf(stderr
, "%s: failed at sendmsg: %s\n", __func__
,
910 return SEND_CREDS_NOTSK
;
911 return SEND_CREDS_FAIL
;
914 return SEND_CREDS_OK
;
917 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
919 struct msghdr msg
= { 0 };
921 struct cmsghdr
*cmsg
;
922 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
935 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
936 fprintf(stderr
, "Failed to set passcred: %s\n", strerror(errno
));
940 if (write(sock
, buf
, 1) != 1) {
941 fprintf(stderr
, "Failed to start write on scm fd: %s\n", strerror(errno
));
947 msg
.msg_control
= cmsgbuf
;
948 msg
.msg_controllen
= sizeof(cmsgbuf
);
951 iov
.iov_len
= sizeof(buf
);
959 if (select(sock
+1, &rfds
, NULL
, NULL
, &tv
) <= 0) {
960 fprintf(stderr
, "Failed to select for scm_cred: %s\n",
964 ret
= recvmsg(sock
, &msg
, MSG_DONTWAIT
);
966 fprintf(stderr
, "Failed to receive scm_cred: %s\n",
971 cmsg
= CMSG_FIRSTHDR(&msg
);
973 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
974 cmsg
->cmsg_level
== SOL_SOCKET
&&
975 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
976 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
985 * pid_to_ns - reads pids from a ucred over a socket, then writes the
986 * int value back over the socket. This shifts the pid from the
987 * sender's pidns into tpid's pidns.
989 static void pid_to_ns(int sock
, pid_t tpid
)
994 while (recv_creds(sock
, &cred
, &v
)) {
997 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
1004 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
1005 * in your old pidns. Only children which you fork will be in the target
1006 * pidns. So the pid_to_ns_wrapper does the setns, then forks a child to
1007 * actually convert pids
1009 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
1011 int newnsfd
= -1, ret
, cpipe
[2];
1018 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
1019 if (ret
< 0 || ret
>= sizeof(fnam
))
1021 newnsfd
= open(fnam
, O_RDONLY
);
1024 if (setns(newnsfd
, 0) < 0)
1028 if (pipe(cpipe
) < 0)
1038 if (write(cpipe
[1], &b
, sizeof(char)) < 0) {
1039 fprintf(stderr
, "%s (child): erorr on write: %s\n",
1040 __func__
, strerror(errno
));
1043 pid_to_ns(sock
, tpid
);
1044 _exit(1); // not reached
1046 // give the child 1 second to be done forking and
1049 FD_SET(cpipe
[0], &s
);
1052 ret
= select(cpipe
[0]+1, &s
, NULL
, NULL
, &tv
);
1055 ret
= read(cpipe
[0], &v
, 1);
1056 if (ret
!= sizeof(char) || v
!= '1')
1059 if (!wait_for_pid(cpid
))
1065 * To read cgroup files with a particular pid, we will setns into the child
1066 * pidns, open a pipe, fork a child - which will be the first to really be in
1067 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
1069 static bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
1071 int sock
[2] = {-1, -1};
1072 char *tmpdata
= NULL
;
1074 pid_t qpid
, cpid
= -1;
1075 bool answer
= false;
1079 size_t sz
= 0, asz
= 0;
1082 if (!cgfs_get_value(contrl
, cg
, file
, &tmpdata
))
1086 * Now we read the pids from returned data one by one, pass
1087 * them into a child in the target namespace, read back the
1088 * translated pids, and put them into our to-return data
1091 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1092 perror("socketpair");
1101 if (!cpid
) // child - exits when done
1102 pid_to_ns_wrapper(sock
[1], tpid
);
1104 char *ptr
= tmpdata
;
1107 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
1109 ret
= send_creds(sock
[0], &cred
, v
, true);
1111 if (ret
== SEND_CREDS_NOTSK
)
1113 if (ret
== SEND_CREDS_FAIL
)
1116 // read converted results
1118 FD_SET(sock
[0], &s
);
1121 ret
= select(sock
[0]+1, &s
, NULL
, NULL
, &tv
);
1123 fprintf(stderr
, "%s: select error waiting for pid from child: %s\n",
1124 __func__
, strerror(errno
));
1127 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
1128 fprintf(stderr
, "%s: error reading pid from child: %s\n",
1129 __func__
, strerror(errno
));
1132 must_strcat_pid(d
, &sz
, &asz
, qpid
);
1134 ptr
= strchr(ptr
, '\n');
1140 cred
.pid
= getpid();
1142 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
1143 // failed to ask child to exit
1144 fprintf(stderr
, "%s: failed to ask child to exit: %s\n",
1145 __func__
, strerror(errno
));
1155 if (sock
[0] != -1) {
1162 static int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
1163 struct fuse_file_info
*fi
)
1165 struct fuse_context
*fc
= fuse_get_context();
1166 struct file_info
*f
= (struct file_info
*)fi
->fh
;
1167 struct cgfs_files
*k
= NULL
;
1172 if (f
->type
!= LXC_TYPE_CGFILE
) {
1173 fprintf(stderr
, "Internal error: directory cache info used in cg_read\n");
1186 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
1192 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_RDONLY
)) { // should never get here
1197 if (strcmp(f
->file
, "tasks") == 0 ||
1198 strcmp(f
->file
, "/tasks") == 0 ||
1199 strcmp(f
->file
, "/cgroup.procs") == 0 ||
1200 strcmp(f
->file
, "cgroup.procs") == 0)
1201 // special case - we have to translate the pids
1202 r
= do_read_pids(fc
->pid
, f
->controller
, f
->cgroup
, f
->file
, &data
);
1204 r
= cgfs_get_value(f
->controller
, f
->cgroup
, f
->file
, &data
);
1218 memcpy(buf
, data
, s
);
1219 if (s
> 0 && s
< size
&& data
[s
-1] != '\n')
1229 static void pid_from_ns(int sock
, pid_t tpid
)
1245 ret
= select(sock
+1, &s
, NULL
, NULL
, &tv
);
1247 fprintf(stderr
, "%s: bad select before read from parent: %s\n",
1248 __func__
, strerror(errno
));
1251 if ((ret
= read(sock
, &vpid
, sizeof(pid_t
))) != sizeof(pid_t
)) {
1252 fprintf(stderr
, "%s: bad read from parent: %s\n",
1253 __func__
, strerror(errno
));
1256 if (vpid
== -1) // done
1260 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
1262 cred
.pid
= getpid();
1263 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
1270 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
1272 int newnsfd
= -1, ret
, cpipe
[2];
1279 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
1280 if (ret
< 0 || ret
>= sizeof(fnam
))
1282 newnsfd
= open(fnam
, O_RDONLY
);
1285 if (setns(newnsfd
, 0) < 0)
1289 if (pipe(cpipe
) < 0)
1301 if (write(cpipe
[1], &b
, sizeof(char)) < 0) {
1302 fprintf(stderr
, "%s (child): erorr on write: %s\n",
1303 __func__
, strerror(errno
));
1306 pid_from_ns(sock
, tpid
);
1309 // give the child 1 second to be done forking and
1312 FD_SET(cpipe
[0], &s
);
1315 ret
= select(cpipe
[0]+1, &s
, NULL
, NULL
, &tv
);
1318 ret
= read(cpipe
[0], &v
, 1);
1319 if (ret
!= sizeof(char) || v
!= '1') {
1323 if (!wait_for_pid(cpid
))
1328 kill(cpid
, SIGKILL
);
1334 * Given host @uid, return the uid to which it maps in
1335 * @pid's user namespace, or -1 if none.
1337 bool hostuid_to_ns(uid_t uid
, pid_t pid
, uid_t
*answer
)
1342 sprintf(line
, "/proc/%d/uid_map", pid
);
1343 if ((f
= fopen(line
, "r")) == NULL
) {
1347 *answer
= convert_id_to_ns(f
, uid
);
1356 * get_pid_creds: get the real uid and gid of @pid from
1358 * (XXX should we use euid here?)
1360 void get_pid_creds(pid_t pid
, uid_t
*uid
, gid_t
*gid
)
1369 sprintf(line
, "/proc/%d/status", pid
);
1370 if ((f
= fopen(line
, "r")) == NULL
) {
1371 fprintf(stderr
, "Error opening %s: %s\n", line
, strerror(errno
));
1374 while (fgets(line
, 400, f
)) {
1375 if (strncmp(line
, "Uid:", 4) == 0) {
1376 if (sscanf(line
+4, "%u", &u
) != 1) {
1377 fprintf(stderr
, "bad uid line for pid %u\n", pid
);
1382 } else if (strncmp(line
, "Gid:", 4) == 0) {
1383 if (sscanf(line
+4, "%u", &g
) != 1) {
1384 fprintf(stderr
, "bad gid line for pid %u\n", pid
);
1395 * May the requestor @r move victim @v to a new cgroup?
1396 * This is allowed if
1397 * . they are the same task
1398 * . they are ownedy by the same uid
1399 * . @r is root on the host, or
1400 * . @v's uid is mapped into @r's where @r is root.
1402 bool may_move_pid(pid_t r
, uid_t r_uid
, pid_t v
)
1404 uid_t v_uid
, tmpuid
;
1411 get_pid_creds(v
, &v_uid
, &v_gid
);
1414 if (hostuid_to_ns(r_uid
, r
, &tmpuid
) && tmpuid
== 0
1415 && hostuid_to_ns(v_uid
, r
, &tmpuid
))
1420 static bool do_write_pids(pid_t tpid
, uid_t tuid
, const char *contrl
, const char *cg
,
1421 const char *file
, const char *buf
)
1423 int sock
[2] = {-1, -1};
1424 pid_t qpid
, cpid
= -1;
1425 FILE *pids_file
= NULL
;
1426 bool answer
= false, fail
= false;
1428 pids_file
= open_pids_file(contrl
, cg
);
1433 * write the pids to a socket, have helper in writer's pidns
1434 * call movepid for us
1436 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1437 perror("socketpair");
1445 if (!cpid
) { // child
1447 pid_from_ns_wrapper(sock
[1], tpid
);
1450 const char *ptr
= buf
;
1451 while (sscanf(ptr
, "%d", &qpid
) == 1) {
1455 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
1456 fprintf(stderr
, "%s: error writing pid to child: %s\n",
1457 __func__
, strerror(errno
));
1461 if (recv_creds(sock
[0], &cred
, &v
)) {
1463 if (!may_move_pid(tpid
, tuid
, cred
.pid
)) {
1467 if (fprintf(pids_file
, "%d", (int) cred
.pid
) < 0)
1472 ptr
= strchr(ptr
, '\n');
1478 /* All good, write the value */
1480 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
1481 fprintf(stderr
, "Warning: failed to ask child to exit\n");
1489 if (sock
[0] != -1) {
1494 if (fclose(pids_file
) != 0)
1500 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
1501 struct fuse_file_info
*fi
)
1503 struct fuse_context
*fc
= fuse_get_context();
1504 char *localbuf
= NULL
;
1505 struct cgfs_files
*k
= NULL
;
1506 struct file_info
*f
= (struct file_info
*)fi
->fh
;
1509 if (f
->type
!= LXC_TYPE_CGFILE
) {
1510 fprintf(stderr
, "Internal error: directory cache info used in cg_write\n");
1520 localbuf
= alloca(size
+1);
1521 localbuf
[size
] = '\0';
1522 memcpy(localbuf
, buf
, size
);
1524 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
1529 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_WRONLY
)) {
1534 if (strcmp(f
->file
, "tasks") == 0 ||
1535 strcmp(f
->file
, "/tasks") == 0 ||
1536 strcmp(f
->file
, "/cgroup.procs") == 0 ||
1537 strcmp(f
->file
, "cgroup.procs") == 0)
1538 // special case - we have to translate the pids
1539 r
= do_write_pids(fc
->pid
, fc
->uid
, f
->controller
, f
->cgroup
, f
->file
, localbuf
);
1541 r
= cgfs_set_value(f
->controller
, f
->cgroup
, f
->file
, localbuf
);
1551 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
1553 struct fuse_context
*fc
= fuse_get_context();
1554 char *cgdir
= NULL
, *fpath
= NULL
, *path1
, *path2
, *controller
;
1555 struct cgfs_files
*k
= NULL
;
1562 if (strcmp(path
, "/cgroup") == 0)
1565 controller
= pick_controller_from_path(fc
, path
);
1568 cgroup
= find_cgroup_in_path(path
);
1570 /* this is just /cgroup/controller */
1573 get_cgdir_and_path(cgroup
, &cgdir
, &fpath
);
1583 if (is_child_cgroup(controller
, path1
, path2
)) {
1584 // get uid, gid, from '/tasks' file and make up a mode
1585 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1586 k
= cgfs_get_key(controller
, cgroup
, "tasks");
1589 k
= cgfs_get_key(controller
, path1
, path2
);
1597 * This being a fuse request, the uid and gid must be valid
1598 * in the caller's namespace. So we can just check to make
1599 * sure that the caller is root in his uid, and privileged
1600 * over the file's current owner.
1602 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
)) {
1607 ret
= cgfs_chown_file(controller
, cgroup
, uid
, gid
);
1616 int cg_chmod(const char *path
, mode_t mode
)
1618 struct fuse_context
*fc
= fuse_get_context();
1619 char * cgdir
= NULL
, *fpath
= NULL
, *path1
, *path2
, *controller
;
1620 struct cgfs_files
*k
= NULL
;
1627 if (strcmp(path
, "/cgroup") == 0)
1630 controller
= pick_controller_from_path(fc
, path
);
1633 cgroup
= find_cgroup_in_path(path
);
1635 /* this is just /cgroup/controller */
1638 get_cgdir_and_path(cgroup
, &cgdir
, &fpath
);
1648 if (is_child_cgroup(controller
, path1
, path2
)) {
1649 // get uid, gid, from '/tasks' file and make up a mode
1650 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1651 k
= cgfs_get_key(controller
, cgroup
, "tasks");
1654 k
= cgfs_get_key(controller
, path1
, path2
);
1662 * This being a fuse request, the uid and gid must be valid
1663 * in the caller's namespace. So we can just check to make
1664 * sure that the caller is root in his uid, and privileged
1665 * over the file's current owner.
1667 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
1672 if (!cgfs_chmod_file(controller
, cgroup
, mode
)) {
1684 int cg_mkdir(const char *path
, mode_t mode
)
1686 struct fuse_context
*fc
= fuse_get_context();
1687 char *fpath
= NULL
, *path1
, *cgdir
= NULL
, *controller
, *next
= NULL
;
1695 controller
= pick_controller_from_path(fc
, path
);
1699 cgroup
= find_cgroup_in_path(path
);
1703 get_cgdir_and_path(cgroup
, &cgdir
, &fpath
);
1709 if (!caller_is_in_ancestor(fc
->pid
, controller
, path1
, &next
)) {
1710 if (fpath
&& strcmp(next
, fpath
) == 0)
1717 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
)) {
1721 if (!caller_is_in_ancestor(fc
->pid
, controller
, path1
, NULL
)) {
1726 ret
= cgfs_create(controller
, cgroup
, fc
->uid
, fc
->gid
);
1734 static int cg_rmdir(const char *path
)
1736 struct fuse_context
*fc
= fuse_get_context();
1737 char *fpath
= NULL
, *cgdir
= NULL
, *controller
, *next
= NULL
;
1744 controller
= pick_controller_from_path(fc
, path
);
1748 cgroup
= find_cgroup_in_path(path
);
1752 get_cgdir_and_path(cgroup
, &cgdir
, &fpath
);
1758 if (!caller_is_in_ancestor(fc
->pid
, controller
, cgroup
, &next
)) {
1759 if (!fpath
|| strcmp(next
, fpath
) == 0)
1766 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
)) {
1770 if (!caller_is_in_ancestor(fc
->pid
, controller
, cgroup
, NULL
)) {
1775 if (!cgfs_remove(controller
, cgroup
)) {
1788 static bool startswith(const char *line
, const char *pref
)
1790 if (strncmp(line
, pref
, strlen(pref
)) == 0)
1795 static void get_mem_cached(char *memstat
, unsigned long *v
)
1801 if (startswith(memstat
, "total_cache")) {
1802 sscanf(memstat
+ 11, "%lu", v
);
1806 eol
= strchr(memstat
, '\n');
1813 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
1819 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
1821 size_t len
= strlen(key
);
1825 if (startswith(str
, key
)) {
1826 sscanf(str
+ len
, "%lu", v
);
1829 eol
= strchr(str
, '\n');
1836 static int read_file(const char *path
, char *buf
, size_t size
,
1837 struct file_info
*d
)
1839 size_t linelen
= 0, total_len
= 0, rv
= 0;
1841 char *cache
= d
->buf
;
1842 size_t cache_size
= d
->buflen
;
1843 FILE *f
= fopen(path
, "r");
1847 while (getline(&line
, &linelen
, f
) != -1) {
1848 size_t l
= snprintf(cache
, cache_size
, "%s", line
);
1850 perror("Error writing to cache");
1854 if (l
>= cache_size
) {
1855 fprintf(stderr
, "Internal error: truncated write to cache\n");
1859 if (l
< cache_size
) {
1864 cache
+= cache_size
;
1865 total_len
+= cache_size
;
1871 d
->size
= total_len
;
1872 if (total_len
> size
) total_len
= size
;
1874 /* read from off 0 */
1875 memcpy(buf
, d
->buf
, total_len
);
1884 * FUSE ops for /proc
1887 static unsigned long get_memlimit(const char *cgroup
)
1889 char *memlimit_str
= NULL
;
1890 unsigned long memlimit
= -1;
1892 if (cgfs_get_value("memory", cgroup
, "memory.limit_in_bytes", &memlimit_str
))
1893 memlimit
= strtoul(memlimit_str
, NULL
, 10);
1900 static unsigned long get_min_memlimit(const char *cgroup
)
1902 char *copy
= strdupa(cgroup
);
1903 unsigned long memlimit
= 0, retlimit
;
1905 retlimit
= get_memlimit(copy
);
1907 while (strcmp(copy
, "/") != 0) {
1908 copy
= dirname(copy
);
1909 memlimit
= get_memlimit(copy
);
1910 if (memlimit
!= -1 && memlimit
< retlimit
)
1911 retlimit
= memlimit
;
1917 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
1918 struct fuse_file_info
*fi
)
1920 struct fuse_context
*fc
= fuse_get_context();
1921 struct file_info
*d
= (struct file_info
*)fi
->fh
;
1923 char *memusage_str
= NULL
, *memstat_str
= NULL
,
1924 *memswlimit_str
= NULL
, *memswusage_str
= NULL
;
1925 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0, memswusage
= 0,
1926 cached
= 0, hosttotal
= 0;
1928 size_t linelen
= 0, total_len
= 0, rv
= 0;
1929 char *cache
= d
->buf
;
1930 size_t cache_size
= d
->buflen
;
1934 if (offset
> d
->size
)
1938 int left
= d
->size
- offset
;
1939 total_len
= left
> size
? size
: left
;
1940 memcpy(buf
, cache
+ offset
, total_len
);
1944 cg
= get_pid_cgroup(fc
->pid
, "memory");
1946 return read_file("/proc/meminfo", buf
, size
, d
);
1948 memlimit
= get_min_memlimit(cg
);
1949 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
1951 if (!cgfs_get_value("memory", cg
, "memory.stat", &memstat_str
))
1954 memusage
= strtoul(memusage_str
, NULL
, 10);
1958 // Following values are allowed to fail, because swapaccount might be turned
1959 // off for current kernel
1960 if(cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
) &&
1961 cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
))
1963 memswlimit
= strtoul(memswlimit_str
, NULL
, 10);
1964 memswusage
= strtoul(memswusage_str
, NULL
, 10);
1967 if (memswlimit
>= memlimit
)
1969 if (memswusage_str
>= memlimit
)
1974 get_mem_cached(memstat_str
, &cached
);
1976 f
= fopen("/proc/meminfo", "r");
1980 while (getline(&line
, &linelen
, f
) != -1) {
1982 char *printme
, lbuf
[100];
1984 memset(lbuf
, 0, 100);
1985 if (startswith(line
, "MemTotal:")) {
1986 sscanf(line
+14, "%lu", &hosttotal
);
1987 if (hosttotal
< memlimit
)
1988 memlimit
= hosttotal
;
1989 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
1991 } else if (startswith(line
, "MemFree:")) {
1992 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
1994 } else if (startswith(line
, "MemAvailable:")) {
1995 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
);
1997 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0) {
1998 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
- memlimit
);
2000 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 && memswusage
> 0) {
2001 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n",
2002 (memswlimit
- memlimit
) - (memswusage
- memusage
));
2004 } else if (startswith(line
, "Buffers:")) {
2005 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
2007 } else if (startswith(line
, "Cached:")) {
2008 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
2010 } else if (startswith(line
, "SwapCached:")) {
2011 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
2016 l
= snprintf(cache
, cache_size
, "%s", printme
);
2018 perror("Error writing to cache");
2023 if (l
>= cache_size
) {
2024 fprintf(stderr
, "Internal error: truncated write to cache\n");
2035 d
->size
= total_len
;
2036 if (total_len
> size
) total_len
= size
;
2037 memcpy(buf
, d
->buf
, total_len
);
2046 free(memswlimit_str
);
2047 free(memswusage_str
);
2053 * Read the cpuset.cpus for cg
2054 * Return the answer in a newly allocated string which must be freed
2056 static char *get_cpuset(const char *cg
)
2060 if (!cgfs_get_value("cpuset", cg
, "cpuset.cpus", &answer
))
2065 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
2067 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
2071 if (sscanf(line
, "processor : %d", &cpu
) != 1)
2073 return cpu_in_cpuset(cpu
, cpuset
);
2077 * check whether this is a '^processor" line in /proc/cpuinfo
2079 static bool is_processor_line(const char *line
)
2083 if (sscanf(line
, "processor : %d", &cpu
) == 1)
2088 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
2089 struct fuse_file_info
*fi
)
2091 struct fuse_context
*fc
= fuse_get_context();
2092 struct file_info
*d
= (struct file_info
*)fi
->fh
;
2094 char *cpuset
= NULL
;
2096 size_t linelen
= 0, total_len
= 0, rv
= 0;
2097 bool am_printing
= false;
2099 char *cache
= d
->buf
;
2100 size_t cache_size
= d
->buflen
;
2104 if (offset
> d
->size
)
2108 int left
= d
->size
- offset
;
2109 total_len
= left
> size
? size
: left
;
2110 memcpy(buf
, cache
+ offset
, total_len
);
2114 cg
= get_pid_cgroup(fc
->pid
, "cpuset");
2116 return read_file("proc/cpuinfo", buf
, size
, d
);
2118 cpuset
= get_cpuset(cg
);
2122 f
= fopen("/proc/cpuinfo", "r");
2126 while (getline(&line
, &linelen
, f
) != -1) {
2128 if (is_processor_line(line
)) {
2129 am_printing
= cpuline_in_cpuset(line
, cpuset
);
2132 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
2134 perror("Error writing to cache");
2138 if (l
>= cache_size
) {
2139 fprintf(stderr
, "Internal error: truncated write to cache\n");
2143 if (l
< cache_size
){
2148 cache
+= cache_size
;
2149 total_len
+= cache_size
;
2157 l
= snprintf(cache
, cache_size
, "%s", line
);
2159 perror("Error writing to cache");
2163 if (l
>= cache_size
) {
2164 fprintf(stderr
, "Internal error: truncated write to cache\n");
2168 if (l
< cache_size
) {
2173 cache
+= cache_size
;
2174 total_len
+= cache_size
;
2182 d
->size
= total_len
;
2183 if (total_len
> size
) total_len
= size
;
2185 /* read from off 0 */
2186 memcpy(buf
, d
->buf
, total_len
);
2197 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
2198 struct fuse_file_info
*fi
)
2200 struct fuse_context
*fc
= fuse_get_context();
2201 struct file_info
*d
= (struct file_info
*)fi
->fh
;
2203 char *cpuset
= NULL
;
2205 size_t linelen
= 0, total_len
= 0, rv
= 0;
2206 int curcpu
= -1; /* cpu numbering starts at 0 */
2207 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0;
2208 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0, iowait_sum
= 0,
2209 irq_sum
= 0, softirq_sum
= 0, steal_sum
= 0, guest_sum
= 0;
2210 #define CPUALL_MAX_SIZE BUF_RESERVE_SIZE
2211 char cpuall
[CPUALL_MAX_SIZE
];
2212 /* reserve for cpu all */
2213 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
2214 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
2218 if (offset
> d
->size
)
2222 int left
= d
->size
- offset
;
2223 total_len
= left
> size
? size
: left
;
2224 memcpy(buf
, d
->buf
+ offset
, total_len
);
2228 cg
= get_pid_cgroup(fc
->pid
, "cpuset");
2230 return read_file("/proc/stat", buf
, size
, d
);
2232 cpuset
= get_cpuset(cg
);
2236 f
= fopen("/proc/stat", "r");
2241 if (getline(&line
, &linelen
, f
) < 0) {
2242 fprintf(stderr
, "proc_stat_read read first line failed\n");
2246 while (getline(&line
, &linelen
, f
) != -1) {
2249 char cpu_char
[10]; /* That's a lot of cores */
2252 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
2253 /* not a ^cpuN line containing a number N, just print it */
2254 l
= snprintf(cache
, cache_size
, "%s", line
);
2256 perror("Error writing to cache");
2260 if (l
>= cache_size
) {
2261 fprintf(stderr
, "Internal error: truncated write to cache\n");
2265 if (l
< cache_size
) {
2271 //no more space, break it
2272 cache
+= cache_size
;
2273 total_len
+= cache_size
;
2279 if (sscanf(cpu_char
, "%d", &cpu
) != 1)
2281 if (!cpu_in_cpuset(cpu
, cpuset
))
2285 c
= strchr(line
, ' ');
2288 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
2290 perror("Error writing to cache");
2295 if (l
>= cache_size
) {
2296 fprintf(stderr
, "Internal error: truncated write to cache\n");
2305 if (sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu", &user
, &nice
, &system
, &idle
, &iowait
, &irq
,
2306 &softirq
, &steal
, &guest
) != 9)
2310 system_sum
+= system
;
2312 iowait_sum
+= iowait
;
2314 softirq_sum
+= softirq
;
2321 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
2322 "cpu ", user_sum
, nice_sum
, system_sum
, idle_sum
, iowait_sum
, irq_sum
, softirq_sum
, steal_sum
, guest_sum
);
2323 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
){
2324 memcpy(cache
, cpuall
, cpuall_len
);
2325 cache
+= cpuall_len
;
2327 /* shouldn't happen */
2328 fprintf(stderr
, "proc_stat_read copy cpuall failed, cpuall_len=%d\n", cpuall_len
);
2332 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
2333 total_len
+= cpuall_len
;
2335 d
->size
= total_len
;
2336 if (total_len
> size
) total_len
= size
;
2338 memcpy(buf
, d
->buf
, total_len
);
2351 * How to guess what to present for uptime?
2352 * One thing we could do would be to take the date on the caller's
2353 * memory.usage_in_bytes file, which should equal the time of creation
2354 * of his cgroup. However, a task could be in a sub-cgroup of the
2355 * container. The same problem exists if we try to look at the ages
2356 * of processes in the caller's cgroup.
2358 * So we'll fork a task that will enter the caller's pidns, mount a
2359 * fresh procfs, get the age of /proc/1, and pass that back over a pipe.
2361 * For the second uptime #, we'll do as Stéphane had done, just copy
2362 * the number from /proc/uptime. Not sure how to best emulate 'idle'
2363 * time. Maybe someone can come up with a good algorithm and submit a
2364 * patch. Maybe something based on cpushare info?
2367 /* return age of the reaper for $pid, taken from ctime of its procdir */
2368 static long int get_pid1_time(pid_t pid
)
2371 int fd
, cpipe
[2], ret
;
2378 if (unshare(CLONE_NEWNS
))
2381 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
2382 perror("rslave mount failed");
2386 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", pid
);
2387 if (ret
< 0 || ret
>= sizeof(fnam
))
2390 fd
= open(fnam
, O_RDONLY
);
2392 perror("get_pid1_time open of ns/pid");
2396 perror("get_pid1_time setns 1");
2402 if (pipe(cpipe
) < 0)
2414 umount2("/proc", MNT_DETACH
);
2415 if (mount("proc", "/proc", "proc", 0, NULL
)) {
2416 perror("get_pid1_time mount");
2419 ret
= lstat("/proc/1", &sb
);
2421 perror("get_pid1_time lstat");
2424 long int retval
= time(NULL
) - sb
.st_ctime
;
2425 if (write(cpipe
[1], &retval
, sizeof(retval
)) < 0) {
2426 fprintf(stderr
, "%s (child): erorr on write: %s\n",
2427 __func__
, strerror(errno
));
2434 // give the child 1 second to be done forking and
2437 FD_SET(cpipe
[0], &s
);
2440 ret
= select(cpipe
[0]+1, &s
, NULL
, NULL
, &tv
);
2443 ret
= read(cpipe
[0], &v
, 1);
2444 if (ret
!= sizeof(char) || v
!= '1') {
2454 kill(cpid
, SIGKILL
);
2460 static long int getreaperage(pid_t qpid
)
2462 int pid
, mypipe
[2], ret
;
2465 long int mtime
, answer
= 0;
2473 if (!pid
) { // child
2474 mtime
= get_pid1_time(qpid
);
2475 if (write(mypipe
[1], &mtime
, sizeof(mtime
)) != sizeof(mtime
))
2476 fprintf(stderr
, "Warning: bad write from getreaperage\n");
2486 FD_SET(mypipe
[0], &s
);
2489 ret
= select(mypipe
[0]+1, &s
, NULL
, NULL
, &tv
);
2495 fprintf(stderr
, "timed out\n");
2498 if (read(mypipe
[0], &mtime
, sizeof(mtime
)) != sizeof(mtime
)) {
2511 * fork a task which switches to @task's namespace and writes '1'.
2512 * over a unix sock so we can read the task's reaper's pid in our
2515 void write_task_init_pid_exit(int sock
, pid_t target
)
2523 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
2524 if (ret
< 0 || ret
>= sizeof(fnam
))
2527 fd
= open(fnam
, O_RDONLY
);
2529 perror("write_task_init_pid_exit open of ns/pid");
2533 perror("write_task_init_pid_exit setns 1");
2545 /* we are the child */
2550 send_creds(sock
, &cred
, v
, true);
2554 static pid_t
get_task_reaper_pid(pid_t task
)
2562 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2563 perror("socketpair");
2572 write_task_init_pid_exit(sock
[0], task
);
2575 if (!recv_creds(sock
[1], &cred
, &v
))
2586 static unsigned long get_reaper_busy(pid_t task
)
2588 pid_t init
= get_task_reaper_pid(task
);
2589 char *cgroup
= NULL
, *usage_str
= NULL
;
2590 unsigned long usage
= 0;
2595 cgroup
= get_pid_cgroup(task
, "cpuacct");
2598 if (!cgfs_get_value("cpuacct", cgroup
, "cpuacct.usage", &usage_str
))
2600 usage
= strtoul(usage_str
, NULL
, 10);
2610 * We read /proc/uptime and reuse its second field.
2611 * For the first field, we use the mtime for the reaper for
2612 * the calling pid as returned by getreaperage
2614 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
2615 struct fuse_file_info
*fi
)
2617 struct fuse_context
*fc
= fuse_get_context();
2618 struct file_info
*d
= (struct file_info
*)fi
->fh
;
2619 long int reaperage
= getreaperage(fc
->pid
);
2620 unsigned long int busytime
= get_reaper_busy(fc
->pid
), idletime
;
2621 char *cache
= d
->buf
;
2622 size_t total_len
= 0;
2625 if (offset
> d
->size
)
2629 int left
= d
->size
- offset
;
2630 total_len
= left
> size
? size
: left
;
2631 memcpy(buf
, cache
+ offset
, total_len
);
2635 idletime
= reaperage
- busytime
;
2636 if (idletime
> reaperage
)
2637 idletime
= reaperage
;
2639 total_len
= snprintf(d
->buf
, d
->size
, "%ld.0 %lu.0\n", reaperage
, idletime
);
2641 perror("Error writing to cache");
2645 d
->size
= (int)total_len
;
2648 if (total_len
> size
) total_len
= size
;
2650 memcpy(buf
, d
->buf
, total_len
);
2654 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
2655 struct fuse_file_info
*fi
)
2658 struct fuse_context
*fc
= fuse_get_context();
2659 struct file_info
*d
= (struct file_info
*)fi
->fh
;
2661 char *io_serviced_str
= NULL
, *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
2662 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
;
2663 unsigned long read
= 0, write
= 0;
2664 unsigned long read_merged
= 0, write_merged
= 0;
2665 unsigned long read_sectors
= 0, write_sectors
= 0;
2666 unsigned long read_ticks
= 0, write_ticks
= 0;
2667 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
2668 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
2669 char *cache
= d
->buf
;
2670 size_t cache_size
= d
->buflen
;
2672 size_t linelen
= 0, total_len
= 0, rv
= 0;
2673 unsigned int major
= 0, minor
= 0;
2678 if (offset
> d
->size
)
2682 int left
= d
->size
- offset
;
2683 total_len
= left
> size
? size
: left
;
2684 memcpy(buf
, cache
+ offset
, total_len
);
2688 cg
= get_pid_cgroup(fc
->pid
, "blkio");
2690 return read_file("/proc/diskstats", buf
, size
, d
);
2692 if (!cgfs_get_value("blkio", cg
, "blkio.io_serviced", &io_serviced_str
))
2694 if (!cgfs_get_value("blkio", cg
, "blkio.io_merged", &io_merged_str
))
2696 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_bytes", &io_service_bytes_str
))
2698 if (!cgfs_get_value("blkio", cg
, "blkio.io_wait_time", &io_wait_time_str
))
2700 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_time", &io_service_time_str
))
2704 f
= fopen("/proc/diskstats", "r");
2708 while (getline(&line
, &linelen
, f
) != -1) {
2710 char *printme
, lbuf
[256];
2712 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
2714 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
2715 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
2716 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
2717 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
2718 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
2719 read_sectors
= read_sectors
/512;
2720 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
2721 write_sectors
= write_sectors
/512;
2723 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
2724 rd_svctm
= rd_svctm
/1000000;
2725 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
2726 rd_wait
= rd_wait
/1000000;
2727 read_ticks
= rd_svctm
+ rd_wait
;
2729 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
2730 wr_svctm
= wr_svctm
/1000000;
2731 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
2732 wr_wait
= wr_wait
/1000000;
2733 write_ticks
= wr_svctm
+ wr_wait
;
2735 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
2736 tot_ticks
= tot_ticks
/1000000;
2741 memset(lbuf
, 0, 256);
2742 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
) {
2743 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
2744 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
2745 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
2750 l
= snprintf(cache
, cache_size
, "%s", printme
);
2752 perror("Error writing to fuse buf");
2756 if (l
>= cache_size
) {
2757 fprintf(stderr
, "Internal error: truncated write to cache\n");
2767 d
->size
= total_len
;
2768 if (total_len
> size
) total_len
= size
;
2769 memcpy(buf
, d
->buf
, total_len
);
2777 free(io_serviced_str
);
2778 free(io_merged_str
);
2779 free(io_service_bytes_str
);
2780 free(io_wait_time_str
);
2781 free(io_service_time_str
);
2785 static off_t
get_procfile_size(const char *which
)
2787 FILE *f
= fopen(which
, "r");
2790 ssize_t sz
, answer
= 0;
2794 while ((sz
= getline(&line
, &len
, f
)) != -1)
2802 static int proc_getattr(const char *path
, struct stat
*sb
)
2804 struct timespec now
;
2806 memset(sb
, 0, sizeof(struct stat
));
2807 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
2809 sb
->st_uid
= sb
->st_gid
= 0;
2810 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
2811 if (strcmp(path
, "/proc") == 0) {
2812 sb
->st_mode
= S_IFDIR
| 00555;
2816 if (strcmp(path
, "/proc/meminfo") == 0 ||
2817 strcmp(path
, "/proc/cpuinfo") == 0 ||
2818 strcmp(path
, "/proc/uptime") == 0 ||
2819 strcmp(path
, "/proc/stat") == 0 ||
2820 strcmp(path
, "/proc/diskstats") == 0) {
2822 sb
->st_mode
= S_IFREG
| 00444;
2830 static int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
2831 struct fuse_file_info
*fi
)
2833 if (filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
2834 filler(buf
, "meminfo", NULL
, 0) != 0 ||
2835 filler(buf
, "stat", NULL
, 0) != 0 ||
2836 filler(buf
, "uptime", NULL
, 0) != 0 ||
2837 filler(buf
, "diskstats", NULL
, 0) != 0)
2842 static int proc_open(const char *path
, struct fuse_file_info
*fi
)
2845 struct file_info
*info
;
2847 if (strcmp(path
, "/proc/meminfo") == 0)
2848 type
= LXC_TYPE_PROC_MEMINFO
;
2849 else if (strcmp(path
, "/proc/cpuinfo") == 0)
2850 type
= LXC_TYPE_PROC_CPUINFO
;
2851 else if (strcmp(path
, "/proc/uptime") == 0)
2852 type
= LXC_TYPE_PROC_UPTIME
;
2853 else if (strcmp(path
, "/proc/stat") == 0)
2854 type
= LXC_TYPE_PROC_STAT
;
2855 else if (strcmp(path
, "/proc/diskstats") == 0)
2856 type
= LXC_TYPE_PROC_DISKSTATS
;
2860 info
= malloc(sizeof(*info
));
2864 memset(info
, 0, sizeof(*info
));
2867 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
2869 info
->buf
= malloc(info
->buflen
);
2870 } while (!info
->buf
);
2871 memset(info
->buf
, 0, info
->buflen
);
2872 /* set actual size to buffer size */
2873 info
->size
= info
->buflen
;
2875 fi
->fh
= (unsigned long)info
;
2879 static int proc_release(const char *path
, struct fuse_file_info
*fi
)
2881 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2883 do_release_file_info(f
);
2887 static int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2888 struct fuse_file_info
*fi
)
2890 struct file_info
*f
= (struct file_info
*) fi
->fh
;
2893 case LXC_TYPE_PROC_MEMINFO
:
2894 return proc_meminfo_read(buf
, size
, offset
, fi
);
2895 case LXC_TYPE_PROC_CPUINFO
:
2896 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
2897 case LXC_TYPE_PROC_UPTIME
:
2898 return proc_uptime_read(buf
, size
, offset
, fi
);
2899 case LXC_TYPE_PROC_STAT
:
2900 return proc_stat_read(buf
, size
, offset
, fi
);
2901 case LXC_TYPE_PROC_DISKSTATS
:
2902 return proc_diskstats_read(buf
, size
, offset
, fi
);
2910 * these just delegate to the /proc and /cgroup ops as
2914 static int lxcfs_getattr(const char *path
, struct stat
*sb
)
2916 if (strcmp(path
, "/") == 0) {
2917 sb
->st_mode
= S_IFDIR
| 00755;
2921 if (strncmp(path
, "/cgroup", 7) == 0) {
2922 return cg_getattr(path
, sb
);
2924 if (strncmp(path
, "/proc", 5) == 0) {
2925 return proc_getattr(path
, sb
);
2930 static int lxcfs_opendir(const char *path
, struct fuse_file_info
*fi
)
2932 if (strcmp(path
, "/") == 0)
2935 if (strncmp(path
, "/cgroup", 7) == 0) {
2936 return cg_opendir(path
, fi
);
2938 if (strcmp(path
, "/proc") == 0)
2943 static int lxcfs_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
2944 struct fuse_file_info
*fi
)
2946 if (strcmp(path
, "/") == 0) {
2947 if (filler(buf
, "proc", NULL
, 0) != 0 ||
2948 filler(buf
, "cgroup", NULL
, 0) != 0)
2952 if (strncmp(path
, "/cgroup", 7) == 0)
2953 return cg_readdir(path
, buf
, filler
, offset
, fi
);
2954 if (strcmp(path
, "/proc") == 0)
2955 return proc_readdir(path
, buf
, filler
, offset
, fi
);
2959 static int lxcfs_releasedir(const char *path
, struct fuse_file_info
*fi
)
2961 if (strcmp(path
, "/") == 0)
2963 if (strncmp(path
, "/cgroup", 7) == 0) {
2964 return cg_releasedir(path
, fi
);
2966 if (strcmp(path
, "/proc") == 0)
2971 static int lxcfs_open(const char *path
, struct fuse_file_info
*fi
)
2973 if (strncmp(path
, "/cgroup", 7) == 0)
2974 return cg_open(path
, fi
);
2975 if (strncmp(path
, "/proc", 5) == 0)
2976 return proc_open(path
, fi
);
2981 static int lxcfs_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2982 struct fuse_file_info
*fi
)
2984 if (strncmp(path
, "/cgroup", 7) == 0)
2985 return cg_read(path
, buf
, size
, offset
, fi
);
2986 if (strncmp(path
, "/proc", 5) == 0)
2987 return proc_read(path
, buf
, size
, offset
, fi
);
2992 int lxcfs_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
2993 struct fuse_file_info
*fi
)
2995 if (strncmp(path
, "/cgroup", 7) == 0) {
2996 return cg_write(path
, buf
, size
, offset
, fi
);
3002 static int lxcfs_flush(const char *path
, struct fuse_file_info
*fi
)
3007 static int lxcfs_release(const char *path
, struct fuse_file_info
*fi
)
3009 if (strncmp(path
, "/cgroup", 7) == 0)
3010 return cg_release(path
, fi
);
3011 if (strncmp(path
, "/proc", 5) == 0)
3012 return proc_release(path
, fi
);
3017 static int lxcfs_fsync(const char *path
, int datasync
, struct fuse_file_info
*fi
)
3022 int lxcfs_mkdir(const char *path
, mode_t mode
)
3024 if (strncmp(path
, "/cgroup", 7) == 0)
3025 return cg_mkdir(path
, mode
);
3030 int lxcfs_chown(const char *path
, uid_t uid
, gid_t gid
)
3032 if (strncmp(path
, "/cgroup", 7) == 0)
3033 return cg_chown(path
, uid
, gid
);
3039 * cat first does a truncate before doing ops->write. This doesn't
3040 * really make sense for cgroups. So just return 0 always but do
3043 int lxcfs_truncate(const char *path
, off_t newsize
)
3045 if (strncmp(path
, "/cgroup", 7) == 0)
3050 int lxcfs_rmdir(const char *path
)
3052 if (strncmp(path
, "/cgroup", 7) == 0)
3053 return cg_rmdir(path
);
3057 int lxcfs_chmod(const char *path
, mode_t mode
)
3059 if (strncmp(path
, "/cgroup", 7) == 0)
3060 return cg_chmod(path
, mode
);
3064 const struct fuse_operations lxcfs_ops
= {
3065 .getattr
= lxcfs_getattr
,
3069 .mkdir
= lxcfs_mkdir
,
3071 .rmdir
= lxcfs_rmdir
,
3075 .chmod
= lxcfs_chmod
,
3076 .chown
= lxcfs_chown
,
3077 .truncate
= lxcfs_truncate
,
3082 .release
= lxcfs_release
,
3083 .write
= lxcfs_write
,
3086 .flush
= lxcfs_flush
,
3087 .fsync
= lxcfs_fsync
,
3092 .removexattr
= NULL
,
3094 .opendir
= lxcfs_opendir
,
3095 .readdir
= lxcfs_readdir
,
3096 .releasedir
= lxcfs_releasedir
,
3107 static void usage(const char *me
)
3109 fprintf(stderr
, "Usage:\n");
3110 fprintf(stderr
, "\n");
3111 fprintf(stderr
, "%s mountpoint\n", me
);
3112 fprintf(stderr
, "%s -h\n", me
);
3116 static bool is_help(char *w
)
3118 if (strcmp(w
, "-h") == 0 ||
3119 strcmp(w
, "--help") == 0 ||
3120 strcmp(w
, "-help") == 0 ||
3121 strcmp(w
, "help") == 0)
3126 void swallow_arg(int *argcp
, char *argv
[], char *which
)
3130 for (i
= 1; argv
[i
]; i
++) {
3131 if (strcmp(argv
[i
], which
) != 0)
3133 for (; argv
[i
]; i
++) {
3134 argv
[i
] = argv
[i
+1];
3141 void swallow_option(int *argcp
, char *argv
[], char *opt
, char *v
)
3145 for (i
= 1; argv
[i
]; i
++) {
3148 if (strcmp(argv
[i
], opt
) != 0)
3150 if (strcmp(argv
[i
+1], v
) != 0) {
3151 fprintf(stderr
, "Warning: unexpected fuse option %s\n", v
);
3154 for (; argv
[i
+1]; i
++) {
3155 argv
[i
] = argv
[i
+2];
3162 int main(int argc
, char *argv
[])
3166 * what we pass to fuse_main is:
3167 * argv[0] -s -f -o allow_other,directio argv[1] NULL
3169 int nargs
= 5, cnt
= 0;
3173 /* for travis which runs on 12.04 */
3174 if (glib_check_version (2, 36, 0) != NULL
)
3178 /* accomodate older init scripts */
3179 swallow_arg(&argc
, argv
, "-s");
3180 swallow_arg(&argc
, argv
, "-f");
3181 swallow_option(&argc
, argv
, "-o", "allow_other");
3183 if (argc
== 2 && strcmp(argv
[1], "--version") == 0) {
3184 fprintf(stderr
, "%s\n", VERSION
);
3187 if (argc
!= 2 || is_help(argv
[1]))
3190 newargv
[cnt
++] = argv
[0];
3191 newargv
[cnt
++] = "-f";
3192 newargv
[cnt
++] = "-o";
3193 newargv
[cnt
++] = "allow_other,direct_io,entry_timeout=0.5,attr_timeout=0.5";
3194 newargv
[cnt
++] = argv
[1];
3195 newargv
[cnt
++] = NULL
;
3197 if (!cgfs_setup_controllers())
3200 ret
= fuse_main(nargs
, newargv
, &lxcfs_ops
, NULL
);