summaryrefslogtreecommitdiffabout
path: root/mfd/callout.c
blob: acecb26f642af7c7b0e35b345b4f7fa8d8552163 (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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
/* This file is part of Mailfromd.
   Copyright (C) 2005, 2006, 2007, 2008, 2009 Sergey Poznyakoff

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#define MF_SOURCE_NAME  MF_SOURCE_CALLOUT
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <syslog.h>
#include <signal.h>
#include <pwd.h>
#include <grp.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

#include <mailutils/mailutils.h>
#include <mailutils/daemon.h>

#include "mailfromd.h"

#define SMTP_MAJOR(c) ((c)/100)

struct smtp_io_data {
	char *id;            /* I/O id */
	char *email;
	char *ehlo;
	char *mailfrom;

	time_t timeout[SMTP_NUM_TIMEOUT];
	smtp_io_callback_t callback;
	void *callback_closure;
	mu_stream_t stream;  /* I/O stream */
	size_t send_off;     /* Send offset */
	size_t recv_off;     /* Receive offset */
	struct obstack stk;  /* Obstack for keeping commands/replies */
	char *command;       /* Last issued command */ 
	char *reply;         /* Last received reply */
	char *start;         /* First line of the reply, if it was multiline */
	char buf[128];       /* Input buffer */
	size_t level;        /* Number of bytes in buf */
	int code;            /* Reply code */
};

struct smtp_io_data *
smtp_io_create(const char *id, time_t timeout[], smtp_io_callback_t callback,
	       void *closure)
{
	struct smtp_io_data *iop = xzalloc(sizeof(*iop));

	if (!id)
		iop->id = xstrdup("null");
	else {
		size_t len;
		iop->id = xstrdup(id);
		len = strlen(iop->id);
		if (len > 2 && strcmp(iop->id + len - 2, ": ") == 0)
			iop->id[len - 2] = 0;
	}
	memcpy(&iop->timeout, timeout, sizeof(iop->timeout));
	iop->callback = callback;
	iop->callback_closure = closure;
	obstack_init(&iop->stk);
	iop->send_off = iop->recv_off = 0;
	iop->start = iop->command = iop->reply = NULL;
	iop->level = 0;
	return iop;
}

static void
replstr(char **pdst, const char *str)
{
	if (*pdst)
		free(*pdst);
	*pdst = xstrdup(str);
}

void
smtp_io_init(struct smtp_io_data *iop)
{
	iop->send_off = iop->recv_off = 0;
	iop->start = iop->command = iop->reply = NULL;
	iop->level = 0;
}	
	
void
smtp_io_setup_callout(struct smtp_io_data *iop,
		      const char *email,
		      const char *ehlo,
		      const char *mailfrom)
{
	replstr(&iop->email, email);
	replstr(&iop->ehlo, ehlo);
	replstr(&iop->mailfrom, mailfrom);
}

void
smtp_io_free(struct smtp_io_data *iop)
{
	if (iop->stream) {
		mu_stream_close (iop->stream);
		mu_stream_destroy(&iop->stream,
				  mu_stream_get_owner(iop->stream));
	}
	obstack_free(&iop->stk, NULL);
	free(iop->id);
	free(iop->email);
	free(iop->ehlo);
	free(iop->mailfrom);
	free(iop);
}

void
transcript(const char *id, char *prefix, const char *msg)
{
	if (do_transcript) {
		int len = strlen(msg);
		if (msg[len-1] == '\n') {
			--len;
			if (len > 0 && msg[len-1] == '\r')
				--len;
		}
		if (len) 
			logmsg(LOG_INFO, "%s: %s %*.*s",
			       id,
			       prefix, len, len, msg);
	}
}


struct timeout_ctl {
  time_t start;
  time_t timeout;
};

static void
init_timeout_ctl(struct timeout_ctl *tctl, time_t timeout)
{
	tctl->start = time(NULL);
	tctl->timeout = timeout;
}

