#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <linux/landlock.h>
#include <linux/netlink.h>
#include <seccomp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>

/* Primero a gente declara os acessos que o Landlock vai governar.
   A gente declara aqui todos os acessos que o Landlock conhece.
   Isso quer dizer que tudo o que o Lanlock conhece vai ser negado
   por padrão. Depois a gente faz regras pra liberar o acesso por
   recurso.
*/

/*
  Aqui uma pegadinha. A abi do Landlock já está na versão 9, mas meu sistema
  roda um kernel que tem a abi 6. Então aqui eu defino o que não existe na
  abi 6 pra eu poder referenciar e compilar no meu sistema. Eu defino
  assim pra que quando eu atualizar meu kernel pra uma abi mais nova eu
  não precise alterar o código, ele já suporta a abi mais nova.
*/

/* FS_RESOLVE_UNIX incluído na abi 9 */
#ifndef LANDLOCK_ACCESS_FS_RESOLVE_UNIX
#define LANDLOCK_ACCESS_FS_RESOLVE_UNIX (1ULL << 16)
#endif

/* Os próximos 3 RESTRICT_SELF_* foram incluídos na abi 7*/
#ifndef LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF
#define LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF (1ULL << 0)
#endif
#ifndef LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON
#define LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON (1ULL << 1)
#endif
#ifndef LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF
#define LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF (1ULL << 2)
#endif

/* RESTRICT_SELF_TSYNC foi incluídos na abi 8 */
#ifndef LANDLOCK_RESTRICT_SELF_TSYNC
#define LANDLOCK_RESTRICT_SELF_TSYNC (1ULL << 3)
#endif

/* Os recursos de acesso ao sistema de arquivos.
   Note que a permissão FS_RESOLVE_UNIX se refere a conectar por path.
   Abstract pipes são governados por outra regra.
*/
#define FS_HANDLED                                                             \
  (LANDLOCK_ACCESS_FS_EXECUTE | /* permissão de execução */                    \
   LANDLOCK_ACCESS_FS_WRITE_FILE | /* permissão de escrita de arquivos */      \
   LANDLOCK_ACCESS_FS_READ_FILE | /* permissão de leitura em arquivo */        \
   LANDLOCK_ACCESS_FS_READ_DIR | /* permissão de leitura em diretório */       \
   LANDLOCK_ACCESS_FS_REMOVE_DIR | /* permissão para remover diretório */      \
   LANDLOCK_ACCESS_FS_REMOVE_FILE | /* permissão para remover arquivo */       \
   LANDLOCK_ACCESS_FS_MAKE_CHAR | /* permissão para criar char devices */      \
   LANDLOCK_ACCESS_FS_MAKE_DIR | /* permissão para fazer diretório */          \
   LANDLOCK_ACCESS_FS_MAKE_REG | /* permissão para criar/renomer arquivo */    \
   LANDLOCK_ACCESS_FS_MAKE_SOCK | /* permissão para criar unix sockets */      \
   LANDLOCK_ACCESS_FS_MAKE_FIFO | /* permissão para criar pipes */             \
   LANDLOCK_ACCESS_FS_MAKE_BLOCK | /* permissão para criar block devices */    \
   LANDLOCK_ACCESS_FS_MAKE_SYM | /* permissão para criar links simbólicos */   \
   LANDLOCK_ACCESS_FS_REFER | /* permissão para fazer link entre diretórios  */\
   LANDLOCK_ACCESS_FS_TRUNCATE | /* permissão para truncar arquivos */         \
   LANDLOCK_ACCESS_FS_IOCTL_DEV | /* permissão para ioctl em devices */        \
   LANDLOCK_ACCESS_FS_RESOLVE_UNIX /* permissão para conectar em  unix sockets por path */)

/* recursos de acesso à rede */
#define NET_HANDLED                                                            \
  (LANDLOCK_ACCESS_NET_BIND_TCP | /* permissão para  bind em  uma porta tcp local */\
   LANDLOCK_ACCESS_NET_CONNECT_TCP /* permissão para connect em porta tcp remota*/)

