]> mj.ucw.cz Git - moe.git/blobdiff - isolate/isolate.c
Isolate: Fix missing short option for box-id.
[moe.git] / isolate / isolate.c
index 72c2149e5afb03202044e84480a059d00e5ee014..c383664619d0698336702e3e2b755b58f97dfed0 100644 (file)
@@ -1,14 +1,14 @@
 /*
- *     A Process Isolator based in Linux Containers
+ *     A Process Isolator based on Linux Containers
  *
  *     (c) 2012 Martin Mares <mj@ucw.cz>
+ *     (c) 2012 Bernard Blackham <bernard@blackham.com.au>
  */
 
 #define _GNU_SOURCE
 
 #include "autoconf.h"
 
-// FIXME: prune
 #include <errno.h>
 #include <stdio.h>
 #include <fcntl.h>
 #include <sched.h>
 #include <time.h>
 #include <grp.h>
+#include <mntent.h>
+#include <limits.h>
 #include <sys/wait.h>
-#include <sys/user.h>
 #include <sys/time.h>
-#include <sys/ptrace.h>
 #include <sys/signal.h>
-#include <sys/sysinfo.h>
 #include <sys/resource.h>
 #include <sys/mount.h>
 #include <sys/stat.h>
+#include <sys/quota.h>
+#include <sys/vfs.h>
 
 #define NONRET __attribute__((noreturn))
 #define UNUSED __attribute__((unused))
 #define ARRAY_SIZE(a) (int)(sizeof(a)/sizeof(a[0]))
 
-// FIXME: Make configurable, probably in compile time
-#define BOX_DIR "/tmp/box"
-#define BOX_UID 60000
-#define BOX_GID 60000
-
 static int timeout;                    /* milliseconds */
 static int wall_timeout;
 static int extra_timeout;
@@ -47,30 +43,40 @@ static int pass_environ;
 static int verbose;
 static int memory_limit;
 static int stack_limit;
+static int block_quota;
+static int inode_quota;
 static int max_processes = 1;
 static char *redir_stdin, *redir_stdout, *redir_stderr;
 
 static int cg_enable;
 static int cg_memory_limit;
 static int cg_timing;
-static char *cg_root = "/sys/fs/cgroup";
 
+static int box_id;
+static char box_dir[1024];
+static pid_t box_pid;
+
+static uid_t box_uid;
+static gid_t box_gid;
 static uid_t orig_uid;
 static gid_t orig_gid;
 
-static pid_t box_pid;
-static volatile sig_atomic_t timer_tick;
-static struct timeval start_time;
-static int ticks_per_sec;
 static int partial_line;
 static char cleanup_cmd[256];
 
+static struct timeval start_time;
+static int ticks_per_sec;
 static int total_ms, wall_ms;
+static volatile sig_atomic_t timer_tick;
+
+static int error_pipes[2];
+static int write_errors_to_fd;
+static int read_errors_from_fd;
 
 static void die(char *msg, ...) NONRET;
 static void cg_stats(void);
 static int get_wall_time_ms(void);
-static int get_run_time_ms(void);
+static int get_run_time_ms(struct rusage *rus);
 
 /*** Meta-files ***/
 
