xref: /dragonfly/libexec/dma/net.c (revision 235099c3)
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(const char *host)
280 {
281 	struct addrinfo hints, *res, *res0;
282 	char servname[128];
283 	const char *errmsg = NULL;
284 	int fd, error = 0, port;
285 
286 	if (config->port != 0)
287 		port = config->port;
288 	else
289 		port = SMTP_PORT;
290 
291 	/* XXX FIXME get MX record of host */
292 	/* Shamelessly taken from getaddrinfo(3) */
293 	memset(&hints, 0, sizeof(hints));
294 	hints.ai_family = PF_UNSPEC;
295 	hints.ai_socktype = SOCK_STREAM;
296 	hints.ai_protocol = IPPROTO_TCP;
297 
298 	snprintf(servname, sizeof(servname), "%d", port);
299 	error = getaddrinfo(host, servname, &hints, &res0);
300 	if (error) {
301 		syslog(LOG_NOTICE, "remote delivery deferred: %s", gai_strerror(error));
302 		return (-1);
303 	}
304 	fd = -1;
305 	for (res = res0; res; res = res->ai_next) {
306 		fd=socket(res->ai_family, res->ai_socktype, res->ai_protocol);
307 		if (fd < 0) {
308 			errmsg = "socket failed";
309 			continue;
310 		}
311 		if (connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
312 			errmsg = "connect failed";
313 			close(fd);
314 			fd = -1;
315 			continue;
316 		}
317 		break;
318 	}
319 	if (fd < 0) {
320 		syslog(LOG_NOTICE, "remote delivery deferred: %s (%s:%s)",
321 			errmsg, host, servname);
322 		freeaddrinfo(res0);
323 		return (-1);
324 	}
325 	freeaddrinfo(res0);
326 	return (fd);
327 }
328 
329 static void
330 close_connection(int fd)
331 {
332 	if (((config->features & SECURETRANS) != 0) &&
333 	    ((config->features & NOSSL) == 0))
334 		SSL_shutdown(config->ssl);
335 
336 	if (config->ssl != NULL)
337 		SSL_free(config->ssl);
338 
339 	close(fd);
340 }
341 
342 int
343 deliver_remote(struct qitem *it, const char **errmsg)
344 {
345 	struct authuser *a;
346 	char *host, line[1000];
347 	int fd, error = 0, do_auth = 0, res = 0;
348 	size_t linelen;
349 	/* asprintf can't take const */
350 	void *errmsgc = __DECONST(char **, errmsg);
351 
352 	if (fseek(it->mailf, 0, SEEK_SET) != 0) {
353 		asprintf(errmsgc, "can not seek: %s", strerror(errno));
354 		return (-1);
355 	}
356 
357 	host = strrchr(it->addr, '@');
358 	/* Should not happen */
359 	if (host == NULL) {
360 		asprintf(errmsgc, "Internal error: badly formed address %s",
361 		    it->addr);
362 		return(-1);
363 	} else {
364 		/* Step over the @ */
365 		host++;
366 	}
367 
368 	/* Smarthost support? */
369 	if (config->smarthost != NULL && strlen(config->smarthost) > 0) {
370 		syslog(LOG_INFO, "using smarthost (%s:%i)",
371 		       config->smarthost, config->port);
372 		host = config->smarthost;
373 	}
374 
375 	fd = open_connection(host);
376 	if (fd < 0)
377 		return (1);
378 
379 	/* Check first reply from remote host */
380 	config->features |= NOSSL;
381 	res = read_remote(fd, 0, NULL);
382 	if (res != 2) {
383 		syslog(LOG_WARNING, "Invalid initial response: %i", res);
384 		return(1);
385 	}
386 	config->features &= ~NOSSL;
387 
388 	if ((config->features & SECURETRANS) != 0) {
389 		error = smtp_init_crypto(fd, config->features);
390 		if (error >= 0)
391 			syslog(LOG_DEBUG, "SSL initialization successful");
392 		else
393 			goto out;
394 	}
395 
396 	/* XXX allow HELO fallback */
397 	/* XXX record ESMTP keywords */
398 	send_remote_command(fd, "EHLO %s", hostname());
399 	if (read_remote(fd, 0, NULL) != 2) {
400 		syslog(LOG_WARNING, "remote delivery deferred: EHLO failed: %s", neterr);
401 		asprintf(errmsgc, "%s did not like our EHLO:\n%s",
402 		    host, neterr);
403 		return (-1);
404 	}
405 
406 	/*
407 	 * Use SMTP authentication if the user defined an entry for the remote
408 	 * or smarthost
409 	 */
410 	SLIST_FOREACH(a, &authusers, next) {
411 		if (strcmp(a->host, host) == 0) {
412 			do_auth = 1;
413 			break;
414 		}
415 	}
416 
417 	if (do_auth == 1) {
418 		/*
419 		 * Check if the user wants plain text login without using
420 		 * encryption.
421 		 */
422 		syslog(LOG_INFO, "using SMTP authentication");
423 		error = smtp_login(fd, a->login, a->password);
424 		if (error < 0) {
425 			syslog(LOG_ERR, "remote delivery failed:"
426 					" SMTP login failed: %m");
427 			asprintf(errmsgc, "SMTP login to %s failed", host);
428 			return (-1);
429 		}
430 		/* SMTP login is not available, so try without */
431 		else if (error > 0) {
432 			syslog(LOG_WARNING, "SMTP login not available. Trying without.");
433 		}
434 	}
435 
436 #define READ_REMOTE_CHECK(c, exp)	\
437 	res = read_remote(fd, 0, NULL); \
438 	if (res == 5) { \
439 		syslog(LOG_ERR, "remote delivery failed: " \
440 		       c " failed: %s", neterr); \
441 		asprintf(errmsgc, "%s did not like our " c ":\n%s", \
442 		    host, neterr); \
443 		return (-1); \
444 	} else if (res != exp) { \
445 		syslog(LOG_NOTICE, "remote delivery deferred: " \
446 		       c " failed: %s", neterr); \
447 		return (1); \
448 	}
449 
450 	/* XXX send ESMTP ENVID, RET (FULL/HDRS) and 8BITMIME */
451 	send_remote_command(fd, "MAIL FROM:<%s>", it->sender);
452 	READ_REMOTE_CHECK("MAIL FROM", 2);
453 
454 	/* XXX send ESMTP ORCPT */
455 	send_remote_command(fd, "RCPT TO:<%s>", it->addr);
456 	READ_REMOTE_CHECK("RCPT TO", 2);
457 
458 	send_remote_command(fd, "DATA");
459 	READ_REMOTE_CHECK("DATA", 3);
460 
461 	error = 0;
462 	while (!feof(it->mailf)) {
463 		if (fgets(line, sizeof(line), it->mailf) == NULL)
464 			break;
465 		linelen = strlen(line);
466 		if (linelen == 0 || line[linelen - 1] != '\n') {
467 			syslog(LOG_CRIT, "remote delivery failed: corrupted queue file");
468 			*errmsg = "corrupted queue file";
469 			error = -1;
470 			goto out;
471 		}
472 
473 		/* Remove trailing \n's and escape leading dots */
474 		trim_line(line);
475 
476 		/*
477 		 * If the first character is a dot, we escape it so the line
478 		 * length increases
479 		*/
480 		if (line[0] == '.')
481 			linelen++;
482 
483 		if (send_remote_command(fd, "%s", line) != (ssize_t)linelen+1) {
484 			syslog(LOG_NOTICE, "remote delivery deferred: write error");
485 			error = 1;
486 			goto out;
487 		}
488 	}
489 
490 	send_remote_command(fd, ".");
491 	READ_REMOTE_CHECK("final DATA", 2);
492 
493 	send_remote_command(fd, "QUIT");
494 	if (read_remote(fd, 0, NULL) != 2)
495 		syslog(LOG_INFO, "remote delivery succeeded but QUIT failed: %s", neterr);
496 out:
497 
498 	close_connection(fd);
499 	return (error);
500 }
501 
502