xref: /openbsd/usr.sbin/relayd/proc.c (revision a1416996)
1 /*	$OpenBSD: proc.c,v 1.45 2024/01/17 10:01:24 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
proc_getid(struct privsep_proc * procs,unsigned int nproc,const char * proc_name)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
proc_exec(struct privsep * ps,struct privsep_proc * procs,unsigned int nproc,int argc,char ** argv)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
proc_connect(struct privsep * ps)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
proc_init(struct privsep * ps,struct privsep_proc * procs,unsigned int nproc,int debug,int argc,char ** argv,enum privsep_procid proc_id)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
proc_accept(struct privsep * ps,int fd,enum privsep_procid dst,unsigned int n)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
proc_setup(struct privsep * ps,struct privsep_proc * procs,unsigned int nproc)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
proc_kill(struct privsep * ps)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 || (pid == -1 && errno == EINTR));
381 }
382 
383 void
proc_open(struct privsep * ps,int src,int dst)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 			/* No need for CA to CA or RELAY to RELAY sockets. */
399 			if ((src == PROC_CA && dst == PROC_CA) ||
400 			    (src == PROC_RELAY && dst == PROC_RELAY))
401 				continue;
402 
403 			pa = &ps->ps_pipes[src][i];
404 			pb = &ps->ps_pipes[dst][j];
405 			if (socketpair(AF_UNIX,
406 			    SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC,
407 			    PF_UNSPEC, fds) == -1)
408 				fatal("%s: socketpair", __func__);
409 
410 			pa->pp_pipes[dst][j] = fds[0];
411 			pb->pp_pipes[src][i] = fds[1];
412 
413 			pf.pf_procid = src;
414 			pf.pf_instance = i;
415 			if (proc_compose_imsg(ps, dst, j, IMSG_CTL_PROCFD,
416 			    -1, pb->pp_pipes[src][i], &pf, sizeof(pf)) == -1)
417 				fatal("%s: proc_compose_imsg", __func__);
418 
419 			pf.pf_procid = dst;
420 			pf.pf_instance = j;
421 			if (proc_compose_imsg(ps, src, i, IMSG_CTL_PROCFD,
422 			    -1, pa->pp_pipes[dst][j], &pf, sizeof(pf)) == -1)
423 				fatal("%s: proc_compose_imsg", __func__);
424 
425 			/*
426 			 * We have to flush to send the descriptors and close
427 			 * them to avoid the fd ramp on startup.
428 			 */
429 			if (proc_flush_imsg(ps, src, i) == -1 ||
430 			    proc_flush_imsg(ps, dst, j) == -1)
431 				fatal("%s: imsg_flush", __func__);
432 		}
433 	}
434 }
435 
436 void
proc_close(struct privsep * ps)437 proc_close(struct privsep *ps)
438 {
439 	unsigned int		 dst, n;
440 	struct privsep_pipes	*pp;
441 
442 	if (ps == NULL)
443 		return;
444 
445 	pp = ps->ps_pp;
446 
447 	for (dst = 0; dst < PROC_MAX; dst++) {
448 		if (ps->ps_ievs[dst] == NULL)
449 			continue;
450 
451 		for (n = 0; n < ps->ps_instances[dst]; n++) {
452 			if (pp->pp_pipes[dst][n] == -1)
453 				continue;
454 
455 			/* Cancel the fd, close and invalidate the fd */
456 			event_del(&(ps->ps_ievs[dst][n].ev));
457 			imsg_clear(&(ps->ps_ievs[dst][n].ibuf));
458 			close(pp->pp_pipes[dst][n]);
459 			pp->pp_pipes[dst][n] = -1;
460 		}
461 		free(ps->ps_ievs[dst]);
462 	}
463 }
464 
465 void
proc_shutdown(struct privsep_proc * p)466 proc_shutdown(struct privsep_proc *p)
467 {
468 	struct privsep	*ps = p->p_ps;
469 
470 	if (p->p_id == PROC_CONTROL && ps)
471 		control_cleanup(&ps->ps_csock);
472 
473 	if (p->p_shutdown != NULL)
474 		(*p->p_shutdown)();
475 
476 	proc_close(ps);
477 
478 	log_info("%s exiting, pid %d", p->p_title, getpid());
479 
480 	exit(0);
481 }
482 
483 void
proc_sig_handler(int sig,short event,void * arg)484 proc_sig_handler(int sig, short event, void *arg)
485 {
486 	struct privsep_proc	*p = arg;
487 
488 	switch (sig) {
489 	case SIGINT:
490 	case SIGTERM:
491 		proc_shutdown(p);
492 		break;
493 	case SIGCHLD:
494 	case SIGHUP:
495 	case SIGPIPE:
496 	case SIGUSR1:
497 		/* ignore */
498 		break;
499 	default:
500 		fatalx("%s: unexpected signal", __func__);
501 		/* NOTREACHED */
502 	}
503 }
504 
505 void
proc_run(struct privsep * ps,struct privsep_proc * p,struct privsep_proc * procs,unsigned int nproc,void (* run)(struct privsep *,struct privsep_proc *,void *),void * arg)506 proc_run(struct privsep *ps, struct privsep_proc *p,
507     struct privsep_proc *procs, unsigned int nproc,
508     void (*run)(struct privsep *, struct privsep_proc *, void *), void *arg)
509 {
510 	struct passwd		*pw;
511 	const char		*root;
512 	struct control_sock	*rcs;
513 
514 	log_procinit(p->p_title);
515 
516 	if (p->p_id == PROC_CONTROL && ps->ps_instance == 0) {
517 		if (control_init(ps, &ps->ps_csock) == -1)
518 			fatalx("%s: control_init", __func__);
519 		TAILQ_FOREACH(rcs, &ps->ps_rcsocks, cs_entry)
520 			if (control_init(ps, rcs) == -1)
521 				fatalx("%s: control_init", __func__);
522 	}
523 
524 	/* Use non-standard user */
525 	if (p->p_pw != NULL)
526 		pw = p->p_pw;
527 	else
528 		pw = ps->ps_pw;
529 
530 	/* Change root directory */
531 	if (p->p_chroot != NULL)
532 		root = p->p_chroot;
533 	else
534 		root = pw->pw_dir;
535 
536 	if (chroot(root) == -1)
537 		fatal("%s: chroot", __func__);
538 	if (chdir("/") == -1)
539 		fatal("%s: chdir(\"/\")", __func__);
540 
541 	privsep_process = p->p_id;
542 
543 	setproctitle("%s", p->p_title);
544 
545 	if (setgroups(1, &pw->pw_gid) ||
546 	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
547 	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
548 		fatal("%s: cannot drop privileges", __func__);
549 
550 	event_init();
551 
552 	signal_set(&ps->ps_evsigint, SIGINT, proc_sig_handler, p);
553 	signal_set(&ps->ps_evsigterm, SIGTERM, proc_sig_handler, p);
554 	signal_set(&ps->ps_evsigchld, SIGCHLD, proc_sig_handler, p);
555 	signal_set(&ps->ps_evsighup, SIGHUP, proc_sig_handler, p);
556 	signal_set(&ps->ps_evsigpipe, SIGPIPE, proc_sig_handler, p);
557 	signal_set(&ps->ps_evsigusr1, SIGUSR1, proc_sig_handler, p);
558 
559 	signal_add(&ps->ps_evsigint, NULL);
560 	signal_add(&ps->ps_evsigterm, NULL);
561 	signal_add(&ps->ps_evsigchld, NULL);
562 	signal_add(&ps->ps_evsighup, NULL);
563 	signal_add(&ps->ps_evsigpipe, NULL);
564 	signal_add(&ps->ps_evsigusr1, NULL);
565 
566 	proc_setup(ps, procs, nproc);
567 	proc_accept(ps, PROC_PARENT_SOCK_FILENO, PROC_PARENT, 0);
568 	if (p->p_id == PROC_CONTROL && ps->ps_instance == 0) {
569 		if (control_listen(&ps->ps_csock) == -1)
570 			fatalx("%s: control_listen", __func__);
571 		TAILQ_FOREACH(rcs, &ps->ps_rcsocks, cs_entry)
572 			if (control_listen(rcs) == -1)
573 				fatalx("%s: control_listen", __func__);
574 	}
575 
576 	DPRINTF("%s: %s %d/%d, pid %d", __func__, p->p_title,
577 	    ps->ps_instance + 1, ps->ps_instances[p->p_id], getpid());
578 
579 	if (run != NULL)
580 		run(ps, p, arg);
581 
582 	event_dispatch();
583 
584 	proc_shutdown(p);
585 }
586 
587 void
proc_dispatch(int fd,short event,void * arg)588 proc_dispatch(int fd, short event, void *arg)
589 {
590 	struct imsgev		*iev = arg;
591 	struct privsep_proc	*p = iev->proc;
592 	struct privsep		*ps = p->p_ps;
593 	struct imsgbuf		*ibuf;
594 	struct imsg		 imsg;
595 	ssize_t			 n;
596 	int			 verbose;
597 	const char		*title;
598 	struct privsep_fd	 pf;
599 
600 	title = ps->ps_title[privsep_process];
601 	ibuf = &iev->ibuf;
602 
603 	if (event & EV_READ) {
604 		if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
605 			fatal("%s: imsg_read", __func__);
606 		if (n == 0) {
607 			/* this pipe is dead, so remove the event handler */
608 			event_del(&iev->ev);
609 			event_loopexit(NULL);
610 			return;
611 		}
612 	}
613 
614 	if (event & EV_WRITE) {
615 		if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
616 			fatal("%s: msgbuf_write", __func__);
617 		if (n == 0) {
618 			/* this pipe is dead, so remove the event handler */
619 			event_del(&iev->ev);
620 			event_loopexit(NULL);
621 			return;
622 		}
623 	}
624 
625 	for (;;) {
626 		if ((n = imsg_get(ibuf, &imsg)) == -1)
627 			fatal("%s: imsg_get", __func__);
628 		if (n == 0)
629 			break;
630 
631 #if DEBUG > 1
632 		log_debug("%s: %s %d got imsg %d peerid %d from %s %d",
633 		    __func__, title, ps->ps_instance + 1,
634 		    imsg.hdr.type, imsg.hdr.peerid, p->p_title, imsg.hdr.pid);
635 #endif
636 
637 		/*
638 		 * Check the message with the program callback
639 		 */
640 		if ((p->p_cb)(fd, p, &imsg) == 0) {
641 			/* Message was handled by the callback, continue */
642 			imsg_free(&imsg);
643 			continue;
644 		}
645 
646 		/*
647 		 * Generic message handling
648 		 */
649 		switch (imsg.hdr.type) {
650 		case IMSG_CTL_VERBOSE:
651 			IMSG_SIZE_CHECK(&imsg, &verbose);
652 			memcpy(&verbose, imsg.data, sizeof(verbose));
653 			log_setverbose(verbose);
654 			break;
655 		case IMSG_CTL_PROCFD:
656 			IMSG_SIZE_CHECK(&imsg, &pf);
657 			memcpy(&pf, imsg.data, sizeof(pf));
658 			proc_accept(ps, imsg_get_fd(&imsg), pf.pf_procid,
659 			    pf.pf_instance);
660 			break;
661 		default:
662 			fatalx("%s: %s %d got invalid imsg %d peerid %d "
663 			    "from %s %d",
664 			    __func__, title, ps->ps_instance + 1,
665 			    imsg.hdr.type, imsg.hdr.peerid,
666 			    p->p_title, imsg.hdr.pid);
667 		}
668 		imsg_free(&imsg);
669 	}
670 	imsg_event_add(iev);
671 }
672 
673 int
proc_dispatch_null(int fd,struct privsep_proc * p,struct imsg * imsg)674 proc_dispatch_null(int fd, struct privsep_proc *p, struct imsg *imsg)
675 {
676 	return (-1);
677 }
678 
679 /*
680  * imsg helper functions
681  */
682 
683 void
imsg_event_add(struct imsgev * iev)684 imsg_event_add(struct imsgev *iev)
685 {
686 	if (iev->handler == NULL) {
687 		imsg_flush(&iev->ibuf);
688 		return;
689 	}
690 
691 	iev->events = EV_READ;
692 	if (iev->ibuf.w.queued)
693 		iev->events |= EV_WRITE;
694 
695 	event_del(&iev->ev);
696 	event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev->data);
697 	event_add(&iev->ev, NULL);
698 }
699 
700 int
imsg_compose_event(struct imsgev * iev,uint16_t type,uint32_t peerid,pid_t pid,int fd,void * data,uint16_t datalen)701 imsg_compose_event(struct imsgev *iev, uint16_t type, uint32_t peerid,
702     pid_t pid, int fd, void *data, uint16_t datalen)
703 {
704 	int	ret;
705 
706 	if ((ret = imsg_compose(&iev->ibuf, type, peerid,
707 	    pid, fd, data, datalen)) == -1)
708 		return (ret);
709 	imsg_event_add(iev);
710 	return (ret);
711 }
712 
713 int
imsg_composev_event(struct imsgev * iev,uint16_t type,uint32_t peerid,pid_t pid,int fd,const struct iovec * iov,int iovcnt)714 imsg_composev_event(struct imsgev *iev, uint16_t type, uint32_t peerid,
715     pid_t pid, int fd, const struct iovec *iov, int iovcnt)
716 {
717 	int	ret;
718 
719 	if ((ret = imsg_composev(&iev->ibuf, type, peerid,
720 	    pid, fd, iov, iovcnt)) == -1)
721 		return (ret);
722 	imsg_event_add(iev);
723 	return (ret);
724 }
725 
726 void
proc_range(struct privsep * ps,enum privsep_procid id,int * n,int * m)727 proc_range(struct privsep *ps, enum privsep_procid id, int *n, int *m)
728 {
729 	if (*n == -1) {
730 		/* Use a range of all target instances */
731 		*n = 0;
732 		*m = ps->ps_instances[id];
733 	} else {
734 		/* Use only a single slot of the specified peer process */
735 		*m = *n + 1;
736 	}
737 }
738 
739 int
proc_compose_imsg(struct privsep * ps,enum privsep_procid id,int n,uint16_t type,uint32_t peerid,int fd,void * data,uint16_t datalen)740 proc_compose_imsg(struct privsep *ps, enum privsep_procid id, int n,
741     uint16_t type, uint32_t peerid, int fd, void *data, uint16_t datalen)
742 {
743 	int	 m;
744 
745 	proc_range(ps, id, &n, &m);
746 	for (; n < m; n++) {
747 		if (imsg_compose_event(&ps->ps_ievs[id][n],
748 		    type, peerid, ps->ps_instance + 1, fd, data, datalen) == -1)
749 			return (-1);
750 	}
751 
752 	return (0);
753 }
754 
755 int
proc_compose(struct privsep * ps,enum privsep_procid id,uint16_t type,void * data,uint16_t datalen)756 proc_compose(struct privsep *ps, enum privsep_procid id,
757     uint16_t type, void *data, uint16_t datalen)
758 {
759 	return (proc_compose_imsg(ps, id, -1, type, -1, -1, data, datalen));
760 }
761 
762 int
proc_composev_imsg(struct privsep * ps,enum privsep_procid id,int n,uint16_t type,uint32_t peerid,int fd,const struct iovec * iov,int iovcnt)763 proc_composev_imsg(struct privsep *ps, enum privsep_procid id, int n,
764     uint16_t type, uint32_t peerid, int fd, const struct iovec *iov, int iovcnt)
765 {
766 	int	 m;
767 
768 	proc_range(ps, id, &n, &m);
769 	for (; n < m; n++)
770 		if (imsg_composev_event(&ps->ps_ievs[id][n],
771 		    type, peerid, ps->ps_instance + 1, fd, iov, iovcnt) == -1)
772 			return (-1);
773 
774 	return (0);
775 }
776 
777 int
proc_composev(struct privsep * ps,enum privsep_procid id,uint16_t type,const struct iovec * iov,int iovcnt)778 proc_composev(struct privsep *ps, enum privsep_procid id,
779     uint16_t type, const struct iovec *iov, int iovcnt)
780 {
781 	return (proc_composev_imsg(ps, id, -1, type, -1, -1, iov, iovcnt));
782 }
783 
784 int
proc_forward_imsg(struct privsep * ps,struct imsg * imsg,enum privsep_procid id,int n)785 proc_forward_imsg(struct privsep *ps, struct imsg *imsg,
786     enum privsep_procid id, int n)
787 {
788 	return (proc_compose_imsg(ps, id, n, imsg->hdr.type,
789 	    imsg->hdr.peerid, -1, imsg->data, IMSG_DATA_SIZE(imsg)));
790 }
791 
792 struct imsgbuf *
proc_ibuf(struct privsep * ps,enum privsep_procid id,int n)793 proc_ibuf(struct privsep *ps, enum privsep_procid id, int n)
794 {
795 	int	 m;
796 
797 	proc_range(ps, id, &n, &m);
798 	return (&ps->ps_ievs[id][n].ibuf);
799 }
800 
801 struct imsgev *
proc_iev(struct privsep * ps,enum privsep_procid id,int n)802 proc_iev(struct privsep *ps, enum privsep_procid id, int n)
803 {
804 	int	 m;
805 
806 	proc_range(ps, id, &n, &m);
807 	return (&ps->ps_ievs[id][n]);
808 }
809 
810 /* This function should only be called with care as it breaks async I/O */
811 int
proc_flush_imsg(struct privsep * ps,enum privsep_procid id,int n)812 proc_flush_imsg(struct privsep *ps, enum privsep_procid id, int n)
813 {
814 	struct imsgbuf	*ibuf;
815 	int		 m, ret = 0;
816 
817 	proc_range(ps, id, &n, &m);
818 	for (; n < m; n++) {
819 		if ((ibuf = proc_ibuf(ps, id, n)) == NULL)
820 			return (-1);
821 		do {
822 			ret = imsg_flush(ibuf);
823 		} while (ret == -1 && errno == EAGAIN);
824 		if (ret == -1)
825 			break;
826 		imsg_event_add(&ps->ps_ievs[id][n]);
827 	}
828 
829 	return (ret);
830 }
831