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