summaryrefslogtreecommitdiff
path: root/usr.sbin/smtpd/mda.c
blob: 40d0a9b81794ee271e3a4180d29a8d2941b4c3d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
/*	$OpenBSD: mda.c,v 1.35 2010/01/03 14:37:37 chl Exp $	*/

/*
 * Copyright (c) 2008 Gilles Chehade <gilles@openbsd.org>
 * Copyright (c) 2008 Pierre-Yves Ritschard <pyr@openbsd.org>
 * Copyright (c) 2009 Jacek Masiulaniec <jacekm@dobremiasto.net>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/types.h>
#include <sys/queue.h>
#include <sys/tree.h>
#include <sys/param.h>
#include <sys/socket.h>

#include <event.h>
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include "smtpd.h"

__dead void	mda_shutdown(void);
void		mda_sig_handler(int, short, void *);
void		mda_dispatch_parent(int, short, void *);
void		mda_dispatch_queue(int, short, void *);
void		mda_dispatch_runner(int, short, void *);
void		mda_setup_events(struct smtpd *);
void		mda_disable_events(struct smtpd *);
void		mda_store(struct batch *);
void		mda_event(int, short, void *);
void		mda_store_done(struct batch *);
void		mda_done(struct smtpd *, struct batch *);

void
mda_sig_handler(int sig, short event, void *p)
{
	switch (sig) {
	case SIGINT:
	case SIGTERM:
		mda_shutdown();
		break;
	default:
		fatalx("mda_sig_handler: unexpected signal");
	}
}

void
mda_dispatch_parent(int sig, short event, void *p)
{
	struct smtpd		*env = p;
	struct imsgev		*iev;
	struct imsgbuf		*ibuf;
	struct imsg		 imsg;
	ssize_t			 n;

	iev = env->sc_ievs[PROC_PARENT];
	ibuf = &iev->ibuf;

	if (event & EV_READ) {
		if ((n = imsg_read(ibuf)) == -1)
			fatal("imsg_read_error");
		if (n == 0) {
			/* this pipe is dead, so remove the event handler */
			event_del(&iev->ev);
			event_loopexit(NULL);
			return;
		}
	}

	if (event & EV_WRITE) {
		if (msgbuf_write(&ibuf->w) == -1)
			fatal("msgbuf_write");
	}

	for (;;) {
		if ((n = imsg_get(ibuf, &imsg)) == -1)
			fatal("mda_dispatch_parent: imsg_get error");
		if (n == 0)
			break;

		switch (imsg.hdr.type) {
		case IMSG_PARENT_MAILBOX_OPEN: {
			struct batch		*b = imsg.data;

			IMSG_SIZE_CHECK(b);

			if ((b = batch_by_id(env, b->id)) == NULL)
				fatalx("mda: internal inconsistency");

			/* parent ensures mboxfd is valid */
			if (imsg.fd == -1)
				fatalx("mda: mboxfd pass failure");

			/* got user's mbox fd */
			if ((b->mboxfp = fdopen(imsg.fd, "w")) == NULL) {
				log_warn("mda: fdopen");
				mda_done(env, b);
				break;
			}

			/* 
			 * From now on, delivery session must be deinited in
			 * the parent process as well as in mda.
			 */
			b->cleanup_parent = 1;

			/* get message content fd */
			imsg_compose_event(env->sc_ievs[PROC_PARENT],
			    IMSG_PARENT_MESSAGE_OPEN, 0, 0, -1, b,
			    sizeof(*b));
			break;
		}

		case IMSG_PARENT_MESSAGE_OPEN: {
			struct batch	*b = imsg.data;

			IMSG_SIZE_CHECK(b);

			if ((b = batch_by_id(env, b->id)) == NULL)
				fatalx("mda: internal inconsistency");

			if (imsg.fd == -1) {
				mda_done(env, b);
				break;
			}

			if ((b->datafp = fdopen(imsg.fd, "r")) == NULL) {
				log_warn("mda: fdopen");
				mda_done(env, b);
				break;
			}

			/* got message content, copy it to mbox */
			mda_store(b);
			break;
		}

		case IMSG_MDA_FINALIZE: {
			struct batch		*b = imsg.data;
			enum message_status	 status;

			IMSG_SIZE_CHECK(b);

			status = b->message.status;
			if ((b = batch_by_id(env, b->id)) == NULL)
				fatalx("mda: internal inconsistency");
			b->message.status = status;

			mda_done(env, b);
			break;
		}

		case IMSG_CTL_VERBOSE: {
			int verbose;

			IMSG_SIZE_CHECK(&verbose);

			memcpy(&verbose, imsg.data, sizeof(verbose));
			log_verbose(verbose);
			break;
		}
		default:
			log_warnx("mda_dispatch_parent: got imsg %d",
			    imsg.hdr.type);
			fatalx("mda_dispatch_parent: unexpected imsg");
		}
		imsg_free(&imsg);
	}
	imsg_event_add(iev);
}

