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