xref: /dragonfly/libexec/dma/net.c (revision 19fe1c42)
1 /*
2  * Copyright (c) 2008 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthias Schmidt <matthias@dragonflybsd.org>, University of Marburg,
6  * Germany.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  * 3. Neither the name of The DragonFly Project nor the names of its
19  *    contributors may be used to endorse or promote products derived
20  *    from this software without specific, prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
26  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  * $DragonFly: src/libexec/dma/net.c,v 1.9 2008/09/30 17:47:21 swildner Exp $
36  */
37 
38 #include <sys/param.h>
39 #include <sys/queue.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <sys/socket.h>
43 #include <netinet/in.h>
44 #include <arpa/inet.h>
45 
46 #ifdef HAVE_CRYPTO
47 #include <openssl/ssl.h>
48 #endif /* HAVE_CRYPTO */
49 
50 #include <err.h>
51 #include <netdb.h>
52 #include <setjmp.h>
53 #include <signal.h>
54 #include <syslog.h>
55 #include <unistd.h>
56 
57 #include "dma.h"
58 
59 extern struct config *config;
60 extern struct authusers authusers;
61 static jmp_buf timeout_alarm;
62 
63 static void
64 sig_alarm(int signo __unused)
65 {
66 	longjmp(timeout_alarm, 1);
67 }
68 
69 ssize_t
70 send_remote_command(int fd, const char* fmt, ...)
71 {
72 	va_list va;
73 	char cmd[4096];
74 	ssize_t len = 0;
75 
76 	va_start(va, fmt);
77 	vsprintf(cmd, fmt, va);
78 
79 	if (((config->features & SECURETRANS) != 0) &&
80 	    ((config->features & NOSSL) == 0)) {
81 		len = SSL_write(config->ssl, (const char*)cmd, strlen(cmd));
82 		SSL_write(config->ssl, "\r\n", 2);
83 	}
84 	else {
85 		len = write(fd, cmd, strlen(cmd));
86 		write(fd, "\r\n", 2);
87 	}
88 	va_end(va);
89 
90 	return (len+2);
91 }
92 
93 int
94 read_remote(int fd, int extbufsize, char *extbuf)
95 {
96 	ssize_t rlen = 0;
97 	size_t pos, len;
98 	char buff[BUF_SIZE];
99 	int done = 0, status = 0, extbufpos = 0;
100 
101 	if (signal(SIGALRM, sig_alarm) == SIG_ERR) {
102 		syslog(LOG_ERR, "SIGALRM error: %m");
103 	}
104 	if (setjmp(timeout_alarm) != 0) {
105 		syslog(LOG_ERR, "Timeout reached");
106 		return (1);
107 	}
108 	alarm(CON_TIMEOUT);
109 
110 	/*
111 	 * Remote reading code from femail.c written by Henning Brauer of
112 	 * OpenBSD and released under a BSD style license.
113 	 */
114 	for (len = pos = 0; !done; ) {
115 		rlen = 0;
116 		if (pos == 0 ||
117 		    (pos > 0 && memchr(buff + pos, '\n', len - pos) == NULL)) {
118 			memmove(buff, buff + pos, len - pos);
119 			len -= pos;
120 			pos = 0;
121 			if (((config->features & SECURETRANS) != 0) &&
122 			    (config->features & NOSSL) == 0) {
123 				if ((rlen = SSL_read(config->ssl, buff + len,
124 				    sizeof(buff) - len)) == -1)
125 					err(1, "read");
126 			} else {
127 				if ((rlen = read(fd, buff + len,
128 				    sizeof(buff) - len)) == -1)
129 					err(1, "read");
130 			}
131 			len += rlen;
132 		}
133 		/*
134 		 * If there is an external buffer with a size bigger than zero
135 		 * and as long as there is space in the external buffer and
136 		 * there are new characters read from the mailserver
137 		 * copy them to the external buffer
138 		 */
139 		if (extbufpos <= (extbufsize - 1) && rlen && extbufsize > 0
140 		    && extbuf != NULL) {
141 			/* do not write over the bounds of the buffer */
142 			if(extbufpos + rlen > (extbufsize - 1)) {
143 				rlen = extbufsize - extbufpos;
144 			}
145 			memcpy(extbuf + extbufpos, buff + len - rlen, rlen);
146 			extbufpos += rlen;
147 		}
148 		for (; pos < len && buff[pos] >= '0' && buff[pos] <= '9'; pos++)
149 			; /* Do nothing */
150 
151 		if (pos == len)
152 			return (0);
153 
154 		if (buff[pos] == ' ')
155 			done = 1;
156 		else if (buff[pos] != '-')
157 			syslog(LOG_ERR, "invalid syntax in reply from server");
158 
159 		/* skip up to \n */
160 		for (; pos < len && buff[pos - 1] != '\n'; pos++)
161 			; /* Do nothing */
162 
163 	}
164 	alarm(0);
165 
166 	status = atoi(buff);
167 	return (status/100);
168 }
169 
170 /*
171  * Handle SMTP authentication
172  */
173 static int
174 smtp_login(struct qitem *it, int fd, char *login, char* password)
175 {
176 	char *temp;
177 	int len, res = 0;
178 
179 #ifdef HAVE_CRYPTO
180 	res = smtp_auth_md5(it, fd, login, password);
181 	if (res == 0) {
182 		return (0);
183 	} else if (res == -2) {
184 	/*
185 	 * If the return code is -2, then then the login attempt failed,
186 	 * do not try other login mechanisms
187 	 */
188 		return (-1);
189 	}
190 #endif /* HAVE_CRYPTO */
191 
192 	if ((config->features & INSECURE) != 0) {
193 		/* Send AUTH command according to RFC 2554 */
194 		send_remote_command(fd, "AUTH LOGIN");
195 		if (read_remote(fd, 0, NULL) != 3) {
196 			syslog(LOG_ERR, "%s: remote delivery deferred:"
197 					" AUTH login not available: %m", it->queueid);
198 			return (1);
199 		}
200 
201 		len = base64_encode(login, strlen(login), &temp);
202 		if (len <= 0)
203 			return (-1);
204 
205 		send_remote_command(fd, "%s", temp);
206 		if (read_remote(fd, 0, NULL) != 3) {
207 			syslog(LOG_ERR, "%s: remote delivery deferred:"
208 					" AUTH login failed: %m", it->queueid);
209 			return (-1);
210 		}
211 
212 		len = base64_encode(password, strlen(password), &temp);
213 		if (len <= 0)
214 			return (-1);
215 
216 		send_remote_command(fd, "%s", temp);
217 		res = read_remote(fd, 0, NULL);
218 		if (res == 5) {
219 			syslog(LOG_ERR, "%s: remote delivery failed:"
220 					" Authentication failed: %m", it->queueid);
221 			return (-1);
222 		} else if (res != 2) {
223 			syslog(LOG_ERR, "%s: remote delivery failed:"
224 					" AUTH password failed: %m", it->queueid);
225 			return (-1);
226 		}
227 	} else {
228 		syslog(LOG_ERR, "%s: non-encrypted SMTP login is disabled in config, so skipping it. ",
229 				it->queueid);
230 		return (1);
231 	}
232 
233 	return (0);
234 }
235 
236 static int
237 open_connection(struct qitem *it, const char *host)
238 {
239 	struct addrinfo hints, *res, *res0;
240 	char servname[128];
241 	const char *errmsg = NULL;
242 	int fd, error = 0, port;
243 
244 	if (config->port != 0)
245 		port = config->port;
246 	else
247 		port = SMTP_PORT;
248 
249 	/* FIXME get MX record of host */
250 	/* Shamelessly taken from getaddrinfo(3) */
251 	memset(&hints, 0, sizeof(hints));
252 	hints.ai_family = PF_UNSPEC;
253 	hints.ai_socktype = SOCK_STREAM;
254 	hints.ai_protocol = IPPROTO_TCP;
255 
256 	snprintf(servname, sizeof(servname), "%d", port);
257 	error = getaddrinfo(host, servname, &hints, &res0);
258 	if (error) {
259 		syslog(LOG_ERR, "%s: remote delivery deferred: "
260 		       "%s: %m", it->queueid, gai_strerror(error));
261 		return (-1);
262 	}
263 	fd = -1;
264 	for (res = res0; res; res = res->ai_next) {
265 		fd=socket(res->ai_family, res->ai_socktype, res->ai_protocol);
266 		if (fd < 0) {
267 			errmsg = "socket failed";
268 			continue;
269 		}
270 		if (connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
271 			errmsg = "connect failed";
272 			close(fd);
273 			fd = -1;
274 			continue;
275 		}
276 		break;
277 	}
278 	if (fd < 0) {
279 		syslog(LOG_ERR, "%s: remote delivery deferred: %s (%s:%s)",
280 			it->queueid, errmsg, host, servname);
281 		freeaddrinfo(res0);
282 		return (-1);
283 	}
284 	freeaddrinfo(res0);
285 	return (fd);
286 }
287 
288 static void
289 copy_qitem(struct qitem *target, struct qitem *it) {
290 	target->sender = it->sender;
291 	target->addr = it->addr;
292 	target->pipeuser = it->pipeuser;
293 	target->queuefn = it->queuefn;
294 	target->queueid = it->queueid;
295 	target->queuef = it->queuef;
296 	target->hdrlen = it->hdrlen;
297 	target->local = 0;
298 }
299 
300 int
301 deliver_remote(struct qitem *it, const char **errmsg, struct queue **queue)
302 {
303 	struct authuser *a;
304 	char *host, line[1000];
305 	int fd, error = 0, do_auth = 0, res = 0;
306 	size_t linelen;
307 
308 	host = strrchr(it->addr, '@');
309 	/* Should not happen */
310 	if (host == NULL)
311 		return(-1);
312 	else
313 		/* Step over the @ */
314 		host++;
315 
316 	/* Smarthost support? */
317 	if (config->smarthost != NULL && strlen(config->smarthost) > 0) {
318 		syslog(LOG_INFO, "%s: using smarthost (%s)",
319 		       it->queueid, config->smarthost);
320 		host = config->smarthost;
321 	}
322 
323 	fd = open_connection(it, host);
324 	if (fd < 0)
325 		return(1);
326 
327 	/* Check first reply from remote host */
328 	config->features |= NOSSL;
329 	res = read_remote(fd, 0, NULL);
330 	if (res != 2) {
331 		syslog(LOG_INFO, "%s: Invalid initial response: %i",
332 			it->queueid, res);
333 		return(1);
334 	}
335 	config->features &= ~NOSSL;
336 
337 #ifdef HAVE_CRYPTO
338 	if ((config->features & SECURETRANS) != 0) {
339 		error = smtp_init_crypto(it, fd, config->features);
340 		if (error >= 0)
341 			syslog(LOG_INFO, "%s: SSL initialization successful",
342 				it->queueid);
343 		else
344 			goto out;
345 	}
346 
347 	/*
348 	 * If the user doesn't want STARTTLS, but SSL encryption, we
349 	 * have to enable SSL first, then send EHLO
350 	 */
351 	if (((config->features & STARTTLS) == 0) &&
352 	    ((config->features & SECURETRANS) != 0)) {
353 		send_remote_command(fd, "EHLO %s", hostname());
354 		if (read_remote(fd, 0, NULL) != 2) {
355 			syslog(LOG_ERR, "%s: remote delivery deferred: "
356 			       " EHLO failed: %m", it->queueid);
357 			return (-1);
358 		}
359 	}
360 #endif /* HAVE_CRYPTO */
361 	if (((config->features & SECURETRANS) == 0)) {
362 		send_remote_command(fd, "EHLO %s", hostname());
363 		if (read_remote(fd, 0, NULL) != 2) {
364 			syslog(LOG_ERR, "%s: remote delivery deferred: "
365 			       " EHLO failed: %m", it->queueid);
366 			return (-1);
367 		}
368 	}
369 
370 	/*
371 	 * Use SMTP authentication if the user defined an entry for the remote
372 	 * or smarthost
373 	 */
374 	SLIST_FOREACH(a, &authusers, next) {
375 		if (strcmp(a->host, host) == 0) {
376 			do_auth = 1;
377 			break;
378 		}
379 	}
380 
381 	if (do_auth == 1) {
382 		/*
383 		 * Check if the user wants plain text login without using
384 		 * encryption.
385 		 */
386 		syslog(LOG_INFO, "%s: Use SMTP authentication",
387 				it->queueid);
388 		error = smtp_login(it, fd, a->login, a->password);
389 		if (error < 0) {
390 			syslog(LOG_ERR, "%s: remote delivery failed:"
391 					" SMTP login failed: %m", it->queueid);
392 			return(-1);
393 		}
394 		/* SMTP login is not available, so try without */
395 		else if (error > 0)
396 			syslog(LOG_ERR, "%s: SMTP login not available."
397 					" Try without", it->queueid);
398 	}
399 
400 	send_remote_command(fd, "MAIL FROM:<%s>", it->sender);
401 	if (read_remote(fd, 0, NULL) != 2) {
402 		syslog(LOG_ERR, "%s: remote delivery deferred:"
403 		       " MAIL FROM failed: %m", it->queueid);
404 		return(1);
405 	}
406 
407 	if (queue == NULL) {
408 	/* without given queue send only to one receipient */
409 		send_remote_command(fd, "RCPT TO:<%s>", it->addr);
410 		if (read_remote(fd, 0, NULL) != 2) {
411 			syslog(LOG_ERR, "%s: remote delivery deferred:"
412 					" RCPT TO failed: %m", it->queueid);
413 			return(1);
414 		}
415 	} else {
416 	/* Iterate over all recepients and open only one connection */
417 /*
418  * we need 3 queues:
419  * 	-delivered addresses
420  *	-temporary errors
421  *	-permanent errors
422  * these 3 queues are given in **queues (+the first queue with all the qitems to send)
423  *
424  */
425 
426 		struct qitem *tit;
427 		int rcpt_success = 0;
428 		struct stat st;
429 		LIST_FOREACH(tit, &queue[0]->queue, next) {
430 			struct qitem *qit;
431 			qit = calloc(1, sizeof(struct qitem));
432 			copy_qitem(qit, tit);
433 
434 			if (stat(tit->queuefn, &st) != 0) {
435 				syslog(LOG_ERR, "%s: lost queue file `%s'",
436 						tit->queueid, tit->queuefn);
437 				/* drop qitem and mark it as successfully sent */
438 				LIST_INSERT_HEAD(&queue[1]->queue, qit, next);
439 				continue;
440 			}
441 
442 			send_remote_command(fd, "RCPT TO:<%s>", tit->addr);
443 			switch (read_remote(fd, 0, NULL)) {
444 			case 2: /* everythings fine, receipient accepted */
445 				/* add item to temporary queue, these items will be deleted in deliver_smarthost */
446 				rcpt_success = 1;
447 				LIST_INSERT_HEAD(&queue[1]->queue, qit, next);
448 				syslog(LOG_INFO, "%s: mail from=<%s> to=<%s>",
449 						tit->queueid, tit->sender, tit->addr);
450 				break;
451 			case 4: /* temporary error, try again later */
452 				/* add item to a temporary queue, these items will be tried again */
453 				LIST_INSERT_HEAD(&queue[2]->queue, qit, next);
454 				syslog(LOG_INFO, "%s: mail from=<%s> to=<%s>",
455 						tit->queueid, tit->sender, tit->addr);
456 				syslog(LOG_ERR, "%s: remote delivery deferred:"
457 						" RCPT TO failed: %m", tit->queueid);
458 				break;
459 			case 5: /* permanent error, bounce */
460 				/* add item to a queue, which will be returned to deliver_smarthost */
461 				LIST_INSERT_HEAD(&queue[3]->queue, qit, next);
462 				syslog(LOG_INFO, "%s: mail from=<%s> to=<%s>",
463 						tit->queueid, tit->sender, tit->addr);
464 				syslog(LOG_ERR, "%s: remote delivery failed:"
465 						" RCPT TO failed: %m", tit->queueid);
466 				break;
467 			}
468 		}
469 		/* if there was no successful RCPT TO, return _WITHOUT_ error */
470 		if (!rcpt_success)
471 			goto out;
472 	}
473 
474 	send_remote_command(fd, "DATA");
475 	if (read_remote(fd, 0, NULL) != 3) {
476 		syslog(LOG_ERR, "%s: remote delivery deferred:"
477 		       " DATA failed: %m", it->queueid);
478 		return (1);
479 	}
480 
481 	if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0) {
482 		syslog(LOG_ERR, "%s: remote delivery deferred: cannot seek: %m",
483 		       it->queueid);
484 		return (1);
485 	}
486 
487 	while (!feof(it->queuef)) {
488 		if (fgets(line, sizeof(line), it->queuef) == NULL)
489 			break;
490 		linelen = strlen(line);
491 		if (linelen == 0 || line[linelen - 1] != '\n') {
492 			syslog(LOG_CRIT, "%s: remote delivery failed:"
493 				"corrupted queue file", it->queueid);
494 			*errmsg = "corrupted queue file";
495 			error = -1;
496 			goto out;
497 		}
498 
499 		/* Remove trailing \n's and escape leading dots */
500 		trim_line(line);
501 
502 		/*
503 		 * If the first character is a dot, we escape it so the line
504 		 * length increases
505 		*/
506 		if (line[0] == '.')
507 			linelen++;
508 
509 		if (send_remote_command(fd, "%s", line) != (ssize_t)linelen+1) {
510 			syslog(LOG_ERR, "%s: remote delivery deferred: "
511 				"write error", it->queueid);
512 			error = 1;
513 			goto out;
514 		}
515 	}
516 
517 	send_remote_command(fd, ".");
518 	if (read_remote(fd, 0, NULL) != 2) {
519 		syslog(LOG_ERR, "%s: remote delivery deferred: %m",
520 		       it->queueid);
521 		return (1);
522 	}
523 
524 	send_remote_command(fd, "QUIT");
525 	if (read_remote(fd, 0, NULL) != 2) {
526 		syslog(LOG_ERR, "%s: remote delivery deferred: "
527 		       "QUIT failed: %m", it->queueid);
528 		return (1);
529 	}
530 out:
531 
532 	close(fd);
533 	return (error);
534 }
535 
536