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