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