/* recursos scoped (não faço ideia do porquê isso chama scoped) */
#define SCOPED                                                                 \
  (LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET | /*permissão pra conectar a unix      \
                                            sockets abstratos (tipo dbus)*/    \
   LANDLOCK_SCOPE_SIGNAL /* permissão para enviar sinais */)

/* RESTRICT_SELF_* controlam o comportamento do Landlock, não acesso a recursos
   Por padrão o Landlock restringe a thread chamadora e suas threads filhas.
   TSYNC faz com que as threads irmãs também sejam restringidas.
 */

#define RESTRICT_FLAGS                                                         \
  (LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF | /* desabilita o log dos calls no \
                                                 executável */                \
   LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON |   /* desabilita o log dos calls em \
                                                 novo executável */           \
   LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF | /* desabilita o log no          \
                                                  subdomínios */              \
   LANDLOCK_RESTRICT_SELF_TSYNC /* restringe também as threads irmãs*/)

/* permissões de leitura para arquivo e diretório */
#define PERMS_READ                                                             \
  (LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_READ_DIR |                \
   LANDLOCK_ACCESS_FS_EXECUTE)

/* permissões de leitura e escrita para arquivo e diretório */
#define PERMS_READ_WRITE                                                       \
  (PERMS_READ | LANDLOCK_ACCESS_FS_WRITE_FILE |                                \
   LANDLOCK_ACCESS_FS_REMOVE_DIR | LANDLOCK_ACCESS_FS_REMOVE_FILE |            \
   LANDLOCK_ACCESS_FS_MAKE_DIR | LANDLOCK_ACCESS_FS_MAKE_REG |                 \
   LANDLOCK_ACCESS_FS_TRUNCATE | LANDLOCK_ACCESS_FS_RESOLVE_UNIX)

/* permissões usadas só por diretórios. elas serão removidas as perms para um
 * arquivo */
#define PERMS_DIRS_ONLY                                                        \
  (LANDLOCK_ACCESS_FS_READ_DIR | LANDLOCK_ACCESS_FS_REMOVE_DIR |               \
   LANDLOCK_ACCESS_FS_REMOVE_FILE | LANDLOCK_ACCESS_FS_MAKE_DIR |              \
   LANDLOCK_ACCESS_FS_MAKE_REG)

/*
  Essa máscara aqui é usada na comparação das flags do socket.
  Ela está declarada aqui porque ela só é declarada internamente
  no kernel.
*/
#ifndef SOCK_TYPE_MASK
#define SOCK_TYPE_MASK 0xf
#endif

/*
  Aqui são os syscalls usados em system v ipc. eles serão bloqueados
  pelo seccomp
*/
static const char *SYSV_IPC_SYSCALLS[] = {
    "msgget",     "msgsnd", "msgrcv", "msgctl", "semget", "semop",
    "semtimedop", "semctl", "shmget", "shmat",  "shmdt",  "shmctl",
};

/*
  Aqui são outros syscalls que mexem em outros processos ou
  usam memória compartilhada. Também serão bloqueados
*/
static const char *DENY_SYSCALLS[] = {
    "ptrace",
    "process_vm_readv",
    "process_vm_writev",
    "pidfd_getfd",
    "process_madvise",
    "kcmp",
    "keyctl",
    "add_key",
    "request_key",
    "io_uring_setup",
    "bpf",
    "perf_event_open",
    "userfaultfd",
};

#define SYSV_IPC_N (sizeof SYSV_IPC_SYSCALLS / sizeof SYSV_IPC_SYSCALLS[0])
#define DENY_SYSCALLS_N (sizeof DENY_SYSCALLS / sizeof DENY_SYSCALLS[0])

/*
  Retorna a versão da api do kernel que está rodando. Usado para saber quais
  recursos são suportados pelo kernel
*/
static long check_abi() {
  return syscall(SYS_landlock_create_ruleset, NULL, 0,
                 LANDLOCK_CREATE_RULESET_VERSION);
}

