2 * A Process Isolator based on Linux Containers
4 * (c) 2012 Martin Mares <mj@ucw.cz>
5 * (c) 2012 Bernard Blackham <bernard@blackham.com.au>
26 #include <sys/signal.h>
27 #include <sys/resource.h>
28 #include <sys/mount.h>
31 #define NONRET __attribute__((noreturn))
32 #define UNUSED __attribute__((unused))
33 #define ARRAY_SIZE(a) (int)(sizeof(a)/sizeof(a[0]))
35 static int timeout; /* milliseconds */
36 static int wall_timeout;
37 static int extra_timeout;
38 static int pass_environ;
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;
46 static int cg_memory_limit;
50 static char box_dir[1024];
55 static uid_t orig_uid;
56 static gid_t orig_gid;
58 static int partial_line;
59 static char cleanup_cmd[256];
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;
66 static int error_pipes[2];
67 static int write_errors_to_fd;
68 static int read_errors_from_fd;
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);
77 static FILE *metafile;
80 meta_open(const char *name)
82 if (!strcmp(name, "-"))
87 metafile = fopen(name, "w");
89 die("Failed to open metafile '%s'",name);
95 if (metafile && metafile != stdout)
99 static void __attribute__((format(printf,1,2)))
100 meta_printf(const char *fmt, ...)
107 vfprintf(metafile, fmt, args);
112 final_stats(struct rusage *rus)
114 total_ms = get_run_time_ms(rus);
115 wall_ms = get_wall_time_ms();
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);
126 /*** Messages and exits ***/
129 xsystem(const char *cmd)
131 int ret = system(cmd);
133 die("system(\"%s\"): %m", cmd);
134 if (!WIFEXITED(ret) || WEXITSTATUS(ret))
135 die("system(\"%s\"): Exited with status %d", cmd, ret);
143 kill(-box_pid, SIGKILL);
144 kill(box_pid, SIGKILL);
145 meta_printf("killed:1\n");
150 p = wait4(box_pid, &stat, 0, &rus);
151 while (p < 0 && errno == EINTR);
153 fprintf(stderr, "UGH: Lost track of the process (%m)\n");
158 if (rc < 2 && cleanup_cmd[0])
159 xsystem(cleanup_cmd);
173 /* Report an error of the sandbox itself */
174 static void NONRET __attribute__((format(printf,1,2)))
180 int n = vsnprintf(buf, sizeof(buf), msg, args);
182 if (write_errors_to_fd)
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);
190 // Otherwise, we in the box keeper process, so we report errors normally
192 meta_printf("status:XX\nmessage:%s\n", buf);
198 /* Report an error of the program inside the sandbox */
199 static void NONRET __attribute__((format(printf,1,2)))
205 if (msg[0] && msg[1] && msg[2] == ':' && msg[3] == ' ')
207 meta_printf("status:%c%c\n", msg[0], msg[1]);
211 vsnprintf(buf, sizeof(buf), msg, args);
212 meta_printf("message:%s\n", buf);
218 /* Write a message, but only if in verbose mode */
219 static void __attribute__((format(printf,1,2)))
226 int len = strlen(msg);
228 partial_line = (msg[len-1] != '\n');
229 vfprintf(stderr, msg, args);
235 /*** Utility functions ***/
240 void *p = malloc(size);
242 die("Out of memory");
249 char *p = strdup(str);
251 die("Out of memory");
255 static int dir_exists(char *path)
258 return (stat(path, &st) >= 0 && S_ISDIR(st.st_mode));
261 /*** Environment rules ***/
264 char *var; // Variable to match
265 char *val; // ""=clear, NULL=inherit
267 struct env_rule *next;
270 static struct env_rule *first_env_rule;
271 static struct env_rule **last_env_rule = &first_env_rule;
273 static struct env_rule default_env_rules[] = {
274 { "LIBC_FATAL_STDERR_", "1" }
278 set_env_action(char *a0)
280 struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
281 char *a = (char *)(r+1);
284 char *sep = strchr(a, '=');
296 last_env_rule = &r->next;
302 match_env_var(char *env_entry, struct env_rule *r)
304 if (strncmp(env_entry, r->var, r->var_len))
306 return (env_entry[r->var_len] == '=');
310 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
312 // First remove the variable if already set
314 while (pos < *env_sizep && !match_env_var(env[pos], r))
316 if (pos < *env_sizep)
319 env[pos] = env[*env_sizep];
320 env[*env_sizep] = NULL;
323 // What is the new value?
329 new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
330 sprintf(new, "%s=%s", r->var, r->val);
335 while (environ[pos] && !match_env_var(environ[pos], r))
337 if (!(new = environ[pos]))
341 // Add it at the end of the array
342 env[(*env_sizep)++] = new;
343 env[*env_sizep] = NULL;
347 setup_environment(void)
349 // Link built-in rules with user rules
350 for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
352 default_env_rules[i].next = first_env_rule;
353 first_env_rule = &default_env_rules[i];
356 // Scan the original environment
357 char **orig_env = environ;
359 while (orig_env[orig_size])
362 // For each rule, reserve one more slot and calculate length
364 for (struct env_rule *r = first_env_rule; r; r=r->next)
367 r->var_len = strlen(r->var);
370 // Create a new environment
371 char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
375 memcpy(env, environ, orig_size * sizeof(char *));
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);
386 // Return the new env and pass some gossip
389 fprintf(stderr, "Passing environment:\n");
390 for (int i=0; env[i]; i++)
391 fprintf(stderr, "\t%s\n", env[i]);
396 /*** Directory rules ***/
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;
405 enum dir_rule_flags {
413 static const char * const dir_flag_names[] = { "rw", "noexec", "fs", "maybe", "dev" };
415 static struct dir_rule *first_dir_rule;
416 static struct dir_rule **last_dir_rule = &first_dir_rule;
418 static int add_dir_rule(char *in, char *out, unsigned int flags)
420 // Make sure that "in" is relative
427 if (flags & DIR_FLAG_FS)
429 if (!out || out[0] == '/')
434 if (out && out[0] != '/' && strncmp(out, "./", 2))
438 // Override an existing rule
440 for (r = first_dir_rule; r; r = r->next)
441 if (!strcmp(r->inside, in))
447 r = xmalloc(sizeof(*r));
450 last_dir_rule = &r->next;
458 static unsigned int parse_dir_option(char *opt)
460 for (unsigned int i = 0; i < ARRAY_SIZE(dir_flag_names); i++)
461 if (!strcmp(opt, dir_flag_names[i]))
463 die("Unknown directory option %s", opt);
466 static int set_dir_action(char *arg)
470 char *colon = strchr(arg, ':');
471 unsigned int flags = 0;
475 char *next = strchr(colon, ':');
478 flags |= parse_dir_option(colon);
482 char *eq = strchr(arg, '=');
486 return add_dir_rule(arg, (*eq ? eq : NULL), flags);
490 char *out = xmalloc(1 + strlen(arg) + 1);
491 sprintf(out, "/%s", arg);
492 return add_dir_rule(arg, out, flags);
496 static void init_dir_rules(void)
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");
507 static void make_dir(char *path)
509 char *sep = (path[0] == '/' ? path+1 : path);
513 sep = strchr(sep, '/');
517 if (!dir_exists(path) && mkdir(path, 0777) < 0)
518 die("Cannot create directory %s: %m\n", path);
526 static void apply_dir_rules(void)
528 for (struct dir_rule *r = first_dir_rule; r; r=r->next)
530 char *in = r->inside;
531 char *out = r->outside;
534 msg("Not binding anything on %s\n", r->inside);
538 if ((r->flags & DIR_FLAG_MAYBE) && !dir_exists(out))
540 msg("Not binding %s on %s (does not exist)\n", out, r->inside);
545 snprintf(root_in, sizeof(root_in), "root/%s", in);
548 unsigned long mount_flags = 0;
549 if (!(r->flags & DIR_FLAG_RW))
550 mount_flags |= MS_RDONLY;
551 if (r->flags & DIR_FLAG_NOEXEC)
552 mount_flags |= MS_NOEXEC;
553 if (!(r->flags & DIR_FLAG_DEV))
554 mount_flags |= MS_NODEV;
556 if (r->flags & DIR_FLAG_FS)
558 msg("Mounting %s on %s (flags %lx)\n", out, in, mount_flags);
559 if (mount("none", root_in, out, mount_flags, "") < 0)
560 die("Cannot mount %s on %s: %m", out, in);
564 mount_flags |= MS_BIND | MS_NOSUID;
565 msg("Binding %s on %s (flags %lx)\n", out, in, mount_flags);
566 // Most mount flags need remount to work
567 if (mount(out, root_in, "none", mount_flags, "") < 0 ||
568 mount(out, root_in, "none", MS_REMOUNT | mount_flags, "") < 0)
569 die("Cannot mount %s on %s: %m", out, in);
574 /*** Control groups ***/
576 static char cg_path[256];
578 #define CG_BUFSIZE 1024
581 cg_read(char *attr, char *buf)
591 snprintf(path, sizeof(path), "%s/%s", cg_path, attr);
593 int fd = open(path, O_RDONLY);
598 die("Cannot read %s: %m", path);
601 int n = read(fd, buf, CG_BUFSIZE);
603 die("Cannot read %s: %m", path);
604 if (n >= CG_BUFSIZE - 1)
605 die("Attribute %s too long", path);
606 if (n > 0 && buf[n-1] == '\n')
611 msg("CG: Read %s = %s\n", attr, buf);
617 static void __attribute__((format(printf,2,3)))
618 cg_write(char *attr, char *fmt, ...)
623 char buf[CG_BUFSIZE];
624 int n = vsnprintf(buf, sizeof(buf), fmt, args);
626 die("cg_writef: Value for attribute %s is too long", attr);
629 msg("CG: Write %s = %s", attr, buf);
632 snprintf(path, sizeof(path), "%s/%s", cg_path, attr);
634 int fd = open(path, O_WRONLY | O_TRUNC);
636 die("Cannot write %s: %m", path);
638 int written = write(fd, buf, n);
640 die("Cannot set %s to %s: %m", path, buf);
642 die("Short write to %s (%d out of %d bytes)", path, written, n);
654 char *cg_root = CONFIG_ISOLATE_CGROUP_ROOT;
655 if (!dir_exists(cg_root))
656 die("Control group filesystem at %s not mounted", cg_root);
658 snprintf(cg_path, sizeof(cg_path), "%s/box-%d", cg_root, box_id);
659 msg("Using control group %s\n", cg_path);
669 char buf[CG_BUFSIZE];
671 if (stat(cg_path, &st) >= 0 || errno != ENOENT)
673 msg("Control group %s already exists, trying to empty it.\n", cg_path);
674 if (rmdir(cg_path) < 0)
675 die("Failed to reset control group %s: %m", cg_path);
678 if (mkdir(cg_path, 0777) < 0)
679 die("Failed to create control group %s: %m", cg_path);
681 // If cpuset module is enabled, copy allowed cpus and memory nodes from parent group
682 if (cg_read("?../cpuset.cpus", buf))
683 cg_write("cpuset.cpus", "%s", buf);
684 if (cg_read("?../cpuset.mems", buf))
685 cg_write("cpuset.mems", "%s", buf);
694 msg("Entering control group %s\n", cg_path);
697 if (stat(cg_path, &st) < 0)
698 die("Control group %s does not exist: %m", cg_path);
702 cg_write("memory.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
703 cg_write("memory.memsw.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
707 cg_write("cpuacct.usage", "0\n");
709 cg_write("tasks", "%d\n", (int) getpid());
713 cg_get_run_time_ms(void)
718 char buf[CG_BUFSIZE];
719 cg_read("cpuacct.usage", buf);
720 unsigned long long ns = atoll(buf);
730 char buf[CG_BUFSIZE];
732 // Memory usage statistics
733 unsigned long long mem=0, memsw=0;
734 if (cg_read("?memory.max_usage_in_bytes", buf))
736 if (cg_read("?memory.memsw.max_usage_in_bytes", buf))
743 meta_printf("cg-mem:%lld\n", mem >> 10);
749 char buf[CG_BUFSIZE];
754 cg_read("tasks", buf);
756 die("Some tasks left in control group %s, failed to remove it", cg_path);
758 if (rmdir(cg_path) < 0)
759 die("Cannot remove control group %s: %m", cg_path);
762 /*** The keeper process ***/
765 signal_alarm(int unused UNUSED)
767 /* Time limit checks are synchronous, so we only schedule them there. */
773 signal_int(int unused UNUSED)
775 /* Interrupts are fatal, so no synchronization requirements. */
776 meta_printf("exitsig:%d\n", SIGINT);
777 err("SG: Interrupted");
780 #define PROC_BUF_SIZE 4096
782 read_proc_file(char *buf, char *name, int *fdp)
788 sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
789 *fdp = open(buf, O_RDONLY);
791 die("open(%s): %m", buf);
793 lseek(*fdp, 0, SEEK_SET);
794 if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
795 die("read on /proc/$pid/%s: %m", name);
796 if (c >= PROC_BUF_SIZE-1)
797 die("/proc/$pid/%s too long", name);
802 get_wall_time_ms(void)
804 struct timeval now, wall;
805 gettimeofday(&now, NULL);
806 timersub(&now, &start_time, &wall);
807 return wall.tv_sec*1000 + wall.tv_usec/1000;
811 get_run_time_ms(struct rusage *rus)
814 return cg_get_run_time_ms();
818 struct timeval total;
819 timeradd(&rus->ru_utime, &rus->ru_stime, &total);
820 return total.tv_sec*1000 + total.tv_usec/1000;
823 char buf[PROC_BUF_SIZE], *x;
825 static int proc_stat_fd;
827 read_proc_file(buf, "stat", &proc_stat_fd);
829 while (*x && *x != ' ')
834 die("proc stat syntax error 1");
835 while (*x && (*x != ')' || x[1] != ' '))
837 while (*x == ')' || *x == ' ')
839 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
840 die("proc stat syntax error 2");
842 return (utime + stime) * 1000 / ticks_per_sec;
850 int wall_ms = get_wall_time_ms();
851 if (wall_ms > wall_timeout)
852 err("TO: Time limit exceeded (wall clock)");
854 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
858 int ms = get_run_time_ms(NULL);
860 fprintf(stderr, "[time check: %d msec]\n", ms);
861 if (ms > timeout && ms > extra_timeout)
862 err("TO: Time limit exceeded");
869 read_errors_from_fd = error_pipes[0];
870 close(error_pipes[1]);
873 bzero(&sa, sizeof(sa));
874 sa.sa_handler = signal_int;
875 sigaction(SIGINT, &sa, NULL);
877 gettimeofday(&start_time, NULL);
878 ticks_per_sec = sysconf(_SC_CLK_TCK);
879 if (ticks_per_sec <= 0)
880 die("Invalid ticks_per_sec!");
882 if (timeout || wall_timeout)
884 sa.sa_handler = signal_alarm;
885 sigaction(SIGALRM, &sa, NULL);
899 p = wait4(box_pid, &stat, 0, &rus);
907 die("wait4: unknown pid %d exited!", p);
910 // Check error pipe if there is an internal error passed from inside the box
912 int n = read(read_errors_from_fd, interr, sizeof(interr) - 1);
922 if (WEXITSTATUS(stat))
924 meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
925 err("RE: Exited with error status %d", WEXITSTATUS(stat));
927 if (timeout && total_ms > timeout)
928 err("TO: Time limit exceeded");
929 if (wall_timeout && wall_ms > wall_timeout)
930 err("TO: Time limit exceeded (wall clock)");
932 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall)\n",
933 total_ms/1000, total_ms%1000,
934 wall_ms/1000, wall_ms%1000);
937 else if (WIFSIGNALED(stat))
939 meta_printf("exitsig:%d\n", WTERMSIG(stat));
941 err("SG: Caught fatal signal %d", WTERMSIG(stat));
943 else if (WIFSTOPPED(stat))
945 meta_printf("exitsig:%d\n", WSTOPSIG(stat));
947 err("SG: Stopped by signal %d", WSTOPSIG(stat));
950 die("wait4: unknown status %x, giving up!", stat);
954 /*** The process running inside the box ***/
959 if (mkdir("root", 0750) < 0 && errno != EEXIST)
960 die("mkdir('root'): %m");
962 if (mount("none", "root", "tmpfs", 0, "mode=755") < 0)
963 die("Cannot mount root ramdisk: %m");
967 if (chroot("root") < 0)
968 die("Chroot failed: %m");
970 if (chdir("root/box") < 0)
971 die("Cannot change current directory: %m");
975 setup_credentials(void)
977 if (setresgid(box_gid, box_gid, box_gid) < 0)
978 die("setresgid: %m");
979 if (setgroups(0, NULL) < 0)
980 die("setgroups: %m");
981 if (setresuid(box_uid, box_uid, box_uid) < 0)
982 die("setresuid: %m");
992 if (open(redir_stdin, O_RDONLY) != 0)
993 die("open(\"%s\"): %m", redir_stdin);
998 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
999 die("open(\"%s\"): %m", redir_stdout);
1004 if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
1005 die("open(\"%s\"): %m", redir_stderr);
1012 setup_rlim(const char *res_name, int res, rlim_t limit)
1014 struct rlimit rl = { .rlim_cur = limit, .rlim_max = limit };
1015 if (setrlimit(res, &rl) < 0)
1016 die("setrlimit(%s, %jd)", res_name, (intmax_t) limit);
1022 #define RLIM(res, val) setup_rlim("RLIMIT_" #res, RLIMIT_##res, val)
1025 RLIM(AS, memory_limit * 1024);
1027 RLIM(STACK, (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY));
1032 RLIM(NPROC, max_processes);
1038 box_inside(void *arg)
1041 write_errors_to_fd = error_pipes[1];
1042 close(error_pipes[0]);
1046 setup_credentials();
1049 char **env = setup_environment();
1051 execve(args[0], args, env);
1052 die("execve(\"%s\"): %m", args[0]);
1058 if (box_id < 0 || box_id >= CONFIG_ISOLATE_NUM_BOXES)
1059 die("Sandbox ID out of range (allowed: 0-%d)", CONFIG_ISOLATE_NUM_BOXES-1);
1060 box_uid = CONFIG_ISOLATE_FIRST_UID + box_id;
1061 box_gid = CONFIG_ISOLATE_FIRST_GID + box_id;
1063 snprintf(box_dir, sizeof(box_dir), "%s/%d", CONFIG_ISOLATE_BOX_DIR, box_id);
1065 if (chdir(box_dir) < 0)
1066 die("chdir(%s): %m", box_dir);
1074 msg("Preparing sandbox directory\n");
1075 xsystem("rm -rf box");
1076 if (mkdir("box", 0700) < 0)
1077 die("Cannot create box: %m");
1078 if (chown("box", orig_uid, orig_gid) < 0)
1079 die("Cannot chown box: %m");
1089 if (!dir_exists("box"))
1090 die("Box directory not found, there isn't anything to clean up");
1092 msg("Deleting sandbox directory\n");
1093 xsystem("rm -rf box");
1100 if (!dir_exists("box"))
1101 die("Box directory not found, did you run `isolate --init'?");
1104 snprintf(cmd, sizeof(cmd), "chown -R %d.%d box", box_uid, box_gid);
1106 snprintf(cleanup_cmd, sizeof(cleanup_cmd), "chown -R %d.%d box", orig_uid, orig_gid);
1108 if (pipe(error_pipes) < 0)
1110 for (int i=0; i<2; i++)
1111 if (fcntl(error_pipes[i], F_SETFD, fcntl(error_pipes[i], F_GETFD) | FD_CLOEXEC) < 0 ||
1112 fcntl(error_pipes[i], F_SETFL, fcntl(error_pipes[i], F_GETFL) | O_NONBLOCK) < 0)
1113 die("fcntl on pipe: %m");
1116 box_inside, // Function to execute as the body of the new process
1117 argv, // Pass our stack
1118 SIGCHLD | CLONE_NEWIPC | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWPID,
1119 argv); // Pass the arguments
1123 die("clone returned 0");
1130 printf("Process isolator 1.0\n");
1131 printf("(c) 2012 Martin Mares and Bernard Blackham\n");
1132 printf("\nCompile-time configuration:\n");
1133 printf("Sandbox directory: %s\n", CONFIG_ISOLATE_BOX_DIR);
1134 printf("Sandbox credentials: uid=%u-%u gid=%u-%u\n",
1135 CONFIG_ISOLATE_FIRST_UID,
1136 CONFIG_ISOLATE_FIRST_UID + CONFIG_ISOLATE_NUM_BOXES - 1,
1137 CONFIG_ISOLATE_FIRST_GID,
1138 CONFIG_ISOLATE_FIRST_GID + CONFIG_ISOLATE_NUM_BOXES - 1);
1146 fprintf(stderr, "Invalid arguments!\n");
1148 Usage: isolate [<options>] <command>\n\
1151 -b, --box-id=<id>\tWhen multiple sandboxes are used in parallel, each must get a unique ID\n\
1152 -c, --cg[=<parent>]\tPut process in a control group (optionally a sub-group of <parent>)\n\
1153 --cg-mem=<size>\tLimit memory usage of the control group to <size> KB\n\
1154 --cg-timing\t\tTime limits affects total run time of the control group\n\
1155 -d, --dir=<dir>\t\tMake a directory <dir> visible inside the sandbox\n\
1156 --dir=<in>=<out>\tMake a directory <out> outside visible as <in> inside\n\
1157 --dir=<in>=\t\tDelete a previously defined directory rule (even a default one)\n\
1158 --dir=...:<opt>\tSpecify options for a rule:\n\
1159 \t\t\t\tdev\tAllow access to special files\n\
1160 \t\t\t\tfs\tMount a filesystem (e.g., --dir=/proc:proc:fs)\n\
1161 \t\t\t\tmaybe\tSkip the rule if <out> does not exist\n\
1162 \t\t\t\tnoexec\tDo not allow execution of binaries\n\
1163 \t\t\t\trw\tAllow read-write access\n\
1164 -E, --env=<var>\t\tInherit the environment variable <var> from the parent process\n\
1165 -E, --env=<var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
1166 -x, --extra-time=<time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
1167 \t\t\tso that its real execution time is reported (seconds, fractions allowed)\n\
1168 -e, --full-env\t\tInherit full environment of the parent process\n\
1169 -m, --mem=<size>\tLimit address space to <size> KB\n\
1170 -M, --meta=<file>\tOutput process information to <file> (name:value)\n\
1171 -k, --stack=<size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
1172 -r, --stderr=<file>\tRedirect stderr to <file>\n\
1173 -i, --stdin=<file>\tRedirect stdin from <file>\n\
1174 -o, --stdout=<file>\tRedirect stdout to <file>\n\
1175 -p, --processes[=<max>]\tEnable multiple processes (at most <max> of them); needs --cg\n\
1176 -t, --time=<time>\tSet run time limit (seconds, fractions allowed)\n\
1177 -v, --verbose\t\tBe verbose (use multiple times for even more verbosity)\n\
1178 -w, --wall-time=<time>\tSet wall clock time limit (seconds, fractions allowed)\n\
1181 --init\t\tInitialize sandbox (and its control group when --cg is used)\n\
1182 --run -- <cmd> ...\tRun given command within sandbox\n\
1183 --cleanup\t\tClean up sandbox\n\
1184 --version\t\tDisplay program version and configuration\n\
1198 static const char short_opts[] = "c:d:eE:i:k:m:M:o:p::r:t:vw:x:";
1200 static const struct option long_opts[] = {
1201 { "box-id", 1, NULL, 'b' },
1202 { "cg", 1, NULL, 'c' },
1203 { "cg-mem", 1, NULL, OPT_CG_MEM },
1204 { "cg-timing", 0, NULL, OPT_CG_TIMING },
1205 { "cleanup", 0, NULL, OPT_CLEANUP },
1206 { "dir", 1, NULL, 'd' },
1207 { "env", 1, NULL, 'E' },
1208 { "extra-time", 1, NULL, 'x' },
1209 { "full-env", 0, NULL, 'e' },
1210 { "init", 0, NULL, OPT_INIT },
1211 { "mem", 1, NULL, 'm' },
1212 { "meta", 1, NULL, 'M' },
1213 { "processes", 2, NULL, 'p' },
1214 { "run", 0, NULL, OPT_RUN },
1215 { "stack", 1, NULL, 'k' },
1216 { "stderr", 1, NULL, 'r' },
1217 { "stdin", 1, NULL, 'i' },
1218 { "stdout", 1, NULL, 'o' },
1219 { "time", 1, NULL, 't' },
1220 { "verbose", 0, NULL, 'v' },
1221 { "version", 0, NULL, OPT_VERSION },
1222 { "wall-time", 1, NULL, 'w' },
1223 { NULL, 0, NULL, 0 }
1227 main(int argc, char **argv)
1230 enum opt_code mode = 0;
1234 while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) >= 0)
1238 box_id = atoi(optarg);
1244 if (!set_dir_action(optarg))
1251 if (!set_env_action(optarg))
1255 stack_limit = atoi(optarg);
1258 redir_stdin = optarg;
1261 memory_limit = atoi(optarg);
1267 redir_stdout = optarg;
1271 max_processes = atoi(optarg);
1276 redir_stderr = optarg;
1279 timeout = 1000*atof(optarg);
1285 wall_timeout = 1000*atof(optarg);
1288 extra_timeout = 1000*atof(optarg);
1297 cg_memory_limit = atoi(optarg);
1308 if (mode == OPT_VERSION)
1315 die("Must be started as root");
1316 orig_uid = getuid();
1317 orig_gid = getgid();
1341 die("Internal error: mode mismatch");