]> mj.ucw.cz Git - moe.git/blob - isolate.c
ea14aa9998ba4f6e79dd6a838104ad92b558af7b
[moe.git] / 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 /*** Utility functions ***/
236
237 static void *
238 xmalloc(size_t size)
239 {
240   void *p = malloc(size);
241   if (!p)
242     die("Out of memory");
243   return p;
244 }
245
246 static char *
247 xstrdup(char *str)
248 {
249   char *p = strdup(str);
250   if (!p)
251     die("Out of memory");
252   return p;
253 }
254
255 static int dir_exists(char *path)
256 {
257   struct stat st;
258   return (stat(path, &st) >= 0 && S_ISDIR(st.st_mode));
259 }
260
261 /*** Environment rules ***/
262
263 struct env_rule {
264   char *var;                    // Variable to match
265   char *val;                    // ""=clear, NULL=inherit
266   int var_len;
267   struct env_rule *next;
268 };
269
270 static struct env_rule *first_env_rule;
271 static struct env_rule **last_env_rule = &first_env_rule;
272
273 static struct env_rule default_env_rules[] = {
274   { "LIBC_FATAL_STDERR_", "1" }
275 };
276
277 static int
278 set_env_action(char *a0)
279 {
280   struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
281   char *a = (char *)(r+1);
282   strcpy(a, a0);
283
284   char *sep = strchr(a, '=');
285   if (sep == a)
286     return 0;
287   r->var = a;
288   if (sep)
289     {
290       *sep++ = 0;
291       r->val = sep;
292     }
293   else
294     r->val = NULL;
295   *last_env_rule = r;
296   last_env_rule = &r->next;
297   r->next = NULL;
298   return 1;
299 }
300
301 static int
302 match_env_var(char *env_entry, struct env_rule *r)
303 {
304   if (strncmp(env_entry, r->var, r->var_len))
305     return 0;
306   return (env_entry[r->var_len] == '=');
307 }
308
309 static void
310 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
311 {
312   // First remove the variable if already set
313   int pos = 0;
314   while (pos < *env_sizep && !match_env_var(env[pos], r))
315     pos++;
316   if (pos < *env_sizep)
317     {
318       (*env_sizep)--;
319       env[pos] = env[*env_sizep];
320       env[*env_sizep] = NULL;
321     }
322
323   // What is the new value?
324   char *new;
325   if (r->val)
326     {
327       if (!r->val[0])
328         return;
329       new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
330       sprintf(new, "%s=%s", r->var, r->val);
331     }
332   else
333     {
334       pos = 0;
335       while (environ[pos] && !match_env_var(environ[pos], r))
336         pos++;
337       if (!(new = environ[pos]))
338         return;
339     }
340
341   // Add it at the end of the array
342   env[(*env_sizep)++] = new;
343   env[*env_sizep] = NULL;
344 }
345
346 static char **
347 setup_environment(void)
348 {
349   // Link built-in rules with user rules
350   for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
351     {
352       default_env_rules[i].next = first_env_rule;
353       first_env_rule = &default_env_rules[i];
354     }
355
356   // Scan the original environment
357   char **orig_env = environ;
358   int orig_size = 0;
359   while (orig_env[orig_size])
360     orig_size++;
361
362   // For each rule, reserve one more slot and calculate length
363   int num_rules = 0;
364   for (struct env_rule *r = first_env_rule; r; r=r->next)
365     {
366       num_rules++;
367       r->var_len = strlen(r->var);
368     }
369
370   // Create a new environment
371   char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
372   int size;
373   if (pass_environ)
374     {
375       memcpy(env, environ, orig_size * sizeof(char *));
376       size = orig_size;
377     }
378   else
379     size = 0;
380   env[size] = NULL;
381
382   // Apply the rules one by one
383   for (struct env_rule *r = first_env_rule; r; r=r->next)
384     apply_env_rule(env, &size, r);
385
386   // Return the new env and pass some gossip
387   if (verbose > 1)
388     {
389       fprintf(stderr, "Passing environment:\n");
390       for (int i=0; env[i]; i++)
391         fprintf(stderr, "\t%s\n", env[i]);
392     }
393   return env;
394 }
395
396 /*** Mount rules ***/
397
398 struct dir_rule {
399   char *inside;                 // A relative path
400   char *outside;                // This can be an absolute path or a relative path starting with "./"
401   unsigned int flags;           // DIR_FLAG_xxx
402   struct dir_rule *next;
403 };
404
405 enum dir_rule_flags {
406   DIR_FLAG_RW = 1,
407   DIR_FLAG_NOEXEC = 2,
408   DIR_FLAG_FS = 4,
409   DIR_FLAG_MAYBE = 8,
410 };
411
412 static struct dir_rule *first_dir_rule;
413 static struct dir_rule **last_dir_rule = &first_dir_rule;
414
415 static int add_dir_rule(char *in, char *out, unsigned int flags)
416 {
417   // Make sure that "in" is relative
418   while (in[0] == '/')
419     in++;
420   if (!*in)
421     return 0;
422
423   // Check "out"
424   if (flags & DIR_FLAG_FS)
425     {
426       if (!out || out[0] == '/')
427         return 0;
428     }
429   else
430     {
431       if (out && out[0] != '/' && strncmp(out, "./", 2))
432         return 0;
433     }
434
435   // Override an existing rule
436   struct dir_rule *r;
437   for (r = first_dir_rule; r; r=r->next)
438     if (!strcmp(r->inside, in))
439       break;
440
441   // Add a new rule
442   if (!r)
443     {
444       struct dir_rule *r = xmalloc(sizeof(*r));
445       r->inside = in;
446       *last_dir_rule = r;
447       last_dir_rule = &r->next;
448       r->next = NULL;
449     }
450   r->outside = out;
451   r->flags = flags;
452   return 1;
453 }
454
455 static unsigned int parse_dir_option(char *opt)
456 {
457   if (!strcmp(opt, "rw"))
458     return DIR_FLAG_RW;
459   if (!strcmp(opt, "noexec"))
460     return DIR_FLAG_NOEXEC;
461   if (!strcmp(opt, "fs"))
462     return DIR_FLAG_FS;
463   if (!strcmp(opt, "maybe"))
464     return DIR_FLAG_MAYBE;
465   die("Unknown directory option %s", opt);
466 }
467
468 static int set_dir_action(char *arg)
469 {
470   arg = xstrdup(arg);
471
472   char *colon = strchr(arg, ':');
473   unsigned int flags = 0;
474   while (colon)
475     {
476       char *opt = colon + 1;
477       char *next = strchr(opt, ':');
478       if (next)
479         *next = 0;
480       flags |= parse_dir_option(opt);
481       colon = next;
482     }
483
484   char *eq = strchr(arg, '=');
485   if (eq)
486     {
487       *eq++ = 0;
488       return add_dir_rule(arg, (*eq ? eq : NULL), flags);
489     }
490   else
491     {
492       char *out = xmalloc(1 + strlen(arg) + 1);
493       sprintf(out, "/%s", arg);
494       return add_dir_rule(arg, out, flags);
495     }
496 }
497
498 static void init_dir_rules(void)
499 {
500   set_dir_action("box=./box:rw");
501   set_dir_action("bin");
502   set_dir_action("dev");
503   set_dir_action("lib");
504   set_dir_action("lib64:maybe");
505   set_dir_action("proc=proc:fs");
506   set_dir_action("usr");
507 }
508
509 static void make_dir(char *path)
510 {
511   char *sep = path;
512   for (;;)
513     {
514       sep = strchr(sep, '/');
515       if (sep)
516         *sep = 0;
517
518       if (!dir_exists(path) && mkdir(path, 0777) < 0)
519         die("Cannot create directory %s: %m\n", path);
520
521       if (!sep)
522         return;
523       *sep++ = '/';
524     }
525 }
526
527 static void apply_dir_rules(void)
528 {
529   for (struct dir_rule *r = first_dir_rule; r; r=r->next)
530     {
531       char *in = r->inside;
532       char *out = r->outside;
533       if (!out)
534         {
535           msg("Not binding anything on %s\n", r->inside);
536           continue;
537         }
538
539       if ((r->flags & DIR_FLAG_MAYBE) && !dir_exists(out))
540         {
541           msg("Not binding %s on %s (does not exist)\n", out, r->inside);
542           continue;
543         }
544
545       char root_in[1024];
546       snprintf(root_in, sizeof(root_in), "root/%s", in);
547       make_dir(root_in);
548
549       unsigned long mount_flags = 0;
550       if (!(r->flags & DIR_FLAG_RW))
551         mount_flags |= MS_RDONLY;
552       if (r->flags & DIR_FLAG_NOEXEC)
553         mount_flags |= MS_NOEXEC;
554
555       if (r->flags & DIR_FLAG_FS)
556         {
557           msg("Mounting %s on %s\n", out, in);
558           if (mount("none", root_in, out, mount_flags, "") < 0)
559             die("Cannot mount %s on %s: %m", out, in);
560         }
561       else
562         {
563           msg("Binding %s on %s\n", out, in);
564           if (mount(out, root_in, "none", MS_BIND | MS_NOSUID | MS_NODEV | mount_flags, "") < 0)
565             die("Cannot bind %s on %s: %m", out, in);
566         }
567     }
568 }
569
570 /*** Control groups ***/
571
572 static char cg_path[256];
573
574 #define CG_BUFSIZE 1024
575
576 static int
577 cg_read(char *attr, char *buf)
578 {
579   int maybe = 0;
580   if (attr[0] == '?')
581     {
582       attr++;
583       maybe = 1;
584     }
585
586   char path[256];
587   snprintf(path, sizeof(path), "%s/%s", cg_path, attr);
588
589   int fd = open(path, O_RDONLY);
590   if (fd < 0)
591     {
592       if (maybe)
593         return 0;
594       die("Cannot read %s: %m", path);
595     }
596
597   int n = read(fd, buf, CG_BUFSIZE);
598   if (n < 0)
599     die("Cannot read %s: %m", path);
600   if (n >= CG_BUFSIZE - 1)
601     die("Attribute %s too long", path);
602   if (n > 0 && buf[n-1] == '\n')
603     n--;
604   buf[n] = 0;
605
606   if (verbose > 1)
607     msg("CG: Read %s = %s\n", attr, buf);
608
609   close(fd);
610   return 1;
611 }
612
613 static void __attribute__((format(printf,2,3)))
614 cg_write(char *attr, char *fmt, ...)
615 {
616   va_list args;
617   va_start(args, fmt);
618
619   char buf[CG_BUFSIZE];
620   int n = vsnprintf(buf, sizeof(buf), fmt, args);
621   if (n >= CG_BUFSIZE)
622     die("cg_writef: Value for attribute %s is too long", attr);
623
624   if (verbose > 1)
625     msg("CG: Write %s = %s", attr, buf);
626
627   char path[256];
628   snprintf(path, sizeof(path), "%s/%s", cg_path, attr);
629
630   int fd = open(path, O_WRONLY | O_TRUNC);
631   if (fd < 0)
632     die("Cannot write %s: %m", path);
633
634   int written = write(fd, buf, n);
635   if (written < 0)
636     die("Cannot set %s to %s: %m", path, buf);
637   if (written != n)
638     die("Short write to %s (%d out of %d bytes)", path, written, n);
639
640   close(fd);
641   va_end(args);
642 }
643
644 static void
645 cg_init(void)
646 {
647   if (!cg_enable)
648     return;
649
650   if (!dir_exists(cg_root))
651     die("Control group filesystem at %s not mounted", cg_root);
652
653   snprintf(cg_path, sizeof(cg_path), "%s/box-%d", cg_root, BOX_UID);
654   msg("Using control group %s\n", cg_path);
655 }
656
657 static void
658 cg_prepare(void)
659 {
660   if (!cg_enable)
661     return;
662
663   struct stat st;
664   char buf[CG_BUFSIZE];
665
666   if (stat(cg_path, &st) >= 0 || errno != ENOENT)
667     {
668       msg("Control group %s already exists, trying to empty it.\n", cg_path);
669       if (rmdir(cg_path) < 0)
670         die("Failed to reset control group %s: %m", cg_path);
671     }
672
673   if (mkdir(cg_path, 0777) < 0)
674     die("Failed to create control group %s: %m", cg_path);
675
676   // If cpuset module is enabled, copy allowed cpus and memory nodes from parent group
677   if (cg_read("?../cpuset.cpus", buf))
678     cg_write("cpuset.cpus", "%s", buf);
679   if (cg_read("?../cpuset.mems", buf))
680     cg_write("cpuset.mems", "%s", buf);
681 }
682
683 static void
684 cg_enter(void)
685 {
686   if (!cg_enable)
687     return;
688
689   msg("Entering control group %s\n", cg_path);
690
691   struct stat st;
692   if (stat(cg_path, &st) < 0)
693     die("Control group %s does not exist: %m", cg_path);
694
695   if (cg_memory_limit)
696     {
697       cg_write("memory.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
698       cg_write("memory.memsw.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
699     }
700
701   if (cg_timing)
702     cg_write("cpuacct.usage", "0\n");
703
704   cg_write("tasks", "%d\n", (int) getpid());
705 }
706
707 static int
708 cg_get_run_time_ms(void)
709 {
710   if (!cg_enable)
711     return 0;
712
713   char buf[CG_BUFSIZE];
714   cg_read("cpuacct.usage", buf);
715   unsigned long long ns = atoll(buf);
716   return ns / 1000000;
717 }
718
719 static void
720 cg_stats(void)
721 {
722   if (!cg_enable)
723     return;
724
725   char buf[CG_BUFSIZE];
726
727   // Memory usage statistics
728   unsigned long long mem=0, memsw=0;
729   if (cg_read("?memory.max_usage_in_bytes", buf))
730     mem = atoll(buf);
731   if (cg_read("?memory.memsw.max_usage_in_bytes", buf))
732     {
733       memsw = atoll(buf);
734       if (memsw > mem)
735         mem = memsw;
736     }
737   if (mem)
738     meta_printf("cg-mem:%lld\n", mem >> 10);
739 }
740
741 static void
742 cg_remove(void)
743 {
744   char buf[CG_BUFSIZE];
745
746   if (!cg_enable)
747     return;
748
749   cg_read("tasks", buf);
750   if (buf[0])
751     die("Some tasks left in control group %s, failed to remove it", cg_path);
752
753   if (rmdir(cg_path) < 0)
754     die("Cannot remove control group %s: %m", cg_path);
755 }
756
757 /*** The keeper process ***/
758
759 static void
760 signal_alarm(int unused UNUSED)
761 {
762   /* Time limit checks are synchronous, so we only schedule them there. */
763   timer_tick = 1;
764   alarm(1);
765 }
766
767 static void
768 signal_int(int unused UNUSED)
769 {
770   /* Interrupts are fatal, so no synchronization requirements. */
771   meta_printf("exitsig:%d\n", SIGINT);
772   err("SG: Interrupted");
773 }
774
775 #define PROC_BUF_SIZE 4096
776 static void
777 read_proc_file(char *buf, char *name, int *fdp)
778 {
779   int c;
780
781   if (!*fdp)
782     {
783       sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
784       *fdp = open(buf, O_RDONLY);
785       if (*fdp < 0)
786         die("open(%s): %m", buf);
787     }
788   lseek(*fdp, 0, SEEK_SET);
789   if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
790     die("read on /proc/$pid/%s: %m", name);
791   if (c >= PROC_BUF_SIZE-1)
792     die("/proc/$pid/%s too long", name);
793   buf[c] = 0;
794 }
795
796 static int
797 get_wall_time_ms(void)
798 {
799   struct timeval now, wall;
800   gettimeofday(&now, NULL);
801   timersub(&now, &start_time, &wall);
802   return wall.tv_sec*1000 + wall.tv_usec/1000;
803 }
804
805 static int
806 get_run_time_ms(struct rusage *rus)
807 {
808   if (cg_timing)
809     return cg_get_run_time_ms();
810
811   if (rus)
812     {
813       struct timeval total;
814       timeradd(&rus->ru_utime, &rus->ru_stime, &total);
815       return total.tv_sec*1000 + total.tv_usec/1000;
816     }
817
818   char buf[PROC_BUF_SIZE], *x;
819   int utime, stime;
820   static int proc_stat_fd;
821
822   read_proc_file(buf, "stat", &proc_stat_fd);
823   x = buf;
824   while (*x && *x != ' ')
825     x++;
826   while (*x == ' ')
827     x++;
828   if (*x++ != '(')
829     die("proc stat syntax error 1");
830   while (*x && (*x != ')' || x[1] != ' '))
831     x++;
832   while (*x == ')' || *x == ' ')
833     x++;
834   if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
835     die("proc stat syntax error 2");
836
837   return (utime + stime) * 1000 / ticks_per_sec;
838 }
839
840 static void
841 check_timeout(void)
842 {
843   if (wall_timeout)
844     {
845       int wall_ms = get_wall_time_ms();
846       if (wall_ms > wall_timeout)
847         err("TO: Time limit exceeded (wall clock)");
848       if (verbose > 1)
849         fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
850     }
851   if (timeout)
852     {
853       int ms = get_run_time_ms(NULL);
854       if (verbose > 1)
855         fprintf(stderr, "[time check: %d msec]\n", ms);
856       if (ms > timeout && ms > extra_timeout)
857         err("TO: Time limit exceeded");
858     }
859 }
860
861 static void
862 box_keeper(void)
863 {
864   read_errors_from_fd = error_pipes[0];
865   close(error_pipes[1]);
866
867   struct sigaction sa;
868   bzero(&sa, sizeof(sa));
869   sa.sa_handler = signal_int;
870   sigaction(SIGINT, &sa, NULL);
871
872   gettimeofday(&start_time, NULL);
873   ticks_per_sec = sysconf(_SC_CLK_TCK);
874   if (ticks_per_sec <= 0)
875     die("Invalid ticks_per_sec!");
876
877   if (timeout || wall_timeout)
878     {
879       sa.sa_handler = signal_alarm;
880       sigaction(SIGALRM, &sa, NULL);
881       alarm(1);
882     }
883
884   for(;;)
885     {
886       struct rusage rus;
887       int stat;
888       pid_t p;
889       if (timer_tick)
890         {
891           check_timeout();
892           timer_tick = 0;
893         }
894       p = wait4(box_pid, &stat, 0, &rus);
895       if (p < 0)
896         {
897           if (errno == EINTR)
898             continue;
899           die("wait4: %m");
900         }
901       if (p != box_pid)
902         die("wait4: unknown pid %d exited!", p);
903       box_pid = 0;
904
905       // Check error pipe if there is an internal error passed from inside the box
906       char interr[1024];
907       int n = read(read_errors_from_fd, interr, sizeof(interr) - 1);
908       if (n > 0)
909         {
910           interr[n] = 0;
911           die("%s", interr);
912         }
913
914       if (WIFEXITED(stat))
915         {
916           final_stats(&rus);
917           if (WEXITSTATUS(stat))
918             {
919               meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
920               err("RE: Exited with error status %d", WEXITSTATUS(stat));
921             }
922           if (timeout && total_ms > timeout)
923             err("TO: Time limit exceeded");
924           if (wall_timeout && wall_ms > wall_timeout)
925             err("TO: Time limit exceeded (wall clock)");
926           flush_line();
927           fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall)\n",
928               total_ms/1000, total_ms%1000,
929               wall_ms/1000, wall_ms%1000);
930           box_exit(0);
931         }
932       else if (WIFSIGNALED(stat))
933         {
934           meta_printf("exitsig:%d\n", WTERMSIG(stat));
935           final_stats(&rus);
936           err("SG: Caught fatal signal %d", WTERMSIG(stat));
937         }
938       else if (WIFSTOPPED(stat))
939         {
940           meta_printf("exitsig:%d\n", WSTOPSIG(stat));
941           final_stats(&rus);
942           err("SG: Stopped by signal %d", WSTOPSIG(stat));
943         }
944       else
945         die("wait4: unknown status %x, giving up!", stat);
946     }
947 }
948
949 /*** The process running inside the box ***/
950
951 static void
952 setup_root(void)
953 {
954   if (mkdir("root", 0750) < 0 && errno != EEXIST)
955     die("mkdir('root'): %m");
956
957   if (mount("none", "root", "tmpfs", 0, "mode=755") < 0)
958     die("Cannot mount root ramdisk: %m");
959
960   apply_dir_rules();
961
962   if (chroot("root") < 0)
963     die("Chroot failed: %m");
964
965   if (chdir("root/box") < 0)
966     die("Cannot change current directory: %m");
967 }
968
969 static void
970 setup_credentials(void)
971 {
972   if (setresgid(BOX_GID, BOX_GID, BOX_GID) < 0)
973     die("setresgid: %m");
974   if (setgroups(0, NULL) < 0)
975     die("setgroups: %m");
976   if (setresuid(BOX_UID, BOX_UID, BOX_UID) < 0)
977     die("setresuid: %m");
978   setpgrp();
979 }
980
981 static void
982 setup_fds(void)
983 {
984   if (redir_stdin)
985     {
986       close(0);
987       if (open(redir_stdin, O_RDONLY) != 0)
988         die("open(\"%s\"): %m", redir_stdin);
989     }
990   if (redir_stdout)
991     {
992       close(1);
993       if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
994         die("open(\"%s\"): %m", redir_stdout);
995     }
996   if (redir_stderr)
997     {
998       close(2);
999       if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
1000         die("open(\"%s\"): %m", redir_stderr);
1001     }
1002   else
1003     dup2(1, 2);
1004 }
1005
1006 static void
1007 setup_rlim(const char *res_name, int res, rlim_t limit)
1008 {
1009   struct rlimit rl = { .rlim_cur = limit, .rlim_max = limit };
1010   if (setrlimit(res, &rl) < 0)
1011     die("setrlimit(%s, %jd)", res_name, (intmax_t) limit);
1012 }
1013
1014 static void
1015 setup_rlimits(void)
1016 {
1017 #define RLIM(res, val) setup_rlim("RLIMIT_" #res, RLIMIT_##res, val)
1018
1019   if (memory_limit)
1020     RLIM(AS, memory_limit * 1024);
1021
1022   RLIM(STACK, (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY));
1023   RLIM(NOFILE, 64);
1024   RLIM(MEMLOCK, 0);
1025
1026   if (max_processes)
1027     RLIM(NPROC, max_processes);
1028
1029 #undef RLIM
1030 }
1031
1032 static int
1033 box_inside(void *arg)
1034 {
1035   char **args = arg;
1036   write_errors_to_fd = error_pipes[1];
1037   close(error_pipes[0]);
1038
1039   cg_enter();
1040   setup_root();
1041   setup_credentials();
1042   setup_fds();
1043   setup_rlimits();
1044   char **env = setup_environment();
1045
1046   execve(args[0], args, env);
1047   die("execve(\"%s\"): %m", args[0]);
1048 }
1049
1050 /*** Commands ***/
1051
1052 static void
1053 init(void)
1054 {
1055   msg("Preparing sandbox directory\n");
1056   xsystem("rm -rf box");
1057   if (mkdir("box", 0700) < 0)
1058     die("Cannot create box: %m");
1059   if (chown("box", orig_uid, orig_gid) < 0)
1060     die("Cannot chown box: %m");
1061
1062   cg_prepare();
1063 }
1064
1065 static void
1066 cleanup(void)
1067 {
1068   if (!dir_exists("box"))
1069     die("Box directory not found, there isn't anything to clean up");
1070
1071   msg("Deleting sandbox directory\n");
1072   xsystem("rm -rf box");
1073   cg_remove();
1074 }
1075
1076 static void
1077 run(char **argv)
1078 {
1079   if (!dir_exists("box"))
1080     die("Box directory not found, did you run `isolate --init'?");
1081
1082   char cmd[256];
1083   snprintf(cmd, sizeof(cmd), "chown -R %d.%d box", BOX_UID, BOX_GID);
1084   xsystem(cmd);
1085   snprintf(cleanup_cmd, sizeof(cleanup_cmd), "chown -R %d.%d box", orig_uid, orig_gid);
1086
1087   if (pipe(error_pipes) < 0)
1088     die("pipe: %m");
1089   for (int i=0; i<2; i++)
1090     if (fcntl(error_pipes[i], F_SETFD, fcntl(error_pipes[i], F_GETFD) | FD_CLOEXEC) < 0 ||
1091         fcntl(error_pipes[i], F_SETFL, fcntl(error_pipes[i], F_GETFL) | O_NONBLOCK) < 0)
1092       die("fcntl on pipe: %m");
1093
1094   box_pid = clone(
1095     box_inside,                 // Function to execute as the body of the new process
1096     argv,                       // Pass our stack
1097     SIGCHLD | CLONE_NEWIPC | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWPID,
1098     argv);                      // Pass the arguments
1099   if (box_pid < 0)
1100     die("clone: %m");
1101   if (!box_pid)
1102     die("clone returned 0");
1103   box_keeper();
1104 }
1105
1106 static void
1107 show_version(void)
1108 {
1109   printf("Process isolator 1.0\n");
1110   printf("(c) 2012 Martin Mares and Bernard Blackham\n");
1111   printf("\nCompile-time configuration:\n");
1112   printf("Sandbox directory: %s\n", BOX_DIR);
1113   printf("Sandbox credentials: uid=%u gid=%u\n", BOX_UID, BOX_GID);
1114 }
1115
1116 /*** Options ***/
1117
1118 static void
1119 usage(void)
1120 {
1121   fprintf(stderr, "Invalid arguments!\n");
1122   printf("\
1123 Usage: isolate [<options>] <command>\n\
1124 \n\
1125 Options:\n\
1126 -c, --cg[=<parent>]\tPut process in a control group (optionally a sub-group of <parent>)\n\
1127     --cg-mem=<size>\tLimit memory usage of the control group to <size> KB\n\
1128     --cg-timing\t\tTime limits affects total run time of the control group\n\
1129 -d, --dir=<dir>\t\tMake a directory <dir> visible inside the sandbox\n\
1130     --dir=<in>=<out>\tMake a directory <out> outside visible as <in> inside\n\
1131     --dir=<in>=\t\tDelete a previously defined directory rule (even a default one)\n\
1132     --dir=...:<opt>\tSpecify options for a rule: rw, noexec, fs, maybe\n\
1133 -E, --env=<var>\t\tInherit the environment variable <var> from the parent process\n\
1134 -E, --env=<var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
1135 -x, --extra-time=<time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
1136 \t\t\tso that its real execution time is reported (seconds, fractions allowed)\n\
1137 -e, --full-env\t\tInherit full environment of the parent process\n\
1138 -m, --mem=<size>\tLimit address space to <size> KB\n\
1139 -M, --meta=<file>\tOutput process information to <file> (name:value)\n\
1140 -k, --stack=<size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
1141 -r, --stderr=<file>\tRedirect stderr to <file>\n\
1142 -i, --stdin=<file>\tRedirect stdin from <file>\n\
1143 -o, --stdout=<file>\tRedirect stdout to <file>\n\
1144 -p, --processes[=<max>]\tEnable multiple processes (at most <max> of them); needs --cg\n\
1145 -t, --time=<time>\tSet run time limit (seconds, fractions allowed)\n\
1146 -v, --verbose\t\tBe verbose (use multiple times for even more verbosity)\n\
1147 -w, --wall-time=<time>\tSet wall clock time limit (seconds, fractions allowed)\n\
1148 \n\
1149 Commands:\n\
1150     --init\t\tInitialize sandbox (and its control group when --cg is used)\n\
1151     --run -- <cmd> ...\tRun given command within sandbox\n\
1152     --cleanup\t\tClean up sandbox\n\
1153     --version\t\tDisplay program version and configuration\n\
1154 ");
1155   exit(2);
1156 }
1157
1158 enum opt_code {
1159   OPT_INIT = 256,
1160   OPT_RUN,
1161   OPT_CLEANUP,
1162   OPT_VERSION,
1163   OPT_CG_MEM,
1164   OPT_CG_TIMING,
1165 };
1166
1167 static const char short_opts[] = "c::d:eE:i:k:m:M:o:p::r:t:vw:x:";
1168
1169 static const struct option long_opts[] = {
1170   { "cg",               2, NULL, 'c' },
1171   { "cg-mem",           1, NULL, OPT_CG_MEM },
1172   { "cg-timing",        0, NULL, OPT_CG_TIMING },
1173   { "cleanup",          0, NULL, OPT_CLEANUP },
1174   { "dir",              1, NULL, 'd' },
1175   { "env",              1, NULL, 'E' },
1176   { "extra-time",       1, NULL, 'x' },
1177   { "full-env",         0, NULL, 'e' },
1178   { "init",             0, NULL, OPT_INIT },
1179   { "mem",              1, NULL, 'm' },
1180   { "meta",             1, NULL, 'M' },
1181   { "processes",        2, NULL, 'p' },
1182   { "run",              0, NULL, OPT_RUN },
1183   { "stack",            1, NULL, 'k' },
1184   { "stderr",           1, NULL, 'r' },
1185   { "stdin",            1, NULL, 'i' },
1186   { "stdout",           1, NULL, 'o' },
1187   { "time",             1, NULL, 't' },
1188   { "verbose",          0, NULL, 'v' },
1189   { "version",          0, NULL, OPT_VERSION },
1190   { "wall-time",        1, NULL, 'w' },
1191   { NULL,               0, NULL, 0 }
1192 };
1193
1194 int
1195 main(int argc, char **argv)
1196 {
1197   int c;
1198   enum opt_code mode = 0;
1199
1200   init_dir_rules();
1201
1202   while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) >= 0)
1203     switch (c)
1204       {
1205       case 'c':
1206         if (optarg)
1207           cg_root = optarg;
1208         cg_enable = 1;
1209         break;
1210       case 'd':
1211         if (!set_dir_action(optarg))
1212           usage();
1213         break;
1214       case 'e':
1215         pass_environ = 1;
1216         break;
1217       case 'E':
1218         if (!set_env_action(optarg))
1219           usage();
1220         break;
1221       case 'k':
1222         stack_limit = atoi(optarg);
1223         break;
1224       case 'i':
1225         redir_stdin = optarg;
1226         break;
1227       case 'm':
1228         memory_limit = atoi(optarg);
1229         break;
1230       case 'M':
1231         meta_open(optarg);
1232         break;
1233       case 'o':
1234         redir_stdout = optarg;
1235         break;
1236       case 'p':
1237         if (optarg)
1238           max_processes = atoi(optarg);
1239         else
1240           max_processes = 0;
1241         break;
1242       case 'r':
1243         redir_stderr = optarg;
1244         break;
1245       case 't':
1246         timeout = 1000*atof(optarg);
1247         break;
1248       case 'v':
1249         verbose++;
1250         break;
1251       case 'w':
1252         wall_timeout = 1000*atof(optarg);
1253         break;
1254       case 'x':
1255         extra_timeout = 1000*atof(optarg);
1256         break;
1257       case OPT_INIT:
1258       case OPT_RUN:
1259       case OPT_CLEANUP:
1260       case OPT_VERSION:
1261         mode = c;
1262         break;
1263       case OPT_CG_MEM:
1264         cg_memory_limit = atoi(optarg);
1265         break;
1266       case OPT_CG_TIMING:
1267         cg_timing = 1;
1268         break;
1269       default:
1270         usage();
1271       }
1272
1273   if (!mode)
1274     usage();
1275   if (mode == OPT_VERSION)
1276     {
1277       show_version();
1278       return 0;
1279     }
1280
1281   if (geteuid())
1282     die("Must be started as root");
1283   orig_uid = getuid();
1284   orig_gid = getgid();
1285
1286   umask(022);
1287   if (chdir(BOX_DIR) < 0)
1288     die("chdir(%s): %m", BOX_DIR);
1289   cg_init();
1290
1291   switch (mode)
1292     {
1293     case OPT_INIT:
1294       if (optind < argc)
1295         usage();
1296       init();
1297       break;
1298     case OPT_RUN:
1299       if (optind >= argc)
1300         usage();
1301       run(argv+optind);
1302       break;
1303     case OPT_CLEANUP:
1304       if (optind < argc)
1305         usage();
1306       cleanup();
1307       break;
1308     default:
1309       die("Internal error: mode mismatch");
1310     }
1311   exit(0);
1312 }