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