@@ -111,7 +117,7 @@ meta_printf(const char *fmt, ...)
 static void
 final_stats(struct rusage *rus)
 {
-  total_ms = get_run_time_ms();
+  total_ms = get_run_time_ms(rus);
   wall_ms = get_wall_time_ms();
 
   meta_printf("time:%d.%03d\n", total_ms/1000, total_ms%1000);
@@ -176,9 +182,19 @@ die(char *msg, ...)
 {
   va_list args;
   va_start(args, msg);
-  flush_line();
   char buf[1024];
-  vsnprintf(buf, sizeof(buf), msg, args);
+  int n = vsnprintf(buf, sizeof(buf), msg, args);
+
+  if (write_errors_to_fd)
+    {
+      // We are inside the box, have to use error pipe for error reporting.
+      // We hope that the whole error message fits in PIPE_BUF bytes.
+      write(write_errors_to_fd, buf, n);
+      exit(2);
+    }
+
+  // Otherwise, we in the box keeper process, so we report errors normally
+  flush_line();
   meta_printf("status:XX\nmessage:%s\n", buf);
   fputs(buf, stderr);
   fputc('\n', stderr);
@@ -222,6 +238,8 @@ msg(char *msg, ...)
   va_end(args);
 }
 
+/*** Utility functions ***/
+
 static void *
 xmalloc(size_t size)
 {
@@ -231,6 +249,21 @@ xmalloc(size_t size)
   return p;
 }
 
+static char *
+xstrdup(char *str)
+{
+  char *p = strdup(str);
+  if (!p)
+    die("Out of memory");
+  return p;
+}
+
+static int dir_exists(char *path)
+{
+  struct stat st;
+  return (stat(path, &st) >= 0 && S_ISDIR(st.st_mode));
+}
+
 /*** Environment rules ***/
 
 struct env_rule {
@@ -366,6 +399,184 @@ setup_environment(void)
   return env;
 }
 
+/*** Directory rules ***/
+
+struct dir_rule {
+  char *inside;                        // A relative path
+  char *outside;               // This can be an absolute path or a relative path starting with "./"
+  unsigned int flags;          // DIR_FLAG_xxx
+  struct dir_rule *next;
+};
+
+enum dir_rule_flags {
+  DIR_FLAG_RW = 1,
+  DIR_FLAG_NOEXEC = 2,
+  DIR_FLAG_FS = 4,
+  DIR_FLAG_MAYBE = 8,
+  DIR_FLAG_DEV = 16,
+};
+
+static const char * const dir_flag_names[] = { "rw", "noexec", "fs", "maybe", "dev" };
+
+static struct dir_rule *first_dir_rule;
+static struct dir_rule **last_dir_rule = &first_dir_rule;
+
+static int add_dir_rule(char *in, char *out, unsigned int flags)
+{
+  // Make sure that "in" is relative
+  while (in[0] == '/')
+    in++;
+  if (!*in)
+    return 0;
+
+  // Check "out"
+  if (flags & DIR_FLAG_FS)
+    {
+      if (!out || out[0] == '/')
+       return 0;
+    }
+  else
+    {
+      if (out && out[0] != '/' && strncmp(out, "./", 2))
+       return 0;
+    }
+
+  // Override an existing rule
+  struct dir_rule *r;
+  for (r = first_dir_rule; r; r = r->next)
+    if (!strcmp(r->inside, in))
+      break;
+
+  // Add a new rule
+  if (!r)
+    {
+      r = xmalloc(sizeof(*r));
+      r->inside = in;
+      *last_dir_rule = r;
+      last_dir_rule = &r->next;
+      r->next = NULL;
+    }
+  r->outside = out;
+  r->flags = flags;
+  return 1;
+}
+
+static unsigned int parse_dir_option(char *opt)
+{
+  for (unsigned int i = 0; i < ARRAY_SIZE(dir_flag_names); i++)
+    if (!strcmp(opt, dir_flag_names[i]))
+      return 1U << i;
+  die("Unknown directory option %s", opt);
+}
+
+static int set_dir_action(char *arg)
+{
+  arg = xstrdup(arg);
+
+  char *colon = strchr(arg, ':');
+  unsigned int flags = 0;
+  while (colon)
+    {
+      *colon++ = 0;
+      char *next = strchr(colon, ':');
+      if (next)
+       *next = 0;
+      flags |= parse_dir_option(colon);
+      colon = next;
+    }
+
+  char *eq = strchr(arg, '=');
+  if (eq)
+    {
+      *eq++ = 0;
+      return add_dir_rule(arg, (*eq ? eq : NULL), flags);
+    }
+  else
+    {
+      char *out = xmalloc(1 + strlen(arg) + 1);
+      sprintf(out, "/%s", arg);
+      return add_dir_rule(arg, out, flags);
+    }
+}
+
+static void init_dir_rules(void)
+{
+  set_dir_action("box=./box:rw");
+  set_dir_action("bin");
+  set_dir_action("dev:dev");
+  set_dir_action("lib");
+  set_dir_action("lib64:maybe");
+  set_dir_action("proc=proc:fs");
+  set_dir_action("usr");
+}
+
+static void make_dir(char *path)
+{
+  char *sep = (path[0] == '/' ? path+1 : path);
+
+  for (;;)
+    {
+      sep = strchr(sep, '/');
+      if (sep)
+       *sep = 0;
+
+      if (!dir_exists(path) && mkdir(path, 0777) < 0)
+       die("Cannot create directory %s: %m\n", path);
+
+      if (!sep)
+       return;
+      *sep++ = '/';
+    }
+}
+
+static void apply_dir_rules(void)
+{
+  for (struct dir_rule *r = first_dir_rule; r; r=r->next)
+    {
+      char *in = r->inside;
+      char *out = r->outside;
+      if (!out)
+       {
+         msg("Not binding anything on %s\n", r->inside);
+         continue;
+       }
+
+      if ((r->flags & DIR_FLAG_MAYBE) && !dir_exists(out))
+       {
+         msg("Not binding %s on %s (does not exist)\n", out, r->inside);
+         continue;
+       }
+
+      char root_in[1024];
+      snprintf(root_in, sizeof(root_in), "root/%s", in);
+      make_dir(root_in);
+
+      unsigned long mount_flags = 0;
+      if (!(r->flags & DIR_FLAG_RW))
+       mount_flags |= MS_RDONLY;
+      if (r->flags & DIR_FLAG_NOEXEC)
+       mount_flags |= MS_NOEXEC;
+      if (!(r->flags & DIR_FLAG_DEV))
+       mount_flags |= MS_NODEV;
+
+      if (r->flags & DIR_FLAG_FS)
+       {
+         msg("Mounting %s on %s (flags %lx)\n", out, in, mount_flags);
+         if (mount("none", root_in, out, mount_flags, "") < 0)
+           die("Cannot mount %s on %s: %m", out, in);
+       }
+      else
+       {
+         mount_flags |= MS_BIND | MS_NOSUID;
+         msg("Binding %s on %s (flags %lx)\n", out, in, mount_flags);
+         // Most mount flags need remount to work
+         if (mount(out, root_in, "none", mount_flags, "") < 0 ||
+             mount(out, root_in, "none", MS_REMOUNT | mount_flags, "") < 0)
+           die("Cannot mount %s on %s: %m", out, in);
+       }
+    }
+}
+
 /*** Control groups ***/
 
 static char cg_path[256];
@@ -446,11 +657,11 @@ cg_init(void)
   if (!cg_enable)
     return;
 
-  struct stat st;
-  if (stat(cg_root, &st) < 0 || !S_ISDIR(st.st_mode))
+  char *cg_root = CONFIG_ISOLATE_CGROUP_ROOT;
+  if (!dir_exists(cg_root))
     die("Control group filesystem at %s not mounted", cg_root);
 
-  snprintf(cg_path, sizeof(cg_path), "%s/box-%d", cg_root, BOX_UID);
+  snprintf(cg_path, sizeof(cg_path), "%s/box-%d", cg_root, box_id);
   msg("Using control group %s\n", cg_path);
 }
 
