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