Fix heavy-pipeline SMTP command input corruption. Bug 2250
[exim.git] / src / src / smtp_in.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2018 */
6 /* See the file NOTICE for conditions of use and distribution. */
7
8 /* Functions for handling an incoming SMTP call. */
9
10
11 #include "exim.h"
12 #include <assert.h>
13
14
15 /* Initialize for TCP wrappers if so configured. It appears that the macro
16 HAVE_IPV6 is used in some versions of the tcpd.h header, so we unset it before
17 including that header, and restore its value afterwards. */
18
19 #ifdef USE_TCP_WRAPPERS
20
21   #if HAVE_IPV6
22   #define EXIM_HAVE_IPV6
23   #endif
24   #undef HAVE_IPV6
25   #include <tcpd.h>
26   #undef HAVE_IPV6
27   #ifdef EXIM_HAVE_IPV6
28   #define HAVE_IPV6 TRUE
29   #endif
30
31 int allow_severity = LOG_INFO;
32 int deny_severity  = LOG_NOTICE;
33 uschar *tcp_wrappers_name;
34 #endif
35
36
37 /* Size of buffer for reading SMTP commands. We used to use 512, as defined
38 by RFC 821. However, RFC 1869 specifies that this must be increased for SMTP
39 commands that accept arguments, and this in particular applies to AUTH, where
40 the data can be quite long.  More recently this value was 2048 in Exim;
41 however, RFC 4954 (circa 2007) recommends 12288 bytes to handle AUTH.  Clients
42 such as Thunderbird will send an AUTH with an initial-response for GSSAPI.
43 The maximum size of a Kerberos ticket under Windows 2003 is 12000 bytes, and
44 we need room to handle large base64-encoded AUTHs for GSSAPI.
45 */
46
47 #define SMTP_CMD_BUFFER_SIZE  16384
48
49 /* Size of buffer for reading SMTP incoming packets */
50
51 #define IN_BUFFER_SIZE  8192
52
53 /* Structure for SMTP command list */
54
55 typedef struct {
56   const char *name;
57   int len;
58   short int cmd;
59   short int has_arg;
60   short int is_mail_cmd;
61 } smtp_cmd_list;
62
63 /* Codes for identifying commands. We order them so that those that come first
64 are those for which synchronization is always required. Checking this can help
65 block some spam.  */
66
67 enum {
68   /* These commands are required to be synchronized, i.e. to be the last in a
69   block of commands when pipelining. */
70
71   HELO_CMD, EHLO_CMD, DATA_CMD, /* These are listed in the pipelining */
72   VRFY_CMD, EXPN_CMD, NOOP_CMD, /* RFC as requiring synchronization */
73   ETRN_CMD,                     /* This by analogy with TURN from the RFC */
74   STARTTLS_CMD,                 /* Required by the STARTTLS RFC */
75   TLS_AUTH_CMD,                 /* auto-command at start of SSL */
76
77   /* This is a dummy to identify the non-sync commands when pipelining */
78
79   NON_SYNC_CMD_PIPELINING,
80
81   /* These commands need not be synchronized when pipelining */
82
83   MAIL_CMD, RCPT_CMD, RSET_CMD,
84
85   /* This is a dummy to identify the non-sync commands when not pipelining */
86
87   NON_SYNC_CMD_NON_PIPELINING,
88
89   /* RFC3030 section 2: "After all MAIL and RCPT responses are collected and
90   processed the message is sent using a series of BDAT commands"
91   implies that BDAT should be synchronized.  However, we see Google, at least,
92   sending MAIL,RCPT,BDAT-LAST in a single packet, clearly not waiting for
93   processing of the RCPT response(s).  We shall do the same, and not require
94   synch for BDAT.  Worse, as the chunk may (very likely will) follow the
95   command-header in the same packet we cannot do the usual "is there any
96   follow-on data after the command line" even for non-pipeline mode.
97   So we'll need an explicit check after reading the expected chunk amount
98   when non-pipe, before sending the ACK. */
99
100   BDAT_CMD,
101
102   /* I have been unable to find a statement about the use of pipelining
103   with AUTH, so to be on the safe side it is here, though I kind of feel
104   it should be up there with the synchronized commands. */
105
106   AUTH_CMD,
107
108   /* I'm not sure about these, but I don't think they matter. */
109
110   QUIT_CMD, HELP_CMD,
111
112 #ifdef SUPPORT_PROXY
113   PROXY_FAIL_IGNORE_CMD,
114 #endif
115
116   /* These are specials that don't correspond to actual commands */
117
118   EOF_CMD, OTHER_CMD, BADARG_CMD, BADCHAR_CMD, BADSYN_CMD,
119   TOO_MANY_NONMAIL_CMD };
120
121
122 /* This is a convenience macro for adding the identity of an SMTP command
123 to the circular buffer that holds a list of the last n received. */
124
125 #define HAD(n) \
126     smtp_connection_had[smtp_ch_index++] = n; \
127     if (smtp_ch_index >= SMTP_HBUFF_SIZE) smtp_ch_index = 0
128
129
130 /*************************************************
131 *                Local static variables          *
132 *************************************************/
133
134 static auth_instance *authenticated_by;
135 static BOOL auth_advertised;
136 #ifdef SUPPORT_TLS
137 static BOOL tls_advertised;
138 #endif
139 static BOOL dsn_advertised;
140 static BOOL esmtp;
141 static BOOL helo_required = FALSE;
142 static BOOL helo_verify = FALSE;
143 static BOOL helo_seen;
144 static BOOL helo_accept_junk;
145 static BOOL count_nonmail;
146 static BOOL pipelining_advertised;
147 static BOOL rcpt_smtp_response_same;
148 static BOOL rcpt_in_progress;
149 static int  nonmail_command_count;
150 static BOOL smtp_exit_function_called = 0;
151 #ifdef SUPPORT_I18N
152 static BOOL smtputf8_advertised;
153 #endif
154 static int  synprot_error_count;
155 static int  unknown_command_count;
156 static int  sync_cmd_limit;
157 static int  smtp_write_error = 0;
158
159 static uschar *rcpt_smtp_response;
160 static uschar *smtp_data_buffer;
161 static uschar *smtp_cmd_data;
162
163 /* We need to know the position of RSET, HELO, EHLO, AUTH, and STARTTLS. Their
164 final fields of all except AUTH are forced TRUE at the start of a new message
165 setup, to allow one of each between messages that is not counted as a nonmail
166 command. (In fact, only one of HELO/EHLO is not counted.) Also, we have to
167 allow a new EHLO after starting up TLS.
168
169 AUTH is "falsely" labelled as a mail command initially, so that it doesn't get
170 counted. However, the flag is changed when AUTH is received, so that multiple
171 failing AUTHs will eventually hit the limit. After a successful AUTH, another
172 AUTH is already forbidden. After a TLS session is started, AUTH's flag is again
173 forced TRUE, to allow for the re-authentication that can happen at that point.
174
175 QUIT is also "falsely" labelled as a mail command so that it doesn't up the
176 count of non-mail commands and possibly provoke an error.
177
178 tls_auth is a pseudo-command, never expected in input.  It is activated
179 on TLS startup and looks for a tls authenticator. */
180
181 static smtp_cmd_list cmd_list[] = {
182   /* name         len                     cmd     has_arg is_mail_cmd */
183
184   { "rset",       sizeof("rset")-1,       RSET_CMD, FALSE, FALSE },  /* First */
185   { "helo",       sizeof("helo")-1,       HELO_CMD, TRUE,  FALSE },
186   { "ehlo",       sizeof("ehlo")-1,       EHLO_CMD, TRUE,  FALSE },
187   { "auth",       sizeof("auth")-1,       AUTH_CMD, TRUE,  TRUE  },
188   #ifdef SUPPORT_TLS
189   { "starttls",   sizeof("starttls")-1,   STARTTLS_CMD, FALSE, FALSE },
190   { "tls_auth",   0,                      TLS_AUTH_CMD, FALSE, FALSE },
191   #endif
192
193 /* If you change anything above here, also fix the definitions below. */
194
195   { "mail from:", sizeof("mail from:")-1, MAIL_CMD, TRUE,  TRUE  },
196   { "rcpt to:",   sizeof("rcpt to:")-1,   RCPT_CMD, TRUE,  TRUE  },
197   { "data",       sizeof("data")-1,       DATA_CMD, FALSE, TRUE  },
198   { "bdat",       sizeof("bdat")-1,       BDAT_CMD, TRUE,  TRUE  },
199   { "quit",       sizeof("quit")-1,       QUIT_CMD, FALSE, TRUE  },
200   { "noop",       sizeof("noop")-1,       NOOP_CMD, TRUE,  FALSE },
201   { "etrn",       sizeof("etrn")-1,       ETRN_CMD, TRUE,  FALSE },
202   { "vrfy",       sizeof("vrfy")-1,       VRFY_CMD, TRUE,  FALSE },
203   { "expn",       sizeof("expn")-1,       EXPN_CMD, TRUE,  FALSE },
204   { "help",       sizeof("help")-1,       HELP_CMD, TRUE,  FALSE }
205 };
206
207 static smtp_cmd_list *cmd_list_end =
208   cmd_list + sizeof(cmd_list)/sizeof(smtp_cmd_list);
209
210 #define CMD_LIST_RSET      0
211 #define CMD_LIST_HELO      1
212 #define CMD_LIST_EHLO      2
213 #define CMD_LIST_AUTH      3
214 #define CMD_LIST_STARTTLS  4
215 #define CMD_LIST_TLS_AUTH  5
216
217 /* This list of names is used for performing the smtp_no_mail logging action.
218 It must be kept in step with the SCH_xxx enumerations. */
219
220 static uschar *smtp_names[] =
221   {
222   US"NONE", US"AUTH", US"DATA", US"BDAT", US"EHLO", US"ETRN", US"EXPN",
223   US"HELO", US"HELP", US"MAIL", US"NOOP", US"QUIT", US"RCPT", US"RSET",
224   US"STARTTLS", US"VRFY" };
225
226 static uschar *protocols_local[] = {
227   US"local-smtp",        /* HELO */
228   US"local-smtps",       /* The rare case EHLO->STARTTLS->HELO */
229   US"local-esmtp",       /* EHLO */
230   US"local-esmtps",      /* EHLO->STARTTLS->EHLO */
231   US"local-esmtpa",      /* EHLO->AUTH */
232   US"local-esmtpsa"      /* EHLO->STARTTLS->EHLO->AUTH */
233   };
234 static uschar *protocols[] = {
235   US"smtp",              /* HELO */
236   US"smtps",             /* The rare case EHLO->STARTTLS->HELO */
237   US"esmtp",             /* EHLO */
238   US"esmtps",            /* EHLO->STARTTLS->EHLO */
239   US"esmtpa",            /* EHLO->AUTH */
240   US"esmtpsa"            /* EHLO->STARTTLS->EHLO->AUTH */
241   };
242
243 #define pnormal  0
244 #define pextend  2
245 #define pcrpted  1  /* added to pextend or pnormal */
246 #define pauthed  2  /* added to pextend */
247
248 /* Sanity check and validate optional args to MAIL FROM: envelope */
249 enum {
250   ENV_MAIL_OPT_NULL,
251   ENV_MAIL_OPT_SIZE, ENV_MAIL_OPT_BODY, ENV_MAIL_OPT_AUTH,
252 #ifndef DISABLE_PRDR
253   ENV_MAIL_OPT_PRDR,
254 #endif
255   ENV_MAIL_OPT_RET, ENV_MAIL_OPT_ENVID,
256 #ifdef SUPPORT_I18N
257   ENV_MAIL_OPT_UTF8,
258 #endif
259   };
260 typedef struct {
261   uschar *   name;  /* option requested during MAIL cmd */
262   int       value;  /* enum type */
263   BOOL need_value;  /* TRUE requires value (name=value pair format)
264                        FALSE is a singleton */
265   } env_mail_type_t;
266 static env_mail_type_t env_mail_type_list[] = {
267     { US"SIZE",   ENV_MAIL_OPT_SIZE,   TRUE  },
268     { US"BODY",   ENV_MAIL_OPT_BODY,   TRUE  },
269     { US"AUTH",   ENV_MAIL_OPT_AUTH,   TRUE  },
270 #ifndef DISABLE_PRDR
271     { US"PRDR",   ENV_MAIL_OPT_PRDR,   FALSE },
272 #endif
273     { US"RET",    ENV_MAIL_OPT_RET,    TRUE },
274     { US"ENVID",  ENV_MAIL_OPT_ENVID,  TRUE },
275 #ifdef SUPPORT_I18N
276     { US"SMTPUTF8",ENV_MAIL_OPT_UTF8,  FALSE },         /* rfc6531 */
277 #endif
278     /* keep this the last entry */
279     { US"NULL",   ENV_MAIL_OPT_NULL,   FALSE },
280   };
281
282 /* When reading SMTP from a remote host, we have to use our own versions of the
283 C input-reading functions, in order to be able to flush the SMTP output only
284 when about to read more data from the socket. This is the only way to get
285 optimal performance when the client is using pipelining. Flushing for every
286 command causes a separate packet and reply packet each time; saving all the
287 responses up (when pipelining) combines them into one packet and one response.
288
289 For simplicity, these functions are used for *all* SMTP input, not only when
290 receiving over a socket. However, after setting up a secure socket (SSL), input
291 is read via the OpenSSL library, and another set of functions is used instead
292 (see tls.c).
293
294 These functions are set in the receive_getc etc. variables and called with the
295 same interface as the C functions. However, since there can only ever be
296 one incoming SMTP call, we just use a single buffer and flags. There is no need
297 to implement a complicated private FILE-like structure.*/
298
299 static uschar *smtp_inbuffer;
300 static uschar *smtp_inptr;
301 static uschar *smtp_inend;
302 static int     smtp_had_eof;
303 static int     smtp_had_error;
304
305
306 /* forward declarations */
307 static int smtp_read_command(BOOL check_sync, unsigned buffer_lim);
308 static int synprot_error(int type, int code, uschar *data, uschar *errmess);
309 static void smtp_quit_handler(uschar **, uschar **);
310 static void smtp_rset_handler(void);
311
312 /*************************************************
313 *          Recheck synchronization               *
314 *************************************************/
315
316 /* Synchronization checks can never be perfect because a packet may be on its
317 way but not arrived when the check is done.  Normally, the checks happen when
318 commands are read: Exim ensures that there is no more input in the input buffer.
319 In normal cases, the response to the command will be fast, and there is no
320 further check.
321
322 However, for some commands an ACL is run, and that can include delays. In those
323 cases, it is useful to do another check on the input just before sending the
324 response. This also applies at the start of a connection. This function does
325 that check by means of the select() function, as long as the facility is not
326 disabled or inappropriate. A failure of select() is ignored.
327
328 When there is unwanted input, we read it so that it appears in the log of the
329 error.
330
331 Arguments: none
332 Returns:   TRUE if all is well; FALSE if there is input pending
333 */
334
335 static BOOL
336 wouldblock_reading(void)
337 {
338 int fd, rc;
339 fd_set fds;
340 struct timeval tzero;
341
342 #ifdef SUPPORT_TLS
343 if (tls_in.active >= 0)
344  return !tls_could_read();
345 #endif
346
347 if (smtp_inptr < smtp_inend)
348   return FALSE;
349
350 fd = fileno(smtp_in);
351 FD_ZERO(&fds);
352 FD_SET(fd, &fds);
353 tzero.tv_sec = 0;
354 tzero.tv_usec = 0;
355 rc = select(fd + 1, (SELECT_ARG2_TYPE *)&fds, NULL, NULL, &tzero);
356
357 if (rc <= 0) return TRUE;     /* Not ready to read */
358 rc = smtp_getc(GETC_BUFFER_UNLIMITED);
359 if (rc < 0) return TRUE;      /* End of file or error */
360
361 smtp_ungetc(rc);
362 return FALSE;
363 }
364
365 static BOOL
366 check_sync(void)
367 {
368 if (!smtp_enforce_sync || !sender_host_address || sender_host_notsocket)
369   return TRUE;
370
371 return wouldblock_reading();
372 }
373
374
375 /* If there's input waiting (and we're doing pipelineing) then we can pipeline
376 a reponse with the one following. */
377
378 static BOOL
379 pipeline_response(void)
380 {
381 if (  !smtp_enforce_sync || !sender_host_address
382    || sender_host_notsocket || !pipelining_advertised)
383   return FALSE;
384
385 return !wouldblock_reading();
386 }
387
388
389
390 /*************************************************
391 *          Log incomplete transactions           *
392 *************************************************/
393
394 /* This function is called after a transaction has been aborted by RSET, QUIT,
395 connection drops or other errors. It logs the envelope information received
396 so far in order to preserve address verification attempts.
397
398 Argument:   string to indicate what aborted the transaction
399 Returns:    nothing
400 */
401
402 static void
403 incomplete_transaction_log(uschar *what)
404 {
405 if (sender_address == NULL ||                 /* No transaction in progress */
406     !LOGGING(smtp_incomplete_transaction))
407   return;
408
409 /* Build list of recipients for logging */
410
411 if (recipients_count > 0)
412   {
413   int i;
414   raw_recipients = store_get(recipients_count * sizeof(uschar *));
415   for (i = 0; i < recipients_count; i++)
416     raw_recipients[i] = recipients_list[i].address;
417   raw_recipients_count = recipients_count;
418   }
419
420 log_write(L_smtp_incomplete_transaction, LOG_MAIN|LOG_SENDER|LOG_RECIPIENTS,
421   "%s incomplete transaction (%s)", host_and_ident(TRUE), what);
422 }
423
424
425
426
427 /* Refill the buffer, and notify DKIM verification code.
428 Return false for error or EOF.
429 */
430
431 static BOOL
432 smtp_refill(unsigned lim)
433 {
434 int rc, save_errno;
435 if (!smtp_out) return FALSE;
436 fflush(smtp_out);
437 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
438
439 /* Limit amount read, so non-message data is not fed to DKIM.
440 Take care to not touch the safety NUL at the end of the buffer. */
441
442 rc = read(fileno(smtp_in), smtp_inbuffer, MIN(IN_BUFFER_SIZE-1, lim));
443 save_errno = errno;
444 alarm(0);
445 if (rc <= 0)
446   {
447   /* Must put the error text in fixed store, because this might be during
448   header reading, where it releases unused store above the header. */
449   if (rc < 0)
450     {
451     smtp_had_error = save_errno;
452     smtp_read_error = string_copy_malloc(
453       string_sprintf(" (error: %s)", strerror(save_errno)));
454     }
455   else smtp_had_eof = 1;
456   return FALSE;
457   }
458 #ifndef DISABLE_DKIM
459 dkim_exim_verify_feed(smtp_inbuffer, rc);
460 #endif
461 smtp_inend = smtp_inbuffer + rc;
462 smtp_inptr = smtp_inbuffer;
463 return TRUE;
464 }
465
466 /*************************************************
467 *          SMTP version of getc()                *
468 *************************************************/
469
470 /* This gets the next byte from the SMTP input buffer. If the buffer is empty,
471 it flushes the output, and refills the buffer, with a timeout. The signal
472 handler is set appropriately by the calling function. This function is not used
473 after a connection has negotiated itself into an TLS/SSL state.
474
475 Arguments:  lim         Maximum amount to read/buffer
476 Returns:    the next character or EOF
477 */
478
479 int
480 smtp_getc(unsigned lim)
481 {
482 if (smtp_inptr >= smtp_inend)
483   if (!smtp_refill(lim))
484     return EOF;
485 return *smtp_inptr++;
486 }
487
488 uschar *
489 smtp_getbuf(unsigned * len)
490 {
491 unsigned size;
492 uschar * buf;
493
494 if (smtp_inptr >= smtp_inend)
495   if (!smtp_refill(*len))
496     { *len = 0; return NULL; }
497
498 if ((size = smtp_inend - smtp_inptr) > *len) size = *len;
499 buf = smtp_inptr;
500 smtp_inptr += size;
501 *len = size;
502 return buf;
503 }
504
505 void
506 smtp_get_cache(void)
507 {
508 #ifndef DISABLE_DKIM
509 int n = smtp_inend - smtp_inptr;
510 if (n > 0)
511   dkim_exim_verify_feed(smtp_inptr, n);
512 #endif
513 }
514
515
516 /* Get a byte from the smtp input, in CHUNKING mode.  Handle ack of the
517 previous BDAT chunk and getting new ones when we run out.  Uses the
518 underlying smtp_getc or tls_getc both for that and for getting the
519 (buffered) data byte.  EOD signals (an expected) no further data.
520 ERR signals a protocol error, and EOF a closed input stream.
521
522 Called from read_bdat_smtp() in receive.c for the message body, but also
523 by the headers read loop in receive_msg(); manipulates chunking_state
524 to handle the BDAT command/response.
525 Placed here due to the correlation with the above smtp_getc(), which it wraps,
526 and also by the need to do smtp command/response handling.
527
528 Arguments:  lim         (ignored)
529 Returns:    the next character or ERR, EOD or EOF
530 */
531
532 int
533 bdat_getc(unsigned lim)
534 {
535 uschar * user_msg = NULL;
536 uschar * log_msg;
537
538 for(;;)
539   {
540 #ifndef DISABLE_DKIM
541   BOOL dkim_save;
542 #endif
543
544   if (chunking_data_left > 0)
545     return lwr_receive_getc(chunking_data_left--);
546
547   receive_getc = lwr_receive_getc;
548   receive_getbuf = lwr_receive_getbuf;
549   receive_ungetc = lwr_receive_ungetc;
550 #ifndef DISABLE_DKIM
551   dkim_save = dkim_collect_input;
552   dkim_collect_input = FALSE;
553 #endif
554
555   /* Unless PIPELINING was offered, there should be no next command
556   until after we ack that chunk */
557
558   if (!pipelining_advertised && !check_sync())
559     {
560     unsigned n = smtp_inend - smtp_inptr;
561     if (n > 32) n = 32;
562
563     incomplete_transaction_log(US"sync failure");
564     log_write(0, LOG_MAIN|LOG_REJECT, "SMTP protocol synchronization error "
565       "(next input sent too soon: pipelining was not advertised): "
566       "rejected \"%s\" %s next input=\"%s\"%s",
567       smtp_cmd_buffer, host_and_ident(TRUE),
568       string_printing(string_copyn(smtp_inptr, n)),
569       smtp_inend - smtp_inptr > n ? "..." : "");
570     (void) synprot_error(L_smtp_protocol_error, 554, NULL,
571       US"SMTP synchronization error");
572     goto repeat_until_rset;
573     }
574
575   /* If not the last, ack the received chunk.  The last response is delayed
576   until after the data ACL decides on it */
577
578   if (chunking_state == CHUNKING_LAST)
579     {
580 #ifndef DISABLE_DKIM
581     dkim_exim_verify_feed(NULL, 0);     /* notify EOD */
582 #endif
583     return EOD;
584     }
585
586   smtp_printf("250 %u byte chunk received\r\n", FALSE, chunking_datasize);
587   chunking_state = CHUNKING_OFFERED;
588   DEBUG(D_receive) debug_printf("chunking state %d\n", (int)chunking_state);
589
590   /* Expect another BDAT cmd from input. RFC 3030 says nothing about
591   QUIT, RSET or NOOP but handling them seems obvious */
592
593 next_cmd:
594   switch(smtp_read_command(TRUE, 1))
595     {
596     default:
597       (void) synprot_error(L_smtp_protocol_error, 503, NULL,
598         US"only BDAT permissible after non-LAST BDAT");
599
600   repeat_until_rset:
601       switch(smtp_read_command(TRUE, 1))
602         {
603         case QUIT_CMD:  smtp_quit_handler(&user_msg, &log_msg); /*FALLTHROUGH */
604         case EOF_CMD:   return EOF;
605         case RSET_CMD:  smtp_rset_handler(); return ERR;
606         default:        if (synprot_error(L_smtp_protocol_error, 503, NULL,
607                                           US"only RSET accepted now") > 0)
608                           return EOF;
609                         goto repeat_until_rset;
610         }
611
612     case QUIT_CMD:
613       smtp_quit_handler(&user_msg, &log_msg);
614       /*FALLTHROUGH*/
615     case EOF_CMD:
616       return EOF;
617
618     case RSET_CMD:
619       smtp_rset_handler();
620       return ERR;
621
622     case NOOP_CMD:
623       HAD(SCH_NOOP);
624       smtp_printf("250 OK\r\n", FALSE);
625       goto next_cmd;
626
627     case BDAT_CMD:
628       {
629       int n;
630
631       if (sscanf(CS smtp_cmd_data, "%u %n", &chunking_datasize, &n) < 1)
632         {
633         (void) synprot_error(L_smtp_protocol_error, 501, NULL,
634           US"missing size for BDAT command");
635         return ERR;
636         }
637       chunking_state = strcmpic(smtp_cmd_data+n, US"LAST") == 0
638         ? CHUNKING_LAST : CHUNKING_ACTIVE;
639       chunking_data_left = chunking_datasize;
640       DEBUG(D_receive) debug_printf("chunking state %d, %d bytes\n",
641                                     (int)chunking_state, chunking_data_left);
642
643       if (chunking_datasize == 0)
644         if (chunking_state == CHUNKING_LAST)
645           return EOD;
646         else
647           {
648           (void) synprot_error(L_smtp_protocol_error, 504, NULL,
649             US"zero size for BDAT command");
650           goto repeat_until_rset;
651           }
652
653       receive_getc = bdat_getc;
654       receive_getbuf = bdat_getbuf;     /* r~getbuf is never actually used */
655       receive_ungetc = bdat_ungetc;
656 #ifndef DISABLE_DKIM
657       dkim_collect_input = dkim_save;
658 #endif
659       break;    /* to top of main loop */
660       }
661     }
662   }
663 }
664
665 uschar *
666 bdat_getbuf(unsigned * len)
667 {
668 uschar * buf;
669
670 if (chunking_data_left <= 0)
671   { *len = 0; return NULL; }
672
673 if (*len > chunking_data_left) *len = chunking_data_left;
674 buf = lwr_receive_getbuf(len);  /* Either smtp_getbuf or tls_getbuf */
675 chunking_data_left -= *len;
676 return buf;
677 }
678
679 void
680 bdat_flush_data(void)
681 {
682 while (chunking_data_left)
683   {
684   unsigned n = chunking_data_left;
685   if (!bdat_getbuf(&n)) break;
686   }
687
688 receive_getc = lwr_receive_getc;
689 receive_getbuf = lwr_receive_getbuf;
690 receive_ungetc = lwr_receive_ungetc;
691
692 if (chunking_state != CHUNKING_LAST)
693   {
694   chunking_state = CHUNKING_OFFERED;
695   DEBUG(D_receive) debug_printf("chunking state %d\n", (int)chunking_state);
696   }
697 }
698
699
700
701
702 /*************************************************
703 *          SMTP version of ungetc()              *
704 *************************************************/
705
706 /* Puts a character back in the input buffer. Only ever
707 called once.
708
709 Arguments:
710   ch           the character
711
712 Returns:       the character
713 */
714
715 int
716 smtp_ungetc(int ch)
717 {
718 *--smtp_inptr = ch;
719 return ch;
720 }
721
722
723 int
724 bdat_ungetc(int ch)
725 {
726 chunking_data_left++;
727 return lwr_receive_ungetc(ch);
728 }
729
730
731
732 /*************************************************
733 *          SMTP version of feof()                *
734 *************************************************/
735
736 /* Tests for a previous EOF
737
738 Arguments:     none
739 Returns:       non-zero if the eof flag is set
740 */
741
742 int
743 smtp_feof(void)
744 {
745 return smtp_had_eof;
746 }
747
748
749
750
751 /*************************************************
752 *          SMTP version of ferror()              *
753 *************************************************/
754
755 /* Tests for a previous read error, and returns with errno
756 restored to what it was when the error was detected.
757
758 Arguments:     none
759 Returns:       non-zero if the error flag is set
760 */
761
762 int
763 smtp_ferror(void)
764 {
765 errno = smtp_had_error;
766 return smtp_had_error;
767 }
768
769
770
771 /*************************************************
772 *      Test for characters in the SMTP buffer    *
773 *************************************************/
774
775 /* Used at the end of a message
776
777 Arguments:     none
778 Returns:       TRUE/FALSE
779 */
780
781 BOOL
782 smtp_buffered(void)
783 {
784 return smtp_inptr < smtp_inend;
785 }
786
787
788
789 /*************************************************
790 *     Write formatted string to SMTP channel     *
791 *************************************************/
792
793 /* This is a separate function so that we don't have to repeat everything for
794 TLS support or debugging. It is global so that the daemon and the
795 authentication functions can use it. It does not return any error indication,
796 because major problems such as dropped connections won't show up till an output
797 flush for non-TLS connections. The smtp_fflush() function is available for
798 checking that: for convenience, TLS output errors are remembered here so that
799 they are also picked up later by smtp_fflush().
800
801 Arguments:
802   format      format string
803   more        further data expected
804   ...         optional arguments
805
806 Returns:      nothing
807 */
808
809 void
810 smtp_printf(const char *format, BOOL more, ...)
811 {
812 va_list ap;
813
814 va_start(ap, more);
815 smtp_vprintf(format, more, ap);
816 va_end(ap);
817 }
818
819 /* This is split off so that verify.c:respond_printf() can, in effect, call
820 smtp_printf(), bearing in mind that in C a vararg function can't directly
821 call another vararg function, only a function which accepts a va_list. */
822
823 void
824 smtp_vprintf(const char *format, BOOL more, va_list ap)
825 {
826 BOOL yield;
827
828 yield = string_vformat(big_buffer, big_buffer_size, format, ap);
829
830 DEBUG(D_receive)
831   {
832   void *reset_point = store_get(0);
833   uschar *msg_copy, *cr, *end;
834   msg_copy = string_copy(big_buffer);
835   end = msg_copy + Ustrlen(msg_copy);
836   while ((cr = Ustrchr(msg_copy, '\r')) != NULL)   /* lose CRs */
837   memmove(cr, cr + 1, (end--) - cr);
838   debug_printf("SMTP>> %s", msg_copy);
839   store_reset(reset_point);
840   }
841
842 if (!yield)
843   {
844   log_write(0, LOG_MAIN|LOG_PANIC, "string too large in smtp_printf()");
845   smtp_closedown(US"Unexpected error");
846   exim_exit(EXIT_FAILURE, NULL);
847   }
848
849 /* If this is the first output for a (non-batch) RCPT command, see if all RCPTs
850 have had the same. Note: this code is also present in smtp_respond(). It would
851 be tidier to have it only in one place, but when it was added, it was easier to
852 do it that way, so as not to have to mess with the code for the RCPT command,
853 which sometimes uses smtp_printf() and sometimes smtp_respond(). */
854
855 if (rcpt_in_progress)
856   {
857   if (rcpt_smtp_response == NULL)
858     rcpt_smtp_response = string_copy(big_buffer);
859   else if (rcpt_smtp_response_same &&
860            Ustrcmp(rcpt_smtp_response, big_buffer) != 0)
861     rcpt_smtp_response_same = FALSE;
862   rcpt_in_progress = FALSE;
863   }
864
865 /* Now write the string */
866
867 #ifdef SUPPORT_TLS
868 if (tls_in.active >= 0)
869   {
870   if (tls_write(TRUE, big_buffer, Ustrlen(big_buffer), more) < 0)
871     smtp_write_error = -1;
872   }
873 else
874 #endif
875
876 if (fprintf(smtp_out, "%s", big_buffer) < 0) smtp_write_error = -1;
877 }
878
879
880
881 /*************************************************
882 *        Flush SMTP out and check for error      *
883 *************************************************/
884
885 /* This function isn't currently used within Exim (it detects errors when it
886 tries to read the next SMTP input), but is available for use in local_scan().
887 For non-TLS connections, it flushes the output and checks for errors. For
888 TLS-connections, it checks for a previously-detected TLS write error.
889
890 Arguments:  none
891 Returns:    0 for no error; -1 after an error
892 */
893
894 int
895 smtp_fflush(void)
896 {
897 if (tls_in.active < 0 && fflush(smtp_out) != 0) smtp_write_error = -1;
898 return smtp_write_error;
899 }
900
901
902
903 /*************************************************
904 *          SMTP command read timeout             *
905 *************************************************/
906
907 /* Signal handler for timing out incoming SMTP commands. This attempts to
908 finish off tidily.
909
910 Argument: signal number (SIGALRM)
911 Returns:  nothing
912 */
913
914 static void
915 command_timeout_handler(int sig)
916 {
917 sig = sig;    /* Keep picky compilers happy */
918 log_write(L_lost_incoming_connection,
919           LOG_MAIN, "SMTP command timeout on%s connection from %s",
920           (tls_in.active >= 0)? " TLS" : "",
921           host_and_ident(FALSE));
922 if (smtp_batched_input)
923   moan_smtp_batch(NULL, "421 SMTP command timeout");  /* Does not return */
924 smtp_notquit_exit(US"command-timeout", US"421",
925   US"%s: SMTP command timeout - closing connection", smtp_active_hostname);
926 exim_exit(EXIT_FAILURE, US"receiving");
927 }
928
929
930
931 /*************************************************
932 *               SIGTERM received                 *
933 *************************************************/
934
935 /* Signal handler for handling SIGTERM. Again, try to finish tidily.
936
937 Argument: signal number (SIGTERM)
938 Returns:  nothing
939 */
940
941 static void
942 command_sigterm_handler(int sig)
943 {
944 sig = sig;    /* Keep picky compilers happy */
945 log_write(0, LOG_MAIN, "%s closed after SIGTERM", smtp_get_connection_info());
946 if (smtp_batched_input)
947   moan_smtp_batch(NULL, "421 SIGTERM received");  /* Does not return */
948 smtp_notquit_exit(US"signal-exit", US"421",
949   US"%s: Service not available - closing connection", smtp_active_hostname);
950 exim_exit(EXIT_FAILURE, US"receiving");
951 }
952
953
954
955
956 #ifdef SUPPORT_PROXY
957 /*************************************************
958 *     Restore socket timeout to previous value   *
959 *************************************************/
960 /* If the previous value was successfully retrieved, restore
961 it before returning control to the non-proxy routines
962
963 Arguments: fd     - File descriptor for input
964            get_ok - Successfully retrieved previous values
965            tvtmp  - Time struct with previous values
966            vslen  - Length of time struct
967 Returns:   none
968 */
969 static void
970 restore_socket_timeout(int fd, int get_ok, struct timeval * tvtmp, socklen_t vslen)
971 {
972 if (get_ok == 0)
973   (void) setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, CS tvtmp, vslen);
974 }
975
976 /*************************************************
977 *       Check if host is required proxy host     *
978 *************************************************/
979 /* The function determines if inbound host will be a regular smtp host
980 or if it is configured that it must use Proxy Protocol.  A local
981 connection cannot.
982
983 Arguments: none
984 Returns:   bool
985 */
986
987 static BOOL
988 check_proxy_protocol_host()
989 {
990 int rc;
991
992 if (  sender_host_address
993    && (rc = verify_check_this_host(CUSS &hosts_proxy, NULL, NULL,
994                            sender_host_address, NULL)) == OK)
995   {
996   DEBUG(D_receive)
997     debug_printf("Detected proxy protocol configured host\n");
998   proxy_session = TRUE;
999   }
1000 return proxy_session;
1001 }
1002
1003
1004 /*************************************************
1005 *    Read data until newline or end of buffer    *
1006 *************************************************/
1007 /* While SMTP is server-speaks-first, TLS is client-speaks-first, so we can't
1008 read an entire buffer and assume there will be nothing past a proxy protocol
1009 header.  Our approach normally is to use stdio, but again that relies upon
1010 "STARTTLS\r\n" and a server response before the client starts TLS handshake, or
1011 reading _nothing_ before client TLS handshake.  So we don't want to use the
1012 usual buffering reads which may read enough to block TLS starting.
1013
1014 So unfortunately we're down to "read one byte at a time, with a syscall each,
1015 and expect a little overhead", for all proxy-opened connections which are v1,
1016 just to handle the TLS-on-connect case.  Since SSL functions wrap the
1017 underlying fd, we can't assume that we can feed them any already-read content.
1018
1019 We need to know where to read to, the max capacity, and we'll read until we
1020 get a CR and one more character.  Let the caller scream if it's CR+!LF.
1021
1022 Return the amount read.
1023 */
1024
1025 static int
1026 swallow_until_crlf(int fd, uschar *base, int already, int capacity)
1027 {
1028 uschar *to = base + already;
1029 uschar *cr;
1030 int have = 0;
1031 int ret;
1032 int last = 0;
1033
1034 /* For "PROXY UNKNOWN\r\n" we, at time of writing, expect to have read
1035 up through the \r; for the _normal_ case, we haven't yet seen the \r. */
1036
1037 cr = memchr(base, '\r', already);
1038 if (cr != NULL)
1039   {
1040   if ((cr - base) < already - 1)
1041     {
1042     /* \r and presumed \n already within what we have; probably not
1043     actually proxy protocol, but abort cleanly. */
1044     return 0;
1045     }
1046   /* \r is last character read, just need one more. */
1047   last = 1;
1048   }
1049
1050 while (capacity > 0)
1051   {
1052   do { ret = recv(fd, to, 1, 0); } while (ret == -1 && errno == EINTR);
1053   if (ret == -1)
1054     return -1;
1055   have++;
1056   if (last)
1057     return have;
1058   if (*to == '\r')
1059     last = 1;
1060   capacity--;
1061   to++;
1062   }
1063
1064 /* reached end without having room for a final newline, abort */
1065 errno = EOVERFLOW;
1066 return -1;
1067 }
1068
1069 /*************************************************
1070 *         Setup host for proxy protocol          *
1071 *************************************************/
1072 /* The function configures the connection based on a header from the
1073 inbound host to use Proxy Protocol. The specification is very exact
1074 so exit with an error if do not find the exact required pieces. This
1075 includes an incorrect number of spaces separating args.
1076
1077 Arguments: none
1078 Returns:   Boolean success
1079 */
1080
1081 static void
1082 setup_proxy_protocol_host()
1083 {
1084 union {
1085   struct {
1086     uschar line[108];
1087   } v1;
1088   struct {
1089     uschar sig[12];
1090     uint8_t ver_cmd;
1091     uint8_t fam;
1092     uint16_t len;
1093     union {
1094       struct { /* TCP/UDP over IPv4, len = 12 */
1095         uint32_t src_addr;
1096         uint32_t dst_addr;
1097         uint16_t src_port;
1098         uint16_t dst_port;
1099       } ip4;
1100       struct { /* TCP/UDP over IPv6, len = 36 */
1101         uint8_t  src_addr[16];
1102         uint8_t  dst_addr[16];
1103         uint16_t src_port;
1104         uint16_t dst_port;
1105       } ip6;
1106       struct { /* AF_UNIX sockets, len = 216 */
1107         uschar   src_addr[108];
1108         uschar   dst_addr[108];
1109       } unx;
1110     } addr;
1111   } v2;
1112 } hdr;
1113
1114 /* Temp variables used in PPv2 address:port parsing */
1115 uint16_t tmpport;
1116 char tmpip[INET_ADDRSTRLEN];
1117 struct sockaddr_in tmpaddr;
1118 char tmpip6[INET6_ADDRSTRLEN];
1119 struct sockaddr_in6 tmpaddr6;
1120
1121 /* We can't read "all data until end" because while SMTP is
1122 server-speaks-first, the TLS handshake is client-speaks-first, so for
1123 TLS-on-connect ports the proxy protocol header will usually be immediately
1124 followed by a TLS handshake, and with N TLS libraries, we can't reliably
1125 reinject data for reading by those.  So instead we first read "enough to be
1126 safely read within the header, and figure out how much more to read".
1127 For v1 we will later read to the end-of-line, for v2 we will read based upon
1128 the stated length.
1129
1130 The v2 sig is 12 octets, and another 4 gets us the length, so we know how much
1131 data is needed total.  For v1, where the line looks like:
1132 PROXY TCPn L3src L3dest SrcPort DestPort \r\n
1133
1134 However, for v1 there's also `PROXY UNKNOWN\r\n` which is only 15 octets.
1135 We seem to support that.  So, if we read 14 octets then we can tell if we're
1136 v2 or v1.  If we're v1, we can continue reading as normal.
1137
1138 If we're v2, we can't slurp up the entire header.  We need the length in the
1139 15th & 16th octets, then to read everything after that.
1140
1141 So to safely handle v1 and v2, with client-sent-first supported correctly,
1142 we have to do a minimum of 3 read calls, not 1.  Eww.
1143 */
1144
1145 #define PROXY_INITIAL_READ 14
1146 #define PROXY_V2_HEADER_SIZE 16
1147 #if PROXY_INITIAL_READ > PROXY_V2_HEADER_SIZE
1148 # error Code bug in sizes of data to read for proxy usage
1149 #endif
1150
1151 int get_ok = 0;
1152 int size, ret;
1153 int fd = fileno(smtp_in);
1154 const char v2sig[12] = "\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A";
1155 uschar * iptype;  /* To display debug info */
1156 struct timeval tv;
1157 struct timeval tvtmp;
1158 socklen_t vslen = sizeof(struct timeval);
1159 BOOL yield = FALSE;
1160
1161 /* Save current socket timeout values */
1162 get_ok = getsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, CS &tvtmp, &vslen);
1163
1164 /* Proxy Protocol host must send header within a short time
1165 (default 3 seconds) or it's considered invalid */
1166 tv.tv_sec  = PROXY_NEGOTIATION_TIMEOUT_SEC;
1167 tv.tv_usec = PROXY_NEGOTIATION_TIMEOUT_USEC;
1168 if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, CS &tv, sizeof(tv)) < 0)
1169   goto bad;
1170
1171 do
1172   {
1173   /* The inbound host was declared to be a Proxy Protocol host, so
1174   don't do a PEEK into the data, actually slurp up enough to be
1175   "safe". Can't take it all because TLS-on-connect clients follow
1176   immediately with TLS handshake. */
1177   ret = recv(fd, &hdr, PROXY_INITIAL_READ, 0);
1178   }
1179   while (ret == -1 && errno == EINTR);
1180
1181 if (ret == -1)
1182   goto proxyfail;
1183
1184 /* For v2, handle reading the length, and then the rest. */
1185 if ((ret == PROXY_INITIAL_READ) && (memcmp(&hdr.v2, v2sig, sizeof(v2sig)) == 0))
1186   {
1187   int retmore;
1188   uint8_t ver;
1189
1190   /* First get the length fields. */
1191   do
1192     {
1193     retmore = recv(fd, (uschar*)&hdr + ret, PROXY_V2_HEADER_SIZE - PROXY_INITIAL_READ, 0);
1194     } while (retmore == -1 && errno == EINTR);
1195   if (retmore == -1)
1196     goto proxyfail;
1197   ret += retmore;
1198
1199   ver = (hdr.v2.ver_cmd & 0xf0) >> 4;
1200
1201   /* May 2014: haproxy combined the version and command into one byte to
1202   allow two full bytes for the length field in order to proxy SSL
1203   connections.  SSL Proxy is not supported in this version of Exim, but
1204   must still separate values here. */
1205
1206   if (ver != 0x02)
1207     {
1208     DEBUG(D_receive) debug_printf("Invalid Proxy Protocol version: %d\n", ver);
1209     goto proxyfail;
1210     }
1211
1212   /* The v2 header will always be 16 bytes per the spec. */
1213   size = 16 + ntohs(hdr.v2.len);
1214   DEBUG(D_receive) debug_printf("Detected PROXYv2 header, size %d (limit %d)\n",
1215       size, (int)sizeof(hdr));
1216
1217   /* We should now have 16 octets (PROXY_V2_HEADER_SIZE), and we know the total
1218   amount that we need.  Double-check that the size is not unreasonable, then
1219   get the rest. */
1220   if (size > sizeof(hdr))
1221     {
1222     DEBUG(D_receive) debug_printf("PROXYv2 header size unreasonably large; security attack?\n");
1223     goto proxyfail;
1224     }
1225
1226   do
1227     {
1228     do
1229       {
1230       retmore = recv(fd, (uschar*)&hdr + ret, size-ret, 0);
1231       } while (retmore == -1 && errno == EINTR);
1232     if (retmore == -1)
1233       goto proxyfail;
1234     ret += retmore;
1235     DEBUG(D_receive) debug_printf("PROXYv2: have %d/%d required octets\n", ret, size);
1236     } while (ret < size);
1237
1238   } /* end scope for getting rest of data for v2 */
1239
1240 /* At this point: if PROXYv2, we've read the exact size required for all data;
1241 if PROXYv1 then we've read "less than required for any valid line" and should
1242 read the rest". */
1243
1244 if (ret >= 16 && memcmp(&hdr.v2, v2sig, 12) == 0)
1245   {
1246   uint8_t cmd = (hdr.v2.ver_cmd & 0x0f);
1247
1248   switch (cmd)
1249     {
1250     case 0x01: /* PROXY command */
1251       switch (hdr.v2.fam)
1252         {
1253         case 0x11:  /* TCPv4 address type */
1254           iptype = US"IPv4";
1255           tmpaddr.sin_addr.s_addr = hdr.v2.addr.ip4.src_addr;
1256           inet_ntop(AF_INET, &tmpaddr.sin_addr, CS &tmpip, sizeof(tmpip));
1257           if (!string_is_ip_address(US tmpip, NULL))
1258             {
1259             DEBUG(D_receive) debug_printf("Invalid %s source IP\n", iptype);
1260             goto proxyfail;
1261             }
1262           proxy_local_address = sender_host_address;
1263           sender_host_address = string_copy(US tmpip);
1264           tmpport             = ntohs(hdr.v2.addr.ip4.src_port);
1265           proxy_local_port    = sender_host_port;
1266           sender_host_port    = tmpport;
1267           /* Save dest ip/port */
1268           tmpaddr.sin_addr.s_addr = hdr.v2.addr.ip4.dst_addr;
1269           inet_ntop(AF_INET, &tmpaddr.sin_addr, CS &tmpip, sizeof(tmpip));
1270           if (!string_is_ip_address(US tmpip, NULL))
1271             {
1272             DEBUG(D_receive) debug_printf("Invalid %s dest port\n", iptype);
1273             goto proxyfail;
1274             }
1275           proxy_external_address = string_copy(US tmpip);
1276           tmpport              = ntohs(hdr.v2.addr.ip4.dst_port);
1277           proxy_external_port  = tmpport;
1278           goto done;
1279         case 0x21:  /* TCPv6 address type */
1280           iptype = US"IPv6";
1281           memmove(tmpaddr6.sin6_addr.s6_addr, hdr.v2.addr.ip6.src_addr, 16);
1282           inet_ntop(AF_INET6, &tmpaddr6.sin6_addr, CS &tmpip6, sizeof(tmpip6));
1283           if (!string_is_ip_address(US tmpip6, NULL))
1284             {
1285             DEBUG(D_receive) debug_printf("Invalid %s source IP\n", iptype);
1286             goto proxyfail;
1287             }
1288           proxy_local_address = sender_host_address;
1289           sender_host_address = string_copy(US tmpip6);
1290           tmpport             = ntohs(hdr.v2.addr.ip6.src_port);
1291           proxy_local_port    = sender_host_port;
1292           sender_host_port    = tmpport;
1293           /* Save dest ip/port */
1294           memmove(tmpaddr6.sin6_addr.s6_addr, hdr.v2.addr.ip6.dst_addr, 16);
1295           inet_ntop(AF_INET6, &tmpaddr6.sin6_addr, CS &tmpip6, sizeof(tmpip6));
1296           if (!string_is_ip_address(US tmpip6, NULL))
1297             {
1298             DEBUG(D_receive) debug_printf("Invalid %s dest port\n", iptype);
1299             goto proxyfail;
1300             }
1301           proxy_external_address = string_copy(US tmpip6);
1302           tmpport              = ntohs(hdr.v2.addr.ip6.dst_port);
1303           proxy_external_port  = tmpport;
1304           goto done;
1305         default:
1306           DEBUG(D_receive)
1307             debug_printf("Unsupported PROXYv2 connection type: 0x%02x\n",
1308                          hdr.v2.fam);
1309           goto proxyfail;
1310         }
1311       /* Unsupported protocol, keep local connection address */
1312       break;
1313     case 0x00: /* LOCAL command */
1314       /* Keep local connection address for LOCAL */
1315       iptype = US"local";
1316       break;
1317     default:
1318       DEBUG(D_receive)
1319         debug_printf("Unsupported PROXYv2 command: 0x%x\n", cmd);
1320       goto proxyfail;
1321     }
1322   }
1323 else if (ret >= 8 && memcmp(hdr.v1.line, "PROXY", 5) == 0)
1324   {
1325   uschar *p;
1326   uschar *end;
1327   uschar *sp;     /* Utility variables follow */
1328   int     tmp_port;
1329   int     r2;
1330   char   *endc;
1331
1332   /* get the rest of the line */
1333   r2 = swallow_until_crlf(fd, (uschar*)&hdr, ret, sizeof(hdr)-ret);
1334   if (r2 == -1)
1335     goto proxyfail;
1336   ret += r2;
1337
1338   p = string_copy(hdr.v1.line);
1339   end = memchr(p, '\r', ret - 1);
1340
1341   if (!end || (end == (uschar*)&hdr + ret) || end[1] != '\n')
1342     {
1343     DEBUG(D_receive) debug_printf("Partial or invalid PROXY header\n");
1344     goto proxyfail;
1345     }
1346   *end = '\0'; /* Terminate the string */
1347   size = end + 2 - p; /* Skip header + CRLF */
1348   DEBUG(D_receive) debug_printf("Detected PROXYv1 header\n");
1349   DEBUG(D_receive) debug_printf("Bytes read not within PROXY header: %d\n", ret - size);
1350   /* Step through the string looking for the required fields. Ensure
1351   strict adherence to required formatting, exit for any error. */
1352   p += 5;
1353   if (!isspace(*(p++)))
1354     {
1355     DEBUG(D_receive) debug_printf("Missing space after PROXY command\n");
1356     goto proxyfail;
1357     }
1358   if (!Ustrncmp(p, CCS"TCP4", 4))
1359     iptype = US"IPv4";
1360   else if (!Ustrncmp(p,CCS"TCP6", 4))
1361     iptype = US"IPv6";
1362   else if (!Ustrncmp(p,CCS"UNKNOWN", 7))
1363     {
1364     iptype = US"Unknown";
1365     goto done;
1366     }
1367   else
1368     {
1369     DEBUG(D_receive) debug_printf("Invalid TCP type\n");
1370     goto proxyfail;
1371     }
1372
1373   p += Ustrlen(iptype);
1374   if (!isspace(*(p++)))
1375     {
1376     DEBUG(D_receive) debug_printf("Missing space after TCP4/6 command\n");
1377     goto proxyfail;
1378     }
1379   /* Find the end of the arg */
1380   if ((sp = Ustrchr(p, ' ')) == NULL)
1381     {
1382     DEBUG(D_receive)
1383       debug_printf("Did not find proxied src %s\n", iptype);
1384     goto proxyfail;
1385     }
1386   *sp = '\0';
1387   if(!string_is_ip_address(p, NULL))
1388     {
1389     DEBUG(D_receive)
1390       debug_printf("Proxied src arg is not an %s address\n", iptype);
1391     goto proxyfail;
1392     }
1393   proxy_local_address = sender_host_address;
1394   sender_host_address = p;
1395   p = sp + 1;
1396   if ((sp = Ustrchr(p, ' ')) == NULL)
1397     {
1398     DEBUG(D_receive)
1399       debug_printf("Did not find proxy dest %s\n", iptype);
1400     goto proxyfail;
1401     }
1402   *sp = '\0';
1403   if(!string_is_ip_address(p, NULL))
1404     {
1405     DEBUG(D_receive)
1406       debug_printf("Proxy dest arg is not an %s address\n", iptype);
1407     goto proxyfail;
1408     }
1409   proxy_external_address = p;
1410   p = sp + 1;
1411   if ((sp = Ustrchr(p, ' ')) == NULL)
1412     {
1413     DEBUG(D_receive) debug_printf("Did not find proxied src port\n");
1414     goto proxyfail;
1415     }
1416   *sp = '\0';
1417   tmp_port = strtol(CCS p, &endc, 10);
1418   if (*endc || tmp_port == 0)
1419     {
1420     DEBUG(D_receive)
1421       debug_printf("Proxied src port '%s' not an integer\n", p);
1422     goto proxyfail;
1423     }
1424   proxy_local_port = sender_host_port;
1425   sender_host_port = tmp_port;
1426   p = sp + 1;
1427   if ((sp = Ustrchr(p, '\0')) == NULL)
1428     {
1429     DEBUG(D_receive) debug_printf("Did not find proxy dest port\n");
1430     goto proxyfail;
1431     }
1432   tmp_port = strtol(CCS p, &endc, 10);
1433   if (*endc || tmp_port == 0)
1434     {
1435     DEBUG(D_receive)
1436       debug_printf("Proxy dest port '%s' not an integer\n", p);
1437     goto proxyfail;
1438     }
1439   proxy_external_port = tmp_port;
1440   /* Already checked for /r /n above. Good V1 header received. */
1441   }
1442 else
1443   {
1444   /* Wrong protocol */
1445   DEBUG(D_receive) debug_printf("Invalid proxy protocol version negotiation\n");
1446   (void) swallow_until_crlf(fd, (uschar*)&hdr, ret, sizeof(hdr)-ret);
1447   goto proxyfail;
1448   }
1449
1450 done:
1451   DEBUG(D_receive)
1452     debug_printf("Valid %s sender from Proxy Protocol header\n", iptype);
1453   yield = proxy_session;
1454
1455 /* Don't flush any potential buffer contents. Any input on proxyfail
1456 should cause a synchronization failure */
1457
1458 proxyfail:
1459   restore_socket_timeout(fd, get_ok, &tvtmp, vslen);
1460
1461 bad:
1462   if (yield)
1463     {
1464     sender_host_name = NULL;
1465     (void) host_name_lookup();
1466     host_build_sender_fullhost();
1467     }
1468   else
1469     {
1470     proxy_session_failed = TRUE;
1471     DEBUG(D_receive)
1472       debug_printf("Failure to extract proxied host, only QUIT allowed\n");
1473     }
1474
1475 return;
1476 }
1477 #endif
1478
1479 /*************************************************
1480 *           Read one command line                *
1481 *************************************************/
1482
1483 /* Strictly, SMTP commands coming over the net are supposed to end with CRLF.
1484 There are sites that don't do this, and in any case internal SMTP probably
1485 should check only for LF. Consequently, we check here for LF only. The line
1486 ends up with [CR]LF removed from its end. If we get an overlong line, treat as
1487 an unknown command. The command is read into the global smtp_cmd_buffer so that
1488 it is available via $smtp_command.
1489
1490 The character reading routine sets up a timeout for each block actually read
1491 from the input (which may contain more than one command). We set up a special
1492 signal handler that closes down the session on a timeout. Control does not
1493 return when it runs.
1494
1495 Arguments:
1496   check_sync    if TRUE, check synchronization rules if global option is TRUE
1497   buffer_lim    maximum to buffer in lower layer
1498
1499 Returns:       a code identifying the command (enumerated above)
1500 */
1501
1502 static int
1503 smtp_read_command(BOOL check_sync, unsigned buffer_lim)
1504 {
1505 int c;
1506 int ptr = 0;
1507 smtp_cmd_list *p;
1508 BOOL hadnull = FALSE;
1509
1510 os_non_restarting_signal(SIGALRM, command_timeout_handler);
1511
1512 while ((c = (receive_getc)(buffer_lim)) != '\n' && c != EOF)
1513   {
1514   if (ptr >= SMTP_CMD_BUFFER_SIZE)
1515     {
1516     os_non_restarting_signal(SIGALRM, sigalrm_handler);
1517     return OTHER_CMD;
1518     }
1519   if (c == 0)
1520     {
1521     hadnull = TRUE;
1522     c = '?';
1523     }
1524   smtp_cmd_buffer[ptr++] = c;
1525   }
1526
1527 receive_linecount++;    /* For BSMTP errors */
1528 os_non_restarting_signal(SIGALRM, sigalrm_handler);
1529
1530 /* If hit end of file, return pseudo EOF command. Whether we have a
1531 part-line already read doesn't matter, since this is an error state. */
1532
1533 if (c == EOF) return EOF_CMD;
1534
1535 /* Remove any CR and white space at the end of the line, and terminate the
1536 string. */
1537
1538 while (ptr > 0 && isspace(smtp_cmd_buffer[ptr-1])) ptr--;
1539 smtp_cmd_buffer[ptr] = 0;
1540
1541 DEBUG(D_receive) debug_printf("SMTP<< %s\n", smtp_cmd_buffer);
1542
1543 /* NULLs are not allowed in SMTP commands */
1544
1545 if (hadnull) return BADCHAR_CMD;
1546
1547 /* Scan command list and return identity, having set the data pointer
1548 to the start of the actual data characters. Check for SMTP synchronization
1549 if required. */
1550
1551 for (p = cmd_list; p < cmd_list_end; p++)
1552   {
1553 #ifdef SUPPORT_PROXY
1554   /* Only allow QUIT command if Proxy Protocol parsing failed */
1555   if (proxy_session && proxy_session_failed && p->cmd != QUIT_CMD)
1556     continue;
1557 #endif
1558   if (  p->len
1559      && strncmpic(smtp_cmd_buffer, US p->name, p->len) == 0
1560      && (  smtp_cmd_buffer[p->len-1] == ':'    /* "mail from:" or "rcpt to:" */
1561         || smtp_cmd_buffer[p->len] == 0
1562         || smtp_cmd_buffer[p->len] == ' '
1563      )  )
1564     {
1565     if (smtp_inptr < smtp_inend &&                     /* Outstanding input */
1566         p->cmd < sync_cmd_limit &&                     /* Command should sync */
1567         check_sync &&                                  /* Local flag set */
1568         smtp_enforce_sync &&                           /* Global flag set */
1569         sender_host_address != NULL &&                 /* Not local input */
1570         !sender_host_notsocket)                        /* Really is a socket */
1571       return BADSYN_CMD;
1572
1573     /* The variables $smtp_command and $smtp_command_argument point into the
1574     unmodified input buffer. A copy of the latter is taken for actual
1575     processing, so that it can be chopped up into separate parts if necessary,
1576     for example, when processing a MAIL command options such as SIZE that can
1577     follow the sender address. */
1578
1579     smtp_cmd_argument = smtp_cmd_buffer + p->len;
1580     while (isspace(*smtp_cmd_argument)) smtp_cmd_argument++;
1581     Ustrcpy(smtp_data_buffer, smtp_cmd_argument);
1582     smtp_cmd_data = smtp_data_buffer;
1583
1584     /* Count non-mail commands from those hosts that are controlled in this
1585     way. The default is all hosts. We don't waste effort checking the list
1586     until we get a non-mail command, but then cache the result to save checking
1587     again. If there's a DEFER while checking the host, assume it's in the list.
1588
1589     Note that one instance of RSET, EHLO/HELO, and STARTTLS is allowed at the
1590     start of each incoming message by fiddling with the value in the table. */
1591
1592     if (!p->is_mail_cmd)
1593       {
1594       if (count_nonmail == TRUE_UNSET) count_nonmail =
1595         verify_check_host(&smtp_accept_max_nonmail_hosts) != FAIL;
1596       if (count_nonmail && ++nonmail_command_count > smtp_accept_max_nonmail)
1597         return TOO_MANY_NONMAIL_CMD;
1598       }
1599
1600     /* If there is data for a command that does not expect it, generate the
1601     error here. */
1602
1603     return (p->has_arg || *smtp_cmd_data == 0)? p->cmd : BADARG_CMD;
1604     }
1605   }
1606
1607 #ifdef SUPPORT_PROXY
1608 /* Only allow QUIT command if Proxy Protocol parsing failed */
1609 if (proxy_session && proxy_session_failed)
1610   return PROXY_FAIL_IGNORE_CMD;
1611 #endif
1612
1613 /* Enforce synchronization for unknown commands */
1614
1615 if (  smtp_inptr < smtp_inend           /* Outstanding input */
1616    && check_sync                        /* Local flag set */
1617    && smtp_enforce_sync                 /* Global flag set */
1618    && sender_host_address               /* Not local input */
1619    && !sender_host_notsocket)           /* Really is a socket */
1620   return BADSYN_CMD;
1621
1622 return OTHER_CMD;
1623 }
1624
1625
1626
1627 /*************************************************
1628 *          Forced closedown of call              *
1629 *************************************************/
1630
1631 /* This function is called from log.c when Exim is dying because of a serious
1632 disaster, and also from some other places. If an incoming non-batched SMTP
1633 channel is open, it swallows the rest of the incoming message if in the DATA
1634 phase, sends the reply string, and gives an error to all subsequent commands
1635 except QUIT. The existence of an SMTP call is detected by the non-NULLness of
1636 smtp_in.
1637
1638 Arguments:
1639   message   SMTP reply string to send, excluding the code
1640
1641 Returns:    nothing
1642 */
1643
1644 void
1645 smtp_closedown(uschar *message)
1646 {
1647 if (!smtp_in || smtp_batched_input) return;
1648 receive_swallow_smtp();
1649 smtp_printf("421 %s\r\n", FALSE, message);
1650
1651 for (;;) switch(smtp_read_command(FALSE, GETC_BUFFER_UNLIMITED))
1652   {
1653   case EOF_CMD:
1654     return;
1655
1656   case QUIT_CMD:
1657     smtp_printf("221 %s closing connection\r\n", FALSE, smtp_active_hostname);
1658     mac_smtp_fflush();
1659     return;
1660
1661   case RSET_CMD:
1662     smtp_printf("250 Reset OK\r\n", FALSE);
1663     break;
1664
1665   default:
1666     smtp_printf("421 %s\r\n", FALSE, message);
1667     break;
1668   }
1669 }
1670
1671
1672
1673
1674 /*************************************************
1675 *        Set up connection info for logging      *
1676 *************************************************/
1677
1678 /* This function is called when logging information about an SMTP connection.
1679 It sets up appropriate source information, depending on the type of connection.
1680 If sender_fullhost is NULL, we are at a very early stage of the connection;
1681 just use the IP address.
1682
1683 Argument:    none
1684 Returns:     a string describing the connection
1685 */
1686
1687 uschar *
1688 smtp_get_connection_info(void)
1689 {
1690 const uschar * hostname = sender_fullhost
1691   ? sender_fullhost : sender_host_address;
1692
1693 if (host_checking)
1694   return string_sprintf("SMTP connection from %s", hostname);
1695
1696 if (sender_host_unknown || sender_host_notsocket)
1697   return string_sprintf("SMTP connection from %s", sender_ident);
1698
1699 if (is_inetd)
1700   return string_sprintf("SMTP connection from %s (via inetd)", hostname);
1701
1702 if (LOGGING(incoming_interface) && interface_address != NULL)
1703   return string_sprintf("SMTP connection from %s I=[%s]:%d", hostname,
1704     interface_address, interface_port);
1705
1706 return string_sprintf("SMTP connection from %s", hostname);
1707 }
1708
1709
1710
1711 #ifdef SUPPORT_TLS
1712 /* Append TLS-related information to a log line
1713
1714 Arguments:
1715   g             String under construction: allocated string to extend, or NULL
1716
1717 Returns:        Allocated string or NULL
1718 */
1719 static gstring *
1720 s_tlslog(gstring * g)
1721 {
1722 if (LOGGING(tls_cipher) && tls_in.cipher)
1723   g = string_append(g, 2, US" X=", tls_in.cipher);
1724 if (LOGGING(tls_certificate_verified) && tls_in.cipher)
1725   g = string_append(g, 2, US" CV=", tls_in.certificate_verified? "yes":"no");
1726 if (LOGGING(tls_peerdn) && tls_in.peerdn)
1727   g = string_append(g, 3, US" DN=\"", string_printing(tls_in.peerdn), US"\"");
1728 if (LOGGING(tls_sni) && tls_in.sni)
1729   g = string_append(g, 3, US" SNI=\"", string_printing(tls_in.sni), US"\"");
1730 return g;
1731 }
1732 #endif
1733
1734 /*************************************************
1735 *      Log lack of MAIL if so configured         *
1736 *************************************************/
1737
1738 /* This function is called when an SMTP session ends. If the log selector
1739 smtp_no_mail is set, write a log line giving some details of what has happened
1740 in the SMTP session.
1741
1742 Arguments:   none
1743 Returns:     nothing
1744 */
1745
1746 void
1747 smtp_log_no_mail(void)
1748 {
1749 int i;
1750 uschar * sep, * s;
1751 gstring * g = NULL;
1752
1753 if (smtp_mailcmd_count > 0 || !LOGGING(smtp_no_mail))
1754   return;
1755
1756 if (sender_host_authenticated)
1757   {
1758   g = string_append(g, 2, US" A=", sender_host_authenticated);
1759   if (authenticated_id) g = string_append(g, 2, US":", authenticated_id);
1760   }
1761
1762 #ifdef SUPPORT_TLS
1763 g = s_tlslog(g);
1764 #endif
1765
1766 sep = smtp_connection_had[SMTP_HBUFF_SIZE-1] != SCH_NONE ?  US" C=..." : US" C=";
1767
1768 for (i = smtp_ch_index; i < SMTP_HBUFF_SIZE; i++)
1769   if (smtp_connection_had[i] != SCH_NONE)
1770     {
1771     g = string_append(g, 2, sep, smtp_names[smtp_connection_had[i]]);
1772     sep = US",";
1773     }
1774
1775 for (i = 0; i < smtp_ch_index; i++)
1776   {
1777   g = string_append(g, 2, sep, smtp_names[smtp_connection_had[i]]);
1778   sep = US",";
1779   }
1780
1781 if (!(s = string_from_gstring(g))) s = US"";
1782
1783 log_write(0, LOG_MAIN, "no MAIL in %sSMTP connection from %s D=%s%s",
1784   tcp_in_fastopen ? US"TFO " : US"",
1785   host_and_ident(FALSE), string_timesince(&smtp_connection_start), s);
1786 }
1787
1788
1789 /* Return list of recent smtp commands */
1790
1791 uschar *
1792 smtp_cmd_hist(void)
1793 {
1794 int  i;
1795 gstring * list = NULL;
1796 uschar * s;
1797
1798 for (i = smtp_ch_index; i < SMTP_HBUFF_SIZE; i++)
1799   if (smtp_connection_had[i] != SCH_NONE)
1800     list = string_append_listele(list, ',', smtp_names[smtp_connection_had[i]]);
1801
1802 for (i = 0; i < smtp_ch_index; i++)
1803   list = string_append_listele(list, ',', smtp_names[smtp_connection_had[i]]);
1804
1805 s = string_from_gstring(list);
1806 return s ? s : US"";
1807 }
1808
1809
1810
1811
1812 /*************************************************
1813 *   Check HELO line and set sender_helo_name     *
1814 *************************************************/
1815
1816 /* Check the format of a HELO line. The data for HELO/EHLO is supposed to be
1817 the domain name of the sending host, or an ip literal in square brackets. The
1818 argument is placed in sender_helo_name, which is in malloc store, because it
1819 must persist over multiple incoming messages. If helo_accept_junk is set, this
1820 host is permitted to send any old junk (needed for some broken hosts).
1821 Otherwise, helo_allow_chars can be used for rogue characters in general
1822 (typically people want to let in underscores).
1823
1824 Argument:
1825   s       the data portion of the line (already past any white space)
1826
1827 Returns:  TRUE or FALSE
1828 */
1829
1830 static BOOL
1831 check_helo(uschar *s)
1832 {
1833 uschar *start = s;
1834 uschar *end = s + Ustrlen(s);
1835 BOOL yield = helo_accept_junk;
1836
1837 /* Discard any previous helo name */
1838
1839 if (sender_helo_name)
1840   {
1841   store_free(sender_helo_name);
1842   sender_helo_name = NULL;
1843   }
1844
1845 /* Skip tests if junk is permitted. */
1846
1847 if (!yield)
1848
1849   /* Allow the new standard form for IPv6 address literals, namely,
1850   [IPv6:....], and because someone is bound to use it, allow an equivalent
1851   IPv4 form. Allow plain addresses as well. */
1852
1853   if (*s == '[')
1854     {
1855     if (end[-1] == ']')
1856       {
1857       end[-1] = 0;
1858       if (strncmpic(s, US"[IPv6:", 6) == 0)
1859         yield = (string_is_ip_address(s+6, NULL) == 6);
1860       else if (strncmpic(s, US"[IPv4:", 6) == 0)
1861         yield = (string_is_ip_address(s+6, NULL) == 4);
1862       else
1863         yield = (string_is_ip_address(s+1, NULL) != 0);
1864       end[-1] = ']';
1865       }
1866     }
1867
1868   /* Non-literals must be alpha, dot, hyphen, plus any non-valid chars
1869   that have been configured (usually underscore - sigh). */
1870
1871   else if (*s)
1872     for (yield = TRUE; *s; s++)
1873       if (!isalnum(*s) && *s != '.' && *s != '-' &&
1874           Ustrchr(helo_allow_chars, *s) == NULL)
1875         {
1876         yield = FALSE;
1877         break;
1878         }
1879
1880 /* Save argument if OK */
1881
1882 if (yield) sender_helo_name = string_copy_malloc(start);
1883 return yield;
1884 }
1885
1886
1887
1888
1889
1890 /*************************************************
1891 *         Extract SMTP command option            *
1892 *************************************************/
1893
1894 /* This function picks the next option setting off the end of smtp_cmd_data. It
1895 is called for MAIL FROM and RCPT TO commands, to pick off the optional ESMTP
1896 things that can appear there.
1897
1898 Arguments:
1899    name           point this at the name
1900    value          point this at the data string
1901
1902 Returns:          TRUE if found an option
1903 */
1904
1905 static BOOL
1906 extract_option(uschar **name, uschar **value)
1907 {
1908 uschar *n;
1909 uschar *v = smtp_cmd_data + Ustrlen(smtp_cmd_data) - 1;
1910 while (isspace(*v)) v--;
1911 v[1] = 0;
1912 while (v > smtp_cmd_data && *v != '=' && !isspace(*v))
1913   {
1914   /* Take care to not stop at a space embedded in a quoted local-part */
1915
1916   if (*v == '"') do v--; while (*v != '"' && v > smtp_cmd_data+1);
1917   v--;
1918   }
1919
1920 n = v;
1921 if (*v == '=')
1922   {
1923   while(isalpha(n[-1])) n--;
1924   /* RFC says SP, but TAB seen in wild and other major MTAs accept it */
1925   if (!isspace(n[-1])) return FALSE;
1926   n[-1] = 0;
1927   }
1928 else
1929   {
1930   n++;
1931   if (v == smtp_cmd_data) return FALSE;
1932   }
1933 *v++ = 0;
1934 *name = n;
1935 *value = v;
1936 return TRUE;
1937 }
1938
1939
1940
1941
1942
1943 /*************************************************
1944 *         Reset for new message                  *
1945 *************************************************/
1946
1947 /* This function is called whenever the SMTP session is reset from
1948 within either of the setup functions; also from the daemon loop.
1949
1950 Argument:   the stacking pool storage reset point
1951 Returns:    nothing
1952 */
1953
1954 void
1955 smtp_reset(void *reset_point)
1956 {
1957 recipients_list = NULL;
1958 rcpt_count = rcpt_defer_count = rcpt_fail_count =
1959   raw_recipients_count = recipients_count = recipients_list_max = 0;
1960 message_linecount = 0;
1961 message_size = -1;
1962 acl_added_headers = NULL;
1963 acl_removed_headers = NULL;
1964 queue_only_policy = FALSE;
1965 rcpt_smtp_response = NULL;
1966 rcpt_smtp_response_same = TRUE;
1967 rcpt_in_progress = FALSE;
1968 deliver_freeze = FALSE;                              /* Can be set by ACL */
1969 freeze_tell = freeze_tell_config;                    /* Can be set by ACL */
1970 fake_response = OK;                                  /* Can be set by ACL */
1971 #ifdef WITH_CONTENT_SCAN
1972 no_mbox_unspool = FALSE;                             /* Can be set by ACL */
1973 #endif
1974 submission_mode = FALSE;                             /* Can be set by ACL */
1975 suppress_local_fixups = suppress_local_fixups_default; /* Can be set by ACL */
1976 active_local_from_check = local_from_check;          /* Can be set by ACL */
1977 active_local_sender_retain = local_sender_retain;    /* Can be set by ACL */
1978 sending_ip_address = NULL;
1979 return_path = sender_address = NULL;
1980 sender_data = NULL;                                  /* Can be set by ACL */
1981 deliver_localpart_parent = deliver_localpart_orig = NULL;
1982 deliver_domain_parent = deliver_domain_orig = NULL;
1983 callout_address = NULL;
1984 submission_name = NULL;                              /* Can be set by ACL */
1985 raw_sender = NULL;                  /* After SMTP rewrite, before qualifying */
1986 sender_address_unrewritten = NULL;  /* Set only after verify rewrite */
1987 sender_verified_list = NULL;        /* No senders verified */
1988 memset(sender_address_cache, 0, sizeof(sender_address_cache));
1989 memset(sender_domain_cache, 0, sizeof(sender_domain_cache));
1990
1991 authenticated_sender = NULL;
1992 #ifdef EXPERIMENTAL_BRIGHTMAIL
1993 bmi_run = 0;
1994 bmi_verdicts = NULL;
1995 #endif
1996 dnslist_domain = dnslist_matched = NULL;
1997 #ifndef DISABLE_DKIM
1998 dkim_cur_signer = dkim_signers = NULL;
1999 dkim_disable_verify = dkim_collect_input = FALSE;
2000 #endif
2001 dsn_ret = 0;
2002 dsn_envid = NULL;
2003 deliver_host = deliver_host_address = NULL;     /* Can be set by ACL */
2004 #ifndef DISABLE_PRDR
2005 prdr_requested = FALSE;
2006 #endif
2007 #ifdef SUPPORT_SPF
2008 spf_header_comment = spf_received = spf_result = spf_smtp_comment = NULL;
2009 #endif
2010 #ifdef EXPERIMENTAL_ARC
2011 arc_state = arc_state_reason = NULL;
2012 #endif
2013 #ifdef SUPPORT_I18N
2014 message_smtputf8 = FALSE;
2015 #endif
2016 body_linecount = body_zerocount = 0;
2017
2018 sender_rate = sender_rate_limit = sender_rate_period = NULL;
2019 ratelimiters_mail = NULL;           /* Updated by ratelimit ACL condition */
2020                    /* Note that ratelimiters_conn persists across resets. */
2021
2022 /* Reset message ACL variables */
2023
2024 acl_var_m = NULL;
2025
2026 /* The message body variables use malloc store. They may be set if this is
2027 not the first message in an SMTP session and the previous message caused them
2028 to be referenced in an ACL. */
2029
2030 if (message_body)
2031   {
2032   store_free(message_body);
2033   message_body = NULL;
2034   }
2035
2036 if (message_body_end)
2037   {
2038   store_free(message_body_end);
2039   message_body_end = NULL;
2040   }
2041
2042 /* Warning log messages are also saved in malloc store. They are saved to avoid
2043 repetition in the same message, but it seems right to repeat them for different
2044 messages. */
2045
2046 while (acl_warn_logged)
2047   {
2048   string_item *this = acl_warn_logged;
2049   acl_warn_logged = acl_warn_logged->next;
2050   store_free(this);
2051   }
2052 store_reset(reset_point);
2053 }
2054
2055
2056
2057
2058
2059 /*************************************************
2060 *  Initialize for incoming batched SMTP message  *
2061 *************************************************/
2062
2063 /* This function is called from smtp_setup_msg() in the case when
2064 smtp_batched_input is true. This happens when -bS is used to pass a whole batch
2065 of messages in one file with SMTP commands between them. All errors must be
2066 reported by sending a message, and only MAIL FROM, RCPT TO, and DATA are
2067 relevant. After an error on a sender, or an invalid recipient, the remainder
2068 of the message is skipped. The value of received_protocol is already set.
2069
2070 Argument: none
2071 Returns:  > 0 message successfully started (reached DATA)
2072           = 0 QUIT read or end of file reached
2073           < 0 should not occur
2074 */
2075
2076 static int
2077 smtp_setup_batch_msg(void)
2078 {
2079 int done = 0;
2080 void *reset_point = store_get(0);
2081
2082 /* Save the line count at the start of each transaction - single commands
2083 like HELO and RSET count as whole transactions. */
2084
2085 bsmtp_transaction_linecount = receive_linecount;
2086
2087 if ((receive_feof)()) return 0;   /* Treat EOF as QUIT */
2088
2089 cancel_cutthrough_connection(TRUE, US"smtp_setup_batch_msg");
2090 smtp_reset(reset_point);                /* Reset for start of message */
2091
2092 /* Deal with SMTP commands. This loop is exited by setting done to a POSITIVE
2093 value. The values are 2 larger than the required yield of the function. */
2094
2095 while (done <= 0)
2096   {
2097   uschar *errmess;
2098   uschar *recipient = NULL;
2099   int start, end, sender_domain, recipient_domain;
2100
2101   switch(smtp_read_command(FALSE, GETC_BUFFER_UNLIMITED))
2102     {
2103     /* The HELO/EHLO commands set sender_address_helo if they have
2104     valid data; otherwise they are ignored, except that they do
2105     a reset of the state. */
2106
2107     case HELO_CMD:
2108     case EHLO_CMD:
2109
2110       check_helo(smtp_cmd_data);
2111       /* Fall through */
2112
2113     case RSET_CMD:
2114       cancel_cutthrough_connection(TRUE, US"RSET received");
2115       smtp_reset(reset_point);
2116       bsmtp_transaction_linecount = receive_linecount;
2117       break;
2118
2119
2120     /* The MAIL FROM command requires an address as an operand. All we
2121     do here is to parse it for syntactic correctness. The form "<>" is
2122     a special case which converts into an empty string. The start/end
2123     pointers in the original are not used further for this address, as
2124     it is the canonical extracted address which is all that is kept. */
2125
2126     case MAIL_CMD:
2127       smtp_mailcmd_count++;              /* Count for no-mail log */
2128       if (sender_address != NULL)
2129         /* The function moan_smtp_batch() does not return. */
2130         moan_smtp_batch(smtp_cmd_buffer, "503 Sender already given");
2131
2132       if (smtp_cmd_data[0] == 0)
2133         /* The function moan_smtp_batch() does not return. */
2134         moan_smtp_batch(smtp_cmd_buffer, "501 MAIL FROM must have an address operand");
2135
2136       /* Reset to start of message */
2137
2138       cancel_cutthrough_connection(TRUE, US"MAIL received");
2139       smtp_reset(reset_point);
2140
2141       /* Apply SMTP rewrite */
2142
2143       raw_sender = ((rewrite_existflags & rewrite_smtp) != 0)?
2144         rewrite_one(smtp_cmd_data, rewrite_smtp|rewrite_smtp_sender, NULL, FALSE,
2145           US"", global_rewrite_rules) : smtp_cmd_data;
2146
2147       /* Extract the address; the TRUE flag allows <> as valid */
2148
2149       raw_sender =
2150         parse_extract_address(raw_sender, &errmess, &start, &end, &sender_domain,
2151           TRUE);
2152
2153       if (!raw_sender)
2154         /* The function moan_smtp_batch() does not return. */
2155         moan_smtp_batch(smtp_cmd_buffer, "501 %s", errmess);
2156
2157       sender_address = string_copy(raw_sender);
2158
2159       /* Qualify unqualified sender addresses if permitted to do so. */
2160
2161       if (  !sender_domain
2162          && sender_address[0] != 0 && sender_address[0] != '@')
2163         if (allow_unqualified_sender)
2164           {
2165           sender_address = rewrite_address_qualify(sender_address, FALSE);
2166           DEBUG(D_receive) debug_printf("unqualified address %s accepted "
2167             "and rewritten\n", raw_sender);
2168           }
2169         /* The function moan_smtp_batch() does not return. */
2170         else
2171           moan_smtp_batch(smtp_cmd_buffer, "501 sender address must contain "
2172             "a domain");
2173       break;
2174
2175
2176     /* The RCPT TO command requires an address as an operand. All we do
2177     here is to parse it for syntactic correctness. There may be any number
2178     of RCPT TO commands, specifying multiple senders. We build them all into
2179     a data structure that is in argc/argv format. The start/end values
2180     given by parse_extract_address are not used, as we keep only the
2181     extracted address. */
2182
2183     case RCPT_CMD:
2184       if (!sender_address)
2185         /* The function moan_smtp_batch() does not return. */
2186         moan_smtp_batch(smtp_cmd_buffer, "503 No sender yet given");
2187
2188       if (smtp_cmd_data[0] == 0)
2189         /* The function moan_smtp_batch() does not return. */
2190         moan_smtp_batch(smtp_cmd_buffer,
2191           "501 RCPT TO must have an address operand");
2192
2193       /* Check maximum number allowed */
2194
2195       if (recipients_max > 0 && recipients_count + 1 > recipients_max)
2196         /* The function moan_smtp_batch() does not return. */
2197         moan_smtp_batch(smtp_cmd_buffer, "%s too many recipients",
2198           recipients_max_reject? "552": "452");
2199
2200       /* Apply SMTP rewrite, then extract address. Don't allow "<>" as a
2201       recipient address */
2202
2203       recipient = rewrite_existflags & rewrite_smtp
2204         ? rewrite_one(smtp_cmd_data, rewrite_smtp, NULL, FALSE, US"",
2205                       global_rewrite_rules)
2206         : smtp_cmd_data;
2207
2208       recipient = parse_extract_address(recipient, &errmess, &start, &end,
2209         &recipient_domain, FALSE);
2210
2211       if (!recipient)
2212         /* The function moan_smtp_batch() does not return. */
2213         moan_smtp_batch(smtp_cmd_buffer, "501 %s", errmess);
2214
2215       /* If the recipient address is unqualified, qualify it if permitted. Then
2216       add it to the list of recipients. */
2217
2218       if (!recipient_domain)
2219         if (allow_unqualified_recipient)
2220           {
2221           DEBUG(D_receive) debug_printf("unqualified address %s accepted\n",
2222             recipient);
2223           recipient = rewrite_address_qualify(recipient, TRUE);
2224           }
2225         /* The function moan_smtp_batch() does not return. */
2226         else
2227           moan_smtp_batch(smtp_cmd_buffer,
2228             "501 recipient address must contain a domain");
2229
2230       receive_add_recipient(recipient, -1);
2231       break;
2232
2233
2234     /* The DATA command is legal only if it follows successful MAIL FROM
2235     and RCPT TO commands. This function is complete when a valid DATA
2236     command is encountered. */
2237
2238     case DATA_CMD:
2239       if (!sender_address || recipients_count <= 0)
2240         /* The function moan_smtp_batch() does not return. */
2241         if (!sender_address)
2242           moan_smtp_batch(smtp_cmd_buffer,
2243             "503 MAIL FROM:<sender> command must precede DATA");
2244         else
2245           moan_smtp_batch(smtp_cmd_buffer,
2246             "503 RCPT TO:<recipient> must precede DATA");
2247       else
2248         {
2249         done = 3;                      /* DATA successfully achieved */
2250         message_ended = END_NOTENDED;  /* Indicate in middle of message */
2251         }
2252       break;
2253
2254
2255     /* The VRFY, EXPN, HELP, ETRN, and NOOP commands are ignored. */
2256
2257     case VRFY_CMD:
2258     case EXPN_CMD:
2259     case HELP_CMD:
2260     case NOOP_CMD:
2261     case ETRN_CMD:
2262       bsmtp_transaction_linecount = receive_linecount;
2263       break;
2264
2265
2266     case EOF_CMD:
2267     case QUIT_CMD:
2268       done = 2;
2269       break;
2270
2271
2272     case BADARG_CMD:
2273       /* The function moan_smtp_batch() does not return. */
2274       moan_smtp_batch(smtp_cmd_buffer, "501 Unexpected argument data");
2275       break;
2276
2277
2278     case BADCHAR_CMD:
2279       /* The function moan_smtp_batch() does not return. */
2280       moan_smtp_batch(smtp_cmd_buffer, "501 Unexpected NULL in SMTP command");
2281       break;
2282
2283
2284     default:
2285       /* The function moan_smtp_batch() does not return. */
2286       moan_smtp_batch(smtp_cmd_buffer, "500 Command unrecognized");
2287       break;
2288     }
2289   }
2290
2291 return done - 2;  /* Convert yield values */
2292 }
2293
2294
2295
2296
2297 static BOOL
2298 smtp_log_tls_fail(uschar * errstr)
2299 {
2300 uschar * conn_info = smtp_get_connection_info();
2301
2302 if (Ustrncmp(conn_info, US"SMTP ", 5) == 0) conn_info += 5;
2303 /* I'd like to get separated H= here, but too hard for now */
2304
2305 log_write(0, LOG_MAIN, "TLS error on %s %s", conn_info, errstr);
2306 return FALSE;
2307 }
2308
2309
2310
2311
2312 #ifdef TCP_FASTOPEN
2313 static void
2314 tfo_in_check(void)
2315 {
2316 # ifdef TCP_INFO
2317 struct tcp_info tinfo;
2318 socklen_t len = sizeof(tinfo);
2319
2320 if (  getsockopt(fileno(smtp_out), IPPROTO_TCP, TCP_INFO, &tinfo, &len) == 0
2321    && tinfo.tcpi_state == TCP_SYN_RECV
2322    )
2323   {
2324   DEBUG(D_receive) debug_printf("TCP_FASTOPEN mode connection (state TCP_SYN_RECV)\n");
2325   tcp_in_fastopen = TRUE;
2326   }
2327 # endif
2328 }
2329 #endif
2330
2331
2332 /*************************************************
2333 *          Start an SMTP session                 *
2334 *************************************************/
2335
2336 /* This function is called at the start of an SMTP session. Thereafter,
2337 smtp_setup_msg() is called to initiate each separate message. This
2338 function does host-specific testing, and outputs the banner line.
2339
2340 Arguments:     none
2341 Returns:       FALSE if the session can not continue; something has
2342                gone wrong, or the connection to the host is blocked
2343 */
2344
2345 BOOL
2346 smtp_start_session(void)
2347 {
2348 int esclen;
2349 uschar *user_msg, *log_msg;
2350 uschar *code, *esc;
2351 uschar *p, *s;
2352 gstring * ss;
2353
2354 gettimeofday(&smtp_connection_start, NULL);
2355 for (smtp_ch_index = 0; smtp_ch_index < SMTP_HBUFF_SIZE; smtp_ch_index++)
2356   smtp_connection_had[smtp_ch_index] = SCH_NONE;
2357 smtp_ch_index = 0;
2358
2359 /* Default values for certain variables */
2360
2361 helo_seen = esmtp = helo_accept_junk = FALSE;
2362 smtp_mailcmd_count = 0;
2363 count_nonmail = TRUE_UNSET;
2364 synprot_error_count = unknown_command_count = nonmail_command_count = 0;
2365 smtp_delay_mail = smtp_rlm_base;
2366 auth_advertised = FALSE;
2367 pipelining_advertised = FALSE;
2368 pipelining_enable = TRUE;
2369 sync_cmd_limit = NON_SYNC_CMD_NON_PIPELINING;
2370 smtp_exit_function_called = FALSE;    /* For avoiding loop in not-quit exit */
2371
2372 /* If receiving by -bs from a trusted user, or testing with -bh, we allow
2373 authentication settings from -oMaa to remain in force. */
2374
2375 if (!host_checking && !sender_host_notsocket)
2376   sender_host_auth_pubname = sender_host_authenticated = NULL;
2377 authenticated_by = NULL;
2378
2379 #ifdef SUPPORT_TLS
2380 tls_in.cipher = tls_in.peerdn = NULL;
2381 tls_in.ourcert = tls_in.peercert = NULL;
2382 tls_in.sni = NULL;
2383 tls_in.ocsp = OCSP_NOT_REQ;
2384 tls_advertised = FALSE;
2385 #endif
2386 dsn_advertised = FALSE;
2387 #ifdef SUPPORT_I18N
2388 smtputf8_advertised = FALSE;
2389 #endif
2390
2391 /* Reset ACL connection variables */
2392
2393 acl_var_c = NULL;
2394
2395 /* Allow for trailing 0 in the command and data buffers. */
2396
2397 if (!(smtp_cmd_buffer = US malloc(2*SMTP_CMD_BUFFER_SIZE + 2)))
2398   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
2399     "malloc() failed for SMTP command buffer");
2400
2401 smtp_cmd_buffer[0] = 0;
2402 smtp_data_buffer = smtp_cmd_buffer + SMTP_CMD_BUFFER_SIZE + 1;
2403
2404 /* For batched input, the protocol setting can be overridden from the
2405 command line by a trusted caller. */
2406
2407 if (smtp_batched_input)
2408   {
2409   if (!received_protocol) received_protocol = US"local-bsmtp";
2410   }
2411
2412 /* For non-batched SMTP input, the protocol setting is forced here. It will be
2413 reset later if any of EHLO/AUTH/STARTTLS are received. */
2414
2415 else
2416   received_protocol =
2417     (sender_host_address ? protocols : protocols_local) [pnormal];
2418
2419 /* Set up the buffer for inputting using direct read() calls, and arrange to
2420 call the local functions instead of the standard C ones.  Place a NUL at the
2421 end of the buffer to safety-stop C-string reads from it. */
2422
2423 if (!(smtp_inbuffer = US malloc(IN_BUFFER_SIZE)))
2424   log_write(0, LOG_MAIN|LOG_PANIC_DIE, "malloc() failed for SMTP input buffer");
2425 smtp_inbuffer[IN_BUFFER_SIZE-1] = '\0';
2426
2427 receive_getc = smtp_getc;
2428 receive_getbuf = smtp_getbuf;
2429 receive_get_cache = smtp_get_cache;
2430 receive_ungetc = smtp_ungetc;
2431 receive_feof = smtp_feof;
2432 receive_ferror = smtp_ferror;
2433 receive_smtp_buffered = smtp_buffered;
2434 smtp_inptr = smtp_inend = smtp_inbuffer;
2435 smtp_had_eof = smtp_had_error = 0;
2436
2437 /* Set up the message size limit; this may be host-specific */
2438
2439 thismessage_size_limit = expand_string_integer(message_size_limit, TRUE);
2440 if (expand_string_message)
2441   {
2442   if (thismessage_size_limit == -1)
2443     log_write(0, LOG_MAIN|LOG_PANIC, "unable to expand message_size_limit: "
2444       "%s", expand_string_message);
2445   else
2446     log_write(0, LOG_MAIN|LOG_PANIC, "invalid message_size_limit: "
2447       "%s", expand_string_message);
2448   smtp_closedown(US"Temporary local problem - please try later");
2449   return FALSE;
2450   }
2451
2452 /* When a message is input locally via the -bs or -bS options, sender_host_
2453 unknown is set unless -oMa was used to force an IP address, in which case it
2454 is checked like a real remote connection. When -bs is used from inetd, this
2455 flag is not set, causing the sending host to be checked. The code that deals
2456 with IP source routing (if configured) is never required for -bs or -bS and
2457 the flag sender_host_notsocket is used to suppress it.
2458
2459 If smtp_accept_max and smtp_accept_reserve are set, keep some connections in
2460 reserve for certain hosts and/or networks. */
2461
2462 if (!sender_host_unknown)
2463   {
2464   int rc;
2465   BOOL reserved_host = FALSE;
2466
2467   /* Look up IP options (source routing info) on the socket if this is not an
2468   -oMa "host", and if any are found, log them and drop the connection.
2469
2470   Linux (and others now, see below) is different to everyone else, so there
2471   has to be some conditional compilation here. Versions of Linux before 2.1.15
2472   used a structure whose name was "options". Somebody finally realized that
2473   this name was silly, and it got changed to "ip_options". I use the
2474   newer name here, but there is a fudge in the script that sets up os.h
2475   to define a macro in older Linux systems.
2476
2477   Sigh. Linux is a fast-moving target. Another generation of Linux uses
2478   glibc 2, which has chosen ip_opts for the structure name. This is now
2479   really a glibc thing rather than a Linux thing, so the condition name
2480   has been changed to reflect this. It is relevant also to GNU/Hurd.
2481
2482   Mac OS 10.x (Darwin) is like the later glibc versions, but without the
2483   setting of the __GLIBC__ macro, so we can't detect it automatically. There's
2484   a special macro defined in the os.h file.
2485
2486   Some DGUX versions on older hardware appear not to support IP options at
2487   all, so there is now a general macro which can be set to cut out this
2488   support altogether.
2489
2490   How to do this properly in IPv6 is not yet known. */
2491
2492   #if !HAVE_IPV6 && !defined(NO_IP_OPTIONS)
2493
2494   #ifdef GLIBC_IP_OPTIONS
2495     #if (!defined __GLIBC__) || (__GLIBC__ < 2)
2496     #define OPTSTYLE 1
2497     #else
2498     #define OPTSTYLE 2
2499     #endif
2500   #elif defined DARWIN_IP_OPTIONS
2501     #define OPTSTYLE 2
2502   #else
2503     #define OPTSTYLE 3
2504   #endif
2505
2506   if (!host_checking && !sender_host_notsocket)
2507     {
2508     #if OPTSTYLE == 1
2509     EXIM_SOCKLEN_T optlen = sizeof(struct ip_options) + MAX_IPOPTLEN;
2510     struct ip_options *ipopt = store_get(optlen);
2511     #elif OPTSTYLE == 2
2512     struct ip_opts ipoptblock;
2513     struct ip_opts *ipopt = &ipoptblock;
2514     EXIM_SOCKLEN_T optlen = sizeof(ipoptblock);
2515     #else
2516     struct ipoption ipoptblock;
2517     struct ipoption *ipopt = &ipoptblock;
2518     EXIM_SOCKLEN_T optlen = sizeof(ipoptblock);
2519     #endif
2520
2521     /* Occasional genuine failures of getsockopt() have been seen - for
2522     example, "reset by peer". Therefore, just log and give up on this
2523     call, unless the error is ENOPROTOOPT. This error is given by systems
2524     that have the interfaces but not the mechanism - e.g. GNU/Hurd at the time
2525     of writing. So for that error, carry on - we just can't do an IP options
2526     check. */
2527
2528     DEBUG(D_receive) debug_printf("checking for IP options\n");
2529
2530     if (getsockopt(fileno(smtp_out), IPPROTO_IP, IP_OPTIONS, US (ipopt),
2531           &optlen) < 0)
2532       {
2533       if (errno != ENOPROTOOPT)
2534         {
2535         log_write(0, LOG_MAIN, "getsockopt() failed from %s: %s",
2536           host_and_ident(FALSE), strerror(errno));
2537         smtp_printf("451 SMTP service not available\r\n", FALSE);
2538         return FALSE;
2539         }
2540       }
2541
2542     /* Deal with any IP options that are set. On the systems I have looked at,
2543     the value of MAX_IPOPTLEN has been 40, meaning that there should never be
2544     more logging data than will fit in big_buffer. Nevertheless, after somebody
2545     questioned this code, I've added in some paranoid checking. */
2546
2547     else if (optlen > 0)
2548       {
2549       uschar *p = big_buffer;
2550       uschar *pend = big_buffer + big_buffer_size;
2551       uschar *opt, *adptr;
2552       int optcount;
2553       struct in_addr addr;
2554
2555       #if OPTSTYLE == 1
2556       uschar *optstart = US (ipopt->__data);
2557       #elif OPTSTYLE == 2
2558       uschar *optstart = US (ipopt->ip_opts);
2559       #else
2560       uschar *optstart = US (ipopt->ipopt_list);
2561       #endif
2562
2563       DEBUG(D_receive) debug_printf("IP options exist\n");
2564
2565       Ustrcpy(p, "IP options on incoming call:");
2566       p += Ustrlen(p);
2567
2568       for (opt = optstart; opt != NULL &&
2569            opt < US (ipopt) + optlen;)
2570         {
2571         switch (*opt)
2572           {
2573           case IPOPT_EOL:
2574           opt = NULL;
2575           break;
2576
2577           case IPOPT_NOP:
2578           opt++;
2579           break;
2580
2581           case IPOPT_SSRR:
2582           case IPOPT_LSRR:
2583           if (!string_format(p, pend-p, " %s [@%s",
2584                (*opt == IPOPT_SSRR)? "SSRR" : "LSRR",
2585                #if OPTSTYLE == 1
2586                inet_ntoa(*((struct in_addr *)(&(ipopt->faddr))))))
2587                #elif OPTSTYLE == 2
2588                inet_ntoa(ipopt->ip_dst)))
2589                #else
2590                inet_ntoa(ipopt->ipopt_dst)))
2591                #endif
2592             {
2593             opt = NULL;
2594             break;
2595             }
2596
2597           p += Ustrlen(p);
2598           optcount = (opt[1] - 3) / sizeof(struct in_addr);
2599           adptr = opt + 3;
2600           while (optcount-- > 0)
2601             {
2602             memcpy(&addr, adptr, sizeof(addr));
2603             if (!string_format(p, pend - p - 1, "%s%s",
2604                   (optcount == 0)? ":" : "@", inet_ntoa(addr)))
2605               {
2606               opt = NULL;
2607               break;
2608               }
2609             p += Ustrlen(p);
2610             adptr += sizeof(struct in_addr);
2611             }
2612           *p++ = ']';
2613           opt += opt[1];
2614           break;
2615
2616           default:
2617             {
2618             int i;
2619             if (pend - p < 4 + 3*opt[1]) { opt = NULL; break; }
2620             Ustrcat(p, "[ ");
2621             p += 2;
2622             for (i = 0; i < opt[1]; i++)
2623               p += sprintf(CS p, "%2.2x ", opt[i]);
2624             *p++ = ']';
2625             }
2626           opt += opt[1];
2627           break;
2628           }
2629         }
2630
2631       *p = 0;
2632       log_write(0, LOG_MAIN, "%s", big_buffer);
2633
2634       /* Refuse any call with IP options. This is what tcpwrappers 7.5 does. */
2635
2636       log_write(0, LOG_MAIN|LOG_REJECT,
2637         "connection from %s refused (IP options)", host_and_ident(FALSE));
2638
2639       smtp_printf("554 SMTP service not available\r\n", FALSE);
2640       return FALSE;
2641       }
2642
2643     /* Length of options = 0 => there are no options */
2644
2645     else DEBUG(D_receive) debug_printf("no IP options found\n");
2646     }
2647   #endif  /* HAVE_IPV6 && !defined(NO_IP_OPTIONS) */
2648
2649   /* Set keep-alive in socket options. The option is on by default. This
2650   setting is an attempt to get rid of some hanging connections that stick in
2651   read() when the remote end (usually a dialup) goes away. */
2652
2653   if (smtp_accept_keepalive && !sender_host_notsocket)
2654     ip_keepalive(fileno(smtp_out), sender_host_address, FALSE);
2655
2656   /* If the current host matches host_lookup, set the name by doing a
2657   reverse lookup. On failure, sender_host_name will be NULL and
2658   host_lookup_failed will be TRUE. This may or may not be serious - optional
2659   checks later. */
2660
2661   if (verify_check_host(&host_lookup) == OK)
2662     {
2663     (void)host_name_lookup();
2664     host_build_sender_fullhost();
2665     }
2666
2667   /* Delay this until we have the full name, if it is looked up. */
2668
2669   set_process_info("handling incoming connection from %s",
2670     host_and_ident(FALSE));
2671
2672   /* Expand smtp_receive_timeout, if needed */
2673
2674   if (smtp_receive_timeout_s)
2675     {
2676     uschar * exp;
2677     if (  !(exp = expand_string(smtp_receive_timeout_s))
2678        || !(*exp)
2679        || (smtp_receive_timeout = readconf_readtime(exp, 0, FALSE)) < 0
2680        )
2681       log_write(0, LOG_MAIN|LOG_PANIC,
2682         "bad value for smtp_receive_timeout: '%s'", exp ? exp : US"");
2683     }
2684
2685   /* Test for explicit connection rejection */
2686
2687   if (verify_check_host(&host_reject_connection) == OK)
2688     {
2689     log_write(L_connection_reject, LOG_MAIN|LOG_REJECT, "refused connection "
2690       "from %s (host_reject_connection)", host_and_ident(FALSE));
2691     smtp_printf("554 SMTP service not available\r\n", FALSE);
2692     return FALSE;
2693     }
2694
2695   /* Test with TCP Wrappers if so configured. There is a problem in that
2696   hosts_ctl() returns 0 (deny) under a number of system failure circumstances,
2697   such as disks dying. In these cases, it is desirable to reject with a 4xx
2698   error instead of a 5xx error. There isn't a "right" way to detect such
2699   problems. The following kludge is used: errno is zeroed before calling
2700   hosts_ctl(). If the result is "reject", a 5xx error is given only if the
2701   value of errno is 0 or ENOENT (which happens if /etc/hosts.{allow,deny} does
2702   not exist). */
2703
2704 #ifdef USE_TCP_WRAPPERS
2705   errno = 0;
2706   if (!(tcp_wrappers_name = expand_string(tcp_wrappers_daemon_name)))
2707     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Expansion of \"%s\" "
2708       "(tcp_wrappers_name) failed: %s", string_printing(tcp_wrappers_name),
2709         expand_string_message);
2710
2711   if (!hosts_ctl(tcp_wrappers_name,
2712          sender_host_name ? CS sender_host_name : STRING_UNKNOWN,
2713          sender_host_address ? CS sender_host_address : STRING_UNKNOWN,
2714          sender_ident ? CS sender_ident : STRING_UNKNOWN))
2715     {
2716     if (errno == 0 || errno == ENOENT)
2717       {
2718       HDEBUG(D_receive) debug_printf("tcp wrappers rejection\n");
2719       log_write(L_connection_reject,
2720                 LOG_MAIN|LOG_REJECT, "refused connection from %s "
2721                 "(tcp wrappers)", host_and_ident(FALSE));
2722       smtp_printf("554 SMTP service not available\r\n", FALSE);
2723       }
2724     else
2725       {
2726       int save_errno = errno;
2727       HDEBUG(D_receive) debug_printf("tcp wrappers rejected with unexpected "
2728         "errno value %d\n", save_errno);
2729       log_write(L_connection_reject,
2730                 LOG_MAIN|LOG_REJECT, "temporarily refused connection from %s "
2731                 "(tcp wrappers errno=%d)", host_and_ident(FALSE), save_errno);
2732       smtp_printf("451 Temporary local problem - please try later\r\n", FALSE);
2733       }
2734     return FALSE;
2735     }
2736 #endif
2737
2738   /* Check for reserved slots. The value of smtp_accept_count has already been
2739   incremented to include this process. */
2740
2741   if (smtp_accept_max > 0 &&
2742       smtp_accept_count > smtp_accept_max - smtp_accept_reserve)
2743     {
2744     if ((rc = verify_check_host(&smtp_reserve_hosts)) != OK)
2745       {
2746       log_write(L_connection_reject,
2747         LOG_MAIN, "temporarily refused connection from %s: not in "
2748         "reserve list: connected=%d max=%d reserve=%d%s",
2749         host_and_ident(FALSE), smtp_accept_count - 1, smtp_accept_max,
2750         smtp_accept_reserve, (rc == DEFER)? " (lookup deferred)" : "");
2751       smtp_printf("421 %s: Too many concurrent SMTP connections; "
2752         "please try again later\r\n", FALSE, smtp_active_hostname);
2753       return FALSE;
2754       }
2755     reserved_host = TRUE;
2756     }
2757
2758   /* If a load level above which only messages from reserved hosts are
2759   accepted is set, check the load. For incoming calls via the daemon, the
2760   check is done in the superior process if there are no reserved hosts, to
2761   save a fork. In all cases, the load average will already be available
2762   in a global variable at this point. */
2763
2764   if (smtp_load_reserve >= 0 &&
2765        load_average > smtp_load_reserve &&
2766        !reserved_host &&
2767        verify_check_host(&smtp_reserve_hosts) != OK)
2768     {
2769     log_write(L_connection_reject,
2770       LOG_MAIN, "temporarily refused connection from %s: not in "
2771       "reserve list and load average = %.2f", host_and_ident(FALSE),
2772       (double)load_average/1000.0);
2773     smtp_printf("421 %s: Too much load; please try again later\r\n", FALSE,
2774       smtp_active_hostname);
2775     return FALSE;
2776     }
2777
2778   /* Determine whether unqualified senders or recipients are permitted
2779   for this host. Unfortunately, we have to do this every time, in order to
2780   set the flags so that they can be inspected when considering qualifying
2781   addresses in the headers. For a site that permits no qualification, this
2782   won't take long, however. */
2783
2784   allow_unqualified_sender =
2785     verify_check_host(&sender_unqualified_hosts) == OK;
2786
2787   allow_unqualified_recipient =
2788     verify_check_host(&recipient_unqualified_hosts) == OK;
2789
2790   /* Determine whether HELO/EHLO is required for this host. The requirement
2791   can be hard or soft. */
2792
2793   helo_required = verify_check_host(&helo_verify_hosts) == OK;
2794   if (!helo_required)
2795     helo_verify = verify_check_host(&helo_try_verify_hosts) == OK;
2796
2797   /* Determine whether this hosts is permitted to send syntactic junk
2798   after a HELO or EHLO command. */
2799
2800   helo_accept_junk = verify_check_host(&helo_accept_junk_hosts) == OK;
2801   }
2802
2803 /* For batch SMTP input we are now done. */
2804
2805 if (smtp_batched_input) return TRUE;
2806
2807 /* If valid Proxy Protocol source is connecting, set up session.
2808  * Failure will not allow any SMTP function other than QUIT. */
2809
2810 #ifdef SUPPORT_PROXY
2811 proxy_session = FALSE;
2812 proxy_session_failed = FALSE;
2813 if (check_proxy_protocol_host())
2814   setup_proxy_protocol_host();
2815 #endif
2816
2817   /* Start up TLS if tls_on_connect is set. This is for supporting the legacy
2818   smtps port for use with older style SSL MTAs. */
2819
2820 #ifdef SUPPORT_TLS
2821   if (tls_in.on_connect)
2822     {
2823     if (tls_server_start(tls_require_ciphers, &user_msg) != OK)
2824       return smtp_log_tls_fail(user_msg);
2825     cmd_list[CMD_LIST_TLS_AUTH].is_mail_cmd = TRUE;
2826     }
2827 #endif
2828
2829 /* Run the connect ACL if it exists */
2830
2831 user_msg = NULL;
2832 if (acl_smtp_connect)
2833   {
2834   int rc;
2835   if ((rc = acl_check(ACL_WHERE_CONNECT, NULL, acl_smtp_connect, &user_msg,
2836                       &log_msg)) != OK)
2837     {
2838     (void) smtp_handle_acl_fail(ACL_WHERE_CONNECT, rc, user_msg, log_msg);
2839     return FALSE;
2840     }
2841   }
2842
2843 /* Output the initial message for a two-way SMTP connection. It may contain
2844 newlines, which then cause a multi-line response to be given. */
2845
2846 code = US"220";   /* Default status code */
2847 esc = US"";       /* Default extended status code */
2848 esclen = 0;       /* Length of esc */
2849
2850 if (!user_msg)
2851   {
2852   if (!(s = expand_string(smtp_banner)))
2853     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Expansion of \"%s\" (smtp_banner) "
2854       "failed: %s", smtp_banner, expand_string_message);
2855   }
2856 else
2857   {
2858   int codelen = 3;
2859   s = user_msg;
2860   smtp_message_code(&code, &codelen, &s, NULL, TRUE);
2861   if (codelen > 4)
2862     {
2863     esc = code + 4;
2864     esclen = codelen - 4;
2865     }
2866   }
2867
2868 /* Remove any terminating newlines; might as well remove trailing space too */
2869
2870 p = s + Ustrlen(s);
2871 while (p > s && isspace(p[-1])) p--;
2872 *p = 0;
2873
2874 /* It seems that CC:Mail is braindead, and assumes that the greeting message
2875 is all contained in a single IP packet. The original code wrote out the
2876 greeting using several calls to fprint/fputc, and on busy servers this could
2877 cause it to be split over more than one packet - which caused CC:Mail to fall
2878 over when it got the second part of the greeting after sending its first
2879 command. Sigh. To try to avoid this, build the complete greeting message
2880 first, and output it in one fell swoop. This gives a better chance of it
2881 ending up as a single packet. */
2882
2883 ss = string_get(256);
2884
2885 p = s;
2886 do       /* At least once, in case we have an empty string */
2887   {
2888   int len;
2889   uschar *linebreak = Ustrchr(p, '\n');
2890   ss = string_catn(ss, code, 3);
2891   if (!linebreak)
2892     {
2893     len = Ustrlen(p);
2894     ss = string_catn(ss, US" ", 1);
2895     }
2896   else
2897     {
2898     len = linebreak - p;
2899     ss = string_catn(ss, US"-", 1);
2900     }
2901   ss = string_catn(ss, esc, esclen);
2902   ss = string_catn(ss, p, len);
2903   ss = string_catn(ss, US"\r\n", 2);
2904   p += len;
2905   if (linebreak) p++;
2906   }
2907 while (*p);
2908
2909 /* Before we write the banner, check that there is no input pending, unless
2910 this synchronisation check is disabled. */
2911
2912 if (!check_sync())
2913   {
2914   unsigned n = smtp_inend - smtp_inptr;
2915   if (n > 32) n = 32;
2916
2917   log_write(0, LOG_MAIN|LOG_REJECT, "SMTP protocol "
2918     "synchronization error (input sent without waiting for greeting): "
2919     "rejected connection from %s input=\"%s\"", host_and_ident(TRUE),
2920     string_printing(string_copyn(smtp_inptr, n)));
2921   smtp_printf("554 SMTP synchronization error\r\n", FALSE);
2922   return FALSE;
2923   }
2924
2925 /* Now output the banner */
2926
2927 smtp_printf("%s", FALSE, string_from_gstring(ss));
2928
2929 /* Attempt to see if we sent the banner before the last ACK of the 3-way
2930 handshake arrived.  If so we must have managed a TFO. */
2931
2932 #ifdef TCP_FASTOPEN
2933 tfo_in_check();
2934 #endif
2935
2936 return TRUE;
2937 }
2938
2939
2940
2941
2942
2943 /*************************************************
2944 *     Handle SMTP syntax and protocol errors     *
2945 *************************************************/
2946
2947 /* Write to the log for SMTP syntax errors in incoming commands, if configured
2948 to do so. Then transmit the error response. The return value depends on the
2949 number of syntax and protocol errors in this SMTP session.
2950
2951 Arguments:
2952   type      error type, given as a log flag bit
2953   code      response code; <= 0 means don't send a response
2954   data      data to reflect in the response (can be NULL)
2955   errmess   the error message
2956
2957 Returns:    -1   limit of syntax/protocol errors NOT exceeded
2958             +1   limit of syntax/protocol errors IS exceeded
2959
2960 These values fit in with the values of the "done" variable in the main
2961 processing loop in smtp_setup_msg(). */
2962
2963 static int
2964 synprot_error(int type, int code, uschar *data, uschar *errmess)
2965 {
2966 int yield = -1;
2967
2968 log_write(type, LOG_MAIN, "SMTP %s error in \"%s\" %s %s",
2969   (type == L_smtp_syntax_error)? "syntax" : "protocol",
2970   string_printing(smtp_cmd_buffer), host_and_ident(TRUE), errmess);
2971
2972 if (++synprot_error_count > smtp_max_synprot_errors)
2973   {
2974   yield = 1;
2975   log_write(0, LOG_MAIN|LOG_REJECT, "SMTP call from %s dropped: too many "
2976     "syntax or protocol errors (last command was \"%s\")",
2977     host_and_ident(FALSE), string_printing(smtp_cmd_buffer));
2978   }
2979
2980 if (code > 0)
2981   {
2982   smtp_printf("%d%c%s%s%s\r\n", FALSE, code, yield == 1 ? '-' : ' ',
2983     data ? data : US"", data ? US": " : US"", errmess);
2984   if (yield == 1)
2985     smtp_printf("%d Too many syntax or protocol errors\r\n", FALSE, code);
2986   }
2987
2988 return yield;
2989 }
2990
2991
2992
2993
2994 /*************************************************
2995 *    Send SMTP response, possibly multiline      *
2996 *************************************************/
2997
2998 /* There are, it seems, broken clients out there that cannot handle multiline
2999 responses. If no_multiline_responses is TRUE (it can be set from an ACL), we
3000 output nothing for non-final calls, and only the first line for anything else.
3001
3002 Arguments:
3003   code          SMTP code, may involve extended status codes
3004   codelen       length of smtp code; if > 4 there's an ESC
3005   final         FALSE if the last line isn't the final line
3006   msg           message text, possibly containing newlines
3007
3008 Returns:        nothing
3009 */
3010
3011 void
3012 smtp_respond(uschar* code, int codelen, BOOL final, uschar *msg)
3013 {
3014 int esclen = 0;
3015 uschar *esc = US"";
3016
3017 if (!final && no_multiline_responses) return;
3018
3019 if (codelen > 4)
3020   {
3021   esc = code + 4;
3022   esclen = codelen - 4;
3023   }
3024
3025 /* If this is the first output for a (non-batch) RCPT command, see if all RCPTs
3026 have had the same. Note: this code is also present in smtp_printf(). It would
3027 be tidier to have it only in one place, but when it was added, it was easier to
3028 do it that way, so as not to have to mess with the code for the RCPT command,
3029 which sometimes uses smtp_printf() and sometimes smtp_respond(). */
3030
3031 if (rcpt_in_progress)
3032   {
3033   if (rcpt_smtp_response == NULL)
3034     rcpt_smtp_response = string_copy(msg);
3035   else if (rcpt_smtp_response_same &&
3036            Ustrcmp(rcpt_smtp_response, msg) != 0)
3037     rcpt_smtp_response_same = FALSE;
3038   rcpt_in_progress = FALSE;
3039   }
3040
3041 /* Now output the message, splitting it up into multiple lines if necessary.
3042 We only handle pipelining these responses as far as nonfinal/final groups,
3043 not the whole MAIL/RCPT/DATA response set. */
3044
3045 for (;;)
3046   {
3047   uschar *nl = Ustrchr(msg, '\n');
3048   if (nl == NULL)
3049     {
3050     smtp_printf("%.3s%c%.*s%s\r\n", !final, code, final ? ' ':'-', esclen, esc, msg);
3051     return;
3052     }
3053   else if (nl[1] == 0 || no_multiline_responses)
3054     {
3055     smtp_printf("%.3s%c%.*s%.*s\r\n", !final, code, final ? ' ':'-', esclen, esc,
3056       (int)(nl - msg), msg);
3057     return;
3058     }
3059   else
3060     {
3061     smtp_printf("%.3s-%.*s%.*s\r\n", TRUE, code, esclen, esc, (int)(nl - msg), msg);
3062     msg = nl + 1;
3063     while (isspace(*msg)) msg++;
3064     }
3065   }
3066 }
3067
3068
3069
3070
3071 /*************************************************
3072 *            Parse user SMTP message             *
3073 *************************************************/
3074
3075 /* This function allows for user messages overriding the response code details
3076 by providing a suitable response code string at the start of the message
3077 user_msg. Check the message for starting with a response code and optionally an
3078 extended status code. If found, check that the first digit is valid, and if so,
3079 change the code pointer and length to use the replacement. An invalid code
3080 causes a panic log; in this case, if the log messages is the same as the user
3081 message, we must also adjust the value of the log message to show the code that
3082 is actually going to be used (the original one).
3083
3084 This function is global because it is called from receive.c as well as within
3085 this module.
3086
3087 Note that the code length returned includes the terminating whitespace
3088 character, which is always included in the regex match.
3089
3090 Arguments:
3091   code          SMTP code, may involve extended status codes
3092   codelen       length of smtp code; if > 4 there's an ESC
3093   msg           message text
3094   log_msg       optional log message, to be adjusted with the new SMTP code
3095   check_valid   if true, verify the response code
3096
3097 Returns:        nothing
3098 */
3099
3100 void
3101 smtp_message_code(uschar **code, int *codelen, uschar **msg, uschar **log_msg,
3102   BOOL check_valid)
3103 {
3104 int n;
3105 int ovector[3];
3106
3107 if (!msg || !*msg) return;
3108
3109 if ((n = pcre_exec(regex_smtp_code, NULL, CS *msg, Ustrlen(*msg), 0,
3110   PCRE_EOPT, ovector, sizeof(ovector)/sizeof(int))) < 0) return;
3111
3112 if (check_valid && (*msg)[0] != (*code)[0])
3113   {
3114   log_write(0, LOG_MAIN|LOG_PANIC, "configured error code starts with "
3115     "incorrect digit (expected %c) in \"%s\"", (*code)[0], *msg);
3116   if (log_msg != NULL && *log_msg == *msg)
3117     *log_msg = string_sprintf("%s %s", *code, *log_msg + ovector[1]);
3118   }
3119 else
3120   {
3121   *code = *msg;
3122   *codelen = ovector[1];    /* Includes final space */
3123   }
3124 *msg += ovector[1];         /* Chop the code off the message */
3125 return;
3126 }
3127
3128
3129
3130
3131 /*************************************************
3132 *           Handle an ACL failure                *
3133 *************************************************/
3134
3135 /* This function is called when acl_check() fails. As well as calls from within
3136 this module, it is called from receive.c for an ACL after DATA. It sorts out
3137 logging the incident, and sends the error response. A message containing
3138 newlines is turned into a multiline SMTP response, but for logging, only the
3139 first line is used.
3140
3141 There's a table of default permanent failure response codes to use in
3142 globals.c, along with the table of names. VFRY is special. Despite RFC1123 it
3143 defaults disabled in Exim. However, discussion in connection with RFC 821bis
3144 (aka RFC 2821) has concluded that the response should be 252 in the disabled
3145 state, because there are broken clients that try VRFY before RCPT. A 5xx
3146 response should be given only when the address is positively known to be
3147 undeliverable. Sigh. We return 252 if there is no VRFY ACL or it provides
3148 no explicit code, but if there is one we let it know best.
3149 Also, for ETRN, 458 is given on refusal, and for AUTH, 503.
3150
3151 From Exim 4.63, it is possible to override the response code details by
3152 providing a suitable response code string at the start of the message provided
3153 in user_msg. The code's first digit is checked for validity.
3154
3155 Arguments:
3156   where        where the ACL was called from
3157   rc           the failure code
3158   user_msg     a message that can be included in an SMTP response
3159   log_msg      a message for logging
3160
3161 Returns:     0 in most cases
3162              2 if the failure code was FAIL_DROP, in which case the
3163                SMTP connection should be dropped (this value fits with the
3164                "done" variable in smtp_setup_msg() below)
3165 */
3166
3167 int
3168 smtp_handle_acl_fail(int where, int rc, uschar *user_msg, uschar *log_msg)
3169 {
3170 BOOL drop = rc == FAIL_DROP;
3171 int codelen = 3;
3172 uschar *smtp_code;
3173 uschar *lognl;
3174 uschar *sender_info = US"";
3175 uschar *what =
3176 #ifdef WITH_CONTENT_SCAN
3177   where == ACL_WHERE_MIME ? US"during MIME ACL checks" :
3178 #endif
3179   where == ACL_WHERE_PREDATA ? US"DATA" :
3180   where == ACL_WHERE_DATA ? US"after DATA" :
3181 #ifndef DISABLE_PRDR
3182   where == ACL_WHERE_PRDR ? US"after DATA PRDR" :
3183 #endif
3184   smtp_cmd_data ?
3185     string_sprintf("%s %s", acl_wherenames[where], smtp_cmd_data) :
3186     string_sprintf("%s in \"connect\" ACL", acl_wherenames[where]);
3187
3188 if (drop) rc = FAIL;
3189
3190 /* Set the default SMTP code, and allow a user message to change it. */
3191
3192 smtp_code = rc == FAIL ? acl_wherecodes[where] : US"451";
3193 smtp_message_code(&smtp_code, &codelen, &user_msg, &log_msg,
3194   where != ACL_WHERE_VRFY);
3195
3196 /* We used to have sender_address here; however, there was a bug that was not
3197 updating sender_address after a rewrite during a verify. When this bug was
3198 fixed, sender_address at this point became the rewritten address. I'm not sure
3199 this is what should be logged, so I've changed to logging the unrewritten
3200 address to retain backward compatibility. */
3201
3202 #ifndef WITH_CONTENT_SCAN
3203 if (where == ACL_WHERE_RCPT || where == ACL_WHERE_DATA)
3204 #else
3205 if (where == ACL_WHERE_RCPT || where == ACL_WHERE_DATA || where == ACL_WHERE_MIME)
3206 #endif
3207   {
3208   sender_info = string_sprintf("F=<%s>%s%s%s%s ",
3209     sender_address_unrewritten ? sender_address_unrewritten : sender_address,
3210     sender_host_authenticated ? US" A="                                    : US"",
3211     sender_host_authenticated ? sender_host_authenticated                  : US"",
3212     sender_host_authenticated && authenticated_id ? US":"                  : US"",
3213     sender_host_authenticated && authenticated_id ? authenticated_id       : US""
3214     );
3215   }
3216
3217 /* If there's been a sender verification failure with a specific message, and
3218 we have not sent a response about it yet, do so now, as a preliminary line for
3219 failures, but not defers. However, always log it for defer, and log it for fail
3220 unless the sender_verify_fail log selector has been turned off. */
3221
3222 if (sender_verified_failed &&
3223     !testflag(sender_verified_failed, af_sverify_told))
3224   {
3225   BOOL save_rcpt_in_progress = rcpt_in_progress;
3226   rcpt_in_progress = FALSE;  /* So as not to treat these as the error */
3227
3228   setflag(sender_verified_failed, af_sverify_told);
3229
3230   if (rc != FAIL || LOGGING(sender_verify_fail))
3231     log_write(0, LOG_MAIN|LOG_REJECT, "%s sender verify %s for <%s>%s",
3232       host_and_ident(TRUE),
3233       ((sender_verified_failed->special_action & 255) == DEFER)? "defer":"fail",
3234       sender_verified_failed->address,
3235       (sender_verified_failed->message == NULL)? US"" :
3236       string_sprintf(": %s", sender_verified_failed->message));
3237
3238   if (rc == FAIL && sender_verified_failed->user_message)
3239     smtp_respond(smtp_code, codelen, FALSE, string_sprintf(
3240         testflag(sender_verified_failed, af_verify_pmfail)?
3241           "Postmaster verification failed while checking <%s>\n%s\n"
3242           "Several RFCs state that you are required to have a postmaster\n"
3243           "mailbox for each mail domain. This host does not accept mail\n"
3244           "from domains whose servers reject the postmaster address."
3245           :
3246         testflag(sender_verified_failed, af_verify_nsfail)?
3247           "Callback setup failed while verifying <%s>\n%s\n"
3248           "The initial connection, or a HELO or MAIL FROM:<> command was\n"
3249           "rejected. Refusing MAIL FROM:<> does not help fight spam, disregards\n"
3250           "RFC requirements, and stops you from receiving standard bounce\n"
3251           "messages. This host does not accept mail from domains whose servers\n"
3252           "refuse bounces."
3253           :
3254           "Verification failed for <%s>\n%s",
3255         sender_verified_failed->address,
3256         sender_verified_failed->user_message));
3257
3258   rcpt_in_progress = save_rcpt_in_progress;
3259   }
3260
3261 /* Sort out text for logging */
3262
3263 log_msg = log_msg ? string_sprintf(": %s", log_msg) : US"";
3264 if ((lognl = Ustrchr(log_msg, '\n'))) *lognl = 0;
3265
3266 /* Send permanent failure response to the command, but the code used isn't
3267 always a 5xx one - see comments at the start of this function. If the original
3268 rc was FAIL_DROP we drop the connection and yield 2. */
3269
3270 if (rc == FAIL)
3271   smtp_respond(smtp_code, codelen, TRUE,
3272     user_msg ? user_msg : US"Administrative prohibition");
3273
3274 /* Send temporary failure response to the command. Don't give any details,
3275 unless acl_temp_details is set. This is TRUE for a callout defer, a "defer"
3276 verb, and for a header verify when smtp_return_error_details is set.
3277
3278 This conditional logic is all somewhat of a mess because of the odd
3279 interactions between temp_details and return_error_details. One day it should
3280 be re-implemented in a tidier fashion. */
3281
3282 else
3283   if (acl_temp_details && user_msg)
3284     {
3285     if (  smtp_return_error_details
3286        && sender_verified_failed
3287        && sender_verified_failed->message
3288        )
3289       smtp_respond(smtp_code, codelen, FALSE, sender_verified_failed->message);
3290
3291     smtp_respond(smtp_code, codelen, TRUE, user_msg);
3292     }
3293   else
3294     smtp_respond(smtp_code, codelen, TRUE,
3295       US"Temporary local problem - please try later");
3296
3297 /* Log the incident to the logs that are specified by log_reject_target
3298 (default main, reject). This can be empty to suppress logging of rejections. If
3299 the connection is not forcibly to be dropped, return 0. Otherwise, log why it
3300 is closing if required and return 2.  */
3301
3302 if (log_reject_target != 0)
3303   {
3304 #ifdef SUPPORT_TLS
3305   gstring * g = s_tlslog(NULL);
3306   uschar * tls = string_from_gstring(g);
3307   if (!tls) tls = US"";
3308 #else
3309   uschar * tls = US"";
3310 #endif
3311   log_write(where == ACL_WHERE_CONNECT ? L_connection_reject : 0,
3312     log_reject_target, "%s%s%s %s%srejected %s%s",
3313     LOGGING(dnssec) && sender_host_dnssec ? US" DS" : US"",
3314     host_and_ident(TRUE),
3315     tls,
3316     sender_info,
3317     rc == FAIL ? US"" : US"temporarily ",
3318     what, log_msg);
3319   }
3320
3321 if (!drop) return 0;
3322
3323 log_write(L_smtp_connection, LOG_MAIN, "%s closed by DROP in ACL",
3324   smtp_get_connection_info());
3325
3326 /* Run the not-quit ACL, but without any custom messages. This should not be a
3327 problem, because we get here only if some other ACL has issued "drop", and
3328 in that case, *its* custom messages will have been used above. */
3329
3330 smtp_notquit_exit(US"acl-drop", NULL, NULL);
3331 return 2;
3332 }
3333
3334
3335
3336
3337 /*************************************************
3338 *     Handle SMTP exit when QUIT is not given    *
3339 *************************************************/
3340
3341 /* This function provides a logging/statistics hook for when an SMTP connection
3342 is dropped on the floor or the other end goes away. It's a global function
3343 because it's called from receive.c as well as this module. As well as running
3344 the NOTQUIT ACL, if there is one, this function also outputs a final SMTP
3345 response, either with a custom message from the ACL, or using a default. There
3346 is one case, however, when no message is output - after "drop". In that case,
3347 the ACL that obeyed "drop" has already supplied the custom message, and NULL is
3348 passed to this function.
3349
3350 In case things go wrong while processing this function, causing an error that
3351 may re-enter this function, there is a recursion check.
3352
3353 Arguments:
3354   reason          What $smtp_notquit_reason will be set to in the ACL;
3355                     if NULL, the ACL is not run
3356   code            The error code to return as part of the response
3357   defaultrespond  The default message if there's no user_msg
3358
3359 Returns:          Nothing
3360 */
3361
3362 void
3363 smtp_notquit_exit(uschar *reason, uschar *code, uschar *defaultrespond, ...)
3364 {
3365 int rc;
3366 uschar *user_msg = NULL;
3367 uschar *log_msg = NULL;
3368
3369 /* Check for recursive acll */
3370
3371 if (smtp_exit_function_called)
3372   {
3373   log_write(0, LOG_PANIC, "smtp_notquit_exit() called more than once (%s)",
3374     reason);
3375   return;
3376   }
3377 smtp_exit_function_called = TRUE;
3378
3379 /* Call the not-QUIT ACL, if there is one, unless no reason is given. */
3380
3381 if (acl_smtp_notquit && reason)
3382   {
3383   smtp_notquit_reason = reason;
3384   if ((rc = acl_check(ACL_WHERE_NOTQUIT, NULL, acl_smtp_notquit, &user_msg,
3385                       &log_msg)) == ERROR)
3386     log_write(0, LOG_MAIN|LOG_PANIC, "ACL for not-QUIT returned ERROR: %s",
3387       log_msg);
3388   }
3389
3390 /* Write an SMTP response if we are expected to give one. As the default
3391 responses are all internal, they should always fit in the buffer, but code a
3392 warning, just in case. Note that string_vformat() still leaves a complete
3393 string, even if it is incomplete. */
3394
3395 if (code && defaultrespond)
3396   {
3397   if (user_msg)
3398     smtp_respond(code, 3, TRUE, user_msg);
3399   else
3400     {
3401     uschar buffer[128];
3402     va_list ap;
3403     va_start(ap, defaultrespond);
3404     if (!string_vformat(buffer, sizeof(buffer), CS defaultrespond, ap))
3405       log_write(0, LOG_MAIN|LOG_PANIC, "string too large in smtp_notquit_exit()");
3406     smtp_printf("%s %s\r\n", FALSE, code, buffer);
3407     va_end(ap);
3408     }
3409   mac_smtp_fflush();
3410   }
3411 }
3412
3413
3414
3415
3416 /*************************************************
3417 *             Verify HELO argument               *
3418 *************************************************/
3419
3420 /* This function is called if helo_verify_hosts or helo_try_verify_hosts is
3421 matched. It is also called from ACL processing if verify = helo is used and
3422 verification was not previously tried (i.e. helo_try_verify_hosts was not
3423 matched). The result of its processing is to set helo_verified and
3424 helo_verify_failed. These variables should both be FALSE for this function to
3425 be called.
3426
3427 Note that EHLO/HELO is legitimately allowed to quote an address literal. Allow
3428 for IPv6 ::ffff: literals.
3429
3430 Argument:   none
3431 Returns:    TRUE if testing was completed;
3432             FALSE on a temporary failure
3433 */
3434
3435 BOOL
3436 smtp_verify_helo(void)
3437 {
3438 BOOL yield = TRUE;
3439
3440 HDEBUG(D_receive) debug_printf("verifying EHLO/HELO argument \"%s\"\n",
3441   sender_helo_name);
3442
3443 if (sender_helo_name == NULL)
3444   {
3445   HDEBUG(D_receive) debug_printf("no EHLO/HELO command was issued\n");
3446   }
3447
3448 /* Deal with the case of -bs without an IP address */
3449
3450 else if (sender_host_address == NULL)
3451   {
3452   HDEBUG(D_receive) debug_printf("no client IP address: assume success\n");
3453   helo_verified = TRUE;
3454   }
3455
3456 /* Deal with the more common case when there is a sending IP address */
3457
3458 else if (sender_helo_name[0] == '[')
3459   {
3460   helo_verified = Ustrncmp(sender_helo_name+1, sender_host_address,
3461     Ustrlen(sender_host_address)) == 0;
3462
3463   #if HAVE_IPV6
3464   if (!helo_verified)
3465     {
3466     if (strncmpic(sender_host_address, US"::ffff:", 7) == 0)
3467       helo_verified = Ustrncmp(sender_helo_name + 1,
3468         sender_host_address + 7, Ustrlen(sender_host_address) - 7) == 0;
3469     }
3470   #endif
3471
3472   HDEBUG(D_receive)
3473     { if (helo_verified) debug_printf("matched host address\n"); }
3474   }
3475
3476 /* Do a reverse lookup if one hasn't already given a positive or negative
3477 response. If that fails, or the name doesn't match, try checking with a forward
3478 lookup. */
3479
3480 else
3481   {
3482   if (sender_host_name == NULL && !host_lookup_failed)
3483     yield = host_name_lookup() != DEFER;
3484
3485   /* If a host name is known, check it and all its aliases. */
3486
3487   if (sender_host_name)
3488     if ((helo_verified = strcmpic(sender_host_name, sender_helo_name) == 0))
3489       {
3490       sender_helo_dnssec = sender_host_dnssec;
3491       HDEBUG(D_receive) debug_printf("matched host name\n");
3492       }
3493     else
3494       {
3495       uschar **aliases = sender_host_aliases;
3496       while (*aliases)
3497         if ((helo_verified = strcmpic(*aliases++, sender_helo_name) == 0))
3498           {
3499           sender_helo_dnssec = sender_host_dnssec;
3500           break;
3501           }
3502
3503       HDEBUG(D_receive) if (helo_verified)
3504           debug_printf("matched alias %s\n", *(--aliases));
3505       }
3506
3507   /* Final attempt: try a forward lookup of the helo name */
3508
3509   if (!helo_verified)
3510     {
3511     int rc;
3512     host_item h;
3513     dnssec_domains d;
3514     host_item *hh;
3515
3516     h.name = sender_helo_name;
3517     h.address = NULL;
3518     h.mx = MX_NONE;
3519     h.next = NULL;
3520     d.request = US"*";
3521     d.require = US"";
3522
3523     HDEBUG(D_receive) debug_printf("getting IP address for %s\n",
3524       sender_helo_name);
3525     rc = host_find_bydns(&h, NULL, HOST_FIND_BY_A | HOST_FIND_BY_AAAA,
3526                           NULL, NULL, NULL, &d, NULL, NULL);
3527     if (rc == HOST_FOUND || rc == HOST_FOUND_LOCAL)
3528       for (hh = &h; hh; hh = hh->next)
3529         if (Ustrcmp(hh->address, sender_host_address) == 0)
3530           {
3531           helo_verified = TRUE;
3532           if (h.dnssec == DS_YES) sender_helo_dnssec = TRUE;
3533           HDEBUG(D_receive)
3534             {
3535             debug_printf("IP address for %s matches calling address\n"
3536               "Forward DNS security status: %sverified\n",
3537               sender_helo_name, sender_helo_dnssec ? "" : "un");
3538             }
3539           break;
3540           }
3541     }
3542   }
3543
3544 if (!helo_verified) helo_verify_failed = TRUE;  /* We've tried ... */
3545 return yield;
3546 }
3547
3548
3549
3550
3551 /*************************************************
3552 *        Send user response message              *
3553 *************************************************/
3554
3555 /* This function is passed a default response code and a user message. It calls
3556 smtp_message_code() to check and possibly modify the response code, and then
3557 calls smtp_respond() to transmit the response. I put this into a function
3558 just to avoid a lot of repetition.
3559
3560 Arguments:
3561   code         the response code
3562   user_msg     the user message
3563
3564 Returns:       nothing
3565 */
3566
3567 static void
3568 smtp_user_msg(uschar *code, uschar *user_msg)
3569 {
3570 int len = 3;
3571 smtp_message_code(&code, &len, &user_msg, NULL, TRUE);
3572 smtp_respond(code, len, TRUE, user_msg);
3573 }
3574
3575
3576
3577 static int
3578 smtp_in_auth(auth_instance *au, uschar ** s, uschar ** ss)
3579 {
3580 const uschar *set_id = NULL;
3581 int rc, i;
3582
3583 /* Run the checking code, passing the remainder of the command line as
3584 data. Initials the $auth<n> variables as empty. Initialize $0 empty and set
3585 it as the only set numerical variable. The authenticator may set $auth<n>
3586 and also set other numeric variables. The $auth<n> variables are preferred
3587 nowadays; the numerical variables remain for backwards compatibility.
3588
3589 Afterwards, have a go at expanding the set_id string, even if
3590 authentication failed - for bad passwords it can be useful to log the
3591 userid. On success, require set_id to expand and exist, and put it in
3592 authenticated_id. Save this in permanent store, as the working store gets
3593 reset at HELO, RSET, etc. */
3594
3595 for (i = 0; i < AUTH_VARS; i++) auth_vars[i] = NULL;
3596 expand_nmax = 0;
3597 expand_nlength[0] = 0;   /* $0 contains nothing */
3598
3599 rc = (au->info->servercode)(au, smtp_cmd_data);
3600 if (au->set_id) set_id = expand_string(au->set_id);
3601 expand_nmax = -1;        /* Reset numeric variables */
3602 for (i = 0; i < AUTH_VARS; i++) auth_vars[i] = NULL;   /* Reset $auth<n> */
3603
3604 /* The value of authenticated_id is stored in the spool file and printed in
3605 log lines. It must not contain binary zeros or newline characters. In
3606 normal use, it never will, but when playing around or testing, this error
3607 can (did) happen. To guard against this, ensure that the id contains only
3608 printing characters. */
3609
3610 if (set_id) set_id = string_printing(set_id);
3611
3612 /* For the non-OK cases, set up additional logging data if set_id
3613 is not empty. */
3614
3615 if (rc != OK)
3616   set_id = set_id && *set_id
3617     ? string_sprintf(" (set_id=%s)", set_id) : US"";
3618
3619 /* Switch on the result */
3620
3621 switch(rc)
3622   {
3623   case OK:
3624   if (!au->set_id || set_id)    /* Complete success */
3625     {
3626     if (set_id) authenticated_id = string_copy_malloc(set_id);
3627     sender_host_authenticated = au->name;
3628     sender_host_auth_pubname  = au->public_name;
3629     authentication_failed = FALSE;
3630     authenticated_fail_id = NULL;   /* Impossible to already be set? */
3631
3632     received_protocol =
3633       (sender_host_address ? protocols : protocols_local)
3634         [pextend + pauthed + (tls_in.active >= 0 ? pcrpted:0)];
3635     *s = *ss = US"235 Authentication succeeded";
3636     authenticated_by = au;
3637     break;
3638     }
3639
3640   /* Authentication succeeded, but we failed to expand the set_id string.
3641   Treat this as a temporary error. */
3642
3643   auth_defer_msg = expand_string_message;
3644   /* Fall through */
3645
3646   case DEFER:
3647   if (set_id) authenticated_fail_id = string_copy_malloc(set_id);
3648   *s = string_sprintf("435 Unable to authenticate at present%s",
3649     auth_defer_user_msg);
3650   *ss = string_sprintf("435 Unable to authenticate at present%s: %s",
3651     set_id, auth_defer_msg);
3652   break;
3653
3654   case BAD64:
3655   *s = *ss = US"501 Invalid base64 data";
3656   break;
3657
3658   case CANCELLED:
3659   *s = *ss = US"501 Authentication cancelled";
3660   break;
3661
3662   case UNEXPECTED:
3663   *s = *ss = US"553 Initial data not expected";
3664   break;
3665
3666   case FAIL:
3667   if (set_id) authenticated_fail_id = string_copy_malloc(set_id);
3668   *s = US"535 Incorrect authentication data";
3669   *ss = string_sprintf("535 Incorrect authentication data%s", set_id);
3670   break;
3671
3672   default:
3673   if (set_id) authenticated_fail_id = string_copy_malloc(set_id);
3674   *s = US"435 Internal error";
3675   *ss = string_sprintf("435 Internal error%s: return %d from authentication "
3676     "check", set_id, rc);
3677   break;
3678   }
3679
3680 return rc;
3681 }
3682
3683
3684
3685
3686
3687 static int
3688 qualify_recipient(uschar ** recipient, uschar * smtp_cmd_data, uschar * tag)
3689 {
3690 int rd;
3691 if (allow_unqualified_recipient || strcmpic(*recipient, US"postmaster") == 0)
3692   {
3693   DEBUG(D_receive) debug_printf("unqualified address %s accepted\n",
3694     *recipient);
3695   rd = Ustrlen(recipient) + 1;
3696   *recipient = rewrite_address_qualify(*recipient, TRUE);
3697   return rd;
3698   }
3699 smtp_printf("501 %s: recipient address must contain a domain\r\n", FALSE,
3700   smtp_cmd_data);
3701 log_write(L_smtp_syntax_error,
3702   LOG_MAIN|LOG_REJECT, "unqualified %s rejected: <%s> %s%s",
3703   tag, *recipient, host_and_ident(TRUE), host_lookup_msg);
3704 return 0;
3705 }
3706
3707
3708
3709
3710 static void
3711 smtp_quit_handler(uschar ** user_msgp, uschar ** log_msgp)
3712 {
3713 HAD(SCH_QUIT);
3714 incomplete_transaction_log(US"QUIT");
3715 if (acl_smtp_quit)
3716   {
3717   int rc = acl_check(ACL_WHERE_QUIT, NULL, acl_smtp_quit, user_msgp, log_msgp);
3718   if (rc == ERROR)
3719     log_write(0, LOG_MAIN|LOG_PANIC, "ACL for QUIT returned ERROR: %s",
3720       *log_msgp);
3721   }
3722 if (*user_msgp)
3723   smtp_respond(US"221", 3, TRUE, *user_msgp);
3724 else
3725   smtp_printf("221 %s closing connection\r\n", FALSE, smtp_active_hostname);
3726
3727 #ifdef SUPPORT_TLS
3728 tls_close(TRUE, TLS_SHUTDOWN_NOWAIT);
3729 #endif
3730
3731 log_write(L_smtp_connection, LOG_MAIN, "%s closed by QUIT",
3732   smtp_get_connection_info());
3733 }
3734
3735
3736 static void
3737 smtp_rset_handler(void)
3738 {
3739 HAD(SCH_RSET);
3740 incomplete_transaction_log(US"RSET");
3741 smtp_printf("250 Reset OK\r\n", FALSE);
3742 cmd_list[CMD_LIST_RSET].is_mail_cmd = FALSE;
3743 }
3744
3745
3746
3747 /*************************************************
3748 *       Initialize for SMTP incoming message     *
3749 *************************************************/
3750
3751 /* This function conducts the initial dialogue at the start of an incoming SMTP
3752 message, and builds a list of recipients. However, if the incoming message
3753 is part of a batch (-bS option) a separate function is called since it would
3754 be messy having tests splattered about all over this function. This function
3755 therefore handles the case where interaction is occurring. The input and output
3756 files are set up in smtp_in and smtp_out.
3757
3758 The global recipients_list is set to point to a vector of recipient_item
3759 blocks, whose number is given by recipients_count. This is extended by the
3760 receive_add_recipient() function. The global variable sender_address is set to
3761 the sender's address. The yield is +1 if a message has been successfully
3762 started, 0 if a QUIT command was encountered or the connection was refused from
3763 the particular host, or -1 if the connection was lost.
3764
3765 Argument: none
3766
3767 Returns:  > 0 message successfully started (reached DATA)
3768           = 0 QUIT read or end of file reached or call refused
3769           < 0 lost connection
3770 */
3771
3772 int
3773 smtp_setup_msg(void)
3774 {
3775 int done = 0;
3776 BOOL toomany = FALSE;
3777 BOOL discarded = FALSE;
3778 BOOL last_was_rej_mail = FALSE;
3779 BOOL last_was_rcpt = FALSE;
3780 void *reset_point = store_get(0);
3781
3782 DEBUG(D_receive) debug_printf("smtp_setup_msg entered\n");
3783
3784 /* Reset for start of new message. We allow one RSET not to be counted as a
3785 nonmail command, for those MTAs that insist on sending it between every
3786 message. Ditto for EHLO/HELO and for STARTTLS, to allow for going in and out of
3787 TLS between messages (an Exim client may do this if it has messages queued up
3788 for the host). Note: we do NOT reset AUTH at this point. */
3789
3790 smtp_reset(reset_point);
3791 message_ended = END_NOTSTARTED;
3792
3793 chunking_state = chunking_offered ? CHUNKING_OFFERED : CHUNKING_NOT_OFFERED;
3794
3795 cmd_list[CMD_LIST_RSET].is_mail_cmd = TRUE;
3796 cmd_list[CMD_LIST_HELO].is_mail_cmd = TRUE;
3797 cmd_list[CMD_LIST_EHLO].is_mail_cmd = TRUE;
3798 #ifdef SUPPORT_TLS
3799 cmd_list[CMD_LIST_STARTTLS].is_mail_cmd = TRUE;
3800 #endif
3801
3802 /* Set the local signal handler for SIGTERM - it tries to end off tidily */
3803
3804 os_non_restarting_signal(SIGTERM, command_sigterm_handler);
3805
3806 /* Batched SMTP is handled in a different function. */
3807
3808 if (smtp_batched_input) return smtp_setup_batch_msg();
3809
3810 /* Deal with SMTP commands. This loop is exited by setting done to a POSITIVE
3811 value. The values are 2 larger than the required yield of the function. */
3812
3813 while (done <= 0)
3814   {
3815   const uschar **argv;
3816   uschar *etrn_command;
3817   uschar *etrn_serialize_key;
3818   uschar *errmess;
3819   uschar *log_msg, *smtp_code;
3820   uschar *user_msg = NULL;
3821   uschar *recipient = NULL;
3822   uschar *hello = NULL;
3823   uschar *s, *ss;
3824   BOOL was_rej_mail = FALSE;
3825   BOOL was_rcpt = FALSE;
3826   void (*oldsignal)(int);
3827   pid_t pid;
3828   int start, end, sender_domain, recipient_domain;
3829   int rc;
3830   int c;
3831   auth_instance *au;
3832   uschar *orcpt = NULL;
3833   int flags;
3834   gstring * g;
3835
3836 #ifdef AUTH_TLS
3837   /* Check once per STARTTLS or SSL-on-connect for a TLS AUTH */
3838   if (  tls_in.active >= 0
3839      && tls_in.peercert
3840      && tls_in.certificate_verified
3841      && cmd_list[CMD_LIST_TLS_AUTH].is_mail_cmd
3842      )
3843     {
3844     cmd_list[CMD_LIST_TLS_AUTH].is_mail_cmd = FALSE;
3845
3846     for (au = auths; au; au = au->next)
3847       if (strcmpic(US"tls", au->driver_name) == 0)
3848         {
3849         if (  acl_smtp_auth
3850            && (rc = acl_check(ACL_WHERE_AUTH, NULL, acl_smtp_auth,
3851                       &user_msg, &log_msg)) != OK
3852            )
3853           done = smtp_handle_acl_fail(ACL_WHERE_AUTH, rc, user_msg, log_msg);
3854         else
3855           {
3856           smtp_cmd_data = NULL;
3857
3858           if (smtp_in_auth(au, &s, &ss) == OK)
3859             { DEBUG(D_auth) debug_printf("tls auth succeeded\n"); }
3860           else
3861             { DEBUG(D_auth) debug_printf("tls auth not succeeded\n"); }
3862           }
3863         break;
3864         }
3865     }
3866 #endif
3867
3868 #ifdef TCP_QUICKACK
3869   if (smtp_in)          /* Avoid pure-ACKs while in cmd pingpong phase */
3870     (void) setsockopt(fileno(smtp_in), IPPROTO_TCP, TCP_QUICKACK,
3871             US &off, sizeof(off));
3872 #endif
3873
3874   switch(smtp_read_command(TRUE, GETC_BUFFER_UNLIMITED))
3875     {
3876     /* The AUTH command is not permitted to occur inside a transaction, and may
3877     occur successfully only once per connection. Actually, that isn't quite
3878     true. When TLS is started, all previous information about a connection must
3879     be discarded, so a new AUTH is permitted at that time.
3880
3881     AUTH may only be used when it has been advertised. However, it seems that
3882     there are clients that send AUTH when it hasn't been advertised, some of
3883     them even doing this after HELO. And there are MTAs that accept this. Sigh.
3884     So there's a get-out that allows this to happen.
3885
3886     AUTH is initially labelled as a "nonmail command" so that one occurrence
3887     doesn't get counted. We change the label here so that multiple failing
3888     AUTHS will eventually hit the nonmail threshold. */
3889
3890     case AUTH_CMD:
3891     HAD(SCH_AUTH);
3892     authentication_failed = TRUE;
3893     cmd_list[CMD_LIST_AUTH].is_mail_cmd = FALSE;
3894
3895     if (!auth_advertised && !allow_auth_unadvertised)
3896       {
3897       done = synprot_error(L_smtp_protocol_error, 503, NULL,
3898         US"AUTH command used when not advertised");
3899       break;
3900       }
3901     if (sender_host_authenticated)
3902       {
3903       done = synprot_error(L_smtp_protocol_error, 503, NULL,
3904         US"already authenticated");
3905       break;
3906       }
3907     if (sender_address)
3908       {
3909       done = synprot_error(L_smtp_protocol_error, 503, NULL,
3910         US"not permitted in mail transaction");
3911       break;
3912       }
3913
3914     /* Check the ACL */
3915
3916     if (  acl_smtp_auth
3917        && (rc = acl_check(ACL_WHERE_AUTH, NULL, acl_smtp_auth,
3918                   &user_msg, &log_msg)) != OK
3919        )
3920       {
3921       done = smtp_handle_acl_fail(ACL_WHERE_AUTH, rc, user_msg, log_msg);
3922       break;
3923       }
3924
3925     /* Find the name of the requested authentication mechanism. */
3926
3927     s = smtp_cmd_data;
3928     while ((c = *smtp_cmd_data) != 0 && !isspace(c))
3929       {
3930       if (!isalnum(c) && c != '-' && c != '_')
3931         {
3932         done = synprot_error(L_smtp_syntax_error, 501, NULL,
3933           US"invalid character in authentication mechanism name");
3934         goto COMMAND_LOOP;
3935         }
3936       smtp_cmd_data++;
3937       }
3938
3939     /* If not at the end of the line, we must be at white space. Terminate the
3940     name and move the pointer on to any data that may be present. */
3941
3942     if (*smtp_cmd_data != 0)
3943       {
3944       *smtp_cmd_data++ = 0;
3945       while (isspace(*smtp_cmd_data)) smtp_cmd_data++;
3946       }
3947
3948     /* Search for an authentication mechanism which is configured for use
3949     as a server and which has been advertised (unless, sigh, allow_auth_
3950     unadvertised is set). */
3951
3952     for (au = auths; au; au = au->next)
3953       if (strcmpic(s, au->public_name) == 0 && au->server &&
3954           (au->advertised || allow_auth_unadvertised))
3955         break;
3956
3957     if (au)
3958       {
3959       c = smtp_in_auth(au, &s, &ss);
3960
3961       smtp_printf("%s\r\n", FALSE, s);
3962       if (c != OK)
3963         log_write(0, LOG_MAIN|LOG_REJECT, "%s authenticator failed for %s: %s",
3964           au->name, host_and_ident(FALSE), ss);
3965       }
3966     else
3967       done = synprot_error(L_smtp_protocol_error, 504, NULL,
3968         string_sprintf("%s authentication mechanism not supported", s));
3969
3970     break;  /* AUTH_CMD */
3971
3972     /* The HELO/EHLO commands are permitted to appear in the middle of a
3973     session as well as at the beginning. They have the effect of a reset in
3974     addition to their other functions. Their absence at the start cannot be
3975     taken to be an error.
3976
3977     RFC 2821 says:
3978
3979       If the EHLO command is not acceptable to the SMTP server, 501, 500,
3980       or 502 failure replies MUST be returned as appropriate.  The SMTP
3981       server MUST stay in the same state after transmitting these replies
3982       that it was in before the EHLO was received.
3983
3984     Therefore, we do not do the reset until after checking the command for
3985     acceptability. This change was made for Exim release 4.11. Previously
3986     it did the reset first. */
3987
3988     case HELO_CMD:
3989     HAD(SCH_HELO);
3990     hello = US"HELO";
3991     esmtp = FALSE;
3992     goto HELO_EHLO;
3993
3994     case EHLO_CMD:
3995     HAD(SCH_EHLO);
3996     hello = US"EHLO";
3997     esmtp = TRUE;
3998
3999     HELO_EHLO:      /* Common code for HELO and EHLO */
4000     cmd_list[CMD_LIST_HELO].is_mail_cmd = FALSE;
4001     cmd_list[CMD_LIST_EHLO].is_mail_cmd = FALSE;
4002
4003     /* Reject the HELO if its argument was invalid or non-existent. A
4004     successful check causes the argument to be saved in malloc store. */
4005
4006     if (!check_helo(smtp_cmd_data))
4007       {
4008       smtp_printf("501 Syntactically invalid %s argument(s)\r\n", FALSE, hello);
4009
4010       log_write(0, LOG_MAIN|LOG_REJECT, "rejected %s from %s: syntactically "
4011         "invalid argument(s): %s", hello, host_and_ident(FALSE),
4012         (*smtp_cmd_argument == 0)? US"(no argument given)" :
4013                            string_printing(smtp_cmd_argument));
4014
4015       if (++synprot_error_count > smtp_max_synprot_errors)
4016         {
4017         log_write(0, LOG_MAIN|LOG_REJECT, "SMTP call from %s dropped: too many "
4018           "syntax or protocol errors (last command was \"%s\")",
4019           host_and_ident(FALSE), string_printing(smtp_cmd_buffer));
4020         done = 1;
4021         }
4022
4023       break;
4024       }
4025
4026     /* If sender_host_unknown is true, we have got here via the -bs interface,
4027     not called from inetd. Otherwise, we are running an IP connection and the
4028     host address will be set. If the helo name is the primary name of this
4029     host and we haven't done a reverse lookup, force one now. If helo_required
4030     is set, ensure that the HELO name matches the actual host. If helo_verify
4031     is set, do the same check, but softly. */
4032
4033     if (!sender_host_unknown)
4034       {
4035       BOOL old_helo_verified = helo_verified;
4036       uschar *p = smtp_cmd_data;
4037
4038       while (*p != 0 && !isspace(*p)) { *p = tolower(*p); p++; }
4039       *p = 0;
4040
4041       /* Force a reverse lookup if HELO quoted something in helo_lookup_domains
4042       because otherwise the log can be confusing. */
4043
4044       if (  !sender_host_name
4045          && (deliver_domain = sender_helo_name,  /* set $domain */
4046              match_isinlist(sender_helo_name, CUSS &helo_lookup_domains, 0,
4047               &domainlist_anchor, NULL, MCL_DOMAIN, TRUE, NULL)) == OK)
4048         (void)host_name_lookup();
4049
4050       /* Rebuild the fullhost info to include the HELO name (and the real name
4051       if it was looked up.) */
4052
4053       host_build_sender_fullhost();  /* Rebuild */
4054       set_process_info("handling%s incoming connection from %s",
4055         (tls_in.active >= 0)? " TLS" : "", host_and_ident(FALSE));
4056
4057       /* Verify if configured. This doesn't give much security, but it does
4058       make some people happy to be able to do it. If helo_required is set,
4059       (host matches helo_verify_hosts) failure forces rejection. If helo_verify
4060       is set (host matches helo_try_verify_hosts), it does not. This is perhaps
4061       now obsolescent, since the verification can now be requested selectively
4062       at ACL time. */
4063
4064       helo_verified = helo_verify_failed = sender_helo_dnssec = FALSE;
4065       if (helo_required || helo_verify)
4066         {
4067         BOOL tempfail = !smtp_verify_helo();
4068         if (!helo_verified)
4069           {
4070           if (helo_required)
4071             {
4072             smtp_printf("%d %s argument does not match calling host\r\n", FALSE,
4073               tempfail? 451 : 550, hello);
4074             log_write(0, LOG_MAIN|LOG_REJECT, "%srejected \"%s %s\" from %s",
4075               tempfail? "temporarily " : "",
4076               hello, sender_helo_name, host_and_ident(FALSE));
4077             helo_verified = old_helo_verified;
4078             break;                   /* End of HELO/EHLO processing */
4079             }
4080           HDEBUG(D_all) debug_printf("%s verification failed but host is in "
4081             "helo_try_verify_hosts\n", hello);
4082           }
4083         }
4084       }
4085
4086 #ifdef SUPPORT_SPF
4087     /* set up SPF context */
4088     spf_init(sender_helo_name, sender_host_address);
4089 #endif
4090
4091     /* Apply an ACL check if one is defined; afterwards, recheck
4092     synchronization in case the client started sending in a delay. */
4093
4094     if (acl_smtp_helo)
4095       if ((rc = acl_check(ACL_WHERE_HELO, NULL, acl_smtp_helo,
4096                 &user_msg, &log_msg)) != OK)
4097         {
4098         done = smtp_handle_acl_fail(ACL_WHERE_HELO, rc, user_msg, log_msg);
4099         if (sender_helo_name)
4100           {
4101           store_free(sender_helo_name);
4102           sender_helo_name = NULL;
4103           }
4104         host_build_sender_fullhost();  /* Rebuild */
4105         break;
4106         }
4107       else if (!check_sync()) goto SYNC_FAILURE;
4108
4109     /* Generate an OK reply. The default string includes the ident if present,
4110     and also the IP address if present. Reflecting back the ident is intended
4111     as a deterrent to mail forgers. For maximum efficiency, and also because
4112     some broken systems expect each response to be in a single packet, arrange
4113     that the entire reply is sent in one write(). */
4114
4115     auth_advertised = FALSE;
4116     pipelining_advertised = FALSE;
4117 #ifdef SUPPORT_TLS
4118     tls_advertised = FALSE;
4119 #endif
4120     dsn_advertised = FALSE;
4121 #ifdef SUPPORT_I18N
4122     smtputf8_advertised = FALSE;
4123 #endif
4124
4125     smtp_code = US"250 ";        /* Default response code plus space*/
4126     if (!user_msg)
4127       {
4128       s = string_sprintf("%.3s %s Hello %s%s%s",
4129         smtp_code,
4130         smtp_active_hostname,
4131         sender_ident ? sender_ident : US"",
4132         sender_ident ? US" at " : US"",
4133         sender_host_name ? sender_host_name : sender_helo_name);
4134       g = string_cat(NULL, s);
4135
4136       if (sender_host_address)
4137         {
4138         g = string_catn(g, US" [", 2);
4139         g = string_cat (g, sender_host_address);
4140         g = string_catn(g, US"]", 1);
4141         }
4142       }
4143
4144     /* A user-supplied EHLO greeting may not contain more than one line. Note
4145     that the code returned by smtp_message_code() includes the terminating
4146     whitespace character. */
4147
4148     else
4149       {
4150       char *ss;
4151       int codelen = 4;
4152       smtp_message_code(&smtp_code, &codelen, &user_msg, NULL, TRUE);
4153       s = string_sprintf("%.*s%s", codelen, smtp_code, user_msg);
4154       if ((ss = strpbrk(CS s, "\r\n")) != NULL)
4155         {
4156         log_write(0, LOG_MAIN|LOG_PANIC, "EHLO/HELO response must not contain "
4157           "newlines: message truncated: %s", string_printing(s));
4158         *ss = 0;
4159         }
4160       g = string_cat(NULL, s);
4161       }
4162
4163     g = string_catn(g, US"\r\n", 2);
4164
4165     /* If we received EHLO, we must create a multiline response which includes
4166     the functions supported. */
4167
4168     if (esmtp)
4169       {
4170       g->s[3] = '-';
4171
4172       /* I'm not entirely happy with this, as an MTA is supposed to check
4173       that it has enough room to accept a message of maximum size before
4174       it sends this. However, there seems little point in not sending it.
4175       The actual size check happens later at MAIL FROM time. By postponing it
4176       till then, VRFY and EXPN can be used after EHLO when space is short. */
4177
4178       if (thismessage_size_limit > 0)
4179         {
4180         sprintf(CS big_buffer, "%.3s-SIZE %d\r\n", smtp_code,
4181           thismessage_size_limit);
4182         g = string_cat(g, big_buffer);
4183         }
4184       else
4185         {
4186         g = string_catn(g, smtp_code, 3);
4187         g = string_catn(g, US"-SIZE\r\n", 7);
4188         }
4189
4190       /* Exim does not do protocol conversion or data conversion. It is 8-bit
4191       clean; if it has an 8-bit character in its hand, it just sends it. It
4192       cannot therefore specify 8BITMIME and remain consistent with the RFCs.
4193       However, some users want this option simply in order to stop MUAs
4194       mangling messages that contain top-bit-set characters. It is therefore
4195       provided as an option. */
4196
4197       if (accept_8bitmime)
4198         {
4199         g = string_catn(g, smtp_code, 3);
4200         g = string_catn(g, US"-8BITMIME\r\n", 11);
4201         }
4202
4203       /* Advertise DSN support if configured to do so. */
4204       if (verify_check_host(&dsn_advertise_hosts) != FAIL)
4205         {
4206         g = string_catn(g, smtp_code, 3);
4207         g = string_catn(g, US"-DSN\r\n", 6);
4208         dsn_advertised = TRUE;
4209         }
4210
4211       /* Advertise ETRN/VRFY/EXPN if there's are ACL checking whether a host is
4212       permitted to issue them; a check is made when any host actually tries. */
4213
4214       if (acl_smtp_etrn)
4215         {
4216         g = string_catn(g, smtp_code, 3);
4217         g = string_catn(g, US"-ETRN\r\n", 7);
4218         }
4219       if (acl_smtp_vrfy)
4220         {
4221         g = string_catn(g, smtp_code, 3);
4222         g = string_catn(g, US"-VRFY\r\n", 7);
4223         }
4224       if (acl_smtp_expn)
4225         {
4226         g = string_catn(g, smtp_code, 3);
4227         g = string_catn(g, US"-EXPN\r\n", 7);
4228         }
4229
4230       /* Exim is quite happy with pipelining, so let the other end know that
4231       it is safe to use it, unless advertising is disabled. */
4232
4233       if (pipelining_enable &&
4234           verify_check_host(&pipelining_advertise_hosts) == OK)
4235         {
4236         g = string_catn(g, smtp_code, 3);
4237         g = string_catn(g, US"-PIPELINING\r\n", 13);
4238         sync_cmd_limit = NON_SYNC_CMD_PIPELINING;
4239         pipelining_advertised = TRUE;
4240         }
4241
4242
4243       /* If any server authentication mechanisms are configured, advertise
4244       them if the current host is in auth_advertise_hosts. The problem with
4245       advertising always is that some clients then require users to
4246       authenticate (and aren't configurable otherwise) even though it may not
4247       be necessary (e.g. if the host is in host_accept_relay).
4248
4249       RFC 2222 states that SASL mechanism names contain only upper case
4250       letters, so output the names in upper case, though we actually recognize
4251       them in either case in the AUTH command. */
4252
4253       if (  auths
4254 #ifdef AUTH_TLS
4255          && !sender_host_authenticated
4256 #endif
4257          && verify_check_host(&auth_advertise_hosts) == OK
4258          )
4259         {
4260         auth_instance *au;
4261         BOOL first = TRUE;
4262         for (au = auths; au; au = au->next)
4263           {
4264           au->advertised = FALSE;
4265           if (au->server)
4266             {
4267             DEBUG(D_auth+D_expand) debug_printf_indent(
4268               "Evaluating advertise_condition for %s athenticator\n",
4269               au->public_name);
4270             if (  !au->advertise_condition
4271                || expand_check_condition(au->advertise_condition, au->name,
4272                       US"authenticator")
4273                )
4274               {
4275               int saveptr;
4276               if (first)
4277                 {
4278                 g = string_catn(g, smtp_code, 3);
4279                 g = string_catn(g, US"-AUTH", 5);
4280                 first = FALSE;
4281                 auth_advertised = TRUE;
4282                 }
4283               saveptr = g->ptr;
4284               g = string_catn(g, US" ", 1);
4285               g = string_cat (g, au->public_name);
4286               while (++saveptr < g->ptr) g->s[saveptr] = toupper(g->s[saveptr]);
4287               au->advertised = TRUE;
4288               }
4289             }
4290           }
4291
4292         if (!first) g = string_catn(g, US"\r\n", 2);
4293         }
4294
4295       /* RFC 3030 CHUNKING */
4296
4297       if (verify_check_host(&chunking_advertise_hosts) != FAIL)
4298         {
4299         g = string_catn(g, smtp_code, 3);
4300         g = string_catn(g, US"-CHUNKING\r\n", 11);
4301         chunking_offered = TRUE;
4302         chunking_state = CHUNKING_OFFERED;
4303         }
4304
4305       /* Advertise TLS (Transport Level Security) aka SSL (Secure Socket Layer)
4306       if it has been included in the binary, and the host matches
4307       tls_advertise_hosts. We must *not* advertise if we are already in a
4308       secure connection. */
4309
4310 #ifdef SUPPORT_TLS
4311       if (tls_in.active < 0 &&
4312           verify_check_host(&tls_advertise_hosts) != FAIL)
4313         {
4314         g = string_catn(g, smtp_code, 3);
4315         g = string_catn(g, US"-STARTTLS\r\n", 11);
4316         tls_advertised = TRUE;
4317         }
4318 #endif
4319
4320 #ifndef DISABLE_PRDR
4321       /* Per Recipient Data Response, draft by Eric A. Hall extending RFC */
4322       if (prdr_enable)
4323         {
4324         g = string_catn(g, smtp_code, 3);
4325         g = string_catn(g, US"-PRDR\r\n", 7);
4326         }
4327 #endif
4328
4329 #ifdef SUPPORT_I18N
4330       if (  accept_8bitmime
4331          && verify_check_host(&smtputf8_advertise_hosts) != FAIL)
4332         {
4333         g = string_catn(g, smtp_code, 3);
4334         g = string_catn(g, US"-SMTPUTF8\r\n", 11);
4335         smtputf8_advertised = TRUE;
4336         }
4337 #endif
4338
4339       /* Finish off the multiline reply with one that is always available. */
4340
4341       g = string_catn(g, smtp_code, 3);
4342       g = string_catn(g, US" HELP\r\n", 7);
4343       }
4344
4345     /* Terminate the string (for debug), write it, and note that HELO/EHLO
4346     has been seen. */
4347
4348 #ifdef SUPPORT_TLS
4349     if (tls_in.active >= 0) (void)tls_write(TRUE, g->s, g->ptr, FALSE); else
4350 #endif
4351
4352       {
4353       int i = fwrite(g->s, 1, g->ptr, smtp_out); i = i; /* compiler quietening */
4354       }
4355     DEBUG(D_receive)
4356       {
4357       uschar *cr;
4358
4359       (void) string_from_gstring(g);
4360       while ((cr = Ustrchr(g->s, '\r')) != NULL)   /* lose CRs */
4361         memmove(cr, cr + 1, (g->ptr--) - (cr - g->s));
4362       debug_printf("SMTP>> %s", g->s);
4363       }
4364     helo_seen = TRUE;
4365
4366     /* Reset the protocol and the state, abandoning any previous message. */
4367     received_protocol =
4368       (sender_host_address ? protocols : protocols_local)
4369         [ (esmtp
4370           ? pextend + (sender_host_authenticated ? pauthed : 0)
4371           : pnormal)
4372         + (tls_in.active >= 0 ? pcrpted : 0)
4373         ];
4374     cancel_cutthrough_connection(TRUE, US"sent EHLO response");
4375     smtp_reset(reset_point);
4376     toomany = FALSE;
4377     break;   /* HELO/EHLO */
4378
4379
4380     /* The MAIL command requires an address as an operand. All we do
4381     here is to parse it for syntactic correctness. The form "<>" is
4382     a special case which converts into an empty string. The start/end
4383     pointers in the original are not used further for this address, as
4384     it is the canonical extracted address which is all that is kept. */
4385
4386     case MAIL_CMD:
4387     HAD(SCH_MAIL);
4388     smtp_mailcmd_count++;              /* Count for limit and ratelimit */
4389     was_rej_mail = TRUE;               /* Reset if accepted */
4390     env_mail_type_t * mail_args;       /* Sanity check & validate args */
4391
4392     if (helo_required && !helo_seen)
4393       {
4394       smtp_printf("503 HELO or EHLO required\r\n", FALSE);
4395       log_write(0, LOG_MAIN|LOG_REJECT, "rejected MAIL from %s: no "
4396         "HELO/EHLO given", host_and_ident(FALSE));
4397       break;
4398       }
4399
4400     if (sender_address != NULL)
4401       {
4402       done = synprot_error(L_smtp_protocol_error, 503, NULL,
4403         US"sender already given");
4404       break;
4405       }
4406
4407     if (smtp_cmd_data[0] == 0)
4408       {
4409       done = synprot_error(L_smtp_protocol_error, 501, NULL,
4410         US"MAIL must have an address operand");
4411       break;
4412       }
4413
4414     /* Check to see if the limit for messages per connection would be
4415     exceeded by accepting further messages. */
4416
4417     if (smtp_accept_max_per_connection > 0 &&
4418         smtp_mailcmd_count > smtp_accept_max_per_connection)
4419       {
4420       smtp_printf("421 too many messages in this connection\r\n", FALSE);
4421       log_write(0, LOG_MAIN|LOG_REJECT, "rejected MAIL command %s: too many "
4422         "messages in one connection", host_and_ident(TRUE));
4423       break;
4424       }
4425
4426     /* Reset for start of message - even if this is going to fail, we
4427     obviously need to throw away any previous data. */
4428
4429     cancel_cutthrough_connection(TRUE, US"MAIL received");
4430     smtp_reset(reset_point);
4431     toomany = FALSE;
4432     sender_data = recipient_data = NULL;
4433
4434     /* Loop, checking for ESMTP additions to the MAIL FROM command. */
4435
4436     if (esmtp) for(;;)
4437       {
4438       uschar *name, *value, *end;
4439       unsigned long int size;
4440       BOOL arg_error = FALSE;
4441
4442       if (!extract_option(&name, &value)) break;
4443
4444       for (mail_args = env_mail_type_list;
4445            mail_args->value != ENV_MAIL_OPT_NULL;
4446            mail_args++
4447           )
4448         if (strcmpic(name, mail_args->name) == 0)
4449           break;
4450       if (mail_args->need_value && strcmpic(value, US"") == 0)
4451         break;
4452
4453       switch(mail_args->value)
4454         {
4455         /* Handle SIZE= by reading the value. We don't do the check till later,
4456         in order to be able to log the sender address on failure. */
4457         case ENV_MAIL_OPT_SIZE:
4458           if (((size = Ustrtoul(value, &end, 10)), *end == 0))
4459             {
4460             if ((size == ULONG_MAX && errno == ERANGE) || size > INT_MAX)
4461               size = INT_MAX;
4462             message_size = (int)size;
4463             }
4464           else
4465             arg_error = TRUE;
4466           break;
4467
4468         /* If this session was initiated with EHLO and accept_8bitmime is set,
4469         Exim will have indicated that it supports the BODY=8BITMIME option. In
4470         fact, it does not support this according to the RFCs, in that it does not
4471         take any special action for forwarding messages containing 8-bit
4472         characters. That is why accept_8bitmime is not the default setting, but
4473         some sites want the action that is provided. We recognize both "8BITMIME"
4474         and "7BIT" as body types, but take no action. */
4475         case ENV_MAIL_OPT_BODY:
4476           if (accept_8bitmime) {
4477             if (strcmpic(value, US"8BITMIME") == 0)
4478               body_8bitmime = 8;
4479             else if (strcmpic(value, US"7BIT") == 0)
4480               body_8bitmime = 7;
4481             else
4482               {
4483               body_8bitmime = 0;
4484               done = synprot_error(L_smtp_syntax_error, 501, NULL,
4485                 US"invalid data for BODY");
4486               goto COMMAND_LOOP;
4487               }
4488             DEBUG(D_receive) debug_printf("8BITMIME: %d\n", body_8bitmime);
4489             break;
4490           }
4491           arg_error = TRUE;
4492           break;
4493
4494         /* Handle the two DSN options, but only if configured to do so (which
4495         will have caused "DSN" to be given in the EHLO response). The code itself
4496         is included only if configured in at build time. */
4497
4498         case ENV_MAIL_OPT_RET:
4499           if (dsn_advertised)
4500             {
4501             /* Check if RET has already been set */
4502             if (dsn_ret > 0)
4503               {
4504               synprot_error(L_smtp_syntax_error, 501, NULL,
4505                 US"RET can be specified once only");
4506               goto COMMAND_LOOP;
4507               }
4508             dsn_ret = strcmpic(value, US"HDRS") == 0
4509               ? dsn_ret_hdrs
4510               : strcmpic(value, US"FULL") == 0
4511               ? dsn_ret_full
4512               : 0;
4513             DEBUG(D_receive) debug_printf("DSN_RET: %d\n", dsn_ret);
4514             /* Check for invalid invalid value, and exit with error */
4515             if (dsn_ret == 0)
4516               {
4517               synprot_error(L_smtp_syntax_error, 501, NULL,
4518                 US"Value for RET is invalid");
4519               goto COMMAND_LOOP;
4520               }
4521             }
4522           break;
4523         case ENV_MAIL_OPT_ENVID:
4524           if (dsn_advertised)
4525             {
4526             /* Check if the dsn envid has been already set */
4527             if (dsn_envid != NULL)
4528               {
4529               synprot_error(L_smtp_syntax_error, 501, NULL,
4530                 US"ENVID can be specified once only");
4531               goto COMMAND_LOOP;
4532               }
4533             dsn_envid = string_copy(value);
4534             DEBUG(D_receive) debug_printf("DSN_ENVID: %s\n", dsn_envid);
4535             }
4536           break;
4537
4538         /* Handle the AUTH extension. If the value given is not "<>" and either
4539         the ACL says "yes" or there is no ACL but the sending host is
4540         authenticated, we set it up as the authenticated sender. However, if the
4541         authenticator set a condition to be tested, we ignore AUTH on MAIL unless
4542         the condition is met. The value of AUTH is an xtext, which means that +,
4543         = and cntrl chars are coded in hex; however "<>" is unaffected by this
4544         coding. */
4545         case ENV_MAIL_OPT_AUTH:
4546           if (Ustrcmp(value, "<>") != 0)
4547             {
4548             int rc;
4549             uschar *ignore_msg;
4550
4551             if (auth_xtextdecode(value, &authenticated_sender) < 0)
4552               {
4553               /* Put back terminator overrides for error message */
4554               value[-1] = '=';
4555               name[-1] = ' ';
4556               done = synprot_error(L_smtp_syntax_error, 501, NULL,
4557                 US"invalid data for AUTH");
4558               goto COMMAND_LOOP;
4559               }
4560             if (!acl_smtp_mailauth)
4561               {
4562               ignore_msg = US"client not authenticated";
4563               rc = sender_host_authenticated ? OK : FAIL;
4564               }
4565             else
4566               {
4567               ignore_msg = US"rejected by ACL";
4568               rc = acl_check(ACL_WHERE_MAILAUTH, NULL, acl_smtp_mailauth,
4569                 &user_msg, &log_msg);
4570               }
4571
4572             switch (rc)
4573               {
4574               case OK:
4575                 if (authenticated_by == NULL ||
4576                     authenticated_by->mail_auth_condition == NULL ||
4577                     expand_check_condition(authenticated_by->mail_auth_condition,
4578                         authenticated_by->name, US"authenticator"))
4579                   break;     /* Accept the AUTH */
4580
4581                 ignore_msg = US"server_mail_auth_condition failed";
4582                 if (authenticated_id != NULL)
4583                   ignore_msg = string_sprintf("%s: authenticated ID=\"%s\"",
4584                     ignore_msg, authenticated_id);
4585
4586               /* Fall through */
4587
4588               case FAIL:
4589                 authenticated_sender = NULL;
4590                 log_write(0, LOG_MAIN, "ignoring AUTH=%s from %s (%s)",
4591                   value, host_and_ident(TRUE), ignore_msg);
4592                 break;
4593
4594               /* Should only get DEFER or ERROR here. Put back terminator
4595               overrides for error message */
4596
4597               default:
4598                 value[-1] = '=';
4599                 name[-1] = ' ';
4600                 (void)smtp_handle_acl_fail(ACL_WHERE_MAILAUTH, rc, user_msg,
4601                   log_msg);
4602                 goto COMMAND_LOOP;
4603               }
4604             }
4605             break;
4606
4607 #ifndef DISABLE_PRDR
4608         case ENV_MAIL_OPT_PRDR:
4609           if (prdr_enable)
4610             prdr_requested = TRUE;
4611           break;
4612 #endif
4613
4614 #ifdef SUPPORT_I18N
4615         case ENV_MAIL_OPT_UTF8:
4616           if (smtputf8_advertised)
4617             {
4618             int old_pool = store_pool;
4619
4620             DEBUG(D_receive) debug_printf("smtputf8 requested\n");
4621             message_smtputf8 = allow_utf8_domains = TRUE;
4622             store_pool = POOL_PERM;
4623             received_protocol = string_sprintf("utf8%s", received_protocol);
4624             store_pool = old_pool;
4625             }
4626           break;
4627 #endif
4628         /* No valid option. Stick back the terminator characters and break
4629         the loop.  Do the name-terminator second as extract_option sets
4630         value==name when it found no equal-sign.
4631         An error for a malformed address will occur. */
4632         case ENV_MAIL_OPT_NULL:
4633           value[-1] = '=';
4634           name[-1] = ' ';
4635           arg_error = TRUE;
4636           break;
4637
4638         default:  assert(0);
4639         }
4640       /* Break out of for loop if switch() had bad argument or
4641          when start of the email address is reached */
4642       if (arg_error) break;
4643       }
4644
4645     /* If we have passed the threshold for rate limiting, apply the current
4646     delay, and update it for next time, provided this is a limited host. */
4647
4648     if (smtp_mailcmd_count > smtp_rlm_threshold &&
4649         verify_check_host(&smtp_ratelimit_hosts) == OK)
4650       {
4651       DEBUG(D_receive) debug_printf("rate limit MAIL: delay %.3g sec\n",
4652         smtp_delay_mail/1000.0);
4653       millisleep((int)smtp_delay_mail);
4654       smtp_delay_mail *= smtp_rlm_factor;
4655       if (smtp_delay_mail > (double)smtp_rlm_limit)
4656         smtp_delay_mail = (double)smtp_rlm_limit;
4657       }
4658
4659     /* Now extract the address, first applying any SMTP-time rewriting. The
4660     TRUE flag allows "<>" as a sender address. */
4661
4662     raw_sender = rewrite_existflags & rewrite_smtp
4663       ? rewrite_one(smtp_cmd_data, rewrite_smtp, NULL, FALSE, US"",
4664                     global_rewrite_rules)
4665       : smtp_cmd_data;
4666
4667     raw_sender =
4668       parse_extract_address(raw_sender, &errmess, &start, &end, &sender_domain,
4669         TRUE);
4670
4671     if (!raw_sender)
4672       {
4673       done = synprot_error(L_smtp_syntax_error, 501, smtp_cmd_data, errmess);
4674       break;
4675       }
4676
4677     sender_address = raw_sender;
4678
4679     /* If there is a configured size limit for mail, check that this message
4680     doesn't exceed it. The check is postponed to this point so that the sender
4681     can be logged. */
4682
4683     if (thismessage_size_limit > 0 && message_size > thismessage_size_limit)
4684       {
4685       smtp_printf("552 Message size exceeds maximum permitted\r\n", FALSE);
4686       log_write(L_size_reject,
4687           LOG_MAIN|LOG_REJECT, "rejected MAIL FROM:<%s> %s: "
4688           "message too big: size%s=%d max=%d",
4689           sender_address,
4690           host_and_ident(TRUE),
4691           (message_size == INT_MAX)? ">" : "",
4692           message_size,
4693           thismessage_size_limit);
4694       sender_address = NULL;
4695       break;
4696       }
4697
4698     /* Check there is enough space on the disk unless configured not to.
4699     When smtp_check_spool_space is set, the check is for thismessage_size_limit
4700     plus the current message - i.e. we accept the message only if it won't
4701     reduce the space below the threshold. Add 5000 to the size to allow for
4702     overheads such as the Received: line and storing of recipients, etc.
4703     By putting the check here, even when SIZE is not given, it allow VRFY
4704     and EXPN etc. to be used when space is short. */
4705
4706     if (!receive_check_fs(
4707          (smtp_check_spool_space && message_size >= 0)?
4708             message_size + 5000 : 0))
4709       {
4710       smtp_printf("452 Space shortage, please try later\r\n", FALSE);
4711       sender_address = NULL;
4712       break;
4713       }
4714
4715     /* If sender_address is unqualified, reject it, unless this is a locally
4716     generated message, or the sending host or net is permitted to send
4717     unqualified addresses - typically local machines behaving as MUAs -
4718     in which case just qualify the address. The flag is set above at the start
4719     of the SMTP connection. */
4720
4721     if (sender_domain == 0 && sender_address[0] != 0)
4722       {
4723       if (allow_unqualified_sender)
4724         {
4725         sender_domain = Ustrlen(sender_address) + 1;
4726         sender_address = rewrite_address_qualify(sender_address, FALSE);
4727         DEBUG(D_receive) debug_printf("unqualified address %s accepted\n",
4728           raw_sender);
4729         }
4730       else
4731         {
4732         smtp_printf("501 %s: sender address must contain a domain\r\n", FALSE,
4733           smtp_cmd_data);
4734         log_write(L_smtp_syntax_error,
4735           LOG_MAIN|LOG_REJECT,
4736           "unqualified sender rejected: <%s> %s%s",
4737           raw_sender,
4738           host_and_ident(TRUE),
4739           host_lookup_msg);
4740         sender_address = NULL;
4741         break;
4742         }
4743       }
4744
4745     /* Apply an ACL check if one is defined, before responding. Afterwards,
4746     when pipelining is not advertised, do another sync check in case the ACL
4747     delayed and the client started sending in the meantime. */
4748
4749     if (acl_smtp_mail)
4750       {
4751       rc = acl_check(ACL_WHERE_MAIL, NULL, acl_smtp_mail, &user_msg, &log_msg);
4752       if (rc == OK && !pipelining_advertised && !check_sync())
4753         goto SYNC_FAILURE;
4754       }
4755     else
4756       rc = OK;
4757
4758     if (rc == OK || rc == DISCARD)
4759       {
4760       BOOL more = pipeline_response();
4761
4762       if (!user_msg)
4763         smtp_printf("%s%s%s", more, US"250 OK",
4764                   #ifndef DISABLE_PRDR
4765                     prdr_requested ? US", PRDR Requested" : US"",
4766                   #else
4767                     US"",
4768                   #endif
4769                     US"\r\n");
4770       else
4771         {
4772       #ifndef DISABLE_PRDR
4773         if (prdr_requested)
4774            user_msg = string_sprintf("%s%s", user_msg, US", PRDR Requested");
4775       #endif
4776         smtp_user_msg(US"250", user_msg);
4777         }
4778       smtp_delay_rcpt = smtp_rlr_base;
4779       recipients_discarded = (rc == DISCARD);
4780       was_rej_mail = FALSE;
4781       }
4782     else
4783       {
4784       done = smtp_handle_acl_fail(ACL_WHERE_MAIL, rc, user_msg, log_msg);
4785       sender_address = NULL;
4786       }
4787     break;
4788
4789
4790     /* The RCPT command requires an address as an operand. There may be any
4791     number of RCPT commands, specifying multiple recipients. We build them all
4792     into a data structure. The start/end values given by parse_extract_address
4793     are not used, as we keep only the extracted address. */
4794
4795     case RCPT_CMD:
4796     HAD(SCH_RCPT);
4797     rcpt_count++;
4798     was_rcpt = rcpt_in_progress = TRUE;
4799
4800     /* There must be a sender address; if the sender was rejected and
4801     pipelining was advertised, we assume the client was pipelining, and do not
4802     count this as a protocol error. Reset was_rej_mail so that further RCPTs
4803     get the same treatment. */
4804
4805     if (sender_address == NULL)
4806       {
4807       if (pipelining_advertised && last_was_rej_mail)
4808         {
4809         smtp_printf("503 sender not yet given\r\n", FALSE);
4810         was_rej_mail = TRUE;
4811         }
4812       else
4813         {
4814         done = synprot_error(L_smtp_protocol_error, 503, NULL,
4815           US"sender not yet given");
4816         was_rcpt = FALSE;             /* Not a valid RCPT */
4817         }
4818       rcpt_fail_count++;
4819       break;
4820       }
4821
4822     /* Check for an operand */
4823
4824     if (smtp_cmd_data[0] == 0)
4825       {
4826       done = synprot_error(L_smtp_syntax_error, 501, NULL,
4827         US"RCPT must have an address operand");
4828       rcpt_fail_count++;
4829       break;
4830       }
4831
4832     /* Set the DSN flags orcpt and dsn_flags from the session*/
4833     orcpt = NULL;
4834     flags = 0;
4835
4836     if (esmtp) for(;;)
4837       {
4838       uschar *name, *value;
4839
4840       if (!extract_option(&name, &value))
4841         break;
4842
4843       if (dsn_advertised && strcmpic(name, US"ORCPT") == 0)
4844         {
4845         /* Check whether orcpt has been already set */
4846         if (orcpt)
4847           {
4848           synprot_error(L_smtp_syntax_error, 501, NULL,
4849             US"ORCPT can be specified once only");
4850           goto COMMAND_LOOP;
4851           }
4852         orcpt = string_copy(value);
4853         DEBUG(D_receive) debug_printf("DSN orcpt: %s\n", orcpt);
4854         }
4855
4856       else if (dsn_advertised && strcmpic(name, US"NOTIFY") == 0)
4857         {
4858         /* Check if the notify flags have been already set */
4859         if (flags > 0)
4860           {
4861           synprot_error(L_smtp_syntax_error, 501, NULL,
4862               US"NOTIFY can be specified once only");
4863           goto COMMAND_LOOP;
4864           }
4865         if (strcmpic(value, US"NEVER") == 0)
4866           flags |= rf_notify_never;
4867         else
4868           {
4869           uschar *p = value;
4870           while (*p != 0)
4871             {
4872             uschar *pp = p;
4873             while (*pp != 0 && *pp != ',') pp++;
4874             if (*pp == ',') *pp++ = 0;
4875             if (strcmpic(p, US"SUCCESS") == 0)
4876               {
4877               DEBUG(D_receive) debug_printf("DSN: Setting notify success\n");
4878               flags |= rf_notify_success;
4879               }
4880             else if (strcmpic(p, US"FAILURE") == 0)
4881               {
4882               DEBUG(D_receive) debug_printf("DSN: Setting notify failure\n");
4883               flags |= rf_notify_failure;
4884               }
4885             else if (strcmpic(p, US"DELAY") == 0)
4886               {
4887               DEBUG(D_receive) debug_printf("DSN: Setting notify delay\n");
4888               flags |= rf_notify_delay;
4889               }
4890             else
4891               {
4892               /* Catch any strange values */
4893               synprot_error(L_smtp_syntax_error, 501, NULL,
4894                 US"Invalid value for NOTIFY parameter");
4895               goto COMMAND_LOOP;
4896               }
4897             p = pp;
4898             }
4899             DEBUG(D_receive) debug_printf("DSN Flags: %x\n", flags);
4900           }
4901         }
4902
4903       /* Unknown option. Stick back the terminator characters and break
4904       the loop. An error for a malformed address will occur. */
4905
4906       else
4907         {
4908         DEBUG(D_receive) debug_printf("Invalid RCPT option: %s : %s\n", name, value);
4909         name[-1] = ' ';
4910         value[-1] = '=';
4911         break;
4912         }
4913       }
4914
4915     /* Apply SMTP rewriting then extract the working address. Don't allow "<>"
4916     as a recipient address */
4917
4918     recipient = rewrite_existflags & rewrite_smtp
4919       ? rewrite_one(smtp_cmd_data, rewrite_smtp, NULL, FALSE, US"",
4920           global_rewrite_rules)
4921       : smtp_cmd_data;
4922
4923     if (!(recipient = parse_extract_address(recipient, &errmess, &start, &end,
4924       &recipient_domain, FALSE)))
4925       {
4926       done = synprot_error(L_smtp_syntax_error, 501, smtp_cmd_data, errmess);
4927       rcpt_fail_count++;
4928       break;
4929       }
4930
4931     /* If the recipient address is unqualified, reject it, unless this is a
4932     locally generated message. However, unqualified addresses are permitted
4933     from a configured list of hosts and nets - typically when behaving as
4934     MUAs rather than MTAs. Sad that SMTP is used for both types of traffic,
4935     really. The flag is set at the start of the SMTP connection.
4936
4937     RFC 1123 talks about supporting "the reserved mailbox postmaster"; I always
4938     assumed this meant "reserved local part", but the revision of RFC 821 and
4939     friends now makes it absolutely clear that it means *mailbox*. Consequently
4940     we must always qualify this address, regardless. */
4941
4942     if (!recipient_domain)
4943       if (!(recipient_domain = qualify_recipient(&recipient, smtp_cmd_data,
4944                                   US"recipient")))
4945         {
4946         rcpt_fail_count++;
4947         break;
4948         }
4949
4950     /* Check maximum allowed */
4951
4952     if (rcpt_count > recipients_max && recipients_max > 0)
4953       {
4954       if (recipients_max_reject)
4955         {
4956         rcpt_fail_count++;
4957         smtp_printf("552 too many recipients\r\n", FALSE);
4958         if (!toomany)
4959           log_write(0, LOG_MAIN|LOG_REJECT, "too many recipients: message "
4960             "rejected: sender=<%s> %s", sender_address, host_and_ident(TRUE));
4961         }
4962       else
4963         {
4964         rcpt_defer_count++;
4965         smtp_printf("452 too many recipients\r\n", FALSE);
4966         if (!toomany)
4967           log_write(0, LOG_MAIN|LOG_REJECT, "too many recipients: excess "
4968             "temporarily rejected: sender=<%s> %s", sender_address,
4969             host_and_ident(TRUE));
4970         }
4971
4972       toomany = TRUE;
4973       break;
4974       }
4975
4976     /* If we have passed the threshold for rate limiting, apply the current
4977     delay, and update it for next time, provided this is a limited host. */
4978
4979     if (rcpt_count > smtp_rlr_threshold &&
4980         verify_check_host(&smtp_ratelimit_hosts) == OK)
4981       {
4982       DEBUG(D_receive) debug_printf("rate limit RCPT: delay %.3g sec\n",
4983         smtp_delay_rcpt/1000.0);
4984       millisleep((int)smtp_delay_rcpt);
4985       smtp_delay_rcpt *= smtp_rlr_factor;
4986       if (smtp_delay_rcpt > (double)smtp_rlr_limit)
4987         smtp_delay_rcpt = (double)smtp_rlr_limit;
4988       }
4989
4990     /* If the MAIL ACL discarded all the recipients, we bypass ACL checking
4991     for them. Otherwise, check the access control list for this recipient. As
4992     there may be a delay in this, re-check for a synchronization error
4993     afterwards, unless pipelining was advertised. */
4994
4995     if (recipients_discarded)
4996       rc = DISCARD;
4997     else
4998       if (  (rc = acl_check(ACL_WHERE_RCPT, recipient, acl_smtp_rcpt, &user_msg,
4999                     &log_msg)) == OK
5000          && !pipelining_advertised && !check_sync())
5001         goto SYNC_FAILURE;
5002
5003     /* The ACL was happy */
5004
5005     if (rc == OK)
5006       {
5007       BOOL more = pipeline_response();
5008
5009       if (user_msg)
5010         smtp_user_msg(US"250", user_msg);
5011       else
5012         smtp_printf("250 Accepted\r\n", more);
5013       receive_add_recipient(recipient, -1);
5014
5015       /* Set the dsn flags in the recipients_list */
5016       recipients_list[recipients_count-1].orcpt = orcpt;
5017       recipients_list[recipients_count-1].dsn_flags = flags;
5018
5019       DEBUG(D_receive) debug_printf("DSN: orcpt: %s  flags: %d\n",
5020         recipients_list[recipients_count-1].orcpt,
5021         recipients_list[recipients_count-1].dsn_flags);
5022       }
5023
5024     /* The recipient was discarded */
5025
5026     else if (rc == DISCARD)
5027       {
5028       if (user_msg)
5029         smtp_user_msg(US"250", user_msg);
5030       else
5031         smtp_printf("250 Accepted\r\n", FALSE);
5032       rcpt_fail_count++;
5033       discarded = TRUE;
5034       log_write(0, LOG_MAIN|LOG_REJECT, "%s F=<%s> RCPT %s: "
5035         "discarded by %s ACL%s%s", host_and_ident(TRUE),
5036         sender_address_unrewritten? sender_address_unrewritten : sender_address,
5037         smtp_cmd_argument, recipients_discarded? "MAIL" : "RCPT",
5038         log_msg ? US": " : US"", log_msg ? log_msg : US"");
5039       }
5040
5041     /* Either the ACL failed the address, or it was deferred. */
5042
5043     else
5044       {
5045       if (rc == FAIL) rcpt_fail_count++; else rcpt_defer_count++;
5046       done = smtp_handle_acl_fail(ACL_WHERE_RCPT, rc, user_msg, log_msg);
5047       }
5048     break;
5049
5050
5051     /* The DATA command is legal only if it follows successful MAIL FROM
5052     and RCPT TO commands. However, if pipelining is advertised, a bad DATA is
5053     not counted as a protocol error if it follows RCPT (which must have been
5054     rejected if there are no recipients.) This function is complete when a
5055     valid DATA command is encountered.
5056
5057     Note concerning the code used: RFC 2821 says this:
5058
5059      -  If there was no MAIL, or no RCPT, command, or all such commands
5060         were rejected, the server MAY return a "command out of sequence"
5061         (503) or "no valid recipients" (554) reply in response to the
5062         DATA command.
5063
5064     The example in the pipelining RFC 2920 uses 554, but I use 503 here
5065     because it is the same whether pipelining is in use or not.
5066
5067     If all the RCPT commands that precede DATA provoked the same error message
5068     (often indicating some kind of system error), it is helpful to include it
5069     with the DATA rejection (an idea suggested by Tony Finch). */
5070
5071     case BDAT_CMD:
5072     HAD(SCH_BDAT);
5073       {
5074       int n;
5075
5076       if (chunking_state != CHUNKING_OFFERED)
5077         {
5078         done = synprot_error(L_smtp_protocol_error, 503, NULL,
5079           US"BDAT command used when CHUNKING not advertised");
5080         break;
5081         }
5082
5083       /* grab size, endmarker */
5084
5085       if (sscanf(CS smtp_cmd_data, "%u %n", &chunking_datasize, &n) < 1)
5086         {
5087         done = synprot_error(L_smtp_protocol_error, 501, NULL,
5088           US"missing size for BDAT command");
5089         break;
5090         }
5091       chunking_state = strcmpic(smtp_cmd_data+n, US"LAST") == 0
5092         ? CHUNKING_LAST : CHUNKING_ACTIVE;
5093       chunking_data_left = chunking_datasize;
5094       DEBUG(D_receive) debug_printf("chunking state %d, %d bytes\n",
5095                                     (int)chunking_state, chunking_data_left);
5096
5097       /* push the current receive_* function on the "stack", and
5098       replace them by bdat_getc(), which in turn will use the lwr_receive_*
5099       functions to do the dirty work. */
5100       lwr_receive_getc = receive_getc;
5101       lwr_receive_getbuf = receive_getbuf;
5102       lwr_receive_ungetc = receive_ungetc;
5103
5104       receive_getc = bdat_getc;
5105       receive_ungetc = bdat_ungetc;
5106
5107       dot_ends = FALSE;
5108
5109       goto DATA_BDAT;
5110       }
5111
5112     case DATA_CMD:
5113     HAD(SCH_DATA);
5114     dot_ends = TRUE;
5115
5116     DATA_BDAT:          /* Common code for DATA and BDAT */
5117     if (!discarded && recipients_count <= 0)
5118       {
5119       if (rcpt_smtp_response_same && rcpt_smtp_response != NULL)
5120         {
5121         uschar *code = US"503";
5122         int len = Ustrlen(rcpt_smtp_response);
5123         smtp_respond(code, 3, FALSE, US"All RCPT commands were rejected with "
5124           "this error:");
5125         /* Responses from smtp_printf() will have \r\n on the end */
5126         if (len > 2 && rcpt_smtp_response[len-2] == '\r')
5127           rcpt_smtp_response[len-2] = 0;
5128         smtp_respond(code, 3, FALSE, rcpt_smtp_response);
5129         }
5130       if (pipelining_advertised && last_was_rcpt)
5131         smtp_printf("503 Valid RCPT command must precede %s\r\n", FALSE,
5132           smtp_names[smtp_connection_had[smtp_ch_index-1]]);
5133       else
5134         done = synprot_error(L_smtp_protocol_error, 503, NULL,
5135           smtp_connection_had[smtp_ch_index-1] == SCH_DATA
5136           ? US"valid RCPT command must precede DATA"
5137           : US"valid RCPT command must precede BDAT");
5138
5139       if (chunking_state > CHUNKING_OFFERED)
5140         bdat_flush_data();
5141       break;
5142       }
5143
5144     if (toomany && recipients_max_reject)
5145       {
5146       sender_address = NULL;  /* This will allow a new MAIL without RSET */
5147       sender_address_unrewritten = NULL;
5148       smtp_printf("554 Too many recipients\r\n", FALSE);
5149       break;
5150       }
5151
5152     if (chunking_state > CHUNKING_OFFERED)
5153       rc = OK;                  /* No predata ACL or go-ahead output for BDAT */
5154     else
5155       {
5156       /* If there is an ACL, re-check the synchronization afterwards, since the
5157       ACL may have delayed.  To handle cutthrough delivery enforce a dummy call
5158       to get the DATA command sent. */
5159
5160       if (acl_smtp_predata == NULL && cutthrough.fd < 0)
5161         rc = OK;
5162       else
5163         {
5164         uschar * acl = acl_smtp_predata ? acl_smtp_predata : US"accept";
5165         enable_dollar_recipients = TRUE;
5166         rc = acl_check(ACL_WHERE_PREDATA, NULL, acl, &user_msg,
5167           &log_msg);
5168         enable_dollar_recipients = FALSE;
5169         if (rc == OK && !check_sync())
5170           goto SYNC_FAILURE;
5171
5172         if (rc != OK)
5173           {     /* Either the ACL failed the address, or it was deferred. */
5174           done = smtp_handle_acl_fail(ACL_WHERE_PREDATA, rc, user_msg, log_msg);
5175           break;
5176           }
5177         }
5178
5179       if (user_msg)
5180         smtp_user_msg(US"354", user_msg);
5181       else
5182         smtp_printf(
5183           "354 Enter message, ending with \".\" on a line by itself\r\n", FALSE);
5184       }
5185
5186 #ifdef TCP_QUICKACK
5187     if (smtp_in)        /* all ACKs needed to ramp window up for bulk data */
5188       (void) setsockopt(fileno(smtp_in), IPPROTO_TCP, TCP_QUICKACK,
5189               US &on, sizeof(on));
5190 #endif
5191     done = 3;
5192     message_ended = END_NOTENDED;   /* Indicate in middle of data */
5193
5194     break;
5195
5196
5197     case VRFY_CMD:
5198       {
5199       uschar * address;
5200
5201       HAD(SCH_VRFY);
5202
5203       if (!(address = parse_extract_address(smtp_cmd_data, &errmess,
5204             &start, &end, &recipient_domain, FALSE)))
5205         {
5206         smtp_printf("501 %s\r\n", FALSE, errmess);
5207         break;
5208         }
5209
5210       if (!recipient_domain)
5211         if (!(recipient_domain = qualify_recipient(&address, smtp_cmd_data,
5212                                     US"verify")))
5213           break;
5214
5215       if ((rc = acl_check(ACL_WHERE_VRFY, address, acl_smtp_vrfy,
5216                     &user_msg, &log_msg)) != OK)
5217         done = smtp_handle_acl_fail(ACL_WHERE_VRFY, rc, user_msg, log_msg);
5218       else
5219         {
5220         uschar * s = NULL;
5221         address_item * addr = deliver_make_addr(address, FALSE);
5222
5223         switch(verify_address(addr, NULL, vopt_is_recipient | vopt_qualify, -1,
5224                -1, -1, NULL, NULL, NULL))
5225           {
5226           case OK:
5227             s = string_sprintf("250 <%s> is deliverable", address);
5228             break;
5229
5230           case DEFER:
5231             s = (addr->user_message != NULL)?
5232               string_sprintf("451 <%s> %s", address, addr->user_message) :
5233               string_sprintf("451 Cannot resolve <%s> at this time", address);
5234             break;
5235
5236           case FAIL:
5237             s = (addr->user_message != NULL)?
5238               string_sprintf("550 <%s> %s", address, addr->user_message) :
5239               string_sprintf("550 <%s> is not deliverable", address);
5240             log_write(0, LOG_MAIN, "VRFY failed for %s %s",
5241               smtp_cmd_argument, host_and_ident(TRUE));
5242             break;
5243           }
5244
5245         smtp_printf("%s\r\n", FALSE, s);
5246         }
5247       break;
5248       }
5249
5250
5251     case EXPN_CMD:
5252     HAD(SCH_EXPN);
5253     rc = acl_check(ACL_WHERE_EXPN, NULL, acl_smtp_expn, &user_msg, &log_msg);
5254     if (rc != OK)
5255       done = smtp_handle_acl_fail(ACL_WHERE_EXPN, rc, user_msg, log_msg);
5256     else
5257       {
5258       BOOL save_log_testing_mode = log_testing_mode;
5259       address_test_mode = log_testing_mode = TRUE;
5260       (void) verify_address(deliver_make_addr(smtp_cmd_data, FALSE),
5261         smtp_out, vopt_is_recipient | vopt_qualify | vopt_expn, -1, -1, -1,
5262         NULL, NULL, NULL);
5263       address_test_mode = FALSE;
5264       log_testing_mode = save_log_testing_mode;    /* true for -bh */
5265       }
5266     break;
5267
5268
5269     #ifdef SUPPORT_TLS
5270
5271     case STARTTLS_CMD:
5272     HAD(SCH_STARTTLS);
5273     if (!tls_advertised)
5274       {
5275       done = synprot_error(L_smtp_protocol_error, 503, NULL,
5276         US"STARTTLS command used when not advertised");
5277       break;
5278       }
5279
5280     /* Apply an ACL check if one is defined */
5281
5282     if (  acl_smtp_starttls
5283        && (rc = acl_check(ACL_WHERE_STARTTLS, NULL, acl_smtp_starttls,
5284                   &user_msg, &log_msg)) != OK
5285        )
5286       {
5287       done = smtp_handle_acl_fail(ACL_WHERE_STARTTLS, rc, user_msg, log_msg);
5288       break;
5289       }
5290
5291     /* RFC 2487 is not clear on when this command may be sent, though it
5292     does state that all information previously obtained from the client
5293     must be discarded if a TLS session is started. It seems reasonable to
5294     do an implied RSET when STARTTLS is received. */
5295
5296     incomplete_transaction_log(US"STARTTLS");
5297     cancel_cutthrough_connection(TRUE, US"STARTTLS received");
5298     smtp_reset(reset_point);
5299     toomany = FALSE;
5300     cmd_list[CMD_LIST_STARTTLS].is_mail_cmd = FALSE;
5301
5302     /* There's an attack where more data is read in past the STARTTLS command
5303     before TLS is negotiated, then assumed to be part of the secure session
5304     when used afterwards; we use segregated input buffers, so are not
5305     vulnerable, but we want to note when it happens and, for sheer paranoia,
5306     ensure that the buffer is "wiped".
5307     Pipelining sync checks will normally have protected us too, unless disabled
5308     by configuration. */
5309
5310     if (receive_smtp_buffered())
5311       {
5312       DEBUG(D_any)
5313         debug_printf("Non-empty input buffer after STARTTLS; naive attack?\n");
5314       if (tls_in.active < 0)
5315         smtp_inend = smtp_inptr = smtp_inbuffer;
5316       /* and if TLS is already active, tls_server_start() should fail */
5317       }
5318
5319     /* There is nothing we value in the input buffer and if TLS is successfully
5320     negotiated, we won't use this buffer again; if TLS fails, we'll just read
5321     fresh content into it.  The buffer contains arbitrary content from an
5322     untrusted remote source; eg: NOOP <shellcode>\r\nSTARTTLS\r\n
5323     It seems safest to just wipe away the content rather than leave it as a
5324     target to jump to. */
5325
5326     memset(smtp_inbuffer, 0, IN_BUFFER_SIZE);
5327
5328     /* Attempt to start up a TLS session, and if successful, discard all
5329     knowledge that was obtained previously. At least, that's what the RFC says,
5330     and that's what happens by default. However, in order to work round YAEB,
5331     there is an option to remember the esmtp state. Sigh.
5332
5333     We must allow for an extra EHLO command and an extra AUTH command after
5334     STARTTLS that don't add to the nonmail command count. */
5335
5336     s = NULL;
5337     if ((rc = tls_server_start(tls_require_ciphers, &s)) == OK)
5338       {
5339       if (!tls_remember_esmtp)
5340         helo_seen = esmtp = auth_advertised = pipelining_advertised = FALSE;
5341       cmd_list[CMD_LIST_EHLO].is_mail_cmd = TRUE;
5342       cmd_list[CMD_LIST_AUTH].is_mail_cmd = TRUE;
5343       cmd_list[CMD_LIST_TLS_AUTH].is_mail_cmd = TRUE;
5344       if (sender_helo_name)
5345         {
5346         store_free(sender_helo_name);
5347         sender_helo_name = NULL;
5348         host_build_sender_fullhost();  /* Rebuild */
5349         set_process_info("handling incoming TLS connection from %s",
5350           host_and_ident(FALSE));
5351         }
5352       received_protocol =
5353         (sender_host_address ? protocols : protocols_local)
5354           [ (esmtp
5355             ? pextend + (sender_host_authenticated ? pauthed : 0)
5356             : pnormal)
5357           + (tls_in.active >= 0 ? pcrpted : 0)
5358           ];
5359
5360       sender_host_auth_pubname = sender_host_authenticated = NULL;
5361       authenticated_id = NULL;
5362       sync_cmd_limit = NON_SYNC_CMD_NON_PIPELINING;
5363       DEBUG(D_tls) debug_printf("TLS active\n");
5364       break;     /* Successful STARTTLS */
5365       }
5366     else
5367       (void) smtp_log_tls_fail(s);
5368
5369     /* Some local configuration problem was discovered before actually trying
5370     to do a TLS handshake; give a temporary error. */
5371
5372     if (rc == DEFER)
5373       {
5374       smtp_printf("454 TLS currently unavailable\r\n", FALSE);
5375       break;
5376       }
5377
5378     /* Hard failure. Reject everything except QUIT or closed connection. One
5379     cause for failure is a nested STARTTLS, in which case tls_in.active remains
5380     set, but we must still reject all incoming commands. */
5381
5382     DEBUG(D_tls) debug_printf("TLS failed to start\n");
5383     while (done <= 0) switch(smtp_read_command(FALSE, GETC_BUFFER_UNLIMITED))
5384       {
5385       case EOF_CMD:
5386         log_write(L_smtp_connection, LOG_MAIN, "%s closed by EOF",
5387           smtp_get_connection_info());
5388         smtp_notquit_exit(US"tls-failed", NULL, NULL);
5389         done = 2;
5390         break;
5391
5392       /* It is perhaps arguable as to which exit ACL should be called here,
5393       but as it is probably a situation that almost never arises, it
5394       probably doesn't matter. We choose to call the real QUIT ACL, which in
5395       some sense is perhaps "right". */
5396
5397       case QUIT_CMD:
5398         user_msg = NULL;
5399         if (  acl_smtp_quit
5400            && ((rc = acl_check(ACL_WHERE_QUIT, NULL, acl_smtp_quit, &user_msg,
5401                               &log_msg)) == ERROR))
5402             log_write(0, LOG_MAIN|LOG_PANIC, "ACL for QUIT returned ERROR: %s",
5403               log_msg);
5404         if (user_msg)
5405           smtp_respond(US"221", 3, TRUE, user_msg);
5406         else
5407           smtp_printf("221 %s closing connection\r\n", FALSE, smtp_active_hostname);
5408         log_write(L_smtp_connection, LOG_MAIN, "%s closed by QUIT",
5409           smtp_get_connection_info());
5410         done = 2;
5411         break;
5412
5413       default:
5414         smtp_printf("554 Security failure\r\n", FALSE);
5415         break;
5416       }
5417     tls_close(TRUE, TLS_SHUTDOWN_NOWAIT);
5418     break;
5419     #endif
5420
5421
5422     /* The ACL for QUIT is provided for gathering statistical information or
5423     similar; it does not affect the response code, but it can supply a custom
5424     message. */
5425
5426     case QUIT_CMD:
5427     smtp_quit_handler(&user_msg, &log_msg);
5428     done = 2;
5429     break;
5430
5431
5432     case RSET_CMD:
5433     smtp_rset_handler();
5434     cancel_cutthrough_connection(TRUE, US"RSET received");
5435     smtp_reset(reset_point);
5436     toomany = FALSE;
5437     break;
5438
5439
5440     case NOOP_CMD:
5441     HAD(SCH_NOOP);
5442     smtp_printf("250 OK\r\n", FALSE);
5443     break;
5444
5445
5446     /* Show ETRN/EXPN/VRFY if there's an ACL for checking hosts; if actually
5447     used, a check will be done for permitted hosts. Show STARTTLS only if not
5448     already in a TLS session and if it would be advertised in the EHLO
5449     response. */
5450
5451     case HELP_CMD:
5452     HAD(SCH_HELP);
5453     smtp_printf("214-Commands supported:\r\n", TRUE);
5454       {
5455       uschar buffer[256];
5456       buffer[0] = 0;
5457       Ustrcat(buffer, " AUTH");
5458       #ifdef SUPPORT_TLS
5459       if (tls_in.active < 0 &&
5460           verify_check_host(&tls_advertise_hosts) != FAIL)
5461         Ustrcat(buffer, " STARTTLS");
5462       #endif
5463       Ustrcat(buffer, " HELO EHLO MAIL RCPT DATA BDAT");
5464       Ustrcat(buffer, " NOOP QUIT RSET HELP");
5465       if (acl_smtp_etrn != NULL) Ustrcat(buffer, " ETRN");
5466       if (acl_smtp_expn != NULL) Ustrcat(buffer, " EXPN");
5467       if (acl_smtp_vrfy != NULL) Ustrcat(buffer, " VRFY");
5468       smtp_printf("214%s\r\n", FALSE, buffer);
5469       }
5470     break;
5471
5472
5473     case EOF_CMD:
5474     incomplete_transaction_log(US"connection lost");
5475     smtp_notquit_exit(US"connection-lost", US"421",
5476       US"%s lost input connection", smtp_active_hostname);
5477
5478     /* Don't log by default unless in the middle of a message, as some mailers
5479     just drop the call rather than sending QUIT, and it clutters up the logs.
5480     */
5481
5482     if (sender_address || recipients_count > 0)
5483       log_write(L_lost_incoming_connection, LOG_MAIN,
5484         "unexpected %s while reading SMTP command from %s%s%s D=%s",
5485         sender_host_unknown ? "EOF" : "disconnection",
5486         tcp_in_fastopen && !tcp_in_fastopen_logged ? US"TFO " : US"",
5487         host_and_ident(FALSE), smtp_read_error,
5488         string_timesince(&smtp_connection_start)
5489         );
5490
5491     else
5492       log_write(L_smtp_connection, LOG_MAIN, "%s %slost%s D=%s",
5493         smtp_get_connection_info(),
5494         tcp_in_fastopen && !tcp_in_fastopen_logged ? US"TFO " : US"",
5495         smtp_read_error,
5496         string_timesince(&smtp_connection_start)
5497         );
5498
5499     done = 1;
5500     break;
5501
5502
5503     case ETRN_CMD:
5504     HAD(SCH_ETRN);
5505     if (sender_address)
5506       {
5507       done = synprot_error(L_smtp_protocol_error, 503, NULL,
5508         US"ETRN is not permitted inside a transaction");
5509       break;
5510       }
5511
5512     log_write(L_etrn, LOG_MAIN, "ETRN %s received from %s", smtp_cmd_argument,
5513       host_and_ident(FALSE));
5514
5515     if ((rc = acl_check(ACL_WHERE_ETRN, NULL, acl_smtp_etrn,
5516                 &user_msg, &log_msg)) != OK)
5517       {
5518       done = smtp_handle_acl_fail(ACL_WHERE_ETRN, rc, user_msg, log_msg);
5519       break;
5520       }
5521
5522     /* Compute the serialization key for this command. */
5523
5524     etrn_serialize_key = string_sprintf("etrn-%s\n", smtp_cmd_data);
5525
5526     /* If a command has been specified for running as a result of ETRN, we
5527     permit any argument to ETRN. If not, only the # standard form is permitted,
5528     since that is strictly the only kind of ETRN that can be implemented
5529     according to the RFC. */
5530
5531     if (smtp_etrn_command)
5532       {
5533       uschar *error;
5534       BOOL rc;
5535       etrn_command = smtp_etrn_command;
5536       deliver_domain = smtp_cmd_data;
5537       rc = transport_set_up_command(&argv, smtp_etrn_command, TRUE, 0, NULL,
5538         US"ETRN processing", &error);
5539       deliver_domain = NULL;
5540       if (!rc)
5541         {
5542         log_write(0, LOG_MAIN|LOG_PANIC, "failed to set up ETRN command: %s",
5543           error);
5544         smtp_printf("458 Internal failure\r\n", FALSE);
5545         break;
5546         }
5547       }
5548
5549     /* Else set up to call Exim with the -R option. */
5550
5551     else
5552       {
5553       if (*smtp_cmd_data++ != '#')
5554         {
5555         done = synprot_error(L_smtp_syntax_error, 501, NULL,
5556           US"argument must begin with #");
5557         break;
5558         }
5559       etrn_command = US"exim -R";
5560       argv = CUSS child_exec_exim(CEE_RETURN_ARGV, TRUE, NULL, TRUE,
5561         *queue_name ? 4 : 2,
5562         US"-R", smtp_cmd_data,
5563         US"-MCG", queue_name);
5564       }
5565
5566     /* If we are host-testing, don't actually do anything. */
5567
5568     if (host_checking)
5569       {
5570       HDEBUG(D_any)
5571         {
5572         debug_printf("ETRN command is: %s\n", etrn_command);
5573         debug_printf("ETRN command execution skipped\n");
5574         }
5575       if (user_msg == NULL) smtp_printf("250 OK\r\n", FALSE);
5576         else smtp_user_msg(US"250", user_msg);
5577       break;
5578       }
5579
5580
5581     /* If ETRN queue runs are to be serialized, check the database to
5582     ensure one isn't already running. */
5583
5584     if (smtp_etrn_serialize && !enq_start(etrn_serialize_key, 1))
5585       {
5586       smtp_printf("458 Already processing %s\r\n", FALSE, smtp_cmd_data);
5587       break;
5588       }
5589
5590     /* Fork a child process and run the command. We don't want to have to
5591     wait for the process at any point, so set SIGCHLD to SIG_IGN before
5592     forking. It should be set that way anyway for external incoming SMTP,
5593     but we save and restore to be tidy. If serialization is required, we
5594     actually run the command in yet another process, so we can wait for it
5595     to complete and then remove the serialization lock. */
5596
5597     oldsignal = signal(SIGCHLD, SIG_IGN);
5598
5599     if ((pid = fork()) == 0)
5600       {
5601       smtp_input = FALSE;       /* This process is not associated with the */
5602       (void)fclose(smtp_in);    /* SMTP call any more. */
5603       (void)fclose(smtp_out);
5604
5605       signal(SIGCHLD, SIG_DFL);      /* Want to catch child */
5606
5607       /* If not serializing, do the exec right away. Otherwise, fork down
5608       into another process. */
5609
5610       if (!smtp_etrn_serialize || (pid = fork()) == 0)
5611         {
5612         DEBUG(D_exec) debug_print_argv(argv);
5613         exim_nullstd();                   /* Ensure std{in,out,err} exist */
5614         execv(CS argv[0], (char *const *)argv);
5615         log_write(0, LOG_MAIN|LOG_PANIC_DIE, "exec of \"%s\" (ETRN) failed: %s",
5616           etrn_command, strerror(errno));
5617         _exit(EXIT_FAILURE);         /* paranoia */
5618         }
5619
5620       /* Obey this if smtp_serialize and the 2nd fork yielded non-zero. That
5621       is, we are in the first subprocess, after forking again. All we can do
5622       for a failing fork is to log it. Otherwise, wait for the 2nd process to
5623       complete, before removing the serialization. */
5624
5625       if (pid < 0)
5626         log_write(0, LOG_MAIN|LOG_PANIC, "2nd fork for serialized ETRN "
5627           "failed: %s", strerror(errno));
5628       else
5629         {
5630         int status;
5631         DEBUG(D_any) debug_printf("waiting for serialized ETRN process %d\n",
5632           (int)pid);
5633         (void)wait(&status);
5634         DEBUG(D_any) debug_printf("serialized ETRN process %d ended\n",
5635           (int)pid);
5636         }
5637
5638       enq_end(etrn_serialize_key);
5639       _exit(EXIT_SUCCESS);
5640       }
5641
5642     /* Back in the top level SMTP process. Check that we started a subprocess
5643     and restore the signal state. */
5644
5645     if (pid < 0)
5646       {
5647       log_write(0, LOG_MAIN|LOG_PANIC, "fork of process for ETRN failed: %s",
5648         strerror(errno));
5649       smtp_printf("458 Unable to fork process\r\n", FALSE);
5650       if (smtp_etrn_serialize) enq_end(etrn_serialize_key);
5651       }
5652     else
5653       {
5654       if (user_msg == NULL) smtp_printf("250 OK\r\n", FALSE);
5655         else smtp_user_msg(US"250", user_msg);
5656       }
5657
5658     signal(SIGCHLD, oldsignal);
5659     break;
5660
5661
5662     case BADARG_CMD:
5663     done = synprot_error(L_smtp_syntax_error, 501, NULL,
5664       US"unexpected argument data");
5665     break;
5666
5667
5668     /* This currently happens only for NULLs, but could be extended. */
5669
5670     case BADCHAR_CMD:
5671     done = synprot_error(L_smtp_syntax_error, 0, NULL,       /* Just logs */
5672       US"NUL character(s) present (shown as '?')");
5673     smtp_printf("501 NUL characters are not allowed in SMTP commands\r\n", FALSE);
5674     break;
5675
5676
5677     case BADSYN_CMD:
5678     SYNC_FAILURE:
5679     if (smtp_inend >= smtp_inbuffer + IN_BUFFER_SIZE)
5680       smtp_inend = smtp_inbuffer + IN_BUFFER_SIZE - 1;
5681     c = smtp_inend - smtp_inptr;
5682     if (c > 150) c = 150;       /* limit logged amount */
5683     smtp_inptr[c] = 0;
5684     incomplete_transaction_log(US"sync failure");
5685     log_write(0, LOG_MAIN|LOG_REJECT, "SMTP protocol synchronization error "
5686       "(next input sent too soon: pipelining was%s advertised): "
5687       "rejected \"%s\" %s next input=\"%s\"",
5688       pipelining_advertised? "" : " not",
5689       smtp_cmd_buffer, host_and_ident(TRUE),
5690       string_printing(smtp_inptr));
5691     smtp_notquit_exit(US"synchronization-error", US"554",
5692       US"SMTP synchronization error");
5693     done = 1;   /* Pretend eof - drops connection */
5694     break;
5695
5696
5697     case TOO_MANY_NONMAIL_CMD:
5698     s = smtp_cmd_buffer;
5699     while (*s != 0 && !isspace(*s)) s++;
5700     incomplete_transaction_log(US"too many non-mail commands");
5701     log_write(0, LOG_MAIN|LOG_REJECT, "SMTP call from %s dropped: too many "
5702       "nonmail commands (last was \"%.*s\")",  host_and_ident(FALSE),
5703       (int)(s - smtp_cmd_buffer), smtp_cmd_buffer);
5704     smtp_notquit_exit(US"bad-commands", US"554", US"Too many nonmail commands");
5705     done = 1;   /* Pretend eof - drops connection */
5706     break;
5707
5708 #ifdef SUPPORT_PROXY
5709     case PROXY_FAIL_IGNORE_CMD:
5710     smtp_printf("503 Command refused, required Proxy negotiation failed\r\n", FALSE);
5711     break;
5712 #endif
5713
5714     default:
5715     if (unknown_command_count++ >= smtp_max_unknown_commands)
5716       {
5717       log_write(L_smtp_syntax_error, LOG_MAIN,
5718         "SMTP syntax error in \"%s\" %s %s",
5719         string_printing(smtp_cmd_buffer), host_and_ident(TRUE),
5720         US"unrecognized command");
5721       incomplete_transaction_log(US"unrecognized command");
5722       smtp_notquit_exit(US"bad-commands", US"500",
5723         US"Too many unrecognized commands");
5724       done = 2;
5725       log_write(0, LOG_MAIN|LOG_REJECT, "SMTP call from %s dropped: too many "
5726         "unrecognized commands (last was \"%s\")", host_and_ident(FALSE),
5727         string_printing(smtp_cmd_buffer));
5728       }
5729     else
5730       done = synprot_error(L_smtp_syntax_error, 500, NULL,
5731         US"unrecognized command");
5732     break;
5733     }
5734
5735   /* This label is used by goto's inside loops that want to break out to
5736   the end of the command-processing loop. */
5737
5738   COMMAND_LOOP:
5739   last_was_rej_mail = was_rej_mail;     /* Remember some last commands for */
5740   last_was_rcpt = was_rcpt;             /* protocol error handling */
5741   continue;
5742   }
5743
5744 return done - 2;  /* Convert yield values */
5745 }
5746
5747
5748
5749 gstring *
5750 authres_smtpauth(gstring * g)
5751 {
5752 if (!sender_host_authenticated)
5753   return g;
5754
5755 g = string_append(g, 2, US";\n\tauth=pass (", sender_host_auth_pubname);
5756
5757 if (Ustrcmp(sender_host_auth_pubname, "tls") != 0)
5758   g = string_append(g, 2, US") smtp.auth=", authenticated_id);
5759 else if (authenticated_id)
5760   g = string_append(g, 2, US") x509.auth=", authenticated_id);
5761 else
5762   g = string_catn(g, US") reason=x509.auth", 17);
5763
5764 if (authenticated_sender)
5765   g = string_append(g, 2, US" smtp.mailfrom=", authenticated_sender);
5766 return g;
5767 }
5768
5769
5770
5771 /* vi: aw ai sw=2
5772 */
5773 /* End of smtp_in.c */