#define UPDATE_TTW(t) do {                                           \
        time_t now = time(NULL);                                     \
	time_t delta = now - (t).start;                              \
	if ((t).timeout > delta)                                     \
		(t).timeout -= delta;                                \
	else                                                         \
		(t).timeout = 0;                                     \
        (t).start = now;                                             \
} while (0)

static int
smtp_stream_wait(mu_stream_t stream, int flags, struct timeout_ctl *tctl)
{
	int rc;
	int oflags = flags;
	struct timeval tv;
	
	while (tctl->timeout) {
		tv.tv_sec = tctl->timeout;
		tv.tv_usec = 0;
		rc = mu_stream_wait(stream, &oflags, &tv);

		/* Correct the timeout */
		UPDATE_TTW(*tctl);
		
		switch (rc) {
		case 0:
			if (flags & oflags)
				return 0;
			/* FALLTHROUGH */
		case EAGAIN:
		case EINPROGRESS:
			continue;

		default:
			return rc;
		}
	}
			
	return ETIMEDOUT;
}

static int
smtp_wait(struct smtp_io_data *iop, int flags, struct timeout_ctl *tctl)
{
	return smtp_stream_wait(iop->stream, flags, tctl);
}

static int
smtp_send(struct smtp_io_data *iop, const char *command)
{
	size_t len = strlen(command);
	struct timeout_ctl tctl;

	init_timeout_ctl (&tctl, io_timeout);
	
	iop->reply = NULL; /* Clear reply for logging purposes */
	transcript(iop->id, "SEND:", command);
	do {
		size_t nb;
		int rc;
		
		UPDATE_TTW(tctl);
		
		rc = mu_stream_write(iop->stream, command, len,
					 iop->send_off, &nb);
		if (rc == 0) {
			if (nb == 0) {
				mu_error(_("stream_write: wrote 0 bytes"));
				return -1;
			}
			iop->send_off += nb;
			len -= nb;
			command += nb;
		} else if (rc == EAGAIN) {
			rc = smtp_wait(iop, MU_STREAM_READY_WR, &tctl);
			if (rc) {
				mu_error(_("smtp_wait failed: %s"),
					  mu_strerror(rc));
				return -1;
			}
			continue;
		} else {
			mu_error("mu_stream_write: %s",
				  mu_strerror (rc));
			return -1;
		}
	} while (len > 0);
	return 0;
}

static int
smtp_send2(struct smtp_io_data *iop, const char *command, const char *arg)
{
	obstack_grow(&iop->stk, command, strlen(command));
	if (arg)
		obstack_grow(&iop->stk, arg, strlen(arg));
	obstack_grow(&iop->stk, "\r\n", 2);
	obstack_1grow(&iop->stk, 0);
	iop->command = obstack_finish(&iop->stk);
	
	return smtp_send(iop, iop->command);
}

static int
smtp_send3(struct smtp_io_data *iop, const char *command,
	   const char *arg1, const char *arg2)
{
	obstack_grow(&iop->stk, command, strlen(command));
	obstack_grow(&iop->stk, arg1, strlen(arg1));
	obstack_grow(&iop->stk, arg2, strlen(arg2));
	obstack_grow(&iop->stk, "\r\n", 2);
	obstack_1grow(&iop->stk, 0);
	iop->command = obstack_finish(&iop->stk);
	
	return smtp_send(iop, iop->command);
}

