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