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