static int
smtp_recvline(struct smtp_io_data *iop, enum smtp_timeout to)
{
	struct timeout_ctl tctl;
	
	init_timeout_ctl(&tctl, iop->timeout[to]);
	for (;;) {
		char *p;
		
		UPDATE_TTW(tctl);
		
		if (iop->level == 0) {
			int rc = mu_stream_read(iop->stream,
						iop->buf, sizeof iop->buf,
						iop->recv_off, &iop->level);
			if (rc == 0) {
				if (iop->level == 0) {
					mu_error(_("stream_read: read 0 bytes"));
					return -1;
				}
				iop->recv_off += iop->level;
			} else if (rc == EAGAIN) {
				rc = smtp_wait(iop, 
					       MU_STREAM_READY_RD, &tctl);
				if (rc) {
					mu_error(_("smtp_wait failed: %s"),
						  mu_strerror(rc));
					return -1;
				}
				continue;
			} else {
				mu_error("mu_stream_read: %s",
					  mu_strerror (rc));
				return -1;
			}
		}


		p = memchr(iop->buf, '\n', iop->level);
		if (!p) {
			obstack_grow(&iop->stk, iop->buf, iop->level);
			iop->level = 0;
			continue;
		} else {
			size_t len = p - iop->buf + 1;
			obstack_grow(&iop->stk, iop->buf, len);
			obstack_1grow(&iop->stk, 0);
			iop->reply = obstack_finish(&iop->stk);
			iop->level -= len;
			memmove(iop->buf, iop->buf + len, iop->level);
			break;
		}
	}
	return 0;
}

static int
smtp_recv(struct smtp_io_data *iop, enum smtp_timeout to)
{
	char *p;
	iop->start = NULL;
	do {
		int code;
		int rc = smtp_recvline(iop, to);
		if (rc)
			return -1;
		transcript(iop->id, "RECV:", iop->reply);
		code = strtoul(iop->reply, &p, 0);
		if (p - iop->reply != 3 || (*p != '-' && *p != ' ')) {
			mu_error(_("unexpected reply from server: %s"),
				 iop->reply);
			return -1;
		} else if (!iop->start) {
			iop->start = iop->reply;
			iop->code = code;
		} else if (iop->code != code) {
			mu_error(_("unexpected reply code from server: %d"),
				 code);
			return -1;
		}
	} while (*p == '-');
	obstack_1grow (&iop->stk, 0);
	obstack_finish (&iop->stk);
	return 0;
}

const char *
smtp_last_sent(struct smtp_io_data *iop)
{
	if (iop->command) {
		size_t len = strcspn(iop->command, "\r\n");
		iop->command[len] = 0;
		return iop->command;
	}
	return "nothing";
}

const char *
smtp_last_received(struct smtp_io_data *iop)
{
	if (iop->reply) {
		size_t len = strcspn(iop->reply, "\r\n");
		iop->reply[len] = 0;
		return iop->reply;
	}
	return "nothing";
}

const char *
smtp_io_email(struct smtp_io_data *iop)
{
	return iop->email;
}


/* Milter-specific functions */

static mf_status
reset(struct smtp_io_data *io)
{
	smtp_send(io, "RSET");
	if (smtp_recv(io, smtp_timeout_rset)) 
		return mf_temp_failure;
	else if (SMTP_MAJOR(io->code) != 2) 
		return SMTP_MAJOR(io->code) == 4 ?
			mf_temp_failure : mf_failure;
	return mf_success;
}

