xref: /openbsd-src/usr.sbin/httpd/proc.c (revision 7c0ec4b8992567abb1e1536622dc789a9a39d9f1)
1 /*	$OpenBSD: proc.c,v 1.45 2024/04/09 15:48:01 tobhe 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 "httpd.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 			imsg_init(&iev->ibuf, ps->ps_pp->pp_pipes[dst][inst]);
159 			event_set(&iev->ev, iev->ibuf.fd, iev->events,
160 			    iev->handler, iev->data);
161 			event_add(&iev->ev, NULL);
162 		}
163 	}
164 
165 	/* Distribute the socketpair()s for everyone. */
166 	for (src = 0; src < PROC_MAX; src++)
167 		for (dst = src; dst < PROC_MAX; dst++) {
168 			/* Parent already distributed its fds. */
169 			if (src == PROC_PARENT || dst == PROC_PARENT)
170 				continue;
171 
172 			proc_open(ps, src, dst);
173 		}
174 }
175 
176 void
177 proc_init(struct privsep *ps, struct privsep_proc *procs, unsigned int nproc,
178     int debug, int argc, char **argv, enum privsep_procid proc_id)
179 {
180 	struct privsep_proc	*p = NULL;
181 	struct privsep_pipes	*pa, *pb;
182 	unsigned int		 proc;
183 	unsigned int		 dst;
184 	int			 fds[2];
185 
186 	/* Don't initiate anything if we are not really going to run. */
187 	if (ps->ps_noaction)
188 		return;
189 
190 	if (proc_id == PROC_PARENT) {
191 		privsep_process = PROC_PARENT;
192 		proc_setup(ps, procs, nproc);
193 
194 		if (!debug && daemon(1, 0) == -1)
195 			fatal("failed to daemonize");
196 
197 		/*
198 		 * Create the children sockets so we can use them
199 		 * to distribute the rest of the socketpair()s using
200 		 * proc_connect() later.
201 		 */
202 		for (dst = 0; dst < PROC_MAX; dst++) {
203 			/* Don't create socket for ourselves. */
204 			if (dst == PROC_PARENT)
205 				continue;
206 
207 			for (proc = 0; proc < ps->ps_instances[dst]; proc++) {
208 				pa = &ps->ps_pipes[PROC_PARENT][0];
209 				pb = &ps->ps_pipes[dst][proc];
210 				if (socketpair(AF_UNIX,
211 				    SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC,
212 				    PF_UNSPEC, fds) == -1)
213 					fatal("%s: socketpair", __func__);
214 
215 				pa->pp_pipes[dst][proc] = fds[0];
216 				pb->pp_pipes[PROC_PARENT][0] = fds[1];
217 			}
218 		}
219 
220 		/* Engage! */
221 		proc_exec(ps, procs, nproc, argc, argv);
222 		return;
223 	}
224 
225 	/* Initialize a child */
226 	for (proc = 0; proc < nproc; proc++) {
227 		if (procs[proc].p_id != proc_id)
228 			continue;
229 		p = &procs[proc];
230 		break;
231 	}
232 	if (p == NULL || p->p_init == NULL)
233 		fatalx("%s: process %d missing process initialization",
234 		    __func__, proc_id);
235 
236 	p->p_init(ps, p);
237 
238 	fatalx("failed to initiate child process");
239 }
240 
241 void
242 proc_accept(struct privsep *ps, int fd, enum privsep_procid dst,
243     unsigned int n)
244 {
245 	struct privsep_pipes	*pp = ps->ps_pp;
246 	struct imsgev		*iev;
247 
248 	if (ps->ps_ievs[dst] == NULL) {
249 #if DEBUG > 1
250 		log_debug("%s: %s src %d %d to dst %d %d not connected",
251 		    __func__, ps->ps_title[privsep_process],
252 		    privsep_process, ps->ps_instance + 1,
253 		    dst, n + 1);
254 #endif
255 		close(fd);
256 		return;
257 	}
258 
259 	if (pp->pp_pipes[dst][n] != -1) {
260 		log_warnx("%s: duplicated descriptor", __func__);
261 		close(fd);
262 		return;
263 	} else
264 		pp->pp_pipes[dst][n] = fd;
265 
266 	iev = &ps->ps_ievs[dst][n];
267 	imsg_init(&iev->ibuf, fd);
268 	event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev->data);
269 	event_add(&iev->ev, NULL);
270 }
271 
272 void
273 proc_setup(struct privsep *ps, struct privsep_proc *procs, unsigned int nproc)
274 {
275 	unsigned int		 i, j, src, dst, id;
276 	struct privsep_pipes	*pp;
277 
278 	/* Initialize parent title, ps_instances and procs. */
279 	ps->ps_title[PROC_PARENT] = "parent";
280 
281 	for (src = 0; src < PROC_MAX; src++)
282 		/* Default to 1 process instance */
283 		if (ps->ps_instances[src] < 1)
284 			ps->ps_instances[src] = 1;
285 
286 	for (src = 0; src < nproc; src++) {
287 		procs[src].p_ps = ps;
288 		if (procs[src].p_cb == NULL)
289 			procs[src].p_cb = proc_dispatch_null;
290 
291 		id = procs[src].p_id;
292 		ps->ps_title[id] = procs[src].p_title;
293 		if ((ps->ps_ievs[id] = calloc(ps->ps_instances[id],
294 		    sizeof(struct imsgev))) == NULL)
295 			fatal("%s: calloc", __func__);
296 
297 		/* With this set up, we are ready to call imsg_init(). */
298 		for (i = 0; i < ps->ps_instances[id]; i++) {
299 			ps->ps_ievs[id][i].handler = proc_dispatch;
300 			ps->ps_ievs[id][i].events = EV_READ;
301 			ps->ps_ievs[id][i].proc = &procs[src];
302 			ps->ps_ievs[id][i].data = &ps->ps_ievs[id][i];
303 		}
304 	}
305 
306 	/*
307 	 * Allocate pipes for all process instances (incl. parent)
308 	 *
309 	 * - ps->ps_pipes: N:M mapping
310 	 * N source processes connected to M destination processes:
311 	 * [src][instances][dst][instances], for example
312 	 * [PROC_RELAY][3][PROC_CA][3]
313 	 *
314 	 * - ps->ps_pp: per-process 1:M part of ps->ps_pipes
315 	 * Each process instance has a destination array of socketpair fds:
316 	 * [dst][instances], for example
317 	 * [PROC_PARENT][0]
318 	 */
319 	for (src = 0; src < PROC_MAX; src++) {
320 		/* Allocate destination array for each process */
321 		if ((ps->ps_pipes[src] = calloc(ps->ps_instances[src],
322 		    sizeof(struct privsep_pipes))) == NULL)
323 			fatal("%s: calloc", __func__);
324 
325 		for (i = 0; i < ps->ps_instances[src]; i++) {
326 			pp = &ps->ps_pipes[src][i];
327 
328 			for (dst = 0; dst < PROC_MAX; dst++) {
329 				/* Allocate maximum fd integers */
330 				if ((pp->pp_pipes[dst] =
331 				    calloc(ps->ps_instances[dst],
332 				    sizeof(int))) == NULL)
333 					fatal("%s: calloc", __func__);
334 
335 				/* Mark fd as unused */
336 				for (j = 0; j < ps->ps_instances[dst]; j++)
337 					pp->pp_pipes[dst][j] = -1;
338 			}
339 		}
340 	}
341 
342 	ps->ps_pp = &ps->ps_pipes[privsep_process][ps->ps_instance];
343 }
344 
345 void
346 proc_kill(struct privsep *ps)
347 {
348 	char		*cause;
349 	pid_t		 pid;
350 	int		 len, status;
351 
352 	if (privsep_process != PROC_PARENT)
353 		return;
354 
355 	proc_close(ps);
356 
357 	do {
358 		pid = waitpid(WAIT_ANY, &status, 0);
359 		if (pid <= 0)
360 			continue;
361 
362 		if (WIFSIGNALED(status)) {
363 			len = asprintf(&cause, "terminated; signal %d",
364 			    WTERMSIG(status));
365 		} else if (WIFEXITED(status)) {
366 			if (WEXITSTATUS(status) != 0)
367 				len = asprintf(&cause, "exited abnormally");
368 			else
369 				len = 0;
370 		} else
371 			len = -1;
372 
373 		if (len == 0) {
374 			/* child exited OK, don't print a warning message */
375 		} else if (len != -1) {
376 			log_warnx("lost child: pid %u %s", pid, cause);
377 			free(cause);
378 		} else
379 			log_warnx("lost child: pid %u", pid);
380 	} while (pid != -1 || errno == EINTR);
381 }
382 
383 void
384 proc_open(struct privsep *ps, int src, int dst)
385 {
386 	struct privsep_pipes	*pa, *pb;
387 	struct privsep_fd	 pf;
388 	int			 fds[2];
389 	unsigned int		 i, j;
390 
391 	/* Exchange pipes between process. */
392 	for (i = 0; i < ps->ps_instances[src]; i++) {
393 		for (j = 0; j < ps->ps_instances[dst]; j++) {
394 			/* Don't create sockets for ourself. */
395 			if (src == dst && i == j)
396 				continue;
397 
398 			/* Servers don't talk to each other. */
399 			if (src == PROC_SERVER && dst == PROC_SERVER)
400 				continue;
401 
402 			pa = &ps->ps_pipes[src][i];
403 			pb = &ps->ps_pipes[dst][j];
404 			if (socketpair(AF_UNIX,
405 			    SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC,
406 			    PF_UNSPEC, fds) == -1)
407 				fatal("%s: socketpair", __func__);
408 
409 			pa->pp_pipes[dst][j] = fds[0];
410 			pb->pp_pipes[src][i] = fds[1];
411 
412 			pf.pf_procid = src;
413 			pf.pf_instance = i;
414 			if (proc_compose_imsg(ps, dst, j, IMSG_CTL_PROCFD,
415 			    -1, pb->pp_pipes[src][i], &pf, sizeof(pf)) == -1)
416 				fatal("%s: proc_compose_imsg", __func__);
417 
418 			pf.pf_procid = dst;
419 			pf.pf_instance = j;
420 			if (proc_compose_imsg(ps, src, i, IMSG_CTL_PROCFD,
421 			    -1, pa->pp_pipes[dst][j], &pf, sizeof(pf)) == -1)
422 				fatal("%s: proc_compose_imsg", __func__);
423 
424 			/*
425 			 * We have to flush to send the descriptors and close
426 			 * them to avoid the fd ramp on startup.
427 			 */
428 			if (proc_flush_imsg(ps, src, i) == -1 ||
429 			    proc_flush_imsg(ps, dst, j) == -1)
430 				fatal("%s: imsg_flush", __func__);
431 		}
432 	}
433 }
434 
435 void
436 proc_close(struct privsep *ps)
437 {
438 	unsigned int		 dst, n;
439 	struct privsep_pipes	*pp;
440 
441 	if (ps == NULL)
442 		return;
443 
444 	pp = ps->ps_pp;
445 
446 	for (dst = 0; dst < PROC_MAX; dst++) {
447 		if (ps->ps_ievs[dst] == NULL)
448 			continue;
449 
450 		for (n = 0; n < ps->ps_instances[dst]; n++) {
451 			if (pp->pp_pipes[dst][n] == -1)
452 				continue;
453 
454 			/* Cancel the fd, close and invalidate the fd */
455 			event_del(&(ps->ps_ievs[dst][n].ev));
456 			imsg_clear(&(ps->ps_ievs[dst][n].ibuf));
457 			close(pp->pp_pipes[dst][n]);
458 			pp->pp_pipes[dst][n] = -1;
459 		}
460 		free(ps->ps_ievs[dst]);
461 	}
462 }
463 
464 void
465 proc_shutdown(struct privsep_proc *p)
466 {
467 	struct privsep	*ps = p->p_ps;
468 
469 	if (p->p_id == PROC_CONTROL && ps)
470 		control_cleanup(&ps->ps_csock);
471 
472 	if (p->p_shutdown != NULL)
473 		(*p->p_shutdown)();
474 
475 	proc_close(ps);
476 
477 	log_info("%s exiting, pid %d", p->p_title, getpid());
478 
479 	exit(0);
480 }
481 
482 void
483 proc_sig_handler(int sig, short event, void *arg)
484 {
485 	struct privsep_proc	*p = arg;
486 
487 	switch (sig) {
488 	case SIGINT:
489 	case SIGTERM:
490 		proc_shutdown(p);
491 		break;
492 	case SIGCHLD:
493 	case SIGHUP:
494 	case SIGPIPE:
495 	case SIGUSR1:
496 		/* ignore */
497 		break;
498 	default:
499 		fatalx("%s: unexpected signal", __func__);
500 		/* NOTREACHED */
501 	}
502 }
503 
504 void
505 proc_run(struct privsep *ps, struct privsep_proc *p,
506     struct privsep_proc *procs, unsigned int nproc,
507     void (*run)(struct privsep *, struct privsep_proc *, void *), void *arg)
508 {
509 	struct passwd		*pw;
510 	const char		*root;
511 	struct control_sock	*rcs;
512 
513 	log_procinit(p->p_title);
514 
515 	if (p->p_id == PROC_CONTROL && ps->ps_instance == 0) {
516 		if (control_init(ps, &ps->ps_csock) == -1)
517 			fatalx("%s: control_init", __func__);
518 		TAILQ_FOREACH(rcs, &ps->ps_rcsocks, cs_entry)
519 			if (control_init(ps, rcs) == -1)
520 				fatalx("%s: control_init", __func__);
521 	}
522 
523 	/* Use non-standard user */
524 	if (p->p_pw != NULL)
525 		pw = p->p_pw;
526 	else
527 		pw = ps->ps_pw;
528 
529 	/* Change root directory */
530 	if (p->p_chroot != NULL)
531 		root = p->p_chroot;
532 	else
533 		root = pw->pw_dir;
534 
535 	if (chroot(root) == -1)
536 		fatal("%s: chroot", __func__);
537 	if (chdir("/") == -1)
538 		fatal("%s: chdir(\"/\")", __func__);
539 
540 	privsep_process = p->p_id;
541 
542 	setproctitle("%s", p->p_title);
543 
544 	if (setgroups(1, &pw->pw_gid) ||
545 	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
546 	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
547 		fatal("%s: cannot drop privileges", __func__);
548 
549 	event_init();
550 
551 	signal_set(&ps->ps_evsigint, SIGINT, proc_sig_handler, p);
552 	signal_set(&ps->ps_evsigterm, SIGTERM, proc_sig_handler, p);
553 	signal_set(&ps->ps_evsigchld, SIGCHLD, proc_sig_handler, p);
554 	signal_set(&ps->ps_evsighup, SIGHUP, proc_sig_handler, p);
555 	signal_set(&ps->ps_evsigpipe, SIGPIPE, proc_sig_handler, p);
556 	signal_set(&ps->ps_evsigusr1, SIGUSR1, proc_sig_handler, p);
557 
558 	signal_add(&ps->ps_evsigint, NULL);
559 	signal_add(&ps->ps_evsigterm, NULL);
560 	signal_add(&ps->ps_evsigchld, NULL);
561 	signal_add(&ps->ps_evsighup, NULL);
562 	signal_add(&ps->ps_evsigpipe, NULL);
563 	signal_add(&ps->ps_evsigusr1, NULL);
564 
565 	proc_setup(ps, procs, nproc);
566 	proc_accept(ps, PROC_PARENT_SOCK_FILENO, PROC_PARENT, 0);
567 	if (p->p_id == PROC_CONTROL && ps->ps_instance == 0) {
568 		if (control_listen(&ps->ps_csock) == -1)
569 			fatalx("%s: control_listen", __func__);
570 		TAILQ_FOREACH(rcs, &ps->ps_rcsocks, cs_entry)
571 			if (control_listen(rcs) == -1)
572 				fatalx("%s: control_listen", __func__);
573 	}
574 
575 	DPRINTF("%s: %s %d/%d, pid %d", __func__, p->p_title,
576 	    ps->ps_instance + 1, ps->ps_instances[p->p_id], getpid());
577 
578 	if (run != NULL)
579 		run(ps, p, arg);
580 
581 	event_dispatch();
582 
583 	proc_shutdown(p);
584 }
585 
586 void
587 proc_dispatch(int fd, short event, void *arg)
588 {
589 	struct imsgev		*iev = arg;
590 	struct privsep_proc	*p = iev->proc;
591 	struct privsep		*ps = p->p_ps;
592 	struct imsgbuf		*ibuf;
593 	struct imsg		 imsg;
594 	ssize_t			 n;
595 	int			 verbose;
596 	const char		*title;
597 	struct privsep_fd	 pf;
598 
599 	title = ps->ps_title[privsep_process];
600 	ibuf = &iev->ibuf;
601 
602 	if (event & EV_READ) {
603 		if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
604 			fatal("%s: imsg_read", __func__);
605 		if (n == 0) {
606 			/* this pipe is dead, so remove the event handler */
607 			event_del(&iev->ev);
608 			event_loopexit(NULL);
609 			return;
610 		}
611 	}
612 
613 	if (event & EV_WRITE) {
614 		if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
615 			fatal("%s: msgbuf_write", __func__);
616 		if (n == 0) {
617 			/* this pipe is dead, so remove the event handler */
618 			event_del(&iev->ev);
619 			event_loopexit(NULL);
620 			return;
621 		}
622 	}
623 
624 	for (;;) {
625 		if ((n = imsg_get(ibuf, &imsg)) == -1)
626 			fatal("%s: imsg_get", __func__);
627 		if (n == 0)
628 			break;
629 
630 #if DEBUG > 1
631 		log_debug("%s: %s %d got imsg %d peerid %d from %s %d",
632 		    __func__, title, ps->ps_instance + 1,
633 		    imsg.hdr.type, imsg.hdr.peerid, p->p_title, imsg.hdr.pid);
634 #endif
635 
636 		/*
637 		 * Check the message with the program callback
638 		 */
639 		if ((p->p_cb)(fd, p, &imsg) == 0) {
640 			/* Message was handled by the callback, continue */
641 			imsg_free(&imsg);
642 			continue;
643 		}
644 
645 		/*
646 		 * Generic message handling
647 		 */
648 		switch (imsg.hdr.type) {
649 		case IMSG_CTL_VERBOSE:
650 			IMSG_SIZE_CHECK(&imsg, &verbose);
651 			memcpy(&verbose, imsg.data, sizeof(verbose));
652 			log_setverbose(verbose);
653 			break;
654 		case IMSG_CTL_PROCFD:
655 			IMSG_SIZE_CHECK(&imsg, &pf);
656 			memcpy(&pf, imsg.data, sizeof(pf));
657 			proc_accept(ps, imsg_get_fd(&imsg), pf.pf_procid,
658 			    pf.pf_instance);
659 			break;
660 		default:
661 			fatalx("%s: %s %d got invalid imsg %d peerid %d "
662 			    "from %s %d",
663 			    __func__, title, ps->ps_instance + 1,
664 			    imsg.hdr.type, imsg.hdr.peerid,
665 			    p->p_title, imsg.hdr.pid);
666 		}
667 		imsg_free(&imsg);
668 	}
669 	imsg_event_add(iev);
670 }
671 
672 int
673 proc_dispatch_null(int fd, struct privsep_proc *p, struct imsg *imsg)
674 {
675 	return (-1);
676 }
677 
678 /*
679  * imsg helper functions
680  */
681 
682 void
683 imsg_event_add(struct imsgev *iev)
684 {
685 	if (iev->handler == NULL) {
686 		imsg_flush(&iev->ibuf);
687 		return;
688 	}
689 
690 	iev->events = EV_READ;
691 	if (iev->ibuf.w.queued)
692 		iev->events |= EV_WRITE;
693 
694 	event_del(&iev->ev);
695 	event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev->data);
696 	event_add(&iev->ev, NULL);
697 }
698 
699 int
700 imsg_compose_event(struct imsgev *iev, uint16_t type, uint32_t peerid,
701     pid_t pid, int fd, void *data, uint16_t datalen)
702 {
703 	int	ret;
704 
705 	if ((ret = imsg_compose(&iev->ibuf, type, peerid,
706 	    pid, fd, data, datalen)) == -1)
707 		return (ret);
708 	imsg_event_add(iev);
709 	return (ret);
710 }
711 
712 int
713 imsg_composev_event(struct imsgev *iev, uint16_t type, uint32_t peerid,
714     pid_t pid, int fd, const struct iovec *iov, int iovcnt)
715 {
716 	int	ret;
717 
718 	if ((ret = imsg_composev(&iev->ibuf, type, peerid,
719 	    pid, fd, iov, iovcnt)) == -1)
720 		return (ret);
721 	imsg_event_add(iev);
722 	return (ret);
723 }
724 
725 void
726 proc_range(struct privsep *ps, enum privsep_procid id, int *n, int *m)
727 {
728 	if (*n == -1) {
729 		/* Use a range of all target instances */
730 		*n = 0;
731 		*m = ps->ps_instances[id];
732 	} else {
733 		/* Use only a single slot of the specified peer process */
734 		*m = *n + 1;
735 	}
736 }
737 
738 int
739 proc_compose_imsg(struct privsep *ps, enum privsep_procid id, int n,
740     uint16_t type, uint32_t peerid, int fd, void *data, uint16_t datalen)
741 {
742 	int	 m;
743 
744 	proc_range(ps, id, &n, &m);
745 	for (; n < m; n++) {
746 		if (imsg_compose_event(&ps->ps_ievs[id][n],
747 		    type, peerid, ps->ps_instance + 1, fd, data, datalen) == -1)
748 			return (-1);
749 	}
750 
751 	return (0);
752 }
753 
754 int
755 proc_compose(struct privsep *ps, enum privsep_procid id,
756     uint16_t type, void *data, uint16_t datalen)
757 {
758 	return (proc_compose_imsg(ps, id, -1, type, -1, -1, data, datalen));
759 }
760 
761 int
762 proc_composev_imsg(struct privsep *ps, enum privsep_procid id, int n,
763     uint16_t type, uint32_t peerid, int fd, const struct iovec *iov, int iovcnt)
764 {
765 	int	 m;
766 
767 	proc_range(ps, id, &n, &m);
768 	for (; n < m; n++)
769 		if (imsg_composev_event(&ps->ps_ievs[id][n],
770 		    type, peerid, ps->ps_instance + 1, fd, iov, iovcnt) == -1)
771 			return (-1);
772 
773 	return (0);
774 }
775 
776 int
777 proc_composev(struct privsep *ps, enum privsep_procid id,
778     uint16_t type, const struct iovec *iov, int iovcnt)
779 {
780 	return (proc_composev_imsg(ps, id, -1, type, -1, -1, iov, iovcnt));
781 }
782 
783 int
784 proc_forward_imsg(struct privsep *ps, struct imsg *imsg,
785     enum privsep_procid id, int n)
786 {
787 	return (proc_compose_imsg(ps, id, n, imsg->hdr.type,
788 	    imsg->hdr.peerid, -1, imsg->data, IMSG_DATA_SIZE(imsg)));
789 }
790 
791 struct imsgbuf *
792 proc_ibuf(struct privsep *ps, enum privsep_procid id, int n)
793 {
794 	int	 m;
795 
796 	proc_range(ps, id, &n, &m);
797 	return (&ps->ps_ievs[id][n].ibuf);
798 }
799 
800 struct imsgev *
801 proc_iev(struct privsep *ps, enum privsep_procid id, int n)
802 {
803 	int	 m;
804 
805 	proc_range(ps, id, &n, &m);
806 	return (&ps->ps_ievs[id][n]);
807 }
808 
809 /* This function should only be called with care as it breaks async I/O */
810 int
811 proc_flush_imsg(struct privsep *ps, enum privsep_procid id, int n)
812 {
813 	struct imsgbuf	*ibuf;
814 	int		 m, ret = 0;
815 
816 	proc_range(ps, id, &n, &m);
817 	for (; n < m; n++) {
818 		if ((ibuf = proc_ibuf(ps, id, n)) == NULL)
819 			return (-1);
820 		do {
821 			ret = imsg_flush(ibuf);
822 		} while (ret == -1 && errno == EAGAIN);
823 		if (ret == -1)
824 			break;
825 		imsg_event_add(&ps->ps_ievs[id][n]);
826 	}
827 
828 	return (ret);
829 }
830