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