static mf_status
callout_io(struct smtp_io_data *io, const char *hostname, mu_address_t addr)
{
	size_t i;
	size_t mailcount;
	mf_status status;
	
	if (io->callback)
		io->callback(io->callback_closure, "INIT", 
			     smtp_last_received(io));
	
	mu_address_get_count(addr, &mailcount);
		
	if (smtp_recv(io, smtp_timeout_initial))
		return mf_temp_failure;

	if (io->callback)
		io->callback(io->callback_closure, "GRTNG", 
			     smtp_last_received(io));

	if (SMTP_MAJOR(io->code) != 2) 
		return SMTP_MAJOR(io->code) == 4 ?
			mf_temp_failure : mf_not_found;
			
	smtp_send2(io, "HELO ", io->ehlo);
	if (smtp_recv(io, smtp_timeout_helo))
		return mf_temp_failure;

	if (SMTP_MAJOR(io->code) == 5) {
		/* Let's try EHLO, then */
		smtp_send2(io, "EHLO ", io->ehlo);
		if (smtp_recv(io, smtp_timeout_helo))
			return mf_not_found;
	}

	if (io->callback)
		io->callback(io->callback_closure,
			     "HELO", smtp_last_received(io));
	
	if (SMTP_MAJOR(io->code) != 2)
		return SMTP_MAJOR(io->code) == 4 ?
			mf_temp_failure : mf_not_found;

	status = mf_success;
	for (i = 1; i <= mailcount; i++) {
		const char *fromaddr;
			
		mu_address_sget_email(addr, i, &fromaddr);
			
		smtp_send3(io, "MAIL FROM:<", fromaddr, ">");
		
		if (smtp_recv(io, smtp_timeout_mail))
			return mf_temp_failure;
		else if (SMTP_MAJOR(io->code) != 2) {
			if (SMTP_MAJOR(io->code) == 4) {
				if (reset(io) != mf_success) {
					/* RSET must always return 250
					   If it does not, there's no
					   use talking to this host
					   any more */
					return mf_failure;
				} else
					status = mf_temp_failure;
			} else
				status = mf_not_found;
		} else {
			status = mf_success;
			break;
		}
	}
	if (status != mf_success)
		return status;

	smtp_send3(io, "RCPT TO:<", io->email, ">");
	if (smtp_recv(io, smtp_timeout_rcpt))
		return mf_temp_failure;
	else if (SMTP_MAJOR(io->code) != 2) 
		return SMTP_MAJOR(io->code) == 4 ?
				mf_temp_failure : mf_not_found;
	return mf_success;
}	


mf_status
smtp_io_open(struct smtp_io_data *io, const char *hostname)
{
	int rc;
	mu_stream_t stream;
	struct timeout_ctl tctl;
	
	rc = mu_tcp_stream_create_with_source_ip (&stream, hostname, 25,
						  source_address,
						  MU_STREAM_NONBLOCK);
	if (rc) {
		mu_error(_("%s: cannot connect to `%s': %s"),
			 io->id, hostname,
			 mu_strerror(rc));
		return mf_temp_failure;
	}
	
	init_timeout_ctl(&tctl, io->timeout[smtp_timeout_connect]);
	while ((rc = mu_stream_open(stream))) {
		if ((rc == EAGAIN || rc == EINPROGRESS)
		    && tctl.timeout) {
			rc = smtp_stream_wait(stream, MU_STREAM_READY_WR,
					      &tctl);
			if (rc == 0) {
				UPDATE_TTW(tctl);
				continue;
			}
		}
		mu_error("%s: stream_open: %s",
			 io->id, mu_strerror(rc));
		mu_stream_destroy(&stream, mu_stream_get_owner(stream));
		return mf_temp_failure;
	}
	debug(100,"stream opened");
	io->stream = stream;
	return mf_success;
}

void
smtp_io_close(struct smtp_io_data *io)
{
	if (io->stream) {
		mu_stream_close(io->stream);
		mu_stream_destroy(&io->stream,
				  mu_stream_get_owner(io->stream));
	}
}

mf_status
callout_host(struct smtp_io_data *io, const char *hostname)
{
	int rc;
	mf_status status = mf_success;
	mu_address_t addr;
	const char *mailfrom;
	
	debug2(10, "email = %s, hostname = %s", io->email, hostname);

	smtp_io_init(io);
	status = smtp_io_open(io, hostname);
	if (status != mf_success)
		return status;

	/* FIXME-MU: compensate for mailutils deficiency */
	mailfrom = (io->mailfrom[0] == 0) ? "<>" : io->mailfrom;
	rc = mu_address_create(&addr, mailfrom);
	if (rc) {
		mu_error(_("cannot create address `%s': %s"),
			 mailfrom, mu_strerror(rc));
		return mf_temp_failure;
	}

	status = callout_io(io, hostname, addr);
	
	mu_address_destroy(&addr); 

	if (io->callback) {
		io->callback(io->callback_closure,
			     "SENT", smtp_last_sent(io));
		io->callback(io->callback_closure,
			     "RECV", smtp_last_received(io));
	}
	
	debug4(1,
	       "%s: poll exited with status: %s; sent \"%s\", got \"%s\"",
	       io->id,
	       mf_status_str(status),
	       smtp_last_sent(io),
	       smtp_last_received(io));
	
	smtp_send2(io, "QUIT", NULL);
	smtp_recv(io, smtp_timeout_quit);

	smtp_io_close(io);
	
	return status;
}

