xref: /openbsd-src/usr.sbin/relayd/proc.c (revision 6676295ff107abd6850f48ae428e19963f4b1dc5)
1 /*	$OpenBSD: proc.c,v 1.52 2024/11/21 13:38:45 claudio Exp $	*/
2 
3 /*
4  * Copyright (c) 2010 - 2016 Reyk Floeter <reyk@openbsd.org>
5  * Copyright (c) 2008 Pierre-Yves Ritschard <pyr@openbsd.org>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #include <sys/types.h>
21 #include <sys/queue.h>
22 #include <sys/socket.h>
23 #include <sys/wait.h>
24 
25 #include <fcntl.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <unistd.h>
29 #include <string.h>
30 #include <errno.h>
31 #include <signal.h>
32 #include <paths.h>
33 #include <pwd.h>
34 #include <event.h>
35 #include <imsg.h>
36 
37 #include "relayd.h"
38 
39 void	 proc_exec(struct privsep *, struct privsep_proc *, unsigned int, int,
40 	    char **);
41 void	 proc_setup(struct privsep *, struct privsep_proc *, unsigned int);
42 void	 proc_open(struct privsep *, int, int);
43 void	 proc_accept(struct privsep *, int, enum privsep_procid,
44 	    unsigned int);
45 void	 proc_close(struct privsep *);
46 void	 proc_shutdown(struct privsep_proc *);
47 void	 proc_sig_handler(int, short, void *);
48 void	 proc_range(struct privsep *, enum privsep_procid, int *, int *);
49 int	 proc_dispatch_null(int, struct privsep_proc *, struct imsg *);
50 
51 enum privsep_procid
52 proc_getid(struct privsep_proc *procs, unsigned int nproc,
53     const char *proc_name)
54 {
55 	struct privsep_proc	*p;
56 	unsigned int		 proc;
57 
58 	for (proc = 0; proc < nproc; proc++) {
59 		p = &procs[proc];
60 		if (strcmp(p->p_title, proc_name))
61 			continue;
62 
63 		return (p->p_id);
64 	}
65 
66 	return (PROC_MAX);
67 }
68 
69 void
70 proc_exec(struct privsep *ps, struct privsep_proc *procs, unsigned int nproc,
71     int argc, char **argv)
72 {
73 	unsigned int		 proc, nargc, i, proc_i;
74 	char			**nargv;
75 	struct privsep_proc	*p;
76 	char			 num[32];
77 	int			 fd;
78 
79 	/* Prepare the new process argv. */
80 	nargv = calloc(argc + 5, sizeof(char *));
81 	if (nargv == NULL)
82 		fatal("%s: calloc", __func__);
83 
84 	/* Copy call argument first. */
85 	nargc = 0;
86 	nargv[nargc++] = argv[0];
87 
88 	/* Set process name argument and save the position. */
89 	nargv[nargc++] = "-P";
90 	proc_i = nargc;
91 	nargc++;
92 
93 	/* Point process instance arg to stack and copy the original args. */
94 	nargv[nargc++] = "-I";
95 	nargv[nargc++] = num;
96 	for (i = 1; i < (unsigned int) argc; i++)
97 		nargv[nargc++] = argv[i];
98 
99 	nargv[nargc] = NULL;
100 
101 	for (proc = 0; proc < nproc; proc++) {
102 		p = &procs[proc];
103 
104 		/* Update args with process title. */
105 		nargv[proc_i] = (char *)(uintptr_t)p->p_title;
106 
107 		/* Fire children processes. */
108 		for (i = 0; i < ps->ps_instances[p->p_id]; i++) {
109 			/* Update the process instance number. */
110 			snprintf(num, sizeof(num), "%u", i);
111 
112 			fd = ps->ps_pipes[p->p_id][i].pp_pipes[PROC_PARENT][0];
113 			ps->ps_pipes[p->p_id][i].pp_pipes[PROC_PARENT][0] = -1;
114 
115 			switch (fork()) {
116 			case -1:
117 				fatal("%s: fork", __func__);
118 				break;
119 			case 0:
120 				/* Prepare parent socket. */
121 				if (fd != PROC_PARENT_SOCK_FILENO) {
122 					if (dup2(fd, PROC_PARENT_SOCK_FILENO)
123 					    == -1)
124 						fatal("dup2");
125 				} else if (fcntl(fd, F_SETFD, 0) == -1)
126 					fatal("fcntl");
127 
128 				execvp(argv[0], nargv);
129 				fatal("%s: execvp", __func__);
130 				break;
131 			default:
132 				/* Close child end. */
133 				close(fd);
134 				break;
135 			}
136 		}
137 	}
138 	free(nargv);
139 }
140 
141 void
142 proc_connect(struct privsep *ps)
143 {
144 	struct imsgev		*iev;
145 	unsigned int		 src, dst, inst;
146 
147 	/* Don't distribute any sockets if we are not really going to run. */
148 	if (ps->ps_noaction)
149 		return;
150 
151 	for (dst = 0; dst < PROC_MAX; dst++) {
152 		/* We don't communicate with ourselves. */
153 		if (dst == PROC_PARENT)
154 			continue;
155 
156 		for (inst = 0; inst < ps->ps_instances[dst]; inst++) {
157 			iev = &ps->ps_ievs[dst][inst];
158 			if (imsgbuf_init(&iev->ibuf,
159 			    ps->ps_pp->pp_pipes[dst][inst]) == -1)
160 				fatal("imsgbuf_init");
161 			imsgbuf_allow_fdpass(&iev->ibuf);
162 			event_set(&iev->ev, iev->ibuf.fd, iev->events,
163 			    iev->handler, iev->data);
164 			event_add(&iev->ev, NULL);
165 		}
166 	}
167 
168 	/* Distribute the socketpair()s for everyone. */
169 	for (src = 0; src < PROC_MAX; src++)
170 		for (dst = src; dst < PROC_MAX; dst++) {
171 			/* Parent already distributed its fds. */
172 			if (src == PROC_PARENT || dst == PROC_PARENT)
173 				continue;
174 
175 			proc_open(ps, src, dst);
176 		}
177 }
178 
179 void
180 proc_init(struct privsep *ps, struct privsep_proc *procs, unsigned int nproc,
181     int debug, int argc, char **argv, enum privsep_procid proc_id)
182 {
183 	struct privsep_proc	*p = NULL;
184 	struct privsep_pipes	*pa, *pb;
185 	unsigned int		 proc;
186 	unsigned int		 dst;
187 	int			 fds[2];
188 
189 	/* Don't initiate anything if we are not really going to run. */
190 	if (ps->ps_noaction)
191 		return;
192 
193 	if (proc_id == PROC_PARENT) {
194 		privsep_process = PROC_PARENT;
195 		proc_setup(ps, procs, nproc);
196 
197 		if (!debug && daemon(1, 0) == -1)
198 			fatal("failed to daemonize");
199 
200 		/*
201 		 * Create the children sockets so we can use them
202 		 * to distribute the rest of the socketpair()s using
203 		 * proc_connect() later.
204 		 */
205 		for (dst = 0; dst < PROC_MAX; dst++) {
206 			/* Don't create socket for ourselves. */
207 			if (dst == PROC_PARENT)
208 				continue;
209 
210 			for (proc = 0; proc < ps->ps_instances[dst]; proc++) {
211 				pa = &ps->ps_pipes[PROC_PARENT][0];
212 				pb = &ps->ps_pipes[dst][proc];
213 				if (socketpair(AF_UNIX,
214 				    SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC,
215 				    PF_UNSPEC, fds) == -1)
216 					fatal("%s: socketpair", __func__);
217 
218 				pa->pp_pipes[dst][proc] = fds[0];
219 				pb->pp_pipes[PROC_PARENT][0] = fds[1];
220 			}
221 		}
222 
223 		/* Engage! */
224 		proc_exec(ps, procs, nproc, argc, argv);
225 		return;
226 	}
227 
228 	/* Initialize a child */
229 	for (proc = 0; proc < nproc; proc++) {
230 		if (procs[proc].p_id != proc_id)
231 			continue;
232 		p = &procs[proc];
233 		break;
234 	}
235 	if (p == NULL || p->p_init == NULL)
236 		fatalx("%s: process %d missing process initialization",
237 		    __func__, proc_id);
238 
239 	p->p_init(ps, p);
240 
241 	fatalx("failed to initiate child process");
242 }
243 
244 void
245 proc_accept(struct privsep *ps, int fd, enum privsep_procid dst,
246     unsigned int n)
247 {
248 	struct privsep_pipes	*pp = ps->ps_pp;
249 	struct imsgev		*iev;
250 
251 	if (ps->ps_ievs[dst] == NULL) {
252 #if DEBUG > 1
253 		log_debug("%s: %s src %d %d to dst %d %d not connected",
254 		    __func__, ps->ps_title[privsep_process],
255 		    privsep_process, ps->ps_instance + 1,
256 		    dst, n + 1);
257 #endif
258 		close(fd);
259 		return;
260 	}
261 
262 	if (pp->pp_pipes[dst][n] != -1) {
263 		log_warnx("%s: duplicated descriptor", __func__);
264 		close(fd);
265 		return;
266 	} else
267 		pp->pp_pipes[dst][n] = fd;
268 
269 	iev = &ps->ps_ievs[dst][n];
270 	if (imsgbuf_init(&iev->ibuf, fd) == -1)
271 		fatal("imsgbuf_init");
272 	imsgbuf_allow_fdpass(&iev->ibuf);
273 	event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev->data);
274 	event_add(&iev->ev, NULL);
275 }
276 
277 void
278 proc_setup(struct privsep *ps, struct privsep_proc *procs, unsigned int nproc)
279 {
280 	unsigned int		 i, j, src, dst, id;
281 	struct privsep_pipes	*pp;
282 
283 	/* Initialize parent title, ps_instances and procs. */
284 	ps->ps_title[PROC_PARENT] = "parent";
285 
286 	for (src = 0; src < PROC_MAX; src++)
287 		/* Default to 1 process instance */
288 		if (ps->ps_instances[src] < 1)
289 			ps->ps_instances[src] = 1;
290 
291 	for (src = 0; src < nproc; src++) {
292 		procs[src].p_ps = ps;
293 		if (procs[src].p_cb == NULL)
294 			procs[src].p_cb = proc_dispatch_null;
295 
296 		id = procs[src].p_id;
297 		ps->ps_title[id] = procs[src].p_title;
298 		if ((ps->ps_ievs[id] = calloc(ps->ps_instances[id],
299 		    sizeof(struct imsgev))) == NULL)
300 			fatal("%s: calloc", __func__);
301 
302 		/* With this set up, we are ready to call imsgbuf_init(). */
303 		for (i = 0; i < ps->ps_instances[id]; i++) {
304 			ps->ps_ievs[id][i].handler = proc_dispatch;
305 			ps->ps_ievs[id][i].events = EV_READ;
306 			ps->ps_ievs[id][i].proc = &procs[src];
307 			ps->ps_ievs[id][i].data = &ps->ps_ievs[id][i];
308 		}
309 	}
310 
311 	/*
312 	 * Allocate pipes for all process instances (incl. parent)
313 	 *
314 	 * - ps->ps_pipes: N:M mapping
315 	 * N source processes connected to M destination processes:
316 	 * [src][instances][dst][instances], for example
317 	 * [PROC_RELAY][3][PROC_CA][3]
318 	 *
319 	 * - ps->ps_pp: per-process 1:M part of ps->ps_pipes
320 	 * Each process instance has a destination array of socketpair fds:
321 	 * [dst][instances], for example
322 	 * [PROC_PARENT][0]
323 	 */
324 	for (src = 0; src < PROC_MAX; src++) {
325 		/* Allocate destination array for each process */
326 		if ((ps->ps_pipes[src] = calloc(ps->ps_instances[src],
327 		    sizeof(struct privsep_pipes))) == NULL)
328 			fatal("%s: calloc", __func__);
329 
330 		for (i = 0; i < ps->ps_instances[src]; i++) {
331 			pp = &ps->ps_pipes[src][i];
332 
333 			for (dst = 0; dst < PROC_MAX; dst++) {
334 				/* Allocate maximum fd integers */
335 				if ((pp->pp_pipes[dst] =
336 				    calloc(ps->ps_instances[dst],
337 				    sizeof(int))) == NULL)
338 					fatal("%s: calloc", __func__);
339 
340 				/* Mark fd as unused */
341 				for (j = 0; j < ps->ps_instances[dst]; j++)
342 					pp->pp_pipes[dst][j] = -1;
343 			}
344 		}
345 	}
346 
347 	ps->ps_pp = &ps->ps_pipes[privsep_process][ps->ps_instance];
348 }
349 
350 void
351 proc_kill(struct privsep *ps)
352 {
353 	char		*cause;
354 	pid_t		 pid;
355 	int		 len, status;
356 
357 	if (privsep_process != PROC_PARENT)
358 		return;
359 
360 	proc_close(ps);
361 
362 	do {
363 		pid = waitpid(WAIT_ANY, &status, 0);
364 		if (pid <= 0)
365 			continue;
366 
367 		if (WIFSIGNALED(status)) {
368 			len = asprintf(&cause, "terminated; signal %d",
369 			    WTERMSIG(status));
370 		} else if (WIFEXITED(status)) {
371 			if (WEXITSTATUS(status) != 0)
372 				len = asprintf(&cause, "exited abnormally");
373 			else
374 				len = 0;
375 		} else
376 			len = -1;
377 
378 		if (len == 0) {
379 			/* child exited OK, don't print a warning message */
380 		} else if (len != -1) {
381 			log_warnx("lost child: pid %u %s", pid, cause);
382 			free(cause);
383 		} else
384 			log_warnx("lost child: pid %u", pid);
385 	} while (pid != -1 || (pid == -1 && errno == EINTR));
386 }
387 
388 void
389 proc_open(struct privsep *ps, int src, int dst)
390 {
391 	struct privsep_pipes	*pa, *pb;
392 	struct privsep_fd	 pf;
393 	int			 fds[2];
394 	unsigned int		 i, j;
395 
396 	/* Exchange pipes between process. */
397 	for (i = 0; i < ps->ps_instances[src]; i++) {
398 		for (j = 0; j < ps->ps_instances[dst]; j++) {
399 			/* Don't create sockets for ourself. */
400 			if (src == dst && i == j)
401 				continue;
402 
403 			/* No need for CA to CA or RELAY to RELAY sockets. */
404 			if ((src == PROC_CA && dst == PROC_CA) ||
405 			    (src == PROC_RELAY && dst == PROC_RELAY))
406 				continue;
407 
408 			pa = &ps->ps_pipes[src][i];
409 			pb = &ps->ps_pipes[dst][j];
410 			if (socketpair(AF_UNIX,
411 			    SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC,
412 			    PF_UNSPEC, fds) == -1)
413 				fatal("%s: socketpair", __func__);
414 
415 			pa->pp_pipes[dst][j] = fds[0];
416 			pb->pp_pipes[src][i] = fds[1];
417 
418 			pf.pf_procid = src;
419 			pf.pf_instance = i;
420 			if (proc_compose_imsg(ps, dst, j, IMSG_CTL_PROCFD,
421 			    -1, pb->pp_pipes[src][i], &pf, sizeof(pf)) == -1)
422 				fatal("%s: proc_compose_imsg", __func__);
423 
424 			pf.pf_procid = dst;
425 			pf.pf_instance = j;
426 			if (proc_compose_imsg(ps, src, i, IMSG_CTL_PROCFD,
427 			    -1, pa->pp_pipes[dst][j], &pf, sizeof(pf)) == -1)
428 				fatal("%s: proc_compose_imsg", __func__);
429 
430 			/*
431 			 * We have to flush to send the descriptors and close
432 			 * them to avoid the fd ramp on startup.
433 			 */
434 			if (proc_flush_imsg(ps, src, i) == -1 ||
435 			    proc_flush_imsg(ps, dst, j) == -1)
436 				fatal("%s: proc_flush_imsg", __func__);
437 		}
438 	}
439 }
440 
441 void
442 proc_close(struct privsep *ps)
443 {
444 	unsigned int		 dst, n;
445 	struct privsep_pipes	*pp;
446 
447 	if (ps == NULL)
448 		return;
449 
450 	pp = ps->ps_pp;
451 
452 	for (dst = 0; dst < PROC_MAX; dst++) {
453 		if (ps->ps_ievs[dst] == NULL)
454 			continue;
455 
456 		for (n = 0; n < ps->ps_instances[dst]; n++) {
457 			if (pp->pp_pipes[dst][n] == -1)
458 				continue;
459 
460 			/* Cancel the fd, close and invalidate the fd */
461 			event_del(&(ps->ps_ievs[dst][n].ev));
462 			imsgbuf_clear(&(ps->ps_ievs[dst][n].ibuf));
463 			close(pp->pp_pipes[dst][n]);
464 			pp->pp_pipes[dst][n] = -1;
465 		}
466 		free(ps->ps_ievs[dst]);
467 	}
468 }
469 
470 void
471 proc_shutdown(struct privsep_proc *p)
472 {
473 	struct privsep	*ps = p->p_ps;
474 
475 	if (p->p_id == PROC_CONTROL && ps)
476 		control_cleanup(&ps->ps_csock);
477 
478 	if (p->p_shutdown != NULL)
479 		(*p->p_shutdown)();
480 
481 	proc_close(ps);
482 
483 	log_info("%s exiting, pid %d", p->p_title, getpid());
484 
485 	exit(0);
486 }
487 
488 void
489 proc_sig_handler(int sig, short event, void *arg)
490 {
491 	struct privsep_proc	*p = arg;
492 
493 	switch (sig) {
494 	case SIGINT:
495 	case SIGTERM:
496 		proc_shutdown(p);
497 		break;
498 	case SIGCHLD:
499 	case SIGHUP:
500 	case SIGPIPE:
501 	case SIGUSR1:
502 		/* ignore */
503 		break;
504 	default:
505 		fatalx("%s: unexpected signal", __func__);
506 		/* NOTREACHED */
507 	}
508 }
509 
510 void
511 proc_run(struct privsep *ps, struct privsep_proc *p,
512     struct privsep_proc *procs, unsigned int nproc,
513     void (*run)(struct privsep *, struct privsep_proc *, void *), void *arg)
514 {
515 	struct passwd		*pw;
516 	const char		*root;
517 	struct control_sock	*rcs;
518 
519 	log_procinit(p->p_title);
520 
521 	if (p->p_id == PROC_CONTROL && ps->ps_instance == 0) {
522 		if (control_init(ps, &ps->ps_csock) == -1)
523 			fatalx("%s: control_init", __func__);
524 		TAILQ_FOREACH(rcs, &ps->ps_rcsocks, cs_entry)
525 			if (control_init(ps, rcs) == -1)
526 				fatalx("%s: control_init", __func__);
527 	}
528 
529 	/* Use non-standard user */
530 	if (p->p_pw != NULL)
531 		pw = p->p_pw;
532 	else
533 		pw = ps->ps_pw;
534 
535 	/* Change root directory */
536 	if (p->p_chroot != NULL)
537 		root = p->p_chroot;
538 	else
539 		root = pw->pw_dir;
540 
541 	if (chroot(root) == -1)
542 		fatal("%s: chroot", __func__);
543 	if (chdir("/") == -1)
544 		fatal("%s: chdir(\"/\")", __func__);
545 
546 	privsep_process = p->p_id;
547 
548 	setproctitle("%s", p->p_title);
549 
550 	if (setgroups(1, &pw->pw_gid) ||
551 	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
552 	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
553 		fatal("%s: cannot drop privileges", __func__);
554 
555 	event_init();
556 
557 	signal_set(&ps->ps_evsigint, SIGINT, proc_sig_handler, p);
558 	signal_set(&ps->ps_evsigterm, SIGTERM, proc_sig_handler, p);
559 	signal_set(&ps->ps_evsigchld, SIGCHLD, proc_sig_handler, p);
560 	signal_set(&ps->ps_evsighup, SIGHUP, proc_sig_handler, p);
561 	signal_set(&ps->ps_evsigpipe, SIGPIPE, proc_sig_handler, p);
562 	signal_set(&ps->ps_evsigusr1, SIGUSR1, proc_sig_handler, p);
563 
564 	signal_add(&ps->ps_evsigint, NULL);
565 	signal_add(&ps->ps_evsigterm, NULL);
566 	signal_add(&ps->ps_evsigchld, NULL);
567 	signal_add(&ps->ps_evsighup, NULL);
568 	signal_add(&ps->ps_evsigpipe, NULL);
569 	signal_add(&ps->ps_evsigusr1, NULL);
570 
571 	proc_setup(ps, procs, nproc);
572 	proc_accept(ps, PROC_PARENT_SOCK_FILENO, PROC_PARENT, 0);
573 	if (p->p_id == PROC_CONTROL && ps->ps_instance == 0) {
574 		if (control_listen(&ps->ps_csock) == -1)
575 			fatalx("%s: control_listen", __func__);
576 		TAILQ_FOREACH(rcs, &ps->ps_rcsocks, cs_entry)
577 			if (control_listen(rcs) == -1)
578 				fatalx("%s: control_listen", __func__);
579 	}
580 
581 	DPRINTF("%s: %s %d/%d, pid %d", __func__, p->p_title,
582 	    ps->ps_instance + 1, ps->ps_instances[p->p_id], getpid());
583 
584 	if (run != NULL)
585 		run(ps, p, arg);
586 
587 	event_dispatch();
588 
589 	proc_shutdown(p);
590 }
591 
592 void
593 proc_dispatch(int fd, short event, void *arg)
594 {
595 	struct imsgev		*iev = arg;
596 	struct privsep_proc	*p = iev->proc;
597 	struct privsep		*ps = p->p_ps;
598 	struct imsgbuf		*ibuf;
599 	struct imsg		 imsg;
600 	ssize_t			 n;
601 	int			 verbose;
602 	const char		*title;
603 	struct privsep_fd	 pf;
604 
605 	title = ps->ps_title[privsep_process];
606 	ibuf = &iev->ibuf;
607 
608 	if (event & EV_READ) {
609 		if ((n = imsgbuf_read(ibuf)) == -1)
610 			fatal("%s: imsgbuf_read", __func__);
611 		if (n == 0) {
612 			/* this pipe is dead, so remove the event handler */
613 			event_del(&iev->ev);
614 			event_loopexit(NULL);
615 			return;
616 		}
617 	}
618 
619 	if (event & EV_WRITE) {
620 		if (imsgbuf_write(ibuf) == -1) {
621 			if (errno == EPIPE) {
622 				/* this pipe is dead, remove the handler */
623 				event_del(&iev->ev);
624 				event_loopexit(NULL);
625 				return;
626 			}
627 			fatal("%s: imsgbuf_write", __func__);
628 		}
629 	}
630 
631 	for (;;) {
632 		if ((n = imsg_get(ibuf, &imsg)) == -1)
633 			fatal("%s: imsg_get", __func__);
634 		if (n == 0)
635 			break;
636 
637 #if DEBUG > 1
638 		log_debug("%s: %s %d got imsg %d peerid %d from %s %d",
639 		    __func__, title, ps->ps_instance + 1,
640 		    imsg.hdr.type, imsg.hdr.peerid, p->p_title, imsg.hdr.pid);
641 #endif
642 
643 		/*
644 		 * Check the message with the program callback
645 		 */
646 		if ((p->p_cb)(fd, p, &imsg) == 0) {
647 			/* Message was handled by the callback, continue */
648 			imsg_free(&imsg);
649 			continue;
650 		}
651 
652 		/*
653 		 * Generic message handling
654 		 */
655 		switch (imsg.hdr.type) {
656 		case IMSG_CTL_VERBOSE:
657 			IMSG_SIZE_CHECK(&imsg, &verbose);
658 			memcpy(&verbose, imsg.data, sizeof(verbose));
659 			log_setverbose(verbose);
660 			break;
661 		case IMSG_CTL_PROCFD:
662 			IMSG_SIZE_CHECK(&imsg, &pf);
663 			memcpy(&pf, imsg.data, sizeof(pf));
664 			proc_accept(ps, imsg_get_fd(&imsg), pf.pf_procid,
665 			    pf.pf_instance);
666 			break;
667 		default:
668 			fatalx("%s: %s %d got invalid imsg %d peerid %d "
669 			    "from %s %d",
670 			    __func__, title, ps->ps_instance + 1,
671 			    imsg.hdr.type, imsg.hdr.peerid,
672 			    p->p_title, imsg.hdr.pid);
673 		}
674 		imsg_free(&imsg);
675 	}
676 	imsg_event_add(iev);
677 }
678 
679 int
680 proc_dispatch_null(int fd, struct privsep_proc *p, struct imsg *imsg)
681 {
682 	return (-1);
683 }
684 
685 /*
686  * imsg helper functions
687  */
688 
689 void
690 imsg_event_add(struct imsgev *iev)
691 {
692 	if (iev->handler == NULL) {
693 		imsgbuf_flush(&iev->ibuf);
694 		return;
695 	}
696 
697 	iev->events = EV_READ;
698 	if (imsgbuf_queuelen(&iev->ibuf) > 0)
699 		iev->events |= EV_WRITE;
700 
701 	event_del(&iev->ev);
702 	event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev->data);
703 	event_add(&iev->ev, NULL);
704 }
705 
706 int
707 imsg_compose_event(struct imsgev *iev, uint16_t type, uint32_t peerid,
708     pid_t pid, int fd, void *data, uint16_t datalen)
709 {
710 	int	ret;
711 
712 	if ((ret = imsg_compose(&iev->ibuf, type, peerid,
713 	    pid, fd, data, datalen)) == -1)
714 		return (ret);
715 	imsg_event_add(iev);
716 	return (ret);
717 }
718 
719 int
720 imsg_composev_event(struct imsgev *iev, uint16_t type, uint32_t peerid,
721     pid_t pid, int fd, const struct iovec *iov, int iovcnt)
722 {
723 	int	ret;
724 
725 	if ((ret = imsg_composev(&iev->ibuf, type, peerid,
726 	    pid, fd, iov, iovcnt)) == -1)
727 		return (ret);
728 	imsg_event_add(iev);
729 	return (ret);
730 }
731 
732 void
733 proc_range(struct privsep *ps, enum privsep_procid id, int *n, int *m)
734 {
735 	if (*n == -1) {
736 		/* Use a range of all target instances */
737 		*n = 0;
738 		*m = ps->ps_instances[id];
739 	} else {
740 		/* Use only a single slot of the specified peer process */
741 		*m = *n + 1;
742 	}
743 }
744 
745 int
746 proc_compose_imsg(struct privsep *ps, enum privsep_procid id, int n,
747     uint16_t type, uint32_t peerid, int fd, void *data, uint16_t datalen)
748 {
749 	int	 m;
750 
751 	proc_range(ps, id, &n, &m);
752 	for (; n < m; n++) {
753 		if (imsg_compose_event(&ps->ps_ievs[id][n],
754 		    type, peerid, ps->ps_instance + 1, fd, data, datalen) == -1)
755 			return (-1);
756 	}
757 
758 	return (0);
759 }
760 
761 int
762 proc_compose(struct privsep *ps, enum privsep_procid id,
763     uint16_t type, void *data, uint16_t datalen)
764 {
765 	return (proc_compose_imsg(ps, id, -1, type, -1, -1, data, datalen));
766 }
767 
768 int
769 proc_composev_imsg(struct privsep *ps, enum privsep_procid id, int n,
770     uint16_t type, uint32_t peerid, int fd, const struct iovec *iov, int iovcnt)
771 {
772 	int	 m;
773 
774 	proc_range(ps, id, &n, &m);
775 	for (; n < m; n++)
776 		if (imsg_composev_event(&ps->ps_ievs[id][n],
777 		    type, peerid, ps->ps_instance + 1, fd, iov, iovcnt) == -1)
778 			return (-1);
779 
780 	return (0);
781 }
782 
783 int
784 proc_composev(struct privsep *ps, enum privsep_procid id,
785     uint16_t type, const struct iovec *iov, int iovcnt)
786 {
787 	return (proc_composev_imsg(ps, id, -1, type, -1, -1, iov, iovcnt));
788 }
789 
790 int
791 proc_forward_imsg(struct privsep *ps, struct imsg *imsg,
792     enum privsep_procid id, int n)
793 {
794 	return (proc_compose_imsg(ps, id, n, imsg->hdr.type,
795 	    imsg->hdr.peerid, -1, imsg->data, IMSG_DATA_SIZE(imsg)));
796 }
797 
798 struct imsgbuf *
799 proc_ibuf(struct privsep *ps, enum privsep_procid id, int n)
800 {
801 	int	 m;
802 
803 	proc_range(ps, id, &n, &m);
804 	return (&ps->ps_ievs[id][n].ibuf);
805 }
806 
807 struct imsgev *
808 proc_iev(struct privsep *ps, enum privsep_procid id, int n)
809 {
810 	int	 m;
811 
812 	proc_range(ps, id, &n, &m);
813 	return (&ps->ps_ievs[id][n]);
814 }
815 
816 /* This function should only be called with care as it breaks async I/O */
817 int
818 proc_flush_imsg(struct privsep *ps, enum privsep_procid id, int n)
819 {
820 	struct imsgbuf	*ibuf;
821 	int		 m, ret = 0;
822 
823 	proc_range(ps, id, &n, &m);
824 	for (; n < m; n++) {
825 		if ((ibuf = proc_ibuf(ps, id, n)) == NULL)
826 			return (-1);
827 		if ((ret = imsgbuf_flush(ibuf)) == -1)
828 			break;
829 		imsg_event_add(&ps->ps_ievs[id][n]);
830 	}
831 
832 	return (ret);
833 }
834