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