]> mj.ucw.cz Git - eval.git/blob - isolate/isolate.c
ebc11a64f86d4f9a4121d79da2640bb7d684387c
[eval.git] / isolate / isolate.c
1 /*
2  *      A Process Isolator based on Linux Containers
3  *
4  *      (c) 2012-2015 Martin Mares <mj@ucw.cz>
5  *      (c) 2012-2014 Bernard Blackham <bernard@blackham.com.au>
6  */
7
8 /***********************************************************
9  ** This is not the master version of Isolate any longer. **
10  ** See https://github.com/ioi/isolate for its new home.  **
11  ***********************************************************/
12
13 #define _GNU_SOURCE
14
15 #include "autoconf.h"
16
17 #include <errno.h>
18 #include <stdio.h>
19 #include <fcntl.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <stdarg.h>
23 #include <stdint.h>
24 #include <unistd.h>
25 #include <getopt.h>
26 #include <sched.h>
27 #include <time.h>
28 #include <ftw.h>
29 #include <grp.h>
30 #include <mntent.h>
31 #include <limits.h>
32 #include <sys/wait.h>
33 #include <sys/time.h>
34 #include <sys/signal.h>
35 #include <sys/resource.h>
36 #include <sys/mount.h>
37 #include <sys/stat.h>
38 #include <sys/quota.h>
39 #include <sys/vfs.h>
40 #include <sys/fsuid.h>
41
42 #define NONRET __attribute__((noreturn))
43 #define UNUSED __attribute__((unused))
44 #define ARRAY_SIZE(a) (int)(sizeof(a)/sizeof(a[0]))
45
46 static int timeout;                     /* milliseconds */
47 static int wall_timeout;
48 static int extra_timeout;
49 static int pass_environ;
50 static int verbose;
51 static int memory_limit;
52 static int stack_limit;
53 static int block_quota;
54 static int inode_quota;
55 static int max_processes = 1;
56 static char *redir_stdin, *redir_stdout, *redir_stderr;
57 static char *set_cwd;
58
59 static int cg_enable;
60 static int cg_memory_limit;
61 static int cg_timing;
62
63 static int box_id;
64 static char box_dir[1024];
65 static pid_t box_pid;
66
67 static uid_t box_uid;
68 static gid_t box_gid;
69 static uid_t orig_uid;
70 static gid_t orig_gid;
71
72 static int partial_line;
73 static int cleanup_ownership;
74
75 static struct timeval start_time;
76 static int ticks_per_sec;
77 static int total_ms, wall_ms;
78 static volatile sig_atomic_t timer_tick;
79
80 static int error_pipes[2];
81 static int write_errors_to_fd;
82 static int read_errors_from_fd;
83
84 static void die(char *msg, ...) NONRET;
85 static void cg_stats(void);
86 static int get_wall_time_ms(void);
87 static int get_run_time_ms(struct rusage *rus);
88
89 static void chowntree(char *path, uid_t uid, gid_t gid);
90
91 /*** Meta-files ***/
92
93 static FILE *metafile;
94
95 static void
96 meta_open(const char *name)
97 {
98   if (!strcmp(name, "-"))
99     {
100       metafile = stdout;
101       return;
102     }
103   if (setfsuid(getuid()) < 0)
104     die("Failed to switch FS UID: %m");
105   metafile = fopen(name, "w");
106   if (setfsuid(geteuid()) < 0)
107     die("Failed to switch FS UID back: %m");
108   if (!metafile)
109     die("Failed to open metafile '%s'",name);
110 }
111
112 static void
113 meta_close(void)
114 {
115   if (metafile && metafile != stdout)
116     fclose(metafile);
117 }
118
119 static void __attribute__((format(printf,1,2)))
120 meta_printf(const char *fmt, ...)
121 {
122   if (!metafile)
123     return;
124
125   va_list args;
126   va_start(args, fmt);
127   vfprintf(metafile, fmt, args);
128   va_end(args);
129 }
130
131 static void
132 final_stats(struct rusage *rus)
133 {
134   total_ms = get_run_time_ms(rus);
135   wall_ms = get_wall_time_ms();
136
137   meta_printf("time:%d.%03d\n", total_ms/1000, total_ms%1000);
138   meta_printf("time-wall:%d.%03d\n", wall_ms/1000, wall_ms%1000);
139   meta_printf("max-rss:%ld\n", rus->ru_maxrss);
140   meta_printf("csw-voluntary:%ld\n", rus->ru_nvcsw);
141   meta_printf("csw-forced:%ld\n", rus->ru_nivcsw);
142
143   cg_stats();
144 }
145
146 /*** Messages and exits ***/
147
148 static void NONRET
149 box_exit(int rc)
150 {
151   if (box_pid > 0)
152     {
153       kill(-box_pid, SIGKILL);
154       kill(box_pid, SIGKILL);
155       meta_printf("killed:1\n");
156
157       struct rusage rus;
158       int p, stat;
159       do
160         p = wait4(box_pid, &stat, 0, &rus);
161       while (p < 0 && errno == EINTR);
162       if (p < 0)
163         fprintf(stderr, "UGH: Lost track of the process (%m)\n");
164       else
165         final_stats(&rus);
166     }
167
168   if (rc < 2 && cleanup_ownership)
169     chowntree("box", orig_uid, orig_gid);
170
171   meta_close();
172   exit(rc);
173 }
174
175 static void
176 flush_line(void)
177 {
178   if (partial_line)
179     fputc('\n', stderr);
180   partial_line = 0;
181 }
182
183 /* Report an error of the sandbox itself */
184 static void NONRET __attribute__((format(printf,1,2)))
185 die(char *msg, ...)
186 {
187   va_list args;
188   va_start(args, msg);
189   char buf[1024];
190   int n = vsnprintf(buf, sizeof(buf), msg, args);
191
192   if (write_errors_to_fd)
193     {
194       // We are inside the box, have to use error pipe for error reporting.
195       // We hope that the whole error message fits in PIPE_BUF bytes.
196       write(write_errors_to_fd, buf, n);
197       exit(2);
198     }
199
200   // Otherwise, we in the box keeper process, so we report errors normally
201   flush_line();
202   meta_printf("status:XX\nmessage:%s\n", buf);
203   fputs(buf, stderr);
204   fputc('\n', stderr);
205   box_exit(2);
206 }
207
208 /* Report an error of the program inside the sandbox */
209 static void NONRET __attribute__((format(printf,1,2)))
210 err(char *msg, ...)
211 {
212   va_list args;
213   va_start(args, msg);
214   flush_line();
215   if (msg[0] && msg[1] && msg[2] == ':' && msg[3] == ' ')
216     {
217       meta_printf("status:%c%c\n", msg[0], msg[1]);
218       msg += 4;
219     }
220   char buf[1024];
221   vsnprintf(buf, sizeof(buf), msg, args);
222   meta_printf("message:%s\n", buf);
223   fputs(buf, stderr);
224   fputc('\n', stderr);
225   box_exit(1);
226 }
227
228 /* Write a message, but only if in verbose mode */
229 static void __attribute__((format(printf,1,2)))
230 msg(char *msg, ...)
231 {
232   va_list args;
233   va_start(args, msg);
234   if (verbose)
235     {
236       int len = strlen(msg);
237       if (len > 0)
238         partial_line = (msg[len-1] != '\n');
239       vfprintf(stderr, msg, args);
240       fflush(stderr);
241     }
242   va_end(args);
243 }
244
245 /*** Utility functions ***/
246
247 static void *
248 xmalloc(size_t size)
249 {
250   void *p = malloc(size);
251   if (!p)
252     die("Out of memory");
253   return p;
254 }
255
256 static char *
257 xstrdup(char *str)
258 {
259   char *p = strdup(str);
260   if (!p)
261     die("Out of memory");
262   return p;
263 }
264
265 static int dir_exists(char *path)
266 {
267   struct stat st;
268   return (stat(path, &st) >= 0 && S_ISDIR(st.st_mode));
269 }
270
271 static int rmtree_helper(const char *fpath, const struct stat *sb,
272     int typeflag UNUSED, struct FTW *ftwbuf UNUSED)
273 {
274   if (S_ISDIR(sb->st_mode))
275     {
276       if (rmdir(fpath) < 0)
277         die("Cannot rmdir %s: %m", fpath);
278     }
279   else
280     {
281       if (unlink(fpath) < 0)
282         die("Cannot unlink %s: %m", fpath);
283     }
284   return FTW_CONTINUE;
285 }
286
287 static void
288 rmtree(char *path)
289 {
290   nftw(path, rmtree_helper, 32, FTW_MOUNT | FTW_PHYS | FTW_DEPTH);
291 }
292
293 static uid_t chown_uid;
294 static gid_t chown_gid;
295
296 static int chowntree_helper(const char *fpath, const struct stat *sb UNUSED,
297     int typeflag UNUSED, struct FTW *ftwbuf UNUSED)
298 {
299   if (lchown(fpath, chown_uid, chown_gid) < 0)
300     die("Cannot chown %s: %m", fpath);
301   else
302     return FTW_CONTINUE;
303 }
304
305 static void
306 chowntree(char *path, uid_t uid, gid_t gid)
307 {
308   chown_uid = uid;
309   chown_gid = gid;
310   nftw(path, chowntree_helper, 32, FTW_MOUNT | FTW_PHYS);
311 }
312
313 /*** Environment rules ***/
314
315 struct env_rule {
316   char *var;                    // Variable to match
317   char *val;                    // ""=clear, NULL=inherit
318   int var_len;
319   struct env_rule *next;
320 };
321
322 static struct env_rule *first_env_rule;
323 static struct env_rule **last_env_rule = &first_env_rule;
324
325 static struct env_rule default_env_rules[] = {
326   { "LIBC_FATAL_STDERR_", "1" }
327 };
328
329 static int
330 set_env_action(char *a0)
331 {
332   struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
333   char *a = (char *)(r+1);
334   strcpy(a, a0);
335
336   char *sep = strchr(a, '=');
337   if (sep == a)
338     return 0;
339   r->var = a;
340   if (sep)
341     {
342       *sep++ = 0;
343       r->val = sep;
344     }
345   else
346     r->val = NULL;
347   *last_env_rule = r;
348   last_env_rule = &r->next;
349   r->next = NULL;
350   return 1;
351 }
352
353 static int
354 match_env_var(char *env_entry, struct env_rule *r)
355 {
356   if (strncmp(env_entry, r->var, r->var_len))
357     return 0;
358   return (env_entry[r->var_len] == '=');
359 }
360
361 static void
362 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
363 {
364   // First remove the variable if already set
365   int pos = 0;
366   while (pos < *env_sizep && !match_env_var(env[pos], r))
367     pos++;
368   if (pos < *env_sizep)
369     {
370       (*env_sizep)--;
371       env[pos] = env[*env_sizep];
372       env[*env_sizep] = NULL;
373     }
374
375   // What is the new value?
376   char *new;
377   if (r->val)
378     {
379       if (!r->val[0])
380         return;
381       new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
382       sprintf(new, "%s=%s", r->var, r->val);
383     }
384   else
385     {
386       pos = 0;
387       while (environ[pos] && !match_env_var(environ[pos], r))
388         pos++;
389       if (!(new = environ[pos]))
390         return;
391     }
392
393   // Add it at the end of the array
394   env[(*env_sizep)++] = new;
395   env[*env_sizep] = NULL;
396 }
397
398 static char **
399 setup_environment(void)
400 {
401   // Link built-in rules with user rules
402   for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
403     {
404       default_env_rules[i].next = first_env_rule;
405       first_env_rule = &default_env_rules[i];
406     }
407
408   // Scan the original environment
409   char **orig_env = environ;
410   int orig_size = 0;
411   while (orig_env[orig_size])
412     orig_size++;
413
414   // For each rule, reserve one more slot and calculate length
415   int num_rules = 0;
416   for (struct env_rule *r = first_env_rule; r; r=r->next)
417     {
418       num_rules++;
419       r->var_len = strlen(r->var);
420     }
421
422   // Create a new environment
423   char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
424   int size;
425   if (pass_environ)
426     {
427       memcpy(env, environ, orig_size * sizeof(char *));
428       size = orig_size;
429     }
430   else
431     size = 0;
432   env[size] = NULL;
433
434   // Apply the rules one by one
435   for (struct env_rule *r = first_env_rule; r; r=r->next)
436     apply_env_rule(env, &size, r);
437
438   // Return the new env and pass some gossip
439   if (verbose > 1)
440     {
441       fprintf(stderr, "Passing environment:\n");
442       for (int i=0; env[i]; i++)
443         fprintf(stderr, "\t%s\n", env[i]);
444     }
445   return env;
446 }
447
448 /*** Directory rules ***/
449
450 struct dir_rule {
451   char *inside;                 // A relative path
452   char *outside;                // This can be an absolute path or a relative path starting with "./"
453   unsigned int flags;           // DIR_FLAG_xxx
454   struct dir_rule *next;
455 };
456
457 enum dir_rule_flags {
458   DIR_FLAG_RW = 1,
459   DIR_FLAG_NOEXEC = 2,
460   DIR_FLAG_FS = 4,
461   DIR_FLAG_MAYBE = 8,
462   DIR_FLAG_DEV = 16,
463 };
464
465 static const char * const dir_flag_names[] = { "rw", "noexec", "fs", "maybe", "dev" };
466
467 static struct dir_rule *first_dir_rule;
468 static struct dir_rule **last_dir_rule = &first_dir_rule;
469
470 static int add_dir_rule(char *in, char *out, unsigned int flags)
471 {
472   // Make sure that "in" is relative
473   while (in[0] == '/')
474     in++;
475   if (!*in)
476     return 0;
477
478   // Check "out"
479   if (flags & DIR_FLAG_FS)
480     {
481       if (!out || out[0] == '/')
482         return 0;
483     }
484   else
485     {
486       if (out && out[0] != '/' && strncmp(out, "./", 2))
487         return 0;
488     }
489
490   // Override an existing rule
491   struct dir_rule *r;
492   for (r = first_dir_rule; r; r = r->next)
493     if (!strcmp(r->inside, in))
494       break;
495
496   // Add a new rule
497   if (!r)
498     {
499       r = xmalloc(sizeof(*r));
500       r->inside = in;
501       *last_dir_rule = r;
502       last_dir_rule = &r->next;
503       r->next = NULL;
504     }
505   r->outside = out;
506   r->flags = flags;
507   return 1;
508 }
509
510 static unsigned int parse_dir_option(char *opt)
511 {
512   for (unsigned int i = 0; i < ARRAY_SIZE(dir_flag_names); i++)
513     if (!strcmp(opt, dir_flag_names[i]))
514       return 1U << i;
515   die("Unknown directory option %s", opt);
516 }
517
518 static int set_dir_action(char *arg)
519 {
520   arg = xstrdup(arg);
521
522   char *colon = strchr(arg, ':');
523   unsigned int flags = 0;
524   while (colon)
525     {
526       *colon++ = 0;
527       char *next = strchr(colon, ':');
528       if (next)
529         *next = 0;
530       flags |= parse_dir_option(colon);
531       colon = next;
532     }
533
534   char *eq = strchr(arg, '=');
535   if (eq)
536     {
537       *eq++ = 0;
538       return add_dir_rule(arg, (*eq ? eq : NULL), flags);
539     }
540   else
541     {
542       char *out = xmalloc(1 + strlen(arg) + 1);
543       sprintf(out, "/%s", arg);
544       return add_dir_rule(arg, out, flags);
545     }
546 }
547
548 static void init_dir_rules(void)
549 {
550   set_dir_action("box=./box:rw");
551   set_dir_action("bin");
552   set_dir_action("dev:dev");
553   set_dir_action("lib");
554   set_dir_action("lib64:maybe");
555   set_dir_action("proc=proc:fs");
556   set_dir_action("usr");
557 }
558
559 static void make_dir(char *path)
560 {
561   char *sep = (path[0] == '/' ? path+1 : path);
562
563   for (;;)
564     {
565       sep = strchr(sep, '/');
566       if (sep)
567         *sep = 0;
568
569       if (!dir_exists(path) && mkdir(path, 0777) < 0)
570         die("Cannot create directory %s: %m\n", path);
571
572       if (!sep)
573         return;
574       *sep++ = '/';
575     }
576 }
577
578 static void apply_dir_rules(void)
579 {
580   for (struct dir_rule *r = first_dir_rule; r; r=r->next)
581     {
582       char *in = r->inside;
583       char *out = r->outside;
584       if (!out)
585         {
586           msg("Not binding anything on %s\n", r->inside);
587           continue;
588         }
589
590       if ((r->flags & DIR_FLAG_MAYBE) && !dir_exists(out))
591         {
592           msg("Not binding %s on %s (does not exist)\n", out, r->inside);
593           continue;
594         }
595
596       char root_in[1024];
597       snprintf(root_in, sizeof(root_in), "root/%s", in);
598       make_dir(root_in);
599
600       unsigned long mount_flags = 0;
601       if (!(r->flags & DIR_FLAG_RW))
602         mount_flags |= MS_RDONLY;
603       if (r->flags & DIR_FLAG_NOEXEC)
604         mount_flags |= MS_NOEXEC;
605       if (!(r->flags & DIR_FLAG_DEV))
606         mount_flags |= MS_NODEV;
607
608       if (r->flags & DIR_FLAG_FS)
609         {
610           msg("Mounting %s on %s (flags %lx)\n", out, in, mount_flags);
611           if (mount("none", root_in, out, mount_flags, "") < 0)
612             die("Cannot mount %s on %s: %m", out, in);
613         }
614       else
615         {
616           mount_flags |= MS_BIND | MS_NOSUID;
617           msg("Binding %s on %s (flags %lx)\n", out, in, mount_flags);
618           // Most mount flags need remount to work
619           if (mount(out, root_in, "none", mount_flags, "") < 0 ||
620               mount(out, root_in, "none", MS_REMOUNT | mount_flags, "") < 0)
621             die("Cannot mount %s on %s: %m", out, in);
622         }
623     }
624 }
625
626 /*** Control groups ***/
627
628 struct cg_controller_desc {
629   const char *name;
630   int optional;
631 };
632
633 typedef enum {
634   CG_MEMORY = 0,
635   CG_CPUACCT,
636   CG_CPUSET,
637   CG_NUM_CONTROLLERS,
638 } cg_controller;
639
640 static const struct cg_controller_desc cg_controllers[CG_NUM_CONTROLLERS+1] = {
641   [CG_MEMORY]  = { "memory",  0 },
642   [CG_CPUACCT] = { "cpuacct", 0 },
643   [CG_CPUSET]  = { "cpuset",  1 },
644   [CG_NUM_CONTROLLERS] = { NULL, 0 },
645 };
646
647 #define FOREACH_CG_CONTROLLER(_controller) \
648   for (cg_controller (_controller) = 0; \
649        (_controller) < CG_NUM_CONTROLLERS; (_controller)++)
650
651 static const char *cg_controller_name(cg_controller c)
652 {
653   return cg_controllers[c].name;
654 }
655
656 static int cg_controller_optional(cg_controller c)
657 {
658   return cg_controllers[c].optional;
659 }
660
661 static char cg_name[256];
662
663 #define CG_BUFSIZE 1024
664
665 static void
666 cg_makepath(char *buf, size_t len, cg_controller c, const char *attr)
667 {
668   const char *cg_root = CONFIG_ISOLATE_CGROUP_ROOT;
669   snprintf(buf, len, "%s/%s/%s/%s", cg_root, cg_controller_name(c), cg_name, attr);
670 }
671
672 static int
673 cg_read(cg_controller controller, const char *attr, char *buf)
674 {
675   int maybe = 0;
676   if (attr[0] == '?')
677     {
678       attr++;
679       maybe = 1;
680     }
681
682   char path[256];
683   cg_makepath(path, sizeof(path), controller, attr);
684
685   int fd = open(path, O_RDONLY);
686   if (fd < 0)
687     {
688       if (maybe)
689         return 0;
690       die("Cannot read %s: %m", path);
691     }
692
693   int n = read(fd, buf, CG_BUFSIZE);
694   if (n < 0)
695     {
696       if (maybe)
697         return 0;
698       die("Cannot read %s: %m", path);
699     }
700   if (n >= CG_BUFSIZE - 1)
701     die("Attribute %s too long", path);
702   if (n > 0 && buf[n-1] == '\n')
703     n--;
704   buf[n] = 0;
705
706   if (verbose > 1)
707     msg("CG: Read %s = %s\n", attr, buf);
708
709   close(fd);
710   return 1;
711 }
712
713 static void __attribute__((format(printf,3,4)))
714 cg_write(cg_controller controller, const char *attr, const char *fmt, ...)
715 {
716   int maybe = 0;
717   if (attr[0] == '?')
718     {
719       attr++;
720       maybe = 1;
721     }
722
723   va_list args;
724   va_start(args, fmt);
725
726   char buf[CG_BUFSIZE];
727   int n = vsnprintf(buf, sizeof(buf), fmt, args);
728   if (n >= CG_BUFSIZE)
729     die("cg_write: Value for attribute %s is too long", attr);
730
731   if (verbose > 1)
732     msg("CG: Write %s = %s", attr, buf);
733
734   char path[256];
735   cg_makepath(path, sizeof(path), controller, attr);
736
737   int fd = open(path, O_WRONLY | O_TRUNC);
738   if (fd < 0)
739     {
740       if (maybe)
741         return;
742       else
743         die("Cannot write %s: %m", path);
744     }
745
746   int written = write(fd, buf, n);
747   if (written < 0)
748     {
749       if (maybe)
750         return;
751       else
752         die("Cannot set %s to %s: %m", path, buf);
753     }
754   if (written != n)
755     die("Short write to %s (%d out of %d bytes)", path, written, n);
756
757   close(fd);
758   va_end(args);
759 }
760
761 static void
762 cg_init(void)
763 {
764   if (!cg_enable)
765     return;
766
767   char *cg_root = CONFIG_ISOLATE_CGROUP_ROOT;
768   if (!dir_exists(cg_root))
769     die("Control group filesystem at %s not mounted", cg_root);
770
771   snprintf(cg_name, sizeof(cg_name), "box-%d", box_id);
772   msg("Using control group %s\n", cg_name);
773 }
774
775 static void
776 cg_prepare(void)
777 {
778   if (!cg_enable)
779     return;
780
781   struct stat st;
782   char buf[CG_BUFSIZE];
783   char path[256];
784
785   FOREACH_CG_CONTROLLER(controller)
786     {
787       cg_makepath(path, sizeof(path), controller, "");
788       if (stat(path, &st) >= 0 || errno != ENOENT)
789         {
790           msg("Control group %s already exists, trying to empty it.\n", path);
791           if (rmdir(path) < 0)
792             die("Failed to reset control group %s: %m", path);
793         }
794
795       if (mkdir(path, 0777) < 0 && !cg_controller_optional(controller))
796         die("Failed to create control group %s: %m", path);
797     }
798
799   // If cpuset module is enabled, copy allowed cpus and memory nodes from parent group
800   if (cg_read(CG_CPUSET, "?cpuset.cpus", buf))
801     cg_write(CG_CPUSET, "cpuset.cpus", "%s", buf);
802   if (cg_read(CG_CPUSET, "?cpuset.mems", buf))
803     cg_write(CG_CPUSET, "cpuset.mems", "%s", buf);
804 }
805
806 static void
807 cg_enter(void)
808 {
809   if (!cg_enable)
810     return;
811
812   msg("Entering control group %s\n", cg_name);
813
814   FOREACH_CG_CONTROLLER(controller)
815     {
816       if (cg_controller_optional(controller))
817         cg_write(controller, "?tasks", "%d\n", (int) getpid());
818       else
819         cg_write(controller, "tasks", "%d\n", (int) getpid());
820     }
821
822   if (cg_memory_limit)
823     {
824       cg_write(CG_MEMORY, "memory.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
825       cg_write(CG_MEMORY, "?memory.memsw.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
826     }
827
828   if (cg_timing)
829     cg_write(CG_CPUACCT, "cpuacct.usage", "0\n");
830 }
831
832 static int
833 cg_get_run_time_ms(void)
834 {
835   if (!cg_enable)
836     return 0;
837
838   char buf[CG_BUFSIZE];
839   cg_read(CG_CPUACCT, "cpuacct.usage", buf);
840   unsigned long long ns = atoll(buf);
841   return ns / 1000000;
842 }
843
844 static void
845 cg_stats(void)
846 {
847   if (!cg_enable)
848     return;
849
850   char buf[CG_BUFSIZE];
851
852   // Memory usage statistics
853   unsigned long long mem=0, memsw=0;
854   if (cg_read(CG_MEMORY, "?memory.max_usage_in_bytes", buf))
855     mem = atoll(buf);
856   if (cg_read(CG_MEMORY, "?memory.memsw.max_usage_in_bytes", buf))
857     {
858       memsw = atoll(buf);
859       if (memsw > mem)
860         mem = memsw;
861     }
862   if (mem)
863     meta_printf("cg-mem:%lld\n", mem >> 10);
864 }
865
866 static void
867 cg_remove(void)
868 {
869   char buf[CG_BUFSIZE];
870
871   if (!cg_enable)
872     return;
873
874   FOREACH_CG_CONTROLLER(controller)
875     {
876       if (cg_controller_optional(controller))
877         {
878           if (!cg_read(controller, "?tasks", buf))
879             continue;
880         }
881       else
882         cg_read(controller, "tasks", buf);
883
884       if (buf[0])
885         die("Some tasks left in controller %s of cgroup %s, failed to remove it",
886             cg_controller_name(controller), cg_name);
887
888       char path[256];
889       cg_makepath(path, sizeof(path), controller, "");
890
891       if (rmdir(path) < 0)
892         die("Cannot remove control group %s: %m", path);
893     }
894 }
895
896 /*** Disk quotas ***/
897
898 static int
899 path_begins_with(char *path, char *with)
900 {
901   while (*with)
902     if (*path++ != *with++)
903       return 0;
904   return (!*with || *with == '/');
905 }
906
907 static char *
908 find_device(char *path)
909 {
910   FILE *f = setmntent("/proc/mounts", "r");
911   if (!f)
912     die("Cannot open /proc/mounts: %m");
913
914   struct mntent *me;
915   int best_len = 0;
916   char *best_dev = NULL;
917   while (me = getmntent(f))
918     {
919       if (!path_begins_with(me->mnt_fsname, "/dev"))
920         continue;
921       if (path_begins_with(path, me->mnt_dir))
922         {
923           int len = strlen(me->mnt_dir);
924           if (len > best_len)
925             {
926               best_len = len;
927               free(best_dev);
928               best_dev = xstrdup(me->mnt_fsname);
929             }
930         }
931     }
932   endmntent(f);
933   return best_dev;
934 }
935
936 static void
937 set_quota(void)
938 {
939   if (!block_quota)
940     return;
941
942   char cwd[PATH_MAX];
943   if (!getcwd(cwd, sizeof(cwd)))
944     die("getcwd: %m");
945
946   char *dev = find_device(cwd);
947   if (!dev)
948     die("Cannot identify filesystem which contains %s", cwd);
949   msg("Quota: Mapped path %s to a filesystem on %s\n", cwd, dev);
950
951   // Sanity check
952   struct stat dev_st, cwd_st;
953   if (stat(dev, &dev_st) < 0)
954     die("Cannot identify block device %s: %m", dev);
955   if (!S_ISBLK(dev_st.st_mode))
956     die("Expected that %s is a block device", dev);
957   if (stat(".", &cwd_st) < 0)
958     die("Cannot stat cwd: %m");
959   if (cwd_st.st_dev != dev_st.st_rdev)
960     die("Identified %s as a filesystem on %s, but it is obviously false", cwd, dev);
961
962   struct dqblk dq = {
963     .dqb_bhardlimit = block_quota,
964     .dqb_bsoftlimit = block_quota,
965     .dqb_ihardlimit = inode_quota,
966     .dqb_isoftlimit = inode_quota,
967     .dqb_valid = QIF_LIMITS,
968   };
969   if (quotactl(QCMD(Q_SETQUOTA, USRQUOTA), dev, box_uid, (caddr_t) &dq) < 0)
970     die("Cannot set disk quota: %m");
971   msg("Quota: Set block quota %d and inode quota %d\n", block_quota, inode_quota);
972
973   free(dev);
974 }
975
976 /*** The keeper process ***/
977
978 static void
979 signal_alarm(int unused UNUSED)
980 {
981   /* Time limit checks are synchronous, so we only schedule them there. */
982   timer_tick = 1;
983   alarm(1);
984 }
985
986 static void
987 signal_int(int unused UNUSED)
988 {
989   /* Interrupts are fatal, so no synchronization requirements. */
990   meta_printf("exitsig:%d\n", SIGINT);
991   err("SG: Interrupted");
992 }
993
994 #define PROC_BUF_SIZE 4096
995 static void
996 read_proc_file(char *buf, char *name, int *fdp)
997 {
998   int c;
999
1000   if (!*fdp)
1001     {
1002       sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
1003       *fdp = open(buf, O_RDONLY);
1004       if (*fdp < 0)
1005         die("open(%s): %m", buf);
1006     }
1007   lseek(*fdp, 0, SEEK_SET);
1008   if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
1009     die("read on /proc/$pid/%s: %m", name);
1010   if (c >= PROC_BUF_SIZE-1)
1011     die("/proc/$pid/%s too long", name);
1012   buf[c] = 0;
1013 }
1014
1015 static int
1016 get_wall_time_ms(void)
1017 {
1018   struct timeval now, wall;
1019   gettimeofday(&now, NULL);
1020   timersub(&now, &start_time, &wall);
1021   return wall.tv_sec*1000 + wall.tv_usec/1000;
1022 }
1023
1024 static int
1025 get_run_time_ms(struct rusage *rus)
1026 {
1027   if (cg_timing)
1028     return cg_get_run_time_ms();
1029
1030   if (rus)
1031     {
1032       struct timeval total;
1033       timeradd(&rus->ru_utime, &rus->ru_stime, &total);
1034       return total.tv_sec*1000 + total.tv_usec/1000;
1035     }
1036
1037   char buf[PROC_BUF_SIZE], *x;
1038   int utime, stime;
1039   static int proc_stat_fd;
1040
1041   read_proc_file(buf, "stat", &proc_stat_fd);
1042   x = buf;
1043   while (*x && *x != ' ')
1044     x++;
1045   while (*x == ' ')
1046     x++;
1047   if (*x++ != '(')
1048     die("proc stat syntax error 1");
1049   while (*x && (*x != ')' || x[1] != ' '))
1050     x++;
1051   while (*x == ')' || *x == ' ')
1052     x++;
1053   if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
1054     die("proc stat syntax error 2");
1055
1056   return (utime + stime) * 1000 / ticks_per_sec;
1057 }
1058
1059 static void
1060 check_timeout(void)
1061 {
1062   if (wall_timeout)
1063     {
1064       int wall_ms = get_wall_time_ms();
1065       if (wall_ms > wall_timeout)
1066         err("TO: Time limit exceeded (wall clock)");
1067       if (verbose > 1)
1068         fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
1069     }
1070   if (timeout)
1071     {
1072       int ms = get_run_time_ms(NULL);
1073       if (verbose > 1)
1074         fprintf(stderr, "[time check: %d msec]\n", ms);
1075       if (ms > timeout && ms > extra_timeout)
1076         err("TO: Time limit exceeded");
1077     }
1078 }
1079
1080 static void
1081 box_keeper(void)
1082 {
1083   read_errors_from_fd = error_pipes[0];
1084   close(error_pipes[1]);
1085
1086   struct sigaction sa;
1087   bzero(&sa, sizeof(sa));
1088   sa.sa_handler = signal_int;
1089   sigaction(SIGINT, &sa, NULL);
1090
1091   gettimeofday(&start_time, NULL);
1092   ticks_per_sec = sysconf(_SC_CLK_TCK);
1093   if (ticks_per_sec <= 0)
1094     die("Invalid ticks_per_sec!");
1095
1096   if (timeout || wall_timeout)
1097     {
1098       sa.sa_handler = signal_alarm;
1099       sigaction(SIGALRM, &sa, NULL);
1100       alarm(1);
1101     }
1102
1103   for(;;)
1104     {
1105       struct rusage rus;
1106       int stat;
1107       pid_t p;
1108       if (timer_tick)
1109         {
1110           check_timeout();
1111           timer_tick = 0;
1112         }
1113       p = wait4(box_pid, &stat, 0, &rus);
1114       if (p < 0)
1115         {
1116           if (errno == EINTR)
1117             continue;
1118           die("wait4: %m");
1119         }
1120       if (p != box_pid)
1121         die("wait4: unknown pid %d exited!", p);
1122       box_pid = 0;
1123
1124       // Check error pipe if there is an internal error passed from inside the box
1125       char interr[1024];
1126       int n = read(read_errors_from_fd, interr, sizeof(interr) - 1);
1127       if (n > 0)
1128         {
1129           interr[n] = 0;
1130           die("%s", interr);
1131         }
1132
1133       if (WIFEXITED(stat))
1134         {
1135           final_stats(&rus);
1136           if (WEXITSTATUS(stat))
1137             {
1138               meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
1139               err("RE: Exited with error status %d", WEXITSTATUS(stat));
1140             }
1141           if (timeout && total_ms > timeout)
1142             err("TO: Time limit exceeded");
1143           if (wall_timeout && wall_ms > wall_timeout)
1144             err("TO: Time limit exceeded (wall clock)");
1145           flush_line();
1146           fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall)\n",
1147               total_ms/1000, total_ms%1000,
1148               wall_ms/1000, wall_ms%1000);
1149           box_exit(0);
1150         }
1151       else if (WIFSIGNALED(stat))
1152         {
1153           meta_printf("exitsig:%d\n", WTERMSIG(stat));
1154           final_stats(&rus);
1155           err("SG: Caught fatal signal %d", WTERMSIG(stat));
1156         }
1157       else if (WIFSTOPPED(stat))
1158         {
1159           meta_printf("exitsig:%d\n", WSTOPSIG(stat));
1160           final_stats(&rus);
1161           err("SG: Stopped by signal %d", WSTOPSIG(stat));
1162         }
1163       else
1164         die("wait4: unknown status %x, giving up!", stat);
1165     }
1166 }
1167
1168 /*** The process running inside the box ***/
1169
1170 static void
1171 setup_root(void)
1172 {
1173   if (mkdir("root", 0750) < 0 && errno != EEXIST)
1174     die("mkdir('root'): %m");
1175
1176   if (mount("none", "root", "tmpfs", 0, "mode=755") < 0)
1177     die("Cannot mount root ramdisk: %m");
1178
1179   apply_dir_rules();
1180
1181   if (chroot("root") < 0)
1182     die("Chroot failed: %m");
1183
1184   if (chdir("root/box") < 0)
1185     die("Cannot change current directory: %m");
1186 }
1187
1188 static void
1189 setup_credentials(void)
1190 {
1191   if (setresgid(box_gid, box_gid, box_gid) < 0)
1192     die("setresgid: %m");
1193   if (setgroups(0, NULL) < 0)
1194     die("setgroups: %m");
1195   if (setresuid(box_uid, box_uid, box_uid) < 0)
1196     die("setresuid: %m");
1197   setpgrp();
1198 }
1199
1200 static void
1201 setup_fds(void)
1202 {
1203   if (redir_stdin)
1204     {
1205       close(0);
1206       if (open(redir_stdin, O_RDONLY) != 0)
1207         die("open(\"%s\"): %m", redir_stdin);
1208     }
1209   if (redir_stdout)
1210     {
1211       close(1);
1212       if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
1213         die("open(\"%s\"): %m", redir_stdout);
1214     }
1215   if (redir_stderr)
1216     {
1217       close(2);
1218       if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
1219         die("open(\"%s\"): %m", redir_stderr);
1220     }
1221   else
1222     dup2(1, 2);
1223 }
1224
1225 static void
1226 setup_rlim(const char *res_name, int res, rlim_t limit)
1227 {
1228   struct rlimit rl = { .rlim_cur = limit, .rlim_max = limit };
1229   if (setrlimit(res, &rl) < 0)
1230     die("setrlimit(%s, %jd)", res_name, (intmax_t) limit);
1231 }
1232
1233 static void
1234 setup_rlimits(void)
1235 {
1236 #define RLIM(res, val) setup_rlim("RLIMIT_" #res, RLIMIT_##res, val)
1237
1238   if (memory_limit)
1239     RLIM(AS, (rlim_t)memory_limit * 1024);
1240
1241   RLIM(STACK, (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY));
1242   RLIM(NOFILE, 64);
1243   RLIM(MEMLOCK, 0);
1244
1245   if (max_processes)
1246     RLIM(NPROC, max_processes);
1247
1248 #undef RLIM
1249 }
1250
1251 static int
1252 box_inside(void *arg)
1253 {
1254   char **args = arg;
1255   write_errors_to_fd = error_pipes[1];
1256   close(error_pipes[0]);
1257   meta_close();
1258
1259   cg_enter();
1260   setup_root();
1261   setup_credentials();
1262   setup_fds();
1263   setup_rlimits();
1264   char **env = setup_environment();
1265
1266   if (set_cwd && chdir(set_cwd))
1267     die("chdir: %m");
1268
1269   execve(args[0], args, env);
1270   die("execve(\"%s\"): %m", args[0]);
1271 }
1272
1273 static void
1274 box_init(void)
1275 {
1276   if (box_id < 0 || box_id >= CONFIG_ISOLATE_NUM_BOXES)
1277     die("Sandbox ID out of range (allowed: 0-%d)", CONFIG_ISOLATE_NUM_BOXES-1);
1278   box_uid = CONFIG_ISOLATE_FIRST_UID + box_id;
1279   box_gid = CONFIG_ISOLATE_FIRST_GID + box_id;
1280
1281   snprintf(box_dir, sizeof(box_dir), "%s/%d", CONFIG_ISOLATE_BOX_DIR, box_id);
1282   make_dir(box_dir);
1283   if (chdir(box_dir) < 0)
1284     die("chdir(%s): %m", box_dir);
1285 }
1286
1287 /*** Commands ***/
1288
1289 static void
1290 init(void)
1291 {
1292   msg("Preparing sandbox directory\n");
1293   rmtree("box");
1294   if (mkdir("box", 0700) < 0)
1295     die("Cannot create box: %m");
1296   if (chown("box", orig_uid, orig_gid) < 0)
1297     die("Cannot chown box: %m");
1298
1299   cg_prepare();
1300   set_quota();
1301
1302   puts(box_dir);
1303 }
1304
1305 static void
1306 cleanup(void)
1307 {
1308   if (!dir_exists("box"))
1309     die("Box directory not found, there isn't anything to clean up");
1310
1311   msg("Deleting sandbox directory\n");
1312   rmtree(box_dir);
1313   cg_remove();
1314 }
1315
1316 static void
1317 run(char **argv)
1318 {
1319   if (!dir_exists("box"))
1320     die("Box directory not found, did you run `isolate --init'?");
1321
1322   chowntree("box", box_uid, box_gid);
1323   cleanup_ownership = 1;
1324
1325   if (pipe(error_pipes) < 0)
1326     die("pipe: %m");
1327   for (int i=0; i<2; i++)
1328     if (fcntl(error_pipes[i], F_SETFD, fcntl(error_pipes[i], F_GETFD) | FD_CLOEXEC) < 0 ||
1329         fcntl(error_pipes[i], F_SETFL, fcntl(error_pipes[i], F_GETFL) | O_NONBLOCK) < 0)
1330       die("fcntl on pipe: %m");
1331
1332   box_pid = clone(
1333     box_inside,                 // Function to execute as the body of the new process
1334     argv,                       // Pass our stack
1335     SIGCHLD | CLONE_NEWIPC | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWPID,
1336     argv);                      // Pass the arguments
1337   if (box_pid < 0)
1338     die("clone: %m");
1339   if (!box_pid)
1340     die("clone returned 0");
1341   box_keeper();
1342 }
1343
1344 static void
1345 show_version(void)
1346 {
1347   printf("Process isolator 1.0\n");
1348   printf("(c) 2012 Martin Mares and Bernard Blackham\n");
1349   printf("\nCompile-time configuration:\n");
1350   printf("Sandbox directory: %s\n", CONFIG_ISOLATE_BOX_DIR);
1351   printf("Sandbox credentials: uid=%u-%u gid=%u-%u\n",
1352     CONFIG_ISOLATE_FIRST_UID,
1353     CONFIG_ISOLATE_FIRST_UID + CONFIG_ISOLATE_NUM_BOXES - 1,
1354     CONFIG_ISOLATE_FIRST_GID,
1355     CONFIG_ISOLATE_FIRST_GID + CONFIG_ISOLATE_NUM_BOXES - 1);
1356 }
1357
1358 /*** Options ***/
1359
1360 static void __attribute__((format(printf,1,2)))
1361 usage(const char *msg, ...)
1362 {
1363   if (msg != NULL)
1364     {
1365       va_list args;
1366       va_start(args, msg);
1367       vfprintf(stderr, msg, args);
1368       va_end(args);
1369     }
1370   printf("\
1371 Usage: isolate [<options>] <command>\n\
1372 \n\
1373 Options:\n\
1374 -b, --box-id=<id>\tWhen multiple sandboxes are used in parallel, each must get a unique ID\n\
1375 -c, --cg[=<parent>]\tPut process in a control group (optionally a sub-group of <parent>)\n\
1376     --cg-mem=<size>\tLimit memory usage of the control group to <size> KB\n\
1377     --cg-timing\t\tTime limits affects total run time of the control group\n\
1378 -d, --dir=<dir>\t\tMake a directory <dir> visible inside the sandbox\n\
1379     --dir=<in>=<out>\tMake a directory <out> outside visible as <in> inside\n\
1380     --dir=<in>=\t\tDelete a previously defined directory rule (even a default one)\n\
1381     --dir=...:<opt>\tSpecify options for a rule:\n\
1382 \t\t\t\tdev\tAllow access to special files\n\
1383 \t\t\t\tfs\tMount a filesystem (e.g., --dir=/proc:proc:fs)\n\
1384 \t\t\t\tmaybe\tSkip the rule if <out> does not exist\n\
1385 \t\t\t\tnoexec\tDo not allow execution of binaries\n\
1386 \t\t\t\trw\tAllow read-write access\n\
1387 -E, --env=<var>\t\tInherit the environment variable <var> from the parent process\n\
1388 -E, --env=<var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
1389 -x, --extra-time=<time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
1390 \t\t\tso that its real execution time is reported (seconds, fractions allowed)\n\
1391 -e, --full-env\t\tInherit full environment of the parent process\n\
1392 -m, --mem=<size>\tLimit address space to <size> KB\n\
1393 -M, --meta=<file>\tOutput process information to <file> (name:value)\n\
1394 -q, --quota=<blk>,<ino>\tSet disk quota to <blk> blocks and <ino> inodes\n\
1395 -k, --stack=<size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
1396 -r, --stderr=<file>\tRedirect stderr to <file>\n\
1397 -i, --stdin=<file>\tRedirect stdin from <file>\n\
1398 -o, --stdout=<file>\tRedirect stdout to <file>\n\
1399 -p, --processes[=<max>]\tEnable multiple processes (at most <max> of them); needs --cg\n\
1400 -t, --time=<time>\tSet run time limit (seconds, fractions allowed)\n\
1401 -v, --verbose\t\tBe verbose (use multiple times for even more verbosity)\n\
1402 -w, --wall-time=<time>\tSet wall clock time limit (seconds, fractions allowed)\n\
1403 \n\
1404 Commands:\n\
1405     --init\t\tInitialize sandbox (and its control group when --cg is used)\n\
1406     --run -- <cmd> ...\tRun given command within sandbox\n\
1407     --cleanup\t\tClean up sandbox\n\
1408     --version\t\tDisplay program version and configuration\n\
1409 ");
1410   exit(2);
1411 }
1412
1413 enum opt_code {
1414   OPT_INIT = 256,
1415   OPT_RUN,
1416   OPT_CLEANUP,
1417   OPT_VERSION,
1418   OPT_CG,
1419   OPT_CG_MEM,
1420   OPT_CG_TIMING,
1421 };
1422
1423 static const char short_opts[] = "b:c:d:eE:i:k:m:M:o:p::q:r:t:vw:x:";
1424
1425 static const struct option long_opts[] = {
1426   { "box-id",           1, NULL, 'b' },
1427   { "chdir",            1, NULL, 'c' },
1428   { "cg",               0, NULL, OPT_CG },
1429   { "cg-mem",           1, NULL, OPT_CG_MEM },
1430   { "cg-timing",        0, NULL, OPT_CG_TIMING },
1431   { "cleanup",          0, NULL, OPT_CLEANUP },
1432   { "dir",              1, NULL, 'd' },
1433   { "env",              1, NULL, 'E' },
1434   { "extra-time",       1, NULL, 'x' },
1435   { "full-env",         0, NULL, 'e' },
1436   { "init",             0, NULL, OPT_INIT },
1437   { "mem",              1, NULL, 'm' },
1438   { "meta",             1, NULL, 'M' },
1439   { "processes",        2, NULL, 'p' },
1440   { "quota",            1, NULL, 'q' },
1441   { "run",              0, NULL, OPT_RUN },
1442   { "stack",            1, NULL, 'k' },
1443   { "stderr",           1, NULL, 'r' },
1444   { "stdin",            1, NULL, 'i' },
1445   { "stdout",           1, NULL, 'o' },
1446   { "time",             1, NULL, 't' },
1447   { "verbose",          0, NULL, 'v' },
1448   { "version",          0, NULL, OPT_VERSION },
1449   { "wall-time",        1, NULL, 'w' },
1450   { NULL,               0, NULL, 0 }
1451 };
1452
1453 int
1454 main(int argc, char **argv)
1455 {
1456   int c;
1457   char *sep;
1458   enum opt_code mode = 0;
1459
1460   init_dir_rules();
1461
1462   while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) >= 0)
1463     switch (c)
1464       {
1465       case 'b':
1466         box_id = atoi(optarg);
1467         break;
1468       case 'c':
1469         set_cwd = optarg;
1470         break;
1471       case OPT_CG:
1472         cg_enable = 1;
1473         break;
1474       case 'd':
1475         if (!set_dir_action(optarg))
1476           usage("Invalid directory specified: %s\n", optarg);
1477         break;
1478       case 'e':
1479         pass_environ = 1;
1480         break;
1481       case 'E':
1482         if (!set_env_action(optarg))
1483           usage("Invalid environment specified: %s\n", optarg);
1484         break;
1485       case 'k':
1486         stack_limit = atoi(optarg);
1487         break;
1488       case 'i':
1489         redir_stdin = optarg;
1490         break;
1491       case 'm':
1492         memory_limit = atoi(optarg);
1493         break;
1494       case 'M':
1495         meta_open(optarg);
1496         break;
1497       case 'o':
1498         redir_stdout = optarg;
1499         break;
1500       case 'p':
1501         if (optarg)
1502           max_processes = atoi(optarg);
1503         else
1504           max_processes = 0;
1505         break;
1506       case 'q':
1507         sep = strchr(optarg, ',');
1508         if (!sep)
1509           usage("Invalid quota specified: %s\n", optarg);
1510         block_quota = atoi(optarg);
1511         inode_quota = atoi(sep+1);
1512         break;
1513       case 'r':
1514         redir_stderr = optarg;
1515         break;
1516       case 't':
1517         timeout = 1000*atof(optarg);
1518         break;
1519       case 'v':
1520         verbose++;
1521         break;
1522       case 'w':
1523         wall_timeout = 1000*atof(optarg);
1524         break;
1525       case 'x':
1526         extra_timeout = 1000*atof(optarg);
1527         break;
1528       case OPT_INIT:
1529       case OPT_RUN:
1530       case OPT_CLEANUP:
1531       case OPT_VERSION:
1532         if (!mode || (int) mode == c)
1533           mode = c;
1534         else
1535           usage("Only one command is allowed.\n");
1536         break;
1537       case OPT_CG_MEM:
1538         cg_memory_limit = atoi(optarg);
1539         break;
1540       case OPT_CG_TIMING:
1541         cg_timing = 1;
1542         break;
1543       default:
1544         usage(NULL);
1545       }
1546
1547   if (!mode)
1548     usage("Please specify an isolate command (e.g. --init, --run).\n");
1549   if (mode == OPT_VERSION)
1550     {
1551       show_version();
1552       return 0;
1553     }
1554
1555   if (geteuid())
1556     die("Must be started as root");
1557   orig_uid = getuid();
1558   orig_gid = getgid();
1559
1560   umask(022);
1561   box_init();
1562   cg_init();
1563
1564   switch (mode)
1565     {
1566     case OPT_INIT:
1567       if (optind < argc)
1568         usage("--init mode takes no parameters\n");
1569       init();
1570       break;
1571     case OPT_RUN:
1572       if (optind >= argc)
1573         usage("--run mode requires a command to run\n");
1574       run(argv+optind);
1575       break;
1576     case OPT_CLEANUP:
1577       if (optind < argc)
1578         usage("--cleanup mode takes no parameters\n");
1579       cleanup();
1580       break;
1581     default:
1582       die("Internal error: mode mismatch");
1583     }
1584   exit(0);
1585 }