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