xref: /openbsd-src/usr.sbin/smtpd/smtpd.c (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
1 /*	$OpenBSD: smtpd.c,v 1.286 2016/09/08 12:06:43 eric Exp $	*/
2 
3 /*
4  * Copyright (c) 2008 Gilles Chehade <gilles@poolp.org>
5  * Copyright (c) 2008 Pierre-Yves Ritschard <pyr@openbsd.org>
6  * Copyright (c) 2009 Jacek Masiulaniec <jacekm@dobremiasto.net>
7  *
8  * Permission to use, copy, modify, and distribute this software for any
9  * purpose with or without fee is hereby granted, provided that the above
10  * copyright notice and this permission notice appear in all copies.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19  */
20 
21 #include <sys/types.h>
22 #include <sys/queue.h>
23 #include <sys/tree.h>
24 #include <sys/socket.h>
25 #include <sys/wait.h>
26 #include <sys/stat.h>
27 #include <sys/uio.h>
28 #include <sys/mman.h>
29 
30 #include <bsd_auth.h>
31 #include <dirent.h>
32 #include <err.h>
33 #include <errno.h>
34 #include <event.h>
35 #include <fcntl.h>
36 #include <fts.h>
37 #include <imsg.h>
38 #include <inttypes.h>
39 #include <login_cap.h>
40 #include <paths.h>
41 #include <poll.h>
42 #include <pwd.h>
43 #include <signal.h>
44 #include <stdio.h>
45 #include <limits.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <time.h>
49 #include <unistd.h>
50 
51 #include <openssl/ssl.h>
52 #include <openssl/evp.h>
53 
54 #include "smtpd.h"
55 #include "log.h"
56 #include "ssl.h"
57 
58 #define SMTPD_MAXARG 32
59 
60 static void parent_imsg(struct mproc *, struct imsg *);
61 static void usage(void);
62 static int smtpd(void);
63 static void parent_shutdown(void);
64 static void parent_send_config(int, short, void *);
65 static void parent_send_config_lka(void);
66 static void parent_send_config_pony(void);
67 static void parent_send_config_ca(void);
68 static void parent_sig_handler(int, short, void *);
69 static void forkmda(struct mproc *, uint64_t, struct deliver *);
70 static int parent_forward_open(char *, char *, uid_t, gid_t);
71 static struct child *child_add(pid_t, int, const char *);
72 static struct mproc *start_child(int, char **, char *);
73 static struct mproc *setup_peer(enum smtp_proc_type, pid_t, int);
74 static void setup_peers(struct mproc *, struct mproc *);
75 static void setup_done(struct mproc *);
76 static void setup_proc(void);
77 static struct mproc *setup_peer(enum smtp_proc_type, pid_t, int);
78 static int imsg_wait(struct imsgbuf *, struct imsg *, int);
79 
80 static void	offline_scan(int, short, void *);
81 static int	offline_add(char *);
82 static void	offline_done(void);
83 static int	offline_enqueue(char *);
84 
85 static void	purge_task(void);
86 static int	parent_auth_user(const char *, const char *);
87 static void	load_pki_tree(void);
88 static void	load_pki_keys(void);
89 
90 enum child_type {
91 	CHILD_DAEMON,
92 	CHILD_MDA,
93 	CHILD_ENQUEUE_OFFLINE,
94 };
95 
96 struct child {
97 	pid_t			 pid;
98 	enum child_type		 type;
99 	const char		*title;
100 	int			 mda_out;
101 	uint64_t		 mda_id;
102 	char			*path;
103 	char			*cause;
104 };
105 
106 struct offline {
107 	TAILQ_ENTRY(offline)	 entry;
108 	char			*path;
109 };
110 
111 #define OFFLINE_READMAX		20
112 #define OFFLINE_QUEUEMAX	5
113 static size_t			offline_running = 0;
114 TAILQ_HEAD(, offline)		offline_q;
115 
116 static struct event		config_ev;
117 static struct event		offline_ev;
118 static struct timeval		offline_timeout;
119 
120 static pid_t			purge_pid = -1;
121 
122 extern char	**environ;
123 void		(*imsg_callback)(struct mproc *, struct imsg *);
124 
125 enum smtp_proc_type	smtpd_process;
126 
127 struct smtpd	*env = NULL;
128 
129 struct mproc	*p_control = NULL;
130 struct mproc	*p_lka = NULL;
131 struct mproc	*p_parent = NULL;
132 struct mproc	*p_queue = NULL;
133 struct mproc	*p_scheduler = NULL;
134 struct mproc	*p_pony = NULL;
135 struct mproc	*p_ca = NULL;
136 
137 const char	*backend_queue = "fs";
138 const char	*backend_scheduler = "ramqueue";
139 const char	*backend_stat = "ram";
140 
141 int	profiling = 0;
142 int	verbose = 0;
143 int	debug = 0;
144 int	foreground = 0;
145 int	foreground_log = 0;
146 int	control_socket = -1;
147 
148 struct tree	 children;
149 
150 static void
151 parent_imsg(struct mproc *p, struct imsg *imsg)
152 {
153 	struct forward_req	*fwreq;
154 	struct deliver		 deliver;
155 	struct child		*c;
156 	struct msg		 m;
157 	const void		*data;
158 	const char		*username, *password, *cause;
159 	uint64_t		 reqid;
160 	size_t			 sz;
161 	void			*i;
162 	int			 fd, n, v, ret;
163 
164 	if (imsg == NULL)
165 		fatalx("process %s socket closed", p->name);
166 
167 	if (p->proc == PROC_LKA) {
168 		switch (imsg->hdr.type) {
169 		case IMSG_LKA_OPEN_FORWARD:
170 			CHECK_IMSG_DATA_SIZE(imsg, sizeof *fwreq);
171 			fwreq = imsg->data;
172 			fd = parent_forward_open(fwreq->user, fwreq->directory,
173 			    fwreq->uid, fwreq->gid);
174 			fwreq->status = 0;
175 			if (fd == -1 && errno != ENOENT) {
176 				if (errno == EAGAIN)
177 					fwreq->status = -1;
178 			}
179 			else
180 				fwreq->status = 1;
181 			m_compose(p, IMSG_LKA_OPEN_FORWARD, 0, 0, fd,
182 			    fwreq, sizeof *fwreq);
183 			return;
184 
185 		case IMSG_LKA_AUTHENTICATE:
186 			/*
187 			 * If we reached here, it means we want root to lookup
188 			 * system user.
189 			 */
190 			m_msg(&m, imsg);
191 			m_get_id(&m, &reqid);
192 			m_get_string(&m, &username);
193 			m_get_string(&m, &password);
194 			m_end(&m);
195 
196 			ret = parent_auth_user(username, password);
197 
198 			m_create(p, IMSG_LKA_AUTHENTICATE, 0, 0, -1);
199 			m_add_id(p, reqid);
200 			m_add_int(p, ret);
201 			m_close(p);
202 			return;
203 		}
204 	}
205 
206 	if (p->proc == PROC_PONY) {
207 		switch (imsg->hdr.type) {
208 		case IMSG_MDA_FORK:
209 			m_msg(&m, imsg);
210 			m_get_id(&m, &reqid);
211 			m_get_data(&m, &data, &sz);
212 			m_end(&m);
213 			if (sz != sizeof(deliver))
214 				fatalx("expected deliver");
215 			memmove(&deliver, data, sz);
216 			forkmda(p, reqid, &deliver);
217 			return;
218 
219 		case IMSG_MDA_KILL:
220 			m_msg(&m, imsg);
221 			m_get_id(&m, &reqid);
222 			m_get_string(&m, &cause);
223 			m_end(&m);
224 
225 			i = NULL;
226 			while ((n = tree_iter(&children, &i, NULL, (void**)&c)))
227 				if (c->type == CHILD_MDA &&
228 				    c->mda_id == reqid &&
229 				    c->cause == NULL)
230 					break;
231 			if (!n) {
232 				log_debug("debug: smtpd: "
233 				    "kill request: proc not found");
234 				return;
235 			}
236 
237 			c->cause = xstrdup(cause, "parent_imsg");
238 			log_debug("debug: smtpd: kill requested for %u: %s",
239 			    c->pid, c->cause);
240 			kill(c->pid, SIGTERM);
241 			return;
242 		}
243 	}
244 
245 	if (p->proc == PROC_CONTROL) {
246 		switch (imsg->hdr.type) {
247 		case IMSG_CTL_VERBOSE:
248 			m_msg(&m, imsg);
249 			m_get_int(&m, &v);
250 			m_end(&m);
251 			log_verbose(v);
252 			return;
253 
254 		case IMSG_CTL_PROFILE:
255 			m_msg(&m, imsg);
256 			m_get_int(&m, &v);
257 			m_end(&m);
258 			profiling = v;
259 			return;
260 		}
261 	}
262 
263 	errx(1, "parent_imsg: unexpected %s imsg from %s",
264 	    imsg_to_str(imsg->hdr.type), proc_title(p->proc));
265 }
266 
267 static void
268 usage(void)
269 {
270 	extern char	*__progname;
271 
272 	fprintf(stderr, "usage: %s [-dhnv] [-D macro=value] "
273 	    "[-f file] [-P system] [-T trace]\n", __progname);
274 	exit(1);
275 }
276 
277 static void
278 parent_shutdown(void)
279 {
280 	pid_t pid;
281 
282 	mproc_clear(p_ca);
283 	mproc_clear(p_pony);
284 	mproc_clear(p_control);
285 	mproc_clear(p_lka);
286 	mproc_clear(p_scheduler);
287 	mproc_clear(p_queue);
288 
289 	do {
290 		pid = waitpid(WAIT_MYPGRP, NULL, 0);
291 	} while (pid != -1 || (pid == -1 && errno == EINTR));
292 
293 	unlink(SMTPD_SOCKET);
294 
295 	log_info("Exiting");
296 	exit(0);
297 }
298 
299 static void
300 parent_send_config(int fd, short event, void *p)
301 {
302 	parent_send_config_lka();
303 	parent_send_config_pony();
304 	parent_send_config_ca();
305 	purge_config(PURGE_PKI);
306 }
307 
308 static void
309 parent_send_config_pony(void)
310 {
311 	log_debug("debug: parent_send_config: configuring pony process");
312 	m_compose(p_pony, IMSG_CONF_START, 0, 0, -1, NULL, 0);
313 	m_compose(p_pony, IMSG_CONF_END, 0, 0, -1, NULL, 0);
314 }
315 
316 void
317 parent_send_config_lka()
318 {
319 	log_debug("debug: parent_send_config_ruleset: reloading");
320 	m_compose(p_lka, IMSG_CONF_START, 0, 0, -1, NULL, 0);
321 	m_compose(p_lka, IMSG_CONF_END, 0, 0, -1, NULL, 0);
322 }
323 
324 static void
325 parent_send_config_ca(void)
326 {
327 	log_debug("debug: parent_send_config: configuring ca process");
328 	m_compose(p_ca, IMSG_CONF_START, 0, 0, -1, NULL, 0);
329 	m_compose(p_ca, IMSG_CONF_END, 0, 0, -1, NULL, 0);
330 }
331 
332 static void
333 parent_sig_handler(int sig, short event, void *p)
334 {
335 	struct child	*child;
336 	int		 status, fail;
337 	pid_t		 pid;
338 	char		*cause;
339 
340 	switch (sig) {
341 	case SIGTERM:
342 	case SIGINT:
343 		log_debug("debug: got signal %d", sig);
344 		parent_shutdown();
345 		/* NOT REACHED */
346 
347 	case SIGCHLD:
348 		do {
349 			int len;
350 
351 			pid = waitpid(-1, &status, WNOHANG);
352 			if (pid <= 0)
353 				continue;
354 
355 			fail = 0;
356 			if (WIFSIGNALED(status)) {
357 				fail = 1;
358 				len = asprintf(&cause, "terminated; signal %d",
359 				    WTERMSIG(status));
360 			} else if (WIFEXITED(status)) {
361 				if (WEXITSTATUS(status) != 0) {
362 					fail = 1;
363 					len = asprintf(&cause,
364 					    "exited abnormally");
365 				} else
366 					len = asprintf(&cause, "exited okay");
367 			} else
368 				/* WIFSTOPPED or WIFCONTINUED */
369 				continue;
370 
371 			if (len == -1)
372 				fatal("asprintf");
373 
374 			if (pid == purge_pid)
375 				purge_pid = -1;
376 
377 			child = tree_pop(&children, pid);
378 			if (child == NULL)
379 				goto skip;
380 
381 			switch (child->type) {
382 			case CHILD_DAEMON:
383 				if (fail)
384 					log_warnx("warn: lost child: %s %s",
385 					    child->title, cause);
386 				break;
387 
388 			case CHILD_MDA:
389 				if (WIFSIGNALED(status) &&
390 				    WTERMSIG(status) == SIGALRM) {
391 					char *tmp;
392 					if (asprintf(&tmp,
393 					    "terminated; timeout") != -1) {
394 						free(cause);
395 						cause = tmp;
396 					}
397 				}
398 				else if (child->cause &&
399 				    WIFSIGNALED(status) &&
400 				    WTERMSIG(status) == SIGTERM) {
401 					free(cause);
402 					cause = child->cause;
403 					child->cause = NULL;
404 				}
405 				free(child->cause);
406 				log_debug("debug: smtpd: mda process done "
407 				    "for session %016"PRIx64 ": %s",
408 				    child->mda_id, cause);
409 				m_create(p_pony, IMSG_MDA_DONE, 0, 0,
410 				    child->mda_out);
411 				m_add_id(p_pony, child->mda_id);
412 				m_add_string(p_pony, cause);
413 				m_close(p_pony);
414 				/* free(cause); */
415 				break;
416 
417 			case CHILD_ENQUEUE_OFFLINE:
418 				if (fail)
419 					log_warnx("warn: smtpd: "
420 					    "couldn't enqueue offline "
421 					    "message %s; smtpctl %s",
422 					    child->path, cause);
423 				else
424 					unlink(child->path);
425 				free(child->path);
426 				offline_done();
427 				break;
428 
429 			default:
430 				fatalx("smtpd: unexpected child type");
431 			}
432 			free(child);
433     skip:
434 			free(cause);
435 		} while (pid > 0 || (pid == -1 && errno == EINTR));
436 
437 		break;
438 	default:
439 		fatalx("smtpd: unexpected signal");
440 	}
441 }
442 
443 int
444 main(int argc, char *argv[])
445 {
446 	int		 c, i;
447 	int		 opts, flags;
448 	const char	*conffile = CONF_FILE;
449 	int		 save_argc = argc;
450 	char		**save_argv = argv;
451 	char		*rexec = NULL;
452 	struct smtpd	 conf;
453 
454 	env = &conf;
455 
456 	flags = 0;
457 	opts = 0;
458 	debug = 0;
459 	verbose = 0;
460 
461 	log_init(1);
462 
463 	TAILQ_INIT(&offline_q);
464 
465 	while ((c = getopt(argc, argv, "B:dD:hnP:f:FT:vx:")) != -1) {
466 		switch (c) {
467 		case 'B':
468 			if (strstr(optarg, "queue=") == optarg)
469 				backend_queue = strchr(optarg, '=') + 1;
470 			else if (strstr(optarg, "scheduler=") == optarg)
471 				backend_scheduler = strchr(optarg, '=') + 1;
472 			else if (strstr(optarg, "stat=") == optarg)
473 				backend_stat = strchr(optarg, '=') + 1;
474 			else
475 				log_warnx("warn: "
476 				    "invalid backend specifier %s",
477 				    optarg);
478 			break;
479 		case 'd':
480 			foreground = 1;
481 			foreground_log = 1;
482 			break;
483 		case 'D':
484 			if (cmdline_symset(optarg) < 0)
485 				log_warnx("warn: "
486 				    "could not parse macro definition %s",
487 				    optarg);
488 			break;
489 		case 'h':
490 			log_info("version: " SMTPD_NAME " " SMTPD_VERSION);
491 			usage();
492 			break;
493 		case 'n':
494 			debug = 2;
495 			opts |= SMTPD_OPT_NOACTION;
496 			break;
497 		case 'f':
498 			conffile = optarg;
499 			break;
500 		case 'F':
501 			foreground = 1;
502 			break;
503 
504 		case 'T':
505 			if (!strcmp(optarg, "imsg"))
506 				verbose |= TRACE_IMSG;
507 			else if (!strcmp(optarg, "io"))
508 				verbose |= TRACE_IO;
509 			else if (!strcmp(optarg, "smtp"))
510 				verbose |= TRACE_SMTP;
511 			else if (!strcmp(optarg, "mfa") ||
512 			    !strcmp(optarg, "filter") ||
513 			    !strcmp(optarg, "filters"))
514 				verbose |= TRACE_FILTERS;
515 			else if (!strcmp(optarg, "mta") ||
516 			    !strcmp(optarg, "transfer"))
517 				verbose |= TRACE_MTA;
518 			else if (!strcmp(optarg, "bounce") ||
519 			    !strcmp(optarg, "bounces"))
520 				verbose |= TRACE_BOUNCE;
521 			else if (!strcmp(optarg, "scheduler"))
522 				verbose |= TRACE_SCHEDULER;
523 			else if (!strcmp(optarg, "lookup"))
524 				verbose |= TRACE_LOOKUP;
525 			else if (!strcmp(optarg, "stat") ||
526 			    !strcmp(optarg, "stats"))
527 				verbose |= TRACE_STAT;
528 			else if (!strcmp(optarg, "rules"))
529 				verbose |= TRACE_RULES;
530 			else if (!strcmp(optarg, "mproc"))
531 				verbose |= TRACE_MPROC;
532 			else if (!strcmp(optarg, "expand"))
533 				verbose |= TRACE_EXPAND;
534 			else if (!strcmp(optarg, "table") ||
535 			    !strcmp(optarg, "tables"))
536 				verbose |= TRACE_TABLES;
537 			else if (!strcmp(optarg, "queue"))
538 				verbose |= TRACE_QUEUE;
539 			else if (!strcmp(optarg, "all"))
540 				verbose |= ~TRACE_DEBUG;
541 			else if (!strcmp(optarg, "profstat"))
542 				profiling |= PROFILE_TOSTAT;
543 			else if (!strcmp(optarg, "profile-imsg"))
544 				profiling |= PROFILE_IMSG;
545 			else if (!strcmp(optarg, "profile-queue"))
546 				profiling |= PROFILE_QUEUE;
547 			else
548 				log_warnx("warn: unknown trace flag \"%s\"",
549 				    optarg);
550 			break;
551 		case 'P':
552 			if (!strcmp(optarg, "smtp"))
553 				flags |= SMTPD_SMTP_PAUSED;
554 			else if (!strcmp(optarg, "mta"))
555 				flags |= SMTPD_MTA_PAUSED;
556 			else if (!strcmp(optarg, "mda"))
557 				flags |= SMTPD_MDA_PAUSED;
558 			break;
559 		case 'v':
560 			verbose |=  TRACE_DEBUG;
561 			break;
562 		case 'x':
563 			rexec = optarg;
564 			break;
565 		default:
566 			usage();
567 		}
568 	}
569 
570 	argv += optind;
571 	argc -= optind;
572 
573 	if (argc || *argv)
574 		usage();
575 
576 	ssl_init();
577 
578 	if (parse_config(&conf, conffile, opts))
579 		exit(1);
580 
581 	if (strlcpy(env->sc_conffile, conffile, PATH_MAX)
582 	    >= PATH_MAX)
583 		errx(1, "config file exceeds PATH_MAX");
584 
585 	if (env->sc_opts & SMTPD_OPT_NOACTION) {
586 		if (env->sc_queue_key &&
587 		    crypto_setup(env->sc_queue_key,
588 		    strlen(env->sc_queue_key)) == 0) {
589 			fatalx("crypto_setup:"
590 			    "invalid key for queue encryption");
591 		}
592 		load_pki_tree();
593 		load_pki_keys();
594 		fprintf(stderr, "configuration OK\n");
595 		exit(0);
596 	}
597 
598 	env->sc_flags |= flags;
599 
600 	/* check for root privileges */
601 	if (geteuid())
602 		errx(1, "need root privileges");
603 
604 	log_init(foreground_log);
605 	log_verbose(verbose);
606 
607 	load_pki_tree();
608 	load_pki_keys();
609 
610 	log_debug("debug: using \"%s\" queue backend", backend_queue);
611 	log_debug("debug: using \"%s\" scheduler backend", backend_scheduler);
612 	log_debug("debug: using \"%s\" stat backend", backend_stat);
613 
614 	if (env->sc_hostname[0] == '\0')
615 		errx(1, "machine does not have a hostname set");
616 	env->sc_uptime = time(NULL);
617 
618 	if (rexec == NULL) {
619 		smtpd_process = PROC_PARENT;
620 
621 		if (env->sc_queue_flags & QUEUE_ENCRYPTION) {
622 			if (env->sc_queue_key == NULL) {
623 				char	*password;
624 
625 				password = getpass("queue key: ");
626 				if (password == NULL)
627 					err(1, "getpass");
628 
629 				env->sc_queue_key = strdup(password);
630 				explicit_bzero(password, strlen(password));
631 				if (env->sc_queue_key == NULL)
632 					err(1, "strdup");
633 			}
634 			else {
635 				char   *buf = NULL;
636 				size_t	sz = 0;
637 				ssize_t	len;
638 
639 				if (strcasecmp(env->sc_queue_key, "stdin") == 0) {
640 					if ((len = getline(&buf, &sz, stdin)) == -1)
641 						err(1, "getline");
642 					if (buf[len - 1] == '\n')
643 						buf[len - 1] = '\0';
644 					env->sc_queue_key = buf;
645 				}
646 			}
647 		}
648 
649 		log_info("info: %s %s starting", SMTPD_NAME, SMTPD_VERSION);
650 
651 		if (!foreground)
652 			if (daemon(0, 0) == -1)
653 				err(1, "failed to daemonize");
654 
655 		/* setup all processes */
656 
657 		p_ca = start_child(save_argc, save_argv, "ca");
658 		p_ca->proc = PROC_CA;
659 
660 		p_control = start_child(save_argc, save_argv, "control");
661 		p_control->proc = PROC_CONTROL;
662 
663 		p_lka = start_child(save_argc, save_argv, "lka");
664 		p_lka->proc = PROC_LKA;
665 
666 		p_pony = start_child(save_argc, save_argv, "pony");
667 		p_pony->proc = PROC_PONY;
668 
669 		p_queue = start_child(save_argc, save_argv, "queue");
670 		p_queue->proc = PROC_QUEUE;
671 
672 		p_scheduler = start_child(save_argc, save_argv, "scheduler");
673 		p_scheduler->proc = PROC_SCHEDULER;
674 
675 		setup_peers(p_control, p_ca);
676 		setup_peers(p_control, p_lka);
677 		setup_peers(p_control, p_pony);
678 		setup_peers(p_control, p_queue);
679 		setup_peers(p_control, p_scheduler);
680 		setup_peers(p_pony, p_ca);
681 		setup_peers(p_pony, p_lka);
682 		setup_peers(p_pony, p_queue);
683 		setup_peers(p_queue, p_lka);
684 		setup_peers(p_queue, p_scheduler);
685 
686 		if (env->sc_queue_key) {
687 			if (imsg_compose(&p_queue->imsgbuf, IMSG_SETUP_KEY, 0,
688 			    0, -1, env->sc_queue_key, strlen(env->sc_queue_key)
689 			    + 1) == -1)
690 				fatal("imsg_compose");
691 			if (imsg_flush(&p_queue->imsgbuf) == -1)
692 				fatal("imsg_flush");
693 		}
694 
695 		setup_done(p_ca);
696 		setup_done(p_control);
697 		setup_done(p_lka);
698 		setup_done(p_pony);
699 		setup_done(p_queue);
700 		setup_done(p_scheduler);
701 
702 		log_debug("smtpd: setup done");
703 
704 		return smtpd();
705 	}
706 
707 	if (!strcmp(rexec, "ca")) {
708 		smtpd_process = PROC_CA;
709 		setup_proc();
710 
711 		return ca();
712 	}
713 
714 	else if (!strcmp(rexec, "control")) {
715 		smtpd_process = PROC_CONTROL;
716 		setup_proc();
717 
718 		/* the control socket ensures that only one smtpd instance is running */
719 		control_socket = control_create_socket();
720 
721 		env->sc_stat = stat_backend_lookup(backend_stat);
722 		if (env->sc_stat == NULL)
723 			errx(1, "could not find stat backend \"%s\"", backend_stat);
724 
725 		return control();
726 	}
727 
728 	else if (!strcmp(rexec, "lka")) {
729 		smtpd_process = PROC_LKA;
730 		setup_proc();
731 
732 		return lka();
733 	}
734 
735 	else if (!strcmp(rexec, "pony")) {
736 		smtpd_process = PROC_PONY;
737 		setup_proc();
738 
739 		return pony();
740 	}
741 
742 	else if (!strcmp(rexec, "queue")) {
743 		smtpd_process = PROC_QUEUE;
744 		setup_proc();
745 
746 		if (env->sc_queue_flags & QUEUE_COMPRESSION)
747 			env->sc_comp = compress_backend_lookup("gzip");
748 
749 		if (!queue_init(backend_queue, 1))
750 			errx(1, "could not initialize queue backend");
751 
752 		return queue();
753 	}
754 
755 	else if (!strcmp(rexec, "scheduler")) {
756 		smtpd_process = PROC_SCHEDULER;
757 		setup_proc();
758 
759 		for (i = 0; i < MAX_BOUNCE_WARN; i++) {
760 			if (env->sc_bounce_warn[i] == 0)
761 				break;
762 			log_debug("debug: bounce warning after %s",
763 			    duration_to_text(env->sc_bounce_warn[i]));
764 		}
765 
766 		return scheduler();
767 	}
768 
769 	fatalx("bad rexec: %s", rexec);
770 
771 	return (1);
772 }
773 
774 static struct mproc *
775 start_child(int save_argc, char **save_argv, char *rexec)
776 {
777 	struct mproc *p;
778 	char *argv[SMTPD_MAXARG];
779 	int sp[2], argc = 0;
780 	pid_t pid;
781 
782 	if (save_argc >= SMTPD_MAXARG - 2)
783 		fatalx("too many arguments");
784 
785 	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, sp) == -1)
786 		fatal("socketpair");
787 
788 	io_set_nonblocking(sp[0]);
789 	io_set_nonblocking(sp[1]);
790 
791 	switch (pid = fork()) {
792 	case -1:
793 		fatal("%s: fork", save_argv[0]);
794 	case 0:
795 		break;
796 	default:
797 		close(sp[0]);
798 		p = calloc(1, sizeof(*p));
799 		if (p == NULL)
800 			fatal("calloc");
801 		if((p->name = strdup(rexec)) == NULL)
802 			fatal("strdup");
803 		mproc_init(p, sp[1]);
804 		p->pid = pid;
805 		p->handler = parent_imsg;
806 		return p;
807 	}
808 
809 	if (dup2(sp[0], 3) == -1)
810 		fatal("%s: dup2", rexec);
811 
812 	if (closefrom(4) == -1)
813 		fatal("%s: closefrom", rexec);
814 
815 	for (argc = 0; argc < save_argc; argc++)
816 		argv[argc] = save_argv[argc];
817 	argv[argc++] = "-x";
818 	argv[argc++] = rexec;
819 	argv[argc++] = NULL;
820 
821 	execvp(argv[0], argv);
822 	fatal("%s: execvp", rexec);
823 }
824 
825 static void
826 setup_peers(struct mproc *a, struct mproc *b)
827 {
828 	int sp[2];
829 
830 	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, sp) == -1)
831 		fatal("socketpair");
832 
833 	io_set_nonblocking(sp[0]);
834 	io_set_nonblocking(sp[1]);
835 
836 	if (imsg_compose(&a->imsgbuf, IMSG_SETUP_PEER, b->proc, b->pid, sp[0],
837 	    NULL, 0) == -1)
838 		fatal("imsg_compose");
839 	if (imsg_flush(&a->imsgbuf) == -1)
840 		fatal("imsg_flush");
841 
842 	if (imsg_compose(&b->imsgbuf, IMSG_SETUP_PEER, a->proc, a->pid, sp[1],
843 	    NULL, 0) == -1)
844 		fatal("imsg_compose");
845 	if (imsg_flush(&b->imsgbuf) == -1)
846 		fatal("imsg_flush");
847 }
848 
849 static void
850 setup_done(struct mproc *p)
851 {
852 	struct imsg imsg;
853 
854 	if (imsg_compose(&p->imsgbuf, IMSG_SETUP_DONE, 0, 0, -1, NULL, 0) == -1)
855 		fatal("imsg_compose");
856 	if (imsg_flush(&p->imsgbuf) == -1)
857 		fatal("imsg_flush");
858 
859 	if (imsg_wait(&p->imsgbuf, &imsg, 10000) == -1)
860 		fatal("imsg_wait");
861 
862 	if (imsg.hdr.type != IMSG_SETUP_DONE)
863 		fatalx("expect IMSG_SETUP_DONE");
864 
865 	log_debug("setup_done: %s[%d] done", p->name, p->pid);
866 
867 	imsg_free(&imsg);
868 }
869 
870 static void
871 setup_proc(void)
872 {
873 	struct imsgbuf *ibuf;
874 	struct imsg imsg;
875         int setup = 1;
876 
877 	p_parent = calloc(1, sizeof(*p_parent));
878 	if (p_parent == NULL)
879 		fatal("calloc");
880 	if((p_parent->name = strdup("parent")) == NULL)
881 		fatal("strdup");
882 	p_parent->proc = PROC_PARENT;
883 	p_parent->handler = imsg_dispatch;
884 	mproc_init(p_parent, 3);
885 
886 	ibuf = &p_parent->imsgbuf;
887 
888 	while (setup) {
889 		if (imsg_wait(ibuf, &imsg, 10000) == -1)
890 			fatal("imsg_wait");
891 
892 		switch (imsg.hdr.type) {
893 		case IMSG_SETUP_KEY:
894 			env->sc_queue_key = strdup(imsg.data);
895 			break;
896 		case IMSG_SETUP_PEER:
897 			setup_peer(imsg.hdr.peerid, imsg.hdr.pid, imsg.fd);
898 			break;
899 		case IMSG_SETUP_DONE:
900 			setup = 0;
901 			break;
902 		default:
903 			fatal("bad imsg %d", imsg.hdr.type);
904 		}
905 		imsg_free(&imsg);
906 	}
907 
908 	if (imsg_compose(ibuf, IMSG_SETUP_DONE, 0, 0, -1, NULL, 0) == -1)
909 		fatal("imsg_compose");
910 
911 	if (imsg_flush(ibuf) == -1)
912 		fatal("imsg_flush");
913 
914 	log_debug("setup_proc: %s done", proc_title(smtpd_process));
915 }
916 
917 static struct mproc *
918 setup_peer(enum smtp_proc_type proc, pid_t pid, int sock)
919 {
920 	struct mproc *p, **pp;
921 
922 	log_debug("setup_peer: %s -> %s[%u] fd=%d", proc_title(smtpd_process),
923 	    proc_title(proc), pid, sock);
924 
925 	if (sock == -1)
926 		fatalx("peer socket not received");
927 
928 	switch (proc) {
929 	case PROC_LKA:
930 		pp = &p_lka;
931 		break;
932 	case PROC_QUEUE:
933 		pp = &p_queue;
934 		break;
935 	case PROC_CONTROL:
936 		pp = &p_control;
937 		break;
938 	case PROC_SCHEDULER:
939 		pp = &p_scheduler;
940 		break;
941 	case PROC_PONY:
942 		pp = &p_pony;
943 		break;
944 	case PROC_CA:
945 		pp = &p_ca;
946 		break;
947 	default:
948 		fatalx("unknown peer");
949 	}
950 
951 	if (*pp)
952 		fatalx("peer already set");
953 
954 	p = calloc(1, sizeof(*p));
955 	if (p == NULL)
956 		fatal("calloc");
957 	if((p->name = strdup(proc_title(proc))) == NULL)
958 		fatal("strdup");
959 	mproc_init(p, sock);
960 	p->pid = pid;
961 	p->proc = proc;
962 	p->handler = imsg_dispatch;
963 
964 	*pp = p;
965 
966 	return p;
967 }
968 
969 static int
970 imsg_wait(struct imsgbuf *ibuf, struct imsg *imsg, int timeout)
971 {
972 	struct pollfd pfd[1];
973 	ssize_t n;
974 
975 	pfd[0].fd = ibuf->fd;
976 	pfd[0].events = POLLIN;
977 
978 	while (1) {
979 		if ((n = imsg_get(ibuf, imsg)) == -1)
980 			return -1;
981 		if (n)
982 			return 1;
983 
984 		n = poll(pfd, 1, timeout);
985 		if (n == -1)
986 			return -1;
987 		if (n == 0) {
988 			errno = ETIMEDOUT;
989 			return -1;
990 		}
991 
992 		if (((n = imsg_read(ibuf)) == -1 && errno != EAGAIN) || n == 0)
993 			return -1;
994 	}
995 }
996 
997 int
998 smtpd(void) {
999 	struct event	 ev_sigint;
1000 	struct event	 ev_sigterm;
1001 	struct event	 ev_sigchld;
1002 	struct event	 ev_sighup;
1003 	struct timeval	 tv;
1004 
1005 	imsg_callback = parent_imsg;
1006 
1007 	tree_init(&children);
1008 
1009 	child_add(p_queue->pid, CHILD_DAEMON, proc_title(PROC_QUEUE));
1010 	child_add(p_control->pid, CHILD_DAEMON, proc_title(PROC_CONTROL));
1011 	child_add(p_lka->pid, CHILD_DAEMON, proc_title(PROC_LKA));
1012 	child_add(p_scheduler->pid, CHILD_DAEMON, proc_title(PROC_SCHEDULER));
1013 	child_add(p_pony->pid, CHILD_DAEMON, proc_title(PROC_PONY));
1014 	child_add(p_ca->pid, CHILD_DAEMON, proc_title(PROC_CA));
1015 
1016 	event_init();
1017 
1018 	signal_set(&ev_sigint, SIGINT, parent_sig_handler, NULL);
1019 	signal_set(&ev_sigterm, SIGTERM, parent_sig_handler, NULL);
1020 	signal_set(&ev_sigchld, SIGCHLD, parent_sig_handler, NULL);
1021 	signal_set(&ev_sighup, SIGHUP, parent_sig_handler, NULL);
1022 	signal_add(&ev_sigint, NULL);
1023 	signal_add(&ev_sigterm, NULL);
1024 	signal_add(&ev_sigchld, NULL);
1025 	signal_add(&ev_sighup, NULL);
1026 	signal(SIGPIPE, SIG_IGN);
1027 
1028 	config_peer(PROC_CONTROL);
1029 	config_peer(PROC_LKA);
1030 	config_peer(PROC_QUEUE);
1031 	config_peer(PROC_CA);
1032 	config_peer(PROC_PONY);
1033 
1034 	evtimer_set(&config_ev, parent_send_config, NULL);
1035 	memset(&tv, 0, sizeof(tv));
1036 	evtimer_add(&config_ev, &tv);
1037 
1038 	/* defer offline scanning for a second */
1039 	evtimer_set(&offline_ev, offline_scan, NULL);
1040 	offline_timeout.tv_sec = 1;
1041 	offline_timeout.tv_usec = 0;
1042 	evtimer_add(&offline_ev, &offline_timeout);
1043 
1044 	purge_task();
1045 
1046 	if (pledge("stdio rpath wpath cpath fattr flock tmppath "
1047 	    "getpw sendfd proc exec id inet unix", NULL) == -1)
1048 		err(1, "pledge");
1049 
1050 	event_dispatch();
1051 	fatalx("exited event loop");
1052 
1053 	return (0);
1054 }
1055 
1056 static void
1057 load_pki_tree(void)
1058 {
1059 	struct pki	*pki;
1060 	struct ca	*sca;
1061 	const char	*k;
1062 	void		*iter_dict;
1063 
1064 	log_debug("debug: init ssl-tree");
1065 	iter_dict = NULL;
1066 	while (dict_iter(env->sc_pki_dict, &iter_dict, &k, (void **)&pki)) {
1067 		log_debug("info: loading pki information for %s", k);
1068 		if (pki->pki_cert_file == NULL)
1069 			fatalx("load_pki_tree: missing certificate file");
1070 		if (pki->pki_key_file == NULL)
1071 			fatalx("load_pki_tree: missing key file");
1072 
1073 		if (!ssl_load_certificate(pki, pki->pki_cert_file))
1074 			fatalx("load_pki_tree: failed to load certificate file");
1075 	}
1076 
1077 	log_debug("debug: init ca-tree");
1078 	iter_dict = NULL;
1079 	while (dict_iter(env->sc_ca_dict, &iter_dict, &k, (void **)&sca)) {
1080 		log_debug("info: loading CA information for %s", k);
1081 		if (!ssl_load_cafile(sca, sca->ca_cert_file))
1082 			fatalx("load_pki_tree: failed to load CA file");
1083 	}
1084 }
1085 
1086 void
1087 load_pki_keys(void)
1088 {
1089 	struct pki	*pki;
1090 	const char	*k;
1091 	void		*iter_dict;
1092 
1093 	log_debug("debug: init ssl-tree");
1094 	iter_dict = NULL;
1095 	while (dict_iter(env->sc_pki_dict, &iter_dict, &k, (void **)&pki)) {
1096 		log_debug("info: loading pki keys for %s", k);
1097 
1098 		if (!ssl_load_keyfile(pki, pki->pki_key_file, k))
1099 			fatalx("load_pki_keys: failed to load key file");
1100 	}
1101 }
1102 
1103 int
1104 fork_proc_backend(const char *key, const char *conf, const char *procname)
1105 {
1106 	pid_t		pid;
1107 	int		sp[2];
1108 	char		path[PATH_MAX];
1109 	char		name[PATH_MAX];
1110 	char		*arg;
1111 
1112 	if (strlcpy(name, conf, sizeof(name)) >= sizeof(name)) {
1113 		log_warnx("warn: %s-proc: conf too long", key);
1114 		return (0);
1115 	}
1116 
1117 	arg = strchr(name, ':');
1118 	if (arg)
1119 		*arg++ = '\0';
1120 
1121 	if (snprintf(path, sizeof(path), PATH_LIBEXEC "/%s-%s", key, name) >=
1122 	    (ssize_t)sizeof(path)) {
1123 		log_warn("warn: %s-proc: exec path too long", key);
1124 		return (-1);
1125 	}
1126 
1127 	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, sp) == -1) {
1128 		log_warn("warn: %s-proc: socketpair", key);
1129 		return (-1);
1130 	}
1131 
1132 	if ((pid = fork()) == -1) {
1133 		log_warn("warn: %s-proc: fork", key);
1134 		close(sp[0]);
1135 		close(sp[1]);
1136 		return (-1);
1137 	}
1138 
1139 	if (pid == 0) {
1140 		/* child process */
1141 		dup2(sp[0], STDIN_FILENO);
1142 		if (closefrom(STDERR_FILENO + 1) < 0)
1143 			exit(1);
1144 
1145 		if (procname == NULL)
1146 			procname = name;
1147 
1148 		execl(path, procname, arg, (char *)NULL);
1149 		err(1, "execl: %s", path);
1150 	}
1151 
1152 	/* parent process */
1153 	close(sp[0]);
1154 
1155 	return (sp[1]);
1156 }
1157 
1158 struct child *
1159 child_add(pid_t pid, int type, const char *title)
1160 {
1161 	struct child	*child;
1162 
1163 	if ((child = calloc(1, sizeof(*child))) == NULL)
1164 		fatal("smtpd: child_add: calloc");
1165 
1166 	child->pid = pid;
1167 	child->type = type;
1168 	child->title = title;
1169 
1170 	tree_xset(&children, pid, child);
1171 
1172 	return (child);
1173 }
1174 
1175 static void
1176 purge_task(void)
1177 {
1178 	struct passwd	*pw;
1179 	DIR		*d;
1180 	int		 n;
1181 	uid_t		 uid;
1182 	gid_t		 gid;
1183 
1184 	n = 0;
1185 	if ((d = opendir(PATH_SPOOL PATH_PURGE))) {
1186 		while (readdir(d) != NULL)
1187 			n++;
1188 		closedir(d);
1189 	} else
1190 		log_warn("warn: purge_task: opendir");
1191 
1192 	if (n > 2) {
1193 		switch (purge_pid = fork()) {
1194 		case -1:
1195 			log_warn("warn: purge_task: fork");
1196 			break;
1197 		case 0:
1198 			if ((pw = getpwnam(SMTPD_USER)) == NULL)
1199 				fatalx("unknown user " SMTPD_USER);
1200 			if (chroot(PATH_SPOOL PATH_PURGE) == -1)
1201 				fatal("smtpd: chroot");
1202 			if (chdir("/") == -1)
1203 				fatal("smtpd: chdir");
1204 			uid = pw->pw_uid;
1205 			gid = pw->pw_gid;
1206 			if (setgroups(1, &gid) ||
1207 			    setresgid(gid, gid, gid) ||
1208 			    setresuid(uid, uid, uid))
1209 				fatal("smtpd: cannot drop privileges");
1210 			rmtree("/", 1);
1211 			_exit(0);
1212 			break;
1213 		default:
1214 			break;
1215 		}
1216 	}
1217 }
1218 
1219 static void
1220 forkmda(struct mproc *p, uint64_t id, struct deliver *deliver)
1221 {
1222 	char		 ebuf[128], sfn[32];
1223 	struct delivery_backend	*db;
1224 	struct child	*child;
1225 	pid_t		 pid;
1226 	int		 allout, pipefd[2];
1227 
1228 	log_debug("debug: smtpd: forking mda for session %016"PRIx64
1229 	    ": \"%s\" as %s", id, deliver->to, deliver->user);
1230 
1231 	db = delivery_backend_lookup(deliver->mode);
1232 	if (db == NULL) {
1233 		(void)snprintf(ebuf, sizeof ebuf, "could not find delivery backend");
1234 		m_create(p_pony, IMSG_MDA_DONE, 0, 0, -1);
1235 		m_add_id(p_pony, id);
1236 		m_add_string(p_pony, ebuf);
1237 		m_close(p_pony);
1238 		return;
1239 	}
1240 
1241 	if (deliver->userinfo.uid == 0 && !db->allow_root) {
1242 		(void)snprintf(ebuf, sizeof ebuf, "not allowed to deliver to: %s",
1243 		    deliver->user);
1244 		m_create(p_pony, IMSG_MDA_DONE, 0, 0, -1);
1245 		m_add_id(p_pony, id);
1246 		m_add_string(p_pony, ebuf);
1247 		m_close(p_pony);
1248 		return;
1249 	}
1250 
1251 	if (pipe(pipefd) < 0) {
1252 		(void)snprintf(ebuf, sizeof ebuf, "pipe: %s", strerror(errno));
1253 		m_create(p_pony, IMSG_MDA_DONE, 0, 0, -1);
1254 		m_add_id(p_pony, id);
1255 		m_add_string(p_pony, ebuf);
1256 		m_close(p_pony);
1257 		return;
1258 	}
1259 
1260 	/* prepare file which captures stdout and stderr */
1261 	(void)strlcpy(sfn, "/tmp/smtpd.out.XXXXXXXXXXX", sizeof(sfn));
1262 	allout = mkstemp(sfn);
1263 	if (allout < 0) {
1264 		(void)snprintf(ebuf, sizeof ebuf, "mkstemp: %s", strerror(errno));
1265 		m_create(p_pony, IMSG_MDA_DONE, 0, 0, -1);
1266 		m_add_id(p_pony, id);
1267 		m_add_string(p_pony, ebuf);
1268 		m_close(p_pony);
1269 		close(pipefd[0]);
1270 		close(pipefd[1]);
1271 		return;
1272 	}
1273 	unlink(sfn);
1274 
1275 	pid = fork();
1276 	if (pid < 0) {
1277 		(void)snprintf(ebuf, sizeof ebuf, "fork: %s", strerror(errno));
1278 		m_create(p_pony, IMSG_MDA_DONE, 0, 0, -1);
1279 		m_add_id(p_pony, id);
1280 		m_add_string(p_pony, ebuf);
1281 		m_close(p_pony);
1282 		close(pipefd[0]);
1283 		close(pipefd[1]);
1284 		close(allout);
1285 		return;
1286 	}
1287 
1288 	/* parent passes the child fd over to mda */
1289 	if (pid > 0) {
1290 		child = child_add(pid, CHILD_MDA, NULL);
1291 		child->mda_out = allout;
1292 		child->mda_id = id;
1293 		close(pipefd[0]);
1294 		m_create(p, IMSG_MDA_FORK, 0, 0, pipefd[1]);
1295 		m_add_id(p, id);
1296 		m_close(p);
1297 		return;
1298 	}
1299 
1300 	if (chdir(deliver->userinfo.directory) < 0 && chdir("/") < 0)
1301 		err(1, "chdir");
1302 	if (setgroups(1, &deliver->userinfo.gid) ||
1303 	    setresgid(deliver->userinfo.gid, deliver->userinfo.gid, deliver->userinfo.gid) ||
1304 	    setresuid(deliver->userinfo.uid, deliver->userinfo.uid, deliver->userinfo.uid))
1305 		err(1, "forkmda: cannot drop privileges");
1306 	if (dup2(pipefd[0], STDIN_FILENO) < 0 ||
1307 	    dup2(allout, STDOUT_FILENO) < 0 ||
1308 	    dup2(allout, STDERR_FILENO) < 0)
1309 		err(1, "forkmda: dup2");
1310 	if (closefrom(STDERR_FILENO + 1) < 0)
1311 		err(1, "closefrom");
1312 	if (setsid() < 0)
1313 		err(1, "setsid");
1314 	if (signal(SIGPIPE, SIG_DFL) == SIG_ERR ||
1315 	    signal(SIGINT, SIG_DFL) == SIG_ERR ||
1316 	    signal(SIGTERM, SIG_DFL) == SIG_ERR ||
1317 	    signal(SIGCHLD, SIG_DFL) == SIG_ERR ||
1318 	    signal(SIGHUP, SIG_DFL) == SIG_ERR)
1319 		err(1, "signal");
1320 
1321 	/* avoid hangs by setting 5m timeout */
1322 	alarm(300);
1323 
1324 	db->open(deliver);
1325 }
1326 
1327 static void
1328 offline_scan(int fd, short ev, void *arg)
1329 {
1330 	char		*path_argv[2];
1331 	FTS		*fts = arg;
1332 	FTSENT		*e;
1333 	int		 n = 0;
1334 
1335 	path_argv[0] = PATH_SPOOL PATH_OFFLINE;
1336 	path_argv[1] = NULL;
1337 
1338 	if (fts == NULL) {
1339 		log_debug("debug: smtpd: scanning offline queue...");
1340 		fts = fts_open(path_argv, FTS_PHYSICAL | FTS_NOCHDIR, NULL);
1341 		if (fts == NULL) {
1342 			log_warn("fts_open: %s", path_argv[0]);
1343 			return;
1344 		}
1345 	}
1346 
1347 	while ((e = fts_read(fts)) != NULL) {
1348 		if (e->fts_info != FTS_F)
1349 			continue;
1350 
1351 		/* offline files must be at depth 1 */
1352 		if (e->fts_level != 1)
1353 			continue;
1354 
1355 		/* offline file group must match parent directory group */
1356 		if (e->fts_statp->st_gid != e->fts_parent->fts_statp->st_gid)
1357 			continue;
1358 
1359 		if (e->fts_statp->st_size == 0) {
1360 			if (unlink(e->fts_accpath) == -1)
1361 				log_warnx("warn: smtpd: could not unlink %s", e->fts_accpath);
1362 			continue;
1363 		}
1364 
1365 		if (offline_add(e->fts_name)) {
1366 			log_warnx("warn: smtpd: "
1367 			    "could not add offline message %s", e->fts_name);
1368 			continue;
1369 		}
1370 
1371 		if ((n++) == OFFLINE_READMAX) {
1372 			evtimer_set(&offline_ev, offline_scan, fts);
1373 			offline_timeout.tv_sec = 0;
1374 			offline_timeout.tv_usec = 100000;
1375 			evtimer_add(&offline_ev, &offline_timeout);
1376 			return;
1377 		}
1378 	}
1379 
1380 	log_debug("debug: smtpd: offline scanning done");
1381 	fts_close(fts);
1382 }
1383 
1384 static int
1385 offline_enqueue(char *name)
1386 {
1387 	char		*path;
1388 	struct stat	 sb;
1389 	pid_t		 pid;
1390 	struct child	*child;
1391 	struct passwd	*pw;
1392 	int		 pathlen;
1393 
1394 	pathlen = asprintf(&path, "%s/%s", PATH_SPOOL PATH_OFFLINE, name);
1395 	if (pathlen == -1) {
1396 		log_warnx("warn: smtpd: asprintf");
1397 		return (-1);
1398 	}
1399 
1400 	if (pathlen >= PATH_MAX) {
1401 		log_warnx("warn: smtpd: pathname exceeds PATH_MAX");
1402 		free(path);
1403 		return (-1);
1404 	}
1405 
1406 	log_debug("debug: smtpd: enqueueing offline message %s", path);
1407 
1408 	if ((pid = fork()) == -1) {
1409 		log_warn("warn: smtpd: fork");
1410 		free(path);
1411 		return (-1);
1412 	}
1413 
1414 	if (pid == 0) {
1415 		char	*envp[2], *p = NULL, *tmp;
1416 		int	 fd;
1417 		FILE	*fp;
1418 		size_t	 sz = 0;
1419 		ssize_t	 len;
1420 		arglist	 args;
1421 
1422 		if (closefrom(STDERR_FILENO + 1) == -1)
1423 			_exit(1);
1424 
1425 		memset(&args, 0, sizeof(args));
1426 
1427 		if ((fd = open(path, O_RDONLY|O_NOFOLLOW|O_NONBLOCK)) == -1) {
1428 			log_warn("warn: smtpd: open: %s", path);
1429 			_exit(1);
1430 		}
1431 
1432 		if (fstat(fd, &sb) == -1) {
1433 			log_warn("warn: smtpd: fstat: %s", path);
1434 			_exit(1);
1435 		}
1436 
1437 		if (!S_ISREG(sb.st_mode)) {
1438 			log_warnx("warn: smtpd: file %s (uid %d) not regular",
1439 			    path, sb.st_uid);
1440 			_exit(1);
1441 		}
1442 
1443 		if (sb.st_nlink != 1) {
1444 			log_warnx("warn: smtpd: file %s is hard-link", path);
1445 			_exit(1);
1446 		}
1447 
1448 		pw = getpwuid(sb.st_uid);
1449 		if (pw == NULL) {
1450 			log_warnx("warn: smtpd: getpwuid for uid %d failed",
1451 			    sb.st_uid);
1452 			_exit(1);
1453 		}
1454 
1455 		if (setgroups(1, &pw->pw_gid) ||
1456 		    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
1457 		    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
1458 			_exit(1);
1459 
1460 		if ((fp = fdopen(fd, "r")) == NULL)
1461 			_exit(1);
1462 
1463 		if (chdir(pw->pw_dir) == -1 && chdir("/") == -1)
1464 			_exit(1);
1465 
1466 		if (setsid() == -1 ||
1467 		    signal(SIGPIPE, SIG_DFL) == SIG_ERR ||
1468 		    dup2(fileno(fp), STDIN_FILENO) == -1)
1469 			_exit(1);
1470 
1471 		if ((len = getline(&p, &sz, fp)) == -1)
1472 			_exit(1);
1473 
1474 		if (p[len - 1] != '\n')
1475 			_exit(1);
1476 		p[len - 1] = '\0';
1477 
1478 		addargs(&args, "%s", "sendmail");
1479 		addargs(&args, "%s", "-S");
1480 
1481 		while ((tmp = strsep(&p, "|")) != NULL)
1482 			addargs(&args, "%s", tmp);
1483 
1484 		free(p);
1485 		if (lseek(fileno(fp), len, SEEK_SET) == -1)
1486 			_exit(1);
1487 
1488 		envp[0] = "PATH=" _PATH_DEFPATH;
1489 		envp[1] = (char *)NULL;
1490 		environ = envp;
1491 
1492 		execvp(PATH_SMTPCTL, args.list);
1493 		_exit(1);
1494 	}
1495 
1496 	offline_running++;
1497 	child = child_add(pid, CHILD_ENQUEUE_OFFLINE, NULL);
1498 	child->path = path;
1499 
1500 	return (0);
1501 }
1502 
1503 static int
1504 offline_add(char *path)
1505 {
1506 	struct offline	*q;
1507 
1508 	if (offline_running < OFFLINE_QUEUEMAX)
1509 		/* skip queue */
1510 		return offline_enqueue(path);
1511 
1512 	q = malloc(sizeof(*q) + strlen(path) + 1);
1513 	if (q == NULL)
1514 		return (-1);
1515 	q->path = (char *)q + sizeof(*q);
1516 	memmove(q->path, path, strlen(path) + 1);
1517 	TAILQ_INSERT_TAIL(&offline_q, q, entry);
1518 
1519 	return (0);
1520 }
1521 
1522 static void
1523 offline_done(void)
1524 {
1525 	struct offline	*q;
1526 
1527 	offline_running--;
1528 
1529 	while (offline_running < OFFLINE_QUEUEMAX) {
1530 		if ((q = TAILQ_FIRST(&offline_q)) == NULL)
1531 			break; /* all done */
1532 		TAILQ_REMOVE(&offline_q, q, entry);
1533 		offline_enqueue(q->path);
1534 		free(q);
1535 	}
1536 }
1537 
1538 static int
1539 parent_forward_open(char *username, char *directory, uid_t uid, gid_t gid)
1540 {
1541 	char		pathname[PATH_MAX];
1542 	int		fd;
1543 	struct stat	sb;
1544 
1545 	if (!bsnprintf(pathname, sizeof (pathname), "%s/.forward",
1546 		directory)) {
1547 		log_warnx("warn: smtpd: %s: pathname too large", pathname);
1548 		return -1;
1549 	}
1550 
1551 	if (stat(directory, &sb) < 0) {
1552 		log_warn("warn: smtpd: parent_forward_open: %s", directory);
1553 		return -1;
1554 	}
1555 	if (sb.st_mode & S_ISVTX) {
1556 		log_warnx("warn: smtpd: parent_forward_open: %s is sticky",
1557 		    directory);
1558 		errno = EAGAIN;
1559 		return -1;
1560 	}
1561 
1562 	do {
1563 		fd = open(pathname, O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
1564 	} while (fd == -1 && errno == EINTR);
1565 	if (fd == -1) {
1566 		if (errno == ENOENT)
1567 			return -1;
1568 		if (errno == EMFILE || errno == ENFILE || errno == EIO) {
1569 			errno = EAGAIN;
1570 			return -1;
1571 		}
1572 		if (errno == ELOOP)
1573 			log_warnx("warn: smtpd: parent_forward_open: %s: "
1574 			    "cannot follow symbolic links", pathname);
1575 		else
1576 			log_warn("warn: smtpd: parent_forward_open: %s", pathname);
1577 		return -1;
1578 	}
1579 
1580 	if (!secure_file(fd, pathname, directory, uid, 1)) {
1581 		log_warnx("warn: smtpd: %s: unsecure file", pathname);
1582 		close(fd);
1583 		return -1;
1584 	}
1585 
1586 	return fd;
1587 }
1588 
1589 void
1590 imsg_dispatch(struct mproc *p, struct imsg *imsg)
1591 {
1592 	struct timespec	t0, t1, dt;
1593 	int		msg;
1594 
1595 	if (imsg == NULL) {
1596 		imsg_callback(p, imsg);
1597 		return;
1598 	}
1599 
1600 	log_imsg(smtpd_process, p->proc, imsg);
1601 
1602 	if (profiling & PROFILE_IMSG)
1603 		clock_gettime(CLOCK_MONOTONIC, &t0);
1604 
1605 	msg = imsg->hdr.type;
1606 	imsg_callback(p, imsg);
1607 
1608 	if (profiling & PROFILE_IMSG) {
1609 		clock_gettime(CLOCK_MONOTONIC, &t1);
1610 		timespecsub(&t1, &t0, &dt);
1611 
1612 		log_debug("profile-imsg: %s %s %s %d %lld.%09ld",
1613 		    proc_name(smtpd_process),
1614 		    proc_name(p->proc),
1615 		    imsg_to_str(msg),
1616 		    (int)imsg->hdr.len,
1617 		    (long long)dt.tv_sec,
1618 		    dt.tv_nsec);
1619 
1620 		if (profiling & PROFILE_TOSTAT) {
1621 			char	key[STAT_KEY_SIZE];
1622 			/* can't profstat control process yet */
1623 			if (smtpd_process == PROC_CONTROL)
1624 				return;
1625 
1626 			if (!bsnprintf(key, sizeof key,
1627 				"profiling.imsg.%s.%s.%s",
1628 				proc_name(smtpd_process),
1629 				proc_name(p->proc),
1630 				imsg_to_str(msg)))
1631 				return;
1632 			stat_set(key, stat_timespec(&dt));
1633 		}
1634 	}
1635 }
1636 
1637 void
1638 log_imsg(int to, int from, struct imsg *imsg)
1639 {
1640 
1641 	if (to == PROC_CONTROL && imsg->hdr.type == IMSG_STAT_SET)
1642 		return;
1643 
1644 	if (imsg->fd != -1)
1645 		log_trace(TRACE_IMSG, "imsg: %s <- %s: %s (len=%zu, fd=%d)",
1646 		    proc_name(to),
1647 		    proc_name(from),
1648 		    imsg_to_str(imsg->hdr.type),
1649 		    imsg->hdr.len - IMSG_HEADER_SIZE,
1650 		    imsg->fd);
1651 	else
1652 		log_trace(TRACE_IMSG, "imsg: %s <- %s: %s (len=%zu)",
1653 		    proc_name(to),
1654 		    proc_name(from),
1655 		    imsg_to_str(imsg->hdr.type),
1656 		    imsg->hdr.len - IMSG_HEADER_SIZE);
1657 }
1658 
1659 const char *
1660 proc_title(enum smtp_proc_type proc)
1661 {
1662 	switch (proc) {
1663 	case PROC_PARENT:
1664 		return "[priv]";
1665 	case PROC_LKA:
1666 		return "lookup";
1667 	case PROC_QUEUE:
1668 		return "queue";
1669 	case PROC_CONTROL:
1670 		return "control";
1671 	case PROC_SCHEDULER:
1672 		return "scheduler";
1673 	case PROC_PONY:
1674 		return "pony express";
1675 	case PROC_CA:
1676 		return "klondike";
1677 	default:
1678 		return "unknown";
1679 	}
1680 }
1681 
1682 const char *
1683 proc_name(enum smtp_proc_type proc)
1684 {
1685 	switch (proc) {
1686 	case PROC_PARENT:
1687 		return "parent";
1688 	case PROC_LKA:
1689 		return "lka";
1690 	case PROC_QUEUE:
1691 		return "queue";
1692 	case PROC_CONTROL:
1693 		return "control";
1694 	case PROC_SCHEDULER:
1695 		return "scheduler";
1696 	case PROC_PONY:
1697 		return "pony";
1698 	case PROC_CA:
1699 		return "ca";
1700 	case PROC_FILTER:
1701 		return "filter-proc";
1702 	case PROC_CLIENT:
1703 		return "client-proc";
1704 	default:
1705 		return "unknown";
1706 	}
1707 }
1708 
1709 #define CASE(x) case x : return #x
1710 
1711 const char *
1712 imsg_to_str(int type)
1713 {
1714 	static char	 buf[32];
1715 
1716 	switch (type) {
1717 	CASE(IMSG_NONE);
1718 
1719 	CASE(IMSG_CTL_OK);
1720 	CASE(IMSG_CTL_FAIL);
1721 
1722 	CASE(IMSG_CTL_GET_DIGEST);
1723 	CASE(IMSG_CTL_GET_STATS);
1724 	CASE(IMSG_CTL_LIST_MESSAGES);
1725 	CASE(IMSG_CTL_LIST_ENVELOPES);
1726 	CASE(IMSG_CTL_MTA_SHOW_HOSTS);
1727 	CASE(IMSG_CTL_MTA_SHOW_RELAYS);
1728 	CASE(IMSG_CTL_MTA_SHOW_ROUTES);
1729 	CASE(IMSG_CTL_MTA_SHOW_HOSTSTATS);
1730 	CASE(IMSG_CTL_MTA_BLOCK);
1731 	CASE(IMSG_CTL_MTA_UNBLOCK);
1732 	CASE(IMSG_CTL_MTA_SHOW_BLOCK);
1733 	CASE(IMSG_CTL_PAUSE_EVP);
1734 	CASE(IMSG_CTL_PAUSE_MDA);
1735 	CASE(IMSG_CTL_PAUSE_MTA);
1736 	CASE(IMSG_CTL_PAUSE_SMTP);
1737 	CASE(IMSG_CTL_PROFILE);
1738 	CASE(IMSG_CTL_PROFILE_DISABLE);
1739 	CASE(IMSG_CTL_PROFILE_ENABLE);
1740 	CASE(IMSG_CTL_RESUME_EVP);
1741 	CASE(IMSG_CTL_RESUME_MDA);
1742 	CASE(IMSG_CTL_RESUME_MTA);
1743 	CASE(IMSG_CTL_RESUME_SMTP);
1744 	CASE(IMSG_CTL_RESUME_ROUTE);
1745 	CASE(IMSG_CTL_REMOVE);
1746 	CASE(IMSG_CTL_SCHEDULE);
1747 	CASE(IMSG_CTL_SHOW_STATUS);
1748 	CASE(IMSG_CTL_TRACE_DISABLE);
1749 	CASE(IMSG_CTL_TRACE_ENABLE);
1750 	CASE(IMSG_CTL_UPDATE_TABLE);
1751 	CASE(IMSG_CTL_VERBOSE);
1752 	CASE(IMSG_CTL_DISCOVER_EVPID);
1753 	CASE(IMSG_CTL_DISCOVER_MSGID);
1754 	CASE(IMSG_CTL_UNCORRUPT_MSGID);
1755 
1756 	CASE(IMSG_CTL_SMTP_SESSION);
1757 
1758 	CASE(IMSG_SETUP_KEY);
1759 	CASE(IMSG_SETUP_PEER);
1760 	CASE(IMSG_SETUP_DONE);
1761 
1762 	CASE(IMSG_CONF_START);
1763 	CASE(IMSG_CONF_END);
1764 
1765 	CASE(IMSG_STAT_INCREMENT);
1766 	CASE(IMSG_STAT_DECREMENT);
1767 	CASE(IMSG_STAT_SET);
1768 
1769 	CASE(IMSG_LKA_AUTHENTICATE);
1770 	CASE(IMSG_LKA_OPEN_FORWARD);
1771 	CASE(IMSG_LKA_ENVELOPE_SUBMIT);
1772 	CASE(IMSG_LKA_ENVELOPE_COMMIT);
1773 
1774 	CASE(IMSG_QUEUE_DELIVER);
1775 	CASE(IMSG_QUEUE_DELIVERY_OK);
1776 	CASE(IMSG_QUEUE_DELIVERY_TEMPFAIL);
1777 	CASE(IMSG_QUEUE_DELIVERY_PERMFAIL);
1778 	CASE(IMSG_QUEUE_DELIVERY_LOOP);
1779 	CASE(IMSG_QUEUE_DISCOVER_EVPID);
1780 	CASE(IMSG_QUEUE_DISCOVER_MSGID);
1781 	CASE(IMSG_QUEUE_ENVELOPE_ACK);
1782 	CASE(IMSG_QUEUE_ENVELOPE_COMMIT);
1783 	CASE(IMSG_QUEUE_ENVELOPE_REMOVE);
1784 	CASE(IMSG_QUEUE_ENVELOPE_SCHEDULE);
1785 	CASE(IMSG_QUEUE_ENVELOPE_SUBMIT);
1786 	CASE(IMSG_QUEUE_HOLDQ_HOLD);
1787 	CASE(IMSG_QUEUE_HOLDQ_RELEASE);
1788 	CASE(IMSG_QUEUE_MESSAGE_COMMIT);
1789 	CASE(IMSG_QUEUE_MESSAGE_ROLLBACK);
1790 	CASE(IMSG_QUEUE_SMTP_SESSION);
1791 	CASE(IMSG_QUEUE_TRANSFER);
1792 
1793 	CASE(IMSG_MDA_DELIVERY_OK);
1794 	CASE(IMSG_MDA_DELIVERY_TEMPFAIL);
1795 	CASE(IMSG_MDA_DELIVERY_PERMFAIL);
1796 	CASE(IMSG_MDA_DELIVERY_LOOP);
1797 	CASE(IMSG_MDA_DELIVERY_HOLD);
1798 	CASE(IMSG_MDA_DONE);
1799 	CASE(IMSG_MDA_FORK);
1800 	CASE(IMSG_MDA_HOLDQ_RELEASE);
1801 	CASE(IMSG_MDA_LOOKUP_USERINFO);
1802 	CASE(IMSG_MDA_KILL);
1803 	CASE(IMSG_MDA_OPEN_MESSAGE);
1804 
1805 	CASE(IMSG_MTA_DELIVERY_OK);
1806 	CASE(IMSG_MTA_DELIVERY_TEMPFAIL);
1807 	CASE(IMSG_MTA_DELIVERY_PERMFAIL);
1808 	CASE(IMSG_MTA_DELIVERY_LOOP);
1809 	CASE(IMSG_MTA_DELIVERY_HOLD);
1810 	CASE(IMSG_MTA_DNS_HOST);
1811 	CASE(IMSG_MTA_DNS_HOST_END);
1812 	CASE(IMSG_MTA_DNS_PTR);
1813 	CASE(IMSG_MTA_DNS_MX);
1814 	CASE(IMSG_MTA_DNS_MX_PREFERENCE);
1815 	CASE(IMSG_MTA_HOLDQ_RELEASE);
1816 	CASE(IMSG_MTA_LOOKUP_CREDENTIALS);
1817 	CASE(IMSG_MTA_LOOKUP_SOURCE);
1818 	CASE(IMSG_MTA_LOOKUP_HELO);
1819 	CASE(IMSG_MTA_OPEN_MESSAGE);
1820 	CASE(IMSG_MTA_SCHEDULE);
1821 	CASE(IMSG_MTA_TLS_INIT);
1822 	CASE(IMSG_MTA_TLS_VERIFY_CERT);
1823 	CASE(IMSG_MTA_TLS_VERIFY_CHAIN);
1824 	CASE(IMSG_MTA_TLS_VERIFY);
1825 
1826 	CASE(IMSG_SCHED_ENVELOPE_BOUNCE);
1827 	CASE(IMSG_SCHED_ENVELOPE_DELIVER);
1828 	CASE(IMSG_SCHED_ENVELOPE_EXPIRE);
1829 	CASE(IMSG_SCHED_ENVELOPE_INJECT);
1830 	CASE(IMSG_SCHED_ENVELOPE_REMOVE);
1831 	CASE(IMSG_SCHED_ENVELOPE_TRANSFER);
1832 
1833 	CASE(IMSG_SMTP_AUTHENTICATE);
1834 	CASE(IMSG_SMTP_DNS_PTR);
1835 	CASE(IMSG_SMTP_MESSAGE_COMMIT);
1836 	CASE(IMSG_SMTP_MESSAGE_CREATE);
1837 	CASE(IMSG_SMTP_MESSAGE_ROLLBACK);
1838 	CASE(IMSG_SMTP_MESSAGE_OPEN);
1839 	CASE(IMSG_SMTP_CHECK_SENDER);
1840 	CASE(IMSG_SMTP_EXPAND_RCPT);
1841 	CASE(IMSG_SMTP_LOOKUP_HELO);
1842 	CASE(IMSG_SMTP_TLS_INIT);
1843 	CASE(IMSG_SMTP_TLS_VERIFY_CERT);
1844 	CASE(IMSG_SMTP_TLS_VERIFY_CHAIN);
1845 	CASE(IMSG_SMTP_TLS_VERIFY);
1846 
1847 	CASE(IMSG_SMTP_REQ_CONNECT);
1848 	CASE(IMSG_SMTP_REQ_HELO);
1849 	CASE(IMSG_SMTP_REQ_MAIL);
1850 	CASE(IMSG_SMTP_REQ_RCPT);
1851 	CASE(IMSG_SMTP_REQ_DATA);
1852 	CASE(IMSG_SMTP_REQ_EOM);
1853 	CASE(IMSG_SMTP_EVENT_RSET);
1854 	CASE(IMSG_SMTP_EVENT_COMMIT);
1855 	CASE(IMSG_SMTP_EVENT_ROLLBACK);
1856 	CASE(IMSG_SMTP_EVENT_DISCONNECT);
1857 
1858 	CASE(IMSG_CA_PRIVENC);
1859 	CASE(IMSG_CA_PRIVDEC);
1860 	default:
1861 		(void)snprintf(buf, sizeof(buf), "IMSG_??? (%d)", type);
1862 
1863 		return buf;
1864 	}
1865 }
1866 
1867 int
1868 parent_auth_user(const char *username, const char *password)
1869 {
1870 	char	user[LOGIN_NAME_MAX];
1871 	char	pass[LINE_MAX];
1872 	int	ret;
1873 
1874 	(void)strlcpy(user, username, sizeof(user));
1875 	(void)strlcpy(pass, password, sizeof(pass));
1876 
1877 	ret = auth_userokay(user, NULL, "auth-smtp", pass);
1878 	if (ret)
1879 		return LKA_OK;
1880 	return LKA_PERMFAIL;
1881 }
1882