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;