@@ -550,13 +761,90 @@ cg_remove(void)
   if (buf[0])
     die("Some tasks left in control group %s, failed to remove it", cg_path);
 
-  // FIXME: Is this needed?
-  // cg_write("memory.force_empty", "0\n");
-
   if (rmdir(cg_path) < 0)
     die("Cannot remove control group %s: %m", cg_path);
 }
 
+/*** Disk quotas ***/
+
+static int
+path_begins_with(char *path, char *with)
+{
+  while (*with)
+    if (*path++ != *with++)
+      return 0;
+  return (!*with || *with == '/');
+}
+
+static char *
+find_device(char *path)
+{
+  FILE *f = setmntent("/proc/mounts", "r");
+  if (!f)
+    die("Cannot open /proc/mounts: %m");
+
+  struct mntent *me;
+  int best_len = 0;
+  char *best_dev = NULL;
+  while (me = getmntent(f))
+    {
+      if (!path_begins_with(me->mnt_fsname, "/dev"))
+       continue;
+      if (path_begins_with(path, me->mnt_dir))
+       {
+         int len = strlen(me->mnt_dir);
+         if (len > best_len)
+           {
+             best_len = len;
+             free(best_dev);
+             best_dev = xstrdup(me->mnt_fsname);
+           }
+       }
+    }
+  endmntent(f);
+  return best_dev;
+}
+
+static void
+set_quota(void)
+{
+  if (!block_quota)
+    return;
+
+  char cwd[PATH_MAX];
+  if (!getcwd(cwd, sizeof(cwd)))
+    die("getcwd: %m");
+
+  char *dev = find_device(cwd);
+  if (!dev)
+    die("Cannot identify filesystem which contains %s", cwd);
+  msg("Quota: Mapped path %s to a filesystem on %s\n", cwd, dev);
+
+  // Sanity check
+  struct stat dev_st, cwd_st;
+  if (stat(dev, &dev_st) < 0)
+    die("Cannot identify block device %s: %m", dev);
+  if (!S_ISBLK(dev_st.st_mode))
+    die("Expected that %s is a block device", dev);
+  if (stat(".", &cwd_st) < 0)
+    die("Cannot stat cwd: %m");
+  if (cwd_st.st_dev != dev_st.st_rdev)
+    die("Identified %s as a filesystem on %s, but it is obviously false", cwd, dev);
+
+  struct dqblk dq = {
+    .dqb_bhardlimit = block_quota,
+    .dqb_bsoftlimit = block_quota,
+    .dqb_ihardlimit = inode_quota,
+    .dqb_isoftlimit = inode_quota,
+    .dqb_valid = QIF_LIMITS,
+  };
+  if (quotactl(QCMD(Q_SETQUOTA, USRQUOTA), dev, box_uid, (caddr_t) &dq) < 0)
+    die("Cannot set disk quota: %m");
+  msg("Quota: Set block quota %d and inode quota %d\n", block_quota, inode_quota);
+
+  free(dev);
+}
+
 /*** The keeper process ***/
 
 static void