mf_status
callout_mx(struct smtp_io_data *iop, const char *hostname, int *pcount)
{
	int i;
	mxbuf_t mxbuf;
	mf_status rc, mxstat = getmx(hostname, mxbuf);

	if (pcount)
		*pcount = 0;
	switch (mxstat) {
	case mf_temp_failure:
	case mf_failure:
	case mf_not_found:
		rc = mxstat;
		break;

	case mf_success:
		debug1(2,"Checking MX servers for %s", iop->email);
		rc = mf_not_found;
		for (i = 0; i < MAXMXCOUNT && mxbuf[i]; i++) {
			rc = callout_host(iop, mxbuf[i]);
			if (mf_resolved(rc))
				break;
		}
		if (pcount) {
			for (; i < MAXMXCOUNT && mxbuf[i]; i++)
				;
			*pcount = i;
		}
		dns_freemx(mxbuf);
		break;
		
	default:
		abort();
	}
	return rc;
}

/* Method "strict". Verifies whether EMAIL is understood either by
   host CLIENT_ADDR or one of MX servers of its domain */
mf_status
callout_strict(struct smtp_io_data *iop, const char *hostname)
{
	mf_status rc;

	rc = callout_host(iop, hostname);
	if (!mf_resolved(rc)) {
		int mxcount;
		mf_status mx_stat;
		mx_stat = callout_mx(iop, hostname, &mxcount);
		if (!(mx_stat == mf_not_found && mxcount == 0)
		    && (mf_resolved(mx_stat)
			|| mx_stat == mf_temp_failure))
			rc = mx_stat;
	}
	return rc;
}

mf_status
callout_standard(struct smtp_io_data *iop)
{
	int rc;
	
	char *p = strchr(iop->email, '@');
	if (p == NULL) {
		mu_error(_("invalid address: %s"), iop->email);
		rc = mf_not_found;
	} else {
		int mxcount;
		p++;
		rc = callout_mx(iop, p, &mxcount);
		if (rc != mf_success && mxcount == 0) {
			mf_status host_stat;
			host_stat = callout_host(iop, p);
			if (mf_resolved(host_stat)
			    || host_stat == mf_temp_failure)
				rc = host_stat;
		}
	}
	return rc;
}


mf_status
listens_on (const char *hostname, int port, time_t timeout)
{
	unsigned count = 0;
	mu_stream_t stream;
	int rc;
	struct timeout_ctl tctl;
	
	if (port == 0)
		port = 25;

	debug2(10, "hostname = %s, port = %d", hostname, port);
	rc = mu_tcp_stream_create_with_source_ip (&stream, hostname, port,
						  source_address,
						  MU_STREAM_NONBLOCK);
	if (rc) {
		debug1 (10, "mu_tcp_stream_create_with_source_ip: %s",
			mu_strerror (rc));
		return mf_failure;
	}

	init_timeout_ctl(&tctl, timeout);
	while ((rc = mu_stream_open(stream))) {
		if ((rc == EAGAIN || rc == EINPROGRESS) && tctl.timeout) {
			rc = smtp_stream_wait(stream, MU_STREAM_READY_WR,
                                              &tctl);
			if (rc == 0) {
				UPDATE_TTW(tctl);
				continue;
			}
		}
		break;
	}
	mu_stream_destroy(&stream, mu_stream_get_owner(stream));

	debug3 (10, "mu_stream_open(%s): %s, %u", hostname, mu_strerror(rc),
		count);

	return rc == 0 ? mf_success :
		(rc == EAGAIN || rc == EINPROGRESS) ?
		mf_temp_failure : mf_failure;
}

Return to:

Send suggestions and report system problems to the System administrator.