1 /* $Cambridge: exim/src/src/smtp_in.c,v 1.54 2007/02/20 11:37:16 ph10 Exp $ */
3 /*************************************************
4 * Exim - an Internet mail transport agent *
5 *************************************************/
7 /* Copyright (c) University of Cambridge 1995 - 2007 */
8 /* See the file NOTICE for conditions of use and distribution. */
10 /* Functions for handling an incoming SMTP call. */
16 /* Initialize for TCP wrappers if so configured. It appears that the macro
17 HAVE_IPV6 is used in some versions of the tcpd.h header, so we unset it before
18 including that header, and restore its value afterwards. */
20 #ifdef USE_TCP_WRAPPERS
23 #define EXIM_HAVE_IPV6
29 #define HAVE_IPV6 TRUE
32 int allow_severity = LOG_INFO;
33 int deny_severity = LOG_NOTICE;
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. */
42 #define smtp_cmd_buffer_size 2048
44 /* Size of buffer for reading SMTP incoming packets */
46 #define in_buffer_size 8192
48 /* Structure for SMTP command list */
55 short int is_mail_cmd;
58 /* Codes for identifying commands. We order them so that those that come first
59 are those for which synchronization is always required. Checking this can help
63 /* These commands are required to be synchronized, i.e. to be the last in a
64 block of commands when pipelining. */
66 HELO_CMD, EHLO_CMD, DATA_CMD, /* These are listed in the pipelining */
67 VRFY_CMD, EXPN_CMD, NOOP_CMD, /* RFC as requiring synchronization */
68 ETRN_CMD, /* This by analogy with TURN from the RFC */
69 STARTTLS_CMD, /* Required by the STARTTLS RFC */
71 /* This is a dummy to identify the non-sync commands when pipelining */
73 NON_SYNC_CMD_PIPELINING,
75 /* These commands need not be synchronized when pipelining */
77 MAIL_CMD, RCPT_CMD, RSET_CMD,
79 /* This is a dummy to identify the non-sync commands when not pipelining */
81 NON_SYNC_CMD_NON_PIPELINING,
83 /* I have been unable to find a statement about the use of pipelining
84 with AUTH, so to be on the safe side it is here, though I kind of feel
85 it should be up there with the synchronized commands. */
89 /* I'm not sure about these, but I don't think they matter. */
93 /* These are specials that don't correspond to actual commands */
95 EOF_CMD, OTHER_CMD, BADARG_CMD, BADCHAR_CMD, BADSYN_CMD,
96 TOO_MANY_NONMAIL_CMD };
99 /* This is a convenience macro for adding the identity of an SMTP command
100 to the circular buffer that holds a list of the last n received. */
103 smtp_connection_had[smtp_ch_index++] = n; \
104 if (smtp_ch_index >= SMTP_HBUFF_SIZE) smtp_ch_index = 0
107 /*************************************************
108 * Local static variables *
109 *************************************************/
111 static auth_instance *authenticated_by;
112 static BOOL auth_advertised;
114 static BOOL tls_advertised;
117 static BOOL helo_required = FALSE;
118 static BOOL helo_verify = FALSE;
119 static BOOL helo_seen;
120 static BOOL helo_accept_junk;
121 static BOOL count_nonmail;
122 static BOOL pipelining_advertised;
123 static int nonmail_command_count;
124 static int synprot_error_count;
125 static int unknown_command_count;
126 static int sync_cmd_limit;
127 static int smtp_write_error = 0;
129 static uschar *smtp_data_buffer;
130 static uschar *smtp_cmd_data;
132 /* We need to know the position of RSET, HELO, EHLO, AUTH, and STARTTLS. Their
133 final fields of all except AUTH are forced TRUE at the start of a new message
134 setup, to allow one of each between messages that is not counted as a nonmail
135 command. (In fact, only one of HELO/EHLO is not counted.) Also, we have to
136 allow a new EHLO after starting up TLS.
138 AUTH is "falsely" labelled as a mail command initially, so that it doesn't get
139 counted. However, the flag is changed when AUTH is received, so that multiple
140 failing AUTHs will eventually hit the limit. After a successful AUTH, another
141 AUTH is already forbidden. After a TLS session is started, AUTH's flag is again
142 forced TRUE, to allow for the re-authentication that can happen at that point.
144 QUIT is also "falsely" labelled as a mail command so that it doesn't up the
145 count of non-mail commands and possibly provoke an error. */
147 static smtp_cmd_list cmd_list[] = {
148 { "rset", sizeof("rset")-1, RSET_CMD, FALSE, FALSE }, /* First */
149 { "helo", sizeof("helo")-1, HELO_CMD, TRUE, FALSE },
150 { "ehlo", sizeof("ehlo")-1, EHLO_CMD, TRUE, FALSE },
151 { "auth", sizeof("auth")-1, AUTH_CMD, TRUE, TRUE },
153 { "starttls", sizeof("starttls")-1, STARTTLS_CMD, FALSE, FALSE },
156 /* If you change anything above here, also fix the definitions below. */
158 { "mail from:", sizeof("mail from:")-1, MAIL_CMD, TRUE, TRUE },
159 { "rcpt to:", sizeof("rcpt to:")-1, RCPT_CMD, TRUE, TRUE },
160 { "data", sizeof("data")-1, DATA_CMD, FALSE, TRUE },
161 { "quit", sizeof("quit")-1, QUIT_CMD, FALSE, TRUE },
162 { "noop", sizeof("noop")-1, NOOP_CMD, TRUE, FALSE },
163 { "etrn", sizeof("etrn")-1, ETRN_CMD, TRUE, FALSE },
164 { "vrfy", sizeof("vrfy")-1, VRFY_CMD, TRUE, FALSE },
165 { "expn", sizeof("expn")-1, EXPN_CMD, TRUE, FALSE },
166 { "help", sizeof("help")-1, HELP_CMD, TRUE, FALSE }
169 static smtp_cmd_list *cmd_list_end =
170 cmd_list + sizeof(cmd_list)/sizeof(smtp_cmd_list);
172 #define CMD_LIST_RSET 0
173 #define CMD_LIST_HELO 1
174 #define CMD_LIST_EHLO 2
175 #define CMD_LIST_AUTH 3
176 #define CMD_LIST_STARTTLS 4
178 /* This list of names is used for performing the smtp_no_mail logging action.
179 It must be kept in step with the SCH_xxx enumerations. */
181 static uschar *smtp_names[] =
183 US"NONE", US"AUTH", US"DATA", US"EHLO", US"ETRN", US"EXPN", US"HELO",
184 US"HELP", US"MAIL", US"NOOP", US"QUIT", US"RCPT", US"RSET", US"STARTTLS",
187 static uschar *protocols[] = {
188 US"local-smtp", /* HELO */
189 US"local-smtps", /* The rare case EHLO->STARTTLS->HELO */
190 US"local-esmtp", /* EHLO */
191 US"local-esmtps", /* EHLO->STARTTLS->EHLO */
192 US"local-esmtpa", /* EHLO->AUTH */
193 US"local-esmtpsa" /* EHLO->STARTTLS->EHLO->AUTH */
198 #define pcrpted 1 /* added to pextend or pnormal */
199 #define pauthed 2 /* added to pextend */
200 #define pnlocal 6 /* offset to remove "local" */
202 /* When reading SMTP from a remote host, we have to use our own versions of the
203 C input-reading functions, in order to be able to flush the SMTP output only
204 when about to read more data from the socket. This is the only way to get
205 optimal performance when the client is using pipelining. Flushing for every
206 command causes a separate packet and reply packet each time; saving all the
207 responses up (when pipelining) combines them into one packet and one response.
209 For simplicity, these functions are used for *all* SMTP input, not only when
210 receiving over a socket. However, after setting up a secure socket (SSL), input
211 is read via the OpenSSL library, and another set of functions is used instead
214 These functions are set in the receive_getc etc. variables and called with the
215 same interface as the C functions. However, since there can only ever be
216 one incoming SMTP call, we just use a single buffer and flags. There is no need
217 to implement a complicated private FILE-like structure.*/
219 static uschar *smtp_inbuffer;
220 static uschar *smtp_inptr;
221 static uschar *smtp_inend;
222 static int smtp_had_eof;
223 static int smtp_had_error;
226 /*************************************************
227 * SMTP version of getc() *
228 *************************************************/
230 /* This gets the next byte from the SMTP input buffer. If the buffer is empty,
231 it flushes the output, and refills the buffer, with a timeout. The signal
232 handler is set appropriately by the calling function. This function is not used
233 after a connection has negotated itself into an TLS/SSL state.
236 Returns: the next character or EOF
242 if (smtp_inptr >= smtp_inend)
246 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
247 rc = read(fileno(smtp_in), smtp_inbuffer, in_buffer_size);
252 /* Must put the error text in fixed store, because this might be during
253 header reading, where it releases unused store above the header. */
256 smtp_had_error = save_errno;
257 smtp_read_error = string_copy_malloc(
258 string_sprintf(" (error: %s)", strerror(save_errno)));
260 else smtp_had_eof = 1;
263 smtp_inend = smtp_inbuffer + rc;
264 smtp_inptr = smtp_inbuffer;
266 return *smtp_inptr++;
271 /*************************************************
272 * SMTP version of ungetc() *
273 *************************************************/
275 /* Puts a character back in the input buffer. Only ever
281 Returns: the character
287 *(--smtp_inptr) = ch;
294 /*************************************************
295 * SMTP version of feof() *
296 *************************************************/
298 /* Tests for a previous EOF
301 Returns: non-zero if the eof flag is set
313 /*************************************************
314 * SMTP version of ferror() *
315 *************************************************/
317 /* Tests for a previous read error, and returns with errno
318 restored to what it was when the error was detected.
321 Returns: non-zero if the error flag is set
327 errno = smtp_had_error;
328 return smtp_had_error;
334 /*************************************************
335 * Write formatted string to SMTP channel *
336 *************************************************/
338 /* This is a separate function so that we don't have to repeat everything for
339 TLS support or debugging. It is global so that the daemon and the
340 authentication functions can use it. It does not return any error indication,
341 because major problems such as dropped connections won't show up till an output
342 flush for non-TLS connections. The smtp_fflush() function is available for
343 checking that: for convenience, TLS output errors are remembered here so that
344 they are also picked up later by smtp_fflush().
348 ... optional arguments
354 smtp_printf(char *format, ...)
361 va_start(ap, format);
362 (void) string_vformat(big_buffer, big_buffer_size, format, ap);
364 end = big_buffer + Ustrlen(big_buffer);
365 while ((cr = Ustrchr(big_buffer, '\r')) != NULL) /* lose CRs */
366 memmove(cr, cr + 1, (end--) - cr);
367 debug_printf("SMTP>> %s", big_buffer);
370 va_start(ap, format);
372 /* If in a TLS session we have to format the string, and then write it using a
378 if (!string_vformat(big_buffer, big_buffer_size, format, ap))
380 log_write(0, LOG_MAIN|LOG_PANIC, "string too large in smtp_printf");
381 smtp_closedown(US"Unexpected error");
382 exim_exit(EXIT_FAILURE);
384 if (tls_write(big_buffer, Ustrlen(big_buffer)) < 0) smtp_write_error = -1;
389 /* Otherwise, just use the standard library function. */
391 if (vfprintf(smtp_out, format, ap) < 0) smtp_write_error = -1;
397 /*************************************************
398 * Flush SMTP out and check for error *
399 *************************************************/
401 /* This function isn't currently used within Exim (it detects errors when it
402 tries to read the next SMTP input), but is available for use in local_scan().
403 For non-TLS connections, it flushes the output and checks for errors. For
404 TLS-connections, it checks for a previously-detected TLS write error.
407 Returns: 0 for no error; -1 after an error
413 if (tls_active < 0 && fflush(smtp_out) != 0) smtp_write_error = -1;
414 return smtp_write_error;
419 /*************************************************
420 * SMTP command read timeout *
421 *************************************************/
423 /* Signal handler for timing out incoming SMTP commands. This attempts to
426 Argument: signal number (SIGALRM)
431 command_timeout_handler(int sig)
433 sig = sig; /* Keep picky compilers happy */
434 log_write(L_lost_incoming_connection,
435 LOG_MAIN, "SMTP command timeout on%s connection from %s",
436 (tls_active >= 0)? " TLS" : "",
437 host_and_ident(FALSE));
438 if (smtp_batched_input)
439 moan_smtp_batch(NULL, "421 SMTP command timeout"); /* Does not return */
440 smtp_printf("421 %s: SMTP command timeout - closing connection\r\n",
441 smtp_active_hostname);
443 exim_exit(EXIT_FAILURE);
448 /*************************************************
450 *************************************************/
452 /* Signal handler for handling SIGTERM. Again, try to finish tidily.
454 Argument: signal number (SIGTERM)
459 command_sigterm_handler(int sig)
461 sig = sig; /* Keep picky compilers happy */
462 log_write(0, LOG_MAIN, "%s closed after SIGTERM", smtp_get_connection_info());
463 if (smtp_batched_input)
464 moan_smtp_batch(NULL, "421 SIGTERM received"); /* Does not return */
465 smtp_printf("421 %s: Service not available - closing connection\r\n",
466 smtp_active_hostname);
467 exim_exit(EXIT_FAILURE);
472 /*************************************************
473 * Read one command line *
474 *************************************************/
476 /* Strictly, SMTP commands coming over the net are supposed to end with CRLF.
477 There are sites that don't do this, and in any case internal SMTP probably
478 should check only for LF. Consequently, we check here for LF only. The line
479 ends up with [CR]LF removed from its end. If we get an overlong line, treat as
480 an unknown command. The command is read into the global smtp_cmd_buffer so that
481 it is available via $smtp_command.
483 The character reading routine sets up a timeout for each block actually read
484 from the input (which may contain more than one command). We set up a special
485 signal handler that closes down the session on a timeout. Control does not
489 check_sync if TRUE, check synchronization rules if global option is TRUE
491 Returns: a code identifying the command (enumerated above)
495 smtp_read_command(BOOL check_sync)
500 BOOL hadnull = FALSE;
502 os_non_restarting_signal(SIGALRM, command_timeout_handler);
504 while ((c = (receive_getc)()) != '\n' && c != EOF)
506 if (ptr >= smtp_cmd_buffer_size)
508 os_non_restarting_signal(SIGALRM, sigalrm_handler);
516 smtp_cmd_buffer[ptr++] = c;
519 receive_linecount++; /* For BSMTP errors */
520 os_non_restarting_signal(SIGALRM, sigalrm_handler);
522 /* If hit end of file, return pseudo EOF command. Whether we have a
523 part-line already read doesn't matter, since this is an error state. */
525 if (c == EOF) return EOF_CMD;
527 /* Remove any CR and white space at the end of the line, and terminate the
530 while (ptr > 0 && isspace(smtp_cmd_buffer[ptr-1])) ptr--;
531 smtp_cmd_buffer[ptr] = 0;
533 DEBUG(D_receive) debug_printf("SMTP<< %s\n", smtp_cmd_buffer);
535 /* NULLs are not allowed in SMTP commands */
537 if (hadnull) return BADCHAR_CMD;
539 /* Scan command list and return identity, having set the data pointer
540 to the start of the actual data characters. Check for SMTP synchronization
543 for (p = cmd_list; p < cmd_list_end; p++)
545 if (strncmpic(smtp_cmd_buffer, US p->name, p->len) == 0 &&
546 (smtp_cmd_buffer[p->len-1] == ':' || /* "mail from:" or "rcpt to:" */
547 smtp_cmd_buffer[p->len] == 0 ||
548 smtp_cmd_buffer[p->len] == ' '))
550 if (smtp_inptr < smtp_inend && /* Outstanding input */
551 p->cmd < sync_cmd_limit && /* Command should sync */
552 check_sync && /* Local flag set */
553 smtp_enforce_sync && /* Global flag set */
554 sender_host_address != NULL && /* Not local input */
555 !sender_host_notsocket) /* Really is a socket */
558 /* The variables $smtp_command and $smtp_command_argument point into the
559 unmodified input buffer. A copy of the latter is taken for actual
560 processing, so that it can be chopped up into separate parts if necessary,
561 for example, when processing a MAIL command options such as SIZE that can
562 follow the sender address. */
564 smtp_cmd_argument = smtp_cmd_buffer + p->len;
565 while (isspace(*smtp_cmd_argument)) smtp_cmd_argument++;
566 Ustrcpy(smtp_data_buffer, smtp_cmd_argument);
567 smtp_cmd_data = smtp_data_buffer;
569 /* Count non-mail commands from those hosts that are controlled in this
570 way. The default is all hosts. We don't waste effort checking the list
571 until we get a non-mail command, but then cache the result to save checking
572 again. If there's a DEFER while checking the host, assume it's in the list.
574 Note that one instance of RSET, EHLO/HELO, and STARTTLS is allowed at the
575 start of each incoming message by fiddling with the value in the table. */
579 if (count_nonmail == TRUE_UNSET) count_nonmail =
580 verify_check_host(&smtp_accept_max_nonmail_hosts) != FAIL;
581 if (count_nonmail && ++nonmail_command_count > smtp_accept_max_nonmail)
582 return TOO_MANY_NONMAIL_CMD;
585 /* If there is data for a command that does not expect it, generate the
588 return (p->has_arg || *smtp_cmd_data == 0)? p->cmd : BADARG_CMD;
592 /* Enforce synchronization for unknown commands */
594 if (smtp_inptr < smtp_inend && /* Outstanding input */
595 check_sync && /* Local flag set */
596 smtp_enforce_sync && /* Global flag set */
597 sender_host_address != NULL && /* Not local input */
598 !sender_host_notsocket) /* Really is a socket */
606 /*************************************************
607 * Forced closedown of call *
608 *************************************************/
610 /* This function is called from log.c when Exim is dying because of a serious
611 disaster, and also from some other places. If an incoming non-batched SMTP
612 channel is open, it swallows the rest of the incoming message if in the DATA
613 phase, sends the reply string, and gives an error to all subsequent commands
614 except QUIT. The existence of an SMTP call is detected by the non-NULLness of
617 Argument: SMTP reply string to send, excluding the code
622 smtp_closedown(uschar *message)
624 if (smtp_in == NULL || smtp_batched_input) return;
625 receive_swallow_smtp();
626 smtp_printf("421 %s\r\n", message);
630 switch(smtp_read_command(FALSE))
636 smtp_printf("221 %s closing connection\r\n", smtp_active_hostname);
641 smtp_printf("250 Reset OK\r\n");
645 smtp_printf("421 %s\r\n", message);
654 /*************************************************
655 * Set up connection info for logging *
656 *************************************************/
658 /* This function is called when logging information about an SMTP connection.
659 It sets up appropriate source information, depending on the type of connection.
660 If sender_fullhost is NULL, we are at a very early stage of the connection;
661 just use the IP address.
664 Returns: a string describing the connection
668 smtp_get_connection_info(void)
670 uschar *hostname = (sender_fullhost == NULL)?
671 sender_host_address : sender_fullhost;
674 return string_sprintf("SMTP connection from %s", hostname);
676 if (sender_host_unknown || sender_host_notsocket)
677 return string_sprintf("SMTP connection from %s", sender_ident);
680 return string_sprintf("SMTP connection from %s (via inetd)", hostname);
682 if ((log_extra_selector & LX_incoming_interface) != 0 &&
683 interface_address != NULL)
684 return string_sprintf("SMTP connection from %s I=[%s]:%d", hostname,
685 interface_address, interface_port);
687 return string_sprintf("SMTP connection from %s", hostname);
692 /*************************************************
693 * Log lack of MAIL if so configured *
694 *************************************************/
696 /* This function is called when an SMTP session ends. If the log selector
697 smtp_no_mail is set, write a log line giving some details of what has happened
705 smtp_log_no_mail(void)
710 if (smtp_mailcmd_count > 0 || (log_extra_selector & LX_smtp_no_mail) == 0)
716 if (sender_host_authenticated != NULL)
718 s = string_append(s, &size, &ptr, 2, US" A=", sender_host_authenticated);
719 if (authenticated_id != NULL)
720 s = string_append(s, &size, &ptr, 2, US":", authenticated_id);
724 if ((log_extra_selector & LX_tls_cipher) != 0 && tls_cipher != NULL)
725 s = string_append(s, &size, &ptr, 2, US" X=", tls_cipher);
726 if ((log_extra_selector & LX_tls_certificate_verified) != 0 &&
728 s = string_append(s, &size, &ptr, 2, US" CV=",
729 tls_certificate_verified? "yes":"no");
730 if ((log_extra_selector & LX_tls_peerdn) != 0 && tls_peerdn != NULL)
731 s = string_append(s, &size, &ptr, 3, US" DN=\"", tls_peerdn, US"\"");
734 sep = (smtp_connection_had[SMTP_HBUFF_SIZE-1] != SCH_NONE)?
735 US" C=..." : US" C=";
736 for (i = smtp_ch_index; i < SMTP_HBUFF_SIZE; i++)
738 if (smtp_connection_had[i] != SCH_NONE)
740 s = string_append(s, &size, &ptr, 2, sep,
741 smtp_names[smtp_connection_had[i]]);
746 for (i = 0; i < smtp_ch_index; i++)
748 s = string_append(s, &size, &ptr, 2, sep, smtp_names[smtp_connection_had[i]]);
752 if (s != NULL) s[ptr] = 0; else s = US"";
753 log_write(0, LOG_MAIN, "no MAIL in SMTP connection from %s D=%s%s",
754 host_and_ident(FALSE),
755 readconf_printtime(time(NULL) - smtp_connection_start), s);
760 /*************************************************
761 * Check HELO line and set sender_helo_name *
762 *************************************************/
764 /* Check the format of a HELO line. The data for HELO/EHLO is supposed to be
765 the domain name of the sending host, or an ip literal in square brackets. The
766 arrgument is placed in sender_helo_name, which is in malloc store, because it
767 must persist over multiple incoming messages. If helo_accept_junk is set, this
768 host is permitted to send any old junk (needed for some broken hosts).
769 Otherwise, helo_allow_chars can be used for rogue characters in general
770 (typically people want to let in underscores).
773 s the data portion of the line (already past any white space)
775 Returns: TRUE or FALSE
779 check_helo(uschar *s)
782 uschar *end = s + Ustrlen(s);
783 BOOL yield = helo_accept_junk;
785 /* Discard any previous helo name */
787 if (sender_helo_name != NULL)
789 store_free(sender_helo_name);
790 sender_helo_name = NULL;
793 /* Skip tests if junk is permitted. */
797 /* Allow the new standard form for IPv6 address literals, namely,
798 [IPv6:....], and because someone is bound to use it, allow an equivalent
799 IPv4 form. Allow plain addresses as well. */
806 if (strncmpic(s, US"[IPv6:", 6) == 0)
807 yield = (string_is_ip_address(s+6, NULL) == 6);
808 else if (strncmpic(s, US"[IPv4:", 6) == 0)
809 yield = (string_is_ip_address(s+6, NULL) == 4);
811 yield = (string_is_ip_address(s+1, NULL) != 0);
816 /* Non-literals must be alpha, dot, hyphen, plus any non-valid chars
817 that have been configured (usually underscore - sigh). */
824 if (!isalnum(*s) && *s != '.' && *s != '-' &&
825 Ustrchr(helo_allow_chars, *s) == NULL)
835 /* Save argument if OK */
837 if (yield) sender_helo_name = string_copy_malloc(start);
845 /*************************************************
846 * Extract SMTP command option *
847 *************************************************/
849 /* This function picks the next option setting off the end of smtp_cmd_data. It
850 is called for MAIL FROM and RCPT TO commands, to pick off the optional ESMTP
851 things that can appear there.
854 name point this at the name
855 value point this at the data string
857 Returns: TRUE if found an option
861 extract_option(uschar **name, uschar **value)
864 uschar *v = smtp_cmd_data + Ustrlen(smtp_cmd_data) - 1;
865 while (isspace(*v)) v--;
868 while (v > smtp_cmd_data && *v != '=' && !isspace(*v)) v--;
869 if (*v != '=') return FALSE;
872 while(isalpha(n[-1])) n--;
874 if (n[-1] != ' ') return FALSE;
887 /*************************************************
888 * Reset for new message *
889 *************************************************/
891 /* This function is called whenever the SMTP session is reset from
892 within either of the setup functions.
894 Argument: the stacking pool storage reset point
899 smtp_reset(void *reset_point)
901 store_reset(reset_point);
902 recipients_list = NULL;
903 rcpt_count = rcpt_defer_count = rcpt_fail_count =
904 raw_recipients_count = recipients_count = recipients_list_max = 0;
905 message_linecount = 0;
907 acl_added_headers = NULL;
908 queue_only_policy = FALSE;
909 deliver_freeze = FALSE; /* Can be set by ACL */
910 freeze_tell = freeze_tell_config; /* Can be set by ACL */
911 fake_response = OK; /* Can be set by ACL */
912 #ifdef WITH_CONTENT_SCAN
913 no_mbox_unspool = FALSE; /* Can be set by ACL */
915 submission_mode = FALSE; /* Can be set by ACL */
916 suppress_local_fixups = FALSE; /* Can be set by ACL */
917 active_local_from_check = local_from_check; /* Can be set by ACL */
918 active_local_sender_retain = local_sender_retain; /* Can be set by ACL */
919 sender_address = NULL;
920 submission_name = NULL; /* Can be set by ACL */
921 raw_sender = NULL; /* After SMTP rewrite, before qualifying */
922 sender_address_unrewritten = NULL; /* Set only after verify rewrite */
923 sender_verified_list = NULL; /* No senders verified */
924 memset(sender_address_cache, 0, sizeof(sender_address_cache));
925 memset(sender_domain_cache, 0, sizeof(sender_domain_cache));
926 authenticated_sender = NULL;
927 #ifdef EXPERIMENTAL_BRIGHTMAIL
931 #ifdef EXPERIMENTAL_DOMAINKEYS
934 #ifdef EXPERIMENTAL_SPF
935 spf_header_comment = NULL;
938 spf_smtp_comment = NULL;
940 body_linecount = body_zerocount = 0;
942 sender_rate = sender_rate_limit = sender_rate_period = NULL;
943 ratelimiters_mail = NULL; /* Updated by ratelimit ACL condition */
944 /* Note that ratelimiters_conn persists across resets. */
946 /* Reset message ACL variables */
950 /* The message body variables use malloc store. They may be set if this is
951 not the first message in an SMTP session and the previous message caused them
952 to be referenced in an ACL. */
954 if (message_body != NULL)
956 store_free(message_body);
960 if (message_body_end != NULL)
962 store_free(message_body_end);
963 message_body_end = NULL;
966 /* Warning log messages are also saved in malloc store. They are saved to avoid
967 repetition in the same message, but it seems right to repeat them for different
970 while (acl_warn_logged != NULL)
972 string_item *this = acl_warn_logged;
973 acl_warn_logged = acl_warn_logged->next;
982 /*************************************************
983 * Initialize for incoming batched SMTP message *
984 *************************************************/
986 /* This function is called from smtp_setup_msg() in the case when
987 smtp_batched_input is true. This happens when -bS is used to pass a whole batch
988 of messages in one file with SMTP commands between them. All errors must be
989 reported by sending a message, and only MAIL FROM, RCPT TO, and DATA are
990 relevant. After an error on a sender, or an invalid recipient, the remainder
991 of the message is skipped. The value of received_protocol is already set.
994 Returns: > 0 message successfully started (reached DATA)
995 = 0 QUIT read or end of file reached
1000 smtp_setup_batch_msg(void)
1003 void *reset_point = store_get(0);
1005 /* Save the line count at the start of each transaction - single commands
1006 like HELO and RSET count as whole transactions. */
1008 bsmtp_transaction_linecount = receive_linecount;
1010 if ((receive_feof)()) return 0; /* Treat EOF as QUIT */
1012 smtp_reset(reset_point); /* Reset for start of message */
1014 /* Deal with SMTP commands. This loop is exited by setting done to a POSITIVE
1015 value. The values are 2 larger than the required yield of the function. */
1020 uschar *recipient = NULL;
1021 int start, end, sender_domain, recipient_domain;
1023 switch(smtp_read_command(FALSE))
1025 /* The HELO/EHLO commands set sender_address_helo if they have
1026 valid data; otherwise they are ignored, except that they do
1027 a reset of the state. */
1032 check_helo(smtp_cmd_data);
1036 smtp_reset(reset_point);
1037 bsmtp_transaction_linecount = receive_linecount;
1041 /* The MAIL FROM command requires an address as an operand. All we
1042 do here is to parse it for syntactic correctness. The form "<>" is
1043 a special case which converts into an empty string. The start/end
1044 pointers in the original are not used further for this address, as
1045 it is the canonical extracted address which is all that is kept. */
1048 if (sender_address != NULL)
1049 /* The function moan_smtp_batch() does not return. */
1050 moan_smtp_batch(smtp_cmd_buffer, "503 Sender already given");
1052 if (smtp_cmd_data[0] == 0)
1053 /* The function moan_smtp_batch() does not return. */
1054 moan_smtp_batch(smtp_cmd_buffer, "501 MAIL FROM must have an address operand");
1056 /* Reset to start of message */
1058 smtp_reset(reset_point);
1060 /* Apply SMTP rewrite */
1062 raw_sender = ((rewrite_existflags & rewrite_smtp) != 0)?
1063 rewrite_one(smtp_cmd_data, rewrite_smtp|rewrite_smtp_sender, NULL, FALSE,
1064 US"", global_rewrite_rules) : smtp_cmd_data;
1066 /* Extract the address; the TRUE flag allows <> as valid */
1069 parse_extract_address(raw_sender, &errmess, &start, &end, &sender_domain,
1072 if (raw_sender == NULL)
1073 /* The function moan_smtp_batch() does not return. */
1074 moan_smtp_batch(smtp_cmd_buffer, "501 %s", errmess);
1076 sender_address = string_copy(raw_sender);
1078 /* Qualify unqualified sender addresses if permitted to do so. */
1080 if (sender_domain == 0 && sender_address[0] != 0 && sender_address[0] != '@')
1082 if (allow_unqualified_sender)
1084 sender_address = rewrite_address_qualify(sender_address, FALSE);
1085 DEBUG(D_receive) debug_printf("unqualified address %s accepted "
1086 "and rewritten\n", raw_sender);
1088 /* The function moan_smtp_batch() does not return. */
1089 else moan_smtp_batch(smtp_cmd_buffer, "501 sender address must contain "
1095 /* The RCPT TO command requires an address as an operand. All we do
1096 here is to parse it for syntactic correctness. There may be any number
1097 of RCPT TO commands, specifying multiple senders. We build them all into
1098 a data structure that is in argc/argv format. The start/end values
1099 given by parse_extract_address are not used, as we keep only the
1100 extracted address. */
1103 if (sender_address == NULL)
1104 /* The function moan_smtp_batch() does not return. */
1105 moan_smtp_batch(smtp_cmd_buffer, "503 No sender yet given");
1107 if (smtp_cmd_data[0] == 0)
1108 /* The function moan_smtp_batch() does not return. */
1109 moan_smtp_batch(smtp_cmd_buffer, "501 RCPT TO must have an address operand");
1111 /* Check maximum number allowed */
1113 if (recipients_max > 0 && recipients_count + 1 > recipients_max)
1114 /* The function moan_smtp_batch() does not return. */
1115 moan_smtp_batch(smtp_cmd_buffer, "%s too many recipients",
1116 recipients_max_reject? "552": "452");
1118 /* Apply SMTP rewrite, then extract address. Don't allow "<>" as a
1119 recipient address */
1121 recipient = ((rewrite_existflags & rewrite_smtp) != 0)?
1122 rewrite_one(smtp_cmd_data, rewrite_smtp, NULL, FALSE, US"",
1123 global_rewrite_rules) : smtp_cmd_data;
1125 /* rfc821_domains = TRUE; << no longer needed */
1126 recipient = parse_extract_address(recipient, &errmess, &start, &end,
1127 &recipient_domain, FALSE);
1128 /* rfc821_domains = FALSE; << no longer needed */
1130 if (recipient == NULL)
1131 /* The function moan_smtp_batch() does not return. */
1132 moan_smtp_batch(smtp_cmd_buffer, "501 %s", errmess);
1134 /* If the recipient address is unqualified, qualify it if permitted. Then
1135 add it to the list of recipients. */
1137 if (recipient_domain == 0)
1139 if (allow_unqualified_recipient)
1141 DEBUG(D_receive) debug_printf("unqualified address %s accepted\n",
1143 recipient = rewrite_address_qualify(recipient, TRUE);
1145 /* The function moan_smtp_batch() does not return. */
1146 else moan_smtp_batch(smtp_cmd_buffer, "501 recipient address must contain "
1149 receive_add_recipient(recipient, -1);
1153 /* The DATA command is legal only if it follows successful MAIL FROM
1154 and RCPT TO commands. This function is complete when a valid DATA
1155 command is encountered. */
1158 if (sender_address == NULL || recipients_count <= 0)
1160 /* The function moan_smtp_batch() does not return. */
1161 if (sender_address == NULL)
1162 moan_smtp_batch(smtp_cmd_buffer,
1163 "503 MAIL FROM:<sender> command must precede DATA");
1165 moan_smtp_batch(smtp_cmd_buffer,
1166 "503 RCPT TO:<recipient> must precede DATA");
1170 done = 3; /* DATA successfully achieved */
1171 message_ended = END_NOTENDED; /* Indicate in middle of message */
1176 /* The VRFY, EXPN, HELP, ETRN, and NOOP commands are ignored. */
1183 bsmtp_transaction_linecount = receive_linecount;
1194 /* The function moan_smtp_batch() does not return. */
1195 moan_smtp_batch(smtp_cmd_buffer, "501 Unexpected argument data");
1200 /* The function moan_smtp_batch() does not return. */
1201 moan_smtp_batch(smtp_cmd_buffer, "501 Unexpected NULL in SMTP command");
1206 /* The function moan_smtp_batch() does not return. */
1207 moan_smtp_batch(smtp_cmd_buffer, "500 Command unrecognized");
1212 return done - 2; /* Convert yield values */
1218 /*************************************************
1219 * Start an SMTP session *
1220 *************************************************/
1222 /* This function is called at the start of an SMTP session. Thereafter,
1223 smtp_setup_msg() is called to initiate each separate message. This
1224 function does host-specific testing, and outputs the banner line.
1227 Returns: FALSE if the session can not continue; something has
1228 gone wrong, or the connection to the host is blocked
1232 smtp_start_session(void)
1236 uschar *user_msg, *log_msg;
1240 smtp_connection_start = time(NULL);
1241 for (smtp_ch_index = 0; smtp_ch_index < SMTP_HBUFF_SIZE; smtp_ch_index++)
1242 smtp_connection_had[smtp_ch_index] = SCH_NONE;
1245 /* Default values for certain variables */
1247 helo_seen = esmtp = helo_accept_junk = FALSE;
1248 smtp_mailcmd_count = 0;
1249 count_nonmail = TRUE_UNSET;
1250 synprot_error_count = unknown_command_count = nonmail_command_count = 0;
1251 smtp_delay_mail = smtp_rlm_base;
1252 auth_advertised = FALSE;
1253 pipelining_advertised = FALSE;
1254 pipelining_enable = TRUE;
1255 sync_cmd_limit = NON_SYNC_CMD_NON_PIPELINING;
1257 memset(sender_host_cache, 0, sizeof(sender_host_cache));
1259 /* If receiving by -bs from a trusted user, or testing with -bh, we allow
1260 authentication settings from -oMaa to remain in force. */
1262 if (!host_checking && !sender_host_notsocket) sender_host_authenticated = NULL;
1263 authenticated_by = NULL;
1266 tls_cipher = tls_peerdn = NULL;
1267 tls_advertised = FALSE;
1270 /* Reset ACL connection variables */
1274 /* Allow for trailing 0 in the command and data buffers. */
1276 smtp_cmd_buffer = (uschar *)malloc(2*smtp_cmd_buffer_size + 2);
1277 if (smtp_cmd_buffer == NULL)
1278 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1279 "malloc() failed for SMTP command buffer");
1280 smtp_data_buffer = smtp_cmd_buffer + smtp_cmd_buffer_size + 1;
1282 /* For batched input, the protocol setting can be overridden from the
1283 command line by a trusted caller. */
1285 if (smtp_batched_input)
1287 if (received_protocol == NULL) received_protocol = US"local-bsmtp";
1290 /* For non-batched SMTP input, the protocol setting is forced here. It will be
1291 reset later if any of EHLO/AUTH/STARTTLS are received. */
1295 protocols[pnormal] + ((sender_host_address != NULL)? pnlocal : 0);
1297 /* Set up the buffer for inputting using direct read() calls, and arrange to
1298 call the local functions instead of the standard C ones. */
1300 smtp_inbuffer = (uschar *)malloc(in_buffer_size);
1301 if (smtp_inbuffer == NULL)
1302 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "malloc() failed for SMTP input buffer");
1303 receive_getc = smtp_getc;
1304 receive_ungetc = smtp_ungetc;
1305 receive_feof = smtp_feof;
1306 receive_ferror = smtp_ferror;
1307 smtp_inptr = smtp_inend = smtp_inbuffer;
1308 smtp_had_eof = smtp_had_error = 0;
1310 /* Set up the message size limit; this may be host-specific */
1312 thismessage_size_limit = expand_string_integer(message_size_limit, TRUE);
1313 if (expand_string_message != NULL)
1315 if (thismessage_size_limit == -1)
1316 log_write(0, LOG_MAIN|LOG_PANIC, "unable to expand message_size_limit: "
1317 "%s", expand_string_message);
1319 log_write(0, LOG_MAIN|LOG_PANIC, "invalid message_size_limit: "
1320 "%s", expand_string_message);
1321 smtp_closedown(US"Temporary local problem - please try later");
1325 /* When a message is input locally via the -bs or -bS options, sender_host_
1326 unknown is set unless -oMa was used to force an IP address, in which case it
1327 is checked like a real remote connection. When -bs is used from inetd, this
1328 flag is not set, causing the sending host to be checked. The code that deals
1329 with IP source routing (if configured) is never required for -bs or -bS and
1330 the flag sender_host_notsocket is used to suppress it.
1332 If smtp_accept_max and smtp_accept_reserve are set, keep some connections in
1333 reserve for certain hosts and/or networks. */
1335 if (!sender_host_unknown)
1338 BOOL reserved_host = FALSE;
1340 /* Look up IP options (source routing info) on the socket if this is not an
1341 -oMa "host", and if any are found, log them and drop the connection.
1343 Linux (and others now, see below) is different to everyone else, so there
1344 has to be some conditional compilation here. Versions of Linux before 2.1.15
1345 used a structure whose name was "options". Somebody finally realized that
1346 this name was silly, and it got changed to "ip_options". I use the
1347 newer name here, but there is a fudge in the script that sets up os.h
1348 to define a macro in older Linux systems.
1350 Sigh. Linux is a fast-moving target. Another generation of Linux uses
1351 glibc 2, which has chosen ip_opts for the structure name. This is now
1352 really a glibc thing rather than a Linux thing, so the condition name
1353 has been changed to reflect this. It is relevant also to GNU/Hurd.
1355 Mac OS 10.x (Darwin) is like the later glibc versions, but without the
1356 setting of the __GLIBC__ macro, so we can't detect it automatically. There's
1357 a special macro defined in the os.h file.
1359 Some DGUX versions on older hardware appear not to support IP options at
1360 all, so there is now a general macro which can be set to cut out this
1363 How to do this properly in IPv6 is not yet known. */
1365 #if !HAVE_IPV6 && !defined(NO_IP_OPTIONS)
1367 #ifdef GLIBC_IP_OPTIONS
1368 #if (!defined __GLIBC__) || (__GLIBC__ < 2)
1373 #elif defined DARWIN_IP_OPTIONS
1379 if (!host_checking && !sender_host_notsocket)
1382 EXIM_SOCKLEN_T optlen = sizeof(struct ip_options) + MAX_IPOPTLEN;
1383 struct ip_options *ipopt = store_get(optlen);
1385 struct ip_opts ipoptblock;
1386 struct ip_opts *ipopt = &ipoptblock;
1387 EXIM_SOCKLEN_T optlen = sizeof(ipoptblock);
1389 struct ipoption ipoptblock;
1390 struct ipoption *ipopt = &ipoptblock;
1391 EXIM_SOCKLEN_T optlen = sizeof(ipoptblock);
1394 /* Occasional genuine failures of getsockopt() have been seen - for
1395 example, "reset by peer". Therefore, just log and give up on this
1396 call, unless the error is ENOPROTOOPT. This error is given by systems
1397 that have the interfaces but not the mechanism - e.g. GNU/Hurd at the time
1398 of writing. So for that error, carry on - we just can't do an IP options
1401 DEBUG(D_receive) debug_printf("checking for IP options\n");
1403 if (getsockopt(fileno(smtp_out), IPPROTO_IP, IP_OPTIONS, (uschar *)(ipopt),
1406 if (errno != ENOPROTOOPT)
1408 log_write(0, LOG_MAIN, "getsockopt() failed from %s: %s",
1409 host_and_ident(FALSE), strerror(errno));
1410 smtp_printf("451 SMTP service not available\r\n");
1415 /* Deal with any IP options that are set. On the systems I have looked at,
1416 the value of MAX_IPOPTLEN has been 40, meaning that there should never be
1417 more logging data than will fit in big_buffer. Nevertheless, after somebody
1418 questioned this code, I've added in some paranoid checking. */
1420 else if (optlen > 0)
1422 uschar *p = big_buffer;
1423 uschar *pend = big_buffer + big_buffer_size;
1424 uschar *opt, *adptr;
1426 struct in_addr addr;
1429 uschar *optstart = (uschar *)(ipopt->__data);
1431 uschar *optstart = (uschar *)(ipopt->ip_opts);
1433 uschar *optstart = (uschar *)(ipopt->ipopt_list);
1436 DEBUG(D_receive) debug_printf("IP options exist\n");
1438 Ustrcpy(p, "IP options on incoming call:");
1441 for (opt = optstart; opt != NULL &&
1442 opt < (uschar *)(ipopt) + optlen;)
1456 if (!string_format(p, pend-p, " %s [@%s",
1457 (*opt == IPOPT_SSRR)? "SSRR" : "LSRR",
1459 inet_ntoa(*((struct in_addr *)(&(ipopt->faddr))))))
1461 inet_ntoa(ipopt->ip_dst)))
1463 inet_ntoa(ipopt->ipopt_dst)))
1471 optcount = (opt[1] - 3) / sizeof(struct in_addr);
1473 while (optcount-- > 0)
1475 memcpy(&addr, adptr, sizeof(addr));
1476 if (!string_format(p, pend - p - 1, "%s%s",
1477 (optcount == 0)? ":" : "@", inet_ntoa(addr)))
1483 adptr += sizeof(struct in_addr);
1492 if (pend - p < 4 + 3*opt[1]) { opt = NULL; break; }
1495 for (i = 0; i < opt[1]; i++)
1497 sprintf(CS p, "%2.2x ", opt[i]);
1508 log_write(0, LOG_MAIN, "%s", big_buffer);
1510 /* Refuse any call with IP options. This is what tcpwrappers 7.5 does. */
1512 log_write(0, LOG_MAIN|LOG_REJECT,
1513 "connection from %s refused (IP options)", host_and_ident(FALSE));
1515 smtp_printf("554 SMTP service not available\r\n");
1519 /* Length of options = 0 => there are no options */
1521 else DEBUG(D_receive) debug_printf("no IP options found\n");
1523 #endif /* HAVE_IPV6 && !defined(NO_IP_OPTIONS) */
1525 /* Set keep-alive in socket options. The option is on by default. This
1526 setting is an attempt to get rid of some hanging connections that stick in
1527 read() when the remote end (usually a dialup) goes away. */
1529 if (smtp_accept_keepalive && !sender_host_notsocket)
1530 ip_keepalive(fileno(smtp_out), sender_host_address, FALSE);
1532 /* If the current host matches host_lookup, set the name by doing a
1533 reverse lookup. On failure, sender_host_name will be NULL and
1534 host_lookup_failed will be TRUE. This may or may not be serious - optional
1537 if (verify_check_host(&host_lookup) == OK)
1539 (void)host_name_lookup();
1540 host_build_sender_fullhost();
1543 /* Delay this until we have the full name, if it is looked up. */
1545 set_process_info("handling incoming connection from %s",
1546 host_and_ident(FALSE));
1548 /* Start up TLS if tls_on_connect is set. This is for supporting the legacy
1549 smtps port for use with older style SSL MTAs. */
1552 if (tls_on_connect &&
1553 tls_server_start(tls_require_ciphers,
1554 gnutls_require_mac, gnutls_require_kx, gnutls_require_proto) != OK)
1558 /* Test for explicit connection rejection */
1560 if (verify_check_host(&host_reject_connection) == OK)
1562 log_write(L_connection_reject, LOG_MAIN|LOG_REJECT, "refused connection "
1563 "from %s (host_reject_connection)", host_and_ident(FALSE));
1564 smtp_printf("554 SMTP service not available\r\n");
1568 /* Test with TCP Wrappers if so configured. There is a problem in that
1569 hosts_ctl() returns 0 (deny) under a number of system failure circumstances,
1570 such as disks dying. In these cases, it is desirable to reject with a 4xx
1571 error instead of a 5xx error. There isn't a "right" way to detect such
1572 problems. The following kludge is used: errno is zeroed before calling
1573 hosts_ctl(). If the result is "reject", a 5xx error is given only if the
1574 value of errno is 0 or ENOENT (which happens if /etc/hosts.{allow,deny} does
1577 #ifdef USE_TCP_WRAPPERS
1579 if (!hosts_ctl("exim",
1580 (sender_host_name == NULL)? STRING_UNKNOWN : CS sender_host_name,
1581 (sender_host_address == NULL)? STRING_UNKNOWN : CS sender_host_address,
1582 (sender_ident == NULL)? STRING_UNKNOWN : CS sender_ident))
1584 if (errno == 0 || errno == ENOENT)
1586 HDEBUG(D_receive) debug_printf("tcp wrappers rejection\n");
1587 log_write(L_connection_reject,
1588 LOG_MAIN|LOG_REJECT, "refused connection from %s "
1589 "(tcp wrappers)", host_and_ident(FALSE));
1590 smtp_printf("554 SMTP service not available\r\n");
1594 int save_errno = errno;
1595 HDEBUG(D_receive) debug_printf("tcp wrappers rejected with unexpected "
1596 "errno value %d\n", save_errno);
1597 log_write(L_connection_reject,
1598 LOG_MAIN|LOG_REJECT, "temporarily refused connection from %s "
1599 "(tcp wrappers errno=%d)", host_and_ident(FALSE), save_errno);
1600 smtp_printf("451 Temporary local problem - please try later\r\n");
1606 /* Check for reserved slots. The value of smtp_accept_count has already been
1607 incremented to include this process. */
1609 if (smtp_accept_max > 0 &&
1610 smtp_accept_count > smtp_accept_max - smtp_accept_reserve)
1612 if ((rc = verify_check_host(&smtp_reserve_hosts)) != OK)
1614 log_write(L_connection_reject,
1615 LOG_MAIN, "temporarily refused connection from %s: not in "
1616 "reserve list: connected=%d max=%d reserve=%d%s",
1617 host_and_ident(FALSE), smtp_accept_count - 1, smtp_accept_max,
1618 smtp_accept_reserve, (rc == DEFER)? " (lookup deferred)" : "");
1619 smtp_printf("421 %s: Too many concurrent SMTP connections; "
1620 "please try again later\r\n", smtp_active_hostname);
1623 reserved_host = TRUE;
1626 /* If a load level above which only messages from reserved hosts are
1627 accepted is set, check the load. For incoming calls via the daemon, the
1628 check is done in the superior process if there are no reserved hosts, to
1629 save a fork. In all cases, the load average will already be available
1630 in a global variable at this point. */
1632 if (smtp_load_reserve >= 0 &&
1633 load_average > smtp_load_reserve &&
1635 verify_check_host(&smtp_reserve_hosts) != OK)
1637 log_write(L_connection_reject,
1638 LOG_MAIN, "temporarily refused connection from %s: not in "
1639 "reserve list and load average = %.2f", host_and_ident(FALSE),
1640 (double)load_average/1000.0);
1641 smtp_printf("421 %s: Too much load; please try again later\r\n",
1642 smtp_active_hostname);
1646 /* Determine whether unqualified senders or recipients are permitted
1647 for this host. Unfortunately, we have to do this every time, in order to
1648 set the flags so that they can be inspected when considering qualifying
1649 addresses in the headers. For a site that permits no qualification, this
1650 won't take long, however. */
1652 allow_unqualified_sender =
1653 verify_check_host(&sender_unqualified_hosts) == OK;
1655 allow_unqualified_recipient =
1656 verify_check_host(&recipient_unqualified_hosts) == OK;
1658 /* Determine whether HELO/EHLO is required for this host. The requirement
1659 can be hard or soft. */
1661 helo_required = verify_check_host(&helo_verify_hosts) == OK;
1663 helo_verify = verify_check_host(&helo_try_verify_hosts) == OK;
1665 /* Determine whether this hosts is permitted to send syntactic junk
1666 after a HELO or EHLO command. */
1668 helo_accept_junk = verify_check_host(&helo_accept_junk_hosts) == OK;
1671 /* For batch SMTP input we are now done. */
1673 if (smtp_batched_input) return TRUE;
1675 /* Run the ACL if it exists */
1678 if (acl_smtp_connect != NULL)
1681 rc = acl_check(ACL_WHERE_CONNECT, NULL, acl_smtp_connect, &user_msg,
1685 (void)smtp_handle_acl_fail(ACL_WHERE_CONNECT, rc, user_msg, log_msg);
1690 /* Output the initial message for a two-way SMTP connection. It may contain
1691 newlines, which then cause a multi-line response to be given. */
1693 code = US"220"; /* Default status code */
1694 esc = US""; /* Default extended status code */
1695 esclen = 0; /* Length of esc */
1697 if (user_msg == NULL)
1699 s = expand_string(smtp_banner);
1701 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Expansion of \"%s\" (smtp_banner) "
1702 "failed: %s", smtp_banner, expand_string_message);
1708 smtp_message_code(&code, &codelen, &s, NULL);
1712 esclen = codelen - 4;
1716 /* Remove any terminating newlines; might as well remove trailing space too */
1719 while (p > s && isspace(p[-1])) p--;
1722 /* It seems that CC:Mail is braindead, and assumes that the greeting message
1723 is all contained in a single IP packet. The original code wrote out the
1724 greeting using several calls to fprint/fputc, and on busy servers this could
1725 cause it to be split over more than one packet - which caused CC:Mail to fall
1726 over when it got the second part of the greeting after sending its first
1727 command. Sigh. To try to avoid this, build the complete greeting message
1728 first, and output it in one fell swoop. This gives a better chance of it
1729 ending up as a single packet. */
1731 ss = store_get(size);
1735 do /* At least once, in case we have an empty string */
1738 uschar *linebreak = Ustrchr(p, '\n');
1739 ss = string_cat(ss, &size, &ptr, code, 3);
1740 if (linebreak == NULL)
1743 ss = string_cat(ss, &size, &ptr, US" ", 1);
1747 len = linebreak - p;
1748 ss = string_cat(ss, &size, &ptr, US"-", 1);
1750 ss = string_cat(ss, &size, &ptr, esc, esclen);
1751 ss = string_cat(ss, &size, &ptr, p, len);
1752 ss = string_cat(ss, &size, &ptr, US"\r\n", 2);
1754 if (linebreak != NULL) p++;
1758 ss[ptr] = 0; /* string_cat leaves room for this */
1760 /* Before we write the banner, check that there is no input pending, unless
1761 this synchronisation check is disabled. */
1763 if (smtp_enforce_sync && sender_host_address != NULL && !sender_host_notsocket)
1766 struct timeval tzero;
1770 FD_SET(fileno(smtp_in), &fds);
1771 if (select(fileno(smtp_in) + 1, (SELECT_ARG2_TYPE *)&fds, NULL, NULL,
1774 int rc = read(fileno(smtp_in), smtp_inbuffer, in_buffer_size);
1777 if (rc > 150) rc = 150;
1778 smtp_inbuffer[rc] = 0;
1779 log_write(0, LOG_MAIN|LOG_REJECT, "SMTP protocol "
1780 "synchronization error (input sent without waiting for greeting): "
1781 "rejected connection from %s input=\"%s\"", host_and_ident(TRUE),
1782 string_printing(smtp_inbuffer));
1783 smtp_printf("554 SMTP synchronization error\r\n");
1789 /* Now output the banner */
1791 smtp_printf("%s", ss);
1799 /*************************************************
1800 * Handle SMTP syntax and protocol errors *
1801 *************************************************/
1803 /* Write to the log for SMTP syntax errors in incoming commands, if configured
1804 to do so. Then transmit the error response. The return value depends on the
1805 number of syntax and protocol errors in this SMTP session.
1808 type error type, given as a log flag bit
1809 code response code; <= 0 means don't send a response
1810 data data to reflect in the response (can be NULL)
1811 errmess the error message
1813 Returns: -1 limit of syntax/protocol errors NOT exceeded
1814 +1 limit of syntax/protocol errors IS exceeded
1816 These values fit in with the values of the "done" variable in the main
1817 processing loop in smtp_setup_msg(). */
1820 synprot_error(int type, int code, uschar *data, uschar *errmess)
1824 log_write(type, LOG_MAIN, "SMTP %s error in \"%s\" %s %s",
1825 (type == L_smtp_syntax_error)? "syntax" : "protocol",
1826 string_printing(smtp_cmd_buffer), host_and_ident(TRUE), errmess);
1828 if (++synprot_error_count > smtp_max_synprot_errors)
1831 log_write(0, LOG_MAIN|LOG_REJECT, "SMTP call from %s dropped: too many "
1832 "syntax or protocol errors (last command was \"%s\")",
1833 host_and_ident(FALSE), smtp_cmd_buffer);
1838 smtp_printf("%d%c%s%s%s\r\n", code, (yield == 1)? '-' : ' ',
1839 (data == NULL)? US"" : data, (data == NULL)? US"" : US": ", errmess);
1841 smtp_printf("%d Too many syntax or protocol errors\r\n", code);
1850 /*************************************************
1851 * Log incomplete transactions *
1852 *************************************************/
1854 /* This function is called after a transaction has been aborted by RSET, QUIT,
1855 connection drops or other errors. It logs the envelope information received
1856 so far in order to preserve address verification attempts.
1858 Argument: string to indicate what aborted the transaction
1863 incomplete_transaction_log(uschar *what)
1865 if (sender_address == NULL || /* No transaction in progress */
1866 (log_write_selector & L_smtp_incomplete_transaction) == 0 /* Not logging */
1869 /* Build list of recipients for logging */
1871 if (recipients_count > 0)
1874 raw_recipients = store_get(recipients_count * sizeof(uschar *));
1875 for (i = 0; i < recipients_count; i++)
1876 raw_recipients[i] = recipients_list[i].address;
1877 raw_recipients_count = recipients_count;
1880 log_write(L_smtp_incomplete_transaction, LOG_MAIN|LOG_SENDER|LOG_RECIPIENTS,
1881 "%s incomplete transaction (%s)", host_and_ident(TRUE), what);
1887 /*************************************************
1888 * Send SMTP response, possibly multiline *
1889 *************************************************/
1891 /* There are, it seems, broken clients out there that cannot handle multiline
1892 responses. If no_multiline_responses is TRUE (it can be set from an ACL), we
1893 output nothing for non-final calls, and only the first line for anything else.
1896 code SMTP code, may involve extended status codes
1897 codelen length of smtp code; if > 4 there's an ESC
1898 final FALSE if the last line isn't the final line
1899 msg message text, possibly containing newlines
1905 smtp_respond(uschar* code, int codelen, BOOL final, uschar *msg)
1910 if (!final && no_multiline_responses) return;
1915 esclen = codelen - 4;
1920 uschar *nl = Ustrchr(msg, '\n');
1923 smtp_printf("%.3s%c%.*s%s\r\n", code, final? ' ':'-', esclen, esc, msg);
1926 else if (nl[1] == 0 || no_multiline_responses)
1928 smtp_printf("%.3s%c%.*s%.*s\r\n", code, final? ' ':'-', esclen, esc,
1929 (int)(nl - msg), msg);
1934 smtp_printf("%.3s-%.*s%.*s\r\n", code, esclen, esc, (int)(nl - msg), msg);
1936 while (isspace(*msg)) msg++;
1944 /*************************************************
1945 * Parse user SMTP message *
1946 *************************************************/
1948 /* This function allows for user messages overriding the response code details
1949 by providing a suitable response code string at the start of the message
1950 user_msg. Check the message for starting with a response code and optionally an
1951 extended status code. If found, check that the first digit is valid, and if so,
1952 change the code pointer and length to use the replacement. An invalid code
1953 causes a panic log; in this case, if the log messages is the same as the user
1954 message, we must also adjust the value of the log message to show the code that
1955 is actually going to be used (the original one).
1957 This function is global because it is called from receive.c as well as within
1960 Note that the code length returned includes the terminating whitespace
1961 character, which is always included in the regex match.
1964 code SMTP code, may involve extended status codes
1965 codelen length of smtp code; if > 4 there's an ESC
1967 log_msg optional log message, to be adjusted with the new SMTP code
1973 smtp_message_code(uschar **code, int *codelen, uschar **msg, uschar **log_msg)
1978 if (msg == NULL || *msg == NULL) return;
1980 n = pcre_exec(regex_smtp_code, NULL, CS *msg, Ustrlen(*msg), 0,
1981 PCRE_EOPT, ovector, sizeof(ovector)/sizeof(int));
1984 if ((*msg)[0] != (*code)[0])
1986 log_write(0, LOG_MAIN|LOG_PANIC, "configured error code starts with "
1987 "incorrect digit (expected %c) in \"%s\"", (*code)[0], *msg);
1988 if (log_msg != NULL && *log_msg == *msg)
1989 *log_msg = string_sprintf("%s %s", *code, *log_msg + ovector[1]);
1994 *codelen = ovector[1]; /* Includes final space */
1996 *msg += ovector[1]; /* Chop the code off the message */
2003 /*************************************************
2004 * Handle an ACL failure *
2005 *************************************************/
2007 /* This function is called when acl_check() fails. As well as calls from within
2008 this module, it is called from receive.c for an ACL after DATA. It sorts out
2009 logging the incident, and sets up the error response. A message containing
2010 newlines is turned into a multiline SMTP response, but for logging, only the
2013 There's a table of default permanent failure response codes to use in
2014 globals.c, along with the table of names. VFRY is special. Despite RFC1123 it
2015 defaults disabled in Exim. However, discussion in connection with RFC 821bis
2016 (aka RFC 2821) has concluded that the response should be 252 in the disabled
2017 state, because there are broken clients that try VRFY before RCPT. A 5xx
2018 response should be given only when the address is positively known to be
2019 undeliverable. Sigh. Also, for ETRN, 458 is given on refusal, and for AUTH,
2022 From Exim 4.63, it is possible to override the response code details by
2023 providing a suitable response code string at the start of the message provided
2024 in user_msg. The code's first digit is checked for validity.
2027 where where the ACL was called from
2029 user_msg a message that can be included in an SMTP response
2030 log_msg a message for logging
2032 Returns: 0 in most cases
2033 2 if the failure code was FAIL_DROP, in which case the
2034 SMTP connection should be dropped (this value fits with the
2035 "done" variable in smtp_setup_msg() below)
2039 smtp_handle_acl_fail(int where, int rc, uschar *user_msg, uschar *log_msg)
2041 BOOL drop = rc == FAIL_DROP;
2045 uschar *sender_info = US"";
2047 #ifdef WITH_CONTENT_SCAN
2048 (where == ACL_WHERE_MIME)? US"during MIME ACL checks" :
2050 (where == ACL_WHERE_PREDATA)? US"DATA" :
2051 (where == ACL_WHERE_DATA)? US"after DATA" :
2052 (smtp_cmd_data == NULL)?
2053 string_sprintf("%s in \"connect\" ACL", acl_wherenames[where]) :
2054 string_sprintf("%s %s", acl_wherenames[where], smtp_cmd_data);
2056 if (drop) rc = FAIL;
2058 /* Set the default SMTP code, and allow a user message to change it. */
2060 smtp_code = (rc != FAIL)? US"451" : acl_wherecodes[where];
2061 smtp_message_code(&smtp_code, &codelen, &user_msg, &log_msg);
2063 /* We used to have sender_address here; however, there was a bug that was not
2064 updating sender_address after a rewrite during a verify. When this bug was
2065 fixed, sender_address at this point became the rewritten address. I'm not sure
2066 this is what should be logged, so I've changed to logging the unrewritten
2067 address to retain backward compatibility. */
2069 #ifndef WITH_CONTENT_SCAN
2070 if (where == ACL_WHERE_RCPT || where == ACL_WHERE_DATA)
2072 if (where == ACL_WHERE_RCPT || where == ACL_WHERE_DATA || where == ACL_WHERE_MIME)
2075 sender_info = string_sprintf("F=<%s> ", (sender_address_unrewritten != NULL)?
2076 sender_address_unrewritten : sender_address);
2079 /* If there's been a sender verification failure with a specific message, and
2080 we have not sent a response about it yet, do so now, as a preliminary line for
2081 failures, but not defers. However, always log it for defer, and log it for fail
2082 unless the sender_verify_fail log selector has been turned off. */
2084 if (sender_verified_failed != NULL &&
2085 !testflag(sender_verified_failed, af_sverify_told))
2087 setflag(sender_verified_failed, af_sverify_told);
2089 if (rc != FAIL || (log_extra_selector & LX_sender_verify_fail) != 0)
2090 log_write(0, LOG_MAIN|LOG_REJECT, "%s sender verify %s for <%s>%s",
2091 host_and_ident(TRUE),
2092 ((sender_verified_failed->special_action & 255) == DEFER)? "defer":"fail",
2093 sender_verified_failed->address,
2094 (sender_verified_failed->message == NULL)? US"" :
2095 string_sprintf(": %s", sender_verified_failed->message));
2097 if (rc == FAIL && sender_verified_failed->user_message != NULL)
2098 smtp_respond(smtp_code, codelen, FALSE, string_sprintf(
2099 testflag(sender_verified_failed, af_verify_pmfail)?
2100 "Postmaster verification failed while checking <%s>\n%s\n"
2101 "Several RFCs state that you are required to have a postmaster\n"
2102 "mailbox for each mail domain. This host does not accept mail\n"
2103 "from domains whose servers reject the postmaster address."
2105 testflag(sender_verified_failed, af_verify_nsfail)?
2106 "Callback setup failed while verifying <%s>\n%s\n"
2107 "The initial connection, or a HELO or MAIL FROM:<> command was\n"
2108 "rejected. Refusing MAIL FROM:<> does not help fight spam, disregards\n"
2109 "RFC requirements, and stops you from receiving standard bounce\n"
2110 "messages. This host does not accept mail from domains whose servers\n"
2113 "Verification failed for <%s>\n%s",
2114 sender_verified_failed->address,
2115 sender_verified_failed->user_message));
2118 /* Sort out text for logging */
2120 log_msg = (log_msg == NULL)? US"" : string_sprintf(": %s", log_msg);
2121 lognl = Ustrchr(log_msg, '\n');
2122 if (lognl != NULL) *lognl = 0;
2124 /* Send permanent failure response to the command, but the code used isn't
2125 always a 5xx one - see comments at the start of this function. If the original
2126 rc was FAIL_DROP we drop the connection and yield 2. */
2128 if (rc == FAIL) smtp_respond(smtp_code, codelen, TRUE, (user_msg == NULL)?
2129 US"Administrative prohibition" : user_msg);
2131 /* Send temporary failure response to the command. Don't give any details,
2132 unless acl_temp_details is set. This is TRUE for a callout defer, a "defer"
2133 verb, and for a header verify when smtp_return_error_details is set.
2135 This conditional logic is all somewhat of a mess because of the odd
2136 interactions between temp_details and return_error_details. One day it should
2137 be re-implemented in a tidier fashion. */
2141 if (acl_temp_details && user_msg != NULL)
2143 if (smtp_return_error_details &&
2144 sender_verified_failed != NULL &&
2145 sender_verified_failed->message != NULL)
2147 smtp_respond(smtp_code, codelen, FALSE, sender_verified_failed->message);
2149 smtp_respond(smtp_code, codelen, TRUE, user_msg);
2152 smtp_respond(smtp_code, codelen, TRUE,
2153 US"Temporary local problem - please try later");
2156 /* Log the incident to the logs that are specified by log_reject_target
2157 (default main, reject). This can be empty to suppress logging of rejections. If
2158 the connection is not forcibly to be dropped, return 0. Otherwise, log why it
2159 is closing if required and return 2. */
2161 if (log_reject_target != 0)
2162 log_write(0, log_reject_target, "%s %s%srejected %s%s",
2163 host_and_ident(TRUE),
2164 sender_info, (rc == FAIL)? US"" : US"temporarily ", what, log_msg);
2166 if (!drop) return 0;
2168 log_write(L_smtp_connection, LOG_MAIN, "%s closed by DROP in ACL",
2169 smtp_get_connection_info());
2176 /*************************************************
2177 * Verify HELO argument *
2178 *************************************************/
2180 /* This function is called if helo_verify_hosts or helo_try_verify_hosts is
2181 matched. It is also called from ACL processing if verify = helo is used and
2182 verification was not previously tried (i.e. helo_try_verify_hosts was not
2183 matched). The result of its processing is to set helo_verified and
2184 helo_verify_failed. These variables should both be FALSE for this function to
2187 Note that EHLO/HELO is legitimately allowed to quote an address literal. Allow
2188 for IPv6 ::ffff: literals.
2191 Returns: TRUE if testing was completed;
2192 FALSE on a temporary failure
2196 smtp_verify_helo(void)
2200 HDEBUG(D_receive) debug_printf("verifying EHLO/HELO argument \"%s\"\n",
2203 if (sender_helo_name == NULL)
2205 HDEBUG(D_receive) debug_printf("no EHLO/HELO command was issued\n");
2208 /* Deal with the case of -bs without an IP address */
2210 else if (sender_host_address == NULL)
2212 HDEBUG(D_receive) debug_printf("no client IP address: assume success\n");
2213 helo_verified = TRUE;
2216 /* Deal with the more common case when there is a sending IP address */
2218 else if (sender_helo_name[0] == '[')
2220 helo_verified = Ustrncmp(sender_helo_name+1, sender_host_address,
2221 Ustrlen(sender_host_address)) == 0;
2226 if (strncmpic(sender_host_address, US"::ffff:", 7) == 0)
2227 helo_verified = Ustrncmp(sender_helo_name + 1,
2228 sender_host_address + 7, Ustrlen(sender_host_address) - 7) == 0;
2233 { if (helo_verified) debug_printf("matched host address\n"); }
2236 /* Do a reverse lookup if one hasn't already given a positive or negative
2237 response. If that fails, or the name doesn't match, try checking with a forward
2242 if (sender_host_name == NULL && !host_lookup_failed)
2243 yield = host_name_lookup() != DEFER;
2245 /* If a host name is known, check it and all its aliases. */
2247 if (sender_host_name != NULL)
2249 helo_verified = strcmpic(sender_host_name, sender_helo_name) == 0;
2253 HDEBUG(D_receive) debug_printf("matched host name\n");
2257 uschar **aliases = sender_host_aliases;
2258 while (*aliases != NULL)
2260 helo_verified = strcmpic(*aliases++, sender_helo_name) == 0;
2261 if (helo_verified) break;
2266 debug_printf("matched alias %s\n", *(--aliases));
2271 /* Final attempt: try a forward lookup of the helo name */
2277 h.name = sender_helo_name;
2281 HDEBUG(D_receive) debug_printf("getting IP address for %s\n",
2283 rc = host_find_byname(&h, NULL, 0, NULL, TRUE);
2284 if (rc == HOST_FOUND || rc == HOST_FOUND_LOCAL)
2289 if (Ustrcmp(hh->address, sender_host_address) == 0)
2291 helo_verified = TRUE;
2293 debug_printf("IP address for %s matches calling address\n",
2303 if (!helo_verified) helo_verify_failed = TRUE; /* We've tried ... */
2310 /*************************************************
2311 * Send user response message *
2312 *************************************************/
2314 /* This function is passed a default response code and a user message. It calls
2315 smtp_message_code() to check and possibly modify the response code, and then
2316 calls smtp_respond() to transmit the response. I put this into a function
2317 just to avoid a lot of repetition.
2320 code the response code
2321 user_msg the user message
2327 smtp_user_msg(uschar *code, uschar *user_msg)
2330 smtp_message_code(&code, &len, &user_msg, NULL);
2331 smtp_respond(code, len, TRUE, user_msg);
2337 /*************************************************
2338 * Initialize for SMTP incoming message *
2339 *************************************************/
2341 /* This function conducts the initial dialogue at the start of an incoming SMTP
2342 message, and builds a list of recipients. However, if the incoming message
2343 is part of a batch (-bS option) a separate function is called since it would
2344 be messy having tests splattered about all over this function. This function
2345 therefore handles the case where interaction is occurring. The input and output
2346 files are set up in smtp_in and smtp_out.
2348 The global recipients_list is set to point to a vector of recipient_item
2349 blocks, whose number is given by recipients_count. This is extended by the
2350 receive_add_recipient() function. The global variable sender_address is set to
2351 the sender's address. The yield is +1 if a message has been successfully
2352 started, 0 if a QUIT command was encountered or the connection was refused from
2353 the particular host, or -1 if the connection was lost.
2357 Returns: > 0 message successfully started (reached DATA)
2358 = 0 QUIT read or end of file reached or call refused
2363 smtp_setup_msg(void)
2366 BOOL toomany = FALSE;
2367 BOOL discarded = FALSE;
2368 BOOL last_was_rej_mail = FALSE;
2369 BOOL last_was_rcpt = FALSE;
2370 void *reset_point = store_get(0);
2372 DEBUG(D_receive) debug_printf("smtp_setup_msg entered\n");
2374 /* Reset for start of new message. We allow one RSET not to be counted as a
2375 nonmail command, for those MTAs that insist on sending it between every
2376 message. Ditto for EHLO/HELO and for STARTTLS, to allow for going in and out of
2377 TLS between messages (an Exim client may do this if it has messages queued up
2378 for the host). Note: we do NOT reset AUTH at this point. */
2380 smtp_reset(reset_point);
2381 message_ended = END_NOTSTARTED;
2383 cmd_list[CMD_LIST_RSET].is_mail_cmd = TRUE;
2384 cmd_list[CMD_LIST_HELO].is_mail_cmd = TRUE;
2385 cmd_list[CMD_LIST_EHLO].is_mail_cmd = TRUE;
2387 cmd_list[CMD_LIST_STARTTLS].is_mail_cmd = TRUE;
2390 /* Set the local signal handler for SIGTERM - it tries to end off tidily */
2392 os_non_restarting_signal(SIGTERM, command_sigterm_handler);
2394 /* Batched SMTP is handled in a different function. */
2396 if (smtp_batched_input) return smtp_setup_batch_msg();
2398 /* Deal with SMTP commands. This loop is exited by setting done to a POSITIVE
2399 value. The values are 2 larger than the required yield of the function. */
2404 uschar *etrn_command;
2405 uschar *etrn_serialize_key;
2407 uschar *log_msg, *smtp_code;
2408 uschar *user_msg = NULL;
2409 uschar *recipient = NULL;
2410 uschar *hello = NULL;
2411 uschar *set_id = NULL;
2413 BOOL was_rej_mail = FALSE;
2414 BOOL was_rcpt = FALSE;
2415 void (*oldsignal)(int);
2417 int start, end, sender_domain, recipient_domain;
2422 switch(smtp_read_command(TRUE))
2424 /* The AUTH command is not permitted to occur inside a transaction, and may
2425 occur successfully only once per connection. Actually, that isn't quite
2426 true. When TLS is started, all previous information about a connection must
2427 be discarded, so a new AUTH is permitted at that time.
2429 AUTH may only be used when it has been advertised. However, it seems that
2430 there are clients that send AUTH when it hasn't been advertised, some of
2431 them even doing this after HELO. And there are MTAs that accept this. Sigh.
2432 So there's a get-out that allows this to happen.
2434 AUTH is initially labelled as a "nonmail command" so that one occurrence
2435 doesn't get counted. We change the label here so that multiple failing
2436 AUTHS will eventually hit the nonmail threshold. */
2440 authentication_failed = TRUE;
2441 cmd_list[CMD_LIST_AUTH].is_mail_cmd = FALSE;
2443 if (!auth_advertised && !allow_auth_unadvertised)
2445 done = synprot_error(L_smtp_protocol_error, 503, NULL,
2446 US"AUTH command used when not advertised");
2449 if (sender_host_authenticated != NULL)
2451 done = synprot_error(L_smtp_protocol_error, 503, NULL,
2452 US"already authenticated");
2455 if (sender_address != NULL)
2457 done = synprot_error(L_smtp_protocol_error, 503, NULL,
2458 US"not permitted in mail transaction");
2464 if (acl_smtp_auth != NULL)
2466 rc = acl_check(ACL_WHERE_AUTH, NULL, acl_smtp_auth, &user_msg, &log_msg);
2469 done = smtp_handle_acl_fail(ACL_WHERE_AUTH, rc, user_msg, log_msg);
2474 /* Find the name of the requested authentication mechanism. */
2477 while ((c = *smtp_cmd_data) != 0 && !isspace(c))
2479 if (!isalnum(c) && c != '-' && c != '_')
2481 done = synprot_error(L_smtp_syntax_error, 501, NULL,
2482 US"invalid character in authentication mechanism name");
2488 /* If not at the end of the line, we must be at white space. Terminate the
2489 name and move the pointer on to any data that may be present. */
2491 if (*smtp_cmd_data != 0)
2493 *smtp_cmd_data++ = 0;
2494 while (isspace(*smtp_cmd_data)) smtp_cmd_data++;
2497 /* Search for an authentication mechanism which is configured for use
2498 as a server and which has been advertised (unless, sigh, allow_auth_
2499 unadvertised is set). */
2501 for (au = auths; au != NULL; au = au->next)
2503 if (strcmpic(s, au->public_name) == 0 && au->server &&
2504 (au->advertised || allow_auth_unadvertised)) break;
2509 done = synprot_error(L_smtp_protocol_error, 504, NULL,
2510 string_sprintf("%s authentication mechanism not supported", s));
2514 /* Run the checking code, passing the remainder of the command line as
2515 data. Initials the $auth<n> variables as empty. Initialize $0 empty and set
2516 it as the only set numerical variable. The authenticator may set $auth<n>
2517 and also set other numeric variables. The $auth<n> variables are preferred
2518 nowadays; the numerical variables remain for backwards compatibility.
2520 Afterwards, have a go at expanding the set_id string, even if
2521 authentication failed - for bad passwords it can be useful to log the
2522 userid. On success, require set_id to expand and exist, and put it in
2523 authenticated_id. Save this in permanent store, as the working store gets
2524 reset at HELO, RSET, etc. */
2526 for (i = 0; i < AUTH_VARS; i++) auth_vars[i] = NULL;
2528 expand_nlength[0] = 0; /* $0 contains nothing */
2530 c = (au->info->servercode)(au, smtp_cmd_data);
2531 if (au->set_id != NULL) set_id = expand_string(au->set_id);
2532 expand_nmax = -1; /* Reset numeric variables */
2533 for (i = 0; i < AUTH_VARS; i++) auth_vars[i] = NULL; /* Reset $auth<n> */
2535 /* The value of authenticated_id is stored in the spool file and printed in
2536 log lines. It must not contain binary zeros or newline characters. In
2537 normal use, it never will, but when playing around or testing, this error
2538 can (did) happen. To guard against this, ensure that the id contains only
2539 printing characters. */
2541 if (set_id != NULL) set_id = string_printing(set_id);
2543 /* For the non-OK cases, set up additional logging data if set_id
2548 if (set_id != NULL && *set_id != 0)
2549 set_id = string_sprintf(" (set_id=%s)", set_id);
2553 /* Switch on the result */
2558 if (au->set_id == NULL || set_id != NULL) /* Complete success */
2560 if (set_id != NULL) authenticated_id = string_copy_malloc(set_id);
2561 sender_host_authenticated = au->name;
2562 authentication_failed = FALSE;
2564 protocols[pextend + pauthed + ((tls_active >= 0)? pcrpted:0)] +
2565 ((sender_host_address != NULL)? pnlocal : 0);
2566 s = ss = US"235 Authentication succeeded";
2567 authenticated_by = au;
2571 /* Authentication succeeded, but we failed to expand the set_id string.
2572 Treat this as a temporary error. */
2574 auth_defer_msg = expand_string_message;
2578 s = string_sprintf("435 Unable to authenticate at present%s",
2579 auth_defer_user_msg);
2580 ss = string_sprintf("435 Unable to authenticate at present%s: %s",
2581 set_id, auth_defer_msg);
2585 s = ss = US"501 Invalid base64 data";
2589 s = ss = US"501 Authentication cancelled";
2593 s = ss = US"553 Initial data not expected";
2597 s = US"535 Incorrect authentication data";
2598 ss = string_sprintf("535 Incorrect authentication data%s", set_id);
2602 s = US"435 Internal error";
2603 ss = string_sprintf("435 Internal error%s: return %d from authentication "
2604 "check", set_id, c);
2608 smtp_printf("%s\r\n", s);
2610 log_write(0, LOG_MAIN|LOG_REJECT, "%s authenticator failed for %s: %s",
2611 au->name, host_and_ident(FALSE), ss);
2613 break; /* AUTH_CMD */
2615 /* The HELO/EHLO commands are permitted to appear in the middle of a
2616 session as well as at the beginning. They have the effect of a reset in
2617 addition to their other functions. Their absence at the start cannot be
2618 taken to be an error.
2622 If the EHLO command is not acceptable to the SMTP server, 501, 500,
2623 or 502 failure replies MUST be returned as appropriate. The SMTP
2624 server MUST stay in the same state after transmitting these replies
2625 that it was in before the EHLO was received.
2627 Therefore, we do not do the reset until after checking the command for
2628 acceptability. This change was made for Exim release 4.11. Previously
2629 it did the reset first. */
2642 HELO_EHLO: /* Common code for HELO and EHLO */
2643 cmd_list[CMD_LIST_HELO].is_mail_cmd = FALSE;
2644 cmd_list[CMD_LIST_EHLO].is_mail_cmd = FALSE;
2646 /* Reject the HELO if its argument was invalid or non-existent. A
2647 successful check causes the argument to be saved in malloc store. */
2649 if (!check_helo(smtp_cmd_data))
2651 smtp_printf("501 Syntactically invalid %s argument(s)\r\n", hello);
2653 log_write(0, LOG_MAIN|LOG_REJECT, "rejected %s from %s: syntactically "
2654 "invalid argument(s): %s", hello, host_and_ident(FALSE),
2655 (*smtp_cmd_argument == 0)? US"(no argument given)" :
2656 string_printing(smtp_cmd_argument));
2658 if (++synprot_error_count > smtp_max_synprot_errors)
2660 log_write(0, LOG_MAIN|LOG_REJECT, "SMTP call from %s dropped: too many "
2661 "syntax or protocol errors (last command was \"%s\")",
2662 host_and_ident(FALSE), smtp_cmd_buffer);
2669 /* If sender_host_unknown is true, we have got here via the -bs interface,
2670 not called from inetd. Otherwise, we are running an IP connection and the
2671 host address will be set. If the helo name is the primary name of this
2672 host and we haven't done a reverse lookup, force one now. If helo_required
2673 is set, ensure that the HELO name matches the actual host. If helo_verify
2674 is set, do the same check, but softly. */
2676 if (!sender_host_unknown)
2678 BOOL old_helo_verified = helo_verified;
2679 uschar *p = smtp_cmd_data;
2681 while (*p != 0 && !isspace(*p)) { *p = tolower(*p); p++; }
2684 /* Force a reverse lookup if HELO quoted something in helo_lookup_domains
2685 because otherwise the log can be confusing. */
2687 if (sender_host_name == NULL &&
2688 (deliver_domain = sender_helo_name, /* set $domain */
2689 match_isinlist(sender_helo_name, &helo_lookup_domains, 0,
2690 &domainlist_anchor, NULL, MCL_DOMAIN, TRUE, NULL)) == OK)
2691 (void)host_name_lookup();
2693 /* Rebuild the fullhost info to include the HELO name (and the real name
2694 if it was looked up.) */
2696 host_build_sender_fullhost(); /* Rebuild */
2697 set_process_info("handling%s incoming connection from %s",
2698 (tls_active >= 0)? " TLS" : "", host_and_ident(FALSE));
2700 /* Verify if configured. This doesn't give much security, but it does
2701 make some people happy to be able to do it. If helo_required is set,
2702 (host matches helo_verify_hosts) failure forces rejection. If helo_verify
2703 is set (host matches helo_try_verify_hosts), it does not. This is perhaps
2704 now obsolescent, since the verification can now be requested selectively
2707 helo_verified = helo_verify_failed = FALSE;
2708 if (helo_required || helo_verify)
2710 BOOL tempfail = !smtp_verify_helo();
2715 smtp_printf("%d %s argument does not match calling host\r\n",
2716 tempfail? 451 : 550, hello);
2717 log_write(0, LOG_MAIN|LOG_REJECT, "%srejected \"%s %s\" from %s",
2718 tempfail? "temporarily " : "",
2719 hello, sender_helo_name, host_and_ident(FALSE));
2720 helo_verified = old_helo_verified;
2721 break; /* End of HELO/EHLO processing */
2723 HDEBUG(D_all) debug_printf("%s verification failed but host is in "
2724 "helo_try_verify_hosts\n", hello);
2729 #ifdef EXPERIMENTAL_SPF
2730 /* set up SPF context */
2731 spf_init(sender_helo_name, sender_host_address);
2734 /* Apply an ACL check if one is defined */
2736 if (acl_smtp_helo != NULL)
2738 rc = acl_check(ACL_WHERE_HELO, NULL, acl_smtp_helo, &user_msg, &log_msg);
2741 done = smtp_handle_acl_fail(ACL_WHERE_HELO, rc, user_msg, log_msg);
2742 sender_helo_name = NULL;
2743 host_build_sender_fullhost(); /* Rebuild */
2748 /* Generate an OK reply. The default string includes the ident if present,
2749 and also the IP address if present. Reflecting back the ident is intended
2750 as a deterrent to mail forgers. For maximum efficiency, and also because
2751 some broken systems expect each response to be in a single packet, arrange
2752 that the entire reply is sent in one write(). */
2754 auth_advertised = FALSE;
2755 pipelining_advertised = FALSE;
2757 tls_advertised = FALSE;
2760 smtp_code = US"250 "; /* Default response code plus space*/
2761 if (user_msg == NULL)
2763 s = string_sprintf("%.3s %s Hello %s%s%s",
2765 smtp_active_hostname,
2766 (sender_ident == NULL)? US"" : sender_ident,
2767 (sender_ident == NULL)? US"" : US" at ",
2768 (sender_host_name == NULL)? sender_helo_name : sender_host_name);
2773 if (sender_host_address != NULL)
2775 s = string_cat(s, &size, &ptr, US" [", 2);
2776 s = string_cat(s, &size, &ptr, sender_host_address,
2777 Ustrlen(sender_host_address));
2778 s = string_cat(s, &size, &ptr, US"]", 1);
2782 /* A user-supplied EHLO greeting may not contain more than one line. Note
2783 that the code returned by smtp_message_code() includes the terminating
2784 whitespace character. */
2790 smtp_message_code(&smtp_code, &codelen, &user_msg, NULL);
2791 s = string_sprintf("%.*s%s", codelen, smtp_code, user_msg);
2792 if ((ss = strpbrk(CS s, "\r\n")) != NULL)
2794 log_write(0, LOG_MAIN|LOG_PANIC, "EHLO/HELO response must not contain "
2795 "newlines: message truncated: %s", string_printing(s));
2802 s = string_cat(s, &size, &ptr, US"\r\n", 2);
2804 /* If we received EHLO, we must create a multiline response which includes
2805 the functions supported. */
2811 /* I'm not entirely happy with this, as an MTA is supposed to check
2812 that it has enough room to accept a message of maximum size before
2813 it sends this. However, there seems little point in not sending it.
2814 The actual size check happens later at MAIL FROM time. By postponing it
2815 till then, VRFY and EXPN can be used after EHLO when space is short. */
2817 if (thismessage_size_limit > 0)
2819 sprintf(CS big_buffer, "%.3s-SIZE %d\r\n", smtp_code,
2820 thismessage_size_limit);
2821 s = string_cat(s, &size, &ptr, big_buffer, Ustrlen(big_buffer));
2825 s = string_cat(s, &size, &ptr, smtp_code, 3);
2826 s = string_cat(s, &size, &ptr, US"-SIZE\r\n", 7);
2829 /* Exim does not do protocol conversion or data conversion. It is 8-bit
2830 clean; if it has an 8-bit character in its hand, it just sends it. It
2831 cannot therefore specify 8BITMIME and remain consistent with the RFCs.
2832 However, some users want this option simply in order to stop MUAs
2833 mangling messages that contain top-bit-set characters. It is therefore
2834 provided as an option. */
2836 if (accept_8bitmime)
2838 s = string_cat(s, &size, &ptr, smtp_code, 3);
2839 s = string_cat(s, &size, &ptr, US"-8BITMIME\r\n", 11);
2842 /* Advertise ETRN if there's an ACL checking whether a host is
2843 permitted to issue it; a check is made when any host actually tries. */
2845 if (acl_smtp_etrn != NULL)
2847 s = string_cat(s, &size, &ptr, smtp_code, 3);
2848 s = string_cat(s, &size, &ptr, US"-ETRN\r\n", 7);
2851 /* Advertise EXPN if there's an ACL checking whether a host is
2852 permitted to issue it; a check is made when any host actually tries. */
2854 if (acl_smtp_expn != NULL)
2856 s = string_cat(s, &size, &ptr, smtp_code, 3);
2857 s = string_cat(s, &size, &ptr, US"-EXPN\r\n", 7);
2860 /* Exim is quite happy with pipelining, so let the other end know that
2861 it is safe to use it, unless advertising is disabled. */
2863 if (pipelining_enable &&
2864 verify_check_host(&pipelining_advertise_hosts) == OK)
2866 s = string_cat(s, &size, &ptr, smtp_code, 3);
2867 s = string_cat(s, &size, &ptr, US"-PIPELINING\r\n", 13);
2868 sync_cmd_limit = NON_SYNC_CMD_PIPELINING;
2869 pipelining_advertised = TRUE;
2872 /* If any server authentication mechanisms are configured, advertise
2873 them if the current host is in auth_advertise_hosts. The problem with
2874 advertising always is that some clients then require users to
2875 authenticate (and aren't configurable otherwise) even though it may not
2876 be necessary (e.g. if the host is in host_accept_relay).
2878 RFC 2222 states that SASL mechanism names contain only upper case
2879 letters, so output the names in upper case, though we actually recognize
2880 them in either case in the AUTH command. */
2884 if (verify_check_host(&auth_advertise_hosts) == OK)
2888 for (au = auths; au != NULL; au = au->next)
2890 if (au->server && (au->advertise_condition == NULL ||
2891 expand_check_condition(au->advertise_condition, au->name,
2892 US"authenticator")))
2897 s = string_cat(s, &size, &ptr, smtp_code, 3);
2898 s = string_cat(s, &size, &ptr, US"-AUTH", 5);
2900 auth_advertised = TRUE;
2903 s = string_cat(s, &size, &ptr, US" ", 1);
2904 s = string_cat(s, &size, &ptr, au->public_name,
2905 Ustrlen(au->public_name));
2906 while (++saveptr < ptr) s[saveptr] = toupper(s[saveptr]);
2907 au->advertised = TRUE;
2909 else au->advertised = FALSE;
2911 if (!first) s = string_cat(s, &size, &ptr, US"\r\n", 2);
2915 /* Advertise TLS (Transport Level Security) aka SSL (Secure Socket Layer)
2916 if it has been included in the binary, and the host matches
2917 tls_advertise_hosts. We must *not* advertise if we are already in a
2918 secure connection. */
2921 if (tls_active < 0 &&
2922 verify_check_host(&tls_advertise_hosts) != FAIL)
2924 s = string_cat(s, &size, &ptr, smtp_code, 3);
2925 s = string_cat(s, &size, &ptr, US"-STARTTLS\r\n", 11);
2926 tls_advertised = TRUE;
2930 /* Finish off the multiline reply with one that is always available. */
2932 s = string_cat(s, &size, &ptr, smtp_code, 3);
2933 s = string_cat(s, &size, &ptr, US" HELP\r\n", 7);
2936 /* Terminate the string (for debug), write it, and note that HELO/EHLO
2942 if (tls_active >= 0) (void)tls_write(s, ptr); else
2945 (void)fwrite(s, 1, ptr, smtp_out);
2949 while ((cr = Ustrchr(s, '\r')) != NULL) /* lose CRs */
2950 memmove(cr, cr + 1, (ptr--) - (cr - s));
2951 debug_printf("SMTP>> %s", s);
2955 /* Reset the protocol and the state, abandoning any previous message. */
2957 received_protocol = (esmtp?
2959 ((sender_host_authenticated != NULL)? pauthed : 0) +
2960 ((tls_active >= 0)? pcrpted : 0)]
2962 protocols[pnormal + ((tls_active >= 0)? pcrpted : 0)])
2964 ((sender_host_address != NULL)? pnlocal : 0);
2966 smtp_reset(reset_point);
2968 break; /* HELO/EHLO */
2971 /* The MAIL command requires an address as an operand. All we do
2972 here is to parse it for syntactic correctness. The form "<>" is
2973 a special case which converts into an empty string. The start/end
2974 pointers in the original are not used further for this address, as
2975 it is the canonical extracted address which is all that is kept. */
2979 smtp_mailcmd_count++; /* Count for limit and ratelimit */
2980 was_rej_mail = TRUE; /* Reset if accepted */
2982 if (helo_required && !helo_seen)
2984 smtp_printf("503 HELO or EHLO required\r\n");
2985 log_write(0, LOG_MAIN|LOG_REJECT, "rejected MAIL from %s: no "
2986 "HELO/EHLO given", host_and_ident(FALSE));
2990 if (sender_address != NULL)
2992 done = synprot_error(L_smtp_protocol_error, 503, NULL,
2993 US"sender already given");
2997 if (smtp_cmd_data[0] == 0)
2999 done = synprot_error(L_smtp_protocol_error, 501, NULL,
3000 US"MAIL must have an address operand");
3004 /* Check to see if the limit for messages per connection would be
3005 exceeded by accepting further messages. */
3007 if (smtp_accept_max_per_connection > 0 &&
3008 smtp_mailcmd_count > smtp_accept_max_per_connection)
3010 smtp_printf("421 too many messages in this connection\r\n");
3011 log_write(0, LOG_MAIN|LOG_REJECT, "rejected MAIL command %s: too many "
3012 "messages in one connection", host_and_ident(TRUE));
3016 /* Reset for start of message - even if this is going to fail, we
3017 obviously need to throw away any previous data. */
3019 smtp_reset(reset_point);
3021 sender_data = recipient_data = NULL;
3023 /* Loop, checking for ESMTP additions to the MAIL FROM command. */
3027 uschar *name, *value, *end;
3028 unsigned long int size;
3030 if (!extract_option(&name, &value)) break;
3032 /* Handle SIZE= by reading the value. We don't do the check till later,
3033 in order to be able to log the sender address on failure. */
3035 if (strcmpic(name, US"SIZE") == 0 &&
3036 ((size = (int)Ustrtoul(value, &end, 10)), *end == 0))
3038 if ((size == ULONG_MAX && errno == ERANGE) || size > INT_MAX)
3040 message_size = (int)size;
3043 /* If this session was initiated with EHLO and accept_8bitmime is set,
3044 Exim will have indicated that it supports the BODY=8BITMIME option. In
3045 fact, it does not support this according to the RFCs, in that it does not
3046 take any special action for forwarding messages containing 8-bit
3047 characters. That is why accept_8bitmime is not the default setting, but
3048 some sites want the action that is provided. We recognize both "8BITMIME"
3049 and "7BIT" as body types, but take no action. */
3051 else if (accept_8bitmime && strcmpic(name, US"BODY") == 0 &&
3052 (strcmpic(value, US"8BITMIME") == 0 ||
3053 strcmpic(value, US"7BIT") == 0)) {}
3055 /* Handle the AUTH extension. If the value given is not "<>" and either
3056 the ACL says "yes" or there is no ACL but the sending host is
3057 authenticated, we set it up as the authenticated sender. However, if the
3058 authenticator set a condition to be tested, we ignore AUTH on MAIL unless
3059 the condition is met. The value of AUTH is an xtext, which means that +,
3060 = and cntrl chars are coded in hex; however "<>" is unaffected by this
3063 else if (strcmpic(name, US"AUTH") == 0)
3065 if (Ustrcmp(value, "<>") != 0)
3070 if (auth_xtextdecode(value, &authenticated_sender) < 0)
3072 /* Put back terminator overrides for error message */
3075 done = synprot_error(L_smtp_syntax_error, 501, NULL,
3076 US"invalid data for AUTH");
3080 if (acl_smtp_mailauth == NULL)
3082 ignore_msg = US"client not authenticated";
3083 rc = (sender_host_authenticated != NULL)? OK : FAIL;
3087 ignore_msg = US"rejected by ACL";
3088 rc = acl_check(ACL_WHERE_MAILAUTH, NULL, acl_smtp_mailauth,
3089 &user_msg, &log_msg);
3095 if (authenticated_by == NULL ||
3096 authenticated_by->mail_auth_condition == NULL ||
3097 expand_check_condition(authenticated_by->mail_auth_condition,
3098 authenticated_by->name, US"authenticator"))
3099 break; /* Accept the AUTH */
3101 ignore_msg = US"server_mail_auth_condition failed";
3102 if (authenticated_id != NULL)
3103 ignore_msg = string_sprintf("%s: authenticated ID=\"%s\"",
3104 ignore_msg, authenticated_id);
3109 authenticated_sender = NULL;
3110 log_write(0, LOG_MAIN, "ignoring AUTH=%s from %s (%s)",
3111 value, host_and_ident(TRUE), ignore_msg);
3114 /* Should only get DEFER or ERROR here. Put back terminator
3115 overrides for error message */
3120 (void)smtp_handle_acl_fail(ACL_WHERE_MAILAUTH, rc, user_msg,
3127 /* Unknown option. Stick back the terminator characters and break
3128 the loop. An error for a malformed address will occur. */
3138 /* If we have passed the threshold for rate limiting, apply the current
3139 delay, and update it for next time, provided this is a limited host. */
3141 if (smtp_mailcmd_count > smtp_rlm_threshold &&
3142 verify_check_host(&smtp_ratelimit_hosts) == OK)
3144 DEBUG(D_receive) debug_printf("rate limit MAIL: delay %.3g sec\n",
3145 smtp_delay_mail/1000.0);
3146 millisleep((int)smtp_delay_mail);
3147 smtp_delay_mail *= smtp_rlm_factor;
3148 if (smtp_delay_mail > (double)smtp_rlm_limit)
3149 smtp_delay_mail = (double)smtp_rlm_limit;
3152 /* Now extract the address, first applying any SMTP-time rewriting. The
3153 TRUE flag allows "<>" as a sender address. */
3155 raw_sender = ((rewrite_existflags & rewrite_smtp) != 0)?
3156 rewrite_one(smtp_cmd_data, rewrite_smtp, NULL, FALSE, US"",
3157 global_rewrite_rules) : smtp_cmd_data;
3159 /* rfc821_domains = TRUE; << no longer needed */
3161 parse_extract_address(raw_sender, &errmess, &start, &end, &sender_domain,
3163 /* rfc821_domains = FALSE; << no longer needed */
3165 if (raw_sender == NULL)
3167 done = synprot_error(L_smtp_syntax_error, 501, smtp_cmd_data, errmess);
3171 sender_address = raw_sender;
3173 /* If there is a configured size limit for mail, check that this message
3174 doesn't exceed it. The check is postponed to this point so that the sender
3177 if (thismessage_size_limit > 0 && message_size > thismessage_size_limit)
3179 smtp_printf("552 Message size exceeds maximum permitted\r\n");
3180 log_write(L_size_reject,
3181 LOG_MAIN|LOG_REJECT, "rejected MAIL FROM:<%s> %s: "
3182 "message too big: size%s=%d max=%d",
3184 host_and_ident(TRUE),
3185 (message_size == INT_MAX)? ">" : "",
3187 thismessage_size_limit);
3188 sender_address = NULL;
3192 /* Check there is enough space on the disk unless configured not to.
3193 When smtp_check_spool_space is set, the check is for thismessage_size_limit
3194 plus the current message - i.e. we accept the message only if it won't
3195 reduce the space below the threshold. Add 5000 to the size to allow for
3196 overheads such as the Received: line and storing of recipients, etc.
3197 By putting the check here, even when SIZE is not given, it allow VRFY
3198 and EXPN etc. to be used when space is short. */
3200 if (!receive_check_fs(
3201 (smtp_check_spool_space && message_size >= 0)?
3202 message_size + 5000 : 0))
3204 smtp_printf("452 Space shortage, please try later\r\n");
3205 sender_address = NULL;
3209 /* If sender_address is unqualified, reject it, unless this is a locally
3210 generated message, or the sending host or net is permitted to send
3211 unqualified addresses - typically local machines behaving as MUAs -
3212 in which case just qualify the address. The flag is set above at the start
3213 of the SMTP connection. */
3215 if (sender_domain == 0 && sender_address[0] != 0)
3217 if (allow_unqualified_sender)
3219 sender_domain = Ustrlen(sender_address) + 1;
3220 sender_address = rewrite_address_qualify(sender_address, FALSE);
3221 DEBUG(D_receive) debug_printf("unqualified address %s accepted\n",
3226 smtp_printf("501 %s: sender address must contain a domain\r\n",
3228 log_write(L_smtp_syntax_error,
3229 LOG_MAIN|LOG_REJECT,
3230 "unqualified sender rejected: <%s> %s%s",
3232 host_and_ident(TRUE),
3234 sender_address = NULL;
3239 /* Apply an ACL check if one is defined, before responding */
3241 rc = (acl_smtp_mail == NULL)? OK :
3242 acl_check(ACL_WHERE_MAIL, NULL, acl_smtp_mail, &user_msg, &log_msg);
3244 if (rc == OK || rc == DISCARD)
3246 if (user_msg == NULL) smtp_printf("250 OK\r\n");
3247 else smtp_user_msg(US"250", user_msg);
3248 smtp_delay_rcpt = smtp_rlr_base;
3249 recipients_discarded = (rc == DISCARD);
3250 was_rej_mail = FALSE;
3254 done = smtp_handle_acl_fail(ACL_WHERE_MAIL, rc, user_msg, log_msg);
3255 sender_address = NULL;
3260 /* The RCPT command requires an address as an operand. All we do
3261 here is to parse it for syntactic correctness. There may be any number
3262 of RCPT commands, specifying multiple senders. We build them all into
3263 a data structure that is in argc/argv format. The start/end values
3264 given by parse_extract_address are not used, as we keep only the
3265 extracted address. */
3272 /* There must be a sender address; if the sender was rejected and
3273 pipelining was advertised, we assume the client was pipelining, and do not
3274 count this as a protocol error. Reset was_rej_mail so that further RCPTs
3275 get the same treatment. */
3277 if (sender_address == NULL)
3279 if (pipelining_advertised && last_was_rej_mail)
3281 smtp_printf("503 sender not yet given\r\n");
3282 was_rej_mail = TRUE;
3286 done = synprot_error(L_smtp_protocol_error, 503, NULL,
3287 US"sender not yet given");
3288 was_rcpt = FALSE; /* Not a valid RCPT */
3294 /* Check for an operand */
3296 if (smtp_cmd_data[0] == 0)
3298 done = synprot_error(L_smtp_syntax_error, 501, NULL,
3299 US"RCPT must have an address operand");
3304 /* Apply SMTP rewriting then extract the working address. Don't allow "<>"
3305 as a recipient address */
3307 recipient = ((rewrite_existflags & rewrite_smtp) != 0)?
3308 rewrite_one(smtp_cmd_data, rewrite_smtp, NULL, FALSE, US"",
3309 global_rewrite_rules) : smtp_cmd_data;
3311 /* rfc821_domains = TRUE; << no longer needed */
3312 recipient = parse_extract_address(recipient, &errmess, &start, &end,
3313 &recipient_domain, FALSE);
3314 /* rfc821_domains = FALSE; << no longer needed */
3316 if (recipient == NULL)
3318 done = synprot_error(L_smtp_syntax_error, 501, smtp_cmd_data, errmess);
3323 /* If the recipient address is unqualified, reject it, unless this is a
3324 locally generated message. However, unqualified addresses are permitted
3325 from a configured list of hosts and nets - typically when behaving as
3326 MUAs rather than MTAs. Sad that SMTP is used for both types of traffic,
3327 really. The flag is set at the start of the SMTP connection.
3329 RFC 1123 talks about supporting "the reserved mailbox postmaster"; I always
3330 assumed this meant "reserved local part", but the revision of RFC 821 and
3331 friends now makes it absolutely clear that it means *mailbox*. Consequently
3332 we must always qualify this address, regardless. */
3334 if (recipient_domain == 0)
3336 if (allow_unqualified_recipient ||
3337 strcmpic(recipient, US"postmaster") == 0)
3339 DEBUG(D_receive) debug_printf("unqualified address %s accepted\n",
3341 recipient_domain = Ustrlen(recipient) + 1;
3342 recipient = rewrite_address_qualify(recipient, TRUE);
3347 smtp_printf("501 %s: recipient address must contain a domain\r\n",
3349 log_write(L_smtp_syntax_error,
3350 LOG_MAIN|LOG_REJECT, "unqualified recipient rejected: "
3351 "<%s> %s%s", recipient, host_and_ident(TRUE),
3357 /* Check maximum allowed */
3359 if (rcpt_count > recipients_max && recipients_max > 0)
3361 if (recipients_max_reject)
3364 smtp_printf("552 too many recipients\r\n");
3366 log_write(0, LOG_MAIN|LOG_REJECT, "too many recipients: message "
3367 "rejected: sender=<%s> %s", sender_address, host_and_ident(TRUE));
3372 smtp_printf("452 too many recipients\r\n");
3374 log_write(0, LOG_MAIN|LOG_REJECT, "too many recipients: excess "
3375 "temporarily rejected: sender=<%s> %s", sender_address,
3376 host_and_ident(TRUE));
3383 /* If we have passed the threshold for rate limiting, apply the current
3384 delay, and update it for next time, provided this is a limited host. */
3386 if (rcpt_count > smtp_rlr_threshold &&
3387 verify_check_host(&smtp_ratelimit_hosts) == OK)
3389 DEBUG(D_receive) debug_printf("rate limit RCPT: delay %.3g sec\n",
3390 smtp_delay_rcpt/1000.0);
3391 millisleep((int)smtp_delay_rcpt);
3392 smtp_delay_rcpt *= smtp_rlr_factor;
3393 if (smtp_delay_rcpt > (double)smtp_rlr_limit)
3394 smtp_delay_rcpt = (double)smtp_rlr_limit;
3397 /* If the MAIL ACL discarded all the recipients, we bypass ACL checking
3398 for them. Otherwise, check the access control list for this recipient. */
3400 rc = recipients_discarded? DISCARD :
3401 acl_check(ACL_WHERE_RCPT, recipient, acl_smtp_rcpt, &user_msg, &log_msg);
3403 /* The ACL was happy */
3407 if (user_msg == NULL) smtp_printf("250 Accepted\r\n");
3408 else smtp_user_msg(US"250", user_msg);
3409 receive_add_recipient(recipient, -1);
3412 /* The recipient was discarded */
3414 else if (rc == DISCARD)
3416 if (user_msg == NULL) smtp_printf("250 Accepted\r\n");
3417 else smtp_user_msg(US"250", user_msg);
3420 log_write(0, LOG_MAIN|LOG_REJECT, "%s F=<%s> rejected RCPT %s: "
3421 "discarded by %s ACL%s%s", host_and_ident(TRUE),
3422 (sender_address_unrewritten != NULL)?
3423 sender_address_unrewritten : sender_address,
3424 smtp_cmd_argument, recipients_discarded? "MAIL" : "RCPT",
3425 (log_msg == NULL)? US"" : US": ",
3426 (log_msg == NULL)? US"" : log_msg);
3429 /* Either the ACL failed the address, or it was deferred. */
3433 if (rc == FAIL) rcpt_fail_count++; else rcpt_defer_count++;
3434 done = smtp_handle_acl_fail(ACL_WHERE_RCPT, rc, user_msg, log_msg);
3439 /* The DATA command is legal only if it follows successful MAIL FROM
3440 and RCPT TO commands. However, if pipelining is advertised, a bad DATA is
3441 not counted as a protocol error if it follows RCPT (which must have been
3442 rejected if there are no recipients.) This function is complete when a
3443 valid DATA command is encountered.
3445 Note concerning the code used: RFC 2821 says this:
3447 - If there was no MAIL, or no RCPT, command, or all such commands
3448 were rejected, the server MAY return a "command out of sequence"
3449 (503) or "no valid recipients" (554) reply in response to the
3452 The example in the pipelining RFC 2920 uses 554, but I use 503 here
3453 because it is the same whether pipelining is in use or not. */
3457 if (!discarded && recipients_count <= 0)
3459 if (pipelining_advertised && last_was_rcpt)
3460 smtp_printf("503 valid RCPT command must precede DATA\r\n");
3462 done = synprot_error(L_smtp_protocol_error, 503, NULL,
3463 US"valid RCPT command must precede DATA");
3467 if (toomany && recipients_max_reject)
3469 sender_address = NULL; /* This will allow a new MAIL without RSET */
3470 sender_address_unrewritten = NULL;
3471 smtp_printf("554 Too many recipients\r\n");
3475 if (acl_smtp_predata == NULL) rc = OK; else
3477 enable_dollar_recipients = TRUE;
3478 rc = acl_check(ACL_WHERE_PREDATA, NULL, acl_smtp_predata, &user_msg,
3480 enable_dollar_recipients = FALSE;
3485 if (user_msg == NULL)
3486 smtp_printf("354 Enter message, ending with \".\" on a line by itself\r\n");
3487 else smtp_user_msg(US"354", user_msg);
3489 message_ended = END_NOTENDED; /* Indicate in middle of data */
3492 /* Either the ACL failed the address, or it was deferred. */
3495 done = smtp_handle_acl_fail(ACL_WHERE_PREDATA, rc, user_msg, log_msg);
3502 rc = acl_check(ACL_WHERE_VRFY, NULL, acl_smtp_vrfy, &user_msg, &log_msg);
3504 done = smtp_handle_acl_fail(ACL_WHERE_VRFY, rc, user_msg, log_msg);
3510 /* rfc821_domains = TRUE; << no longer needed */
3511 address = parse_extract_address(smtp_cmd_data, &errmess, &start, &end,
3512 &recipient_domain, FALSE);
3513 /* rfc821_domains = FALSE; << no longer needed */
3515 if (address == NULL)
3516 s = string_sprintf("501 %s", errmess);
3519 address_item *addr = deliver_make_addr(address, FALSE);
3520 switch(verify_address(addr, NULL, vopt_is_recipient | vopt_qualify, -1,
3521 -1, -1, NULL, NULL, NULL))
3524 s = string_sprintf("250 <%s> is deliverable", address);
3528 s = (addr->user_message != NULL)?
3529 string_sprintf("451 <%s> %s", address, addr->user_message) :
3530 string_sprintf("451 Cannot resolve <%s> at this time", address);
3534 s = (addr->user_message != NULL)?
3535 string_sprintf("550 <%s> %s", address, addr->user_message) :
3536 string_sprintf("550 <%s> is not deliverable", address);
3537 log_write(0, LOG_MAIN, "VRFY failed for %s %s",
3538 smtp_cmd_argument, host_and_ident(TRUE));
3543 smtp_printf("%s\r\n", s);
3550 rc = acl_check(ACL_WHERE_EXPN, NULL, acl_smtp_expn, &user_msg, &log_msg);
3552 done = smtp_handle_acl_fail(ACL_WHERE_EXPN, rc, user_msg, log_msg);
3555 BOOL save_log_testing_mode = log_testing_mode;
3556 address_test_mode = log_testing_mode = TRUE;
3557 (void) verify_address(deliver_make_addr(smtp_cmd_data, FALSE),
3558 smtp_out, vopt_is_recipient | vopt_qualify | vopt_expn, -1, -1, -1,
3560 address_test_mode = FALSE;
3561 log_testing_mode = save_log_testing_mode; /* true for -bh */
3570 if (!tls_advertised)
3572 done = synprot_error(L_smtp_protocol_error, 503, NULL,
3573 US"STARTTLS command used when not advertised");
3577 /* Apply an ACL check if one is defined */
3579 if (acl_smtp_starttls != NULL)
3581 rc = acl_check(ACL_WHERE_STARTTLS, NULL, acl_smtp_starttls, &user_msg,
3585 done = smtp_handle_acl_fail(ACL_WHERE_STARTTLS, rc, user_msg, log_msg);
3590 /* RFC 2487 is not clear on when this command may be sent, though it
3591 does state that all information previously obtained from the client
3592 must be discarded if a TLS session is started. It seems reasonble to
3593 do an implied RSET when STARTTLS is received. */
3595 incomplete_transaction_log(US"STARTTLS");
3596 smtp_reset(reset_point);
3598 cmd_list[CMD_LIST_STARTTLS].is_mail_cmd = FALSE;
3600 /* Attempt to start up a TLS session, and if successful, discard all
3601 knowledge that was obtained previously. At least, that's what the RFC says,
3602 and that's what happens by default. However, in order to work round YAEB,
3603 there is an option to remember the esmtp state. Sigh.
3605 We must allow for an extra EHLO command and an extra AUTH command after
3606 STARTTLS that don't add to the nonmail command count. */
3608 if ((rc = tls_server_start(tls_require_ciphers, gnutls_require_mac,
3609 gnutls_require_kx, gnutls_require_proto)) == OK)
3611 if (!tls_remember_esmtp)
3612 helo_seen = esmtp = auth_advertised = pipelining_advertised = FALSE;
3613 cmd_list[CMD_LIST_EHLO].is_mail_cmd = TRUE;
3614 cmd_list[CMD_LIST_AUTH].is_mail_cmd = TRUE;
3615 if (sender_helo_name != NULL)
3617 store_free(sender_helo_name);
3618 sender_helo_name = NULL;
3619 host_build_sender_fullhost(); /* Rebuild */
3620 set_process_info("handling incoming TLS connection from %s",
3621 host_and_ident(FALSE));
3623 received_protocol = (esmtp?
3624 protocols[pextend + pcrpted +
3625 ((sender_host_authenticated != NULL)? pauthed : 0)]
3627 protocols[pnormal + pcrpted])
3629 ((sender_host_address != NULL)? pnlocal : 0);
3631 sender_host_authenticated = NULL;
3632 authenticated_id = NULL;
3633 sync_cmd_limit = NON_SYNC_CMD_NON_PIPELINING;
3634 DEBUG(D_tls) debug_printf("TLS active\n");
3635 break; /* Successful STARTTLS */
3638 /* Some local configuration problem was discovered before actually trying
3639 to do a TLS handshake; give a temporary error. */
3641 else if (rc == DEFER)
3643 smtp_printf("454 TLS currently unavailable\r\n");
3647 /* Hard failure. Reject everything except QUIT or closed connection. One
3648 cause for failure is a nested STARTTLS, in which case tls_active remains
3649 set, but we must still reject all incoming commands. */
3651 DEBUG(D_tls) debug_printf("TLS failed to start\n");
3654 switch(smtp_read_command(FALSE))
3657 log_write(L_smtp_connection, LOG_MAIN, "%s closed by EOF",
3658 smtp_get_connection_info());
3663 smtp_printf("221 %s closing connection\r\n", smtp_active_hostname);
3664 log_write(L_smtp_connection, LOG_MAIN, "%s closed by QUIT",
3665 smtp_get_connection_info());
3670 smtp_printf("554 Security failure\r\n");
3679 /* The ACL for QUIT is provided for gathering statistical information or
3680 similar; it does not affect the response code, but it can supply a custom
3685 incomplete_transaction_log(US"QUIT");
3687 if (acl_smtp_quit != NULL)
3689 rc = acl_check(ACL_WHERE_QUIT, NULL, acl_smtp_quit,&user_msg,&log_msg);
3691 log_write(0, LOG_MAIN|LOG_PANIC, "ACL for QUIT returned ERROR: %s",
3695 if (user_msg == NULL)
3696 smtp_printf("221 %s closing connection\r\n", smtp_active_hostname);
3698 smtp_respond(US"221", 3, TRUE, user_msg);
3705 log_write(L_smtp_connection, LOG_MAIN, "%s closed by QUIT",
3706 smtp_get_connection_info());
3712 incomplete_transaction_log(US"RSET");
3713 smtp_reset(reset_point);
3715 smtp_printf("250 Reset OK\r\n");
3716 cmd_list[CMD_LIST_RSET].is_mail_cmd = FALSE;
3722 smtp_printf("250 OK\r\n");
3726 /* Show ETRN/EXPN/VRFY if there's
3727 an ACL for checking hosts; if actually used, a check will be done for
3732 smtp_printf("214-Commands supported:\r\n");
3736 Ustrcat(buffer, " AUTH");
3738 Ustrcat(buffer, " STARTTLS");
3740 Ustrcat(buffer, " HELO EHLO MAIL RCPT DATA");
3741 Ustrcat(buffer, " NOOP QUIT RSET HELP");
3742 if (acl_smtp_etrn != NULL) Ustrcat(buffer, " ETRN");
3743 if (acl_smtp_expn != NULL) Ustrcat(buffer, " EXPN");
3744 if (acl_smtp_vrfy != NULL) Ustrcat(buffer, " VRFY");
3745 smtp_printf("214%s\r\n", buffer);
3751 incomplete_transaction_log(US"connection lost");
3752 smtp_printf("421 %s lost input connection\r\n", smtp_active_hostname);
3754 /* Don't log by default unless in the middle of a message, as some mailers
3755 just drop the call rather than sending QUIT, and it clutters up the logs.
3758 if (sender_address != NULL || recipients_count > 0)
3759 log_write(L_lost_incoming_connection,
3761 "unexpected %s while reading SMTP command from %s%s",
3762 sender_host_unknown? "EOF" : "disconnection",
3763 host_and_ident(FALSE), smtp_read_error);
3765 else log_write(L_smtp_connection, LOG_MAIN, "%s lost%s",
3766 smtp_get_connection_info(), smtp_read_error);
3774 if (sender_address != NULL)
3776 done = synprot_error(L_smtp_protocol_error, 503, NULL,
3777 US"ETRN is not permitted inside a transaction");
3781 log_write(L_etrn, LOG_MAIN, "ETRN %s received from %s", smtp_cmd_argument,
3782 host_and_ident(FALSE));
3784 rc = acl_check(ACL_WHERE_ETRN, NULL, acl_smtp_etrn, &user_msg, &log_msg);
3787 done = smtp_handle_acl_fail(ACL_WHERE_ETRN, rc, user_msg, log_msg);
3791 /* Compute the serialization key for this command. */
3793 etrn_serialize_key = string_sprintf("etrn-%s\n", smtp_cmd_data);
3795 /* If a command has been specified for running as a result of ETRN, we
3796 permit any argument to ETRN. If not, only the # standard form is permitted,
3797 since that is strictly the only kind of ETRN that can be implemented
3798 according to the RFC. */
3800 if (smtp_etrn_command != NULL)
3804 etrn_command = smtp_etrn_command;
3805 deliver_domain = smtp_cmd_data;
3806 rc = transport_set_up_command(&argv, smtp_etrn_command, TRUE, 0, NULL,
3807 US"ETRN processing", &error);
3808 deliver_domain = NULL;
3811 log_write(0, LOG_MAIN|LOG_PANIC, "failed to set up ETRN command: %s",
3813 smtp_printf("458 Internal failure\r\n");
3818 /* Else set up to call Exim with the -R option. */
3822 if (*smtp_cmd_data++ != '#')
3824 done = synprot_error(L_smtp_syntax_error, 501, NULL,
3825 US"argument must begin with #");
3828 etrn_command = US"exim -R";
3829 argv = child_exec_exim(CEE_RETURN_ARGV, TRUE, NULL, TRUE, 2, US"-R",
3833 /* If we are host-testing, don't actually do anything. */
3839 debug_printf("ETRN command is: %s\n", etrn_command);
3840 debug_printf("ETRN command execution skipped\n");
3842 if (user_msg == NULL) smtp_printf("250 OK\r\n");
3843 else smtp_user_msg(US"250", user_msg);
3848 /* If ETRN queue runs are to be serialized, check the database to
3849 ensure one isn't already running. */
3851 if (smtp_etrn_serialize && !enq_start(etrn_serialize_key))
3853 smtp_printf("458 Already processing %s\r\n", smtp_cmd_data);
3857 /* Fork a child process and run the command. We don't want to have to
3858 wait for the process at any point, so set SIGCHLD to SIG_IGN before
3859 forking. It should be set that way anyway for external incoming SMTP,
3860 but we save and restore to be tidy. If serialization is required, we
3861 actually run the command in yet another process, so we can wait for it
3862 to complete and then remove the serialization lock. */
3864 oldsignal = signal(SIGCHLD, SIG_IGN);
3866 if ((pid = fork()) == 0)
3868 smtp_input = FALSE; /* This process is not associated with the */
3869 (void)fclose(smtp_in); /* SMTP call any more. */
3870 (void)fclose(smtp_out);
3872 signal(SIGCHLD, SIG_DFL); /* Want to catch child */
3874 /* If not serializing, do the exec right away. Otherwise, fork down
3875 into another process. */
3877 if (!smtp_etrn_serialize || (pid = fork()) == 0)
3879 DEBUG(D_exec) debug_print_argv(argv);
3880 exim_nullstd(); /* Ensure std{in,out,err} exist */
3881 execv(CS argv[0], (char *const *)argv);
3882 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "exec of \"%s\" (ETRN) failed: %s",
3883 etrn_command, strerror(errno));
3884 _exit(EXIT_FAILURE); /* paranoia */
3887 /* Obey this if smtp_serialize and the 2nd fork yielded non-zero. That
3888 is, we are in the first subprocess, after forking again. All we can do
3889 for a failing fork is to log it. Otherwise, wait for the 2nd process to
3890 complete, before removing the serialization. */
3893 log_write(0, LOG_MAIN|LOG_PANIC, "2nd fork for serialized ETRN "
3894 "failed: %s", strerror(errno));
3898 DEBUG(D_any) debug_printf("waiting for serialized ETRN process %d\n",
3900 (void)wait(&status);
3901 DEBUG(D_any) debug_printf("serialized ETRN process %d ended\n",
3905 enq_end(etrn_serialize_key);
3906 _exit(EXIT_SUCCESS);
3909 /* Back in the top level SMTP process. Check that we started a subprocess
3910 and restore the signal state. */
3914 log_write(0, LOG_MAIN|LOG_PANIC, "fork of process for ETRN failed: %s",
3916 smtp_printf("458 Unable to fork process\r\n");
3917 if (smtp_etrn_serialize) enq_end(etrn_serialize_key);
3921 if (user_msg == NULL) smtp_printf("250 OK\r\n");
3922 else smtp_user_msg(US"250", user_msg);
3925 signal(SIGCHLD, oldsignal);
3930 done = synprot_error(L_smtp_syntax_error, 501, NULL,
3931 US"unexpected argument data");
3935 /* This currently happens only for NULLs, but could be extended. */
3938 done = synprot_error(L_smtp_syntax_error, 0, NULL, /* Just logs */
3939 US"NULL character(s) present (shown as '?')");
3940 smtp_printf("501 NULL characters are not allowed in SMTP commands\r\n");
3945 if (smtp_inend >= smtp_inbuffer + in_buffer_size)
3946 smtp_inend = smtp_inbuffer + in_buffer_size - 1;
3947 c = smtp_inend - smtp_inptr;
3948 if (c > 150) c = 150;
3950 incomplete_transaction_log(US"sync failure");
3951 log_write(0, LOG_MAIN|LOG_REJECT, "SMTP protocol synchronization error "
3952 "(next input sent too soon: pipelining was%s advertised): "
3953 "rejected \"%s\" %s next input=\"%s\"",
3954 pipelining_advertised? "" : " not",
3955 smtp_cmd_buffer, host_and_ident(TRUE),
3956 string_printing(smtp_inptr));
3957 smtp_printf("554 SMTP synchronization error\r\n");
3958 done = 1; /* Pretend eof - drops connection */
3962 case TOO_MANY_NONMAIL_CMD:
3963 s = smtp_cmd_buffer;
3964 while (*s != 0 && !isspace(*s)) s++;
3965 incomplete_transaction_log(US"too many non-mail commands");
3966 log_write(0, LOG_MAIN|LOG_REJECT, "SMTP call from %s dropped: too many "
3967 "nonmail commands (last was \"%.*s\")", host_and_ident(FALSE),
3968 s - smtp_cmd_buffer, smtp_cmd_buffer);
3969 smtp_printf("554 Too many nonmail commands\r\n");
3970 done = 1; /* Pretend eof - drops connection */
3975 if (unknown_command_count++ >= smtp_max_unknown_commands)
3977 log_write(L_smtp_syntax_error, LOG_MAIN,
3978 "SMTP syntax error in \"%s\" %s %s",
3979 string_printing(smtp_cmd_buffer), host_and_ident(TRUE),
3980 US"unrecognized command");
3981 incomplete_transaction_log(US"unrecognized command");
3982 smtp_printf("500 Too many unrecognized commands\r\n");
3984 log_write(0, LOG_MAIN|LOG_REJECT, "SMTP call from %s dropped: too many "
3985 "unrecognized commands (last was \"%s\")", host_and_ident(FALSE),
3989 done = synprot_error(L_smtp_syntax_error, 500, NULL,
3990 US"unrecognized command");
3994 /* This label is used by goto's inside loops that want to break out to
3995 the end of the command-processing loop. */
3998 last_was_rej_mail = was_rej_mail; /* Remember some last commands for */
3999 last_was_rcpt = was_rcpt; /* protocol error handling */
4003 return done - 2; /* Convert yield values */
4006 /* End of smtp_in.c */