xref: /dflybsd-src/libexec/dma/net.c (revision 90ea502b8c5d21f908cedff6680ee2bc9e74ce74)
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 
36 #include <sys/param.h>
37 #include <sys/queue.h>
38 #include <sys/stat.h>
39 #include <sys/types.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
43 
44 #include <openssl/ssl.h>
45 #include <openssl/err.h>
46 
47 #include <err.h>
48 #include <errno.h>
49 #include <netdb.h>
50 #include <setjmp.h>
51 #include <signal.h>
52 #include <syslog.h>
53 #include <unistd.h>
54 
55 #include "dma.h"
56 
57 static jmp_buf timeout_alarm;
58 char neterr[BUF_SIZE];
59 
60 char *
61 ssl_errstr(void)
62 {
63 	long oerr, nerr;
64 
65 	oerr = 0;
66 	while ((nerr = ERR_get_error()) != 0)
67 		oerr = nerr;
68 
69 	return (ERR_error_string(oerr, NULL));
70 }
71 
72 static void
73 sig_alarm(int signo)
74 {
75 	(void)signo;	/* so that gcc doesn't complain */
76 	longjmp(timeout_alarm, 1);
77 }
78 
79 ssize_t
80 send_remote_command(int fd, const char* fmt, ...)
81 {
82 	va_list va;
83 	char cmd[4096];
84 	size_t len, pos;
85 	int s;
86 	ssize_t n;
87 
88 	va_start(va, fmt);
89 	s = vsnprintf(cmd, sizeof(cmd) - 2, fmt, va);
90 	va_end(va);
91 	if (s == sizeof(cmd) - 2 || s < 0) {
92 		strcpy(neterr, "Internal error: oversized command string");
93 		return (-1);
94 	}
95 
96 	/* We *know* there are at least two more bytes available */
97 	strcat(cmd, "\r\n");
98 	len = strlen(cmd);
99 
100 	if (((config.features & SECURETRANS) != 0) &&
101 	    ((config.features & NOSSL) == 0)) {
102 		while ((s = SSL_write(config.ssl, (const char*)cmd, len)) <= 0) {
103 			s = SSL_get_error(config.ssl, s);
104 			if (s != SSL_ERROR_WANT_READ &&
105 			    s != SSL_ERROR_WANT_WRITE) {
106 				strncpy(neterr, ssl_errstr(), sizeof(neterr));
107 				return (-1);
108 			}
109 		}
110 	}
111 	else {
112 		pos = 0;
113 		while (pos < len) {
114 			n = write(fd, cmd + pos, len - pos);
115 			if (n < 0)
116 				return (-1);
117 			pos += n;
118 		}
119 	}
120 
121 	return (len);
122 }
123 
124 int
125 read_remote(int fd, int extbufsize, char *extbuf)
126 {
127 	ssize_t rlen = 0;
128 	size_t pos, len;
129 	char buff[BUF_SIZE];
130 	int done = 0, status = 0, extbufpos = 0;
131 
132 	if (signal(SIGALRM, sig_alarm) == SIG_ERR) {
133 		snprintf(neterr, sizeof(neterr), "SIGALRM error: %s",
134 		    strerror(errno));
135 		return (-1);
136 	}
137 	if (setjmp(timeout_alarm) != 0) {
138 		snprintf(neterr, sizeof(neterr), "Timeout reached");
139 		return (-1);
140 	}
141 	alarm(CON_TIMEOUT);
142 
143 	/*
144 	 * Remote reading code from femail.c written by Henning Brauer of
145 	 * OpenBSD and released under a BSD style license.
146 	 */
147 	for (len = pos = 0; !done; ) {
148 		rlen = 0;
149 		if (pos == 0 ||
150 		    (pos > 0 && memchr(buff + pos, '\n', len - pos) == NULL)) {
151 			memmove(buff, buff + pos, len - pos);
152 			len -= pos;
153 			pos = 0;
154 			if (((config.features & SECURETRANS) != 0) &&
155 			    (config.features & NOSSL) == 0) {
156 				if ((rlen = SSL_read(config.ssl, buff + len,
157 				    sizeof(buff) - len)) == -1) {
158 					strncpy(neterr, ssl_errstr(), sizeof(neterr));
159 					return (-1);
160 				}
161 			} else {
162 				if ((rlen = read(fd, buff + len, sizeof(buff) - len)) == -1) {
163 					strncpy(neterr, strerror(errno), sizeof(neterr));
164 					return (-1);
165 				}
166 			}
167 			len += rlen;
168 		}
169 		/*
170 		 * If there is an external buffer with a size bigger than zero
171 		 * and as long as there is space in the external buffer and
172 		 * there are new characters read from the mailserver
173 		 * copy them to the external buffer
174 		 */
175 		if (extbufpos <= (extbufsize - 1) && rlen && extbufsize > 0
176 		    && extbuf != NULL) {
177 			/* do not write over the bounds of the buffer */
178 			if(extbufpos + rlen > (extbufsize - 1)) {
179 				rlen = extbufsize - extbufpos;
180 			}
181 			memcpy(extbuf + extbufpos, buff + len - rlen, rlen);
182 			extbufpos += rlen;
183 		}
184 		for (; pos < len && buff[pos] >= '0' && buff[pos] <= '9'; pos++)
185 			; /* Do nothing */
186 
187 		if (pos == len)
188 			return (0);
189 
190 		if (buff[pos] == ' ') {
191 			done = 1;
192 		} else if (buff[pos] != '-') {
193 			strcpy(neterr, "invalid syntax in reply from server");
194 			return (-1);
195 		}
196 
197 		/* skip up to \n */
198 		for (; pos < len && buff[pos - 1] != '\n'; pos++)
199 			; /* Do nothing */
200 
201 	}
202 	alarm(0);
203 
204 	buff[len] = '\0';
205 	while (len > 0 && (buff[len - 1] == '\r' || buff[len - 1] == '\n'))
206 		buff[--len] = '\0';
207 	snprintf(neterr, sizeof(neterr), "%s", buff);
208 	status = atoi(buff);
209 	return (status/100);
210 }
211 
212 /*
213  * Handle SMTP authentication
214  */
215 static int
216 smtp_login(int fd, char *login, char* password)
217 {
218 	char *temp;
219 	int len, res = 0;
220 
221 	res = smtp_auth_md5(fd, login, password);
222 	if (res == 0) {
223 		return (0);
224 	} else if (res == -2) {
225 	/*
226 	 * If the return code is -2, then then the login attempt failed,
227 	 * do not try other login mechanisms
228 	 */
229 		return (1);
230 	}
231 
232 	if ((config.features & INSECURE) != 0 ||
233 	    (config.features & SECURETRANS) != 0) {
234 		/* Send AUTH command according to RFC 2554 */
235 		send_remote_command(fd, "AUTH LOGIN");
236 		if (read_remote(fd, 0, NULL) != 3) {
237 			syslog(LOG_NOTICE, "remote delivery deferred:"
238 					" AUTH login not available: %s",
239 					neterr);
240 			return (1);
241 		}
242 
243 		len = base64_encode(login, strlen(login), &temp);
244 		if (len < 0) {
245 encerr:
246 			syslog(LOG_ERR, "can not encode auth reply: %m");
247 			return (1);
248 		}
249 
250 		send_remote_command(fd, "%s", temp);
251 		free(temp);
252 		res = read_remote(fd, 0, NULL);
253 		if (res != 3) {
254 			syslog(LOG_NOTICE, "remote delivery %s: AUTH login failed: %s",
255 			       res == 5 ? "failed" : "deferred", neterr);
256 			return (res == 5 ? -1 : 1);
257 		}
258 
259 		len = base64_encode(password, strlen(password), &temp);
260 		if (len < 0)
261 			goto encerr;
262 
263 		send_remote_command(fd, "%s", temp);
264 		free(temp);
265 		res = read_remote(fd, 0, NULL);
266 		if (res != 2) {
267 			syslog(LOG_NOTICE, "remote delivery %s: Authentication failed: %s",
268 					res == 5 ? "failed" : "deferred", neterr);
269 			return (res == 5 ? -1 : 1);
270 		}
271 	} else {
272 		syslog(LOG_WARNING, "non-encrypted SMTP login is disabled in config, so skipping it. ");
273 		return (1);
274 	}
275 
276 	return (0);
277 }
278 
279 static int
280 open_connection(struct mx_hostentry *h)
281 {
282 	int fd;
283 
284 	syslog(LOG_INFO, "trying remote delivery to %s [%s] pref %d",
285 	       h->host, h->addr, h->pref);
286 
287 	fd = socket(h->ai.ai_family, h->ai.ai_socktype, h->ai.ai_protocol);
288 	if (fd < 0) {
289 		syslog(LOG_INFO, "socket for %s [%s] failed: %m",
290 		       h->host, h->addr);
291 		return (-1);
292 	}
293 
294 	if (connect(fd, (struct sockaddr *)&h->sa, h->ai.ai_addrlen) < 0) {
295 		syslog(LOG_INFO, "connect to %s [%s] failed: %m",
296 		       h->host, h->addr);
297 		close(fd);
298 		return (-1);
299 	}
300 
301 	return (fd);
302 }
303 
304 static void
305 close_connection(int fd)
306 {
307 	if (((config.features & SECURETRANS) != 0) &&
308 	    ((config.features & NOSSL) == 0))
309 		SSL_shutdown(config.ssl);
310 
311 	if (config.ssl != NULL)
312 		SSL_free(config.ssl);
313 
314 	close(fd);
315 }
316 
317 static int
318 deliver_to_host(struct qitem *it, struct mx_hostentry *host, void *errmsgc)
319 {
320 	struct authuser *a;
321 	char line[1000];
322 	size_t linelen;
323 	int fd, error = 0, do_auth = 0, res = 0;
324 
325 	if (fseek(it->mailf, 0, SEEK_SET) != 0) {
326 		asprintf(errmsgc, "can not seek: %s", strerror(errno));
327 		return (-1);
328 	}
329 
330 	fd = open_connection(host);
331 	if (fd < 0)
332 		return (1);
333 
334 #define READ_REMOTE_CHECK(c, exp)	\
335 	res = read_remote(fd, 0, NULL); \
336 	if (res == 5) { \
337 		syslog(LOG_ERR, "remote delivery to %s [%s] failed after %s: %s", \
338 		       host->host, host->addr, c, neterr); \
339 		asprintf(errmsgc, "%s [%s] did not like our %s:\n%s", \
340 			 host->host, host->addr, c, neterr); \
341 		return (-1); \
342 	} else if (res != exp) { \
343 		syslog(LOG_NOTICE, "remote delivery deferred: %s [%s] failed after %s: %s", \
344 		       host->host, host->addr, c, neterr); \
345 		return (1); \
346 	}
347 
348 	/* Check first reply from remote host */
349 	config.features |= NOSSL;
350 	READ_REMOTE_CHECK("connect", 2);
351 
352 	config.features &= ~NOSSL;
353 
354 	if ((config.features & SECURETRANS) != 0) {
355 		error = smtp_init_crypto(fd, config.features);
356 		if (error == 0)
357 			syslog(LOG_DEBUG, "SSL initialization successful");
358 		else
359 			goto out;
360 	}
361 
362 	/* XXX allow HELO fallback */
363 	/* XXX record ESMTP keywords */
364 	send_remote_command(fd, "EHLO %s", hostname());
365 	READ_REMOTE_CHECK("EHLO", 2);
366 
367 	/*
368 	 * Use SMTP authentication if the user defined an entry for the remote
369 	 * or smarthost
370 	 */
371 	SLIST_FOREACH(a, &authusers, next) {
372 		if (strcmp(a->host, host->host) == 0) {
373 			do_auth = 1;
374 			break;
375 		}
376 	}
377 
378 	if (do_auth == 1) {
379 		/*
380 		 * Check if the user wants plain text login without using
381 		 * encryption.
382 		 */
383 		syslog(LOG_INFO, "using SMTP authentication for user %s", a->login);
384 		error = smtp_login(fd, a->login, a->password);
385 		if (error < 0) {
386 			syslog(LOG_ERR, "remote delivery failed:"
387 					" SMTP login failed: %m");
388 			asprintf(errmsgc, "SMTP login to %s failed", host->host);
389 			return (-1);
390 		}
391 		/* SMTP login is not available, so try without */
392 		else if (error > 0) {
393 			syslog(LOG_WARNING, "SMTP login not available. Trying without.");
394 		}
395 	}
396 
397 	/* XXX send ESMTP ENVID, RET (FULL/HDRS) and 8BITMIME */
398 	send_remote_command(fd, "MAIL FROM:<%s>", it->sender);
399 	READ_REMOTE_CHECK("MAIL FROM", 2);
400 
401 	/* XXX send ESMTP ORCPT */
402 	send_remote_command(fd, "RCPT TO:<%s>", it->addr);
403 	READ_REMOTE_CHECK("RCPT TO", 2);
404 
405 	send_remote_command(fd, "DATA");
406 	READ_REMOTE_CHECK("DATA", 3);
407 
408 	error = 0;
409 	while (!feof(it->mailf)) {
410 		if (fgets(line, sizeof(line), it->mailf) == NULL)
411 			break;
412 		linelen = strlen(line);
413 		if (linelen == 0 || line[linelen - 1] != '\n') {
414 			syslog(LOG_CRIT, "remote delivery failed: corrupted queue file");
415 			*(const char **)errmsgc = "corrupted queue file";
416 			error = -1;
417 			goto out;
418 		}
419 
420 		/* Remove trailing \n's and escape leading dots */
421 		trim_line(line);
422 
423 		/*
424 		 * If the first character is a dot, we escape it so the line
425 		 * length increases
426 		*/
427 		if (line[0] == '.')
428 			linelen++;
429 
430 		if (send_remote_command(fd, "%s", line) != (ssize_t)linelen+1) {
431 			syslog(LOG_NOTICE, "remote delivery deferred: write error");
432 			error = 1;
433 			goto out;
434 		}
435 	}
436 
437 	send_remote_command(fd, ".");
438 	READ_REMOTE_CHECK("final DATA", 2);
439 
440 	send_remote_command(fd, "QUIT");
441 	if (read_remote(fd, 0, NULL) != 2)
442 		syslog(LOG_INFO, "remote delivery succeeded but QUIT failed: %s", neterr);
443 out:
444 
445 	close_connection(fd);
446 	return (error);
447 }
448 
449 int
450 deliver_remote(struct qitem *it, const char **errmsg)
451 {
452 	/* asprintf can't take const */
453 	void *errmsgc = __DECONST(char **, errmsg);
454 	struct mx_hostentry *hosts, *h;
455 	const char *host;
456 	int port;
457 	int error = 1, smarthost = 0;
458 
459 	host = strrchr(it->addr, '@');
460 	/* Should not happen */
461 	if (host == NULL) {
462 		asprintf(errmsgc, "Internal error: badly formed address %s",
463 		    it->addr);
464 		return(-1);
465 	} else {
466 		/* Step over the @ */
467 		host++;
468 	}
469 
470 	port = SMTP_PORT;
471 
472 	/* Smarthost support? */
473 	if (config.smarthost != NULL) {
474 		host = config.smarthost;
475 		port = config.port;
476 		syslog(LOG_INFO, "using smarthost (%s:%i)", host, port);
477 		smarthost = 1;
478 	}
479 
480 	error = dns_get_mx_list(host, port, &hosts, smarthost);
481 	if (error) {
482 		syslog(LOG_NOTICE, "remote delivery %s: DNS failure (%s)",
483 		       error < 0 ? "failed" : "deferred",
484 		       host);
485 		return (error);
486 	}
487 
488 	for (h = hosts; *h->host != 0; h++) {
489 		switch (deliver_to_host(it, h, errmsgc)) {
490 		case 0:
491 			/* success */
492 			error = 0;
493 			goto out;
494 		case 1:
495 			/* temp failure */
496 			error = 1;
497 			break;
498 		default:
499 			/* perm failure */
500 			error = -1;
501 			goto out;
502 		}
503 	}
504 out:
505 	free(hosts);
506 
507 	return (error);
508 }
509