1958d22c4d2baea55fca92103e291aacfb8b87d4
[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.5 2008/03/04 11:36:09 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)
94 {
95         ssize_t rlen = 0;
96         size_t pos, len;
97         char buff[BUF_SIZE];
98         int done = 0, status = 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                 if (pos == 0 ||
115                     (pos > 0 && memchr(buff + pos, '\n', len - pos) == NULL)) {
116                         memmove(buff, buff + pos, len - pos);
117                         len -= pos;
118                         pos = 0;
119                         if (((config->features & SECURETRANS) != 0) &&
120                             (config->features & NOSSL) == 0) {
121                                 if ((rlen = SSL_read(config->ssl, buff + len,
122                                     sizeof(buff) - len)) == -1)
123                                         err(1, "read");
124                         } else {
125                                 if ((rlen = read(fd, buff + len,
126                                     sizeof(buff) - len)) == -1)
127                                         err(1, "read");
128                         }
129                         len += rlen;
130                 }
131                 for (; pos < len && buff[pos] >= '0' && buff[pos] <= '9'; pos++)
132                         ; /* Do nothing */
133
134                 if (pos == len)
135                         return (0);
136
137                 if (buff[pos] == ' ')
138                         done = 1;
139                 else if (buff[pos] != '-')
140                         syslog(LOG_ERR, "invalid syntax in reply from server");
141
142                 /* skip up to \n */
143                 for (; pos < len && buff[pos - 1] != '\n'; pos++)
144                         ; /* Do nothing */
145
146         }
147         alarm(0);
148
149         status = atoi(buff);
150         return (status/100);
151 }
152
153 /*
154  * Handle SMTP authentication
155  *
156  * XXX TODO: give me AUTH CRAM-MD5
157  */
158 static int
159 smtp_login(struct qitem *it, int fd, char *login, char* password)
160 {
161         char *temp;
162         int len, res = 0;
163
164         /* Send AUTH command according to RFC 2554 */
165         send_remote_command(fd, "AUTH LOGIN");
166         if (read_remote(fd) != 3) {
167                 syslog(LOG_ERR, "%s: remote delivery deferred:"
168                        " AUTH login not available: %m", it->queueid);
169                 return (1);
170         }
171
172         len = base64_encode(login, strlen(login), &temp);
173         if (len <= 0)
174                 return (-1);
175
176         send_remote_command(fd, "%s", temp);
177         if (read_remote(fd) != 3) {
178                 syslog(LOG_ERR, "%s: remote delivery deferred:"
179                        " AUTH login failed: %m", it->queueid);
180                 return (-1);
181         }
182
183         len = base64_encode(password, strlen(password), &temp);
184         if (len <= 0)
185                 return (-1);
186
187         send_remote_command(fd, "%s", temp);
188         res = read_remote(fd);
189         if (res == 5) {
190                 syslog(LOG_ERR, "%s: remote delivery failed:"
191                        " Authentication failed: %m", it->queueid);
192                 return (-1);
193         } else if (res != 2) {
194                 syslog(LOG_ERR, "%s: remote delivery failed:"
195                        " AUTH password failed: %m", it->queueid);
196                 return (-1);
197         }
198
199         return (0);
200 }
201
202 static int
203 open_connection(struct qitem *it, const char *host)
204 {
205         struct addrinfo hints, *res, *res0;
206         char servname[128];
207         const char *errmsg = NULL;
208         int fd, error = 0, port;
209
210         if (config->port != 0)
211                 port = config->port;
212         else
213                 port = SMTP_PORT;
214
215         /* Shamelessly taken from getaddrinfo(3) */
216         memset(&hints, 0, sizeof(hints));
217         hints.ai_family = PF_UNSPEC;
218         hints.ai_socktype = SOCK_STREAM;
219         hints.ai_protocol = IPPROTO_TCP;
220
221         snprintf(servname, sizeof(servname), "%d", port);
222         error = getaddrinfo(host, servname, &hints, &res0);
223         if (error) {
224                 syslog(LOG_ERR, "%s: remote delivery deferred: "
225                        "%s: %m", it->queueid, gai_strerror(error));
226                 return (-1);
227         }
228         fd = -1;
229         for (res = res0; res; res = res->ai_next) {
230                 fd=socket(res->ai_family, res->ai_socktype, res->ai_protocol);
231                 if (fd < 0) {
232                         errmsg = "socket failed";
233                         continue;
234                 }
235                 if (connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
236                         errmsg = "connect failed";
237                         close(fd);
238                         fd = -1;
239                         continue;
240                 }
241                 break;
242         }
243         if (fd < 0) {
244                 syslog(LOG_ERR, "%s: remote delivery deferred: %s (%s:%s)",
245                         it->queueid, errmsg, host, servname);
246                 freeaddrinfo(res0);
247                 return (-1);
248         }
249         freeaddrinfo(res0);
250         return (fd);
251 }
252
253 int
254 deliver_remote(struct qitem *it, const char **errmsg)
255 {
256         struct authuser *a;
257         char *host, line[1000];
258         int fd, error = 0, do_auth = 0, res = 0;
259         size_t linelen;
260
261         host = strrchr(it->addr, '@');
262         /* Should not happen */
263         if (host == NULL)
264                 return(-1);
265         else
266                 /* Step over the @ */
267                 host++;
268
269         /* Smarthost support? */
270         if (config->smarthost != NULL && strlen(config->smarthost) > 0) {
271                 syslog(LOG_INFO, "%s: using smarthost (%s)",
272                        it->queueid, config->smarthost);
273                 host = config->smarthost;
274         }
275
276         fd = open_connection(it, host);
277         if (fd < 0)
278                 return (1);
279
280         /* Check first reply from remote host */
281         config->features |= NOSSL;
282         res = read_remote(fd);
283         if (res != 2) {
284                 syslog(LOG_INFO, "%s: Invalid initial response: %i",
285                         it->queueid, res);
286                 return(1);
287         }
288         config->features &= ~NOSSL;
289
290 #ifdef HAVE_CRYPTO
291         if ((config->features & SECURETRANS) != 0) {
292                 error = smtp_init_crypto(it, fd, config->features);
293                 if (error >= 0)
294                         syslog(LOG_INFO, "%s: SSL initialization sucessful",
295                                 it->queueid);
296                 else
297                         goto out;
298         }
299
300         /*
301          * If the user doesn't want STARTTLS, but SSL encryption, we
302          * have to enable SSL first, then send EHLO
303          */
304         if (((config->features & STARTTLS) == 0) &&
305             ((config->features & SECURETRANS) != 0)) {
306                 send_remote_command(fd, "EHLO %s", hostname());
307                 if (read_remote(fd) != 2) {
308                         syslog(LOG_ERR, "%s: remote delivery deferred: "
309                                " EHLO failed: %m", it->queueid);
310                         return (-1);
311                 }
312         }
313 #endif /* HAVE_CRYPTO */
314         if (((config->features & SECURETRANS) == 0)) {
315                 send_remote_command(fd, "EHLO %s", hostname());
316                 if (read_remote(fd) != 2) {
317                         syslog(LOG_ERR, "%s: remote delivery deferred: "
318                                " EHLO failed: %m", it->queueid);
319                         return (-1);
320                 }
321         }
322
323         /*
324          * Use SMTP authentication if the user defined an entry for the remote
325          * or smarthost
326          */
327         SLIST_FOREACH(a, &authusers, next) {
328                 if (strcmp(a->host, host) == 0) {
329                         do_auth = 1;
330                         break;
331                 }
332         }
333
334         if (do_auth == 1) {
335                 /*
336                  * Check if the user wants plain text login without using
337                  * encryption.
338                  */
339                 if ((config->features & INSECURE) != 0) {
340                         syslog(LOG_INFO, "%s: Use SMTP authentication",
341                                 it->queueid);
342                         error = smtp_login(it, fd, a->login, a->password);
343                         if (error < 0) {
344                                 syslog(LOG_ERR, "%s: remote delivery failed:"
345                                         " SMTP login failed: %m", it->queueid);
346                                 return (-1);
347                         }
348                         /* SMTP login is not available, so try without */
349                         else if (error > 0)
350                                 syslog(LOG_ERR, "%s: SMTP login not available."
351                                         " Try without", it->queueid);
352                 } else {
353                         syslog(LOG_ERR, "%s: Skip SMTP login. ",
354                                 it->queueid);
355                 }
356         }
357
358         send_remote_command(fd, "MAIL FROM:<%s>", it->sender);
359         if (read_remote(fd) != 2) {
360                 syslog(LOG_ERR, "%s: remote delivery deferred:"
361                        " MAIL FROM failed: %m", it->queueid);
362                 return (1);
363         }
364
365         /* XXX TODO:
366          * Iterate over all recepients and open only one connection
367          */
368         send_remote_command(fd, "RCPT TO:<%s>", it->addr);
369         if (read_remote(fd) != 2) {
370                 syslog(LOG_ERR, "%s: remote delivery deferred:"
371                        " RCPT TO failed: %m", it->queueid);
372                 return (1);
373         }
374
375         send_remote_command(fd, "DATA");
376         if (read_remote(fd) != 3) {
377                 syslog(LOG_ERR, "%s: remote delivery deferred:"
378                        " DATA failed: %m", it->queueid);
379                 return (1);
380         }
381
382         if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0) {
383                 syslog(LOG_ERR, "%s: remote delivery deferred: cannot seek: %m",
384                        it->queueid);
385                 return (1);
386         }
387
388         while (!feof(it->queuef)) {
389                 if (fgets(line, sizeof(line), it->queuef) == NULL)
390                         break;
391                 linelen = strlen(line);
392                 if (linelen == 0 || line[linelen - 1] != '\n') {
393                         syslog(LOG_CRIT, "%s: remote delivery failed:"
394                                 "corrupted queue file", it->queueid);
395                         *errmsg = "corrupted queue file";
396                         error = -1;
397                         goto out;
398                 }
399
400                 /* Remove trailing \n's and escape leading dots */
401                 trim_line(line);
402
403                 /*
404                  * If the first character is a dot, we escape it so the line
405                  * length increases
406                 */
407                 if (line[0] == '.')
408                         linelen++;
409
410                 if (send_remote_command(fd, "%s", line) != (ssize_t)linelen+1) {
411                         syslog(LOG_ERR, "%s: remote delivery deferred: "
412                                 "write error", it->queueid);
413                         error = 1;
414                         goto out;
415                 }
416         }
417
418         send_remote_command(fd, ".");
419         if (read_remote(fd) != 2) {
420                 syslog(LOG_ERR, "%s: remote delivery deferred: %m",
421                        it->queueid);
422                 return (1);
423         }
424
425         send_remote_command(fd, "QUIT");
426         if (read_remote(fd) != 2) {
427                 syslog(LOG_ERR, "%s: remote delivery deferred: "
428                        "QUIT failed: %m", it->queueid);
429                 return (1);
430         }
431 out:
432
433         close(fd);
434         return (error);
435 }
436