/*
  Retorna os acessos ao fs governados pelo Landlock. Leva em consideração
  a versão de abi para não passar acessos desconhecidos pelo kernel
*/
static unsigned long long get_handled_access_fs(long abi) {
  unsigned long long handled = FS_HANDLED;
  if (abi < 2) {
    handled &= ~LANDLOCK_ACCESS_FS_REFER;
  }
  if (abi < 3) {
    handled &= ~LANDLOCK_ACCESS_FS_TRUNCATE;
  }
  if (abi < 5) {
    handled &= ~LANDLOCK_ACCESS_FS_IOCTL_DEV;
  }
  if (abi < 9) {
    handled &= ~LANDLOCK_ACCESS_FS_RESOLVE_UNIX;
  }
  return handled;
}

/* Retorna os acessos à rede governados pelo Landlock. */
static unsigned long long get_handled_access_net(long abi) {
  unsigned long long handled = NET_HANDLED;
  if (abi < 4) {
    handled = 0;
  }
  return handled;
}

/* Retorna os acessos scoped governados pelo Landlock */
static unsigned long long get_handled_scopes(long abi) {
  unsigned long long scopes = SCOPED;
  if (abi < 6) {
    scopes = 0;
  }
  return scopes;
}

/*
  Retorna as RESTRICT_SELF_* flags suportadas pelo host
*/
static unsigned long long get_supported_restrict_flags(long abi) {
  unsigned long long flags = RESTRICT_FLAGS;
  if (abi < 7) {
    flags &= ~(LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF |
               LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON |
               LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF);
  }
  if (abi < 8) {
    flags &= ~LANDLOCK_RESTRICT_SELF_TSYNC;
  }
  return flags;
}

/* Retorna as pemissões de escrita e leitura suportadas pelo kernel */
static unsigned long long get_perms_read_write(long abi) {
  unsigned long long perms = PERMS_READ_WRITE;
  if (abi < 3) {
    perms &= ~LANDLOCK_ACCESS_FS_TRUNCATE;
  }
  if (abi < 9) {
    perms &= ~LANDLOCK_ACCESS_FS_RESOLVE_UNIX;
  }
  return perms;
}

/*
  cria uma nova ruleset para fs, net ou scoped. Aqui a gente passa tudo
  o que vai ser controlado pelo Landlock aqui e depois criamos as exceções
  para acesso
*/
static long create_ruleset(const struct landlock_ruleset_attr *attr) {
  return syscall(SYS_landlock_create_ruleset, attr,
                 sizeof(struct landlock_ruleset_attr), 0);
}

/* Aqui a gente adiciona a permissão de acesso à um recurso */
static long add_rule(int ruleset_fd,
                     const struct landlock_path_beneath_attr *pb) {
  return syscall(SYS_landlock_add_rule, ruleset_fd, LANDLOCK_RULE_PATH_BENEATH,
                 pb, 0);
}

/*
   é isso aqui que 'trava' o processo. Depois de aplicar as regras e as exceções
   a gente chama isso aqui pra aplicar e travar tudo
*/
static long restrict_self(int ruleset_fd, unsigned long long flags) {
  if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
    return -1;
  }
  return syscall(SYS_landlock_restrict_self, ruleset_fd, flags);
}

/*
  aqui a gente libera o acesso a algum recurso por path.
  se um path não for um diretório as PERMS_DIRS_ONLY são removidas
  dos acessos concedidos.
*/
static long allow_access(int ruleset_fd, const char *path,
                         struct landlock_path_beneath_attr *pb) {
  long r;
  int parent_fd;
  struct stat st;

  parent_fd = open(path, O_PATH | O_CLOEXEC);
  if (parent_fd < 0) {
    return -1;
  }

  if (fstat(parent_fd, &st) < 0) {
    close(parent_fd);
    return -1;
  }
  if (!S_ISDIR(st.st_mode)) {
    pb->allowed_access &= ~PERMS_DIRS_ONLY;
  }
  pb->parent_fd = parent_fd;
  r = add_rule(ruleset_fd, pb);
  close(pb->parent_fd);
  return r;
}

