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