xref: /dragonfly/libexec/dma/net.c (revision 60233e58)
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 int
289 deliver_remote(struct qitem *it, const char **errmsg)
290 {
291 	struct authuser *a;
292 	char *host, line[1000];
293 	int fd, error = 0, do_auth = 0, res = 0;
294 	size_t linelen;
295 
296 	host = strrchr(it->addr, '@');
297 	/* Should not happen */
298 	if (host == NULL)
299 		return(-1);
300 	else
301 		/* Step over the @ */
302 		host++;
303 
304 	/* Smarthost support? */
305 	if (config->smarthost != NULL && strlen(config->smarthost) > 0) {
306 		syslog(LOG_INFO, "%s: using smarthost (%s:%i)",
307 		       it->queueid, config->smarthost, config->port);
308 		host = config->smarthost;
309 	}
310 
311 	fd = open_connection(it, host);
312 	if (fd < 0)
313 		return (1);
314 
315 	/* Check first reply from remote host */
316 	config->features |= NOSSL;
317 	res = read_remote(fd, 0, NULL);
318 	if (res != 2) {
319 		syslog(LOG_INFO, "%s: Invalid initial response: %i",
320 			it->queueid, res);
321 		return(1);
322 	}
323 	config->features &= ~NOSSL;
324 
325 #ifdef HAVE_CRYPTO
326 	if ((config->features & SECURETRANS) != 0) {
327 		error = smtp_init_crypto(it, fd, config->features);
328 		if (error >= 0)
329 			syslog(LOG_INFO, "%s: SSL initialization successful",
330 				it->queueid);
331 		else
332 			goto out;
333 	}
334 
335 	/*
336 	 * If the user doesn't want STARTTLS, but SSL encryption, we
337 	 * have to enable SSL first, then send EHLO
338 	 */
339 	if (((config->features & STARTTLS) == 0) &&
340 	    ((config->features & SECURETRANS) != 0)) {
341 		send_remote_command(fd, "EHLO %s", hostname());
342 		if (read_remote(fd, 0, NULL) != 2) {
343 			syslog(LOG_ERR, "%s: remote delivery deferred: "
344 			       " EHLO failed: %m", it->queueid);
345 			return (-1);
346 		}
347 	}
348 #endif /* HAVE_CRYPTO */
349 	if (((config->features & SECURETRANS) == 0)) {
350 		send_remote_command(fd, "EHLO %s", hostname());
351 		if (read_remote(fd, 0, NULL) != 2) {
352 			syslog(LOG_ERR, "%s: remote delivery deferred: "
353 			       " EHLO failed: %m", it->queueid);
354 			return (-1);
355 		}
356 	}
357 
358 	/*
359 	 * Use SMTP authentication if the user defined an entry for the remote
360 	 * or smarthost
361 	 */
362 	SLIST_FOREACH(a, &authusers, next) {
363 		if (strcmp(a->host, host) == 0) {
364 			do_auth = 1;
365 			break;
366 		}
367 	}
368 
369 	if (do_auth == 1) {
370 		/*
371 		 * Check if the user wants plain text login without using
372 		 * encryption.
373 		 */
374 		syslog(LOG_INFO, "%s: Use SMTP authentication",
375 				it->queueid);
376 		error = smtp_login(it, fd, a->login, a->password);
377 		if (error < 0) {
378 			syslog(LOG_ERR, "%s: remote delivery failed:"
379 					" SMTP login failed: %m", it->queueid);
380 			return (-1);
381 		}
382 		/* SMTP login is not available, so try without */
383 		else if (error > 0)
384 			syslog(LOG_ERR, "%s: SMTP login not available."
385 					" Try without", it->queueid);
386 	}
387 
388 	send_remote_command(fd, "MAIL FROM:<%s>", it->sender);
389 	if (read_remote(fd, 0, NULL) != 2) {
390 		syslog(LOG_ERR, "%s: remote delivery deferred:"
391 		       " MAIL FROM failed: %m", it->queueid);
392 		return (1);
393 	}
394 
395 	send_remote_command(fd, "RCPT TO:<%s>", it->addr);
396 	if (read_remote(fd, 0, NULL) != 2) {
397 		syslog(LOG_ERR, "%s: remote delivery deferred:"
398 				" RCPT TO failed: %m", it->queueid);
399 		return (1);
400 	}
401 
402 	send_remote_command(fd, "DATA");
403 	if (read_remote(fd, 0, NULL) != 3) {
404 		syslog(LOG_ERR, "%s: remote delivery deferred:"
405 		       " DATA failed: %m", it->queueid);
406 		return (1);
407 	}
408 
409 	if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0) {
410 		syslog(LOG_ERR, "%s: remote delivery deferred: cannot seek: %m",
411 		       it->queueid);
412 		return (1);
413 	}
414 
415 	while (!feof(it->queuef)) {
416 		if (fgets(line, sizeof(line), it->queuef) == NULL)
417 			break;
418 		linelen = strlen(line);
419 		if (linelen == 0 || line[linelen - 1] != '\n') {
420 			syslog(LOG_CRIT, "%s: remote delivery failed:"
421 				"corrupted queue file", it->queueid);
422 			*errmsg = "corrupted queue file";
423 			error = -1;
424 			goto out;
425 		}
426 
427 		/* Remove trailing \n's and escape leading dots */
428 		trim_line(line);
429 
430 		/*
431 		 * If the first character is a dot, we escape it so the line
432 		 * length increases
433 		*/
434 		if (line[0] == '.')
435 			linelen++;
436 
437 		if (send_remote_command(fd, "%s", line) != (ssize_t)linelen+1) {
438 			syslog(LOG_ERR, "%s: remote delivery deferred: "
439 				"write error", it->queueid);
440 			error = 1;
441 			goto out;
442 		}
443 	}
444 
445 	send_remote_command(fd, ".");
446 	if (read_remote(fd, 0, NULL) != 2) {
447 		syslog(LOG_ERR, "%s: remote delivery deferred: %m",
448 		       it->queueid);
449 		return (1);
450 	}
451 
452 	send_remote_command(fd, "QUIT");
453 	if (read_remote(fd, 0, NULL) != 2) {
454 		syslog(LOG_ERR, "%s: remote delivery deferred: "
455 		       "QUIT failed: %m", it->queueid);
456 		return (1);
457 	}
458 out:
459 
460 	close(fd);
461 	return (error);
462 }
463 
464