]> mj.ucw.cz Git - eval.git/blob - isolate/isolate.c
f27ff635aebcce5905a69c0dc76b555b5a017588
[eval.git] / isolate / isolate.c
1 /*
2  *      A Process Isolator based on Linux Containers
3  *
4  *      (c) 2012-2013 Martin Mares <mj@ucw.cz>
5  *      (c) 2012-2013 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 <mntent.h>
25 #include <limits.h>
26 #include <sys/wait.h>
27 #include <sys/time.h>
28 #include <sys/signal.h>
29 #include <sys/resource.h>
30 #include <sys/mount.h>
31 #include <sys/stat.h>
32 #include <sys/quota.h>
33 #include <sys/vfs.h>
34
35 #define NONRET __attribute__((noreturn))
36 #define UNUSED __attribute__((unused))
37 #define ARRAY_SIZE(a) (int)(sizeof(a)/sizeof(a[0]))
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 block_quota;
47 static int inode_quota;
48 static int max_processes = 1;
49 static char *redir_stdin, *redir_stdout, *redir_stderr;
50 static char *set_cwd;
51
52 static int cg_enable;
53 static int cg_memory_limit;
54 static int cg_timing;
55
56 static int box_id;
57 static char box_dir[1024];
58 static pid_t box_pid;
59
60 static uid_t box_uid;
61 static gid_t box_gid;
62 static uid_t orig_uid;
63 static gid_t orig_gid;
64
65 static int partial_line;
66 static char cleanup_cmd[256];
67
68 static struct timeval start_time;
69 static int ticks_per_sec;
70 static int total_ms, wall_ms;
71 static volatile sig_atomic_t timer_tick;
72
73 static int error_pipes[2];
74 static int write_errors_to_fd;
75 static int read_errors_from_fd;
76
77 static void die(char *msg, ...) NONRET;
78 static void cg_stats(void);
79 static int get_wall_time_ms(void);
80 static int get_run_time_ms(struct rusage *rus);
81
82 /*** Meta-files ***/
83
84 static FILE *metafile;
85
86 static void
87 meta_open(const char *name)
88 {
89   if (!strcmp(name, "-"))
90     {
91       metafile = stdout;
92       return;
93     }
94   metafile = fopen(name, "w");
95   if (!metafile)
96     die("Failed to open metafile '%s'",name);
97 }
98
99 static void
100 meta_close(void)
101 {
102   if (metafile && metafile != stdout)
103     fclose(metafile);
104 }
105
106 static void __attribute__((format(printf,1,2)))
107 meta_printf(const char *fmt, ...)
108 {
109   if (!metafile)
110     return;
111
112   va_list args;
113   va_start(args, fmt);
114   vfprintf(metafile, fmt, args);
115   va_end(args);
116 }
117
118 static void
119 final_stats(struct rusage *rus)
120 {
121   total_ms = get_run_time_ms(rus);
122   wall_ms = get_wall_time_ms();
123
124   meta_printf("time:%d.%03d\n", total_ms/1000, total_ms%1000);
125   meta_printf("time-wall:%d.%03d\n", wall_ms/1000, wall_ms%1000);
126   meta_printf("max-rss:%ld\n", rus->ru_maxrss);
127   meta_printf("csw-voluntary:%ld\n", rus->ru_nvcsw);
128   meta_printf("csw-forced:%ld\n", rus->ru_nivcsw);
129
130   cg_stats();
131 }
132
133 /*** Messages and exits ***/
134
135 static void
136 xsystem(const char *cmd)
137 {
138   int ret = system(cmd);
139   if (ret < 0)
140     die("system(\"%s\"): %m", cmd);
141   if (!WIFEXITED(ret) || WEXITSTATUS(ret))
142     die("system(\"%s\"): Exited with status %d", cmd, ret);
143 }
144
145 static void NONRET
146 box_exit(int rc)
147 {
148   if (box_pid > 0)
149     {
150       kill(-box_pid, SIGKILL);
151       kill(box_pid, SIGKILL);
152       meta_printf("killed:1\n");
153
154       struct rusage rus;
155       int p, stat;
156       do
157         p = wait4(box_pid, &stat, 0, &rus);
158       while (p < 0 && errno == EINTR);
159       if (p < 0)
160         fprintf(stderr, "UGH: Lost track of the process (%m)\n");
161       else
162         final_stats(&rus);
163     }
164
165   if (rc < 2 && cleanup_cmd[0])
166     xsystem(cleanup_cmd);
167
168   meta_close();
169   exit(rc);
170 }
171
172 static void
173 flush_line(void)
174 {
175   if (partial_line)
176     fputc('\n', stderr);
177   partial_line = 0;
178 }
179
180 /* Report an error of the sandbox itself */
181 static void NONRET __attribute__((format(printf,1,2)))
182 die(char *msg, ...)
183 {
184   va_list args;
185   va_start(args, msg);
186   char buf[1024];
187   int n = vsnprintf(buf, sizeof(buf), msg, args);
188
189   if (write_errors_to_fd)
190     {
191       // We are inside the box, have to use error pipe for error reporting.
192       // We hope that the whole error message fits in PIPE_BUF bytes.
193       write(write_errors_to_fd, buf, n);
194       exit(2);
195     }
196
197   // Otherwise, we in the box keeper process, so we report errors normally
198   flush_line();
199   meta_printf("status:XX\nmessage:%s\n", buf);
200   fputs(buf, stderr);
201   fputc('\n', stderr);
202   box_exit(2);
203 }
204
205 /* Report an error of the program inside the sandbox */
206 static void NONRET __attribute__((format(printf,1,2)))
207 err(char *msg, ...)
208 {
209   va_list args;
210   va_start(args, msg);
211   flush_line();
212   if (msg[0] && msg[1] && msg[2] == ':' && msg[3] == ' ')
213     {
214       meta_printf("status:%c%c\n", msg[0], msg[1]);
215       msg += 4;
216     }
217   char buf[1024];
218   vsnprintf(buf, sizeof(buf), msg, args);
219   meta_printf("message:%s\n", buf);
220   fputs(buf, stderr);
221   fputc('\n', stderr);
222   box_exit(1);
223 }
224
225 /* Write a message, but only if in verbose mode */
226 static void __attribute__((format(printf,1,2)))
227 msg(char *msg, ...)
228 {
229   va_list args;
230   va_start(args, msg);
231   if (verbose)
232     {
233       int len = strlen(msg);
234       if (len > 0)
235         partial_line = (msg[len-1] != '\n');
236       vfprintf(stderr, msg, args);
237       fflush(stderr);
238     }
239   va_end(args);
240 }
241
242 /*** Utility functions ***/
243
244 static void *
245 xmalloc(size_t size)
246 {
247   void *p = malloc(size);
248   if (!p)
249     die("Out of memory");
250   return p;
251 }
252
253 static char *
254 xstrdup(char *str)
255 {
256   char *p = strdup(str);
257   if (!p)
258     die("Out of memory");
259   return p;
260 }
261
262 static int dir_exists(char *path)
263 {
264   struct stat st;
265   return (stat(path, &st) >= 0 && S_ISDIR(st.st_mode));
266 }
267
268 /*** Environment rules ***/
269
270 struct env_rule {
271   char *var;                    // Variable to match
272   char *val;                    // ""=clear, NULL=inherit
273   int var_len;
274   struct env_rule *next;
275 };
276
277 static struct env_rule *first_env_rule;
278 static struct env_rule **last_env_rule = &first_env_rule;
279
280 static struct env_rule default_env_rules[] = {
281   { "LIBC_FATAL_STDERR_", "1" }
282 };
283
284 static int
285 set_env_action(char *a0)
286 {
287   struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
288   char *a = (char *)(r+1);
289   strcpy(a, a0);
290
291   char *sep = strchr(a, '=');
292   if (sep == a)
293     return 0;
294   r->var = a;
295   if (sep)
296     {
297       *sep++ = 0;
298       r->val = sep;
299     }
300   else
301     r->val = NULL;
302   *last_env_rule = r;
303   last_env_rule = &r->next;
304   r->next = NULL;
305   return 1;
306 }
307
308 static int
309 match_env_var(char *env_entry, struct env_rule *r)
310 {
311   if (strncmp(env_entry, r->var, r->var_len))
312     return 0;
313   return (env_entry[r->var_len] == '=');
314 }
315
316 static void
317 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
318 {
319   // First remove the variable if already set
320   int pos = 0;
321   while (pos < *env_sizep && !match_env_var(env[pos], r))
322     pos++;
323   if (pos < *env_sizep)
324     {
325       (*env_sizep)--;
326       env[pos] = env[*env_sizep];
327       env[*env_sizep] = NULL;
328     }
329
330   // What is the new value?
331   char *new;
332   if (r->val)
333     {
334       if (!r->val[0])
335         return;
336       new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
337       sprintf(new, "%s=%s", r->var, r->val);
338     }
339   else
340     {
341       pos = 0;
342       while (environ[pos] && !match_env_var(environ[pos], r))
343         pos++;
344       if (!(new = environ[pos]))
345         return;
346     }
347
348   // Add it at the end of the array
349   env[(*env_sizep)++] = new;
350   env[*env_sizep] = NULL;
351 }
352
353 static char **
354 setup_environment(void)
355 {
356   // Link built-in rules with user rules
357   for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
358     {
359       default_env_rules[i].next = first_env_rule;
360       first_env_rule = &default_env_rules[i];
361     }
362
363   // Scan the original environment
364   char **orig_env = environ;
365   int orig_size = 0;
366   while (orig_env[orig_size])
367     orig_size++;
368
369   // For each rule, reserve one more slot and calculate length
370   int num_rules = 0;
371   for (struct env_rule *r = first_env_rule; r; r=r->next)
372     {
373       num_rules++;
374       r->var_len = strlen(r->var);
375     }
376
377   // Create a new environment
378   char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
379   int size;
380   if (pass_environ)
381     {
382       memcpy(env, environ, orig_size * sizeof(char *));
383       size = orig_size;
384     }
385   else
386     size = 0;
387   env[size] = NULL;
388
389   // Apply the rules one by one
390   for (struct env_rule *r = first_env_rule; r; r=r->next)
391     apply_env_rule(env, &size, r);
392
393   // Return the new env and pass some gossip
394   if (verbose > 1)
395     {
396       fprintf(stderr, "Passing environment:\n");
397       for (int i=0; env[i]; i++)
398         fprintf(stderr, "\t%s\n", env[i]);
399     }
400   return env;
401 }
402
403 /*** Directory rules ***/
404
405 struct dir_rule {
406   char *inside;                 // A relative path
407   char *outside;                // This can be an absolute path or a relative path starting with "./"
408   unsigned int flags;           // DIR_FLAG_xxx
409   struct dir_rule *next;
410 };
411
412 enum dir_rule_flags {
413   DIR_FLAG_RW = 1,
414   DIR_FLAG_NOEXEC = 2,
415   DIR_FLAG_FS = 4,
416   DIR_FLAG_MAYBE = 8,
417   DIR_FLAG_DEV = 16,
418 };
419
420 static const char * const dir_flag_names[] = { "rw", "noexec", "fs", "maybe", "dev" };
421
422 static struct dir_rule *first_dir_rule;
423 static struct dir_rule **last_dir_rule = &first_dir_rule;
424
425 static int add_dir_rule(char *in, char *out, unsigned int flags)
426 {
427   // Make sure that "in" is relative
428   while (in[0] == '/')
429     in++;
430   if (!*in)
431     return 0;
432
433   // Check "out"
434   if (flags & DIR_FLAG_FS)
435     {
436       if (!out || out[0] == '/')
437         return 0;
438     }
439   else
440     {
441       if (out && out[0] != '/' && strncmp(out, "./", 2))
442         return 0;
443     }
444
445   // Override an existing rule
446   struct dir_rule *r;
447   for (r = first_dir_rule; r; r = r->next)
448     if (!strcmp(r->inside, in))
449       break;
450
451   // Add a new rule
452   if (!r)
453     {
454       r = xmalloc(sizeof(*r));
455       r->inside = in;
456       *last_dir_rule = r;
457       last_dir_rule = &r->next;
458       r->next = NULL;
459     }
460   r->outside = out;
461   r->flags = flags;
462   return 1;
463 }
464
465 static unsigned int parse_dir_option(char *opt)
466 {
467   for (unsigned int i = 0; i < ARRAY_SIZE(dir_flag_names); i++)
468     if (!strcmp(opt, dir_flag_names[i]))
469       return 1U << i;
470   die("Unknown directory option %s", opt);
471 }
472
473 static int set_dir_action(char *arg)
474 {
475   arg = xstrdup(arg);
476
477   char *colon = strchr(arg, ':');
478   unsigned int flags = 0;
479   while (colon)
480     {
481       *colon++ = 0;
482       char *next = strchr(colon, ':');
483       if (next)
484         *next = 0;
485       flags |= parse_dir_option(colon);
486       colon = next;
487     }
488
489   char *eq = strchr(arg, '=');
490   if (eq)
491     {
492       *eq++ = 0;
493       return add_dir_rule(arg, (*eq ? eq : NULL), flags);
494     }
495   else
496     {
497       char *out = xmalloc(1 + strlen(arg) + 1);
498       sprintf(out, "/%s", arg);
499       return add_dir_rule(arg, out, flags);
500     }
501 }
502
503 static void init_dir_rules(void)
504 {
505   set_dir_action("box=./box:rw");
506   set_dir_action("bin");
507   set_dir_action("dev:dev");
508   set_dir_action("lib");
509   set_dir_action("lib64:maybe");
510   set_dir_action("proc=proc:fs");
511   set_dir_action("usr");
512 }
513
514 static void make_dir(char *path)
515 {
516   char *sep = (path[0] == '/' ? path+1 : path);
517
518   for (;;)
519     {
520       sep = strchr(sep, '/');
521       if (sep)
522         *sep = 0;
523
524       if (!dir_exists(path) && mkdir(path, 0777) < 0)
525         die("Cannot create directory %s: %m\n", path);
526
527       if (!sep)
528         return;
529       *sep++ = '/';
530     }
531 }
532
533 static void apply_dir_rules(void)
534 {
535   for (struct dir_rule *r = first_dir_rule; r; r=r->next)
536     {
537       char *in = r->inside;
538       char *out = r->outside;
539       if (!out)
540         {
541           msg("Not binding anything on %s\n", r->inside);
542           continue;
543         }
544
545       if ((r->flags & DIR_FLAG_MAYBE) && !dir_exists(out))
546         {
547           msg("Not binding %s on %s (does not exist)\n", out, r->inside);
548           continue;
549         }
550
551       char root_in[1024];
552       snprintf(root_in, sizeof(root_in), "root/%s", in);
553       make_dir(root_in);
554
555       unsigned long mount_flags = 0;
556       if (!(r->flags & DIR_FLAG_RW))
557         mount_flags |= MS_RDONLY;
558       if (r->flags & DIR_FLAG_NOEXEC)
559         mount_flags |= MS_NOEXEC;
560       if (!(r->flags & DIR_FLAG_DEV))
561         mount_flags |= MS_NODEV;
562
563       if (r->flags & DIR_FLAG_FS)
564         {
565           msg("Mounting %s on %s (flags %lx)\n", out, in, mount_flags);
566           if (mount("none", root_in, out, mount_flags, "") < 0)
567             die("Cannot mount %s on %s: %m", out, in);
568         }
569       else
570         {
571           mount_flags |= MS_BIND | MS_NOSUID;
572           msg("Binding %s on %s (flags %lx)\n", out, in, mount_flags);
573           // Most mount flags need remount to work
574           if (mount(out, root_in, "none", mount_flags, "") < 0 ||
575               mount(out, root_in, "none", MS_REMOUNT | mount_flags, "") < 0)
576             die("Cannot mount %s on %s: %m", out, in);
577         }
578     }
579 }
580
581 /*** Control groups ***/
582
583 struct cg_controller_desc {
584   const char *name;
585   int optional;
586 };
587
588 typedef enum {
589   CG_MEMORY = 0,
590   CG_CPUACCT,
591   CG_CPUSET,
592   CG_NUM_CONTROLLERS,
593 } cg_controller;
594
595 static const struct cg_controller_desc cg_controllers[CG_NUM_CONTROLLERS+1] = {
596   [CG_MEMORY]  = { "memory",  0 },
597   [CG_CPUACCT] = { "cpuacct", 0 },
598   [CG_CPUSET]  = { "cpuset",  1 },
599   [CG_NUM_CONTROLLERS] = { NULL, 0 },
600 };
601
602 #define FOREACH_CG_CONTROLLER(_controller) \
603   for (cg_controller (_controller) = 0; \
604       (_controller) < CG_NUM_CONTROLLERS; (_controller)++)
605
606 static const char *cg_controller_name(cg_controller c)
607 {
608   return cg_controllers[c].name;
609 }
610
611 static const int cg_controller_optional(cg_controller c)
612 {
613   return cg_controllers[c].optional;
614 }
615
616 static char cg_name[256];
617
618 #define CG_BUFSIZE 1024
619
620 static void
621 cg_makepath(char *buf, size_t len, cg_controller c, const char *attr)
622 {
623   const char *cg_root = CONFIG_ISOLATE_CGROUP_ROOT;
624   snprintf(buf, len, "%s/%s/%s/%s", cg_root, cg_controller_name(c), cg_name, attr);
625 }
626
627 static int
628 cg_read(cg_controller controller, const char *attr, char *buf)
629 {
630   int maybe = 0;
631   if (attr[0] == '?')
632     {
633       attr++;
634       maybe = 1;
635     }
636
637   char path[256];
638   cg_makepath(path, sizeof(path), controller, attr);
639
640   int fd = open(path, O_RDONLY);
641   if (fd < 0)
642     {
643       if (maybe)
644         return 0;
645       die("Cannot read %s: %m", path);
646     }
647
648   int n = read(fd, buf, CG_BUFSIZE);
649   if (n < 0)
650     {
651       if (maybe)
652         return 0;
653       die("Cannot read %s: %m", path);
654     }
655   if (n >= CG_BUFSIZE - 1)
656     die("Attribute %s too long", path);
657   if (n > 0 && buf[n-1] == '\n')
658     n--;
659   buf[n] = 0;
660
661   if (verbose > 1)
662     msg("CG: Read %s = %s\n", attr, buf);
663
664   close(fd);
665   return 1;
666 }
667
668 static void __attribute__((format(printf,3,4)))
669 cg_write(cg_controller controller, const char *attr, const char *fmt, ...)
670 {
671   int maybe = 0;
672   if (attr[0] == '?')
673     {
674       attr++;
675       maybe = 1;
676     }
677
678   va_list args;
679   va_start(args, fmt);
680
681   char buf[CG_BUFSIZE];
682   int n = vsnprintf(buf, sizeof(buf), fmt, args);
683   if (n >= CG_BUFSIZE)
684     die("cg_write: Value for attribute %s is too long", attr);
685
686   if (verbose > 1)
687     msg("CG: Write %s = %s", attr, buf);
688
689   char path[256];
690   cg_makepath(path, sizeof(path), controller, attr);
691
692   int fd = open(path, O_WRONLY | O_TRUNC);
693   if (fd < 0)
694     {
695       if (maybe)
696         return;
697       else
698         die("Cannot write %s: %m", path);
699     }
700
701   int written = write(fd, buf, n);
702   if (written < 0)
703     {
704       if (maybe)
705         return;
706       else
707         die("Cannot set %s to %s: %m", path, buf);
708     }
709   if (written != n)
710     die("Short write to %s (%d out of %d bytes)", path, written, n);
711
712   close(fd);
713   va_end(args);
714 }
715
716 static void
717 cg_init(void)
718 {
719   if (!cg_enable)
720     return;
721
722   char *cg_root = CONFIG_ISOLATE_CGROUP_ROOT;
723   if (!dir_exists(cg_root))
724     die("Control group filesystem at %s not mounted", cg_root);
725
726   snprintf(cg_name, sizeof(cg_name), "box-%d", box_id);
727   msg("Using control group %s\n", cg_name);
728 }
729
730 static void
731 cg_prepare(void)
732 {
733   if (!cg_enable)
734     return;
735
736   struct stat st;
737   char buf[CG_BUFSIZE];
738   char path[256];
739
740   FOREACH_CG_CONTROLLER(controller)
741     {
742       cg_makepath(path, sizeof(path), controller, "");
743       if (stat(path, &st) >= 0 || errno != ENOENT)
744         {
745           msg("Control group %s already exists, trying to empty it.\n", path);
746           if (rmdir(path) < 0)
747             die("Failed to reset control group %s: %m", path);
748         }
749
750       if (mkdir(path, 0777) < 0 && !cg_controller_optional(controller))
751         die("Failed to create control group %s: %m", path);
752     }
753
754   // If cpuset module is enabled, copy allowed cpus and memory nodes from parent group
755   if (cg_read(CG_CPUSET, "?cpuset.cpus", buf))
756     cg_write(CG_CPUSET, "cpuset.cpus", "%s", buf);
757   if (cg_read(CG_CPUSET, "?cpuset.mems", buf))
758     cg_write(CG_CPUSET, "cpuset.mems", "%s", buf);
759 }
760
761 static void
762 cg_enter(void)
763 {
764   if (!cg_enable)
765     return;
766
767   msg("Entering control group %s\n", cg_name);
768
769   FOREACH_CG_CONTROLLER(controller)
770     {
771       if (cg_controller_optional(controller))
772         cg_write(controller, "?tasks", "%d\n", (int) getpid());
773       else
774         cg_write(controller, "tasks", "%d\n", (int) getpid());
775     }
776
777   if (cg_memory_limit)
778     {
779       cg_write(CG_MEMORY, "memory.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
780       cg_write(CG_MEMORY, "?memory.memsw.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
781     }
782
783   if (cg_timing)
784     cg_write(CG_CPUACCT, "cpuacct.usage", "0\n");
785 }
786
787 static int
788 cg_get_run_time_ms(void)
789 {
790   if (!cg_enable)
791     return 0;
792
793   char buf[CG_BUFSIZE];
794   cg_read(CG_CPUACCT, "cpuacct.usage", buf);
795   unsigned long long ns = atoll(buf);
796   return ns / 1000000;
797 }
798
799 static void
800 cg_stats(void)
801 {
802   if (!cg_enable)
803     return;
804
805   char buf[CG_BUFSIZE];
806
807   // Memory usage statistics
808   unsigned long long mem=0, memsw=0;
809   if (cg_read(CG_MEMORY, "?memory.max_usage_in_bytes", buf))
810     mem = atoll(buf);
811   if (cg_read(CG_MEMORY, "?memory.memsw.max_usage_in_bytes", buf))
812     {
813       memsw = atoll(buf);
814       if (memsw > mem)
815         mem = memsw;
816     }
817   if (mem)
818     meta_printf("cg-mem:%lld\n", mem >> 10);
819 }
820
821 static void
822 cg_remove(void)
823 {
824   char buf[CG_BUFSIZE];
825
826   if (!cg_enable)
827     return;
828
829   FOREACH_CG_CONTROLLER(controller)
830     {
831       if (cg_controller_optional(controller)) {
832         if (!cg_read(controller, "?tasks", buf))
833           continue;
834       } else
835         cg_read(controller, "tasks", buf);
836
837       if (buf[0])
838         die("Some tasks left in controller %s of cgroup %s, failed to remove it",
839             cg_controller_name(controller), cg_name);
840
841       char path[256];
842       cg_makepath(path, sizeof(path), controller, "");
843
844       if (rmdir(path) < 0)
845         die("Cannot remove control group %s: %m", path);
846     }
847 }
848
849 /*** Disk quotas ***/
850
851 static int
852 path_begins_with(char *path, char *with)
853 {
854   while (*with)
855     if (*path++ != *with++)
856       return 0;
857   return (!*with || *with == '/');
858 }
859
860 static char *
861 find_device(char *path)
862 {
863   FILE *f = setmntent("/proc/mounts", "r");
864   if (!f)
865     die("Cannot open /proc/mounts: %m");
866
867   struct mntent *me;
868   int best_len = 0;
869   char *best_dev = NULL;
870   while (me = getmntent(f))
871     {
872       if (!path_begins_with(me->mnt_fsname, "/dev"))
873         continue;
874       if (path_begins_with(path, me->mnt_dir))
875         {
876           int len = strlen(me->mnt_dir);
877           if (len > best_len)
878             {
879               best_len = len;
880               free(best_dev);
881               best_dev = xstrdup(me->mnt_fsname);
882             }
883         }
884     }
885   endmntent(f);
886   return best_dev;
887 }
888
889 static void
890 set_quota(void)
891 {
892   if (!block_quota)
893     return;
894
895   char cwd[PATH_MAX];
896   if (!getcwd(cwd, sizeof(cwd)))
897     die("getcwd: %m");
898
899   char *dev = find_device(cwd);
900   if (!dev)
901     die("Cannot identify filesystem which contains %s", cwd);
902   msg("Quota: Mapped path %s to a filesystem on %s\n", cwd, dev);
903
904   // Sanity check
905   struct stat dev_st, cwd_st;
906   if (stat(dev, &dev_st) < 0)
907     die("Cannot identify block device %s: %m", dev);
908   if (!S_ISBLK(dev_st.st_mode))
909     die("Expected that %s is a block device", dev);
910   if (stat(".", &cwd_st) < 0)
911     die("Cannot stat cwd: %m");
912   if (cwd_st.st_dev != dev_st.st_rdev)
913     die("Identified %s as a filesystem on %s, but it is obviously false", cwd, dev);
914
915   struct dqblk dq = {
916     .dqb_bhardlimit = block_quota,
917     .dqb_bsoftlimit = block_quota,
918     .dqb_ihardlimit = inode_quota,
919     .dqb_isoftlimit = inode_quota,
920     .dqb_valid = QIF_LIMITS,
921   };
922   if (quotactl(QCMD(Q_SETQUOTA, USRQUOTA), dev, box_uid, (caddr_t) &dq) < 0)
923     die("Cannot set disk quota: %m");
924   msg("Quota: Set block quota %d and inode quota %d\n", block_quota, inode_quota);
925
926   free(dev);
927 }
928
929 /*** The keeper process ***/
930
931 static void
932 signal_alarm(int unused UNUSED)
933 {
934   /* Time limit checks are synchronous, so we only schedule them there. */
935   timer_tick = 1;
936   alarm(1);
937 }
938
939 static void
940 signal_int(int unused UNUSED)
941 {
942   /* Interrupts are fatal, so no synchronization requirements. */
943   meta_printf("exitsig:%d\n", SIGINT);
944   err("SG: Interrupted");
945 }
946
947 #define PROC_BUF_SIZE 4096
948 static void
949 read_proc_file(char *buf, char *name, int *fdp)
950 {
951   int c;
952
953   if (!*fdp)
954     {
955       sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
956       *fdp = open(buf, O_RDONLY);
957       if (*fdp < 0)
958         die("open(%s): %m", buf);
959     }
960   lseek(*fdp, 0, SEEK_SET);
961   if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
962     die("read on /proc/$pid/%s: %m", name);
963   if (c >= PROC_BUF_SIZE-1)
964     die("/proc/$pid/%s too long", name);
965   buf[c] = 0;
966 }
967
968 static int
969 get_wall_time_ms(void)
970 {
971   struct timeval now, wall;
972   gettimeofday(&now, NULL);
973   timersub(&now, &start_time, &wall);
974   return wall.tv_sec*1000 + wall.tv_usec/1000;
975 }
976
977 static int
978 get_run_time_ms(struct rusage *rus)
979 {
980   if (cg_timing)
981     return cg_get_run_time_ms();
982
983   if (rus)
984     {
985       struct timeval total;
986       timeradd(&rus->ru_utime, &rus->ru_stime, &total);
987       return total.tv_sec*1000 + total.tv_usec/1000;
988     }
989
990   char buf[PROC_BUF_SIZE], *x;
991   int utime, stime;
992   static int proc_stat_fd;
993
994   read_proc_file(buf, "stat", &proc_stat_fd);
995   x = buf;
996   while (*x && *x != ' ')
997     x++;
998   while (*x == ' ')
999     x++;
1000   if (*x++ != '(')
1001     die("proc stat syntax error 1");
1002   while (*x && (*x != ')' || x[1] != ' '))
1003     x++;
1004   while (*x == ')' || *x == ' ')
1005     x++;
1006   if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
1007     die("proc stat syntax error 2");
1008
1009   return (utime + stime) * 1000 / ticks_per_sec;
1010 }
1011
1012 static void
1013 check_timeout(void)
1014 {
1015   if (wall_timeout)
1016     {
1017       int wall_ms = get_wall_time_ms();
1018       if (wall_ms > wall_timeout)
1019         err("TO: Time limit exceeded (wall clock)");
1020       if (verbose > 1)
1021         fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
1022     }
1023   if (timeout)
1024     {
1025       int ms = get_run_time_ms(NULL);
1026       if (verbose > 1)
1027         fprintf(stderr, "[time check: %d msec]\n", ms);
1028       if (ms > timeout && ms > extra_timeout)
1029         err("TO: Time limit exceeded");
1030     }
1031 }
1032
1033 static void
1034 box_keeper(void)
1035 {
1036   read_errors_from_fd = error_pipes[0];
1037   close(error_pipes[1]);
1038
1039   struct sigaction sa;
1040   bzero(&sa, sizeof(sa));
1041   sa.sa_handler = signal_int;
1042   sigaction(SIGINT, &sa, NULL);
1043
1044   gettimeofday(&start_time, NULL);
1045   ticks_per_sec = sysconf(_SC_CLK_TCK);
1046   if (ticks_per_sec <= 0)
1047     die("Invalid ticks_per_sec!");
1048
1049   if (timeout || wall_timeout)
1050     {
1051       sa.sa_handler = signal_alarm;
1052       sigaction(SIGALRM, &sa, NULL);
1053       alarm(1);
1054     }
1055
1056   for(;;)
1057     {
1058       struct rusage rus;
1059       int stat;
1060       pid_t p;
1061       if (timer_tick)
1062         {
1063           check_timeout();
1064           timer_tick = 0;
1065         }
1066       p = wait4(box_pid, &stat, 0, &rus);
1067       if (p < 0)
1068         {
1069           if (errno == EINTR)
1070             continue;
1071           die("wait4: %m");
1072         }
1073       if (p != box_pid)
1074         die("wait4: unknown pid %d exited!", p);
1075       box_pid = 0;
1076
1077       // Check error pipe if there is an internal error passed from inside the box
1078       char interr[1024];
1079       int n = read(read_errors_from_fd, interr, sizeof(interr) - 1);
1080       if (n > 0)
1081         {
1082           interr[n] = 0;
1083           die("%s", interr);
1084         }
1085
1086       if (WIFEXITED(stat))
1087         {
1088           final_stats(&rus);
1089           if (WEXITSTATUS(stat))
1090             {
1091               meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
1092               err("RE: Exited with error status %d", WEXITSTATUS(stat));
1093             }
1094           if (timeout && total_ms > timeout)
1095             err("TO: Time limit exceeded");
1096           if (wall_timeout && wall_ms > wall_timeout)
1097             err("TO: Time limit exceeded (wall clock)");
1098           flush_line();
1099           fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall)\n",
1100               total_ms/1000, total_ms%1000,
1101               wall_ms/1000, wall_ms%1000);
1102           box_exit(0);
1103         }
1104       else if (WIFSIGNALED(stat))
1105         {
1106           meta_printf("exitsig:%d\n", WTERMSIG(stat));
1107           final_stats(&rus);
1108           err("SG: Caught fatal signal %d", WTERMSIG(stat));
1109         }
1110       else if (WIFSTOPPED(stat))
1111         {
1112           meta_printf("exitsig:%d\n", WSTOPSIG(stat));
1113           final_stats(&rus);
1114           err("SG: Stopped by signal %d", WSTOPSIG(stat));
1115         }
1116       else
1117         die("wait4: unknown status %x, giving up!", stat);
1118     }
1119 }
1120
1121 /*** The process running inside the box ***/
1122
1123 static void
1124 setup_root(void)
1125 {
1126   if (mkdir("root", 0750) < 0 && errno != EEXIST)
1127     die("mkdir('root'): %m");
1128
1129   if (mount("none", "root", "tmpfs", 0, "mode=755") < 0)
1130     die("Cannot mount root ramdisk: %m");
1131
1132   apply_dir_rules();
1133
1134   if (chroot("root") < 0)
1135     die("Chroot failed: %m");
1136
1137   if (chdir("root/box") < 0)
1138     die("Cannot change current directory: %m");
1139 }
1140
1141 static void
1142 setup_credentials(void)
1143 {
1144   if (setresgid(box_gid, box_gid, box_gid) < 0)
1145     die("setresgid: %m");
1146   if (setgroups(0, NULL) < 0)
1147     die("setgroups: %m");
1148   if (setresuid(box_uid, box_uid, box_uid) < 0)
1149     die("setresuid: %m");
1150   setpgrp();
1151 }
1152
1153 static void
1154 setup_fds(void)
1155 {
1156   if (redir_stdin)
1157     {
1158       close(0);
1159       if (open(redir_stdin, O_RDONLY) != 0)
1160         die("open(\"%s\"): %m", redir_stdin);
1161     }
1162   if (redir_stdout)
1163     {
1164       close(1);
1165       if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
1166         die("open(\"%s\"): %m", redir_stdout);
1167     }
1168   if (redir_stderr)
1169     {
1170       close(2);
1171       if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
1172         die("open(\"%s\"): %m", redir_stderr);
1173     }
1174   else
1175     dup2(1, 2);
1176 }
1177
1178 static void
1179 setup_rlim(const char *res_name, int res, rlim_t limit)
1180 {
1181   struct rlimit rl = { .rlim_cur = limit, .rlim_max = limit };
1182   if (setrlimit(res, &rl) < 0)
1183     die("setrlimit(%s, %jd)", res_name, (intmax_t) limit);
1184 }
1185
1186 static void
1187 setup_rlimits(void)
1188 {
1189 #define RLIM(res, val) setup_rlim("RLIMIT_" #res, RLIMIT_##res, val)
1190
1191   if (memory_limit)
1192     RLIM(AS, memory_limit * 1024);
1193
1194   RLIM(STACK, (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY));
1195   RLIM(NOFILE, 64);
1196   RLIM(MEMLOCK, 0);
1197
1198   if (max_processes)
1199     RLIM(NPROC, max_processes);
1200
1201 #undef RLIM
1202 }
1203
1204 static int
1205 box_inside(void *arg)
1206 {
1207   char **args = arg;
1208   write_errors_to_fd = error_pipes[1];
1209   close(error_pipes[0]);
1210
1211   cg_enter();
1212   setup_root();
1213   setup_credentials();
1214   setup_fds();
1215   setup_rlimits();
1216   char **env = setup_environment();
1217
1218   if (set_cwd && chdir(set_cwd))
1219     die("chdir: %m");
1220
1221   execve(args[0], args, env);
1222   die("execve(\"%s\"): %m", args[0]);
1223 }
1224
1225 static void
1226 box_init(void)
1227 {
1228   if (box_id < 0 || box_id >= CONFIG_ISOLATE_NUM_BOXES)
1229     die("Sandbox ID out of range (allowed: 0-%d)", CONFIG_ISOLATE_NUM_BOXES-1);
1230   box_uid = CONFIG_ISOLATE_FIRST_UID + box_id;
1231   box_gid = CONFIG_ISOLATE_FIRST_GID + box_id;
1232
1233   snprintf(box_dir, sizeof(box_dir), "%s/%d", CONFIG_ISOLATE_BOX_DIR, box_id);
1234   make_dir(box_dir);
1235   if (chdir(box_dir) < 0)
1236     die("chdir(%s): %m", box_dir);
1237 }
1238
1239 /*** Commands ***/
1240
1241 static void
1242 init(void)
1243 {
1244   msg("Preparing sandbox directory\n");
1245   xsystem("rm -rf box");
1246   if (mkdir("box", 0700) < 0)
1247     die("Cannot create box: %m");
1248   if (chown("box", orig_uid, orig_gid) < 0)
1249     die("Cannot chown box: %m");
1250
1251   cg_prepare();
1252   set_quota();
1253
1254   puts(box_dir);
1255 }
1256
1257 static void
1258 cleanup(void)
1259 {
1260   if (!dir_exists("box"))
1261     die("Box directory not found, there isn't anything to clean up");
1262
1263   msg("Deleting sandbox directory\n");
1264   xsystem("rm -rf *");
1265   if (rmdir(box_dir) < 0)
1266     die("Cannot remove %s: %m", box_dir);
1267   cg_remove();
1268 }
1269
1270 static void
1271 run(char **argv)
1272 {
1273   if (!dir_exists("box"))
1274     die("Box directory not found, did you run `isolate --init'?");
1275
1276   char cmd[256];
1277   snprintf(cmd, sizeof(cmd), "chown -R %d.%d box", box_uid, box_gid);
1278   xsystem(cmd);
1279   snprintf(cleanup_cmd, sizeof(cleanup_cmd), "chown -R %d.%d box", orig_uid, orig_gid);
1280
1281   if (pipe(error_pipes) < 0)
1282     die("pipe: %m");
1283   for (int i=0; i<2; i++)
1284     if (fcntl(error_pipes[i], F_SETFD, fcntl(error_pipes[i], F_GETFD) | FD_CLOEXEC) < 0 ||
1285         fcntl(error_pipes[i], F_SETFL, fcntl(error_pipes[i], F_GETFL) | O_NONBLOCK) < 0)
1286       die("fcntl on pipe: %m");
1287
1288   box_pid = clone(
1289     box_inside,                 // Function to execute as the body of the new process
1290     argv,                       // Pass our stack
1291     SIGCHLD | CLONE_NEWIPC | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWPID,
1292     argv);                      // Pass the arguments
1293   if (box_pid < 0)
1294     die("clone: %m");
1295   if (!box_pid)
1296     die("clone returned 0");
1297   box_keeper();
1298 }
1299
1300 static void
1301 show_version(void)
1302 {
1303   printf("Process isolator 1.0\n");
1304   printf("(c) 2012 Martin Mares and Bernard Blackham\n");
1305   printf("\nCompile-time configuration:\n");
1306   printf("Sandbox directory: %s\n", CONFIG_ISOLATE_BOX_DIR);
1307   printf("Sandbox credentials: uid=%u-%u gid=%u-%u\n",
1308     CONFIG_ISOLATE_FIRST_UID,
1309     CONFIG_ISOLATE_FIRST_UID + CONFIG_ISOLATE_NUM_BOXES - 1,
1310     CONFIG_ISOLATE_FIRST_GID,
1311     CONFIG_ISOLATE_FIRST_GID + CONFIG_ISOLATE_NUM_BOXES - 1);
1312 }
1313
1314 /*** Options ***/
1315
1316 static void __attribute__((format(printf,1,2)))
1317 usage(const char *msg, ...)
1318 {
1319   if (msg != NULL)
1320     {
1321       va_list args;
1322       va_start(args, msg);
1323       vfprintf(stderr, msg, args);
1324       va_end(args);
1325     }
1326   printf("\
1327 Usage: isolate [<options>] <command>\n\
1328 \n\
1329 Options:\n\
1330 -b, --box-id=<id>\tWhen multiple sandboxes are used in parallel, each must get a unique ID\n\
1331 -c, --cg[=<parent>]\tPut process in a control group (optionally a sub-group of <parent>)\n\
1332     --cg-mem=<size>\tLimit memory usage of the control group to <size> KB\n\
1333     --cg-timing\t\tTime limits affects total run time of the control group\n\
1334 -d, --dir=<dir>\t\tMake a directory <dir> visible inside the sandbox\n\
1335     --dir=<in>=<out>\tMake a directory <out> outside visible as <in> inside\n\
1336     --dir=<in>=\t\tDelete a previously defined directory rule (even a default one)\n\
1337     --dir=...:<opt>\tSpecify options for a rule:\n\
1338 \t\t\t\tdev\tAllow access to special files\n\
1339 \t\t\t\tfs\tMount a filesystem (e.g., --dir=/proc:proc:fs)\n\
1340 \t\t\t\tmaybe\tSkip the rule if <out> does not exist\n\
1341 \t\t\t\tnoexec\tDo not allow execution of binaries\n\
1342 \t\t\t\trw\tAllow read-write access\n\
1343 -E, --env=<var>\t\tInherit the environment variable <var> from the parent process\n\
1344 -E, --env=<var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
1345 -x, --extra-time=<time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
1346 \t\t\tso that its real execution time is reported (seconds, fractions allowed)\n\
1347 -e, --full-env\t\tInherit full environment of the parent process\n\
1348 -m, --mem=<size>\tLimit address space to <size> KB\n\
1349 -M, --meta=<file>\tOutput process information to <file> (name:value)\n\
1350 -q, --quota=<blk>,<ino>\tSet disk quota to <blk> blocks and <ino> inodes\n\
1351 -k, --stack=<size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
1352 -r, --stderr=<file>\tRedirect stderr to <file>\n\
1353 -i, --stdin=<file>\tRedirect stdin from <file>\n\
1354 -o, --stdout=<file>\tRedirect stdout to <file>\n\
1355 -p, --processes[=<max>]\tEnable multiple processes (at most <max> of them); needs --cg\n\
1356 -t, --time=<time>\tSet run time limit (seconds, fractions allowed)\n\
1357 -v, --verbose\t\tBe verbose (use multiple times for even more verbosity)\n\
1358 -w, --wall-time=<time>\tSet wall clock time limit (seconds, fractions allowed)\n\
1359 \n\
1360 Commands:\n\
1361     --init\t\tInitialize sandbox (and its control group when --cg is used)\n\
1362     --run -- <cmd> ...\tRun given command within sandbox\n\
1363     --cleanup\t\tClean up sandbox\n\
1364     --version\t\tDisplay program version and configuration\n\
1365 ");
1366   exit(2);
1367 }
1368
1369 enum opt_code {
1370   OPT_INIT = 256,
1371   OPT_RUN,
1372   OPT_CLEANUP,
1373   OPT_VERSION,
1374   OPT_CG,
1375   OPT_CG_MEM,
1376   OPT_CG_TIMING,
1377 };
1378
1379 static const char short_opts[] = "b:c:d:eE:i:k:m:M:o:p::q:r:t:vw:x:";
1380
1381 static const struct option long_opts[] = {
1382   { "box-id",           1, NULL, 'b' },
1383   { "chdir",            1, NULL, 'c' },
1384   { "cg",               0, NULL, OPT_CG },
1385   { "cg-mem",           1, NULL, OPT_CG_MEM },
1386   { "cg-timing",        0, NULL, OPT_CG_TIMING },
1387   { "cleanup",          0, NULL, OPT_CLEANUP },
1388   { "dir",              1, NULL, 'd' },
1389   { "env",              1, NULL, 'E' },
1390   { "extra-time",       1, NULL, 'x' },
1391   { "full-env",         0, NULL, 'e' },
1392   { "init",             0, NULL, OPT_INIT },
1393   { "mem",              1, NULL, 'm' },
1394   { "meta",             1, NULL, 'M' },
1395   { "processes",        2, NULL, 'p' },
1396   { "quota",            1, NULL, 'q' },
1397   { "run",              0, NULL, OPT_RUN },
1398   { "stack",            1, NULL, 'k' },
1399   { "stderr",           1, NULL, 'r' },
1400   { "stdin",            1, NULL, 'i' },
1401   { "stdout",           1, NULL, 'o' },
1402   { "time",             1, NULL, 't' },
1403   { "verbose",          0, NULL, 'v' },
1404   { "version",          0, NULL, OPT_VERSION },
1405   { "wall-time",        1, NULL, 'w' },
1406   { NULL,               0, NULL, 0 }
1407 };
1408
1409 int
1410 main(int argc, char **argv)
1411 {
1412   int c;
1413   char *sep;
1414   enum opt_code mode = 0;
1415
1416   init_dir_rules();
1417
1418   while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) >= 0)
1419     switch (c)
1420       {
1421       case 'b':
1422         box_id = atoi(optarg);
1423         break;
1424       case 'c':
1425         set_cwd = optarg;
1426         break;
1427       case OPT_CG:
1428         cg_enable = 1;
1429         break;
1430       case 'd':
1431         if (!set_dir_action(optarg))
1432           usage("Invalid directory specified: %s\n", optarg);
1433         break;
1434       case 'e':
1435         pass_environ = 1;
1436         break;
1437       case 'E':
1438         if (!set_env_action(optarg))
1439           usage("Invalid environment specified: %s\n", optarg);
1440         break;
1441       case 'k':
1442         stack_limit = atoi(optarg);
1443         break;
1444       case 'i':
1445         redir_stdin = optarg;
1446         break;
1447       case 'm':
1448         memory_limit = atoi(optarg);
1449         break;
1450       case 'M':
1451         meta_open(optarg);
1452         break;
1453       case 'o':
1454         redir_stdout = optarg;
1455         break;
1456       case 'p':
1457         if (optarg)
1458           max_processes = atoi(optarg);
1459         else
1460           max_processes = 0;
1461         break;
1462       case 'q':
1463         sep = strchr(optarg, ',');
1464         if (!sep)
1465           usage("Invalid quota specified: %s\n", optarg);
1466         block_quota = atoi(optarg);
1467         inode_quota = atoi(sep+1);
1468         break;
1469       case 'r':
1470         redir_stderr = optarg;
1471         break;
1472       case 't':
1473         timeout = 1000*atof(optarg);
1474         break;
1475       case 'v':
1476         verbose++;
1477         break;
1478       case 'w':
1479         wall_timeout = 1000*atof(optarg);
1480         break;
1481       case 'x':
1482         extra_timeout = 1000*atof(optarg);
1483         break;
1484       case OPT_INIT:
1485       case OPT_RUN:
1486       case OPT_CLEANUP:
1487       case OPT_VERSION:
1488         if (!mode || mode == c)
1489           mode = c;
1490         else
1491           usage("Only one command is allowed.\n");
1492         break;
1493       case OPT_CG_MEM:
1494         cg_memory_limit = atoi(optarg);
1495         break;
1496       case OPT_CG_TIMING:
1497         cg_timing = 1;
1498         break;
1499       default:
1500         usage(NULL);
1501       }
1502
1503   if (!mode)
1504     usage("Please specify an isolate command (e.g. --init, --run).\n");
1505   if (mode == OPT_VERSION)
1506     {
1507       show_version();
1508       return 0;
1509     }
1510
1511   if (geteuid())
1512     die("Must be started as root");
1513   orig_uid = getuid();
1514   orig_gid = getgid();
1515
1516   umask(022);
1517   box_init();
1518   cg_init();
1519
1520   switch (mode)
1521     {
1522     case OPT_INIT:
1523       if (optind < argc)
1524         usage("--init mode takes no parameters\n");
1525       init();
1526       break;
1527     case OPT_RUN:
1528       if (optind >= argc)
1529         usage("--run mode requires a command to run\n");
1530       run(argv+optind);
1531       break;
1532     case OPT_CLEANUP:
1533       if (optind < argc)
1534         usage("--cleanup mode takes no parameters\n");
1535       cleanup();
1536       break;
1537     default:
1538       die("Internal error: mode mismatch");
1539     }
1540   exit(0);
1541 }