/* dá acesso de leitura a um dado path */
static long allow_read_access(int ruleset_fd, const char *path) {
  struct landlock_path_beneath_attr pb = {.allowed_access = PERMS_READ};

  return allow_access(ruleset_fd, path, &pb);
}

/* dá acesso de leitura e escrita a um determinado path  */
static long allow_read_write_access(int ruleset_fd, const char *path,
                                    long abi) {
  struct landlock_path_beneath_attr pb = {.allowed_access =
                                              get_perms_read_write(abi)};
  return allow_access(ruleset_fd, path, &pb);
}

/* dá acesso de bind ou connect tcp a uma determinada porta  */
static long add_net_rule(int ruleset_fd, unsigned long long allowed_access,
                         unsigned short port) {
  struct landlock_net_port_attr attr = {
      .allowed_access = allowed_access,
      .port = port,
  };
  return syscall(SYS_landlock_add_rule, ruleset_fd, LANDLOCK_RULE_NET_PORT,
                 &attr, 0);
}

/* dá acesso de connect a uma determinada porta  */
static long allow_net_connect_access(int ruleset_fd, unsigned short port) {
  return add_net_rule(ruleset_fd, LANDLOCK_ACCESS_NET_CONNECT_TCP, port);
}

/* dá acesso de bind a uma determinada porta. */
static long allow_net_bind_access(int ruleset_fd, unsigned short port) {
  return add_net_rule(ruleset_fd, LANDLOCK_ACCESS_NET_BIND_TCP, port);
}

/*
  Aqui a gente bloqueia todas as famílias de socket exceto AF_INET, AF_INET6,
  AF_NETLINK e AF_UNIX. Esses vão ter regras individuais pra cada
*/
static int deny_socket_families(scmp_filter_ctx ctx) {
  int r;

  for (int f = 0; f < AF_MAX; f++) {
    if (f == AF_INET || f == AF_INET6 || f == AF_NETLINK || f == AF_UNIX) {
      continue;
    }
    /*
      o seccomp_rule_add_exact funciona assim: o primeiro parâmetro é
      o contexto do seccomp (a gente vai criar isso no setup). O segundo
      argumento é a ação, no caso aqui vai dar um erro EACCES, o terceiro
      é o tipo do syscall, aqui é call pra sockets. O quarto é um número
      indicando quantas comparações vão ser feitas a seguir e os últimos
      parâmetros são comparações com os próximos argumentos do syscall.
    */
    r = seccomp_rule_add_exact(ctx, SCMP_ACT_ERRNO(EACCES), SCMP_SYS(socket), 1,
                               SCMP_A0(SCMP_CMP_EQ, (scmp_datum_t)f));
    if (r < 0) {
      return -1;
    }
  }
  /*
    Aqui é mais uma proteção. Famílias com número acima de AF_MAX também
    são bloquadas, assim se alguma família for adicionada no futuro também
    é bloqueada
  */
  r = seccomp_rule_add_exact(ctx, SCMP_ACT_ERRNO(EACCES), SCMP_SYS(socket), 1,
                             SCMP_A0(SCMP_CMP_GE, AF_MAX));
  if (r < 0) {
    return -1;
  }
  return 0;
}

/*
  Bloqueia AF_INET e AF_INET6 SOCK_RAW. Raw sockets podem ser usados
  pra criar pacotes 'na mão' e burlar os checks do landlock
*/
static int deny_inet_raw(scmp_filter_ctx ctx) {
  int r;

  r = seccomp_rule_add_exact(
      ctx, SCMP_ACT_ERRNO(EACCES), SCMP_SYS(socket), 2,
      SCMP_A0(SCMP_CMP_EQ, AF_INET),
      SCMP_A1(SCMP_CMP_MASKED_EQ, SOCK_TYPE_MASK, SOCK_RAW));
  if (r < 0) {
    return -1;
  }
  r = seccomp_rule_add_exact(
      ctx, SCMP_ACT_ERRNO(EACCES), SCMP_SYS(socket), 2,
      SCMP_A0(SCMP_CMP_EQ, AF_INET6),
      SCMP_A1(SCMP_CMP_MASKED_EQ, SOCK_TYPE_MASK, SOCK_RAW));
  if (r < 0) {
    return -1;
  }
  return 0;
}