@@ -606,11 +894,18 @@ get_wall_time_ms(void)
 }
 
 static int
-get_run_time_ms(void)
+get_run_time_ms(struct rusage *rus)
 {
   if (cg_timing)
     return cg_get_run_time_ms();
 
+  if (rus)
+    {
+      struct timeval total;
+      timeradd(&rus->ru_utime, &rus->ru_stime, &total);
+      return total.tv_sec*1000 + total.tv_usec/1000;
+    }
+
   char buf[PROC_BUF_SIZE], *x;
   int utime, stime;
   static int proc_stat_fd;
@@ -646,7 +941,7 @@ check_timeout(void)
     }
   if (timeout)
     {
-      int ms = get_run_time_ms();
+      int ms = get_run_time_ms(NULL);
       if (verbose > 1)
        fprintf(stderr, "[time check: %d msec]\n", ms);
       if (ms > timeout && ms > extra_timeout)
@@ -657,8 +952,10 @@ check_timeout(void)
 static void
 box_keeper(void)
 {
-  struct sigaction sa;
+  read_errors_from_fd = error_pipes[0];
+  close(error_pipes[1]);
 
+  struct sigaction sa;
   bzero(&sa, sizeof(sa));
   sa.sa_handler = signal_int;
   sigaction(SIGINT, &sa, NULL);
@@ -694,13 +991,22 @@ box_keeper(void)
        }
       if (p != box_pid)
        die("wait4: unknown pid %d exited!", p);
+      box_pid = 0;
+
+      // Check error pipe if there is an internal error passed from inside the box
+      char interr[1024];
+      int n = read(read_errors_from_fd, interr, sizeof(interr) - 1);
+      if (n > 0)
+       {
+         interr[n] = 0;
+         die("%s", interr);
+       }
+
       if (WIFEXITED(stat))
        {
-         box_pid = 0;
          final_stats(&rus);
          if (WEXITSTATUS(stat))
            {
-             // FIXME: Recognize internal errors during setup
              meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
              err("RE: Exited with error status %d", WEXITSTATUS(stat));
            }
@@ -714,16 +1020,14 @@ box_keeper(void)
              wall_ms/1000, wall_ms%1000);
          box_exit(0);
        }
-      if (WIFSIGNALED(stat))
+      else if (WIFSIGNALED(stat))
        {
-         box_pid = 0;
          meta_printf("exitsig:%d\n", WTERMSIG(stat));
          final_stats(&rus);
          err("SG: Caught fatal signal %d", WTERMSIG(stat));
        }
