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