]> mj.ucw.cz Git - moe.git/blob - isolate/isolate.c
Isolate: Introduce directory rules
[moe.git] / isolate / isolate.c
1 /*
2  *      A Process Isolator based on Linux Containers
3  *
4  *      (c) 2012 Martin Mares <mj@ucw.cz>
5  *      (c) 2012 Bernard Blackham <bernard@blackham.com.au>
6  */
7
8 #define _GNU_SOURCE
9
10 #include "autoconf.h"
11
12 #include <errno.h>
13 #include <stdio.h>
14 #include <fcntl.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <stdarg.h>
18 #include <stdint.h>
19 #include <unistd.h>
20 #include <getopt.h>
21 #include <sched.h>
22 #include <time.h>
23 #include <grp.h>
24 #include <sys/wait.h>
25 #include <sys/time.h>
26 #include <sys/signal.h>
27 #include <sys/resource.h>
28 #include <sys/mount.h>
29 #include <sys/stat.h>
30
31 #define NONRET __attribute__((noreturn))
32 #define UNUSED __attribute__((unused))
33 #define ARRAY_SIZE(a) (int)(sizeof(a)/sizeof(a[0]))
34
35 #define BOX_DIR CONFIG_ISOLATE_BOX_DIR
36 #define BOX_UID CONFIG_ISOLATE_BOX_UID
37 #define BOX_GID CONFIG_ISOLATE_BOX_GID
38
39 static int timeout;                     /* milliseconds */
40 static int wall_timeout;
41 static int extra_timeout;
42 static int pass_environ;
43 static int verbose;
44 static int memory_limit;
45 static int stack_limit;
46 static int max_processes = 1;
47 static char *redir_stdin, *redir_stdout, *redir_stderr;
48
49 static int cg_enable;
50 static int cg_memory_limit;
51 static int cg_timing;
52 static char *cg_root = "/sys/fs/cgroup";
53
54 static uid_t orig_uid;
55 static gid_t orig_gid;
56
57 static pid_t box_pid;
58 static int partial_line;
59 static char cleanup_cmd[256];
60
61 static struct timeval start_time;
62 static int ticks_per_sec;
63 static int total_ms, wall_ms;
64 static volatile sig_atomic_t timer_tick;
65
66 static int error_pipes[2];
67 static int write_errors_to_fd;
68 static int read_errors_from_fd;
69
70 static void die(char *msg, ...) NONRET;
71 static void cg_stats(void);
72 static int get_wall_time_ms(void);
73 static int get_run_time_ms(struct rusage *rus);
74
75 /*** Meta-files ***/
76
77 static FILE *metafile;
78
79 static void
80 meta_open(const char *name)
81 {
82   if (!strcmp(name, "-"))
83     {
84       metafile = stdout;
85       return;
86     }
87   metafile = fopen(name, "w");
88   if (!metafile)
89     die("Failed to open metafile '%s'",name);
90 }
91
92 static void
93 meta_close(void)
94 {
95   if (metafile && metafile != stdout)
96     fclose(metafile);
97 }
98
99 static void __attribute__((format(printf,1,2)))
100 meta_printf(const char *fmt, ...)
101 {
102   if (!metafile)
103     return;
104
105   va_list args;
106   va_start(args, fmt);
107   vfprintf(metafile, fmt, args);
108   va_end(args);
109 }
110
111 static void
112 final_stats(struct rusage *rus)
113 {
114   total_ms = get_run_time_ms(rus);
115   wall_ms = get_wall_time_ms();
116
117   meta_printf("time:%d.%03d\n", total_ms/1000, total_ms%1000);
118   meta_printf("time-wall:%d.%03d\n", wall_ms/1000, wall_ms%1000);
119   meta_printf("max-rss:%ld\n", rus->ru_maxrss);
120   meta_printf("csw-voluntary:%ld\n", rus->ru_nvcsw);
121   meta_printf("csw-forced:%ld\n", rus->ru_nivcsw);
122
123   cg_stats();
124 }
125
126 /*** Messages and exits ***/
127
128 static void
129 xsystem(const char *cmd)
130 {
131   int ret = system(cmd);
132   if (ret < 0)
133     die("system(\"%s\"): %m", cmd);
134   if (!WIFEXITED(ret) || WEXITSTATUS(ret))
135     die("system(\"%s\"): Exited with status %d", cmd, ret);
136 }
137
138 static void NONRET
139 box_exit(int rc)
140 {
141   if (box_pid > 0)
142     {
143       kill(-box_pid, SIGKILL);
144       kill(box_pid, SIGKILL);
145       meta_printf("killed:1\n");
146
147       struct rusage rus;
148       int p, stat;
149       do
150         p = wait4(box_pid, &stat, 0, &rus);
151       while (p < 0 && errno == EINTR);
152       if (p < 0)
153         fprintf(stderr, "UGH: Lost track of the process (%m)\n");
154       else
155         final_stats(&rus);
156     }
157
158   if (rc < 2 && cleanup_cmd[0])
159     xsystem(cleanup_cmd);
160
161   meta_close();
162   exit(rc);
163 }
164
165 static void
166 flush_line(void)
167 {
168   if (partial_line)
169     fputc('\n', stderr);
170   partial_line = 0;
171 }
172
173 /* Report an error of the sandbox itself */
174 static void NONRET __attribute__((format(printf,1,2)))
175 die(char *msg, ...)
176 {
177   va_list args;
178   va_start(args, msg);
179   char buf[1024];
180   int n = vsnprintf(buf, sizeof(buf), msg, args);
181
182   if (write_errors_to_fd)
183     {
184       // We are inside the box, have to use error pipe for error reporting.
185       // We hope that the whole error message fits in PIPE_BUF bytes.
186       write(write_errors_to_fd, buf, n);
187       exit(2);
188     }
189
190   // Otherwise, we in the box keeper process, so we report errors normally
191   flush_line();
192   meta_printf("status:XX\nmessage:%s\n", buf);
193   fputs(buf, stderr);
194   fputc('\n', stderr);
195   box_exit(2);
196 }
197
198 /* Report an error of the program inside the sandbox */
199 static void NONRET __attribute__((format(printf,1,2)))
200 err(char *msg, ...)
201 {
202   va_list args;
203   va_start(args, msg);
204   flush_line();
205   if (msg[0] && msg[1] && msg[2] == ':' && msg[3] == ' ')
206     {
207       meta_printf("status:%c%c\n", msg[0], msg[1]);
208       msg += 4;
209     }
210   char buf[1024];
211   vsnprintf(buf, sizeof(buf), msg, args);
212   meta_printf("message:%s\n", buf);
213   fputs(buf, stderr);
214   fputc('\n', stderr);
215   box_exit(1);
216 }
217
218 /* Write a message, but only if in verbose mode */
219 static void __attribute__((format(printf,1,2)))
220 msg(char *msg, ...)
221 {
222   va_list args;
223   va_start(args, msg);
224   if (verbose)
225     {
226       int len = strlen(msg);
227       if (len > 0)
228         partial_line = (msg[len-1] != '\n');
229       vfprintf(stderr, msg, args);
230       fflush(stderr);
231     }
232   va_end(args);
233 }
234
235 /*** 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:
401                                 //   - an absolute path
402                                 //   - a relative path starting with "./"
403                                 //   - one of the above prefixed with "?" to mean "only if exists"
404                                 //   - "procfs"
405   struct dir_rule *next;
406 };
407
408 static struct dir_rule *first_dir_rule;
409 static struct dir_rule **last_dir_rule = &first_dir_rule;
410
411 static int add_dir_rule(char *in, char *out)
412 {
413   // Make sure that "in" is relative
414   while (in[0] == '/')
415     in++;
416   if (!*in)
417     return 0;
418
419   // Check "out"
420   if (out)
421     {
422       char *o = out;
423       if (*o == '?')
424         o++;
425       if (!(o[0] == '/' ||
426             !strncmp(o, "./", 2) ||
427             !strcmp(o, "procfs")))
428         return 0;
429     }
430
431   // Override an existing rule
432   for (struct dir_rule *r = first_dir_rule; r; r=r->next)
433     if (!strcmp(r->inside, in))
434       {
435         r->outside = out;
436         return 1;
437       }
438
439   // Add a new rule
440   struct dir_rule *r = xmalloc(sizeof(*r));
441   r->inside = in;
442   r->outside = out;
443   *last_dir_rule = r;
444   last_dir_rule = &r->next;
445   r->next = NULL;
446
447   return 1;
448 }
449
450 static int set_dir_action(char *arg)
451 {
452   arg = xstrdup(arg);
453   char *sep = strchr(arg, '=');
454
455   if (sep)
456     {
457       *sep++ = 0;
458       return add_dir_rule(arg, (*sep ? sep : NULL));
459     }
460   else
461     {
462       char *out = xmalloc(1 + strlen(arg) + 1);
463       sprintf(out, "/%s", arg);
464       return add_dir_rule(arg, out);
465     }
466 }
467
468 static void init_dir_rules(void)
469 {
470   set_dir_action("box=./box");
471   set_dir_action("bin");
472   set_dir_action("dev");
473   set_dir_action("lib");
474   set_dir_action("lib64=?/lib64");
475   set_dir_action("proc=procfs");
476   set_dir_action("usr");
477 }
478
479 static void make_dir(char *path)
480 {
481   char *sep = path;
482   for (;;)
483     {
484       sep = strchr(sep, '/');
485       if (sep)
486         *sep = 0;
487
488       if (dir_exists(path))
489         {
490           if (sep)
491             *sep = '/';
492           return;
493         }
494
495       if (mkdir(path, 0777) < 0)
496         die("Cannot create directory %s: %m\n", path);
497
498       if (!sep)
499         return;
500       *sep++ = '/';
501     }
502 }
503
504 static void apply_dir_rules(void)
505 {
506   for (struct dir_rule *r = first_dir_rule; r; r=r->next)
507     {
508       char *in = r->inside;
509       char *out = r->outside;
510       if (!out)
511         {
512           msg("Not binding anything on %s\n", r->inside);
513           continue;
514         }
515
516       if (out[0] == '?')
517         {
518           out++;
519           if (!dir_exists(out))
520             {
521               msg("Not binding %s on %s (does not exist)\n", out, r->inside);
522               continue;
523             }
524         }
525
526       char root_in[1024];
527       snprintf(root_in, sizeof(root_in), "root/%s", in);
528       make_dir(root_in);
529
530       if (!strcmp(out, "procfs"))
531         {
532           msg("Mounting procfs on %s\n", in);
533           if (mount("none", root_in, "proc", 0, "") < 0)
534             die("Cannot mount proc on %s: %m", in);
535         }
536       else
537         {
538           msg("Binding %s on %s\n", out, in);
539           if (mount(out, root_in, "none", MS_BIND | MS_NOSUID | MS_NODEV, "") < 0)
540             die("Cannot bind %s on %s: %m", out, in);
541         }
542     }
543 }
544
545 /*** Control groups ***/
546
547 static char cg_path[256];
548
549 #define CG_BUFSIZE 1024
550
551 static int
552 cg_read(char *attr, char *buf)
553 {
554   int maybe = 0;
555   if (attr[0] == '?')
556     {
557       attr++;
558       maybe = 1;
559     }
560
561   char path[256];
562   snprintf(path, sizeof(path), "%s/%s", cg_path, attr);
563
564   int fd = open(path, O_RDONLY);
565   if (fd < 0)
566     {
567       if (maybe)
568         return 0;
569       die("Cannot read %s: %m", path);
570     }
571
572   int n = read(fd, buf, CG_BUFSIZE);
573   if (n < 0)
574     die("Cannot read %s: %m", path);
575   if (n >= CG_BUFSIZE - 1)
576     die("Attribute %s too long", path);
577   if (n > 0 && buf[n-1] == '\n')
578     n--;
579   buf[n] = 0;
580
581   if (verbose > 1)
582     msg("CG: Read %s = %s\n", attr, buf);
583
584   close(fd);
585   return 1;
586 }
587
588 static void __attribute__((format(printf,2,3)))
589 cg_write(char *attr, char *fmt, ...)
590 {
591   va_list args;
592   va_start(args, fmt);
593
594   char buf[CG_BUFSIZE];
595   int n = vsnprintf(buf, sizeof(buf), fmt, args);
596   if (n >= CG_BUFSIZE)
597     die("cg_writef: Value for attribute %s is too long", attr);
598
599   if (verbose > 1)
600     msg("CG: Write %s = %s", attr, buf);
601
602   char path[256];
603   snprintf(path, sizeof(path), "%s/%s", cg_path, attr);
604
605   int fd = open(path, O_WRONLY | O_TRUNC);
606   if (fd < 0)
607     die("Cannot write %s: %m", path);
608
609   int written = write(fd, buf, n);
610   if (written < 0)
611     die("Cannot set %s to %s: %m", path, buf);
612   if (written != n)
613     die("Short write to %s (%d out of %d bytes)", path, written, n);
614
615   close(fd);
616   va_end(args);
617 }
618
619 static void
620 cg_init(void)
621 {
622   if (!cg_enable)
623     return;
624
625   if (!dir_exists(cg_root))
626     die("Control group filesystem at %s not mounted", cg_root);
627
628   snprintf(cg_path, sizeof(cg_path), "%s/box-%d", cg_root, BOX_UID);
629   msg("Using control group %s\n", cg_path);
630 }
631
632 static void
633 cg_prepare(void)
634 {
635   if (!cg_enable)
636     return;
637
638   struct stat st;
639   char buf[CG_BUFSIZE];
640
641   if (stat(cg_path, &st) >= 0 || errno != ENOENT)
642     {
643       msg("Control group %s already exists, trying to empty it.\n", cg_path);
644       if (rmdir(cg_path) < 0)
645         die("Failed to reset control group %s: %m", cg_path);
646     }
647
648   if (mkdir(cg_path, 0777) < 0)
649     die("Failed to create control group %s: %m", cg_path);
650
651   // If cpuset module is enabled, copy allowed cpus and memory nodes from parent group
652   if (cg_read("?../cpuset.cpus", buf))
653     cg_write("cpuset.cpus", "%s", buf);
654   if (cg_read("?../cpuset.mems", buf))
655     cg_write("cpuset.mems", "%s", buf);
656 }
657
658 static void
659 cg_enter(void)
660 {
661   if (!cg_enable)
662     return;
663
664   msg("Entering control group %s\n", cg_path);
665
666   struct stat st;
667   if (stat(cg_path, &st) < 0)
668     die("Control group %s does not exist: %m", cg_path);
669
670   if (cg_memory_limit)
671     {
672       cg_write("memory.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
673       cg_write("memory.memsw.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
674     }
675
676   if (cg_timing)
677     cg_write("cpuacct.usage", "0\n");
678
679   cg_write("tasks", "%d\n", (int) getpid());
680 }
681
682 static int
683 cg_get_run_time_ms(void)
684 {
685   if (!cg_enable)
686     return 0;
687
688   char buf[CG_BUFSIZE];
689   cg_read("cpuacct.usage", buf);
690   unsigned long long ns = atoll(buf);
691   return ns / 1000000;
692 }
693
694 static void
695 cg_stats(void)
696 {
697   if (!cg_enable)
698     return;
699
700   char buf[CG_BUFSIZE];
701
702   // Memory usage statistics
703   unsigned long long mem=0, memsw=0;
704   if (cg_read("?memory.max_usage_in_bytes", buf))
705     mem = atoll(buf);
706   if (cg_read("?memory.memsw.max_usage_in_bytes", buf))
707     {
708       memsw = atoll(buf);
709       if (memsw > mem)
710         mem = memsw;
711     }
712   if (mem)
713     meta_printf("cg-mem:%lld\n", mem >> 10);
714 }
715
716 static void
717 cg_remove(void)
718 {
719   char buf[CG_BUFSIZE];
720
721   if (!cg_enable)
722     return;
723
724   cg_read("tasks", buf);
725   if (buf[0])
726     die("Some tasks left in control group %s, failed to remove it", cg_path);
727
728   if (rmdir(cg_path) < 0)
729     die("Cannot remove control group %s: %m", cg_path);
730 }
731
732 /*** The keeper process ***/
733
734 static void
735 signal_alarm(int unused UNUSED)
736 {
737   /* Time limit checks are synchronous, so we only schedule them there. */
738   timer_tick = 1;
739   alarm(1);
740 }
741
742 static void
743 signal_int(int unused UNUSED)
744 {
745   /* Interrupts are fatal, so no synchronization requirements. */
746   meta_printf("exitsig:%d\n", SIGINT);
747   err("SG: Interrupted");
748 }
749
750 #define PROC_BUF_SIZE 4096
751 static void
752 read_proc_file(char *buf, char *name, int *fdp)
753 {
754   int c;
755
756   if (!*fdp)
757     {
758       sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
759       *fdp = open(buf, O_RDONLY);
760       if (*fdp < 0)
761         die("open(%s): %m", buf);
762     }
763   lseek(*fdp, 0, SEEK_SET);
764   if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
765     die("read on /proc/$pid/%s: %m", name);
766   if (c >= PROC_BUF_SIZE-1)
767     die("/proc/$pid/%s too long", name);
768   buf[c] = 0;
769 }
770
771 static int
772 get_wall_time_ms(void)
773 {
774   struct timeval now, wall;
775   gettimeofday(&now, NULL);
776   timersub(&now, &start_time, &wall);
777   return wall.tv_sec*1000 + wall.tv_usec/1000;
778 }
779
780 static int
781 get_run_time_ms(struct rusage *rus)
782 {
783   if (cg_timing)
784     return cg_get_run_time_ms();
785
786   if (rus)
787     {
788       struct timeval total;
789       timeradd(&rus->ru_utime, &rus->ru_stime, &total);
790       return total.tv_sec*1000 + total.tv_usec/1000;
791     }
792
793   char buf[PROC_BUF_SIZE], *x;
794   int utime, stime;
795   static int proc_stat_fd;
796
797   read_proc_file(buf, "stat", &proc_stat_fd);
798   x = buf;
799   while (*x && *x != ' ')
800     x++;
801   while (*x == ' ')
802     x++;
803   if (*x++ != '(')
804     die("proc stat syntax error 1");
805   while (*x && (*x != ')' || x[1] != ' '))
806     x++;
807   while (*x == ')' || *x == ' ')
808     x++;
809   if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
810     die("proc stat syntax error 2");
811
812   return (utime + stime) * 1000 / ticks_per_sec;
813 }
814
815 static void
816 check_timeout(void)
817 {
818   if (wall_timeout)
819     {
820       int wall_ms = get_wall_time_ms();
821       if (wall_ms > wall_timeout)
822         err("TO: Time limit exceeded (wall clock)");
823       if (verbose > 1)
824         fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
825     }
826   if (timeout)
827     {
828       int ms = get_run_time_ms(NULL);
829       if (verbose > 1)
830         fprintf(stderr, "[time check: %d msec]\n", ms);
831       if (ms > timeout && ms > extra_timeout)
832         err("TO: Time limit exceeded");
833     }
834 }
835
836 static void
837 box_keeper(void)
838 {
839   read_errors_from_fd = error_pipes[0];
840   close(error_pipes[1]);
841
842   struct sigaction sa;
843   bzero(&sa, sizeof(sa));
844   sa.sa_handler = signal_int;
845   sigaction(SIGINT, &sa, NULL);
846
847   gettimeofday(&start_time, NULL);
848   ticks_per_sec = sysconf(_SC_CLK_TCK);
849   if (ticks_per_sec <= 0)
850     die("Invalid ticks_per_sec!");
851
852   if (timeout || wall_timeout)
853     {
854       sa.sa_handler = signal_alarm;
855       sigaction(SIGALRM, &sa, NULL);
856       alarm(1);
857     }
858
859   for(;;)
860     {
861       struct rusage rus;
862       int stat;
863       pid_t p;
864       if (timer_tick)
865         {
866           check_timeout();
867           timer_tick = 0;
868         }
869       p = wait4(box_pid, &stat, 0, &rus);
870       if (p < 0)
871         {
872           if (errno == EINTR)
873             continue;
874           die("wait4: %m");
875         }
876       if (p != box_pid)
877         die("wait4: unknown pid %d exited!", p);
878       box_pid = 0;
879
880       // Check error pipe if there is an internal error passed from inside the box
881       char interr[1024];
882       int n = read(read_errors_from_fd, interr, sizeof(interr) - 1);
883       if (n > 0)
884         {
885           interr[n] = 0;
886           die("%s", interr);
887         }
888
889       if (WIFEXITED(stat))
890         {
891           final_stats(&rus);
892           if (WEXITSTATUS(stat))
893             {
894               meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
895               err("RE: Exited with error status %d", WEXITSTATUS(stat));
896             }
897           if (timeout && total_ms > timeout)
898             err("TO: Time limit exceeded");
899           if (wall_timeout && wall_ms > wall_timeout)
900             err("TO: Time limit exceeded (wall clock)");
901           flush_line();
902           fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall)\n",
903               total_ms/1000, total_ms%1000,
904               wall_ms/1000, wall_ms%1000);
905           box_exit(0);
906         }
907       else if (WIFSIGNALED(stat))
908         {
909           meta_printf("exitsig:%d\n", WTERMSIG(stat));
910           final_stats(&rus);
911           err("SG: Caught fatal signal %d", WTERMSIG(stat));
912         }
913       else if (WIFSTOPPED(stat))
914         {
915           meta_printf("exitsig:%d\n", WSTOPSIG(stat));
916           final_stats(&rus);
917           err("SG: Stopped by signal %d", WSTOPSIG(stat));
918         }
919       else
920         die("wait4: unknown status %x, giving up!", stat);
921     }
922 }
923
924 /*** The process running inside the box ***/
925
926 static void
927 setup_root(void)
928 {
929   if (mkdir("root", 0750) < 0 && errno != EEXIST)
930     die("mkdir('root'): %m");
931
932   if (mount("none", "root", "tmpfs", 0, "mode=755") < 0)
933     die("Cannot mount root ramdisk: %m");
934
935   apply_dir_rules();
936
937   if (chroot("root") < 0)
938     die("Chroot failed: %m");
939
940   if (chdir("root/box") < 0)
941     die("Cannot change current directory: %m");
942 }
943
944 static void
945 setup_credentials(void)
946 {
947   if (setresgid(BOX_GID, BOX_GID, BOX_GID) < 0)
948     die("setresgid: %m");
949   if (setgroups(0, NULL) < 0)
950     die("setgroups: %m");
951   if (setresuid(BOX_UID, BOX_UID, BOX_UID) < 0)
952     die("setresuid: %m");
953   setpgrp();
954 }
955
956 static void
957 setup_fds(void)
958 {
959   if (redir_stdin)
960     {
961       close(0);
962       if (open(redir_stdin, O_RDONLY) != 0)
963         die("open(\"%s\"): %m", redir_stdin);
964     }
965   if (redir_stdout)
966     {
967       close(1);
968       if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
969         die("open(\"%s\"): %m", redir_stdout);
970     }
971   if (redir_stderr)
972     {
973       close(2);
974       if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
975         die("open(\"%s\"): %m", redir_stderr);
976     }
977   else
978     dup2(1, 2);
979 }
980
981 static void
982 setup_rlim(const char *res_name, int res, rlim_t limit)
983 {
984   struct rlimit rl = { .rlim_cur = limit, .rlim_max = limit };
985   if (setrlimit(res, &rl) < 0)
986     die("setrlimit(%s, %jd)", res_name, (intmax_t) limit);
987 }
988
989 static void
990 setup_rlimits(void)
991 {
992 #define RLIM(res, val) setup_rlim("RLIMIT_" #res, RLIMIT_##res, val)
993
994   if (memory_limit)
995     RLIM(AS, memory_limit * 1024);
996
997   RLIM(STACK, (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY));
998   RLIM(NOFILE, 64);
999   RLIM(MEMLOCK, 0);
1000
1001   if (max_processes)
1002     RLIM(NPROC, max_processes);
1003
1004 #undef RLIM
1005 }
1006
1007 static int
1008 box_inside(void *arg)
1009 {
1010   char **args = arg;
1011   write_errors_to_fd = error_pipes[1];
1012   close(error_pipes[0]);
1013
1014   cg_enter();
1015   setup_root();
1016   setup_credentials();
1017   setup_fds();
1018   setup_rlimits();
1019   char **env = setup_environment();
1020
1021   execve(args[0], args, env);
1022   die("execve(\"%s\"): %m", args[0]);
1023 }
1024
1025 /*** Commands ***/
1026
1027 static void
1028 init(void)
1029 {
1030   msg("Preparing sandbox directory\n");
1031   xsystem("rm -rf box");
1032   if (mkdir("box", 0700) < 0)
1033     die("Cannot create box: %m");
1034   if (chown("box", orig_uid, orig_gid) < 0)
1035     die("Cannot chown box: %m");
1036
1037   cg_prepare();
1038 }
1039
1040 static void
1041 cleanup(void)
1042 {
1043   if (!dir_exists("box"))
1044     die("Box directory not found, there isn't anything to clean up");
1045
1046   msg("Deleting sandbox directory\n");
1047   xsystem("rm -rf box");
1048   cg_remove();
1049 }
1050
1051 static void
1052 run(char **argv)
1053 {
1054   if (!dir_exists("box"))
1055     die("Box directory not found, did you run `isolate --init'?");
1056
1057   char cmd[256];
1058   snprintf(cmd, sizeof(cmd), "chown -R %d.%d box", BOX_UID, BOX_GID);
1059   xsystem(cmd);
1060   snprintf(cleanup_cmd, sizeof(cleanup_cmd), "chown -R %d.%d box", orig_uid, orig_gid);
1061
1062   if (pipe(error_pipes) < 0)
1063     die("pipe: %m");
1064   for (int i=0; i<2; i++)
1065     if (fcntl(error_pipes[i], F_SETFD, fcntl(error_pipes[i], F_GETFD) | FD_CLOEXEC) < 0 ||
1066         fcntl(error_pipes[i], F_SETFL, fcntl(error_pipes[i], F_GETFL) | O_NONBLOCK) < 0)
1067       die("fcntl on pipe: %m");
1068
1069   box_pid = clone(
1070     box_inside,                 // Function to execute as the body of the new process
1071     argv,                       // Pass our stack
1072     SIGCHLD | CLONE_NEWIPC | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWPID,
1073     argv);                      // Pass the arguments
1074   if (box_pid < 0)
1075     die("clone: %m");
1076   if (!box_pid)
1077     die("clone returned 0");
1078   box_keeper();
1079 }
1080
1081 static void
1082 show_version(void)
1083 {
1084   printf("Process isolator 1.0\n");
1085   printf("(c) 2012 Martin Mares and Bernard Blackham\n");
1086   printf("\nCompile-time configuration:\n");
1087   printf("Sandbox directory: %s\n", BOX_DIR);
1088   printf("Sandbox credentials: uid=%u gid=%u\n", BOX_UID, BOX_GID);
1089 }
1090
1091 /*** Options ***/
1092
1093 static void
1094 usage(void)
1095 {
1096   fprintf(stderr, "Invalid arguments!\n");
1097   printf("\
1098 Usage: isolate [<options>] <command>\n\
1099 \n\
1100 Options:\n\
1101 -c, --cg[=<parent>]\tPut process in a control group (optionally a sub-group of <parent>)\n\
1102     --cg-mem=<size>\tLimit memory usage of the control group to <size> KB\n\
1103     --cg-timing\t\tTime limits affects total run time of the control group\n\
1104 -d, --dir=<dir>\t\tMake a directory <dir> visible inside the sandbox\n\
1105 -d, --dir=<in>=<out>\tMake a directory <out> outside visible as <in> inside\n\
1106 -d, --dir=<in>=\t\tDelete a previously defined directory rule (even a default one)\n\
1107 -E, --env=<var>\t\tInherit the environment variable <var> from the parent process\n\
1108 -E, --env=<var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
1109 -x, --extra-time=<time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
1110 \t\t\tso that its real execution time is reported (seconds, fractions allowed)\n\
1111 -e, --full-env\t\tInherit full environment of the parent process\n\
1112 -m, --mem=<size>\tLimit address space to <size> KB\n\
1113 -M, --meta=<file>\tOutput process information to <file> (name:value)\n\
1114 -k, --stack=<size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
1115 -r, --stderr=<file>\tRedirect stderr to <file>\n\
1116 -i, --stdin=<file>\tRedirect stdin from <file>\n\
1117 -o, --stdout=<file>\tRedirect stdout to <file>\n\
1118 -p, --processes[=<max>]\tEnable multiple processes (at most <max> of them); needs --cg\n\
1119 -t, --time=<time>\tSet run time limit (seconds, fractions allowed)\n\
1120 -v, --verbose\t\tBe verbose (use multiple times for even more verbosity)\n\
1121 -w, --wall-time=<time>\tSet wall clock time limit (seconds, fractions allowed)\n\
1122 \n\
1123 Commands:\n\
1124     --init\t\tInitialize sandbox (and its control group when --cg is used)\n\
1125     --run -- <cmd> ...\tRun given command within sandbox\n\
1126     --cleanup\t\tClean up sandbox\n\
1127     --version\t\tDisplay program version and configuration\n\
1128 ");
1129   exit(2);
1130 }
1131
1132 enum opt_code {
1133   OPT_INIT = 256,
1134   OPT_RUN,
1135   OPT_CLEANUP,
1136   OPT_VERSION,
1137   OPT_CG_MEM,
1138   OPT_CG_TIMING,
1139 };
1140
1141 static const char short_opts[] = "c::d:eE:i:k:m:M:o:p::r:t:vw:x:";
1142
1143 static const struct option long_opts[] = {
1144   { "cg",               2, NULL, 'c' },
1145   { "cg-mem",           1, NULL, OPT_CG_MEM },
1146   { "cg-timing",        0, NULL, OPT_CG_TIMING },
1147   { "cleanup",          0, NULL, OPT_CLEANUP },
1148   { "dir",              1, NULL, 'd' },
1149   { "env",              1, NULL, 'E' },
1150   { "extra-time",       1, NULL, 'x' },
1151   { "full-env",         0, NULL, 'e' },
1152   { "init",             0, NULL, OPT_INIT },
1153   { "mem",              1, NULL, 'm' },
1154   { "meta",             1, NULL, 'M' },
1155   { "processes",        2, NULL, 'p' },
1156   { "run",              0, NULL, OPT_RUN },
1157   { "stack",            1, NULL, 'k' },
1158   { "stderr",           1, NULL, 'r' },
1159   { "stdin",            1, NULL, 'i' },
1160   { "stdout",           1, NULL, 'o' },
1161   { "time",             1, NULL, 't' },
1162   { "verbose",          0, NULL, 'v' },
1163   { "version",          0, NULL, OPT_VERSION },
1164   { "wall-time",        1, NULL, 'w' },
1165   { NULL,               0, NULL, 0 }
1166 };
1167
1168 int
1169 main(int argc, char **argv)
1170 {
1171   int c;
1172   enum opt_code mode = 0;
1173
1174   init_dir_rules();
1175
1176   while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) >= 0)
1177     switch (c)
1178       {
1179       case 'c':
1180         if (optarg)
1181           cg_root = optarg;
1182         cg_enable = 1;
1183         break;
1184       case 'd':
1185         if (!set_dir_action(optarg))
1186           usage();
1187         break;
1188       case 'e':
1189         pass_environ = 1;
1190         break;
1191       case 'E':
1192         if (!set_env_action(optarg))
1193           usage();
1194         break;
1195       case 'k':
1196         stack_limit = atoi(optarg);
1197         break;
1198       case 'i':
1199         redir_stdin = optarg;
1200         break;
1201       case 'm':
1202         memory_limit = atoi(optarg);
1203         break;
1204       case 'M':
1205         meta_open(optarg);
1206         break;
1207       case 'o':
1208         redir_stdout = optarg;
1209         break;
1210       case 'p':
1211         if (optarg)
1212           max_processes = atoi(optarg);
1213         else
1214           max_processes = 0;
1215         break;
1216       case 'r':
1217         redir_stderr = optarg;
1218         break;
1219       case 't':
1220         timeout = 1000*atof(optarg);
1221         break;
1222       case 'v':
1223         verbose++;
1224         break;
1225       case 'w':
1226         wall_timeout = 1000*atof(optarg);
1227         break;
1228       case 'x':
1229         extra_timeout = 1000*atof(optarg);
1230         break;
1231       case OPT_INIT:
1232       case OPT_RUN:
1233       case OPT_CLEANUP:
1234       case OPT_VERSION:
1235         mode = c;
1236         break;
1237       case OPT_CG_MEM:
1238         cg_memory_limit = atoi(optarg);
1239         break;
1240       case OPT_CG_TIMING:
1241         cg_timing = 1;
1242         break;
1243       default:
1244         usage();
1245       }
1246
1247   if (!mode)
1248     usage();
1249   if (mode == OPT_VERSION)
1250     {
1251       show_version();
1252       return 0;
1253     }
1254
1255   if (geteuid())
1256     die("Must be started as root");
1257   orig_uid = getuid();
1258   orig_gid = getgid();
1259
1260   umask(022);
1261   if (chdir(BOX_DIR) < 0)
1262     die("chdir(%s): %m", BOX_DIR);
1263   cg_init();
1264
1265   switch (mode)
1266     {
1267     case OPT_INIT:
1268       if (optind < argc)
1269         usage();
1270       init();
1271       break;
1272     case OPT_RUN:
1273       if (optind >= argc)
1274         usage();
1275       run(argv+optind);
1276       break;
1277     case OPT_CLEANUP:
1278       if (optind < argc)
1279         usage();
1280       cleanup();
1281       break;
1282     default:
1283       die("Internal error: mode mismatch");
1284     }
1285   exit(0);
1286 }