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