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