dma: restructure logging
[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(int fd, char *login, char* password)
218 {
219         char *temp;
220         int len, res = 0;
221
222         res = smtp_auth_md5(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, "remote delivery deferred:"
239                                         " AUTH login not available: %s",
240                                         neterr);
241                         return (1);
242                 }
243
244                 len = base64_encode(login, strlen(login), &temp);
245                 if (len < 0) {
246 encerr:
247                         syslog(LOG_ERR, "can not encode auth reply: %m");
248                         return (1);
249                 }
250
251                 send_remote_command(fd, "%s", temp);
252                 free(temp);
253                 res = read_remote(fd, 0, NULL);
254                 if (res != 3) {
255                         syslog(LOG_NOTICE, "remote delivery %s: AUTH login failed: %s",
256                                res == 5 ? "failed" : "deferred", neterr);
257                         return (res == 5 ? -1 : 1);
258                 }
259
260                 len = base64_encode(password, strlen(password), &temp);
261                 if (len < 0)
262                         goto encerr;
263
264                 send_remote_command(fd, "%s", temp);
265                 free(temp);
266                 res = read_remote(fd, 0, NULL);
267                 if (res != 2) {
268                         syslog(LOG_NOTICE, "remote delivery %s: Authentication failed: %s",
269                                         res == 5 ? "failed" : "deferred", neterr);
270                         return (res == 5 ? -1 : 1);
271                 }
272         } else {
273                 syslog(LOG_WARNING, "non-encrypted SMTP login is disabled in config, so skipping it. ");
274                 return (1);
275         }
276
277         return (0);
278 }
279
280 static int
281 open_connection(const char *host)
282 {
283         struct addrinfo hints, *res, *res0;
284         char servname[128];
285         const char *errmsg = NULL;
286         int fd, error = 0, port;
287
288         if (config->port != 0)
289                 port = config->port;
290         else
291                 port = SMTP_PORT;
292
293         /* FIXME get MX record of host */
294         /* Shamelessly taken from getaddrinfo(3) */
295         memset(&hints, 0, sizeof(hints));
296         hints.ai_family = PF_UNSPEC;
297         hints.ai_socktype = SOCK_STREAM;
298         hints.ai_protocol = IPPROTO_TCP;
299
300         snprintf(servname, sizeof(servname), "%d", port);
301         error = getaddrinfo(host, servname, &hints, &res0);
302         if (error) {
303                 syslog(LOG_NOTICE, "remote delivery deferred: %s", gai_strerror(error));
304                 return (-1);
305         }
306         fd = -1;
307         for (res = res0; res; res = res->ai_next) {
308                 fd=socket(res->ai_family, res->ai_socktype, res->ai_protocol);
309                 if (fd < 0) {
310                         errmsg = "socket failed";
311                         continue;
312                 }
313                 if (connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
314                         errmsg = "connect failed";
315                         close(fd);
316                         fd = -1;
317                         continue;
318                 }
319                 break;
320         }
321         if (fd < 0) {
322                 syslog(LOG_NOTICE, "remote delivery deferred: %s (%s:%s)",
323                         errmsg, host, servname);
324                 freeaddrinfo(res0);
325                 return (-1);
326         }
327         freeaddrinfo(res0);
328         return (fd);
329 }
330
331 static void
332 close_connection(int fd)
333 {
334         if (((config->features & SECURETRANS) != 0) &&
335             ((config->features & NOSSL) == 0))
336                 SSL_shutdown(config->ssl);
337
338         if (config->ssl != NULL)
339                 SSL_free(config->ssl);
340
341         close(fd);
342 }
343
344 int
345 deliver_remote(struct qitem *it, const char **errmsg)
346 {
347         struct authuser *a;
348         char *host, line[1000];
349         int fd, error = 0, do_auth = 0, res = 0;
350         size_t linelen;
351         /* asprintf can't take const */
352         void *errmsgc = __DECONST(char **, errmsg);
353
354         host = strrchr(it->addr, '@');
355         /* Should not happen */
356         if (host == NULL) {
357                 asprintf(errmsgc, "Internal error: badly formed address %s",
358                     it->addr);
359                 return(-1);
360         } else {
361                 /* Step over the @ */
362                 host++;
363         }
364
365         /* Smarthost support? */
366         if (config->smarthost != NULL && strlen(config->smarthost) > 0) {
367                 syslog(LOG_INFO, "using smarthost (%s:%i)",
368                        config->smarthost, config->port);
369                 host = config->smarthost;
370         }
371
372         fd = open_connection(host);
373         if (fd < 0)
374                 return (1);
375
376         /* Check first reply from remote host */
377         config->features |= NOSSL;
378         res = read_remote(fd, 0, NULL);
379         if (res != 2) {
380                 syslog(LOG_WARNING, "Invalid initial response: %i", res);
381                 return(1);
382         }
383         config->features &= ~NOSSL;
384
385         if ((config->features & SECURETRANS) != 0) {
386                 error = smtp_init_crypto(fd, config->features);
387                 if (error >= 0)
388                         syslog(LOG_DEBUG, "SSL initialization successful");
389                 else
390                         goto out;
391         }
392
393         send_remote_command(fd, "EHLO %s", hostname());
394         if (read_remote(fd, 0, NULL) != 2) {
395                 syslog(LOG_WARNING, "remote delivery deferred: EHLO failed: %s", neterr);
396                 asprintf(errmsgc, "%s did not like our EHLO:\n%s",
397                     host, neterr);
398                 return (-1);
399         }
400
401         /*
402          * Use SMTP authentication if the user defined an entry for the remote
403          * or smarthost
404          */
405         SLIST_FOREACH(a, &authusers, next) {
406                 if (strcmp(a->host, host) == 0) {
407                         do_auth = 1;
408                         break;
409                 }
410         }
411
412         if (do_auth == 1) {
413                 /*
414                  * Check if the user wants plain text login without using
415                  * encryption.
416                  */
417                 syslog(LOG_INFO, "using SMTP authentication");
418                 error = smtp_login(fd, a->login, a->password);
419                 if (error < 0) {
420                         syslog(LOG_ERR, "remote delivery failed:"
421                                         " SMTP login failed: %m");
422                         asprintf(errmsgc, "SMTP login to %s failed", host);
423                         return (-1);
424                 }
425                 /* SMTP login is not available, so try without */
426                 else if (error > 0) {
427                         syslog(LOG_WARNING, "SMTP login not available. Trying without.");
428                 }
429         }
430
431 #define READ_REMOTE_CHECK(c, exp)       \
432         res = read_remote(fd, 0, NULL); \
433         if (res == 5) { \
434                 syslog(LOG_ERR, "remote delivery failed: " \
435                        c " failed: %s", neterr); \
436                 asprintf(errmsgc, "%s did not like our " c ":\n%s", \
437                     host, neterr); \
438                 return (-1); \
439         } else if (res != exp) { \
440                 syslog(LOG_NOTICE, "remote delivery deferred: " \
441                        c " failed: %s", neterr); \
442                 return (1); \
443         }
444
445         send_remote_command(fd, "MAIL FROM:<%s>", it->sender);
446         READ_REMOTE_CHECK("MAIL FROM", 2);
447
448         send_remote_command(fd, "RCPT TO:<%s>", it->addr);
449         READ_REMOTE_CHECK("RCPT TO", 2);
450
451         send_remote_command(fd, "DATA");
452         READ_REMOTE_CHECK("DATA", 3);
453
454         if (fseek(it->mailf, it->hdrlen, SEEK_SET) != 0) {
455                 syslog(LOG_ERR, "remote delivery deferred: cannot seek: %s", neterr);
456                 return (1);
457         }
458
459         error = 0;
460         while (!feof(it->mailf)) {
461                 if (fgets(line, sizeof(line), it->mailf) == NULL)
462                         break;
463                 linelen = strlen(line);
464                 if (linelen == 0 || line[linelen - 1] != '\n') {
465                         syslog(LOG_CRIT, "remote delivery failed: corrupted queue file");
466                         *errmsg = "corrupted queue file";
467                         error = -1;
468                         goto out;
469                 }
470
471                 /* Remove trailing \n's and escape leading dots */
472                 trim_line(line);
473
474                 /*
475                  * If the first character is a dot, we escape it so the line
476                  * length increases
477                 */
478                 if (line[0] == '.')
479                         linelen++;
480
481                 if (send_remote_command(fd, "%s", line) != (ssize_t)linelen+1) {
482                         syslog(LOG_NOTICE, "remote delivery deferred: write error");
483                         error = 1;
484                         goto out;
485                 }
486         }
487
488         send_remote_command(fd, ".");
489         READ_REMOTE_CHECK("final DATA", 2);
490
491         send_remote_command(fd, "QUIT");
492         if (read_remote(fd, 0, NULL) != 2)
493                 syslog(LOG_INFO, "remote delivery succeeded but QUIT failed: %s", neterr);
494 out:
495
496         close_connection(fd);
497         return (error);
498 }
499