-      if (WIFSTOPPED(stat))
+      else if (WIFSTOPPED(stat))
        {
-         box_pid = 0;
          meta_printf("exitsig:%d\n", WSTOPSIG(stat));
          final_stats(&rus);
          err("SG: Stopped by signal %d", WSTOPSIG(stat));
@@ -744,27 +1048,7 @@ setup_root(void)
   if (mount("none", "root", "tmpfs", 0, "mode=755") < 0)
     die("Cannot mount root ramdisk: %m");
 
-  // FIXME: Make the list of bind-mounts configurable
-  // FIXME: Virtual /dev?
-  // FIXME: Read-only mounts?
-
-  static const char * const dirs[] = { "box", "/bin", "/lib", "/usr", "/dev" };
-  for (int i=0; i < ARRAY_SIZE(dirs); i++)
-    {
-      const char *d = dirs[i];
-      char buf[1024];  // FIXME
-      sprintf(buf, "root/%s", (d[0] == '/' ? d+1 : d));
-      msg("Binding %s on %s\n", d, buf);
-      if (mkdir(buf, 0755) < 0)
-       die("mkdir(%s): %m", buf);
-      if (mount(d, buf, "none", MS_BIND | MS_NOSUID | MS_NODEV, "") < 0)
-       die("Cannot bind %s on %s: %m", d, buf);
-    }
-
-  if (mkdir("root/proc", 0755) < 0)
-    die("Cannot create proc: %m");
-  if (mount("none", "root/proc", "proc", 0, "") < 0)
-    die("Cannot mount proc: %m");
+  apply_dir_rules();
 
   if (chroot("root") < 0)
     die("Chroot failed: %m");
@@ -773,30 +1057,21 @@ setup_root(void)
     die("Cannot change current directory: %m");
 }
 
-static int
-box_inside(void *arg)
+static void
+setup_credentials(void)
 {
-  char **argv = arg;
-  int argc = 0;
-  while (argv[argc])
-    argc++;
-
-  struct rlimit rl;
-  char *args[argc+1];
-
-  memcpy(args, argv, argc * sizeof(char *));
-  args[argc] = NULL;
-
-  cg_enter();
-  setup_root();
-
-  if (setresgid(BOX_GID, BOX_GID, BOX_GID) < 0)
+  if (setresgid(box_gid, box_gid, box_gid) < 0)
     die("setresgid: %m");
   if (setgroups(0, NULL) < 0)
     die("setgroups: %m");
-  if (setresuid(BOX_UID, BOX_UID, BOX_UID) < 0)
+  if (setresuid(box_uid, box_uid, box_uid) < 0)
     die("setresuid: %m");
+  setpgrp();
+}
 
+static void
+setup_fds(void)
+{
   if (redir_stdin)
     {
       close(0);
@@ -817,39 +1092,68 @@ box_inside(void *arg)
     }
   else
     dup2(1, 2);
-  setpgrp();
+}
 
-  if (memory_limit)
-    {
-      rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
-      if (setrlimit(RLIMIT_AS, &rl) < 0)
-       die("setrlimit(RLIMIT_AS): %m");
-    }
+static void
+setup_rlim(const char *res_name, int res, rlim_t limit)
+{
+  struct rlimit rl = { .rlim_cur = limit, .rlim_max = limit };
+  if (setrlimit(res, &rl) < 0)
+    die("setrlimit(%s, %jd)", res_name, (intmax_t) limit);
+}
+
+static void
+setup_rlimits(void)
+{
+#define RLIM(res, val) setup_rlim("RLIMIT_" #res, RLIMIT_##res, val)
 
-  rl.rlim_cur = rl.rlim_max = (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY);
-  if (setrlimit(RLIMIT_STACK, &rl) < 0)
-    die("setrlimit(RLIMIT_STACK): %m");
+  if (memory_limit)
+    RLIM(AS, memory_limit * 1024);
 
-  rl.rlim_cur = rl.rlim_max = 64;
-  if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
-    die("setrlimit(RLIMIT_NOFILE): %m");
+  RLIM(STACK, (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY));
+  RLIM(NOFILE, 64);
+  RLIM(MEMLOCK, 0);
 
   if (max_processes)
-    {
-      rl.rlim_cur = rl.rlim_max = max_processes;
-      if (setrlimit(RLIMIT_NPROC, &rl) < 0)
-       die("setrlimit(RLIMIT_NPROC): %m");
-    }
+    RLIM(NPROC, max_processes);
 
-  rl.rlim_cur = rl.rlim_max = 0;
-  if (setrlimit(RLIMIT_MEMLOCK, &rl) < 0)
-    die("setrlimit(RLIMIT_MEMLOCK): %m");
+#undef RLIM
+}
 
+static int
+box_inside(void *arg)
+{
+  char **args = arg;
+  write_errors_to_fd = error_pipes[1];
+  close(error_pipes[0]);
+
+  cg_enter();
+  setup_root();
+  setup_credentials();
+  setup_fds();
+  setup_rlimits();
   char **env = setup_environment();
+
   execve(args[0], args, env);
   die("execve(\"%s\"): %m", args[0]);
 }
 