void
mda_dispatch_queue(int sig, short event, void *p)
{
	struct smtpd		*env = p;
	struct imsgev		*iev;
	struct imsgbuf		*ibuf;
	struct imsg		 imsg;
	ssize_t			 n;

	iev = env->sc_ievs[PROC_QUEUE];
	ibuf = &iev->ibuf;

	if (event & EV_READ) {
		if ((n = imsg_read(ibuf)) == -1)
			fatal("imsg_read_error");
		if (n == 0) {
			/* this pipe is dead, so remove the event handler */
			event_del(&iev->ev);
			event_loopexit(NULL);
			return;
		}
	}

	if (event & EV_WRITE) {
		if (msgbuf_write(&ibuf->w) == -1)
			fatal("msgbuf_write");
	}

	for (;;) {
		if ((n = imsg_get(ibuf, &imsg)) == -1)
			fatal("mda_dispatch_queue: imsg_get error");
		if (n == 0)
			break;

		switch (imsg.hdr.type) {
		default:
			log_warnx("mda_dispatch_queue: got imsg %d",
			    imsg.hdr.type);
			fatalx("mda_dispatch_queue: unexpected imsg");
		}
		imsg_free(&imsg);
	}
	imsg_event_add(iev);
}

void
mda_dispatch_runner(int sig, short event, void *p)
{
	struct smtpd		*env = p;
	struct imsgev		*iev;
	struct imsgbuf		*ibuf;
	struct imsg		 imsg;
	ssize_t			 n;

	iev = env->sc_ievs[PROC_RUNNER];
	ibuf = &iev->ibuf;

	if (event & EV_READ) {
		if ((n = imsg_read(ibuf)) == -1)
			fatal("imsg_read_error");
		if (n == 0) {
			/* this pipe is dead, so remove the event handler */
			event_del(&iev->ev);
			event_loopexit(NULL);
			return;
		}
	}

	if (event & EV_WRITE) {
		if (msgbuf_write(&ibuf->w) == -1)
			fatal("msgbuf_write");
	}

	for (;;) {
		if ((n = imsg_get(ibuf, &imsg)) == -1)
			fatal("mda_dispatch_runner: imsg_get error");
		if (n == 0)
			break;

		switch (imsg.hdr.type) {
		case IMSG_BATCH_CREATE: {
			struct batch	*req = imsg.data;
			struct batch	*b;

			IMSG_SIZE_CHECK(req);

			/* runner opens delivery session */
			if ((b = malloc(sizeof(*b))) == NULL)
				fatal(NULL);
			*b = *req;
			b->env = env;
			b->mboxfp = NULL;
			b->datafp = NULL;
			SPLAY_INSERT(batchtree, &env->batch_queue, b);
			break;
		}

		case IMSG_BATCH_APPEND: {
			struct message	*append = imsg.data;
			struct batch	*b;

			IMSG_SIZE_CHECK(append);

			/* runner submits the message to deliver */
			if ((b = batch_by_id(env, append->batch_id)) == NULL)
				fatalx("mda: internal inconsistency");
			if (b->message.message_id[0])
				fatal("mda: runner submitted extra msg");
			b->message = *append;

			/* safe default */
			b->message.status = S_MESSAGE_TEMPFAILURE;
			break;
		}

		case IMSG_BATCH_CLOSE: {
			struct batch	*b = imsg.data;

			IMSG_SIZE_CHECK(b);

			/* runner finished opening delivery session;
			 * request user's mbox fd */
			if ((b = batch_by_id(env, b->id)) == NULL)
				fatalx("mda: internal inconsistency");
			imsg_compose_event(env->sc_ievs[PROC_PARENT],
			    IMSG_PARENT_MAILBOX_OPEN, 0, 0, -1, b,
			    sizeof(*b));
			break;
		}
		default:
			log_warnx("mda_dispatch_runner: got imsg %d",
			    imsg.hdr.type);
			fatalx("mda_dispatch_runner: unexpected imsg");
		}
		imsg_free(&imsg);
	}
	imsg_event_add(iev);
}