/*
  Bloqueia AF_NETLINK NETLINK_USERSOCK porque esse protocolo é
  usado para ipc.
*/
static int deny_netlink_usersock(scmp_filter_ctx ctx) {
  int r;

  r = seccomp_rule_add_exact(ctx, SCMP_ACT_ERRNO(EACCES), SCMP_SYS(socket), 2,
                             SCMP_A0(SCMP_CMP_EQ, AF_NETLINK),
                             SCMP_A2(SCMP_CMP_EQ, NETLINK_USERSOCK));
  if (r < 0) {
    return -1;
  }
  return 0;
}

/* Bloqueia o uso de unix sockets */
static int deny_unix_sockets(scmp_filter_ctx ctx) {
  int r;

  r = seccomp_rule_add_exact(ctx, SCMP_ACT_ERRNO(EACCES), SCMP_SYS(socket), 1,
                             SCMP_A0(SCMP_CMP_EQ, AF_UNIX));
  if (r < 0) {
    return -1;
  }
  return 0;
}

/* Bloqueia AF_INET, AF_INET6 e AF_NETLINK */
static int deny_network_sockets(scmp_filter_ctx ctx) {
  int r;

  r = seccomp_rule_add_exact(ctx, SCMP_ACT_ERRNO(EACCES), SCMP_SYS(socket), 1,
                             SCMP_A0(SCMP_CMP_EQ, AF_INET));
  if (r < 0) {
    return -1;
  }
  r = seccomp_rule_add_exact(ctx, SCMP_ACT_ERRNO(EACCES), SCMP_SYS(socket), 1,
                             SCMP_A0(SCMP_CMP_EQ, AF_INET6));
  if (r < 0) {
    return -1;
  }
  r = seccomp_rule_add_exact(ctx, SCMP_ACT_ERRNO(EACCES), SCMP_SYS(socket), 1,
                             SCMP_A0(SCMP_CMP_EQ, AF_NETLINK));
  if (r < 0) {
    return -1;
  }
  return 0;
}

/*
  Recebe uma lista de nomes de syscalls e bloqueia cada um deles
*/
static int deny_syscall_list(scmp_filter_ctx ctx, const char *const *names,
                             size_t n) {
  for (size_t k = 0; k < n; k++) {
    int nr = seccomp_syscall_resolve_name(names[k]);
    if (nr == __NR_SCMP_ERROR) {
      return -1;
    }
    int r = seccomp_rule_add_exact(ctx, SCMP_ACT_ERRNO(ENOSYS), nr, 0);
    if (r < 0) {
      return -1;
    }
  }
  return 0;
}

/* Bloqueia os syscalls de system V ipc */
static int deny_sysv_ipc(scmp_filter_ctx ctx) {
  return deny_syscall_list(ctx, SYSV_IPC_SYSCALLS, SYSV_IPC_N);
}

/* Bloqueia os syscalls mexem em processo externos e memória comparttilhada */
static int deny_dangerous_syscalls(scmp_filter_ctx ctx) {
  return deny_syscall_list(ctx, DENY_SYSCALLS, DENY_SYSCALLS_N);
}

