5692c61a6bd363b1b881a17b849e82179990bb86
[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
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         /* 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         host = strrchr(it->addr, '@');
353         /* Should not happen */
354         if (host == NULL) {
355                 asprintf(errmsgc, "Internal error: badly formed address %s",
356                     it->addr);
357                 return(-1);
358         } else {
359                 /* Step over the @ */
360                 host++;
361         }
362
363         /* Smarthost support? */
364         if (config->smarthost != NULL && strlen(config->smarthost) > 0) {
365                 syslog(LOG_INFO, "using smarthost (%s:%i)",
366                        config->smarthost, config->port);
367                 host = config->smarthost;
368         }
369
370         fd = open_connection(host);
371         if (fd < 0)
372                 return (1);
373
374         /* Check first reply from remote host */
375         config->features |= NOSSL;
376         res = read_remote(fd, 0, NULL);
377         if (res != 2) {
378                 syslog(LOG_WARNING, "Invalid initial response: %i", res);
379                 return(1);
380         }
381         config->features &= ~NOSSL;
382
383         if ((config->features & SECURETRANS) != 0) {
384                 error = smtp_init_crypto(fd, config->features);
385                 if (error >= 0)
386                         syslog(LOG_DEBUG, "SSL initialization successful");
387                 else
388                         goto out;
389         }
390
391         send_remote_command(fd, "EHLO %s", hostname());
392         if (read_remote(fd, 0, NULL) != 2) {
393                 syslog(LOG_WARNING, "remote delivery deferred: EHLO failed: %s", neterr);
394                 asprintf(errmsgc, "%s did not like our EHLO:\n%s",
395                     host, neterr);
396                 return (-1);
397         }
398
399         /*
400          * Use SMTP authentication if the user defined an entry for the remote
401          * or smarthost
402          */
403         SLIST_FOREACH(a, &authusers, next) {
404                 if (strcmp(a->host, host) == 0) {
405                         do_auth = 1;
406                         break;
407                 }
408         }
409
410         if (do_auth == 1) {
411                 /*
412                  * Check if the user wants plain text login without using
413                  * encryption.
414                  */
415                 syslog(LOG_INFO, "using SMTP authentication");
416                 error = smtp_login(fd, a->login, a->password);
417                 if (error < 0) {
418                         syslog(LOG_ERR, "remote delivery failed:"
419                                         " SMTP login failed: %m");
420                         asprintf(errmsgc, "SMTP login to %s failed", host);
421                         return (-1);
422                 }
423                 /* SMTP login is not available, so try without */
424                 else if (error > 0) {
425                         syslog(LOG_WARNING, "SMTP login not available. Trying without.");
426                 }
427         }
428
429 #define READ_REMOTE_CHECK(c, exp)       \
430         res = read_remote(fd, 0, NULL); \
431         if (res == 5) { \
432                 syslog(LOG_ERR, "remote delivery failed: " \
433                        c " failed: %s", neterr); \
434                 asprintf(errmsgc, "%s did not like our " c ":\n%s", \
435                     host, neterr); \
436                 return (-1); \
437         } else if (res != exp) { \
438                 syslog(LOG_NOTICE, "remote delivery deferred: " \
439                        c " failed: %s", neterr); \
440                 return (1); \
441         }
442
443         send_remote_command(fd, "MAIL FROM:<%s>", it->sender);
444         READ_REMOTE_CHECK("MAIL FROM", 2);
445
446         send_remote_command(fd, "RCPT TO:<%s>", it->addr);
447         READ_REMOTE_CHECK("RCPT TO", 2);
448
449         send_remote_command(fd, "DATA");
450         READ_REMOTE_CHECK("DATA", 3);
451
452         if (fseek(it->mailf, it->hdrlen, SEEK_SET) != 0) {
453                 syslog(LOG_ERR, "remote delivery deferred: cannot seek: %s", neterr);
454                 return (1);
455         }
456
457         error = 0;
458         while (!feof(it->mailf)) {
459                 if (fgets(line, sizeof(line), it->mailf) == NULL)
460                         break;
461                 linelen = strlen(line);
462                 if (linelen == 0 || line[linelen - 1] != '\n') {
463                         syslog(LOG_CRIT, "remote delivery failed: corrupted queue file");
464                         *errmsg = "corrupted queue file";
465                         error = -1;
466                         goto out;
467                 }
468
469                 /* Remove trailing \n's and escape leading dots */
470                 trim_line(line);
471
472                 /*
473                  * If the first character is a dot, we escape it so the line
474                  * length increases
475                 */
476                 if (line[0] == '.')
477                         linelen++;
478
479                 if (send_remote_command(fd, "%s", line) != (ssize_t)linelen+1) {
480                         syslog(LOG_NOTICE, "remote delivery deferred: write error");
481                         error = 1;
482                         goto out;
483                 }
484         }
485
486         send_remote_command(fd, ".");
487         READ_REMOTE_CHECK("final DATA", 2);
488
489         send_remote_command(fd, "QUIT");
490         if (read_remote(fd, 0, NULL) != 2)
491                 syslog(LOG_INFO, "remote delivery succeeded but QUIT failed: %s", neterr);
492 out:
493
494         close_connection(fd);
495         return (error);
496 }
497