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