$smtp_command and $smtp_command_argument were incomplete for MAIL
[exim.git] / src / src / smtp_in.c
CommitLineData
ca86f471 1/* $Cambridge: exim/src/src/smtp_in.c,v 1.54 2007/02/20 11:37:16 ph10 Exp $ */
059ec3d9
PH
2
3/*************************************************
4* Exim - an Internet mail transport agent *
5*************************************************/
6
184e8823 7/* Copyright (c) University of Cambridge 1995 - 2007 */
059ec3d9
PH
8/* See the file NOTICE for conditions of use and distribution. */
9
10/* Functions for handling an incoming SMTP call. */
11
12
13#include "exim.h"
14
15
16/* Initialize for TCP wrappers if so configured. It appears that the macro
17HAVE_IPV6 is used in some versions of the tcpd.h header, so we unset it before
18including that header, and restore its value afterwards. */
19
20#ifdef USE_TCP_WRAPPERS
21
22 #if HAVE_IPV6
23 #define EXIM_HAVE_IPV6
24 #endif
25 #undef HAVE_IPV6
26 #include <tcpd.h>
27 #undef HAVE_IPV6
28 #ifdef EXIM_HAVE_IPV6
29 #define HAVE_IPV6 TRUE
30 #endif
31
32int allow_severity = LOG_INFO;
33int deny_severity = LOG_NOTICE;
34#endif
35
36
8d67ada3
PH
37/* Size of buffer for reading SMTP commands. We used to use 512, as defined
38by RFC 821. However, RFC 1869 specifies that this must be increased for SMTP
39commands that accept arguments, and this in particular applies to AUTH, where
40the data can be quite long. */
059ec3d9 41
3ee512ff 42#define smtp_cmd_buffer_size 2048
059ec3d9
PH
43
44/* Size of buffer for reading SMTP incoming packets */
45
46#define in_buffer_size 8192
47
48/* Structure for SMTP command list */
49
50typedef struct {
51 char *name;
52 int len;
53 short int cmd;
54 short int has_arg;
55 short int is_mail_cmd;
56} smtp_cmd_list;
57
58/* Codes for identifying commands. We order them so that those that come first
59are those for which synchronization is always required. Checking this can help
60block some spam. */
61
62enum {
63 /* These commands are required to be synchronized, i.e. to be the last in a
64 block of commands when pipelining. */
65
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 */
70
71 /* This is a dummy to identify the non-sync commands when pipelining */
72
73 NON_SYNC_CMD_PIPELINING,
74
75 /* These commands need not be synchronized when pipelining */
76
77 MAIL_CMD, RCPT_CMD, RSET_CMD,
78
79 /* This is a dummy to identify the non-sync commands when not pipelining */
80
81 NON_SYNC_CMD_NON_PIPELINING,
82
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. */
86
87 AUTH_CMD,
88
89 /* I'm not sure about these, but I don't think they matter. */
90
91 QUIT_CMD, HELP_CMD,
92
93 /* These are specials that don't correspond to actual commands */
94
95 EOF_CMD, OTHER_CMD, BADARG_CMD, BADCHAR_CMD, BADSYN_CMD,
96 TOO_MANY_NONMAIL_CMD };
97
98
b4ed4da0
PH
99/* This is a convenience macro for adding the identity of an SMTP command
100to the circular buffer that holds a list of the last n received. */
101
102#define HAD(n) \
103 smtp_connection_had[smtp_ch_index++] = n; \
104 if (smtp_ch_index >= SMTP_HBUFF_SIZE) smtp_ch_index = 0
105
059ec3d9
PH
106
107/*************************************************
108* Local static variables *
109*************************************************/
110
111static auth_instance *authenticated_by;
112static BOOL auth_advertised;
113#ifdef SUPPORT_TLS
114static BOOL tls_advertised;
115#endif
116static BOOL esmtp;
117static BOOL helo_required = FALSE;
118static BOOL helo_verify = FALSE;
119static BOOL helo_seen;
120static BOOL helo_accept_junk;
121static BOOL count_nonmail;
122static BOOL pipelining_advertised;
123static int nonmail_command_count;
124static int synprot_error_count;
125static int unknown_command_count;
126static int sync_cmd_limit;
127static int smtp_write_error = 0;
128
ca86f471
PH
129static uschar *smtp_data_buffer;
130static uschar *smtp_cmd_data;
131
059ec3d9
PH
132/* We need to know the position of RSET, HELO, EHLO, AUTH, and STARTTLS. Their
133final fields of all except AUTH are forced TRUE at the start of a new message
134setup, to allow one of each between messages that is not counted as a nonmail
135command. (In fact, only one of HELO/EHLO is not counted.) Also, we have to
136allow a new EHLO after starting up TLS.
137
138AUTH is "falsely" labelled as a mail command initially, so that it doesn't get
139counted. However, the flag is changed when AUTH is received, so that multiple
140failing AUTHs will eventually hit the limit. After a successful AUTH, another
141AUTH is already forbidden. After a TLS session is started, AUTH's flag is again
142forced TRUE, to allow for the re-authentication that can happen at that point.
143
144QUIT is also "falsely" labelled as a mail command so that it doesn't up the
145count of non-mail commands and possibly provoke an error. */
146
147static 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 },
152 #ifdef SUPPORT_TLS
153 { "starttls", sizeof("starttls")-1, STARTTLS_CMD, FALSE, FALSE },
154 #endif
155
156/* If you change anything above here, also fix the definitions below. */
157
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 }
167};
168
169static smtp_cmd_list *cmd_list_end =
170 cmd_list + sizeof(cmd_list)/sizeof(smtp_cmd_list);
171
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
177
b4ed4da0
PH
178/* This list of names is used for performing the smtp_no_mail logging action.
179It must be kept in step with the SCH_xxx enumerations. */
180
181static uschar *smtp_names[] =
182 {
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",
185 US"VRFY" };
186
059ec3d9 187static uschar *protocols[] = {
981756db
PH
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 */
059ec3d9
PH
194 };
195
196#define pnormal 0
981756db
PH
197#define pextend 2
198#define pcrpted 1 /* added to pextend or pnormal */
199#define pauthed 2 /* added to pextend */
059ec3d9
PH
200#define pnlocal 6 /* offset to remove "local" */
201
202/* When reading SMTP from a remote host, we have to use our own versions of the
203C input-reading functions, in order to be able to flush the SMTP output only
204when about to read more data from the socket. This is the only way to get
205optimal performance when the client is using pipelining. Flushing for every
206command causes a separate packet and reply packet each time; saving all the
207responses up (when pipelining) combines them into one packet and one response.
208
209For simplicity, these functions are used for *all* SMTP input, not only when
210receiving over a socket. However, after setting up a secure socket (SSL), input
211is read via the OpenSSL library, and another set of functions is used instead
212(see tls.c).
213
214These functions are set in the receive_getc etc. variables and called with the
215same interface as the C functions. However, since there can only ever be
216one incoming SMTP call, we just use a single buffer and flags. There is no need
217to implement a complicated private FILE-like structure.*/
218
219static uschar *smtp_inbuffer;
220static uschar *smtp_inptr;
221static uschar *smtp_inend;
222static int smtp_had_eof;
223static int smtp_had_error;
224
225
226/*************************************************
227* SMTP version of getc() *
228*************************************************/
229
230/* This gets the next byte from the SMTP input buffer. If the buffer is empty,
231it flushes the output, and refills the buffer, with a timeout. The signal
232handler is set appropriately by the calling function. This function is not used
233after a connection has negotated itself into an TLS/SSL state.
234
235Arguments: none
236Returns: the next character or EOF
237*/
238
239int
240smtp_getc(void)
241{
242if (smtp_inptr >= smtp_inend)
243 {
244 int rc, save_errno;
245 fflush(smtp_out);
246 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
247 rc = read(fileno(smtp_in), smtp_inbuffer, in_buffer_size);
248 save_errno = errno;
249 alarm(0);
250 if (rc <= 0)
251 {
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. */
254 if (rc < 0)
255 {
256 smtp_had_error = save_errno;
257 smtp_read_error = string_copy_malloc(
258 string_sprintf(" (error: %s)", strerror(save_errno)));
259 }
260 else smtp_had_eof = 1;
261 return EOF;
262 }
263 smtp_inend = smtp_inbuffer + rc;
264 smtp_inptr = smtp_inbuffer;
265 }
266return *smtp_inptr++;
267}
268
269
270
271/*************************************************
272* SMTP version of ungetc() *
273*************************************************/
274
275/* Puts a character back in the input buffer. Only ever
276called once.
277
278Arguments:
279 ch the character
280
281Returns: the character
282*/
283
284int
285smtp_ungetc(int ch)
286{
287*(--smtp_inptr) = ch;
288return ch;
289}
290
291
292
293
294/*************************************************
295* SMTP version of feof() *
296*************************************************/
297
298/* Tests for a previous EOF
299
300Arguments: none
301Returns: non-zero if the eof flag is set
302*/
303
304int
305smtp_feof(void)
306{
307return smtp_had_eof;
308}
309
310
311
312
313/*************************************************
314* SMTP version of ferror() *
315*************************************************/
316
317/* Tests for a previous read error, and returns with errno
318restored to what it was when the error was detected.
319
320Arguments: none
321Returns: non-zero if the error flag is set
322*/
323
324int
325smtp_ferror(void)
326{
327errno = smtp_had_error;
328return smtp_had_error;
329}
330
331
332
333
334/*************************************************
335* Write formatted string to SMTP channel *
336*************************************************/
337
338/* This is a separate function so that we don't have to repeat everything for
339TLS support or debugging. It is global so that the daemon and the
340authentication functions can use it. It does not return any error indication,
341because major problems such as dropped connections won't show up till an output
342flush for non-TLS connections. The smtp_fflush() function is available for
343checking that: for convenience, TLS output errors are remembered here so that
344they are also picked up later by smtp_fflush().
345
346Arguments:
347 format format string
348 ... optional arguments
349
350Returns: nothing
351*/
352
353void
354smtp_printf(char *format, ...)
355{
356va_list ap;
357
358DEBUG(D_receive)
359 {
898d150f 360 uschar *cr, *end;
059ec3d9
PH
361 va_start(ap, format);
362 (void) string_vformat(big_buffer, big_buffer_size, format, ap);
898d150f
PH
363 va_end(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);
059ec3d9
PH
367 debug_printf("SMTP>> %s", big_buffer);
368 }
369
370va_start(ap, format);
371
372/* If in a TLS session we have to format the string, and then write it using a
373TLS function. */
374
375#ifdef SUPPORT_TLS
376if (tls_active >= 0)
377 {
378 if (!string_vformat(big_buffer, big_buffer_size, format, ap))
379 {
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);
383 }
384 if (tls_write(big_buffer, Ustrlen(big_buffer)) < 0) smtp_write_error = -1;
385 }
386else
387#endif
388
389/* Otherwise, just use the standard library function. */
390
391if (vfprintf(smtp_out, format, ap) < 0) smtp_write_error = -1;
392va_end(ap);
393}
394
395
396
397/*************************************************
398* Flush SMTP out and check for error *
399*************************************************/
400
401/* This function isn't currently used within Exim (it detects errors when it
402tries to read the next SMTP input), but is available for use in local_scan().
403For non-TLS connections, it flushes the output and checks for errors. For
404TLS-connections, it checks for a previously-detected TLS write error.
405
406Arguments: none
407Returns: 0 for no error; -1 after an error
408*/
409
410int
411smtp_fflush(void)
412{
413if (tls_active < 0 && fflush(smtp_out) != 0) smtp_write_error = -1;
414return smtp_write_error;
415}
416
417
418
419/*************************************************
420* SMTP command read timeout *
421*************************************************/
422
423/* Signal handler for timing out incoming SMTP commands. This attempts to
424finish off tidily.
425
426Argument: signal number (SIGALRM)
427Returns: nothing
428*/
429
430static void
431command_timeout_handler(int sig)
432{
433sig = sig; /* Keep picky compilers happy */
434log_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));
438if (smtp_batched_input)
439 moan_smtp_batch(NULL, "421 SMTP command timeout"); /* Does not return */
440smtp_printf("421 %s: SMTP command timeout - closing connection\r\n",
441 smtp_active_hostname);
442mac_smtp_fflush();
443exim_exit(EXIT_FAILURE);
444}
445
446
447
448/*************************************************
449* SIGTERM received *
450*************************************************/
451
452/* Signal handler for handling SIGTERM. Again, try to finish tidily.
453
454Argument: signal number (SIGTERM)
455Returns: nothing
456*/
457
458static void
459command_sigterm_handler(int sig)
460{
461sig = sig; /* Keep picky compilers happy */
462log_write(0, LOG_MAIN, "%s closed after SIGTERM", smtp_get_connection_info());
463if (smtp_batched_input)
464 moan_smtp_batch(NULL, "421 SIGTERM received"); /* Does not return */
465smtp_printf("421 %s: Service not available - closing connection\r\n",
466 smtp_active_hostname);
467exim_exit(EXIT_FAILURE);
468}
469
470
471
472/*************************************************
473* Read one command line *
474*************************************************/
475
476/* Strictly, SMTP commands coming over the net are supposed to end with CRLF.
477There are sites that don't do this, and in any case internal SMTP probably
478should check only for LF. Consequently, we check here for LF only. The line
479ends up with [CR]LF removed from its end. If we get an overlong line, treat as
3ee512ff
PH
480an unknown command. The command is read into the global smtp_cmd_buffer so that
481it is available via $smtp_command.
059ec3d9
PH
482
483The character reading routine sets up a timeout for each block actually read
484from the input (which may contain more than one command). We set up a special
485signal handler that closes down the session on a timeout. Control does not
486return when it runs.
487
488Arguments:
489 check_sync if TRUE, check synchronization rules if global option is TRUE
490
491Returns: a code identifying the command (enumerated above)
492*/
493
494static int
495smtp_read_command(BOOL check_sync)
496{
497int c;
498int ptr = 0;
499smtp_cmd_list *p;
500BOOL hadnull = FALSE;
501
502os_non_restarting_signal(SIGALRM, command_timeout_handler);
503
504while ((c = (receive_getc)()) != '\n' && c != EOF)
505 {
3ee512ff 506 if (ptr >= smtp_cmd_buffer_size)
059ec3d9
PH
507 {
508 os_non_restarting_signal(SIGALRM, sigalrm_handler);
509 return OTHER_CMD;
510 }
511 if (c == 0)
512 {
513 hadnull = TRUE;
514 c = '?';
515 }
3ee512ff 516 smtp_cmd_buffer[ptr++] = c;
059ec3d9
PH
517 }
518
519receive_linecount++; /* For BSMTP errors */
520os_non_restarting_signal(SIGALRM, sigalrm_handler);
521
522/* If hit end of file, return pseudo EOF command. Whether we have a
523part-line already read doesn't matter, since this is an error state. */
524
525if (c == EOF) return EOF_CMD;
526
527/* Remove any CR and white space at the end of the line, and terminate the
528string. */
529
3ee512ff
PH
530while (ptr > 0 && isspace(smtp_cmd_buffer[ptr-1])) ptr--;
531smtp_cmd_buffer[ptr] = 0;
059ec3d9 532
3ee512ff 533DEBUG(D_receive) debug_printf("SMTP<< %s\n", smtp_cmd_buffer);
059ec3d9
PH
534
535/* NULLs are not allowed in SMTP commands */
536
537if (hadnull) return BADCHAR_CMD;
538
539/* Scan command list and return identity, having set the data pointer
540to the start of the actual data characters. Check for SMTP synchronization
541if required. */
542
543for (p = cmd_list; p < cmd_list_end; p++)
544 {
084efe8d
PH
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] == ' '))
059ec3d9
PH
549 {
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 */
556 return BADSYN_CMD;
557
ca86f471
PH
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. */
059ec3d9 563
3ee512ff 564 smtp_cmd_argument = smtp_cmd_buffer + p->len;
ca86f471
PH
565 while (isspace(*smtp_cmd_argument)) smtp_cmd_argument++;
566 Ustrcpy(smtp_data_buffer, smtp_cmd_argument);
567 smtp_cmd_data = smtp_data_buffer;
059ec3d9
PH
568
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.
573
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. */
576
577 if (!p->is_mail_cmd)
578 {
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;
583 }
584
ca86f471
PH
585 /* If there is data for a command that does not expect it, generate the
586 error here. */
059ec3d9 587
ca86f471 588 return (p->has_arg || *smtp_cmd_data == 0)? p->cmd : BADARG_CMD;
059ec3d9
PH
589 }
590 }
591
592/* Enforce synchronization for unknown commands */
593
594if (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 */
599 return BADSYN_CMD;
600
601return OTHER_CMD;
602}
603
604
605
606/*************************************************
607* Forced closedown of call *
608*************************************************/
609
610/* This function is called from log.c when Exim is dying because of a serious
611disaster, and also from some other places. If an incoming non-batched SMTP
612channel is open, it swallows the rest of the incoming message if in the DATA
613phase, sends the reply string, and gives an error to all subsequent commands
614except QUIT. The existence of an SMTP call is detected by the non-NULLness of
615smtp_in.
616
617Argument: SMTP reply string to send, excluding the code
618Returns: nothing
619*/
620
621void
622smtp_closedown(uschar *message)
623{
624if (smtp_in == NULL || smtp_batched_input) return;
625receive_swallow_smtp();
626smtp_printf("421 %s\r\n", message);
627
628for (;;)
629 {
630 switch(smtp_read_command(FALSE))
631 {
632 case EOF_CMD:
633 return;
634
635 case QUIT_CMD:
636 smtp_printf("221 %s closing connection\r\n", smtp_active_hostname);
637 mac_smtp_fflush();
638 return;
639
640 case RSET_CMD:
641 smtp_printf("250 Reset OK\r\n");
642 break;
643
644 default:
645 smtp_printf("421 %s\r\n", message);
646 break;
647 }
648 }
649}
650
651
652
653
654/*************************************************
655* Set up connection info for logging *
656*************************************************/
657
658/* This function is called when logging information about an SMTP connection.
659It sets up appropriate source information, depending on the type of connection.
dac79d3e
PH
660If sender_fullhost is NULL, we are at a very early stage of the connection;
661just use the IP address.
059ec3d9
PH
662
663Argument: none
664Returns: a string describing the connection
665*/
666
667uschar *
668smtp_get_connection_info(void)
669{
dac79d3e
PH
670uschar *hostname = (sender_fullhost == NULL)?
671 sender_host_address : sender_fullhost;
672
059ec3d9 673if (host_checking)
dac79d3e 674 return string_sprintf("SMTP connection from %s", hostname);
059ec3d9
PH
675
676if (sender_host_unknown || sender_host_notsocket)
677 return string_sprintf("SMTP connection from %s", sender_ident);
678
679if (is_inetd)
dac79d3e 680 return string_sprintf("SMTP connection from %s (via inetd)", hostname);
059ec3d9
PH
681
682if ((log_extra_selector & LX_incoming_interface) != 0 &&
683 interface_address != NULL)
dac79d3e 684 return string_sprintf("SMTP connection from %s I=[%s]:%d", hostname,
059ec3d9
PH
685 interface_address, interface_port);
686
dac79d3e 687return string_sprintf("SMTP connection from %s", hostname);
059ec3d9
PH
688}
689
690
691
b4ed4da0
PH
692/*************************************************
693* Log lack of MAIL if so configured *
694*************************************************/
695
696/* This function is called when an SMTP session ends. If the log selector
697smtp_no_mail is set, write a log line giving some details of what has happened
698in the SMTP session.
699
700Arguments: none
701Returns: nothing
702*/
703
704void
705smtp_log_no_mail(void)
706{
707int size, ptr, i;
708uschar *s, *sep;
709
710if (smtp_mailcmd_count > 0 || (log_extra_selector & LX_smtp_no_mail) == 0)
711 return;
712
713s = NULL;
714size = ptr = 0;
715
716if (sender_host_authenticated != NULL)
717 {
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);
721 }
722
723#ifdef SUPPORT_TLS
724if ((log_extra_selector & LX_tls_cipher) != 0 && tls_cipher != NULL)
725 s = string_append(s, &size, &ptr, 2, US" X=", tls_cipher);
726if ((log_extra_selector & LX_tls_certificate_verified) != 0 &&
727 tls_cipher != NULL)
728 s = string_append(s, &size, &ptr, 2, US" CV=",
729 tls_certificate_verified? "yes":"no");
730if ((log_extra_selector & LX_tls_peerdn) != 0 && tls_peerdn != NULL)
731 s = string_append(s, &size, &ptr, 3, US" DN=\"", tls_peerdn, US"\"");
732#endif
733
734sep = (smtp_connection_had[SMTP_HBUFF_SIZE-1] != SCH_NONE)?
735 US" C=..." : US" C=";
736for (i = smtp_ch_index; i < SMTP_HBUFF_SIZE; i++)
737 {
738 if (smtp_connection_had[i] != SCH_NONE)
739 {
740 s = string_append(s, &size, &ptr, 2, sep,
741 smtp_names[smtp_connection_had[i]]);
742 sep = US",";
743 }
744 }
745
746for (i = 0; i < smtp_ch_index; i++)
747 {
748 s = string_append(s, &size, &ptr, 2, sep, smtp_names[smtp_connection_had[i]]);
749 sep = US",";
750 }
751
752if (s != NULL) s[ptr] = 0; else s = US"";
753log_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);
756}
757
758
759
059ec3d9
PH
760/*************************************************
761* Check HELO line and set sender_helo_name *
762*************************************************/
763
764/* Check the format of a HELO line. The data for HELO/EHLO is supposed to be
765the domain name of the sending host, or an ip literal in square brackets. The
766arrgument is placed in sender_helo_name, which is in malloc store, because it
767must persist over multiple incoming messages. If helo_accept_junk is set, this
768host is permitted to send any old junk (needed for some broken hosts).
769Otherwise, helo_allow_chars can be used for rogue characters in general
770(typically people want to let in underscores).
771
772Argument:
773 s the data portion of the line (already past any white space)
774
775Returns: TRUE or FALSE
776*/
777
778static BOOL
779check_helo(uschar *s)
780{
781uschar *start = s;
782uschar *end = s + Ustrlen(s);
783BOOL yield = helo_accept_junk;
784
785/* Discard any previous helo name */
786
787if (sender_helo_name != NULL)
788 {
789 store_free(sender_helo_name);
790 sender_helo_name = NULL;
791 }
792
793/* Skip tests if junk is permitted. */
794
795if (!yield)
796 {
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. */
800
801 if (*s == '[')
802 {
803 if (end[-1] == ']')
804 {
805 end[-1] = 0;
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);
810 else
811 yield = (string_is_ip_address(s+1, NULL) != 0);
812 end[-1] = ']';
813 }
814 }
815
816 /* Non-literals must be alpha, dot, hyphen, plus any non-valid chars
817 that have been configured (usually underscore - sigh). */
818
819 else if (*s != 0)
820 {
821 yield = TRUE;
822 while (*s != 0)
823 {
824 if (!isalnum(*s) && *s != '.' && *s != '-' &&
825 Ustrchr(helo_allow_chars, *s) == NULL)
826 {
827 yield = FALSE;
828 break;
829 }
830 s++;
831 }
832 }
833 }
834
835/* Save argument if OK */
836
837if (yield) sender_helo_name = string_copy_malloc(start);
838return yield;
839}
840
841
842
843
844
845/*************************************************
846* Extract SMTP command option *
847*************************************************/
848
ca86f471 849/* This function picks the next option setting off the end of smtp_cmd_data. It
059ec3d9
PH
850is called for MAIL FROM and RCPT TO commands, to pick off the optional ESMTP
851things that can appear there.
852
853Arguments:
854 name point this at the name
855 value point this at the data string
856
857Returns: TRUE if found an option
858*/
859
860static BOOL
861extract_option(uschar **name, uschar **value)
862{
863uschar *n;
ca86f471 864uschar *v = smtp_cmd_data + Ustrlen(smtp_cmd_data) - 1;
059ec3d9
PH
865while (isspace(*v)) v--;
866v[1] = 0;
867
ca86f471 868while (v > smtp_cmd_data && *v != '=' && !isspace(*v)) v--;
059ec3d9
PH
869if (*v != '=') return FALSE;
870
871n = v;
872while(isalpha(n[-1])) n--;
873
874if (n[-1] != ' ') return FALSE;
875
876n[-1] = 0;
877*name = n;
878*v++ = 0;
879*value = v;
880return TRUE;
881}
882
883
884
885
886
059ec3d9
PH
887/*************************************************
888* Reset for new message *
889*************************************************/
890
891/* This function is called whenever the SMTP session is reset from
892within either of the setup functions.
893
894Argument: the stacking pool storage reset point
895Returns: nothing
896*/
897
898static void
899smtp_reset(void *reset_point)
900{
059ec3d9
PH
901store_reset(reset_point);
902recipients_list = NULL;
903rcpt_count = rcpt_defer_count = rcpt_fail_count =
904 raw_recipients_count = recipients_count = recipients_list_max = 0;
2e0c1448 905message_linecount = 0;
059ec3d9 906message_size = -1;
71fafd95 907acl_added_headers = NULL;
059ec3d9 908queue_only_policy = FALSE;
69358f02 909deliver_freeze = FALSE; /* Can be set by ACL */
6a3f1455 910freeze_tell = freeze_tell_config; /* Can be set by ACL */
29aba418 911fake_response = OK; /* Can be set by ACL */
6951ac6c 912#ifdef WITH_CONTENT_SCAN
8523533c
TK
913no_mbox_unspool = FALSE; /* Can be set by ACL */
914#endif
69358f02 915submission_mode = FALSE; /* Can be set by ACL */
8800895a 916suppress_local_fixups = FALSE; /* Can be set by ACL */
69358f02
PH
917active_local_from_check = local_from_check; /* Can be set by ACL */
918active_local_sender_retain = local_sender_retain; /* Can be set by ACL */
059ec3d9 919sender_address = NULL;
2fe1a124 920submission_name = NULL; /* Can be set by ACL */
059ec3d9
PH
921raw_sender = NULL; /* After SMTP rewrite, before qualifying */
922sender_address_unrewritten = NULL; /* Set only after verify rewrite */
923sender_verified_list = NULL; /* No senders verified */
924memset(sender_address_cache, 0, sizeof(sender_address_cache));
925memset(sender_domain_cache, 0, sizeof(sender_domain_cache));
926authenticated_sender = NULL;
8523533c
TK
927#ifdef EXPERIMENTAL_BRIGHTMAIL
928bmi_run = 0;
929bmi_verdicts = NULL;
930#endif
fb2274d4
TK
931#ifdef EXPERIMENTAL_DOMAINKEYS
932dk_do_verify = 0;
933#endif
8523533c
TK
934#ifdef EXPERIMENTAL_SPF
935spf_header_comment = NULL;
936spf_received = NULL;
8e669ac1 937spf_result = NULL;
8523533c
TK
938spf_smtp_comment = NULL;
939#endif
059ec3d9
PH
940body_linecount = body_zerocount = 0;
941
870f6ba8
TF
942sender_rate = sender_rate_limit = sender_rate_period = NULL;
943ratelimiters_mail = NULL; /* Updated by ratelimit ACL condition */
944 /* Note that ratelimiters_conn persists across resets. */
945
38a0a95f 946/* Reset message ACL variables */
47ca6d6c 947
38a0a95f 948acl_var_m = NULL;
059ec3d9
PH
949
950/* The message body variables use malloc store. They may be set if this is
951not the first message in an SMTP session and the previous message caused them
952to be referenced in an ACL. */
953
954if (message_body != NULL)
955 {
956 store_free(message_body);
957 message_body = NULL;
958 }
959
960if (message_body_end != NULL)
961 {
962 store_free(message_body_end);
963 message_body_end = NULL;
964 }
965
966/* Warning log messages are also saved in malloc store. They are saved to avoid
967repetition in the same message, but it seems right to repeat them for different
4e88a19f 968messages. */
059ec3d9
PH
969
970while (acl_warn_logged != NULL)
971 {
972 string_item *this = acl_warn_logged;
973 acl_warn_logged = acl_warn_logged->next;
974 store_free(this);
975 }
976}
977
978
979
980
981
982/*************************************************
983* Initialize for incoming batched SMTP message *
984*************************************************/
985
986/* This function is called from smtp_setup_msg() in the case when
987smtp_batched_input is true. This happens when -bS is used to pass a whole batch
988of messages in one file with SMTP commands between them. All errors must be
989reported by sending a message, and only MAIL FROM, RCPT TO, and DATA are
990relevant. After an error on a sender, or an invalid recipient, the remainder
991of the message is skipped. The value of received_protocol is already set.
992
993Argument: none
994Returns: > 0 message successfully started (reached DATA)
995 = 0 QUIT read or end of file reached
996 < 0 should not occur
997*/
998
999static int
1000smtp_setup_batch_msg(void)
1001{
1002int done = 0;
1003void *reset_point = store_get(0);
1004
1005/* Save the line count at the start of each transaction - single commands
1006like HELO and RSET count as whole transactions. */
1007
1008bsmtp_transaction_linecount = receive_linecount;
1009
1010if ((receive_feof)()) return 0; /* Treat EOF as QUIT */
1011
1012smtp_reset(reset_point); /* Reset for start of message */
1013
1014/* Deal with SMTP commands. This loop is exited by setting done to a POSITIVE
1015value. The values are 2 larger than the required yield of the function. */
1016
1017while (done <= 0)
1018 {
1019 uschar *errmess;
1020 uschar *recipient = NULL;
1021 int start, end, sender_domain, recipient_domain;
1022
1023 switch(smtp_read_command(FALSE))
1024 {
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. */
1028
1029 case HELO_CMD:
1030 case EHLO_CMD:
1031
ca86f471 1032 check_helo(smtp_cmd_data);
059ec3d9
PH
1033 /* Fall through */
1034
1035 case RSET_CMD:
1036 smtp_reset(reset_point);
1037 bsmtp_transaction_linecount = receive_linecount;
1038 break;
1039
1040
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. */
1046
1047 case MAIL_CMD:
1048 if (sender_address != NULL)
1049 /* The function moan_smtp_batch() does not return. */
3ee512ff 1050 moan_smtp_batch(smtp_cmd_buffer, "503 Sender already given");
059ec3d9 1051
ca86f471 1052 if (smtp_cmd_data[0] == 0)
059ec3d9 1053 /* The function moan_smtp_batch() does not return. */
3ee512ff 1054 moan_smtp_batch(smtp_cmd_buffer, "501 MAIL FROM must have an address operand");
059ec3d9
PH
1055
1056 /* Reset to start of message */
1057
1058 smtp_reset(reset_point);
1059
1060 /* Apply SMTP rewrite */
1061
1062 raw_sender = ((rewrite_existflags & rewrite_smtp) != 0)?
ca86f471
PH
1063 rewrite_one(smtp_cmd_data, rewrite_smtp|rewrite_smtp_sender, NULL, FALSE,
1064 US"", global_rewrite_rules) : smtp_cmd_data;
059ec3d9
PH
1065
1066 /* Extract the address; the TRUE flag allows <> as valid */
1067
1068 raw_sender =
1069 parse_extract_address(raw_sender, &errmess, &start, &end, &sender_domain,
1070 TRUE);
1071
1072 if (raw_sender == NULL)
1073 /* The function moan_smtp_batch() does not return. */
3ee512ff 1074 moan_smtp_batch(smtp_cmd_buffer, "501 %s", errmess);
059ec3d9
PH
1075
1076 sender_address = string_copy(raw_sender);
1077
1078 /* Qualify unqualified sender addresses if permitted to do so. */
1079
1080 if (sender_domain == 0 && sender_address[0] != 0 && sender_address[0] != '@')
1081 {
1082 if (allow_unqualified_sender)
1083 {
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);
1087 }
1088 /* The function moan_smtp_batch() does not return. */
3ee512ff 1089 else moan_smtp_batch(smtp_cmd_buffer, "501 sender address must contain "
059ec3d9
PH
1090 "a domain");
1091 }
1092 break;
1093
1094
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. */
1101
1102 case RCPT_CMD:
1103 if (sender_address == NULL)
1104 /* The function moan_smtp_batch() does not return. */
3ee512ff 1105 moan_smtp_batch(smtp_cmd_buffer, "503 No sender yet given");
059ec3d9 1106
ca86f471 1107 if (smtp_cmd_data[0] == 0)
059ec3d9 1108 /* The function moan_smtp_batch() does not return. */
3ee512ff 1109 moan_smtp_batch(smtp_cmd_buffer, "501 RCPT TO must have an address operand");
059ec3d9
PH
1110
1111 /* Check maximum number allowed */
1112
1113 if (recipients_max > 0 && recipients_count + 1 > recipients_max)
1114 /* The function moan_smtp_batch() does not return. */
3ee512ff 1115 moan_smtp_batch(smtp_cmd_buffer, "%s too many recipients",
059ec3d9
PH
1116 recipients_max_reject? "552": "452");
1117
1118 /* Apply SMTP rewrite, then extract address. Don't allow "<>" as a
1119 recipient address */
1120
1121 recipient = ((rewrite_existflags & rewrite_smtp) != 0)?
ca86f471
PH
1122 rewrite_one(smtp_cmd_data, rewrite_smtp, NULL, FALSE, US"",
1123 global_rewrite_rules) : smtp_cmd_data;
059ec3d9
PH
1124
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 */
1129
1130 if (recipient == NULL)
1131 /* The function moan_smtp_batch() does not return. */
3ee512ff 1132 moan_smtp_batch(smtp_cmd_buffer, "501 %s", errmess);
059ec3d9
PH
1133
1134 /* If the recipient address is unqualified, qualify it if permitted. Then
1135 add it to the list of recipients. */
1136
1137 if (recipient_domain == 0)
1138 {
1139 if (allow_unqualified_recipient)
1140 {
1141 DEBUG(D_receive) debug_printf("unqualified address %s accepted\n",
1142 recipient);
1143 recipient = rewrite_address_qualify(recipient, TRUE);
1144 }
1145 /* The function moan_smtp_batch() does not return. */
3ee512ff 1146 else moan_smtp_batch(smtp_cmd_buffer, "501 recipient address must contain "
059ec3d9
PH
1147 "a domain");
1148 }
1149 receive_add_recipient(recipient, -1);
1150 break;
1151
1152
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. */
1156
1157 case DATA_CMD:
1158 if (sender_address == NULL || recipients_count <= 0)
1159 {
1160 /* The function moan_smtp_batch() does not return. */
1161 if (sender_address == NULL)
3ee512ff 1162 moan_smtp_batch(smtp_cmd_buffer,
059ec3d9
PH
1163 "503 MAIL FROM:<sender> command must precede DATA");
1164 else
3ee512ff 1165 moan_smtp_batch(smtp_cmd_buffer,
059ec3d9
PH
1166 "503 RCPT TO:<recipient> must precede DATA");
1167 }
1168 else
1169 {
1170 done = 3; /* DATA successfully achieved */
1171 message_ended = END_NOTENDED; /* Indicate in middle of message */
1172 }
1173 break;
1174
1175
1176 /* The VRFY, EXPN, HELP, ETRN, and NOOP commands are ignored. */
1177
1178 case VRFY_CMD:
1179 case EXPN_CMD:
1180 case HELP_CMD:
1181 case NOOP_CMD:
1182 case ETRN_CMD:
1183 bsmtp_transaction_linecount = receive_linecount;
1184 break;
1185
1186
1187 case EOF_CMD:
1188 case QUIT_CMD:
1189 done = 2;
1190 break;
1191
1192
1193 case BADARG_CMD:
1194 /* The function moan_smtp_batch() does not return. */
3ee512ff 1195 moan_smtp_batch(smtp_cmd_buffer, "501 Unexpected argument data");
059ec3d9
PH
1196 break;
1197
1198
1199 case BADCHAR_CMD:
1200 /* The function moan_smtp_batch() does not return. */
3ee512ff 1201 moan_smtp_batch(smtp_cmd_buffer, "501 Unexpected NULL in SMTP command");
059ec3d9
PH
1202 break;
1203
1204
1205 default:
1206 /* The function moan_smtp_batch() does not return. */
3ee512ff 1207 moan_smtp_batch(smtp_cmd_buffer, "500 Command unrecognized");
059ec3d9
PH
1208 break;
1209 }
1210 }
1211
1212return done - 2; /* Convert yield values */
1213}
1214
1215
1216
1217
1218/*************************************************
1219* Start an SMTP session *
1220*************************************************/
1221
1222/* This function is called at the start of an SMTP session. Thereafter,
1223smtp_setup_msg() is called to initiate each separate message. This
1224function does host-specific testing, and outputs the banner line.
1225
1226Arguments: none
1227Returns: FALSE if the session can not continue; something has
1228 gone wrong, or the connection to the host is blocked
1229*/
1230
1231BOOL
1232smtp_start_session(void)
1233{
1234int size = 256;
4e88a19f
PH
1235int ptr, esclen;
1236uschar *user_msg, *log_msg;
1237uschar *code, *esc;
059ec3d9
PH
1238uschar *p, *s, *ss;
1239
b4ed4da0
PH
1240smtp_connection_start = time(NULL);
1241for (smtp_ch_index = 0; smtp_ch_index < SMTP_HBUFF_SIZE; smtp_ch_index++)
1242 smtp_connection_had[smtp_ch_index] = SCH_NONE;
1243smtp_ch_index = 0;
1244
00f00ca5
PH
1245/* Default values for certain variables */
1246
059ec3d9 1247helo_seen = esmtp = helo_accept_junk = FALSE;
b4ed4da0 1248smtp_mailcmd_count = 0;
059ec3d9
PH
1249count_nonmail = TRUE_UNSET;
1250synprot_error_count = unknown_command_count = nonmail_command_count = 0;
1251smtp_delay_mail = smtp_rlm_base;
1252auth_advertised = FALSE;
1253pipelining_advertised = FALSE;
cf8b11a5 1254pipelining_enable = TRUE;
059ec3d9
PH
1255sync_cmd_limit = NON_SYNC_CMD_NON_PIPELINING;
1256
1257memset(sender_host_cache, 0, sizeof(sender_host_cache));
1258
33d73e3b
PH
1259/* If receiving by -bs from a trusted user, or testing with -bh, we allow
1260authentication settings from -oMaa to remain in force. */
1261
1262if (!host_checking && !sender_host_notsocket) sender_host_authenticated = NULL;
059ec3d9
PH
1263authenticated_by = NULL;
1264
1265#ifdef SUPPORT_TLS
1266tls_cipher = tls_peerdn = NULL;
1267tls_advertised = FALSE;
1268#endif
1269
1270/* Reset ACL connection variables */
1271
38a0a95f 1272acl_var_c = NULL;
059ec3d9 1273
ca86f471 1274/* Allow for trailing 0 in the command and data buffers. */
3ee512ff 1275
ca86f471 1276smtp_cmd_buffer = (uschar *)malloc(2*smtp_cmd_buffer_size + 2);
3ee512ff 1277if (smtp_cmd_buffer == NULL)
059ec3d9
PH
1278 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1279 "malloc() failed for SMTP command buffer");
ca86f471 1280smtp_data_buffer = smtp_cmd_buffer + smtp_cmd_buffer_size + 1;
059ec3d9
PH
1281
1282/* For batched input, the protocol setting can be overridden from the
1283command line by a trusted caller. */
1284
1285if (smtp_batched_input)
1286 {
1287 if (received_protocol == NULL) received_protocol = US"local-bsmtp";
1288 }
1289
1290/* For non-batched SMTP input, the protocol setting is forced here. It will be
1291reset later if any of EHLO/AUTH/STARTTLS are received. */
1292
1293else
1294 received_protocol =
1295 protocols[pnormal] + ((sender_host_address != NULL)? pnlocal : 0);
1296
1297/* Set up the buffer for inputting using direct read() calls, and arrange to
1298call the local functions instead of the standard C ones. */
1299
1300smtp_inbuffer = (uschar *)malloc(in_buffer_size);
1301if (smtp_inbuffer == NULL)
1302 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "malloc() failed for SMTP input buffer");
1303receive_getc = smtp_getc;
1304receive_ungetc = smtp_ungetc;
1305receive_feof = smtp_feof;
1306receive_ferror = smtp_ferror;
1307smtp_inptr = smtp_inend = smtp_inbuffer;
1308smtp_had_eof = smtp_had_error = 0;
1309
1310/* Set up the message size limit; this may be host-specific */
1311
d45b1de8
PH
1312thismessage_size_limit = expand_string_integer(message_size_limit, TRUE);
1313if (expand_string_message != NULL)
059ec3d9
PH
1314 {
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);
1318 else
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");
1322 return FALSE;
1323 }
1324
1325/* When a message is input locally via the -bs or -bS options, sender_host_
1326unknown is set unless -oMa was used to force an IP address, in which case it
1327is checked like a real remote connection. When -bs is used from inetd, this
1328flag is not set, causing the sending host to be checked. The code that deals
1329with IP source routing (if configured) is never required for -bs or -bS and
1330the flag sender_host_notsocket is used to suppress it.
1331
1332If smtp_accept_max and smtp_accept_reserve are set, keep some connections in
1333reserve for certain hosts and/or networks. */
1334
1335if (!sender_host_unknown)
1336 {
1337 int rc;
1338 BOOL reserved_host = FALSE;
1339
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.
1342
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.
1349
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.
1354
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.
1358
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
1361 support altogether.
1362
1363 How to do this properly in IPv6 is not yet known. */
1364
1365 #if !HAVE_IPV6 && !defined(NO_IP_OPTIONS)
1366
1367 #ifdef GLIBC_IP_OPTIONS
1368 #if (!defined __GLIBC__) || (__GLIBC__ < 2)
1369 #define OPTSTYLE 1
1370 #else
1371 #define OPTSTYLE 2
1372 #endif
1373 #elif defined DARWIN_IP_OPTIONS
1374 #define OPTSTYLE 2
1375 #else
1376 #define OPTSTYLE 3
1377 #endif
1378
1379 if (!host_checking && !sender_host_notsocket)
1380 {
1381 #if OPTSTYLE == 1
36a3b041 1382 EXIM_SOCKLEN_T optlen = sizeof(struct ip_options) + MAX_IPOPTLEN;
059ec3d9
PH
1383 struct ip_options *ipopt = store_get(optlen);
1384 #elif OPTSTYLE == 2
1385 struct ip_opts ipoptblock;
1386 struct ip_opts *ipopt = &ipoptblock;
36a3b041 1387 EXIM_SOCKLEN_T optlen = sizeof(ipoptblock);
059ec3d9
PH
1388 #else
1389 struct ipoption ipoptblock;
1390 struct ipoption *ipopt = &ipoptblock;
36a3b041 1391 EXIM_SOCKLEN_T optlen = sizeof(ipoptblock);
059ec3d9
PH
1392 #endif
1393
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
1399 check. */
1400
1401 DEBUG(D_receive) debug_printf("checking for IP options\n");
1402
1403 if (getsockopt(fileno(smtp_out), IPPROTO_IP, IP_OPTIONS, (uschar *)(ipopt),
1404 &optlen) < 0)
1405 {
1406 if (errno != ENOPROTOOPT)
1407 {
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");
1411 return FALSE;
1412 }
1413 }
1414
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. */
1419
1420 else if (optlen > 0)
1421 {
1422 uschar *p = big_buffer;
1423 uschar *pend = big_buffer + big_buffer_size;
1424 uschar *opt, *adptr;
1425 int optcount;
1426 struct in_addr addr;
1427
1428 #if OPTSTYLE == 1
1429 uschar *optstart = (uschar *)(ipopt->__data);
1430 #elif OPTSTYLE == 2
1431 uschar *optstart = (uschar *)(ipopt->ip_opts);
1432 #else
1433 uschar *optstart = (uschar *)(ipopt->ipopt_list);
1434 #endif
1435
1436 DEBUG(D_receive) debug_printf("IP options exist\n");
1437
1438 Ustrcpy(p, "IP options on incoming call:");
1439 p += Ustrlen(p);
1440
1441 for (opt = optstart; opt != NULL &&
1442 opt < (uschar *)(ipopt) + optlen;)
1443 {
1444 switch (*opt)
1445 {
1446 case IPOPT_EOL:
1447 opt = NULL;
1448 break;
1449
1450 case IPOPT_NOP:
1451 opt++;
1452 break;
1453
1454 case IPOPT_SSRR:
1455 case IPOPT_LSRR:
1456 if (!string_format(p, pend-p, " %s [@%s",
1457 (*opt == IPOPT_SSRR)? "SSRR" : "LSRR",
1458 #if OPTSTYLE == 1
1459 inet_ntoa(*((struct in_addr *)(&(ipopt->faddr))))))
1460 #elif OPTSTYLE == 2
1461 inet_ntoa(ipopt->ip_dst)))
1462 #else
1463 inet_ntoa(ipopt->ipopt_dst)))
1464 #endif
1465 {
1466 opt = NULL;
1467 break;
1468 }
1469
1470 p += Ustrlen(p);
1471 optcount = (opt[1] - 3) / sizeof(struct in_addr);
1472 adptr = opt + 3;
1473 while (optcount-- > 0)
1474 {
1475 memcpy(&addr, adptr, sizeof(addr));
1476 if (!string_format(p, pend - p - 1, "%s%s",
1477 (optcount == 0)? ":" : "@", inet_ntoa(addr)))
1478 {
1479 opt = NULL;
1480 break;
1481 }
1482 p += Ustrlen(p);
1483 adptr += sizeof(struct in_addr);
1484 }
1485 *p++ = ']';
1486 opt += opt[1];
1487 break;
1488
1489 default:
1490 {
1491 int i;
1492 if (pend - p < 4 + 3*opt[1]) { opt = NULL; break; }
1493 Ustrcat(p, "[ ");
1494 p += 2;
1495 for (i = 0; i < opt[1]; i++)
1496 {
1497 sprintf(CS p, "%2.2x ", opt[i]);
1498 p += 3;
1499 }
1500 *p++ = ']';
1501 }
1502 opt += opt[1];
1503 break;
1504 }
1505 }
1506
1507 *p = 0;
1508 log_write(0, LOG_MAIN, "%s", big_buffer);
1509
1510 /* Refuse any call with IP options. This is what tcpwrappers 7.5 does. */
1511
1512 log_write(0, LOG_MAIN|LOG_REJECT,
1513 "connection from %s refused (IP options)", host_and_ident(FALSE));
1514
1515 smtp_printf("554 SMTP service not available\r\n");
1516 return FALSE;
1517 }
1518
1519 /* Length of options = 0 => there are no options */
1520
1521 else DEBUG(D_receive) debug_printf("no IP options found\n");
1522 }
1523 #endif /* HAVE_IPV6 && !defined(NO_IP_OPTIONS) */
1524
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. */
1528
1529 if (smtp_accept_keepalive && !sender_host_notsocket)
1530 ip_keepalive(fileno(smtp_out), sender_host_address, FALSE);
1531
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
1535 checks later. */
1536
1537 if (verify_check_host(&host_lookup) == OK)
1538 {
1539 (void)host_name_lookup();
1540 host_build_sender_fullhost();
1541 }
1542
1543 /* Delay this until we have the full name, if it is looked up. */
1544
1545 set_process_info("handling incoming connection from %s",
1546 host_and_ident(FALSE));
1547
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. */
1550
1551 #ifdef SUPPORT_TLS
83da1223
PH
1552 if (tls_on_connect &&
1553 tls_server_start(tls_require_ciphers,
1554 gnutls_require_mac, gnutls_require_kx, gnutls_require_proto) != OK)
059ec3d9
PH
1555 return FALSE;
1556 #endif
1557
1558 /* Test for explicit connection rejection */
1559
1560 if (verify_check_host(&host_reject_connection) == OK)
1561 {
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");
1565 return FALSE;
1566 }
1567
afb3eaaf
PH
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
1575 not exist). */
059ec3d9
PH
1576
1577 #ifdef USE_TCP_WRAPPERS
afb3eaaf 1578 errno = 0;
059ec3d9
PH
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))
1583 {
afb3eaaf
PH
1584 if (errno == 0 || errno == ENOENT)
1585 {
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");
1591 }
1592 else
1593 {
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");
1601 }
059ec3d9
PH
1602 return FALSE;
1603 }
1604 #endif
1605
b01dd148
PH
1606 /* Check for reserved slots. The value of smtp_accept_count has already been
1607 incremented to include this process. */
059ec3d9
PH
1608
1609 if (smtp_accept_max > 0 &&
b01dd148 1610 smtp_accept_count > smtp_accept_max - smtp_accept_reserve)
059ec3d9
PH
1611 {
1612 if ((rc = verify_check_host(&smtp_reserve_hosts)) != OK)
1613 {
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",
b01dd148 1617 host_and_ident(FALSE), smtp_accept_count - 1, smtp_accept_max,
059ec3d9
PH
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);
1621 return FALSE;
1622 }
1623 reserved_host = TRUE;
1624 }
1625
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. */
1631
1632 if (smtp_load_reserve >= 0 &&
1633 load_average > smtp_load_reserve &&
1634 !reserved_host &&
1635 verify_check_host(&smtp_reserve_hosts) != OK)
1636 {
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);
1643 return FALSE;
1644 }
1645
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. */
1651
1652 allow_unqualified_sender =
1653 verify_check_host(&sender_unqualified_hosts) == OK;
1654
1655 allow_unqualified_recipient =
1656 verify_check_host(&recipient_unqualified_hosts) == OK;
1657
1658 /* Determine whether HELO/EHLO is required for this host. The requirement
1659 can be hard or soft. */
1660
1661 helo_required = verify_check_host(&helo_verify_hosts) == OK;
1662 if (!helo_required)
1663 helo_verify = verify_check_host(&helo_try_verify_hosts) == OK;
1664
1665 /* Determine whether this hosts is permitted to send syntactic junk
1666 after a HELO or EHLO command. */
1667
1668 helo_accept_junk = verify_check_host(&helo_accept_junk_hosts) == OK;
1669 }
1670
1671/* For batch SMTP input we are now done. */
1672
1673if (smtp_batched_input) return TRUE;
1674
1675/* Run the ACL if it exists */
1676
4e88a19f 1677user_msg = NULL;
059ec3d9
PH
1678if (acl_smtp_connect != NULL)
1679 {
1680 int rc;
64ffc24f 1681 rc = acl_check(ACL_WHERE_CONNECT, NULL, acl_smtp_connect, &user_msg,
059ec3d9
PH
1682 &log_msg);
1683 if (rc != OK)
1684 {
1685 (void)smtp_handle_acl_fail(ACL_WHERE_CONNECT, rc, user_msg, log_msg);
1686 return FALSE;
1687 }
1688 }
1689
1690/* Output the initial message for a two-way SMTP connection. It may contain
1691newlines, which then cause a multi-line response to be given. */
1692
4e88a19f
PH
1693code = US"220"; /* Default status code */
1694esc = US""; /* Default extended status code */
1695esclen = 0; /* Length of esc */
1696
1697if (user_msg == NULL)
1698 {
1699 s = expand_string(smtp_banner);
1700 if (s == NULL)
1701 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Expansion of \"%s\" (smtp_banner) "
1702 "failed: %s", smtp_banner, expand_string_message);
1703 }
1704else
1705 {
1706 int codelen = 3;
1707 s = user_msg;
1708 smtp_message_code(&code, &codelen, &s, NULL);
d6a96edc 1709 if (codelen > 4)
4e88a19f
PH
1710 {
1711 esc = code + 4;
1712 esclen = codelen - 4;
1713 }
1714 }
059ec3d9
PH
1715
1716/* Remove any terminating newlines; might as well remove trailing space too */
1717
1718p = s + Ustrlen(s);
1719while (p > s && isspace(p[-1])) p--;
1720*p = 0;
1721
1722/* It seems that CC:Mail is braindead, and assumes that the greeting message
1723is all contained in a single IP packet. The original code wrote out the
1724greeting using several calls to fprint/fputc, and on busy servers this could
1725cause it to be split over more than one packet - which caused CC:Mail to fall
1726over when it got the second part of the greeting after sending its first
1727command. Sigh. To try to avoid this, build the complete greeting message
1728first, and output it in one fell swoop. This gives a better chance of it
1729ending up as a single packet. */
1730
1731ss = store_get(size);
1732ptr = 0;
1733
1734p = s;
1735do /* At least once, in case we have an empty string */
1736 {
1737 int len;
1738 uschar *linebreak = Ustrchr(p, '\n');
4e88a19f 1739 ss = string_cat(ss, &size, &ptr, code, 3);
059ec3d9
PH
1740 if (linebreak == NULL)
1741 {
1742 len = Ustrlen(p);
4e88a19f 1743 ss = string_cat(ss, &size, &ptr, US" ", 1);
059ec3d9
PH
1744 }
1745 else
1746 {
1747 len = linebreak - p;
4e88a19f 1748 ss = string_cat(ss, &size, &ptr, US"-", 1);
059ec3d9 1749 }
4e88a19f 1750 ss = string_cat(ss, &size, &ptr, esc, esclen);
059ec3d9
PH
1751 ss = string_cat(ss, &size, &ptr, p, len);
1752 ss = string_cat(ss, &size, &ptr, US"\r\n", 2);
1753 p += len;
1754 if (linebreak != NULL) p++;
1755 }
1756while (*p != 0);
1757
1758ss[ptr] = 0; /* string_cat leaves room for this */
1759
1760/* Before we write the banner, check that there is no input pending, unless
1761this synchronisation check is disabled. */
1762
1763if (smtp_enforce_sync && sender_host_address != NULL && !sender_host_notsocket)
1764 {
1765 fd_set fds;
1766 struct timeval tzero;
1767 tzero.tv_sec = 0;
1768 tzero.tv_usec = 0;
1769 FD_ZERO(&fds);
1770 FD_SET(fileno(smtp_in), &fds);
1771 if (select(fileno(smtp_in) + 1, (SELECT_ARG2_TYPE *)&fds, NULL, NULL,
1772 &tzero) > 0)
1773 {
00f00ca5 1774 int rc = read(fileno(smtp_in), smtp_inbuffer, in_buffer_size);
f9b9210e
PH
1775 if (rc > 0)
1776 {
1777 if (rc > 150) rc = 150;
1778 smtp_inbuffer[rc] = 0;
3af76a81 1779 log_write(0, LOG_MAIN|LOG_REJECT, "SMTP protocol "
f9b9210e
PH
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");
1784 return FALSE;
1785 }
059ec3d9
PH
1786 }
1787 }
1788
1789/* Now output the banner */
1790
1791smtp_printf("%s", ss);
1792return TRUE;
1793}
1794
1795
1796
1797
1798
1799/*************************************************
1800* Handle SMTP syntax and protocol errors *
1801*************************************************/
1802
1803/* Write to the log for SMTP syntax errors in incoming commands, if configured
1804to do so. Then transmit the error response. The return value depends on the
1805number of syntax and protocol errors in this SMTP session.
1806
1807Arguments:
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
1812
1813Returns: -1 limit of syntax/protocol errors NOT exceeded
1814 +1 limit of syntax/protocol errors IS exceeded
1815
1816These values fit in with the values of the "done" variable in the main
1817processing loop in smtp_setup_msg(). */
1818
1819static int
1820synprot_error(int type, int code, uschar *data, uschar *errmess)
1821{
1822int yield = -1;
1823
1824log_write(type, LOG_MAIN, "SMTP %s error in \"%s\" %s %s",
1825 (type == L_smtp_syntax_error)? "syntax" : "protocol",
3ee512ff 1826 string_printing(smtp_cmd_buffer), host_and_ident(TRUE), errmess);
059ec3d9
PH
1827
1828if (++synprot_error_count > smtp_max_synprot_errors)
1829 {
1830 yield = 1;
1831 log_write(0, LOG_MAIN|LOG_REJECT, "SMTP call from %s dropped: too many "
1832 "syntax or protocol errors (last command was \"%s\")",
3ee512ff 1833 host_and_ident(FALSE), smtp_cmd_buffer);
059ec3d9
PH
1834 }
1835
1836if (code > 0)
1837 {
1838 smtp_printf("%d%c%s%s%s\r\n", code, (yield == 1)? '-' : ' ',
1839 (data == NULL)? US"" : data, (data == NULL)? US"" : US": ", errmess);
1840 if (yield == 1)
1841 smtp_printf("%d Too many syntax or protocol errors\r\n", code);
1842 }
1843
1844return yield;
1845}
1846
1847
1848
1849
1850/*************************************************
1851* Log incomplete transactions *
1852*************************************************/
1853
1854/* This function is called after a transaction has been aborted by RSET, QUIT,
1855connection drops or other errors. It logs the envelope information received
1856so far in order to preserve address verification attempts.
1857
1858Argument: string to indicate what aborted the transaction
1859Returns: nothing
1860*/
1861
1862static void
1863incomplete_transaction_log(uschar *what)
1864{
1865if (sender_address == NULL || /* No transaction in progress */
1866 (log_write_selector & L_smtp_incomplete_transaction) == 0 /* Not logging */
1867 ) return;
1868
1869/* Build list of recipients for logging */
1870
1871if (recipients_count > 0)
1872 {
1873 int i;
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;
1878 }
1879
1880log_write(L_smtp_incomplete_transaction, LOG_MAIN|LOG_SENDER|LOG_RECIPIENTS,
1881 "%s incomplete transaction (%s)", host_and_ident(TRUE), what);
1882}
1883
1884
1885
1886
1887/*************************************************
1888* Send SMTP response, possibly multiline *
1889*************************************************/
1890
1891/* There are, it seems, broken clients out there that cannot handle multiline
1892responses. If no_multiline_responses is TRUE (it can be set from an ACL), we
1893output nothing for non-final calls, and only the first line for anything else.
1894
1895Arguments:
a5bd321b 1896 code SMTP code, may involve extended status codes
d6a96edc 1897 codelen length of smtp code; if > 4 there's an ESC
059ec3d9
PH
1898 final FALSE if the last line isn't the final line
1899 msg message text, possibly containing newlines
1900
1901Returns: nothing
1902*/
1903
1904void
a5bd321b 1905smtp_respond(uschar* code, int codelen, BOOL final, uschar *msg)
059ec3d9 1906{
a5bd321b
PH
1907int esclen = 0;
1908uschar *esc = US"";
1909
059ec3d9
PH
1910if (!final && no_multiline_responses) return;
1911
d6a96edc 1912if (codelen > 4)
a5bd321b
PH
1913 {
1914 esc = code + 4;
1915 esclen = codelen - 4;
1916 }
1917
059ec3d9
PH
1918for (;;)
1919 {
1920 uschar *nl = Ustrchr(msg, '\n');
1921 if (nl == NULL)
1922 {
a5bd321b 1923 smtp_printf("%.3s%c%.*s%s\r\n", code, final? ' ':'-', esclen, esc, msg);
059ec3d9
PH
1924 return;
1925 }
1926 else if (nl[1] == 0 || no_multiline_responses)
1927 {
a5bd321b
PH
1928 smtp_printf("%.3s%c%.*s%.*s\r\n", code, final? ' ':'-', esclen, esc,
1929 (int)(nl - msg), msg);
059ec3d9
PH
1930 return;
1931 }
1932 else
1933 {
a5bd321b 1934 smtp_printf("%.3s-%.*s%.*s\r\n", code, esclen, esc, (int)(nl - msg), msg);
059ec3d9
PH
1935 msg = nl + 1;
1936 while (isspace(*msg)) msg++;
1937 }
1938 }
1939}
1940
1941
1942
1943
4e88a19f
PH
1944/*************************************************
1945* Parse user SMTP message *
1946*************************************************/
1947
1948/* This function allows for user messages overriding the response code details
1949by providing a suitable response code string at the start of the message
1950user_msg. Check the message for starting with a response code and optionally an
1951extended status code. If found, check that the first digit is valid, and if so,
1952change the code pointer and length to use the replacement. An invalid code
1953causes a panic log; in this case, if the log messages is the same as the user
1954message, we must also adjust the value of the log message to show the code that
1955is actually going to be used (the original one).
1956
1957This function is global because it is called from receive.c as well as within
1958this module.
1959
d6a96edc
PH
1960Note that the code length returned includes the terminating whitespace
1961character, which is always included in the regex match.
1962
4e88a19f
PH
1963Arguments:
1964 code SMTP code, may involve extended status codes
d6a96edc 1965 codelen length of smtp code; if > 4 there's an ESC
4e88a19f
PH
1966 msg message text
1967 log_msg optional log message, to be adjusted with the new SMTP code
1968
1969Returns: nothing
1970*/
1971
1972void
1973smtp_message_code(uschar **code, int *codelen, uschar **msg, uschar **log_msg)
1974{
1975int n;
1976int ovector[3];
1977
1978if (msg == NULL || *msg == NULL) return;
1979
1980n = pcre_exec(regex_smtp_code, NULL, CS *msg, Ustrlen(*msg), 0,
1981 PCRE_EOPT, ovector, sizeof(ovector)/sizeof(int));
1982if (n < 0) return;
1983
1984if ((*msg)[0] != (*code)[0])
1985 {
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]);
1990 }
1991else
1992 {
1993 *code = *msg;
1994 *codelen = ovector[1]; /* Includes final space */
1995 }
1996*msg += ovector[1]; /* Chop the code off the message */
1997return;
1998}
1999
2000
2001
2002
059ec3d9
PH
2003/*************************************************
2004* Handle an ACL failure *
2005*************************************************/
2006
2007/* This function is called when acl_check() fails. As well as calls from within
2008this module, it is called from receive.c for an ACL after DATA. It sorts out
2009logging the incident, and sets up the error response. A message containing
2010newlines is turned into a multiline SMTP response, but for logging, only the
2011first line is used.
2012
a5bd321b
PH
2013There's a table of default permanent failure response codes to use in
2014globals.c, along with the table of names. VFRY is special. Despite RFC1123 it
2015defaults 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
2017state, because there are broken clients that try VRFY before RCPT. A 5xx
2018response should be given only when the address is positively known to be
2019undeliverable. Sigh. Also, for ETRN, 458 is given on refusal, and for AUTH,
2020503.
2021
2022From Exim 4.63, it is possible to override the response code details by
2023providing a suitable response code string at the start of the message provided
2024in user_msg. The code's first digit is checked for validity.
059ec3d9
PH
2025
2026Arguments:
2027 where where the ACL was called from
2028 rc the failure code
2029 user_msg a message that can be included in an SMTP response
2030 log_msg a message for logging
2031
2032Returns: 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)
2036*/
2037
2038int
2039smtp_handle_acl_fail(int where, int rc, uschar *user_msg, uschar *log_msg)
2040{
059ec3d9 2041BOOL drop = rc == FAIL_DROP;
a5bd321b 2042int codelen = 3;
a5bd321b 2043uschar *smtp_code;
059ec3d9
PH
2044uschar *lognl;
2045uschar *sender_info = US"";
64ffc24f 2046uschar *what =
8523533c 2047#ifdef WITH_CONTENT_SCAN
64ffc24f 2048 (where == ACL_WHERE_MIME)? US"during MIME ACL checks" :
8e669ac1 2049#endif
64ffc24f
PH
2050 (where == ACL_WHERE_PREDATA)? US"DATA" :
2051 (where == ACL_WHERE_DATA)? US"after DATA" :
ca86f471 2052 (smtp_cmd_data == NULL)?
64ffc24f 2053 string_sprintf("%s in \"connect\" ACL", acl_wherenames[where]) :
ca86f471 2054 string_sprintf("%s %s", acl_wherenames[where], smtp_cmd_data);
059ec3d9
PH
2055
2056if (drop) rc = FAIL;
2057
4e88a19f 2058/* Set the default SMTP code, and allow a user message to change it. */
a5bd321b
PH
2059
2060smtp_code = (rc != FAIL)? US"451" : acl_wherecodes[where];
4e88a19f 2061smtp_message_code(&smtp_code, &codelen, &user_msg, &log_msg);
a5bd321b 2062
059ec3d9
PH
2063/* We used to have sender_address here; however, there was a bug that was not
2064updating sender_address after a rewrite during a verify. When this bug was
2065fixed, sender_address at this point became the rewritten address. I'm not sure
2066this is what should be logged, so I've changed to logging the unrewritten
2067address to retain backward compatibility. */
2068
8523533c 2069#ifndef WITH_CONTENT_SCAN
059ec3d9 2070if (where == ACL_WHERE_RCPT || where == ACL_WHERE_DATA)
8523533c
TK
2071#else
2072if (where == ACL_WHERE_RCPT || where == ACL_WHERE_DATA || where == ACL_WHERE_MIME)
2073#endif
059ec3d9
PH
2074 {
2075 sender_info = string_sprintf("F=<%s> ", (sender_address_unrewritten != NULL)?
2076 sender_address_unrewritten : sender_address);
2077 }
2078
2079/* If there's been a sender verification failure with a specific message, and
2080we have not sent a response about it yet, do so now, as a preliminary line for
278c6e6c
PH
2081failures, but not defers. However, always log it for defer, and log it for fail
2082unless the sender_verify_fail log selector has been turned off. */
059ec3d9
PH
2083
2084if (sender_verified_failed != NULL &&
2085 !testflag(sender_verified_failed, af_sverify_told))
2086 {
2087 setflag(sender_verified_failed, af_sverify_told);
2088
278c6e6c
PH
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));
059ec3d9
PH
2096
2097 if (rc == FAIL && sender_verified_failed->user_message != NULL)
a5bd321b 2098 smtp_respond(smtp_code, codelen, FALSE, string_sprintf(
059ec3d9
PH
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."
2104 :
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"
2111 "refuse bounces."
2112 :
2113 "Verification failed for <%s>\n%s",
2114 sender_verified_failed->address,
2115 sender_verified_failed->user_message));
2116 }
2117
2118/* Sort out text for logging */
2119
2120log_msg = (log_msg == NULL)? US"" : string_sprintf(": %s", log_msg);
2121lognl = Ustrchr(log_msg, '\n');
2122if (lognl != NULL) *lognl = 0;
2123
2124/* Send permanent failure response to the command, but the code used isn't
2125always a 5xx one - see comments at the start of this function. If the original
2126rc was FAIL_DROP we drop the connection and yield 2. */
2127
a5bd321b 2128if (rc == FAIL) smtp_respond(smtp_code, codelen, TRUE, (user_msg == NULL)?
059ec3d9
PH
2129 US"Administrative prohibition" : user_msg);
2130
2131/* Send temporary failure response to the command. Don't give any details,
2132unless acl_temp_details is set. This is TRUE for a callout defer, a "defer"
2133verb, and for a header verify when smtp_return_error_details is set.
2134
2135This conditional logic is all somewhat of a mess because of the odd
2136interactions between temp_details and return_error_details. One day it should
2137be re-implemented in a tidier fashion. */
2138
2139else
2140 {
2141 if (acl_temp_details && user_msg != NULL)
2142 {
2143 if (smtp_return_error_details &&
2144 sender_verified_failed != NULL &&
2145 sender_verified_failed->message != NULL)
2146 {
a5bd321b 2147 smtp_respond(smtp_code, codelen, FALSE, sender_verified_failed->message);
059ec3d9 2148 }
a5bd321b 2149 smtp_respond(smtp_code, codelen, TRUE, user_msg);
059ec3d9
PH
2150 }
2151 else
a5bd321b
PH
2152 smtp_respond(smtp_code, codelen, TRUE,
2153 US"Temporary local problem - please try later");
059ec3d9
PH
2154 }
2155
6ea85e9a
PH
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
2158the connection is not forcibly to be dropped, return 0. Otherwise, log why it
2159is closing if required and return 2. */
059ec3d9 2160
6ea85e9a
PH
2161if (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);
059ec3d9
PH
2165
2166if (!drop) return 0;
2167
2168log_write(L_smtp_connection, LOG_MAIN, "%s closed by DROP in ACL",
2169 smtp_get_connection_info());
2170return 2;
2171}
2172
2173
2174
2175
d7b47fd0
PH
2176/*************************************************
2177* Verify HELO argument *
2178*************************************************/
2179
2180/* This function is called if helo_verify_hosts or helo_try_verify_hosts is
2181matched. It is also called from ACL processing if verify = helo is used and
2182verification was not previously tried (i.e. helo_try_verify_hosts was not
2183matched). The result of its processing is to set helo_verified and
2184helo_verify_failed. These variables should both be FALSE for this function to
2185be called.
2186
2187Note that EHLO/HELO is legitimately allowed to quote an address literal. Allow
2188for IPv6 ::ffff: literals.
2189
2190Argument: none
2191Returns: TRUE if testing was completed;
2192 FALSE on a temporary failure
2193*/
2194
2195BOOL
2196smtp_verify_helo(void)
2197{
2198BOOL yield = TRUE;
2199
2200HDEBUG(D_receive) debug_printf("verifying EHLO/HELO argument \"%s\"\n",
2201 sender_helo_name);
2202
2203if (sender_helo_name == NULL)
2204 {
2205 HDEBUG(D_receive) debug_printf("no EHLO/HELO command was issued\n");
2206 }
2207
d1d5595c
PH
2208/* Deal with the case of -bs without an IP address */
2209
2210else if (sender_host_address == NULL)
2211 {
2212 HDEBUG(D_receive) debug_printf("no client IP address: assume success\n");
2213 helo_verified = TRUE;
2214 }
2215
2216/* Deal with the more common case when there is a sending IP address */
2217
d7b47fd0
PH
2218else if (sender_helo_name[0] == '[')
2219 {
2220 helo_verified = Ustrncmp(sender_helo_name+1, sender_host_address,
2221 Ustrlen(sender_host_address)) == 0;
2222
2223 #if HAVE_IPV6
2224 if (!helo_verified)
2225 {
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;
2229 }
2230 #endif
2231
2232 HDEBUG(D_receive)
2233 { if (helo_verified) debug_printf("matched host address\n"); }
2234 }
2235
2236/* Do a reverse lookup if one hasn't already given a positive or negative
2237response. If that fails, or the name doesn't match, try checking with a forward
2238lookup. */
2239
2240else
2241 {
2242 if (sender_host_name == NULL && !host_lookup_failed)
2243 yield = host_name_lookup() != DEFER;
2244
2245 /* If a host name is known, check it and all its aliases. */
2246
2247 if (sender_host_name != NULL)
2248 {
2249 helo_verified = strcmpic(sender_host_name, sender_helo_name) == 0;
2250
2251 if (helo_verified)
2252 {
2253 HDEBUG(D_receive) debug_printf("matched host name\n");
2254 }
2255 else
2256 {
2257 uschar **aliases = sender_host_aliases;
2258 while (*aliases != NULL)
2259 {
2260 helo_verified = strcmpic(*aliases++, sender_helo_name) == 0;
2261 if (helo_verified) break;
2262 }
2263 HDEBUG(D_receive)
2264 {
2265 if (helo_verified)
2266 debug_printf("matched alias %s\n", *(--aliases));
2267 }
2268 }
2269 }
2270
2271 /* Final attempt: try a forward lookup of the helo name */
2272
2273 if (!helo_verified)
2274 {
2275 int rc;
2276 host_item h;
2277 h.name = sender_helo_name;
2278 h.address = NULL;
2279 h.mx = MX_NONE;
2280 h.next = NULL;
2281 HDEBUG(D_receive) debug_printf("getting IP address for %s\n",
2282 sender_helo_name);
322050c2 2283 rc = host_find_byname(&h, NULL, 0, NULL, TRUE);
d7b47fd0
PH
2284 if (rc == HOST_FOUND || rc == HOST_FOUND_LOCAL)
2285 {
2286 host_item *hh = &h;
2287 while (hh != NULL)
2288 {
2289 if (Ustrcmp(hh->address, sender_host_address) == 0)
2290 {
2291 helo_verified = TRUE;
2292 HDEBUG(D_receive)
2293 debug_printf("IP address for %s matches calling address\n",
2294 sender_helo_name);
2295 break;
2296 }
2297 hh = hh->next;
2298 }
2299 }
2300 }
2301 }
2302
d1d5595c 2303if (!helo_verified) helo_verify_failed = TRUE; /* We've tried ... */
d7b47fd0
PH
2304return yield;
2305}
2306
2307
2308
2309
4e88a19f
PH
2310/*************************************************
2311* Send user response message *
2312*************************************************/
2313
2314/* This function is passed a default response code and a user message. It calls
2315smtp_message_code() to check and possibly modify the response code, and then
2316calls smtp_respond() to transmit the response. I put this into a function
2317just to avoid a lot of repetition.
2318
2319Arguments:
2320 code the response code
2321 user_msg the user message
2322
2323Returns: nothing
2324*/
2325
2326static void
2327smtp_user_msg(uschar *code, uschar *user_msg)
2328{
2329int len = 3;
2330smtp_message_code(&code, &len, &user_msg, NULL);
2331smtp_respond(code, len, TRUE, user_msg);
2332}
2333
2334
2335
2336
059ec3d9
PH
2337/*************************************************
2338* Initialize for SMTP incoming message *
2339*************************************************/
2340
2341/* This function conducts the initial dialogue at the start of an incoming SMTP
2342message, and builds a list of recipients. However, if the incoming message
2343is part of a batch (-bS option) a separate function is called since it would
2344be messy having tests splattered about all over this function. This function
2345therefore handles the case where interaction is occurring. The input and output
2346files are set up in smtp_in and smtp_out.
2347
2348The global recipients_list is set to point to a vector of recipient_item
2349blocks, whose number is given by recipients_count. This is extended by the
2350receive_add_recipient() function. The global variable sender_address is set to
2351the sender's address. The yield is +1 if a message has been successfully
2352started, 0 if a QUIT command was encountered or the connection was refused from
2353the particular host, or -1 if the connection was lost.
2354
2355Argument: none
2356
2357Returns: > 0 message successfully started (reached DATA)
2358 = 0 QUIT read or end of file reached or call refused
2359 < 0 lost connection
2360*/
2361
2362int
2363smtp_setup_msg(void)
2364{
2365int done = 0;
2366BOOL toomany = FALSE;
2367BOOL discarded = FALSE;
2368BOOL last_was_rej_mail = FALSE;
2369BOOL last_was_rcpt = FALSE;
2370void *reset_point = store_get(0);
2371
2372DEBUG(D_receive) debug_printf("smtp_setup_msg entered\n");
2373
2374/* Reset for start of new message. We allow one RSET not to be counted as a
2375nonmail command, for those MTAs that insist on sending it between every
2376message. Ditto for EHLO/HELO and for STARTTLS, to allow for going in and out of
2377TLS between messages (an Exim client may do this if it has messages queued up
2378for the host). Note: we do NOT reset AUTH at this point. */
2379
2380smtp_reset(reset_point);
2381message_ended = END_NOTSTARTED;
2382
2383cmd_list[CMD_LIST_RSET].is_mail_cmd = TRUE;
2384cmd_list[CMD_LIST_HELO].is_mail_cmd = TRUE;
2385cmd_list[CMD_LIST_EHLO].is_mail_cmd = TRUE;
2386#ifdef SUPPORT_TLS
2387cmd_list[CMD_LIST_STARTTLS].is_mail_cmd = TRUE;
2388#endif
2389
2390/* Set the local signal handler for SIGTERM - it tries to end off tidily */
2391
2392os_non_restarting_signal(SIGTERM, command_sigterm_handler);
2393
2394/* Batched SMTP is handled in a different function. */
2395
2396if (smtp_batched_input) return smtp_setup_batch_msg();
2397
2398/* Deal with SMTP commands. This loop is exited by setting done to a POSITIVE
2399value. The values are 2 larger than the required yield of the function. */
2400
2401while (done <= 0)
2402 {
2403 uschar **argv;
2404 uschar *etrn_command;
2405 uschar *etrn_serialize_key;
2406 uschar *errmess;
4e88a19f
PH
2407 uschar *log_msg, *smtp_code;
2408 uschar *user_msg = NULL;
059ec3d9
PH
2409 uschar *recipient = NULL;
2410 uschar *hello = NULL;
2411 uschar *set_id = NULL;
2412 uschar *s, *ss;
2413 BOOL was_rej_mail = FALSE;
2414 BOOL was_rcpt = FALSE;
2415 void (*oldsignal)(int);
2416 pid_t pid;
2417 int start, end, sender_domain, recipient_domain;
2418 int ptr, size, rc;
f78eb7c6 2419 int c, i;
059ec3d9
PH
2420 auth_instance *au;
2421
2422 switch(smtp_read_command(TRUE))
2423 {
2424 /* The AUTH command is not permitted to occur inside a transaction, and may
c46782ef
PH
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.
2428
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.
059ec3d9
PH
2433
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. */
2437
2438 case AUTH_CMD:
b4ed4da0 2439 HAD(SCH_AUTH);
059ec3d9
PH
2440 authentication_failed = TRUE;
2441 cmd_list[CMD_LIST_AUTH].is_mail_cmd = FALSE;
2442
c46782ef 2443 if (!auth_advertised && !allow_auth_unadvertised)
059ec3d9
PH
2444 {
2445 done = synprot_error(L_smtp_protocol_error, 503, NULL,
2446 US"AUTH command used when not advertised");
2447 break;
2448 }
2449 if (sender_host_authenticated != NULL)
2450 {
2451 done = synprot_error(L_smtp_protocol_error, 503, NULL,
2452 US"already authenticated");
2453 break;
2454 }
2455 if (sender_address != NULL)
2456 {
2457 done = synprot_error(L_smtp_protocol_error, 503, NULL,
2458 US"not permitted in mail transaction");
2459 break;
2460 }
2461
2462 /* Check the ACL */
2463
2464 if (acl_smtp_auth != NULL)
2465 {
64ffc24f 2466 rc = acl_check(ACL_WHERE_AUTH, NULL, acl_smtp_auth, &user_msg, &log_msg);
059ec3d9
PH
2467 if (rc != OK)
2468 {
2469 done = smtp_handle_acl_fail(ACL_WHERE_AUTH, rc, user_msg, log_msg);
2470 break;
2471 }
2472 }
2473
2474 /* Find the name of the requested authentication mechanism. */
2475
ca86f471
PH
2476 s = smtp_cmd_data;
2477 while ((c = *smtp_cmd_data) != 0 && !isspace(c))
059ec3d9
PH
2478 {
2479 if (!isalnum(c) && c != '-' && c != '_')
2480 {
2481 done = synprot_error(L_smtp_syntax_error, 501, NULL,
2482 US"invalid character in authentication mechanism name");
2483 goto COMMAND_LOOP;
2484 }
ca86f471 2485 smtp_cmd_data++;
059ec3d9
PH
2486 }
2487
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. */
2490
ca86f471 2491 if (*smtp_cmd_data != 0)
059ec3d9 2492 {
ca86f471
PH
2493 *smtp_cmd_data++ = 0;
2494 while (isspace(*smtp_cmd_data)) smtp_cmd_data++;
059ec3d9
PH
2495 }
2496
2497 /* Search for an authentication mechanism which is configured for use
c46782ef
PH
2498 as a server and which has been advertised (unless, sigh, allow_auth_
2499 unadvertised is set). */
059ec3d9
PH
2500
2501 for (au = auths; au != NULL; au = au->next)
2502 {
2503 if (strcmpic(s, au->public_name) == 0 && au->server &&
c46782ef 2504 (au->advertised || allow_auth_unadvertised)) break;
059ec3d9
PH
2505 }
2506
2507 if (au == NULL)
2508 {
2509 done = synprot_error(L_smtp_protocol_error, 504, NULL,
2510 string_sprintf("%s authentication mechanism not supported", s));
2511 break;
2512 }
2513
f78eb7c6
PH
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.
059ec3d9 2519
f78eb7c6
PH
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. */
2525
2526 for (i = 0; i < AUTH_VARS; i++) auth_vars[i] = NULL;
059ec3d9
PH
2527 expand_nmax = 0;
2528 expand_nlength[0] = 0; /* $0 contains nothing */
2529
ca86f471 2530 c = (au->info->servercode)(au, smtp_cmd_data);
059ec3d9
PH
2531 if (au->set_id != NULL) set_id = expand_string(au->set_id);
2532 expand_nmax = -1; /* Reset numeric variables */
f78eb7c6 2533 for (i = 0; i < AUTH_VARS; i++) auth_vars[i] = NULL; /* Reset $auth<n> */
059ec3d9 2534
0612b098
PH
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. */
2540
2541 if (set_id != NULL) set_id = string_printing(set_id);
2542
059ec3d9
PH
2543 /* For the non-OK cases, set up additional logging data if set_id
2544 is not empty. */
2545
2546 if (c != OK)
2547 {
2548 if (set_id != NULL && *set_id != 0)
2549 set_id = string_sprintf(" (set_id=%s)", set_id);
2550 else set_id = US"";
2551 }
2552
2553 /* Switch on the result */
2554
2555 switch(c)
2556 {
2557 case OK:
2558 if (au->set_id == NULL || set_id != NULL) /* Complete success */
2559 {
2560 if (set_id != NULL) authenticated_id = string_copy_malloc(set_id);
2561 sender_host_authenticated = au->name;
2562 authentication_failed = FALSE;
2563 received_protocol =
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;
2568 break;
2569 }
2570
2571 /* Authentication succeeded, but we failed to expand the set_id string.
2572 Treat this as a temporary error. */
2573
2574 auth_defer_msg = expand_string_message;
2575 /* Fall through */
2576
2577 case DEFER:
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);
2582 break;
2583
2584 case BAD64:
2585 s = ss = US"501 Invalid base64 data";
2586 break;
2587
2588 case CANCELLED:
2589 s = ss = US"501 Authentication cancelled";
2590 break;
2591
2592 case UNEXPECTED:
2593 s = ss = US"553 Initial data not expected";
2594 break;
2595
2596 case FAIL:
2597 s = US"535 Incorrect authentication data";
2598 ss = string_sprintf("535 Incorrect authentication data%s", set_id);
2599 break;
2600
2601 default:
2602 s = US"435 Internal error";
2603 ss = string_sprintf("435 Internal error%s: return %d from authentication "
2604 "check", set_id, c);
2605 break;
2606 }
2607
2608 smtp_printf("%s\r\n", s);
2609 if (c != OK)
2610 log_write(0, LOG_MAIN|LOG_REJECT, "%s authenticator failed for %s: %s",
2611 au->name, host_and_ident(FALSE), ss);
2612
2613 break; /* AUTH_CMD */
2614
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.
2619
2620 RFC 2821 says:
2621
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.
2626
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. */
2630
2631 case HELO_CMD:
b4ed4da0 2632 HAD(SCH_HELO);
059ec3d9
PH
2633 hello = US"HELO";
2634 esmtp = FALSE;
2635 goto HELO_EHLO;
2636
2637 case EHLO_CMD:
b4ed4da0 2638 HAD(SCH_EHLO);
059ec3d9
PH
2639 hello = US"EHLO";
2640 esmtp = TRUE;
2641
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;
2645
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. */
2648
ca86f471 2649 if (!check_helo(smtp_cmd_data))
059ec3d9
PH
2650 {
2651 smtp_printf("501 Syntactically invalid %s argument(s)\r\n", hello);
2652
2653 log_write(0, LOG_MAIN|LOG_REJECT, "rejected %s from %s: syntactically "
2654 "invalid argument(s): %s", hello, host_and_ident(FALSE),
3ee512ff
PH
2655 (*smtp_cmd_argument == 0)? US"(no argument given)" :
2656 string_printing(smtp_cmd_argument));
059ec3d9
PH
2657
2658 if (++synprot_error_count > smtp_max_synprot_errors)
2659 {
2660 log_write(0, LOG_MAIN|LOG_REJECT, "SMTP call from %s dropped: too many "
2661 "syntax or protocol errors (last command was \"%s\")",
3ee512ff 2662 host_and_ident(FALSE), smtp_cmd_buffer);
059ec3d9
PH
2663 done = 1;
2664 }
2665
2666 break;
2667 }
2668
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. */
2675
2676 if (!sender_host_unknown)
2677 {
2678 BOOL old_helo_verified = helo_verified;
ca86f471 2679 uschar *p = smtp_cmd_data;
059ec3d9
PH
2680
2681 while (*p != 0 && !isspace(*p)) { *p = tolower(*p); p++; }
2682 *p = 0;
2683
2684 /* Force a reverse lookup if HELO quoted something in helo_lookup_domains
2685 because otherwise the log can be confusing. */
2686
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();
2692
2693 /* Rebuild the fullhost info to include the HELO name (and the real name
2694 if it was looked up.) */
2695
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));
2699
2700 /* Verify if configured. This doesn't give much security, but it does
d7b47fd0
PH
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
2705 at ACL time. */
059ec3d9 2706
d7b47fd0 2707 helo_verified = helo_verify_failed = FALSE;
059ec3d9
PH
2708 if (helo_required || helo_verify)
2709 {
d7b47fd0 2710 BOOL tempfail = !smtp_verify_helo();
059ec3d9
PH
2711 if (!helo_verified)
2712 {
2713 if (helo_required)
2714 {
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 */
2722 }
2723 HDEBUG(D_all) debug_printf("%s verification failed but host is in "
2724 "helo_try_verify_hosts\n", hello);
2725 }
2726 }
2727 }
2728
8523533c
TK
2729#ifdef EXPERIMENTAL_SPF
2730 /* set up SPF context */
2731 spf_init(sender_helo_name, sender_host_address);
2732#endif
2733
059ec3d9
PH
2734 /* Apply an ACL check if one is defined */
2735
2736 if (acl_smtp_helo != NULL)
2737 {
64ffc24f 2738 rc = acl_check(ACL_WHERE_HELO, NULL, acl_smtp_helo, &user_msg, &log_msg);
059ec3d9
PH
2739 if (rc != OK)
2740 {
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 */
2744 break;
2745 }
2746 }
2747
4e88a19f
PH
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(). */
059ec3d9
PH
2753
2754 auth_advertised = FALSE;
2755 pipelining_advertised = FALSE;
2756 #ifdef SUPPORT_TLS
2757 tls_advertised = FALSE;
2758 #endif
2759
d6a96edc 2760 smtp_code = US"250 "; /* Default response code plus space*/
4e88a19f
PH
2761 if (user_msg == NULL)
2762 {
2763 s = string_sprintf("%.3s %s Hello %s%s%s",
2764 smtp_code,
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);
2769
2770 ptr = Ustrlen(s);
2771 size = ptr + 1;
059ec3d9 2772
4e88a19f
PH
2773 if (sender_host_address != NULL)
2774 {
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);
2779 }
2780 }
2781
d6a96edc
PH
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. */
059ec3d9 2785
4e88a19f 2786 else
059ec3d9 2787 {
4e88a19f 2788 char *ss;
d6a96edc 2789 int codelen = 4;
4e88a19f 2790 smtp_message_code(&smtp_code, &codelen, &user_msg, NULL);
d6a96edc 2791 s = string_sprintf("%.*s%s", codelen, smtp_code, user_msg);
4e88a19f
PH
2792 if ((ss = strpbrk(CS s, "\r\n")) != NULL)
2793 {
2794 log_write(0, LOG_MAIN|LOG_PANIC, "EHLO/HELO response must not contain "
2795 "newlines: message truncated: %s", string_printing(s));
2796 *ss = 0;
2797 }
2798 ptr = Ustrlen(s);
2799 size = ptr + 1;
059ec3d9
PH
2800 }
2801
2802 s = string_cat(s, &size, &ptr, US"\r\n", 2);
2803
2804 /* If we received EHLO, we must create a multiline response which includes
2805 the functions supported. */
2806
2807 if (esmtp)
2808 {
2809 s[3] = '-';
2810
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. */
2816
2817 if (thismessage_size_limit > 0)
2818 {
4e88a19f
PH
2819 sprintf(CS big_buffer, "%.3s-SIZE %d\r\n", smtp_code,
2820 thismessage_size_limit);
059ec3d9
PH
2821 s = string_cat(s, &size, &ptr, big_buffer, Ustrlen(big_buffer));
2822 }
2823 else
2824 {
4e88a19f
PH
2825 s = string_cat(s, &size, &ptr, smtp_code, 3);
2826 s = string_cat(s, &size, &ptr, US"-SIZE\r\n", 7);
059ec3d9
PH
2827 }
2828
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. */
2835
2836 if (accept_8bitmime)
4e88a19f
PH
2837 {
2838 s = string_cat(s, &size, &ptr, smtp_code, 3);
2839 s = string_cat(s, &size, &ptr, US"-8BITMIME\r\n", 11);
2840 }
059ec3d9
PH
2841
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. */
2844
2845 if (acl_smtp_etrn != NULL)
2846 {
4e88a19f
PH
2847 s = string_cat(s, &size, &ptr, smtp_code, 3);
2848 s = string_cat(s, &size, &ptr, US"-ETRN\r\n", 7);
059ec3d9
PH
2849 }
2850
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. */
2853
2854 if (acl_smtp_expn != NULL)
2855 {
4e88a19f
PH
2856 s = string_cat(s, &size, &ptr, smtp_code, 3);
2857 s = string_cat(s, &size, &ptr, US"-EXPN\r\n", 7);
059ec3d9
PH
2858 }
2859
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. */
2862
cf8b11a5
PH
2863 if (pipelining_enable &&
2864 verify_check_host(&pipelining_advertise_hosts) == OK)
059ec3d9 2865 {
4e88a19f
PH
2866 s = string_cat(s, &size, &ptr, smtp_code, 3);
2867 s = string_cat(s, &size, &ptr, US"-PIPELINING\r\n", 13);
059ec3d9
PH
2868 sync_cmd_limit = NON_SYNC_CMD_PIPELINING;
2869 pipelining_advertised = TRUE;
2870 }
2871
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).
2877
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. */
2881
2882 if (auths != NULL)
2883 {
2884 if (verify_check_host(&auth_advertise_hosts) == OK)
2885 {
2886 auth_instance *au;
2887 BOOL first = TRUE;
2888 for (au = auths; au != NULL; au = au->next)
2889 {
2890 if (au->server && (au->advertise_condition == NULL ||
2891 expand_check_condition(au->advertise_condition, au->name,
2892 US"authenticator")))
2893 {
2894 int saveptr;
2895 if (first)
2896 {
4e88a19f
PH
2897 s = string_cat(s, &size, &ptr, smtp_code, 3);
2898 s = string_cat(s, &size, &ptr, US"-AUTH", 5);
059ec3d9
PH
2899 first = FALSE;
2900 auth_advertised = TRUE;
2901 }
2902 saveptr = ptr;
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;
2908 }
2909 else au->advertised = FALSE;
2910 }
2911 if (!first) s = string_cat(s, &size, &ptr, US"\r\n", 2);
2912 }
2913 }
2914
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. */
2919
2920 #ifdef SUPPORT_TLS
2921 if (tls_active < 0 &&
2922 verify_check_host(&tls_advertise_hosts) != FAIL)
2923 {
4e88a19f
PH
2924 s = string_cat(s, &size, &ptr, smtp_code, 3);
2925 s = string_cat(s, &size, &ptr, US"-STARTTLS\r\n", 11);
059ec3d9
PH
2926 tls_advertised = TRUE;
2927 }
2928 #endif
2929
2930 /* Finish off the multiline reply with one that is always available. */
2931
4e88a19f
PH
2932 s = string_cat(s, &size, &ptr, smtp_code, 3);
2933 s = string_cat(s, &size, &ptr, US" HELP\r\n", 7);
059ec3d9
PH
2934 }
2935
2936 /* Terminate the string (for debug), write it, and note that HELO/EHLO
2937 has been seen. */
2938
2939 s[ptr] = 0;
2940
2941 #ifdef SUPPORT_TLS
2942 if (tls_active >= 0) (void)tls_write(s, ptr); else
2943 #endif
2944
f1e894f3 2945 (void)fwrite(s, 1, ptr, smtp_out);
898d150f
PH
2946 DEBUG(D_receive)
2947 {
2948 uschar *cr;
2949 while ((cr = Ustrchr(s, '\r')) != NULL) /* lose CRs */
2950 memmove(cr, cr + 1, (ptr--) - (cr - s));
2951 debug_printf("SMTP>> %s", s);
2952 }
059ec3d9 2953 helo_seen = TRUE;
4e88a19f
PH
2954
2955 /* Reset the protocol and the state, abandoning any previous message. */
2956
2957 received_protocol = (esmtp?
2958 protocols[pextend +
2959 ((sender_host_authenticated != NULL)? pauthed : 0) +
2960 ((tls_active >= 0)? pcrpted : 0)]
2961 :
2962 protocols[pnormal + ((tls_active >= 0)? pcrpted : 0)])
2963 +
2964 ((sender_host_address != NULL)? pnlocal : 0);
2965
2966 smtp_reset(reset_point);
2967 toomany = FALSE;
059ec3d9
PH
2968 break; /* HELO/EHLO */
2969
2970
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. */
2976
2977 case MAIL_CMD:
b4ed4da0 2978 HAD(SCH_MAIL);
059ec3d9
PH
2979 smtp_mailcmd_count++; /* Count for limit and ratelimit */
2980 was_rej_mail = TRUE; /* Reset if accepted */
2981
2982 if (helo_required && !helo_seen)
2983 {
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));
2987 break;
2988 }
2989
2990 if (sender_address != NULL)
2991 {
2992 done = synprot_error(L_smtp_protocol_error, 503, NULL,
2993 US"sender already given");
2994 break;
2995 }
2996
ca86f471 2997 if (smtp_cmd_data[0] == 0)
059ec3d9
PH
2998 {
2999 done = synprot_error(L_smtp_protocol_error, 501, NULL,
3000 US"MAIL must have an address operand");
3001 break;
3002 }
3003
3004 /* Check to see if the limit for messages per connection would be
3005 exceeded by accepting further messages. */
3006
3007 if (smtp_accept_max_per_connection > 0 &&
3008 smtp_mailcmd_count > smtp_accept_max_per_connection)
3009 {
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));
3013 break;
3014 }
3015
3016 /* Reset for start of message - even if this is going to fail, we
3017 obviously need to throw away any previous data. */
3018
3019 smtp_reset(reset_point);
3020 toomany = FALSE;
3021 sender_data = recipient_data = NULL;
3022
3023 /* Loop, checking for ESMTP additions to the MAIL FROM command. */
3024
3025 if (esmtp) for(;;)
3026 {
3027 uschar *name, *value, *end;
3028 unsigned long int size;
3029
3030 if (!extract_option(&name, &value)) break;
3031
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. */
3034
3035 if (strcmpic(name, US"SIZE") == 0 &&
3036 ((size = (int)Ustrtoul(value, &end, 10)), *end == 0))
3037 {
3038 if ((size == ULONG_MAX && errno == ERANGE) || size > INT_MAX)
3039 size = INT_MAX;
3040 message_size = (int)size;
3041 }
3042
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. */
3050
3051 else if (accept_8bitmime && strcmpic(name, US"BODY") == 0 &&
3052 (strcmpic(value, US"8BITMIME") == 0 ||
3053 strcmpic(value, US"7BIT") == 0)) {}
3054
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
3061 coding. */
3062
3063 else if (strcmpic(name, US"AUTH") == 0)
3064 {
3065 if (Ustrcmp(value, "<>") != 0)
3066 {
3067 int rc;
3068 uschar *ignore_msg;
3069
3070 if (auth_xtextdecode(value, &authenticated_sender) < 0)
3071 {
3072 /* Put back terminator overrides for error message */
3073 name[-1] = ' ';
3074 value[-1] = '=';
3075 done = synprot_error(L_smtp_syntax_error, 501, NULL,
3076 US"invalid data for AUTH");
3077 goto COMMAND_LOOP;
3078 }
3079
3080 if (acl_smtp_mailauth == NULL)
3081 {
3082 ignore_msg = US"client not authenticated";
3083 rc = (sender_host_authenticated != NULL)? OK : FAIL;
3084 }
3085 else
3086 {
3087 ignore_msg = US"rejected by ACL";
3088 rc = acl_check(ACL_WHERE_MAILAUTH, NULL, acl_smtp_mailauth,
3089 &user_msg, &log_msg);
3090 }
3091
3092 switch (rc)
3093 {
3094 case OK:
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 */
3100
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);
3105
3106 /* Fall through */
3107
3108 case FAIL:
3109 authenticated_sender = NULL;
3110 log_write(0, LOG_MAIN, "ignoring AUTH=%s from %s (%s)",
3111 value, host_and_ident(TRUE), ignore_msg);
3112 break;
3113
3114 /* Should only get DEFER or ERROR here. Put back terminator
3115 overrides for error message */
3116
3117 default:
3118 name[-1] = ' ';
3119 value[-1] = '=';
3120 (void)smtp_handle_acl_fail(ACL_WHERE_MAILAUTH, rc, user_msg,
3121 log_msg);
3122 goto COMMAND_LOOP;
3123 }
3124 }
3125 }
3126
3127 /* Unknown option. Stick back the terminator characters and break
3128 the loop. An error for a malformed address will occur. */
3129
3130 else
3131 {
3132 name[-1] = ' ';
3133 value[-1] = '=';
3134 break;
3135 }
3136 }
3137
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. */
3140
3141 if (smtp_mailcmd_count > smtp_rlm_threshold &&
3142 verify_check_host(&smtp_ratelimit_hosts) == OK)
3143 {
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;
3150 }
3151
3152 /* Now extract the address, first applying any SMTP-time rewriting. The
3153 TRUE flag allows "<>" as a sender address. */
3154
3155 raw_sender = ((rewrite_existflags & rewrite_smtp) != 0)?
ca86f471
PH
3156 rewrite_one(smtp_cmd_data, rewrite_smtp, NULL, FALSE, US"",
3157 global_rewrite_rules) : smtp_cmd_data;
059ec3d9
PH
3158
3159 /* rfc821_domains = TRUE; << no longer needed */
3160 raw_sender =
3161 parse_extract_address(raw_sender, &errmess, &start, &end, &sender_domain,
3162 TRUE);
3163 /* rfc821_domains = FALSE; << no longer needed */
3164
3165 if (raw_sender == NULL)
3166 {
ca86f471 3167 done = synprot_error(L_smtp_syntax_error, 501, smtp_cmd_data, errmess);
059ec3d9
PH
3168 break;
3169 }
3170
3171 sender_address = raw_sender;
3172
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
3175 can be logged. */
3176
3177 if (thismessage_size_limit > 0 && message_size > thismessage_size_limit)
3178 {
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",
3183 sender_address,
3184 host_and_ident(TRUE),
3185 (message_size == INT_MAX)? ">" : "",
3186 message_size,
3187 thismessage_size_limit);
3188 sender_address = NULL;
3189 break;
3190 }
3191
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. */
3199
3200 if (!receive_check_fs(
3201 (smtp_check_spool_space && message_size >= 0)?
3202 message_size + 5000 : 0))
3203 {
3204 smtp_printf("452 Space shortage, please try later\r\n");
3205 sender_address = NULL;
3206 break;
3207 }
3208
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. */
3214
3215 if (sender_domain == 0 && sender_address[0] != 0)
3216 {
3217 if (allow_unqualified_sender)
3218 {
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",
3222 raw_sender);
3223 }
3224 else
3225 {
3226 smtp_printf("501 %s: sender address must contain a domain\r\n",
ca86f471 3227 smtp_cmd_data);
059ec3d9
PH
3228 log_write(L_smtp_syntax_error,
3229 LOG_MAIN|LOG_REJECT,
3230 "unqualified sender rejected: <%s> %s%s",
3231 raw_sender,
3232 host_and_ident(TRUE),
3233 host_lookup_msg);
3234 sender_address = NULL;
3235 break;
3236 }
3237 }
3238
3239 /* Apply an ACL check if one is defined, before responding */
3240
3241 rc = (acl_smtp_mail == NULL)? OK :
3242 acl_check(ACL_WHERE_MAIL, NULL, acl_smtp_mail, &user_msg, &log_msg);
3243
3244 if (rc == OK || rc == DISCARD)
3245 {
4e88a19f
PH
3246 if (user_msg == NULL) smtp_printf("250 OK\r\n");
3247 else smtp_user_msg(US"250", user_msg);
059ec3d9
PH
3248 smtp_delay_rcpt = smtp_rlr_base;
3249 recipients_discarded = (rc == DISCARD);
3250 was_rej_mail = FALSE;
3251 }
059ec3d9
PH
3252 else
3253 {
3254 done = smtp_handle_acl_fail(ACL_WHERE_MAIL, rc, user_msg, log_msg);
3255 sender_address = NULL;
3256 }
3257 break;
3258
3259
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. */
3266
3267 case RCPT_CMD:
b4ed4da0 3268 HAD(SCH_RCPT);
059ec3d9
PH
3269 rcpt_count++;
3270 was_rcpt = TRUE;
3271
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. */
3276
3277 if (sender_address == NULL)
3278 {
3279 if (pipelining_advertised && last_was_rej_mail)
3280 {
3281 smtp_printf("503 sender not yet given\r\n");
3282 was_rej_mail = TRUE;
3283 }
3284 else
3285 {
3286 done = synprot_error(L_smtp_protocol_error, 503, NULL,
3287 US"sender not yet given");
3288 was_rcpt = FALSE; /* Not a valid RCPT */
3289 }
3290 rcpt_fail_count++;
3291 break;
3292 }
3293
3294 /* Check for an operand */
3295
ca86f471 3296 if (smtp_cmd_data[0] == 0)
059ec3d9
PH
3297 {
3298 done = synprot_error(L_smtp_syntax_error, 501, NULL,
3299 US"RCPT must have an address operand");
3300 rcpt_fail_count++;
3301 break;
3302 }
3303
3304 /* Apply SMTP rewriting then extract the working address. Don't allow "<>"
3305 as a recipient address */
3306
3307 recipient = ((rewrite_existflags & rewrite_smtp) != 0)?
ca86f471
PH
3308 rewrite_one(smtp_cmd_data, rewrite_smtp, NULL, FALSE, US"",
3309 global_rewrite_rules) : smtp_cmd_data;
059ec3d9
PH
3310
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 */
3315
3316 if (recipient == NULL)
3317 {
ca86f471 3318 done = synprot_error(L_smtp_syntax_error, 501, smtp_cmd_data, errmess);
059ec3d9
PH
3319 rcpt_fail_count++;
3320 break;
3321 }
3322
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.
3328
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. */
3333
3334 if (recipient_domain == 0)
3335 {
3336 if (allow_unqualified_recipient ||
3337 strcmpic(recipient, US"postmaster") == 0)
3338 {
3339 DEBUG(D_receive) debug_printf("unqualified address %s accepted\n",
3340 recipient);
3341 recipient_domain = Ustrlen(recipient) + 1;
3342 recipient = rewrite_address_qualify(recipient, TRUE);
3343 }
3344 else
3345 {
3346 rcpt_fail_count++;
3347 smtp_printf("501 %s: recipient address must contain a domain\r\n",
ca86f471 3348 smtp_cmd_data);
059ec3d9
PH
3349 log_write(L_smtp_syntax_error,
3350 LOG_MAIN|LOG_REJECT, "unqualified recipient rejected: "
3351 "<%s> %s%s", recipient, host_and_ident(TRUE),
3352 host_lookup_msg);
3353 break;
3354 }
3355 }
3356
3357 /* Check maximum allowed */
3358
3359 if (rcpt_count > recipients_max && recipients_max > 0)
3360 {
3361 if (recipients_max_reject)
3362 {
3363 rcpt_fail_count++;
3364 smtp_printf("552 too many recipients\r\n");
3365 if (!toomany)
3366 log_write(0, LOG_MAIN|LOG_REJECT, "too many recipients: message "
3367 "rejected: sender=<%s> %s", sender_address, host_and_ident(TRUE));
3368 }
3369 else
3370 {
3371 rcpt_defer_count++;
3372 smtp_printf("452 too many recipients\r\n");
3373 if (!toomany)
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));
3377 }
3378
3379 toomany = TRUE;
3380 break;
3381 }
3382
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. */
3385
3386 if (rcpt_count > smtp_rlr_threshold &&
3387 verify_check_host(&smtp_ratelimit_hosts) == OK)
3388 {
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;
3395 }
3396
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. */
3399
3400 rc = recipients_discarded? DISCARD :
3401 acl_check(ACL_WHERE_RCPT, recipient, acl_smtp_rcpt, &user_msg, &log_msg);
3402
3403 /* The ACL was happy */
3404
3405 if (rc == OK)
3406 {
4e88a19f
PH
3407 if (user_msg == NULL) smtp_printf("250 Accepted\r\n");
3408 else smtp_user_msg(US"250", user_msg);
059ec3d9
PH
3409 receive_add_recipient(recipient, -1);
3410 }
3411
3412 /* The recipient was discarded */
3413
3414 else if (rc == DISCARD)
3415 {
4e88a19f
PH
3416 if (user_msg == NULL) smtp_printf("250 Accepted\r\n");
3417 else smtp_user_msg(US"250", user_msg);
059ec3d9
PH
3418 rcpt_fail_count++;
3419 discarded = TRUE;
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,
3ee512ff 3424 smtp_cmd_argument, recipients_discarded? "MAIL" : "RCPT",
059ec3d9
PH
3425 (log_msg == NULL)? US"" : US": ",
3426 (log_msg == NULL)? US"" : log_msg);
3427 }
3428
3429 /* Either the ACL failed the address, or it was deferred. */
3430
3431 else
3432 {
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);
3435 }
3436 break;
3437
3438
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.
3444
3445 Note concerning the code used: RFC 2821 says this:
3446
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
3450 DATA command.
3451
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. */
3454
3455 case DATA_CMD:
b4ed4da0 3456 HAD(SCH_DATA);
059ec3d9
PH
3457 if (!discarded && recipients_count <= 0)
3458 {
3459 if (pipelining_advertised && last_was_rcpt)
3460 smtp_printf("503 valid RCPT command must precede DATA\r\n");
3461 else
3462 done = synprot_error(L_smtp_protocol_error, 503, NULL,
3463 US"valid RCPT command must precede DATA");
3464 break;
3465 }
3466
3467 if (toomany && recipients_max_reject)
3468 {
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");
3472 break;
3473 }
8e669ac1 3474
5be20824 3475 if (acl_smtp_predata == NULL) rc = OK; else
8e669ac1 3476 {
5be20824 3477 enable_dollar_recipients = TRUE;
8e669ac1 3478 rc = acl_check(ACL_WHERE_PREDATA, NULL, acl_smtp_predata, &user_msg,
5be20824
PH
3479 &log_msg);
3480 enable_dollar_recipients = FALSE;
3481 }
059ec3d9
PH
3482
3483 if (rc == OK)
3484 {
4e88a19f
PH
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);
059ec3d9
PH
3488 done = 3;
3489 message_ended = END_NOTENDED; /* Indicate in middle of data */
3490 }
3491
3492 /* Either the ACL failed the address, or it was deferred. */
3493
3494 else
3495 done = smtp_handle_acl_fail(ACL_WHERE_PREDATA, rc, user_msg, log_msg);
3496
3497 break;
3498
3499
3500 case VRFY_CMD:
b4ed4da0 3501 HAD(SCH_VRFY);
64ffc24f 3502 rc = acl_check(ACL_WHERE_VRFY, NULL, acl_smtp_vrfy, &user_msg, &log_msg);
059ec3d9
PH
3503 if (rc != OK)
3504 done = smtp_handle_acl_fail(ACL_WHERE_VRFY, rc, user_msg, log_msg);
3505 else
3506 {
3507 uschar *address;
3508 uschar *s = NULL;
3509
3510 /* rfc821_domains = TRUE; << no longer needed */
ca86f471 3511 address = parse_extract_address(smtp_cmd_data, &errmess, &start, &end,
059ec3d9
PH
3512 &recipient_domain, FALSE);
3513 /* rfc821_domains = FALSE; << no longer needed */
3514
3515 if (address == NULL)
3516 s = string_sprintf("501 %s", errmess);
3517 else
3518 {
3519 address_item *addr = deliver_make_addr(address, FALSE);
3520 switch(verify_address(addr, NULL, vopt_is_recipient | vopt_qualify, -1,
4deaf07d 3521 -1, -1, NULL, NULL, NULL))
059ec3d9
PH
3522 {
3523 case OK:
3524 s = string_sprintf("250 <%s> is deliverable", address);
3525 break;
3526
3527 case DEFER:
81e509d7
PH
3528 s = (addr->user_message != NULL)?
3529 string_sprintf("451 <%s> %s", address, addr->user_message) :
059ec3d9
PH
3530 string_sprintf("451 Cannot resolve <%s> at this time", address);
3531 break;
3532
3533 case FAIL:
81e509d7
PH
3534 s = (addr->user_message != NULL)?
3535 string_sprintf("550 <%s> %s", address, addr->user_message) :
059ec3d9
PH
3536 string_sprintf("550 <%s> is not deliverable", address);
3537 log_write(0, LOG_MAIN, "VRFY failed for %s %s",
3ee512ff 3538 smtp_cmd_argument, host_and_ident(TRUE));
059ec3d9
PH
3539 break;
3540 }
3541 }
3542
3543 smtp_printf("%s\r\n", s);
3544 }
3545 break;
3546
3547
3548 case EXPN_CMD:
b4ed4da0 3549 HAD(SCH_EXPN);
64ffc24f 3550 rc = acl_check(ACL_WHERE_EXPN, NULL, acl_smtp_expn, &user_msg, &log_msg);
059ec3d9
PH
3551 if (rc != OK)
3552 done = smtp_handle_acl_fail(ACL_WHERE_EXPN, rc, user_msg, log_msg);
3553 else
3554 {
3555 BOOL save_log_testing_mode = log_testing_mode;
3556 address_test_mode = log_testing_mode = TRUE;
ca86f471 3557 (void) verify_address(deliver_make_addr(smtp_cmd_data, FALSE),
64ffc24f
PH
3558 smtp_out, vopt_is_recipient | vopt_qualify | vopt_expn, -1, -1, -1,
3559 NULL, NULL, NULL);
059ec3d9
PH
3560 address_test_mode = FALSE;
3561 log_testing_mode = save_log_testing_mode; /* true for -bh */
3562 }
3563 break;
3564
3565
3566 #ifdef SUPPORT_TLS
3567
3568 case STARTTLS_CMD:
b4ed4da0 3569 HAD(SCH_STARTTLS);
059ec3d9
PH
3570 if (!tls_advertised)
3571 {
3572 done = synprot_error(L_smtp_protocol_error, 503, NULL,
3573 US"STARTTLS command used when not advertised");
3574 break;
3575 }
3576
3577 /* Apply an ACL check if one is defined */
3578
3579 if (acl_smtp_starttls != NULL)
3580 {
3581 rc = acl_check(ACL_WHERE_STARTTLS, NULL, acl_smtp_starttls, &user_msg,
3582 &log_msg);
3583 if (rc != OK)
3584 {
3585 done = smtp_handle_acl_fail(ACL_WHERE_STARTTLS, rc, user_msg, log_msg);
3586 break;
3587 }
3588 }
3589
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. */
3594
3595 incomplete_transaction_log(US"STARTTLS");
3596 smtp_reset(reset_point);
3597 toomany = FALSE;
3598 cmd_list[CMD_LIST_STARTTLS].is_mail_cmd = FALSE;
3599
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.
3604
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. */
3607
83da1223
PH
3608 if ((rc = tls_server_start(tls_require_ciphers, gnutls_require_mac,
3609 gnutls_require_kx, gnutls_require_proto)) == OK)
059ec3d9
PH
3610 {
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)
3616 {
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));
3622 }
3623 received_protocol = (esmtp?
3624 protocols[pextend + pcrpted +
3625 ((sender_host_authenticated != NULL)? pauthed : 0)]
3626 :
981756db 3627 protocols[pnormal + pcrpted])
059ec3d9
PH
3628 +
3629 ((sender_host_address != NULL)? pnlocal : 0);
3630
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 */
3636 }
3637
3638 /* Some local configuration problem was discovered before actually trying
3639 to do a TLS handshake; give a temporary error. */
3640
3641 else if (rc == DEFER)
3642 {
3643 smtp_printf("454 TLS currently unavailable\r\n");
3644 break;
3645 }
3646
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. */
3650
3651 DEBUG(D_tls) debug_printf("TLS failed to start\n");
3652 while (done <= 0)
3653 {
3654 switch(smtp_read_command(FALSE))
3655 {
3656 case EOF_CMD:
3657 log_write(L_smtp_connection, LOG_MAIN, "%s closed by EOF",
3658 smtp_get_connection_info());
3659 done = 2;
3660 break;
3661
3662 case QUIT_CMD:
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());
3666 done = 2;
3667 break;
3668
3669 default:
3670 smtp_printf("554 Security failure\r\n");
3671 break;
3672 }
3673 }
3674 tls_close(TRUE);
3675 break;
3676 #endif
3677
3678
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
3681 message. */
3682
3683 case QUIT_CMD:
b4ed4da0 3684 HAD(SCH_QUIT);
059ec3d9
PH
3685 incomplete_transaction_log(US"QUIT");
3686
3687 if (acl_smtp_quit != NULL)
3688 {
64ffc24f 3689 rc = acl_check(ACL_WHERE_QUIT, NULL, acl_smtp_quit,&user_msg,&log_msg);
059ec3d9
PH
3690 if (rc == ERROR)
3691 log_write(0, LOG_MAIN|LOG_PANIC, "ACL for QUIT returned ERROR: %s",
3692 log_msg);
3693 }
059ec3d9
PH
3694
3695 if (user_msg == NULL)
3696 smtp_printf("221 %s closing connection\r\n", smtp_active_hostname);
3697 else
4e88a19f 3698 smtp_respond(US"221", 3, TRUE, user_msg);
059ec3d9
PH
3699
3700 #ifdef SUPPORT_TLS
3701 tls_close(TRUE);
3702 #endif
3703
3704 done = 2;
3705 log_write(L_smtp_connection, LOG_MAIN, "%s closed by QUIT",
3706 smtp_get_connection_info());
3707 break;
3708
3709
3710 case RSET_CMD:
b4ed4da0 3711 HAD(SCH_RSET);
059ec3d9
PH
3712 incomplete_transaction_log(US"RSET");
3713 smtp_reset(reset_point);
3714 toomany = FALSE;
3715 smtp_printf("250 Reset OK\r\n");
3716 cmd_list[CMD_LIST_RSET].is_mail_cmd = FALSE;
3717 break;
3718
3719
3720 case NOOP_CMD:
b4ed4da0 3721 HAD(SCH_NOOP);
059ec3d9
PH
3722 smtp_printf("250 OK\r\n");
3723 break;
3724
3725
3726 /* Show ETRN/EXPN/VRFY if there's
3727 an ACL for checking hosts; if actually used, a check will be done for
3728 permitted hosts. */
3729
3730 case HELP_CMD:
b4ed4da0 3731 HAD(SCH_HELP);
059ec3d9
PH
3732 smtp_printf("214-Commands supported:\r\n");
3733 {
3734 uschar buffer[256];
3735 buffer[0] = 0;
3736 Ustrcat(buffer, " AUTH");
3737 #ifdef SUPPORT_TLS
3738 Ustrcat(buffer, " STARTTLS");
3739 #endif
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);
3746 }
3747 break;
3748
3749
3750 case EOF_CMD:
3751 incomplete_transaction_log(US"connection lost");
3752 smtp_printf("421 %s lost input connection\r\n", smtp_active_hostname);
3753
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.
3756 */
3757
3758 if (sender_address != NULL || recipients_count > 0)
3759 log_write(L_lost_incoming_connection,
3760 LOG_MAIN,
3761 "unexpected %s while reading SMTP command from %s%s",
3762 sender_host_unknown? "EOF" : "disconnection",
3763 host_and_ident(FALSE), smtp_read_error);
3764
3765 else log_write(L_smtp_connection, LOG_MAIN, "%s lost%s",
3766 smtp_get_connection_info(), smtp_read_error);
3767
3768 done = 1;
3769 break;
3770
3771
3772 case ETRN_CMD:
b4ed4da0 3773 HAD(SCH_ETRN);
059ec3d9
PH
3774 if (sender_address != NULL)
3775 {
3776 done = synprot_error(L_smtp_protocol_error, 503, NULL,
3777 US"ETRN is not permitted inside a transaction");
3778 break;
3779 }
3780
3ee512ff 3781 log_write(L_etrn, LOG_MAIN, "ETRN %s received from %s", smtp_cmd_argument,
059ec3d9
PH
3782 host_and_ident(FALSE));
3783
64ffc24f 3784 rc = acl_check(ACL_WHERE_ETRN, NULL, acl_smtp_etrn, &user_msg, &log_msg);
059ec3d9
PH
3785 if (rc != OK)
3786 {
3787 done = smtp_handle_acl_fail(ACL_WHERE_ETRN, rc, user_msg, log_msg);
3788 break;
3789 }
3790
3791 /* Compute the serialization key for this command. */
3792
ca86f471 3793 etrn_serialize_key = string_sprintf("etrn-%s\n", smtp_cmd_data);
059ec3d9
PH
3794
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. */
3799
3800 if (smtp_etrn_command != NULL)
3801 {
3802 uschar *error;
3803 BOOL rc;
3804 etrn_command = smtp_etrn_command;
ca86f471 3805 deliver_domain = smtp_cmd_data;
059ec3d9
PH
3806 rc = transport_set_up_command(&argv, smtp_etrn_command, TRUE, 0, NULL,
3807 US"ETRN processing", &error);
3808 deliver_domain = NULL;
3809 if (!rc)
3810 {
3811 log_write(0, LOG_MAIN|LOG_PANIC, "failed to set up ETRN command: %s",
3812 error);
3813 smtp_printf("458 Internal failure\r\n");
3814 break;
3815 }
3816 }
3817
3818 /* Else set up to call Exim with the -R option. */
3819
3820 else
3821 {
ca86f471 3822 if (*smtp_cmd_data++ != '#')
059ec3d9
PH
3823 {
3824 done = synprot_error(L_smtp_syntax_error, 501, NULL,
3825 US"argument must begin with #");
3826 break;
3827 }
3828 etrn_command = US"exim -R";
3829 argv = child_exec_exim(CEE_RETURN_ARGV, TRUE, NULL, TRUE, 2, US"-R",
ca86f471 3830 smtp_cmd_data);
059ec3d9
PH
3831 }
3832
3833 /* If we are host-testing, don't actually do anything. */
3834
3835 if (host_checking)
3836 {
3837 HDEBUG(D_any)
3838 {
3839 debug_printf("ETRN command is: %s\n", etrn_command);
3840 debug_printf("ETRN command execution skipped\n");
3841 }
4e88a19f
PH
3842 if (user_msg == NULL) smtp_printf("250 OK\r\n");
3843 else smtp_user_msg(US"250", user_msg);
059ec3d9
PH
3844 break;
3845 }
3846
3847
3848 /* If ETRN queue runs are to be serialized, check the database to
3849 ensure one isn't already running. */
3850
3851 if (smtp_etrn_serialize && !enq_start(etrn_serialize_key))
3852 {
ca86f471 3853 smtp_printf("458 Already processing %s\r\n", smtp_cmd_data);
059ec3d9
PH
3854 break;
3855 }
3856
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. */
3863
3864 oldsignal = signal(SIGCHLD, SIG_IGN);
3865
3866 if ((pid = fork()) == 0)
3867 {
f1e894f3
PH
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);
059ec3d9
PH
3871
3872 signal(SIGCHLD, SIG_DFL); /* Want to catch child */
3873
3874 /* If not serializing, do the exec right away. Otherwise, fork down
3875 into another process. */
3876
3877 if (!smtp_etrn_serialize || (pid = fork()) == 0)
3878 {
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 */
3885 }
3886
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. */
3891
3892 if (pid < 0)
3893 log_write(0, LOG_MAIN|LOG_PANIC, "2nd fork for serialized ETRN "
3894 "failed: %s", strerror(errno));
3895 else
3896 {
3897 int status;
3898 DEBUG(D_any) debug_printf("waiting for serialized ETRN process %d\n",
3899 (int)pid);
3900 (void)wait(&status);
3901 DEBUG(D_any) debug_printf("serialized ETRN process %d ended\n",
3902 (int)pid);
3903 }
3904
3905 enq_end(etrn_serialize_key);
3906 _exit(EXIT_SUCCESS);
3907 }
3908
3909 /* Back in the top level SMTP process. Check that we started a subprocess
3910 and restore the signal state. */
3911
3912 if (pid < 0)
3913 {
3914 log_write(0, LOG_MAIN|LOG_PANIC, "fork of process for ETRN failed: %s",
3915 strerror(errno));
3916 smtp_printf("458 Unable to fork process\r\n");
3917 if (smtp_etrn_serialize) enq_end(etrn_serialize_key);
3918 }
4e88a19f
PH
3919 else
3920 {
3921 if (user_msg == NULL) smtp_printf("250 OK\r\n");
3922 else smtp_user_msg(US"250", user_msg);
3923 }
059ec3d9
PH
3924
3925 signal(SIGCHLD, oldsignal);
3926 break;
3927
3928
3929 case BADARG_CMD:
3930 done = synprot_error(L_smtp_syntax_error, 501, NULL,
3931 US"unexpected argument data");
3932 break;
3933
3934
3935 /* This currently happens only for NULLs, but could be extended. */
3936
3937 case BADCHAR_CMD:
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");
3941 break;
3942
3943
3944 case BADSYN_CMD:
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;
3949 smtp_inptr[c] = 0;
3950 incomplete_transaction_log(US"sync failure");
3af76a81 3951 log_write(0, LOG_MAIN|LOG_REJECT, "SMTP protocol synchronization error "
059ec3d9
PH
3952 "(next input sent too soon: pipelining was%s advertised): "
3953 "rejected \"%s\" %s next input=\"%s\"",
3954 pipelining_advertised? "" : " not",
3ee512ff 3955 smtp_cmd_buffer, host_and_ident(TRUE),
059ec3d9
PH
3956 string_printing(smtp_inptr));
3957 smtp_printf("554 SMTP synchronization error\r\n");
3958 done = 1; /* Pretend eof - drops connection */
3959 break;
3960
3961
3962 case TOO_MANY_NONMAIL_CMD:
ca86f471
PH
3963 s = smtp_cmd_buffer;
3964 while (*s != 0 && !isspace(*s)) s++;
059ec3d9
PH
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),
ca86f471 3968 s - smtp_cmd_buffer, smtp_cmd_buffer);
059ec3d9
PH
3969 smtp_printf("554 Too many nonmail commands\r\n");
3970 done = 1; /* Pretend eof - drops connection */
3971 break;
3972
3973
3974 default:
3975 if (unknown_command_count++ >= smtp_max_unknown_commands)
3976 {
3977 log_write(L_smtp_syntax_error, LOG_MAIN,
3978 "SMTP syntax error in \"%s\" %s %s",
3ee512ff 3979 string_printing(smtp_cmd_buffer), host_and_ident(TRUE),
059ec3d9
PH
3980 US"unrecognized command");
3981 incomplete_transaction_log(US"unrecognized command");
3982 smtp_printf("500 Too many unrecognized commands\r\n");
3983 done = 2;
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),
3ee512ff 3986 smtp_cmd_buffer);
059ec3d9
PH
3987 }
3988 else
3989 done = synprot_error(L_smtp_syntax_error, 500, NULL,
3990 US"unrecognized command");
3991 break;
3992 }
3993
3994 /* This label is used by goto's inside loops that want to break out to
3995 the end of the command-processing loop. */
3996
3997 COMMAND_LOOP:
3998 last_was_rej_mail = was_rej_mail; /* Remember some last commands for */
3999 last_was_rcpt = was_rcpt; /* protocol error handling */
4000 continue;
4001 }
4002
4003return done - 2; /* Convert yield values */
4004}
4005
4006/* End of smtp_in.c */