/*
  Aplica os filtros do seccomp. Isso vai ser chamado no final do setup.
*/
static int apply_seccomp(int allow_unix_sockets, int allow_network_sockets) {

  /*
    primeiro a gente cria o contextop do seccomp, aqui dizendo
    que por padrão todos os syscalls são liberados
  */
  scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_ALLOW);

  if (ctx == NULL) {
    return -1;
  }
  int r = 0;

  /* o tsync aqui é igual ao tsync no landlock. trava também as threads irmãs */
  r = seccomp_attr_set(ctx, SCMP_FLTATR_CTL_TSYNC, 1);
  if (r < 0) {
    return -1;
  }
  if (deny_socket_families(ctx) < 0) {
    seccomp_release(ctx);
    return -1;
  }
  if (deny_inet_raw(ctx) < 0) {
    seccomp_release(ctx);
    return -1;
  }
  if (deny_netlink_usersock(ctx) < 0) {
    seccomp_release(ctx);
    return -1;
  }
  if (!allow_unix_sockets && deny_unix_sockets(ctx) < 0) {
    seccomp_release(ctx);
    return -1;
  }
  if (!allow_network_sockets && deny_network_sockets(ctx) < 0) {
    seccomp_release(ctx);
    return -1;
  }
  if (deny_sysv_ipc(ctx) < 0) {
    seccomp_release(ctx);
    return -1;
  }
  if (deny_dangerous_syscalls(ctx) < 0) {
    seccomp_release(ctx);
    return -1;
  }
  /* esse load aqui é o que faz as regras serem aplicadas */
  if (seccomp_load(ctx) != 0) {
    seccomp_release(ctx);
    return -1;
  }
  seccomp_release(ctx);
  return 0;
}

/*
   aqui as opções que a gente vai passar pro setup da coisa toda.
   A ideia aqui é que a gente fecha tudo por padrão e passa uma
   lista de recursos que quer liberar acesso.
*/
struct sandbox_opts {
  /* diretórios com permissão de leitura */
  const char **r_dir;
  int n_r;
  int cap_r;
  /* diretórios com permissão de escrita */
  const char **rw_dir;
  int n_rw;
  int cap_rw;
  /* portas permitidas para connect */
  unsigned short *connect_ports;
  int n_connect;
  int cap_connect;
  /* portas permitidas para bind */
  unsigned short *bind_ports;
  int n_bind;
  int cap_bind;
  int allow_unix_sockets;
  int allow_network_sockets;
};

/* Aqui a gente liga todas as retrições e libera só para os recursos pedidos */
int sandbox_setup(const struct sandbox_opts *opts) {
  long abi = check_abi();
  if (abi < 1) {
    return -1;
  }
  unsigned long long handled = get_handled_access_fs(abi);
  unsigned long long handled_net = get_handled_access_net(abi);
  struct landlock_ruleset_attr r_perm = {
      .handled_access_fs = handled,
      .handled_access_net = handled_net,
      .scoped = get_handled_scopes(abi),
  };
  long ruleset_ret = create_ruleset(&r_perm);
  if (ruleset_ret < 0) {
    return -1;
  }
  int ruleset = (int)ruleset_ret;
  for (int k = 0; k < opts->n_r; k++) {
    if (allow_read_access(ruleset, opts->r_dir[k]) < 0) {
      return -1;
    }
  }
  for (int k = 0; k < opts->n_rw; k++) {
    if (allow_read_write_access(ruleset, opts->rw_dir[k], abi) < 0) {
      return -1;
    }
  }
  for (int k = 0; k < opts->n_connect; k++) {
    if (allow_net_connect_access(ruleset, opts->connect_ports[k]) < 0) {
      return -1;
    }
  }
  for (int k = 0; k < opts->n_bind; k++) {
    if (allow_net_bind_access(ruleset, opts->bind_ports[k]) < 0) {
      return -1;
    }
  }
  if (restrict_self(ruleset, get_supported_restrict_flags(abi)) < 0) {
    return -1;
  }
  close(ruleset);
  if (apply_seccomp(opts->allow_unix_sockets, opts->allow_network_sockets) <
      0) {
    return -1;
  }
  return 0;
}

/*
   Agora o que a gente usa pra fazer uma cli. A ideia é que a gente
   passa --ro, --rw, --allow-connect-portt e --allow-bind-port para
   liberar os recursos que queremos. O fim da linha de comando é um --
   e depois disso é o comando que vamos rodar dentro do sandbox.
*/

