2 * Copyright (c) 2008-2014, Simon Schubert <2@0x2c.org>.
3 * Copyright (c) 2008 The DragonFly Project. All rights reserved.
5 * This code is derived from software contributed to The DragonFly Project
6 * by Matthias Schmidt <matthias@dragonflybsd.org>, University of Marburg,
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
19 * 3. Neither the name of The DragonFly Project nor the names of its
20 * contributors may be used to endorse or promote products derived
21 * from this software without specific, prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
29 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
31 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
32 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
33 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 #include <sys/param.h>
40 #include <sys/queue.h>
42 #include <sys/types.h>
43 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
47 #include <openssl/ssl.h>
48 #include <openssl/err.h>
63 char neterr
[ERRMSG_SIZE
];
71 while ((nerr
= ERR_get_error()) != 0)
74 return (ERR_error_string(oerr
, NULL
));
78 send_remote_command(int fd
, const char* fmt
, ...)
87 s
= vsnprintf(cmd
, sizeof(cmd
) - 2, fmt
, va
);
89 if (s
== sizeof(cmd
) - 2 || s
< 0) {
90 strcpy(neterr
, "Internal error: oversized command string");
94 /* We *know* there are at least two more bytes available */
98 if (((config
.features
& SECURETRANSFER
) != 0) &&
99 ((config
.features
& NOSSL
) == 0)) {
100 while ((s
= SSL_write(config
.ssl
, (const char*)cmd
, len
)) <= 0) {
101 s
= SSL_get_error(config
.ssl
, s
);
102 if (s
!= SSL_ERROR_WANT_READ
&&
103 s
!= SSL_ERROR_WANT_WRITE
) {
104 strlcpy(neterr
, ssl_errstr(), sizeof(neterr
));
112 n
= write(fd
, cmd
+ pos
, len
- pos
);
123 read_remote(int fd
, int extbufsize
, char *extbuf
)
126 size_t pos
, len
, copysize
;
128 int done
= 0, status
= 0, status_running
= 0, extbufpos
= 0;
129 enum { parse_status
, parse_spacedash
, parse_rest
} parsestate
;
131 if (do_timeout(CON_TIMEOUT
, 1) != 0) {
132 snprintf(neterr
, sizeof(neterr
), "Timeout reached");
137 * Remote reading code from femail.c written by Henning Brauer of
138 * OpenBSD and released under a BSD style license.
142 parsestate
= parse_status
;
144 while (!(done
&& parsestate
== parse_status
)) {
147 (pos
> 0 && memchr(buff
+ pos
, '\n', len
- pos
) == NULL
)) {
148 memmove(buff
, buff
+ pos
, len
- pos
);
151 if (((config
.features
& SECURETRANSFER
) != 0) &&
152 (config
.features
& NOSSL
) == 0) {
153 if ((rlen
= SSL_read(config
.ssl
, buff
+ len
, sizeof(buff
) - len
)) == -1) {
154 strlcpy(neterr
, ssl_errstr(), sizeof(neterr
));
158 if ((rlen
= read(fd
, buff
+ len
, sizeof(buff
) - len
)) == -1) {
159 strlcpy(neterr
, strerror(errno
), sizeof(neterr
));
165 copysize
= sizeof(neterr
) - strlen(neterr
) - 1;
168 strncat(neterr
, buff
, copysize
);
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
176 if (extbufpos
<= (extbufsize
- 1) && rlen
> 0 && extbufsize
> 0 && extbuf
!= NULL
) {
177 /* do not write over the bounds of the buffer */
178 if(extbufpos
+ rlen
> (extbufsize
- 1)) {
179 rlen
= extbufsize
- extbufpos
;
181 memcpy(extbuf
+ extbufpos
, buff
+ len
- rlen
, rlen
);
188 switch (parsestate
) {
190 for (; pos
< len
; pos
++) {
191 if (isdigit(buff
[pos
])) {
192 status_running
= status_running
* 10 + (buff
[pos
] - '0');
194 status
= status_running
;
196 parsestate
= parse_spacedash
;
202 case parse_spacedash
:
210 /* XXX read capabilities */
214 strcpy(neterr
, "invalid syntax in reply from server");
219 parsestate
= parse_rest
;
224 for (; pos
< len
; pos
++) {
225 if (buff
[pos
] == '\n') {
227 parsestate
= parse_status
;
237 /* chop off trailing newlines */
238 while (neterr
[0] != 0 && strchr("\r\n", neterr
[strlen(neterr
) - 1]) != 0)
239 neterr
[strlen(neterr
) - 1] = 0;
249 * Handle SMTP authentication
252 smtp_login(int fd
, char *login
, char* password
, const struct smtp_features
* features
)
258 if (features
->auth
.cram_md5
) {
259 res
= smtp_auth_md5(fd
, login
, password
);
262 } else if (res
== -2) {
264 * If the return code is -2, then then the login attempt failed,
265 * do not try other login mechanisms
272 if (features
->auth
.login
) {
273 if ((config
.features
& INSECURE
) != 0 ||
274 (config
.features
& SECURETRANSFER
) != 0) {
275 /* Send AUTH command according to RFC 2554 */
276 send_remote_command(fd
, "AUTH LOGIN");
277 if (read_remote(fd
, 0, NULL
) != 3) {
278 syslog(LOG_NOTICE
, "remote delivery deferred:"
279 " AUTH login not available: %s",
284 len
= base64_encode(login
, strlen(login
), &temp
);
287 syslog(LOG_ERR
, "can not encode auth reply: %m");
291 send_remote_command(fd
, "%s", temp
);
293 res
= read_remote(fd
, 0, NULL
);
295 syslog(LOG_NOTICE
, "remote delivery %s: AUTH login failed: %s",
296 res
== 5 ? "failed" : "deferred", neterr
);
297 return (res
== 5 ? -1 : 1);
300 len
= base64_encode(password
, strlen(password
), &temp
);
304 send_remote_command(fd
, "%s", temp
);
306 res
= read_remote(fd
, 0, NULL
);
308 syslog(LOG_NOTICE
, "remote delivery %s: Authentication failed: %s",
309 res
== 5 ? "failed" : "deferred", neterr
);
310 return (res
== 5 ? -1 : 1);
313 syslog(LOG_WARNING
, "non-encrypted SMTP login is disabled in config, so skipping it. ");
322 open_connection(struct mx_hostentry
*h
)
326 syslog(LOG_INFO
, "trying remote delivery to %s [%s] pref %d",
327 h
->host
, h
->addr
, h
->pref
);
329 fd
= socket(h
->ai
.ai_family
, h
->ai
.ai_socktype
, h
->ai
.ai_protocol
);
331 syslog(LOG_INFO
, "socket for %s [%s] failed: %m",
336 if (connect(fd
, (struct sockaddr
*)&h
->sa
, h
->ai
.ai_addrlen
) < 0) {
337 syslog(LOG_INFO
, "connect to %s [%s] failed: %m",
347 close_connection(int fd
)
349 if (config
.ssl
!= NULL
) {
350 if (((config
.features
& SECURETRANSFER
) != 0) &&
351 ((config
.features
& NOSSL
) == 0))
352 SSL_shutdown(config
.ssl
);
353 SSL_free(config
.ssl
);
359 static void parse_auth_line(char* line
, struct smtp_auth_mechanisms
* auth
) {
360 // Skip the auth prefix
361 line
+= strlen("AUTH ");
363 char* method
= strtok(line
, " ");
365 if (strcmp(method
, "CRAM-MD5") == 0)
368 else if (strcmp(method
, "LOGIN") == 0)
371 method
= strtok(NULL
, " ");
375 int perform_server_greeting(int fd
, struct smtp_features
* features
) {
378 XXX allow HELO fallback
380 send_remote_command(fd
, "EHLO %s", hostname());
382 char buffer
[EHLO_RESPONSE_SIZE
];
383 memset(buffer
, 0, sizeof(buffer
));
385 int res
= read_remote(fd
, sizeof(buffer
) - 1, buffer
);
387 // Got an unexpected response
391 // Reset all features
392 memset(features
, 0, sizeof(*features
));
394 // Run through the buffer line by line
395 char linebuffer
[EHLO_RESPONSE_SIZE
];
399 char* line
= linebuffer
;
400 while (*p
&& *p
!= '\n') {
404 // p should never point to NULL after the loop
405 // above unless we reached the end of the buffer.
406 // In that case we will raise an error.
411 // Otherwise p points to the newline character which
415 // Terminte the string (and remove the carriage-return character)
419 // End main loop for empty lines
424 // - Must start with 250, followed by dash or space
425 // - We won't check for the correct usage of space and dash because
426 // that is already done in read_remote().
427 if ((strncmp(line
, "250-", 4) != 0) && (strncmp(line
, "250 ", 4) != 0)) {
428 syslog(LOG_ERR
, "Invalid line: %s\n", line
);
435 // Check for STARTTLS
436 if (strcmp(line
, "STARTTLS") == 0)
437 features
->starttls
= 1;
439 // Parse authentication mechanisms
440 else if (strncmp(line
, "AUTH ", 5) == 0)
441 parse_auth_line(line
, &features
->auth
);
444 syslog(LOG_DEBUG
, "Server greeting successfully completed");
447 if (features
->starttls
)
448 syslog(LOG_DEBUG
, " Server supports STARTTLS");
450 syslog(LOG_DEBUG
, " Server does not support STARTTLS");
453 if (features
->auth
.cram_md5
) {
454 syslog(LOG_DEBUG
, " Server supports CRAM-MD5 authentication");
456 if (features
->auth
.login
) {
457 syslog(LOG_DEBUG
, " Server supports LOGIN authentication");
464 deliver_to_host(struct qitem
*it
, struct mx_hostentry
*host
)
467 struct smtp_features features
;
468 char line
[1000], *addrtmp
= NULL
, *to_addr
;
470 int fd
, error
= 0, do_auth
= 0, res
= 0;
472 if (fseek(it
->mailf
, 0, SEEK_SET
) != 0) {
473 snprintf(errmsg
, sizeof(errmsg
), "can not seek: %s", strerror(errno
));
477 fd
= open_connection(host
);
481 #define READ_REMOTE_CHECK(c, exp) \
483 res = read_remote(fd, 0, NULL); \
485 syslog(LOG_ERR, "remote delivery to %s [%s] failed after %s: %s", \
486 host->host, host->addr, c, neterr); \
487 snprintf(errmsg, sizeof(errmsg), "%s [%s] did not like our %s:\n%s", \
488 host->host, host->addr, c, neterr); \
491 } else if (res != exp) { \
492 syslog(LOG_NOTICE, "remote delivery deferred: %s [%s] failed after %s: %s", \
493 host->host, host->addr, c, neterr); \
499 /* Check first reply from remote host */
500 if ((config
.features
& SECURETRANSFER
) == 0 ||
501 (config
.features
& STARTTLS
) != 0) {
502 config
.features
|= NOSSL
;
503 READ_REMOTE_CHECK("connect", 2);
505 config
.features
&= ~NOSSL
;
508 if ((config
.features
& SECURETRANSFER
) != 0) {
509 error
= smtp_init_crypto(fd
, config
.features
, &features
);
511 syslog(LOG_DEBUG
, "SSL initialization successful");
515 if ((config
.features
& STARTTLS
) == 0)
516 READ_REMOTE_CHECK("connect", 2);
520 if (perform_server_greeting(fd
, &features
) != 0) {
521 syslog(LOG_ERR
, "Could not perform server greeting at %s [%s]: %s",
522 host
->host
, host
->addr
, neterr
);
527 * Use SMTP authentication if the user defined an entry for the remote
530 SLIST_FOREACH(a
, &authusers
, next
) {
531 if (strcmp(a
->host
, host
->host
) == 0) {
539 * Check if the user wants plain text login without using
542 syslog(LOG_INFO
, "using SMTP authentication for user %s", a
->login
);
543 error
= smtp_login(fd
, a
->login
, a
->password
, &features
);
545 syslog(LOG_ERR
, "remote delivery failed:"
546 " SMTP login failed: %m");
547 snprintf(errmsg
, sizeof(errmsg
), "SMTP login to %s failed", host
->host
);
551 /* SMTP login is not available, so try without */
552 else if (error
> 0) {
553 syslog(LOG_WARNING
, "SMTP login not available. Trying without.");
557 /* XXX send ESMTP ENVID, RET (FULL/HDRS) and 8BITMIME */
558 send_remote_command(fd
, "MAIL FROM:<%s>", it
->sender
);
559 READ_REMOTE_CHECK("MAIL FROM", 2);
561 /* XXX send ESMTP ORCPT */
562 if ((addrtmp
= strdup(it
->addr
)) == NULL
) {
563 syslog(LOG_CRIT
, "remote delivery deferred: unable to allocate memory");
567 to_addr
= strtok(addrtmp
, ",");
568 while (to_addr
!= NULL
) {
569 send_remote_command(fd
, "RCPT TO:<%s>", to_addr
);
570 READ_REMOTE_CHECK("RCPT TO", 2);
571 to_addr
= strtok(NULL
, ",");
574 send_remote_command(fd
, "DATA");
575 READ_REMOTE_CHECK("DATA", 3);
578 while (!feof(it
->mailf
)) {
579 if (fgets(line
, sizeof(line
), it
->mailf
) == NULL
)
581 linelen
= strlen(line
);
582 if (linelen
== 0 || line
[linelen
- 1] != '\n') {
583 syslog(LOG_CRIT
, "remote delivery failed: corrupted queue file");
584 snprintf(errmsg
, sizeof(errmsg
), "corrupted queue file");
589 /* Remove trailing \n's and escape leading dots */
593 * If the first character is a dot, we escape it so the line
599 if (send_remote_command(fd
, "%s", line
) != (ssize_t
)linelen
+1) {
600 syslog(LOG_NOTICE
, "remote delivery deferred: write error");
606 send_remote_command(fd
, ".");
607 READ_REMOTE_CHECK("final DATA", 2);
609 send_remote_command(fd
, "QUIT");
610 if (read_remote(fd
, 0, NULL
) != 2)
611 syslog(LOG_INFO
, "remote delivery succeeded but QUIT failed: %s", neterr
);
615 close_connection(fd
);
620 deliver_remote(struct qitem
*it
)
622 struct mx_hostentry
*hosts
, *h
;
625 int error
= 1, smarthost
= 0;
629 /* Smarthost support? */
630 if (config
.smarthost
!= NULL
) {
631 host
= config
.smarthost
;
633 syslog(LOG_INFO
, "using smarthost (%s:%i)", host
, port
);
636 host
= strrchr(it
->addr
, '@');
637 /* Should not happen */
639 snprintf(errmsg
, sizeof(errmsg
), "Internal error: badly formed address %s",
643 /* Step over the @ */
648 error
= dns_get_mx_list(host
, port
, &hosts
, smarthost
);
650 snprintf(errmsg
, sizeof(errmsg
), "DNS lookup failure: host %s not found", host
);
651 syslog(LOG_NOTICE
, "remote delivery %s: DNS lookup failure: host %s not found",
652 error
< 0 ? "failed" : "deferred",
657 for (h
= hosts
; *h
->host
!= 0; h
++) {
658 switch (deliver_to_host(it
, h
)) {