Avoid doing logging in signal-handlers. Bug 1007
[exim.git] / src / src / receive.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2018 */
6 /* See the file NOTICE for conditions of use and distribution. */
7
8 /* Code for receiving a message and setting up spool files. */
9
10 #include "exim.h"
11 #include <setjmp.h>
12
13 #ifdef EXPERIMENTAL_DCC
14 extern int dcc_ok;
15 #endif
16
17 #ifdef EXPERIMENTAL_DMARC
18 # include "dmarc.h"
19 #endif /* EXPERIMENTAL_DMARC */
20
21 /*************************************************
22 *                Local static variables          *
23 *************************************************/
24
25 static FILE   *data_file = NULL;
26 static int     data_fd = -1;
27 static uschar *spool_name = US"";
28
29 enum CH_STATE {LF_SEEN, MID_LINE, CR_SEEN};
30
31 jmp_buf local_scan_env;         /* error-handling context for local_scan */
32 unsigned had_local_scan_crash;
33 unsigned had_local_scan_timeout;
34
35
36 /*************************************************
37 *      Non-SMTP character reading functions      *
38 *************************************************/
39
40 /* These are the default functions that are set up in the variables such as
41 receive_getc initially. They just call the standard functions, passing stdin as
42 the file. (When SMTP input is occurring, different functions are used by
43 changing the pointer variables.) */
44
45 int
46 stdin_getc(unsigned lim)
47 {
48 int c = getc(stdin);
49
50 if (had_data_timeout)
51   {
52   fprintf(stderr, "exim: timed out while reading - message abandoned\n");
53   log_write(L_lost_incoming_connection,
54             LOG_MAIN, "timed out while reading local message");
55   receive_bomb_out(US"data-timeout", NULL);   /* Does not return */
56   }
57 if (had_data_sigint)
58   {
59   if (filter_test == FTEST_NONE)
60     {
61     fprintf(stderr, "\nexim: %s received - message abandoned\n",
62       had_data_sigint == SIGTERM ? "SIGTERM" : "SIGINT");
63     log_write(0, LOG_MAIN, "%s received while reading local message",
64       had_data_sigint == SIGTERM ? "SIGTERM" : "SIGINT");
65     }
66   receive_bomb_out(US"signal-exit", NULL);    /* Does not return */
67   }
68 return c;
69 }
70
71 int
72 stdin_ungetc(int c)
73 {
74 return ungetc(c, stdin);
75 }
76
77 int
78 stdin_feof(void)
79 {
80 return feof(stdin);
81 }
82
83 int
84 stdin_ferror(void)
85 {
86 return ferror(stdin);
87 }
88
89
90
91
92 /*************************************************
93 *     Check that a set sender is allowed         *
94 *************************************************/
95
96 /* This function is called when a local caller sets an explicit sender address.
97 It checks whether this is permitted, which it is for trusted callers.
98 Otherwise, it must match the pattern(s) in untrusted_set_sender.
99
100 Arguments:  the proposed sender address
101 Returns:    TRUE for a trusted caller
102             TRUE if the address has been set, untrusted_set_sender has been
103               set, and the address matches something in the list
104             FALSE otherwise
105 */
106
107 BOOL
108 receive_check_set_sender(uschar *newsender)
109 {
110 uschar *qnewsender;
111 if (trusted_caller) return TRUE;
112 if (!newsender || !untrusted_set_sender) return FALSE;
113 qnewsender = Ustrchr(newsender, '@')
114   ? newsender : string_sprintf("%s@%s", newsender, qualify_domain_sender);
115 return match_address_list_basic(qnewsender, CUSS &untrusted_set_sender, 0) == OK;
116 }
117
118
119
120
121 /*************************************************
122 *          Read space info for a partition       *
123 *************************************************/
124
125 /* This function is called by receive_check_fs() below, and also by string
126 expansion for variables such as $spool_space. The field names for the statvfs
127 structure are macros, because not all OS have F_FAVAIL and it seems tidier to
128 have macros for F_BAVAIL and F_FILES as well. Some kinds of file system do not
129 have inodes, and they return -1 for the number available.
130
131 Later: It turns out that some file systems that do not have the concept of
132 inodes return 0 rather than -1. Such systems should also return 0 for the total
133 number of inodes, so we require that to be greater than zero before returning
134 an inode count.
135
136 Arguments:
137   isspool       TRUE for spool partition, FALSE for log partition
138   inodeptr      address of int to receive inode count; -1 if there isn't one
139
140 Returns:        available on-root space, in kilobytes
141                 -1 for log partition if there isn't one
142
143 All values are -1 if the STATFS functions are not available.
144 */
145
146 int
147 receive_statvfs(BOOL isspool, int *inodeptr)
148 {
149 #ifdef HAVE_STATFS
150 struct STATVFS statbuf;
151 struct stat dummy;
152 uschar *path;
153 uschar *name;
154 uschar buffer[1024];
155
156 /* The spool directory must always exist. */
157
158 if (isspool)
159   {
160   path = spool_directory;
161   name = US"spool";
162   }
163
164 /* Need to cut down the log file path to the directory, and to ignore any
165 appearance of "syslog" in it. */
166
167 else
168   {
169   int sep = ':';              /* Not variable - outside scripts use */
170   const uschar *p = log_file_path;
171   name = US"log";
172
173   /* An empty log_file_path means "use the default". This is the same as an
174   empty item in a list. */
175
176   if (*p == 0) p = US":";
177   while ((path = string_nextinlist(&p, &sep, buffer, sizeof(buffer))))
178     if (Ustrcmp(path, "syslog") != 0)
179       break;
180
181   if (path == NULL)  /* No log files */
182     {
183     *inodeptr = -1;
184     return -1;
185     }
186
187   /* An empty string means use the default, which is in the spool directory.
188   But don't just use the spool directory, as it is possible that the log
189   subdirectory has been symbolically linked elsewhere. */
190
191   if (path[0] == 0)
192     {
193     sprintf(CS buffer, CS"%s/log", CS spool_directory);
194     path = buffer;
195     }
196   else
197     {
198     uschar *cp;
199     if ((cp = Ustrrchr(path, '/')) != NULL) *cp = 0;
200     }
201   }
202
203 /* We now have the path; do the business */
204
205 memset(&statbuf, 0, sizeof(statbuf));
206
207 if (STATVFS(CS path, &statbuf) != 0)
208   if (stat(CS path, &dummy) == -1 && errno == ENOENT)
209     {                           /* Can happen on first run after installation */
210     *inodeptr = -1;
211     return -1;
212     }
213   else
214     {
215     log_write(0, LOG_MAIN|LOG_PANIC, "cannot accept message: failed to stat "
216       "%s directory %s: %s", name, path, strerror(errno));
217     smtp_closedown(US"spool or log directory problem");
218     exim_exit(EXIT_FAILURE, NULL);
219     }
220
221 *inodeptr = (statbuf.F_FILES > 0)? statbuf.F_FAVAIL : -1;
222
223 /* Disks are getting huge. Take care with computing the size in kilobytes. */
224
225 return (int)(((double)statbuf.F_BAVAIL * (double)statbuf.F_FRSIZE)/1024.0);
226
227 #else
228 /* Unable to find partition sizes in this environment. */
229
230 *inodeptr = -1;
231 return -1;
232 #endif
233 }
234
235
236
237
238 /*************************************************
239 *     Check space on spool and log partitions    *
240 *************************************************/
241
242 /* This function is called before accepting a message; if any thresholds are
243 set, it checks them. If a message_size is supplied, it checks that there is
244 enough space for that size plus the threshold - i.e. that the message won't
245 reduce the space to the threshold. Not all OS have statvfs(); for those that
246 don't, this function always returns TRUE. For some OS the old function and
247 struct name statfs is used; that is handled by a macro, defined in exim.h.
248
249 Arguments:
250   msg_size     the (estimated) size of an incoming message
251
252 Returns:       FALSE if there isn't enough space, or if the information cannot
253                  be obtained
254                TRUE if no check was done or there is enough space
255 */
256
257 BOOL
258 receive_check_fs(int msg_size)
259 {
260 int space, inodes;
261
262 if (check_spool_space > 0 || msg_size > 0 || check_spool_inodes > 0)
263   {
264   space = receive_statvfs(TRUE, &inodes);
265
266   DEBUG(D_receive)
267     debug_printf("spool directory space = %dK inodes = %d "
268       "check_space = %dK inodes = %d msg_size = %d\n",
269       space, inodes, check_spool_space, check_spool_inodes, msg_size);
270
271   if ((space >= 0 && space < check_spool_space) ||
272       (inodes >= 0 && inodes < check_spool_inodes))
273     {
274     log_write(0, LOG_MAIN, "spool directory space check failed: space=%d "
275       "inodes=%d", space, inodes);
276     return FALSE;
277     }
278   }
279
280 if (check_log_space > 0 || check_log_inodes > 0)
281   {
282   space = receive_statvfs(FALSE, &inodes);
283
284   DEBUG(D_receive)
285     debug_printf("log directory space = %dK inodes = %d "
286       "check_space = %dK inodes = %d\n",
287       space, inodes, check_log_space, check_log_inodes);
288
289   if ((space >= 0 && space < check_log_space) ||
290       (inodes >= 0 && inodes < check_log_inodes))
291     {
292     log_write(0, LOG_MAIN, "log directory space check failed: space=%d "
293       "inodes=%d", space, inodes);
294     return FALSE;
295     }
296   }
297
298 return TRUE;
299 }
300
301
302
303 /*************************************************
304 *         Bomb out while reading a message       *
305 *************************************************/
306
307 /* The common case of wanting to bomb out is if a SIGTERM or SIGINT is
308 received, or if there is a timeout. A rarer case might be if the log files are
309 screwed up and Exim can't open them to record a message's arrival. Handling
310 that case is done by setting a flag to cause the log functions to call this
311 function if there is an ultimate disaster. That is why it is globally
312 accessible.
313
314 Arguments:
315   reason     text reason to pass to the not-quit ACL
316   msg        default SMTP response to give if in an SMTP session
317 Returns:     it doesn't
318 */
319
320 void
321 receive_bomb_out(uschar *reason, uschar *msg)
322 {
323   static BOOL already_bombing_out;
324 /* The smtp_notquit_exit() below can call ACLs which can trigger recursive
325 timeouts, if someone has something slow in their quit ACL.  Since the only
326 things we should be doing are to close down cleanly ASAP, on the second
327 pass we also close down stuff that might be opened again, before bypassing
328 the ACL call and exiting. */
329
330 /* If spool_name is set, it contains the name of the data file that is being
331 written. Unlink it before closing so that it cannot be picked up by a delivery
332 process. Ensure that any header file is also removed. */
333
334 if (spool_name[0] != '\0')
335   {
336   Uunlink(spool_name);
337   spool_name[Ustrlen(spool_name) - 1] = 'H';
338   Uunlink(spool_name);
339   spool_name[0] = '\0';
340   }
341
342 /* Now close the file if it is open, either as a fd or a stream. */
343
344 if (data_file)
345   {
346   (void)fclose(data_file);
347   data_file = NULL;
348   }
349 else if (data_fd >= 0)
350   {
351   (void)close(data_fd);
352   data_fd = -1;
353   }
354
355 /* Attempt to close down an SMTP connection tidily. For non-batched SMTP, call
356 smtp_notquit_exit(), which runs the NOTQUIT ACL, if present, and handles the
357 SMTP response. */
358
359 if (!already_bombing_out)
360   {
361   already_bombing_out = TRUE;
362   if (smtp_input)
363     {
364     if (smtp_batched_input)
365       moan_smtp_batch(NULL, "421 %s - message abandoned", msg);  /* No return */
366     smtp_notquit_exit(reason, US"421", US"%s %s - closing connection.",
367       smtp_active_hostname, msg);
368     }
369   }
370
371 /* Exit from the program (non-BSMTP cases) */
372
373 exim_exit(EXIT_FAILURE, NULL);
374 }
375
376
377 /*************************************************
378 *              Data read timeout                 *
379 *************************************************/
380
381 /* Handler function for timeouts that occur while reading the data that
382 comprises a message.
383
384 Argument:  the signal number
385 Returns:   nothing
386 */
387
388 static void
389 data_timeout_handler(int sig)
390 {
391 had_data_timeout = sig;
392 }
393
394
395
396 /*************************************************
397 *              local_scan() timeout              *
398 *************************************************/
399
400 /* Handler function for timeouts that occur while running a local_scan()
401 function.  Posix recommends against calling longjmp() from a signal-handler,
402 but the GCC manual says you can so we will, and trust that it's better than
403 calling probably non-signal-safe functions during logging from within the
404 handler, even with other compilers.
405
406 See also https://cwe.mitre.org/data/definitions/745.html which also lists
407 it as unsafe.
408
409 This is all because we have no control over what might be written for a
410 local-scan function, so cannot sprinkle had-signal checks after each
411 call-site.  At least with the default "do-nothing" function we won't
412 ever get here.
413
414 Argument:  the signal number
415 Returns:   nothing
416 */
417
418 static void
419 local_scan_timeout_handler(int sig)
420 {
421 had_local_scan_timeout = sig;
422 siglongjmp(local_scan_env, 1);
423 }
424
425
426
427 /*************************************************
428 *            local_scan() crashed                *
429 *************************************************/
430
431 /* Handler function for signals that occur while running a local_scan()
432 function.
433
434 Argument:  the signal number
435 Returns:   nothing
436 */
437
438 static void
439 local_scan_crash_handler(int sig)
440 {
441 had_local_scan_crash = sig;
442 siglongjmp(local_scan_env, 1);
443 }
444
445
446
447 /*************************************************
448 *           SIGTERM or SIGINT received           *
449 *************************************************/
450
451 /* Handler for SIGTERM or SIGINT signals that occur while reading the
452 data that comprises a message.
453
454 Argument:  the signal number
455 Returns:   nothing
456 */
457
458 static void
459 data_sigterm_sigint_handler(int sig)
460 {
461 had_data_sigint = sig;
462 }
463
464
465
466 /*************************************************
467 *          Add new recipient to list             *
468 *************************************************/
469
470 /* This function builds a list of recipient addresses in argc/argv
471 format.
472
473 Arguments:
474   recipient   the next address to add to recipients_list
475   pno         parent number for fixed aliases; -1 otherwise
476
477 Returns:      nothing
478 */
479
480 void
481 receive_add_recipient(uschar *recipient, int pno)
482 {
483 if (recipients_count >= recipients_list_max)
484   {
485   recipient_item *oldlist = recipients_list;
486   int oldmax = recipients_list_max;
487   recipients_list_max = recipients_list_max? 2*recipients_list_max : 50;
488   recipients_list = store_get(recipients_list_max * sizeof(recipient_item));
489   if (oldlist != NULL)
490     memcpy(recipients_list, oldlist, oldmax * sizeof(recipient_item));
491   }
492
493 recipients_list[recipients_count].address = recipient;
494 recipients_list[recipients_count].pno = pno;
495 #ifdef EXPERIMENTAL_BRIGHTMAIL
496 recipients_list[recipients_count].bmi_optin = bmi_current_optin;
497 /* reset optin string pointer for next recipient */
498 bmi_current_optin = NULL;
499 #endif
500 recipients_list[recipients_count].orcpt = NULL;
501 recipients_list[recipients_count].dsn_flags = 0;
502 recipients_list[recipients_count++].errors_to = NULL;
503 }
504
505
506
507
508 /*************************************************
509 *        Send user response message              *
510 *************************************************/
511
512 /* This function is passed a default response code and a user message. It calls
513 smtp_message_code() to check and possibly modify the response code, and then
514 calls smtp_respond() to transmit the response. I put this into a function
515 just to avoid a lot of repetition.
516
517 Arguments:
518   code         the response code
519   user_msg     the user message
520
521 Returns:       nothing
522 */
523
524 #ifndef DISABLE_PRDR
525 static void
526 smtp_user_msg(uschar *code, uschar *user_msg)
527 {
528 int len = 3;
529 smtp_message_code(&code, &len, &user_msg, NULL, TRUE);
530 smtp_respond(code, len, TRUE, user_msg);
531 }
532 #endif
533
534
535
536
537
538 /*************************************************
539 *        Remove a recipient from the list        *
540 *************************************************/
541
542 /* This function is provided for local_scan() to use.
543
544 Argument:
545   recipient   address to remove
546
547 Returns:      TRUE if it did remove something; FALSE otherwise
548 */
549
550 BOOL
551 receive_remove_recipient(uschar *recipient)
552 {
553 int count;
554 DEBUG(D_receive) debug_printf("receive_remove_recipient(\"%s\") called\n",
555   recipient);
556 for (count = 0; count < recipients_count; count++)
557   {
558   if (Ustrcmp(recipients_list[count].address, recipient) == 0)
559     {
560     if ((--recipients_count - count) > 0)
561       memmove(recipients_list + count, recipients_list + count + 1,
562         (recipients_count - count)*sizeof(recipient_item));
563     return TRUE;
564     }
565   }
566 return FALSE;
567 }
568
569
570
571
572
573 /*************************************************
574 *     Read data portion of a non-SMTP message    *
575 *************************************************/
576
577 /* This function is called to read the remainder of a message (following the
578 header) when the input is not from SMTP - we are receiving a local message on
579 a standard input stream. The message is always terminated by EOF, and is also
580 terminated by a dot on a line by itself if the flag dot_ends is TRUE. Split the
581 two cases for maximum efficiency.
582
583 Ensure that the body ends with a newline. This will naturally be the case when
584 the termination is "\n.\n" but may not be otherwise. The RFC defines messages
585 as "sequences of lines" - this of course strictly applies only to SMTP, but
586 deliveries into BSD-type mailbox files also require it. Exim used to have a
587 flag for doing this at delivery time, but as it was always set for all
588 transports, I decided to simplify things by putting the check here instead.
589
590 There is at least one MUA (dtmail) that sends CRLF via this interface, and
591 other programs are known to do this as well. Exim used to have a option for
592 dealing with this: in July 2003, after much discussion, the code has been
593 changed to default to treat any of LF, CRLF, and bare CR as line terminators.
594
595 However, for the case when a dot on a line by itself terminates a message, the
596 only recognized terminating sequences before and after the dot are LF and CRLF.
597 Otherwise, having read EOL . CR, you don't know whether to read another
598 character or not.
599
600 Internally, in messages stored in Exim's spool files, LF is used as the line
601 terminator. Under the new regime, bare CRs will no longer appear in these
602 files.
603
604 Arguments:
605   fout      a FILE to which to write the message
606
607 Returns:    One of the END_xxx values indicating why it stopped reading
608 */
609
610 static int
611 read_message_data(FILE *fout)
612 {
613 int ch_state;
614 register int ch;
615 register int linelength = 0;
616
617 /* Handle the case when only EOF terminates the message */
618
619 if (!dot_ends)
620   {
621   register int last_ch = '\n';
622
623   for (; (ch = (receive_getc)(GETC_BUFFER_UNLIMITED)) != EOF; last_ch = ch)
624     {
625     if (ch == 0) body_zerocount++;
626     if (last_ch == '\r' && ch != '\n')
627       {
628       if (linelength > max_received_linelength)
629         max_received_linelength = linelength;
630       linelength = 0;
631       if (fputc('\n', fout) == EOF) return END_WERROR;
632       message_size++;
633       body_linecount++;
634       }
635     if (ch == '\r') continue;
636
637     if (fputc(ch, fout) == EOF) return END_WERROR;
638     if (ch == '\n')
639       {
640       if (linelength > max_received_linelength)
641         max_received_linelength = linelength;
642       linelength = 0;
643       body_linecount++;
644       }
645     else linelength++;
646     if (++message_size > thismessage_size_limit) return END_SIZE;
647     }
648
649   if (last_ch != '\n')
650     {
651     if (linelength > max_received_linelength)
652       max_received_linelength = linelength;
653     if (fputc('\n', fout) == EOF) return END_WERROR;
654     message_size++;
655     body_linecount++;
656     }
657
658   return END_EOF;
659   }
660
661 /* Handle the case when a dot on a line on its own, or EOF, terminates. */
662
663 ch_state = 1;
664
665 while ((ch = (receive_getc)(GETC_BUFFER_UNLIMITED)) != EOF)
666   {
667   if (ch == 0) body_zerocount++;
668   switch (ch_state)
669     {
670     case 0:                         /* Normal state (previous char written) */
671     if (ch == '\n')
672       {
673       body_linecount++;
674       if (linelength > max_received_linelength)
675         max_received_linelength = linelength;
676       linelength = -1;
677       ch_state = 1;
678       }
679     else if (ch == '\r')
680       { ch_state = 2; continue; }
681     break;
682
683     case 1:                         /* After written "\n" */
684     if (ch == '.') { ch_state = 3; continue; }
685     if (ch == '\r') { ch_state = 2; continue; }
686     if (ch == '\n') { body_linecount++; linelength = -1; }
687     else ch_state = 0;
688     break;
689
690     case 2:
691     body_linecount++;               /* After unwritten "\r" */
692     if (linelength > max_received_linelength)
693       max_received_linelength = linelength;
694     if (ch == '\n')
695       {
696       ch_state = 1;
697       linelength = -1;
698       }
699     else
700       {
701       if (message_size++, fputc('\n', fout) == EOF) return END_WERROR;
702       if (ch == '\r') continue;
703       ch_state = 0;
704       linelength = 0;
705       }
706     break;
707
708     case 3:                         /* After "\n." (\n written, dot not) */
709     if (ch == '\n') return END_DOT;
710     if (ch == '\r') { ch_state = 4; continue; }
711     message_size++;
712     linelength++;
713     if (fputc('.', fout) == EOF) return END_WERROR;
714     ch_state = 0;
715     break;
716
717     case 4:                         /* After "\n.\r" (\n written, rest not) */
718     if (ch == '\n') return END_DOT;
719     message_size += 2;
720     body_linecount++;
721     if (fputs(".\n", fout) == EOF) return END_WERROR;
722     if (ch == '\r') { ch_state = 2; continue; }
723     ch_state = 0;
724     break;
725     }
726
727   linelength++;
728   if (fputc(ch, fout) == EOF) return END_WERROR;
729   if (++message_size > thismessage_size_limit) return END_SIZE;
730   }
731
732 /* Get here if EOF read. Unless we have just written "\n", we need to ensure
733 the message ends with a newline, and we must also write any characters that
734 were saved up while testing for an ending dot. */
735
736 if (ch_state != 1)
737   {
738   static uschar *ends[] = { US"\n", NULL, US"\n", US".\n", US".\n" };
739   if (fputs(CS ends[ch_state], fout) == EOF) return END_WERROR;
740   message_size += Ustrlen(ends[ch_state]);
741   body_linecount++;
742   }
743
744 return END_EOF;
745 }
746
747
748
749
750 /*************************************************
751 *      Read data portion of an SMTP message      *
752 *************************************************/
753
754 /* This function is called to read the remainder of an SMTP message (after the
755 headers), or to skip over it when an error has occurred. In this case, the
756 output file is passed as NULL.
757
758 If any line begins with a dot, that character is skipped. The input should only
759 be successfully terminated by CR LF . CR LF unless it is local (non-network)
760 SMTP, in which case the CRs are optional, but...
761
762 FUDGE: It seems that sites on the net send out messages with just LF
763 terminators, despite the warnings in the RFCs, and other MTAs handle this. So
764 we make the CRs optional in all cases.
765
766 July 2003: Bare CRs cause trouble. We now treat them as line terminators as
767 well, so that there are no CRs in spooled messages. However, the message
768 terminating dot is not recognized between two bare CRs.
769
770 Arguments:
771   fout      a FILE to which to write the message; NULL if skipping
772
773 Returns:    One of the END_xxx values indicating why it stopped reading
774 */
775
776 static int
777 read_message_data_smtp(FILE *fout)
778 {
779 int ch_state = 0;
780 int ch;
781 int linelength = 0;
782
783 while ((ch = (receive_getc)(GETC_BUFFER_UNLIMITED)) != EOF)
784   {
785   if (ch == 0) body_zerocount++;
786   switch (ch_state)
787     {
788     case 0:                             /* After LF or CRLF */
789     if (ch == '.')
790       {
791       ch_state = 3;
792       continue;                         /* Don't ever write . after LF */
793       }
794     ch_state = 1;
795
796     /* Else fall through to handle as normal uschar. */
797
798     case 1:                             /* Normal state */
799     if (ch == '\n')
800       {
801       ch_state = 0;
802       body_linecount++;
803       if (linelength > max_received_linelength)
804         max_received_linelength = linelength;
805       linelength = -1;
806       }
807     else if (ch == '\r')
808       {
809       ch_state = 2;
810       continue;
811       }
812     break;
813
814     case 2:                             /* After (unwritten) CR */
815     body_linecount++;
816     if (linelength > max_received_linelength)
817       max_received_linelength = linelength;
818     linelength = -1;
819     if (ch == '\n')
820       {
821       ch_state = 0;
822       }
823     else
824       {
825       message_size++;
826       if (fout != NULL && fputc('\n', fout) == EOF) return END_WERROR;
827       cutthrough_data_put_nl();
828       if (ch != '\r') ch_state = 1; else continue;
829       }
830     break;
831
832     case 3:                             /* After [CR] LF . */
833     if (ch == '\n')
834       return END_DOT;
835     if (ch == '\r')
836       {
837       ch_state = 4;
838       continue;
839       }
840     /* The dot was removed at state 3. For a doubled dot, here, reinstate
841     it to cutthrough. The current ch, dot or not, is passed both to cutthrough
842     and to file below. */
843     if (ch == '.')
844       {
845       uschar c= ch;
846       cutthrough_data_puts(&c, 1);
847       }
848     ch_state = 1;
849     break;
850
851     case 4:                             /* After [CR] LF . CR */
852     if (ch == '\n') return END_DOT;
853     message_size++;
854     body_linecount++;
855     if (fout != NULL && fputc('\n', fout) == EOF) return END_WERROR;
856     cutthrough_data_put_nl();
857     if (ch == '\r')
858       {
859       ch_state = 2;
860       continue;
861       }
862     ch_state = 1;
863     break;
864     }
865
866   /* Add the character to the spool file, unless skipping; then loop for the
867   next. */
868
869   message_size++;
870   linelength++;
871   if (fout)
872     {
873     if (fputc(ch, fout) == EOF) return END_WERROR;
874     if (message_size > thismessage_size_limit) return END_SIZE;
875     }
876   if(ch == '\n')
877     cutthrough_data_put_nl();
878   else
879     {
880     uschar c = ch;
881     cutthrough_data_puts(&c, 1);
882     }
883   }
884
885 /* Fall through here if EOF encountered. This indicates some kind of error,
886 since a correct message is terminated by [CR] LF . [CR] LF. */
887
888 return END_EOF;
889 }
890
891
892
893
894 /* Variant of the above read_message_data_smtp() specialised for RFC 3030
895 CHUNKING. Accept input lines separated by either CRLF or CR or LF and write
896 LF-delimited spoolfile.  Until we have wireformat spoolfiles, we need the
897 body_linecount accounting for proper re-expansion for the wire, so use
898 a cut-down version of the state-machine above; we don't need to do leading-dot
899 detection and unstuffing.
900
901 Arguments:
902   fout      a FILE to which to write the message; NULL if skipping;
903             must be open for both writing and reading.
904
905 Returns:    One of the END_xxx values indicating why it stopped reading
906 */
907
908 static int
909 read_message_bdat_smtp(FILE *fout)
910 {
911 int linelength = 0, ch;
912 enum CH_STATE ch_state = LF_SEEN;
913 BOOL fix_nl = FALSE;
914
915 for(;;)
916   {
917   switch ((ch = bdat_getc(GETC_BUFFER_UNLIMITED)))
918     {
919     case EOF:   return END_EOF;
920     case ERR:   return END_PROTOCOL;
921     case EOD:
922       /* Nothing to get from the sender anymore. We check the last
923       character written to the spool.
924
925       RFC 3030 states, that BDAT chunks are normal text, terminated by CRLF.
926       If we would be strict, we would refuse such broken messages.
927       But we are liberal, so we fix it.  It would be easy just to append
928       the "\n" to the spool.
929
930       But there are some more things (line counting, message size calculation and such),
931       that would need to be duplicated here.  So we simply do some ungetc
932       trickery.
933       */
934       if (fout)
935         {
936         if (fseek(fout, -1, SEEK_CUR) < 0)      return END_PROTOCOL;
937         if (fgetc(fout) == '\n')                return END_DOT;
938         }
939
940       if (linelength == -1)    /* \r already seen (see below) */
941         {
942         DEBUG(D_receive) debug_printf("Add missing LF\n");
943         bdat_ungetc('\n');
944         continue;
945         }
946       DEBUG(D_receive) debug_printf("Add missing CRLF\n");
947       bdat_ungetc('\r');      /* not even \r was seen */
948       fix_nl = TRUE;
949
950       continue;
951     case '\0':  body_zerocount++; break;
952     }
953   switch (ch_state)
954     {
955     case LF_SEEN:                             /* After LF or CRLF */
956       ch_state = MID_LINE;
957       /* fall through to handle as normal uschar. */
958
959     case MID_LINE:                            /* Mid-line state */
960       if (ch == '\n')
961         {
962         ch_state = LF_SEEN;
963         body_linecount++;
964         if (linelength > max_received_linelength)
965           max_received_linelength = linelength;
966         linelength = -1;
967         }
968       else if (ch == '\r')
969         {
970         ch_state = CR_SEEN;
971        if (fix_nl) bdat_ungetc('\n');
972         continue;                       /* don't write CR */
973         }
974       break;
975
976     case CR_SEEN:                       /* After (unwritten) CR */
977       body_linecount++;
978       if (linelength > max_received_linelength)
979         max_received_linelength = linelength;
980       linelength = -1;
981       if (ch == '\n')
982         ch_state = LF_SEEN;
983       else
984         {
985         message_size++;
986         if (fout && fputc('\n', fout) == EOF) return END_WERROR;
987         cutthrough_data_put_nl();
988         if (ch == '\r') continue;       /* don't write CR */
989         ch_state = MID_LINE;
990         }
991       break;
992     }
993
994   /* Add the character to the spool file, unless skipping */
995
996   message_size++;
997   linelength++;
998   if (fout)
999     {
1000     if (fputc(ch, fout) == EOF) return END_WERROR;
1001     if (message_size > thismessage_size_limit) return END_SIZE;
1002     }
1003   if(ch == '\n')
1004     cutthrough_data_put_nl();
1005   else
1006     {
1007     uschar c = ch;
1008     cutthrough_data_puts(&c, 1);
1009     }
1010   }
1011 /*NOTREACHED*/
1012 }
1013
1014 static int
1015 read_message_bdat_smtp_wire(FILE *fout)
1016 {
1017 int ch;
1018
1019 /* Remember that this message uses wireformat. */
1020
1021 DEBUG(D_receive) debug_printf("CHUNKING: %s\n",
1022         fout ? "writing spoolfile in wire format" : "flushing input");
1023 spool_file_wireformat = TRUE;
1024
1025 for (;;)
1026   {
1027   if (chunking_data_left > 0)
1028     {
1029     unsigned len = MAX(chunking_data_left, thismessage_size_limit - message_size + 1);
1030     uschar * buf = bdat_getbuf(&len);
1031
1032     if (!buf) return END_EOF;
1033     message_size += len;
1034     if (fout && fwrite(buf, len, 1, fout) != 1) return END_WERROR;
1035     }
1036   else switch (ch = bdat_getc(GETC_BUFFER_UNLIMITED))
1037     {
1038     case EOF: return END_EOF;
1039     case EOD: return END_DOT;
1040     case ERR: return END_PROTOCOL;
1041
1042     default:
1043       message_size++;
1044   /*XXX not done:
1045   linelength
1046   max_received_linelength
1047   body_linecount
1048   body_zerocount
1049   */
1050       if (fout && fputc(ch, fout) == EOF) return END_WERROR;
1051       break;
1052     }
1053   if (message_size > thismessage_size_limit) return END_SIZE;
1054   }
1055 /*NOTREACHED*/
1056 }
1057
1058
1059
1060
1061 /*************************************************
1062 *             Swallow SMTP message               *
1063 *************************************************/
1064
1065 /* This function is called when there has been some kind of error while reading
1066 an SMTP message, and the remaining data may need to be swallowed. It is global
1067 because it is called from smtp_closedown() to shut down an incoming call
1068 tidily.
1069
1070 Argument:    a FILE from which to read the message
1071 Returns:     nothing
1072 */
1073
1074 void
1075 receive_swallow_smtp(void)
1076 {
1077 if (message_ended >= END_NOTENDED)
1078   message_ended = chunking_state <= CHUNKING_OFFERED
1079      ? read_message_data_smtp(NULL)
1080      : read_message_bdat_smtp_wire(NULL);
1081 }
1082
1083
1084
1085 /*************************************************
1086 *           Handle lost SMTP connection          *
1087 *************************************************/
1088
1089 /* This function logs connection loss incidents and generates an appropriate
1090 SMTP response.
1091
1092 Argument:  additional data for the message
1093 Returns:   the SMTP response
1094 */
1095
1096 static uschar *
1097 handle_lost_connection(uschar *s)
1098 {
1099 log_write(L_lost_incoming_connection | L_smtp_connection, LOG_MAIN,
1100   "%s lost while reading message data%s", smtp_get_connection_info(), s);
1101 smtp_notquit_exit(US"connection-lost", NULL, NULL);
1102 return US"421 Lost incoming connection";
1103 }
1104
1105
1106
1107
1108 /*************************************************
1109 *         Handle a non-smtp reception error      *
1110 *************************************************/
1111
1112 /* This function is called for various errors during the reception of non-SMTP
1113 messages. It either sends a message to the sender of the problem message, or it
1114 writes to the standard error stream.
1115
1116 Arguments:
1117   errcode     code for moan_to_sender(), identifying the error
1118   text1       first message text, passed to moan_to_sender()
1119   text2       second message text, used only for stderrr
1120   error_rc    code to pass to exim_exit if no problem
1121   f           FILE containing body of message (may be stdin)
1122   hptr        pointer to instore headers or NULL
1123
1124 Returns:      calls exim_exit(), which does not return
1125 */
1126
1127 static void
1128 give_local_error(int errcode, uschar *text1, uschar *text2, int error_rc,
1129   FILE *f, header_line *hptr)
1130 {
1131 if (error_handling == ERRORS_SENDER)
1132   {
1133   error_block eblock;
1134   eblock.next = NULL;
1135   eblock.text1 = text1;
1136   eblock.text2 = US"";
1137   if (!moan_to_sender(errcode, &eblock, hptr, f, FALSE))
1138     error_rc = EXIT_FAILURE;
1139   }
1140 else
1141   fprintf(stderr, "exim: %s%s\n", text2, text1);  /* Sic */
1142 (void)fclose(f);
1143 exim_exit(error_rc, US"");
1144 }
1145
1146
1147
1148 /*************************************************
1149 *          Add header lines set up by ACL        *
1150 *************************************************/
1151
1152 /* This function is called to add the header lines that were set up by
1153 statements in an ACL to the list of headers in memory. It is done in two stages
1154 like this, because when the ACL for RCPT is running, the other headers have not
1155 yet been received. This function is called twice; once just before running the
1156 DATA ACL, and once after. This is so that header lines added by MAIL or RCPT
1157 are visible to the DATA ACL.
1158
1159 Originally these header lines were added at the end. Now there is support for
1160 three different places: top, bottom, and after the Received: header(s). There
1161 will always be at least one Received: header, even if it is marked deleted, and
1162 even if something else has been put in front of it.
1163
1164 Arguments:
1165   acl_name   text to identify which ACL
1166
1167 Returns:     nothing
1168 */
1169
1170 static void
1171 add_acl_headers(int where, uschar *acl_name)
1172 {
1173 header_line *h, *next;
1174 header_line *last_received = NULL;
1175
1176 switch(where)
1177   {
1178   case ACL_WHERE_DKIM:
1179   case ACL_WHERE_MIME:
1180   case ACL_WHERE_DATA:
1181     if (  cutthrough.fd >= 0 && cutthrough.delivery
1182        && (acl_removed_headers || acl_added_headers))
1183     {
1184     log_write(0, LOG_MAIN|LOG_PANIC, "Header modification in data ACLs"
1185                         " will not take effect on cutthrough deliveries");
1186     return;
1187     }
1188   }
1189
1190 if (acl_removed_headers)
1191   {
1192   DEBUG(D_receive|D_acl) debug_printf_indent(">>Headers removed by %s ACL:\n", acl_name);
1193
1194   for (h = header_list; h; h = h->next) if (h->type != htype_old)
1195     {
1196     const uschar * list = acl_removed_headers;
1197     int sep = ':';         /* This is specified as a colon-separated list */
1198     uschar *s;
1199     uschar buffer[128];
1200
1201     while ((s = string_nextinlist(&list, &sep, buffer, sizeof(buffer))))
1202       if (header_testname(h, s, Ustrlen(s), FALSE))
1203         {
1204         h->type = htype_old;
1205         DEBUG(D_receive|D_acl) debug_printf_indent("  %s", h->text);
1206         }
1207     }
1208   acl_removed_headers = NULL;
1209   DEBUG(D_receive|D_acl) debug_printf_indent(">>\n");
1210   }
1211
1212 if (!acl_added_headers) return;
1213 DEBUG(D_receive|D_acl) debug_printf_indent(">>Headers added by %s ACL:\n", acl_name);
1214
1215 for (h = acl_added_headers; h; h = next)
1216   {
1217   next = h->next;
1218
1219   switch(h->type)
1220     {
1221     case htype_add_top:
1222       h->next = header_list;
1223       header_list = h;
1224       DEBUG(D_receive|D_acl) debug_printf_indent("  (at top)");
1225       break;
1226
1227     case htype_add_rec:
1228       if (!last_received)
1229         {
1230         last_received = header_list;
1231         while (!header_testname(last_received, US"Received", 8, FALSE))
1232           last_received = last_received->next;
1233         while (last_received->next &&
1234                header_testname(last_received->next, US"Received", 8, FALSE))
1235           last_received = last_received->next;
1236         }
1237       h->next = last_received->next;
1238       last_received->next = h;
1239       DEBUG(D_receive|D_acl) debug_printf_indent("  (after Received:)");
1240       break;
1241
1242     case htype_add_rfc:
1243       /* add header before any header which is NOT Received: or Resent- */
1244       last_received = header_list;
1245       while ( last_received->next &&
1246               ( (header_testname(last_received->next, US"Received", 8, FALSE)) ||
1247                 (header_testname_incomplete(last_received->next, US"Resent-", 7, FALSE)) ) )
1248                 last_received = last_received->next;
1249       /* last_received now points to the last Received: or Resent-* header
1250          in an uninterrupted chain of those header types (seen from the beginning
1251          of all headers. Our current header must follow it. */
1252       h->next = last_received->next;
1253       last_received->next = h;
1254       DEBUG(D_receive|D_acl) debug_printf_indent("  (before any non-Received: or Resent-*: header)");
1255       break;
1256
1257     default:
1258       h->next = NULL;
1259       header_last->next = h;
1260       DEBUG(D_receive|D_acl) debug_printf_indent("  ");
1261       break;
1262     }
1263
1264   if (!h->next) header_last = h;
1265
1266   /* Check for one of the known header types (From:, To:, etc.) though in
1267   practice most added headers are going to be "other". Lower case
1268   identification letters are never stored with the header; they are used
1269   for existence tests when messages are received. So discard any lower case
1270   flag values. */
1271
1272   h->type = header_checkname(h, FALSE);
1273   if (h->type >= 'a') h->type = htype_other;
1274
1275   DEBUG(D_receive|D_acl) debug_printf("%s", h->text);
1276   }
1277
1278 acl_added_headers = NULL;
1279 DEBUG(D_receive|D_acl) debug_printf_indent(">>\n");
1280 }
1281
1282
1283
1284 /*************************************************
1285 *       Add host information for log line        *
1286 *************************************************/
1287
1288 /* Called for acceptance and rejecting log lines. This adds information about
1289 the calling host to a string that is being built dynamically.
1290
1291 Arguments:
1292   s           the dynamic string
1293
1294 Returns:      the extended string
1295 */
1296
1297 static gstring *
1298 add_host_info_for_log(gstring * g)
1299 {
1300 if (sender_fullhost)
1301   {
1302   if (LOGGING(dnssec) && sender_host_dnssec)    /*XXX sender_helo_dnssec? */
1303     g = string_catn(g, US" DS", 3);
1304   g = string_append(g, 2, US" H=", sender_fullhost);
1305   if (LOGGING(incoming_interface) && interface_address != NULL)
1306     {
1307     g = string_cat(g,
1308       string_sprintf(" I=[%s]:%d", interface_address, interface_port));
1309     }
1310   }
1311 if (tcp_in_fastopen && !tcp_in_fastopen_logged)
1312   {
1313   g = string_catn(g, US" TFO", 4);
1314   tcp_in_fastopen_logged = TRUE;
1315   }
1316 if (sender_ident)
1317   g = string_append(g, 2, US" U=", sender_ident);
1318 if (received_protocol)
1319   g = string_append(g, 2, US" P=", received_protocol);
1320 return g;
1321 }
1322
1323
1324
1325 #ifdef WITH_CONTENT_SCAN
1326
1327 /*************************************************
1328 *       Run the MIME ACL on a message            *
1329 *************************************************/
1330
1331 /* This code is in a subroutine so that it can be used for both SMTP
1332 and non-SMTP messages. It is called with a non-NULL ACL pointer.
1333
1334 Arguments:
1335   acl                The ACL to run (acl_smtp_mime or acl_not_smtp_mime)
1336   smtp_yield_ptr     Set FALSE to kill messages after dropped connection
1337   smtp_reply_ptr     Where SMTP reply is being built
1338   blackholed_by_ptr  Where "blackholed by" message is being built
1339
1340 Returns:             TRUE to carry on; FALSE to abandon the message
1341 */
1342
1343 static BOOL
1344 run_mime_acl(uschar *acl, BOOL *smtp_yield_ptr, uschar **smtp_reply_ptr,
1345   uschar **blackholed_by_ptr)
1346 {
1347 FILE *mbox_file;
1348 uschar * rfc822_file_path = NULL;
1349 unsigned long mbox_size;
1350 header_line *my_headerlist;
1351 uschar *user_msg, *log_msg;
1352 int mime_part_count_buffer = -1;
1353 uschar * mbox_filename;
1354 int rc = OK;
1355
1356 /* check if it is a MIME message */
1357
1358 for (my_headerlist = header_list; my_headerlist; my_headerlist = my_headerlist->next)
1359   if (  my_headerlist->type != '*'                      /* skip deleted headers */
1360      && strncmpic(my_headerlist->text, US"Content-Type:", 13) == 0
1361      )
1362     {
1363     DEBUG(D_receive) debug_printf("Found Content-Type: header - executing acl_smtp_mime.\n");
1364     goto DO_MIME_ACL;
1365     }
1366
1367 DEBUG(D_receive) debug_printf("No Content-Type: header - presumably not a MIME message.\n");
1368 return TRUE;
1369
1370 DO_MIME_ACL:
1371
1372 /* make sure the eml mbox file is spooled up */
1373 if (!(mbox_file = spool_mbox(&mbox_size, NULL, &mbox_filename)))
1374   {                                                             /* error while spooling */
1375   log_write(0, LOG_MAIN|LOG_PANIC,
1376          "acl_smtp_mime: error while creating mbox spool file, message temporarily rejected.");
1377   Uunlink(spool_name);
1378   unspool_mbox();
1379 #ifdef EXPERIMENTAL_DCC
1380   dcc_ok = 0;
1381 #endif
1382   smtp_respond(US"451", 3, TRUE, US"temporary local problem");
1383   message_id[0] = 0;            /* Indicate no message accepted */
1384   *smtp_reply_ptr = US"";       /* Indicate reply already sent */
1385   return FALSE;                 /* Indicate skip to end of receive function */
1386   }
1387
1388 mime_is_rfc822 = 0;
1389
1390 MIME_ACL_CHECK:
1391 mime_part_count = -1;
1392 rc = mime_acl_check(acl, mbox_file, NULL, &user_msg, &log_msg);
1393 (void)fclose(mbox_file);
1394
1395 if (rfc822_file_path)
1396   {
1397   mime_part_count = mime_part_count_buffer;
1398
1399   if (unlink(CS rfc822_file_path) == -1)
1400     {
1401     log_write(0, LOG_PANIC,
1402          "acl_smtp_mime: can't unlink RFC822 spool file, skipping.");
1403     goto END_MIME_ACL;
1404     }
1405   rfc822_file_path = NULL;
1406   }
1407
1408 /* check if we must check any message/rfc822 attachments */
1409 if (rc == OK)
1410   {
1411   uschar * scandir = string_copyn(mbox_filename,
1412               Ustrrchr(mbox_filename, '/') - mbox_filename);
1413   struct dirent * entry;
1414   DIR * tempdir;
1415
1416   for (tempdir = opendir(CS scandir); entry = readdir(tempdir); )
1417     if (strncmpic(US entry->d_name, US"__rfc822_", 9) == 0)
1418       {
1419       rfc822_file_path = string_sprintf("%s/%s", scandir, entry->d_name);
1420       DEBUG(D_receive)
1421         debug_printf("RFC822 attachment detected: running MIME ACL for '%s'\n",
1422           rfc822_file_path);
1423       break;
1424       }
1425   closedir(tempdir);
1426
1427   if (rfc822_file_path)
1428     {
1429     if ((mbox_file = Ufopen(rfc822_file_path, "rb")))
1430       {
1431       /* set RFC822 expansion variable */
1432       mime_is_rfc822 = 1;
1433       mime_part_count_buffer = mime_part_count;
1434       goto MIME_ACL_CHECK;
1435       }
1436     log_write(0, LOG_PANIC,
1437        "acl_smtp_mime: can't open RFC822 spool file, skipping.");
1438     unlink(CS rfc822_file_path);
1439     }
1440   }
1441
1442 END_MIME_ACL:
1443 add_acl_headers(ACL_WHERE_MIME, US"MIME");
1444 if (rc == DISCARD)
1445   {
1446   recipients_count = 0;
1447   *blackholed_by_ptr = US"MIME ACL";
1448   }
1449 else if (rc != OK)
1450   {
1451   Uunlink(spool_name);
1452   unspool_mbox();
1453 #ifdef EXPERIMENTAL_DCC
1454   dcc_ok = 0;
1455 #endif
1456   if (smtp_input)
1457     {
1458     if (smtp_handle_acl_fail(ACL_WHERE_MIME, rc, user_msg, log_msg) != 0)
1459       *smtp_yield_ptr = FALSE;  /* No more messages after dropped connection */
1460     *smtp_reply_ptr = US"";     /* Indicate reply already sent */
1461     }
1462   message_id[0] = 0;            /* Indicate no message accepted */
1463   return FALSE;                 /* Cause skip to end of receive function */
1464   }
1465
1466 return TRUE;
1467 }
1468
1469 #endif  /* WITH_CONTENT_SCAN */
1470
1471
1472
1473 void
1474 received_header_gen(void)
1475 {
1476 uschar *received;
1477 uschar *timestamp;
1478 header_line *received_header= header_list;
1479
1480 timestamp = expand_string(US"${tod_full}");
1481 if (recipients_count == 1) received_for = recipients_list[0].address;
1482 received = expand_string(received_header_text);
1483 received_for = NULL;
1484
1485 if (!received)
1486   {
1487   if(spool_name[0] != 0)
1488     Uunlink(spool_name);           /* Lose the data file */
1489   log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Expansion of \"%s\" "
1490     "(received_header_text) failed: %s", string_printing(received_header_text),
1491       expand_string_message);
1492   }
1493
1494 /* The first element on the header chain is reserved for the Received header,
1495 so all we have to do is fill in the text pointer, and set the type. However, if
1496 the result of the expansion is an empty string, we leave the header marked as
1497 "old" so as to refrain from adding a Received header. */
1498
1499 if (received[0] == 0)
1500   {
1501   received_header->text = string_sprintf("Received: ; %s\n", timestamp);
1502   received_header->type = htype_old;
1503   }
1504 else
1505   {
1506   received_header->text = string_sprintf("%s; %s\n", received, timestamp);
1507   received_header->type = htype_received;
1508   }
1509
1510 received_header->slen = Ustrlen(received_header->text);
1511
1512 DEBUG(D_receive) debug_printf(">>Generated Received: header line\n%c %s",
1513   received_header->type, received_header->text);
1514 }
1515
1516
1517
1518 /*************************************************
1519 *                 Receive message                *
1520 *************************************************/
1521
1522 /* Receive a message on the given input, and put it into a pair of spool files.
1523 Either a non-null list of recipients, or the extract flag will be true, or
1524 both. The flag sender_local is true for locally generated messages. The flag
1525 submission_mode is true if an ACL has obeyed "control = submission". The flag
1526 suppress_local_fixups is true if an ACL has obeyed "control =
1527 suppress_local_fixups" or -G was passed on the command-line.
1528 The flag smtp_input is true if the message is to be
1529 handled using SMTP conventions about termination and lines starting with dots.
1530 For non-SMTP messages, dot_ends is true for dot-terminated messages.
1531
1532 If a message was successfully read, message_id[0] will be non-zero.
1533
1534 The general actions of this function are:
1535
1536   . Read the headers of the message (if any) into a chain of store
1537     blocks.
1538
1539   . If there is a "sender:" header and the message is locally originated,
1540     throw it away, unless the caller is trusted, or unless
1541     active_local_sender_retain is set - which can only happen if
1542     active_local_from_check is false.
1543
1544   . If recipients are to be extracted from the message, build the
1545     recipients list from the headers, removing any that were on the
1546     original recipients list (unless extract_addresses_remove_arguments is
1547     false), and at the same time, remove any bcc header that may be present.
1548
1549   . Get the spool file for the data, sort out its unique name, open
1550     and lock it (but don't give it the name yet).
1551
1552   . Generate a "Message-Id" header if the message doesn't have one, for
1553     locally-originated messages.
1554
1555   . Generate a "Received" header.
1556
1557   . Ensure the recipients list is fully qualified and rewritten if necessary.
1558
1559   . If there are any rewriting rules, apply them to the sender address
1560     and also to the headers.
1561
1562   . If there is no from: header, generate one, for locally-generated messages
1563     and messages in "submission mode" only.
1564
1565   . If the sender is local, check that from: is correct, and if not, generate
1566     a Sender: header, unless message comes from a trusted caller, or this
1567     feature is disabled by active_local_from_check being false.
1568
1569   . If there is no "date" header, generate one, for locally-originated
1570     or submission mode messages only.
1571
1572   . Copy the rest of the input, or up to a terminating "." if in SMTP or
1573     dot_ends mode, to the data file. Leave it open, to hold the lock.
1574
1575   . Write the envelope and the headers to a new file.
1576
1577   . Set the name for the header file; close it.
1578
1579   . Set the name for the data file; close it.
1580
1581 Because this function can potentially be called many times in a single
1582 SMTP connection, all store should be got by store_get(), so that it will be
1583 automatically retrieved after the message is accepted.
1584
1585 FUDGE: It seems that sites on the net send out messages with just LF
1586 terminators, despite the warnings in the RFCs, and other MTAs handle this. So
1587 we make the CRs optional in all cases.
1588
1589 July 2003: Bare CRs in messages, especially in header lines, cause trouble. A
1590 new regime is now in place in which bare CRs in header lines are turned into LF
1591 followed by a space, so as not to terminate the header line.
1592
1593 February 2004: A bare LF in a header line in a message whose first line was
1594 terminated by CRLF is treated in the same way as a bare CR.
1595
1596 Arguments:
1597   extract_recip  TRUE if recipients are to be extracted from the message's
1598                    headers
1599
1600 Returns:  TRUE   there are more messages to be read (SMTP input)
1601           FALSE  there are no more messages to be read (non-SMTP input
1602                  or SMTP connection collapsed, or other failure)
1603
1604 When reading a message for filter testing, the returned value indicates
1605 whether the headers (which is all that is read) were terminated by '.' or
1606 not. */
1607
1608 BOOL
1609 receive_msg(BOOL extract_recip)
1610 {
1611 int  i;
1612 int  rc = FAIL;
1613 int  msg_size = 0;
1614 int  process_info_len = Ustrlen(process_info);
1615 int  error_rc = error_handling == ERRORS_SENDER
1616         ? errors_sender_rc : EXIT_FAILURE;
1617 int  header_size = 256;
1618 int  start, end, domain;
1619 int  id_resolution;
1620 int  had_zero = 0;
1621 int  prevlines_length = 0;
1622
1623 register int ptr = 0;
1624
1625 BOOL contains_resent_headers = FALSE;
1626 BOOL extracted_ignored = FALSE;
1627 BOOL first_line_ended_crlf = TRUE_UNSET;
1628 BOOL smtp_yield = TRUE;
1629 BOOL yield = FALSE;
1630
1631 BOOL resents_exist = FALSE;
1632 uschar *resent_prefix = US"";
1633 uschar *blackholed_by = NULL;
1634 uschar *blackhole_log_msg = US"";
1635 enum {NOT_TRIED, TMP_REJ, PERM_REJ, ACCEPTED} cutthrough_done = NOT_TRIED;
1636
1637 flock_t lock_data;
1638 error_block *bad_addresses = NULL;
1639
1640 uschar *frozen_by = NULL;
1641 uschar *queued_by = NULL;
1642
1643 uschar *errmsg;
1644 gstring * g;
1645 struct stat statbuf;
1646
1647 /* Final message to give to SMTP caller, and messages from ACLs */
1648
1649 uschar *smtp_reply = NULL;
1650 uschar *user_msg, *log_msg;
1651
1652 /* Working header pointers */
1653
1654 header_line *h, *next;
1655
1656 /* Flags for noting the existence of certain headers (only one left) */
1657
1658 BOOL date_header_exists = FALSE;
1659
1660 /* Pointers to receive the addresses of headers whose contents we need. */
1661
1662 header_line *from_header = NULL;
1663 header_line *subject_header = NULL;
1664 header_line *msgid_header = NULL;
1665 header_line *received_header;
1666
1667 #ifdef EXPERIMENTAL_DMARC
1668 int dmarc_up = 0;
1669 #endif /* EXPERIMENTAL_DMARC */
1670
1671 /* Variables for use when building the Received: header. */
1672
1673 uschar *timestamp;
1674 int tslen;
1675
1676
1677 /* Release any open files that might have been cached while preparing to
1678 accept the message - e.g. by verifying addresses - because reading a message
1679 might take a fair bit of real time. */
1680
1681 search_tidyup();
1682
1683 /* Extracting the recipient list from an input file is incompatible with
1684 cutthrough delivery with the no-spool option.  It shouldn't be possible
1685 to set up the combination, but just in case kill any ongoing connection. */
1686 if (extract_recip || !smtp_input)
1687   cancel_cutthrough_connection(TRUE, US"not smtp input");
1688
1689 /* Initialize the chain of headers by setting up a place-holder for Received:
1690 header. Temporarily mark it as "old", i.e. not to be used. We keep header_last
1691 pointing to the end of the chain to make adding headers simple. */
1692
1693 received_header = header_list = header_last = store_get(sizeof(header_line));
1694 header_list->next = NULL;
1695 header_list->type = htype_old;
1696 header_list->text = NULL;
1697 header_list->slen = 0;
1698
1699 /* Control block for the next header to be read. */
1700
1701 next = store_get(sizeof(header_line));
1702 next->text = store_get(header_size);
1703
1704 /* Initialize message id to be null (indicating no message read), and the
1705 header names list to be the normal list. Indicate there is no data file open
1706 yet, initialize the size and warning count, and deal with no size limit. */
1707
1708 message_id[0] = 0;
1709 data_file = NULL;
1710 data_fd = -1;
1711 spool_name = US"";
1712 message_size = 0;
1713 warning_count = 0;
1714 received_count = 1;            /* For the one we will add */
1715
1716 if (thismessage_size_limit <= 0) thismessage_size_limit = INT_MAX;
1717
1718 /* While reading the message, the following counts are computed. */
1719
1720 message_linecount = body_linecount = body_zerocount =
1721   max_received_linelength = 0;
1722
1723 #ifndef DISABLE_DKIM
1724 /* Call into DKIM to set up the context.  In CHUNKING mode
1725 we clear the dot-stuffing flag */
1726 if (smtp_input && !smtp_batched_input && !dkim_disable_verify)
1727   dkim_exim_verify_init(chunking_state <= CHUNKING_OFFERED);
1728 #endif
1729
1730 #ifdef EXPERIMENTAL_DMARC
1731 /* initialize libopendmarc */
1732 dmarc_up = dmarc_init();
1733 #endif
1734
1735 /* Remember the time of reception. Exim uses time+pid for uniqueness of message
1736 ids, and fractions of a second are required. See the comments that precede the
1737 message id creation below. */
1738
1739 (void)gettimeofday(&message_id_tv, NULL);
1740
1741 /* For other uses of the received time we can operate with granularity of one
1742 second, and for that we use the global variable received_time. This is for
1743 things like ultimate message timeouts. */
1744
1745 received_time = message_id_tv;
1746
1747 /* If SMTP input, set the special handler for timeouts. The alarm() calls
1748 happen in the smtp_getc() function when it refills its buffer. */
1749
1750 had_data_timeout = 0;
1751 if (smtp_input)
1752   os_non_restarting_signal(SIGALRM, data_timeout_handler);
1753
1754 /* If not SMTP input, timeout happens only if configured, and we just set a
1755 single timeout for the whole message. */
1756
1757 else if (receive_timeout > 0)
1758   {
1759   os_non_restarting_signal(SIGALRM, data_timeout_handler);
1760   alarm(receive_timeout);
1761   }
1762
1763 /* SIGTERM and SIGINT are caught always. */
1764
1765 had_data_sigint = 0;
1766 signal(SIGTERM, data_sigterm_sigint_handler);
1767 signal(SIGINT, data_sigterm_sigint_handler);
1768
1769 /* Header lines in messages are not supposed to be very long, though when
1770 unfolded, to: and cc: headers can take up a lot of store. We must also cope
1771 with the possibility of junk being thrown at us. Start by getting 256 bytes for
1772 storing the header, and extend this as necessary using string_cat().
1773
1774 To cope with total lunacies, impose an upper limit on the length of the header
1775 section of the message, as otherwise the store will fill up. We must also cope
1776 with the possibility of binary zeros in the data. Hence we cannot use fgets().
1777 Folded header lines are joined into one string, leaving the '\n' characters
1778 inside them, so that writing them out reproduces the input.
1779
1780 Loop for each character of each header; the next structure for chaining the
1781 header is set up already, with ptr the offset of the next character in
1782 next->text. */
1783
1784 for (;;)
1785   {
1786   int ch = (receive_getc)(GETC_BUFFER_UNLIMITED);
1787
1788   /* If we hit EOF on a SMTP connection, it's an error, since incoming
1789   SMTP must have a correct "." terminator. */
1790
1791   if (ch == EOF && smtp_input /* && !smtp_batched_input */)
1792     {
1793     smtp_reply = handle_lost_connection(US" (header)");
1794     smtp_yield = FALSE;
1795     goto TIDYUP;                       /* Skip to end of function */
1796     }
1797
1798   /* See if we are at the current header's size limit - there must be at least
1799   four bytes left. This allows for the new character plus a zero, plus two for
1800   extra insertions when we are playing games with dots and carriage returns. If
1801   we are at the limit, extend the text buffer. This could have been done
1802   automatically using string_cat() but because this is a tightish loop storing
1803   only one character at a time, we choose to do it inline. Normally
1804   store_extend() will be able to extend the block; only at the end of a big
1805   store block will a copy be needed. To handle the case of very long headers
1806   (and sometimes lunatic messages can have ones that are 100s of K long) we
1807   call store_release() for strings that have been copied - if the string is at
1808   the start of a block (and therefore the only thing in it, because we aren't
1809   doing any other gets), the block gets freed. We can only do this release if
1810   there were no allocations since the once that we want to free. */
1811
1812   if (ptr >= header_size - 4)
1813     {
1814     int oldsize = header_size;
1815     /* header_size += 256; */
1816     header_size *= 2;
1817     if (!store_extend(next->text, oldsize, header_size))
1818       next->text = store_newblock(next->text, header_size, ptr);
1819     }
1820
1821   /* Cope with receiving a binary zero. There is dispute about whether
1822   these should be allowed in RFC 822 messages. The middle view is that they
1823   should not be allowed in headers, at least. Exim takes this attitude at
1824   the moment. We can't just stomp on them here, because we don't know that
1825   this line is a header yet. Set a flag to cause scanning later. */
1826
1827   if (ch == 0) had_zero++;
1828
1829   /* Test for termination. Lines in remote SMTP are terminated by CRLF, while
1830   those from data files use just LF. Treat LF in local SMTP input as a
1831   terminator too. Treat EOF as a line terminator always. */
1832
1833   if (ch == EOF) goto EOL;
1834
1835   /* FUDGE: There are sites out there that don't send CRs before their LFs, and
1836   other MTAs accept this. We are therefore forced into this "liberalisation"
1837   too, so we accept LF as a line terminator whatever the source of the message.
1838   However, if the first line of the message ended with a CRLF, we treat a bare
1839   LF specially by inserting a white space after it to ensure that the header
1840   line is not terminated. */
1841
1842   if (ch == '\n')
1843     {
1844     if (first_line_ended_crlf == TRUE_UNSET) first_line_ended_crlf = FALSE;
1845       else if (first_line_ended_crlf) receive_ungetc(' ');
1846     goto EOL;
1847     }
1848
1849   /* This is not the end of the line. If this is SMTP input and this is
1850   the first character in the line and it is a "." character, ignore it.
1851   This implements the dot-doubling rule, though header lines starting with
1852   dots aren't exactly common. They are legal in RFC 822, though. If the
1853   following is CRLF or LF, this is the line that that terminates the
1854   entire message. We set message_ended to indicate this has happened (to
1855   prevent further reading), and break out of the loop, having freed the
1856   empty header, and set next = NULL to indicate no data line. */
1857
1858   if (ptr == 0 && ch == '.' && dot_ends)
1859     {
1860     ch = (receive_getc)(GETC_BUFFER_UNLIMITED);
1861     if (ch == '\r')
1862       {
1863       ch = (receive_getc)(GETC_BUFFER_UNLIMITED);
1864       if (ch != '\n')
1865         {
1866         receive_ungetc(ch);
1867         ch = '\r';              /* Revert to CR */
1868         }
1869       }
1870     if (ch == '\n')
1871       {
1872       message_ended = END_DOT;
1873       store_reset(next);
1874       next = NULL;
1875       break;                    /* End character-reading loop */
1876       }
1877
1878     /* For non-SMTP input, the dot at the start of the line was really a data
1879     character. What is now in ch is the following character. We guaranteed
1880     enough space for this above. */
1881
1882     if (!smtp_input)
1883       {
1884       next->text[ptr++] = '.';
1885       message_size++;
1886       }
1887     }
1888
1889   /* If CR is immediately followed by LF, end the line, ignoring the CR, and
1890   remember this case if this is the first line ending. */
1891
1892   if (ch == '\r')
1893     {
1894     ch = (receive_getc)(GETC_BUFFER_UNLIMITED);
1895     if (ch == '\n')
1896       {
1897       if (first_line_ended_crlf == TRUE_UNSET) first_line_ended_crlf = TRUE;
1898       goto EOL;
1899       }
1900
1901     /* Otherwise, put back the character after CR, and turn the bare CR
1902     into LF SP. */
1903
1904     ch = (receive_ungetc)(ch);
1905     next->text[ptr++] = '\n';
1906     message_size++;
1907     ch = ' ';
1908     }
1909
1910   /* We have a data character for the header line. */
1911
1912   next->text[ptr++] = ch;    /* Add to buffer */
1913   message_size++;            /* Total message size so far */
1914
1915   /* Handle failure due to a humungously long header section. The >= allows
1916   for the terminating \n. Add what we have so far onto the headers list so
1917   that it gets reflected in any error message, and back up the just-read
1918   character. */
1919
1920   if (message_size >= header_maxsize)
1921     {
1922     next->text[ptr] = 0;
1923     next->slen = ptr;
1924     next->type = htype_other;
1925     next->next = NULL;
1926     header_last->next = next;
1927     header_last = next;
1928
1929     log_write(0, LOG_MAIN, "ridiculously long message header received from "
1930       "%s (more than %d characters): message abandoned",
1931       sender_host_unknown? sender_ident : sender_fullhost, header_maxsize);
1932
1933     if (smtp_input)
1934       {
1935       smtp_reply = US"552 Message header is ridiculously long";
1936       receive_swallow_smtp();
1937       goto TIDYUP;                             /* Skip to end of function */
1938       }
1939
1940     else
1941       {
1942       give_local_error(ERRMESS_VLONGHEADER,
1943         string_sprintf("message header longer than %d characters received: "
1944          "message not accepted", header_maxsize), US"", error_rc, stdin,
1945            header_list->next);
1946       /* Does not return */
1947       }
1948     }
1949
1950   continue;                  /* With next input character */
1951
1952   /* End of header line reached */
1953
1954   EOL:
1955
1956   /* Keep track of lines for BSMTP errors and overall message_linecount. */
1957
1958   receive_linecount++;
1959   message_linecount++;
1960
1961   /* Keep track of maximum line length */
1962
1963   if (ptr - prevlines_length > max_received_linelength)
1964     max_received_linelength = ptr - prevlines_length;
1965   prevlines_length = ptr + 1;
1966
1967   /* Now put in the terminating newline. There is always space for
1968   at least two more characters. */
1969
1970   next->text[ptr++] = '\n';
1971   message_size++;
1972
1973   /* A blank line signals the end of the headers; release the unwanted
1974   space and set next to NULL to indicate this. */
1975
1976   if (ptr == 1)
1977     {
1978     store_reset(next);
1979     next = NULL;
1980     break;
1981     }
1982
1983   /* There is data in the line; see if the next input character is a
1984   whitespace character. If it is, we have a continuation of this header line.
1985   There is always space for at least one character at this point. */
1986
1987   if (ch != EOF)
1988     {
1989     int nextch = (receive_getc)(GETC_BUFFER_UNLIMITED);
1990     if (nextch == ' ' || nextch == '\t')
1991       {
1992       next->text[ptr++] = nextch;
1993       message_size++;
1994       continue;                      /* Iterate the loop */
1995       }
1996     else if (nextch != EOF) (receive_ungetc)(nextch);   /* For next time */
1997     else ch = EOF;                   /* Cause main loop to exit at end */
1998     }
1999
2000   /* We have got to the real line end. Terminate the string and release store
2001   beyond it. If it turns out to be a real header, internal binary zeros will
2002   be squashed later. */
2003
2004   next->text[ptr] = 0;
2005   next->slen = ptr;
2006   store_reset(next->text + ptr + 1);
2007
2008   /* Check the running total size against the overall message size limit. We
2009   don't expect to fail here, but if the overall limit is set less than MESSAGE_
2010   MAXSIZE and a big header is sent, we want to catch it. Just stop reading
2011   headers - the code to read the body will then also hit the buffer. */
2012
2013   if (message_size > thismessage_size_limit) break;
2014
2015   /* A line that is not syntactically correct for a header also marks
2016   the end of the headers. In this case, we leave next containing the
2017   first data line. This might actually be several lines because of the
2018   continuation logic applied above, but that doesn't matter.
2019
2020   It turns out that smail, and presumably sendmail, accept leading lines
2021   of the form
2022
2023   From ph10 Fri Jan  5 12:35 GMT 1996
2024
2025   in messages. The "mail" command on Solaris 2 sends such lines. I cannot
2026   find any documentation of this, but for compatibility it had better be
2027   accepted. Exim restricts it to the case of non-smtp messages, and
2028   treats it as an alternative to the -f command line option. Thus it is
2029   ignored except for trusted users or filter testing. Otherwise it is taken
2030   as the sender address, unless -f was used (sendmail compatibility).
2031
2032   It further turns out that some UUCPs generate the From_line in a different
2033   format, e.g.
2034
2035   From ph10 Fri, 7 Jan 97 14:00:00 GMT
2036
2037   The regex for matching these things is now capable of recognizing both
2038   formats (including 2- and 4-digit years in the latter). In fact, the regex
2039   is now configurable, as is the expansion string to fish out the sender.
2040
2041   Even further on it has been discovered that some broken clients send
2042   these lines in SMTP messages. There is now an option to ignore them from
2043   specified hosts or networks. Sigh. */
2044
2045   if (  header_last == header_list
2046      && (  !smtp_input
2047         || (  sender_host_address
2048            && verify_check_host(&ignore_fromline_hosts) == OK
2049            )
2050         || (!sender_host_address && ignore_fromline_local)
2051         )
2052      && regex_match_and_setup(regex_From, next->text, 0, -1)
2053      )
2054     {
2055     if (!sender_address_forced)
2056       {
2057       uschar *uucp_sender = expand_string(uucp_from_sender);
2058       if (!uucp_sender)
2059         log_write(0, LOG_MAIN|LOG_PANIC,
2060           "expansion of \"%s\" failed after matching "
2061           "\"From \" line: %s", uucp_from_sender, expand_string_message);
2062       else
2063         {
2064         int start, end, domain;
2065         uschar *errmess;
2066         uschar *newsender = parse_extract_address(uucp_sender, &errmess,
2067           &start, &end, &domain, TRUE);
2068         if (newsender)
2069           {
2070           if (domain == 0 && newsender[0] != 0)
2071             newsender = rewrite_address_qualify(newsender, FALSE);
2072
2073           if (filter_test != FTEST_NONE || receive_check_set_sender(newsender))
2074             {
2075             sender_address = newsender;
2076
2077             if (trusted_caller || filter_test != FTEST_NONE)
2078               {
2079               authenticated_sender = NULL;
2080               originator_name = US"";
2081               sender_local = FALSE;
2082               }
2083
2084             if (filter_test != FTEST_NONE)
2085               printf("Sender taken from \"From \" line\n");
2086             }
2087           }
2088         }
2089       }
2090     }
2091
2092   /* Not a leading "From " line. Check to see if it is a valid header line.
2093   Header names may contain any non-control characters except space and colon,
2094   amazingly. */
2095
2096   else
2097     {
2098     uschar *p = next->text;
2099
2100     /* If not a valid header line, break from the header reading loop, leaving
2101     next != NULL, indicating that it holds the first line of the body. */
2102
2103     if (isspace(*p)) break;
2104     while (mac_isgraph(*p) && *p != ':') p++;
2105     while (isspace(*p)) p++;
2106     if (*p != ':')
2107       {
2108       body_zerocount = had_zero;
2109       break;
2110       }
2111
2112     /* We have a valid header line. If there were any binary zeroes in
2113     the line, stomp on them here. */
2114
2115     if (had_zero > 0)
2116       for (p = next->text; p < next->text + ptr; p++) if (*p == 0) *p = '?';
2117
2118     /* It is perfectly legal to have an empty continuation line
2119     at the end of a header, but it is confusing to humans
2120     looking at such messages, since it looks like a blank line.
2121     Reduce confusion by removing redundant white space at the
2122     end. We know that there is at least one printing character
2123     (the ':' tested for above) so there is no danger of running
2124     off the end. */
2125
2126     p = next->text + ptr - 2;
2127     for (;;)
2128       {
2129       while (*p == ' ' || *p == '\t') p--;
2130       if (*p != '\n') break;
2131       ptr = (p--) - next->text + 1;
2132       message_size -= next->slen - ptr;
2133       next->text[ptr] = 0;
2134       next->slen = ptr;
2135       }
2136
2137     /* Add the header to the chain */
2138
2139     next->type = htype_other;
2140     next->next = NULL;
2141     header_last->next = next;
2142     header_last = next;
2143
2144     /* Check the limit for individual line lengths. This comes after adding to
2145     the chain so that the failing line is reflected if a bounce is generated
2146     (for a local message). */
2147
2148     if (header_line_maxsize > 0 && next->slen > header_line_maxsize)
2149       {
2150       log_write(0, LOG_MAIN, "overlong message header line received from "
2151         "%s (more than %d characters): message abandoned",
2152         sender_host_unknown? sender_ident : sender_fullhost,
2153         header_line_maxsize);
2154
2155       if (smtp_input)
2156         {
2157         smtp_reply = US"552 A message header line is too long";
2158         receive_swallow_smtp();
2159         goto TIDYUP;                             /* Skip to end of function */
2160         }
2161
2162       else
2163         give_local_error(ERRMESS_VLONGHDRLINE,
2164           string_sprintf("message header line longer than %d characters "
2165            "received: message not accepted", header_line_maxsize), US"",
2166            error_rc, stdin, header_list->next);
2167         /* Does not return */
2168       }
2169
2170     /* Note if any resent- fields exist. */
2171
2172     if (!resents_exist && strncmpic(next->text, US"resent-", 7) == 0)
2173       {
2174       resents_exist = TRUE;
2175       resent_prefix = US"Resent-";
2176       }
2177     }
2178
2179   /* Reject CHUNKING messages that do not CRLF their first header line */
2180
2181   if (!first_line_ended_crlf && chunking_state > CHUNKING_OFFERED)
2182     {
2183     log_write(L_size_reject, LOG_MAIN|LOG_REJECT, "rejected from <%s>%s%s%s%s: "
2184       "Non-CRLF-terminated header, under CHUNKING: message abandoned",
2185       sender_address,
2186       sender_fullhost ? " H=" : "", sender_fullhost ? sender_fullhost : US"",
2187       sender_ident ? " U=" : "",    sender_ident ? sender_ident : US"");
2188     smtp_printf("552 Message header not CRLF terminated\r\n", FALSE);
2189     bdat_flush_data();
2190     smtp_reply = US"";
2191     goto TIDYUP;                             /* Skip to end of function */
2192     }
2193
2194   /* The line has been handled. If we have hit EOF, break out of the loop,
2195   indicating no pending data line. */
2196
2197   if (ch == EOF) { next = NULL; break; }
2198
2199   /* Set up for the next header */
2200
2201   header_size = 256;
2202   next = store_get(sizeof(header_line));
2203   next->text = store_get(header_size);
2204   ptr = 0;
2205   had_zero = 0;
2206   prevlines_length = 0;
2207   }      /* Continue, starting to read the next header */
2208
2209 /* At this point, we have read all the headers into a data structure in main
2210 store. The first header is still the dummy placeholder for the Received: header
2211 we are going to generate a bit later on. If next != NULL, it contains the first
2212 data line - which terminated the headers before reaching a blank line (not the
2213 normal case). */
2214
2215 DEBUG(D_receive)
2216   {
2217   debug_printf(">>Headers received:\n");
2218   for (h = header_list->next; h; h = h->next)
2219     debug_printf("%s", h->text);
2220   debug_printf("\n");
2221   }
2222
2223 /* End of file on any SMTP connection is an error. If an incoming SMTP call
2224 is dropped immediately after valid headers, the next thing we will see is EOF.
2225 We must test for this specially, as further down the reading of the data is
2226 skipped if already at EOF. */
2227
2228 if (smtp_input && (receive_feof)())
2229   {
2230   smtp_reply = handle_lost_connection(US" (after header)");
2231   smtp_yield = FALSE;
2232   goto TIDYUP;                       /* Skip to end of function */
2233   }
2234
2235 /* If this is a filter test run and no headers were read, output a warning
2236 in case there is a mistake in the test message. */
2237
2238 if (filter_test != FTEST_NONE && header_list->next == NULL)
2239   printf("Warning: no message headers read\n");
2240
2241
2242 /* Scan the headers to identify them. Some are merely marked for later
2243 processing; some are dealt with here. */
2244
2245 for (h = header_list->next; h; h = h->next)
2246   {
2247   BOOL is_resent = strncmpic(h->text, US"resent-", 7) == 0;
2248   if (is_resent) contains_resent_headers = TRUE;
2249
2250   switch (header_checkname(h, is_resent))
2251     {
2252     case htype_bcc:
2253       h->type = htype_bcc;        /* Both Bcc: and Resent-Bcc: */
2254       break;
2255
2256     case htype_cc:
2257       h->type = htype_cc;         /* Both Cc: and Resent-Cc: */
2258       break;
2259
2260       /* Record whether a Date: or Resent-Date: header exists, as appropriate. */
2261
2262     case htype_date:
2263       if (!resents_exist || is_resent) date_header_exists = TRUE;
2264       break;
2265
2266       /* Same comments as about Return-Path: below. */
2267
2268     case htype_delivery_date:
2269       if (delivery_date_remove) h->type = htype_old;
2270       break;
2271
2272       /* Same comments as about Return-Path: below. */
2273
2274     case htype_envelope_to:
2275       if (envelope_to_remove) h->type = htype_old;
2276       break;
2277
2278       /* Mark all "From:" headers so they get rewritten. Save the one that is to
2279       be used for Sender: checking. For Sendmail compatibility, if the "From:"
2280       header consists of just the login id of the user who called Exim, rewrite
2281       it with the gecos field first. Apply this rule to Resent-From: if there
2282       are resent- fields. */
2283
2284     case htype_from:
2285       h->type = htype_from;
2286       if (!resents_exist || is_resent)
2287         {
2288         from_header = h;
2289         if (!smtp_input)
2290           {
2291           int len;
2292           uschar *s = Ustrchr(h->text, ':') + 1;
2293           while (isspace(*s)) s++;
2294           len = h->slen - (s - h->text) - 1;
2295           if (Ustrlen(originator_login) == len &&
2296               strncmpic(s, originator_login, len) == 0)
2297             {
2298             uschar *name = is_resent? US"Resent-From" : US"From";
2299             header_add(htype_from, "%s: %s <%s@%s>\n", name, originator_name,
2300               originator_login, qualify_domain_sender);
2301             from_header = header_last;
2302             h->type = htype_old;
2303             DEBUG(D_receive|D_rewrite)
2304               debug_printf("rewrote \"%s:\" header using gecos\n", name);
2305            }
2306           }
2307         }
2308       break;
2309
2310       /* Identify the Message-id: header for generating "in-reply-to" in the
2311       autoreply transport. For incoming logging, save any resent- value. In both
2312       cases, take just the first of any multiples. */
2313
2314     case htype_id:
2315       if (!msgid_header && (!resents_exist || is_resent))
2316         {
2317         msgid_header = h;
2318         h->type = htype_id;
2319         }
2320       break;
2321
2322       /* Flag all Received: headers */
2323
2324     case htype_received:
2325       h->type = htype_received;
2326       received_count++;
2327       break;
2328
2329       /* "Reply-to:" is just noted (there is no resent-reply-to field) */
2330
2331     case htype_reply_to:
2332       h->type = htype_reply_to;
2333       break;
2334
2335       /* The Return-path: header is supposed to be added to messages when
2336       they leave the SMTP system. We shouldn't receive messages that already
2337       contain Return-path. However, since Exim generates Return-path: on
2338       local delivery, resent messages may well contain it. We therefore
2339       provide an option (which defaults on) to remove any Return-path: headers
2340       on input. Removal actually means flagging as "old", which prevents the
2341       header being transmitted with the message. */
2342
2343     case htype_return_path:
2344       if (return_path_remove) h->type = htype_old;
2345
2346       /* If we are testing a mail filter file, use the value of the
2347       Return-Path: header to set up the return_path variable, which is not
2348       otherwise set. However, remove any <> that surround the address
2349       because the variable doesn't have these. */
2350
2351       if (filter_test != FTEST_NONE)
2352         {
2353         uschar *start = h->text + 12;
2354         uschar *end = start + Ustrlen(start);
2355         while (isspace(*start)) start++;
2356         while (end > start && isspace(end[-1])) end--;
2357         if (*start == '<' && end[-1] == '>')
2358           {
2359           start++;
2360           end--;
2361           }
2362         return_path = string_copyn(start, end - start);
2363         printf("Return-path taken from \"Return-path:\" header line\n");
2364         }
2365       break;
2366
2367     /* If there is a "Sender:" header and the message is locally originated,
2368     and from an untrusted caller and suppress_local_fixups is not set, or if we
2369     are in submission mode for a remote message, mark it "old" so that it will
2370     not be transmitted with the message, unless active_local_sender_retain is
2371     set. (This can only be true if active_local_from_check is false.) If there
2372     are any resent- headers in the message, apply this rule to Resent-Sender:
2373     instead of Sender:. Messages with multiple resent- header sets cannot be
2374     tidily handled. (For this reason, at least one MUA - Pine - turns old
2375     resent- headers into X-resent- headers when resending, leaving just one
2376     set.) */
2377
2378     case htype_sender:
2379       h->type =    !active_local_sender_retain
2380                 && (  sender_local && !trusted_caller && !suppress_local_fixups
2381                    || submission_mode
2382                    )
2383                 && (!resents_exist || is_resent)
2384         ? htype_old : htype_sender;
2385       break;
2386
2387       /* Remember the Subject: header for logging. There is no Resent-Subject */
2388
2389     case htype_subject:
2390       subject_header = h;
2391       break;
2392
2393       /* "To:" gets flagged, and the existence of a recipient header is noted,
2394       whether it's resent- or not. */
2395
2396     case htype_to:
2397       h->type = htype_to;
2398       /****
2399       to_or_cc_header_exists = TRUE;
2400       ****/
2401       break;
2402     }
2403   }
2404
2405 /* Extract recipients from the headers if that is required (the -t option).
2406 Note that this is documented as being done *before* any address rewriting takes
2407 place. There are two possibilities:
2408
2409 (1) According to sendmail documentation for Solaris, IRIX, and HP-UX, any
2410 recipients already listed are to be REMOVED from the message. Smail 3 works
2411 like this. We need to build a non-recipients tree for that list, because in
2412 subsequent processing this data is held in a tree and that's what the
2413 spool_write_header() function expects. Make sure that non-recipient addresses
2414 are fully qualified and rewritten if necessary.
2415
2416 (2) According to other sendmail documentation, -t ADDS extracted recipients to
2417 those in the command line arguments (and it is rumoured some other MTAs do
2418 this). Therefore, there is an option to make Exim behave this way.
2419
2420 *** Notes on "Resent-" header lines ***
2421
2422 The presence of resent-headers in the message makes -t horribly ambiguous.
2423 Experiments with sendmail showed that it uses recipients for all resent-
2424 headers, totally ignoring the concept of "sets of resent- headers" as described
2425 in RFC 2822 section 3.6.6. Sendmail also amalgamates them into a single set
2426 with all the addresses in one instance of each header.
2427
2428 This seems to me not to be at all sensible. Before release 4.20, Exim 4 gave an
2429 error for -t if there were resent- headers in the message. However, after a
2430 discussion on the mailing list, I've learned that there are MUAs that use
2431 resent- headers with -t, and also that the stuff about sets of resent- headers
2432 and their ordering in RFC 2822 is generally ignored. An MUA that submits a
2433 message with -t and resent- header lines makes sure that only *its* resent-
2434 headers are present; previous ones are often renamed as X-resent- for example.
2435
2436 Consequently, Exim has been changed so that, if any resent- header lines are
2437 present, the recipients are taken from all of the appropriate resent- lines,
2438 and not from the ordinary To:, Cc:, etc. */
2439
2440 if (extract_recip)
2441   {
2442   int rcount = 0;
2443   error_block **bnext = &bad_addresses;
2444
2445   if (extract_addresses_remove_arguments)
2446     {
2447     while (recipients_count-- > 0)
2448       {
2449       uschar *s = rewrite_address(recipients_list[recipients_count].address,
2450         TRUE, TRUE, global_rewrite_rules, rewrite_existflags);
2451       tree_add_nonrecipient(s);
2452       }
2453     recipients_list = NULL;
2454     recipients_count = recipients_list_max = 0;
2455     }
2456
2457   /* Now scan the headers */
2458
2459   for (h = header_list->next; h; h = h->next)
2460     {
2461     if ((h->type == htype_to || h->type == htype_cc || h->type == htype_bcc) &&
2462         (!contains_resent_headers || strncmpic(h->text, US"resent-", 7) == 0))
2463       {
2464       uschar *s = Ustrchr(h->text, ':') + 1;
2465       while (isspace(*s)) s++;
2466
2467       parse_allow_group = TRUE;          /* Allow address group syntax */
2468
2469       while (*s != 0)
2470         {
2471         uschar *ss = parse_find_address_end(s, FALSE);
2472         uschar *recipient, *errmess, *p, *pp;
2473         int start, end, domain;
2474
2475         /* Check on maximum */
2476
2477         if (recipients_max > 0 && ++rcount > recipients_max)
2478           {
2479           give_local_error(ERRMESS_TOOMANYRECIP, US"too many recipients",
2480             US"message rejected: ", error_rc, stdin, NULL);
2481           /* Does not return */
2482           }
2483
2484         /* Make a copy of the address, and remove any internal newlines. These
2485         may be present as a result of continuations of the header line. The
2486         white space that follows the newline must not be removed - it is part
2487         of the header. */
2488
2489         pp = recipient = store_get(ss - s + 1);
2490         for (p = s; p < ss; p++) if (*p != '\n') *pp++ = *p;
2491         *pp = 0;
2492
2493 #ifdef SUPPORT_I18N
2494         {
2495         BOOL b = allow_utf8_domains;
2496         allow_utf8_domains = TRUE;
2497 #endif
2498         recipient = parse_extract_address(recipient, &errmess, &start, &end,
2499           &domain, FALSE);
2500
2501 #ifdef SUPPORT_I18N
2502         if (string_is_utf8(recipient))
2503           message_smtputf8 = TRUE;
2504         else
2505           allow_utf8_domains = b;
2506         }
2507 #endif
2508
2509         /* Keep a list of all the bad addresses so we can send a single
2510         error message at the end. However, an empty address is not an error;
2511         just ignore it. This can come from an empty group list like
2512
2513           To: Recipients of list:;
2514
2515         If there are no recipients at all, an error will occur later. */
2516
2517         if (recipient == NULL && Ustrcmp(errmess, "empty address") != 0)
2518           {
2519           int len = Ustrlen(s);
2520           error_block *b = store_get(sizeof(error_block));
2521           while (len > 0 && isspace(s[len-1])) len--;
2522           b->next = NULL;
2523           b->text1 = string_printing(string_copyn(s, len));
2524           b->text2 = errmess;
2525           *bnext = b;
2526           bnext = &(b->next);
2527           }
2528
2529         /* If the recipient is already in the nonrecipients tree, it must
2530         have appeared on the command line with the option extract_addresses_
2531         remove_arguments set. Do not add it to the recipients, and keep a note
2532         that this has happened, in order to give a better error if there are
2533         no recipients left. */
2534
2535         else if (recipient != NULL)
2536           {
2537           if (tree_search(tree_nonrecipients, recipient) == NULL)
2538             receive_add_recipient(recipient, -1);
2539           else
2540             extracted_ignored = TRUE;
2541           }
2542
2543         /* Move on past this address */
2544
2545         s = ss + (*ss? 1:0);
2546         while (isspace(*s)) s++;
2547         }    /* Next address */
2548
2549       parse_allow_group = FALSE;      /* Reset group syntax flags */
2550       parse_found_group = FALSE;
2551
2552       /* If this was the bcc: header, mark it "old", which means it
2553       will be kept on the spool, but not transmitted as part of the
2554       message. */
2555
2556       if (h->type == htype_bcc) h->type = htype_old;
2557       }   /* For appropriate header line */
2558     }     /* For each header line */
2559
2560   }
2561
2562 /* Now build the unique message id. This has changed several times over the
2563 lifetime of Exim. This description was rewritten for Exim 4.14 (February 2003).
2564 Retaining all the history in the comment has become too unwieldy - read
2565 previous release sources if you want it.
2566
2567 The message ID has 3 parts: tttttt-pppppp-ss. Each part is a number in base 62.
2568 The first part is the current time, in seconds. The second part is the current
2569 pid. Both are large enough to hold 32-bit numbers in base 62. The third part
2570 can hold a number in the range 0-3843. It used to be a computed sequence
2571 number, but is now the fractional component of the current time in units of
2572 1/2000 of a second (i.e. a value in the range 0-1999). After a message has been
2573 received, Exim ensures that the timer has ticked at the appropriate level
2574 before proceeding, to avoid duplication if the pid happened to be re-used
2575 within the same time period. It seems likely that most messages will take at
2576 least half a millisecond to be received, so no delay will normally be
2577 necessary. At least for some time...
2578
2579 There is a modification when localhost_number is set. Formerly this was allowed
2580 to be as large as 255. Now it is restricted to the range 0-16, and the final
2581 component of the message id becomes (localhost_number * 200) + fractional time
2582 in units of 1/200 of a second (i.e. a value in the range 0-3399).
2583
2584 Some not-really-Unix operating systems use case-insensitive file names (Darwin,
2585 Cygwin). For these, we have to use base 36 instead of base 62. Luckily, this
2586 still allows the tttttt field to hold a large enough number to last for some
2587 more decades, and the final two-digit field can hold numbers up to 1295, which
2588 is enough for milliseconds (instead of 1/2000 of a second).
2589
2590 However, the pppppp field cannot hold a 32-bit pid, but it can hold a 31-bit
2591 pid, so it is probably safe because pids have to be positive. The
2592 localhost_number is restricted to 0-10 for these hosts, and when it is set, the
2593 final field becomes (localhost_number * 100) + fractional time in centiseconds.
2594
2595 Note that string_base62() returns its data in a static storage block, so it
2596 must be copied before calling string_base62() again. It always returns exactly
2597 6 characters.
2598
2599 There doesn't seem to be anything in the RFC which requires a message id to
2600 start with a letter, but Smail was changed to ensure this. The external form of
2601 the message id (as supplied by string expansion) therefore starts with an
2602 additional leading 'E'. The spool file names do not include this leading
2603 letter and it is not used internally.
2604
2605 NOTE: If ever the format of message ids is changed, the regular expression for
2606 checking that a string is in this format must be updated in a corresponding
2607 way. It appears in the initializing code in exim.c. The macro MESSAGE_ID_LENGTH
2608 must also be changed to reflect the correct string length. The queue-sort code
2609 needs to know the layout. Then, of course, other programs that rely on the
2610 message id format will need updating too. */
2611
2612 Ustrncpy(message_id, string_base62((long int)(message_id_tv.tv_sec)), 6);
2613 message_id[6] = '-';
2614 Ustrncpy(message_id + 7, string_base62((long int)getpid()), 6);
2615
2616 /* Deal with the case where the host number is set. The value of the number was
2617 checked when it was read, to ensure it isn't too big. The timing granularity is
2618 left in id_resolution so that an appropriate wait can be done after receiving
2619 the message, if necessary (we hope it won't be). */
2620
2621 if (host_number_string)
2622   {
2623   id_resolution = (BASE_62 == 62)? 5000 : 10000;
2624   sprintf(CS(message_id + MESSAGE_ID_LENGTH - 3), "-%2s",
2625     string_base62((long int)(
2626       host_number * (1000000/id_resolution) +
2627         message_id_tv.tv_usec/id_resolution)) + 4);
2628   }
2629
2630 /* Host number not set: final field is just the fractional time at an
2631 appropriate resolution. */
2632
2633 else
2634   {
2635   id_resolution = (BASE_62 == 62)? 500 : 1000;
2636   sprintf(CS(message_id + MESSAGE_ID_LENGTH - 3), "-%2s",
2637     string_base62((long int)(message_id_tv.tv_usec/id_resolution)) + 4);
2638   }
2639
2640 /* Add the current message id onto the current process info string if
2641 it will fit. */
2642
2643 (void)string_format(process_info + process_info_len,
2644   PROCESS_INFO_SIZE - process_info_len, " id=%s", message_id);
2645
2646 /* If we are using multiple input directories, set up the one for this message
2647 to be the least significant base-62 digit of the time of arrival. Otherwise
2648 ensure that it is an empty string. */
2649
2650 message_subdir[0] = split_spool_directory ? message_id[5] : 0;
2651
2652 /* Now that we have the message-id, if there is no message-id: header, generate
2653 one, but only for local (without suppress_local_fixups) or submission mode
2654 messages. This can be user-configured if required, but we had better flatten
2655 any illegal characters therein. */
2656
2657 if (  !msgid_header
2658    && ((!sender_host_address && !suppress_local_fixups) || submission_mode))
2659   {
2660   uschar *p;
2661   uschar *id_text = US"";
2662   uschar *id_domain = primary_hostname;
2663
2664   /* Permit only letters, digits, dots, and hyphens in the domain */
2665
2666   if (message_id_domain)
2667     {
2668     uschar *new_id_domain = expand_string(message_id_domain);
2669     if (!new_id_domain)
2670       {
2671       if (!expand_string_forcedfail)
2672         log_write(0, LOG_MAIN|LOG_PANIC,
2673           "expansion of \"%s\" (message_id_header_domain) "
2674           "failed: %s", message_id_domain, expand_string_message);
2675       }
2676     else if (*new_id_domain)
2677       {
2678       id_domain = new_id_domain;
2679       for (p = id_domain; *p; p++)
2680         if (!isalnum(*p) && *p != '.') *p = '-';  /* No need to test '-' ! */
2681       }
2682     }
2683
2684   /* Permit all characters except controls and RFC 2822 specials in the
2685   additional text part. */
2686
2687   if (message_id_text)
2688     {
2689     uschar *new_id_text = expand_string(message_id_text);
2690     if (!new_id_text)
2691       {
2692       if (!expand_string_forcedfail)
2693         log_write(0, LOG_MAIN|LOG_PANIC,
2694           "expansion of \"%s\" (message_id_header_text) "
2695           "failed: %s", message_id_text, expand_string_message);
2696       }
2697     else if (*new_id_text)
2698       {
2699       id_text = new_id_text;
2700       for (p = id_text; *p; p++) if (mac_iscntrl_or_special(*p)) *p = '-';
2701       }
2702     }
2703
2704   /* Add the header line
2705    * Resent-* headers are prepended, per RFC 5322 3.6.6.  Non-Resent-* are
2706    * appended, to preserve classical expectations of header ordering. */
2707
2708   header_add_at_position(!resents_exist, NULL, FALSE, htype_id,
2709     "%sMessage-Id: <%s%s%s@%s>\n", resent_prefix, message_id_external,
2710     (*id_text == 0)? "" : ".", id_text, id_domain);
2711   }
2712
2713 /* If we are to log recipients, keep a copy of the raw ones before any possible
2714 rewriting. Must copy the count, because later ACLs and the local_scan()
2715 function may mess with the real recipients. */
2716
2717 if (LOGGING(received_recipients))
2718   {
2719   raw_recipients = store_get(recipients_count * sizeof(uschar *));
2720   for (i = 0; i < recipients_count; i++)
2721     raw_recipients[i] = string_copy(recipients_list[i].address);
2722   raw_recipients_count = recipients_count;
2723   }
2724
2725 /* Ensure the recipients list is fully qualified and rewritten. Unqualified
2726 recipients will get here only if the conditions were right (allow_unqualified_
2727 recipient is TRUE). */
2728
2729 for (i = 0; i < recipients_count; i++)
2730   recipients_list[i].address =
2731     rewrite_address(recipients_list[i].address, TRUE, TRUE,
2732       global_rewrite_rules, rewrite_existflags);
2733
2734 /* If there is no From: header, generate one for local (without
2735 suppress_local_fixups) or submission_mode messages. If there is no sender
2736 address, but the sender is local or this is a local delivery error, use the
2737 originator login. This shouldn't happen for genuine bounces, but might happen
2738 for autoreplies. The addition of From: must be done *before* checking for the
2739 possible addition of a Sender: header, because untrusted_set_sender allows an
2740 untrusted user to set anything in the envelope (which might then get info
2741 From:) but we still want to ensure a valid Sender: if it is required. */
2742
2743 if (  !from_header
2744    && ((!sender_host_address && !suppress_local_fixups) || submission_mode))
2745   {
2746   uschar *oname = US"";
2747
2748   /* Use the originator_name if this is a locally submitted message and the
2749   caller is not trusted. For trusted callers, use it only if -F was used to
2750   force its value or if we have a non-SMTP message for which -f was not used
2751   to set the sender. */
2752
2753   if (!sender_host_address)
2754     {
2755     if (!trusted_caller || sender_name_forced ||
2756          (!smtp_input && !sender_address_forced))
2757       oname = originator_name;
2758     }
2759
2760   /* For non-locally submitted messages, the only time we use the originator
2761   name is when it was forced by the /name= option on control=submission. */
2762
2763   else if (submission_name) oname = submission_name;
2764
2765   /* Envelope sender is empty */
2766
2767   if (!*sender_address)
2768     {
2769     uschar *fromstart, *fromend;
2770
2771     fromstart = string_sprintf("%sFrom: %s%s",
2772       resent_prefix, oname, *oname ? " <" : "");
2773     fromend = *oname ? US">" : US"";
2774
2775     if (sender_local || local_error_message)
2776       header_add(htype_from, "%s%s@%s%s\n", fromstart,
2777         local_part_quote(originator_login), qualify_domain_sender,
2778         fromend);
2779
2780     else if (submission_mode && authenticated_id)
2781       {
2782       if (!submission_domain)
2783         header_add(htype_from, "%s%s@%s%s\n", fromstart,
2784           local_part_quote(authenticated_id), qualify_domain_sender,
2785           fromend);
2786
2787       else if (!*submission_domain)  /* empty => whole address set */
2788         header_add(htype_from, "%s%s%s\n", fromstart, authenticated_id,
2789           fromend);
2790
2791       else
2792         header_add(htype_from, "%s%s@%s%s\n", fromstart,
2793           local_part_quote(authenticated_id), submission_domain, fromend);
2794
2795       from_header = header_last;    /* To get it checked for Sender: */
2796       }
2797     }
2798
2799   /* There is a non-null envelope sender. Build the header using the original
2800   sender address, before any rewriting that might have been done while
2801   verifying it. */
2802
2803   else
2804     {
2805     header_add(htype_from, "%sFrom: %s%s%s%s\n", resent_prefix,
2806       oname,
2807       *oname ? " <" : "",
2808       sender_address_unrewritten ? sender_address_unrewritten : sender_address,
2809       *oname ? ">" : "");
2810
2811     from_header = header_last;    /* To get it checked for Sender: */
2812     }
2813   }
2814
2815
2816 /* If the sender is local (without suppress_local_fixups), or if we are in
2817 submission mode and there is an authenticated_id, check that an existing From:
2818 is correct, and if not, generate a Sender: header, unless disabled. Any
2819 previously-existing Sender: header was removed above. Note that sender_local,
2820 as well as being TRUE if the caller of exim is not trusted, is also true if a
2821 trusted caller did not supply a -f argument for non-smtp input. To allow
2822 trusted callers to forge From: without supplying -f, we have to test explicitly
2823 here. If the From: header contains more than one address, then the call to
2824 parse_extract_address fails, and a Sender: header is inserted, as required. */
2825
2826 if (  from_header
2827    && (  active_local_from_check
2828       && (  sender_local && !trusted_caller && !suppress_local_fixups
2829          || submission_mode && authenticated_id
2830    )  )  )
2831   {
2832   BOOL make_sender = TRUE;
2833   int start, end, domain;
2834   uschar *errmess;
2835   uschar *from_address =
2836     parse_extract_address(Ustrchr(from_header->text, ':') + 1, &errmess,
2837       &start, &end, &domain, FALSE);
2838   uschar *generated_sender_address;
2839
2840   generated_sender_address = submission_mode
2841     ? !submission_domain
2842     ? string_sprintf("%s@%s",
2843         local_part_quote(authenticated_id), qualify_domain_sender)
2844     : !*submission_domain                       /* empty => full address */
2845     ? string_sprintf("%s", authenticated_id)
2846     : string_sprintf("%s@%s",
2847         local_part_quote(authenticated_id), submission_domain)
2848     : string_sprintf("%s@%s",
2849         local_part_quote(originator_login), qualify_domain_sender);
2850
2851   /* Remove permitted prefixes and suffixes from the local part of the From:
2852   address before doing the comparison with the generated sender. */
2853
2854   if (from_address)
2855     {
2856     int slen;
2857     uschar *at = domain ? from_address + domain - 1 : NULL;
2858
2859     if (at) *at = 0;
2860     from_address += route_check_prefix(from_address, local_from_prefix);
2861     slen = route_check_suffix(from_address, local_from_suffix);
2862     if (slen > 0)
2863       {
2864       memmove(from_address+slen, from_address, Ustrlen(from_address)-slen);
2865       from_address += slen;
2866       }
2867     if (at) *at = '@';
2868
2869     if (  strcmpic(generated_sender_address, from_address) == 0
2870        || (!domain && strcmpic(from_address, originator_login) == 0))
2871         make_sender = FALSE;
2872     }
2873
2874   /* We have to cause the Sender header to be rewritten if there are
2875   appropriate rewriting rules. */
2876
2877   if (make_sender)
2878     if (submission_mode && !submission_name)
2879       header_add(htype_sender, "%sSender: %s\n", resent_prefix,
2880         generated_sender_address);
2881     else
2882       header_add(htype_sender, "%sSender: %s <%s>\n",
2883         resent_prefix,
2884         submission_mode? submission_name : originator_name,
2885         generated_sender_address);
2886
2887   /* Ensure that a non-null envelope sender address corresponds to the
2888   submission mode sender address. */
2889
2890   if (submission_mode && *sender_address)
2891     {
2892     if (!sender_address_unrewritten)
2893       sender_address_unrewritten = sender_address;
2894     sender_address = generated_sender_address;
2895     if (Ustrcmp(sender_address_unrewritten, generated_sender_address) != 0)
2896       log_write(L_address_rewrite, LOG_MAIN,
2897         "\"%s\" from env-from rewritten as \"%s\" by submission mode",
2898         sender_address_unrewritten, generated_sender_address);
2899     }
2900   }
2901
2902 /* If there are any rewriting rules, apply them to the sender address, unless
2903 it has already been rewritten as part of verification for SMTP input. */
2904
2905 if (global_rewrite_rules && !sender_address_unrewritten && *sender_address)
2906   {
2907   sender_address = rewrite_address(sender_address, FALSE, TRUE,
2908     global_rewrite_rules, rewrite_existflags);
2909   DEBUG(D_receive|D_rewrite)
2910     debug_printf("rewritten sender = %s\n", sender_address);
2911   }
2912
2913
2914 /* The headers must be run through rewrite_header(), because it ensures that
2915 addresses are fully qualified, as well as applying any rewriting rules that may
2916 exist.
2917
2918 Qualification of header addresses in a message from a remote host happens only
2919 if the host is in sender_unqualified_hosts or recipient_unqualified hosts, as
2920 appropriate. For local messages, qualification always happens, unless -bnq is
2921 used to explicitly suppress it. No rewriting is done for an unqualified address
2922 that is left untouched.
2923
2924 We start at the second header, skipping our own Received:. This rewriting is
2925 documented as happening *after* recipient addresses are taken from the headers
2926 by the -t command line option. An added Sender: gets rewritten here. */
2927
2928 for (h = header_list->next; h; h = h->next)
2929   {
2930   header_line *newh = rewrite_header(h, NULL, NULL, global_rewrite_rules,
2931     rewrite_existflags, TRUE);
2932   if (newh) h = newh;
2933   }
2934
2935
2936 /* An RFC 822 (sic) message is not legal unless it has at least one of "to",
2937 "cc", or "bcc". Note that although the minimal examples in RFC 822 show just
2938 "to" or "bcc", the full syntax spec allows "cc" as well. If any resent- header
2939 exists, this applies to the set of resent- headers rather than the normal set.
2940
2941 The requirement for a recipient header has been removed in RFC 2822. At this
2942 point in the code, earlier versions of Exim added a To: header for locally
2943 submitted messages, and an empty Bcc: header for others. In the light of the
2944 changes in RFC 2822, this was dropped in November 2003. */
2945
2946
2947 /* If there is no date header, generate one if the message originates locally
2948 (i.e. not over TCP/IP) and suppress_local_fixups is not set, or if the
2949 submission mode flag is set. Messages without Date: are not valid, but it seems
2950 to be more confusing if Exim adds one to all remotely-originated messages.
2951 As per Message-Id, we prepend if resending, else append.
2952 */
2953
2954 if (  !date_header_exists
2955    && ((!sender_host_address && !suppress_local_fixups) || submission_mode))
2956   header_add_at_position(!resents_exist, NULL, FALSE, htype_other,
2957     "%sDate: %s\n", resent_prefix, tod_stamp(tod_full));
2958
2959 search_tidyup();    /* Free any cached resources */
2960
2961 /* Show the complete set of headers if debugging. Note that the first one (the
2962 new Received:) has not yet been set. */
2963
2964 DEBUG(D_receive)
2965   {
2966   debug_printf(">>Headers after rewriting and local additions:\n");
2967   for (h = header_list->next; h; h = h->next)
2968     debug_printf("%c %s", h->type, h->text);
2969   debug_printf("\n");
2970   }
2971
2972 /* The headers are now complete in store. If we are running in filter
2973 testing mode, that is all this function does. Return TRUE if the message
2974 ended with a dot. */
2975
2976 if (filter_test != FTEST_NONE)
2977   {
2978   process_info[process_info_len] = 0;
2979   return message_ended == END_DOT;
2980   }
2981
2982 /*XXX CHUNKING: need to cancel cutthrough under BDAT, for now.  In future,
2983 think more if it could be handled.  Cannot do onward CHUNKING unless
2984 inbound is, but inbound chunking ought to be ok with outbound plain.
2985 Could we do onward CHUNKING given inbound CHUNKING?
2986 */
2987 if (chunking_state > CHUNKING_OFFERED)
2988   cancel_cutthrough_connection(FALSE, US"chunking active");
2989
2990 /* Cutthrough delivery:
2991 We have to create the Received header now rather than at the end of reception,
2992 so the timestamp behaviour is a change to the normal case.
2993 Having created it, send the headers to the destination. */
2994
2995 if (cutthrough.fd >= 0 && cutthrough.delivery)
2996   {
2997   if (received_count > received_headers_max)
2998     {
2999     cancel_cutthrough_connection(TRUE, US"too many headers");
3000     if (smtp_input) receive_swallow_smtp();  /* Swallow incoming SMTP */
3001     log_write(0, LOG_MAIN|LOG_REJECT, "rejected from <%s>%s%s%s%s: "
3002       "Too many \"Received\" headers",
3003       sender_address,
3004       sender_fullhost ? "H=" : "", sender_fullhost ? sender_fullhost : US"",
3005       sender_ident ? "U=" : "", sender_ident ? sender_ident : US"");
3006     message_id[0] = 0;                       /* Indicate no message accepted */
3007     smtp_reply = US"550 Too many \"Received\" headers - suspected mail loop";
3008     goto TIDYUP;                             /* Skip to end of function */
3009     }
3010   received_header_gen();
3011   add_acl_headers(ACL_WHERE_RCPT, US"MAIL or RCPT");
3012   (void) cutthrough_headers_send();
3013   }
3014
3015
3016 /* Open a new spool file for the data portion of the message. We need
3017 to access it both via a file descriptor and a stream. Try to make the
3018 directory if it isn't there. */
3019
3020 spool_name = spool_fname(US"input", message_subdir, message_id, US"-D");
3021 DEBUG(D_receive) debug_printf("Data file name: %s\n", spool_name);
3022
3023 if ((data_fd = Uopen(spool_name, O_RDWR|O_CREAT|O_EXCL, SPOOL_MODE)) < 0)
3024   {
3025   if (errno == ENOENT)
3026     {
3027     (void) directory_make(spool_directory,
3028                         spool_sname(US"input", message_subdir),
3029                         INPUT_DIRECTORY_MODE, TRUE);
3030     data_fd = Uopen(spool_name, O_RDWR|O_CREAT|O_EXCL, SPOOL_MODE);
3031     }
3032   if (data_fd < 0)
3033     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Failed to create spool file %s: %s",
3034       spool_name, strerror(errno));
3035   }
3036
3037 /* Make sure the file's group is the Exim gid, and double-check the mode
3038 because the group setting doesn't always get set automatically. */
3039
3040 if (fchown(data_fd, exim_uid, exim_gid))
3041   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
3042     "Failed setting ownership on spool file %s: %s",
3043     spool_name, strerror(errno));
3044 (void)fchmod(data_fd, SPOOL_MODE);
3045
3046 /* We now have data file open. Build a stream for it and lock it. We lock only
3047 the first line of the file (containing the message ID) because otherwise there
3048 are problems when Exim is run under Cygwin (I'm told). See comments in
3049 spool_in.c, where the same locking is done. */
3050
3051 data_file = fdopen(data_fd, "w+");
3052 lock_data.l_type = F_WRLCK;
3053 lock_data.l_whence = SEEK_SET;
3054 lock_data.l_start = 0;
3055 lock_data.l_len = SPOOL_DATA_START_OFFSET;
3056
3057 if (fcntl(data_fd, F_SETLK, &lock_data) < 0)
3058   log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Cannot lock %s (%d): %s", spool_name,
3059     errno, strerror(errno));
3060
3061 /* We have an open, locked data file. Write the message id to it to make it
3062 self-identifying. Then read the remainder of the input of this message and
3063 write it to the data file. If the variable next != NULL, it contains the first
3064 data line (which was read as a header but then turned out not to have the right
3065 format); write it (remembering that it might contain binary zeros). The result
3066 of fwrite() isn't inspected; instead we call ferror() below. */
3067
3068 fprintf(data_file, "%s-D\n", message_id);
3069 if (next)
3070   {
3071   uschar *s = next->text;
3072   int len = next->slen;
3073   len = fwrite(s, 1, len, data_file);  len = len; /* compiler quietening */
3074   body_linecount++;                 /* Assumes only 1 line */
3075   }
3076
3077 /* Note that we might already be at end of file, or the logical end of file
3078 (indicated by '.'), or might have encountered an error while writing the
3079 message id or "next" line. */
3080
3081 if (!ferror(data_file) && !(receive_feof)() && message_ended != END_DOT)
3082   {
3083   if (smtp_input)
3084     {
3085     message_ended = chunking_state <= CHUNKING_OFFERED
3086       ? read_message_data_smtp(data_file)
3087       : spool_wireformat
3088       ? read_message_bdat_smtp_wire(data_file)
3089       : read_message_bdat_smtp(data_file);
3090     receive_linecount++;                /* The terminating "." line */
3091     }
3092   else message_ended = read_message_data(data_file);
3093
3094   receive_linecount += body_linecount;  /* For BSMTP errors mainly */
3095   message_linecount += body_linecount;
3096
3097   switch (message_ended)
3098     {
3099     /* Handle premature termination of SMTP */
3100
3101     case END_EOF:
3102       if (smtp_input)
3103         {
3104         Uunlink(spool_name);                 /* Lose data file when closed */
3105         cancel_cutthrough_connection(TRUE, US"sender closed connection");
3106         message_id[0] = 0;                   /* Indicate no message accepted */
3107         smtp_reply = handle_lost_connection(US"");
3108         smtp_yield = FALSE;
3109         goto TIDYUP;                         /* Skip to end of function */
3110         }
3111       break;
3112
3113     /* Handle message that is too big. Don't use host_or_ident() in the log
3114     message; we want to see the ident value even for non-remote messages. */
3115
3116     case END_SIZE:
3117       Uunlink(spool_name);                /* Lose the data file when closed */
3118       cancel_cutthrough_connection(TRUE, US"mail too big");
3119       if (smtp_input) receive_swallow_smtp();  /* Swallow incoming SMTP */
3120
3121       log_write(L_size_reject, LOG_MAIN|LOG_REJECT, "rejected from <%s>%s%s%s%s: "
3122         "message too big: read=%d max=%d",
3123         sender_address,
3124         sender_fullhost ? " H=" : "",
3125         sender_fullhost ? sender_fullhost : US"",
3126         sender_ident ? " U=" : "",
3127         sender_ident ? sender_ident : US"",
3128         message_size,
3129         thismessage_size_limit);
3130
3131       if (smtp_input)
3132         {
3133         smtp_reply = US"552 Message size exceeds maximum permitted";
3134         message_id[0] = 0;               /* Indicate no message accepted */
3135         goto TIDYUP;                     /* Skip to end of function */
3136         }
3137       else
3138         {
3139         fseek(data_file, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET);
3140         give_local_error(ERRMESS_TOOBIG,
3141           string_sprintf("message too big (max=%d)", thismessage_size_limit),
3142           US"message rejected: ", error_rc, data_file, header_list);
3143         /* Does not return */
3144         }
3145       break;
3146
3147     /* Handle bad BDAT protocol sequence */
3148
3149     case END_PROTOCOL:
3150       Uunlink(spool_name);              /* Lose the data file when closed */
3151       cancel_cutthrough_connection(TRUE, US"sender protocol error");
3152       smtp_reply = US"";                /* Response already sent */
3153       message_id[0] = 0;                /* Indicate no message accepted */
3154       goto TIDYUP;                      /* Skip to end of function */
3155     }
3156   }
3157
3158 /* Restore the standard SIGALRM handler for any subsequent processing. (For
3159 example, there may be some expansion in an ACL that uses a timer.) */
3160
3161 os_non_restarting_signal(SIGALRM, sigalrm_handler);
3162
3163 /* The message body has now been read into the data file. Call fflush() to
3164 empty the buffers in C, and then call fsync() to get the data written out onto
3165 the disk, as fflush() doesn't do this (or at least, it isn't documented as
3166 having to do this). If there was an I/O error on either input or output,
3167 attempt to send an error message, and unlink the spool file. For non-SMTP input
3168 we can then give up. Note that for SMTP input we must swallow the remainder of
3169 the input in cases of output errors, since the far end doesn't expect to see
3170 anything until the terminating dot line is sent. */
3171
3172 if (fflush(data_file) == EOF || ferror(data_file) ||
3173     EXIMfsync(fileno(data_file)) < 0 || (receive_ferror)())
3174   {
3175   uschar *msg_errno = US strerror(errno);
3176   BOOL input_error = (receive_ferror)() != 0;
3177   uschar *msg = string_sprintf("%s error (%s) while receiving message from %s",
3178     input_error? "Input read" : "Spool write",
3179     msg_errno,
3180     sender_fullhost ? sender_fullhost : sender_ident);
3181
3182   log_write(0, LOG_MAIN, "Message abandoned: %s", msg);
3183   Uunlink(spool_name);                /* Lose the data file */
3184   cancel_cutthrough_connection(TRUE, US"error writing spoolfile");
3185
3186   if (smtp_input)
3187     {
3188     if (input_error)
3189       smtp_reply = US"451 Error while reading input data";
3190     else
3191       {
3192       smtp_reply = US"451 Error while writing spool file";
3193       receive_swallow_smtp();
3194       }
3195     message_id[0] = 0;               /* Indicate no message accepted */
3196     goto TIDYUP;                     /* Skip to end of function */
3197     }
3198
3199   else
3200     {
3201     fseek(data_file, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET);
3202     give_local_error(ERRMESS_IOERR, msg, US"", error_rc, data_file,
3203       header_list);
3204     /* Does not return */
3205     }
3206   }
3207
3208
3209 /* No I/O errors were encountered while writing the data file. */
3210
3211 DEBUG(D_receive) debug_printf("Data file written for message %s\n", message_id);
3212 if (LOGGING(receive_time)) timesince(&received_time_taken, &received_time);
3213
3214
3215 /* If there were any bad addresses extracted by -t, or there were no recipients
3216 left after -t, send a message to the sender of this message, or write it to
3217 stderr if the error handling option is set that way. Note that there may
3218 legitimately be no recipients for an SMTP message if they have all been removed
3219 by "discard".
3220
3221 We need to rewind the data file in order to read it. In the case of no
3222 recipients or stderr error writing, throw the data file away afterwards, and
3223 exit. (This can't be SMTP, which always ensures there's at least one
3224 syntactically good recipient address.) */
3225
3226 if (extract_recip && (bad_addresses || recipients_count == 0))
3227   {
3228   DEBUG(D_receive)
3229     {
3230     if (recipients_count == 0) debug_printf("*** No recipients\n");
3231     if (bad_addresses)
3232       {
3233       error_block *eblock = bad_addresses;
3234       debug_printf("*** Bad address(es)\n");
3235       while (eblock != NULL)
3236         {
3237         debug_printf("  %s: %s\n", eblock->text1, eblock->text2);
3238         eblock = eblock->next;
3239         }
3240       }
3241     }
3242
3243   fseek(data_file, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET);
3244
3245   /* If configured to send errors to the sender, but this fails, force
3246   a failure error code. We use a special one for no recipients so that it
3247   can be detected by the autoreply transport. Otherwise error_rc is set to
3248   errors_sender_rc, which is EXIT_FAILURE unless -oee was given, in which case
3249   it is EXIT_SUCCESS. */
3250
3251   if (error_handling == ERRORS_SENDER)
3252     {
3253     if (!moan_to_sender(
3254           (bad_addresses == NULL)?
3255             (extracted_ignored? ERRMESS_IGADDRESS : ERRMESS_NOADDRESS) :
3256           (recipients_list == NULL)? ERRMESS_BADNOADDRESS : ERRMESS_BADADDRESS,
3257           bad_addresses, header_list, data_file, FALSE))
3258       error_rc = (bad_addresses == NULL)? EXIT_NORECIPIENTS : EXIT_FAILURE;
3259     }
3260   else
3261     {
3262     if (!bad_addresses)
3263       {
3264       if (extracted_ignored)
3265         fprintf(stderr, "exim: all -t recipients overridden by command line\n");
3266       else
3267         fprintf(stderr, "exim: no recipients in message\n");
3268       }
3269     else
3270       {
3271       fprintf(stderr, "exim: invalid address%s",
3272         (bad_addresses->next == NULL)? ":" : "es:\n");
3273       while (bad_addresses != NULL)
3274         {
3275         fprintf(stderr, "  %s: %s\n", bad_addresses->text1,
3276           bad_addresses->text2);
3277         bad_addresses = bad_addresses->next;
3278         }
3279       }
3280     }
3281
3282   if (recipients_count == 0 || error_handling == ERRORS_STDERR)
3283     {
3284     Uunlink(spool_name);
3285     (void)fclose(data_file);
3286     exim_exit(error_rc, US"receiving");
3287     }
3288   }
3289
3290 /* Data file successfully written. Generate text for the Received: header by
3291 expanding the configured string, and adding a timestamp. By leaving this
3292 operation till now, we ensure that the timestamp is the time that message
3293 reception was completed. However, this is deliberately done before calling the
3294 data ACL and local_scan().
3295
3296 This Received: header may therefore be inspected by the data ACL and by code in
3297 the local_scan() function. When they have run, we update the timestamp to be
3298 the final time of reception.
3299
3300 If there is just one recipient, set up its value in the $received_for variable
3301 for use when we generate the Received: header.
3302
3303 Note: the checking for too many Received: headers is handled by the delivery
3304 code. */
3305 /*XXX eventually add excess Received: check for cutthrough case back when classifying them */
3306
3307 if (!received_header->text)     /* Non-cutthrough case */
3308   {
3309   received_header_gen();
3310
3311   /* Set the value of message_body_size for the DATA ACL and for local_scan() */
3312
3313   message_body_size = (fstat(data_fd, &statbuf) == 0)?
3314     statbuf.st_size - SPOOL_DATA_START_OFFSET : -1;
3315
3316   /* If an ACL from any RCPT commands set up any warning headers to add, do so
3317   now, before running the DATA ACL. */
3318
3319   add_acl_headers(ACL_WHERE_RCPT, US"MAIL or RCPT");
3320   }
3321 else
3322   message_body_size = (fstat(data_fd, &statbuf) == 0)?
3323     statbuf.st_size - SPOOL_DATA_START_OFFSET : -1;
3324
3325 /* If an ACL is specified for checking things at this stage of reception of a
3326 message, run it, unless all the recipients were removed by "discard" in earlier
3327 ACLs. That is the only case in which recipients_count can be zero at this
3328 stage. Set deliver_datafile to point to the data file so that $message_body and
3329 $message_body_end can be extracted if needed. Allow $recipients in expansions.
3330 */
3331
3332 deliver_datafile = data_fd;
3333 user_msg = NULL;
3334
3335 enable_dollar_recipients = TRUE;
3336
3337 if (recipients_count == 0)
3338   blackholed_by = recipients_discarded ? US"MAIL ACL" : US"RCPT ACL";
3339
3340 else
3341   {
3342   /* Handle interactive SMTP messages */
3343
3344   if (smtp_input && !smtp_batched_input)
3345     {
3346
3347 #ifndef DISABLE_DKIM
3348     if (!dkim_disable_verify)
3349       {
3350       /* Finish verification */
3351       dkim_exim_verify_finish();
3352
3353       /* Check if we must run the DKIM ACL */
3354       if (acl_smtp_dkim && dkim_verify_signers && *dkim_verify_signers)
3355         {
3356         uschar * dkim_verify_signers_expanded =
3357           expand_string(dkim_verify_signers);
3358         gstring * results = NULL;
3359         int signer_sep = 0;
3360         const uschar * ptr;
3361         uschar * item;
3362         gstring * seen_items = NULL;
3363         int old_pool = store_pool;
3364
3365         store_pool = POOL_PERM;   /* Allow created variables to live to data ACL */
3366
3367         if (!(ptr = dkim_verify_signers_expanded))
3368           log_write(0, LOG_MAIN|LOG_PANIC,
3369             "expansion of dkim_verify_signers option failed: %s",
3370             expand_string_message);
3371
3372         /* Default to OK when no items are present */
3373         rc = OK;
3374         while ((item = string_nextinlist(&ptr, &signer_sep, NULL, 0)))
3375           {
3376           /* Prevent running ACL for an empty item */
3377           if (!item || !*item) continue;
3378
3379           /* Only run ACL once for each domain or identity,
3380           no matter how often it appears in the expanded list. */
3381           if (seen_items)
3382             {
3383             uschar * seen_item;
3384             const uschar * seen_items_list = string_from_gstring(seen_items);
3385             int seen_sep = ':';
3386             BOOL seen_this_item = FALSE;
3387
3388             while ((seen_item = string_nextinlist(&seen_items_list, &seen_sep,
3389                                                   NULL, 0)))
3390               if (Ustrcmp(seen_item,item) == 0)
3391                 {
3392                 seen_this_item = TRUE;
3393                 break;
3394                 }
3395
3396             if (seen_this_item)
3397               {
3398               DEBUG(D_receive)
3399                 debug_printf("acl_smtp_dkim: skipping signer %s, "
3400                   "already seen\n", item);
3401               continue;
3402               }
3403
3404             seen_items = string_catn(seen_items, US":", 1);
3405             }
3406           seen_items = string_cat(seen_items, item);
3407
3408           rc = dkim_exim_acl_run(item, &results, &user_msg, &log_msg);
3409           if (rc != OK)
3410             {
3411             DEBUG(D_receive)
3412               debug_printf("acl_smtp_dkim: acl_check returned %d on %s, "
3413                 "skipping remaining items\n", rc, item);
3414             cancel_cutthrough_connection(TRUE, US"dkim acl not ok");
3415             break;
3416             }
3417           }
3418         dkim_verify_status = string_from_gstring(results);
3419         store_pool = old_pool;
3420         add_acl_headers(ACL_WHERE_DKIM, US"DKIM");
3421         if (rc == DISCARD)
3422           {
3423           recipients_count = 0;
3424           blackholed_by = US"DKIM ACL";
3425           if (log_msg)
3426             blackhole_log_msg = string_sprintf(": %s", log_msg);
3427           }
3428         else if (rc != OK)
3429           {
3430           Uunlink(spool_name);
3431           if (smtp_handle_acl_fail(ACL_WHERE_DKIM, rc, user_msg, log_msg) != 0)
3432             smtp_yield = FALSE;    /* No more messages after dropped connection */
3433           smtp_reply = US"";       /* Indicate reply already sent */
3434           message_id[0] = 0;       /* Indicate no message accepted */
3435           goto TIDYUP;             /* Skip to end of function */
3436           }
3437         }
3438       else
3439         dkim_exim_verify_log_all();
3440       }
3441 #endif /* DISABLE_DKIM */
3442
3443 #ifdef WITH_CONTENT_SCAN
3444     if (  recipients_count > 0
3445        && acl_smtp_mime
3446        && !run_mime_acl(acl_smtp_mime, &smtp_yield, &smtp_reply, &blackholed_by)
3447        )
3448       goto TIDYUP;
3449 #endif /* WITH_CONTENT_SCAN */
3450
3451 #ifdef EXPERIMENTAL_DMARC
3452     dmarc_up = dmarc_store_data(from_header);
3453 #endif /* EXPERIMENTAL_DMARC */
3454
3455 #ifndef DISABLE_PRDR
3456     if (prdr_requested && recipients_count > 1 && acl_smtp_data_prdr)
3457       {
3458       unsigned int c;
3459       int all_pass = OK;
3460       int all_fail = FAIL;
3461
3462       smtp_printf("353 PRDR content analysis beginning\r\n", TRUE);
3463       /* Loop through recipients, responses must be in same order received */
3464       for (c = 0; recipients_count > c; c++)
3465         {
3466         uschar * addr= recipients_list[c].address;
3467         uschar * msg= US"PRDR R=<%s> %s";
3468         uschar * code;
3469         DEBUG(D_receive)
3470           debug_printf("PRDR processing recipient %s (%d of %d)\n",
3471                        addr, c+1, recipients_count);
3472         rc = acl_check(ACL_WHERE_PRDR, addr,
3473                        acl_smtp_data_prdr, &user_msg, &log_msg);
3474
3475         /* If any recipient rejected content, indicate it in final message */
3476         all_pass |= rc;
3477         /* If all recipients rejected, indicate in final message */
3478         all_fail &= rc;
3479
3480         switch (rc)
3481           {
3482           case OK: case DISCARD: code = US"250"; break;
3483           case DEFER:            code = US"450"; break;
3484           default:               code = US"550"; break;
3485           }
3486         if (user_msg != NULL)
3487           smtp_user_msg(code, user_msg);
3488         else
3489           {
3490           switch (rc)
3491             {
3492             case OK: case DISCARD:
3493               msg = string_sprintf(CS msg, addr, "acceptance");        break;
3494             case DEFER:
3495               msg = string_sprintf(CS msg, addr, "temporary refusal"); break;
3496             default:
3497               msg = string_sprintf(CS msg, addr, "refusal");           break;
3498             }
3499           smtp_user_msg(code, msg);
3500           }
3501         if (log_msg)       log_write(0, LOG_MAIN, "PRDR %s %s", addr, log_msg);
3502         else if (user_msg) log_write(0, LOG_MAIN, "PRDR %s %s", addr, user_msg);
3503         else               log_write(0, LOG_MAIN, "%s", CS msg);
3504
3505         if (rc != OK) { receive_remove_recipient(addr); c--; }
3506         }
3507       /* Set up final message, used if data acl gives OK */
3508       smtp_reply = string_sprintf("%s id=%s message %s",
3509                        all_fail == FAIL ? US"550" : US"250",
3510                        message_id,
3511                        all_fail == FAIL
3512                          ? US"rejected for all recipients"
3513                          : all_pass == OK
3514                            ? US"accepted"
3515                            : US"accepted for some recipients");
3516       if (recipients_count == 0)
3517         {
3518         message_id[0] = 0;       /* Indicate no message accepted */
3519         goto TIDYUP;
3520         }
3521       }
3522     else
3523       prdr_requested = FALSE;
3524 #endif /* !DISABLE_PRDR */
3525
3526     /* Check the recipients count again, as the MIME ACL might have changed
3527     them. */
3528
3529     if (acl_smtp_data != NULL && recipients_count > 0)
3530       {
3531       rc = acl_check(ACL_WHERE_DATA, NULL, acl_smtp_data, &user_msg, &log_msg);
3532       add_acl_headers(ACL_WHERE_DATA, US"DATA");
3533       if (rc == DISCARD)
3534         {
3535         recipients_count = 0;
3536         blackholed_by = US"DATA ACL";
3537         if (log_msg)
3538           blackhole_log_msg = string_sprintf(": %s", log_msg);
3539         cancel_cutthrough_connection(TRUE, US"data acl discard");
3540         }
3541       else if (rc != OK)
3542         {
3543         Uunlink(spool_name);
3544         cancel_cutthrough_connection(TRUE, US"data acl not ok");
3545 #ifdef WITH_CONTENT_SCAN
3546         unspool_mbox();
3547 #endif
3548 #ifdef EXPERIMENTAL_DCC
3549         dcc_ok = 0;
3550 #endif
3551         if (smtp_handle_acl_fail(ACL_WHERE_DATA, rc, user_msg, log_msg) != 0)
3552           smtp_yield = FALSE;    /* No more messages after dropped connection */
3553         smtp_reply = US"";       /* Indicate reply already sent */
3554         message_id[0] = 0;       /* Indicate no message accepted */
3555         goto TIDYUP;             /* Skip to end of function */
3556         }
3557       }
3558     }
3559
3560   /* Handle non-SMTP and batch SMTP (i.e. non-interactive) messages. Note that
3561   we cannot take different actions for permanent and temporary rejections. */
3562
3563   else
3564     {
3565
3566 #ifdef WITH_CONTENT_SCAN
3567     if (  acl_not_smtp_mime
3568        && !run_mime_acl(acl_not_smtp_mime, &smtp_yield, &smtp_reply,
3569           &blackholed_by)
3570        )
3571       goto TIDYUP;
3572 #endif /* WITH_CONTENT_SCAN */
3573
3574     if (acl_not_smtp)
3575       {
3576       uschar *user_msg, *log_msg;
3577       authentication_local = TRUE;
3578       rc = acl_check(ACL_WHERE_NOTSMTP, NULL, acl_not_smtp, &user_msg, &log_msg);
3579       if (rc == DISCARD)
3580         {
3581         recipients_count = 0;
3582         blackholed_by = US"non-SMTP ACL";
3583         if (log_msg)
3584           blackhole_log_msg = string_sprintf(": %s", log_msg);
3585         }
3586       else if (rc != OK)
3587         {
3588         Uunlink(spool_name);
3589 #ifdef WITH_CONTENT_SCAN
3590         unspool_mbox();
3591 #endif
3592 #ifdef EXPERIMENTAL_DCC
3593         dcc_ok = 0;
3594 #endif
3595         /* The ACL can specify where rejections are to be logged, possibly
3596         nowhere. The default is main and reject logs. */
3597
3598         if (log_reject_target)
3599           log_write(0, log_reject_target, "F=<%s> rejected by non-SMTP ACL: %s",
3600             sender_address, log_msg);
3601
3602         if (!user_msg) user_msg = US"local configuration problem";
3603         if (smtp_batched_input)
3604           {
3605           moan_smtp_batch(NULL, "%d %s", 550, user_msg);
3606           /* Does not return */
3607           }
3608         else
3609           {
3610           fseek(data_file, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET);
3611           give_local_error(ERRMESS_LOCAL_ACL, user_msg,
3612             US"message rejected by non-SMTP ACL: ", error_rc, data_file,
3613               header_list);
3614           /* Does not return */
3615           }
3616         }
3617       add_acl_headers(ACL_WHERE_NOTSMTP, US"non-SMTP");
3618       }
3619     }
3620
3621   /* The applicable ACLs have been run */
3622
3623   if (deliver_freeze) frozen_by = US"ACL";     /* for later logging */
3624   if (queue_only_policy) queued_by = US"ACL";
3625   }
3626
3627 #ifdef WITH_CONTENT_SCAN
3628 unspool_mbox();
3629 #endif
3630
3631 #ifdef EXPERIMENTAL_DCC
3632 dcc_ok = 0;
3633 #endif
3634
3635
3636 /* The final check on the message is to run the scan_local() function. The
3637 version supplied with Exim always accepts, but this is a hook for sysadmins to
3638 supply their own checking code. The local_scan() function is run even when all
3639 the recipients have been discarded. */
3640
3641 lseek(data_fd, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET);
3642
3643 /* Arrange to catch crashes in local_scan(), so that the -D file gets
3644 deleted, and the incident gets logged. */
3645
3646 if (sigsetjmp(local_scan_env, 1) == 0)
3647   {
3648   had_local_scan_crash = 0;
3649   os_non_restarting_signal(SIGSEGV, local_scan_crash_handler);
3650   os_non_restarting_signal(SIGFPE, local_scan_crash_handler);
3651   os_non_restarting_signal(SIGILL, local_scan_crash_handler);
3652   os_non_restarting_signal(SIGBUS, local_scan_crash_handler);
3653
3654   DEBUG(D_receive) debug_printf("calling local_scan(); timeout=%d\n",
3655     local_scan_timeout);
3656   local_scan_data = NULL;
3657
3658   had_local_scan_timeout = 0;
3659   os_non_restarting_signal(SIGALRM, local_scan_timeout_handler);
3660   if (local_scan_timeout > 0) alarm(local_scan_timeout);
3661   rc = local_scan(data_fd, &local_scan_data);
3662   alarm(0);
3663   os_non_restarting_signal(SIGALRM, sigalrm_handler);
3664
3665   enable_dollar_recipients = FALSE;
3666
3667   store_pool = POOL_MAIN;   /* In case changed */
3668   DEBUG(D_receive) debug_printf("local_scan() returned %d %s\n", rc,
3669     local_scan_data);
3670
3671   os_non_restarting_signal(SIGSEGV, SIG_DFL);
3672   os_non_restarting_signal(SIGFPE, SIG_DFL);
3673   os_non_restarting_signal(SIGILL, SIG_DFL);
3674   os_non_restarting_signal(SIGBUS, SIG_DFL);
3675   }
3676 else
3677   {
3678   if (had_local_scan_crash)
3679     {
3680     log_write(0, LOG_MAIN|LOG_REJECT, "local_scan() function crashed with "
3681       "signal %d - message temporarily rejected (size %d)",
3682       had_local_scan_crash, message_size);
3683     /* Does not return */
3684     receive_bomb_out(US"local-scan-error", US"local verification problem");
3685     }
3686   if (had_local_scan_timeout)
3687     {
3688     log_write(0, LOG_MAIN|LOG_REJECT, "local_scan() function timed out - "
3689       "message temporarily rejected (size %d)", message_size);
3690     /* Does not return */
3691     receive_bomb_out(US"local-scan-timeout", US"local verification problem");
3692     }
3693   }
3694
3695 /* The length check is paranoia against some runaway code, and also because
3696 (for a success return) lines in the spool file are read into big_buffer. */
3697
3698 if (local_scan_data)
3699   {
3700   int len = Ustrlen(local_scan_data);
3701   if (len > LOCAL_SCAN_MAX_RETURN) len = LOCAL_SCAN_MAX_RETURN;
3702   local_scan_data = string_copyn(local_scan_data, len);
3703   }
3704
3705 if (rc == LOCAL_SCAN_ACCEPT_FREEZE)
3706   {
3707   if (!deliver_freeze)         /* ACL might have already frozen */
3708     {
3709     deliver_freeze = TRUE;
3710     deliver_frozen_at = time(NULL);
3711     frozen_by = US"local_scan()";
3712     }
3713   rc = LOCAL_SCAN_ACCEPT;
3714   }
3715 else if (rc == LOCAL_SCAN_ACCEPT_QUEUE)
3716   {
3717   if (!queue_only_policy)      /* ACL might have already queued */
3718     {
3719     queue_only_policy = TRUE;
3720     queued_by = US"local_scan()";
3721     }
3722   rc = LOCAL_SCAN_ACCEPT;
3723   }
3724
3725 /* Message accepted: remove newlines in local_scan_data because otherwise
3726 the spool file gets corrupted. Ensure that all recipients are qualified. */
3727
3728 if (rc == LOCAL_SCAN_ACCEPT)
3729   {
3730   if (local_scan_data)
3731     {
3732     uschar *s;
3733     for (s = local_scan_data; *s != 0; s++) if (*s == '\n') *s = ' ';
3734     }
3735   for (i = 0; i < recipients_count; i++)
3736     {
3737     recipient_item *r = recipients_list + i;
3738     r->address = rewrite_address_qualify(r->address, TRUE);
3739     if (r->errors_to != NULL)
3740       r->errors_to = rewrite_address_qualify(r->errors_to, TRUE);
3741     }
3742   if (recipients_count == 0 && blackholed_by == NULL)
3743     blackholed_by = US"local_scan";
3744   }
3745
3746 /* Message rejected: newlines permitted in local_scan_data to generate
3747 multiline SMTP responses. */
3748
3749 else
3750   {
3751   uschar *istemp = US"";
3752   uschar *smtp_code;
3753   gstring * g;
3754
3755   errmsg = local_scan_data;
3756
3757   Uunlink(spool_name);          /* Cancel this message */
3758   switch(rc)
3759     {
3760     default:
3761       log_write(0, LOG_MAIN, "invalid return %d from local_scan(). Temporary "
3762         "rejection given", rc);
3763       goto TEMPREJECT;
3764
3765     case LOCAL_SCAN_REJECT_NOLOGHDR:
3766       BIT_CLEAR(log_selector, log_selector_size, Li_rejected_header);
3767       /* Fall through */
3768
3769     case LOCAL_SCAN_REJECT:
3770       smtp_code = US"550";
3771       if (!errmsg) errmsg =  US"Administrative prohibition";
3772       break;
3773
3774     case LOCAL_SCAN_TEMPREJECT_NOLOGHDR:
3775       BIT_CLEAR(log_selector, log_selector_size, Li_rejected_header);
3776       /* Fall through */
3777
3778     case LOCAL_SCAN_TEMPREJECT:
3779     TEMPREJECT:
3780       smtp_code = US"451";
3781       if (!errmsg) errmsg = US"Temporary local problem";
3782       istemp = US"temporarily ";
3783       break;
3784     }
3785
3786   g = string_append(NULL, 2, US"F=",
3787     sender_address[0] == 0 ? US"<>" : sender_address);
3788   g = add_host_info_for_log(g);
3789
3790   log_write(0, LOG_MAIN|LOG_REJECT, "%s %srejected by local_scan(): %.256s",
3791     string_from_gstring(g), istemp, string_printing(errmsg));
3792
3793   if (smtp_input)
3794     {
3795     if (!smtp_batched_input)
3796       {
3797       smtp_respond(smtp_code, 3, TRUE, errmsg);
3798       message_id[0] = 0;            /* Indicate no message accepted */
3799       smtp_reply = US"";            /* Indicate reply already sent */
3800       goto TIDYUP;                  /* Skip to end of function */
3801       }
3802     else
3803       {
3804       moan_smtp_batch(NULL, "%s %s", smtp_code, errmsg);
3805       /* Does not return */
3806       }
3807     }
3808   else
3809     {
3810     fseek(data_file, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET);
3811     give_local_error(ERRMESS_LOCAL_SCAN, errmsg,
3812       US"message rejected by local scan code: ", error_rc, data_file,
3813         header_list);
3814     /* Does not return */
3815     }
3816   }
3817
3818 /* Reset signal handlers to ignore signals that previously would have caused
3819 the message to be abandoned. */
3820
3821 signal(SIGTERM, SIG_IGN);
3822 signal(SIGINT, SIG_IGN);
3823
3824
3825 /* Ensure the first time flag is set in the newly-received message. */
3826
3827 deliver_firsttime = TRUE;
3828
3829 #ifdef EXPERIMENTAL_BRIGHTMAIL
3830 if (bmi_run == 1)
3831   { /* rewind data file */
3832   lseek(data_fd, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET);
3833   bmi_verdicts = bmi_process_message(header_list, data_fd);
3834   }
3835 #endif
3836
3837 /* Update the timestamp in our Received: header to account for any time taken by
3838 an ACL or by local_scan(). The new time is the time that all reception
3839 processing is complete. */
3840
3841 timestamp = expand_string(US"${tod_full}");
3842 tslen = Ustrlen(timestamp);
3843
3844 memcpy(received_header->text + received_header->slen - tslen - 1,
3845   timestamp, tslen);
3846
3847 /* In MUA wrapper mode, ignore queueing actions set by ACL or local_scan() */
3848
3849 if (mua_wrapper)
3850   {
3851   deliver_freeze = FALSE;
3852   queue_only_policy = FALSE;
3853   }
3854
3855 /* Keep the data file open until we have written the header file, in order to
3856 hold onto the lock. In a -bh run, or if the message is to be blackholed, we
3857 don't write the header file, and we unlink the data file. If writing the header
3858 file fails, we have failed to accept this message. */
3859
3860 if (host_checking || blackholed_by != NULL)
3861   {
3862   header_line *h;
3863   Uunlink(spool_name);
3864   msg_size = 0;                                  /* Compute size for log line */
3865   for (h = header_list; h != NULL; h = h->next)
3866     if (h->type != '*') msg_size += h->slen;
3867   }
3868
3869 /* Write the -H file */
3870
3871 else
3872   if ((msg_size = spool_write_header(message_id, SW_RECEIVING, &errmsg)) < 0)
3873     {
3874     log_write(0, LOG_MAIN, "Message abandoned: %s", errmsg);
3875     Uunlink(spool_name);           /* Lose the data file */
3876
3877     if (smtp_input)
3878       {
3879       smtp_reply = US"451 Error in writing spool file";
3880       message_id[0] = 0;          /* Indicate no message accepted */
3881       goto TIDYUP;
3882       }
3883     else
3884       {
3885       fseek(data_file, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET);
3886       give_local_error(ERRMESS_IOERR, errmsg, US"", error_rc, data_file,
3887         header_list);
3888       /* Does not return */
3889       }
3890     }
3891
3892
3893 /* The message has now been successfully received. */
3894
3895 receive_messagecount++;
3896
3897 /* In SMTP sessions we may receive several in one connection. After each one,
3898 we wait for the clock to tick at the level of message-id granularity. This is
3899 so that the combination of time+pid is unique, even on systems where the pid
3900 can be re-used within our time interval. We can't shorten the interval without
3901 re-designing the message-id. See comments above where the message id is
3902 created. This is Something For The Future. */
3903
3904 message_id_tv.tv_usec = (message_id_tv.tv_usec/id_resolution) * id_resolution;
3905 exim_wait_tick(&message_id_tv, id_resolution);
3906
3907 /* Add data size to written header size. We do not count the initial file name
3908 that is in the file, but we do add one extra for the notional blank line that
3909 precedes the data. This total differs from message_size in that it include the
3910 added Received: header and any other headers that got created locally. */
3911
3912 fflush(data_file);
3913 fstat(data_fd, &statbuf);
3914
3915 msg_size += statbuf.st_size - SPOOL_DATA_START_OFFSET + 1;
3916
3917 /* Generate a "message received" log entry. We do this by building up a dynamic
3918 string as required. Since we commonly want to add two items at a time, use a
3919 macro to simplify the coding. We log the arrival of a new message while the
3920 file is still locked, just in case the machine is *really* fast, and delivers
3921 it first! Include any message id that is in the message - since the syntax of a
3922 message id is actually an addr-spec, we can use the parse routine to canonicalize
3923 it. */
3924
3925 g = string_get(256);
3926
3927 g = string_append(g, 2,
3928   fake_response == FAIL ? US"(= " : US"<= ",
3929   sender_address[0] == 0 ? US"<>" : sender_address);
3930 if (message_reference)
3931   g = string_append(g, 2, US" R=", message_reference);
3932
3933 g = add_host_info_for_log(g);
3934
3935 #ifdef SUPPORT_TLS
3936 if (LOGGING(tls_cipher) && tls_in.cipher)
3937   g = string_append(g, 2, US" X=", tls_in.cipher);
3938 if (LOGGING(tls_certificate_verified) && tls_in.cipher)
3939   g = string_append(g, 2, US" CV=", tls_in.certificate_verified ? "yes":"no");
3940 if (LOGGING(tls_peerdn) && tls_in.peerdn)
3941   g = string_append(g, 3, US" DN=\"", string_printing(tls_in.peerdn), US"\"");
3942 if (LOGGING(tls_sni) && tls_in.sni)
3943   g = string_append(g, 3, US" SNI=\"", string_printing(tls_in.sni), US"\"");
3944 #endif
3945
3946 if (sender_host_authenticated)
3947   {
3948   g = string_append(g, 2, US" A=", sender_host_authenticated);
3949   if (authenticated_id)
3950     {
3951     g = string_append(g, 2, US":", authenticated_id);
3952     if (LOGGING(smtp_mailauth) && authenticated_sender)
3953       g = string_append(g, 2, US":", authenticated_sender);
3954     }
3955   }
3956
3957 #ifndef DISABLE_PRDR
3958 if (prdr_requested)
3959   g = string_catn(g, US" PRDR", 5);
3960 #endif
3961
3962 #ifdef SUPPORT_PROXY
3963 if (proxy_session && LOGGING(proxy))
3964   g = string_append(g, 2, US" PRX=", proxy_local_address);
3965 #endif
3966
3967 if (chunking_state > CHUNKING_OFFERED)
3968   g = string_catn(g, US" K", 2);
3969
3970 sprintf(CS big_buffer, "%d", msg_size);
3971 g = string_append(g, 2, US" S=", big_buffer);
3972
3973 /* log 8BITMIME mode announced in MAIL_FROM
3974    0 ... no BODY= used
3975    7 ... 7BIT
3976    8 ... 8BITMIME */
3977 if (LOGGING(8bitmime))
3978   {
3979   sprintf(CS big_buffer, "%d", body_8bitmime);
3980   g = string_append(g, 2, US" M8S=", big_buffer);
3981   }
3982
3983 #ifndef DISABLE_DKIM
3984 if (LOGGING(dkim) && dkim_verify_overall)
3985   g = string_append(g, 2, US" DKIM=", dkim_verify_overall);
3986 # ifdef EXPERIMENTAL_ARC
3987 if (LOGGING(dkim) && arc_state && Ustrcmp(arc_state, "pass") == 0)
3988   g = string_catn(g, US" ARC", 4);
3989 # endif
3990 #endif
3991
3992 if (LOGGING(receive_time))
3993   g = string_append(g, 2, US" RT=", string_timediff(&received_time_taken));
3994
3995 if (*queue_name)
3996   g = string_append(g, 2, US" Q=", queue_name);
3997
3998 /* If an addr-spec in a message-id contains a quoted string, it can contain
3999 any characters except " \ and CR and so in particular it can contain NL!
4000 Therefore, make sure we use a printing-characters only version for the log.
4001 Also, allow for domain literals in the message id. */
4002
4003 if (msgid_header)
4004   {
4005   uschar *old_id;
4006   BOOL save_allow_domain_literals = allow_domain_literals;
4007   allow_domain_literals = TRUE;
4008   old_id = parse_extract_address(Ustrchr(msgid_header->text, ':') + 1,
4009     &errmsg, &start, &end, &domain, FALSE);
4010   allow_domain_literals = save_allow_domain_literals;
4011   if (old_id != NULL)
4012     g = string_append(g, 2, US" id=", string_printing(old_id));
4013   }
4014
4015 /* If subject logging is turned on, create suitable printing-character
4016 text. By expanding $h_subject: we make use of the MIME decoding. */
4017
4018 if (LOGGING(subject) && subject_header)
4019   {
4020   int i;
4021   uschar *p = big_buffer;
4022   uschar *ss = expand_string(US"$h_subject:");
4023
4024   /* Backslash-quote any double quotes or backslashes so as to make a
4025   a C-like string, and turn any non-printers into escape sequences. */
4026
4027   *p++ = '\"';
4028   if (*ss != 0) for (i = 0; i < 100 && ss[i] != 0; i++)
4029     {
4030     if (ss[i] == '\"' || ss[i] == '\\') *p++ = '\\';
4031     *p++ = ss[i];
4032     }
4033   *p++ = '\"';
4034   *p = 0;
4035   g = string_append(g, 2, US" T=", string_printing(big_buffer));
4036   }
4037
4038 /* Terminate the string: string_cat() and string_append() leave room, but do
4039 not put the zero in. */
4040
4041 (void) string_from_gstring(g);
4042
4043 /* Create a message log file if message logs are being used and this message is
4044 not blackholed. Write the reception stuff to it. We used to leave message log
4045 creation until the first delivery, but this has proved confusing for some
4046 people. */
4047
4048 if (message_logs && !blackholed_by)
4049   {
4050   int fd;
4051
4052   spool_name = spool_fname(US"msglog", message_subdir, message_id, US"");
4053   
4054   if (  (fd = Uopen(spool_name, O_WRONLY|O_APPEND|O_CREAT, SPOOL_MODE)) < 0
4055      && errno == ENOENT
4056      )
4057     {
4058     (void)directory_make(spool_directory,
4059                         spool_sname(US"msglog", message_subdir),
4060                         MSGLOG_DIRECTORY_MODE, TRUE);
4061     fd = Uopen(spool_name, O_WRONLY|O_APPEND|O_CREAT, SPOOL_MODE);
4062     }
4063
4064   if (fd < 0)
4065     log_write(0, LOG_MAIN|LOG_PANIC, "Couldn't open message log %s: %s",
4066       spool_name, strerror(errno));
4067   else
4068     {
4069     FILE *message_log = fdopen(fd, "a");
4070     if (message_log == NULL)
4071       {
4072       log_write(0, LOG_MAIN|LOG_PANIC, "Couldn't fdopen message log %s: %s",
4073         spool_name, strerror(errno));
4074       (void)close(fd);
4075       }
4076     else
4077       {
4078       uschar *now = tod_stamp(tod_log);
4079       fprintf(message_log, "%s Received from %s\n", now, g->s+3);
4080       if (deliver_freeze) fprintf(message_log, "%s frozen by %s\n", now,
4081         frozen_by);
4082       if (queue_only_policy) fprintf(message_log,
4083         "%s no immediate delivery: queued%s%s by %s\n", now,
4084         *queue_name ? " in " : "", *queue_name ? CS queue_name : "",
4085         queued_by);
4086       (void)fclose(message_log);
4087       }
4088     }
4089   }
4090
4091 /* Everything has now been done for a successful message except logging its
4092 arrival, and outputting an SMTP response. While writing to the log, set a flag
4093 to cause a call to receive_bomb_out() if the log cannot be opened. */
4094
4095 receive_call_bombout = TRUE;
4096
4097 /* Before sending an SMTP response in a TCP/IP session, we check to see if the
4098 connection has gone away. This can only be done if there is no unconsumed input
4099 waiting in the local input buffer. We can test for this by calling
4100 receive_smtp_buffered(). RFC 2920 (pipelining) explicitly allows for additional
4101 input to be sent following the final dot, so the presence of following input is
4102 not an error.
4103
4104 If the connection is still present, but there is no unread input for the
4105 socket, the result of a select() call will be zero. If, however, the connection
4106 has gone away, or if there is pending input, the result of select() will be
4107 non-zero. The two cases can be distinguished by trying to read the next input
4108 character. If we succeed, we can unread it so that it remains in the local
4109 buffer for handling later. If not, the connection has been lost.
4110
4111 Of course, since TCP/IP is asynchronous, there is always a chance that the
4112 connection will vanish between the time of this test and the sending of the
4113 response, but the chance of this happening should be small. */
4114
4115 if (smtp_input && sender_host_address != NULL && !sender_host_notsocket &&
4116     !receive_smtp_buffered())
4117   {
4118   struct timeval tv;
4119   fd_set select_check;
4120   FD_ZERO(&select_check);
4121   FD_SET(fileno(smtp_in), &select_check);
4122   tv.tv_sec = 0;
4123   tv.tv_usec = 0;
4124
4125   if (select(fileno(smtp_in) + 1, &select_check, NULL, NULL, &tv) != 0)
4126     {
4127     int c = (receive_getc)(GETC_BUFFER_UNLIMITED);
4128     if (c != EOF) (receive_ungetc)(c); else
4129       {
4130       smtp_notquit_exit(US"connection-lost", NULL, NULL);
4131       smtp_reply = US"";    /* No attempt to send a response */
4132       smtp_yield = FALSE;   /* Nothing more on this connection */
4133
4134       /* Re-use the log line workspace */
4135
4136       g->ptr = 0;
4137       g = string_cat(g, US"SMTP connection lost after final dot");
4138       g = add_host_info_for_log(g);
4139       log_write(0, LOG_MAIN, "%s", string_from_gstring(g));
4140
4141       /* Delete the files for this aborted message. */
4142
4143       Uunlink(spool_fname(US"input", message_subdir, message_id, US"-D"));
4144       Uunlink(spool_fname(US"input", message_subdir, message_id, US"-H"));
4145       Uunlink(spool_fname(US"msglog", message_subdir, message_id, US""));
4146
4147       goto TIDYUP;
4148       }
4149     }
4150   }
4151
4152 /* The connection has not gone away; we really are going to take responsibility
4153 for this message. */
4154
4155 /* Cutthrough - had sender last-dot; assume we've sent (or bufferred) all
4156    data onward by now.
4157
4158    Send dot onward.  If accepted, wipe the spooled files, log as delivered and accept
4159    the sender's dot (below).
4160    If rejected: copy response to sender, wipe the spooled files, log appropriately.
4161    If temp-reject: normally accept to sender, keep the spooled file - unless defer=pass
4162    in which case pass temp-reject back to initiator and dump the files.
4163
4164    Having the normal spool files lets us do data-filtering, and store/forward on temp-reject.
4165
4166    XXX We do not handle queue-only, freezing, or blackholes.
4167 */
4168 if(cutthrough.fd >= 0 && cutthrough.delivery)
4169   {
4170   uschar * msg = cutthrough_finaldot(); /* Ask the target system to accept the message */
4171                                         /* Logging was done in finaldot() */
4172   switch(msg[0])
4173     {
4174     case '2':   /* Accept. Do the same to the source; dump any spoolfiles.   */
4175       cutthrough_done = ACCEPTED;
4176       break;                                    /* message_id needed for SMTP accept below */
4177
4178     case '4':   /* Temp-reject. Keep spoolfiles and accept, unless defer-pass mode.
4179                 ... for which, pass back the exact error */
4180       if (cutthrough.defer_pass) smtp_reply = string_copy_malloc(msg);
4181       cutthrough_done = TMP_REJ;                /* Avoid the usual immediate delivery attempt */
4182       break;                                    /* message_id needed for SMTP accept below */
4183
4184     default:    /* Unknown response, or error.  Treat as temp-reject.         */
4185       if (cutthrough.defer_pass) smtp_reply = US"450 Onward transmission not accepted";
4186       cutthrough_done = TMP_REJ;                /* Avoid the usual immediate delivery attempt */
4187       break;                                    /* message_id needed for SMTP accept below */
4188
4189     case '5':   /* Perm-reject.  Do the same to the source.  Dump any spoolfiles */
4190       smtp_reply = string_copy_malloc(msg);             /* Pass on the exact error */
4191       cutthrough_done = PERM_REJ;
4192       break;
4193     }
4194   }
4195
4196 #ifndef DISABLE_PRDR
4197 if(!smtp_reply || prdr_requested)
4198 #else
4199 if(!smtp_reply)
4200 #endif
4201   {
4202   log_write(0, LOG_MAIN |
4203     (LOGGING(received_recipients)? LOG_RECIPIENTS : 0) |
4204     (LOGGING(received_sender)? LOG_SENDER : 0),
4205     "%s", g->s);
4206
4207   /* Log any control actions taken by an ACL or local_scan(). */
4208
4209   if (deliver_freeze) log_write(0, LOG_MAIN, "frozen by %s", frozen_by);
4210   if (queue_only_policy) log_write(L_delay_delivery, LOG_MAIN,
4211     "no immediate delivery: queued%s%s by %s",
4212     *queue_name ? " in " : "", *queue_name ? CS queue_name : "",       
4213     queued_by);
4214   }
4215 receive_call_bombout = FALSE;
4216
4217 store_reset(g);   /* The store for the main log message can be reused */
4218
4219 /* If the message is frozen, and freeze_tell is set, do the telling. */
4220
4221 if (deliver_freeze && freeze_tell != NULL && freeze_tell[0] != 0)
4222   {
4223   moan_tell_someone(freeze_tell, NULL, US"Message frozen on arrival",
4224     "Message %s was frozen on arrival by %s.\nThe sender is <%s>.\n",
4225     message_id, frozen_by, sender_address);
4226   }
4227
4228
4229 /* Either a message has been successfully received and written to the two spool
4230 files, or an error in writing the spool has occurred for an SMTP message, or
4231 an SMTP message has been rejected for policy reasons. (For a non-SMTP message
4232 we will have already given up because there's no point in carrying on!) In
4233 either event, we must now close (and thereby unlock) the data file. In the
4234 successful case, this leaves the message on the spool, ready for delivery. In
4235 the error case, the spool file will be deleted. Then tidy up store, interact
4236 with an SMTP call if necessary, and return.
4237
4238 A fflush() was done earlier in the expectation that any write errors on the
4239 data file will be flushed(!) out thereby. Nevertheless, it is theoretically
4240 possible for fclose() to fail - but what to do? What has happened to the lock
4241 if this happens? */
4242
4243
4244 TIDYUP:
4245 process_info[process_info_len] = 0;                /* Remove message id */
4246 if (data_file != NULL) (void)fclose(data_file);    /* Frees the lock */
4247
4248 /* Now reset signal handlers to their defaults */
4249
4250 signal(SIGTERM, SIG_DFL);
4251 signal(SIGINT, SIG_DFL);
4252
4253 /* Tell an SMTP caller the state of play, and arrange to return the SMTP return
4254 value, which defaults TRUE - meaning there may be more incoming messages from
4255 this connection. For non-SMTP callers (where there is only ever one message),
4256 the default is FALSE. */
4257
4258 if (smtp_input)
4259   {
4260   yield = smtp_yield;
4261
4262   /* Handle interactive SMTP callers. After several kinds of error, smtp_reply
4263   is set to the response that should be sent. When it is NULL, we generate
4264   default responses. After an ACL error or local_scan() error, the response has
4265   already been sent, and smtp_reply is an empty string to indicate this. */
4266
4267   if (!smtp_batched_input)
4268     {
4269     if (!smtp_reply)
4270       {
4271       if (fake_response != OK)
4272         smtp_respond(fake_response == DEFER ? US"450" : US"550",
4273           3, TRUE, fake_response_text);
4274
4275       /* An OK response is required; use "message" text if present. */
4276
4277       else if (user_msg)
4278         {
4279         uschar *code = US"250";
4280         int len = 3;
4281         smtp_message_code(&code, &len, &user_msg, NULL, TRUE);
4282         smtp_respond(code, len, TRUE, user_msg);
4283         }
4284
4285       /* Default OK response */
4286
4287       else if (chunking_state > CHUNKING_OFFERED)
4288         {
4289         smtp_printf("250- %u byte chunk, total %d\r\n250 OK id=%s\r\n", FALSE,
4290             chunking_datasize, message_size+message_linecount, message_id);
4291         chunking_state = CHUNKING_OFFERED;
4292         }
4293       else
4294         smtp_printf("250 OK id=%s\r\n", FALSE, message_id);
4295
4296       if (host_checking)
4297         fprintf(stdout,
4298           "\n**** SMTP testing: that is not a real message id!\n\n");
4299       }
4300
4301     /* smtp_reply is set non-empty */
4302
4303     else if (smtp_reply[0] != 0)
4304       if (fake_response != OK && (smtp_reply[0] == '2'))
4305         smtp_respond((fake_response == DEFER)? US"450" : US"550", 3, TRUE,
4306           fake_response_text);
4307       else
4308         smtp_printf("%.1024s\r\n", FALSE, smtp_reply);
4309
4310     switch (cutthrough_done)
4311       {
4312       case ACCEPTED:
4313         log_write(0, LOG_MAIN, "Completed");/* Delivery was done */
4314       case PERM_REJ:
4315                                                          /* Delete spool files */
4316         Uunlink(spool_fname(US"input", message_subdir, message_id, US"-D"));
4317         Uunlink(spool_fname(US"input", message_subdir, message_id, US"-H"));
4318         Uunlink(spool_fname(US"msglog", message_subdir, message_id, US""));
4319         break;
4320
4321       case TMP_REJ:
4322         if (cutthrough.defer_pass)
4323           {
4324           Uunlink(spool_fname(US"input", message_subdir, message_id, US"-D"));
4325           Uunlink(spool_fname(US"input", message_subdir, message_id, US"-H"));
4326           Uunlink(spool_fname(US"msglog", message_subdir, message_id, US""));
4327           }
4328       default:
4329         break;
4330       }
4331     if (cutthrough_done != NOT_TRIED)
4332       {
4333       message_id[0] = 0;          /* Prevent a delivery from starting */
4334       cutthrough.delivery = cutthrough.callout_hold_only = FALSE;
4335       cutthrough.defer_pass = FALSE;
4336       }
4337     }
4338
4339   /* For batched SMTP, generate an error message on failure, and do
4340   nothing on success. The function moan_smtp_batch() does not return -
4341   it exits from the program with a non-zero return code. */
4342
4343   else if (smtp_reply)
4344     moan_smtp_batch(NULL, "%s", smtp_reply);
4345   }
4346
4347
4348 /* If blackholing, we can immediately log this message's sad fate. The data
4349 file has already been unlinked, and the header file was never written to disk.
4350 We must now indicate that nothing was received, to prevent a delivery from
4351 starting. */
4352
4353 if (blackholed_by)
4354   {
4355   const uschar *detail =
4356     local_scan_data ? string_printing(local_scan_data) :
4357     string_sprintf("(%s discarded recipients)", blackholed_by);
4358   log_write(0, LOG_MAIN, "=> blackhole %s%s", detail, blackhole_log_msg);
4359   log_write(0, LOG_MAIN, "Completed");
4360   message_id[0] = 0;
4361   }
4362
4363 /* Reset headers so that logging of rejects for a subsequent message doesn't
4364 include them. It is also important to set header_last = NULL before exiting
4365 from this function, as this prevents certain rewrites that might happen during
4366 subsequent verifying (of another incoming message) from trying to add headers
4367 when they shouldn't. */
4368
4369 header_list = header_last = NULL;
4370
4371 return yield;  /* TRUE if more messages (SMTP only) */
4372 }
4373
4374 /* End of receive.c */