]> mj.ucw.cz Git - eval.git/blob - isolate/isolate.c
Isolate: Report internal errors from inside the box
[eval.git] / isolate / isolate.c
1 /*
2  *      A Process Isolator based in Linux Containers
3  *
4  *      (c) 2012 Martin Mares <mj@ucw.cz>
5  */
6
7 #define _GNU_SOURCE
8
9 #include "autoconf.h"
10
11 #include <errno.h>
12 #include <stdio.h>
13 #include <fcntl.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <stdarg.h>
17 #include <stdint.h>
18 #include <unistd.h>
19 #include <getopt.h>
20 #include <sched.h>
21 #include <time.h>
22 #include <grp.h>
23 #include <sys/wait.h>
24 #include <sys/time.h>
25 #include <sys/signal.h>
26 #include <sys/resource.h>
27 #include <sys/mount.h>
28 #include <sys/stat.h>
29
30 #define NONRET __attribute__((noreturn))
31 #define UNUSED __attribute__((unused))
32 #define ARRAY_SIZE(a) (int)(sizeof(a)/sizeof(a[0]))
33
34 // FIXME: Make configurable, probably in compile time
35 #define BOX_DIR "/tmp/box"
36 #define BOX_UID 60000
37 #define BOX_GID 60000
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(void);
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();
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(void)
617 {
618   if (cg_timing)
619     return cg_get_run_time_ms();
620
621   char buf[PROC_BUF_SIZE], *x;
622   int utime, stime;
623   static int proc_stat_fd;
624
625   read_proc_file(buf, "stat", &proc_stat_fd);
626   x = buf;
627   while (*x && *x != ' ')
628     x++;
629   while (*x == ' ')
630     x++;
631   if (*x++ != '(')
632     die("proc stat syntax error 1");
633   while (*x && (*x != ')' || x[1] != ' '))
634     x++;
635   while (*x == ')' || *x == ' ')
636     x++;
637   if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
638     die("proc stat syntax error 2");
639
640   return (utime + stime) * 1000 / ticks_per_sec;
641 }
642
643 static void
644 check_timeout(void)
645 {
646   if (wall_timeout)
647     {
648       int wall_ms = get_wall_time_ms();
649       if (wall_ms > wall_timeout)
650         err("TO: Time limit exceeded (wall clock)");
651       if (verbose > 1)
652         fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
653     }
654   if (timeout)
655     {
656       int ms = get_run_time_ms();
657       if (verbose > 1)
658         fprintf(stderr, "[time check: %d msec]\n", ms);
659       if (ms > timeout && ms > extra_timeout)
660         err("TO: Time limit exceeded");
661     }
662 }
663
664 static void
665 box_keeper(void)
666 {
667   read_errors_from_fd = error_pipes[0];
668   close(error_pipes[1]);
669
670   struct sigaction sa;
671   bzero(&sa, sizeof(sa));
672   sa.sa_handler = signal_int;
673   sigaction(SIGINT, &sa, NULL);
674
675   gettimeofday(&start_time, NULL);
676   ticks_per_sec = sysconf(_SC_CLK_TCK);
677   if (ticks_per_sec <= 0)
678     die("Invalid ticks_per_sec!");
679
680   if (timeout || wall_timeout)
681     {
682       sa.sa_handler = signal_alarm;
683       sigaction(SIGALRM, &sa, NULL);
684       alarm(1);
685     }
686
687   for(;;)
688     {
689       struct rusage rus;
690       int stat;
691       pid_t p;
692       if (timer_tick)
693         {
694           check_timeout();
695           timer_tick = 0;
696         }
697       p = wait4(box_pid, &stat, 0, &rus);
698       if (p < 0)
699         {
700           if (errno == EINTR)
701             continue;
702           die("wait4: %m");
703         }
704       if (p != box_pid)
705         die("wait4: unknown pid %d exited!", p);
706       box_pid = 0;
707
708       // Check error pipe if there is an internal error passed from inside the box
709       char interr[1024];
710       int n = read(read_errors_from_fd, interr, sizeof(interr) - 1);
711       if (n > 0)
712         {
713           interr[n] = 0;
714           die("%s", interr);
715         }
716
717       if (WIFEXITED(stat))
718         {
719           final_stats(&rus);
720           if (WEXITSTATUS(stat))
721             {
722               meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
723               err("RE: Exited with error status %d", WEXITSTATUS(stat));
724             }
725           if (timeout && total_ms > timeout)
726             err("TO: Time limit exceeded");
727           if (wall_timeout && wall_ms > wall_timeout)
728             err("TO: Time limit exceeded (wall clock)");
729           flush_line();
730           fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall)\n",
731               total_ms/1000, total_ms%1000,
732               wall_ms/1000, wall_ms%1000);
733           box_exit(0);
734         }
735       else if (WIFSIGNALED(stat))
736         {
737           meta_printf("exitsig:%d\n", WTERMSIG(stat));
738           final_stats(&rus);
739           err("SG: Caught fatal signal %d", WTERMSIG(stat));
740         }
741       else if (WIFSTOPPED(stat))
742         {
743           meta_printf("exitsig:%d\n", WSTOPSIG(stat));
744           final_stats(&rus);
745           err("SG: Stopped by signal %d", WSTOPSIG(stat));
746         }
747       else
748         die("wait4: unknown status %x, giving up!", stat);
749     }
750 }
751
752 /*** The process running inside the box ***/
753
754 static void
755 setup_root(void)
756 {
757   if (mkdir("root", 0750) < 0 && errno != EEXIST)
758     die("mkdir('root'): %m");
759
760   if (mount("none", "root", "tmpfs", 0, "mode=755") < 0)
761     die("Cannot mount root ramdisk: %m");
762
763   // FIXME: Make the list of bind-mounts configurable
764   // FIXME: Virtual /dev?
765   // FIXME: Read-only mounts?
766
767   static const char * const dirs[] = { "box", "/bin", "/lib", "/usr", "/dev" };
768   for (int i=0; i < ARRAY_SIZE(dirs); i++)
769     {
770       const char *d = dirs[i];
771       char buf[1024];   // FIXME
772       sprintf(buf, "root/%s", (d[0] == '/' ? d+1 : d));
773       msg("Binding %s on %s\n", d, buf);
774       if (mkdir(buf, 0755) < 0)
775         die("mkdir(%s): %m", buf);
776       if (mount(d, buf, "none", MS_BIND | MS_NOSUID | MS_NODEV, "") < 0)
777         die("Cannot bind %s on %s: %m", d, buf);
778     }
779
780   if (mkdir("root/proc", 0755) < 0)
781     die("Cannot create proc: %m");
782   if (mount("none", "root/proc", "proc", 0, "") < 0)
783     die("Cannot mount proc: %m");
784
785   if (chroot("root") < 0)
786     die("Chroot failed: %m");
787
788   if (chdir("root/box") < 0)
789     die("Cannot change current directory: %m");
790 }
791
792 static int
793 box_inside(void *arg)
794 {
795   write_errors_to_fd = error_pipes[1];
796   close(error_pipes[0]);
797
798   char **argv = arg;
799   int argc = 0;
800   while (argv[argc])
801     argc++;
802
803   struct rlimit rl;
804   char *args[argc+1];
805
806   memcpy(args, argv, argc * sizeof(char *));
807   args[argc] = NULL;
808
809   cg_enter();
810   setup_root();
811
812   if (setresgid(BOX_GID, BOX_GID, BOX_GID) < 0)
813     die("setresgid: %m");
814   if (setgroups(0, NULL) < 0)
815     die("setgroups: %m");
816   if (setresuid(BOX_UID, BOX_UID, BOX_UID) < 0)
817     die("setresuid: %m");
818
819   if (redir_stdin)
820     {
821       close(0);
822       if (open(redir_stdin, O_RDONLY) != 0)
823         die("open(\"%s\"): %m", redir_stdin);
824     }
825   if (redir_stdout)
826     {
827       close(1);
828       if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
829         die("open(\"%s\"): %m", redir_stdout);
830     }
831   if (redir_stderr)
832     {
833       close(2);
834       if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
835         die("open(\"%s\"): %m", redir_stderr);
836     }
837   else
838     dup2(1, 2);
839   setpgrp();
840
841   if (memory_limit)
842     {
843       rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
844       if (setrlimit(RLIMIT_AS, &rl) < 0)
845         die("setrlimit(RLIMIT_AS): %m");
846     }
847
848   rl.rlim_cur = rl.rlim_max = (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY);
849   if (setrlimit(RLIMIT_STACK, &rl) < 0)
850     die("setrlimit(RLIMIT_STACK): %m");
851
852   rl.rlim_cur = rl.rlim_max = 64;
853   if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
854     die("setrlimit(RLIMIT_NOFILE): %m");
855
856   if (max_processes)
857     {
858       rl.rlim_cur = rl.rlim_max = max_processes;
859       if (setrlimit(RLIMIT_NPROC, &rl) < 0)
860         die("setrlimit(RLIMIT_NPROC): %m");
861     }
862
863   rl.rlim_cur = rl.rlim_max = 0;
864   if (setrlimit(RLIMIT_MEMLOCK, &rl) < 0)
865     die("setrlimit(RLIMIT_MEMLOCK): %m");
866
867   char **env = setup_environment();
868   execve(args[0], args, env);
869   die("execve(\"%s\"): %m", args[0]);
870 }
871
872 static void
873 init(void)
874 {
875   msg("Preparing sandbox directory\n");
876   xsystem("rm -rf box");
877   if (mkdir("box", 0700) < 0)
878     die("Cannot create box: %m");
879   if (chown("box", orig_uid, orig_gid) < 0)
880     die("Cannot chown box: %m");
881
882   cg_prepare();
883 }
884
885 static void
886 cleanup(void)
887 {
888   struct stat st;
889   if (stat("box", &st) < 0 || !S_ISDIR(st.st_mode))
890     die("Box directory not found, there isn't anything to clean up");
891
892   msg("Deleting sandbox directory\n");
893   xsystem("rm -rf box");
894   cg_remove();
895 }
896
897 static void
898 run(char **argv)
899 {
900   struct stat st;
901   if (stat("box", &st) < 0 || !S_ISDIR(st.st_mode))
902     die("Box directory not found, did you run `isolate --init'?");
903
904   char cmd[256];
905   snprintf(cmd, sizeof(cmd), "chown -R %d.%d box", BOX_UID, BOX_GID);
906   xsystem(cmd);
907   snprintf(cleanup_cmd, sizeof(cleanup_cmd), "chown -R %d.%d box", orig_uid, orig_gid);
908
909   if (pipe(error_pipes) < 0)
910     die("pipe: %m");
911   for (int i=0; i<2; i++)
912     if (fcntl(error_pipes[i], F_SETFD, fcntl(error_pipes[i], F_GETFD) | FD_CLOEXEC) < 0 ||
913         fcntl(error_pipes[i], F_SETFL, fcntl(error_pipes[i], F_GETFL) | O_NONBLOCK) < 0)
914       die("fcntl on pipe: %m");
915
916   box_pid = clone(
917     box_inside,                 // Function to execute as the body of the new process
918     argv,                       // Pass our stack
919     SIGCHLD | CLONE_NEWIPC | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWPID,
920     argv);                      // Pass the arguments
921   if (box_pid < 0)
922     die("clone: %m");
923   if (!box_pid)
924     die("clone returned 0");
925   box_keeper();
926 }
927
928 static void
929 show_version(void)
930 {
931   // FIXME
932   printf("Process isolator 0.0\n");
933   printf("(c) 2012 Martin Mares <mj@ucw.cz>\n\n");
934   printf("Sandbox directory: %s\n", BOX_DIR);
935   printf("Sandbox credentials: uid=%u gid=%u\n", BOX_UID, BOX_GID);
936 }
937
938 static void
939 usage(void)
940 {
941   fprintf(stderr, "Invalid arguments!\n");
942   printf("\
943 Usage: isolate [<options>] <command>\n\
944 \n\
945 Options:\n\
946 -c, --cg[=<parent>]\tPut process in a control group (optionally a sub-group of <parent>)\n\
947     --cg-mem=<size>\tLimit memory usage of the control group to <size> KB\n\
948     --cg-timing\t\tTime limits affects total run time of the control group\n\
949 -E, --env=<var>\tInherit the environment variable <var> from the parent process\n\
950 -E, --env=<var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
951 -x, --extra-time=<time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
952 \t\t\tso that its real execution time is reported (seconds, fractions allowed)\n\
953 -e, --full-env\t\tInherit full environment of the parent process\n\
954 -m, --mem=<size>\tLimit address space to <size> KB\n\
955 -M, --meta=<file>\tOutput process information to <file> (name:value)\n\
956 -k, --stack=<size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
957 -r, --stderr=<file>\tRedirect stderr to <file>\n\
958 -i, --stdin=<file>\tRedirect stdin from <file>\n\
959 -o, --stdout=<file>\tRedirect stdout to <file>\n\
960 -p, --processes[=<max>]\tEnable multiple processes (at most <max> of them); needs --cg\n\
961 -t, --time=<time>\tSet run time limit (seconds, fractions allowed)\n\
962 -v, --verbose\t\tBe verbose (use multiple times for even more verbosity)\n\
963 -w, --wall-time=<time>\tSet wall clock time limit (seconds, fractions allowed)\n\
964 \n\
965 Commands:\n\
966     --init\t\tInitialize sandbox (and its control group when --cg is used)\n\
967     --run -- <cmd> ...\tRun given command within sandbox\n\
968     --cleanup\t\tClean up sandbox\n\
969     --version\t\tDisplay program version and configuration\n\
970 ");
971   exit(2);
972 }
973
974 enum opt_code {
975   OPT_INIT = 256,
976   OPT_RUN,
977   OPT_CLEANUP,
978   OPT_VERSION,
979   OPT_CG_MEM,
980   OPT_CG_TIMING,
981 };
982
983 static const char short_opts[] = "c::eE:i:k:m:M:o:p::r:t:vw:x:";
984
985 static const struct option long_opts[] = {
986   { "cg",               2, NULL, 'c' },
987   { "cg-mem",           1, NULL, OPT_CG_MEM },
988   { "cg-timing",        0, NULL, OPT_CG_TIMING },
989   { "cleanup",          0, NULL, OPT_CLEANUP },
990   { "env",              1, NULL, 'E' },
991   { "extra-time",       1, NULL, 'x' },
992   { "full-env",         0, NULL, 'e' },
993   { "init",             0, NULL, OPT_INIT },
994   { "mem",              1, NULL, 'm' },
995   { "meta",             1, NULL, 'M' },
996   { "processes",        2, NULL, 'p' },
997   { "run",              0, NULL, OPT_RUN },
998   { "stack",            1, NULL, 'k' },
999   { "stderr",           1, NULL, 'r' },
1000   { "stdin",            1, NULL, 'i' },
1001   { "stdout",           1, NULL, 'o' },
1002   { "time",             1, NULL, 't' },
1003   { "verbose",          0, NULL, 'v' },
1004   { "version",          0, NULL, OPT_VERSION },
1005   { "wall-time",        1, NULL, 'w' },
1006   { NULL,               0, NULL, 0 }
1007 };
1008
1009 int
1010 main(int argc, char **argv)
1011 {
1012   int c;
1013   enum opt_code mode = 0;
1014
1015   while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) >= 0)
1016     switch (c)
1017       {
1018       case 'c':
1019         if (optarg)
1020           cg_root = optarg;
1021         cg_enable = 1;
1022         break;
1023       case 'e':
1024         pass_environ = 1;
1025         break;
1026       case 'E':
1027         if (!set_env_action(optarg))
1028           usage();
1029         break;
1030       case 'k':
1031         stack_limit = atoi(optarg);
1032         break;
1033       case 'i':
1034         redir_stdin = optarg;
1035         break;
1036       case 'm':
1037         memory_limit = atoi(optarg);
1038         break;
1039       case 'M':
1040         meta_open(optarg);
1041         break;
1042       case 'o':
1043         redir_stdout = optarg;
1044         break;
1045       case 'p':
1046         if (optarg)
1047           max_processes = atoi(optarg);
1048         else
1049           max_processes = 0;
1050         break;
1051       case 'r':
1052         redir_stderr = optarg;
1053         break;
1054       case 't':
1055         timeout = 1000*atof(optarg);
1056         break;
1057       case 'v':
1058         verbose++;
1059         break;
1060       case 'w':
1061         wall_timeout = 1000*atof(optarg);
1062         break;
1063       case 'x':
1064         extra_timeout = 1000*atof(optarg);
1065         break;
1066       case OPT_INIT:
1067       case OPT_RUN:
1068       case OPT_CLEANUP:
1069       case OPT_VERSION:
1070         mode = c;
1071         break;
1072       case OPT_CG_MEM:
1073         cg_memory_limit = atoi(optarg);
1074         break;
1075       case OPT_CG_TIMING:
1076         cg_timing = 1;
1077         break;
1078       default:
1079         usage();
1080       }
1081
1082   if (!mode)
1083     usage();
1084   if (mode == OPT_VERSION)
1085     {
1086       show_version();
1087       return 0;
1088     }
1089
1090   if (geteuid())
1091     die("Must be started as root");
1092   orig_uid = getuid();
1093   orig_gid = getgid();
1094
1095   umask(022);
1096   if (chdir(BOX_DIR) < 0)
1097     die("chdir(%s): %m", BOX_DIR);
1098   cg_init();
1099
1100   switch (mode)
1101     {
1102     case OPT_INIT:
1103       if (optind < argc)
1104         usage();
1105       init();
1106       break;
1107     case OPT_RUN:
1108       if (optind >= argc)
1109         usage();
1110       run(argv+optind);
1111       break;
1112     case OPT_CLEANUP:
1113       if (optind < argc)
1114         usage();
1115       cleanup();
1116       break;
1117     default:
1118       die("Internal error: mode mismatch");
1119     }
1120   exit(0);
1121 }