]> mj.ucw.cz Git - moe.git/blob - isolate/isolate.c
Isolate: Polished help text
[moe.git] / isolate / isolate.c
1 /*
2  *      A Process Isolator based on Linux Containers
3  *
4  *      (c) 2012 Martin Mares <mj@ucw.cz>
5  *      (c) 2012 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 <grp.h>
24 #include <sys/wait.h>
25 #include <sys/time.h>
26 #include <sys/signal.h>
27 #include <sys/resource.h>
28 #include <sys/mount.h>
29 #include <sys/stat.h>
30
31 #define NONRET __attribute__((noreturn))
32 #define UNUSED __attribute__((unused))
33 #define ARRAY_SIZE(a) (int)(sizeof(a)/sizeof(a[0]))
34
35 #define BOX_DIR CONFIG_ISOLATE_BOX_DIR
36 #define BOX_UID CONFIG_ISOLATE_BOX_UID
37 #define BOX_GID CONFIG_ISOLATE_BOX_GID
38
39 static int timeout;                     /* milliseconds */
40 static int wall_timeout;
41 static int extra_timeout;
42 static int pass_environ;
43 static int verbose;
44 static int memory_limit;
45 static int stack_limit;
46 static int max_processes = 1;
47 static char *redir_stdin, *redir_stdout, *redir_stderr;
48
49 static int cg_enable;
50 static int cg_memory_limit;
51 static int cg_timing;
52 static char *cg_root = "/sys/fs/cgroup";
53
54 static uid_t orig_uid;
55 static gid_t orig_gid;
56
57 static pid_t box_pid;
58 static int partial_line;
59 static char cleanup_cmd[256];
60
61 static struct timeval start_time;
62 static int ticks_per_sec;
63 static int total_ms, wall_ms;
64 static volatile sig_atomic_t timer_tick;
65
66 static int error_pipes[2];
67 static int write_errors_to_fd;
68 static int read_errors_from_fd;
69
70 static void die(char *msg, ...) NONRET;
71 static void cg_stats(void);
72 static int get_wall_time_ms(void);
73 static int get_run_time_ms(struct rusage *rus);
74
75 /*** Meta-files ***/
76
77 static FILE *metafile;
78
79 static void
80 meta_open(const char *name)
81 {
82   if (!strcmp(name, "-"))
83     {
84       metafile = stdout;
85       return;
86     }
87   metafile = fopen(name, "w");
88   if (!metafile)
89     die("Failed to open metafile '%s'",name);
90 }
91
92 static void
93 meta_close(void)
94 {
95   if (metafile && metafile != stdout)
96     fclose(metafile);
97 }
98
99 static void __attribute__((format(printf,1,2)))
100 meta_printf(const char *fmt, ...)
101 {
102   if (!metafile)
103     return;
104
105   va_list args;
106   va_start(args, fmt);
107   vfprintf(metafile, fmt, args);
108   va_end(args);
109 }
110
111 static void
112 final_stats(struct rusage *rus)
113 {
114   total_ms = get_run_time_ms(rus);
115   wall_ms = get_wall_time_ms();
116
117   meta_printf("time:%d.%03d\n", total_ms/1000, total_ms%1000);
118   meta_printf("time-wall:%d.%03d\n", wall_ms/1000, wall_ms%1000);
119   meta_printf("max-rss:%ld\n", rus->ru_maxrss);
120   meta_printf("csw-voluntary:%ld\n", rus->ru_nvcsw);
121   meta_printf("csw-forced:%ld\n", rus->ru_nivcsw);
122
123   cg_stats();
124 }
125
126 /*** Messages and exits ***/
127
128 static void
129 xsystem(const char *cmd)
130 {
131   int ret = system(cmd);
132   if (ret < 0)
133     die("system(\"%s\"): %m", cmd);
134   if (!WIFEXITED(ret) || WEXITSTATUS(ret))
135     die("system(\"%s\"): Exited with status %d", cmd, ret);
136 }
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_cmd[0])
159     xsystem(cleanup_cmd);
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 static void *
236 xmalloc(size_t size)
237 {
238   void *p = malloc(size);
239   if (!p)
240     die("Out of memory");
241   return p;
242 }
243
244 /*** Environment rules ***/
245
246 struct env_rule {
247   char *var;                    // Variable to match
248   char *val;                    // ""=clear, NULL=inherit
249   int var_len;
250   struct env_rule *next;
251 };
252
253 static struct env_rule *first_env_rule;
254 static struct env_rule **last_env_rule = &first_env_rule;
255
256 static struct env_rule default_env_rules[] = {
257   { "LIBC_FATAL_STDERR_", "1" }
258 };
259
260 static int
261 set_env_action(char *a0)
262 {
263   struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
264   char *a = (char *)(r+1);
265   strcpy(a, a0);
266
267   char *sep = strchr(a, '=');
268   if (sep == a)
269     return 0;
270   r->var = a;
271   if (sep)
272     {
273       *sep++ = 0;
274       r->val = sep;
275     }
276   else
277     r->val = NULL;
278   *last_env_rule = r;
279   last_env_rule = &r->next;
280   r->next = NULL;
281   return 1;
282 }
283
284 static int
285 match_env_var(char *env_entry, struct env_rule *r)
286 {
287   if (strncmp(env_entry, r->var, r->var_len))
288     return 0;
289   return (env_entry[r->var_len] == '=');
290 }
291
292 static void
293 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
294 {
295   // First remove the variable if already set
296   int pos = 0;
297   while (pos < *env_sizep && !match_env_var(env[pos], r))
298     pos++;
299   if (pos < *env_sizep)
300     {
301       (*env_sizep)--;
302       env[pos] = env[*env_sizep];
303       env[*env_sizep] = NULL;
304     }
305
306   // What is the new value?
307   char *new;
308   if (r->val)
309     {
310       if (!r->val[0])
311         return;
312       new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
313       sprintf(new, "%s=%s", r->var, r->val);
314     }
315   else
316     {
317       pos = 0;
318       while (environ[pos] && !match_env_var(environ[pos], r))
319         pos++;
320       if (!(new = environ[pos]))
321         return;
322     }
323
324   // Add it at the end of the array
325   env[(*env_sizep)++] = new;
326   env[*env_sizep] = NULL;
327 }
328
329 static char **
330 setup_environment(void)
331 {
332   // Link built-in rules with user rules
333   for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
334     {
335       default_env_rules[i].next = first_env_rule;
336       first_env_rule = &default_env_rules[i];
337     }
338
339   // Scan the original environment
340   char **orig_env = environ;
341   int orig_size = 0;
342   while (orig_env[orig_size])
343     orig_size++;
344
345   // For each rule, reserve one more slot and calculate length
346   int num_rules = 0;
347   for (struct env_rule *r = first_env_rule; r; r=r->next)
348     {
349       num_rules++;
350       r->var_len = strlen(r->var);
351     }
352
353   // Create a new environment
354   char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
355   int size;
356   if (pass_environ)
357     {
358       memcpy(env, environ, orig_size * sizeof(char *));
359       size = orig_size;
360     }
361   else
362     size = 0;
363   env[size] = NULL;
364
365   // Apply the rules one by one
366   for (struct env_rule *r = first_env_rule; r; r=r->next)
367     apply_env_rule(env, &size, r);
368
369   // Return the new env and pass some gossip
370   if (verbose > 1)
371     {
372       fprintf(stderr, "Passing environment:\n");
373       for (int i=0; env[i]; i++)
374         fprintf(stderr, "\t%s\n", env[i]);
375     }
376   return env;
377 }
378
379 /*** Control groups ***/
380
381 static char cg_path[256];
382
383 #define CG_BUFSIZE 1024
384
385 static int
386 cg_read(char *attr, char *buf)
387 {
388   int maybe = 0;
389   if (attr[0] == '?')
390     {
391       attr++;
392       maybe = 1;
393     }
394
395   char path[256];
396   snprintf(path, sizeof(path), "%s/%s", cg_path, attr);
397
398   int fd = open(path, O_RDONLY);
399   if (fd < 0)
400     {
401       if (maybe)
402         return 0;
403       die("Cannot read %s: %m", path);
404     }
405
406   int n = read(fd, buf, CG_BUFSIZE);
407   if (n < 0)
408     die("Cannot read %s: %m", path);
409   if (n >= CG_BUFSIZE - 1)
410     die("Attribute %s too long", path);
411   if (n > 0 && buf[n-1] == '\n')
412     n--;
413   buf[n] = 0;
414
415   if (verbose > 1)
416     msg("CG: Read %s = %s\n", attr, buf);
417
418   close(fd);
419   return 1;
420 }
421
422 static void __attribute__((format(printf,2,3)))
423 cg_write(char *attr, char *fmt, ...)
424 {
425   va_list args;
426   va_start(args, fmt);
427
428   char buf[CG_BUFSIZE];
429   int n = vsnprintf(buf, sizeof(buf), fmt, args);
430   if (n >= CG_BUFSIZE)
431     die("cg_writef: Value for attribute %s is too long", attr);
432
433   if (verbose > 1)
434     msg("CG: Write %s = %s", attr, buf);
435
436   char path[256];
437   snprintf(path, sizeof(path), "%s/%s", cg_path, attr);
438
439   int fd = open(path, O_WRONLY | O_TRUNC);
440   if (fd < 0)
441     die("Cannot write %s: %m", path);
442
443   int written = write(fd, buf, n);
444   if (written < 0)
445     die("Cannot set %s to %s: %m", path, buf);
446   if (written != n)
447     die("Short write to %s (%d out of %d bytes)", path, written, n);
448
449   close(fd);
450   va_end(args);
451 }
452
453 static void
454 cg_init(void)
455 {
456   if (!cg_enable)
457     return;
458
459   struct stat st;
460   if (stat(cg_root, &st) < 0 || !S_ISDIR(st.st_mode))
461     die("Control group filesystem at %s not mounted", cg_root);
462
463   snprintf(cg_path, sizeof(cg_path), "%s/box-%d", cg_root, BOX_UID);
464   msg("Using control group %s\n", cg_path);
465 }
466
467 static void
468 cg_prepare(void)
469 {
470   if (!cg_enable)
471     return;
472
473   struct stat st;
474   char buf[CG_BUFSIZE];
475
476   if (stat(cg_path, &st) >= 0 || errno != ENOENT)
477     {
478       msg("Control group %s already exists, trying to empty it.\n", cg_path);
479       if (rmdir(cg_path) < 0)
480         die("Failed to reset control group %s: %m", cg_path);
481     }
482
483   if (mkdir(cg_path, 0777) < 0)
484     die("Failed to create control group %s: %m", cg_path);
485
486   // If cpuset module is enabled, copy allowed cpus and memory nodes from parent group
487   if (cg_read("?../cpuset.cpus", buf))
488     cg_write("cpuset.cpus", "%s", buf);
489   if (cg_read("?../cpuset.mems", buf))
490     cg_write("cpuset.mems", "%s", buf);
491 }
492
493 static void
494 cg_enter(void)
495 {
496   if (!cg_enable)
497     return;
498
499   msg("Entering control group %s\n", cg_path);
500
501   struct stat st;
502   if (stat(cg_path, &st) < 0)
503     die("Control group %s does not exist: %m", cg_path);
504
505   if (cg_memory_limit)
506     {
507       cg_write("memory.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
508       cg_write("memory.memsw.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
509     }
510
511   if (cg_timing)
512     cg_write("cpuacct.usage", "0\n");
513
514   cg_write("tasks", "%d\n", (int) getpid());
515 }
516
517 static int
518 cg_get_run_time_ms(void)
519 {
520   if (!cg_enable)
521     return 0;
522
523   char buf[CG_BUFSIZE];
524   cg_read("cpuacct.usage", buf);
525   unsigned long long ns = atoll(buf);
526   return ns / 1000000;
527 }
528
529 static void
530 cg_stats(void)
531 {
532   if (!cg_enable)
533     return;
534
535   char buf[CG_BUFSIZE];
536
537   // Memory usage statistics
538   unsigned long long mem=0, memsw=0;
539   if (cg_read("?memory.max_usage_in_bytes", buf))
540     mem = atoll(buf);
541   if (cg_read("?memory.memsw.max_usage_in_bytes", buf))
542     {
543       memsw = atoll(buf);
544       if (memsw > mem)
545         mem = memsw;
546     }
547   if (mem)
548     meta_printf("cg-mem:%lld\n", mem >> 10);
549 }
550
551 static void
552 cg_remove(void)
553 {
554   char buf[CG_BUFSIZE];
555
556   if (!cg_enable)
557     return;
558
559   cg_read("tasks", buf);
560   if (buf[0])
561     die("Some tasks left in control group %s, failed to remove it", cg_path);
562
563   if (rmdir(cg_path) < 0)
564     die("Cannot remove control group %s: %m", cg_path);
565 }
566
567 /*** The keeper process ***/
568
569 static void
570 signal_alarm(int unused UNUSED)
571 {
572   /* Time limit checks are synchronous, so we only schedule them there. */
573   timer_tick = 1;
574   alarm(1);
575 }
576
577 static void
578 signal_int(int unused UNUSED)
579 {
580   /* Interrupts are fatal, so no synchronization requirements. */
581   meta_printf("exitsig:%d\n", SIGINT);
582   err("SG: Interrupted");
583 }
584
585 #define PROC_BUF_SIZE 4096
586 static void
587 read_proc_file(char *buf, char *name, int *fdp)
588 {
589   int c;
590
591   if (!*fdp)
592     {
593       sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
594       *fdp = open(buf, O_RDONLY);
595       if (*fdp < 0)
596         die("open(%s): %m", buf);
597     }
598   lseek(*fdp, 0, SEEK_SET);
599   if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
600     die("read on /proc/$pid/%s: %m", name);
601   if (c >= PROC_BUF_SIZE-1)
602     die("/proc/$pid/%s too long", name);
603   buf[c] = 0;
604 }
605
606 static int
607 get_wall_time_ms(void)
608 {
609   struct timeval now, wall;
610   gettimeofday(&now, NULL);
611   timersub(&now, &start_time, &wall);
612   return wall.tv_sec*1000 + wall.tv_usec/1000;
613 }
614
615 static int
616 get_run_time_ms(struct rusage *rus)
617 {
618   if (cg_timing)
619     return cg_get_run_time_ms();
620
621   if (rus)
622     {
623       struct timeval total;
624       timeradd(&rus->ru_utime, &rus->ru_stime, &total);
625       return total.tv_sec*1000 + total.tv_usec/1000;
626     }
627
628   char buf[PROC_BUF_SIZE], *x;
629   int utime, stime;
630   static int proc_stat_fd;
631
632   read_proc_file(buf, "stat", &proc_stat_fd);
633   x = buf;
634   while (*x && *x != ' ')
635     x++;
636   while (*x == ' ')
637     x++;
638   if (*x++ != '(')
639     die("proc stat syntax error 1");
640   while (*x && (*x != ')' || x[1] != ' '))
641     x++;
642   while (*x == ')' || *x == ' ')
643     x++;
644   if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
645     die("proc stat syntax error 2");
646
647   return (utime + stime) * 1000 / ticks_per_sec;
648 }
649
650 static void
651 check_timeout(void)
652 {
653   if (wall_timeout)
654     {
655       int wall_ms = get_wall_time_ms();
656       if (wall_ms > wall_timeout)
657         err("TO: Time limit exceeded (wall clock)");
658       if (verbose > 1)
659         fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
660     }
661   if (timeout)
662     {
663       int ms = get_run_time_ms(NULL);
664       if (verbose > 1)
665         fprintf(stderr, "[time check: %d msec]\n", ms);
666       if (ms > timeout && ms > extra_timeout)
667         err("TO: Time limit exceeded");
668     }
669 }
670
671 static void
672 box_keeper(void)
673 {
674   read_errors_from_fd = error_pipes[0];
675   close(error_pipes[1]);
676
677   struct sigaction sa;
678   bzero(&sa, sizeof(sa));
679   sa.sa_handler = signal_int;
680   sigaction(SIGINT, &sa, NULL);
681
682   gettimeofday(&start_time, NULL);
683   ticks_per_sec = sysconf(_SC_CLK_TCK);
684   if (ticks_per_sec <= 0)
685     die("Invalid ticks_per_sec!");
686
687   if (timeout || wall_timeout)
688     {
689       sa.sa_handler = signal_alarm;
690       sigaction(SIGALRM, &sa, NULL);
691       alarm(1);
692     }
693
694   for(;;)
695     {
696       struct rusage rus;
697       int stat;
698       pid_t p;
699       if (timer_tick)
700         {
701           check_timeout();
702           timer_tick = 0;
703         }
704       p = wait4(box_pid, &stat, 0, &rus);
705       if (p < 0)
706         {
707           if (errno == EINTR)
708             continue;
709           die("wait4: %m");
710         }
711       if (p != box_pid)
712         die("wait4: unknown pid %d exited!", p);
713       box_pid = 0;
714
715       // Check error pipe if there is an internal error passed from inside the box
716       char interr[1024];
717       int n = read(read_errors_from_fd, interr, sizeof(interr) - 1);
718       if (n > 0)
719         {
720           interr[n] = 0;
721           die("%s", interr);
722         }
723
724       if (WIFEXITED(stat))
725         {
726           final_stats(&rus);
727           if (WEXITSTATUS(stat))
728             {
729               meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
730               err("RE: Exited with error status %d", WEXITSTATUS(stat));
731             }
732           if (timeout && total_ms > timeout)
733             err("TO: Time limit exceeded");
734           if (wall_timeout && wall_ms > wall_timeout)
735             err("TO: Time limit exceeded (wall clock)");
736           flush_line();
737           fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall)\n",
738               total_ms/1000, total_ms%1000,
739               wall_ms/1000, wall_ms%1000);
740           box_exit(0);
741         }
742       else if (WIFSIGNALED(stat))
743         {
744           meta_printf("exitsig:%d\n", WTERMSIG(stat));
745           final_stats(&rus);
746           err("SG: Caught fatal signal %d", WTERMSIG(stat));
747         }
748       else if (WIFSTOPPED(stat))
749         {
750           meta_printf("exitsig:%d\n", WSTOPSIG(stat));
751           final_stats(&rus);
752           err("SG: Stopped by signal %d", WSTOPSIG(stat));
753         }
754       else
755         die("wait4: unknown status %x, giving up!", stat);
756     }
757 }
758
759 /*** The process running inside the box ***/
760
761 static void
762 setup_root(void)
763 {
764   if (mkdir("root", 0750) < 0 && errno != EEXIST)
765     die("mkdir('root'): %m");
766
767   if (mount("none", "root", "tmpfs", 0, "mode=755") < 0)
768     die("Cannot mount root ramdisk: %m");
769
770   static const char * const dirs[] = { "box", "/bin", "/lib", "/lib64", "/usr", "/dev" };
771   for (int i=0; i < ARRAY_SIZE(dirs); i++)
772     {
773       const char *d = dirs[i];
774       char buf[1024];
775       snprintf(buf, sizeof(buf), "root/%s", (d[0] == '/' ? d+1 : d));
776       msg("Binding %s on %s\n", d, buf);
777       if (mkdir(buf, 0755) < 0)
778         die("mkdir(%s): %m", buf);
779       if (mount(d, buf, "none", MS_BIND | MS_NOSUID | MS_NODEV, "") < 0)
780         die("Cannot bind %s on %s: %m", d, buf);
781     }
782
783   if (mkdir("root/proc", 0755) < 0)
784     die("Cannot create proc: %m");
785   if (mount("none", "root/proc", "proc", 0, "") < 0)
786     die("Cannot mount proc: %m");
787
788   if (chroot("root") < 0)
789     die("Chroot failed: %m");
790
791   if (chdir("root/box") < 0)
792     die("Cannot change current directory: %m");
793 }
794
795 static void
796 setup_credentials(void)
797 {
798   if (setresgid(BOX_GID, BOX_GID, BOX_GID) < 0)
799     die("setresgid: %m");
800   if (setgroups(0, NULL) < 0)
801     die("setgroups: %m");
802   if (setresuid(BOX_UID, BOX_UID, BOX_UID) < 0)
803     die("setresuid: %m");
804   setpgrp();
805 }
806
807 static void
808 setup_fds(void)
809 {
810   if (redir_stdin)
811     {
812       close(0);
813       if (open(redir_stdin, O_RDONLY) != 0)
814         die("open(\"%s\"): %m", redir_stdin);
815     }
816   if (redir_stdout)
817     {
818       close(1);
819       if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
820         die("open(\"%s\"): %m", redir_stdout);
821     }
822   if (redir_stderr)
823     {
824       close(2);
825       if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
826         die("open(\"%s\"): %m", redir_stderr);
827     }
828   else
829     dup2(1, 2);
830 }
831
832 static void
833 setup_rlim(const char *res_name, int res, rlim_t limit)
834 {
835   struct rlimit rl = { .rlim_cur = limit, .rlim_max = limit };
836   if (setrlimit(res, &rl) < 0)
837     die("setrlimit(%s, %jd)", res_name, (intmax_t) limit);
838 }
839
840 static void
841 setup_rlimits(void)
842 {
843 #define RLIM(res, val) setup_rlim("RLIMIT_" #res, RLIMIT_##res, val)
844
845   if (memory_limit)
846     RLIM(AS, memory_limit * 1024);
847
848   RLIM(STACK, (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY));
849   RLIM(NOFILE, 64);
850   RLIM(MEMLOCK, 0);
851
852   if (max_processes)
853     RLIM(NPROC, max_processes);
854
855 #undef RLIM
856 }
857
858 static int
859 box_inside(void *arg)
860 {
861   char **args = arg;
862   write_errors_to_fd = error_pipes[1];
863   close(error_pipes[0]);
864
865   cg_enter();
866   setup_root();
867   setup_credentials();
868   setup_fds();
869   setup_rlimits();
870   char **env = setup_environment();
871
872   execve(args[0], args, env);
873   die("execve(\"%s\"): %m", args[0]);
874 }
875
876 /*** Commands ***/
877
878 static void
879 init(void)
880 {
881   msg("Preparing sandbox directory\n");
882   xsystem("rm -rf box");
883   if (mkdir("box", 0700) < 0)
884     die("Cannot create box: %m");
885   if (chown("box", orig_uid, orig_gid) < 0)
886     die("Cannot chown box: %m");
887
888   cg_prepare();
889 }
890
891 static void
892 cleanup(void)
893 {
894   struct stat st;
895   if (stat("box", &st) < 0 || !S_ISDIR(st.st_mode))
896     die("Box directory not found, there isn't anything to clean up");
897
898   msg("Deleting sandbox directory\n");
899   xsystem("rm -rf box");
900   cg_remove();
901 }
902
903 static void
904 run(char **argv)
905 {
906   struct stat st;
907   if (stat("box", &st) < 0 || !S_ISDIR(st.st_mode))
908     die("Box directory not found, did you run `isolate --init'?");
909
910   char cmd[256];
911   snprintf(cmd, sizeof(cmd), "chown -R %d.%d box", BOX_UID, BOX_GID);
912   xsystem(cmd);
913   snprintf(cleanup_cmd, sizeof(cleanup_cmd), "chown -R %d.%d box", orig_uid, orig_gid);
914
915   if (pipe(error_pipes) < 0)
916     die("pipe: %m");
917   for (int i=0; i<2; i++)
918     if (fcntl(error_pipes[i], F_SETFD, fcntl(error_pipes[i], F_GETFD) | FD_CLOEXEC) < 0 ||
919         fcntl(error_pipes[i], F_SETFL, fcntl(error_pipes[i], F_GETFL) | O_NONBLOCK) < 0)
920       die("fcntl on pipe: %m");
921
922   box_pid = clone(
923     box_inside,                 // Function to execute as the body of the new process
924     argv,                       // Pass our stack
925     SIGCHLD | CLONE_NEWIPC | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWPID,
926     argv);                      // Pass the arguments
927   if (box_pid < 0)
928     die("clone: %m");
929   if (!box_pid)
930     die("clone returned 0");
931   box_keeper();
932 }
933
934 static void
935 show_version(void)
936 {
937   printf("Process isolator 1.0\n");
938   printf("(c) 2012 Martin Mares and Bernard Blackham\n");
939   printf("\nCompile-time configuration:\n");
940   printf("Sandbox directory: %s\n", BOX_DIR);
941   printf("Sandbox credentials: uid=%u gid=%u\n", BOX_UID, BOX_GID);
942 }
943
944 /*** Options ***/
945
946 static void
947 usage(void)
948 {
949   fprintf(stderr, "Invalid arguments!\n");
950   printf("\
951 Usage: isolate [<options>] <command>\n\
952 \n\
953 Options:\n\
954 -c, --cg[=<parent>]\tPut process in a control group (optionally a sub-group of <parent>)\n\
955     --cg-mem=<size>\tLimit memory usage of the control group to <size> KB\n\
956     --cg-timing\t\tTime limits affects total run time of the control group\n\
957 -E, --env=<var>\t\tInherit the environment variable <var> from the parent process\n\
958 -E, --env=<var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
959 -x, --extra-time=<time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
960 \t\t\tso that its real execution time is reported (seconds, fractions allowed)\n\
961 -e, --full-env\t\tInherit full environment of the parent process\n\
962 -m, --mem=<size>\tLimit address space to <size> KB\n\
963 -M, --meta=<file>\tOutput process information to <file> (name:value)\n\
964 -k, --stack=<size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
965 -r, --stderr=<file>\tRedirect stderr to <file>\n\
966 -i, --stdin=<file>\tRedirect stdin from <file>\n\
967 -o, --stdout=<file>\tRedirect stdout to <file>\n\
968 -p, --processes[=<max>]\tEnable multiple processes (at most <max> of them); needs --cg\n\
969 -t, --time=<time>\tSet run time limit (seconds, fractions allowed)\n\
970 -v, --verbose\t\tBe verbose (use multiple times for even more verbosity)\n\
971 -w, --wall-time=<time>\tSet wall clock time limit (seconds, fractions allowed)\n\
972 \n\
973 Commands:\n\
974     --init\t\tInitialize sandbox (and its control group when --cg is used)\n\
975     --run -- <cmd> ...\tRun given command within sandbox\n\
976     --cleanup\t\tClean up sandbox\n\
977     --version\t\tDisplay program version and configuration\n\
978 ");
979   exit(2);
980 }
981
982 enum opt_code {
983   OPT_INIT = 256,
984   OPT_RUN,
985   OPT_CLEANUP,
986   OPT_VERSION,
987   OPT_CG_MEM,
988   OPT_CG_TIMING,
989 };
990
991 static const char short_opts[] = "c::eE:i:k:m:M:o:p::r:t:vw:x:";
992
993 static const struct option long_opts[] = {
994   { "cg",               2, NULL, 'c' },
995   { "cg-mem",           1, NULL, OPT_CG_MEM },
996   { "cg-timing",        0, NULL, OPT_CG_TIMING },
997   { "cleanup",          0, NULL, OPT_CLEANUP },
998   { "env",              1, NULL, 'E' },
999   { "extra-time",       1, NULL, 'x' },
1000   { "full-env",         0, NULL, 'e' },
1001   { "init",             0, NULL, OPT_INIT },
1002   { "mem",              1, NULL, 'm' },
1003   { "meta",             1, NULL, 'M' },
1004   { "processes",        2, NULL, 'p' },
1005   { "run",              0, NULL, OPT_RUN },
1006   { "stack",            1, NULL, 'k' },
1007   { "stderr",           1, NULL, 'r' },
1008   { "stdin",            1, NULL, 'i' },
1009   { "stdout",           1, NULL, 'o' },
1010   { "time",             1, NULL, 't' },
1011   { "verbose",          0, NULL, 'v' },
1012   { "version",          0, NULL, OPT_VERSION },
1013   { "wall-time",        1, NULL, 'w' },
1014   { NULL,               0, NULL, 0 }
1015 };
1016
1017 int
1018 main(int argc, char **argv)
1019 {
1020   int c;
1021   enum opt_code mode = 0;
1022
1023   while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) >= 0)
1024     switch (c)
1025       {
1026       case 'c':
1027         if (optarg)
1028           cg_root = optarg;
1029         cg_enable = 1;
1030         break;
1031       case 'e':
1032         pass_environ = 1;
1033         break;
1034       case 'E':
1035         if (!set_env_action(optarg))
1036           usage();
1037         break;
1038       case 'k':
1039         stack_limit = atoi(optarg);
1040         break;
1041       case 'i':
1042         redir_stdin = optarg;
1043         break;
1044       case 'm':
1045         memory_limit = atoi(optarg);
1046         break;
1047       case 'M':
1048         meta_open(optarg);
1049         break;
1050       case 'o':
1051         redir_stdout = optarg;
1052         break;
1053       case 'p':
1054         if (optarg)
1055           max_processes = atoi(optarg);
1056         else
1057           max_processes = 0;
1058         break;
1059       case 'r':
1060         redir_stderr = optarg;
1061         break;
1062       case 't':
1063         timeout = 1000*atof(optarg);
1064         break;
1065       case 'v':
1066         verbose++;
1067         break;
1068       case 'w':
1069         wall_timeout = 1000*atof(optarg);
1070         break;
1071       case 'x':
1072         extra_timeout = 1000*atof(optarg);
1073         break;
1074       case OPT_INIT:
1075       case OPT_RUN:
1076       case OPT_CLEANUP:
1077       case OPT_VERSION:
1078         mode = c;
1079         break;
1080       case OPT_CG_MEM:
1081         cg_memory_limit = atoi(optarg);
1082         break;
1083       case OPT_CG_TIMING:
1084         cg_timing = 1;
1085         break;
1086       default:
1087         usage();
1088       }
1089
1090   if (!mode)
1091     usage();
1092   if (mode == OPT_VERSION)
1093     {
1094       show_version();
1095       return 0;
1096     }
1097
1098   if (geteuid())
1099     die("Must be started as root");
1100   orig_uid = getuid();
1101   orig_gid = getgid();
1102
1103   umask(022);
1104   if (chdir(BOX_DIR) < 0)
1105     die("chdir(%s): %m", BOX_DIR);
1106   cg_init();
1107
1108   switch (mode)
1109     {
1110     case OPT_INIT:
1111       if (optind < argc)
1112         usage();
1113       init();
1114       break;
1115     case OPT_RUN:
1116       if (optind >= argc)
1117         usage();
1118       run(argv+optind);
1119       break;
1120     case OPT_CLEANUP:
1121       if (optind < argc)
1122         usage();
1123       cleanup();
1124       break;
1125     default:
1126       die("Internal error: mode mismatch");
1127     }
1128   exit(0);
1129 }