void
mda_shutdown(void)
{
	log_info("mail delivery agent exiting");
	_exit(0);
}

void
mda_setup_events(struct smtpd *env)
{
}

void
mda_disable_events(struct smtpd *env)
{
}

pid_t
mda(struct smtpd *env)
{
	pid_t		 pid;
	struct passwd	*pw;

	struct event	 ev_sigint;
	struct event	 ev_sigterm;

	struct peer peers[] = {
		{ PROC_PARENT,	mda_dispatch_parent },
		{ PROC_QUEUE,	mda_dispatch_queue },
		{ PROC_RUNNER,	mda_dispatch_runner }
	};

	switch (pid = fork()) {
	case -1:
		fatal("mda: cannot fork");
	case 0:
		break;
	default:
		return (pid);
	}

	purge_config(env, PURGE_EVERYTHING);

	pw = env->sc_pw;

#ifndef DEBUG
	if (chroot(pw->pw_dir) == -1)
		fatal("mda: chroot");
	if (chdir("/") == -1)
		fatal("mda: chdir(\"/\")");
#else
#warning disabling privilege revocation and chroot in DEBUG MODE
#endif

	smtpd_process = PROC_MDA;
	setproctitle("%s", env->sc_title[smtpd_process]);

#ifndef DEBUG
	if (setgroups(1, &pw->pw_gid) ||
	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
		fatal("mda: cannot drop privileges");
#endif

	SPLAY_INIT(&env->batch_queue);

	event_init();

	signal_set(&ev_sigint, SIGINT, mda_sig_handler, env);
	signal_set(&ev_sigterm, SIGTERM, mda_sig_handler, env);
	signal_add(&ev_sigint, NULL);
	signal_add(&ev_sigterm, NULL);
	signal(SIGPIPE, SIG_IGN);
	signal(SIGHUP, SIG_IGN);

	config_pipes(env, peers, nitems(peers));
	config_peers(env, peers, nitems(peers));

	mda_setup_events(env);
	event_dispatch();
	mda_shutdown();

	return (0);
}

void
mda_store(struct batch *b)
{
	char		*p;
	int		 ch, ret;
	socklen_t	 len;

	if (b->message.sender.user[0] && b->message.sender.domain[0])
		/* XXX: remove user provided Return-Path, if any */
		ret = asprintf(&p, "Return-Path: %s@%s\nDelivered-To: %s@%s\n",
		    b->message.sender.user,
		    b->message.sender.domain,
		    b->message.session_rcpt.user,
		    b->message.session_rcpt.domain);
	else
		ret = asprintf(&p, "Delivered-To: %s@%s\n",
		    b->message.session_rcpt.user,
		    b->message.session_rcpt.domain);

	if (ret == -1)
		fatal("mda_store: asprintf");

	if (b->message.recipient.rule.r_action == A_MAILDIR) {
		fprintf(b->mboxfp, "%s", p);
		while ((ch = fgetc(b->datafp)) != EOF)
			if (fputc(ch, b->mboxfp) == EOF)
				break;
		if (ferror(b->datafp))
			fatal("mda_store: cannot read message in queue");
		if (fflush(b->mboxfp) || ferror(b->mboxfp))
			fatal("mda_store: cannot write to file");
		mda_store_done(b);
	} else {
		session_socket_blockmode(fileno(b->mboxfp), BM_NONBLOCK);
		len = sizeof(b->rbufsz);
		if (getsockopt(fileno(b->mboxfp), SOL_SOCKET, SO_SNDLOWAT,
		    &b->rbufsz, &len) == -1)
			fatal("mda_store: getsockopt");
		if ((b->rbuf = malloc(b->rbufsz)) == NULL)
			fatal(NULL);
		if (write(fileno(b->mboxfp), p, ret) != ret)
			fatal("mda_store: write");
		event_set(&b->ev, fileno(b->mboxfp), EV_WRITE|EV_PERSIST,
		    mda_event, b);
		event_add(&b->ev, NULL);
	}

	free(p);
}

void
mda_event(int fd, short event, void *p)
{
	struct batch	*b = p;
	size_t		 len;

	len = fread(b->rbuf, 1, b->rbufsz, b->datafp);
	if (ferror(b->datafp))
		fatal("mda_event: fread");
	if (write(fd, b->rbuf, len) != (ssize_t)len)
		fatal("mda_event: write");
	if (feof(b->datafp)) {
		event_del(&b->ev);
		mda_store_done(b);
	}
}

void
mda_store_done(struct batch *b)
{
	fclose(b->datafp);
	b->datafp = NULL;

	/* closing mboxfd will trigger EOF in forked mda */
	fsync(fileno(b->mboxfp));
	fclose(b->mboxfp);
	b->mboxfp = NULL;

	/* ... unless it is maildir, in which case we need to
	 * "trigger EOF" differently */
	if (b->message.recipient.rule.r_action == A_MAILDIR)
		imsg_compose_event(b->env->sc_ievs[PROC_PARENT],
		    IMSG_PARENT_MAILDIR_RENAME, 0, 0, -1, b,
		    sizeof(*b));

	/* Waiting for IMSG_MDA_FINALIZE... */
	b->cleanup_parent = 0;
}

void
mda_done(struct smtpd *env, struct batch *b)
{
	if (b->cleanup_parent) {
		/*
		 * Error has occured while both parent and mda maintain some
		 * state for this delivery session.  Need to deinit both.
		 * Deinit parent first.
		 */

		if (b->message.recipient.rule.r_action == A_MAILDIR) {
			/*
			 * In case of maildir, deiniting parent's state consists
			 * of removing the file in tmp.
			 */
			imsg_compose_event(env->sc_ievs[PROC_PARENT],
			    IMSG_PARENT_MAILDIR_FAIL, 0, 0, -1, b,
			    sizeof(*b));
		} else {
			/*
			 * In all other cases, ie. mbox and external, deiniting
			 * parent's state consists of killing its child, and
			 * freeing associated struct child.
			 *
			 * Requesting that parent does this cleanup involves
			 * racing issues.  The race-free way is to simply wait.
			 * Eventually, child timeout in parent will be hit.
			 */
		}

		/*
		 * Either way, parent will eventually send IMSG_MDA_FINALIZE.
		 * Then, the mda deinit will happen.
		 */
		b->cleanup_parent = 0;
	} else {
		/*
		 * Deinit mda.
		 */

		/* update runner (currently: via queue) */
		imsg_compose_event(env->sc_ievs[PROC_QUEUE],
		    IMSG_QUEUE_MESSAGE_UPDATE, 0, 0, -1,
		    &b->message, sizeof(b->message));

		imsg_compose_event(env->sc_ievs[PROC_RUNNER],
		    IMSG_BATCH_DONE, 0, 0, -1, NULL, 0);

		/* log status */
		log_info("%s: to=<%s@%s>, delay=%d, stat=%s",
		    b->message.message_id,
		    b->message.recipient.user,
		    b->message.recipient.domain,
		    time(NULL) - b->message.creation,
		    b->message.status & S_MESSAGE_PERMFAILURE ? "MdaPermError" :
		    b->message.status & S_MESSAGE_TEMPFAILURE ? "MdaTempError" :
		    "Sent");

		/* deallocate resources */
		SPLAY_REMOVE(batchtree, &env->batch_queue, b);
		if (b->mboxfp)
			fclose(b->mboxfp);
		if (b->datafp)
			fclose(b->datafp);
		free(b->rbuf);
		free(b);
	}
}