about summary refs log tree commit diff
path: root/bin
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public12@thebird.nl>2026-09-26 13:09:25 +0000
committerPjotr Prins <pjotr.public12@thebird.nl>2026-09-26 13:09:25 +0000
commit2ff6ab0645463504fd101e73d3e4e2ab75a08c94 (patch)
tree5294b1b455b52fb194e1c9b8c25d80c0b85bfc23 /bin
downloadrun-guix-container-2ff6ab0645463504fd101e73d3e4e2ab75a08c94.tar.gz
run-guix-container: new tool
A C daemon (run as root) that starts Guix system containers on
request over a line-based network protocol, plus an unprivileged
Ruby client.

* START/KILL/LOG/FINGERPRINT protocol; one request per connection
* strict validation of store items before exec (HASH-run-container
  name, guile shebang, container markers, immutable store file)
* --fingerprint WORD identifies the daemon instance (random hash
  when unset); verified by clients and passed to containers in
  GUIX_CONTAINER_FINGERPRINT
* on SIGINT/SIGTERM: SIGTERM all started containers, 10s timeout,
  then SIGKILL
* container boot output appended to /var/log/guix-containers/
* unit tests for launcher and fingerprint logic
Diffstat (limited to 'bin')
-rwxr-xr-xbin/run-guix-container.rb176
-rwxr-xr-xbin/run-guix-system-containerbin0 -> 26936 bytes
-rw-r--r--bin/run-guix-system-container.c756
3 files changed, 932 insertions, 0 deletions
diff --git a/bin/run-guix-container.rb b/bin/run-guix-container.rb
new file mode 100755
index 0000000..c2e79e3
--- /dev/null
+++ b/bin/run-guix-container.rb
@@ -0,0 +1,176 @@
+#!/usr/bin/env ruby
+# run-guix-container.rb
+#
+# Start (or stop) a Guix system container by its store hash.
+#
+#   ./run-guix-container.rb HASH                # find + run the container
+#   ./run-guix-container.rb /gnu/store/HASH-...  # or a full store path
+#   ./run-guix-container.rb --kill PID           # stop a running container
+#   ./run-guix-container.rb --fingerprint v0.1   # verify the daemon first
+#
+# The script validates that:
+#   * the hash looks like a valid base32 Guix store hash (32 chars)
+#   * exactly one matching, executable container script exists in the store
+#   * the script is a Guix container launcher (uses linux-container)
+#
+# It then starts the container in one of two ways:
+#
+# 1. Network API: if --daemon HOST:PORT (or GUIX_CONTAINER_DAEMON) is
+#    given, it sends 'START <hash>' to a run-guix-system-container
+#    --serve daemon on the underlying host, which validates and starts
+#    the container with root privileges.  With --fingerprint WORD the
+#    daemon's fingerprint is checked first (FINGERPRINT command), so
+#    you never talk to a stale daemon by accident.
+# 2. Local sudo: otherwise it invokes sudo run-guix-system-container,
+#    which performs the same validation locally.
+
+STORE = '/gnu/store'
+LAUNCHER = 'run-guix-system-container'
+DEFAULT_DAEMON = '127.0.0.1:8989'
+HASH_RE = /\A[0-9a-z]{32}\z/
+
+def fail(msg)
+  warn "error: #{msg}"
+  exit 1
+end
+
+require 'socket'
+
+def talk_to_daemon(daemon, request)
+  host, port = daemon.split(':', 2)
+  fail "invalid daemon address: #{daemon}" if host.nil? || port.nil?
+  sock = TCPSocket.new(host, Integer(port))
+  sock.puts request
+  response = sock.gets.to_s.strip
+  sock.close
+  response
+end
+
+# Like talk_to_daemon, but reads the whole (possibly multi-line)
+# response — used for LOG, whose body follows the OK line.
+def fetch_from_daemon(daemon, request)
+  host, port = daemon.split(':', 2)
+  fail "invalid daemon address: #{daemon}" if host.nil? || port.nil?
+  sock = TCPSocket.new(host, Integer(port))
+  sock.puts request
+  sock.read
+ensure
+  sock&.close
+end
+
+# Ask the daemon for its fingerprint and compare it with EXPECTED.
+# Returns the daemon's fingerprint; fails on mismatch or protocol error.
+def verify_fingerprint(daemon, expected)
+  response = talk_to_daemon(daemon, 'FINGERPRINT')
+  fail "daemon fingerprint query failed: #{response}" unless response.start_with?('OK ')
+  got = response.split(' ', 2)[1].to_s
+  fail "daemon fingerprint mismatch: expected #{expected}, got #{got}" unless got == expected
+  got
+end
+
+arg = nil
+kill_pid = nil
+log_arg = nil
+fingerprint = nil
+daemon = ENV['GUIX_CONTAINER_DAEMON']
+
+while !ARGV.empty? && ARGV[0].start_with?('--')
+  case ARGV[0]
+  when '--daemon'
+    daemon = ARGV[1]
+    ARGV.shift(2)
+  when '--kill'
+    kill_pid = ARGV[1]
+    ARGV.shift(2)
+  when '--log'
+    log_arg = ARGV[1]
+    ARGV.shift(2)
+  when '--fingerprint'
+    fingerprint = ARGV[1]
+    ARGV.shift(2)
+  when '--daemon-local'
+    daemon ||= DEFAULT_DAEMON
+    ARGV.shift
+  else
+    fail "unknown option: #{ARGV[0]}"
+  end
+end
+arg = ARGV[0]
+
+# --log HASH: fetch and print a container's log from the daemon.
+if log_arg
+  fail "--log requires a daemon (--daemon HOST:PORT)" unless daemon
+  verify_fingerprint(daemon, fingerprint) if fingerprint
+  hash = log_arg.start_with?(STORE + '/') ? File.basename(log_arg).split('-', 2).first : log_arg
+  fail "not a valid store hash: #{hash}" unless hash =~ HASH_RE
+  out = fetch_from_daemon(daemon, "LOG #{hash}")
+  fail "daemon refused: #{out.lines.first&.strip}" unless out.start_with?("OK\n")
+  print out.split("\n", 2)[1].to_s
+  exit 0
+end
+
+# --kill PID: ask the daemon to terminate a container.
+if kill_pid
+  fail "--kill requires a daemon (--daemon HOST:PORT)" unless daemon
+  verify_fingerprint(daemon, fingerprint) if fingerprint
+  fail "invalid pid: #{kill_pid}" unless kill_pid =~ /\A\d+\z/
+  response = talk_to_daemon(daemon, "KILL #{kill_pid}")
+  puts response
+  fail "daemon refused: #{response}" unless response.start_with?('OK ')
+  exit 0
+end
+
+fail 'usage: run-guix-container.rb [--daemon HOST:PORT] HASH|/gnu/store/HASH-...' if arg.nil?
+
+hash =
+  if arg.start_with?(STORE + '/')
+    File.basename(arg).split('-', 2).first
+  else
+    arg
+  end
+
+fail "not a valid store hash: #{hash}" unless hash =~ HASH_RE
+
+# Collect all store entries starting with the hash. A valid nix-base32
+# hash is 32 chars, so no other store item can share the prefix.
+entries = Dir.glob(File.join(STORE, "#{hash}-*")).sort
+fail "no store item found for hash #{hash}" if entries.empty?
+
+# Only keep real files (the container launcher), not .drv or directories.
+candidates = entries.select do |path|
+  File.file?(path) && File.executable?(path) && !path.end_with?('.drv')
+end
+fail "hash #{hash} matches no executable store item" if candidates.empty?
+fail "hash #{hash} is ambiguous: #{candidates.join(' ')}" if candidates.size > 1
+
+container = candidates.first
+
+# Sanity check: it must be a Guix container launcher script (it uses the
+# (gnu build linux-container) module to set up namespaces).
+head = File.open(container, 'rb') { |f| f.read(4096) }
+fail "#{container} is not a Guix container script" unless head.include?('linux-container')
+
+# Start the container.
+if daemon
+  fp = verify_fingerprint(daemon, fingerprint) if fingerprint
+  puts "Starting container #{hash} via daemon #{daemon}" +
+       (fp ? " (fingerprint #{fp})" : '')
+  response = talk_to_daemon(daemon, "START #{hash}")
+  puts response
+  fail "daemon refused: #{response}" unless response.start_with?('OK ')
+  pid = response.split[1]
+  puts "Container running as PID #{pid}; inspect with:"
+  puts "  nsenter -at #{pid} /run/current-system/profile/bin/bash --login"
+  exit 0
+end
+
+# Local sudo path: the privileged launcher must be installed in PATH
+# (in a root-owned directory such as /usr/local/bin, see README).
+launcher = ENV.fetch('PATH', '').split(File::PATH_SEPARATOR)
+               .map { |d| File.join(d, LAUNCHER) }
+               .find { |p| File.file?(p) && File.executable?(p) }
+fail "launcher not found in PATH: #{LAUNCHER} (see README)" unless launcher
+
+puts "Starting container: #{container}"
+exec 'sudo', '--', launcher, container
+fail "exec failed for #{container}"
diff --git a/bin/run-guix-system-container b/bin/run-guix-system-container
new file mode 100755
index 0000000..a412e40
--- /dev/null
+++ b/bin/run-guix-system-container
Binary files differdiff --git a/bin/run-guix-system-container.c b/bin/run-guix-system-container.c
new file mode 100644
index 0000000..8323e90
--- /dev/null
+++ b/bin/run-guix-system-container.c
@@ -0,0 +1,756 @@
+/* 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 <hash> <fingerprint>").
+ * 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.
+ *
+ * Protocol (one line per connection):
+ *   START <hash|/gnu/store/HASH-run-container> [<fingerprint>]\n
+ *     → OK <pid>\n     container started
+ *     → ERR <reason>\n validation failure (a non-matching optional
+ *                     fingerprint yields "ERR fingerprint mismatch")
+ *   KILL <pid>\n
+ *     → OK killed <pid>\n  SIGTERM sent
+ *     → ERR <reason>\n   not a known container, etc.
+ *   LOG <hash|/gnu/store/HASH-run-container>\n
+ *     → OK\n + the raw contents of the container's log file
+ *       (LOG_DIR/HASH-run-container.log)
+ *     → ERR <reason>\n   no log file
+ *   FINGERPRINT\n
+ *     → OK <fingerprint>\n  the daemon's fingerprint
+ *
+ * Container stdout/stderr is appended to LOG_DIR (default
+ * /var/log/guix-containers) so boot failures can be diagnosed.
+ *
+ * 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 <arpa/inet.h>
+#include <ctype.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <netinet/in.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <sys/socket.h>
+#include <time.h>
+#include <unistd.h>
+#include <stdarg.h>
+#include <stdint.h>
+
+#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/<name>.log. */
+#define LOG_DIR "/var/log/guix-containers"
+
+/* 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);
+}
+
+/* ------------------------------------------------------------------ */
+/* 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;
+}
+
+/* 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);
+	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(started_pids[i], SIGKILL);
+		}
+}
+
+static void handle_stop(int sig)
+{
+	(void)sig;
+	stop_requested = 1;
+}
+
+/* Fallback for PIDs started by a previous daemon instance: the
+ * process must be a /gnu/store/HASH-run-container script. */
+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;
+}
+
+/* Handle "KILL <pid>": terminate a container the daemon started
+ * (or a previous instance started). */
+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((pid_t)pid, SIGTERM) != 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 SIGTERM to %ld (client %s)", pid, client_ip);
+	dprintf(fd, "OK killed %ld\n", pid);
+}
+
+/* Handle "LOG <hash|path>": 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/<basename>.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 <arg>\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 (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 <hash|path> [fingerprint]', 'KILL <pid>', 'LOG <hash>' 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;
+		}
+	}
+
+	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;
+
+	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], "--fingerprint") == 0 && i + 1 < argc) {
+			fp_opt = argv[++i];
+		} else {
+			fprintf(stderr,
+				 "usage: %s [--listen IP] [--port N] [--fingerprint WORD]\n"
+				 "  --listen IP        address to listen on (default "
+				 DEFAULT_LISTEN ")\n"
+				 "  --port N           port (default %d)\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();
+	}
+
+	if (geteuid() != 0)
+		logmsg("warning: not running as root; containers started "
+		       "by this process may fail to map their user namespace");
+
+	return serve(listen_ip, port);
+}