1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) University of Cambridge 1995 - 2016 */
6 /* See the file NOTICE for conditions of use and distribution. */
8 /* Functions for handling an incoming SMTP call. */
15 /* Initialize for TCP wrappers if so configured. It appears that the macro
16 HAVE_IPV6 is used in some versions of the tcpd.h header, so we unset it before
17 including that header, and restore its value afterwards. */
19 #ifdef USE_TCP_WRAPPERS
22 #define EXIM_HAVE_IPV6
28 #define HAVE_IPV6 TRUE
31 int allow_severity
= LOG_INFO
;
32 int deny_severity
= LOG_NOTICE
;
33 uschar
*tcp_wrappers_name
;
37 /* Size of buffer for reading SMTP commands. We used to use 512, as defined
38 by RFC 821. However, RFC 1869 specifies that this must be increased for SMTP
39 commands that accept arguments, and this in particular applies to AUTH, where
40 the data can be quite long. More recently this value was 2048 in Exim;
41 however, RFC 4954 (circa 2007) recommends 12288 bytes to handle AUTH. Clients
42 such as Thunderbird will send an AUTH with an initial-response for GSSAPI.
43 The maximum size of a Kerberos ticket under Windows 2003 is 12000 bytes, and
44 we need room to handle large base64-encoded AUTHs for GSSAPI.
47 #define smtp_cmd_buffer_size 16384
49 /* Size of buffer for reading SMTP incoming packets */
51 #define in_buffer_size 8192
53 /* Structure for SMTP command list */
60 short int is_mail_cmd
;
63 /* Codes for identifying commands. We order them so that those that come first
64 are those for which synchronization is always required. Checking this can help
68 /* These commands are required to be synchronized, i.e. to be the last in a
69 block of commands when pipelining. */
71 HELO_CMD
, EHLO_CMD
, DATA_CMD
, /* These are listed in the pipelining */
72 VRFY_CMD
, EXPN_CMD
, NOOP_CMD
, /* RFC as requiring synchronization */
73 ETRN_CMD
, /* This by analogy with TURN from the RFC */
74 STARTTLS_CMD
, /* Required by the STARTTLS RFC */
75 TLS_AUTH_CMD
, /* auto-command at start of SSL */
77 /* This is a dummy to identify the non-sync commands when pipelining */
79 NON_SYNC_CMD_PIPELINING
,
81 /* These commands need not be synchronized when pipelining */
83 MAIL_CMD
, RCPT_CMD
, RSET_CMD
,
85 /* RFC3030 section 2: "After all MAIL and RCPT responses are collected and
86 processed the message is sent using a series of BDAT commands"
87 implies that BDAT should be synchronized. However, we see Google, at least,
88 sending MAIL,RCPT,BDAT-LAST in a single packet, clearly not waiting for
89 processing of the RPCT response(s). We shall do the same, and not require
94 /* This is a dummy to identify the non-sync commands when not pipelining */
96 NON_SYNC_CMD_NON_PIPELINING
,
98 /* I have been unable to find a statement about the use of pipelining
99 with AUTH, so to be on the safe side it is here, though I kind of feel
100 it should be up there with the synchronized commands. */
104 /* I'm not sure about these, but I don't think they matter. */
109 PROXY_FAIL_IGNORE_CMD
,
112 /* These are specials that don't correspond to actual commands */
114 EOF_CMD
, OTHER_CMD
, BADARG_CMD
, BADCHAR_CMD
, BADSYN_CMD
,
115 TOO_MANY_NONMAIL_CMD
};
118 /* This is a convenience macro for adding the identity of an SMTP command
119 to the circular buffer that holds a list of the last n received. */
122 smtp_connection_had[smtp_ch_index++] = n; \
123 if (smtp_ch_index >= SMTP_HBUFF_SIZE) smtp_ch_index = 0
126 /*************************************************
127 * Local static variables *
128 *************************************************/
130 static auth_instance
*authenticated_by
;
131 static BOOL auth_advertised
;
133 static BOOL tls_advertised
;
135 static BOOL dsn_advertised
;
137 static BOOL helo_required
= FALSE
;
138 static BOOL helo_verify
= FALSE
;
139 static BOOL helo_seen
;
140 static BOOL helo_accept_junk
;
141 static BOOL count_nonmail
;
142 static BOOL pipelining_advertised
;
143 static BOOL rcpt_smtp_response_same
;
144 static BOOL rcpt_in_progress
;
145 static int nonmail_command_count
;
148 static BOOL smtp_exit_function_called
= 0;
150 static BOOL smtputf8_advertised
;
152 static int synprot_error_count
;
153 static int unknown_command_count
;
154 static int sync_cmd_limit
;
155 static int smtp_write_error
= 0;
157 static uschar
*rcpt_smtp_response
;
158 static uschar
*smtp_data_buffer
;
159 static uschar
*smtp_cmd_data
;
161 /* We need to know the position of RSET, HELO, EHLO, AUTH, and STARTTLS. Their
162 final fields of all except AUTH are forced TRUE at the start of a new message
163 setup, to allow one of each between messages that is not counted as a nonmail
164 command. (In fact, only one of HELO/EHLO is not counted.) Also, we have to
165 allow a new EHLO after starting up TLS.
167 AUTH is "falsely" labelled as a mail command initially, so that it doesn't get
168 counted. However, the flag is changed when AUTH is received, so that multiple
169 failing AUTHs will eventually hit the limit. After a successful AUTH, another
170 AUTH is already forbidden. After a TLS session is started, AUTH's flag is again
171 forced TRUE, to allow for the re-authentication that can happen at that point.
173 QUIT is also "falsely" labelled as a mail command so that it doesn't up the
174 count of non-mail commands and possibly provoke an error.
176 tls_auth is a pseudo-command, never expected in input. It is activated
177 on TLS startup and looks for a tls authenticator. */
179 static smtp_cmd_list cmd_list
[] = {
180 /* name len cmd has_arg is_mail_cmd */
182 { "rset", sizeof("rset")-1, RSET_CMD
, FALSE
, FALSE
}, /* First */
183 { "helo", sizeof("helo")-1, HELO_CMD
, TRUE
, FALSE
},
184 { "ehlo", sizeof("ehlo")-1, EHLO_CMD
, TRUE
, FALSE
},
185 { "auth", sizeof("auth")-1, AUTH_CMD
, TRUE
, TRUE
},
187 { "starttls", sizeof("starttls")-1, STARTTLS_CMD
, FALSE
, FALSE
},
188 { "tls_auth", 0, TLS_AUTH_CMD
, FALSE
, TRUE
},
191 /* If you change anything above here, also fix the definitions below. */
193 { "mail from:", sizeof("mail from:")-1, MAIL_CMD
, TRUE
, TRUE
},
194 { "rcpt to:", sizeof("rcpt to:")-1, RCPT_CMD
, TRUE
, TRUE
},
195 { "data", sizeof("data")-1, DATA_CMD
, FALSE
, TRUE
},
196 { "bdat", sizeof("bdat")-1, BDAT_CMD
, TRUE
, TRUE
},
197 { "quit", sizeof("quit")-1, QUIT_CMD
, FALSE
, TRUE
},
198 { "noop", sizeof("noop")-1, NOOP_CMD
, TRUE
, FALSE
},
199 { "etrn", sizeof("etrn")-1, ETRN_CMD
, TRUE
, FALSE
},
200 { "vrfy", sizeof("vrfy")-1, VRFY_CMD
, TRUE
, FALSE
},
201 { "expn", sizeof("expn")-1, EXPN_CMD
, TRUE
, FALSE
},
202 { "help", sizeof("help")-1, HELP_CMD
, TRUE
, FALSE
}
205 static smtp_cmd_list
*cmd_list_end
=
206 cmd_list
+ sizeof(cmd_list
)/sizeof(smtp_cmd_list
);
208 #define CMD_LIST_RSET 0
209 #define CMD_LIST_HELO 1
210 #define CMD_LIST_EHLO 2
211 #define CMD_LIST_AUTH 3
212 #define CMD_LIST_STARTTLS 4
213 #define CMD_LIST_TLS_AUTH 5
215 /* This list of names is used for performing the smtp_no_mail logging action.
216 It must be kept in step with the SCH_xxx enumerations. */
218 static uschar
*smtp_names
[] =
220 US
"NONE", US
"AUTH", US
"DATA", US
"BDAT", US
"EHLO", US
"ETRN", US
"EXPN",
221 US
"HELO", US
"HELP", US
"MAIL", US
"NOOP", US
"QUIT", US
"RCPT", US
"RSET",
222 US
"STARTTLS", US
"VRFY" };
224 static uschar
*protocols_local
[] = {
225 US
"local-smtp", /* HELO */
226 US
"local-smtps", /* The rare case EHLO->STARTTLS->HELO */
227 US
"local-esmtp", /* EHLO */
228 US
"local-esmtps", /* EHLO->STARTTLS->EHLO */
229 US
"local-esmtpa", /* EHLO->AUTH */
230 US
"local-esmtpsa" /* EHLO->STARTTLS->EHLO->AUTH */
232 static uschar
*protocols
[] = {
234 US
"smtps", /* The rare case EHLO->STARTTLS->HELO */
235 US
"esmtp", /* EHLO */
236 US
"esmtps", /* EHLO->STARTTLS->EHLO */
237 US
"esmtpa", /* EHLO->AUTH */
238 US
"esmtpsa" /* EHLO->STARTTLS->EHLO->AUTH */
243 #define pcrpted 1 /* added to pextend or pnormal */
244 #define pauthed 2 /* added to pextend */
246 /* Sanity check and validate optional args to MAIL FROM: envelope */
249 ENV_MAIL_OPT_SIZE
, ENV_MAIL_OPT_BODY
, ENV_MAIL_OPT_AUTH
,
253 ENV_MAIL_OPT_RET
, ENV_MAIL_OPT_ENVID
,
259 uschar
* name
; /* option requested during MAIL cmd */
260 int value
; /* enum type */
261 BOOL need_value
; /* TRUE requires value (name=value pair format)
262 FALSE is a singleton */
264 static env_mail_type_t env_mail_type_list
[] = {
265 { US
"SIZE", ENV_MAIL_OPT_SIZE
, TRUE
},
266 { US
"BODY", ENV_MAIL_OPT_BODY
, TRUE
},
267 { US
"AUTH", ENV_MAIL_OPT_AUTH
, TRUE
},
269 { US
"PRDR", ENV_MAIL_OPT_PRDR
, FALSE
},
271 { US
"RET", ENV_MAIL_OPT_RET
, TRUE
},
272 { US
"ENVID", ENV_MAIL_OPT_ENVID
, TRUE
},
274 { US
"SMTPUTF8",ENV_MAIL_OPT_UTF8
, FALSE
}, /* rfc6531 */
276 /* keep this the last entry */
277 { US
"NULL", ENV_MAIL_OPT_NULL
, FALSE
},
280 /* When reading SMTP from a remote host, we have to use our own versions of the
281 C input-reading functions, in order to be able to flush the SMTP output only
282 when about to read more data from the socket. This is the only way to get
283 optimal performance when the client is using pipelining. Flushing for every
284 command causes a separate packet and reply packet each time; saving all the
285 responses up (when pipelining) combines them into one packet and one response.
287 For simplicity, these functions are used for *all* SMTP input, not only when
288 receiving over a socket. However, after setting up a secure socket (SSL), input
289 is read via the OpenSSL library, and another set of functions is used instead
292 These functions are set in the receive_getc etc. variables and called with the
293 same interface as the C functions. However, since there can only ever be
294 one incoming SMTP call, we just use a single buffer and flags. There is no need
295 to implement a complicated private FILE-like structure.*/
297 static uschar
*smtp_inbuffer
;
298 static uschar
*smtp_inptr
;
299 static uschar
*smtp_inend
;
300 static int smtp_had_eof
;
301 static int smtp_had_error
;
304 /* forward declarations */
305 int bdat_ungetc(int ch
);
306 static int smtp_read_command(BOOL check_sync
);
307 static int synprot_error(int type
, int code
, uschar
*data
, uschar
*errmess
);
308 static void smtp_quit_handler(uschar
**, uschar
**);
309 static void smtp_rset_handler(void);
311 /*************************************************
312 * SMTP version of getc() *
313 *************************************************/
315 /* This gets the next byte from the SMTP input buffer. If the buffer is empty,
316 it flushes the output, and refills the buffer, with a timeout. The signal
317 handler is set appropriately by the calling function. This function is not used
318 after a connection has negotated itself into an TLS/SSL state.
321 Returns: the next character or EOF
327 if (smtp_inptr
>= smtp_inend
)
330 if (!smtp_out
) return EOF
;
332 if (smtp_receive_timeout
> 0) alarm(smtp_receive_timeout
);
333 rc
= read(fileno(smtp_in
), smtp_inbuffer
, in_buffer_size
);
338 /* Must put the error text in fixed store, because this might be during
339 header reading, where it releases unused store above the header. */
342 smtp_had_error
= save_errno
;
343 smtp_read_error
= string_copy_malloc(
344 string_sprintf(" (error: %s)", strerror(save_errno
)));
346 else smtp_had_eof
= 1;
350 dkim_exim_verify_feed(smtp_inbuffer
, rc
);
352 smtp_inend
= smtp_inbuffer
+ rc
;
353 smtp_inptr
= smtp_inbuffer
;
355 return *smtp_inptr
++;
362 int n
= smtp_inend
- smtp_inptr
;
364 dkim_exim_verify_feed(smtp_inptr
, n
);
369 /* Get a byte from the smtp input, in CHUNKING mode. Handle ack of the
370 previous BDAT chunk and getting new ones when we run out. Uses the
371 underlying smtp_getc or tls_getc both for that and for getting the
372 (buffered) data byte. EOD signals (an expected) no further data.
373 ERR signals a protocol error, and EOF a closed input stream.
375 Called from read_bdat_smtp() in receive.c for the message body, but also
376 by the headers read loop in receive_msg(); manipulates chunking_state
377 to handle the BDAT command/response.
378 Placed here due to the correlation with the above smtp_getc(), which it wraps,
379 and also by the need to do smtp command/response handling.
382 Returns: the next character or ERR, EOD or EOF
388 uschar
* user_msg
= NULL
;
393 if (chunking_data_left
-- > 0)
394 return lwr_receive_getc();
396 receive_getc
= lwr_receive_getc
;
397 receive_ungetc
= lwr_receive_ungetc
;
399 /* If not the last, ack the received chunk. The last response is delayed
400 until after the data ACL decides on it */
402 if (chunking_state
== CHUNKING_LAST
)
405 dkim_exim_verify_feed(NULL
, 0); /* notify EOD */
410 chunking_state
= CHUNKING_OFFERED
;
411 smtp_printf("250 %u byte chunk received\r\n", chunking_datasize
);
413 /* Expect another BDAT cmd from input. RFC 3030 says nothing about
414 QUIT, RSET or NOOP but handling them seems obvious */
417 switch(smtp_read_command(TRUE
))
420 (void) synprot_error(L_smtp_protocol_error
, 503, NULL
,
421 US
"only BDAT permissible after non-LAST BDAT");
424 switch(smtp_read_command(TRUE
))
426 case QUIT_CMD
: smtp_quit_handler(&user_msg
, &log_msg
); /*FALLTHROUGH */
427 case EOF_CMD
: return EOF
;
428 case RSET_CMD
: smtp_rset_handler(); return ERR
;
429 default: if (synprot_error(L_smtp_protocol_error
, 503, NULL
,
430 US
"only RSET accepted now") > 0)
432 goto repeat_until_rset
;
436 smtp_quit_handler(&user_msg
, &log_msg
);
447 smtp_printf("250 OK\r\n");
454 if (sscanf(CS smtp_cmd_data
, "%u %n", &chunking_datasize
, &n
) < 1)
456 (void) synprot_error(L_smtp_protocol_error
, 501, NULL
,
457 US
"missing size for BDAT command");
460 chunking_state
= strcmpic(smtp_cmd_data
+n
, US
"LAST") == 0
461 ? CHUNKING_LAST
: CHUNKING_ACTIVE
;
462 chunking_data_left
= chunking_datasize
;
464 if (chunking_datasize
== 0)
465 if (chunking_state
== CHUNKING_LAST
)
469 (void) synprot_error(L_smtp_protocol_error
, 504, NULL
,
470 US
"zero size for BDAT command");
471 goto repeat_until_rset
;
474 receive_getc
= bdat_getc
;
475 receive_ungetc
= bdat_ungetc
;
476 break; /* to top of main loop */
483 bdat_flush_data(void)
485 while (chunking_data_left
-- > 0)
486 if (lwr_receive_getc() < 0)
489 receive_getc
= lwr_receive_getc
;
490 receive_ungetc
= lwr_receive_ungetc
;
492 if (chunking_state
!= CHUNKING_LAST
)
493 chunking_state
= CHUNKING_OFFERED
;
499 /*************************************************
500 * SMTP version of ungetc() *
501 *************************************************/
503 /* Puts a character back in the input buffer. Only ever
509 Returns: the character
523 chunking_data_left
++;
524 return lwr_receive_ungetc(ch
);
529 /*************************************************
530 * SMTP version of feof() *
531 *************************************************/
533 /* Tests for a previous EOF
536 Returns: non-zero if the eof flag is set
548 /*************************************************
549 * SMTP version of ferror() *
550 *************************************************/
552 /* Tests for a previous read error, and returns with errno
553 restored to what it was when the error was detected.
556 Returns: non-zero if the error flag is set
562 errno
= smtp_had_error
;
563 return smtp_had_error
;
568 /*************************************************
569 * Test for characters in the SMTP buffer *
570 *************************************************/
572 /* Used at the end of a message
581 return smtp_inptr
< smtp_inend
;
586 /*************************************************
587 * Write formatted string to SMTP channel *
588 *************************************************/
590 /* This is a separate function so that we don't have to repeat everything for
591 TLS support or debugging. It is global so that the daemon and the
592 authentication functions can use it. It does not return any error indication,
593 because major problems such as dropped connections won't show up till an output
594 flush for non-TLS connections. The smtp_fflush() function is available for
595 checking that: for convenience, TLS output errors are remembered here so that
596 they are also picked up later by smtp_fflush().
600 ... optional arguments
606 smtp_printf(const char *format
, ...)
610 va_start(ap
, format
);
611 smtp_vprintf(format
, ap
);
615 /* This is split off so that verify.c:respond_printf() can, in effect, call
616 smtp_printf(), bearing in mind that in C a vararg function can't directly
617 call another vararg function, only a function which accepts a va_list. */
620 smtp_vprintf(const char *format
, va_list ap
)
624 yield
= string_vformat(big_buffer
, big_buffer_size
, format
, ap
);
628 void *reset_point
= store_get(0);
629 uschar
*msg_copy
, *cr
, *end
;
630 msg_copy
= string_copy(big_buffer
);
631 end
= msg_copy
+ Ustrlen(msg_copy
);
632 while ((cr
= Ustrchr(msg_copy
, '\r')) != NULL
) /* lose CRs */
633 memmove(cr
, cr
+ 1, (end
--) - cr
);
634 debug_printf("SMTP>> %s", msg_copy
);
635 store_reset(reset_point
);
640 log_write(0, LOG_MAIN
|LOG_PANIC
, "string too large in smtp_printf()");
641 smtp_closedown(US
"Unexpected error");
642 exim_exit(EXIT_FAILURE
);
645 /* If this is the first output for a (non-batch) RCPT command, see if all RCPTs
646 have had the same. Note: this code is also present in smtp_respond(). It would
647 be tidier to have it only in one place, but when it was added, it was easier to
648 do it that way, so as not to have to mess with the code for the RCPT command,
649 which sometimes uses smtp_printf() and sometimes smtp_respond(). */
651 if (rcpt_in_progress
)
653 if (rcpt_smtp_response
== NULL
)
654 rcpt_smtp_response
= string_copy(big_buffer
);
655 else if (rcpt_smtp_response_same
&&
656 Ustrcmp(rcpt_smtp_response
, big_buffer
) != 0)
657 rcpt_smtp_response_same
= FALSE
;
658 rcpt_in_progress
= FALSE
;
661 /* Now write the string */
664 if (tls_in
.active
>= 0)
666 if (tls_write(TRUE
, big_buffer
, Ustrlen(big_buffer
)) < 0)
667 smtp_write_error
= -1;
672 if (fprintf(smtp_out
, "%s", big_buffer
) < 0) smtp_write_error
= -1;
677 /*************************************************
678 * Flush SMTP out and check for error *
679 *************************************************/
681 /* This function isn't currently used within Exim (it detects errors when it
682 tries to read the next SMTP input), but is available for use in local_scan().
683 For non-TLS connections, it flushes the output and checks for errors. For
684 TLS-connections, it checks for a previously-detected TLS write error.
687 Returns: 0 for no error; -1 after an error
693 if (tls_in
.active
< 0 && fflush(smtp_out
) != 0) smtp_write_error
= -1;
694 return smtp_write_error
;
699 /*************************************************
700 * SMTP command read timeout *
701 *************************************************/
703 /* Signal handler for timing out incoming SMTP commands. This attempts to
706 Argument: signal number (SIGALRM)
711 command_timeout_handler(int sig
)
713 sig
= sig
; /* Keep picky compilers happy */
714 log_write(L_lost_incoming_connection
,
715 LOG_MAIN
, "SMTP command timeout on%s connection from %s",
716 (tls_in
.active
>= 0)? " TLS" : "",
717 host_and_ident(FALSE
));
718 if (smtp_batched_input
)
719 moan_smtp_batch(NULL
, "421 SMTP command timeout"); /* Does not return */
720 smtp_notquit_exit(US
"command-timeout", US
"421",
721 US
"%s: SMTP command timeout - closing connection", smtp_active_hostname
);
722 exim_exit(EXIT_FAILURE
);
727 /*************************************************
729 *************************************************/
731 /* Signal handler for handling SIGTERM. Again, try to finish tidily.
733 Argument: signal number (SIGTERM)
738 command_sigterm_handler(int sig
)
740 sig
= sig
; /* Keep picky compilers happy */
741 log_write(0, LOG_MAIN
, "%s closed after SIGTERM", smtp_get_connection_info());
742 if (smtp_batched_input
)
743 moan_smtp_batch(NULL
, "421 SIGTERM received"); /* Does not return */
744 smtp_notquit_exit(US
"signal-exit", US
"421",
745 US
"%s: Service not available - closing connection", smtp_active_hostname
);
746 exim_exit(EXIT_FAILURE
);
753 /*************************************************
754 * Restore socket timeout to previous value *
755 *************************************************/
756 /* If the previous value was successfully retrieved, restore
757 it before returning control to the non-proxy routines
759 Arguments: fd - File descriptor for input
760 get_ok - Successfully retrieved previous values
761 tvtmp - Time struct with previous values
762 vslen - Length of time struct
766 restore_socket_timeout(int fd
, int get_ok
, struct timeval
* tvtmp
, socklen_t vslen
)
769 (void) setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CS tvtmp
, vslen
);
772 /*************************************************
773 * Check if host is required proxy host *
774 *************************************************/
775 /* The function determines if inbound host will be a regular smtp host
776 or if it is configured that it must use Proxy Protocol.
783 check_proxy_protocol_host()
786 /* Cannot configure local connection as a proxy inbound */
787 if (sender_host_address
== NULL
) return proxy_session
;
789 rc
= verify_check_this_host(CUSS
&hosts_proxy
, NULL
, NULL
,
790 sender_host_address
, NULL
);
794 debug_printf("Detected proxy protocol configured host\n");
795 proxy_session
= TRUE
;
797 return proxy_session
;
801 /*************************************************
802 * Setup host for proxy protocol *
803 *************************************************/
804 /* The function configures the connection based on a header from the
805 inbound host to use Proxy Protocol. The specification is very exact
806 so exit with an error if do not find the exact required pieces. This
807 includes an incorrect number of spaces separating args.
810 Returns: Boolean success
814 setup_proxy_protocol_host()
826 struct { /* TCP/UDP over IPv4, len = 12 */
832 struct { /* TCP/UDP over IPv6, len = 36 */
833 uint8_t src_addr
[16];
834 uint8_t dst_addr
[16];
838 struct { /* AF_UNIX sockets, len = 216 */
839 uschar src_addr
[108];
840 uschar dst_addr
[108];
846 /* Temp variables used in PPv2 address:port parsing */
848 char tmpip
[INET_ADDRSTRLEN
];
849 struct sockaddr_in tmpaddr
;
850 char tmpip6
[INET6_ADDRSTRLEN
];
851 struct sockaddr_in6 tmpaddr6
;
855 int fd
= fileno(smtp_in
);
856 const char v2sig
[12] = "\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A";
857 uschar
*iptype
; /* To display debug info */
859 struct timeval tvtmp
;
860 socklen_t vslen
= sizeof(struct timeval
);
862 /* Save current socket timeout values */
863 get_ok
= getsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CS
&tvtmp
, &vslen
);
865 /* Proxy Protocol host must send header within a short time
866 (default 3 seconds) or it's considered invalid */
867 tv
.tv_sec
= PROXY_NEGOTIATION_TIMEOUT_SEC
;
868 tv
.tv_usec
= PROXY_NEGOTIATION_TIMEOUT_USEC
;
869 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CS
&tv
, sizeof(tv
)) < 0)
874 /* The inbound host was declared to be a Proxy Protocol host, so
875 don't do a PEEK into the data, actually slurp it up. */
876 ret
= recv(fd
, &hdr
, sizeof(hdr
), 0);
878 while (ret
== -1 && errno
== EINTR
);
884 memcmp(&hdr
.v2
, v2sig
, 12) == 0)
888 /* May 2014: haproxy combined the version and command into one byte to
889 allow two full bytes for the length field in order to proxy SSL
890 connections. SSL Proxy is not supported in this version of Exim, but
891 must still seperate values here. */
892 ver
= (hdr
.v2
.ver_cmd
& 0xf0) >> 4;
893 cmd
= (hdr
.v2
.ver_cmd
& 0x0f);
897 DEBUG(D_receive
) debug_printf("Invalid Proxy Protocol version: %d\n", ver
);
900 DEBUG(D_receive
) debug_printf("Detected PROXYv2 header\n");
901 /* The v2 header will always be 16 bytes per the spec. */
902 size
= 16 + hdr
.v2
.len
;
905 DEBUG(D_receive
) debug_printf("Truncated or too large PROXYv2 header (%d/%d)\n",
911 case 0x01: /* PROXY command */
914 case 0x11: /* TCPv4 address type */
916 tmpaddr
.sin_addr
.s_addr
= hdr
.v2
.addr
.ip4
.src_addr
;
917 inet_ntop(AF_INET
, &(tmpaddr
.sin_addr
), (char *)&tmpip
, sizeof(tmpip
));
918 if (!string_is_ip_address(US tmpip
,NULL
))
920 DEBUG(D_receive
) debug_printf("Invalid %s source IP\n", iptype
);
923 proxy_local_address
= sender_host_address
;
924 sender_host_address
= string_copy(US tmpip
);
925 tmpport
= ntohs(hdr
.v2
.addr
.ip4
.src_port
);
926 proxy_local_port
= sender_host_port
;
927 sender_host_port
= tmpport
;
928 /* Save dest ip/port */
929 tmpaddr
.sin_addr
.s_addr
= hdr
.v2
.addr
.ip4
.dst_addr
;
930 inet_ntop(AF_INET
, &(tmpaddr
.sin_addr
), (char *)&tmpip
, sizeof(tmpip
));
931 if (!string_is_ip_address(US tmpip
,NULL
))
933 DEBUG(D_receive
) debug_printf("Invalid %s dest port\n", iptype
);
936 proxy_external_address
= string_copy(US tmpip
);
937 tmpport
= ntohs(hdr
.v2
.addr
.ip4
.dst_port
);
938 proxy_external_port
= tmpport
;
940 case 0x21: /* TCPv6 address type */
942 memmove(tmpaddr6
.sin6_addr
.s6_addr
, hdr
.v2
.addr
.ip6
.src_addr
, 16);
943 inet_ntop(AF_INET6
, &(tmpaddr6
.sin6_addr
), (char *)&tmpip6
, sizeof(tmpip6
));
944 if (!string_is_ip_address(US tmpip6
,NULL
))
946 DEBUG(D_receive
) debug_printf("Invalid %s source IP\n", iptype
);
949 proxy_local_address
= sender_host_address
;
950 sender_host_address
= string_copy(US tmpip6
);
951 tmpport
= ntohs(hdr
.v2
.addr
.ip6
.src_port
);
952 proxy_local_port
= sender_host_port
;
953 sender_host_port
= tmpport
;
954 /* Save dest ip/port */
955 memmove(tmpaddr6
.sin6_addr
.s6_addr
, hdr
.v2
.addr
.ip6
.dst_addr
, 16);
956 inet_ntop(AF_INET6
, &(tmpaddr6
.sin6_addr
), (char *)&tmpip6
, sizeof(tmpip6
));
957 if (!string_is_ip_address(US tmpip6
,NULL
))
959 DEBUG(D_receive
) debug_printf("Invalid %s dest port\n", iptype
);
962 proxy_external_address
= string_copy(US tmpip6
);
963 tmpport
= ntohs(hdr
.v2
.addr
.ip6
.dst_port
);
964 proxy_external_port
= tmpport
;
968 debug_printf("Unsupported PROXYv2 connection type: 0x%02x\n",
972 /* Unsupported protocol, keep local connection address */
974 case 0x00: /* LOCAL command */
975 /* Keep local connection address for LOCAL */
979 debug_printf("Unsupported PROXYv2 command: 0x%x\n", cmd
);
984 memcmp(hdr
.v1
.line
, "PROXY", 5) == 0)
986 uschar
*p
= string_copy(hdr
.v1
.line
);
987 uschar
*end
= memchr(p
, '\r', ret
- 1);
988 uschar
*sp
; /* Utility variables follow */
992 if (!end
|| end
[1] != '\n')
994 DEBUG(D_receive
) debug_printf("Partial or invalid PROXY header\n");
997 *end
= '\0'; /* Terminate the string */
998 size
= end
+ 2 - hdr
.v1
.line
; /* Skip header + CRLF */
999 DEBUG(D_receive
) debug_printf("Detected PROXYv1 header\n");
1000 /* Step through the string looking for the required fields. Ensure
1001 strict adherance to required formatting, exit for any error. */
1003 if (!isspace(*(p
++)))
1005 DEBUG(D_receive
) debug_printf("Missing space after PROXY command\n");
1008 if (!Ustrncmp(p
, CCS
"TCP4", 4))
1010 else if (!Ustrncmp(p
,CCS
"TCP6", 4))
1012 else if (!Ustrncmp(p
,CCS
"UNKNOWN", 7))
1014 iptype
= US
"Unknown";
1019 DEBUG(D_receive
) debug_printf("Invalid TCP type\n");
1023 p
+= Ustrlen(iptype
);
1024 if (!isspace(*(p
++)))
1026 DEBUG(D_receive
) debug_printf("Missing space after TCP4/6 command\n");
1029 /* Find the end of the arg */
1030 if ((sp
= Ustrchr(p
, ' ')) == NULL
)
1033 debug_printf("Did not find proxied src %s\n", iptype
);
1037 if(!string_is_ip_address(p
,NULL
))
1040 debug_printf("Proxied src arg is not an %s address\n", iptype
);
1043 proxy_local_address
= sender_host_address
;
1044 sender_host_address
= p
;
1046 if ((sp
= Ustrchr(p
, ' ')) == NULL
)
1049 debug_printf("Did not find proxy dest %s\n", iptype
);
1053 if(!string_is_ip_address(p
,NULL
))
1056 debug_printf("Proxy dest arg is not an %s address\n", iptype
);
1059 proxy_external_address
= p
;
1061 if ((sp
= Ustrchr(p
, ' ')) == NULL
)
1063 DEBUG(D_receive
) debug_printf("Did not find proxied src port\n");
1067 tmp_port
= strtol(CCS p
,&endc
,10);
1068 if (*endc
|| tmp_port
== 0)
1071 debug_printf("Proxied src port '%s' not an integer\n", p
);
1074 proxy_local_port
= sender_host_port
;
1075 sender_host_port
= tmp_port
;
1077 if ((sp
= Ustrchr(p
, '\0')) == NULL
)
1079 DEBUG(D_receive
) debug_printf("Did not find proxy dest port\n");
1082 tmp_port
= strtol(CCS p
,&endc
,10);
1083 if (*endc
|| tmp_port
== 0)
1086 debug_printf("Proxy dest port '%s' not an integer\n", p
);
1089 proxy_external_port
= tmp_port
;
1090 /* Already checked for /r /n above. Good V1 header received. */
1095 /* Wrong protocol */
1096 DEBUG(D_receive
) debug_printf("Invalid proxy protocol version negotiation\n");
1101 restore_socket_timeout(fd
, get_ok
, &tvtmp
, vslen
);
1102 /* Don't flush any potential buffer contents. Any input should cause a
1103 synchronization failure */
1107 restore_socket_timeout(fd
, get_ok
, &tvtmp
, vslen
);
1109 debug_printf("Valid %s sender from Proxy Protocol header\n", iptype
);
1110 return proxy_session
;
1114 /*************************************************
1115 * Read one command line *
1116 *************************************************/
1118 /* Strictly, SMTP commands coming over the net are supposed to end with CRLF.
1119 There are sites that don't do this, and in any case internal SMTP probably
1120 should check only for LF. Consequently, we check here for LF only. The line
1121 ends up with [CR]LF removed from its end. If we get an overlong line, treat as
1122 an unknown command. The command is read into the global smtp_cmd_buffer so that
1123 it is available via $smtp_command.
1125 The character reading routine sets up a timeout for each block actually read
1126 from the input (which may contain more than one command). We set up a special
1127 signal handler that closes down the session on a timeout. Control does not
1128 return when it runs.
1131 check_sync if TRUE, check synchronization rules if global option is TRUE
1133 Returns: a code identifying the command (enumerated above)
1137 smtp_read_command(BOOL check_sync
)
1142 BOOL hadnull
= FALSE
;
1144 os_non_restarting_signal(SIGALRM
, command_timeout_handler
);
1146 while ((c
= (receive_getc
)()) != '\n' && c
!= EOF
)
1148 if (ptr
>= smtp_cmd_buffer_size
)
1150 os_non_restarting_signal(SIGALRM
, sigalrm_handler
);
1158 smtp_cmd_buffer
[ptr
++] = c
;
1161 receive_linecount
++; /* For BSMTP errors */
1162 os_non_restarting_signal(SIGALRM
, sigalrm_handler
);
1164 /* If hit end of file, return pseudo EOF command. Whether we have a
1165 part-line already read doesn't matter, since this is an error state. */
1167 if (c
== EOF
) return EOF_CMD
;
1169 /* Remove any CR and white space at the end of the line, and terminate the
1172 while (ptr
> 0 && isspace(smtp_cmd_buffer
[ptr
-1])) ptr
--;
1173 smtp_cmd_buffer
[ptr
] = 0;
1175 DEBUG(D_receive
) debug_printf("SMTP<< %s\n", smtp_cmd_buffer
);
1177 /* NULLs are not allowed in SMTP commands */
1179 if (hadnull
) return BADCHAR_CMD
;
1181 /* Scan command list and return identity, having set the data pointer
1182 to the start of the actual data characters. Check for SMTP synchronization
1185 for (p
= cmd_list
; p
< cmd_list_end
; p
++)
1187 #ifdef SUPPORT_PROXY
1188 /* Only allow QUIT command if Proxy Protocol parsing failed */
1189 if (proxy_session
&& proxy_session_failed
)
1191 if (p
->cmd
!= QUIT_CMD
)
1196 && strncmpic(smtp_cmd_buffer
, US p
->name
, p
->len
) == 0
1197 && ( smtp_cmd_buffer
[p
->len
-1] == ':' /* "mail from:" or "rcpt to:" */
1198 || smtp_cmd_buffer
[p
->len
] == 0
1199 || smtp_cmd_buffer
[p
->len
] == ' '
1202 if (smtp_inptr
< smtp_inend
&& /* Outstanding input */
1203 p
->cmd
< sync_cmd_limit
&& /* Command should sync */
1204 check_sync
&& /* Local flag set */
1205 smtp_enforce_sync
&& /* Global flag set */
1206 sender_host_address
!= NULL
&& /* Not local input */
1207 !sender_host_notsocket
) /* Really is a socket */
1210 /* The variables $smtp_command and $smtp_command_argument point into the
1211 unmodified input buffer. A copy of the latter is taken for actual
1212 processing, so that it can be chopped up into separate parts if necessary,
1213 for example, when processing a MAIL command options such as SIZE that can
1214 follow the sender address. */
1216 smtp_cmd_argument
= smtp_cmd_buffer
+ p
->len
;
1217 while (isspace(*smtp_cmd_argument
)) smtp_cmd_argument
++;
1218 Ustrcpy(smtp_data_buffer
, smtp_cmd_argument
);
1219 smtp_cmd_data
= smtp_data_buffer
;
1221 /* Count non-mail commands from those hosts that are controlled in this
1222 way. The default is all hosts. We don't waste effort checking the list
1223 until we get a non-mail command, but then cache the result to save checking
1224 again. If there's a DEFER while checking the host, assume it's in the list.
1226 Note that one instance of RSET, EHLO/HELO, and STARTTLS is allowed at the
1227 start of each incoming message by fiddling with the value in the table. */
1229 if (!p
->is_mail_cmd
)
1231 if (count_nonmail
== TRUE_UNSET
) count_nonmail
=
1232 verify_check_host(&smtp_accept_max_nonmail_hosts
) != FAIL
;
1233 if (count_nonmail
&& ++nonmail_command_count
> smtp_accept_max_nonmail
)
1234 return TOO_MANY_NONMAIL_CMD
;
1237 /* If there is data for a command that does not expect it, generate the
1240 return (p
->has_arg
|| *smtp_cmd_data
== 0)? p
->cmd
: BADARG_CMD
;
1244 #ifdef SUPPORT_PROXY
1245 /* Only allow QUIT command if Proxy Protocol parsing failed */
1246 if (proxy_session
&& proxy_session_failed
)
1247 return PROXY_FAIL_IGNORE_CMD
;
1250 /* Enforce synchronization for unknown commands */
1252 if (smtp_inptr
< smtp_inend
&& /* Outstanding input */
1253 check_sync
&& /* Local flag set */
1254 smtp_enforce_sync
&& /* Global flag set */
1255 sender_host_address
!= NULL
&& /* Not local input */
1256 !sender_host_notsocket
) /* Really is a socket */
1264 /*************************************************
1265 * Recheck synchronization *
1266 *************************************************/
1268 /* Synchronization checks can never be perfect because a packet may be on its
1269 way but not arrived when the check is done. Such checks can in any case only be
1270 done when TLS is not in use. Normally, the checks happen when commands are
1271 read: Exim ensures that there is no more input in the input buffer. In normal
1272 cases, the response to the command will be fast, and there is no further check.
1274 However, for some commands an ACL is run, and that can include delays. In those
1275 cases, it is useful to do another check on the input just before sending the
1276 response. This also applies at the start of a connection. This function does
1277 that check by means of the select() function, as long as the facility is not
1278 disabled or inappropriate. A failure of select() is ignored.
1280 When there is unwanted input, we read it so that it appears in the log of the
1284 Returns: TRUE if all is well; FALSE if there is input pending
1292 struct timeval tzero
;
1294 if (!smtp_enforce_sync
|| sender_host_address
== NULL
||
1295 sender_host_notsocket
|| tls_in
.active
>= 0)
1298 fd
= fileno(smtp_in
);
1303 rc
= select(fd
+ 1, (SELECT_ARG2_TYPE
*)&fds
, NULL
, NULL
, &tzero
);
1305 if (rc
<= 0) return TRUE
; /* Not ready to read */
1307 if (rc
< 0) return TRUE
; /* End of file or error */
1310 rc
= smtp_inend
- smtp_inptr
;
1311 if (rc
> 150) rc
= 150;
1318 /*************************************************
1319 * Forced closedown of call *
1320 *************************************************/
1322 /* This function is called from log.c when Exim is dying because of a serious
1323 disaster, and also from some other places. If an incoming non-batched SMTP
1324 channel is open, it swallows the rest of the incoming message if in the DATA
1325 phase, sends the reply string, and gives an error to all subsequent commands
1326 except QUIT. The existence of an SMTP call is detected by the non-NULLness of
1330 message SMTP reply string to send, excluding the code
1336 smtp_closedown(uschar
*message
)
1338 if (smtp_in
== NULL
|| smtp_batched_input
) return;
1339 receive_swallow_smtp();
1340 smtp_printf("421 %s\r\n", message
);
1342 for (;;) switch(smtp_read_command(FALSE
))
1348 smtp_printf("221 %s closing connection\r\n", smtp_active_hostname
);
1353 smtp_printf("250 Reset OK\r\n");
1357 smtp_printf("421 %s\r\n", message
);
1365 /*************************************************
1366 * Set up connection info for logging *
1367 *************************************************/
1369 /* This function is called when logging information about an SMTP connection.
1370 It sets up appropriate source information, depending on the type of connection.
1371 If sender_fullhost is NULL, we are at a very early stage of the connection;
1372 just use the IP address.
1375 Returns: a string describing the connection
1379 smtp_get_connection_info(void)
1381 uschar
*hostname
= (sender_fullhost
== NULL
)?
1382 sender_host_address
: sender_fullhost
;
1385 return string_sprintf("SMTP connection from %s", hostname
);
1387 if (sender_host_unknown
|| sender_host_notsocket
)
1388 return string_sprintf("SMTP connection from %s", sender_ident
);
1391 return string_sprintf("SMTP connection from %s (via inetd)", hostname
);
1393 if (LOGGING(incoming_interface
) && interface_address
!= NULL
)
1394 return string_sprintf("SMTP connection from %s I=[%s]:%d", hostname
,
1395 interface_address
, interface_port
);
1397 return string_sprintf("SMTP connection from %s", hostname
);
1403 /* Append TLS-related information to a log line
1406 s String under construction: allocated string to extend, or NULL
1407 sizep Pointer to current allocation size (update on return), or NULL
1408 ptrp Pointer to index for new entries in string (update on return), or NULL
1410 Returns: Allocated string or NULL
1413 s_tlslog(uschar
* s
, int * sizep
, int * ptrp
)
1415 int size
= sizep
? *sizep
: 0;
1416 int ptr
= ptrp
? *ptrp
: 0;
1418 if (LOGGING(tls_cipher
) && tls_in
.cipher
!= NULL
)
1419 s
= string_append(s
, &size
, &ptr
, 2, US
" X=", tls_in
.cipher
);
1420 if (LOGGING(tls_certificate_verified
) && tls_in
.cipher
!= NULL
)
1421 s
= string_append(s
, &size
, &ptr
, 2, US
" CV=",
1422 tls_in
.certificate_verified
? "yes":"no");
1423 if (LOGGING(tls_peerdn
) && tls_in
.peerdn
!= NULL
)
1424 s
= string_append(s
, &size
, &ptr
, 3, US
" DN=\"",
1425 string_printing(tls_in
.peerdn
), US
"\"");
1426 if (LOGGING(tls_sni
) && tls_in
.sni
!= NULL
)
1427 s
= string_append(s
, &size
, &ptr
, 3, US
" SNI=\"",
1428 string_printing(tls_in
.sni
), US
"\"");
1433 if (sizep
) *sizep
= size
;
1434 if (ptrp
) *ptrp
= ptr
;
1440 /*************************************************
1441 * Log lack of MAIL if so configured *
1442 *************************************************/
1444 /* This function is called when an SMTP session ends. If the log selector
1445 smtp_no_mail is set, write a log line giving some details of what has happened
1446 in the SMTP session.
1453 smtp_log_no_mail(void)
1458 if (smtp_mailcmd_count
> 0 || !LOGGING(smtp_no_mail
))
1464 if (sender_host_authenticated
!= NULL
)
1466 s
= string_append(s
, &size
, &ptr
, 2, US
" A=", sender_host_authenticated
);
1467 if (authenticated_id
!= NULL
)
1468 s
= string_append(s
, &size
, &ptr
, 2, US
":", authenticated_id
);
1472 s
= s_tlslog(s
, &size
, &ptr
);
1475 sep
= (smtp_connection_had
[SMTP_HBUFF_SIZE
-1] != SCH_NONE
)?
1476 US
" C=..." : US
" C=";
1477 for (i
= smtp_ch_index
; i
< SMTP_HBUFF_SIZE
; i
++)
1479 if (smtp_connection_had
[i
] != SCH_NONE
)
1481 s
= string_append(s
, &size
, &ptr
, 2, sep
,
1482 smtp_names
[smtp_connection_had
[i
]]);
1487 for (i
= 0; i
< smtp_ch_index
; i
++)
1489 s
= string_append(s
, &size
, &ptr
, 2, sep
, smtp_names
[smtp_connection_had
[i
]]);
1493 if (s
!= NULL
) s
[ptr
] = 0; else s
= US
"";
1494 log_write(0, LOG_MAIN
, "no MAIL in SMTP connection from %s D=%s%s",
1495 host_and_ident(FALSE
),
1496 readconf_printtime( (int) ((long)time(NULL
) - (long)smtp_connection_start
)),
1502 /*************************************************
1503 * Check HELO line and set sender_helo_name *
1504 *************************************************/
1506 /* Check the format of a HELO line. The data for HELO/EHLO is supposed to be
1507 the domain name of the sending host, or an ip literal in square brackets. The
1508 arrgument is placed in sender_helo_name, which is in malloc store, because it
1509 must persist over multiple incoming messages. If helo_accept_junk is set, this
1510 host is permitted to send any old junk (needed for some broken hosts).
1511 Otherwise, helo_allow_chars can be used for rogue characters in general
1512 (typically people want to let in underscores).
1515 s the data portion of the line (already past any white space)
1517 Returns: TRUE or FALSE
1521 check_helo(uschar
*s
)
1524 uschar
*end
= s
+ Ustrlen(s
);
1525 BOOL yield
= helo_accept_junk
;
1527 /* Discard any previous helo name */
1529 if (sender_helo_name
!= NULL
)
1531 store_free(sender_helo_name
);
1532 sender_helo_name
= NULL
;
1535 /* Skip tests if junk is permitted. */
1539 /* Allow the new standard form for IPv6 address literals, namely,
1540 [IPv6:....], and because someone is bound to use it, allow an equivalent
1541 IPv4 form. Allow plain addresses as well. */
1548 if (strncmpic(s
, US
"[IPv6:", 6) == 0)
1549 yield
= (string_is_ip_address(s
+6, NULL
) == 6);
1550 else if (strncmpic(s
, US
"[IPv4:", 6) == 0)
1551 yield
= (string_is_ip_address(s
+6, NULL
) == 4);
1553 yield
= (string_is_ip_address(s
+1, NULL
) != 0);
1558 /* Non-literals must be alpha, dot, hyphen, plus any non-valid chars
1559 that have been configured (usually underscore - sigh). */
1566 if (!isalnum(*s
) && *s
!= '.' && *s
!= '-' &&
1567 Ustrchr(helo_allow_chars
, *s
) == NULL
)
1577 /* Save argument if OK */
1579 if (yield
) sender_helo_name
= string_copy_malloc(start
);
1587 /*************************************************
1588 * Extract SMTP command option *
1589 *************************************************/
1591 /* This function picks the next option setting off the end of smtp_cmd_data. It
1592 is called for MAIL FROM and RCPT TO commands, to pick off the optional ESMTP
1593 things that can appear there.
1596 name point this at the name
1597 value point this at the data string
1599 Returns: TRUE if found an option
1603 extract_option(uschar
**name
, uschar
**value
)
1606 uschar
*v
= smtp_cmd_data
+ Ustrlen(smtp_cmd_data
) - 1;
1607 while (isspace(*v
)) v
--;
1609 while (v
> smtp_cmd_data
&& *v
!= '=' && !isspace(*v
)) v
--;
1614 while(isalpha(n
[-1])) n
--;
1615 /* RFC says SP, but TAB seen in wild and other major MTAs accept it */
1616 if (!isspace(n
[-1])) return FALSE
;
1622 if (v
== smtp_cmd_data
) return FALSE
;
1634 /*************************************************
1635 * Reset for new message *
1636 *************************************************/
1638 /* This function is called whenever the SMTP session is reset from
1639 within either of the setup functions.
1641 Argument: the stacking pool storage reset point
1646 smtp_reset(void *reset_point
)
1648 store_reset(reset_point
);
1649 recipients_list
= NULL
;
1650 rcpt_count
= rcpt_defer_count
= rcpt_fail_count
=
1651 raw_recipients_count
= recipients_count
= recipients_list_max
= 0;
1652 cancel_cutthrough_connection("smtp reset");
1653 message_linecount
= 0;
1655 acl_added_headers
= NULL
;
1656 acl_removed_headers
= NULL
;
1657 queue_only_policy
= FALSE
;
1658 rcpt_smtp_response
= NULL
;
1659 rcpt_smtp_response_same
= TRUE
;
1660 rcpt_in_progress
= FALSE
;
1661 deliver_freeze
= FALSE
; /* Can be set by ACL */
1662 freeze_tell
= freeze_tell_config
; /* Can be set by ACL */
1663 fake_response
= OK
; /* Can be set by ACL */
1664 #ifdef WITH_CONTENT_SCAN
1665 no_mbox_unspool
= FALSE
; /* Can be set by ACL */
1667 submission_mode
= FALSE
; /* Can be set by ACL */
1668 suppress_local_fixups
= suppress_local_fixups_default
; /* Can be set by ACL */
1669 active_local_from_check
= local_from_check
; /* Can be set by ACL */
1670 active_local_sender_retain
= local_sender_retain
; /* Can be set by ACL */
1671 sender_address
= NULL
;
1672 submission_name
= NULL
; /* Can be set by ACL */
1673 raw_sender
= NULL
; /* After SMTP rewrite, before qualifying */
1674 sender_address_unrewritten
= NULL
; /* Set only after verify rewrite */
1675 sender_verified_list
= NULL
; /* No senders verified */
1676 memset(sender_address_cache
, 0, sizeof(sender_address_cache
));
1677 memset(sender_domain_cache
, 0, sizeof(sender_domain_cache
));
1679 authenticated_sender
= NULL
;
1680 #ifdef EXPERIMENTAL_BRIGHTMAIL
1682 bmi_verdicts
= NULL
;
1684 #ifndef DISABLE_DKIM
1685 dkim_signers
= NULL
;
1686 dkim_disable_verify
= FALSE
;
1687 dkim_collect_input
= FALSE
;
1691 #ifndef DISABLE_PRDR
1692 prdr_requested
= FALSE
;
1694 #ifdef EXPERIMENTAL_SPF
1695 spf_header_comment
= NULL
;
1696 spf_received
= NULL
;
1698 spf_smtp_comment
= NULL
;
1701 message_smtputf8
= FALSE
;
1703 body_linecount
= body_zerocount
= 0;
1705 sender_rate
= sender_rate_limit
= sender_rate_period
= NULL
;
1706 ratelimiters_mail
= NULL
; /* Updated by ratelimit ACL condition */
1707 /* Note that ratelimiters_conn persists across resets. */
1709 /* Reset message ACL variables */
1713 /* The message body variables use malloc store. They may be set if this is
1714 not the first message in an SMTP session and the previous message caused them
1715 to be referenced in an ACL. */
1717 if (message_body
!= NULL
)
1719 store_free(message_body
);
1720 message_body
= NULL
;
1723 if (message_body_end
!= NULL
)
1725 store_free(message_body_end
);
1726 message_body_end
= NULL
;
1729 /* Warning log messages are also saved in malloc store. They are saved to avoid
1730 repetition in the same message, but it seems right to repeat them for different
1733 while (acl_warn_logged
!= NULL
)
1735 string_item
*this = acl_warn_logged
;
1736 acl_warn_logged
= acl_warn_logged
->next
;
1745 /*************************************************
1746 * Initialize for incoming batched SMTP message *
1747 *************************************************/
1749 /* This function is called from smtp_setup_msg() in the case when
1750 smtp_batched_input is true. This happens when -bS is used to pass a whole batch
1751 of messages in one file with SMTP commands between them. All errors must be
1752 reported by sending a message, and only MAIL FROM, RCPT TO, and DATA are
1753 relevant. After an error on a sender, or an invalid recipient, the remainder
1754 of the message is skipped. The value of received_protocol is already set.
1757 Returns: > 0 message successfully started (reached DATA)
1758 = 0 QUIT read or end of file reached
1759 < 0 should not occur
1763 smtp_setup_batch_msg(void)
1766 void *reset_point
= store_get(0);
1768 /* Save the line count at the start of each transaction - single commands
1769 like HELO and RSET count as whole transactions. */
1771 bsmtp_transaction_linecount
= receive_linecount
;
1773 if ((receive_feof
)()) return 0; /* Treat EOF as QUIT */
1775 smtp_reset(reset_point
); /* Reset for start of message */
1777 /* Deal with SMTP commands. This loop is exited by setting done to a POSITIVE
1778 value. The values are 2 larger than the required yield of the function. */
1783 uschar
*recipient
= NULL
;
1784 int start
, end
, sender_domain
, recipient_domain
;
1786 switch(smtp_read_command(FALSE
))
1788 /* The HELO/EHLO commands set sender_address_helo if they have
1789 valid data; otherwise they are ignored, except that they do
1790 a reset of the state. */
1795 check_helo(smtp_cmd_data
);
1799 smtp_reset(reset_point
);
1800 bsmtp_transaction_linecount
= receive_linecount
;
1804 /* The MAIL FROM command requires an address as an operand. All we
1805 do here is to parse it for syntactic correctness. The form "<>" is
1806 a special case which converts into an empty string. The start/end
1807 pointers in the original are not used further for this address, as
1808 it is the canonical extracted address which is all that is kept. */
1811 smtp_mailcmd_count
++; /* Count for no-mail log */
1812 if (sender_address
!= NULL
)
1813 /* The function moan_smtp_batch() does not return. */
1814 moan_smtp_batch(smtp_cmd_buffer
, "503 Sender already given");
1816 if (smtp_cmd_data
[0] == 0)
1817 /* The function moan_smtp_batch() does not return. */
1818 moan_smtp_batch(smtp_cmd_buffer
, "501 MAIL FROM must have an address operand");
1820 /* Reset to start of message */
1822 smtp_reset(reset_point
);
1824 /* Apply SMTP rewrite */
1826 raw_sender
= ((rewrite_existflags
& rewrite_smtp
) != 0)?
1827 rewrite_one(smtp_cmd_data
, rewrite_smtp
|rewrite_smtp_sender
, NULL
, FALSE
,
1828 US
"", global_rewrite_rules
) : smtp_cmd_data
;
1830 /* Extract the address; the TRUE flag allows <> as valid */
1833 parse_extract_address(raw_sender
, &errmess
, &start
, &end
, &sender_domain
,
1836 if (raw_sender
== NULL
)
1837 /* The function moan_smtp_batch() does not return. */
1838 moan_smtp_batch(smtp_cmd_buffer
, "501 %s", errmess
);
1840 sender_address
= string_copy(raw_sender
);
1842 /* Qualify unqualified sender addresses if permitted to do so. */
1844 if (sender_domain
== 0 && sender_address
[0] != 0 && sender_address
[0] != '@')
1846 if (allow_unqualified_sender
)
1848 sender_address
= rewrite_address_qualify(sender_address
, FALSE
);
1849 DEBUG(D_receive
) debug_printf("unqualified address %s accepted "
1850 "and rewritten\n", raw_sender
);
1852 /* The function moan_smtp_batch() does not return. */
1853 else moan_smtp_batch(smtp_cmd_buffer
, "501 sender address must contain "
1859 /* The RCPT TO command requires an address as an operand. All we do
1860 here is to parse it for syntactic correctness. There may be any number
1861 of RCPT TO commands, specifying multiple senders. We build them all into
1862 a data structure that is in argc/argv format. The start/end values
1863 given by parse_extract_address are not used, as we keep only the
1864 extracted address. */
1867 if (sender_address
== NULL
)
1868 /* The function moan_smtp_batch() does not return. */
1869 moan_smtp_batch(smtp_cmd_buffer
, "503 No sender yet given");
1871 if (smtp_cmd_data
[0] == 0)
1872 /* The function moan_smtp_batch() does not return. */
1873 moan_smtp_batch(smtp_cmd_buffer
, "501 RCPT TO must have an address operand");
1875 /* Check maximum number allowed */
1877 if (recipients_max
> 0 && recipients_count
+ 1 > recipients_max
)
1878 /* The function moan_smtp_batch() does not return. */
1879 moan_smtp_batch(smtp_cmd_buffer
, "%s too many recipients",
1880 recipients_max_reject
? "552": "452");
1882 /* Apply SMTP rewrite, then extract address. Don't allow "<>" as a
1883 recipient address */
1885 recipient
= rewrite_existflags
& rewrite_smtp
1886 ? rewrite_one(smtp_cmd_data
, rewrite_smtp
, NULL
, FALSE
, US
"",
1887 global_rewrite_rules
)
1890 recipient
= parse_extract_address(recipient
, &errmess
, &start
, &end
,
1891 &recipient_domain
, FALSE
);
1894 /* The function moan_smtp_batch() does not return. */
1895 moan_smtp_batch(smtp_cmd_buffer
, "501 %s", errmess
);
1897 /* If the recipient address is unqualified, qualify it if permitted. Then
1898 add it to the list of recipients. */
1900 if (recipient_domain
== 0)
1902 if (allow_unqualified_recipient
)
1904 DEBUG(D_receive
) debug_printf("unqualified address %s accepted\n",
1906 recipient
= rewrite_address_qualify(recipient
, TRUE
);
1908 /* The function moan_smtp_batch() does not return. */
1909 else moan_smtp_batch(smtp_cmd_buffer
, "501 recipient address must contain "
1912 receive_add_recipient(recipient
, -1);
1916 /* The DATA command is legal only if it follows successful MAIL FROM
1917 and RCPT TO commands. This function is complete when a valid DATA
1918 command is encountered. */
1921 if (sender_address
== NULL
|| recipients_count
<= 0)
1923 /* The function moan_smtp_batch() does not return. */
1924 if (sender_address
== NULL
)
1925 moan_smtp_batch(smtp_cmd_buffer
,
1926 "503 MAIL FROM:<sender> command must precede DATA");
1928 moan_smtp_batch(smtp_cmd_buffer
,
1929 "503 RCPT TO:<recipient> must precede DATA");
1933 done
= 3; /* DATA successfully achieved */
1934 message_ended
= END_NOTENDED
; /* Indicate in middle of message */
1939 /* The VRFY, EXPN, HELP, ETRN, and NOOP commands are ignored. */
1946 bsmtp_transaction_linecount
= receive_linecount
;
1957 /* The function moan_smtp_batch() does not return. */
1958 moan_smtp_batch(smtp_cmd_buffer
, "501 Unexpected argument data");
1963 /* The function moan_smtp_batch() does not return. */
1964 moan_smtp_batch(smtp_cmd_buffer
, "501 Unexpected NULL in SMTP command");
1969 /* The function moan_smtp_batch() does not return. */
1970 moan_smtp_batch(smtp_cmd_buffer
, "500 Command unrecognized");
1975 return done
- 2; /* Convert yield values */
1981 /*************************************************
1982 * Start an SMTP session *
1983 *************************************************/
1985 /* This function is called at the start of an SMTP session. Thereafter,
1986 smtp_setup_msg() is called to initiate each separate message. This
1987 function does host-specific testing, and outputs the banner line.
1990 Returns: FALSE if the session can not continue; something has
1991 gone wrong, or the connection to the host is blocked
1995 smtp_start_session(void)
1999 uschar
*user_msg
, *log_msg
;
2003 smtp_connection_start
= time(NULL
);
2004 for (smtp_ch_index
= 0; smtp_ch_index
< SMTP_HBUFF_SIZE
; smtp_ch_index
++)
2005 smtp_connection_had
[smtp_ch_index
] = SCH_NONE
;
2008 /* Default values for certain variables */
2010 helo_seen
= esmtp
= helo_accept_junk
= FALSE
;
2011 smtp_mailcmd_count
= 0;
2012 count_nonmail
= TRUE_UNSET
;
2013 synprot_error_count
= unknown_command_count
= nonmail_command_count
= 0;
2014 smtp_delay_mail
= smtp_rlm_base
;
2015 auth_advertised
= FALSE
;
2016 pipelining_advertised
= FALSE
;
2017 pipelining_enable
= TRUE
;
2018 sync_cmd_limit
= NON_SYNC_CMD_NON_PIPELINING
;
2019 smtp_exit_function_called
= FALSE
; /* For avoiding loop in not-quit exit */
2021 /* If receiving by -bs from a trusted user, or testing with -bh, we allow
2022 authentication settings from -oMaa to remain in force. */
2024 if (!host_checking
&& !sender_host_notsocket
) sender_host_authenticated
= NULL
;
2025 authenticated_by
= NULL
;
2028 tls_in
.cipher
= tls_in
.peerdn
= NULL
;
2029 tls_in
.ourcert
= tls_in
.peercert
= NULL
;
2031 tls_in
.ocsp
= OCSP_NOT_REQ
;
2032 tls_advertised
= FALSE
;
2034 dsn_advertised
= FALSE
;
2036 smtputf8_advertised
= FALSE
;
2039 /* Reset ACL connection variables */
2043 /* Allow for trailing 0 in the command and data buffers. */
2045 if (!(smtp_cmd_buffer
= US
malloc(2*smtp_cmd_buffer_size
+ 2)))
2046 log_write(0, LOG_MAIN
|LOG_PANIC_DIE
,
2047 "malloc() failed for SMTP command buffer");
2049 smtp_cmd_buffer
[0] = 0;
2050 smtp_data_buffer
= smtp_cmd_buffer
+ smtp_cmd_buffer_size
+ 1;
2052 /* For batched input, the protocol setting can be overridden from the
2053 command line by a trusted caller. */
2055 if (smtp_batched_input
)
2057 if (!received_protocol
) received_protocol
= US
"local-bsmtp";
2060 /* For non-batched SMTP input, the protocol setting is forced here. It will be
2061 reset later if any of EHLO/AUTH/STARTTLS are received. */
2065 (sender_host_address
? protocols
: protocols_local
) [pnormal
];
2067 /* Set up the buffer for inputting using direct read() calls, and arrange to
2068 call the local functions instead of the standard C ones. */
2070 if (!(smtp_inbuffer
= (uschar
*)malloc(in_buffer_size
)))
2071 log_write(0, LOG_MAIN
|LOG_PANIC_DIE
, "malloc() failed for SMTP input buffer");
2073 receive_getc
= smtp_getc
;
2074 receive_get_cache
= smtp_get_cache
;
2075 receive_ungetc
= smtp_ungetc
;
2076 receive_feof
= smtp_feof
;
2077 receive_ferror
= smtp_ferror
;
2078 receive_smtp_buffered
= smtp_buffered
;
2079 smtp_inptr
= smtp_inend
= smtp_inbuffer
;
2080 smtp_had_eof
= smtp_had_error
= 0;
2082 /* Set up the message size limit; this may be host-specific */
2084 thismessage_size_limit
= expand_string_integer(message_size_limit
, TRUE
);
2085 if (expand_string_message
!= NULL
)
2087 if (thismessage_size_limit
== -1)
2088 log_write(0, LOG_MAIN
|LOG_PANIC
, "unable to expand message_size_limit: "
2089 "%s", expand_string_message
);
2091 log_write(0, LOG_MAIN
|LOG_PANIC
, "invalid message_size_limit: "
2092 "%s", expand_string_message
);
2093 smtp_closedown(US
"Temporary local problem - please try later");
2097 /* When a message is input locally via the -bs or -bS options, sender_host_
2098 unknown is set unless -oMa was used to force an IP address, in which case it
2099 is checked like a real remote connection. When -bs is used from inetd, this
2100 flag is not set, causing the sending host to be checked. The code that deals
2101 with IP source routing (if configured) is never required for -bs or -bS and
2102 the flag sender_host_notsocket is used to suppress it.
2104 If smtp_accept_max and smtp_accept_reserve are set, keep some connections in
2105 reserve for certain hosts and/or networks. */
2107 if (!sender_host_unknown
)
2110 BOOL reserved_host
= FALSE
;
2112 /* Look up IP options (source routing info) on the socket if this is not an
2113 -oMa "host", and if any are found, log them and drop the connection.
2115 Linux (and others now, see below) is different to everyone else, so there
2116 has to be some conditional compilation here. Versions of Linux before 2.1.15
2117 used a structure whose name was "options". Somebody finally realized that
2118 this name was silly, and it got changed to "ip_options". I use the
2119 newer name here, but there is a fudge in the script that sets up os.h
2120 to define a macro in older Linux systems.
2122 Sigh. Linux is a fast-moving target. Another generation of Linux uses
2123 glibc 2, which has chosen ip_opts for the structure name. This is now
2124 really a glibc thing rather than a Linux thing, so the condition name
2125 has been changed to reflect this. It is relevant also to GNU/Hurd.
2127 Mac OS 10.x (Darwin) is like the later glibc versions, but without the
2128 setting of the __GLIBC__ macro, so we can't detect it automatically. There's
2129 a special macro defined in the os.h file.
2131 Some DGUX versions on older hardware appear not to support IP options at
2132 all, so there is now a general macro which can be set to cut out this
2135 How to do this properly in IPv6 is not yet known. */
2137 #if !HAVE_IPV6 && !defined(NO_IP_OPTIONS)
2139 #ifdef GLIBC_IP_OPTIONS
2140 #if (!defined __GLIBC__) || (__GLIBC__ < 2)
2145 #elif defined DARWIN_IP_OPTIONS
2151 if (!host_checking
&& !sender_host_notsocket
)
2154 EXIM_SOCKLEN_T optlen
= sizeof(struct ip_options
) + MAX_IPOPTLEN
;
2155 struct ip_options
*ipopt
= store_get(optlen
);
2157 struct ip_opts ipoptblock
;
2158 struct ip_opts
*ipopt
= &ipoptblock
;
2159 EXIM_SOCKLEN_T optlen
= sizeof(ipoptblock
);
2161 struct ipoption ipoptblock
;
2162 struct ipoption
*ipopt
= &ipoptblock
;
2163 EXIM_SOCKLEN_T optlen
= sizeof(ipoptblock
);
2166 /* Occasional genuine failures of getsockopt() have been seen - for
2167 example, "reset by peer". Therefore, just log and give up on this
2168 call, unless the error is ENOPROTOOPT. This error is given by systems
2169 that have the interfaces but not the mechanism - e.g. GNU/Hurd at the time
2170 of writing. So for that error, carry on - we just can't do an IP options
2173 DEBUG(D_receive
) debug_printf("checking for IP options\n");
2175 if (getsockopt(fileno(smtp_out
), IPPROTO_IP
, IP_OPTIONS
, (uschar
*)(ipopt
),
2178 if (errno
!= ENOPROTOOPT
)
2180 log_write(0, LOG_MAIN
, "getsockopt() failed from %s: %s",
2181 host_and_ident(FALSE
), strerror(errno
));
2182 smtp_printf("451 SMTP service not available\r\n");
2187 /* Deal with any IP options that are set. On the systems I have looked at,
2188 the value of MAX_IPOPTLEN has been 40, meaning that there should never be
2189 more logging data than will fit in big_buffer. Nevertheless, after somebody
2190 questioned this code, I've added in some paranoid checking. */
2192 else if (optlen
> 0)
2194 uschar
*p
= big_buffer
;
2195 uschar
*pend
= big_buffer
+ big_buffer_size
;
2196 uschar
*opt
, *adptr
;
2198 struct in_addr addr
;
2201 uschar
*optstart
= (uschar
*)(ipopt
->__data
);
2203 uschar
*optstart
= (uschar
*)(ipopt
->ip_opts
);
2205 uschar
*optstart
= (uschar
*)(ipopt
->ipopt_list
);
2208 DEBUG(D_receive
) debug_printf("IP options exist\n");
2210 Ustrcpy(p
, "IP options on incoming call:");
2213 for (opt
= optstart
; opt
!= NULL
&&
2214 opt
< (uschar
*)(ipopt
) + optlen
;)
2228 if (!string_format(p
, pend
-p
, " %s [@%s",
2229 (*opt
== IPOPT_SSRR
)? "SSRR" : "LSRR",
2231 inet_ntoa(*((struct in_addr
*)(&(ipopt
->faddr
))))))
2233 inet_ntoa(ipopt
->ip_dst
)))
2235 inet_ntoa(ipopt
->ipopt_dst
)))
2243 optcount
= (opt
[1] - 3) / sizeof(struct in_addr
);
2245 while (optcount
-- > 0)
2247 memcpy(&addr
, adptr
, sizeof(addr
));
2248 if (!string_format(p
, pend
- p
- 1, "%s%s",
2249 (optcount
== 0)? ":" : "@", inet_ntoa(addr
)))
2255 adptr
+= sizeof(struct in_addr
);
2264 if (pend
- p
< 4 + 3*opt
[1]) { opt
= NULL
; break; }
2267 for (i
= 0; i
< opt
[1]; i
++)
2269 sprintf(CS p
, "%2.2x ", opt
[i
]);
2280 log_write(0, LOG_MAIN
, "%s", big_buffer
);
2282 /* Refuse any call with IP options. This is what tcpwrappers 7.5 does. */
2284 log_write(0, LOG_MAIN
|LOG_REJECT
,
2285 "connection from %s refused (IP options)", host_and_ident(FALSE
));
2287 smtp_printf("554 SMTP service not available\r\n");
2291 /* Length of options = 0 => there are no options */
2293 else DEBUG(D_receive
) debug_printf("no IP options found\n");
2295 #endif /* HAVE_IPV6 && !defined(NO_IP_OPTIONS) */
2297 /* Set keep-alive in socket options. The option is on by default. This
2298 setting is an attempt to get rid of some hanging connections that stick in
2299 read() when the remote end (usually a dialup) goes away. */
2301 if (smtp_accept_keepalive
&& !sender_host_notsocket
)
2302 ip_keepalive(fileno(smtp_out
), sender_host_address
, FALSE
);
2304 /* If the current host matches host_lookup, set the name by doing a
2305 reverse lookup. On failure, sender_host_name will be NULL and
2306 host_lookup_failed will be TRUE. This may or may not be serious - optional
2309 if (verify_check_host(&host_lookup
) == OK
)
2311 (void)host_name_lookup();
2312 host_build_sender_fullhost();
2315 /* Delay this until we have the full name, if it is looked up. */
2317 set_process_info("handling incoming connection from %s",
2318 host_and_ident(FALSE
));
2320 /* Expand smtp_receive_timeout, if needed */
2322 if (smtp_receive_timeout_s
)
2325 if ( !(exp
= expand_string(smtp_receive_timeout_s
))
2327 || (smtp_receive_timeout
= readconf_readtime(exp
, 0, FALSE
)) < 0
2329 log_write(0, LOG_MAIN
|LOG_PANIC
,
2330 "bad value for smtp_receive_timeout: '%s'", exp
? exp
: US
"");
2333 /* Start up TLS if tls_on_connect is set. This is for supporting the legacy
2334 smtps port for use with older style SSL MTAs. */
2337 if (tls_in
.on_connect
&& tls_server_start(tls_require_ciphers
) != OK
)
2341 /* Test for explicit connection rejection */
2343 if (verify_check_host(&host_reject_connection
) == OK
)
2345 log_write(L_connection_reject
, LOG_MAIN
|LOG_REJECT
, "refused connection "
2346 "from %s (host_reject_connection)", host_and_ident(FALSE
));
2347 smtp_printf("554 SMTP service not available\r\n");
2351 /* Test with TCP Wrappers if so configured. There is a problem in that
2352 hosts_ctl() returns 0 (deny) under a number of system failure circumstances,
2353 such as disks dying. In these cases, it is desirable to reject with a 4xx
2354 error instead of a 5xx error. There isn't a "right" way to detect such
2355 problems. The following kludge is used: errno is zeroed before calling
2356 hosts_ctl(). If the result is "reject", a 5xx error is given only if the
2357 value of errno is 0 or ENOENT (which happens if /etc/hosts.{allow,deny} does
2360 #ifdef USE_TCP_WRAPPERS
2362 tcp_wrappers_name
= expand_string(tcp_wrappers_daemon_name
);
2363 if (tcp_wrappers_name
== NULL
)
2365 log_write(0, LOG_MAIN
|LOG_PANIC_DIE
, "Expansion of \"%s\" "
2366 "(tcp_wrappers_name) failed: %s", string_printing(tcp_wrappers_name
),
2367 expand_string_message
);
2369 if (!hosts_ctl(tcp_wrappers_name
,
2370 (sender_host_name
== NULL
)? STRING_UNKNOWN
: CS sender_host_name
,
2371 (sender_host_address
== NULL
)? STRING_UNKNOWN
: CS sender_host_address
,
2372 (sender_ident
== NULL
)? STRING_UNKNOWN
: CS sender_ident
))
2374 if (errno
== 0 || errno
== ENOENT
)
2376 HDEBUG(D_receive
) debug_printf("tcp wrappers rejection\n");
2377 log_write(L_connection_reject
,
2378 LOG_MAIN
|LOG_REJECT
, "refused connection from %s "
2379 "(tcp wrappers)", host_and_ident(FALSE
));
2380 smtp_printf("554 SMTP service not available\r\n");
2384 int save_errno
= errno
;
2385 HDEBUG(D_receive
) debug_printf("tcp wrappers rejected with unexpected "
2386 "errno value %d\n", save_errno
);
2387 log_write(L_connection_reject
,
2388 LOG_MAIN
|LOG_REJECT
, "temporarily refused connection from %s "
2389 "(tcp wrappers errno=%d)", host_and_ident(FALSE
), save_errno
);
2390 smtp_printf("451 Temporary local problem - please try later\r\n");
2396 /* Check for reserved slots. The value of smtp_accept_count has already been
2397 incremented to include this process. */
2399 if (smtp_accept_max
> 0 &&
2400 smtp_accept_count
> smtp_accept_max
- smtp_accept_reserve
)
2402 if ((rc
= verify_check_host(&smtp_reserve_hosts
)) != OK
)
2404 log_write(L_connection_reject
,
2405 LOG_MAIN
, "temporarily refused connection from %s: not in "
2406 "reserve list: connected=%d max=%d reserve=%d%s",
2407 host_and_ident(FALSE
), smtp_accept_count
- 1, smtp_accept_max
,
2408 smtp_accept_reserve
, (rc
== DEFER
)? " (lookup deferred)" : "");
2409 smtp_printf("421 %s: Too many concurrent SMTP connections; "
2410 "please try again later\r\n", smtp_active_hostname
);
2413 reserved_host
= TRUE
;
2416 /* If a load level above which only messages from reserved hosts are
2417 accepted is set, check the load. For incoming calls via the daemon, the
2418 check is done in the superior process if there are no reserved hosts, to
2419 save a fork. In all cases, the load average will already be available
2420 in a global variable at this point. */
2422 if (smtp_load_reserve
>= 0 &&
2423 load_average
> smtp_load_reserve
&&
2425 verify_check_host(&smtp_reserve_hosts
) != OK
)
2427 log_write(L_connection_reject
,
2428 LOG_MAIN
, "temporarily refused connection from %s: not in "
2429 "reserve list and load average = %.2f", host_and_ident(FALSE
),
2430 (double)load_average
/1000.0);
2431 smtp_printf("421 %s: Too much load; please try again later\r\n",
2432 smtp_active_hostname
);
2436 /* Determine whether unqualified senders or recipients are permitted
2437 for this host. Unfortunately, we have to do this every time, in order to
2438 set the flags so that they can be inspected when considering qualifying
2439 addresses in the headers. For a site that permits no qualification, this
2440 won't take long, however. */
2442 allow_unqualified_sender
=
2443 verify_check_host(&sender_unqualified_hosts
) == OK
;
2445 allow_unqualified_recipient
=
2446 verify_check_host(&recipient_unqualified_hosts
) == OK
;
2448 /* Determine whether HELO/EHLO is required for this host. The requirement
2449 can be hard or soft. */
2451 helo_required
= verify_check_host(&helo_verify_hosts
) == OK
;
2453 helo_verify
= verify_check_host(&helo_try_verify_hosts
) == OK
;
2455 /* Determine whether this hosts is permitted to send syntactic junk
2456 after a HELO or EHLO command. */
2458 helo_accept_junk
= verify_check_host(&helo_accept_junk_hosts
) == OK
;
2461 /* For batch SMTP input we are now done. */
2463 if (smtp_batched_input
) return TRUE
;
2465 #ifdef SUPPORT_PROXY
2466 /* If valid Proxy Protocol source is connecting, set up session.
2467 * Failure will not allow any SMTP function other than QUIT. */
2468 proxy_session
= FALSE
;
2469 proxy_session_failed
= FALSE
;
2470 if (check_proxy_protocol_host())
2471 if (!setup_proxy_protocol_host())
2473 proxy_session_failed
= TRUE
;
2475 debug_printf("Failure to extract proxied host, only QUIT allowed\n");
2479 sender_host_name
= NULL
;
2480 (void)host_name_lookup();
2481 host_build_sender_fullhost();
2485 /* Run the ACL if it exists */
2488 if (acl_smtp_connect
)
2491 if ((rc
= acl_check(ACL_WHERE_CONNECT
, NULL
, acl_smtp_connect
, &user_msg
,
2494 (void) smtp_handle_acl_fail(ACL_WHERE_CONNECT
, rc
, user_msg
, log_msg
);
2499 /* Output the initial message for a two-way SMTP connection. It may contain
2500 newlines, which then cause a multi-line response to be given. */
2502 code
= US
"220"; /* Default status code */
2503 esc
= US
""; /* Default extended status code */
2504 esclen
= 0; /* Length of esc */
2508 if (!(s
= expand_string(smtp_banner
)))
2509 log_write(0, LOG_MAIN
|LOG_PANIC_DIE
, "Expansion of \"%s\" (smtp_banner) "
2510 "failed: %s", smtp_banner
, expand_string_message
);
2516 smtp_message_code(&code
, &codelen
, &s
, NULL
, TRUE
);
2520 esclen
= codelen
- 4;
2524 /* Remove any terminating newlines; might as well remove trailing space too */
2527 while (p
> s
&& isspace(p
[-1])) p
--;
2530 /* It seems that CC:Mail is braindead, and assumes that the greeting message
2531 is all contained in a single IP packet. The original code wrote out the
2532 greeting using several calls to fprint/fputc, and on busy servers this could
2533 cause it to be split over more than one packet - which caused CC:Mail to fall
2534 over when it got the second part of the greeting after sending its first
2535 command. Sigh. To try to avoid this, build the complete greeting message
2536 first, and output it in one fell swoop. This gives a better chance of it
2537 ending up as a single packet. */
2539 ss
= store_get(size
);
2543 do /* At least once, in case we have an empty string */
2546 uschar
*linebreak
= Ustrchr(p
, '\n');
2547 ss
= string_catn(ss
, &size
, &ptr
, code
, 3);
2548 if (linebreak
== NULL
)
2551 ss
= string_catn(ss
, &size
, &ptr
, US
" ", 1);
2555 len
= linebreak
- p
;
2556 ss
= string_catn(ss
, &size
, &ptr
, US
"-", 1);
2558 ss
= string_catn(ss
, &size
, &ptr
, esc
, esclen
);
2559 ss
= string_catn(ss
, &size
, &ptr
, p
, len
);
2560 ss
= string_catn(ss
, &size
, &ptr
, US
"\r\n", 2);
2562 if (linebreak
!= NULL
) p
++;
2566 ss
[ptr
] = 0; /* string_cat leaves room for this */
2568 /* Before we write the banner, check that there is no input pending, unless
2569 this synchronisation check is disabled. */
2573 log_write(0, LOG_MAIN
|LOG_REJECT
, "SMTP protocol "
2574 "synchronization error (input sent without waiting for greeting): "
2575 "rejected connection from %s input=\"%s\"", host_and_ident(TRUE
),
2576 string_printing(smtp_inptr
));
2577 smtp_printf("554 SMTP synchronization error\r\n");
2581 /* Now output the banner */
2583 smtp_printf("%s", ss
);
2591 /*************************************************
2592 * Handle SMTP syntax and protocol errors *
2593 *************************************************/
2595 /* Write to the log for SMTP syntax errors in incoming commands, if configured
2596 to do so. Then transmit the error response. The return value depends on the
2597 number of syntax and protocol errors in this SMTP session.
2600 type error type, given as a log flag bit
2601 code response code; <= 0 means don't send a response
2602 data data to reflect in the response (can be NULL)
2603 errmess the error message
2605 Returns: -1 limit of syntax/protocol errors NOT exceeded
2606 +1 limit of syntax/protocol errors IS exceeded
2608 These values fit in with the values of the "done" variable in the main
2609 processing loop in smtp_setup_msg(). */
2612 synprot_error(int type
, int code
, uschar
*data
, uschar
*errmess
)
2616 log_write(type
, LOG_MAIN
, "SMTP %s error in \"%s\" %s %s",
2617 (type
== L_smtp_syntax_error
)? "syntax" : "protocol",
2618 string_printing(smtp_cmd_buffer
), host_and_ident(TRUE
), errmess
);
2620 if (++synprot_error_count
> smtp_max_synprot_errors
)
2623 log_write(0, LOG_MAIN
|LOG_REJECT
, "SMTP call from %s dropped: too many "
2624 "syntax or protocol errors (last command was \"%s\")",
2625 host_and_ident(FALSE
), string_printing(smtp_cmd_buffer
));
2630 smtp_printf("%d%c%s%s%s\r\n", code
, (yield
== 1)? '-' : ' ',
2631 (data
== NULL
)? US
"" : data
, (data
== NULL
)? US
"" : US
": ", errmess
);
2633 smtp_printf("%d Too many syntax or protocol errors\r\n", code
);
2642 /*************************************************
2643 * Log incomplete transactions *
2644 *************************************************/
2646 /* This function is called after a transaction has been aborted by RSET, QUIT,
2647 connection drops or other errors. It logs the envelope information received
2648 so far in order to preserve address verification attempts.
2650 Argument: string to indicate what aborted the transaction
2655 incomplete_transaction_log(uschar
*what
)
2657 if (sender_address
== NULL
|| /* No transaction in progress */
2658 !LOGGING(smtp_incomplete_transaction
))
2661 /* Build list of recipients for logging */
2663 if (recipients_count
> 0)
2666 raw_recipients
= store_get(recipients_count
* sizeof(uschar
*));
2667 for (i
= 0; i
< recipients_count
; i
++)
2668 raw_recipients
[i
] = recipients_list
[i
].address
;
2669 raw_recipients_count
= recipients_count
;
2672 log_write(L_smtp_incomplete_transaction
, LOG_MAIN
|LOG_SENDER
|LOG_RECIPIENTS
,
2673 "%s incomplete transaction (%s)", host_and_ident(TRUE
), what
);
2679 /*************************************************
2680 * Send SMTP response, possibly multiline *
2681 *************************************************/
2683 /* There are, it seems, broken clients out there that cannot handle multiline
2684 responses. If no_multiline_responses is TRUE (it can be set from an ACL), we
2685 output nothing for non-final calls, and only the first line for anything else.
2688 code SMTP code, may involve extended status codes
2689 codelen length of smtp code; if > 4 there's an ESC
2690 final FALSE if the last line isn't the final line
2691 msg message text, possibly containing newlines
2697 smtp_respond(uschar
* code
, int codelen
, BOOL final
, uschar
*msg
)
2702 if (!final
&& no_multiline_responses
) return;
2707 esclen
= codelen
- 4;
2710 /* If this is the first output for a (non-batch) RCPT command, see if all RCPTs
2711 have had the same. Note: this code is also present in smtp_printf(). It would
2712 be tidier to have it only in one place, but when it was added, it was easier to
2713 do it that way, so as not to have to mess with the code for the RCPT command,
2714 which sometimes uses smtp_printf() and sometimes smtp_respond(). */
2716 if (rcpt_in_progress
)
2718 if (rcpt_smtp_response
== NULL
)
2719 rcpt_smtp_response
= string_copy(msg
);
2720 else if (rcpt_smtp_response_same
&&
2721 Ustrcmp(rcpt_smtp_response
, msg
) != 0)
2722 rcpt_smtp_response_same
= FALSE
;
2723 rcpt_in_progress
= FALSE
;
2726 /* Not output the message, splitting it up into multiple lines if necessary. */
2730 uschar
*nl
= Ustrchr(msg
, '\n');
2733 smtp_printf("%.3s%c%.*s%s\r\n", code
, final
? ' ':'-', esclen
, esc
, msg
);
2736 else if (nl
[1] == 0 || no_multiline_responses
)
2738 smtp_printf("%.3s%c%.*s%.*s\r\n", code
, final
? ' ':'-', esclen
, esc
,
2739 (int)(nl
- msg
), msg
);
2744 smtp_printf("%.3s-%.*s%.*s\r\n", code
, esclen
, esc
, (int)(nl
- msg
), msg
);
2746 while (isspace(*msg
)) msg
++;
2754 /*************************************************
2755 * Parse user SMTP message *
2756 *************************************************/
2758 /* This function allows for user messages overriding the response code details
2759 by providing a suitable response code string at the start of the message
2760 user_msg. Check the message for starting with a response code and optionally an
2761 extended status code. If found, check that the first digit is valid, and if so,
2762 change the code pointer and length to use the replacement. An invalid code
2763 causes a panic log; in this case, if the log messages is the same as the user
2764 message, we must also adjust the value of the log message to show the code that
2765 is actually going to be used (the original one).
2767 This function is global because it is called from receive.c as well as within
2770 Note that the code length returned includes the terminating whitespace
2771 character, which is always included in the regex match.
2774 code SMTP code, may involve extended status codes
2775 codelen length of smtp code; if > 4 there's an ESC
2777 log_msg optional log message, to be adjusted with the new SMTP code
2778 check_valid if true, verify the response code
2784 smtp_message_code(uschar
**code
, int *codelen
, uschar
**msg
, uschar
**log_msg
,
2790 if (!msg
|| !*msg
) return;
2792 if ((n
= pcre_exec(regex_smtp_code
, NULL
, CS
*msg
, Ustrlen(*msg
), 0,
2793 PCRE_EOPT
, ovector
, sizeof(ovector
)/sizeof(int))) < 0) return;
2795 if (check_valid
&& (*msg
)[0] != (*code
)[0])
2797 log_write(0, LOG_MAIN
|LOG_PANIC
, "configured error code starts with "
2798 "incorrect digit (expected %c) in \"%s\"", (*code
)[0], *msg
);
2799 if (log_msg
!= NULL
&& *log_msg
== *msg
)
2800 *log_msg
= string_sprintf("%s %s", *code
, *log_msg
+ ovector
[1]);
2805 *codelen
= ovector
[1]; /* Includes final space */
2807 *msg
+= ovector
[1]; /* Chop the code off the message */
2814 /*************************************************
2815 * Handle an ACL failure *
2816 *************************************************/
2818 /* This function is called when acl_check() fails. As well as calls from within
2819 this module, it is called from receive.c for an ACL after DATA. It sorts out
2820 logging the incident, and sets up the error response. A message containing
2821 newlines is turned into a multiline SMTP response, but for logging, only the
2824 There's a table of default permanent failure response codes to use in
2825 globals.c, along with the table of names. VFRY is special. Despite RFC1123 it
2826 defaults disabled in Exim. However, discussion in connection with RFC 821bis
2827 (aka RFC 2821) has concluded that the response should be 252 in the disabled
2828 state, because there are broken clients that try VRFY before RCPT. A 5xx
2829 response should be given only when the address is positively known to be
2830 undeliverable. Sigh. We return 252 if there is no VRFY ACL or it provides
2831 no explicit code, but if there is one we let it know best.
2832 Also, for ETRN, 458 is given on refusal, and for AUTH, 503.
2834 From Exim 4.63, it is possible to override the response code details by
2835 providing a suitable response code string at the start of the message provided
2836 in user_msg. The code's first digit is checked for validity.
2839 where where the ACL was called from
2841 user_msg a message that can be included in an SMTP response
2842 log_msg a message for logging
2844 Returns: 0 in most cases
2845 2 if the failure code was FAIL_DROP, in which case the
2846 SMTP connection should be dropped (this value fits with the
2847 "done" variable in smtp_setup_msg() below)
2851 smtp_handle_acl_fail(int where
, int rc
, uschar
*user_msg
, uschar
*log_msg
)
2853 BOOL drop
= rc
== FAIL_DROP
;
2857 uschar
*sender_info
= US
"";
2859 #ifdef WITH_CONTENT_SCAN
2860 where
== ACL_WHERE_MIME
? US
"during MIME ACL checks" :
2862 where
== ACL_WHERE_PREDATA
? US
"DATA" :
2863 where
== ACL_WHERE_DATA
? US
"after DATA" :
2864 #ifndef DISABLE_PRDR
2865 where
== ACL_WHERE_PRDR
? US
"after DATA PRDR" :
2868 string_sprintf("%s %s", acl_wherenames
[where
], smtp_cmd_data
) :
2869 string_sprintf("%s in \"connect\" ACL", acl_wherenames
[where
]);
2871 if (drop
) rc
= FAIL
;
2873 /* Set the default SMTP code, and allow a user message to change it. */
2875 smtp_code
= rc
== FAIL
? acl_wherecodes
[where
] : US
"451";
2876 smtp_message_code(&smtp_code
, &codelen
, &user_msg
, &log_msg
,
2877 where
!= ACL_WHERE_VRFY
);
2879 /* We used to have sender_address here; however, there was a bug that was not
2880 updating sender_address after a rewrite during a verify. When this bug was
2881 fixed, sender_address at this point became the rewritten address. I'm not sure
2882 this is what should be logged, so I've changed to logging the unrewritten
2883 address to retain backward compatibility. */
2885 #ifndef WITH_CONTENT_SCAN
2886 if (where
== ACL_WHERE_RCPT
|| where
== ACL_WHERE_DATA
)
2888 if (where
== ACL_WHERE_RCPT
|| where
== ACL_WHERE_DATA
|| where
== ACL_WHERE_MIME
)
2891 sender_info
= string_sprintf("F=<%s>%s%s%s%s ",
2892 sender_address_unrewritten
? sender_address_unrewritten
: sender_address
,
2893 sender_host_authenticated
? US
" A=" : US
"",
2894 sender_host_authenticated
? sender_host_authenticated
: US
"",
2895 sender_host_authenticated
&& authenticated_id
? US
":" : US
"",
2896 sender_host_authenticated
&& authenticated_id
? authenticated_id
: US
""
2900 /* If there's been a sender verification failure with a specific message, and
2901 we have not sent a response about it yet, do so now, as a preliminary line for
2902 failures, but not defers. However, always log it for defer, and log it for fail
2903 unless the sender_verify_fail log selector has been turned off. */
2905 if (sender_verified_failed
!= NULL
&&
2906 !testflag(sender_verified_failed
, af_sverify_told
))
2908 BOOL save_rcpt_in_progress
= rcpt_in_progress
;
2909 rcpt_in_progress
= FALSE
; /* So as not to treat these as the error */
2911 setflag(sender_verified_failed
, af_sverify_told
);
2913 if (rc
!= FAIL
|| LOGGING(sender_verify_fail
))
2914 log_write(0, LOG_MAIN
|LOG_REJECT
, "%s sender verify %s for <%s>%s",
2915 host_and_ident(TRUE
),
2916 ((sender_verified_failed
->special_action
& 255) == DEFER
)? "defer":"fail",
2917 sender_verified_failed
->address
,
2918 (sender_verified_failed
->message
== NULL
)? US
"" :
2919 string_sprintf(": %s", sender_verified_failed
->message
));
2921 if (rc
== FAIL
&& sender_verified_failed
->user_message
!= NULL
)
2922 smtp_respond(smtp_code
, codelen
, FALSE
, string_sprintf(
2923 testflag(sender_verified_failed
, af_verify_pmfail
)?
2924 "Postmaster verification failed while checking <%s>\n%s\n"
2925 "Several RFCs state that you are required to have a postmaster\n"
2926 "mailbox for each mail domain. This host does not accept mail\n"
2927 "from domains whose servers reject the postmaster address."
2929 testflag(sender_verified_failed
, af_verify_nsfail
)?
2930 "Callback setup failed while verifying <%s>\n%s\n"
2931 "The initial connection, or a HELO or MAIL FROM:<> command was\n"
2932 "rejected. Refusing MAIL FROM:<> does not help fight spam, disregards\n"
2933 "RFC requirements, and stops you from receiving standard bounce\n"
2934 "messages. This host does not accept mail from domains whose servers\n"
2937 "Verification failed for <%s>\n%s",
2938 sender_verified_failed
->address
,
2939 sender_verified_failed
->user_message
));
2941 rcpt_in_progress
= save_rcpt_in_progress
;
2944 /* Sort out text for logging */
2946 log_msg
= log_msg
? string_sprintf(": %s", log_msg
) : US
"";
2947 if ((lognl
= Ustrchr(log_msg
, '\n'))) *lognl
= 0;
2949 /* Send permanent failure response to the command, but the code used isn't
2950 always a 5xx one - see comments at the start of this function. If the original
2951 rc was FAIL_DROP we drop the connection and yield 2. */
2954 smtp_respond(smtp_code
, codelen
, TRUE
,
2955 user_msg
? user_msg
: US
"Administrative prohibition");
2957 /* Send temporary failure response to the command. Don't give any details,
2958 unless acl_temp_details is set. This is TRUE for a callout defer, a "defer"
2959 verb, and for a header verify when smtp_return_error_details is set.
2961 This conditional logic is all somewhat of a mess because of the odd
2962 interactions between temp_details and return_error_details. One day it should
2963 be re-implemented in a tidier fashion. */
2966 if (acl_temp_details
&& user_msg
)
2968 if ( smtp_return_error_details
2969 && sender_verified_failed
2970 && sender_verified_failed
->message
2972 smtp_respond(smtp_code
, codelen
, FALSE
, sender_verified_failed
->message
);
2974 smtp_respond(smtp_code
, codelen
, TRUE
, user_msg
);
2977 smtp_respond(smtp_code
, codelen
, TRUE
,
2978 US
"Temporary local problem - please try later");
2980 /* Log the incident to the logs that are specified by log_reject_target
2981 (default main, reject). This can be empty to suppress logging of rejections. If
2982 the connection is not forcibly to be dropped, return 0. Otherwise, log why it
2983 is closing if required and return 2. */
2985 if (log_reject_target
!= 0)
2988 uschar
* tls
= s_tlslog(NULL
, NULL
, NULL
);
2989 if (!tls
) tls
= US
"";
2991 uschar
* tls
= US
"";
2993 log_write(where
== ACL_WHERE_CONNECT
? L_connection_reject
: 0,
2994 log_reject_target
, "%s%s%s %s%srejected %s%s",
2995 LOGGING(dnssec
) && sender_host_dnssec
? US
" DS" : US
"",
2996 host_and_ident(TRUE
),
2999 rc
== FAIL
? US
"" : US
"temporarily ",
3003 if (!drop
) return 0;
3005 log_write(L_smtp_connection
, LOG_MAIN
, "%s closed by DROP in ACL",
3006 smtp_get_connection_info());
3008 /* Run the not-quit ACL, but without any custom messages. This should not be a
3009 problem, because we get here only if some other ACL has issued "drop", and
3010 in that case, *its* custom messages will have been used above. */
3012 smtp_notquit_exit(US
"acl-drop", NULL
, NULL
);
3019 /*************************************************
3020 * Handle SMTP exit when QUIT is not given *
3021 *************************************************/
3023 /* This function provides a logging/statistics hook for when an SMTP connection
3024 is dropped on the floor or the other end goes away. It's a global function
3025 because it's called from receive.c as well as this module. As well as running
3026 the NOTQUIT ACL, if there is one, this function also outputs a final SMTP
3027 response, either with a custom message from the ACL, or using a default. There
3028 is one case, however, when no message is output - after "drop". In that case,
3029 the ACL that obeyed "drop" has already supplied the custom message, and NULL is
3030 passed to this function.
3032 In case things go wrong while processing this function, causing an error that
3033 may re-enter this funtion, there is a recursion check.
3036 reason What $smtp_notquit_reason will be set to in the ACL;
3037 if NULL, the ACL is not run
3038 code The error code to return as part of the response
3039 defaultrespond The default message if there's no user_msg
3045 smtp_notquit_exit(uschar
*reason
, uschar
*code
, uschar
*defaultrespond
, ...)
3048 uschar
*user_msg
= NULL
;
3049 uschar
*log_msg
= NULL
;
3051 /* Check for recursive acll */
3053 if (smtp_exit_function_called
)
3055 log_write(0, LOG_PANIC
, "smtp_notquit_exit() called more than once (%s)",
3059 smtp_exit_function_called
= TRUE
;
3061 /* Call the not-QUIT ACL, if there is one, unless no reason is given. */
3063 if (acl_smtp_notquit
&& reason
)
3065 smtp_notquit_reason
= reason
;
3066 if ((rc
= acl_check(ACL_WHERE_NOTQUIT
, NULL
, acl_smtp_notquit
, &user_msg
,
3067 &log_msg
)) == ERROR
)
3068 log_write(0, LOG_MAIN
|LOG_PANIC
, "ACL for not-QUIT returned ERROR: %s",
3072 /* Write an SMTP response if we are expected to give one. As the default
3073 responses are all internal, they should always fit in the buffer, but code a
3074 warning, just in case. Note that string_vformat() still leaves a complete
3075 string, even if it is incomplete. */
3077 if (code
&& defaultrespond
)
3080 smtp_respond(code
, 3, TRUE
, user_msg
);
3085 va_start(ap
, defaultrespond
);
3086 if (!string_vformat(buffer
, sizeof(buffer
), CS defaultrespond
, ap
))
3087 log_write(0, LOG_MAIN
|LOG_PANIC
, "string too large in smtp_notquit_exit()");
3088 smtp_printf("%s %s\r\n", code
, buffer
);
3098 /*************************************************
3099 * Verify HELO argument *
3100 *************************************************/
3102 /* This function is called if helo_verify_hosts or helo_try_verify_hosts is
3103 matched. It is also called from ACL processing if verify = helo is used and
3104 verification was not previously tried (i.e. helo_try_verify_hosts was not
3105 matched). The result of its processing is to set helo_verified and
3106 helo_verify_failed. These variables should both be FALSE for this function to
3109 Note that EHLO/HELO is legitimately allowed to quote an address literal. Allow
3110 for IPv6 ::ffff: literals.
3113 Returns: TRUE if testing was completed;
3114 FALSE on a temporary failure
3118 smtp_verify_helo(void)
3122 HDEBUG(D_receive
) debug_printf("verifying EHLO/HELO argument \"%s\"\n",
3125 if (sender_helo_name
== NULL
)
3127 HDEBUG(D_receive
) debug_printf("no EHLO/HELO command was issued\n");
3130 /* Deal with the case of -bs without an IP address */
3132 else if (sender_host_address
== NULL
)
3134 HDEBUG(D_receive
) debug_printf("no client IP address: assume success\n");
3135 helo_verified
= TRUE
;
3138 /* Deal with the more common case when there is a sending IP address */
3140 else if (sender_helo_name
[0] == '[')
3142 helo_verified
= Ustrncmp(sender_helo_name
+1, sender_host_address
,
3143 Ustrlen(sender_host_address
)) == 0;
3148 if (strncmpic(sender_host_address
, US
"::ffff:", 7) == 0)
3149 helo_verified
= Ustrncmp(sender_helo_name
+ 1,
3150 sender_host_address
+ 7, Ustrlen(sender_host_address
) - 7) == 0;
3155 { if (helo_verified
) debug_printf("matched host address\n"); }
3158 /* Do a reverse lookup if one hasn't already given a positive or negative
3159 response. If that fails, or the name doesn't match, try checking with a forward
3164 if (sender_host_name
== NULL
&& !host_lookup_failed
)
3165 yield
= host_name_lookup() != DEFER
;
3167 /* If a host name is known, check it and all its aliases. */
3169 if (sender_host_name
)
3170 if ((helo_verified
= strcmpic(sender_host_name
, sender_helo_name
) == 0))
3172 sender_helo_dnssec
= sender_host_dnssec
;
3173 HDEBUG(D_receive
) debug_printf("matched host name\n");
3177 uschar
**aliases
= sender_host_aliases
;
3179 if ((helo_verified
= strcmpic(*aliases
++, sender_helo_name
) == 0))
3181 sender_helo_dnssec
= sender_host_dnssec
;
3185 HDEBUG(D_receive
) if (helo_verified
)
3186 debug_printf("matched alias %s\n", *(--aliases
));
3189 /* Final attempt: try a forward lookup of the helo name */
3198 h
.name
= sender_helo_name
;
3205 HDEBUG(D_receive
) debug_printf("getting IP address for %s\n",
3207 rc
= host_find_bydns(&h
, NULL
, HOST_FIND_BY_A
,
3208 NULL
, NULL
, NULL
, &d
, NULL
, NULL
);
3209 if (rc
== HOST_FOUND
|| rc
== HOST_FOUND_LOCAL
)
3210 for (hh
= &h
; hh
; hh
= hh
->next
)
3211 if (Ustrcmp(hh
->address
, sender_host_address
) == 0)
3213 helo_verified
= TRUE
;
3214 if (h
.dnssec
== DS_YES
) sender_helo_dnssec
= TRUE
;
3217 debug_printf("IP address for %s matches calling address\n"
3218 "Forward DNS security status: %sverified\n",
3219 sender_helo_name
, sender_helo_dnssec
? "" : "un");
3226 if (!helo_verified
) helo_verify_failed
= TRUE
; /* We've tried ... */
3233 /*************************************************
3234 * Send user response message *
3235 *************************************************/
3237 /* This function is passed a default response code and a user message. It calls
3238 smtp_message_code() to check and possibly modify the response code, and then
3239 calls smtp_respond() to transmit the response. I put this into a function
3240 just to avoid a lot of repetition.
3243 code the response code
3244 user_msg the user message
3250 smtp_user_msg(uschar
*code
, uschar
*user_msg
)
3253 smtp_message_code(&code
, &len
, &user_msg
, NULL
, TRUE
);
3254 smtp_respond(code
, len
, TRUE
, user_msg
);
3260 smtp_in_auth(auth_instance
*au
, uschar
** s
, uschar
** ss
)
3262 const uschar
*set_id
= NULL
;
3265 /* Run the checking code, passing the remainder of the command line as
3266 data. Initials the $auth<n> variables as empty. Initialize $0 empty and set
3267 it as the only set numerical variable. The authenticator may set $auth<n>
3268 and also set other numeric variables. The $auth<n> variables are preferred
3269 nowadays; the numerical variables remain for backwards compatibility.
3271 Afterwards, have a go at expanding the set_id string, even if
3272 authentication failed - for bad passwords it can be useful to log the
3273 userid. On success, require set_id to expand and exist, and put it in
3274 authenticated_id. Save this in permanent store, as the working store gets
3275 reset at HELO, RSET, etc. */
3277 for (i
= 0; i
< AUTH_VARS
; i
++) auth_vars
[i
] = NULL
;
3279 expand_nlength
[0] = 0; /* $0 contains nothing */
3281 rc
= (au
->info
->servercode
)(au
, smtp_cmd_data
);
3282 if (au
->set_id
) set_id
= expand_string(au
->set_id
);
3283 expand_nmax
= -1; /* Reset numeric variables */
3284 for (i
= 0; i
< AUTH_VARS
; i
++) auth_vars
[i
] = NULL
; /* Reset $auth<n> */
3286 /* The value of authenticated_id is stored in the spool file and printed in
3287 log lines. It must not contain binary zeros or newline characters. In
3288 normal use, it never will, but when playing around or testing, this error
3289 can (did) happen. To guard against this, ensure that the id contains only
3290 printing characters. */
3292 if (set_id
) set_id
= string_printing(set_id
);
3294 /* For the non-OK cases, set up additional logging data if set_id
3298 set_id
= set_id
&& *set_id
3299 ? string_sprintf(" (set_id=%s)", set_id
) : US
"";
3301 /* Switch on the result */
3306 if (!au
->set_id
|| set_id
) /* Complete success */
3308 if (set_id
) authenticated_id
= string_copy_malloc(set_id
);
3309 sender_host_authenticated
= au
->name
;
3310 authentication_failed
= FALSE
;
3311 authenticated_fail_id
= NULL
; /* Impossible to already be set? */
3314 (sender_host_address
? protocols
: protocols_local
)
3315 [pextend
+ pauthed
+ (tls_in
.active
>= 0 ? pcrpted
:0)];
3316 *s
= *ss
= US
"235 Authentication succeeded";
3317 authenticated_by
= au
;
3321 /* Authentication succeeded, but we failed to expand the set_id string.
3322 Treat this as a temporary error. */
3324 auth_defer_msg
= expand_string_message
;
3328 if (set_id
) authenticated_fail_id
= string_copy_malloc(set_id
);
3329 *s
= string_sprintf("435 Unable to authenticate at present%s",
3330 auth_defer_user_msg
);
3331 *ss
= string_sprintf("435 Unable to authenticate at present%s: %s",
3332 set_id
, auth_defer_msg
);
3336 *s
= *ss
= US
"501 Invalid base64 data";
3340 *s
= *ss
= US
"501 Authentication cancelled";
3344 *s
= *ss
= US
"553 Initial data not expected";
3348 if (set_id
) authenticated_fail_id
= string_copy_malloc(set_id
);
3349 *s
= US
"535 Incorrect authentication data";
3350 *ss
= string_sprintf("535 Incorrect authentication data%s", set_id
);
3354 if (set_id
) authenticated_fail_id
= string_copy_malloc(set_id
);
3355 *s
= US
"435 Internal error";
3356 *ss
= string_sprintf("435 Internal error%s: return %d from authentication "
3357 "check", set_id
, rc
);
3369 qualify_recipient(uschar
** recipient
, uschar
* smtp_cmd_data
, uschar
* tag
)
3372 if (allow_unqualified_recipient
|| strcmpic(*recipient
, US
"postmaster") == 0)
3374 DEBUG(D_receive
) debug_printf("unqualified address %s accepted\n",
3376 rd
= Ustrlen(recipient
) + 1;
3377 *recipient
= rewrite_address_qualify(*recipient
, TRUE
);
3380 smtp_printf("501 %s: recipient address must contain a domain\r\n",
3382 log_write(L_smtp_syntax_error
,
3383 LOG_MAIN
|LOG_REJECT
, "unqualified %s rejected: <%s> %s%s",
3384 tag
, *recipient
, host_and_ident(TRUE
), host_lookup_msg
);
3392 smtp_quit_handler(uschar
** user_msgp
, uschar
** log_msgp
)
3395 incomplete_transaction_log(US
"QUIT");
3398 int rc
= acl_check(ACL_WHERE_QUIT
, NULL
, acl_smtp_quit
, user_msgp
, log_msgp
);
3400 log_write(0, LOG_MAIN
|LOG_PANIC
, "ACL for QUIT returned ERROR: %s",
3404 smtp_respond(US
"221", 3, TRUE
, *user_msgp
);
3406 smtp_printf("221 %s closing connection\r\n", smtp_active_hostname
);
3409 tls_close(TRUE
, TRUE
);
3412 log_write(L_smtp_connection
, LOG_MAIN
, "%s closed by QUIT",
3413 smtp_get_connection_info());
3418 smtp_rset_handler(void)
3421 incomplete_transaction_log(US
"RSET");
3422 smtp_printf("250 Reset OK\r\n");
3423 cmd_list
[CMD_LIST_RSET
].is_mail_cmd
= FALSE
;
3428 /*************************************************
3429 * Initialize for SMTP incoming message *
3430 *************************************************/
3432 /* This function conducts the initial dialogue at the start of an incoming SMTP
3433 message, and builds a list of recipients. However, if the incoming message
3434 is part of a batch (-bS option) a separate function is called since it would
3435 be messy having tests splattered about all over this function. This function
3436 therefore handles the case where interaction is occurring. The input and output
3437 files are set up in smtp_in and smtp_out.
3439 The global recipients_list is set to point to a vector of recipient_item
3440 blocks, whose number is given by recipients_count. This is extended by the
3441 receive_add_recipient() function. The global variable sender_address is set to
3442 the sender's address. The yield is +1 if a message has been successfully
3443 started, 0 if a QUIT command was encountered or the connection was refused from
3444 the particular host, or -1 if the connection was lost.
3448 Returns: > 0 message successfully started (reached DATA)
3449 = 0 QUIT read or end of file reached or call refused
3454 smtp_setup_msg(void)
3457 BOOL toomany
= FALSE
;
3458 BOOL discarded
= FALSE
;
3459 BOOL last_was_rej_mail
= FALSE
;
3460 BOOL last_was_rcpt
= FALSE
;
3461 void *reset_point
= store_get(0);
3463 DEBUG(D_receive
) debug_printf("smtp_setup_msg entered\n");
3465 /* Reset for start of new message. We allow one RSET not to be counted as a
3466 nonmail command, for those MTAs that insist on sending it between every
3467 message. Ditto for EHLO/HELO and for STARTTLS, to allow for going in and out of
3468 TLS between messages (an Exim client may do this if it has messages queued up
3469 for the host). Note: we do NOT reset AUTH at this point. */
3471 smtp_reset(reset_point
);
3472 message_ended
= END_NOTSTARTED
;
3474 chunking_state
= chunking_offered
? CHUNKING_OFFERED
: CHUNKING_NOT_OFFERED
;
3476 cmd_list
[CMD_LIST_RSET
].is_mail_cmd
= TRUE
;
3477 cmd_list
[CMD_LIST_HELO
].is_mail_cmd
= TRUE
;
3478 cmd_list
[CMD_LIST_EHLO
].is_mail_cmd
= TRUE
;
3480 cmd_list
[CMD_LIST_STARTTLS
].is_mail_cmd
= TRUE
;
3481 cmd_list
[CMD_LIST_TLS_AUTH
].is_mail_cmd
= TRUE
;
3484 /* Set the local signal handler for SIGTERM - it tries to end off tidily */
3486 os_non_restarting_signal(SIGTERM
, command_sigterm_handler
);
3488 /* Batched SMTP is handled in a different function. */
3490 if (smtp_batched_input
) return smtp_setup_batch_msg();
3492 /* Deal with SMTP commands. This loop is exited by setting done to a POSITIVE
3493 value. The values are 2 larger than the required yield of the function. */
3497 const uschar
**argv
;
3498 uschar
*etrn_command
;
3499 uschar
*etrn_serialize_key
;
3501 uschar
*log_msg
, *smtp_code
;
3502 uschar
*user_msg
= NULL
;
3503 uschar
*recipient
= NULL
;
3504 uschar
*hello
= NULL
;
3506 BOOL was_rej_mail
= FALSE
;
3507 BOOL was_rcpt
= FALSE
;
3508 void (*oldsignal
)(int);