/* append um path a lista de paths que vão ser liberadas para ro ou rw */
static int push_path(const char ***list, int *n, int *cap, const char *path) {
  if (*n == *cap) {
    int new_cap = *cap ? *cap * 2 : 4;
    const char **grown =
        realloc((void *)*list, (size_t)new_cap * sizeof **list);
    if (grown == NULL) {
      return -1;
    }
    *list = grown;
    *cap = new_cap;
  }
  (*list)[(*n)++] = path;
  return 0;
}

/* parseia uma string em um int no range de 0..65535 */
static int parse_port(const char *s, unsigned short *out) {
  char *end;
  errno = 0;
  unsigned long v = strtoul(s, &end, 10);
  if (end == s || *end != '\0' || errno != 0 || v > 65535) {
    return -1;
  }
  *out = (unsigned short)v;
  return 0;
}

static int push_port(unsigned short **list, int *n, int *cap,
                     unsigned short port) {
  if (*n == *cap) {
    int new_cap = *cap ? *cap * 2 : 4;
    unsigned short *grown = realloc(*list, (size_t)new_cap * sizeof **list);
    if (grown == NULL) {
      return -1;
    }
    *list = grown;
    *cap = new_cap;
  }
  (*list)[(*n)++] = port;
  return 0;
}

/*
   Parseia a linha de comando preenchendo as opções do sandbox e o
   comando a ser rodado.
*/
int parse_cmd_line(int argc, char *argv[], struct sandbox_opts *opts,
                   char ***cmd) {
  if (cmd != NULL) {
    *cmd = NULL;
  }
  if (argc <= 1) {
    return -1;
  }
  int i = 1;
  while (argc > i) {
    if (strcmp(argv[i], "--ro") == 0) {
      if (i + 1 >= argc) {
        return -1;
      }
      if (push_path(&opts->r_dir, &opts->n_r, &opts->cap_r, argv[i + 1]) < 0) {
        return -1;
      }
      i += 2;
    } else if (strcmp(argv[i], "--rw") == 0) {
      if (i + 1 >= argc) {
        return -1;
      }
      if (push_path(&opts->rw_dir, &opts->n_rw, &opts->cap_rw, argv[i + 1]) <
          0) {
        return -1;
      }
      i += 2;
    } else if (strcmp(argv[i], "--allow-connect-port") == 0) {
      unsigned short port;
      if (i + 1 >= argc) {
        return -1;
      }
      if (parse_port(argv[i + 1], &port) < 0) {
        return -1;
      }
      if (push_port(&opts->connect_ports, &opts->n_connect, &opts->cap_connect,
                    port) < 0) {
        return -1;
      }
      i += 2;
    } else if (strcmp(argv[i], "--allow-bind-port") == 0) {
      unsigned short port;
      if (i + 1 >= argc) {
        return -1;
      }
      if (parse_port(argv[i + 1], &port) < 0) {
        return -1;
      }
      if (push_port(&opts->bind_ports, &opts->n_bind, &opts->cap_bind, port) <
          0) {
        return -1;
      }
      i += 2;
    } else if (strcmp(argv[i], "--allow-network-sockets") == 0) {
      opts->allow_network_sockets = 1;
      i += 1;
    } else if (strcmp(argv[i], "--allow-unix-sockets") == 0) {
      opts->allow_unix_sockets = 1;
      i += 1;
    } else if (strcmp(argv[i], "--") == 0) {
      if (i + 1 >= argc) {
        return -1;
      }
      i++;
      if (cmd != NULL) {
        *cmd = &argv[i];
      }
      return 0;
    } else {
      return -1;
    }
  }
  return -1;
}

int main(int argc, char *argv[]) {
  struct sandbox_opts opts = {0};
  char **cmd = NULL;

  if (parse_cmd_line(argc, argv, &opts, &cmd) < 0) {
    exit(2);
  }

  int r = sandbox_setup(&opts);
  if (r < 0) {
    exit(1);
  }
  if (execvp(cmd[0], cmd) < 0) {
    fprintf(stderr, "sandbox: exec %s: %s\n", cmd[0], strerror(errno));
    exit(1);
  }
  exit(0);
}
