/* run-guix-system-container.c — daemon that starts Guix system * containers on request, meant to be run as root from shepherd (Guix * System) or systemd (Debian). * * Usage: * run-guix-system-container [--listen IP] [--port N] [--fingerprint WORD] * * It listens on the given IP (default 127.0.0.1 — loopback only). * Pass an explicit IP such as 0.0.0.0 to listen on all interfaces. * * The daemon has a FINGERPRINT: a short word or version (e.g. "v0.1") * given with --fingerprint, or a random hash generated at startup when * not specified. Clients can verify they are talking to the daemon * they expect (FINGERPRINT command, or "START "). * The fingerprint is also passed to started containers in the * GUIX_CONTAINER_FINGERPRINT environment variable, so a container can * show which daemon generation started it (e.g. in /etc/issue). * * When the daemon receives SIGINT or SIGTERM it terminates the * containers it started: SIGTERM, then after a 10 s timeout SIGKILL. * * The daemon runs AT MOST ONE container at a time: START is refused * while a previously started container is still alive. * * Protocol (one line per connection): * START []\n * → OK \n container started * → ERR \n validation failure (a non-matching optional * fingerprint yields "ERR fingerprint mismatch") * KILL \n * → OK killed \n SIGKILL (kill -9) sent * → ERR \n not a known container, etc. * LIST\n * → OK\n + one " " line per running container * LOG \n * → OK\n + the raw contents of the container's log file * (LOG_DIR/HASH-run-container.log) * → ERR \n no log file * FINGERPRINT\n * → OK \n the daemon's fingerprint * * Container stdout/stderr is appended to LOG_DIR (default * /var/log/guix-containers) so boot failures can be diagnosed. * * The daemon refuses to start unless it runs as root with CAP_SETUID * and CAP_SYS_ADMIN: without them every START would fork a container * that dies within milliseconds (EPERM writing /proc/PID/uid_map, or * mounting its file systems) and leave no useful trace behind. * * Before exec'ing a container script it is verified that: * - the resolved name is exactly HASH-run-container (32-char nix-base32) * - the script contents reference linux-container * - the file is a direct child of /gnu/store, executable and immutable * (no write bits; Guix store items are 0555 root-owned) * * Build: gcc -O2 -Wall -o run-guix-system-container run-guix-system-container.c */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define PROGRAM "run-guix-system-container" #define STORE "/gnu/store/" #define DEFAULT_PORT 8989 #define DEFAULT_LISTEN "127.0.0.1" #define MAX_LINE 256 /* Container stdout/stderr is appended to LOG_DIR/.log. The * default suits a system-wide install; --log-dir (or * GUIX_CONTAINER_LOG_DIR) takes a directory the daemon can write, for * hosts where /var/log is read-only or the daemon is not system-wide. */ #define DEFAULT_LOG_DIR "/var/log/guix-containers" static const char *log_dir = DEFAULT_LOG_DIR; /* The two capabilities container creation needs, from * (not included to keep the build dependency-free). * CAP_SETUID: write the 65536-entry uid_map of the container's user * namespace. CAP_SYS_ADMIN: mount its file systems, /proc and /dev. */ #define CAP_SETUID 7 #define CAP_SYS_ADMIN 21 /* Fingerprint of this daemon instance: a short word or version * ("v0.1") given with --fingerprint, or a random hash when none is * given. Used to make sure clients talk to the daemon they expect, * and passed to containers via GUIX_CONTAINER_FINGERPRINT. */ static char daemon_fingerprint[33]; /* Set when SIGINT/SIGTERM asks us to shut down. */ static volatile sig_atomic_t stop_requested; static void logmsg(const char *fmt, ...) { va_list ap; flockfile(stderr); fprintf(stderr, "[%d] ", (int)time(NULL)); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fputc('\n', stderr); funlockfile(stderr); } /* ------------------------------------------------------------------ */ /* Privileges */ /* ------------------------------------------------------------------ */ /* Parse the CapEff bitmask (hex) from /proc/self/status. Returns 0 * when it cannot be read, in which case the caller trusts the uid. */ static int read_cap_eff(unsigned long long *caps) { char line[MAX_LINE]; FILE *port = fopen("/proc/self/status", "r"); int found = 0; if (!port) return 0; while (fgets(line, sizeof(line), port)) if (strncmp(line, "CapEff:", 7) == 0) { char *end; *caps = strtoull(line + 7, &end, 16); found = end != line + 7; break; } fclose(port); return found; } /* Refuse to serve when we cannot create containers: as non-root every * START would exec a launcher that dies before it can even write its * log, and a client only sees "OK " followed by silence. */ static int have_container_privileges(void) { unsigned long long cap_eff = 0; int ok = 1; if (geteuid() != 0) { logmsg("error: %s must run as root (uid %d): container " "creation needs CAP_SETUID and CAP_SYS_ADMIN, without " "them every START fails", PROGRAM, (int)geteuid()); return 0; } if (!read_cap_eff(&cap_eff)) return 1; /* no CapEff: trust euid 0 */ if (!(cap_eff & (1ULL << CAP_SETUID))) { logmsg("error: root but without CAP_SETUID: cannot write the " "container's uid_map"); ok = 0; } if (!(cap_eff & (1ULL << CAP_SYS_ADMIN))) { logmsg("error: root but without CAP_SYS_ADMIN: cannot mount " "the container's file systems"); ok = 0; } return ok; } /* Container boot output goes to LOG_DIR. When it cannot be created or * written (read-only /var, hardened unit) that output is lost and a * boot failure cannot be diagnosed, so complain loudly -- but keep * serving, the container itself still works. */ static void check_log_dir(void) { char path[MAX_LINE]; int fd; snprintf(path, sizeof(path), "%s/.writable", log_dir); if (mkdir(log_dir, 0755) < 0 && errno != EEXIST) { logmsg("warning: cannot create %s: %s -- container boot " "output will be lost", log_dir, strerror(errno)); return; } fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644); if (fd < 0) { logmsg("warning: cannot write to %s: %s -- container boot " "output will be lost", log_dir, strerror(errno)); return; } close(fd); unlink(path); } /* ------------------------------------------------------------------ */ /* Fingerprint */ /* ------------------------------------------------------------------ */ /* A fingerprint must be a short word or version like "v0.1": 1–32 * printable characters, no whitespace or control characters. */ static int valid_fingerprint(const char *s) { size_t i, len = strlen(s); if (len == 0 || len > sizeof(daemon_fingerprint) - 1) return 0; for (i = 0; i < len; i++) if (isspace((unsigned char)s[i]) || iscntrl((unsigned char)s[i])) return 0; return 1; } /* Generate a random 8-char hex fingerprint into daemon_fingerprint. */ static void random_fingerprint(void) { unsigned char rnd[4]; int fd = open("/dev/urandom", O_RDONLY); size_t i; if (fd < 0 || read(fd, rnd, sizeof(rnd)) != sizeof(rnd)) { /* fallback: mix of time, pid and a stack address */ unsigned x = (unsigned)time(NULL) ^ ((unsigned)getpid() << 16) ^ (unsigned)(uintptr_t)&rnd; for (i = 0; i < sizeof(rnd); i++) { rnd[i] = (unsigned char)x; x = x * 1103515245u + 12345u; } } if (fd >= 0) close(fd); for (i = 0; i < sizeof(rnd); i++) sprintf(daemon_fingerprint + i * 2, "%02x", rnd[i]); } /* ------------------------------------------------------------------ */ /* Validation */ /* ------------------------------------------------------------------ */ static int is_nix_base32_hash(const char *s, size_t n) { size_t i; if (n != 32) return 0; for (i = 0; i < n; i++) if (!isdigit((unsigned char)s[i]) && !(s[i] >= 'a' && s[i] <= 'z')) return 0; return 1; } /* Resolve a 32-char hash to /gnu/store/HASH-run-container. * Returns a malloc'd path or NULL. */ static char *resolve_container(const char *hash) { DIR *dir = opendir(STORE); struct dirent *de; char *found = NULL; size_t prefix_len = strlen(hash) + 1; char prefix[prefix_len + 1]; if (!dir) return NULL; memcpy(prefix, hash, prefix_len - 1); prefix[prefix_len - 1] = '-'; prefix[prefix_len] = '\0'; while ((de = readdir(dir))) { if (strncmp(de->d_name, prefix, prefix_len) != 0) continue; if (strcmp(de->d_name + prefix_len, "run-container") != 0) continue; if (found) { /* ambiguous: more than one match */ free(found); closedir(dir); return NULL; } if (asprintf(&found, "%s%s", STORE, de->d_name) < 0) found = NULL; } closedir(dir); return found; } /* A generated Guix system container launcher is a guile script with a * distinctive structure. We require all of the following, so that no * regular store binary or unrelated script passes: * * 1. first line is a guile shebang: * #!/gnu/store/...-guile-.../bin/guile ... * (this also rules out ELF binaries, which start with \x7fELF) * 2. it calls (call-with-container ...), the container entry point * 3. it sets GUIX_NEW_SYSTEM, as generated system containers do * 4. it mentions linux-container (the module it uses) */ static int is_container_script(const char *path, const char *base) { const char *dash = strchr(base, '-'); char buf[65536]; ssize_t n, i; int fd, eol = 0; /* The basename must be HASH-run-container: a 32-char nix-base32 * hash, then a dash, then exactly "run-container". */ if (!dash || dash - base != 32 || strcmp(dash + 1, "run-container") != 0) return 0; if (!is_nix_base32_hash(base, dash - base)) return 0; fd = open(path, O_RDONLY); if (fd < 0) return 0; n = read(fd, buf, sizeof(buf) - 1); close(fd); if (n <= 0) return 0; buf[n] = '\0'; /* 1. guile shebang as the first line. */ if (strncmp(buf, "#!/gnu/store/", 13) != 0) return 0; for (i = 13; i < n && buf[i] != '\n'; i++) ; if (i >= n) return 0; eol = i; { char shebang[65536]; memcpy(shebang, buf, eol); shebang[eol] = '\0'; if (!strstr(shebang, "-guile-") || !strstr(shebang, "/bin/guile")) return 0; } /* 2-4. container entry point and generated-system markers. */ if (!strstr(buf, "call-with-container")) return 0; if (!strstr(buf, "GUIX_NEW_SYSTEM")) return 0; if (!strstr(buf, "linux-container")) return 0; return 1; } /* Full validation of a user-supplied argument (hash or store path). * Returns a malloc'd container path, or NULL with *err pointing at a * static error string. */ static char *validate(const char *arg, const char **err) { char *path, *base; struct stat st; size_t store_len = strlen(STORE); *err = "invalid argument"; if (is_nix_base32_hash(arg, strlen(arg))) { path = resolve_container(arg); if (!path) { *err = "no unique HASH-run-container found in the store"; return NULL; } } else { if (strncmp(arg, STORE, store_len) != 0) { *err = "path must be inside " STORE; return NULL; } if (strchr(arg + store_len, '/')) { *err = "path must be a direct child of " STORE; return NULL; } path = strdup(arg); } base = path + store_len; if (access(path, X_OK) != 0) { *err = strerror(errno); goto bad; } /* The file must be immutable: no write bits at all. Guix store * items are created read-only (0555) by the daemon; if any write * bit is set the file may have been tampered with or replaced, * and we refuse to exec it. */ if (stat(path, &st) != 0) { *err = strerror(errno); goto bad; } if (st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) { *err = "container script is writable; refusing to run it"; goto bad; } if (!is_container_script(path, base)) { *err = "not a Guix container launcher (HASH-run-container)"; goto bad; } return path; bad: free(path); return NULL; } /* ------------------------------------------------------------------ */ /* Started-container tracking (for KILL) */ /* ------------------------------------------------------------------ */ static pid_t *started_pids; static size_t started_count, started_cap; static void track_pid(pid_t pid) { if (started_count == started_cap) { size_t cap = started_cap ? started_cap * 2 : 16; pid_t *p = realloc(started_pids, cap * sizeof(*p)); if (!p) return; /* non-fatal: KILL falls back to /proc */ started_pids = p; started_cap = cap; } started_pids[started_count++] = pid; } static void untrack_pid(pid_t pid) { size_t i; for (i = 0; i < started_count; i++) if (started_pids[i] == pid) { memmove(&started_pids[i], &started_pids[i + 1], (started_count - i - 1) * sizeof(*started_pids)); started_count--; return; } } static int pid_tracked(pid_t pid) { size_t i; for (i = 0; i < started_count; i++) if (started_pids[i] == pid) return 1; return 0; } /* Is a process still alive? (kill(0) with EPERM also means alive.) */ static int pid_alive(pid_t pid) { return kill(pid, 0) == 0 || errno != ESRCH; } /* Kill a container the daemon started: SIGKILL its whole process * group (the launcher did setsid(), so the group covers the container's * shepherd PID 1 and all its services); fall back to the single pid. */ static int kill_container_group(pid_t pid) { if (kill(-pid, SIGKILL) == 0) return 0; if (errno == EPERM || errno == ESRCH) return kill(pid, SIGKILL); return -1; } /* Fallback for PIDs started by a previous daemon instance: either a * /gnu/store/HASH-run-container launcher script, or a stray shepherd * (PID 1 of a container whose launcher was killed) running * ".../bin/shepherd --config ...-shepherd.conf". */ static int pid_is_container(pid_t pid) { char path[MAX_LINE], buf[MAX_LINE]; int fd; ssize_t n; snprintf(path, sizeof(path), "/proc/%d/cmdline", (int)pid); fd = open(path, O_RDONLY); if (fd < 0) return 0; n = read(fd, buf, sizeof(buf) - 1); close(fd); if (n <= 0) return 0; buf[n] = '\0'; return strstr(buf, "-run-container") != NULL || (strstr(buf, "bin/shepherd") != NULL && strstr(buf, "-shepherd.conf") != NULL); } /* On shutdown, terminate the containers this daemon started: send * SIGTERM to all of them, wait up to 10 s for them to exit, then * SIGKILL the survivors. */ static void shutdown_containers(void) { size_t i; int waited; if (started_count == 0) return; logmsg("shutting down %zu container(s)", started_count); for (i = 0; i < started_count; i++) kill(-started_pids[i], SIGTERM); /* whole process group */ for (waited = 0; waited < 100; waited++) { /* 100 x 100 ms = 10 s */ int alive = 0; for (i = 0; i < started_count; i++) if (pid_alive(started_pids[i])) alive++; if (alive == 0) { logmsg("all containers exited"); return; } usleep(100 * 1000); } for (i = 0; i < started_count; i++) if (pid_alive(started_pids[i])) { logmsg("container %d did not exit within 10 s; sending SIGKILL", (int)started_pids[i]); kill_container_group(started_pids[i]); } } static void handle_stop(int sig) { (void)sig; stop_requested = 1; } /* Drop pids that are no longer alive from the tracking table. */ static void sweep_dead_pids(void) { size_t i; for (i = 0; i < started_count; ) { if (pid_alive(started_pids[i])) { i++; continue; } untrack_pid(started_pids[i]); } } /* Handle "LIST": report running containers, one " " line * after the OK line. Includes containers started by previous * daemon instances (found by scanning /proc for *-run-container * launchers), so they can be KILLed after a daemon restart. */ static void list_containers(int fd) { size_t i; sweep_dead_pids(); dprintf(fd, "OK\n"); for (i = 0; i < started_count; i++) { char path[MAX_LINE], buf[MAX_LINE], name[MAX_LINE]; char *slash; int f, n; snprintf(path, sizeof(path), "/proc/%d/cmdline", (int)started_pids[i]); f = open(path, O_RDONLY); if (f < 0) continue; n = read(f, buf, sizeof(buf) - 1); close(f); if (n <= 0) continue; buf[n] = '\0'; /* first NUL-terminated arg = argv[0] */ slash = strrchr(buf, '/'); snprintf(name, sizeof(name), "%s", slash ? slash + 1 : buf); dprintf(fd, "%d %s\n", (int)started_pids[i], name); } /* Containers started by a previous daemon instance. */ { DIR *dir = opendir("/proc"); struct dirent *de; int found = started_count; while (dir && (de = readdir(dir))) { char path[MAX_LINE], buf[MAX_LINE], name[MAX_LINE]; char *slash; long pid; char *end; int f, n; pid = strtol(de->d_name, &end, 10); if (*end || pid <= 1) continue; if (pid_tracked((pid_t)pid)) continue; /* already reported */ snprintf(path, sizeof(path), "/proc/%ld/cmdline", pid); f = open(path, O_RDONLY); if (f < 0) continue; n = read(f, buf, sizeof(buf) - 1); close(f); if (n <= 0) continue; buf[n] = '\0'; if (!pid_is_container((pid_t)pid)) continue; slash = strrchr(buf, '/'); snprintf(name, sizeof(name), "%s", slash ? slash + 1 : buf); dprintf(fd, "%d %s (started by a previous daemon)\n", (int)pid, name); found++; } if (dir) closedir(dir); if (found == 0) dprintf(fd, "(none)\n"); } } /* Handle "KILL ": terminate a container the daemon started * (or a previous instance started) with SIGKILL. */ static void kill_container(int fd, const char *arg, const char *client_ip) { char *end; long pid = strtol(arg, &end, 10); if (*end || pid <= 1) { dprintf(fd, "ERR invalid pid\n"); return; } if (!pid_tracked(pid) && !pid_is_container(pid)) { logmsg("refused to kill %ld from %s: not a container", pid, client_ip); dprintf(fd, "ERR not a container started by this daemon\n"); return; } if (kill_container_group((pid_t)pid) != 0) { logmsg("failed to kill %ld: %s", pid, strerror(errno)); dprintf(fd, "ERR %s\n", strerror(errno)); return; } untrack_pid((pid_t)pid); logmsg("sent SIGKILL to %ld (client %s)", pid, client_ip); dprintf(fd, "OK killed %ld\n", pid); } /* Handle "LOG ": dump the container's log file. */ static void send_log(int fd, const char *arg) { char base[MAX_LINE], logpath[MAX_LINE * 2]; char buf[4096]; int log, n; const char *slash; if (is_nix_base32_hash(arg, strlen(arg))) { snprintf(base, sizeof(base), "%s-run-container", arg); } else { slash = strrchr(arg, '/'); snprintf(base, sizeof(base), "%s", slash ? slash + 1 : arg); if (!strstr(base, "-run-container")) { dprintf(fd, "ERR expected HASH or HASH-run-container\n"); return; } } snprintf(logpath, sizeof(logpath), "%s/%s.log", log_dir, base); log = open(logpath, O_RDONLY); if (log < 0) { dprintf(fd, "ERR no log for %s (%s)\n", base, strerror(errno)); return; } dprintf(fd, "OK\n"); while ((n = read(log, buf, sizeof(buf))) > 0) write(fd, buf, n); close(log); } /* ------------------------------------------------------------------ */ /* Starting */ /* ------------------------------------------------------------------ */ /* Start a validated container script detached; returns its pid, or * -1 on failure. The container's stdout/stderr is appended to * LOG_DIR/.log so boot failures can be diagnosed. */ static pid_t start_container(const char *path) { const char *base = strrchr(path, '/'); char logpath[MAX_LINE]; pid_t pid; base = base ? base + 1 : path; /* Prepared by the parent (running as root); ignore errors — we * fall back to /dev/null below. */ mkdir(log_dir, 0755); pid = fork(); if (pid < 0) return -1; if (pid == 0) { int devnull = open("/dev/null", O_RDWR); int log = -1; /* Let the container know which daemon instance (and thus * which fingerprint) started it, so it can show it. */ setenv("GUIX_CONTAINER_FINGERPRINT", daemon_fingerprint, 1); snprintf(logpath, sizeof(logpath), "%s/%s.log", log_dir, base); log = open(logpath, O_WRONLY | O_CREAT | O_APPEND, 0644); if (log >= 0) { dup2(log, STDOUT_FILENO); dup2(log, STDERR_FILENO); if (log > 2) close(log); } if (devnull >= 0) { dup2(devnull, STDIN_FILENO); if (devnull > 2) close(devnull); } setsid(); execl(path, path, (char *)NULL); _exit(127); } track_pid(pid); return pid; } /* ------------------------------------------------------------------ */ /* Server */ /* ------------------------------------------------------------------ */ /* Handle one connection: read "START \n", validate, start, reply. */ static void handle_connection(int fd, const char *client_ip) { char line[MAX_LINE], *p, *arg; char *path; const char *err; pid_t pid; ssize_t n; char *fp_arg; n = read(fd, line, sizeof(line) - 1); if (n <= 0) return; line[n] = '\0'; p = strpbrk(line, "\r\n"); if (p) *p = '\0'; if (strncmp(line, "FINGERPRINT", 11) == 0) { dprintf(fd, "OK %s\n", daemon_fingerprint); return; } if (strcmp(line, "LIST") == 0) { list_containers(fd); return; } if (strncmp(line, "LOG ", 4) == 0) { send_log(fd, line + 4); return; } if (strncmp(line, "KILL ", 5) == 0) { kill_container(fd, line + 5, client_ip); return; } if (strncmp(line, "START ", 6) != 0) { dprintf(fd, "ERR expected 'START [fingerprint]', 'KILL ', 'LIST', 'LOG ' or 'FINGERPRINT'\n"); return; } arg = line + 6; /* Optional second token: the fingerprint the client expects * this daemon to have. */ fp_arg = strchr(arg, ' '); if (fp_arg) { *fp_arg++ = '\0'; if (strcmp(fp_arg, daemon_fingerprint) != 0) { logmsg("fingerprint mismatch from %s (got '%s')", client_ip, fp_arg); dprintf(fd, "ERR fingerprint mismatch\n"); return; } } /* One container at a time: refuse while a previously started * container is still alive. */ sweep_dead_pids(); if (started_count > 0) { logmsg("refused START from %s: container %d already running", client_ip, (int)started_pids[0]); dprintf(fd, "ERR already running container %d; KILL it first\n", (int)started_pids[0]); return; } path = validate(arg, &err); if (!path) { logmsg("rejected '%s' from %s: %s", arg, client_ip, err); dprintf(fd, "ERR %s\n", err); return; } pid = start_container(path); if (pid < 0) { logmsg("failed to start %s: %s", path, strerror(errno)); dprintf(fd, "ERR failed to start container\n"); } else { logmsg("started %s as pid %d (client %s, fingerprint %s)", path, pid, client_ip, daemon_fingerprint); dprintf(fd, "OK %d\n", pid); } free(path); } static int serve(const char *listen_ip, int port) { struct sockaddr_in6 addr6; struct sockaddr_in addr4; struct sockaddr *sa; socklen_t sa_len; int family, srv, one = 1; struct sigaction stop_action; signal(SIGCHLD, SIG_IGN); /* reap children automatically */ /* Shut down on SIGINT/SIGTERM: kill the containers we started. * No SA_RESTART, so accept() is interrupted and we notice. */ memset(&stop_action, 0, sizeof(stop_action)); stop_action.sa_handler = handle_stop; sigemptyset(&stop_action.sa_mask); sigaction(SIGINT, &stop_action, NULL); sigaction(SIGTERM, &stop_action, NULL); memset(&addr6, 0, sizeof(addr6)); memset(&addr4, 0, sizeof(addr4)); if (strchr(listen_ip, ':')) { /* IPv6 address */ family = AF_INET6; addr6.sin6_family = AF_INET6; addr6.sin6_port = htons(port); if (inet_pton(AF_INET6, listen_ip, &addr6.sin6_addr) != 1) { fprintf(stderr, "invalid IPv6 address: %s\n", listen_ip); return 1; } sa = (struct sockaddr *)&addr6; sa_len = sizeof(addr6); } else { /* IPv4 address */ family = AF_INET; addr4.sin_family = AF_INET; addr4.sin_port = htons(port); if (inet_pton(AF_INET, listen_ip, &addr4.sin_addr) != 1) { fprintf(stderr, "invalid IPv4 address: %s\n", listen_ip); return 1; } sa = (struct sockaddr *)&addr4; sa_len = sizeof(addr4); } srv = socket(family, SOCK_STREAM, 0); if (srv < 0) { perror("socket"); return 1; } setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); if (family == AF_INET6) setsockopt(srv, IPPROTO_IPV6, IPV6_V6ONLY, &one, sizeof(one)); if (bind(srv, sa, sa_len) != 0) { perror("bind"); return 1; } if (listen(srv, 16) != 0) { perror("listen"); return 1; } logmsg(PROGRAM " listening on [%s]:%d (fingerprint %s)", listen_ip, port, daemon_fingerprint); for (;;) { struct sockaddr_storage peer; socklen_t peer_len = sizeof(peer); char ip[INET6_ADDRSTRLEN]; int fd = accept(srv, (struct sockaddr *)&peer, &peer_len); const void *src; if (stop_requested) break; if (fd < 0) { if (errno == EINTR) continue; logmsg("accept: %s", strerror(errno)); continue; } src = peer.ss_family == AF_INET6 ? (void *)&((struct sockaddr_in6 *)&peer)->sin6_addr : (void *)&((struct sockaddr_in *)&peer)->sin_addr; inet_ntop(peer.ss_family, src, ip, sizeof(ip)); handle_connection(fd, ip); close(fd); } shutdown_containers(); logmsg(PROGRAM " exiting"); return 0; } /* ------------------------------------------------------------------ */ int main(int argc, char **argv) { const char *listen_ip = DEFAULT_LISTEN; const char *fp_opt = NULL; int port = DEFAULT_PORT; int i; const char *env_log_dir = getenv("GUIX_CONTAINER_LOG_DIR"); if (env_log_dir && *env_log_dir) log_dir = env_log_dir; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "--listen") == 0 && i + 1 < argc) { listen_ip = argv[++i]; } else if (strcmp(argv[i], "--port") == 0 && i + 1 < argc) { char *end; long p = strtol(argv[++i], &end, 10); if (*end || p <= 0 || p > 65535) { fprintf(stderr, "invalid port: %s\n", argv[i]); return 1; } port = p; } else if (strcmp(argv[i], "--log-dir") == 0 && i + 1 < argc) { log_dir = argv[++i]; } else if (strcmp(argv[i], "--fingerprint") == 0 && i + 1 < argc) { fp_opt = argv[++i]; } else { fprintf(stderr, "usage: %s [--listen IP] [--port N] [--log-dir DIR] " "[--fingerprint WORD]\n" " --listen IP address to listen on (default " DEFAULT_LISTEN ")\n" " --port N port (default %d)\n" " --log-dir DIR where container boot output goes\n" " (default " DEFAULT_LOG_DIR ", or\n" " $GUIX_CONTAINER_LOG_DIR)\n" " --fingerprint WORD short word or version (e.g. v0.1)\n" " identifying this daemon; containers\n" " started here get it in the\n" " GUIX_CONTAINER_FINGERPRINT variable.\n" " Default: a random hash.\n", PROGRAM, DEFAULT_PORT); return 1; } } if (fp_opt) { if (!valid_fingerprint(fp_opt)) { fprintf(stderr, "invalid fingerprint: '%s' (1-32 printable chars, no whitespace)\n", fp_opt); return 1; } strncpy(daemon_fingerprint, fp_opt, sizeof(daemon_fingerprint) - 1); daemon_fingerprint[sizeof(daemon_fingerprint) - 1] = '\0'; } else { random_fingerprint(); } /* Say where boot output will go before anything can fail: it is the * first thing an operator needs when a container does not come up, and * it makes --log-dir observable without root. */ logmsg("container logs: %s", log_dir); if (!have_container_privileges()) return 1; check_log_dir(); return serve(listen_ip, port); }