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