+static void
+box_init(void)
+{
+  if (box_id < 0 || box_id >= CONFIG_ISOLATE_NUM_BOXES)
+    die("Sandbox ID out of range (allowed: 0-%d)", CONFIG_ISOLATE_NUM_BOXES-1);
+  box_uid = CONFIG_ISOLATE_FIRST_UID + box_id;
+  box_gid = CONFIG_ISOLATE_FIRST_GID + box_id;
+
+  snprintf(box_dir, sizeof(box_dir), "%s/%d", CONFIG_ISOLATE_BOX_DIR, box_id);
+  make_dir(box_dir);
+  if (chdir(box_dir) < 0)
+    die("chdir(%s): %m", box_dir);
+}
+
+/*** Commands ***/
+
 static void
 init(void)
 {
@@ -861,32 +1165,42 @@ init(void)
     die("Cannot chown box: %m");
 
   cg_prepare();
+  set_quota();
+
+  puts(box_dir);
 }
 
 static void
 cleanup(void)
 {
-  struct stat st;
-  if (stat("box", &st) < 0 || !S_ISDIR(st.st_mode))
+  if (!dir_exists("box"))
     die("Box directory not found, there isn't anything to clean up");
 
   msg("Deleting sandbox directory\n");
-  xsystem("rm -rf box");
+  xsystem("rm -rf *");
+  if (rmdir(box_dir) < 0)
+    die("Cannot remove %s: %m", box_dir);
   cg_remove();
 }
 
 static void
 run(char **argv)
 {
-  struct stat st;
-  if (stat("box", &st) < 0 || !S_ISDIR(st.st_mode))
+  if (!dir_exists("box"))
     die("Box directory not found, did you run `isolate --init'?");
 
   char cmd[256];
-  snprintf(cmd, sizeof(cmd), "chown -R %d.%d box", BOX_UID, BOX_GID);
+  snprintf(cmd, sizeof(cmd), "chown -R %d.%d box", box_uid, box_gid);
   xsystem(cmd);
   snprintf(cleanup_cmd, sizeof(cleanup_cmd), "chown -R %d.%d box", orig_uid, orig_gid);
 
+  if (pipe(error_pipes) < 0)
+    die("pipe: %m");
+  for (int i=0; i<2; i++)
+    if (fcntl(error_pipes[i], F_SETFD, fcntl(error_pipes[i], F_GETFD) | FD_CLOEXEC) < 0 ||
+        fcntl(error_pipes[i], F_SETFL, fcntl(error_pipes[i], F_GETFL) | O_NONBLOCK) < 0)
+      die("fcntl on pipe: %m");
+
   box_pid = clone(
     box_inside,                        // Function to execute as the body of the new process
     argv,                      // Pass our stack
@@ -902,13 +1216,19 @@ run(char **argv)
 static void
 show_version(void)
 {
-  // FIXME
-  printf("Process isolator 0.0\n");
-  printf("(c) 2012 Martin Mares <mj@ucw.cz>\n\n");
-  printf("Sandbox directory: %s\n", BOX_DIR);
-  printf("Sandbox credentials: uid=%u gid=%u\n", BOX_UID, BOX_GID);
+  printf("Process isolator 1.0\n");
+  printf("(c) 2012 Martin Mares and Bernard Blackham\n");
+  printf("\nCompile-time configuration:\n");
+  printf("Sandbox directory: %s\n", CONFIG_ISOLATE_BOX_DIR);
+  printf("Sandbox credentials: uid=%u-%u gid=%u-%u\n",
+    CONFIG_ISOLATE_FIRST_UID,
+    CONFIG_ISOLATE_FIRST_UID + CONFIG_ISOLATE_NUM_BOXES - 1,
+    CONFIG_ISOLATE_FIRST_GID,
+    CONFIG_ISOLATE_FIRST_GID + CONFIG_ISOLATE_NUM_BOXES - 1);
 }
 
+/*** Options ***/
+
 static void
 usage(void)
 {
@@ -917,16 +1237,27 @@ usage(void)
 Usage: isolate [<options>] <command>\n\
 \n\
 Options:\n\
+-b, --box-id=<id>\tWhen multiple sandboxes are used in parallel, each must get a unique ID\n\
 -c, --cg[=<parent>]\tPut process in a control group (optionally a sub-group of <parent>)\n\
     --cg-mem=<size>\tLimit memory usage of the control group to <size> KB\n\
     --cg-timing\t\tTime limits affects total run time of the control group\n\
--E, --env=<var>\tInherit the environment variable <var> from the parent process\n\
+-d, --dir=<dir>\t\tMake a directory <dir> visible inside the sandbox\n\
+    --dir=<in>=<out>\tMake a directory <out> outside visible as <in> inside\n\
+    --dir=<in>=\t\tDelete a previously defined directory rule (even a default one)\n\
+    --dir=...:<opt>\tSpecify options for a rule:\n\
+\t\t\t\tdev\tAllow access to special files\n\
+\t\t\t\tfs\tMount a filesystem (e.g., --dir=/proc:proc:fs)\n\
+\t\t\t\tmaybe\tSkip the rule if <out> does not exist\n\
+\t\t\t\tnoexec\tDo not allow execution of binaries\n\
+\t\t\t\trw\tAllow read-write access\n\
+-E, --env=<var>\t\tInherit the environment variable <var> from the parent process\n\
 -E, --env=<var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
 -x, --extra-time=<time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
 \t\t\tso that its real execution time is reported (seconds, fractions allowed)\n\
 -e, --full-env\t\tInherit full environment of the parent process\n\
 -m, --mem=<size>\tLimit address space to <size> KB\n\
 -M, --meta=<file>\tOutput process information to <file> (name:value)\n\
+-q, --quota=<blk>,<ino>\tSet disk quota to <blk> blocks and <ino> inodes\n\
 -k, --stack=<size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
 -r, --stderr=<file>\tRedirect stderr to <file>\n\
 -i, --stdin=<file>\tRedirect stdin from <file>\n\
@@ -954,13 +1285,15 @@ enum opt_code {
   OPT_CG_TIMING,
 };
 
-static const char short_opts[] = "c::eE:i:k:m:M:o:p::r:t:vw:x:";
+static const char short_opts[] = "b:c:d:eE:i:k:m:M:o:p::q:r:t:vw:x:";
 
 static const struct option long_opts[] = {
-  { "cg",              2, NULL, 'c' },
+  { "box-id",          1, NULL, 'b' },
+  { "cg",              1, NULL, 'c' },
   { "cg-mem",          1, NULL, OPT_CG_MEM },
   { "cg-timing",       0, NULL, OPT_CG_TIMING },
   { "cleanup",         0, NULL, OPT_CLEANUP },
+  { "dir",             1, NULL, 'd' },
   { "env",             1, NULL, 'E' },
   { "extra-time",      1, NULL, 'x' },
   { "full-env",                0, NULL, 'e' },
@@ -968,6 +1301,7 @@ static const struct option long_opts[] = {
   { "mem",             1, NULL, 'm' },
   { "meta",            1, NULL, 'M' },
   { "processes",       2, NULL, 'p' },
+  { "quota",           1, NULL, 'q' },
   { "run",             0, NULL, OPT_RUN },
   { "stack",           1, NULL, 'k' },
   { "stderr",          1, NULL, 'r' },
@@ -984,16 +1318,24 @@ int
 main(int argc, char **argv)
 {
   int c;
+  char *sep;
   enum opt_code mode = 0;
 
+  init_dir_rules();
+
   while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) >= 0)
     switch (c)
       {
+      case 'b':
+       box_id = atoi(optarg);
+       break;
       case 'c':
-       if (optarg)
-         cg_root = optarg;
        cg_enable = 1;
        break;
+      case 'd':
+       if (!set_dir_action(optarg))
+         usage();
+       break;
       case 'e':
        pass_environ = 1;
        break;
@@ -1022,6 +1364,13 @@ main(int argc, char **argv)
        else
          max_processes = 0;
        break;
+      case 'q':
+       sep = strchr(optarg, ',');
+       if (!sep)
+         usage();
+       block_quota = atoi(optarg);
+       inode_quota = atoi(sep+1);
+       break;
       case 'r':
        redir_stderr = optarg;
        break;
@@ -1067,8 +1416,7 @@ main(int argc, char **argv)
   orig_gid = getgid();
 
   umask(022);
-  if (chdir(BOX_DIR) < 0)
-    die("chdir(%s): %m", BOX_DIR);
+  box_init();
   cg_init();
 
   switch (mode)