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