Commit Diff


commit - /dev/null
commit + 61aeeb88b3ff7f4f29a4d4b98e0f2810a2b7f497c04b5b25cc620cf88a5f6bdb
blob - /dev/null
blob + 70f1ac6205cab9bb9908dac6258ab961cf4531b16fe017adedc83a1e6c5c2c37 (mode 644)
--- /dev/null	
+++ .gitignore	
@@ -0,0 +1,9 @@
+**/obj
+**/*.d
+**/*.o
+.gitignore
+**/.gitignore
+**/parse.c
+**/parse.h
+newd/newd
+newctl/newctl
blob - /dev/null
blob + 3458dc2e8696865ade09e4a412e0e0b63d980805e5b81d1675327ad53b29faa2 (mode 644)
--- /dev/null	
+++ LICENSE.md	
@@ -0,0 +1,13 @@
+Copyright (c) 2019-2026 Tracey Emery <tracey@openbsd.org>
+
+Permission to use, copy, modify, and distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
blob - /dev/null
blob + 1e502269e7927cc9c9a93fd5f2be857aa79a8948f01ed4201f725272175eb5d9 (mode 644)
--- /dev/null	
+++ Makefile	
@@ -0,0 +1,3 @@
+SUBDIR = newd newctl
+
+.include <bsd.subdir.mk>
blob - /dev/null
blob + 774d9033dd995d0371d1c879266d521b9ee64d3e4da4f12ea322215fd672e5b2 (mode 644)
--- /dev/null	
+++ README.md	
@@ -0,0 +1,79 @@
+newd for OpenBSD
+================
+
+newd is a base daemon to start new OpenBSD daemons from. It carries the
+privilege separated process layout, the imsg pipes between the processes,
+the newctl control socket, a yacc configuration parser with macro and
+include support, logging, and the rc.d and man page scaffolding, and
+nothing else.
+
+Processes
+---------
+
+* `newd` (parent): runs as root, parses `newd.conf`, forks the children,
+  pushes configuration to them and answers `newctl show parent`.
+* `control`: chrooted and unprivileged, owns `/var/run/newd.sock` and
+  routes `newctl` requests to the parent and replies back to `newctl`.
+* `engine`: chrooted and unprivileged, where the work of the new daemon
+  belongs. Receives configuration from the parent and answers
+  `newctl show engine`.
+
+Startup is: the parent sends `IMSG_CFG_DONE` to both children, the engine
+acknowledges with `IMSG_CFG_DONE`, and the parent then sends
+`IMSG_CTL_START` to both, at which point the engine calls `engine_launch()`.
+
+Building a new daemon
+---------------------
+
+1. Rename `newd`/`newctl`/`NEWD_*`/`_newd` throughout.
+2. Add configuration keywords to `parse.y` (the `%token` line, the sorted
+   table in `lookup()` and a `conf_main` rule) and fields to `struct newd`.
+3. Add `IMSG_*` types to `newd.h`, handle them in the `*_dispatch_*`
+   functions, and send any state the engine needs from `newd_configure()`.
+4. Add `newctl` commands to `parser.c` and handlers to `newctl.c`.
+5. Widen the `pledge` and `unveil` calls as needed.
+
+Prerequisites
+-------------
+
+* OpenBSD 7.7 or higher
+
+Files
+-----
+
+* `/usr/local/sbin/newd`
+* `/usr/local/man/man8/newd.8`
+* `/etc/examples/newd.conf`
+* `/usr/local/man/man5/newd.conf.5`
+* `/etc/rc.d/newd`
+* `/usr/local/sbin/newctl`
+* `/usr/local/man/man8/newctl.8`
+
+Usage
+-----
+
+Compile and install.
+
+		make
+		doas make install
+		doas groupadd _newd
+		doas useradd -d /var/empty -L daemon -g _newd -s /sbin/nologin _newd
+		doas cp newd/examples/etc/rc.d/newd /etc/rc.d/
+		doas cp newd/examples/etc/newd.conf /etc/
+
+Once newd.conf is in place, run `rcctl enable newd` and `rcctl start newd`.
+The daemon can also be run manually from the command line. To keep newd
+from daemonizing, run `newd -d`.
+
+To check it is alive:
+
+		newctl show parent
+		newctl show control
+		newctl show engine
+
+Author
+------
+
+[Tracey Emery](https://github.com/basepr1me/)
+
+See the [License](LICENSE.md) file for more information.
blob - /dev/null
blob + bfacbcb425d0f018d946a1e1457385b6f56444cf066ffe50541084f578af7892 (mode 644)
--- /dev/null	
+++ newctl/Makefile	
@@ -0,0 +1,19 @@
+PROG=		newctl
+
+SRCS+=		newctl.c parser.c
+
+PREFIX=		/usr/local
+BINDIR?=	${PREFIX}/sbin
+MANDIR?=	${PREFIX}/man/man
+
+LDADD=		-lutil
+CFLAGS+=	-Wall -I${.CURDIR}
+CFLAGS+=	-Wstrict-prototypes -Wmissing-prototypes
+CFLAGS+=	-Wmissing-declarations
+CFLAGS+=	-Wshadow -Wpointer-arith
+CFLAGS+=	-Wsign-compare -fno-common
+CFLAGS+=	-I${.CURDIR} -I${.CURDIR}/../newd
+
+MAN=		newctl.8
+
+.include <bsd.prog.mk>
blob - /dev/null
blob + 633f25e56524a38ed195e8458ecbd94aed12e48e35b5388a679445c99de331b1 (mode 644)
--- /dev/null	
+++ newctl/newctl.8	
@@ -0,0 +1,69 @@
+.\"
+.\" Copyright (c) 2016-2026 Tracey Emery <tracey@openbsd.org>
+.\"
+.\" Permission to use, copy, modify, and distribute this software for any
+.\" purpose with or without fee is hereby granted, provided that the above
+.\" copyright notice and this permission notice appear in all copies.
+.\"
+.\" THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+.\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+.\" MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+.\" ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+.\" WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+.\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+.\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+.\"
+.Dd $Mdocdate: November 19 2026 $
+.Dt NEWCTL 8
+.Os
+.Sh NAME
+.Nm newctl
+.Nd control the newd daemon
+.Sh SYNOPSIS
+.Nm
+.Op Fl s Ar socket
+.Ar command
+.Op Ar argument ...
+.Sh DESCRIPTION
+The
+.Nm
+program controls the
+.Xr newd 8
+daemon.
+.Pp
+The following options are available:
+.Bl -tag -width Ds
+.It Fl s Ar socket
+Use
+.Ar socket
+instead of the default
+.Pa /var/run/newd.sock
+to communicate with
+.Xr newd 8 .
+.El
+.Pp
+The following commands are available:
+.Bl -tag -width Ds
+.It Cm log brief
+Disable verbose logging.
+.It Cm log verbose
+Enable verbose logging.
+.It Cm log debug
+Enable very noisy debug logging.
+.It Cm show control
+Return control process logging verbosity.
+.It Cm show engine
+Return engine process logging verbosity.
+.It Cm show parent
+Return parent process logging verbosity.
+.El
+.Sh FILES
+.Bl -tag -width "/var/run/newd.sockXX" -compact
+.It Pa /var/run/newd.sock
+.Ux Ns -domain
+socket used for communication with
+.Xr newd 8 .
+.El
+.Sh SEE ALSO
+.Xr newd.conf 5 ,
+.Xr newd 8
blob - /dev/null
blob + fd37e6355240444e41aaf4946dccf31ccfb8ecd94009fc72872fd32450327be9 (mode 644)
--- /dev/null	
+++ newctl/newctl.c	
@@ -0,0 +1,259 @@
+/*
+ * Copyright (c) 2019, 2020-2026 Tracey Emery <tracey@openbsd.org>
+ * Copyright (c) 2005 Claudio Jeker <claudio@openbsd.org>
+ * Copyright (c) 2004, 2005 Esben Norby <norby@openbsd.org>
+ * Copyright (c) 2003 Henning Brauer <henning@openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <sys/types.h>
+#include <sys/queue.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+
+#include <err.h>
+#include <errno.h>
+#include <event.h>
+#include <imsg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "newd.h"
+#include "parser.h"
+
+__dead void	 usage(void);
+int		 show_parent_msg(struct imsg *);
+int		 show_control_msg(struct imsg *);
+int		 show_engine_msg(struct imsg *);
+const char	*verbose_name(int);
+
+struct imsgbuf	*ibuf;
+
+__dead void
+usage(void)
+{
+	extern char *__progname;
+
+	fprintf(stderr, "usage: %s [-s socket] command [argument ...]\n",
+	    __progname);
+	exit(1);
+}
+
+int
+main(int argc, char *argv[])
+{
+	struct sockaddr_un	 sun;
+	struct parse_result	*res;
+	struct imsg		 imsg;
+	int			 ctl_sock;
+	int			 done = 0;
+	int			 n, verbose = 0;
+	int			 ch;
+	char			*sockname;
+
+	sockname = NEWD_SOCKET;
+	while ((ch = getopt(argc, argv, "s:")) != -1) {
+		switch (ch) {
+		case 's':
+			sockname = optarg;
+			break;
+		default:
+			usage();
+		}
+	}
+	argc -= optind;
+	argv += optind;
+
+	/* Parse command line. */
+	if ((res = parse(argc, argv)) == NULL)
+		exit(1);
+
+	/* Connect to control socket. */
+	if ((ctl_sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
+		err(1, "socket");
+
+	memset(&sun, 0, sizeof(sun));
+	sun.sun_family = AF_UNIX;
+
+	if (strlcpy(sun.sun_path, sockname, sizeof(sun.sun_path)) >=
+	    sizeof(sun.sun_path))
+		errx(1, "socket path too long: %s", sockname);
+	if (connect(ctl_sock, (struct sockaddr *)&sun, sizeof(sun)) == -1)
+		err(1, "connect: %s", sockname);
+
+	if (pledge("stdio", NULL) == -1)
+		err(1, "pledge");
+
+	if ((ibuf = malloc(sizeof(struct imsgbuf))) == NULL)
+		err(1, "%s: malloc", __func__);
+	if (imsgbuf_init(ibuf, ctl_sock) == -1)
+		err(1, "%s: imsgbuf_init", __func__);
+	done = 0;
+
+	/* Check for root only actions */
+	switch (res->action) {
+	case LOG_DEBUG:
+	case LOG_VERBOSE:
+	case LOG_BRIEF:
+		if (geteuid() != 0)
+			errx(1, "need root privileges");
+		break;
+	default:
+		break;
+	}
+
+	/* Process user request. */
+	switch (res->action) {
+	case LOG_DEBUG:
+		verbose++;
+		/* FALLTHROUGH */
+	case LOG_VERBOSE:
+		verbose++;
+		/* FALLTHROUGH */
+	case LOG_BRIEF:
+		imsg_compose(ibuf, IMSG_CTL_VERBOSE, 0, 0, -1,
+		    &verbose, sizeof(verbose));
+		printf("\nLogging request sent.\n");
+		done = 1;
+		break;
+	case SHOW_CONTROL:
+		imsg_compose(ibuf, IMSG_GET_INFO_CONTROL_REQUEST, 0,
+		    0, -1, NULL, 0);
+		break;
+	case SHOW_ENGINE:
+		imsg_compose(ibuf, IMSG_GET_INFO_ENGINE_REQUEST, 0,
+		    0, -1, NULL, 0);
+		break;
+	case SHOW_PARENT:
+		imsg_compose(ibuf, IMSG_GET_INFO_PARENT_REQUEST, 0,
+		    0, -1, NULL, 0);
+		break;
+	case RELOAD:
+		printf("\nReload is not supported.\n");
+		printf("Use `rcctl restart newd` instead.\n");
+		done = 1;
+		break;
+	default:
+		usage();
+	}
+
+	if (imsgbuf_flush(ibuf) == -1)
+		err(1, "write error");
+
+	while (!done) {
+		if ((n = imsgbuf_read(ibuf)) == -1)
+			errx(1, "imsg_read error");
+		if (n == 0)
+			errx(1, "pipe closed");
+
+		while (!done) {
+			if ((n = imsgbuf_get(ibuf, &imsg)) == -1)
+				errx(1, "imsgbuf_get error");
+			if (n == 0)
+				break;
+
+			switch (res->action) {
+			case SHOW_CONTROL:
+				done = show_control_msg(&imsg);
+				break;
+			case SHOW_ENGINE:
+				done = show_engine_msg(&imsg);
+				break;
+			case SHOW_PARENT:
+				done = show_parent_msg(&imsg);
+				break;
+			default:
+				break;
+			}
+			imsg_free(&imsg);
+		}
+	}
+	printf("\n");
+	close(ctl_sock);
+	free(ibuf);
+
+	return (0);
+}
+
+const char *
+verbose_name(int verbose)
+{
+	if (verbose == 2)
+		return ("debug");
+	if (verbose == 1)
+		return ("verbose");
+	return ("brief");
+}
+
+int
+show_parent_msg(struct imsg *imsg)
+{
+	struct newd_parent_info	*npi;
+
+	switch (imsg->hdr.type) {
+	case IMSG_GET_INFO_PARENT_DATA:
+		npi = imsg->data;
+		printf("\nParent says: Logging level is %s (%d).\n",
+		    verbose_name(npi->verbose), npi->verbose);
+		break;
+	case IMSG_GET_INFO_PARENT_END_DATA:
+		return (1);
+	default:
+		break;
+	}
+
+	return (0);
+}
+
+int
+show_control_msg(struct imsg *imsg)
+{
+	struct newd_control_info	*nci;
+
+	switch (imsg->hdr.type) {
+	case IMSG_GET_INFO_CONTROL_DATA:
+		nci = imsg->data;
+		printf("\nControl says: Logging level is %s (%d).\n",
+		    verbose_name(nci->verbose), nci->verbose);
+		break;
+	case IMSG_GET_INFO_CONTROL_END_DATA:
+		return (1);
+	default:
+		break;
+	}
+
+	return (0);
+}
+
+int
+show_engine_msg(struct imsg *imsg)
+{
+	struct newd_engine_info	*nei;
+
+	switch (imsg->hdr.type) {
+	case IMSG_GET_INFO_ENGINE_DATA:
+		nei = imsg->data;
+		printf("\nEngine says: Logging level is %s (%d).\n",
+		    verbose_name(nei->verbose), nei->verbose);
+		break;
+	case IMSG_GET_INFO_ENGINE_END_DATA:
+		return (1);
+	default:
+		break;
+	}
+
+	return (0);
+}
blob - /dev/null
blob + 462e6ad05a1543304fba0ed6471ee13f425adce6fabee3cf6e95714e88891f88 (mode 644)
--- /dev/null	
+++ newctl/parser.c	
@@ -0,0 +1,193 @@
+/*
+ * Copyright (c) 2019, 2020-2026 Tracey Emery <tracey@openbsd.org>
+ * Copyright (c) 2004 Esben Norby <norby@openbsd.org>
+ * Copyright (c) 2003, 2004 Henning Brauer <henning@openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <sys/types.h>
+#include <sys/queue.h>
+#include <sys/socket.h>
+
+#include <err.h>
+#include <errno.h>
+#include <event.h>
+#include <imsg.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "newd.h"
+#include "parser.h"
+
+enum token_type {
+	NOTOKEN,
+	ENDTOKEN,
+	NAME,
+	KEYWORD
+};
+
+struct token {
+	enum token_type		 type;
+	const char		*keyword;
+	int			 value;
+	const struct token	*next;
+};
+
+static const struct token t_log[];
+static const struct token t_main[];
+static const struct token t_show[];
+
+static const struct token t_main[] = {
+	{KEYWORD,	"log",		NONE,		t_log},
+	{KEYWORD,	"reload",	RELOAD,		NULL},
+	{KEYWORD,	"show",		SHOW,		t_show},
+	{ENDTOKEN,	"",		NONE,		NULL}
+};
+
+static const struct token t_log[] = {
+	{KEYWORD,	"brief",	LOG_BRIEF,	NULL},
+	{KEYWORD,	"debug",	LOG_DEBUG,	NULL},
+	{KEYWORD,	"verbose",	LOG_VERBOSE,	NULL},
+	{ENDTOKEN,	"",		NONE,		NULL}
+};
+
+static const struct token t_show[] = {
+	{KEYWORD,	"control",	SHOW_CONTROL,	NULL},
+	{KEYWORD,	"engine",	SHOW_ENGINE,	NULL},
+	{KEYWORD,	"parent",	SHOW_PARENT,	NULL},
+	{ENDTOKEN,	"",		NONE,		NULL}
+};
+
+static const struct token *match_token(const char *, const struct token *,
+    struct parse_result *);
+static void show_valid_args(const struct token *);
+
+struct parse_result *
+parse(int argc, char *argv[])
+{
+	static struct parse_result	res;
+	const struct token	*table = t_main;
+	const struct token	*match;
+
+	memset(&res, 0, sizeof(res));
+
+	while (argc >= 0) {
+		if ((match = match_token(argv[0], table, &res)) == NULL) {
+			fprintf(stderr, "valid commands/args:\n");
+			show_valid_args(table);
+			return (NULL);
+		}
+
+		argc--;
+		argv++;
+
+		if (match->type == NOTOKEN || match->next == NULL)
+			break;
+
+		table = match->next;
+	}
+
+	if (argc > 0) {
+		fprintf(stderr, "superfluous argument: %s\n", argv[0]);
+		return (NULL);
+	}
+
+	return (&res);
+}
+
+/*
+ * A NAME token takes the next word as an argument into res->name, for
+ * commands such as "show foo <name>".  Nothing uses it yet.
+ */
+static const struct token *
+match_token(const char *word, const struct token *table,
+    struct parse_result *res)
+{
+	u_int			 i, match;
+	const struct token	*t = NULL;
+
+	match = 0;
+
+	for (i = 0; table[i].type != ENDTOKEN; i++) {
+		switch (table[i].type) {
+		case NOTOKEN:
+			if (word == NULL || strlen(word) == 0) {
+				match++;
+				t = &table[i];
+			}
+			break;
+		case NAME:
+			if (!match && word != NULL && strlen(word) > 0) {
+				if (strlcpy(res->name, word,
+				    sizeof(res->name)) >= sizeof(res->name)) {
+					fprintf(stderr, "name too long: %s\n",
+					    word);
+					return (NULL);
+				}
+				match++;
+				t = &table[i];
+				if (t->value)
+					res->action = t->value;
+			}
+			break;
+		case KEYWORD:
+			if (word != NULL && strncmp(word, table[i].keyword,
+			    strlen(word)) == 0) {
+				match++;
+				t = &table[i];
+				if (t->value)
+					res->action = t->value;
+			}
+			break;
+		case ENDTOKEN:
+			break;
+		}
+	}
+
+	if (match != 1) {
+		if (word == NULL)
+			fprintf(stderr, "missing argument:\n");
+		else if (match > 1)
+			fprintf(stderr, "ambiguous argument: %s\n", word);
+		else if (match < 1)
+			fprintf(stderr, "unknown argument: %s\n", word);
+		return (NULL);
+	}
+
+	return (t);
+}
+
+static void
+show_valid_args(const struct token *table)
+{
+	int	i;
+
+	for (i = 0; table[i].type != ENDTOKEN; i++) {
+		switch (table[i].type) {
+		case NOTOKEN:
+			fprintf(stderr, "  <cr>\n");
+			break;
+		case NAME:
+			fprintf(stderr, " <name>\n");
+			break;
+		case KEYWORD:
+			fprintf(stderr, "  %s\n", table[i].keyword);
+			break;
+		case ENDTOKEN:
+			break;
+		}
+	}
+}
blob - /dev/null
blob + 99d39cd25e8881967a736ac73941aca91dcf1ce51b7e32840a5665b6de1f905e (mode 644)
--- /dev/null	
+++ newctl/parser.h	
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2019, 2020-2026 Tracey Emery <tracey@openbsd.org>
+ * Copyright (c) 2004 Esben Norby <norby@openbsd.org>
+ * Copyright (c) 2003, 2004 Henning Brauer <henning@openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+enum actions {
+	NONE,
+	LOG_BRIEF,
+	LOG_DEBUG,
+	LOG_VERBOSE,
+	RELOAD,
+	SHOW,
+	SHOW_CONTROL,
+	SHOW_ENGINE,
+	SHOW_PARENT,
+};
+
+struct parse_result {
+	enum actions	action;
+	char		name[NEWD_MAXNAME];
+};
+
+struct parse_result	*parse(int, char *[]);
blob - /dev/null
blob + 53d695810b415db044870a976643f5e1553e068d87a767d10c0edaaf93a341ad (mode 644)
--- /dev/null	
+++ newd/Makefile	
@@ -0,0 +1,23 @@
+PROG =		newd
+SRCS =		parse.y
+SRCS +=		config.c control.c engine.c log.c newd.c
+
+MAN =		newd.8 newd.conf.5
+
+PREFIX=		/usr/local
+BINDIR?=	${PREFIX}/sbin
+MANDIR?=	${PREFIX}/man/man
+
+LDADD =		-levent -lutil
+DPADD =		${LIBEVENT} ${LIBUTIL}
+# DEBUG=		-g -O0 -DDEBUG=0
+CFLAGS +=	-Wall -I${.CURDIR}
+CFLAGS +=	-Wstrict-prototypes -Wmissing-prototypes
+CFLAGS +=	-Wmissing-declarations
+CFLAGS +=	-Wshadow -Wpointer-arith -fno-common
+CFLAGS +=	-Wsign-compare
+YFLAGS =
+
+CLEANFILES+=	y.tab.h
+
+.include <bsd.prog.mk>
blob - /dev/null
blob + dec3636e6348c7c2e84ddf06fdfb162ae38db8bf56774f78658c04016ed06b7f (mode 644)
--- /dev/null	
+++ newd/config.c	
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2020-2026 Tracey Emery <tracey@openbsd.org>
+ * Copyright (c) 2015 Reyk Floeter <reyk@openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <sys/types.h>
+#include <sys/queue.h>
+#include <sys/uio.h>
+
+#include <stdlib.h>
+#include <string.h>
+#include <event.h>
+#include <imsg.h>
+
+#include "newd.h"
+
+/*
+ * Set up the lists and defaults the configuration will be parsed into.
+ * Called by the parent before parsing and by the engine at startup so
+ * both begin from the same empty state.
+ */
+int
+config_init(struct newd *env)
+{
+	return (0);
+}
+
+/*
+ * The parent has finished sending configuration.  Acknowledge it so the
+ * parent can release IMSG_CTL_START once every child is ready.
+ */
+int
+config_getcfg(struct newd *env, struct imsg *imsg)
+{
+	imsg_compose_event(engine_iev_parent, IMSG_CFG_DONE, 0, 0, -1, NULL, 0);
+
+	return (0);
+}
blob - /dev/null
blob + ba7a943569ae06a219b013c6d18763ef278a5ccc071ef20d83fa37672f83d564 (mode 644)
--- /dev/null	
+++ newd/control.c	
@@ -0,0 +1,636 @@
+/*
+ * Copyright (c) 2020-2026 Tracey Emery <tracey@openbsd.org>
+ * Copyright (c) 2010-2015 Reyk Floeter <reyk@openbsd.org>
+ * Copyright (c) 2003, 2004 Henning Brauer <henning@openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <sys/param.h>
+#include <sys/queue.h>
+#include <sys/stat.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+
+#include <errno.h>
+#include <event.h>
+#include <fcntl.h>
+#include <imsg.h>
+#include <pwd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <signal.h>
+
+#include "newd.h"
+
+#define CONTROL_BACKLOG 5
+
+struct control_sock {
+	const char	*cs_name;
+	struct event	 cs_ev;
+	struct event	 cs_evt;
+	int		 cs_fd;
+	int		 cs_restricted;
+};
+
+struct ctl_conn {
+	TAILQ_ENTRY(ctl_conn)	 entry;
+	uint8_t			 flags;
+#define CTL_CONN_NOTIFY		 0x01
+	struct imsgev		 iev;
+	struct sockpeercred	 peercred;
+};
+TAILQ_HEAD(ctl_connlist, ctl_conn);
+
+static struct ctl_connlist	 ctl_conns;
+static struct control_sock	 control_cs;
+static struct imsgev		*control_iev_parent;
+static struct imsgev		*control_iev_engine;
+static struct event		 ev_sigint;
+static struct event		 ev_sigterm;
+static struct event		 ev_sighup;
+static struct event		 ev_sigpipe;
+static struct event		 ev_sigusr1;
+
+struct ctl_conn *control_connbyfd(int);
+int	 control_init(struct control_sock *);
+int	 control_listen(struct control_sock *);
+void	 control_cleanup(struct control_sock *);
+void	 control_accept(int, short, void *);
+void	 control_close(int, struct control_sock *);
+void	 control_dispatch_imsg(int, short, void *);
+void	 control_dispatch_parent(int, short, void *);
+void	 control_dispatch_engine(int, short, void *);
+void	 control_imsg_forward(struct imsg *);
+void	 control_sighdlr(int, short, void *);
+__dead void
+	 control_shutdown(void);
+
+__dead void
+control(int fd_parent, int fd_engine)
+{
+	struct passwd	*pw;
+
+	log_procinit("control");
+
+	/* the socket is bound as root, before the chroot */
+	control_cs.cs_name = NEWD_SOCKET;
+	if (control_init(&control_cs) == -1)
+		fatalx("%s: control_init", __func__);
+
+	if ((pw = getpwnam(NEWD_USER)) == NULL)
+		fatal("unknown user %s", NEWD_USER);
+
+	if (chroot(pw->pw_dir) == -1)
+		fatal("%s: chroot", __func__);
+	if (chdir("/") == -1)
+		fatal("%s: chdir(\"/\")", __func__);
+
+	setproctitle("%s", "control");
+
+	if (setgroups(1, &pw->pw_gid) ||
+	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
+	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
+		fatal("%s: cannot drop privileges", __func__);
+
+	event_init();
+
+	signal_set(&ev_sigint, SIGINT, control_sighdlr, NULL);
+	signal_set(&ev_sigterm, SIGTERM, control_sighdlr, NULL);
+	signal_set(&ev_sighup, SIGHUP, control_sighdlr, NULL);
+	signal_set(&ev_sigpipe, SIGPIPE, control_sighdlr, NULL);
+	signal_set(&ev_sigusr1, SIGUSR1, control_sighdlr, NULL);
+	signal_add(&ev_sigint, NULL);
+	signal_add(&ev_sigterm, NULL);
+	signal_add(&ev_sighup, NULL);
+	signal_add(&ev_sigpipe, NULL);
+	signal_add(&ev_sigusr1, NULL);
+
+	if ((control_iev_parent = calloc(1, sizeof(*control_iev_parent)))
+	    == NULL)
+		fatal("%s: calloc", __func__);
+	imsg_event_init(control_iev_parent, fd_parent,
+	    control_dispatch_parent);
+
+	if ((control_iev_engine = calloc(1, sizeof(*control_iev_engine)))
+	    == NULL)
+		fatal("%s: calloc", __func__);
+	imsg_event_init(control_iev_engine, fd_engine,
+	    control_dispatch_engine);
+
+	TAILQ_INIT(&ctl_conns);
+	if (control_listen(&control_cs) == -1)
+		fatalx("%s: control_listen", __func__);
+
+	if (pledge("stdio cpath unix", NULL) == -1)
+		fatal("pledge");
+
+	event_dispatch();
+
+	control_shutdown();
+}
+
+void
+control_sighdlr(int sig, short event, void *arg)
+{
+	switch (sig) {
+	case SIGINT:
+	case SIGTERM:
+		control_shutdown();
+		break;
+	case SIGHUP:
+	case SIGPIPE:
+	case SIGUSR1:
+		/* ignore */
+		break;
+	default:
+		fatalx("%s: unexpected signal", __func__);
+	}
+}
+
+__dead void
+control_shutdown(void)
+{
+	struct ctl_conn	*c;
+
+	control_cleanup(&control_cs);
+
+	while ((c = TAILQ_FIRST(&ctl_conns)) != NULL) {
+		TAILQ_REMOVE(&ctl_conns, c, entry);
+		event_del(&c->iev.ev);
+		imsgbuf_clear(&c->iev.ibuf);
+		close(c->iev.ibuf.fd);
+		free(c);
+	}
+
+	event_del(&control_iev_parent->ev);
+	imsgbuf_clear(&control_iev_parent->ibuf);
+	close(control_iev_parent->ibuf.fd);
+	free(control_iev_parent);
+	event_del(&control_iev_engine->ev);
+	imsgbuf_clear(&control_iev_engine->ibuf);
+	close(control_iev_engine->ibuf.fd);
+	free(control_iev_engine);
+
+	log_info("control exiting, pid %d", getpid());
+	exit(0);
+}
+
+void
+control_dispatch_engine(int fd, short event, void *arg)
+{
+	struct imsgev	*iev = arg;
+	struct imsgbuf	*ibuf = &iev->ibuf;
+	struct imsg	 imsg;
+	struct ctl_conn	*c;
+	int		 n;
+
+	if (event & EV_READ) {
+		if ((n = imsgbuf_read(ibuf)) == -1)
+			fatal("%s: imsgbuf_read", __func__);
+		if (n == 0) {
+			log_warnx("%s: lost engine process", __func__);
+			control_shutdown();
+		}
+	}
+	if (event & EV_WRITE) {
+		if (imsgbuf_write(ibuf) == -1) {
+			if (errno == EPIPE) {
+				log_warnx("%s: lost engine process", __func__);
+				control_shutdown();
+			}
+			fatal("%s: imsgbuf_write", __func__);
+		}
+	}
+
+	for (;;) {
+		if ((n = imsgbuf_get(ibuf, &imsg)) == -1)
+			fatal("%s: imsgbuf_get", __func__);
+		if (n == 0)
+			break;
+
+		switch (imsg.hdr.type) {
+		case IMSG_GET_INFO_ENGINE_DATA:
+		case IMSG_GET_INFO_ENGINE_END_DATA:
+			c = control_connbyfd(imsg.hdr.peerid);
+			if (c == NULL) {
+				log_warnx("%s: fd %d: not found",
+				    __func__, imsg.hdr.peerid);
+				break;
+			}
+
+			imsg_compose_event(&c->iev, imsg.hdr.type,
+			    0, 0, -1, imsg.data, IMSG_DATA_SIZE(&imsg));
+			break;
+		default:
+			log_warnx("%s: unexpected imsg %d from engine",
+			    __func__, imsg.hdr.type);
+			break;
+		}
+		imsg_free(&imsg);
+	}
+	imsg_event_add(iev);
+}
+
+void
+control_dispatch_parent(int fd, short event, void *arg)
+{
+	struct imsgev	*iev = arg;
+	struct imsgbuf	*ibuf = &iev->ibuf;
+	struct imsg	 imsg;
+	struct ctl_conn	*c;
+	int		 n;
+
+	if (event & EV_READ) {
+		if ((n = imsgbuf_read(ibuf)) == -1)
+			fatal("%s: imsgbuf_read", __func__);
+		if (n == 0) {
+			log_warnx("%s: lost parent process", __func__);
+			control_shutdown();
+		}
+	}
+	if (event & EV_WRITE) {
+		if (imsgbuf_write(ibuf) == -1) {
+			if (errno == EPIPE) {
+				log_warnx("%s: lost parent process", __func__);
+				control_shutdown();
+			}
+			fatal("%s: imsgbuf_write", __func__);
+		}
+	}
+
+	for (;;) {
+		if ((n = imsgbuf_get(ibuf, &imsg)) == -1)
+			fatal("%s: imsgbuf_get", __func__);
+		if (n == 0)
+			break;
+
+		switch (imsg.hdr.type) {
+		case IMSG_GET_INFO_PARENT_DATA:
+		case IMSG_GET_INFO_PARENT_END_DATA:
+			c = control_connbyfd(imsg.hdr.peerid);
+			if (c == NULL) {
+				log_warnx("%s: fd %d: not found",
+				    __func__, imsg.hdr.peerid);
+				break;
+			}
+
+			imsg_compose_event(&c->iev, imsg.hdr.type,
+			    0, 0, -1, imsg.data, IMSG_DATA_SIZE(&imsg));
+			break;
+		case IMSG_CFG_DONE:
+		case IMSG_CTL_START:
+			/* don't do anything */
+			break;
+		default:
+			log_warnx("%s: unexpected imsg %d from parent",
+			    __func__, imsg.hdr.type);
+			break;
+		}
+		imsg_free(&imsg);
+	}
+	imsg_event_add(iev);
+}
+
+int
+control_init(struct control_sock *cs)
+{
+	struct sockaddr_un	 sun;
+	int			 fd;
+	mode_t			 old_umask, mode;
+
+	if (cs->cs_name == NULL)
+		return (0);
+
+	fd = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0);
+	if (fd == -1) {
+		log_warn("%s: socket", __func__);
+		return (-1);
+	}
+
+	memset(&sun, 0, sizeof(sun));
+	sun.sun_family = AF_UNIX;
+	if (strlcpy(sun.sun_path, cs->cs_name, sizeof(sun.sun_path)) >=
+	    sizeof(sun.sun_path)) {
+		log_warnx("%s: socket path too long: %s", __func__,
+		    cs->cs_name);
+		close(fd);
+		return (-1);
+	}
+
+	if (unlink(cs->cs_name) == -1)
+		if (errno != ENOENT) {
+			log_warn("%s: unlink %s", __func__, cs->cs_name);
+			close(fd);
+			return (-1);
+		}
+
+	if (cs->cs_restricted) {
+		old_umask = umask(S_IXUSR|S_IXGRP|S_IXOTH);
+		mode = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH;
+	} else {
+		old_umask = umask(S_IXUSR|S_IXGRP|S_IWOTH|S_IROTH|S_IXOTH);
+		mode = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP;
+	}
+
+	if (bind(fd, (struct sockaddr *)&sun, sizeof(sun)) == -1) {
+		log_warn("%s: bind: %s", __func__, cs->cs_name);
+		close(fd);
+		(void)umask(old_umask);
+		return (-1);
+	}
+
+	(void)umask(old_umask);
+
+	if (chmod(cs->cs_name, mode) == -1) {
+		log_warn("%s: chmod", __func__);
+		close(fd);
+		(void)unlink(cs->cs_name);
+		return (-1);
+	}
+
+	cs->cs_fd = fd;
+
+	return (0);
+}
+
+int
+control_listen(struct control_sock *cs)
+{
+	if (cs->cs_name == NULL)
+		return (0);
+
+	if (listen(cs->cs_fd, CONTROL_BACKLOG) == -1) {
+		log_warn("%s: listen", __func__);
+		return (-1);
+	}
+
+	event_set(&cs->cs_ev, cs->cs_fd, EV_READ,
+	    control_accept, cs);
+	event_add(&cs->cs_ev, NULL);
+	evtimer_set(&cs->cs_evt, control_accept, cs);
+
+	return (0);
+}
+
+void
+control_cleanup(struct control_sock *cs)
+{
+	if (cs->cs_name == NULL)
+		return;
+
+	event_del(&cs->cs_ev);
+	event_del(&cs->cs_evt);
+	close(cs->cs_fd);
+}
+
+/* ARGSUSED */
+void
+control_accept(int listenfd, short event, void *arg)
+{
+	struct control_sock	*cs = arg;
+	int			 connfd;
+	socklen_t		 len;
+	struct sockaddr_un	 sun;
+	struct ctl_conn		*c;
+
+	event_add(&cs->cs_ev, NULL);
+	if (event & EV_TIMEOUT)
+		return;
+
+	len = sizeof(sun);
+	connfd = accept4(listenfd, (struct sockaddr *)&sun, &len,
+	    SOCK_NONBLOCK);
+	if (connfd == -1) {
+		/*
+		 * Pause accept if we are out of file descriptors, or
+		 * libevent will haunt us here too.
+		 */
+		if (errno == ENFILE || errno == EMFILE) {
+			struct timeval evtpause = { 1, 0 };
+
+			event_del(&cs->cs_ev);
+			evtimer_add(&cs->cs_evt, &evtpause);
+		} else if (errno != EWOULDBLOCK && errno != EINTR &&
+		    errno != ECONNABORTED)
+			log_warn("%s: accept", __func__);
+		return;
+	}
+
+	c = calloc(1, sizeof(struct ctl_conn));
+	if (c == NULL) {
+		log_warn("%s", __func__);
+		close(connfd);
+		return;
+	}
+
+	len = sizeof(c->peercred);
+	if (getsockopt(connfd, SOL_SOCKET, SO_PEERCRED,
+	    &c->peercred, &len) != 0) {
+		log_warn("%s: failed to get peer credentials", __func__);
+		close(connfd);
+		free(c);
+		return;
+	}
+
+	if (imsgbuf_init(&c->iev.ibuf, connfd) == -1) {
+		log_warn("%s: failed to init imsgbuf", __func__);
+		close(connfd);
+		free(c);
+		return;
+	}
+
+	c->iev.handler = control_dispatch_imsg;
+	c->iev.events = EV_READ;
+
+	event_set(&c->iev.ev, c->iev.ibuf.fd, c->iev.events,
+	    c->iev.handler, &c->iev);
+	event_add(&c->iev.ev, NULL);
+
+	TAILQ_INSERT_TAIL(&ctl_conns, c, entry);
+}
+
+struct ctl_conn *
+control_connbyfd(int fd)
+{
+	struct ctl_conn	*c;
+
+	TAILQ_FOREACH(c, &ctl_conns, entry) {
+		if (c->iev.ibuf.fd == fd)
+			break;
+	}
+
+	return (c);
+}
+
+void
+control_close(int fd, struct control_sock *cs)
+{
+	struct ctl_conn	*c;
+
+	c = control_connbyfd(fd);
+	if (c == NULL) {
+		log_warn("%s: fd %d: not found", __func__, fd);
+		return;
+	}
+
+	imsgbuf_clear(&c->iev.ibuf);
+	TAILQ_REMOVE(&ctl_conns, c, entry);
+
+	event_del(&c->iev.ev);
+	close(c->iev.ibuf.fd);
+
+	/* Some file descriptors are available again. */
+	if (evtimer_pending(&cs->cs_evt, NULL)) {
+		evtimer_del(&cs->cs_evt);
+		event_add(&cs->cs_ev, NULL);
+	}
+
+	free(c);
+}
+
+/* ARGSUSED */
+void
+control_dispatch_imsg(int fd, short event, void *arg)
+{
+	struct newd_control_info	 nci;
+	struct control_sock		*cs = &control_cs;
+	struct ctl_conn			*c;
+	struct imsg			 imsg;
+	int				 n, v, ret = 0;
+	uid_t				 euid;
+	gid_t				 egid;
+
+	if (getpeereid(fd, &euid, &egid) == -1)
+		return;
+
+	c = control_connbyfd(fd);
+	if (c == NULL) {
+		log_warn("%s: fd %d: not found", __func__, fd);
+		return;
+	}
+
+	if (event & EV_READ) {
+		n = imsgbuf_read(&c->iev.ibuf);
+		if (n == -1 || n == 0) {
+			control_close(fd, cs);
+			return;
+		}
+	}
+
+	if (event & EV_WRITE) {
+		if (imsgbuf_write(&c->iev.ibuf) == -1) {
+			control_close(fd, cs);
+			return;
+		}
+	}
+
+	for (;;) {
+		n = imsgbuf_get(&c->iev.ibuf, &imsg);
+		if (n == -1) {
+			control_close(fd, cs);
+			return;
+		}
+
+		if (n == 0)
+			break;
+
+		/* read-only requests are open to everyone, the rest to root */
+		switch (imsg.hdr.type) {
+		case IMSG_GET_INFO_PARENT_REQUEST:
+		case IMSG_GET_INFO_CONTROL_REQUEST:
+		case IMSG_GET_INFO_ENGINE_REQUEST:
+			break;
+		default:
+			if (c->peercred.uid != 0) {
+				log_warnx("denied request %d from uid %d",
+				    imsg.hdr.type, c->peercred.uid);
+				ret = EPERM;
+				goto fail;
+			}
+			break;
+		}
+
+		control_imsg_forward(&imsg);
+
+		switch (imsg.hdr.type) {
+		case IMSG_CTL_NOTIFY:
+			if (c->flags & CTL_CONN_NOTIFY) {
+				log_debug("%s: "
+				    "client requested notify more than once",
+				    __func__);
+				ret = EINVAL;
+				goto fail;
+			}
+			c->flags |= CTL_CONN_NOTIFY;
+			break;
+		case IMSG_CTL_VERBOSE:
+			IMSG_SIZE_CHECK(&imsg, &v);
+			memcpy(&v, imsg.data, sizeof(v));
+			log_setverbose(v);
+			imsg_forward_event(control_iev_parent, &imsg);
+			break;
+		case IMSG_GET_INFO_CONTROL_REQUEST:
+			nci.verbose = log_getverbose();
+			imsg_compose_event(&c->iev,
+			    IMSG_GET_INFO_CONTROL_DATA, 0, 0, -1,
+			    &nci, sizeof(struct newd_control_info));
+			imsg_compose_event(&c->iev,
+			    IMSG_GET_INFO_CONTROL_END_DATA, 0, 0, -1,
+			    &nci, sizeof(struct newd_control_info));
+			break;
+		case IMSG_GET_INFO_PARENT_REQUEST:
+		case IMSG_GET_INFO_ENGINE_REQUEST:
+			/* the conn fd is the peerid replies are routed by */
+			imsg.hdr.peerid = fd;
+
+			if (imsg_forward_event(control_iev_parent,
+			    &imsg) == -1) {
+				imsg_free(&imsg);
+				control_close(fd, cs);
+				return;
+			}
+			break;
+		default:
+			log_debug("%s: error handling imsg %d",
+			    __func__, imsg.hdr.type);
+			imsg_free(&imsg);
+			control_close(fd, cs);
+			return;
+		}
+		imsg_free(&imsg);
+	}
+
+	imsg_event_add(&c->iev);
+	return;
+
+fail:
+	imsg_free(&imsg);
+	imsg_compose_event(&c->iev, IMSG_CTL_FAIL,
+	    0, 0, -1, &ret, sizeof(ret));
+	imsgbuf_flush(&c->iev.ibuf);
+	control_close(fd, cs);
+}
+
+void
+control_imsg_forward(struct imsg *imsg)
+{
+	struct ctl_conn *c;
+
+	TAILQ_FOREACH(c, &ctl_conns, entry)
+		if (c->flags & CTL_CONN_NOTIFY)
+			imsg_compose_event(&c->iev, imsg->hdr.type,
+			    imsg->hdr.peerid, imsg->hdr.pid, -1, imsg->data,
+			    imsg->hdr.len - IMSG_HEADER_SIZE);
+}
blob - /dev/null
blob + cd14bfb414eea08e5a37072320d561e6a0718e055231a09651708a5566732285 (mode 644)
--- /dev/null	
+++ newd/engine.c	
@@ -0,0 +1,271 @@
+/*
+ * Copyright (c) 2016, 2019-2026 Tracey Emery <tracey@openbsd.org>
+ * Copyright (c) 2015 Mike Larkin <mlarkin@openbsd.org>
+ * Copyright (c) 2007 - 2015 Reyk Floeter <reyk@openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+/*
+ * The engine is the unprivileged worker process.  It holds the state
+ * the daemon operates on, receives its configuration from the parent
+ * and answers newctl requests that the parent forwards to it.
+ */
+
+#include <sys/queue.h>
+#include <sys/time.h>
+#include <sys/param.h>
+#include <sys/socket.h>
+
+#include <errno.h>
+#include <event.h>
+#include <imsg.h>
+#include <pwd.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "newd.h"
+
+void	 engine_dispatch_parent(int, short, void *);
+void	 engine_dispatch_control(int, short, void *);
+void	 engine_sighdlr(int, short, void *);
+__dead void
+	 engine_shutdown(void);
+void	 engine_launch(void);
+void	 engine_show_info(struct imsg *);
+
+struct imsgev		*engine_iev_parent;
+static struct imsgev	*engine_iev_control;
+
+static struct event	 ev_sigint;
+static struct event	 ev_sigterm;
+static struct event	 ev_sighup;
+static struct event	 ev_sigpipe;
+static struct event	 ev_sigusr1;
+
+__dead void
+engine(int fd_parent, int fd_control)
+{
+	struct passwd	*pw;
+
+	log_procinit("engine");
+
+	if ((pw = getpwnam(NEWD_USER)) == NULL)
+		fatal("unknown user %s", NEWD_USER);
+
+	if (chroot(pw->pw_dir) == -1)
+		fatal("%s: chroot", __func__);
+	if (chdir("/") == -1)
+		fatal("%s: chdir(\"/\")", __func__);
+
+	setproctitle("%s", "engine");
+
+	if (setgroups(1, &pw->pw_gid) ||
+	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
+	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
+		fatal("%s: cannot drop privileges", __func__);
+
+	/* start from an empty state, the configuration arrives from the parent */
+	if (config_init(newd_env) == -1)
+		fatal("failed to initialize configuration");
+
+	event_init();
+
+	signal_set(&ev_sigint, SIGINT, engine_sighdlr, NULL);
+	signal_set(&ev_sigterm, SIGTERM, engine_sighdlr, NULL);
+	signal_set(&ev_sighup, SIGHUP, engine_sighdlr, NULL);
+	signal_set(&ev_sigpipe, SIGPIPE, engine_sighdlr, NULL);
+	signal_set(&ev_sigusr1, SIGUSR1, engine_sighdlr, NULL);
+	signal_add(&ev_sigint, NULL);
+	signal_add(&ev_sigterm, NULL);
+	signal_add(&ev_sighup, NULL);
+	signal_add(&ev_sigpipe, NULL);
+	signal_add(&ev_sigusr1, NULL);
+
+	if ((engine_iev_parent = calloc(1, sizeof(*engine_iev_parent)))
+	    == NULL)
+		fatal("%s: calloc", __func__);
+	imsg_event_init(engine_iev_parent, fd_parent, engine_dispatch_parent);
+
+	if ((engine_iev_control = calloc(1, sizeof(*engine_iev_control)))
+	    == NULL)
+		fatal("%s: calloc", __func__);
+	imsg_event_init(engine_iev_control, fd_control,
+	    engine_dispatch_control);
+
+	/* add recvfd here once the parent passes descriptors */
+	if (pledge("stdio", NULL) == -1)
+		fatal("pledge");
+
+	event_dispatch();
+
+	engine_shutdown();
+}
+
+/* everything is configured, start doing work */
+void
+engine_launch(void)
+{
+	log_debug("%s: engine running", __func__);
+}
+
+void
+engine_dispatch_control(int fd, short event, void *arg)
+{
+	struct imsgev	*iev = arg;
+	struct imsgbuf	*ibuf = &iev->ibuf;
+	struct imsg	 imsg;
+	int		 n;
+
+	if (event & EV_READ) {
+		if ((n = imsgbuf_read(ibuf)) == -1)
+			fatal("%s: imsgbuf_read", __func__);
+		if (n == 0) {
+			log_warnx("%s: lost control process", __func__);
+			engine_shutdown();
+		}
+	}
+	if (event & EV_WRITE) {
+		if (imsgbuf_write(ibuf) == -1) {
+			if (errno == EPIPE) {
+				log_warnx("%s: lost control process", __func__);
+				engine_shutdown();
+			}
+			fatal("%s: imsgbuf_write", __func__);
+		}
+	}
+
+	/* control only ever listens to us, requests arrive via the parent */
+	for (;;) {
+		if ((n = imsgbuf_get(ibuf, &imsg)) == -1)
+			fatal("%s: imsgbuf_get", __func__);
+		if (n == 0)
+			break;
+
+		log_warnx("%s: unexpected imsg %d from control", __func__,
+		    imsg.hdr.type);
+		imsg_free(&imsg);
+	}
+	imsg_event_add(iev);
+}
+
+void
+engine_dispatch_parent(int fd, short event, void *arg)
+{
+	struct imsgev	*iev = arg;
+	struct imsgbuf	*ibuf = &iev->ibuf;
+	struct imsg	 imsg;
+	int		 n, verbose;
+
+	if (event & EV_READ) {
+		if ((n = imsgbuf_read(ibuf)) == -1)
+			fatal("%s: imsgbuf_read", __func__);
+		if (n == 0) {
+			log_warnx("%s: lost parent process", __func__);
+			engine_shutdown();
+		}
+	}
+	if (event & EV_WRITE) {
+		if (imsgbuf_write(ibuf) == -1) {
+			if (errno == EPIPE) {
+				log_warnx("%s: lost parent process", __func__);
+				engine_shutdown();
+			}
+			fatal("%s: imsgbuf_write", __func__);
+		}
+	}
+
+	for (;;) {
+		if ((n = imsgbuf_get(ibuf, &imsg)) == -1)
+			fatal("%s: imsgbuf_get", __func__);
+		if (n == 0)
+			break;
+
+		switch (imsg.hdr.type) {
+		case IMSG_CFG_DONE:
+			config_getcfg(newd_env, &imsg);
+			break;
+		case IMSG_CTL_VERBOSE:
+			IMSG_SIZE_CHECK(&imsg, &verbose);
+			memcpy(&verbose, imsg.data, sizeof(verbose));
+			log_setverbose(verbose);
+			break;
+		case IMSG_CTL_START:
+			engine_launch();
+			break;
+		case IMSG_GET_INFO_ENGINE_REQUEST:
+			engine_show_info(&imsg);
+			break;
+		default:
+			log_warnx("%s: unexpected imsg %d from parent",
+			    __func__, imsg.hdr.type);
+			break;
+		}
+		imsg_free(&imsg);
+	}
+	imsg_event_add(iev);
+}
+
+void
+engine_sighdlr(int sig, short event, void *arg)
+{
+	switch (sig) {
+	case SIGINT:
+	case SIGTERM:
+		engine_shutdown();
+		break;
+	case SIGHUP:
+	case SIGPIPE:
+	case SIGUSR1:
+		/* ignore */
+		break;
+	default:
+		fatalx("%s: unexpected signal", __func__);
+	}
+}
+
+__dead void
+engine_shutdown(void)
+{
+	event_del(&engine_iev_parent->ev);
+	imsgbuf_clear(&engine_iev_parent->ibuf);
+	close(engine_iev_parent->ibuf.fd);
+	free(engine_iev_parent);
+	event_del(&engine_iev_control->ev);
+	imsgbuf_clear(&engine_iev_control->ibuf);
+	close(engine_iev_control->ibuf.fd);
+	free(engine_iev_control);
+
+	log_info("engine exiting, pid %d", getpid());
+	exit(0);
+}
+
+/* replies go straight to control, peerid is the newctl connection */
+void
+engine_show_info(struct imsg *imsg)
+{
+	struct newd_engine_info	 nei;
+
+	memset(&nei, 0, sizeof(nei));
+	nei.verbose = log_getverbose();
+
+	if (imsg_compose_event(engine_iev_control, IMSG_GET_INFO_ENGINE_DATA,
+	    imsg->hdr.peerid, 0, -1, &nei, sizeof(nei)) == -1)
+		return;
+
+	imsg_compose_event(engine_iev_control, IMSG_GET_INFO_ENGINE_END_DATA,
+	    imsg->hdr.peerid, 0, -1, &nei, sizeof(nei));
+}
blob - /dev/null
blob + 484a6c0c19ce79ad305bc75806a595c9f5b175aee767944974bd40005b4c4600 (mode 644)
--- /dev/null	
+++ newd/examples/README.md	
@@ -0,0 +1,2 @@
+#newd
+Examples of usage.
blob - /dev/null
blob + 93d0db715a12e1a14a1eaa03c59dd4e7cf56007fe74ed30846cfb170b4ee4f43 (mode 644)
--- /dev/null	
+++ newd/examples/etc/README.md	
@@ -0,0 +1,3 @@
+#newd
+
+Configuration and rc.d examples.
blob - /dev/null
blob + 3fb4ce6e338678d8b407a819471d518efb81b5bd3ea9ca81a949cd6bffaa5aa9 (mode 644)
--- /dev/null	
+++ newd/examples/etc/newd.conf	
@@ -0,0 +1,9 @@
+#
+# newd.conf
+#
+# Macros and include are supported.  Add daemon specific options to the
+# conf_main rule in parse.y and document them in newd.conf.5.
+#
+
+# example_macro = "value"
+# include "/etc/newd.local.conf"
blob - /dev/null
blob + 1ba0c052aeb373eb379198facd896a77cc876a603dbde50a8def659c7d3711b2 (mode 644)
--- /dev/null	
+++ newd/examples/etc/rc.d/newd	
@@ -0,0 +1,9 @@
+#!/bin/sh
+
+daemon="/usr/local/sbin/newd"
+
+. /etc/rc.d/rc.subr
+
+rc_reload=NO
+
+rc_cmd $1
blob - /dev/null
blob + a0ac49b18bf0a574afb7781a1aa80295a31878f46b3788fa26d6c5d989a50d90 (mode 644)
--- /dev/null	
+++ newd/log.c	
@@ -0,0 +1,214 @@
+/*
+ * Copyright (c) 2003, 2004 Henning Brauer <henning@openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <syslog.h>
+#include <errno.h>
+#include <time.h>
+
+static int	 debug;
+static int	 verbose;
+const char	*log_procname;
+
+void	log_init(int, int);
+void	log_procinit(const char *);
+void	log_setverbose(int);
+int	log_getverbose(void);
+void	log_warn(const char *, ...)
+	    __attribute__((__format__ (printf, 1, 2)));
+void	log_warnx(const char *, ...)
+	    __attribute__((__format__ (printf, 1, 2)));
+void	log_info(const char *, ...)
+	    __attribute__((__format__ (printf, 1, 2)));
+void	log_debug(const char *, ...)
+	    __attribute__((__format__ (printf, 1, 2)));
+void	logit(int, const char *, ...)
+	    __attribute__((__format__ (printf, 2, 3)));
+void	vlog(int, const char *, va_list)
+	    __attribute__((__format__ (printf, 2, 0)));
+__dead void fatal(const char *, ...)
+	    __attribute__((__format__ (printf, 1, 2)));
+__dead void fatalx(const char *, ...)
+	    __attribute__((__format__ (printf, 1, 2)));
+
+void
+log_init(int n_debug, int facility)
+{
+	debug = n_debug;
+	verbose = n_debug;
+	log_procinit(getprogname());
+
+	if (!debug)
+		openlog(getprogname(), LOG_PID | LOG_NDELAY, facility);
+
+	tzset();
+}
+
+void
+log_procinit(const char *procname)
+{
+	if (procname != NULL)
+		log_procname = procname;
+}
+
+void
+log_setverbose(int v)
+{
+	verbose = v;
+}
+
+int
+log_getverbose(void)
+{
+	return (verbose);
+}
+
+void
+logit(int pri, const char *fmt, ...)
+{
+	va_list	ap;
+
+	va_start(ap, fmt);
+	vlog(pri, fmt, ap);
+	va_end(ap);
+}
+
+void
+vlog(int pri, const char *fmt, va_list ap)
+{
+	char	*nfmt;
+	int	 saved_errno = errno;
+
+	if (debug) {
+		/* best effort in out of mem situations */
+		if (asprintf(&nfmt, "%s\n", fmt) == -1) {
+			vfprintf(stderr, fmt, ap);
+			fprintf(stderr, "\n");
+		} else {
+			vfprintf(stderr, nfmt, ap);
+			free(nfmt);
+		}
+		fflush(stderr);
+	} else
+		vsyslog(pri, fmt, ap);
+
+	errno = saved_errno;
+}
+
+void
+log_warn(const char *emsg, ...)
+{
+	char		*nfmt;
+	va_list		 ap;
+	int		 saved_errno = errno;
+
+	/* best effort to even work in out of memory situations */
+	if (emsg == NULL)
+		logit(LOG_CRIT, "%s", strerror(saved_errno));
+	else {
+		va_start(ap, emsg);
+
+		if (asprintf(&nfmt, "%s: %s", emsg,
+		    strerror(saved_errno)) == -1) {
+			/* we tried it... */
+			vlog(LOG_CRIT, emsg, ap);
+			logit(LOG_CRIT, "%s", strerror(saved_errno));
+		} else {
+			vlog(LOG_CRIT, nfmt, ap);
+			free(nfmt);
+		}
+		va_end(ap);
+	}
+
+	errno = saved_errno;
+}
+
+void
+log_warnx(const char *emsg, ...)
+{
+	va_list	 ap;
+
+	va_start(ap, emsg);
+	vlog(LOG_CRIT, emsg, ap);
+	va_end(ap);
+}
+
+void
+log_info(const char *emsg, ...)
+{
+	va_list	 ap;
+
+	va_start(ap, emsg);
+	vlog(LOG_INFO, emsg, ap);
+	va_end(ap);
+}
+
+void
+log_debug(const char *emsg, ...)
+{
+	va_list	 ap;
+
+	if (verbose > 1) {
+		va_start(ap, emsg);
+		vlog(LOG_DEBUG, emsg, ap);
+		va_end(ap);
+	}
+}
+
+static void
+vfatalc(int code, const char *emsg, va_list ap)
+{
+	static char	s[BUFSIZ];
+	const char	*sep;
+
+	if (emsg != NULL) {
+		(void)vsnprintf(s, sizeof(s), emsg, ap);
+		sep = ": ";
+	} else {
+		s[0] = '\0';
+		sep = "";
+	}
+	if (code)
+		logit(LOG_CRIT, "%s: %s%s%s",
+		    log_procname, s, sep, strerror(code));
+	else
+		logit(LOG_CRIT, "%s%s%s", log_procname, sep, s);
+}
+
+void
+fatal(const char *emsg, ...)
+{
+	va_list	ap;
+
+	va_start(ap, emsg);
+	vfatalc(errno, emsg, ap);
+	va_end(ap);
+	exit(1);
+}
+
+void
+fatalx(const char *emsg, ...)
+{
+	va_list	ap;
+
+	va_start(ap, emsg);
+	vfatalc(0, emsg, ap);
+	va_end(ap);
+	exit(1);
+}
blob - /dev/null
blob + 34bdd01015240adb81ac7fef772174724f38b507b54883084e9a96a257f05bab (mode 644)
--- /dev/null	
+++ newd/newd.8	
@@ -0,0 +1,103 @@
+.\"
+.\" Copyright (c) 2016-2026 Tracey Emery <tracey@openbsd.org>
+.\"
+.\" Permission to use, copy, modify, and distribute this software for any
+.\" purpose with or without fee is hereby granted, provided that the above
+.\" copyright notice and this permission notice appear in all copies.
+.\"
+.\" THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+.\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+.\" MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+.\" ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+.\" WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+.\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+.\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+.\"
+.Dd $Mdocdate: November 19 2026 $
+.Dt NEWD 8
+.Os
+.Sh NAME
+.Nm newd
+.Nd privilege separated OpenBSD base daemon
+.Sh SYNOPSIS
+.Nm newd
+.Bk -words
+.Op Fl dnv
+.Op Fl D Ar macro Ns = Ns Ar value
+.Op Fl f Ar file
+.Ek
+.Sh DESCRIPTION
+.Nm
+is a skeleton daemon to build new daemons from.
+It runs as three processes: a privileged parent, which reads the
+configuration and forks the others, an unprivileged control process,
+which owns the
+.Xr newctl 8
+socket, and an unprivileged engine process, where the work of the
+daemon is meant to go.
+The processes talk over
+.Xr imsg_init 3
+pipes.
+.Pp
+The options are as follows:
+.Bl -tag -width "-D macro=value"
+.It Fl D Ar macro Ns = Ns Ar value
+Define
+.Ar macro
+to be set to
+.Ar value
+on the command line.
+Overrides the definition of
+.Ar macro
+in the configuration file.
+.It Fl d
+Do not daemonize.
+If this option is specified,
+.Nm
+will run in the foreground and log to
+.Em stderr .
+.It Fl f Ar file
+Specify an alternative configuration file.
+.It Fl n
+Configtest mode.
+Only check the configuration file for validity.
+.It Fl v
+Produce more verbose output.
+.El
+.Pp
+.Nm
+is usually started at boot time, and can be enabled by adding
+.Nm
+to the
+.Va pkg_scripts
+line in
+.Pa /etc/rc.conf.local .
+See
+.Xr rc 8
+and
+.Xr rc.conf 8
+for more information on the boot process and enabling daemons.
+.Pp
+When
+.Nm
+starts up, it reads settings from its configuration file, typically
+.Xr newd.conf 5 .
+.Sh FILES
+.Bl -tag -width "/var/run/newd.sockXXX" -compact
+.It Pa /etc/newd.conf
+Default configuration file.
+.It Pa /var/run/newd.sock
+Socket file for communication with
+.Xr newctl 8 .
+.El
+.Sh SEE ALSO
+.Xr newd.conf 5 ,
+.Xr rc 8 ,
+.Xr rc.conf 8 ,
+.Xr newctl 8
+.Sh AUTHORS
+.An -nosplit
+The
+.Nm
+program was written by
+.An Tracey Emery Aq Mt tracey@openbsd.org .
blob - /dev/null
blob + 3252f157c0f928ee810d955953eecad536d03fe2c5f7a4a0f3eef675e64f4834 (mode 644)
--- /dev/null	
+++ newd/newd.c	
@@ -0,0 +1,540 @@
+/*
+ * Copyright (c) 2016, 2019-2026 Tracey Emery <tracey@openbsd.org>
+ * Copyright (c) 2015 Reyk Floeter <reyk@openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <sys/param.h>
+#include <sys/queue.h>
+#include <sys/socket.h>
+#include <sys/uio.h>
+#include <sys/wait.h>
+#include <sys/cdefs.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <err.h>
+#include <errno.h>
+#include <event.h>
+#include <imsg.h>
+#include <pwd.h>
+#include <signal.h>
+#include <syslog.h>
+#include <unistd.h>
+
+#include "newd.h"
+
+__dead void usage(void);
+
+int	 main(int, char **);
+
+int	 newd_configure(struct newd *);
+void	 newd_configure_done(struct newd *);
+void	 newd_dispatch_control(int, short, void *);
+void	 newd_dispatch_engine(int, short, void *);
+void	 newd_sighdlr(int, short, void *);
+__dead void
+	 newd_shutdown(struct newd *);
+void	 newd_parent_shutdown(struct newd *);
+void	 newd_show_info(struct imsg *);
+
+struct newd	*newd_env;
+
+struct imsgev	*parent_iev_control;
+struct imsgev	*parent_iev_engine;
+
+static struct event	 ev_sigint;
+static struct event	 ev_sigterm;
+static struct event	 ev_sighup;
+static struct event	 ev_sigpipe;
+static struct event	 ev_sigusr1;
+
+void
+imsg_event_init(struct imsgev *iev, int fd, void (*handler)(int, short,
+    void *))
+{
+	if (imsgbuf_init(&iev->ibuf, fd) == -1)
+		fatal("%s: imsgbuf_init", __func__);
+	imsgbuf_allow_fdpass(&iev->ibuf);
+	iev->handler = handler;
+	iev->events = EV_READ;
+	event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev);
+	event_add(&iev->ev, NULL);
+}
+
+void
+imsg_event_add(struct imsgev *iev)
+{
+	iev->events = EV_READ;
+	if (imsgbuf_queuelen(&iev->ibuf) > 0)
+		iev->events |= EV_WRITE;
+
+	event_del(&iev->ev);
+	event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev);
+	event_add(&iev->ev, NULL);
+}
+
+int
+imsg_compose_event(struct imsgev *iev, uint32_t type, uint32_t peerid,
+    pid_t pid, int fd, void *data, size_t datalen)
+{
+	int	 ret;
+
+	if ((ret = imsg_compose(&iev->ibuf, type, peerid, pid, fd, data,
+	    datalen)) == -1)
+		return (ret);
+	imsg_event_add(iev);
+	return (ret);
+}
+
+int
+imsg_composev_event(struct imsgev *iev, uint32_t type, uint32_t peerid,
+    pid_t pid, int fd, const struct iovec *iov, int iovcnt)
+{
+	int	 ret;
+
+	if ((ret = imsg_composev(&iev->ibuf, type, peerid, pid, fd, iov,
+	    iovcnt)) == -1)
+		return (ret);
+	imsg_event_add(iev);
+	return (ret);
+}
+
+int
+imsg_forward_event(struct imsgev *iev, struct imsg *imsg)
+{
+	return (imsg_compose_event(iev, imsg->hdr.type, imsg->hdr.peerid,
+	    imsg->hdr.pid, -1, imsg->data, IMSG_DATA_SIZE(imsg)));
+}
+
+/*
+ * Copy a string payload out of an imsg, bounded by both the payload and
+ * the destination so a short or unterminated message can't over-read.
+ */
+void
+imsg_get_string(struct imsg *imsg, char *buf, size_t len)
+{
+	size_t	 n = IMSG_DATA_SIZE(imsg);
+
+	if (n >= len)
+		n = len - 1;
+	if (n > 0)
+		memcpy(buf, imsg->data, n);
+	buf[n] = '\0';
+}
+
+void
+newd_dispatch_control(int fd, short event, void *arg)
+{
+	struct imsgev	*iev = arg;
+	struct imsgbuf	*ibuf = &iev->ibuf;
+	struct imsg	 imsg;
+	int		 n, verbose;
+
+	if (event & EV_READ) {
+		if ((n = imsgbuf_read(ibuf)) == -1)
+			fatal("%s: imsgbuf_read", __func__);
+		if (n == 0) {
+			log_warnx("%s: lost control process", __func__);
+			newd_shutdown(newd_env);
+		}
+	}
+	if (event & EV_WRITE) {
+		if (imsgbuf_write(ibuf) == -1) {
+			if (errno == EPIPE) {
+				log_warnx("%s: lost control process", __func__);
+				newd_shutdown(newd_env);
+			}
+			fatal("%s: imsgbuf_write", __func__);
+		}
+	}
+
+	for (;;) {
+		if ((n = imsgbuf_get(ibuf, &imsg)) == -1)
+			fatal("%s: imsgbuf_get", __func__);
+		if (n == 0)
+			break;
+
+		switch (imsg.hdr.type) {
+		case IMSG_GET_INFO_PARENT_REQUEST:
+			newd_show_info(&imsg);
+			break;
+		case IMSG_GET_INFO_ENGINE_REQUEST:
+			/* the engine answers the control process directly */
+			imsg_forward_event(parent_iev_engine, &imsg);
+			break;
+		case IMSG_CTL_VERBOSE:
+			IMSG_SIZE_CHECK(&imsg, &verbose);
+			memcpy(&verbose, imsg.data, sizeof(verbose));
+			log_setverbose(verbose);
+			imsg_forward_event(parent_iev_engine, &imsg);
+			break;
+		default:
+			log_warnx("%s: unexpected imsg %d from control",
+			    __func__, imsg.hdr.type);
+			break;
+		}
+		imsg_free(&imsg);
+	}
+	imsg_event_add(iev);
+}
+
+void
+newd_dispatch_engine(int fd, short event, void *arg)
+{
+	struct imsgev	*iev = arg;
+	struct imsgbuf	*ibuf = &iev->ibuf;
+	struct imsg	 imsg;
+	int		 n;
+
+	if (event & EV_READ) {
+		if ((n = imsgbuf_read(ibuf)) == -1)
+			fatal("%s: imsgbuf_read", __func__);
+		if (n == 0) {
+			log_warnx("%s: lost engine process", __func__);
+			newd_shutdown(newd_env);
+		}
+	}
+	if (event & EV_WRITE) {
+		if (imsgbuf_write(ibuf) == -1) {
+			if (errno == EPIPE) {
+				log_warnx("%s: lost engine process", __func__);
+				newd_shutdown(newd_env);
+			}
+			fatal("%s: imsgbuf_write", __func__);
+		}
+	}
+
+	for (;;) {
+		if ((n = imsgbuf_get(ibuf, &imsg)) == -1)
+			fatal("%s: imsgbuf_get", __func__);
+		if (n == 0)
+			break;
+
+		switch (imsg.hdr.type) {
+		case IMSG_CFG_DONE:
+			newd_configure_done(newd_env);
+			break;
+		default:
+			log_warnx("%s: unexpected imsg %d from engine",
+			    __func__, imsg.hdr.type);
+			break;
+		}
+		imsg_free(&imsg);
+	}
+	imsg_event_add(iev);
+}
+
+void
+newd_sighdlr(int sig, short event, void *arg)
+{
+	struct newd	*env = arg;
+
+	switch (sig) {
+	case SIGHUP:
+		log_info("%s: ignoring SIGHUP", __func__);
+		break;
+	case SIGPIPE:
+		log_info("%s: ignoring SIGPIPE", __func__);
+		break;
+	case SIGUSR1:
+		log_info("%s: ignoring SIGUSR1", __func__);
+		break;
+	case SIGTERM:
+	case SIGINT:
+		newd_shutdown(env);
+		break;
+	default:
+		fatalx("unexpected signal");
+	}
+}
+
+__dead void
+usage(void)
+{
+	fprintf(stderr, "usage: %s [-dnv] [-D macro=value] [-f file]\n",
+	    getprogname());
+	exit(1);
+}
+
+int
+main(int argc, char **argv)
+{
+	struct newd		*env;
+	const char		*conffile = NEWD_CONF;
+	int			 ch;
+	int			 pipe_control[2];
+	int			 pipe_engine[2];
+	int			 pipe_control_engine[2];
+
+	if ((env = calloc(1, sizeof(*env))) == NULL)
+		fatal("%s: calloc", __func__);
+
+	while ((ch = getopt(argc, argv, "D:df:vn")) != -1) {
+		switch (ch) {
+		case 'D':
+			if (cmdline_symset(optarg) < 0)
+				log_warnx("could not parse macro definition %s",
+				    optarg);
+			break;
+		case 'd':
+			env->newd_debug = 2;
+			break;
+		case 'f':
+			conffile = optarg;
+			break;
+		case 'v':
+			env->newd_verbose++;
+			break;
+		case 'n':
+			env->newd_debug = 2;
+			env->newd_noaction = 1;
+			break;
+		default:
+			usage();
+		}
+	}
+
+	/* log to stderr until daemonized */
+	log_init(env->newd_debug ? env->newd_debug : 1, LOG_DAEMON);
+
+	argc -= optind;
+	if (argc > 0)
+		usage();
+
+	newd_env = env;
+	env->newd_conffile = conffile;
+
+	if (parse_config(env->newd_conffile, env) == -1)
+		exit(1);
+
+	if (env->newd_noaction && !env->newd_debug)
+		env->newd_debug = 1;
+
+	/* check for root privileges */
+	if (env->newd_noaction == 0) {
+		if (geteuid())
+			fatalx("need root privileges");
+	}
+
+	if (getpwnam(NEWD_USER) == NULL)
+		fatal("unknown user %s", NEWD_USER);
+
+	if (env->newd_noaction) {
+		fprintf(stderr, "configuration OK\n");
+		exit(0);
+	}
+
+	log_init(env->newd_debug, LOG_DAEMON);
+	log_setverbose(env->newd_verbose);
+	log_procinit("newd");
+
+	if (!env->newd_debug && daemon(0, 0) == -1)
+		fatal("can't daemonize");
+
+	log_info("%s startup", getprogname());
+
+	/*
+	 * All pipes are created before forking so the children inherit
+	 * them and no descriptor passing is needed to wire the processes
+	 * together.  Each child closes the ends it does not own.
+	 */
+	if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, PF_UNSPEC,
+	    pipe_control) == -1 ||
+	    socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, PF_UNSPEC,
+	    pipe_engine) == -1 ||
+	    socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, PF_UNSPEC,
+	    pipe_control_engine) == -1)
+		fatal("%s: socketpair", __func__);
+
+	/* control: parent[1], control_engine[0] */
+	switch (fork()) {
+	case -1:
+		fatal("%s: fork", __func__);
+	case 0:
+		close(pipe_control[0]);
+		close(pipe_engine[0]);
+		close(pipe_engine[1]);
+		close(pipe_control_engine[1]);
+		control(pipe_control[1], pipe_control_engine[0]);
+		/* NOTREACHED */
+	}
+
+	/* engine: engine[1], control_engine[1] */
+	switch (fork()) {
+	case -1:
+		fatal("%s: fork", __func__);
+	case 0:
+		close(pipe_control[0]);
+		close(pipe_control[1]);
+		close(pipe_engine[0]);
+		close(pipe_control_engine[0]);
+		engine(pipe_engine[1], pipe_control_engine[1]);
+		/* NOTREACHED */
+	}
+
+	/* parent: the [0] end of every pipe to a child */
+	close(pipe_control[1]);
+	close(pipe_engine[1]);
+	close(pipe_control_engine[0]);
+	close(pipe_control_engine[1]);
+
+	env->newd_eb = event_init();
+
+	signal_set(&ev_sigint, SIGINT, newd_sighdlr, env);
+	signal_set(&ev_sigterm, SIGTERM, newd_sighdlr, env);
+	signal_set(&ev_sighup, SIGHUP, newd_sighdlr, env);
+	signal_set(&ev_sigpipe, SIGPIPE, newd_sighdlr, env);
+	signal_set(&ev_sigusr1, SIGUSR1, newd_sighdlr, env);
+
+	signal_add(&ev_sigint, NULL);
+	signal_add(&ev_sigterm, NULL);
+	signal_add(&ev_sighup, NULL);
+	signal_add(&ev_sigpipe, NULL);
+	signal_add(&ev_sigusr1, NULL);
+
+	if ((parent_iev_control = calloc(1, sizeof(*parent_iev_control)))
+	    == NULL)
+		fatal("%s: calloc", __func__);
+	imsg_event_init(parent_iev_control, pipe_control[0],
+	    newd_dispatch_control);
+
+	if ((parent_iev_engine = calloc(1, sizeof(*parent_iev_engine)))
+	    == NULL)
+		fatal("%s: calloc", __func__);
+	imsg_event_init(parent_iev_engine, pipe_engine[0],
+	    newd_dispatch_engine);
+
+	if (newd_configure(env) == -1)
+		fatalx("configuration failed");
+
+	/*
+	 * Widen these as the daemon grows.  Opening files or sockets from
+	 * the parent after this point needs the matching promises here.
+	 */
+	if (unveil(NULL, NULL) != 0)
+		err(1, "unveil");
+
+	if (pledge("stdio", NULL) == -1)
+		err(1, "pledge");
+
+	event_base_dispatch(env->newd_eb);
+
+	log_debug("%s newd exiting", getprogname());
+
+	return (0);
+}
+
+/*
+ * Push the parsed configuration to the children.  Anything that must be
+ * set up with privileges (listeners, devices) belongs here, before the
+ * parent pledges.
+ */
+int
+newd_configure(struct newd *env)
+{
+	env->cfg_pending = 1;
+
+	imsg_compose_event(parent_iev_control, IMSG_CFG_DONE, 0, 0, -1,
+	    NULL, 0);
+	imsg_compose_event(parent_iev_engine, IMSG_CFG_DONE, 0, 0, -1,
+	    NULL, 0);
+
+	return (0);
+}
+
+void
+newd_configure_done(struct newd *env)
+{
+	if (env->cfg_pending == 0) {
+		log_warnx("%s: configuration already finished", __func__);
+		return;
+	}
+
+	env->cfg_pending--;
+	if (env->cfg_pending == 0) {
+		imsg_compose_event(parent_iev_control, IMSG_CTL_START, 0, 0,
+		    -1, NULL, 0);
+		imsg_compose_event(parent_iev_engine, IMSG_CTL_START, 0, 0,
+		    -1, NULL, 0);
+	}
+}
+
+__dead void
+newd_shutdown(struct newd *env)
+{
+	pid_t	 pid;
+	int	 status;
+
+	/* closing the pipes tells the children to exit */
+	event_del(&parent_iev_control->ev);
+	imsgbuf_clear(&parent_iev_control->ibuf);
+	close(parent_iev_control->ibuf.fd);
+	event_del(&parent_iev_engine->ev);
+	imsgbuf_clear(&parent_iev_engine->ibuf);
+	close(parent_iev_engine->ibuf.fd);
+	free(parent_iev_control);
+	free(parent_iev_engine);
+
+	log_debug("waiting for children to terminate");
+	do {
+		pid = wait(&status);
+		if (pid == -1) {
+			if (errno != EINTR && errno != ECHILD)
+				fatal("wait");
+		} else if (WIFSIGNALED(status))
+			log_warnx("lost child: pid %d terminated; signal %d",
+			    pid, WTERMSIG(status));
+		else if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
+			log_warnx("lost child: pid %d exited abnormally", pid);
+	} while (pid != -1 || (pid == -1 && errno == EINTR));
+
+	newd_parent_shutdown(env);
+
+	log_warnx("newd terminating");
+	exit(0);
+}
+
+void
+newd_show_info(struct imsg *imsg)
+{
+	struct newd_parent_info	 npi;
+
+	switch (imsg->hdr.type) {
+	case IMSG_GET_INFO_PARENT_REQUEST:
+		npi.verbose = log_getverbose();
+		if (imsg_compose_event(parent_iev_control,
+		    IMSG_GET_INFO_PARENT_DATA, imsg->hdr.peerid, 0, -1,
+		    &npi, sizeof(npi)) == -1)
+			return;
+		if (imsg_compose_event(parent_iev_control,
+		    IMSG_GET_INFO_PARENT_END_DATA, imsg->hdr.peerid, 0, -1,
+		    &npi, sizeof(npi)) == -1)
+			return;
+		break;
+	default:
+		log_debug("%s: error handling imsg", __func__);
+		break;
+	}
+}
+
+/* free whatever the parent allocated from the configuration */
+void
+newd_parent_shutdown(struct newd *env)
+{
+	log_debug("newd parent shutting down");
+
+	free(env);
+}
blob - /dev/null
blob + ed1cc554c977572fac9de75651eb0997768fda91c7c9bba0be4a25f1e856b4b7 (mode 644)
--- /dev/null	
+++ newd/newd.conf.5	
@@ -0,0 +1,86 @@
+.\"
+.\" Copyright (c) 2016-2026 Tracey Emery <tracey@openbsd.org>
+.\"
+.\" Permission to use, copy, modify, and distribute this software for any
+.\" purpose with or without fee is hereby granted, provided that the above
+.\" copyright notice and this permission notice appear in all copies.
+.\"
+.\" THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+.\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+.\" MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+.\" ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+.\" WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+.\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+.\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+.\"
+.Dd $Mdocdate: November 19 2026 $
+.Dt NEWD.CONF 5
+.Os
+.Sh NAME
+.Nm newd.conf
+.Nd newd daemon configuration file
+.Sh DESCRIPTION
+.Nm
+is the configuration file for the base daemon,
+.Xr newd 8 .
+.Pp
+The current line can be extended over multiple lines using a backslash
+.Pq Sq \e .
+Comments can be put anywhere in the file using a hash mark
+.Pq Sq # ,
+and extend to the end of the current line.
+Care should be taken when commenting out multi-line text:
+the comment is effective until the end of the entire block.
+.Pp
+Argument names not beginning with a letter, digit, or underscore
+must be quoted.
+.Sh MACROS
+Macros can be defined that will later be expanded in context.
+Macro names must start with a letter, digit, or underscore,
+and may contain any of those characters.
+Macro names may not be reserved words.
+Macros are not expanded inside quotes.
+.Pp
+For example:
+.Bd -literal -offset indent
+level = "1"
+verbose $level
+.Ed
+.Pp
+Additional configuration files can be given on the command line with
+.Ic include :
+.Bd -literal -offset indent
+include "/etc/newd.local.conf"
+.Ed
+.Sh GLOBAL CONFIGURATION
+Here are the settings that can be set globally:
+.Bl -tag -width Ds
+.It Ic verbose Ar number
+Set the logging level at startup.
+0 is brief, 1 is verbose and 2 is debug.
+The level can be changed at run time with
+.Xr newctl 8 .
+.El
+.Sh FILES
+.Bl -tag -width Ds -compact
+.It Pa /etc/newd.conf
+.Xr newd 8
+configuration file.
+.El
+.Sh EXAMPLES
+.Bd -literal -offset indent
+#
+# Global Options
+#
+
+verbose 1
+.Ed
+.Sh SEE ALSO
+.Xr newctl 8 ,
+.Xr newd 8
+.Sh AUTHORS
+.An -nosplit
+The
+.Xr newd 8
+program was written by
+.An Tracey Emery Aq Mt tracey@openbsd.org .
blob - /dev/null
blob + d38e3858913a634275a16fe1f410e6a8dbde49eb93a27cd4e296b70a15935b3e (mode 644)
--- /dev/null	
+++ newd/newd.h	
@@ -0,0 +1,155 @@
+/*
+ * Copyright (c) 2016, 2019-2026 Tracey Emery <tracey@openbsd.org>
+ * Copyright (c) 2015 Mike Larkin <mlarkin@openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#ifdef NEWD_DEBUG
+#define dprintf(x...)   do { log_debug(x); } while(0)
+#else
+#define dprintf(x...)
+#endif /* NEWD_DEBUG */
+
+#define NEWD_CONF		 "/etc/newd.conf"
+#define NEWD_SOCKET		 "/var/run/newd.sock"
+#define NEWD_USER		 "_newd"
+
+#define NEWD_MAXTEXT		 511
+#define NEWD_MAXNAME		 16
+
+#define MAX_IMSG_DATA_SIZE	(MAX_IMSGSIZE - IMSG_HEADER_SIZE)
+#define IMSG_DATA_SIZE(imsg)	((imsg)->hdr.len - IMSG_HEADER_SIZE)
+#define IMSG_SIZE_CHECK(imsg, p) do {					\
+	if (IMSG_DATA_SIZE(imsg) < sizeof(*p))				\
+		fatalx("bad length imsg received (%s)", #p);		\
+} while (0)
+
+/*
+ * Messages travel over three pipes: parent <-> control, parent <-> engine
+ * and control <-> engine.  Requests from newctl enter at the control
+ * process and are forwarded to the parent, which answers itself or hands
+ * them to the engine.  Replies for newctl are routed back to the control
+ * process with the newctl connection fd in peerid.
+ */
+enum imsg_type {
+	IMSG_NONE,
+	IMSG_CTL_OK,
+	IMSG_CTL_FAIL,
+	IMSG_CTL_VERBOSE,
+	IMSG_CTL_NOTIFY,
+
+	IMSG_GET_INFO_PARENT_REQUEST,
+	IMSG_GET_INFO_PARENT_DATA,
+	IMSG_GET_INFO_PARENT_END_DATA,
+
+	IMSG_GET_INFO_CONTROL_REQUEST,
+	IMSG_GET_INFO_CONTROL_DATA,
+	IMSG_GET_INFO_CONTROL_END_DATA,
+
+	IMSG_GET_INFO_ENGINE_REQUEST,
+	IMSG_GET_INFO_ENGINE_DATA,
+	IMSG_GET_INFO_ENGINE_END_DATA,
+
+	IMSG_CTL_START,
+	IMSG_CFG_DONE,
+};
+
+struct imsgev {
+	struct imsgbuf		 ibuf;
+	void			(*handler)(int, short, void *);
+	struct event		 ev;
+	short			 events;
+};
+
+struct newd_parent_info {
+	int		 verbose;
+};
+
+struct newd_control_info {
+	int		 verbose;
+};
+
+struct newd_engine_info {
+	int		 verbose;
+};
+
+struct newd {
+	const char		*newd_conffile;
+
+	int			 newd_debug;
+	int			 newd_verbose;
+	int			 newd_noaction;
+
+	struct event_base	*newd_eb;
+
+	/* children still to acknowledge their configuration */
+	int			 cfg_pending;
+};
+
+extern struct newd	*newd_env;
+
+/* parent process pipes to the control and engine processes */
+extern struct imsgev	*parent_iev_control;
+extern struct imsgev	*parent_iev_engine;
+
+/* engine process pipe to the parent */
+extern struct imsgev	*engine_iev_parent;
+
+/* newd.c */
+void	 imsg_event_init(struct imsgev *, int, void (*)(int, short, void *));
+void	 imsg_event_add(struct imsgev *);
+int	 imsg_compose_event(struct imsgev *, uint32_t, uint32_t, pid_t, int,
+	    void *, size_t);
+int	 imsg_composev_event(struct imsgev *, uint32_t, uint32_t, pid_t, int,
+	    const struct iovec *, int);
+int	 imsg_forward_event(struct imsgev *, struct imsg *);
+void	 imsg_get_string(struct imsg *, char *, size_t);
+
+/* control.c */
+__dead void
+	 control(int, int);
+
+/* engine.c */
+__dead void
+	 engine(int, int);
+
+/* config.c */
+int	 config_init(struct newd *);
+int	 config_getcfg(struct newd *, struct imsg *);
+
+/* parse.y */
+int	 parse_config(const char *, struct newd *);
+int	 cmdline_symset(char *);
+
+/* log.c */
+void	 log_init(int, int);
+void	 log_procinit(const char *);
+void	 log_setverbose(int);
+int	 log_getverbose(void);
+void	 log_warn(const char *, ...)
+	    __attribute__((__format__ (printf, 1, 2)));
+void	 log_warnx(const char *, ...)
+	    __attribute__((__format__ (printf, 1, 2)));
+void	 log_info(const char *, ...)
+	    __attribute__((__format__ (printf, 1, 2)));
+void	 log_debug(const char *, ...)
+	    __attribute__((__format__ (printf, 1, 2)));
+void	 logit(int, const char *, ...)
+	    __attribute__((__format__ (printf, 2, 3)));
+void	 vlog(int, const char *, va_list)
+	    __attribute__((__format__ (printf, 2, 0)));
+__dead void fatal(const char *, ...)
+	    __attribute__((__format__ (printf, 1, 2)));
+__dead void fatalx(const char *, ...)
+	    __attribute__((__format__ (printf, 1, 2)));
blob - /dev/null
blob + 5871ec3a25e996223a802e98c1eb1e5187326ab0ca2e35c40cdc7df15a943bb1 (mode 644)
--- /dev/null	
+++ newd/parse.y	
@@ -0,0 +1,624 @@
+/*
+ * Copyright (c) 2016-2026 Tracey Emery <tracey@openbsd.org>
+ * Copyright (c) 2020 Matthias Pressfreund <mpfr@fn.de>
+ * Copyright (c) 2007 - 2015 Reyk Floeter <reyk@openbsd.org>
+ * Copyright (c) 2008 Gilles Chehade <gilles@openbsd.org>
+ * Copyright (c) 2006 Pierre-Yves Ritschard <pyr@openbsd.org>
+ * Copyright (c) 2004, 2005 Esben Norby <norby@openbsd.org>
+ * Copyright (c) 2004 Ryan McBride <mcbride@openbsd.org>
+ * Copyright (c) 2002, 2003, 2004 Henning Brauer <henning@openbsd.org>
+ * Copyright (c) 2001 Markus Friedl.  All rights reserved.
+ * Copyright (c) 2001 Daniel Hartmeier.  All rights reserved.
+ * Copyright (c) 2001 Theo de Raadt.  All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+%{
+#include <sys/types.h>
+#include <sys/queue.h>
+#include <sys/stat.h>
+
+#include <ctype.h>
+#include <err.h>
+#include <errno.h>
+#include <event.h>
+#include <imsg.h>
+#include <limits.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <syslog.h>
+#include <unistd.h>
+
+#include "newd.h"
+
+TAILQ_HEAD(files, file)		 files = TAILQ_HEAD_INITIALIZER(files);
+static struct file {
+	TAILQ_ENTRY(file)	 entry;
+	FILE			*stream;
+	char			*name;
+	int			 lineno;
+	int			 errors;
+} *file;
+struct file	*newfile(const char *, int);
+static void	 closefile(struct file *);
+int		 check_file_secrecy(int, const char *);
+int		 yyparse(void);
+int		 yylex(void);
+int		 yyerror(const char *, ...)
+    __attribute__((__format__ (printf, 1, 2)))
+    __attribute__((__nonnull__ (1)));
+int		 kw_cmp(const void *, const void *);
+int		 lookup(char *);
+int		 lgetc(int);
+int		 lungetc(int);
+int		 findeol(void);
+
+TAILQ_HEAD(symhead, sym)	 symhead = TAILQ_HEAD_INITIALIZER(symhead);
+struct sym {
+	TAILQ_ENTRY(sym)	 entry;
+	int			 used;
+	int			 persist;
+	char			*nam;
+	char			*val;
+};
+
+int	 symset(const char *, const char *, int);
+char	*symget(const char *);
+
+static int		 errors;
+
+/* the configuration being parsed, for conf_main rules to fill in */
+static struct newd	*newd;
+
+typedef struct {
+	union {
+		long long		 number;
+		char			*string;
+	} v;
+	int lineno;
+} YYSTYPE;
+
+%}
+
+%token	ERROR INCLUDE VERBOSE
+
+%token	<v.string>	STRING
+%token	<v.number>	NUMBER
+%type	<v.string>	string
+
+%%
+
+grammar		: /* empty */
+		| grammar include '\n'
+		| grammar '\n'
+		| grammar conf_main '\n'
+		| grammar error '\n'		{ file->errors++; }
+		| grammar varset '\n'
+		;
+
+include		: INCLUDE STRING		{
+			struct file	*nfile;
+
+			if ((nfile = newfile($2, 1)) == NULL) {
+				yyerror("failed to include file %s", $2);
+				free($2);
+				YYERROR;
+			}
+			free($2);
+
+			file = nfile;
+			lungetc('\n');
+		}
+		;
+
+/*
+ * Global daemon options.  Add new keywords to the %token line, the
+ * sorted keyword table in lookup() and a rule here.
+ */
+conf_main	: VERBOSE NUMBER {
+			if ($2 < 0 || $2 > 2) {
+				yyerror("verbose must be between 0 and 2");
+				YYERROR;
+			}
+			newd->newd_verbose = $2;
+		}
+		;
+
+varset		: STRING '=' string		{
+			char *s = $1;
+			if (newd->newd_verbose)
+				printf("%s = \"%s\"\n", $1, $3);
+			while (*s++) {
+				if (isspace((unsigned char)*s)) {
+					yyerror("macro name cannot contain "
+					    "whitespace");
+					YYERROR;
+				}
+			}
+			if (symset($1, $3, 0) == -1)
+				fatal("cannot store variable");
+			free($1);
+			free($3);
+		}
+		;
+
+string		: string STRING {
+			if (asprintf(&$$, "%s %s", $1, $2) == -1) {
+				free($1);
+				free($2);
+				yyerror("string: asprintf");
+				YYERROR;
+			}
+			free($1);
+			free($2);
+		}
+		| STRING
+		;
+
+%%
+
+struct keywords {
+	const char	*k_name;
+	int		 k_val;
+};
+
+int
+yyerror(const char *fmt, ...)
+{
+	va_list		 ap;
+	char		*msg;
+
+	file->errors++;
+	va_start(ap, fmt);
+	if (vasprintf(&msg, fmt, ap) == -1)
+		fatalx("yyerror vasprintf");
+	va_end(ap);
+	logit(LOG_CRIT, "%s:%d: %s", file->name, yylval.lineno, msg);
+	free(msg);
+	return (0);
+}
+
+int
+kw_cmp(const void *k, const void *e)
+{
+	return (strcmp(k, ((const struct keywords *)e)->k_name));
+}
+
+int
+lookup(char *s)
+{
+	/* This has to be sorted always. */
+	static const struct keywords keywords[] = {
+		{ "include",		INCLUDE },
+		{ "verbose",		VERBOSE },
+	};
+	const struct keywords	*p;
+
+	p = bsearch(s, keywords, sizeof(keywords)/sizeof(keywords[0]),
+	    sizeof(keywords[0]), kw_cmp);
+
+	if (p)
+		return (p->k_val);
+	else
+		return (STRING);
+}
+
+#define MAXPUSHBACK	128
+
+unsigned char	*parsebuf;
+int		 parseindex;
+unsigned char	 pushback_buffer[MAXPUSHBACK];
+int		 pushback_index = 0;
+
+int
+lgetc(int quotec)
+{
+	int		c = 0, next;
+
+	if (parsebuf) {
+		/* Read character from the parsebuffer instead of input. */
+		if (parseindex >= 0) {
+			c = parsebuf[parseindex++];
+			if (c != '\0')
+				return (c);
+			parsebuf = NULL;
+		} else
+			parseindex++;
+	}
+
+	if (pushback_index)
+		return (pushback_buffer[--pushback_index]);
+
+	if (quotec) {
+		c = getc(file->stream);
+		if (c == EOF)
+			yyerror("reached end of file while parsing "
+			    "quoted string");
+		return (c);
+	}
+
+	if (parseindex == 0) {
+		while ((c = getc(file->stream)) == '\\') {
+			if ((next = getc(file->stream)) != '\n') {
+				c = next;
+				break;
+			}
+			yylval.lineno = file->lineno;
+			file->lineno++;
+		}
+	}
+
+	parseindex = 0;
+	return (c);
+}
+
+int
+lungetc(int c)
+{
+	if (c == EOF)
+		return (EOF);
+	if (parsebuf) {
+		parseindex--;
+		if (parseindex >= 0)
+			return (c);
+	}
+	if (pushback_index < MAXPUSHBACK-1)
+		return (pushback_buffer[pushback_index++] = c);
+	else
+		return (EOF);
+}
+
+int
+findeol(void)
+{
+	int	c;
+
+	parsebuf = NULL;
+
+	/* Skip to either EOF or the first real EOL. */
+	while (1) {
+		if (pushback_index)
+			c = pushback_buffer[--pushback_index];
+		else
+			c = lgetc(0);
+		if (c == '\n') {
+			file->lineno++;
+			break;
+		}
+		if (c == EOF)
+			break;
+	}
+	return (ERROR);
+}
+
+int
+yylex(void)
+{
+	unsigned char	 buf[8096];
+	unsigned char	*p, *val;
+	int		 quotec, next, c;
+	int		 token;
+
+top:
+	p = buf;
+	while ((c = lgetc(0)) == ' ' || c == '\t')
+		; /* nothing */
+
+	yylval.lineno = file->lineno;
+	if (c == '#')
+		while ((c = lgetc(0)) != '\n' && c != EOF)
+			; /* nothing */
+	if (c == '$' && parsebuf == NULL) {
+		while (1) {
+			if ((c = lgetc(0)) == EOF)
+				return (0);
+
+			if (p + 1 >= buf + sizeof(buf) - 1) {
+				yyerror("string too long");
+				return (findeol());
+			}
+			if (isalnum(c) || c == '_') {
+				*p++ = c;
+				continue;
+			}
+			*p = '\0';
+			lungetc(c);
+			break;
+		}
+		if ((val = symget(buf)) == NULL) {
+			yyerror("macro '%s' not defined", buf);
+			return (findeol());
+		}
+		parsebuf = val;
+		parseindex = 0;
+		goto top;
+	}
+
+	switch (c) {
+	case '\'':
+	case '"':
+		quotec = c;
+		while (1) {
+			if ((c = lgetc(quotec)) == EOF)
+				return (0);
+			if (c == '\n') {
+				file->lineno++;
+				continue;
+			} else if (c == '\\') {
+				if ((next = lgetc(quotec)) == EOF)
+					return (0);
+				if (next == quotec || c == ' ' || c == '\t')
+					c = next;
+				else if (next == '\n') {
+					file->lineno++;
+					continue;
+				} else
+					lungetc(next);
+			} else if (c == quotec) {
+				*p = '\0';
+				break;
+			} else if (c == '\0') {
+				yyerror("syntax error");
+				return (findeol());
+			}
+			if (p + 1 >= buf + sizeof(buf) - 1) {
+				yyerror("string too long");
+				return (findeol());
+			}
+			*p++ = c;
+		}
+		if ((yylval.v.string = strdup(buf)) == NULL)
+			err(1, "yylex: strdup");
+		return (STRING);
+	}
+
+#define allowed_to_end_number(x) \
+	(isspace(x) || x == ')' || x ==',' || x == '/' || x == '}' || x == '=')
+
+	if (c == '-' || isdigit(c)) {
+		do {
+			*p++ = c;
+			if ((unsigned)(p-buf) >= sizeof(buf)) {
+				yyerror("string too long");
+				return (findeol());
+			}
+		} while ((c = lgetc(0)) != EOF && isdigit(c));
+		lungetc(c);
+		if (p == buf + 1 && buf[0] == '-')
+			goto nodigits;
+		if (c == EOF || allowed_to_end_number(c)) {
+			const char *errstr = NULL;
+
+			*p = '\0';
+			yylval.v.number = strtonum(buf, LLONG_MIN,
+			    LLONG_MAX, &errstr);
+			if (errstr) {
+				yyerror("\"%s\" invalid number: %s",
+				    buf, errstr);
+				return (findeol());
+			}
+			return (NUMBER);
+		} else {
+nodigits:
+			while (p > buf + 1)
+				lungetc(*--p);
+			c = *--p;
+			if (c == '-')
+				return (c);
+		}
+	}
+
+#define allowed_in_string(x) \
+	(isalnum(x) || (ispunct(x) && x != '(' && x != ')' && \
+	x != '{' && x != '}' && \
+	x != '!' && x != '=' && x != '#' && \
+	x != ','))
+
+	if (isalnum(c) || c == ':' || c == '_') {
+		do {
+			*p++ = c;
+			if ((unsigned)(p-buf) >= sizeof(buf)) {
+				yyerror("string too long");
+				return (findeol());
+			}
+		} while ((c = lgetc(0)) != EOF && (allowed_in_string(c)));
+		lungetc(c);
+		*p = '\0';
+		if ((token = lookup(buf)) == STRING) {
+			yylval.v.string = strdup(buf);
+			if (yylval.v.string == NULL)
+				err(1, "yylex: strdup");
+		}
+		return (token);
+	}
+	if (c == '\n') {
+		yylval.lineno = file->lineno;
+		file->lineno++;
+	}
+	if (c == EOF)
+		return (0);
+	return (c);
+}
+
+int
+check_file_secrecy(int fd, const char *fname)
+{
+	struct stat	st;
+
+	if (fstat(fd, &st)) {
+		log_warn("cannot stat %s", fname);
+		return (-1);
+	}
+	if (st.st_uid != 0 && st.st_uid != getuid()) {
+		log_warnx("%s: owner not root or current user", fname);
+		return (-1);
+	}
+	if (st.st_mode & (S_IWGRP | S_IXGRP | S_IRWXO)) {
+		log_warnx("%s: group writable or world read/writable", fname);
+		return (-1);
+	}
+	return (0);
+}
+
+struct file *
+newfile(const char *name, int secret)
+{
+	struct file	*nfile;
+
+	if ((nfile = calloc(1, sizeof(struct file))) == NULL) {
+		log_warn("calloc");
+		return (NULL);
+	}
+	if ((nfile->name = strdup(name)) == NULL) {
+		log_warn("strdup");
+		free(nfile);
+		return (NULL);
+	}
+	if ((nfile->stream = fopen(nfile->name, "r")) == NULL) {
+		log_warn("%s", nfile->name);
+		free(nfile->name);
+		free(nfile);
+		return (NULL);
+	} else if (secret &&
+	    check_file_secrecy(fileno(nfile->stream), nfile->name)) {
+		fclose(nfile->stream);
+		free(nfile->name);
+		free(nfile);
+		return (NULL);
+	}
+	nfile->lineno = 1;
+	return (nfile);
+}
+
+static void
+closefile(struct file *xfile)
+{
+	fclose(xfile->stream);
+	free(xfile->name);
+	free(xfile);
+}
+
+int
+parse_config(const char *filename, struct newd *env)
+{
+	struct sym	*sym, *next;
+
+	if ((file = newfile(filename, 0)) == NULL) {
+		log_warn("failed to open %s", filename);
+		return (0);
+	}
+
+	if (config_init(env) == -1)
+		fatal("failed to initialize configuration");
+
+	newd = env;
+
+	yyparse();
+	errors = file->errors;
+	closefile(file);
+	/* Free macros and check which have not been used. */
+	TAILQ_FOREACH_SAFE(sym, &symhead, entry, next) {
+		if ((newd->newd_verbose > 1) && !sym->used)
+			fprintf(stderr, "warning: macro '%s' not used\n",
+			    sym->nam);
+		if (!sym->persist) {
+			free(sym->nam);
+			free(sym->val);
+			TAILQ_REMOVE(&symhead, sym, entry);
+			free(sym);
+		}
+	}
+
+	if (errors)
+		return (-1);
+
+	return (0);
+}
+
+int
+symset(const char *nam, const char *val, int persist)
+{
+	struct sym	*sym;
+
+	TAILQ_FOREACH(sym, &symhead, entry) {
+		if (strcmp(nam, sym->nam) == 0)
+			break;
+	}
+
+	if (sym != NULL) {
+		if (sym->persist == 1)
+			return (0);
+		else {
+			free(sym->nam);
+			free(sym->val);
+			TAILQ_REMOVE(&symhead, sym, entry);
+			free(sym);
+		}
+	}
+	if ((sym = calloc(1, sizeof(*sym))) == NULL)
+		return (-1);
+	if ((sym->nam = strdup(nam)) == NULL) {
+		free(sym);
+		return (-1);
+	}
+	if ((sym->val = strdup(val)) == NULL) {
+		free(sym->nam);
+		free(sym);
+		return (-1);
+	}
+	sym->used = 0;
+	sym->persist = persist;
+	TAILQ_INSERT_TAIL(&symhead, sym, entry);
+	return (0);
+}
+
+int
+cmdline_symset(char *s)
+{
+	char	*sym, *val;
+	int	 ret;
+	size_t	 len;
+
+	val = strrchr(s, '=');
+	if (val == NULL)
+		return (-1);
+
+	len = strlen(s) - strlen(val) + 1;
+	if ((sym = malloc(len)) == NULL)
+		fatal("%s: malloc", __func__);
+
+	memcpy(sym, s, len - 1);
+	sym[len - 1] = '\0';
+
+	ret = symset(sym, val + 1, 1);
+	free(sym);
+
+	return (ret);
+}
+
+char *
+symget(const char *nam)
+{
+	struct sym	*sym;
+
+	TAILQ_FOREACH(sym, &symhead, entry) {
+		if (strcmp(nam, sym->nam) == 0) {
+			sym->used = 1;
+			return (sym->val);
+		}
+	}
+	return (NULL);
+}