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