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