3334ba2cb3ea98418ed4388ce7856580300c3d37
[exim.git] / src / src / deliver.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2014 */
6 /* See the file NOTICE for conditions of use and distribution. */
7
8 /* The main code for delivering a message. */
9
10
11 #include "exim.h"
12
13
14 /* Data block for keeping track of subprocesses for parallel remote
15 delivery. */
16
17 typedef struct pardata {
18   address_item *addrlist;      /* chain of addresses */
19   address_item *addr;          /* next address data expected for */
20   pid_t pid;                   /* subprocess pid */
21   int fd;                      /* pipe fd for getting result from subprocess */
22   int transport_count;         /* returned transport count value */
23   BOOL done;                   /* no more data needed */
24   uschar *msg;                 /* error message */
25   uschar *return_path;         /* return_path for these addresses */
26 } pardata;
27
28 /* Values for the process_recipients variable */
29
30 enum { RECIP_ACCEPT, RECIP_IGNORE, RECIP_DEFER,
31        RECIP_FAIL, RECIP_FAIL_FILTER, RECIP_FAIL_TIMEOUT,
32        RECIP_FAIL_LOOP};
33
34 /* Mutually recursive functions for marking addresses done. */
35
36 static void child_done(address_item *, uschar *);
37 static void address_done(address_item *, uschar *);
38
39 /* Table for turning base-62 numbers into binary */
40
41 static uschar tab62[] =
42           {0,1,2,3,4,5,6,7,8,9,0,0,0,0,0,0,     /* 0-9 */
43            0,10,11,12,13,14,15,16,17,18,19,20,  /* A-K */
44           21,22,23,24,25,26,27,28,29,30,31,32,  /* L-W */
45           33,34,35, 0, 0, 0, 0, 0,              /* X-Z */
46            0,36,37,38,39,40,41,42,43,44,45,46,  /* a-k */
47           47,48,49,50,51,52,53,54,55,56,57,58,  /* l-w */
48           59,60,61};                            /* x-z */
49
50
51 /*************************************************
52 *            Local static variables              *
53 *************************************************/
54
55 /* addr_duplicate is global because it needs to be seen from the Envelope-To
56 writing code. */
57
58 static address_item *addr_defer = NULL;
59 static address_item *addr_failed = NULL;
60 static address_item *addr_fallback = NULL;
61 static address_item *addr_local = NULL;
62 static address_item *addr_new = NULL;
63 static address_item *addr_remote = NULL;
64 static address_item *addr_route = NULL;
65 static address_item *addr_succeed = NULL;
66
67 static FILE *message_log = NULL;
68 static BOOL update_spool;
69 static BOOL remove_journal;
70 static int  parcount = 0;
71 static pardata *parlist = NULL;
72 static int  return_count;
73 static uschar *frozen_info = US"";
74 static uschar *used_return_path = NULL;
75
76 static uschar spoolname[PATH_MAX];
77
78
79
80 /*************************************************
81 *             Make a new address item            *
82 *************************************************/
83
84 /* This function gets the store and initializes with default values. The
85 transport_return value defaults to DEFER, so that any unexpected failure to
86 deliver does not wipe out the message. The default unique string is set to a
87 copy of the address, so that its domain can be lowercased.
88
89 Argument:
90   address     the RFC822 address string
91   copy        force a copy of the address
92
93 Returns:      a pointer to an initialized address_item
94 */
95
96 address_item *
97 deliver_make_addr(uschar *address, BOOL copy)
98 {
99 address_item *addr = store_get(sizeof(address_item));
100 *addr = address_defaults;
101 if (copy) address = string_copy(address);
102 addr->address = address;
103 addr->unique = string_copy(address);
104 return addr;
105 }
106
107
108
109
110 /*************************************************
111 *     Set expansion values for an address        *
112 *************************************************/
113
114 /* Certain expansion variables are valid only when handling an address or
115 address list. This function sets them up or clears the values, according to its
116 argument.
117
118 Arguments:
119   addr          the address in question, or NULL to clear values
120 Returns:        nothing
121 */
122
123 void
124 deliver_set_expansions(address_item *addr)
125 {
126 if (addr == NULL)
127   {
128   uschar ***p = address_expansions;
129   while (*p != NULL) **p++ = NULL;
130   return;
131   }
132
133 /* Exactly what gets set depends on whether there is one or more addresses, and
134 what they contain. These first ones are always set, taking their values from
135 the first address. */
136
137 if (addr->host_list == NULL)
138   {
139   deliver_host = deliver_host_address = US"";
140   }
141 else
142   {
143   deliver_host = addr->host_list->name;
144   deliver_host_address = addr->host_list->address;
145   }
146
147 deliver_recipients = addr;
148 deliver_address_data = addr->p.address_data;
149 deliver_domain_data = addr->p.domain_data;
150 deliver_localpart_data = addr->p.localpart_data;
151
152 /* These may be unset for multiple addresses */
153
154 deliver_domain = addr->domain;
155 self_hostname = addr->self_hostname;
156
157 #ifdef EXPERIMENTAL_BRIGHTMAIL
158 bmi_deliver = 1;    /* deliver by default */
159 bmi_alt_location = NULL;
160 bmi_base64_verdict = NULL;
161 bmi_base64_tracker_verdict = NULL;
162 #endif
163
164 /* If there's only one address we can set everything. */
165
166 if (addr->next == NULL)
167   {
168   address_item *addr_orig;
169
170   deliver_localpart = addr->local_part;
171   deliver_localpart_prefix = addr->prefix;
172   deliver_localpart_suffix = addr->suffix;
173
174   for (addr_orig = addr; addr_orig->parent != NULL;
175     addr_orig = addr_orig->parent);
176   deliver_domain_orig = addr_orig->domain;
177
178   /* Re-instate any prefix and suffix in the original local part. In all
179   normal cases, the address will have a router associated with it, and we can
180   choose the caseful or caseless version accordingly. However, when a system
181   filter sets up a pipe, file, or autoreply delivery, no router is involved.
182   In this case, though, there won't be any prefix or suffix to worry about. */
183
184   deliver_localpart_orig = (addr_orig->router == NULL)? addr_orig->local_part :
185     addr_orig->router->caseful_local_part?
186       addr_orig->cc_local_part : addr_orig->lc_local_part;
187
188   /* If there's a parent, make its domain and local part available, and if
189   delivering to a pipe or file, or sending an autoreply, get the local
190   part from the parent. For pipes and files, put the pipe or file string
191   into address_pipe and address_file. */
192
193   if (addr->parent != NULL)
194     {
195     deliver_domain_parent = addr->parent->domain;
196     deliver_localpart_parent = (addr->parent->router == NULL)?
197       addr->parent->local_part :
198         addr->parent->router->caseful_local_part?
199           addr->parent->cc_local_part : addr->parent->lc_local_part;
200
201     /* File deliveries have their own flag because they need to be picked out
202     as special more often. */
203
204     if (testflag(addr, af_pfr))
205       {
206       if (testflag(addr, af_file)) address_file = addr->local_part;
207         else if (deliver_localpart[0] == '|') address_pipe = addr->local_part;
208       deliver_localpart = addr->parent->local_part;
209       deliver_localpart_prefix = addr->parent->prefix;
210       deliver_localpart_suffix = addr->parent->suffix;
211       }
212     }
213
214 #ifdef EXPERIMENTAL_BRIGHTMAIL
215     /* Set expansion variables related to Brightmail AntiSpam */
216     bmi_base64_verdict = bmi_get_base64_verdict(deliver_localpart_orig, deliver_domain_orig);
217     bmi_base64_tracker_verdict = bmi_get_base64_tracker_verdict(bmi_base64_verdict);
218     /* get message delivery status (0 - don't deliver | 1 - deliver) */
219     bmi_deliver = bmi_get_delivery_status(bmi_base64_verdict);
220     /* if message is to be delivered, get eventual alternate location */
221     if (bmi_deliver == 1) {
222       bmi_alt_location = bmi_get_alt_location(bmi_base64_verdict);
223     };
224 #endif
225
226   }
227
228 /* For multiple addresses, don't set local part, and leave the domain and
229 self_hostname set only if it is the same for all of them. It is possible to
230 have multiple pipe and file addresses, but only when all addresses have routed
231 to the same pipe or file. */
232
233 else
234   {
235   address_item *addr2;
236   if (testflag(addr, af_pfr))
237     {
238     if (testflag(addr, af_file)) address_file = addr->local_part;
239       else if (addr->local_part[0] == '|') address_pipe = addr->local_part;
240     }
241   for (addr2 = addr->next; addr2 != NULL; addr2 = addr2->next)
242     {
243     if (deliver_domain != NULL &&
244         Ustrcmp(deliver_domain, addr2->domain) != 0)
245       deliver_domain = NULL;
246     if (self_hostname != NULL && (addr2->self_hostname == NULL ||
247         Ustrcmp(self_hostname, addr2->self_hostname) != 0))
248       self_hostname = NULL;
249     if (deliver_domain == NULL && self_hostname == NULL) break;
250     }
251   }
252 }
253
254
255
256
257 /*************************************************
258 *                Open a msglog file              *
259 *************************************************/
260
261 /* This function is used both for normal message logs, and for files in the
262 msglog directory that are used to catch output from pipes. Try to create the
263 directory if it does not exist. From release 4.21, normal message logs should
264 be created when the message is received.
265
266 Argument:
267   filename  the file name
268   mode      the mode required
269   error     used for saying what failed
270
271 Returns:    a file descriptor, or -1 (with errno set)
272 */
273
274 static int
275 open_msglog_file(uschar *filename, int mode, uschar **error)
276 {
277 int fd = Uopen(filename, O_WRONLY|O_APPEND|O_CREAT, mode);
278
279 if (fd < 0 && errno == ENOENT)
280   {
281   uschar temp[16];
282   sprintf(CS temp, "msglog/%s", message_subdir);
283   if (message_subdir[0] == 0) temp[6] = 0;
284   (void)directory_make(spool_directory, temp, MSGLOG_DIRECTORY_MODE, TRUE);
285   fd = Uopen(filename, O_WRONLY|O_APPEND|O_CREAT, mode);
286   }
287
288 /* Set the close-on-exec flag and change the owner to the exim uid/gid (this
289 function is called as root). Double check the mode, because the group setting
290 doesn't always get set automatically. */
291
292 if (fd >= 0)
293   {
294   (void)fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
295   if (fchown(fd, exim_uid, exim_gid) < 0)
296     {
297     *error = US"chown";
298     return -1;
299     }
300   if (fchmod(fd, mode) < 0)
301     {
302     *error = US"chmod";
303     return -1;
304     }
305   }
306 else *error = US"create";
307
308 return fd;
309 }
310
311
312
313
314 /*************************************************
315 *           Write to msglog if required          *
316 *************************************************/
317
318 /* Write to the message log, if configured. This function may also be called
319 from transports.
320
321 Arguments:
322   format       a string format
323
324 Returns:       nothing
325 */
326
327 void
328 deliver_msglog(const char *format, ...)
329 {
330 va_list ap;
331 if (!message_logs) return;
332 va_start(ap, format);
333 vfprintf(message_log, format, ap);
334 fflush(message_log);
335 va_end(ap);
336 }
337
338
339
340
341 /*************************************************
342 *            Replicate status for batch          *
343 *************************************************/
344
345 /* When a transport handles a batch of addresses, it may treat them
346 individually, or it may just put the status in the first one, and return FALSE,
347 requesting that the status be copied to all the others externally. This is the
348 replication function. As well as the status, it copies the transport pointer,
349 which may have changed if appendfile passed the addresses on to a different
350 transport.
351
352 Argument:    pointer to the first address in a chain
353 Returns:     nothing
354 */
355
356 static void
357 replicate_status(address_item *addr)
358 {
359 address_item *addr2;
360 for (addr2 = addr->next; addr2 != NULL; addr2 = addr2->next)
361   {
362   addr2->transport = addr->transport;
363   addr2->transport_return = addr->transport_return;
364   addr2->basic_errno = addr->basic_errno;
365   addr2->more_errno = addr->more_errno;
366   addr2->special_action = addr->special_action;
367   addr2->message = addr->message;
368   addr2->user_message = addr->user_message;
369   }
370 }
371
372
373
374 /*************************************************
375 *              Compare lists of hosts            *
376 *************************************************/
377
378 /* This function is given two pointers to chains of host items, and it yields
379 TRUE if the lists refer to the same hosts in the same order, except that
380
381 (1) Multiple hosts with the same non-negative MX values are permitted to appear
382     in different orders. Round-robinning nameservers can cause this to happen.
383
384 (2) Multiple hosts with the same negative MX values less than MX_NONE are also
385     permitted to appear in different orders. This is caused by randomizing
386     hosts lists.
387
388 This enables Exim to use a single SMTP transaction for sending to two entirely
389 different domains that happen to end up pointing at the same hosts.
390
391 Arguments:
392   one       points to the first host list
393   two       points to the second host list
394
395 Returns:    TRUE if the lists refer to the same host set
396 */
397
398 static BOOL
399 same_hosts(host_item *one, host_item *two)
400 {
401 while (one != NULL && two != NULL)
402   {
403   if (Ustrcmp(one->name, two->name) != 0)
404     {
405     int mx = one->mx;
406     host_item *end_one = one;
407     host_item *end_two = two;
408
409     /* Batch up only if there was no MX and the list was not randomized */
410
411     if (mx == MX_NONE) return FALSE;
412
413     /* Find the ends of the shortest sequence of identical MX values */
414
415     while (end_one->next != NULL && end_one->next->mx == mx &&
416            end_two->next != NULL && end_two->next->mx == mx)
417       {
418       end_one = end_one->next;
419       end_two = end_two->next;
420       }
421
422     /* If there aren't any duplicates, there's no match. */
423
424     if (end_one == one) return FALSE;
425
426     /* For each host in the 'one' sequence, check that it appears in the 'two'
427     sequence, returning FALSE if not. */
428
429     for (;;)
430       {
431       host_item *hi;
432       for (hi = two; hi != end_two->next; hi = hi->next)
433         if (Ustrcmp(one->name, hi->name) == 0) break;
434       if (hi == end_two->next) return FALSE;
435       if (one == end_one) break;
436       one = one->next;
437       }
438
439     /* All the hosts in the 'one' sequence were found in the 'two' sequence.
440     Ensure both are pointing at the last host, and carry on as for equality. */
441
442     two = end_two;
443     }
444
445   /* Hosts matched */
446
447   one = one->next;
448   two = two->next;
449   }
450
451 /* True if both are NULL */
452
453 return (one == two);
454 }
455
456
457
458 /*************************************************
459 *              Compare header lines              *
460 *************************************************/
461
462 /* This function is given two pointers to chains of header items, and it yields
463 TRUE if they are the same header texts in the same order.
464
465 Arguments:
466   one       points to the first header list
467   two       points to the second header list
468
469 Returns:    TRUE if the lists refer to the same header set
470 */
471
472 static BOOL
473 same_headers(header_line *one, header_line *two)
474 {
475 for (;;)
476   {
477   if (one == two) return TRUE;   /* Includes the case where both NULL */
478   if (one == NULL || two == NULL) return FALSE;
479   if (Ustrcmp(one->text, two->text) != 0) return FALSE;
480   one = one->next;
481   two = two->next;
482   }
483 }
484
485
486
487 /*************************************************
488 *            Compare string settings             *
489 *************************************************/
490
491 /* This function is given two pointers to strings, and it returns
492 TRUE if they are the same pointer, or if the two strings are the same.
493
494 Arguments:
495   one       points to the first string
496   two       points to the second string
497
498 Returns:    TRUE or FALSE
499 */
500
501 static BOOL
502 same_strings(uschar *one, uschar *two)
503 {
504 if (one == two) return TRUE;   /* Includes the case where both NULL */
505 if (one == NULL || two == NULL) return FALSE;
506 return (Ustrcmp(one, two) == 0);
507 }
508
509
510
511 /*************************************************
512 *        Compare uid/gid for addresses           *
513 *************************************************/
514
515 /* This function is given a transport and two addresses. It yields TRUE if the
516 uid/gid/initgroups settings for the two addresses are going to be the same when
517 they are delivered.
518
519 Arguments:
520   tp            the transort
521   addr1         the first address
522   addr2         the second address
523
524 Returns:        TRUE or FALSE
525 */
526
527 static BOOL
528 same_ugid(transport_instance *tp, address_item *addr1, address_item *addr2)
529 {
530 if (!tp->uid_set && tp->expand_uid == NULL && !tp->deliver_as_creator)
531   {
532   if (testflag(addr1, af_uid_set) != testflag(addr2, af_gid_set) ||
533        (testflag(addr1, af_uid_set) &&
534          (addr1->uid != addr2->uid ||
535           testflag(addr1, af_initgroups) != testflag(addr2, af_initgroups))))
536     return FALSE;
537   }
538
539 if (!tp->gid_set && tp->expand_gid == NULL)
540   {
541   if (testflag(addr1, af_gid_set) != testflag(addr2, af_gid_set) ||
542      (testflag(addr1, af_gid_set) && addr1->gid != addr2->gid))
543     return FALSE;
544   }
545
546 return TRUE;
547 }
548
549
550
551
552 /*************************************************
553 *      Record that an address is complete        *
554 *************************************************/
555
556 /* This function records that an address is complete. This is straightforward
557 for most addresses, where the unique address is just the full address with the
558 domain lower cased. For homonyms (addresses that are the same as one of their
559 ancestors) their are complications. Their unique addresses have \x\ prepended
560 (where x = 0, 1, 2...), so that de-duplication works correctly for siblings and
561 cousins.
562
563 Exim used to record the unique addresses of homonyms as "complete". This,
564 however, fails when the pattern of redirection varies over time (e.g. if taking
565 unseen copies at only some times of day) because the prepended numbers may vary
566 from one delivery run to the next. This problem is solved by never recording
567 prepended unique addresses as complete. Instead, when a homonymic address has
568 actually been delivered via a transport, we record its basic unique address
569 followed by the name of the transport. This is checked in subsequent delivery
570 runs whenever an address is routed to a transport.
571
572 If the completed address is a top-level one (has no parent, which means it
573 cannot be homonymic) we also add the original address to the non-recipients
574 tree, so that it gets recorded in the spool file and therefore appears as
575 "done" in any spool listings. The original address may differ from the unique
576 address in the case of the domain.
577
578 Finally, this function scans the list of duplicates, marks as done any that
579 match this address, and calls child_done() for their ancestors.
580
581 Arguments:
582   addr        address item that has been completed
583   now         current time as a string
584
585 Returns:      nothing
586 */
587
588 static void
589 address_done(address_item *addr, uschar *now)
590 {
591 address_item *dup;
592
593 update_spool = TRUE;        /* Ensure spool gets updated */
594
595 /* Top-level address */
596
597 if (addr->parent == NULL)
598   {
599   tree_add_nonrecipient(addr->unique);
600   tree_add_nonrecipient(addr->address);
601   }
602
603 /* Homonymous child address */
604
605 else if (testflag(addr, af_homonym))
606   {
607   if (addr->transport != NULL)
608     {
609     tree_add_nonrecipient(
610       string_sprintf("%s/%s", addr->unique + 3, addr->transport->name));
611     }
612   }
613
614 /* Non-homonymous child address */
615
616 else tree_add_nonrecipient(addr->unique);
617
618 /* Check the list of duplicate addresses and ensure they are now marked
619 done as well. */
620
621 for (dup = addr_duplicate; dup != NULL; dup = dup->next)
622   {
623   if (Ustrcmp(addr->unique, dup->unique) == 0)
624     {
625     tree_add_nonrecipient(dup->unique);
626     child_done(dup, now);
627     }
628   }
629 }
630
631
632
633
634 /*************************************************
635 *      Decrease counts in parents and mark done  *
636 *************************************************/
637
638 /* This function is called when an address is complete. If there is a parent
639 address, its count of children is decremented. If there are still other
640 children outstanding, the function exits. Otherwise, if the count has become
641 zero, address_done() is called to mark the parent and its duplicates complete.
642 Then loop for any earlier ancestors.
643
644 Arguments:
645   addr      points to the completed address item
646   now       the current time as a string, for writing to the message log
647
648 Returns:    nothing
649 */
650
651 static void
652 child_done(address_item *addr, uschar *now)
653 {
654 address_item *aa;
655 while (addr->parent != NULL)
656   {
657   addr = addr->parent;
658   if ((addr->child_count -= 1) > 0) return;   /* Incomplete parent */
659   address_done(addr, now);
660
661   /* Log the completion of all descendents only when there is no ancestor with
662   the same original address. */
663
664   for (aa = addr->parent; aa != NULL; aa = aa->parent)
665     if (Ustrcmp(aa->address, addr->address) == 0) break;
666   if (aa != NULL) continue;
667
668   deliver_msglog("%s %s: children all complete\n", now, addr->address);
669   DEBUG(D_deliver) debug_printf("%s: children all complete\n", addr->address);
670   }
671 }
672
673
674
675
676 static uschar *
677 d_hostlog(uschar * s, int * sizep, int * ptrp, address_item * addr)
678 {
679   s = string_append(s, sizep, ptrp, 5, US" H=", addr->host_used->name,
680     US" [", addr->host_used->address, US"]");
681   if ((log_extra_selector & LX_outgoing_port) != 0)
682     s = string_append(s, sizep, ptrp, 2, US":", string_sprintf("%d",
683       addr->host_used->port));
684   return s;
685 }
686
687 #ifdef SUPPORT_TLS
688 static uschar *
689 d_tlslog(uschar * s, int * sizep, int * ptrp, address_item * addr)
690 {
691   if ((log_extra_selector & LX_tls_cipher) != 0 && addr->cipher != NULL)
692     s = string_append(s, sizep, ptrp, 2, US" X=", addr->cipher);
693   if ((log_extra_selector & LX_tls_certificate_verified) != 0 &&
694        addr->cipher != NULL)
695     s = string_append(s, sizep, ptrp, 2, US" CV=",
696       testflag(addr, af_cert_verified)? "yes":"no");
697   if ((log_extra_selector & LX_tls_peerdn) != 0 && addr->peerdn != NULL)
698     s = string_append(s, sizep, ptrp, 3, US" DN=\"",
699       string_printing(addr->peerdn), US"\"");
700   return s;
701 }
702 #endif
703
704 /* If msg is NULL this is a delivery log and logchar is used. Otherwise
705 this is a nonstandard call; no two-character delivery flag is written
706 but sender-host and sender are prefixed and "msg" is inserted in the log line.
707
708 Arguments:
709   flags         passed to log_write()
710 */
711 void
712 delivery_log(int flags, address_item * addr, int logchar, uschar * msg)
713 {
714 uschar *log_address;
715 int size = 256;         /* Used for a temporary, */
716 int ptr = 0;            /* expanding buffer, for */
717 uschar *s;              /* building log lines;   */
718 void *reset_point;      /* released afterwards.  */
719
720
721 /* Log the delivery on the main log. We use an extensible string to build up
722 the log line, and reset the store afterwards. Remote deliveries should always
723 have a pointer to the host item that succeeded; local deliveries can have a
724 pointer to a single host item in their host list, for use by the transport. */
725
726 #ifdef EXPERIMENTAL_TPDA
727   tpda_delivery_ip = NULL;      /* presume no successful remote delivery */
728   tpda_delivery_port = 0;
729   tpda_delivery_fqdn = NULL;
730   tpda_delivery_local_part = NULL;
731   tpda_delivery_domain = NULL;
732   tpda_delivery_confirmation = NULL;
733 #endif
734
735 s = reset_point = store_get(size);
736
737 log_address = string_log_address(addr, (log_write_selector & L_all_parents) != 0, TRUE);
738 if (msg)
739   s = string_append(s, &size, &ptr, 3, host_and_ident(TRUE), US" ", log_address);
740 else
741   {
742   s[ptr++] = logchar;
743   s = string_append(s, &size, &ptr, 2, US"> ", log_address);
744   }
745
746 if ((log_extra_selector & LX_sender_on_delivery) != 0  ||  msg)
747   s = string_append(s, &size, &ptr, 3, US" F=<", sender_address, US">");
748
749 #ifdef EXPERIMENTAL_SRS
750 if(addr->p.srs_sender)
751   s = string_append(s, &size, &ptr, 3, US" SRS=<", addr->p.srs_sender, US">");
752 #endif
753
754 /* You might think that the return path must always be set for a successful
755 delivery; indeed, I did for some time, until this statement crashed. The case
756 when it is not set is for a delivery to /dev/null which is optimised by not
757 being run at all. */
758
759 if (used_return_path != NULL &&
760       (log_extra_selector & LX_return_path_on_delivery) != 0)
761   s = string_append(s, &size, &ptr, 3, US" P=<", used_return_path, US">");
762
763 if (msg)
764   s = string_append(s, &size, &ptr, 2, US" ", msg);
765
766 /* For a delivery from a system filter, there may not be a router */
767 if (addr->router != NULL)
768   s = string_append(s, &size, &ptr, 2, US" R=", addr->router->name);
769
770 s = string_append(s, &size, &ptr, 2, US" T=", addr->transport->name);
771
772 if ((log_extra_selector & LX_delivery_size) != 0)
773   s = string_append(s, &size, &ptr, 2, US" S=",
774     string_sprintf("%d", transport_count));
775
776 /* Local delivery */
777
778 if (addr->transport->info->local)
779   {
780   if (addr->host_list != NULL)
781     {
782     s = string_append(s, &size, &ptr, 2, US" H=", addr->host_list->name);
783     #ifdef EXPERIMENTAL_TPDA
784       tpda_delivery_fqdn = addr->host_list->name;
785     #endif
786     }
787   if (addr->shadow_message != NULL)
788     s = string_cat(s, &size, &ptr, addr->shadow_message,
789       Ustrlen(addr->shadow_message));
790   }
791
792 /* Remote delivery */
793
794 else
795   {
796   if (addr->host_used != NULL)
797     {
798     s = d_hostlog(s, &size, &ptr, addr);
799     if (continue_sequence > 1)
800       s = string_cat(s, &size, &ptr, US"*", 1);
801
802     #ifdef EXPERIMENTAL_TPDA
803     tpda_delivery_ip =           addr->host_used->address;
804     tpda_delivery_port =         addr->host_used->port;
805     tpda_delivery_fqdn =         addr->host_used->name;
806     tpda_delivery_local_part =   addr->local_part;
807     tpda_delivery_domain =       addr->domain;
808     tpda_delivery_confirmation = addr->message;
809     #endif
810     }
811
812   #ifdef SUPPORT_TLS
813   s = d_tlslog(s, &size, &ptr, addr);
814   #endif
815
816   if (addr->authenticator)
817     {
818     s = string_append(s, &size, &ptr, 2, US" A=", addr->authenticator);
819     if (addr->auth_id)
820       {
821       s = string_append(s, &size, &ptr, 2, US":", addr->auth_id);
822       if (log_extra_selector & LX_smtp_mailauth  &&  addr->auth_sndr)
823         s = string_append(s, &size, &ptr, 2, US":", addr->auth_sndr);
824       }
825     }
826
827   #ifdef EXPERIMENTAL_PRDR
828   if (addr->flags & af_prdr_used)
829     s = string_append(s, &size, &ptr, 1, US" PRDR");
830   #endif
831   }
832
833 /* confirmation message (SMTP (host_used) and LMTP (driver_name)) */
834
835 if ((log_extra_selector & LX_smtp_confirmation) != 0 &&
836     addr->message != NULL &&
837     ((addr->host_used != NULL) || (Ustrcmp(addr->transport->driver_name, "lmtp") == 0)))
838   {
839   int i;
840   uschar *p = big_buffer;
841   uschar *ss = addr->message;
842   *p++ = '\"';
843   for (i = 0; i < 100 && ss[i] != 0; i++)
844     {
845     if (ss[i] == '\"' || ss[i] == '\\') *p++ = '\\';
846     *p++ = ss[i];
847     }
848   *p++ = '\"';
849   *p = 0;
850   s = string_append(s, &size, &ptr, 2, US" C=", big_buffer);
851   }
852
853 /* Time on queue and actual time taken to deliver */
854
855 if ((log_extra_selector & LX_queue_time) != 0)
856   {
857   s = string_append(s, &size, &ptr, 2, US" QT=",
858     readconf_printtime(time(NULL) - received_time));
859   }
860
861 if ((log_extra_selector & LX_deliver_time) != 0)
862   {
863   s = string_append(s, &size, &ptr, 2, US" DT=",
864     readconf_printtime(addr->more_errno));
865   }
866
867 /* string_cat() always leaves room for the terminator. Release the
868 store we used to build the line after writing it. */
869
870 s[ptr] = 0;
871 log_write(0, flags, "%s", s);
872
873 #ifdef EXPERIMENTAL_TPDA
874 if (addr->transport->tpda_delivery_action)
875   {
876   DEBUG(D_deliver)
877     debug_printf("  TPDA(Delivery): tpda_deliver_action=|%s| tpda_delivery_IP=%s\n",
878       addr->transport->tpda_delivery_action, tpda_delivery_ip);
879
880   router_name =    addr->router->name;
881   transport_name = addr->transport->name;
882   if (!expand_string(addr->transport->tpda_delivery_action) && *expand_string_message)
883     log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand tpda_deliver_action in %s: %s\n",
884       transport_name, expand_string_message);
885   router_name = NULL;
886   transport_name = NULL;
887   }
888 #endif
889 store_reset(reset_point);
890 return;
891 }
892
893
894
895 /*************************************************
896 *    Actions at the end of handling an address   *
897 *************************************************/
898
899 /* This is a function for processing a single address when all that can be done
900 with it has been done.
901
902 Arguments:
903   addr         points to the address block
904   result       the result of the delivery attempt
905   logflags     flags for log_write() (LOG_MAIN and/or LOG_PANIC)
906   driver_type  indicates which type of driver (transport, or router) was last
907                  to process the address
908   logchar      '=' or '-' for use when logging deliveries with => or ->
909
910 Returns:       nothing
911 */
912
913 static void
914 post_process_one(address_item *addr, int result, int logflags, int driver_type,
915   int logchar)
916 {
917 uschar *now = tod_stamp(tod_log);
918 uschar *driver_kind = NULL;
919 uschar *driver_name = NULL;
920 uschar *log_address;
921
922 int size = 256;         /* Used for a temporary, */
923 int ptr = 0;            /* expanding buffer, for */
924 uschar *s;              /* building log lines;   */
925 void *reset_point;      /* released afterwards.  */
926
927
928 DEBUG(D_deliver) debug_printf("post-process %s (%d)\n", addr->address, result);
929
930 /* Set up driver kind and name for logging. Disable logging if the router or
931 transport has disabled it. */
932
933 if (driver_type == DTYPE_TRANSPORT)
934   {
935   if (addr->transport != NULL)
936     {
937     driver_name = addr->transport->name;
938     driver_kind = US" transport";
939     disable_logging = addr->transport->disable_logging;
940     }
941   else driver_kind = US"transporting";
942   }
943 else if (driver_type == DTYPE_ROUTER)
944   {
945   if (addr->router != NULL)
946     {
947     driver_name = addr->router->name;
948     driver_kind = US" router";
949     disable_logging = addr->router->disable_logging;
950     }
951   else driver_kind = US"routing";
952   }
953
954 /* If there's an error message set, ensure that it contains only printing
955 characters - it should, but occasionally things slip in and this at least
956 stops the log format from getting wrecked. We also scan the message for an LDAP
957 expansion item that has a password setting, and flatten the password. This is a
958 fudge, but I don't know a cleaner way of doing this. (If the item is badly
959 malformed, it won't ever have gone near LDAP.) */
960
961 if (addr->message != NULL)
962   {
963   addr->message = string_printing(addr->message);
964   if (((Ustrstr(addr->message, "failed to expand") != NULL) || (Ustrstr(addr->message, "expansion of ") != NULL)) &&
965       (Ustrstr(addr->message, "mysql") != NULL ||
966        Ustrstr(addr->message, "pgsql") != NULL ||
967 #ifdef EXPERIMENTAL_REDIS
968        Ustrstr(addr->message, "redis") != NULL ||
969 #endif
970        Ustrstr(addr->message, "sqlite") != NULL ||
971        Ustrstr(addr->message, "ldap:") != NULL ||
972        Ustrstr(addr->message, "ldapdn:") != NULL ||
973        Ustrstr(addr->message, "ldapm:") != NULL))
974     {
975       addr->message = string_sprintf("Temporary internal error");
976     }
977   }
978
979 /* If we used a transport that has one of the "return_output" options set, and
980 if it did in fact generate some output, then for return_output we treat the
981 message as failed if it was not already set that way, so that the output gets
982 returned to the sender, provided there is a sender to send it to. For
983 return_fail_output, do this only if the delivery failed. Otherwise we just
984 unlink the file, and remove the name so that if the delivery failed, we don't
985 try to send back an empty or unwanted file. The log_output options operate only
986 on a non-empty file.
987
988 In any case, we close the message file, because we cannot afford to leave a
989 file-descriptor for one address while processing (maybe very many) others. */
990
991 if (addr->return_file >= 0 && addr->return_filename != NULL)
992   {
993   BOOL return_output = FALSE;
994   struct stat statbuf;
995   (void)EXIMfsync(addr->return_file);
996
997   /* If there is no output, do nothing. */
998
999   if (fstat(addr->return_file, &statbuf) == 0 && statbuf.st_size > 0)
1000     {
1001     transport_instance *tb = addr->transport;
1002
1003     /* Handle logging options */
1004
1005     if (tb->log_output || (result == FAIL && tb->log_fail_output) ||
1006                           (result == DEFER && tb->log_defer_output))
1007       {
1008       uschar *s;
1009       FILE *f = Ufopen(addr->return_filename, "rb");
1010       if (f == NULL)
1011         log_write(0, LOG_MAIN|LOG_PANIC, "failed to open %s to log output "
1012           "from %s transport: %s", addr->return_filename, tb->name,
1013           strerror(errno));
1014       else
1015         {
1016         s = US Ufgets(big_buffer, big_buffer_size, f);
1017         if (s != NULL)
1018           {
1019           uschar *p = big_buffer + Ustrlen(big_buffer);
1020           while (p > big_buffer && isspace(p[-1])) p--;
1021           *p = 0;
1022           s = string_printing(big_buffer);
1023           log_write(0, LOG_MAIN, "<%s>: %s transport output: %s",
1024             addr->address, tb->name, s);
1025           }
1026         (void)fclose(f);
1027         }
1028       }
1029
1030     /* Handle returning options, but only if there is an address to return
1031     the text to. */
1032
1033     if (sender_address[0] != 0 || addr->p.errors_address != NULL)
1034       {
1035       if (tb->return_output)
1036         {
1037         addr->transport_return = result = FAIL;
1038         if (addr->basic_errno == 0 && addr->message == NULL)
1039           addr->message = US"return message generated";
1040         return_output = TRUE;
1041         }
1042       else
1043         if (tb->return_fail_output && result == FAIL) return_output = TRUE;
1044       }
1045     }
1046
1047   /* Get rid of the file unless it might be returned, but close it in
1048   all cases. */
1049
1050   if (!return_output)
1051     {
1052     Uunlink(addr->return_filename);
1053     addr->return_filename = NULL;
1054     addr->return_file = -1;
1055     }
1056
1057   (void)close(addr->return_file);
1058   }
1059
1060 /* The success case happens only after delivery by a transport. */
1061
1062 if (result == OK)
1063   {
1064   addr->next = addr_succeed;
1065   addr_succeed = addr;
1066
1067   /* Call address_done() to ensure that we don't deliver to this address again,
1068   and write appropriate things to the message log. If it is a child address, we
1069   call child_done() to scan the ancestors and mark them complete if this is the
1070   last child to complete. */
1071
1072   address_done(addr, now);
1073   DEBUG(D_deliver) debug_printf("%s delivered\n", addr->address);
1074
1075   if (addr->parent == NULL)
1076     deliver_msglog("%s %s: %s%s succeeded\n", now, addr->address,
1077       driver_name, driver_kind);
1078   else
1079     {
1080     deliver_msglog("%s %s <%s>: %s%s succeeded\n", now, addr->address,
1081       addr->parent->address, driver_name, driver_kind);
1082     child_done(addr, now);
1083     }
1084
1085   /* Certificates for logging (via TPDA) */
1086   #ifdef SUPPORT_TLS
1087   tls_out.ourcert = addr->ourcert;
1088   addr->ourcert = NULL;
1089   tls_out.peercert = addr->peercert;
1090   addr->peercert = NULL;
1091
1092   tls_out.cipher = addr->cipher;
1093   tls_out.peerdn = addr->peerdn;
1094   tls_out.ocsp = addr->ocsp;
1095   #endif
1096
1097   delivery_log(LOG_MAIN, addr, logchar, NULL);
1098
1099   #ifdef SUPPORT_TLS
1100   if (tls_out.ourcert)
1101     {
1102     tls_free_cert(tls_out.ourcert);
1103     tls_out.ourcert = NULL;
1104     }
1105   if (tls_out.peercert)
1106     {
1107     tls_free_cert(tls_out.peercert);
1108     tls_out.peercert = NULL;
1109     }
1110   tls_out.cipher = NULL;
1111   tls_out.peerdn = NULL;
1112   tls_out.ocsp = OCSP_NOT_REQ;
1113   #endif
1114   }
1115
1116
1117 /* Soft failure, or local delivery process failed; freezing may be
1118 requested. */
1119
1120 else if (result == DEFER || result == PANIC)
1121   {
1122   if (result == PANIC) logflags |= LOG_PANIC;
1123
1124   /* This puts them on the chain in reverse order. Do not change this, because
1125   the code for handling retries assumes that the one with the retry
1126   information is last. */
1127
1128   addr->next = addr_defer;
1129   addr_defer = addr;
1130
1131   /* The only currently implemented special action is to freeze the
1132   message. Logging of this is done later, just before the -H file is
1133   updated. */
1134
1135   if (addr->special_action == SPECIAL_FREEZE)
1136     {
1137     deliver_freeze = TRUE;
1138     deliver_frozen_at = time(NULL);
1139     update_spool = TRUE;
1140     }
1141
1142   /* If doing a 2-stage queue run, we skip writing to either the message
1143   log or the main log for SMTP defers. */
1144
1145   if (!queue_2stage || addr->basic_errno != 0)
1146     {
1147     uschar ss[32];
1148
1149     /* For errors of the type "retry time not reached" (also remotes skipped
1150     on queue run), logging is controlled by L_retry_defer. Note that this kind
1151     of error number is negative, and all the retry ones are less than any
1152     others. */
1153
1154     unsigned int use_log_selector = (addr->basic_errno <= ERRNO_RETRY_BASE)?
1155       L_retry_defer : 0;
1156
1157     /* Build up the line that is used for both the message log and the main
1158     log. */
1159
1160     s = reset_point = store_get(size);
1161
1162     /* Create the address string for logging. Must not do this earlier, because
1163     an OK result may be changed to FAIL when a pipe returns text. */
1164
1165     log_address = string_log_address(addr,
1166       (log_write_selector & L_all_parents) != 0, result == OK);
1167
1168     s = string_cat(s, &size, &ptr, log_address, Ustrlen(log_address));
1169
1170     /* Either driver_name contains something and driver_kind contains
1171     " router" or " transport" (note the leading space), or driver_name is
1172     a null string and driver_kind contains "routing" without the leading
1173     space, if all routing has been deferred. When a domain has been held,
1174     so nothing has been done at all, both variables contain null strings. */
1175
1176     if (driver_name == NULL)
1177       {
1178       if (driver_kind != NULL)
1179         s = string_append(s, &size, &ptr, 2, US" ", driver_kind);
1180       }
1181      else
1182       {
1183       if (driver_kind[1] == 't' && addr->router != NULL)
1184         s = string_append(s, &size, &ptr, 2, US" R=", addr->router->name);
1185       Ustrcpy(ss, " ?=");
1186       ss[1] = toupper(driver_kind[1]);
1187       s = string_append(s, &size, &ptr, 2, ss, driver_name);
1188       }
1189
1190     sprintf(CS ss, " defer (%d)", addr->basic_errno);
1191     s = string_cat(s, &size, &ptr, ss, Ustrlen(ss));
1192
1193     if (addr->basic_errno > 0)
1194       s = string_append(s, &size, &ptr, 2, US": ",
1195         US strerror(addr->basic_errno));
1196
1197     if (addr->message != NULL)
1198       s = string_append(s, &size, &ptr, 2, US": ", addr->message);
1199
1200     s[ptr] = 0;
1201
1202     /* Log the deferment in the message log, but don't clutter it
1203     up with retry-time defers after the first delivery attempt. */
1204
1205     if (deliver_firsttime || addr->basic_errno > ERRNO_RETRY_BASE)
1206       deliver_msglog("%s %s\n", now, s);
1207
1208     /* Write the main log and reset the store */
1209
1210     log_write(use_log_selector, logflags, "== %s", s);
1211     store_reset(reset_point);
1212     }
1213   }
1214
1215
1216 /* Hard failure. If there is an address to which an error message can be sent,
1217 put this address on the failed list. If not, put it on the deferred list and
1218 freeze the mail message for human attention. The latter action can also be
1219 explicitly requested by a router or transport. */
1220
1221 else
1222   {
1223   /* If this is a delivery error, or a message for which no replies are
1224   wanted, and the message's age is greater than ignore_bounce_errors_after,
1225   force the af_ignore_error flag. This will cause the address to be discarded
1226   later (with a log entry). */
1227
1228   if (sender_address[0] == 0 && message_age >= ignore_bounce_errors_after)
1229     setflag(addr, af_ignore_error);
1230
1231   /* Freeze the message if requested, or if this is a bounce message (or other
1232   message with null sender) and this address does not have its own errors
1233   address. However, don't freeze if errors are being ignored. The actual code
1234   to ignore occurs later, instead of sending a message. Logging of freezing
1235   occurs later, just before writing the -H file. */
1236
1237   if (!testflag(addr, af_ignore_error) &&
1238       (addr->special_action == SPECIAL_FREEZE ||
1239         (sender_address[0] == 0 && addr->p.errors_address == NULL)
1240       ))
1241     {
1242     frozen_info = (addr->special_action == SPECIAL_FREEZE)? US"" :
1243       (sender_local && !local_error_message)?
1244         US" (message created with -f <>)" : US" (delivery error message)";
1245     deliver_freeze = TRUE;
1246     deliver_frozen_at = time(NULL);
1247     update_spool = TRUE;
1248
1249     /* The address is put on the defer rather than the failed queue, because
1250     the message is being retained. */
1251
1252     addr->next = addr_defer;
1253     addr_defer = addr;
1254     }
1255
1256   /* Don't put the address on the nonrecipients tree yet; wait until an
1257   error message has been successfully sent. */
1258
1259   else
1260     {
1261     addr->next = addr_failed;
1262     addr_failed = addr;
1263     }
1264
1265   /* Build up the log line for the message and main logs */
1266
1267   s = reset_point = store_get(size);
1268
1269   /* Create the address string for logging. Must not do this earlier, because
1270   an OK result may be changed to FAIL when a pipe returns text. */
1271
1272   log_address = string_log_address(addr,
1273     (log_write_selector & L_all_parents) != 0, result == OK);
1274
1275   s = string_cat(s, &size, &ptr, log_address, Ustrlen(log_address));
1276
1277   if ((log_extra_selector & LX_sender_on_delivery) != 0)
1278     s = string_append(s, &size, &ptr, 3, US" F=<", sender_address, US">");
1279
1280   /* Return path may not be set if no delivery actually happened */
1281
1282   if (used_return_path != NULL &&
1283       (log_extra_selector & LX_return_path_on_delivery) != 0)
1284     s = string_append(s, &size, &ptr, 3, US" P=<", used_return_path, US">");
1285
1286   if (addr->router != NULL)
1287     s = string_append(s, &size, &ptr, 2, US" R=", addr->router->name);
1288   if (addr->transport != NULL)
1289     s = string_append(s, &size, &ptr, 2, US" T=", addr->transport->name);
1290
1291   if (addr->host_used != NULL)
1292     s = d_hostlog(s, &size, &ptr, addr);
1293
1294   #ifdef SUPPORT_TLS
1295   s = d_tlslog(s, &size, &ptr, addr);
1296   #endif
1297
1298   if (addr->basic_errno > 0)
1299     s = string_append(s, &size, &ptr, 2, US": ",
1300       US strerror(addr->basic_errno));
1301
1302   if (addr->message != NULL)
1303     s = string_append(s, &size, &ptr, 2, US": ", addr->message);
1304
1305   s[ptr] = 0;
1306
1307   /* Do the logging. For the message log, "routing failed" for those cases,
1308   just to make it clearer. */
1309
1310   if (driver_name == NULL)
1311     deliver_msglog("%s %s failed for %s\n", now, driver_kind, s);
1312   else
1313     deliver_msglog("%s %s\n", now, s);
1314
1315   log_write(0, LOG_MAIN, "** %s", s);
1316   store_reset(reset_point);
1317   }
1318
1319 /* Ensure logging is turned on again in all cases */
1320
1321 disable_logging = FALSE;
1322 }
1323
1324
1325
1326
1327 /*************************************************
1328 *            Address-independent error           *
1329 *************************************************/
1330
1331 /* This function is called when there's an error that is not dependent on a
1332 particular address, such as an expansion string failure. It puts the error into
1333 all the addresses in a batch, logs the incident on the main and panic logs, and
1334 clears the expansions. It is mostly called from local_deliver(), but can be
1335 called for a remote delivery via findugid().
1336
1337 Arguments:
1338   logit        TRUE if (MAIN+PANIC) logging required
1339   addr         the first of the chain of addresses
1340   code         the error code
1341   format       format string for error message, or NULL if already set in addr
1342   ...          arguments for the format
1343
1344 Returns:       nothing
1345 */
1346
1347 static void
1348 common_error(BOOL logit, address_item *addr, int code, uschar *format, ...)
1349 {
1350 address_item *addr2;
1351 addr->basic_errno = code;
1352
1353 if (format != NULL)
1354   {
1355   va_list ap;
1356   uschar buffer[512];
1357   va_start(ap, format);
1358   if (!string_vformat(buffer, sizeof(buffer), CS format, ap))
1359     log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1360       "common_error expansion was longer than " SIZE_T_FMT, sizeof(buffer));
1361   va_end(ap);
1362   addr->message = string_copy(buffer);
1363   }
1364
1365 for (addr2 = addr->next; addr2 != NULL; addr2 = addr2->next)
1366   {
1367   addr2->basic_errno = code;
1368   addr2->message = addr->message;
1369   }
1370
1371 if (logit) log_write(0, LOG_MAIN|LOG_PANIC, "%s", addr->message);
1372 deliver_set_expansions(NULL);
1373 }
1374
1375
1376
1377
1378 /*************************************************
1379 *         Check a "never users" list             *
1380 *************************************************/
1381
1382 /* This function is called to check whether a uid is on one of the two "never
1383 users" lists.
1384
1385 Arguments:
1386   uid         the uid to be checked
1387   nusers      the list to be scanned; the first item in the list is the count
1388
1389 Returns:      TRUE if the uid is on the list
1390 */
1391
1392 static BOOL
1393 check_never_users(uid_t uid, uid_t *nusers)
1394 {
1395 int i;
1396 if (nusers == NULL) return FALSE;
1397 for (i = 1; i <= (int)(nusers[0]); i++) if (nusers[i] == uid) return TRUE;
1398 return FALSE;
1399 }
1400
1401
1402
1403 /*************************************************
1404 *          Find uid and gid for a transport      *
1405 *************************************************/
1406
1407 /* This function is called for both local and remote deliveries, to find the
1408 uid/gid under which to run the delivery. The values are taken preferentially
1409 from the transport (either explicit or deliver_as_creator), then from the
1410 address (i.e. the router), and if nothing is set, the exim uid/gid are used. If
1411 the resulting uid is on the "never_users" or the "fixed_never_users" list, a
1412 panic error is logged, and the function fails (which normally leads to delivery
1413 deferral).
1414
1415 Arguments:
1416   addr         the address (possibly a chain)
1417   tp           the transport
1418   uidp         pointer to uid field
1419   gidp         pointer to gid field
1420   igfp         pointer to the use_initgroups field
1421
1422 Returns:       FALSE if failed - error has been set in address(es)
1423 */
1424
1425 static BOOL
1426 findugid(address_item *addr, transport_instance *tp, uid_t *uidp, gid_t *gidp,
1427   BOOL *igfp)
1428 {
1429 uschar *nuname = NULL;
1430 BOOL gid_set = FALSE;
1431
1432 /* Default initgroups flag comes from the transport */
1433
1434 *igfp = tp->initgroups;
1435
1436 /* First see if there's a gid on the transport, either fixed or expandable.
1437 The expanding function always logs failure itself. */
1438
1439 if (tp->gid_set)
1440   {
1441   *gidp = tp->gid;
1442   gid_set = TRUE;
1443   }
1444 else if (tp->expand_gid != NULL)
1445   {
1446   if (route_find_expanded_group(tp->expand_gid, tp->name, US"transport", gidp,
1447     &(addr->message))) gid_set = TRUE;
1448   else
1449     {
1450     common_error(FALSE, addr, ERRNO_GIDFAIL, NULL);
1451     return FALSE;
1452     }
1453   }
1454
1455 /* If the transport did not set a group, see if the router did. */
1456
1457 if (!gid_set && testflag(addr, af_gid_set))
1458   {
1459   *gidp = addr->gid;
1460   gid_set = TRUE;
1461   }
1462
1463 /* Pick up a uid from the transport if one is set. */
1464
1465 if (tp->uid_set) *uidp = tp->uid;
1466
1467 /* Otherwise, try for an expandable uid field. If it ends up as a numeric id,
1468 it does not provide a passwd value from which a gid can be taken. */
1469
1470 else if (tp->expand_uid != NULL)
1471   {
1472   struct passwd *pw;
1473   if (!route_find_expanded_user(tp->expand_uid, tp->name, US"transport", &pw,
1474        uidp, &(addr->message)))
1475     {
1476     common_error(FALSE, addr, ERRNO_UIDFAIL, NULL);
1477     return FALSE;
1478     }
1479   if (!gid_set && pw != NULL)
1480     {
1481     *gidp = pw->pw_gid;
1482     gid_set = TRUE;
1483     }
1484   }
1485
1486 /* If the transport doesn't set the uid, test the deliver_as_creator flag. */
1487
1488 else if (tp->deliver_as_creator)
1489   {
1490   *uidp = originator_uid;
1491   if (!gid_set)
1492     {
1493     *gidp = originator_gid;
1494     gid_set = TRUE;
1495     }
1496   }
1497
1498 /* Otherwise see if the address specifies the uid and if so, take it and its
1499 initgroups flag. */
1500
1501 else if (testflag(addr, af_uid_set))
1502   {
1503   *uidp = addr->uid;
1504   *igfp = testflag(addr, af_initgroups);
1505   }
1506
1507 /* Nothing has specified the uid - default to the Exim user, and group if the
1508 gid is not set. */
1509
1510 else
1511   {
1512   *uidp = exim_uid;
1513   if (!gid_set)
1514     {
1515     *gidp = exim_gid;
1516     gid_set = TRUE;
1517     }
1518   }
1519
1520 /* If no gid is set, it is a disaster. We default to the Exim gid only if
1521 defaulting to the Exim uid. In other words, if the configuration has specified
1522 a uid, it must also provide a gid. */
1523
1524 if (!gid_set)
1525   {
1526   common_error(TRUE, addr, ERRNO_GIDFAIL, US"User set without group for "
1527     "%s transport", tp->name);
1528   return FALSE;
1529   }
1530
1531 /* Check that the uid is not on the lists of banned uids that may not be used
1532 for delivery processes. */
1533
1534 if (check_never_users(*uidp, never_users))
1535   nuname = US"never_users";
1536 else if (check_never_users(*uidp, fixed_never_users))
1537   nuname = US"fixed_never_users";
1538
1539 if (nuname != NULL)
1540   {
1541   common_error(TRUE, addr, ERRNO_UIDFAIL, US"User %ld set for %s transport "
1542     "is on the %s list", (long int)(*uidp), tp->name, nuname);
1543   return FALSE;
1544   }
1545
1546 /* All is well */
1547
1548 return TRUE;
1549 }
1550
1551
1552
1553
1554 /*************************************************
1555 *   Check the size of a message for a transport  *
1556 *************************************************/
1557
1558 /* Checks that the message isn't too big for the selected transport.
1559 This is called only when it is known that the limit is set.
1560
1561 Arguments:
1562   tp          the transport
1563   addr        the (first) address being delivered
1564
1565 Returns:      OK
1566               DEFER   expansion failed or did not yield an integer
1567               FAIL    message too big
1568 */
1569
1570 int
1571 check_message_size(transport_instance *tp, address_item *addr)
1572 {
1573 int rc = OK;
1574 int size_limit;
1575
1576 deliver_set_expansions(addr);
1577 size_limit = expand_string_integer(tp->message_size_limit, TRUE);
1578 deliver_set_expansions(NULL);
1579
1580 if (expand_string_message != NULL)
1581   {
1582   rc = DEFER;
1583   if (size_limit == -1)
1584     addr->message = string_sprintf("failed to expand message_size_limit "
1585       "in %s transport: %s", tp->name, expand_string_message);
1586   else
1587     addr->message = string_sprintf("invalid message_size_limit "
1588       "in %s transport: %s", tp->name, expand_string_message);
1589   }
1590 else if (size_limit > 0 && message_size > size_limit)
1591   {
1592   rc = FAIL;
1593   addr->message =
1594     string_sprintf("message is too big (transport limit = %d)",
1595       size_limit);
1596   }
1597
1598 return rc;
1599 }
1600
1601
1602
1603 /*************************************************
1604 *  Transport-time check for a previous delivery  *
1605 *************************************************/
1606
1607 /* Check that this base address hasn't previously been delivered to its routed
1608 transport. If it has been delivered, mark it done. The check is necessary at
1609 delivery time in order to handle homonymic addresses correctly in cases where
1610 the pattern of redirection changes between delivery attempts (so the unique
1611 fields change). Non-homonymic previous delivery is detected earlier, at routing
1612 time (which saves unnecessary routing).
1613
1614 Arguments:
1615   addr      the address item
1616   testing   TRUE if testing wanted only, without side effects
1617
1618 Returns:    TRUE if previously delivered by the transport
1619 */
1620
1621 static BOOL
1622 previously_transported(address_item *addr, BOOL testing)
1623 {
1624 (void)string_format(big_buffer, big_buffer_size, "%s/%s",
1625   addr->unique + (testflag(addr, af_homonym)? 3:0), addr->transport->name);
1626
1627 if (tree_search(tree_nonrecipients, big_buffer) != 0)
1628   {
1629   DEBUG(D_deliver|D_route|D_transport)
1630     debug_printf("%s was previously delivered (%s transport): discarded\n",
1631     addr->address, addr->transport->name);
1632   if (!testing) child_done(addr, tod_stamp(tod_log));
1633   return TRUE;
1634   }
1635
1636 return FALSE;
1637 }
1638
1639
1640
1641 /******************************************************
1642 *      Check for a given header in a header string    *
1643 ******************************************************/
1644
1645 /* This function is used when generating quota warnings. The configuration may
1646 specify any header lines it likes in quota_warn_message. If certain of them are
1647 missing, defaults are inserted, so we need to be able to test for the presence
1648 of a given header.
1649
1650 Arguments:
1651   hdr         the required header name
1652   hstring     the header string
1653
1654 Returns:      TRUE  the header is in the string
1655               FALSE the header is not in the string
1656 */
1657
1658 static BOOL
1659 contains_header(uschar *hdr, uschar *hstring)
1660 {
1661 int len = Ustrlen(hdr);
1662 uschar *p = hstring;
1663 while (*p != 0)
1664   {
1665   if (strncmpic(p, hdr, len) == 0)
1666     {
1667     p += len;
1668     while (*p == ' ' || *p == '\t') p++;
1669     if (*p == ':') return TRUE;
1670     }
1671   while (*p != 0 && *p != '\n') p++;
1672   if (*p == '\n') p++;
1673   }
1674 return FALSE;
1675 }
1676
1677
1678
1679
1680 /*************************************************
1681 *           Perform a local delivery             *
1682 *************************************************/
1683
1684 /* Each local delivery is performed in a separate process which sets its
1685 uid and gid as specified. This is a safer way than simply changing and
1686 restoring using seteuid(); there is a body of opinion that seteuid() cannot be
1687 used safely. From release 4, Exim no longer makes any use of it. Besides, not
1688 all systems have seteuid().
1689
1690 If the uid/gid are specified in the transport_instance, they are used; the
1691 transport initialization must ensure that either both or neither are set.
1692 Otherwise, the values associated with the address are used. If neither are set,
1693 it is a configuration error.
1694
1695 The transport or the address may specify a home directory (transport over-
1696 rides), and if they do, this is set as $home. If neither have set a working
1697 directory, this value is used for that as well. Otherwise $home is left unset
1698 and the cwd is set to "/" - a directory that should be accessible to all users.
1699
1700 Using a separate process makes it more complicated to get error information
1701 back. We use a pipe to pass the return code and also an error code and error
1702 text string back to the parent process.
1703
1704 Arguments:
1705   addr       points to an address block for this delivery; for "normal" local
1706              deliveries this is the only address to be delivered, but for
1707              pseudo-remote deliveries (e.g. by batch SMTP to a file or pipe)
1708              a number of addresses can be handled simultaneously, and in this
1709              case addr will point to a chain of addresses with the same
1710              characteristics.
1711
1712   shadowing  TRUE if running a shadow transport; this causes output from pipes
1713              to be ignored.
1714
1715 Returns:     nothing
1716 */
1717
1718 static void
1719 deliver_local(address_item *addr, BOOL shadowing)
1720 {
1721 BOOL use_initgroups;
1722 uid_t uid;
1723 gid_t gid;
1724 int status, len, rc;
1725 int pfd[2];
1726 pid_t pid;
1727 uschar *working_directory;
1728 address_item *addr2;
1729 transport_instance *tp = addr->transport;
1730
1731 /* Set up the return path from the errors or sender address. If the transport
1732 has its own return path setting, expand it and replace the existing value. */
1733
1734 if(addr->p.errors_address != NULL)
1735   return_path = addr->p.errors_address;
1736 #ifdef EXPERIMENTAL_SRS
1737 else if(addr->p.srs_sender != NULL)
1738   return_path = addr->p.srs_sender;
1739 #endif
1740 else
1741   return_path = sender_address;
1742
1743 if (tp->return_path != NULL)
1744   {
1745   uschar *new_return_path = expand_string(tp->return_path);
1746   if (new_return_path == NULL)
1747     {
1748     if (!expand_string_forcedfail)
1749       {
1750       common_error(TRUE, addr, ERRNO_EXPANDFAIL,
1751         US"Failed to expand return path \"%s\" in %s transport: %s",
1752         tp->return_path, tp->name, expand_string_message);
1753       return;
1754       }
1755     }
1756   else return_path = new_return_path;
1757   }
1758
1759 /* For local deliveries, one at a time, the value used for logging can just be
1760 set directly, once and for all. */
1761
1762 used_return_path = return_path;
1763
1764 /* Sort out the uid, gid, and initgroups flag. If an error occurs, the message
1765 gets put into the address(es), and the expansions are unset, so we can just
1766 return. */
1767
1768 if (!findugid(addr, tp, &uid, &gid, &use_initgroups)) return;
1769
1770 /* See if either the transport or the address specifies a home directory. A
1771 home directory set in the address may already be expanded; a flag is set to
1772 indicate that. In other cases we must expand it. */
1773
1774 if ((deliver_home = tp->home_dir) != NULL ||       /* Set in transport, or */
1775      ((deliver_home = addr->home_dir) != NULL &&   /* Set in address and */
1776        !testflag(addr, af_home_expanded)))         /*   not expanded */
1777   {
1778   uschar *rawhome = deliver_home;
1779   deliver_home = NULL;                      /* in case it contains $home */
1780   deliver_home = expand_string(rawhome);
1781   if (deliver_home == NULL)
1782     {
1783     common_error(TRUE, addr, ERRNO_EXPANDFAIL, US"home directory \"%s\" failed "
1784       "to expand for %s transport: %s", rawhome, tp->name,
1785       expand_string_message);
1786     return;
1787     }
1788   if (*deliver_home != '/')
1789     {
1790     common_error(TRUE, addr, ERRNO_NOTABSOLUTE, US"home directory path \"%s\" "
1791       "is not absolute for %s transport", deliver_home, tp->name);
1792     return;
1793     }
1794   }
1795
1796 /* See if either the transport or the address specifies a current directory,
1797 and if so, expand it. If nothing is set, use the home directory, unless it is
1798 also unset in which case use "/", which is assumed to be a directory to which
1799 all users have access. It is necessary to be in a visible directory for some
1800 operating systems when running pipes, as some commands (e.g. "rm" under Solaris
1801 2.5) require this. */
1802
1803 working_directory = (tp->current_dir != NULL)?
1804   tp->current_dir : addr->current_dir;
1805
1806 if (working_directory != NULL)
1807   {
1808   uschar *raw = working_directory;
1809   working_directory = expand_string(raw);
1810   if (working_directory == NULL)
1811     {
1812     common_error(TRUE, addr, ERRNO_EXPANDFAIL, US"current directory \"%s\" "
1813       "failed to expand for %s transport: %s", raw, tp->name,
1814       expand_string_message);
1815     return;
1816     }
1817   if (*working_directory != '/')
1818     {
1819     common_error(TRUE, addr, ERRNO_NOTABSOLUTE, US"current directory path "
1820       "\"%s\" is not absolute for %s transport", working_directory, tp->name);
1821     return;
1822     }
1823   }
1824 else working_directory = (deliver_home == NULL)? US"/" : deliver_home;
1825
1826 /* If one of the return_output flags is set on the transport, create and open a
1827 file in the message log directory for the transport to write its output onto.
1828 This is mainly used by pipe transports. The file needs to be unique to the
1829 address. This feature is not available for shadow transports. */
1830
1831 if (!shadowing && (tp->return_output || tp->return_fail_output ||
1832     tp->log_output || tp->log_fail_output))
1833   {
1834   uschar *error;
1835   addr->return_filename =
1836     string_sprintf("%s/msglog/%s/%s-%d-%d", spool_directory, message_subdir,
1837       message_id, getpid(), return_count++);
1838   addr->return_file = open_msglog_file(addr->return_filename, 0400, &error);
1839   if (addr->return_file < 0)
1840     {
1841     common_error(TRUE, addr, errno, US"Unable to %s file for %s transport "
1842       "to return message: %s", error, tp->name, strerror(errno));
1843     return;
1844     }
1845   }
1846
1847 /* Create the pipe for inter-process communication. */
1848
1849 if (pipe(pfd) != 0)
1850   {
1851   common_error(TRUE, addr, ERRNO_PIPEFAIL, US"Creation of pipe failed: %s",
1852     strerror(errno));
1853   return;
1854   }
1855
1856 /* Now fork the process to do the real work in the subprocess, but first
1857 ensure that all cached resources are freed so that the subprocess starts with
1858 a clean slate and doesn't interfere with the parent process. */
1859
1860 search_tidyup();
1861
1862 if ((pid = fork()) == 0)
1863   {
1864   BOOL replicate = TRUE;
1865
1866   /* Prevent core dumps, as we don't want them in users' home directories.
1867   HP-UX doesn't have RLIMIT_CORE; I don't know how to do this in that
1868   system. Some experimental/developing systems (e.g. GNU/Hurd) may define
1869   RLIMIT_CORE but not support it in setrlimit(). For such systems, do not
1870   complain if the error is "not supported".
1871
1872   There are two scenarios where changing the max limit has an effect.  In one,
1873   the user is using a .forward and invoking a command of their choice via pipe;
1874   for these, we do need the max limit to be 0 unless the admin chooses to
1875   permit an increased limit.  In the other, the command is invoked directly by
1876   the transport and is under administrator control, thus being able to raise
1877   the limit aids in debugging.  So there's no general always-right answer.
1878
1879   Thus we inhibit core-dumps completely but let individual transports, while
1880   still root, re-raise the limits back up to aid debugging.  We make the
1881   default be no core-dumps -- few enough people can use core dumps in
1882   diagnosis that it's reasonable to make them something that has to be explicitly requested.
1883   */
1884
1885   #ifdef RLIMIT_CORE
1886   struct rlimit rl;
1887   rl.rlim_cur = 0;
1888   rl.rlim_max = 0;
1889   if (setrlimit(RLIMIT_CORE, &rl) < 0)
1890     {
1891     #ifdef SETRLIMIT_NOT_SUPPORTED
1892     if (errno != ENOSYS && errno != ENOTSUP)
1893     #endif
1894       log_write(0, LOG_MAIN|LOG_PANIC, "setrlimit(RLIMIT_CORE) failed: %s",
1895         strerror(errno));
1896     }
1897   #endif
1898
1899   /* Reset the random number generator, so different processes don't all
1900   have the same sequence. */
1901
1902   random_seed = 0;
1903
1904   /* If the transport has a setup entry, call this first, while still
1905   privileged. (Appendfile uses this to expand quota, for example, while
1906   able to read private files.) */
1907
1908   if (addr->transport->setup != NULL)
1909     {
1910     switch((addr->transport->setup)(addr->transport, addr, NULL, uid, gid,
1911            &(addr->message)))
1912       {
1913       case DEFER:
1914       addr->transport_return = DEFER;
1915       goto PASS_BACK;
1916
1917       case FAIL:
1918       addr->transport_return = PANIC;
1919       goto PASS_BACK;
1920       }
1921     }
1922
1923   /* Ignore SIGINT and SIGTERM during delivery. Also ignore SIGUSR1, as
1924   when the process becomes unprivileged, it won't be able to write to the
1925   process log. SIGHUP is ignored throughout exim, except when it is being
1926   run as a daemon. */
1927
1928   signal(SIGINT, SIG_IGN);
1929   signal(SIGTERM, SIG_IGN);
1930   signal(SIGUSR1, SIG_IGN);
1931
1932   /* Close the unwanted half of the pipe, and set close-on-exec for the other
1933   half - for transports that exec things (e.g. pipe). Then set the required
1934   gid/uid. */
1935
1936   (void)close(pfd[pipe_read]);
1937   (void)fcntl(pfd[pipe_write], F_SETFD, fcntl(pfd[pipe_write], F_GETFD) |
1938     FD_CLOEXEC);
1939   exim_setugid(uid, gid, use_initgroups,
1940     string_sprintf("local delivery to %s <%s> transport=%s", addr->local_part,
1941       addr->address, addr->transport->name));
1942
1943   DEBUG(D_deliver)
1944     {
1945     address_item *batched;
1946     debug_printf("  home=%s current=%s\n", deliver_home, working_directory);
1947     for (batched = addr->next; batched != NULL; batched = batched->next)
1948       debug_printf("additional batched address: %s\n", batched->address);
1949     }
1950
1951   /* Set an appropriate working directory. */
1952
1953   if (Uchdir(working_directory) < 0)
1954     {
1955     addr->transport_return = DEFER;
1956     addr->basic_errno = errno;
1957     addr->message = string_sprintf("failed to chdir to %s", working_directory);
1958     }
1959
1960   /* If successful, call the transport */
1961
1962   else
1963     {
1964     BOOL ok = TRUE;
1965     set_process_info("delivering %s to %s using %s", message_id,
1966      addr->local_part, addr->transport->name);
1967
1968     /* Setting this global in the subprocess means we need never clear it */
1969     transport_name = addr->transport->name;
1970
1971     /* If a transport filter has been specified, set up its argument list.
1972     Any errors will get put into the address, and FALSE yielded. */
1973
1974     if (addr->transport->filter_command != NULL)
1975       {
1976       ok = transport_set_up_command(&transport_filter_argv,
1977         addr->transport->filter_command,
1978         TRUE, PANIC, addr, US"transport filter", NULL);
1979       transport_filter_timeout = addr->transport->filter_timeout;
1980       }
1981     else transport_filter_argv = NULL;
1982
1983     if (ok)
1984       {
1985       debug_print_string(addr->transport->debug_string);
1986       replicate = !(addr->transport->info->code)(addr->transport, addr);
1987       }
1988     }
1989
1990   /* Pass the results back down the pipe. If necessary, first replicate the
1991   status in the top address to the others in the batch. The label is the
1992   subject of a goto when a call to the transport's setup function fails. We
1993   pass the pointer to the transport back in case it got changed as a result of
1994   file_format in appendfile. */
1995
1996   PASS_BACK:
1997
1998   if (replicate) replicate_status(addr);
1999   for (addr2 = addr; addr2 != NULL; addr2 = addr2->next)
2000     {
2001     int i;
2002     int local_part_length = Ustrlen(addr2->local_part);
2003     uschar *s;
2004     int ret;
2005
2006     if(  (ret = write(pfd[pipe_write], (void *)&(addr2->transport_return), sizeof(int))) != sizeof(int)
2007       || (ret = write(pfd[pipe_write], (void *)&transport_count, sizeof(transport_count))) != sizeof(transport_count)
2008       || (ret = write(pfd[pipe_write], (void *)&(addr2->flags), sizeof(addr2->flags))) != sizeof(addr2->flags)
2009       || (ret = write(pfd[pipe_write], (void *)&(addr2->basic_errno), sizeof(int))) != sizeof(int)
2010       || (ret = write(pfd[pipe_write], (void *)&(addr2->more_errno), sizeof(int))) != sizeof(int)
2011       || (ret = write(pfd[pipe_write], (void *)&(addr2->special_action), sizeof(int))) != sizeof(int)
2012       || (ret = write(pfd[pipe_write], (void *)&(addr2->transport),
2013         sizeof(transport_instance *))) != sizeof(transport_instance *)
2014
2015     /* For a file delivery, pass back the local part, in case the original
2016     was only part of the final delivery path. This gives more complete
2017     logging. */
2018
2019       || (testflag(addr2, af_file)
2020           && (  (ret = write(pfd[pipe_write], (void *)&local_part_length, sizeof(int))) != sizeof(int)
2021              || (ret = write(pfd[pipe_write], addr2->local_part, local_part_length)) != local_part_length
2022              )
2023          )
2024       )
2025       log_write(0, LOG_MAIN|LOG_PANIC, "Failed writing transport results to pipe: %s\n",
2026         ret == -1 ? strerror(errno) : "short write");
2027
2028     /* Now any messages */
2029
2030     for (i = 0, s = addr2->message; i < 2; i++, s = addr2->user_message)
2031       {
2032       int message_length = (s == NULL)? 0 : Ustrlen(s) + 1;
2033       if(  (ret = write(pfd[pipe_write], (void *)&message_length, sizeof(int))) != sizeof(int)
2034         || (message_length > 0  && (ret = write(pfd[pipe_write], s, message_length)) != message_length)
2035         )
2036         log_write(0, LOG_MAIN|LOG_PANIC, "Failed writing transport results to pipe: %s\n",
2037           ret == -1 ? strerror(errno) : "short write");
2038       }
2039     }
2040
2041   /* OK, this process is now done. Free any cached resources that it opened,
2042   and close the pipe we were writing down before exiting. */
2043
2044   (void)close(pfd[pipe_write]);
2045   search_tidyup();
2046   exit(EXIT_SUCCESS);
2047   }
2048
2049 /* Back in the main process: panic if the fork did not succeed. This seems
2050 better than returning an error - if forking is failing it is probably best
2051 not to try other deliveries for this message. */
2052
2053 if (pid < 0)
2054   log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Fork failed for local delivery to %s",
2055     addr->address);
2056
2057 /* Read the pipe to get the delivery status codes and error messages. Our copy
2058 of the writing end must be closed first, as otherwise read() won't return zero
2059 on an empty pipe. We check that a status exists for each address before
2060 overwriting the address structure. If data is missing, the default DEFER status
2061 will remain. Afterwards, close the reading end. */
2062
2063 (void)close(pfd[pipe_write]);
2064
2065 for (addr2 = addr; addr2 != NULL; addr2 = addr2->next)
2066   {
2067   len = read(pfd[pipe_read], (void *)&status, sizeof(int));
2068   if (len > 0)
2069     {
2070     int i;
2071     uschar **sptr;
2072
2073     addr2->transport_return = status;
2074     len = read(pfd[pipe_read], (void *)&transport_count,
2075       sizeof(transport_count));
2076     len = read(pfd[pipe_read], (void *)&(addr2->flags), sizeof(addr2->flags));
2077     len = read(pfd[pipe_read], (void *)&(addr2->basic_errno), sizeof(int));
2078     len = read(pfd[pipe_read], (void *)&(addr2->more_errno), sizeof(int));
2079     len = read(pfd[pipe_read], (void *)&(addr2->special_action), sizeof(int));
2080     len = read(pfd[pipe_read], (void *)&(addr2->transport),
2081       sizeof(transport_instance *));
2082
2083     if (testflag(addr2, af_file))
2084       {
2085       int local_part_length;
2086       len = read(pfd[pipe_read], (void *)&local_part_length, sizeof(int));
2087       len = read(pfd[pipe_read], (void *)big_buffer, local_part_length);
2088       big_buffer[local_part_length] = 0;
2089       addr2->local_part = string_copy(big_buffer);
2090       }
2091
2092     for (i = 0, sptr = &(addr2->message); i < 2;
2093          i++, sptr = &(addr2->user_message))
2094       {
2095       int message_length;
2096       len = read(pfd[pipe_read], (void *)&message_length, sizeof(int));
2097       if (message_length > 0)
2098         {
2099         len = read(pfd[pipe_read], (void *)big_buffer, message_length);
2100         if (len > 0) *sptr = string_copy(big_buffer);
2101         }
2102       }
2103     }
2104
2105   else
2106     {
2107     log_write(0, LOG_MAIN|LOG_PANIC, "failed to read delivery status for %s "
2108       "from delivery subprocess", addr2->unique);
2109     break;
2110     }
2111   }
2112
2113 (void)close(pfd[pipe_read]);
2114
2115 /* Unless shadowing, write all successful addresses immediately to the journal
2116 file, to ensure they are recorded asap. For homonymic addresses, use the base
2117 address plus the transport name. Failure to write the journal is panic-worthy,
2118 but don't stop, as it may prove possible subsequently to update the spool file
2119 in order to record the delivery. */
2120
2121 if (!shadowing)
2122   {
2123   for (addr2 = addr; addr2 != NULL; addr2 = addr2->next)
2124     {
2125     if (addr2->transport_return != OK) continue;
2126
2127     if (testflag(addr2, af_homonym))
2128       sprintf(CS big_buffer, "%.500s/%s\n", addr2->unique + 3, tp->name);
2129     else
2130       sprintf(CS big_buffer, "%.500s\n", addr2->unique);
2131
2132     /* In the test harness, wait just a bit to let the subprocess finish off
2133     any debug output etc first. */
2134
2135     if (running_in_test_harness) millisleep(300);
2136
2137     DEBUG(D_deliver) debug_printf("journalling %s", big_buffer);
2138     len = Ustrlen(big_buffer);
2139     if (write(journal_fd, big_buffer, len) != len)
2140       log_write(0, LOG_MAIN|LOG_PANIC, "failed to update journal for %s: %s",
2141         big_buffer, strerror(errno));
2142     }
2143
2144   /* Ensure the journal file is pushed out to disk. */
2145
2146   if (EXIMfsync(journal_fd) < 0)
2147     log_write(0, LOG_MAIN|LOG_PANIC, "failed to fsync journal: %s",
2148       strerror(errno));
2149   }
2150
2151 /* Wait for the process to finish. If it terminates with a non-zero code,
2152 freeze the message (except for SIGTERM, SIGKILL and SIGQUIT), but leave the
2153 status values of all the addresses as they are. Take care to handle the case
2154 when the subprocess doesn't seem to exist. This has been seen on one system
2155 when Exim was called from an MUA that set SIGCHLD to SIG_IGN. When that
2156 happens, wait() doesn't recognize the termination of child processes. Exim now
2157 resets SIGCHLD to SIG_DFL, but this code should still be robust. */
2158
2159 while ((rc = wait(&status)) != pid)
2160   {
2161   if (rc < 0 && errno == ECHILD)      /* Process has vanished */
2162     {
2163     log_write(0, LOG_MAIN, "%s transport process vanished unexpectedly",
2164       addr->transport->driver_name);
2165     status = 0;
2166     break;
2167     }
2168   }
2169
2170 if ((status & 0xffff) != 0)
2171   {
2172   int msb = (status >> 8) & 255;
2173   int lsb = status & 255;
2174   int code = (msb == 0)? (lsb & 0x7f) : msb;
2175   if (msb != 0 || (code != SIGTERM && code != SIGKILL && code != SIGQUIT))
2176     addr->special_action = SPECIAL_FREEZE;
2177   log_write(0, LOG_MAIN|LOG_PANIC, "%s transport process returned non-zero "
2178     "status 0x%04x: %s %d",
2179     addr->transport->driver_name,
2180     status,
2181     (msb == 0)? "terminated by signal" : "exit code",
2182     code);
2183   }
2184
2185 /* If SPECIAL_WARN is set in the top address, send a warning message. */
2186
2187 if (addr->special_action == SPECIAL_WARN &&
2188     addr->transport->warn_message != NULL)
2189   {
2190   int fd;
2191   uschar *warn_message;
2192
2193   DEBUG(D_deliver) debug_printf("Warning message requested by transport\n");
2194
2195   warn_message = expand_string(addr->transport->warn_message);
2196   if (warn_message == NULL)
2197     log_write(0, LOG_MAIN|LOG_PANIC, "Failed to expand \"%s\" (warning "
2198       "message for %s transport): %s", addr->transport->warn_message,
2199       addr->transport->name, expand_string_message);
2200   else
2201     {
2202     pid_t pid = child_open_exim(&fd);
2203     if (pid > 0)
2204       {
2205       FILE *f = fdopen(fd, "wb");
2206       if (errors_reply_to != NULL &&
2207           !contains_header(US"Reply-To", warn_message))
2208         fprintf(f, "Reply-To: %s\n", errors_reply_to);
2209       fprintf(f, "Auto-Submitted: auto-replied\n");
2210       if (!contains_header(US"From", warn_message)) moan_write_from(f);
2211       fprintf(f, "%s", CS warn_message);
2212
2213       /* Close and wait for child process to complete, without a timeout. */
2214
2215       (void)fclose(f);
2216       (void)child_close(pid, 0);
2217       }
2218     }
2219
2220   addr->special_action = SPECIAL_NONE;
2221   }
2222 }
2223
2224
2225
2226 /*************************************************
2227 *              Do local deliveries               *
2228 *************************************************/
2229
2230 /* This function processes the list of addresses in addr_local. True local
2231 deliveries are always done one address at a time. However, local deliveries can
2232 be batched up in some cases. Typically this is when writing batched SMTP output
2233 files for use by some external transport mechanism, or when running local
2234 deliveries over LMTP.
2235
2236 Arguments:   None
2237 Returns:     Nothing
2238 */
2239
2240 static void
2241 do_local_deliveries(void)
2242 {
2243 open_db dbblock;
2244 open_db *dbm_file = NULL;
2245 time_t now = time(NULL);
2246
2247 /* Loop until we have exhausted the supply of local deliveries */
2248
2249 while (addr_local != NULL)
2250   {
2251   time_t delivery_start;
2252   int deliver_time;
2253   address_item *addr2, *addr3, *nextaddr;
2254   int logflags = LOG_MAIN;
2255   int logchar = dont_deliver? '*' : '=';
2256   transport_instance *tp;
2257
2258   /* Pick the first undelivered address off the chain */
2259
2260   address_item *addr = addr_local;
2261   addr_local = addr->next;
2262   addr->next = NULL;
2263
2264   DEBUG(D_deliver|D_transport)
2265     debug_printf("--------> %s <--------\n", addr->address);
2266
2267   /* An internal disaster if there is no transport. Should not occur! */
2268
2269   if ((tp = addr->transport) == NULL)
2270     {
2271     logflags |= LOG_PANIC;
2272     disable_logging = FALSE;  /* Jic */
2273     addr->message =
2274       (addr->router != NULL)?
2275         string_sprintf("No transport set by %s router", addr->router->name)
2276         :
2277         string_sprintf("No transport set by system filter");
2278     post_process_one(addr, DEFER, logflags, DTYPE_TRANSPORT, 0);
2279     continue;
2280     }
2281
2282   /* Check that this base address hasn't previously been delivered to this
2283   transport. The check is necessary at this point to handle homonymic addresses
2284   correctly in cases where the pattern of redirection changes between delivery
2285   attempts. Non-homonymic previous delivery is detected earlier, at routing
2286   time. */
2287
2288   if (previously_transported(addr, FALSE)) continue;
2289
2290   /* There are weird cases where logging is disabled */
2291
2292   disable_logging = tp->disable_logging;
2293
2294   /* Check for batched addresses and possible amalgamation. Skip all the work
2295   if either batch_max <= 1 or there aren't any other addresses for local
2296   delivery. */
2297
2298   if (tp->batch_max > 1 && addr_local != NULL)
2299     {
2300     int batch_count = 1;
2301     BOOL uses_dom = readconf_depends((driver_instance *)tp, US"domain");
2302     BOOL uses_lp = (testflag(addr, af_pfr) &&
2303       (testflag(addr, af_file) || addr->local_part[0] == '|')) ||
2304       readconf_depends((driver_instance *)tp, US"local_part");
2305     uschar *batch_id = NULL;
2306     address_item **anchor = &addr_local;
2307     address_item *last = addr;
2308     address_item *next;
2309
2310     /* Expand the batch_id string for comparison with other addresses.
2311     Expansion failure suppresses batching. */
2312
2313     if (tp->batch_id != NULL)
2314       {
2315       deliver_set_expansions(addr);
2316       batch_id = expand_string(tp->batch_id);
2317       deliver_set_expansions(NULL);
2318       if (batch_id == NULL)
2319         {
2320         log_write(0, LOG_MAIN|LOG_PANIC, "Failed to expand batch_id option "
2321           "in %s transport (%s): %s", tp->name, addr->address,
2322           expand_string_message);
2323         batch_count = tp->batch_max;
2324         }
2325       }
2326
2327     /* Until we reach the batch_max limit, pick off addresses which have the
2328     same characteristics. These are:
2329
2330       same transport
2331       not previously delivered (see comment about 50 lines above)
2332       same local part if the transport's configuration contains $local_part
2333         or if this is a file or pipe delivery from a redirection
2334       same domain if the transport's configuration contains $domain
2335       same errors address
2336       same additional headers
2337       same headers to be removed
2338       same uid/gid for running the transport
2339       same first host if a host list is set
2340     */
2341
2342     while ((next = *anchor) != NULL && batch_count < tp->batch_max)
2343       {
2344       BOOL ok =
2345         tp == next->transport &&
2346         !previously_transported(next, TRUE) &&
2347         (addr->flags & (af_pfr|af_file)) == (next->flags & (af_pfr|af_file)) &&
2348         (!uses_lp  || Ustrcmp(next->local_part, addr->local_part) == 0) &&
2349         (!uses_dom || Ustrcmp(next->domain, addr->domain) == 0) &&
2350         same_strings(next->p.errors_address, addr->p.errors_address) &&
2351         same_headers(next->p.extra_headers, addr->p.extra_headers) &&
2352         same_strings(next->p.remove_headers, addr->p.remove_headers) &&
2353         same_ugid(tp, addr, next) &&
2354         ((addr->host_list == NULL && next->host_list == NULL) ||
2355          (addr->host_list != NULL && next->host_list != NULL &&
2356           Ustrcmp(addr->host_list->name, next->host_list->name) == 0));
2357
2358       /* If the transport has a batch_id setting, batch_id will be non-NULL
2359       from the expansion outside the loop. Expand for this address and compare.
2360       Expansion failure makes this address ineligible for batching. */
2361
2362       if (ok && batch_id != NULL)
2363         {
2364         uschar *bid;
2365         address_item *save_nextnext = next->next;
2366         next->next = NULL;            /* Expansion for a single address */
2367         deliver_set_expansions(next);
2368         next->next = save_nextnext;
2369         bid = expand_string(tp->batch_id);
2370         deliver_set_expansions(NULL);
2371         if (bid == NULL)
2372           {
2373           log_write(0, LOG_MAIN|LOG_PANIC, "Failed to expand batch_id option "
2374             "in %s transport (%s): %s", tp->name, next->address,
2375             expand_string_message);
2376           ok = FALSE;
2377           }
2378         else ok = (Ustrcmp(batch_id, bid) == 0);
2379         }
2380
2381       /* Take address into batch if OK. */
2382
2383       if (ok)
2384         {
2385         *anchor = next->next;           /* Include the address */
2386         next->next = NULL;
2387         last->next = next;
2388         last = next;
2389         batch_count++;
2390         }
2391       else anchor = &(next->next);      /* Skip the address */
2392       }
2393     }
2394
2395   /* We now have one or more addresses that can be delivered in a batch. Check
2396   whether the transport is prepared to accept a message of this size. If not,
2397   fail them all forthwith. If the expansion fails, or does not yield an
2398   integer, defer delivery. */
2399
2400   if (tp->message_size_limit != NULL)
2401     {
2402     int rc = check_message_size(tp, addr);
2403     if (rc != OK)
2404       {
2405       replicate_status(addr);
2406       while (addr != NULL)
2407         {
2408         addr2 = addr->next;
2409         post_process_one(addr, rc, logflags, DTYPE_TRANSPORT, 0);
2410         addr = addr2;
2411         }
2412       continue;    /* With next batch of addresses */
2413       }
2414     }
2415
2416   /* If we are not running the queue, or if forcing, all deliveries will be
2417   attempted. Otherwise, we must respect the retry times for each address. Even
2418   when not doing this, we need to set up the retry key string, and determine
2419   whether a retry record exists, because after a successful delivery, a delete
2420   retry item must be set up. Keep the retry database open only for the duration
2421   of these checks, rather than for all local deliveries, because some local
2422   deliveries (e.g. to pipes) can take a substantial time. */
2423
2424   dbm_file = dbfn_open(US"retry", O_RDONLY, &dbblock, FALSE);
2425   if (dbm_file == NULL)
2426     {
2427     DEBUG(D_deliver|D_retry|D_hints_lookup)
2428       debug_printf("no retry data available\n");
2429     }
2430
2431   addr2 = addr;
2432   addr3 = NULL;
2433   while (addr2 != NULL)
2434     {
2435     BOOL ok = TRUE;   /* to deliver this address */
2436     uschar *retry_key;
2437
2438     /* Set up the retry key to include the domain or not, and change its
2439     leading character from "R" to "T". Must make a copy before doing this,
2440     because the old key may be pointed to from a "delete" retry item after
2441     a routing delay. */
2442
2443     retry_key = string_copy(
2444       (tp->retry_use_local_part)? addr2->address_retry_key :
2445         addr2->domain_retry_key);
2446     *retry_key = 'T';
2447
2448     /* Inspect the retry data. If there is no hints file, delivery happens. */
2449
2450     if (dbm_file != NULL)
2451       {
2452       dbdata_retry *retry_record = dbfn_read(dbm_file, retry_key);
2453
2454       /* If there is no retry record, delivery happens. If there is,
2455       remember it exists so it can be deleted after a successful delivery. */
2456
2457       if (retry_record != NULL)
2458         {
2459         setflag(addr2, af_lt_retry_exists);
2460
2461         /* A retry record exists for this address. If queue running and not
2462         forcing, inspect its contents. If the record is too old, or if its
2463         retry time has come, or if it has passed its cutoff time, delivery
2464         will go ahead. */
2465
2466         DEBUG(D_retry)
2467           {
2468           debug_printf("retry record exists: age=%s ",
2469             readconf_printtime(now - retry_record->time_stamp));
2470           debug_printf("(max %s)\n", readconf_printtime(retry_data_expire));
2471           debug_printf("  time to retry = %s expired = %d\n",
2472             readconf_printtime(retry_record->next_try - now),
2473             retry_record->expired);
2474           }
2475
2476         if (queue_running && !deliver_force)
2477           {
2478           ok = (now - retry_record->time_stamp > retry_data_expire) ||
2479                (now >= retry_record->next_try) ||
2480                retry_record->expired;
2481
2482           /* If we haven't reached the retry time, there is one more check
2483           to do, which is for the ultimate address timeout. */
2484
2485           if (!ok)
2486             ok = retry_ultimate_address_timeout(retry_key, addr2->domain,
2487                 retry_record, now);
2488           }
2489         }
2490       else DEBUG(D_retry) debug_printf("no retry record exists\n");
2491       }
2492
2493     /* This address is to be delivered. Leave it on the chain. */
2494
2495     if (ok)
2496       {
2497       addr3 = addr2;
2498       addr2 = addr2->next;
2499       }
2500
2501     /* This address is to be deferred. Take it out of the chain, and
2502     post-process it as complete. Must take it out of the chain first,
2503     because post processing puts it on another chain. */
2504
2505     else
2506       {
2507       address_item *this = addr2;
2508       this->message = US"Retry time not yet reached";
2509       this->basic_errno = ERRNO_LRETRY;
2510       if (addr3 == NULL) addr2 = addr = addr2->next;
2511         else addr2 = addr3->next = addr2->next;
2512       post_process_one(this, DEFER, logflags, DTYPE_TRANSPORT, 0);
2513       }
2514     }
2515
2516   if (dbm_file != NULL) dbfn_close(dbm_file);
2517
2518   /* If there are no addresses left on the chain, they all deferred. Loop
2519   for the next set of addresses. */
2520
2521   if (addr == NULL) continue;
2522
2523   /* So, finally, we do have some addresses that can be passed to the
2524   transport. Before doing so, set up variables that are relevant to a
2525   single delivery. */
2526
2527   deliver_set_expansions(addr);
2528   delivery_start = time(NULL);
2529   deliver_local(addr, FALSE);
2530   deliver_time = (int)(time(NULL) - delivery_start);
2531
2532   /* If a shadow transport (which must perforce be another local transport), is
2533   defined, and its condition is met, we must pass the message to the shadow
2534   too, but only those addresses that succeeded. We do this by making a new
2535   chain of addresses - also to keep the original chain uncontaminated. We must
2536   use a chain rather than doing it one by one, because the shadow transport may
2537   batch.
2538
2539   NOTE: if the condition fails because of a lookup defer, there is nothing we
2540   can do! */
2541
2542   if (tp->shadow != NULL &&
2543       (tp->shadow_condition == NULL ||
2544       expand_check_condition(tp->shadow_condition, tp->name, US"transport")))
2545     {
2546     transport_instance *stp;
2547     address_item *shadow_addr = NULL;
2548     address_item **last = &shadow_addr;
2549
2550     for (stp = transports; stp != NULL; stp = stp->next)
2551       if (Ustrcmp(stp->name, tp->shadow) == 0) break;
2552
2553     if (stp == NULL)
2554       log_write(0, LOG_MAIN|LOG_PANIC, "shadow transport \"%s\" not found ",
2555         tp->shadow);
2556
2557     /* Pick off the addresses that have succeeded, and make clones. Put into
2558     the shadow_message field a pointer to the shadow_message field of the real
2559     address. */
2560
2561     else for (addr2 = addr; addr2 != NULL; addr2 = addr2->next)
2562       {
2563       if (addr2->transport_return != OK) continue;
2564       addr3 = store_get(sizeof(address_item));
2565       *addr3 = *addr2;
2566       addr3->next = NULL;
2567       addr3->shadow_message = (uschar *)(&(addr2->shadow_message));
2568       addr3->transport = stp;
2569       addr3->transport_return = DEFER;
2570       addr3->return_filename = NULL;
2571       addr3->return_file = -1;
2572       *last = addr3;
2573       last = &(addr3->next);
2574       }
2575
2576     /* If we found any addresses to shadow, run the delivery, and stick any
2577     message back into the shadow_message field in the original. */
2578
2579     if (shadow_addr != NULL)
2580       {
2581       int save_count = transport_count;
2582
2583       DEBUG(D_deliver|D_transport)
2584         debug_printf(">>>>>>>>>>>>>>>> Shadow delivery >>>>>>>>>>>>>>>>\n");
2585       deliver_local(shadow_addr, TRUE);
2586
2587       for(; shadow_addr != NULL; shadow_addr = shadow_addr->next)
2588         {
2589         int sresult = shadow_addr->transport_return;
2590         *((uschar **)(shadow_addr->shadow_message)) = (sresult == OK)?
2591           string_sprintf(" ST=%s", stp->name) :
2592           string_sprintf(" ST=%s (%s%s%s)", stp->name,
2593             (shadow_addr->basic_errno <= 0)?
2594               US"" : US strerror(shadow_addr->basic_errno),
2595             (shadow_addr->basic_errno <= 0 || shadow_addr->message == NULL)?
2596               US"" : US": ",
2597             (shadow_addr->message != NULL)? shadow_addr->message :
2598               (shadow_addr->basic_errno <= 0)? US"unknown error" : US"");
2599
2600         DEBUG(D_deliver|D_transport)
2601           debug_printf("%s shadow transport returned %s for %s\n",
2602             stp->name,
2603             (sresult == OK)?    "OK" :
2604             (sresult == DEFER)? "DEFER" :
2605             (sresult == FAIL)?  "FAIL" :
2606             (sresult == PANIC)? "PANIC" : "?",
2607             shadow_addr->address);
2608         }
2609
2610       DEBUG(D_deliver|D_transport)
2611         debug_printf(">>>>>>>>>>>>>>>> End shadow delivery >>>>>>>>>>>>>>>>\n");
2612
2613       transport_count = save_count;   /* Restore original transport count */
2614       }
2615     }
2616
2617   /* Cancel the expansions that were set up for the delivery. */
2618
2619   deliver_set_expansions(NULL);
2620
2621   /* Now we can process the results of the real transport. We must take each
2622   address off the chain first, because post_process_one() puts it on another
2623   chain. */
2624
2625   for (addr2 = addr; addr2 != NULL; addr2 = nextaddr)
2626     {
2627     int result = addr2->transport_return;
2628     nextaddr = addr2->next;
2629
2630     DEBUG(D_deliver|D_transport)
2631       debug_printf("%s transport returned %s for %s\n",
2632         tp->name,
2633         (result == OK)?    "OK" :
2634         (result == DEFER)? "DEFER" :
2635         (result == FAIL)?  "FAIL" :
2636         (result == PANIC)? "PANIC" : "?",
2637         addr2->address);
2638
2639     /* If there is a retry_record, or if delivery is deferred, build a retry
2640     item for setting a new retry time or deleting the old retry record from
2641     the database. These items are handled all together after all addresses
2642     have been handled (so the database is open just for a short time for
2643     updating). */
2644
2645     if (result == DEFER || testflag(addr2, af_lt_retry_exists))
2646       {
2647       int flags = (result == DEFER)? 0 : rf_delete;
2648       uschar *retry_key = string_copy((tp->retry_use_local_part)?
2649         addr2->address_retry_key : addr2->domain_retry_key);
2650       *retry_key = 'T';
2651       retry_add_item(addr2, retry_key, flags);
2652       }
2653
2654     /* Done with this address */
2655
2656     if (result == OK) addr2->more_errno = deliver_time;
2657     post_process_one(addr2, result, logflags, DTYPE_TRANSPORT, logchar);
2658
2659     /* If a pipe delivery generated text to be sent back, the result may be
2660     changed to FAIL, and we must copy this for subsequent addresses in the
2661     batch. */
2662
2663     if (addr2->transport_return != result)
2664       {
2665       for (addr3 = nextaddr; addr3 != NULL; addr3 = addr3->next)
2666         {
2667         addr3->transport_return = addr2->transport_return;
2668         addr3->basic_errno = addr2->basic_errno;
2669         addr3->message = addr2->message;
2670         }
2671       result = addr2->transport_return;
2672       }
2673
2674     /* Whether or not the result was changed to FAIL, we need to copy the
2675     return_file value from the first address into all the addresses of the
2676     batch, so they are all listed in the error message. */
2677
2678     addr2->return_file = addr->return_file;
2679
2680     /* Change log character for recording successful deliveries. */
2681
2682     if (result == OK) logchar = '-';
2683     }
2684   }        /* Loop back for next batch of addresses */
2685 }
2686
2687
2688
2689
2690 /*************************************************
2691 *           Sort remote deliveries               *
2692 *************************************************/
2693
2694 /* This function is called if remote_sort_domains is set. It arranges that the
2695 chain of addresses for remote deliveries is ordered according to the strings
2696 specified. Try to make this shuffling reasonably efficient by handling
2697 sequences of addresses rather than just single ones.
2698
2699 Arguments:  None
2700 Returns:    Nothing
2701 */
2702
2703 static void
2704 sort_remote_deliveries(void)
2705 {
2706 int sep = 0;
2707 address_item **aptr = &addr_remote;
2708 uschar *listptr = remote_sort_domains;
2709 uschar *pattern;
2710 uschar patbuf[256];
2711
2712 while (*aptr != NULL &&
2713        (pattern = string_nextinlist(&listptr, &sep, patbuf, sizeof(patbuf)))
2714        != NULL)
2715   {
2716   address_item *moved = NULL;
2717   address_item **bptr = &moved;
2718
2719   while (*aptr != NULL)
2720     {
2721     address_item **next;
2722     deliver_domain = (*aptr)->domain;   /* set $domain */
2723     if (match_isinlist(deliver_domain, &pattern, UCHAR_MAX+1,
2724           &domainlist_anchor, NULL, MCL_DOMAIN, TRUE, NULL) == OK)
2725       {
2726       aptr = &((*aptr)->next);
2727       continue;
2728       }
2729
2730     next = &((*aptr)->next);
2731     while (*next != NULL &&
2732            (deliver_domain = (*next)->domain,  /* Set $domain */
2733             match_isinlist(deliver_domain, &pattern, UCHAR_MAX+1,
2734               &domainlist_anchor, NULL, MCL_DOMAIN, TRUE, NULL)) != OK)
2735       next = &((*next)->next);
2736
2737     /* If the batch of non-matchers is at the end, add on any that were
2738     extracted further up the chain, and end this iteration. Otherwise,
2739     extract them from the chain and hang on the moved chain. */
2740
2741     if (*next == NULL)
2742       {
2743       *next = moved;
2744       break;
2745       }
2746
2747     *bptr = *aptr;
2748     *aptr = *next;
2749     *next = NULL;
2750     bptr = next;
2751     aptr = &((*aptr)->next);
2752     }
2753
2754   /* If the loop ended because the final address matched, *aptr will
2755   be NULL. Add on to the end any extracted non-matching addresses. If
2756   *aptr is not NULL, the loop ended via "break" when *next is null, that
2757   is, there was a string of non-matching addresses at the end. In this
2758   case the extracted addresses have already been added on the end. */
2759
2760   if (*aptr == NULL) *aptr = moved;
2761   }
2762
2763 DEBUG(D_deliver)
2764   {
2765   address_item *addr;
2766   debug_printf("remote addresses after sorting:\n");
2767   for (addr = addr_remote; addr != NULL; addr = addr->next)
2768     debug_printf("  %s\n", addr->address);
2769   }
2770 }
2771
2772
2773
2774 /*************************************************
2775 *  Read from pipe for remote delivery subprocess *
2776 *************************************************/
2777
2778 /* This function is called when the subprocess is complete, but can also be
2779 called before it is complete, in order to empty a pipe that is full (to prevent
2780 deadlock). It must therefore keep track of its progress in the parlist data
2781 block.
2782
2783 We read the pipe to get the delivery status codes and a possible error message
2784 for each address, optionally preceded by unusability data for the hosts and
2785 also by optional retry data.
2786
2787 Read in large chunks into the big buffer and then scan through, interpreting
2788 the data therein. In most cases, only a single read will be necessary. No
2789 individual item will ever be anywhere near 2500 bytes in length, so by ensuring
2790 that we read the next chunk when there is less than 2500 bytes left in the
2791 non-final chunk, we can assume each item is complete in the buffer before
2792 handling it. Each item is written using a single write(), which is atomic for
2793 small items (less than PIPE_BUF, which seems to be at least 512 in any Unix and
2794 often bigger) so even if we are reading while the subprocess is still going, we
2795 should never have only a partial item in the buffer.
2796
2797 Argument:
2798   poffset     the offset of the parlist item
2799   eop         TRUE if the process has completed
2800
2801 Returns:      TRUE if the terminating 'Z' item has been read,
2802               or there has been a disaster (i.e. no more data needed);
2803               FALSE otherwise
2804 */
2805
2806 static BOOL
2807 par_read_pipe(int poffset, BOOL eop)
2808 {
2809 host_item *h;
2810 pardata *p = parlist + poffset;
2811 address_item *addrlist = p->addrlist;
2812 address_item *addr = p->addr;
2813 pid_t pid = p->pid;
2814 int fd = p->fd;
2815 uschar *endptr = big_buffer;
2816 uschar *ptr = endptr;
2817 uschar *msg = p->msg;
2818 BOOL done = p->done;
2819 BOOL unfinished = TRUE;
2820
2821 /* Loop through all items, reading from the pipe when necessary. The pipe
2822 is set up to be non-blocking, but there are two different Unix mechanisms in
2823 use. Exim uses O_NONBLOCK if it is defined. This returns 0 for end of file,
2824 and EAGAIN for no more data. If O_NONBLOCK is not defined, Exim uses O_NDELAY,
2825 which returns 0 for both end of file and no more data. We distinguish the
2826 two cases by taking 0 as end of file only when we know the process has
2827 completed.
2828
2829 Each separate item is written to the pipe in a single write(), and as they are
2830 all short items, the writes will all be atomic and we should never find
2831 ourselves in the position of having read an incomplete item. "Short" in this
2832 case can mean up to about 1K in the case when there is a long error message
2833 associated with an address. */
2834
2835 DEBUG(D_deliver) debug_printf("reading pipe for subprocess %d (%s)\n",
2836   (int)p->pid, eop? "ended" : "not ended");
2837
2838 while (!done)
2839   {
2840   retry_item *r, **rp;
2841   int remaining = endptr - ptr;
2842
2843   /* Read (first time) or top up the chars in the buffer if necessary.
2844   There will be only one read if we get all the available data (i.e. don't
2845   fill the buffer completely). */
2846
2847   if (remaining < 2500 && unfinished)
2848     {
2849     int len;
2850     int available = big_buffer_size - remaining;
2851
2852     if (remaining > 0) memmove(big_buffer, ptr, remaining);
2853
2854     ptr = big_buffer;
2855     endptr = big_buffer + remaining;
2856     len = read(fd, endptr, available);
2857
2858     DEBUG(D_deliver) debug_printf("read() yielded %d\n", len);
2859
2860     /* If the result is EAGAIN and the process is not complete, just
2861     stop reading any more and process what we have already. */
2862
2863     if (len < 0)
2864       {
2865       if (!eop && errno == EAGAIN) len = 0; else
2866         {
2867         msg = string_sprintf("failed to read pipe from transport process "
2868           "%d for transport %s: %s", pid, addr->transport->driver_name,
2869           strerror(errno));
2870         break;
2871         }
2872       }
2873
2874     /* If the length is zero (eof or no-more-data), just process what we
2875     already have. Note that if the process is still running and we have
2876     read all the data in the pipe (but less that "available") then we
2877     won't read any more, as "unfinished" will get set FALSE. */
2878
2879     endptr += len;
2880     unfinished = len == available;
2881     }
2882
2883   /* If we are at the end of the available data, exit the loop. */
2884
2885   if (ptr >= endptr) break;
2886
2887   /* Handle each possible type of item, assuming the complete item is
2888   available in store. */
2889
2890   switch (*ptr++)
2891     {
2892     /* Host items exist only if any hosts were marked unusable. Match
2893     up by checking the IP address. */
2894
2895     case 'H':
2896     for (h = addrlist->host_list; h != NULL; h = h->next)
2897       {
2898       if (h->address == NULL || Ustrcmp(h->address, ptr+2) != 0) continue;
2899       h->status = ptr[0];
2900       h->why = ptr[1];
2901       }
2902     ptr += 2;
2903     while (*ptr++);
2904     break;
2905
2906     /* Retry items are sent in a preceding R item for each address. This is
2907     kept separate to keep each message short enough to guarantee it won't
2908     be split in the pipe. Hopefully, in the majority of cases, there won't in
2909     fact be any retry items at all.
2910
2911     The complete set of retry items might include an item to delete a
2912     routing retry if there was a previous routing delay. However, routing
2913     retries are also used when a remote transport identifies an address error.
2914     In that case, there may also be an "add" item for the same key. Arrange
2915     that a "delete" item is dropped in favour of an "add" item. */
2916
2917     case 'R':
2918     if (addr == NULL) goto ADDR_MISMATCH;
2919
2920     DEBUG(D_deliver|D_retry)
2921       debug_printf("reading retry information for %s from subprocess\n",
2922         ptr+1);
2923
2924     /* Cut out any "delete" items on the list. */
2925
2926     for (rp = &(addr->retries); (r = *rp) != NULL; rp = &(r->next))
2927       {
2928       if (Ustrcmp(r->key, ptr+1) == 0)           /* Found item with same key */
2929         {
2930         if ((r->flags & rf_delete) == 0) break;  /* It was not "delete" */
2931         *rp = r->next;                           /* Excise a delete item */
2932         DEBUG(D_deliver|D_retry)
2933           debug_printf("  existing delete item dropped\n");
2934         }
2935       }
2936
2937     /* We want to add a delete item only if there is no non-delete item;
2938     however we still have to step ptr through the data. */
2939
2940     if (r == NULL || (*ptr & rf_delete) == 0)
2941       {
2942       r = store_get(sizeof(retry_item));
2943       r->next = addr->retries;
2944       addr->retries = r;
2945       r->flags = *ptr++;
2946       r->key = string_copy(ptr);
2947       while (*ptr++);
2948       memcpy(&(r->basic_errno), ptr, sizeof(r->basic_errno));
2949       ptr += sizeof(r->basic_errno);
2950       memcpy(&(r->more_errno), ptr, sizeof(r->more_errno));
2951       ptr += sizeof(r->more_errno);
2952       r->message = (*ptr)? string_copy(ptr) : NULL;
2953       DEBUG(D_deliver|D_retry)
2954         debug_printf("  added %s item\n",
2955           ((r->flags & rf_delete) == 0)? "retry" : "delete");
2956       }
2957
2958     else
2959       {
2960       DEBUG(D_deliver|D_retry)
2961         debug_printf("  delete item not added: non-delete item exists\n");
2962       ptr++;
2963       while(*ptr++);
2964       ptr += sizeof(r->basic_errno) + sizeof(r->more_errno);
2965       }
2966
2967     while(*ptr++);
2968     break;
2969
2970     /* Put the amount of data written into the parlist block */
2971
2972     case 'S':
2973     memcpy(&(p->transport_count), ptr, sizeof(transport_count));
2974     ptr += sizeof(transport_count);
2975     break;
2976
2977     /* Address items are in the order of items on the address chain. We
2978     remember the current address value in case this function is called
2979     several times to empty the pipe in stages. Information about delivery
2980     over TLS is sent in a preceding X item for each address. We don't put
2981     it in with the other info, in order to keep each message short enough to
2982     guarantee it won't be split in the pipe. */
2983
2984     #ifdef SUPPORT_TLS
2985     case 'X':
2986     if (addr == NULL) goto ADDR_MISMATCH;          /* Below, in 'A' handler */
2987     switch (*ptr++)
2988       {
2989       case '1':
2990       addr->cipher = NULL;
2991       addr->peerdn = NULL;
2992
2993       if (*ptr)
2994         addr->cipher = string_copy(ptr);
2995       while (*ptr++);
2996       if (*ptr)
2997         addr->peerdn = string_copy(ptr);
2998       break;
2999
3000       case '2':
3001       addr->peercert = NULL;
3002       if (*ptr)
3003         (void) tls_import_cert(ptr, &addr->peercert);
3004       break;
3005
3006       case '3':
3007       addr->ourcert = NULL;
3008       if (*ptr)
3009         (void) tls_import_cert(ptr, &addr->ourcert);
3010       break;
3011
3012       #ifdef EXPERIMENTAL_OCSP
3013       case '4':
3014       addr->ocsp = OCSP_NOT_REQ;
3015       if (*ptr)
3016         addr->ocsp = *ptr - '0';
3017       break;
3018       #endif
3019       }
3020     while (*ptr++);
3021     break;
3022     #endif
3023
3024     case 'C':   /* client authenticator information */
3025     switch (*ptr++)
3026       {
3027       case '1':
3028         addr->authenticator = (*ptr)? string_copy(ptr) : NULL;
3029         break;
3030       case '2':
3031         addr->auth_id = (*ptr)? string_copy(ptr) : NULL;
3032         break;
3033       case '3':
3034         addr->auth_sndr = (*ptr)? string_copy(ptr) : NULL;
3035         break;
3036       }
3037     while (*ptr++);
3038     break;
3039
3040 #ifdef EXPERIMENTAL_PRDR
3041     case 'P':
3042       addr->flags |= af_prdr_used; break;
3043 #endif
3044
3045     case 'A':
3046     if (addr == NULL)
3047       {
3048       ADDR_MISMATCH:
3049       msg = string_sprintf("address count mismatch for data read from pipe "
3050         "for transport process %d for transport %s", pid,
3051           addrlist->transport->driver_name);
3052       done = TRUE;
3053       break;
3054       }
3055
3056     addr->transport_return = *ptr++;
3057     addr->special_action = *ptr++;
3058     memcpy(&(addr->basic_errno), ptr, sizeof(addr->basic_errno));
3059     ptr += sizeof(addr->basic_errno);
3060     memcpy(&(addr->more_errno), ptr, sizeof(addr->more_errno));
3061     ptr += sizeof(addr->more_errno);
3062     memcpy(&(addr->flags), ptr, sizeof(addr->flags));
3063     ptr += sizeof(addr->flags);
3064     addr->message = (*ptr)? string_copy(ptr) : NULL;
3065     while(*ptr++);
3066     addr->user_message = (*ptr)? string_copy(ptr) : NULL;
3067     while(*ptr++);
3068
3069     /* Always two strings for host information, followed by the port number */
3070
3071     if (*ptr != 0)
3072       {
3073       h = store_get(sizeof(host_item));
3074       h->name = string_copy(ptr);
3075       while (*ptr++);
3076       h->address = string_copy(ptr);
3077       while(*ptr++);
3078       memcpy(&(h->port), ptr, sizeof(h->port));
3079       ptr += sizeof(h->port);
3080       addr->host_used = h;
3081       }
3082     else ptr++;
3083
3084     /* Finished with this address */
3085
3086     addr = addr->next;
3087     break;
3088
3089     /* Z marks the logical end of the data. It is followed by '0' if
3090     continue_transport was NULL at the end of transporting, otherwise '1'.
3091     We need to know when it becomes NULL during a delivery down a passed SMTP
3092     channel so that we don't try to pass anything more down it. Of course, for
3093     most normal messages it will remain NULL all the time. */
3094
3095     case 'Z':
3096     if (*ptr == '0')
3097       {
3098       continue_transport = NULL;
3099       continue_hostname = NULL;
3100       }
3101     done = TRUE;
3102     DEBUG(D_deliver) debug_printf("Z%c item read\n", *ptr);
3103     break;
3104
3105     /* Anything else is a disaster. */
3106
3107     default:
3108     msg = string_sprintf("malformed data (%d) read from pipe for transport "
3109       "process %d for transport %s", ptr[-1], pid,
3110         addr->transport->driver_name);
3111     done = TRUE;
3112     break;
3113     }
3114   }
3115
3116 /* The done flag is inspected externally, to determine whether or not to
3117 call the function again when the process finishes. */
3118
3119 p->done = done;
3120
3121 /* If the process hadn't finished, and we haven't seen the end of the data
3122 or suffered a disaster, update the rest of the state, and return FALSE to
3123 indicate "not finished". */
3124
3125 if (!eop && !done)
3126   {
3127   p->addr = addr;
3128   p->msg = msg;
3129   return FALSE;
3130   }
3131
3132 /* Close our end of the pipe, to prevent deadlock if the far end is still
3133 pushing stuff into it. */
3134
3135 (void)close(fd);
3136 p->fd = -1;
3137
3138 /* If we have finished without error, but haven't had data for every address,
3139 something is wrong. */
3140
3141 if (msg == NULL && addr != NULL)
3142   msg = string_sprintf("insufficient address data read from pipe "
3143     "for transport process %d for transport %s", pid,
3144       addr->transport->driver_name);
3145
3146 /* If an error message is set, something has gone wrong in getting back
3147 the delivery data. Put the message into each address and freeze it. */
3148
3149 if (msg != NULL)
3150   {
3151   for (addr = addrlist; addr != NULL; addr = addr->next)
3152     {
3153     addr->transport_return = DEFER;
3154     addr->special_action = SPECIAL_FREEZE;
3155     addr->message = msg;
3156     }
3157   }
3158
3159 /* Return TRUE to indicate we have got all we need from this process, even
3160 if it hasn't actually finished yet. */
3161
3162 return TRUE;
3163 }
3164
3165
3166
3167 /*************************************************
3168 *   Post-process a set of remote addresses       *
3169 *************************************************/
3170
3171 /* Do what has to be done immediately after a remote delivery for each set of
3172 addresses, then re-write the spool if necessary. Note that post_process_one
3173 puts the address on an appropriate queue; hence we must fish off the next
3174 one first. This function is also called if there is a problem with setting
3175 up a subprocess to do a remote delivery in parallel. In this case, the final
3176 argument contains a message, and the action must be forced to DEFER.
3177
3178 Argument:
3179    addr      pointer to chain of address items
3180    logflags  flags for logging
3181    msg       NULL for normal cases; -> error message for unexpected problems
3182    fallback  TRUE if processing fallback hosts
3183
3184 Returns:     nothing
3185 */
3186
3187 static void
3188 remote_post_process(address_item *addr, int logflags, uschar *msg,
3189   BOOL fallback)
3190 {
3191 host_item *h;
3192
3193 /* If any host addresses were found to be unusable, add them to the unusable
3194 tree so that subsequent deliveries don't try them. */
3195
3196 for (h = addr->host_list; h != NULL; h = h->next)
3197   {
3198   if (h->address == NULL) continue;
3199   if (h->status >= hstatus_unusable) tree_add_unusable(h);
3200   }
3201
3202 /* Now handle each address on the chain. The transport has placed '=' or '-'
3203 into the special_action field for each successful delivery. */
3204
3205 while (addr != NULL)
3206   {
3207   address_item *next = addr->next;
3208
3209   /* If msg == NULL (normal processing) and the result is DEFER and we are
3210   processing the main hosts and there are fallback hosts available, put the
3211   address on the list for fallback delivery. */
3212
3213   if (addr->transport_return == DEFER &&
3214       addr->fallback_hosts != NULL &&
3215       !fallback &&
3216       msg == NULL)
3217     {
3218     addr->host_list = addr->fallback_hosts;
3219     addr->next = addr_fallback;
3220     addr_fallback = addr;
3221     DEBUG(D_deliver) debug_printf("%s queued for fallback host(s)\n", addr->address);
3222     }
3223
3224   /* If msg is set (=> unexpected problem), set it in the address before
3225   doing the ordinary post processing. */
3226
3227   else
3228     {
3229     if (msg != NULL)
3230       {
3231       addr->message = msg;
3232       addr->transport_return = DEFER;
3233       }
3234     (void)post_process_one(addr, addr->transport_return, logflags,
3235       DTYPE_TRANSPORT, addr->special_action);
3236     }
3237
3238   /* Next address */
3239
3240   addr = next;
3241   }
3242
3243 /* If we have just delivered down a passed SMTP channel, and that was
3244 the last address, the channel will have been closed down. Now that
3245 we have logged that delivery, set continue_sequence to 1 so that
3246 any subsequent deliveries don't get "*" incorrectly logged. */
3247
3248 if (continue_transport == NULL) continue_sequence = 1;
3249 }
3250
3251
3252
3253 /*************************************************
3254 *     Wait for one remote delivery subprocess    *
3255 *************************************************/
3256
3257 /* This function is called while doing remote deliveries when either the
3258 maximum number of processes exist and we need one to complete so that another
3259 can be created, or when waiting for the last ones to complete. It must wait for
3260 the completion of one subprocess, empty the control block slot, and return a
3261 pointer to the address chain.
3262
3263 Arguments:    none
3264 Returns:      pointer to the chain of addresses handled by the process;
3265               NULL if no subprocess found - this is an unexpected error
3266 */
3267
3268 static address_item *
3269 par_wait(void)
3270 {
3271 int poffset, status;
3272 address_item *addr, *addrlist;
3273 pid_t pid;
3274
3275 set_process_info("delivering %s: waiting for a remote delivery subprocess "
3276   "to finish", message_id);
3277
3278 /* Loop until either a subprocess completes, or there are no subprocesses in
3279 existence - in which case give an error return. We cannot proceed just by
3280 waiting for a completion, because a subprocess may have filled up its pipe, and
3281 be waiting for it to be emptied. Therefore, if no processes have finished, we
3282 wait for one of the pipes to acquire some data by calling select(), with a
3283 timeout just in case.
3284
3285 The simple approach is just to iterate after reading data from a ready pipe.
3286 This leads to non-ideal behaviour when the subprocess has written its final Z
3287 item, closed the pipe, and is in the process of exiting (the common case). A
3288 call to waitpid() yields nothing completed, but select() shows the pipe ready -
3289 reading it yields EOF, so you end up with busy-waiting until the subprocess has
3290 actually finished.
3291
3292 To avoid this, if all the data that is needed has been read from a subprocess
3293 after select(), an explicit wait() for it is done. We know that all it is doing
3294 is writing to the pipe and then exiting, so the wait should not be long.
3295
3296 The non-blocking waitpid() is to some extent just insurance; if we could
3297 reliably detect end-of-file on the pipe, we could always know when to do a
3298 blocking wait() for a completed process. However, because some systems use
3299 NDELAY, which doesn't distinguish between EOF and pipe empty, it is easier to
3300 use code that functions without the need to recognize EOF.
3301
3302 There's a double loop here just in case we end up with a process that is not in
3303 the list of remote delivery processes. Something has obviously gone wrong if
3304 this is the case. (For example, a process that is incorrectly left over from
3305 routing or local deliveries might be found.) The damage can be minimized by
3306 looping back and looking for another process. If there aren't any, the error
3307 return will happen. */
3308
3309 for (;;)   /* Normally we do not repeat this loop */
3310   {
3311   while ((pid = waitpid(-1, &status, WNOHANG)) <= 0)
3312     {
3313     struct timeval tv;
3314     fd_set select_pipes;
3315     int maxpipe, readycount;
3316
3317     /* A return value of -1 can mean several things. If errno != ECHILD, it
3318     either means invalid options (which we discount), or that this process was
3319     interrupted by a signal. Just loop to try the waitpid() again.
3320
3321     If errno == ECHILD, waitpid() is telling us that there are no subprocesses
3322     in existence. This should never happen, and is an unexpected error.
3323     However, there is a nasty complication when running under Linux. If "strace
3324     -f" is being used under Linux to trace this process and its children,
3325     subprocesses are "stolen" from their parents and become the children of the
3326     tracing process. A general wait such as the one we've just obeyed returns
3327     as if there are no children while subprocesses are running. Once a
3328     subprocess completes, it is restored to the parent, and waitpid(-1) finds
3329     it. Thanks to Joachim Wieland for finding all this out and suggesting a
3330     palliative.
3331
3332     This does not happen using "truss" on Solaris, nor (I think) with other
3333     tracing facilities on other OS. It seems to be specific to Linux.
3334
3335     What we do to get round this is to use kill() to see if any of our
3336     subprocesses are still in existence. If kill() gives an OK return, we know
3337     it must be for one of our processes - it can't be for a re-use of the pid,
3338     because if our process had finished, waitpid() would have found it. If any
3339     of our subprocesses are in existence, we proceed to use select() as if
3340     waitpid() had returned zero. I think this is safe. */
3341
3342     if (pid < 0)
3343       {
3344       if (errno != ECHILD) continue;   /* Repeats the waitpid() */
3345
3346       DEBUG(D_deliver)
3347         debug_printf("waitpid() returned -1/ECHILD: checking explicitly "
3348           "for process existence\n");
3349
3350       for (poffset = 0; poffset < remote_max_parallel; poffset++)
3351         {
3352         if ((pid = parlist[poffset].pid) != 0 && kill(pid, 0) == 0)
3353           {
3354           DEBUG(D_deliver) debug_printf("process %d still exists: assume "
3355             "stolen by strace\n", (int)pid);
3356           break;   /* With poffset set */
3357           }
3358         }
3359
3360       if (poffset >= remote_max_parallel)
3361         {
3362         DEBUG(D_deliver) debug_printf("*** no delivery children found\n");
3363         return NULL;   /* This is the error return */
3364         }
3365       }
3366
3367     /* A pid value greater than 0 breaks the "while" loop. A negative value has
3368     been handled above. A return value of zero means that there is at least one
3369     subprocess, but there are no completed subprocesses. See if any pipes are
3370     ready with any data for reading. */
3371
3372     DEBUG(D_deliver) debug_printf("selecting on subprocess pipes\n");
3373
3374     maxpipe = 0;
3375     FD_ZERO(&select_pipes);
3376     for (poffset = 0; poffset < remote_max_parallel; poffset++)
3377       {
3378       if (parlist[poffset].pid != 0)
3379         {
3380         int fd = parlist[poffset].fd;
3381         FD_SET(fd, &select_pipes);
3382         if (fd > maxpipe) maxpipe = fd;
3383         }
3384       }
3385
3386     /* Stick in a 60-second timeout, just in case. */
3387
3388     tv.tv_sec = 60;
3389     tv.tv_usec = 0;
3390
3391     readycount = select(maxpipe + 1, (SELECT_ARG2_TYPE *)&select_pipes,
3392          NULL, NULL, &tv);
3393
3394     /* Scan through the pipes and read any that are ready; use the count
3395     returned by select() to stop when there are no more. Select() can return
3396     with no processes (e.g. if interrupted). This shouldn't matter.
3397
3398     If par_read_pipe() returns TRUE, it means that either the terminating Z was
3399     read, or there was a disaster. In either case, we are finished with this
3400     process. Do an explicit wait() for the process and break the main loop if
3401     it succeeds.
3402
3403     It turns out that we have to deal with the case of an interrupted system
3404     call, which can happen on some operating systems if the signal handling is
3405     set up to do that by default. */
3406
3407     for (poffset = 0;
3408          readycount > 0 && poffset < remote_max_parallel;
3409          poffset++)
3410       {
3411       if ((pid = parlist[poffset].pid) != 0 &&
3412            FD_ISSET(parlist[poffset].fd, &select_pipes))
3413         {
3414         readycount--;
3415         if (par_read_pipe(poffset, FALSE))    /* Finished with this pipe */
3416           {
3417           for (;;)                            /* Loop for signals */
3418             {
3419             pid_t endedpid = waitpid(pid, &status, 0);
3420             if (endedpid == pid) goto PROCESS_DONE;
3421             if (endedpid != (pid_t)(-1) || errno != EINTR)
3422               log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Unexpected error return "
3423                 "%d (errno = %d) from waitpid() for process %d",
3424                 (int)endedpid, errno, (int)pid);
3425             }
3426           }
3427         }
3428       }
3429
3430     /* Now go back and look for a completed subprocess again. */
3431     }
3432
3433   /* A completed process was detected by the non-blocking waitpid(). Find the
3434   data block that corresponds to this subprocess. */
3435
3436   for (poffset = 0; poffset < remote_max_parallel; poffset++)
3437     if (pid == parlist[poffset].pid) break;
3438
3439   /* Found the data block; this is a known remote delivery process. We don't
3440   need to repeat the outer loop. This should be what normally happens. */
3441
3442   if (poffset < remote_max_parallel) break;
3443
3444   /* This situation is an error, but it's probably better to carry on looking
3445   for another process than to give up (as we used to do). */
3446
3447   log_write(0, LOG_MAIN|LOG_PANIC, "Process %d finished: not found in remote "
3448     "transport process list", pid);
3449   }  /* End of the "for" loop */
3450
3451 /* Come here when all the data was completely read after a select(), and
3452 the process in pid has been wait()ed for. */
3453
3454 PROCESS_DONE:
3455
3456 DEBUG(D_deliver)
3457   {
3458   if (status == 0)
3459     debug_printf("remote delivery process %d ended\n", (int)pid);
3460   else
3461     debug_printf("remote delivery process %d ended: status=%04x\n", (int)pid,
3462       status);
3463   }
3464
3465 set_process_info("delivering %s", message_id);
3466
3467 /* Get the chain of processed addresses */
3468
3469 addrlist = parlist[poffset].addrlist;
3470
3471 /* If the process did not finish cleanly, record an error and freeze (except
3472 for SIGTERM, SIGKILL and SIGQUIT), and also ensure the journal is not removed,
3473 in case the delivery did actually happen. */
3474
3475 if ((status & 0xffff) != 0)
3476   {
3477   uschar *msg;
3478   int msb = (status >> 8) & 255;
3479   int lsb = status & 255;
3480   int code = (msb == 0)? (lsb & 0x7f) : msb;
3481
3482   msg = string_sprintf("%s transport process returned non-zero status 0x%04x: "
3483     "%s %d",
3484     addrlist->transport->driver_name,
3485     status,
3486     (msb == 0)? "terminated by signal" : "exit code",
3487     code);
3488
3489   if (msb != 0 || (code != SIGTERM && code != SIGKILL && code != SIGQUIT))
3490     addrlist->special_action = SPECIAL_FREEZE;
3491
3492   for (addr = addrlist; addr != NULL; addr = addr->next)
3493     {
3494     addr->transport_return = DEFER;
3495     addr->message = msg;
3496     }
3497
3498   remove_journal = FALSE;
3499   }
3500
3501 /* Else complete reading the pipe to get the result of the delivery, if all
3502 the data has not yet been obtained. */
3503
3504 else if (!parlist[poffset].done) (void)par_read_pipe(poffset, TRUE);
3505
3506 /* Put the data count and return path into globals, mark the data slot unused,
3507 decrement the count of subprocesses, and return the address chain. */
3508
3509 transport_count = parlist[poffset].transport_count;
3510 used_return_path = parlist[poffset].return_path;
3511 parlist[poffset].pid = 0;
3512 parcount--;
3513 return addrlist;
3514 }
3515
3516
3517
3518 /*************************************************
3519 *      Wait for subprocesses and post-process    *
3520 *************************************************/
3521
3522 /* This function waits for subprocesses until the number that are still running
3523 is below a given threshold. For each complete subprocess, the addresses are
3524 post-processed. If we can't find a running process, there is some shambles.
3525 Better not bomb out, as that might lead to multiple copies of the message. Just
3526 log and proceed as if all done.
3527
3528 Arguments:
3529   max         maximum number of subprocesses to leave running
3530   fallback    TRUE if processing fallback hosts
3531
3532 Returns:      nothing
3533 */
3534
3535 static void
3536 par_reduce(int max, BOOL fallback)
3537 {
3538 while (parcount > max)
3539   {
3540   address_item *doneaddr = par_wait();
3541   if (doneaddr == NULL)
3542     {
3543     log_write(0, LOG_MAIN|LOG_PANIC,
3544       "remote delivery process count got out of step");
3545     parcount = 0;
3546     }
3547   else remote_post_process(doneaddr, LOG_MAIN, NULL, fallback);
3548   }
3549 }
3550
3551
3552
3553
3554 static void
3555 rmt_dlv_checked_write(int fd, void * buf, int size)
3556 {
3557 int ret = write(fd, buf, size);
3558 if(ret != size)
3559   log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Failed writing transport result to pipe: %s\n",
3560     ret == -1 ? strerror(errno) : "short write");
3561 }
3562
3563 /*************************************************
3564 *           Do remote deliveries                 *
3565 *************************************************/
3566
3567 /* This function is called to process the addresses in addr_remote. We must
3568 pick off the queue all addresses that have the same transport, remote
3569 destination, and errors address, and hand them to the transport in one go,
3570 subject to some configured limitations. If this is a run to continue delivering
3571 to an existing delivery channel, skip all but those addresses that can go to
3572 that channel. The skipped addresses just get deferred.
3573
3574 If mua_wrapper is set, all addresses must be able to be sent in a single
3575 transaction. If not, this function yields FALSE.
3576
3577 In Exim 4, remote deliveries are always done in separate processes, even
3578 if remote_max_parallel = 1 or if there's only one delivery to do. The reason
3579 is so that the base process can retain privilege. This makes the
3580 implementation of fallback transports feasible (though not initially done.)
3581
3582 We create up to the configured number of subprocesses, each of which passes
3583 back the delivery state via a pipe. (However, when sending down an existing
3584 connection, remote_max_parallel is forced to 1.)
3585
3586 Arguments:
3587   fallback  TRUE if processing fallback hosts
3588
3589 Returns:    TRUE normally
3590             FALSE if mua_wrapper is set and the addresses cannot all be sent
3591               in one transaction
3592 */
3593
3594 static BOOL
3595 do_remote_deliveries(BOOL fallback)
3596 {
3597 int parmax;
3598 int delivery_count;
3599 int poffset;
3600
3601 parcount = 0;    /* Number of executing subprocesses */
3602
3603 /* When sending down an existing channel, only do one delivery at a time.
3604 We use a local variable (parmax) to hold the maximum number of processes;
3605 this gets reduced from remote_max_parallel if we can't create enough pipes. */
3606
3607 if (continue_transport != NULL) remote_max_parallel = 1;
3608 parmax = remote_max_parallel;
3609
3610 /* If the data for keeping a list of processes hasn't yet been
3611 set up, do so. */
3612
3613 if (parlist == NULL)
3614   {
3615   parlist = store_get(remote_max_parallel * sizeof(pardata));
3616   for (poffset = 0; poffset < remote_max_parallel; poffset++)
3617     parlist[poffset].pid = 0;
3618   }
3619
3620 /* Now loop for each remote delivery */
3621
3622 for (delivery_count = 0; addr_remote != NULL; delivery_count++)
3623   {
3624   pid_t pid;
3625   uid_t uid;
3626   gid_t gid;
3627   int pfd[2];
3628   int address_count = 1;
3629   int address_count_max;
3630   BOOL multi_domain;
3631   BOOL use_initgroups;
3632   BOOL pipe_done = FALSE;
3633   transport_instance *tp;
3634   address_item **anchor = &addr_remote;
3635   address_item *addr = addr_remote;
3636   address_item *last = addr;
3637   address_item *next;
3638
3639   /* Pull the first address right off the list. */
3640
3641   addr_remote = addr->next;
3642   addr->next = NULL;
3643
3644   DEBUG(D_deliver|D_transport)
3645     debug_printf("--------> %s <--------\n", addr->address);
3646
3647   /* If no transport has been set, there has been a big screw-up somewhere. */
3648
3649   if ((tp = addr->transport) == NULL)
3650     {
3651     disable_logging = FALSE;  /* Jic */
3652     remote_post_process(addr, LOG_MAIN|LOG_PANIC,
3653       US"No transport set by router", fallback);
3654     continue;
3655     }
3656
3657   /* Check that this base address hasn't previously been delivered to this
3658   transport. The check is necessary at this point to handle homonymic addresses
3659   correctly in cases where the pattern of redirection changes between delivery
3660   attempts. Non-homonymic previous delivery is detected earlier, at routing
3661   time. */
3662
3663   if (previously_transported(addr, FALSE)) continue;
3664
3665   /* Force failure if the message is too big. */
3666
3667   if (tp->message_size_limit != NULL)
3668     {
3669     int rc = check_message_size(tp, addr);
3670     if (rc != OK)
3671       {
3672       addr->transport_return = rc;
3673       remote_post_process(addr, LOG_MAIN, NULL, fallback);
3674       continue;
3675       }
3676     }
3677
3678   /* Get the flag which specifies whether the transport can handle different
3679   domains that nevertheless resolve to the same set of hosts. */
3680
3681   multi_domain = tp->multi_domain;
3682
3683   /* Get the maximum it can handle in one envelope, with zero meaning
3684   unlimited, which is forced for the MUA wrapper case. */
3685
3686   address_count_max = tp->max_addresses;
3687   if (address_count_max == 0 || mua_wrapper) address_count_max = 999999;
3688
3689
3690   /************************************************************************/
3691   /*****    This is slightly experimental code, but should be safe.   *****/
3692
3693   /* The address_count_max value is the maximum number of addresses that the
3694   transport can send in one envelope. However, the transport must be capable of
3695   dealing with any number of addresses. If the number it gets exceeds its
3696   envelope limitation, it must send multiple copies of the message. This can be
3697   done over a single connection for SMTP, so uses less resources than making
3698   multiple connections. On the other hand, if remote_max_parallel is greater
3699   than one, it is perhaps a good idea to use parallel processing to move the
3700   message faster, even if that results in multiple simultaneous connections to
3701   the same host.
3702
3703   How can we come to some compromise between these two ideals? What we do is to
3704   limit the number of addresses passed to a single instance of a transport to
3705   the greater of (a) its address limit (rcpt_max for SMTP) and (b) the total
3706   number of addresses routed to remote transports divided by
3707   remote_max_parallel. For example, if the message has 100 remote recipients,
3708   remote max parallel is 2, and rcpt_max is 10, we'd never send more than 50 at
3709   once. But if rcpt_max is 100, we could send up to 100.
3710
3711   Of course, not all the remotely addresses in a message are going to go to the
3712   same set of hosts (except in smarthost configurations), so this is just a
3713   heuristic way of dividing up the work.
3714
3715   Furthermore (1), because this may not be wanted in some cases, and also to
3716   cope with really pathological cases, there is also a limit to the number of
3717   messages that are sent over one connection. This is the same limit that is
3718   used when sending several different messages over the same connection.
3719   Continue_sequence is set when in this situation, to the number sent so
3720   far, including this message.
3721
3722   Furthermore (2), when somebody explicitly sets the maximum value to 1, it
3723   is probably because they are using VERP, in which case they want to pass only
3724   one address at a time to the transport, in order to be able to use
3725   $local_part and $domain in constructing a new return path. We could test for
3726   the use of these variables, but as it is so likely they will be used when the
3727   maximum is 1, we don't bother. Just leave the value alone. */
3728
3729   if (address_count_max != 1 &&
3730       address_count_max < remote_delivery_count/remote_max_parallel)
3731     {
3732     int new_max = remote_delivery_count/remote_max_parallel;
3733     int message_max = tp->connection_max_messages;
3734     if (connection_max_messages >= 0) message_max = connection_max_messages;
3735     message_max -= continue_sequence - 1;
3736     if (message_max > 0 && new_max > address_count_max * message_max)
3737       new_max = address_count_max * message_max;
3738     address_count_max = new_max;
3739     }
3740
3741   /************************************************************************/
3742
3743
3744   /* Pick off all addresses which have the same transport, errors address,
3745   destination, and extra headers. In some cases they point to the same host
3746   list, but we also need to check for identical host lists generated from
3747   entirely different domains. The host list pointers can be NULL in the case
3748   where the hosts are defined in the transport. There is also a configured
3749   maximum limit of addresses that can be handled at once (see comments above
3750   for how it is computed). */
3751
3752   while ((next = *anchor) != NULL && address_count < address_count_max)
3753     {
3754     if ((multi_domain || Ustrcmp(next->domain, addr->domain) == 0)
3755         &&
3756         tp == next->transport
3757         &&
3758         same_hosts(next->host_list, addr->host_list)
3759         &&
3760         same_strings(next->p.errors_address, addr->p.errors_address)
3761         &&
3762         same_headers(next->p.extra_headers, addr->p.extra_headers)
3763         &&
3764         same_ugid(tp, next, addr)
3765         &&
3766         (next->p.remove_headers == addr->p.remove_headers ||
3767           (next->p.remove_headers != NULL &&
3768            addr->p.remove_headers != NULL &&
3769            Ustrcmp(next->p.remove_headers, addr->p.remove_headers) == 0)))
3770       {
3771       *anchor = next->next;
3772       next->next = NULL;
3773       next->first = addr;  /* remember top one (for retry processing) */
3774       last->next = next;
3775       last = next;
3776       address_count++;
3777       }
3778     else anchor = &(next->next);
3779     }
3780
3781   /* If we are acting as an MUA wrapper, all addresses must go in a single
3782   transaction. If not, put them back on the chain and yield FALSE. */
3783
3784   if (mua_wrapper && addr_remote != NULL)
3785     {
3786     last->next = addr_remote;
3787     addr_remote = addr;
3788     return FALSE;
3789     }
3790
3791   /* Set up the expansion variables for this set of addresses */
3792
3793   deliver_set_expansions(addr);
3794
3795   /* Ensure any transport-set auth info is fresh */
3796   addr->authenticator = addr->auth_id = addr->auth_sndr = NULL;
3797
3798   /* Compute the return path, expanding a new one if required. The old one
3799   must be set first, as it might be referred to in the expansion. */
3800
3801   if(addr->p.errors_address != NULL)
3802     return_path = addr->p.errors_address;
3803 #ifdef EXPERIMENTAL_SRS
3804   else if(addr->p.srs_sender != NULL)
3805     return_path = addr->p.srs_sender;
3806 #endif
3807   else
3808     return_path = sender_address;
3809
3810   if (tp->return_path != NULL)
3811     {
3812     uschar *new_return_path = expand_string(tp->return_path);
3813     if (new_return_path == NULL)
3814       {
3815       if (!expand_string_forcedfail)
3816         {
3817         remote_post_process(addr, LOG_MAIN|LOG_PANIC,
3818           string_sprintf("Failed to expand return path \"%s\": %s",
3819           tp->return_path, expand_string_message), fallback);
3820         continue;
3821         }
3822       }
3823     else return_path = new_return_path;
3824     }
3825
3826   /* Find the uid, gid, and use_initgroups setting for this transport. Failure
3827   logs and sets up error messages, so we just post-process and continue with
3828   the next address. */
3829
3830   if (!findugid(addr, tp, &uid, &gid, &use_initgroups))
3831     {
3832     remote_post_process(addr, LOG_MAIN|LOG_PANIC, NULL, fallback);
3833     continue;
3834     }
3835
3836   /* If this transport has a setup function, call it now so that it gets
3837   run in this process and not in any subprocess. That way, the results of
3838   any setup that are retained by the transport can be reusable. One of the
3839   things the setup does is to set the fallback host lists in the addresses.
3840   That is why it is called at this point, before the continue delivery
3841   processing, because that might use the fallback hosts. */
3842
3843   if (tp->setup != NULL)
3844     (void)((tp->setup)(addr->transport, addr, NULL, uid, gid, NULL));
3845
3846   /* If this is a run to continue delivery down an already-established
3847   channel, check that this set of addresses matches the transport and
3848   the channel. If it does not, defer the addresses. If a host list exists,
3849   we must check that the continue host is on the list. Otherwise, the
3850   host is set in the transport. */
3851
3852   continue_more = FALSE;           /* In case got set for the last lot */
3853   if (continue_transport != NULL)
3854     {
3855     BOOL ok = Ustrcmp(continue_transport, tp->name) == 0;
3856     if (ok && addr->host_list != NULL)
3857       {
3858       host_item *h;
3859       ok = FALSE;
3860       for (h = addr->host_list; h != NULL; h = h->next)
3861         {
3862         if (Ustrcmp(h->name, continue_hostname) == 0)
3863           { ok = TRUE; break; }
3864         }
3865       }
3866
3867     /* Addresses not suitable; defer or queue for fallback hosts (which
3868     might be the continue host) and skip to next address. */
3869
3870     if (!ok)
3871       {
3872       DEBUG(D_deliver) debug_printf("not suitable for continue_transport\n");
3873       next = addr;
3874
3875       if (addr->fallback_hosts != NULL && !fallback)
3876         {
3877         for (;;)
3878           {
3879           next->host_list = next->fallback_hosts;
3880           DEBUG(D_deliver) debug_printf("%s queued for fallback host(s)\n", next->address);
3881           if (next->next == NULL) break;
3882           next = next->next;
3883           }
3884         next->next = addr_fallback;
3885         addr_fallback = addr;
3886         }
3887
3888       else
3889         {
3890         while (next->next != NULL) next = next->next;
3891         next->next = addr_defer;
3892         addr_defer = addr;
3893         }
3894
3895       continue;
3896       }
3897
3898     /* Set a flag indicating whether there are further addresses that list
3899     the continued host. This tells the transport to leave the channel open,
3900     but not to pass it to another delivery process. */
3901
3902     for (next = addr_remote; next != NULL; next = next->next)
3903       {
3904       host_item *h;
3905       for (h = next->host_list; h != NULL; h = h->next)
3906         {
3907         if (Ustrcmp(h->name, continue_hostname) == 0)
3908           { continue_more = TRUE; break; }
3909         }
3910       }
3911     }
3912
3913   /* The transports set up the process info themselves as they may connect
3914   to more than one remote machine. They also have to set up the filter
3915   arguments, if required, so that the host name and address are available
3916   for expansion. */
3917
3918   transport_filter_argv = NULL;
3919
3920   /* Create the pipe for inter-process communication. If pipe creation
3921   fails, it is probably because the value of remote_max_parallel is so
3922   large that too many file descriptors for pipes have been created. Arrange
3923   to wait for a process to finish, and then try again. If we still can't
3924   create a pipe when all processes have finished, break the retry loop. */
3925
3926   while (!pipe_done)
3927     {
3928     if (pipe(pfd) == 0) pipe_done = TRUE;
3929       else if (parcount > 0) parmax = parcount;
3930         else break;
3931
3932     /* We need to make the reading end of the pipe non-blocking. There are
3933     two different options for this. Exim is cunningly (I hope!) coded so
3934     that it can use either of them, though it prefers O_NONBLOCK, which
3935     distinguishes between EOF and no-more-data. */
3936
3937     #ifdef O_NONBLOCK
3938     (void)fcntl(pfd[pipe_read], F_SETFL, O_NONBLOCK);
3939     #else
3940     (void)fcntl(pfd[pipe_read], F_SETFL, O_NDELAY);
3941     #endif
3942
3943     /* If the maximum number of subprocesses already exist, wait for a process
3944     to finish. If we ran out of file descriptors, parmax will have been reduced
3945     from its initial value of remote_max_parallel. */
3946
3947     par_reduce(parmax - 1, fallback);
3948     }
3949
3950   /* If we failed to create a pipe and there were no processes to wait
3951   for, we have to give up on this one. Do this outside the above loop
3952   so that we can continue the main loop. */
3953
3954   if (!pipe_done)
3955     {
3956     remote_post_process(addr, LOG_MAIN|LOG_PANIC,
3957       string_sprintf("unable to create pipe: %s", strerror(errno)), fallback);
3958     continue;
3959     }
3960
3961   /* Find a free slot in the pardata list. Must do this after the possible
3962   waiting for processes to finish, because a terminating process will free
3963   up a slot. */
3964
3965   for (poffset = 0; poffset < remote_max_parallel; poffset++)
3966     if (parlist[poffset].pid == 0) break;
3967
3968   /* If there isn't one, there has been a horrible disaster. */
3969
3970   if (poffset >= remote_max_parallel)
3971     {
3972     (void)close(pfd[pipe_write]);
3973     (void)close(pfd[pipe_read]);
3974     remote_post_process(addr, LOG_MAIN|LOG_PANIC,
3975       US"Unexpectedly no free subprocess slot", fallback);
3976     continue;
3977     }
3978
3979   /* Now fork a subprocess to do the remote delivery, but before doing so,
3980   ensure that any cached resourses are released so as not to interfere with
3981   what happens in the subprocess. */
3982
3983   search_tidyup();
3984
3985   if ((pid = fork()) == 0)
3986     {
3987     int fd = pfd[pipe_write];
3988     host_item *h;
3989
3990     /* Setting this global in the subprocess means we need never clear it */
3991     transport_name = tp->name;
3992
3993     /* There are weird circumstances in which logging is disabled */
3994     disable_logging = tp->disable_logging;
3995
3996     /* Show pids on debug output if parallelism possible */
3997
3998     if (parmax > 1 && (parcount > 0 || addr_remote != NULL))
3999       {
4000       DEBUG(D_any|D_v) debug_selector |= D_pid;
4001       DEBUG(D_deliver) debug_printf("Remote delivery process started\n");
4002       }
4003
4004     /* Reset the random number generator, so different processes don't all
4005     have the same sequence. In the test harness we want different, but
4006     predictable settings for each delivery process, so do something explicit
4007     here rather they rely on the fixed reset in the random number function. */
4008
4009     random_seed = running_in_test_harness? 42 + 2*delivery_count : 0;
4010
4011     /* Set close-on-exec on the pipe so that it doesn't get passed on to
4012     a new process that may be forked to do another delivery down the same
4013     SMTP connection. */
4014
4015     (void)fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
4016
4017     /* Close open file descriptors for the pipes of other processes
4018     that are running in parallel. */
4019
4020     for (poffset = 0; poffset < remote_max_parallel; poffset++)
4021       if (parlist[poffset].pid != 0) (void)close(parlist[poffset].fd);
4022
4023     /* This process has inherited a copy of the file descriptor
4024     for the data file, but its file pointer is shared with all the
4025     other processes running in parallel. Therefore, we have to re-open
4026     the file in order to get a new file descriptor with its own
4027     file pointer. We don't need to lock it, as the lock is held by
4028     the parent process. There doesn't seem to be any way of doing
4029     a dup-with-new-file-pointer. */
4030
4031     (void)close(deliver_datafile);
4032     sprintf(CS spoolname, "%s/input/%s/%s-D", spool_directory, message_subdir,
4033       message_id);
4034     deliver_datafile = Uopen(spoolname, O_RDWR | O_APPEND, 0);
4035
4036     if (deliver_datafile < 0)
4037       log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Failed to reopen %s for remote "
4038         "parallel delivery: %s", spoolname, strerror(errno));
4039
4040     /* Set the close-on-exec flag */
4041
4042     (void)fcntl(deliver_datafile, F_SETFD, fcntl(deliver_datafile, F_GETFD) |
4043       FD_CLOEXEC);
4044
4045     /* Set the uid/gid of this process; bombs out on failure. */
4046
4047     exim_setugid(uid, gid, use_initgroups,
4048       string_sprintf("remote delivery to %s with transport=%s",
4049         addr->address, tp->name));
4050
4051     /* Close the unwanted half of this process' pipe, set the process state,
4052     and run the transport. Afterwards, transport_count will contain the number
4053     of bytes written. */
4054
4055     (void)close(pfd[pipe_read]);
4056     set_process_info("delivering %s using %s", message_id, tp->name);
4057     debug_print_string(tp->debug_string);
4058     if (!(tp->info->code)(addr->transport, addr)) replicate_status(addr);
4059
4060     set_process_info("delivering %s (just run %s for %s%s in subprocess)",
4061       message_id, tp->name, addr->address, (addr->next == NULL)? "" : ", ...");
4062
4063     /* Ensure any cached resources that we used are now released */
4064
4065     search_tidyup();
4066
4067     /* Pass the result back down the pipe. This is a lot more information
4068     than is needed for a local delivery. We have to send back the error
4069     status for each address, the usability status for each host that is
4070     flagged as unusable, and all the retry items. When TLS is in use, we
4071     send also the cipher and peerdn information. Each type of information
4072     is flagged by an identifying byte, and is then in a fixed format (with
4073     strings terminated by zeros), and there is a final terminator at the
4074     end. The host information and retry information is all attached to
4075     the first address, so that gets sent at the start. */
4076
4077     /* Host unusability information: for most success cases this will
4078     be null. */
4079
4080     for (h = addr->host_list; h != NULL; h = h->next)
4081       {
4082       if (h->address == NULL || h->status < hstatus_unusable) continue;
4083       sprintf(CS big_buffer, "H%c%c%s", h->status, h->why, h->address);
4084       rmt_dlv_checked_write(fd, big_buffer, Ustrlen(big_buffer+3) + 4);
4085       }
4086
4087     /* The number of bytes written. This is the same for each address. Even
4088     if we sent several copies of the message down the same connection, the
4089     size of each one is the same, and it's that value we have got because
4090     transport_count gets reset before calling transport_write_message(). */
4091
4092     big_buffer[0] = 'S';
4093     memcpy(big_buffer+1, &transport_count, sizeof(transport_count));
4094     rmt_dlv_checked_write(fd, big_buffer, sizeof(transport_count) + 1);
4095
4096     /* Information about what happened to each address. Four item types are
4097     used: an optional 'X' item first, for TLS information, then an optional "C"
4098     item for any client-auth info followed by 'R' items for any retry settings,
4099     and finally an 'A' item for the remaining data. */
4100
4101     for(; addr != NULL; addr = addr->next)
4102       {
4103       uschar *ptr;
4104       retry_item *r;
4105
4106       /* The certificate verification status goes into the flags */
4107
4108       if (tls_out.certificate_verified) setflag(addr, af_cert_verified);
4109
4110       /* Use an X item only if there's something to send */
4111
4112       #ifdef SUPPORT_TLS
4113       if (addr->cipher)
4114         {
4115         ptr = big_buffer;
4116         sprintf(CS ptr, "X1%.128s", addr->cipher);
4117         while(*ptr++);
4118         if (!addr->peerdn)
4119           *ptr++ = 0;
4120         else
4121           {
4122           sprintf(CS ptr, "%.512s", addr->peerdn);
4123           while(*ptr++);
4124           }
4125
4126         rmt_dlv_checked_write(fd, big_buffer, ptr - big_buffer);
4127         }
4128       if (addr->peercert)
4129         {
4130         ptr = big_buffer;
4131         *ptr++ = 'X'; *ptr++ = '2';
4132         if (!tls_export_cert(ptr, big_buffer_size-2, addr->peercert))
4133           while(*ptr++);
4134         else
4135           *ptr++ = 0;
4136         rmt_dlv_checked_write(fd, big_buffer, ptr - big_buffer);
4137         }
4138       if (addr->ourcert)
4139         {
4140         ptr = big_buffer;
4141         *ptr++ = 'X'; *ptr++ = '3';
4142         if (!tls_export_cert(ptr, big_buffer_size-2, addr->ourcert))
4143           while(*ptr++);
4144         else
4145           *ptr++ = 0;
4146         rmt_dlv_checked_write(fd, big_buffer, ptr - big_buffer);
4147         }
4148       # ifdef EXPERIMENTAL_OCSP
4149       if (addr->ocsp > OCSP_NOT_REQ)
4150         {
4151         ptr = big_buffer;
4152         sprintf(CS ptr, "X4%c", addr->ocsp + '0');
4153         while(*ptr++);
4154         rmt_dlv_checked_write(fd, big_buffer, ptr - big_buffer);
4155         }
4156       # endif
4157       #endif    /*SUPPORT_TLS*/
4158
4159       if (client_authenticator)
4160         {
4161         ptr = big_buffer;
4162         sprintf(CS big_buffer, "C1%.64s", client_authenticator);
4163         while(*ptr++);
4164         rmt_dlv_checked_write(fd, big_buffer, ptr - big_buffer);
4165         }
4166       if (client_authenticated_id)
4167         {
4168         ptr = big_buffer;
4169         sprintf(CS big_buffer, "C2%.64s", client_authenticated_id);
4170         while(*ptr++);
4171         rmt_dlv_checked_write(fd, big_buffer, ptr - big_buffer);
4172         }
4173       if (client_authenticated_sender)
4174         {
4175         ptr = big_buffer;
4176         sprintf(CS big_buffer, "C3%.64s", client_authenticated_sender);
4177         while(*ptr++);
4178         rmt_dlv_checked_write(fd, big_buffer, ptr - big_buffer);
4179         }
4180
4181       #ifdef EXPERIMENTAL_PRDR
4182       if (addr->flags & af_prdr_used) rmt_dlv_checked_write(fd, "P", 1);
4183       #endif
4184
4185       /* Retry information: for most success cases this will be null. */
4186
4187       for (r = addr->retries; r != NULL; r = r->next)
4188         {
4189         uschar *ptr;
4190         sprintf(CS big_buffer, "R%c%.500s", r->flags, r->key);
4191         ptr = big_buffer + Ustrlen(big_buffer+2) + 3;
4192         memcpy(ptr, &(r->basic_errno), sizeof(r->basic_errno));
4193         ptr += sizeof(r->basic_errno);
4194         memcpy(ptr, &(r->more_errno), sizeof(r->more_errno));
4195         ptr += sizeof(r->more_errno);
4196         if (r->message == NULL) *ptr++ = 0; else
4197           {
4198           sprintf(CS ptr, "%.512s", r->message);
4199           while(*ptr++);
4200           }
4201         rmt_dlv_checked_write(fd, big_buffer, ptr - big_buffer);
4202         }
4203
4204       /* The rest of the information goes in an 'A' item. */
4205
4206       ptr = big_buffer + 3;
4207       sprintf(CS big_buffer, "A%c%c", addr->transport_return,
4208         addr->special_action);
4209       memcpy(ptr, &(addr->basic_errno), sizeof(addr->basic_errno));
4210       ptr += sizeof(addr->basic_errno);
4211       memcpy(ptr, &(addr->more_errno), sizeof(addr->more_errno));
4212       ptr += sizeof(addr->more_errno);
4213       memcpy(ptr, &(addr->flags), sizeof(addr->flags));
4214       ptr += sizeof(addr->flags);
4215
4216       if (addr->message == NULL) *ptr++ = 0; else
4217         {
4218         sprintf(CS ptr, "%.1024s", addr->message);
4219         while(*ptr++);
4220         }
4221
4222       if (addr->user_message == NULL) *ptr++ = 0; else
4223         {
4224         sprintf(CS ptr, "%.1024s", addr->user_message);
4225         while(*ptr++);
4226         }
4227
4228       if (addr->host_used == NULL) *ptr++ = 0; else
4229         {
4230         sprintf(CS ptr, "%.256s", addr->host_used->name);
4231         while(*ptr++);
4232         sprintf(CS ptr, "%.64s", addr->host_used->address);
4233         while(*ptr++);
4234         memcpy(ptr, &(addr->host_used->port), sizeof(addr->host_used->port));
4235         ptr += sizeof(addr->host_used->port);
4236         }
4237       rmt_dlv_checked_write(fd, big_buffer, ptr - big_buffer);
4238       }
4239
4240     /* Add termination flag, close the pipe, and that's it. The character
4241     after 'Z' indicates whether continue_transport is now NULL or not.
4242     A change from non-NULL to NULL indicates a problem with a continuing
4243     connection. */
4244
4245     big_buffer[0] = 'Z';
4246     big_buffer[1] = (continue_transport == NULL)? '0' : '1';
4247     rmt_dlv_checked_write(fd, big_buffer, 2);
4248     (void)close(fd);
4249     exit(EXIT_SUCCESS);
4250     }
4251
4252   /* Back in the mainline: close the unwanted half of the pipe. */
4253
4254   (void)close(pfd[pipe_write]);
4255
4256   /* Fork failed; defer with error message */
4257
4258   if (pid < 0)
4259     {
4260     (void)close(pfd[pipe_read]);
4261     remote_post_process(addr, LOG_MAIN|LOG_PANIC,
4262       string_sprintf("fork failed for remote delivery to %s: %s",
4263         addr->domain, strerror(errno)), fallback);
4264     continue;
4265     }
4266
4267   /* Fork succeeded; increment the count, and remember relevant data for
4268   when the process finishes. */
4269
4270   parcount++;
4271   parlist[poffset].addrlist = parlist[poffset].addr = addr;
4272   parlist[poffset].pid = pid;
4273   parlist[poffset].fd = pfd[pipe_read];
4274   parlist[poffset].done = FALSE;
4275   parlist[poffset].msg = NULL;
4276   parlist[poffset].return_path = return_path;
4277
4278   /* If the process we've just started is sending a message down an existing
4279   channel, wait for it now. This ensures that only one such process runs at
4280   once, whatever the value of remote_max parallel. Otherwise, we might try to
4281   send two or more messages simultaneously down the same channel. This could
4282   happen if there are different domains that include the same host in otherwise
4283   different host lists.
4284
4285   Also, if the transport closes down the channel, this information gets back
4286   (continue_transport gets set to NULL) before we consider any other addresses
4287   in this message. */
4288
4289   if (continue_transport != NULL) par_reduce(0, fallback);
4290
4291   /* Otherwise, if we are running in the test harness, wait a bit, to let the
4292   newly created process get going before we create another process. This should
4293   ensure repeatability in the tests. We only need to wait a tad. */
4294
4295   else if (running_in_test_harness) millisleep(500);
4296   }
4297
4298 /* Reached the end of the list of addresses. Wait for all the subprocesses that
4299 are still running and post-process their addresses. */
4300
4301 par_reduce(0, fallback);
4302 return TRUE;
4303 }
4304
4305
4306
4307
4308 /*************************************************
4309 *   Split an address into local part and domain  *
4310 *************************************************/
4311
4312 /* This function initializes an address for routing by splitting it up into a
4313 local part and a domain. The local part is set up twice - once in its original
4314 casing, and once in lower case, and it is dequoted. We also do the "percent
4315 hack" for configured domains. This may lead to a DEFER result if a lookup
4316 defers. When a percent-hacking takes place, we insert a copy of the original
4317 address as a new parent of this address, as if we have had a redirection.
4318
4319 Argument:
4320   addr      points to an addr_item block containing the address
4321
4322 Returns:    OK
4323             DEFER   - could not determine if domain is %-hackable
4324 */
4325
4326 int
4327 deliver_split_address(address_item *addr)
4328 {
4329 uschar *address = addr->address;
4330 uschar *domain = Ustrrchr(address, '@');
4331 uschar *t;
4332 int len = domain - address;
4333
4334 addr->domain = string_copylc(domain+1);    /* Domains are always caseless */
4335
4336 /* The implication in the RFCs (though I can't say I've seen it spelled out
4337 explicitly) is that quoting should be removed from local parts at the point
4338 where they are locally interpreted. [The new draft "821" is more explicit on
4339 this, Jan 1999.] We know the syntax is valid, so this can be done by simply
4340 removing quoting backslashes and any unquoted doublequotes. */
4341
4342 t = addr->cc_local_part = store_get(len+1);
4343 while(len-- > 0)
4344   {
4345   register int c = *address++;
4346   if (c == '\"') continue;
4347   if (c == '\\')
4348     {
4349     *t++ = *address++;
4350     len--;
4351     }
4352   else *t++ = c;
4353   }
4354 *t = 0;
4355
4356 /* We do the percent hack only for those domains that are listed in
4357 percent_hack_domains. A loop is required, to copy with multiple %-hacks. */
4358
4359 if (percent_hack_domains != NULL)
4360   {
4361   int rc;
4362   uschar *new_address = NULL;
4363   uschar *local_part = addr->cc_local_part;
4364
4365   deliver_domain = addr->domain;  /* set $domain */
4366
4367   while ((rc = match_isinlist(deliver_domain, &percent_hack_domains, 0,
4368            &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE, NULL))
4369              == OK &&
4370          (t = Ustrrchr(local_part, '%')) != NULL)
4371     {
4372     new_address = string_copy(local_part);
4373     new_address[t - local_part] = '@';
4374     deliver_domain = string_copylc(t+1);
4375     local_part = string_copyn(local_part, t - local_part);
4376     }
4377
4378   if (rc == DEFER) return DEFER;   /* lookup deferred */
4379
4380   /* If hackery happened, set up new parent and alter the current address. */
4381
4382   if (new_address != NULL)
4383     {
4384     address_item *new_parent = store_get(sizeof(address_item));
4385     *new_parent = *addr;
4386     addr->parent = new_parent;
4387     addr->address = new_address;
4388     addr->unique = string_copy(new_address);
4389     addr->domain = deliver_domain;
4390     addr->cc_local_part = local_part;
4391     DEBUG(D_deliver) debug_printf("%%-hack changed address to: %s\n",
4392       addr->address);
4393     }
4394   }
4395
4396 /* Create the lowercased version of the final local part, and make that the
4397 default one to be used. */
4398
4399 addr->local_part = addr->lc_local_part = string_copylc(addr->cc_local_part);
4400 return OK;
4401 }
4402
4403
4404
4405
4406 /*************************************************
4407 *      Get next error message text               *
4408 *************************************************/
4409
4410 /* If f is not NULL, read the next "paragraph", from a customized error message
4411 text file, terminated by a line containing ****, and expand it.
4412
4413 Arguments:
4414   f          NULL or a file to read from
4415   which      string indicating which string (for errors)
4416
4417 Returns:     NULL or an expanded string
4418 */
4419
4420 static uschar *
4421 next_emf(FILE *f, uschar *which)
4422 {
4423 int size = 256;
4424 int ptr = 0;
4425 uschar *para, *yield;
4426 uschar buffer[256];
4427
4428 if (f == NULL) return NULL;
4429
4430 if (Ufgets(buffer, sizeof(buffer), f) == NULL ||
4431     Ustrcmp(buffer, "****\n") == 0) return NULL;
4432
4433 para = store_get(size);
4434 for (;;)
4435   {
4436   para = string_cat(para, &size, &ptr, buffer, Ustrlen(buffer));
4437   if (Ufgets(buffer, sizeof(buffer), f) == NULL ||
4438       Ustrcmp(buffer, "****\n") == 0) break;
4439   }
4440 para[ptr] = 0;
4441
4442 yield = expand_string(para);
4443 if (yield != NULL) return yield;
4444
4445 log_write(0, LOG_MAIN|LOG_PANIC, "Failed to expand string from "
4446   "bounce_message_file or warn_message_file (%s): %s", which,
4447   expand_string_message);
4448 return NULL;
4449 }
4450
4451
4452
4453
4454 /*************************************************
4455 *      Close down a passed transport channel     *
4456 *************************************************/
4457
4458 /* This function is called when a passed transport channel cannot be used.
4459 It attempts to close it down tidily. The yield is always DELIVER_NOT_ATTEMPTED
4460 so that the function call can be the argument of a "return" statement.
4461
4462 Arguments:  None
4463 Returns:    DELIVER_NOT_ATTEMPTED
4464 */
4465
4466 static int
4467 continue_closedown(void)
4468 {
4469 if (continue_transport != NULL)
4470   {
4471   transport_instance *t;
4472   for (t = transports; t != NULL; t = t->next)
4473     {
4474     if (Ustrcmp(t->name, continue_transport) == 0)
4475       {
4476       if (t->info->closedown != NULL) (t->info->closedown)(t);
4477       break;
4478       }
4479     }
4480   }
4481 return DELIVER_NOT_ATTEMPTED;
4482 }
4483
4484
4485
4486
4487 /*************************************************
4488 *           Print address information            *
4489 *************************************************/
4490
4491 /* This function is called to output an address, or information about an
4492 address, for bounce or defer messages. If the hide_child flag is set, all we
4493 output is the original ancestor address.
4494
4495 Arguments:
4496   addr         points to the address
4497   f            the FILE to print to
4498   si           an initial string
4499   sc           a continuation string for before "generated"
4500   se           an end string
4501
4502 Returns:       TRUE if the address is not hidden
4503 */
4504
4505 static BOOL
4506 print_address_information(address_item *addr, FILE *f, uschar *si, uschar *sc,
4507   uschar *se)
4508 {
4509 BOOL yield = TRUE;
4510 uschar *printed = US"";
4511 address_item *ancestor = addr;
4512 while (ancestor->parent != NULL) ancestor = ancestor->parent;
4513
4514 fprintf(f, "%s", CS si);
4515
4516 if (addr->parent != NULL && testflag(addr, af_hide_child))
4517   {
4518   printed = US"an undisclosed address";
4519   yield = FALSE;
4520   }
4521 else if (!testflag(addr, af_pfr) || addr->parent == NULL)
4522   printed = addr->address;
4523
4524 else
4525   {
4526   uschar *s = addr->address;
4527   uschar *ss;
4528
4529   if (addr->address[0] == '>') { ss = US"mail"; s++; }
4530   else if (addr->address[0] == '|') ss = US"pipe";
4531   else ss = US"save";
4532
4533   fprintf(f, "%s to %s%sgenerated by ", ss, s, sc);
4534   printed = addr->parent->address;
4535   }
4536
4537 fprintf(f, "%s", CS string_printing(printed));
4538
4539 if (ancestor != addr)
4540   {
4541   uschar *original = (ancestor->onetime_parent == NULL)?
4542     ancestor->address : ancestor->onetime_parent;
4543   if (strcmpic(original, printed) != 0)
4544     fprintf(f, "%s(%sgenerated from %s)", sc,
4545       (ancestor != addr->parent)? "ultimately " : "",
4546       string_printing(original));
4547   }
4548
4549 fprintf(f, "%s", CS se);
4550 return yield;
4551 }
4552
4553
4554
4555
4556
4557 /*************************************************
4558 *         Print error for an address             *
4559 *************************************************/
4560
4561 /* This function is called to print the error information out of an address for
4562 a bounce or a warning message. It tries to format the message reasonably by
4563 introducing newlines. All lines are indented by 4; the initial printing
4564 position must be set before calling.
4565
4566 This function used always to print the error. Nowadays we want to restrict it
4567 to cases such as LMTP/SMTP errors from a remote host, and errors from :fail:
4568 and filter "fail". We no longer pass other information willy-nilly in bounce
4569 and warning messages. Text in user_message is always output; text in message
4570 only if the af_pass_message flag is set.
4571
4572 Arguments:
4573   addr         the address
4574   f            the FILE to print on
4575   t            some leading text
4576
4577 Returns:       nothing
4578 */
4579
4580 static void
4581 print_address_error(address_item *addr, FILE *f, uschar *t)
4582 {
4583 int count = Ustrlen(t);
4584 uschar *s = testflag(addr, af_pass_message)? addr->message : NULL;
4585
4586 if (s == NULL)
4587   {
4588   if (addr->user_message != NULL) s = addr->user_message; else return;
4589   }
4590
4591 fprintf(f, "\n    %s", t);
4592
4593 while (*s != 0)
4594   {
4595   if (*s == '\\' && s[1] == 'n')
4596     {
4597     fprintf(f, "\n    ");
4598     s += 2;
4599     count = 0;
4600     }
4601   else
4602     {
4603     fputc(*s, f);
4604     count++;
4605     if (*s++ == ':' && isspace(*s) && count > 45)
4606       {
4607       fprintf(f, "\n   ");  /* sic (because space follows) */
4608       count = 0;
4609       }
4610     }
4611   }
4612 }
4613
4614
4615
4616
4617
4618
4619 /*************************************************
4620 *     Check list of addresses for duplication    *
4621 *************************************************/
4622
4623 /* This function was introduced when the test for duplicate addresses that are
4624 not pipes, files, or autoreplies was moved from the middle of routing to when
4625 routing was complete. That was to fix obscure cases when the routing history
4626 affects the subsequent routing of identical addresses. This function is called
4627 after routing, to check that the final routed addresses are not duplicates.
4628
4629 If we detect a duplicate, we remember what it is a duplicate of. Note that
4630 pipe, file, and autoreply de-duplication is handled during routing, so we must
4631 leave such "addresses" alone here, as otherwise they will incorrectly be
4632 discarded.
4633
4634 Argument:     address of list anchor
4635 Returns:      nothing
4636 */
4637
4638 static void
4639 do_duplicate_check(address_item **anchor)
4640 {
4641 address_item *addr;
4642 while ((addr = *anchor) != NULL)
4643   {
4644   tree_node *tnode;
4645   if (testflag(addr, af_pfr))
4646     {
4647     anchor = &(addr->next);
4648     }
4649   else if ((tnode = tree_search(tree_duplicates, addr->unique)) != NULL)
4650     {
4651     DEBUG(D_deliver|D_route)
4652       debug_printf("%s is a duplicate address: discarded\n", addr->unique);
4653     *anchor = addr->next;
4654     addr->dupof = tnode->data.ptr;
4655     addr->next = addr_duplicate;
4656     addr_duplicate = addr;
4657     }
4658   else
4659     {
4660     tree_add_duplicate(addr->unique, addr);
4661     anchor = &(addr->next);
4662     }
4663   }
4664 }
4665
4666
4667
4668
4669 /*************************************************
4670 *              Deliver one message               *
4671 *************************************************/
4672
4673 /* This is the function which is called when a message is to be delivered. It
4674 is passed the id of the message. It is possible that the message no longer
4675 exists, if some other process has delivered it, and it is also possible that
4676 the message is being worked on by another process, in which case the data file
4677 will be locked.
4678
4679 If no delivery is attempted for any of the above reasons, the function returns
4680 DELIVER_NOT_ATTEMPTED.
4681
4682 If the give_up flag is set true, do not attempt any deliveries, but instead
4683 fail all outstanding addresses and return the message to the sender (or
4684 whoever).
4685
4686 A delivery operation has a process all to itself; we never deliver more than
4687 one message in the same process. Therefore we needn't worry too much about
4688 store leakage.
4689
4690 Arguments:
4691   id          the id of the message to be delivered
4692   forced      TRUE if delivery was forced by an administrator; this overrides
4693               retry delays and causes a delivery to be tried regardless
4694   give_up     TRUE if an administrator has requested that delivery attempts
4695               be abandoned
4696
4697 Returns:      When the global variable mua_wrapper is FALSE:
4698                 DELIVER_ATTEMPTED_NORMAL   if a delivery attempt was made
4699                 DELIVER_NOT_ATTEMPTED      otherwise (see comment above)
4700               When the global variable mua_wrapper is TRUE:
4701                 DELIVER_MUA_SUCCEEDED      if delivery succeeded
4702                 DELIVER_MUA_FAILED         if delivery failed
4703                 DELIVER_NOT_ATTEMPTED      if not attempted (should not occur)
4704 */
4705
4706 int
4707 deliver_message(uschar *id, BOOL forced, BOOL give_up)
4708 {
4709 int i, rc;
4710 int final_yield = DELIVER_ATTEMPTED_NORMAL;
4711 time_t now = time(NULL);
4712 address_item *addr_last = NULL;
4713 uschar *filter_message = NULL;
4714 FILE *jread;
4715 int process_recipients = RECIP_ACCEPT;
4716 open_db dbblock;
4717 open_db *dbm_file;
4718 extern int acl_where;
4719
4720 uschar *info = (queue_run_pid == (pid_t)0)?
4721   string_sprintf("delivering %s", id) :
4722   string_sprintf("delivering %s (queue run pid %d)", id, queue_run_pid);
4723
4724 /* If the D_process_info bit is on, set_process_info() will output debugging
4725 information. If not, we want to show this initial information if D_deliver or
4726 D_queue_run is set or in verbose mode. */
4727
4728 set_process_info("%s", info);
4729
4730 if ((debug_selector & D_process_info) == 0 &&
4731     (debug_selector & (D_deliver|D_queue_run|D_v)) != 0)
4732   debug_printf("%s\n", info);
4733
4734 /* Ensure that we catch any subprocesses that are created. Although Exim
4735 sets SIG_DFL as its initial default, some routes through the code end up
4736 here with it set to SIG_IGN - cases where a non-synchronous delivery process
4737 has been forked, but no re-exec has been done. We use sigaction rather than
4738 plain signal() on those OS where SA_NOCLDWAIT exists, because we want to be
4739 sure it is turned off. (There was a problem on AIX with this.) */
4740
4741 #ifdef SA_NOCLDWAIT
4742   {
4743   struct sigaction act;
4744   act.sa_handler = SIG_DFL;
4745   sigemptyset(&(act.sa_mask));
4746   act.sa_flags = 0;
4747   sigaction(SIGCHLD, &act, NULL);
4748   }
4749 #else
4750 signal(SIGCHLD, SIG_DFL);
4751 #endif
4752
4753 /* Make the forcing flag available for routers and transports, set up the
4754 global message id field, and initialize the count for returned files and the
4755 message size. This use of strcpy() is OK because the length id is checked when
4756 it is obtained from a command line (the -M or -q options), and otherwise it is
4757 known to be a valid message id. */
4758
4759 Ustrcpy(message_id, id);
4760 deliver_force = forced;
4761 return_count = 0;
4762 message_size = 0;
4763
4764 /* Initialize some flags */
4765
4766 update_spool = FALSE;
4767 remove_journal = TRUE;
4768
4769 /* Set a known context for any ACLs we call via expansions */
4770 acl_where = ACL_WHERE_DELIVERY;
4771
4772 /* Reset the random number generator, so that if several delivery processes are
4773 started from a queue runner that has already used random numbers (for sorting),
4774 they don't all get the same sequence. */
4775
4776 random_seed = 0;
4777
4778 /* Open and lock the message's data file. Exim locks on this one because the
4779 header file may get replaced as it is re-written during the delivery process.
4780 Any failures cause messages to be written to the log, except for missing files
4781 while queue running - another process probably completed delivery. As part of
4782 opening the data file, message_subdir gets set. */
4783
4784 if (!spool_open_datafile(id))
4785   return continue_closedown();  /* yields DELIVER_NOT_ATTEMPTED */
4786
4787 /* The value of message_size at this point has been set to the data length,
4788 plus one for the blank line that notionally precedes the data. */
4789
4790 /* Now read the contents of the header file, which will set up the headers in
4791 store, and also the list of recipients and the tree of non-recipients and
4792 assorted flags. It updates message_size. If there is a reading or format error,
4793 give up; if the message has been around for sufficiently long, remove it. */
4794
4795 sprintf(CS spoolname, "%s-H", id);
4796 if ((rc = spool_read_header(spoolname, TRUE, TRUE)) != spool_read_OK)
4797   {
4798   if (errno == ERRNO_SPOOLFORMAT)
4799     {
4800     struct stat statbuf;
4801     sprintf(CS big_buffer, "%s/input/%s/%s", spool_directory, message_subdir,
4802       spoolname);
4803     if (Ustat(big_buffer, &statbuf) == 0)
4804       log_write(0, LOG_MAIN, "Format error in spool file %s: "
4805         "size=" OFF_T_FMT, spoolname, statbuf.st_size);
4806     else log_write(0, LOG_MAIN, "Format error in spool file %s", spoolname);
4807     }
4808   else
4809     log_write(0, LOG_MAIN, "Error reading spool file %s: %s", spoolname,
4810       strerror(errno));
4811
4812   /* If we managed to read the envelope data, received_time contains the
4813   time the message was received. Otherwise, we can calculate it from the
4814   message id. */
4815
4816   if (rc != spool_read_hdrerror)
4817     {
4818     received_time = 0;
4819     for (i = 0; i < 6; i++)
4820       received_time = received_time * BASE_62 + tab62[id[i] - '0'];
4821     }
4822
4823   /* If we've had this malformed message too long, sling it. */
4824
4825   if (now - received_time > keep_malformed)
4826     {
4827     sprintf(CS spoolname, "%s/msglog/%s/%s", spool_directory, message_subdir, id);
4828     Uunlink(spoolname);
4829     sprintf(CS spoolname, "%s/input/%s/%s-D", spool_directory, message_subdir, id);
4830     Uunlink(spoolname);
4831     sprintf(CS spoolname, "%s/input/%s/%s-H", spool_directory, message_subdir, id);
4832     Uunlink(spoolname);
4833     sprintf(CS spoolname, "%s/input/%s/%s-J", spool_directory, message_subdir, id);
4834     Uunlink(spoolname);
4835     log_write(0, LOG_MAIN, "Message removed because older than %s",
4836       readconf_printtime(keep_malformed));
4837     }
4838
4839   (void)close(deliver_datafile);
4840   deliver_datafile = -1;
4841   return continue_closedown();   /* yields DELIVER_NOT_ATTEMPTED */
4842   }
4843
4844 /* The spool header file has been read. Look to see if there is an existing
4845 journal file for this message. If there is, it means that a previous delivery
4846 attempt crashed (program or host) before it could update the spool header file.
4847 Read the list of delivered addresses from the journal and add them to the
4848 nonrecipients tree. Then update the spool file. We can leave the journal in
4849 existence, as it will get further successful deliveries added to it in this
4850 run, and it will be deleted if this function gets to its end successfully.
4851 Otherwise it might be needed again. */
4852
4853 sprintf(CS spoolname, "%s/input/%s/%s-J", spool_directory, message_subdir, id);
4854 jread = Ufopen(spoolname, "rb");
4855 if (jread != NULL)
4856   {
4857   while (Ufgets(big_buffer, big_buffer_size, jread) != NULL)
4858     {
4859     int n = Ustrlen(big_buffer);
4860     big_buffer[n-1] = 0;
4861     tree_add_nonrecipient(big_buffer);
4862     DEBUG(D_deliver) debug_printf("Previously delivered address %s taken from "
4863       "journal file\n", big_buffer);
4864     }
4865   (void)fclose(jread);
4866   /* Panic-dies on error */
4867   (void)spool_write_header(message_id, SW_DELIVERING, NULL);
4868   }
4869 else if (errno != ENOENT)
4870   {
4871   log_write(0, LOG_MAIN|LOG_PANIC, "attempt to open journal for reading gave: "
4872     "%s", strerror(errno));
4873   return continue_closedown();   /* yields DELIVER_NOT_ATTEMPTED */
4874   }
4875
4876 /* A null recipients list indicates some kind of disaster. */
4877
4878 if (recipients_list == NULL)
4879   {
4880   (void)close(deliver_datafile);
4881   deliver_datafile = -1;
4882   log_write(0, LOG_MAIN, "Spool error: no recipients for %s", spoolname);
4883   return continue_closedown();   /* yields DELIVER_NOT_ATTEMPTED */
4884   }
4885
4886
4887 /* Handle a message that is frozen. There are a number of different things that
4888 can happen, but in the default situation, unless forced, no delivery is
4889 attempted. */
4890
4891 if (deliver_freeze)
4892   {
4893   #ifdef SUPPORT_MOVE_FROZEN_MESSAGES
4894   /* Moving to another directory removes the message from Exim's view. Other
4895   tools must be used to deal with it. Logging of this action happens in
4896   spool_move_message() and its subfunctions. */
4897
4898   if (move_frozen_messages &&
4899       spool_move_message(id, message_subdir, US"", US"F"))
4900     return continue_closedown();   /* yields DELIVER_NOT_ATTEMPTED */
4901   #endif
4902
4903   /* For all frozen messages (bounces or not), timeout_frozen_after sets the
4904   maximum time to keep messages that are frozen. Thaw if we reach it, with a
4905   flag causing all recipients to be failed. The time is the age of the
4906   message, not the time since freezing. */
4907
4908   if (timeout_frozen_after > 0 && message_age >= timeout_frozen_after)
4909     {
4910     log_write(0, LOG_MAIN, "cancelled by timeout_frozen_after");
4911     process_recipients = RECIP_FAIL_TIMEOUT;
4912     }
4913
4914   /* For bounce messages (and others with no sender), thaw if the error message
4915   ignore timer is exceeded. The message will be discarded if this delivery
4916   fails. */
4917
4918   else if (sender_address[0] == 0 && message_age >= ignore_bounce_errors_after)
4919     {
4920     log_write(0, LOG_MAIN, "Unfrozen by errmsg timer");
4921     }
4922
4923   /* If this is a bounce message, or there's no auto thaw, or we haven't
4924   reached the auto thaw time yet, and this delivery is not forced by an admin
4925   user, do not attempt delivery of this message. Note that forced is set for
4926   continuing messages down the same channel, in order to skip load checking and
4927   ignore hold domains, but we don't want unfreezing in that case. */
4928
4929   else
4930     {
4931     if ((sender_address[0] == 0 ||
4932          auto_thaw <= 0 ||
4933          now <= deliver_frozen_at + auto_thaw
4934         )
4935         &&
4936         (!forced || !deliver_force_thaw || !admin_user ||
4937           continue_hostname != NULL
4938         ))
4939       {
4940       (void)close(deliver_datafile);
4941       deliver_datafile = -1;
4942       log_write(L_skip_delivery, LOG_MAIN, "Message is frozen");
4943       return continue_closedown();   /* yields DELIVER_NOT_ATTEMPTED */
4944       }
4945
4946     /* If delivery was forced (by an admin user), assume a manual thaw.
4947     Otherwise it's an auto thaw. */
4948
4949     if (forced)
4950       {
4951       deliver_manual_thaw = TRUE;
4952       log_write(0, LOG_MAIN, "Unfrozen by forced delivery");
4953       }
4954     else log_write(0, LOG_MAIN, "Unfrozen by auto-thaw");
4955     }
4956
4957   /* We get here if any of the rules for unfreezing have triggered. */
4958
4959   deliver_freeze = FALSE;
4960   update_spool = TRUE;
4961   }
4962
4963
4964 /* Open the message log file if we are using them. This records details of
4965 deliveries, deferments, and failures for the benefit of the mail administrator.
4966 The log is not used by exim itself to track the progress of a message; that is
4967 done by rewriting the header spool file. */
4968
4969 if (message_logs)
4970   {
4971   uschar *error;
4972   int fd;
4973
4974   sprintf(CS spoolname, "%s/msglog/%s/%s", spool_directory, message_subdir, id);
4975   fd = open_msglog_file(spoolname, SPOOL_MODE, &error);
4976
4977   if (fd < 0)
4978     {
4979     log_write(0, LOG_MAIN|LOG_PANIC, "Couldn't %s message log %s: %s", error,
4980       spoolname, strerror(errno));
4981     return continue_closedown();   /* yields DELIVER_NOT_ATTEMPTED */
4982     }
4983
4984   /* Make a C stream out of it. */
4985
4986   message_log = fdopen(fd, "a");
4987   if (message_log == NULL)
4988     {
4989     log_write(0, LOG_MAIN|LOG_PANIC, "Couldn't fdopen message log %s: %s",
4990       spoolname, strerror(errno));
4991     return continue_closedown();   /* yields DELIVER_NOT_ATTEMPTED */
4992     }
4993   }
4994
4995
4996 /* If asked to give up on a message, log who did it, and set the action for all
4997 the addresses. */
4998
4999 if (give_up)
5000   {
5001   struct passwd *pw = getpwuid(real_uid);
5002   log_write(0, LOG_MAIN, "cancelled by %s", (pw != NULL)?
5003         US pw->pw_name : string_sprintf("uid %ld", (long int)real_uid));
5004   process_recipients = RECIP_FAIL;
5005   }
5006
5007 /* Otherwise, if there are too many Received: headers, fail all recipients. */
5008
5009 else if (received_count > received_headers_max)
5010   process_recipients = RECIP_FAIL_LOOP;
5011
5012 /* Otherwise, if a system-wide, address-independent message filter is
5013 specified, run it now, except in the case when we are failing all recipients as
5014 a result of timeout_frozen_after. If the system filter yields "delivered", then
5015 ignore the true recipients of the message. Failure of the filter file is
5016 logged, and the delivery attempt fails. */
5017
5018 else if (system_filter != NULL && process_recipients != RECIP_FAIL_TIMEOUT)
5019   {
5020   int rc;
5021   int filtertype;
5022   ugid_block ugid;
5023   redirect_block redirect;
5024
5025   if (system_filter_uid_set)
5026     {
5027     ugid.uid = system_filter_uid;
5028     ugid.gid = system_filter_gid;
5029     ugid.uid_set = ugid.gid_set = TRUE;
5030     }
5031   else
5032     {
5033     ugid.uid_set = ugid.gid_set = FALSE;
5034     }
5035
5036   return_path = sender_address;
5037   enable_dollar_recipients = TRUE;   /* Permit $recipients in system filter */
5038   system_filtering = TRUE;
5039
5040   /* Any error in the filter file causes a delivery to be abandoned. */
5041
5042   redirect.string = system_filter;
5043   redirect.isfile = TRUE;
5044   redirect.check_owner = redirect.check_group = FALSE;
5045   redirect.owners = NULL;
5046   redirect.owngroups = NULL;
5047   redirect.pw = NULL;
5048   redirect.modemask = 0;
5049
5050   DEBUG(D_deliver|D_filter) debug_printf("running system filter\n");
5051
5052   rc = rda_interpret(
5053     &redirect,              /* Where the data is */
5054     RDO_DEFER |             /* Turn on all the enabling options */
5055       RDO_FAIL |            /* Leave off all the disabling options */
5056       RDO_FILTER |
5057       RDO_FREEZE |
5058       RDO_REALLOG |
5059       RDO_REWRITE,
5060     NULL,                   /* No :include: restriction (not used in filter) */
5061     NULL,                   /* No sieve vacation directory (not sieve!) */
5062     NULL,                   /* No sieve enotify mailto owner (not sieve!) */
5063     NULL,                   /* No sieve user address (not sieve!) */
5064     NULL,                   /* No sieve subaddress (not sieve!) */
5065     &ugid,                  /* uid/gid data */
5066     &addr_new,              /* Where to hang generated addresses */
5067     &filter_message,        /* Where to put error message */
5068     NULL,                   /* Don't skip syntax errors */
5069     &filtertype,            /* Will always be set to FILTER_EXIM for this call */
5070     US"system filter");     /* For error messages */
5071
5072   DEBUG(D_deliver|D_filter) debug_printf("system filter returned %d\n", rc);
5073
5074   if (rc == FF_ERROR || rc == FF_NONEXIST)
5075     {
5076     (void)close(deliver_datafile);
5077     deliver_datafile = -1;
5078     log_write(0, LOG_MAIN|LOG_PANIC, "Error in system filter: %s",
5079       string_printing(filter_message));
5080     return continue_closedown();   /* yields DELIVER_NOT_ATTEMPTED */
5081     }
5082
5083   /* Reset things. If the filter message is an empty string, which can happen
5084   for a filter "fail" or "freeze" command with no text, reset it to NULL. */
5085
5086   system_filtering = FALSE;
5087   enable_dollar_recipients = FALSE;
5088   if (filter_message != NULL && filter_message[0] == 0) filter_message = NULL;
5089
5090   /* Save the values of the system filter variables so that user filters
5091   can use them. */
5092
5093   memcpy(filter_sn, filter_n, sizeof(filter_sn));
5094
5095   /* The filter can request that delivery of the original addresses be
5096   deferred. */
5097
5098   if (rc == FF_DEFER)
5099     {
5100     process_recipients = RECIP_DEFER;
5101     deliver_msglog("Delivery deferred by system filter\n");
5102     log_write(0, LOG_MAIN, "Delivery deferred by system filter");
5103     }
5104
5105   /* The filter can request that a message be frozen, but this does not
5106   take place if the message has been manually thawed. In that case, we must
5107   unset "delivered", which is forced by the "freeze" command to make -bF
5108   work properly. */
5109
5110   else if (rc == FF_FREEZE && !deliver_manual_thaw)
5111     {
5112     deliver_freeze = TRUE;
5113     deliver_frozen_at = time(NULL);
5114     process_recipients = RECIP_DEFER;
5115     frozen_info = string_sprintf(" by the system filter%s%s",
5116       (filter_message == NULL)? US"" : US": ",
5117       (filter_message == NULL)? US"" : filter_message);
5118     }
5119
5120   /* The filter can request that a message be failed. The error message may be
5121   quite long - it is sent back to the sender in the bounce - but we don't want
5122   to fill up the log with repetitions of it. If it starts with << then the text
5123   between << and >> is written to the log, with the rest left for the bounce
5124   message. */
5125
5126   else if (rc == FF_FAIL)
5127     {
5128     uschar *colon = US"";
5129     uschar *logmsg = US"";
5130     int loglen = 0;
5131
5132     process_recipients = RECIP_FAIL_FILTER;
5133
5134     if (filter_message != NULL)
5135       {
5136       uschar *logend;
5137       colon = US": ";
5138       if (filter_message[0] == '<' && filter_message[1] == '<' &&
5139           (logend = Ustrstr(filter_message, ">>")) != NULL)
5140         {
5141         logmsg = filter_message + 2;
5142         loglen = logend - logmsg;
5143         filter_message = logend + 2;
5144         if (filter_message[0] == 0) filter_message = NULL;
5145         }
5146       else
5147         {
5148         logmsg = filter_message;
5149         loglen = Ustrlen(filter_message);
5150         }
5151       }
5152
5153     log_write(0, LOG_MAIN, "cancelled by system filter%s%.*s", colon, loglen,
5154       logmsg);
5155     }
5156
5157   /* Delivery can be restricted only to those recipients (if any) that the
5158   filter specified. */
5159
5160   else if (rc == FF_DELIVERED)
5161     {
5162     process_recipients = RECIP_IGNORE;
5163     if (addr_new == NULL)
5164       log_write(0, LOG_MAIN, "=> discarded (system filter)");
5165     else
5166       log_write(0, LOG_MAIN, "original recipients ignored (system filter)");
5167     }
5168
5169   /* If any new addresses were created by the filter, fake up a "parent"
5170   for them. This is necessary for pipes, etc., which are expected to have
5171   parents, and it also gives some sensible logging for others. Allow
5172   pipes, files, and autoreplies, and run them as the filter uid if set,
5173   otherwise as the current uid. */
5174
5175   if (addr_new != NULL)
5176     {
5177     int uid = (system_filter_uid_set)? system_filter_uid : geteuid();
5178     int gid = (system_filter_gid_set)? system_filter_gid : getegid();
5179
5180     /* The text "system-filter" is tested in transport_set_up_command() and in
5181     set_up_shell_command() in the pipe transport, to enable them to permit
5182     $recipients, so don't change it here without also changing it there. */
5183
5184     address_item *p = addr_new;
5185     address_item *parent = deliver_make_addr(US"system-filter", FALSE);
5186
5187     parent->domain = string_copylc(qualify_domain_recipient);
5188     parent->local_part = US"system-filter";
5189
5190     /* As part of this loop, we arrange for addr_last to end up pointing
5191     at the final address. This is used if we go on to add addresses for the
5192     original recipients. */
5193
5194     while (p != NULL)
5195       {
5196       if (parent->child_count == SHRT_MAX)
5197         log_write(0, LOG_MAIN|LOG_PANIC_DIE, "system filter generated more "
5198           "than %d delivery addresses", SHRT_MAX);
5199       parent->child_count++;
5200       p->parent = parent;
5201
5202       if (testflag(p, af_pfr))
5203         {
5204         uschar *tpname;
5205         uschar *type;
5206         p->uid = uid;
5207         p->gid = gid;
5208         setflag(p, af_uid_set |
5209                    af_gid_set |
5210                    af_allow_file |
5211                    af_allow_pipe |
5212                    af_allow_reply);
5213
5214         /* Find the name of the system filter's appropriate pfr transport */
5215
5216         if (p->address[0] == '|')
5217           {
5218           type = US"pipe";
5219           tpname = system_filter_pipe_transport;
5220           address_pipe = p->address;
5221           }
5222         else if (p->address[0] == '>')
5223           {
5224           type = US"reply";
5225           tpname = system_filter_reply_transport;
5226           }
5227         else
5228           {
5229           if (p->address[Ustrlen(p->address)-1] == '/')
5230             {
5231             type = US"directory";
5232             tpname = system_filter_directory_transport;
5233             }
5234           else
5235             {
5236             type = US"file";
5237             tpname = system_filter_file_transport;
5238             }
5239           address_file = p->address;
5240           }
5241
5242         /* Now find the actual transport, first expanding the name. We have
5243         set address_file or address_pipe above. */
5244
5245         if (tpname != NULL)
5246           {
5247           uschar *tmp = expand_string(tpname);
5248           address_file = address_pipe = NULL;
5249           if (tmp == NULL)
5250             p->message = string_sprintf("failed to expand \"%s\" as a "
5251               "system filter transport name", tpname);
5252           tpname = tmp;
5253           }
5254         else
5255           {
5256           p->message = string_sprintf("system_filter_%s_transport is unset",
5257             type);
5258           }
5259
5260         if (tpname != NULL)
5261           {
5262           transport_instance *tp;
5263           for (tp = transports; tp != NULL; tp = tp->next)
5264             {
5265             if (Ustrcmp(tp->name, tpname) == 0)
5266               {
5267               p->transport = tp;
5268               break;
5269               }
5270             }
5271           if (tp == NULL)
5272             p->message = string_sprintf("failed to find \"%s\" transport "
5273               "for system filter delivery", tpname);
5274           }
5275
5276         /* If we couldn't set up a transport, defer the delivery, putting the
5277         error on the panic log as well as the main log. */
5278
5279         if (p->transport == NULL)
5280           {
5281           address_item *badp = p;
5282           p = p->next;
5283           if (addr_last == NULL) addr_new = p; else addr_last->next = p;
5284           badp->local_part = badp->address;   /* Needed for log line */
5285           post_process_one(badp, DEFER, LOG_MAIN|LOG_PANIC, DTYPE_ROUTER, 0);
5286           continue;
5287           }
5288         }    /* End of pfr handling */
5289
5290       /* Either a non-pfr delivery, or we found a transport */
5291
5292       DEBUG(D_deliver|D_filter)
5293         debug_printf("system filter added %s\n", p->address);
5294
5295       addr_last = p;
5296       p = p->next;
5297       }    /* Loop through all addr_new addresses */
5298     }
5299   }
5300
5301
5302 /* Scan the recipients list, and for every one that is not in the non-
5303 recipients tree, add an addr item to the chain of new addresses. If the pno
5304 value is non-negative, we must set the onetime parent from it. This which
5305 points to the relevant entry in the recipients list.
5306
5307 This processing can be altered by the setting of the process_recipients
5308 variable, which is changed if recipients are to be ignored, failed, or
5309 deferred. This can happen as a result of system filter activity, or if the -Mg
5310 option is used to fail all of them.
5311
5312 Duplicate addresses are handled later by a different tree structure; we can't
5313 just extend the non-recipients tree, because that will be re-written to the
5314 spool if the message is deferred, and in any case there are casing
5315 complications for local addresses. */
5316
5317 if (process_recipients != RECIP_IGNORE)
5318   {
5319   for (i = 0; i < recipients_count; i++)
5320     {
5321     if (tree_search(tree_nonrecipients, recipients_list[i].address) == NULL)
5322       {
5323       recipient_item *r = recipients_list + i;
5324       address_item *new = deliver_make_addr(r->address, FALSE);
5325       new->p.errors_address = r->errors_to;
5326
5327       if (r->pno >= 0)
5328         new->onetime_parent = recipients_list[r->pno].address;
5329
5330       switch (process_recipients)
5331         {
5332         /* RECIP_DEFER is set when a system filter freezes a message. */
5333
5334         case RECIP_DEFER:
5335         new->next = addr_defer;
5336         addr_defer = new;
5337         break;
5338
5339
5340         /* RECIP_FAIL_FILTER is set when a system filter has obeyed a "fail"
5341         command. */
5342
5343         case RECIP_FAIL_FILTER:
5344         new->message =
5345           (filter_message == NULL)? US"delivery cancelled" : filter_message;
5346         setflag(new, af_pass_message);
5347         goto RECIP_QUEUE_FAILED;   /* below */
5348
5349
5350         /* RECIP_FAIL_TIMEOUT is set when a message is frozen, but is older
5351         than the value in timeout_frozen_after. Treat non-bounce messages
5352         similarly to -Mg; for bounce messages we just want to discard, so
5353         don't put the address on the failed list. The timeout has already
5354         been logged. */
5355
5356         case RECIP_FAIL_TIMEOUT:
5357         new->message  = US"delivery cancelled; message timed out";
5358         goto RECIP_QUEUE_FAILED;   /* below */
5359
5360
5361         /* RECIP_FAIL is set when -Mg has been used. */
5362
5363         case RECIP_FAIL:
5364         new->message  = US"delivery cancelled by administrator";
5365         /* Fall through */
5366
5367         /* Common code for the failure cases above. If this is not a bounce
5368         message, put the address on the failed list so that it is used to
5369         create a bounce. Otherwise do nothing - this just discards the address.
5370         The incident has already been logged. */
5371
5372         RECIP_QUEUE_FAILED:
5373         if (sender_address[0] != 0)
5374           {
5375           new->next = addr_failed;
5376           addr_failed = new;
5377           }
5378         break;
5379
5380
5381         /* RECIP_FAIL_LOOP is set when there are too many Received: headers
5382         in the message. Process each address as a routing failure; if this
5383         is a bounce message, it will get frozen. */
5384
5385         case RECIP_FAIL_LOOP:
5386         new->message = US"Too many \"Received\" headers - suspected mail loop";
5387         post_process_one(new, FAIL, LOG_MAIN, DTYPE_ROUTER, 0);
5388         break;
5389
5390
5391         /* Value should be RECIP_ACCEPT; take this as the safe default. */
5392
5393         default:
5394         if (addr_new == NULL) addr_new = new; else addr_last->next = new;
5395         addr_last = new;
5396         break;
5397         }
5398       }
5399     }
5400   }
5401
5402 DEBUG(D_deliver)
5403   {
5404   address_item *p = addr_new;
5405   debug_printf("Delivery address list:\n");
5406   while (p != NULL)
5407     {
5408     debug_printf("  %s %s\n", p->address, (p->onetime_parent == NULL)? US"" :
5409       p->onetime_parent);
5410     p = p->next;
5411     }
5412   }
5413
5414 /* Set up the buffers used for copying over the file when delivering. */
5415
5416 deliver_in_buffer = store_malloc(DELIVER_IN_BUFFER_SIZE);
5417 deliver_out_buffer = store_malloc(DELIVER_OUT_BUFFER_SIZE);
5418
5419
5420
5421 /* Until there are no more new addresses, handle each one as follows:
5422
5423  . If this is a generated address (indicated by the presence of a parent
5424    pointer) then check to see whether it is a pipe, file, or autoreply, and
5425    if so, handle it directly here. The router that produced the address will
5426    have set the allow flags into the address, and also set the uid/gid required.
5427    Having the routers generate new addresses and then checking them here at
5428    the outer level is tidier than making each router do the checking, and
5429    means that routers don't need access to the failed address queue.
5430
5431  . Break up the address into local part and domain, and make lowercased
5432    versions of these strings. We also make unquoted versions of the local part.
5433
5434  . Handle the percent hack for those domains for which it is valid.
5435
5436  . For child addresses, determine if any of the parents have the same address.
5437    If so, generate a different string for previous delivery checking. Without
5438    this code, if the address spqr generates spqr via a forward or alias file,
5439    delivery of the generated spqr stops further attempts at the top level spqr,
5440    which is not what is wanted - it may have generated other addresses.
5441
5442  . Check on the retry database to see if routing was previously deferred, but
5443    only if in a queue run. Addresses that are to be routed are put on the
5444    addr_route chain. Addresses that are to be deferred are put on the
5445    addr_defer chain. We do all the checking first, so as not to keep the
5446    retry database open any longer than necessary.
5447
5448  . Now we run the addresses through the routers. A router may put the address
5449    on either the addr_local or the addr_remote chain for local or remote
5450    delivery, respectively, or put it on the addr_failed chain if it is
5451    undeliveable, or it may generate child addresses and put them on the
5452    addr_new chain, or it may defer an address. All the chain anchors are
5453    passed as arguments so that the routers can be called for verification
5454    purposes as well.
5455
5456  . If new addresses have been generated by the routers, da capo.
5457 */
5458
5459 header_rewritten = FALSE;          /* No headers rewritten yet */
5460 while (addr_new != NULL)           /* Loop until all addresses dealt with */
5461   {
5462   address_item *addr, *parent;
5463   dbm_file = dbfn_open(US"retry", O_RDONLY, &dbblock, FALSE);
5464
5465   /* Failure to open the retry database is treated the same as if it does
5466   not exist. In both cases, dbm_file is NULL. */
5467
5468   if (dbm_file == NULL)
5469     {
5470     DEBUG(D_deliver|D_retry|D_route|D_hints_lookup)
5471       debug_printf("no retry data available\n");
5472     }
5473
5474   /* Scan the current batch of new addresses, to handle pipes, files and
5475   autoreplies, and determine which others are ready for routing. */
5476
5477   while (addr_new != NULL)
5478     {
5479     int rc;
5480     uschar *p;
5481     tree_node *tnode;
5482     dbdata_retry *domain_retry_record;
5483     dbdata_retry *address_retry_record;
5484
5485     addr = addr_new;
5486     addr_new = addr->next;
5487
5488     DEBUG(D_deliver|D_retry|D_route)
5489       {
5490       debug_printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
5491       debug_printf("Considering: %s\n", addr->address);
5492       }
5493
5494     /* Handle generated address that is a pipe or a file or an autoreply. */
5495
5496     if (testflag(addr, af_pfr))
5497       {
5498       /* If an autoreply in a filter could not generate a syntactically valid
5499       address, give up forthwith. Set af_ignore_error so that we don't try to
5500       generate a bounce. */
5501
5502       if (testflag(addr, af_bad_reply))
5503         {
5504         addr->basic_errno = ERRNO_BADADDRESS2;
5505         addr->local_part = addr->address;
5506         addr->message =
5507           US"filter autoreply generated syntactically invalid recipient";
5508         setflag(addr, af_ignore_error);
5509         (void)post_process_one(addr, FAIL, LOG_MAIN, DTYPE_ROUTER, 0);
5510         continue;   /* with the next new address */
5511         }
5512
5513       /* If two different users specify delivery to the same pipe or file or
5514       autoreply, there should be two different deliveries, so build a unique
5515       string that incorporates the original address, and use this for
5516       duplicate testing and recording delivery, and also for retrying. */
5517
5518       addr->unique =
5519         string_sprintf("%s:%s", addr->address, addr->parent->unique +
5520           (testflag(addr->parent, af_homonym)? 3:0));
5521
5522       addr->address_retry_key = addr->domain_retry_key =
5523         string_sprintf("T:%s", addr->unique);
5524
5525       /* If a filter file specifies two deliveries to the same pipe or file,
5526       we want to de-duplicate, but this is probably not wanted for two mail
5527       commands to the same address, where probably both should be delivered.
5528       So, we have to invent a different unique string in that case. Just
5529       keep piling '>' characters on the front. */
5530
5531       if (addr->address[0] == '>')
5532         {
5533         while (tree_search(tree_duplicates, addr->unique) != NULL)
5534           addr->unique = string_sprintf(">%s", addr->unique);
5535         }
5536
5537       else if ((tnode = tree_search(tree_duplicates, addr->unique)) != NULL)
5538         {
5539         DEBUG(D_deliver|D_route)
5540           debug_printf("%s is a duplicate address: discarded\n", addr->address);
5541         addr->dupof = tnode->data.ptr;
5542         addr->next = addr_duplicate;
5543         addr_duplicate = addr;
5544         continue;
5545         }
5546
5547       DEBUG(D_deliver|D_route) debug_printf("unique = %s\n", addr->unique);
5548
5549       /* Check for previous delivery */
5550
5551       if (tree_search(tree_nonrecipients, addr->unique) != NULL)
5552         {
5553         DEBUG(D_deliver|D_route)
5554           debug_printf("%s was previously delivered: discarded\n", addr->address);
5555         child_done(addr, tod_stamp(tod_log));
5556         continue;
5557         }
5558
5559       /* Save for checking future duplicates */
5560
5561       tree_add_duplicate(addr->unique, addr);
5562
5563       /* Set local part and domain */
5564
5565       addr->local_part = addr->address;
5566       addr->domain = addr->parent->domain;
5567
5568       /* Ensure that the delivery is permitted. */
5569
5570       if (testflag(addr, af_file))
5571         {
5572         if (!testflag(addr, af_allow_file))
5573           {
5574           addr->basic_errno = ERRNO_FORBIDFILE;
5575           addr->message = US"delivery to file forbidden";
5576           (void)post_process_one(addr, FAIL, LOG_MAIN, DTYPE_ROUTER, 0);
5577           continue;   /* with the next new address */
5578           }
5579         }
5580       else if (addr->address[0] == '|')
5581         {
5582         if (!testflag(addr, af_allow_pipe))
5583           {
5584           addr->basic_errno = ERRNO_FORBIDPIPE;
5585           addr->message = US"delivery to pipe forbidden";
5586           (void)post_process_one(addr, FAIL, LOG_MAIN, DTYPE_ROUTER, 0);
5587           continue;   /* with the next new address */
5588           }
5589         }
5590       else if (!testflag(addr, af_allow_reply))
5591         {
5592         addr->basic_errno = ERRNO_FORBIDREPLY;
5593         addr->message = US"autoreply forbidden";
5594         (void)post_process_one(addr, FAIL, LOG_MAIN, DTYPE_ROUTER, 0);
5595         continue;     /* with the next new address */
5596         }
5597
5598       /* If the errno field is already set to BADTRANSPORT, it indicates
5599       failure to expand a transport string, or find the associated transport,
5600       or an unset transport when one is required. Leave this test till now so
5601       that the forbid errors are given in preference. */
5602
5603       if (addr->basic_errno == ERRNO_BADTRANSPORT)
5604         {
5605         (void)post_process_one(addr, DEFER, LOG_MAIN, DTYPE_ROUTER, 0);
5606         continue;
5607         }
5608
5609       /* Treat /dev/null as a special case and abandon the delivery. This
5610       avoids having to specify a uid on the transport just for this case.
5611       Arrange for the transport name to be logged as "**bypassed**". */
5612
5613       if (Ustrcmp(addr->address, "/dev/null") == 0)
5614         {
5615         uschar *save = addr->transport->name;
5616         addr->transport->name = US"**bypassed**";
5617         (void)post_process_one(addr, OK, LOG_MAIN, DTYPE_TRANSPORT, '=');
5618         addr->transport->name = save;
5619         continue;   /* with the next new address */
5620         }
5621
5622       /* Pipe, file, or autoreply delivery is to go ahead as a normal local
5623       delivery. */
5624
5625       DEBUG(D_deliver|D_route)
5626         debug_printf("queued for %s transport\n", addr->transport->name);
5627       addr->next = addr_local;
5628       addr_local = addr;
5629       continue;       /* with the next new address */
5630       }
5631
5632     /* Handle normal addresses. First, split up into local part and domain,
5633     handling the %-hack if necessary. There is the possibility of a defer from
5634     a lookup in percent_hack_domains. */
5635
5636     if ((rc = deliver_split_address(addr)) == DEFER)
5637       {
5638       addr->message = US"cannot check percent_hack_domains";
5639       addr->basic_errno = ERRNO_LISTDEFER;
5640       (void)post_process_one(addr, DEFER, LOG_MAIN, DTYPE_NONE, 0);
5641       continue;
5642       }
5643
5644     /* Check to see if the domain is held. If so, proceed only if the
5645     delivery was forced by hand. */
5646
5647     deliver_domain = addr->domain;  /* set $domain */
5648     if (!forced && hold_domains != NULL &&
5649          (rc = match_isinlist(addr->domain, &hold_domains, 0,
5650            &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE,
5651            NULL)) != FAIL)
5652       {
5653       if (rc == DEFER)
5654         {
5655         addr->message = US"hold_domains lookup deferred";
5656         addr->basic_errno = ERRNO_LISTDEFER;
5657         }
5658       else
5659         {
5660         addr->message = US"domain is held";
5661         addr->basic_errno = ERRNO_HELD;
5662         }
5663       (void)post_process_one(addr, DEFER, LOG_MAIN, DTYPE_NONE, 0);
5664       continue;
5665       }
5666
5667     /* Now we can check for duplicates and previously delivered addresses. In
5668     order to do this, we have to generate a "unique" value for each address,
5669     because there may be identical actual addresses in a line of descendents.
5670     The "unique" field is initialized to the same value as the "address" field,
5671     but gets changed here to cope with identically-named descendents. */
5672
5673     for (parent = addr->parent; parent != NULL; parent = parent->parent)
5674       if (strcmpic(addr->address, parent->address) == 0) break;
5675
5676     /* If there's an ancestor with the same name, set the homonym flag. This
5677     influences how deliveries are recorded. Then add a prefix on the front of
5678     the unique address. We use \n\ where n starts at 0 and increases each time.
5679     It is unlikely to pass 9, but if it does, it may look odd but will still
5680     work. This means that siblings or cousins with the same names are treated
5681     as duplicates, which is what we want. */
5682
5683     if (parent != NULL)
5684       {
5685       setflag(addr, af_homonym);
5686       if (parent->unique[0] != '\\')
5687         addr->unique = string_sprintf("\\0\\%s", addr->address);
5688       else
5689         addr->unique = string_sprintf("\\%c\\%s", parent->unique[1] + 1,
5690           addr->address);
5691       }
5692
5693     /* Ensure that the domain in the unique field is lower cased, because
5694     domains are always handled caselessly. */
5695
5696     p = Ustrrchr(addr->unique, '@');
5697     while (*p != 0) { *p = tolower(*p); p++; }
5698
5699     DEBUG(D_deliver|D_route) debug_printf("unique = %s\n", addr->unique);
5700
5701     if (tree_search(tree_nonrecipients, addr->unique) != NULL)
5702       {
5703       DEBUG(D_deliver|D_route)
5704         debug_printf("%s was previously delivered: discarded\n", addr->unique);
5705       child_done(addr, tod_stamp(tod_log));
5706       continue;
5707       }
5708
5709     /* Get the routing retry status, saving the two retry keys (with and
5710     without the local part) for subsequent use. If there is no retry record for
5711     the standard address routing retry key, we look for the same key with the
5712     sender attached, because this form is used by the smtp transport after a
5713     4xx response to RCPT when address_retry_include_sender is true. */
5714
5715     addr->domain_retry_key = string_sprintf("R:%s", addr->domain);
5716     addr->address_retry_key = string_sprintf("R:%s@%s", addr->local_part,
5717       addr->domain);
5718
5719     if (dbm_file == NULL)
5720       domain_retry_record = address_retry_record = NULL;
5721     else
5722       {
5723       domain_retry_record = dbfn_read(dbm_file, addr->domain_retry_key);
5724       if (domain_retry_record != NULL &&
5725           now - domain_retry_record->time_stamp > retry_data_expire)
5726         domain_retry_record = NULL;    /* Ignore if too old */
5727
5728       address_retry_record = dbfn_read(dbm_file, addr->address_retry_key);
5729       if (address_retry_record != NULL &&
5730           now - address_retry_record->time_stamp > retry_data_expire)
5731         address_retry_record = NULL;   /* Ignore if too old */
5732
5733       if (address_retry_record == NULL)
5734         {
5735         uschar *altkey = string_sprintf("%s:<%s>", addr->address_retry_key,
5736           sender_address);
5737         address_retry_record = dbfn_read(dbm_file, altkey);
5738         if (address_retry_record != NULL &&
5739             now - address_retry_record->time_stamp > retry_data_expire)
5740           address_retry_record = NULL;   /* Ignore if too old */
5741         }
5742       }
5743
5744     DEBUG(D_deliver|D_retry)
5745       {
5746       if (domain_retry_record == NULL)
5747         debug_printf("no domain retry record\n");
5748       if (address_retry_record == NULL)
5749         debug_printf("no address retry record\n");
5750       }
5751
5752     /* If we are sending a message down an existing SMTP connection, we must
5753     assume that the message which created the connection managed to route
5754     an address to that connection. We do not want to run the risk of taking
5755     a long time over routing here, because if we do, the server at the other
5756     end of the connection may time it out. This is especially true for messages
5757     with lots of addresses. For this kind of delivery, queue_running is not
5758     set, so we would normally route all addresses. We take a pragmatic approach
5759     and defer routing any addresses that have any kind of domain retry record.
5760     That is, we don't even look at their retry times. It doesn't matter if this
5761     doesn't work occasionally. This is all just an optimization, after all.
5762
5763     The reason for not doing the same for address retries is that they normally
5764     arise from 4xx responses, not DNS timeouts. */
5765
5766     if (continue_hostname != NULL && domain_retry_record != NULL)
5767       {
5768       addr->message = US"reusing SMTP connection skips previous routing defer";
5769       addr->basic_errno = ERRNO_RRETRY;
5770       (void)post_process_one(addr, DEFER, LOG_MAIN, DTYPE_ROUTER, 0);
5771       }
5772
5773     /* If we are in a queue run, defer routing unless there is no retry data or
5774     we've passed the next retry time, or this message is forced. In other
5775     words, ignore retry data when not in a queue run.
5776
5777     However, if the domain retry time has expired, always allow the routing
5778     attempt. If it fails again, the address will be failed. This ensures that
5779     each address is routed at least once, even after long-term routing
5780     failures.
5781
5782     If there is an address retry, check that too; just wait for the next
5783     retry time. This helps with the case when the temporary error on the
5784     address was really message-specific rather than address specific, since
5785     it allows other messages through.
5786
5787     We also wait for the next retry time if this is a message sent down an
5788     existing SMTP connection (even though that will be forced). Otherwise there
5789     will be far too many attempts for an address that gets a 4xx error. In
5790     fact, after such an error, we should not get here because, the host should
5791     not be remembered as one this message needs. However, there was a bug that
5792     used to cause this to  happen, so it is best to be on the safe side.
5793
5794     Even if we haven't reached the retry time in the hints, there is one more
5795     check to do, which is for the ultimate address timeout. We only do this
5796     check if there is an address retry record and there is not a domain retry
5797     record; this implies that previous attempts to handle the address had the
5798     retry_use_local_parts option turned on. We use this as an approximation
5799     for the destination being like a local delivery, for example delivery over
5800     LMTP to an IMAP message store. In this situation users are liable to bump
5801     into their quota and thereby have intermittently successful deliveries,
5802     which keep the retry record fresh, which can lead to us perpetually
5803     deferring messages. */
5804
5805     else if (((queue_running && !deliver_force) || continue_hostname != NULL)
5806             &&
5807             ((domain_retry_record != NULL &&
5808               now < domain_retry_record->next_try &&
5809               !domain_retry_record->expired)
5810             ||
5811             (address_retry_record != NULL &&
5812               now < address_retry_record->next_try))
5813             &&
5814             (domain_retry_record != NULL ||
5815              address_retry_record == NULL ||
5816              !retry_ultimate_address_timeout(addr->address_retry_key,
5817                addr->domain, address_retry_record, now)))
5818       {
5819       addr->message = US"retry time not reached";
5820       addr->basic_errno = ERRNO_RRETRY;
5821       (void)post_process_one(addr, DEFER, LOG_MAIN, DTYPE_ROUTER, 0);
5822       }
5823
5824     /* The domain is OK for routing. Remember if retry data exists so it
5825     can be cleaned up after a successful delivery. */
5826
5827     else
5828       {
5829       if (domain_retry_record != NULL || address_retry_record != NULL)
5830         setflag(addr, af_dr_retry_exists);
5831       addr->next = addr_route;
5832       addr_route = addr;
5833       DEBUG(D_deliver|D_route)
5834         debug_printf("%s: queued for routing\n", addr->address);
5835       }
5836     }
5837
5838   /* The database is closed while routing is actually happening. Requests to
5839   update it are put on a chain and all processed together at the end. */
5840
5841   if (dbm_file != NULL) dbfn_close(dbm_file);
5842
5843   /* If queue_domains is set, we don't even want to try routing addresses in
5844   those domains. During queue runs, queue_domains is forced to be unset.
5845   Optimize by skipping this pass through the addresses if nothing is set. */
5846
5847   if (!deliver_force && queue_domains != NULL)
5848     {
5849     address_item *okaddr = NULL;
5850     while (addr_route != NULL)
5851       {
5852       address_item *addr = addr_route;
5853       addr_route = addr->next;
5854
5855       deliver_domain = addr->domain;  /* set $domain */
5856       if ((rc = match_isinlist(addr->domain, &queue_domains, 0,
5857             &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE, NULL))
5858               != OK)
5859         {
5860         if (rc == DEFER)
5861           {
5862           addr->basic_errno = ERRNO_LISTDEFER;
5863           addr->message = US"queue_domains lookup deferred";
5864           (void)post_process_one(addr, DEFER, LOG_MAIN, DTYPE_ROUTER, 0);
5865           }
5866         else
5867           {
5868           addr->next = okaddr;
5869           okaddr = addr;
5870           }
5871         }
5872       else
5873         {
5874         addr->basic_errno = ERRNO_QUEUE_DOMAIN;
5875         addr->message = US"domain is in queue_domains";
5876         (void)post_process_one(addr, DEFER, LOG_MAIN, DTYPE_ROUTER, 0);
5877         }
5878       }
5879
5880     addr_route = okaddr;
5881     }
5882
5883   /* Now route those addresses that are not deferred. */
5884
5885   while (addr_route != NULL)
5886     {
5887     int rc;
5888     address_item *addr = addr_route;
5889     uschar *old_domain = addr->domain;
5890     uschar *old_unique = addr->unique;
5891     addr_route = addr->next;
5892     addr->next = NULL;
5893
5894     /* Just in case some router parameter refers to it. */
5895
5896     return_path = (addr->p.errors_address != NULL)?
5897       addr->p.errors_address : sender_address;
5898
5899     /* If a router defers an address, add a retry item. Whether or not to
5900     use the local part in the key is a property of the router. */
5901
5902     if ((rc = route_address(addr, &addr_local, &addr_remote, &addr_new,
5903          &addr_succeed, v_none)) == DEFER)
5904       retry_add_item(addr, (addr->router->retry_use_local_part)?
5905         string_sprintf("R:%s@%s", addr->local_part, addr->domain) :
5906         string_sprintf("R:%s", addr->domain), 0);
5907
5908     /* Otherwise, if there is an existing retry record in the database, add
5909     retry items to delete both forms. We must also allow for the possibility
5910     of a routing retry that includes the sender address. Since the domain might
5911     have been rewritten (expanded to fully qualified) as a result of routing,
5912     ensure that the rewritten form is also deleted. */
5913
5914     else if (testflag(addr, af_dr_retry_exists))
5915       {
5916       uschar *altkey = string_sprintf("%s:<%s>", addr->address_retry_key,
5917         sender_address);
5918       retry_add_item(addr, altkey, rf_delete);
5919       retry_add_item(addr, addr->address_retry_key, rf_delete);
5920       retry_add_item(addr, addr->domain_retry_key, rf_delete);
5921       if (Ustrcmp(addr->domain, old_domain) != 0)
5922         retry_add_item(addr, string_sprintf("R:%s", old_domain), rf_delete);
5923       }
5924
5925     /* DISCARD is given for :blackhole: and "seen finish". The event has been
5926     logged, but we need to ensure the address (and maybe parents) is marked
5927     done. */
5928
5929     if (rc == DISCARD)
5930       {
5931       address_done(addr, tod_stamp(tod_log));
5932       continue;  /* route next address */
5933       }
5934
5935     /* The address is finished with (failed or deferred). */
5936
5937     if (rc != OK)
5938       {
5939       (void)post_process_one(addr, rc, LOG_MAIN, DTYPE_ROUTER, 0);
5940       continue;  /* route next address */
5941       }
5942
5943     /* The address has been routed. If the router changed the domain, it will
5944     also have changed the unique address. We have to test whether this address
5945     has already been delivered, because it's the unique address that finally
5946     gets recorded. */
5947
5948     if (addr->unique != old_unique &&
5949         tree_search(tree_nonrecipients, addr->unique) != 0)
5950       {
5951       DEBUG(D_deliver|D_route) debug_printf("%s was previously delivered: "
5952         "discarded\n", addr->address);
5953       if (addr_remote == addr) addr_remote = addr->next;
5954       else if (addr_local == addr) addr_local = addr->next;
5955       }
5956
5957     /* If the router has same_domain_copy_routing set, we are permitted to copy
5958     the routing for any other addresses with the same domain. This is an
5959     optimisation to save repeated DNS lookups for "standard" remote domain
5960     routing. The option is settable only on routers that generate host lists.
5961     We play it very safe, and do the optimization only if the address is routed
5962     to a remote transport, there are no header changes, and the domain was not
5963     modified by the router. */
5964
5965     if (addr_remote == addr &&
5966         addr->router->same_domain_copy_routing &&
5967         addr->p.extra_headers == NULL &&
5968         addr->p.remove_headers == NULL &&
5969         old_domain == addr->domain)
5970       {
5971       address_item **chain = &addr_route;
5972       while (*chain != NULL)
5973         {
5974         address_item *addr2 = *chain;
5975         if (Ustrcmp(addr2->domain, addr->domain) != 0)
5976           {
5977           chain = &(addr2->next);
5978           continue;
5979           }
5980
5981         /* Found a suitable address; take it off the routing list and add it to
5982         the remote delivery list. */
5983
5984         *chain = addr2->next;
5985         addr2->next = addr_remote;
5986         addr_remote = addr2;
5987
5988         /* Copy the routing data */
5989
5990         addr2->domain = addr->domain;
5991         addr2->router = addr->router;
5992         addr2->transport = addr->transport;
5993         addr2->host_list = addr->host_list;
5994         addr2->fallback_hosts = addr->fallback_hosts;
5995         addr2->p.errors_address = addr->p.errors_address;
5996         copyflag(addr2, addr, af_hide_child | af_local_host_removed);
5997
5998         DEBUG(D_deliver|D_route)
5999           {
6000           debug_printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"
6001                        "routing %s\n"
6002                        "Routing for %s copied from %s\n",
6003             addr2->address, addr2->address, addr->address);
6004           }
6005         }
6006       }
6007     }  /* Continue with routing the next address. */
6008   }    /* Loop to process any child addresses that the routers created, and
6009           any rerouted addresses that got put back on the new chain. */
6010
6011
6012 /* Debugging: show the results of the routing */
6013
6014 DEBUG(D_deliver|D_retry|D_route)
6015   {
6016   address_item *p = addr_local;
6017   debug_printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
6018   debug_printf("After routing:\n  Local deliveries:\n");
6019   while (p != NULL)
6020     {
6021     debug_printf("    %s\n", p->address);
6022     p = p->next;
6023     }
6024
6025   p = addr_remote;
6026   debug_printf("  Remote deliveries:\n");
6027   while (p != NULL)
6028     {
6029     debug_printf("    %s\n", p->address);
6030     p = p->next;
6031     }
6032
6033   p = addr_failed;
6034   debug_printf("  Failed addresses:\n");
6035   while (p != NULL)
6036     {
6037     debug_printf("    %s\n", p->address);
6038     p = p->next;
6039     }
6040
6041   p = addr_defer;
6042   debug_printf("  Deferred addresses:\n");
6043   while (p != NULL)
6044     {
6045     debug_printf("    %s\n", p->address);
6046     p = p->next;
6047     }
6048   }
6049
6050 /* Free any resources that were cached during routing. */
6051
6052 search_tidyup();
6053 route_tidyup();
6054
6055 /* These two variables are set only during routing, after check_local_user.
6056 Ensure they are not set in transports. */
6057
6058 local_user_gid = (gid_t)(-1);
6059 local_user_uid = (uid_t)(-1);
6060
6061 /* Check for any duplicate addresses. This check is delayed until after
6062 routing, because the flexibility of the routing configuration means that
6063 identical addresses with different parentage may end up being redirected to
6064 different addresses. Checking for duplicates too early (as we previously used
6065 to) makes this kind of thing not work. */
6066
6067 do_duplicate_check(&addr_local);
6068 do_duplicate_check(&addr_remote);
6069
6070 /* When acting as an MUA wrapper, we proceed only if all addresses route to a
6071 remote transport. The check that they all end up in one transaction happens in
6072 the do_remote_deliveries() function. */
6073
6074 if (mua_wrapper && (addr_local != NULL || addr_failed != NULL ||
6075                     addr_defer != NULL))
6076   {
6077   address_item *addr;
6078   uschar *which, *colon, *msg;
6079
6080   if (addr_local != NULL)
6081     {
6082     addr = addr_local;
6083     which = US"local";
6084     }
6085   else if (addr_defer != NULL)
6086     {
6087     addr = addr_defer;
6088     which = US"deferred";
6089     }
6090   else
6091     {
6092     addr = addr_failed;
6093     which = US"failed";
6094     }
6095
6096   while (addr->parent != NULL) addr = addr->parent;
6097
6098   if (addr->message != NULL)
6099     {
6100     colon = US": ";
6101     msg = addr->message;
6102     }
6103   else colon = msg = US"";
6104
6105   /* We don't need to log here for a forced failure as it will already
6106   have been logged. Defer will also have been logged, but as a defer, so we do
6107   need to do the failure logging. */
6108
6109   if (addr != addr_failed)
6110     log_write(0, LOG_MAIN, "** %s routing yielded a %s delivery",
6111       addr->address, which);
6112
6113   /* Always write an error to the caller */
6114
6115   fprintf(stderr, "routing %s yielded a %s delivery%s%s\n", addr->address,
6116     which, colon, msg);
6117
6118   final_yield = DELIVER_MUA_FAILED;
6119   addr_failed = addr_defer = NULL;   /* So that we remove the message */
6120   goto DELIVERY_TIDYUP;
6121   }
6122
6123
6124 /* If this is a run to continue deliveries to an external channel that is
6125 already set up, defer any local deliveries. */
6126
6127 if (continue_transport != NULL)
6128   {
6129   if (addr_defer == NULL) addr_defer = addr_local; else
6130     {
6131     address_item *addr = addr_defer;
6132     while (addr->next != NULL) addr = addr->next;
6133     addr->next = addr_local;
6134     }
6135   addr_local = NULL;
6136   }
6137
6138
6139 /* Because address rewriting can happen in the routers, we should not really do
6140 ANY deliveries until all addresses have been routed, so that all recipients of
6141 the message get the same headers. However, this is in practice not always
6142 possible, since sometimes remote addresses give DNS timeouts for days on end.
6143 The pragmatic approach is to deliver what we can now, saving any rewritten
6144 headers so that at least the next lot of recipients benefit from the rewriting
6145 that has already been done.
6146
6147 If any headers have been rewritten during routing, update the spool file to
6148 remember them for all subsequent deliveries. This can be delayed till later if
6149 there is only address to be delivered - if it succeeds the spool write need not
6150 happen. */
6151
6152 if (header_rewritten &&
6153     ((addr_local != NULL &&
6154        (addr_local->next != NULL || addr_remote != NULL)) ||
6155      (addr_remote != NULL && addr_remote->next != NULL)))
6156   {
6157   /* Panic-dies on error */
6158   (void)spool_write_header(message_id, SW_DELIVERING, NULL);
6159   header_rewritten = FALSE;
6160   }
6161
6162
6163 /* If there are any deliveries to be done, open the journal file. This is used
6164 to record successful deliveries as soon as possible after each delivery is
6165 known to be complete. A file opened with O_APPEND is used so that several
6166 processes can run simultaneously.
6167
6168 The journal is just insurance against crashes. When the spool file is
6169 ultimately updated at the end of processing, the journal is deleted. If a
6170 journal is found to exist at the start of delivery, the addresses listed
6171 therein are added to the non-recipients. */
6172
6173 if (addr_local != NULL || addr_remote != NULL)
6174   {
6175   sprintf(CS spoolname, "%s/input/%s/%s-J", spool_directory, message_subdir, id);
6176   journal_fd = Uopen(spoolname, O_WRONLY|O_APPEND|O_CREAT, SPOOL_MODE);
6177
6178   if (journal_fd < 0)
6179     {
6180     log_write(0, LOG_MAIN|LOG_PANIC, "Couldn't open journal file %s: %s",
6181       spoolname, strerror(errno));
6182     return DELIVER_NOT_ATTEMPTED;
6183     }
6184
6185   /* Set the close-on-exec flag, make the file owned by Exim, and ensure
6186   that the mode is correct - the group setting doesn't always seem to get
6187   set automatically. */
6188
6189   if(  fcntl(journal_fd, F_SETFD, fcntl(journal_fd, F_GETFD) | FD_CLOEXEC)
6190     || fchown(journal_fd, exim_uid, exim_gid)
6191     || fchmod(journal_fd, SPOOL_MODE)
6192     )
6193     {
6194     int ret = Uunlink(spoolname);
6195     log_write(0, LOG_MAIN|LOG_PANIC, "Couldn't set perms on journal file %s: %s",
6196       spoolname, strerror(errno));
6197     if(ret  &&  errno != ENOENT)
6198       log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to unlink %s: %s",
6199         spoolname, strerror(errno));
6200     return DELIVER_NOT_ATTEMPTED;
6201     }
6202   }
6203
6204
6205
6206 /* Now we can get down to the business of actually doing deliveries. Local
6207 deliveries are done first, then remote ones. If ever the problems of how to
6208 handle fallback transports are figured out, this section can be put into a loop
6209 for handling fallbacks, though the uid switching will have to be revised. */
6210
6211 /* Precompile a regex that is used to recognize a parameter in response
6212 to an LHLO command, if is isn't already compiled. This may be used on both
6213 local and remote LMTP deliveries. */
6214
6215 if (regex_IGNOREQUOTA == NULL) regex_IGNOREQUOTA =
6216   regex_must_compile(US"\\n250[\\s\\-]IGNOREQUOTA(\\s|\\n|$)", FALSE, TRUE);
6217
6218 /* Handle local deliveries */
6219
6220 if (addr_local != NULL)
6221   {
6222   DEBUG(D_deliver|D_transport)
6223     debug_printf(">>>>>>>>>>>>>>>> Local deliveries >>>>>>>>>>>>>>>>\n");
6224   do_local_deliveries();
6225   disable_logging = FALSE;
6226   }
6227
6228 /* If queue_run_local is set, we do not want to attempt any remote deliveries,
6229 so just queue them all. */
6230
6231 if (queue_run_local)
6232   {
6233   while (addr_remote != NULL)
6234     {
6235     address_item *addr = addr_remote;
6236     addr_remote = addr->next;
6237     addr->next = NULL;
6238     addr->basic_errno = ERRNO_LOCAL_ONLY;
6239     addr->message = US"remote deliveries suppressed";
6240     (void)post_process_one(addr, DEFER, LOG_MAIN, DTYPE_TRANSPORT, 0);
6241     }
6242   }
6243
6244 /* Handle remote deliveries */
6245
6246 if (addr_remote != NULL)
6247   {
6248   DEBUG(D_deliver|D_transport)
6249     debug_printf(">>>>>>>>>>>>>>>> Remote deliveries >>>>>>>>>>>>>>>>\n");
6250
6251   /* Precompile some regex that are used to recognize parameters in response
6252   to an EHLO command, if they aren't already compiled. */
6253
6254   if (regex_PIPELINING == NULL) regex_PIPELINING =
6255     regex_must_compile(US"\\n250[\\s\\-]PIPELINING(\\s|\\n|$)", FALSE, TRUE);
6256
6257   if (regex_SIZE == NULL) regex_SIZE =
6258     regex_must_compile(US"\\n250[\\s\\-]SIZE(\\s|\\n|$)", FALSE, TRUE);
6259
6260   if (regex_AUTH == NULL) regex_AUTH =
6261     regex_must_compile(US"\\n250[\\s\\-]AUTH\\s+([\\-\\w\\s]+)(?:\\n|$)",
6262       FALSE, TRUE);
6263
6264   #ifdef SUPPORT_TLS
6265   if (regex_STARTTLS == NULL) regex_STARTTLS =
6266     regex_must_compile(US"\\n250[\\s\\-]STARTTLS(\\s|\\n|$)", FALSE, TRUE);
6267   #endif
6268
6269   #ifdef EXPERIMENTAL_PRDR
6270   if (regex_PRDR == NULL) regex_PRDR =
6271     regex_must_compile(US"\\n250[\\s\\-]PRDR(\\s|\\n|$)", FALSE, TRUE);
6272   #endif
6273
6274   /* Now sort the addresses if required, and do the deliveries. The yield of
6275   do_remote_deliveries is FALSE when mua_wrapper is set and all addresses
6276   cannot be delivered in one transaction. */
6277
6278   if (remote_sort_domains != NULL) sort_remote_deliveries();
6279   if (!do_remote_deliveries(FALSE))
6280     {
6281     log_write(0, LOG_MAIN, "** mua_wrapper is set but recipients cannot all "
6282       "be delivered in one transaction");
6283     fprintf(stderr, "delivery to smarthost failed (configuration problem)\n");
6284
6285     final_yield = DELIVER_MUA_FAILED;
6286     addr_failed = addr_defer = NULL;   /* So that we remove the message */
6287     goto DELIVERY_TIDYUP;
6288     }
6289
6290   /* See if any of the addresses that failed got put on the queue for delivery
6291   to their fallback hosts. We do it this way because often the same fallback
6292   host is used for many domains, so all can be sent in a single transaction
6293   (if appropriately configured). */
6294
6295   if (addr_fallback != NULL && !mua_wrapper)
6296     {
6297     DEBUG(D_deliver) debug_printf("Delivering to fallback hosts\n");
6298     addr_remote = addr_fallback;
6299     addr_fallback = NULL;
6300     if (remote_sort_domains != NULL) sort_remote_deliveries();
6301     do_remote_deliveries(TRUE);
6302     }
6303   disable_logging = FALSE;
6304   }
6305
6306
6307 /* All deliveries are now complete. Ignore SIGTERM during this tidying up
6308 phase, to minimize cases of half-done things. */
6309
6310 DEBUG(D_deliver)
6311   debug_printf(">>>>>>>>>>>>>>>> deliveries are done >>>>>>>>>>>>>>>>\n");
6312
6313 /* Root privilege is no longer needed */
6314
6315 exim_setugid(exim_uid, exim_gid, FALSE, US"post-delivery tidying");
6316
6317 set_process_info("tidying up after delivering %s", message_id);
6318 signal(SIGTERM, SIG_IGN);
6319
6320 /* When we are acting as an MUA wrapper, the smtp transport will either have
6321 succeeded for all addresses, or failed them all in normal cases. However, there
6322 are some setup situations (e.g. when a named port does not exist) that cause an
6323 immediate exit with deferral of all addresses. Convert those into failures. We
6324 do not ever want to retry, nor do we want to send a bounce message. */
6325
6326 if (mua_wrapper)
6327   {
6328   if (addr_defer != NULL)
6329     {
6330     address_item *addr, *nextaddr;
6331     for (addr = addr_defer; addr != NULL; addr = nextaddr)
6332       {
6333       log_write(0, LOG_MAIN, "** %s mua_wrapper forced failure for deferred "
6334         "delivery", addr->address);
6335       nextaddr = addr->next;
6336       addr->next = addr_failed;
6337       addr_failed = addr;
6338       }
6339     addr_defer = NULL;
6340     }
6341
6342   /* Now all should either have succeeded or failed. */
6343
6344   if (addr_failed == NULL) final_yield = DELIVER_MUA_SUCCEEDED; else
6345     {
6346     uschar *s = (addr_failed->user_message != NULL)?
6347       addr_failed->user_message : addr_failed->message;
6348
6349     fprintf(stderr, "Delivery failed: ");
6350     if (addr_failed->basic_errno > 0)
6351       {
6352       fprintf(stderr, "%s", strerror(addr_failed->basic_errno));
6353       if (s != NULL) fprintf(stderr, ": ");
6354       }
6355     if (s == NULL)
6356       {
6357       if (addr_failed->basic_errno <= 0) fprintf(stderr, "unknown error");
6358       }
6359     else fprintf(stderr, "%s", CS s);
6360     fprintf(stderr, "\n");
6361
6362     final_yield = DELIVER_MUA_FAILED;
6363     addr_failed = NULL;
6364     }
6365   }
6366
6367 /* In a normal configuration, we now update the retry database. This is done in
6368 one fell swoop at the end in order not to keep opening and closing (and
6369 locking) the database. The code for handling retries is hived off into a
6370 separate module for convenience. We pass it the addresses of the various
6371 chains, because deferred addresses can get moved onto the failed chain if the
6372 retry cutoff time has expired for all alternative destinations. Bypass the
6373 updating of the database if the -N flag is set, which is a debugging thing that
6374 prevents actual delivery. */
6375
6376 else if (!dont_deliver) retry_update(&addr_defer, &addr_failed, &addr_succeed);
6377
6378 /* If any addresses failed, we must send a message to somebody, unless
6379 af_ignore_error is set, in which case no action is taken. It is possible for
6380 several messages to get sent if there are addresses with different
6381 requirements. */
6382
6383 while (addr_failed != NULL)
6384   {
6385   pid_t pid;
6386   int fd;
6387   uschar *logtod = tod_stamp(tod_log);
6388   address_item *addr;
6389   address_item *handled_addr = NULL;
6390   address_item **paddr;
6391   address_item *msgchain = NULL;
6392   address_item **pmsgchain = &msgchain;
6393
6394   /* There are weird cases when logging is disabled in the transport. However,
6395   there may not be a transport (address failed by a router). */
6396
6397   disable_logging = FALSE;
6398   if (addr_failed->transport != NULL)
6399     disable_logging = addr_failed->transport->disable_logging;
6400
6401   DEBUG(D_deliver)
6402     debug_printf("processing failed address %s\n", addr_failed->address);
6403
6404   /* There are only two ways an address in a bounce message can get here:
6405
6406   (1) When delivery was initially deferred, but has now timed out (in the call
6407       to retry_update() above). We can detect this by testing for
6408       af_retry_timedout. If the address does not have its own errors address,
6409       we arrange to ignore the error.
6410
6411   (2) If delivery failures for bounce messages are being ignored. We can detect
6412       this by testing for af_ignore_error. This will also be set if a bounce
6413       message has been autothawed and the ignore_bounce_errors_after time has
6414       passed. It might also be set if a router was explicitly configured to
6415       ignore errors (errors_to = "").
6416
6417   If neither of these cases obtains, something has gone wrong. Log the
6418   incident, but then ignore the error. */
6419
6420   if (sender_address[0] == 0 && addr_failed->p.errors_address == NULL)
6421     {
6422     if (!testflag(addr_failed, af_retry_timedout) &&
6423         !testflag(addr_failed, af_ignore_error))
6424       {
6425       log_write(0, LOG_MAIN|LOG_PANIC, "internal error: bounce message "
6426         "failure is neither frozen nor ignored (it's been ignored)");
6427       }
6428     setflag(addr_failed, af_ignore_error);
6429     }
6430
6431   /* If the first address on the list has af_ignore_error set, just remove
6432   it from the list, throw away any saved message file, log it, and
6433   mark the recipient done. */
6434
6435   if (testflag(addr_failed, af_ignore_error))
6436     {
6437     addr = addr_failed;
6438     addr_failed = addr->next;
6439     if (addr->return_filename != NULL) Uunlink(addr->return_filename);
6440
6441     log_write(0, LOG_MAIN, "%s%s%s%s: error ignored",
6442       addr->address,
6443       (addr->parent == NULL)? US"" : US" <",
6444       (addr->parent == NULL)? US"" : addr->parent->address,
6445       (addr->parent == NULL)? US"" : US">");
6446
6447     address_done(addr, logtod);
6448     child_done(addr, logtod);
6449     /* Panic-dies on error */
6450     (void)spool_write_header(message_id, SW_DELIVERING, NULL);
6451     }
6452
6453   /* Otherwise, handle the sending of a message. Find the error address for
6454   the first address, then send a message that includes all failed addresses
6455   that have the same error address. Note the bounce_recipient is a global so
6456   that it can be accesssed by $bounce_recipient while creating a customized
6457   error message. */
6458
6459   else
6460     {
6461     bounce_recipient = (addr_failed->p.errors_address == NULL)?
6462       sender_address : addr_failed->p.errors_address;
6463
6464     /* Make a subprocess to send a message */
6465
6466     pid = child_open_exim(&fd);
6467
6468     /* Creation of child failed */
6469
6470     if (pid < 0)
6471       log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Process %d (parent %d) failed to "
6472         "create child process to send failure message: %s", getpid(),
6473         getppid(), strerror(errno));
6474
6475     /* Creation of child succeeded */
6476
6477     else
6478       {
6479       int ch, rc;
6480       int filecount = 0;
6481       int rcount = 0;
6482       uschar *bcc, *emf_text;
6483       FILE *f = fdopen(fd, "wb");
6484       FILE *emf = NULL;
6485       BOOL to_sender = strcmpic(sender_address, bounce_recipient) == 0;
6486       int max = (bounce_return_size_limit/DELIVER_IN_BUFFER_SIZE + 1) *
6487         DELIVER_IN_BUFFER_SIZE;
6488
6489       DEBUG(D_deliver)
6490         debug_printf("sending error message to: %s\n", bounce_recipient);
6491
6492       /* Scan the addresses for all that have the same errors address, removing
6493       them from the addr_failed chain, and putting them on msgchain. */
6494
6495       paddr = &addr_failed;
6496       for (addr = addr_failed; addr != NULL; addr = *paddr)
6497         {
6498         if (Ustrcmp(bounce_recipient, (addr->p.errors_address == NULL)?
6499               sender_address : addr->p.errors_address) != 0)
6500           {
6501           paddr = &(addr->next);      /* Not the same; skip */
6502           }
6503         else                          /* The same - dechain */
6504           {
6505           *paddr = addr->next;
6506           *pmsgchain = addr;
6507           addr->next = NULL;
6508           pmsgchain = &(addr->next);
6509           }
6510         }
6511
6512       /* Include X-Failed-Recipients: for automatic interpretation, but do
6513       not let any one header line get too long. We do this by starting a
6514       new header every 50 recipients. Omit any addresses for which the
6515       "hide_child" flag is set. */
6516
6517       for (addr = msgchain; addr != NULL; addr = addr->next)
6518         {
6519         if (testflag(addr, af_hide_child)) continue;
6520         if (rcount >= 50)
6521           {
6522           fprintf(f, "\n");
6523           rcount = 0;
6524           }
6525         fprintf(f, "%s%s",
6526           (rcount++ == 0)? "X-Failed-Recipients: " : ",\n  ",
6527           (testflag(addr, af_pfr) && addr->parent != NULL)?
6528             string_printing(addr->parent->address) :
6529             string_printing(addr->address));
6530         }
6531       if (rcount > 0) fprintf(f, "\n");
6532
6533       /* Output the standard headers */
6534
6535       if (errors_reply_to != NULL)
6536         fprintf(f, "Reply-To: %s\n", errors_reply_to);
6537       fprintf(f, "Auto-Submitted: auto-replied\n");
6538       moan_write_from(f);
6539       fprintf(f, "To: %s\n", bounce_recipient);
6540
6541       /* Open a template file if one is provided. Log failure to open, but
6542       carry on - default texts will be used. */
6543
6544       if (bounce_message_file != NULL)
6545         {
6546         emf = Ufopen(bounce_message_file, "rb");
6547         if (emf == NULL)
6548           log_write(0, LOG_MAIN|LOG_PANIC, "Failed to open %s for error "
6549             "message texts: %s", bounce_message_file, strerror(errno));
6550         }
6551
6552       /* Quietly copy to configured additional addresses if required. */
6553
6554       bcc = moan_check_errorcopy(bounce_recipient);
6555       if (bcc != NULL) fprintf(f, "Bcc: %s\n", bcc);
6556
6557       /* The texts for the message can be read from a template file; if there
6558       isn't one, or if it is too short, built-in texts are used. The first
6559       emf text is a Subject: and any other headers. */
6560
6561       emf_text = next_emf(emf, US"header");
6562       if (emf_text != NULL) fprintf(f, "%s\n", emf_text); else
6563         {
6564         fprintf(f, "Subject: Mail delivery failed%s\n\n",
6565           to_sender? ": returning message to sender" : "");
6566         }
6567
6568       emf_text = next_emf(emf, US"intro");
6569       if (emf_text != NULL) fprintf(f, "%s", CS emf_text); else
6570         {
6571         fprintf(f,
6572 /* This message has been reworded several times. It seems to be confusing to
6573 somebody, however it is worded. I have retreated to the original, simple
6574 wording. */
6575 "This message was created automatically by mail delivery software.\n");
6576         if (bounce_message_text != NULL) fprintf(f, "%s", CS bounce_message_text);
6577         if (to_sender)
6578           {
6579           fprintf(f,
6580 "\nA message that you sent could not be delivered to one or more of its\n"
6581 "recipients. This is a permanent error. The following address(es) failed:\n");
6582           }
6583         else
6584           {
6585           fprintf(f,
6586 "\nA message sent by\n\n  <%s>\n\n"
6587 "could not be delivered to one or more of its recipients. The following\n"
6588 "address(es) failed:\n", sender_address);
6589           }
6590         }
6591       fprintf(f, "\n");
6592
6593       /* Process the addresses, leaving them on the msgchain if they have a
6594       file name for a return message. (There has already been a check in
6595       post_process_one() for the existence of data in the message file.) A TRUE
6596       return from print_address_information() means that the address is not
6597       hidden. */
6598
6599       paddr = &msgchain;
6600       for (addr = msgchain; addr != NULL; addr = *paddr)
6601         {
6602         if (print_address_information(addr, f, US"  ", US"\n    ", US""))
6603           print_address_error(addr, f, US"");
6604
6605         /* End the final line for the address */
6606
6607         fputc('\n', f);
6608
6609         /* Leave on msgchain if there's a return file. */
6610
6611         if (addr->return_file >= 0)
6612           {
6613           paddr = &(addr->next);
6614           filecount++;
6615           }
6616
6617         /* Else save so that we can tick off the recipient when the
6618         message is sent. */
6619
6620         else
6621           {
6622           *paddr = addr->next;
6623           addr->next = handled_addr;
6624           handled_addr = addr;
6625           }
6626         }
6627
6628       fprintf(f, "\n");
6629
6630       /* Get the next text, whether we need it or not, so as to be
6631       positioned for the one after. */
6632
6633       emf_text = next_emf(emf, US"generated text");
6634
6635       /* If there were any file messages passed by the local transports,
6636       include them in the message. Then put the address on the handled chain.
6637       In the case of a batch of addresses that were all sent to the same
6638       transport, the return_file field in all of them will contain the same
6639       fd, and the return_filename field in the *last* one will be set (to the
6640       name of the file). */
6641
6642       if (msgchain != NULL)
6643         {
6644         address_item *nextaddr;
6645
6646         if (emf_text != NULL) fprintf(f, "%s", CS emf_text); else
6647           fprintf(f,
6648             "The following text was generated during the delivery "
6649             "attempt%s:\n", (filecount > 1)? "s" : "");
6650
6651         for (addr = msgchain; addr != NULL; addr = nextaddr)
6652           {
6653           FILE *fm;
6654           address_item *topaddr = addr;
6655
6656           /* List all the addresses that relate to this file */
6657
6658           fprintf(f, "\n");
6659           while(addr != NULL)                   /* Insurance */
6660             {
6661             print_address_information(addr, f, US"------ ",  US"\n       ",
6662               US" ------\n");
6663             if (addr->return_filename != NULL) break;
6664             addr = addr->next;
6665             }
6666           fprintf(f, "\n");
6667
6668           /* Now copy the file */
6669
6670           fm = Ufopen(addr->return_filename, "rb");
6671
6672           if (fm == NULL)
6673             fprintf(f, "    +++ Exim error... failed to open text file: %s\n",
6674               strerror(errno));
6675           else
6676             {
6677             while ((ch = fgetc(fm)) != EOF) fputc(ch, f);
6678             (void)fclose(fm);
6679             }
6680           Uunlink(addr->return_filename);
6681
6682           /* Can now add to handled chain, first fishing off the next
6683           address on the msgchain. */
6684
6685           nextaddr = addr->next;
6686           addr->next = handled_addr;
6687           handled_addr = topaddr;
6688           }
6689         fprintf(f, "\n");
6690         }
6691
6692       /* Now copy the message, trying to give an intelligible comment if
6693       it is too long for it all to be copied. The limit isn't strictly
6694       applied because of the buffering. There is, however, an option
6695       to suppress copying altogether. */
6696
6697       emf_text = next_emf(emf, US"copy");
6698
6699       if (bounce_return_message)
6700         {
6701         int topt = topt_add_return_path;
6702         if (!bounce_return_body) topt |= topt_no_body;
6703
6704         if (emf_text != NULL) fprintf(f, "%s", CS emf_text); else
6705           {
6706           if (bounce_return_body) fprintf(f,
6707 "------ This is a copy of the message, including all the headers. ------\n");
6708           else fprintf(f,
6709 "------ This is a copy of the message's headers. ------\n");
6710           }
6711
6712         /* While reading the "truncated" message, set return_size_limit to
6713         the actual max testing value, rounded. We need to read the message
6714         whether we are going to use it or not. */
6715
6716           {
6717           int temp = bounce_return_size_limit;
6718           bounce_return_size_limit = (max/1000)*1000;
6719           emf_text = next_emf(emf, US"truncated");
6720           bounce_return_size_limit = temp;
6721           }
6722
6723         if (bounce_return_body && bounce_return_size_limit > 0)
6724           {
6725           struct stat statbuf;
6726           if (fstat(deliver_datafile, &statbuf) == 0 && statbuf.st_size > max)
6727             {
6728             if (emf_text != NULL) fprintf(f, "%s", CS emf_text); else
6729               {
6730               fprintf(f,
6731 "------ The body of the message is " OFF_T_FMT " characters long; only the first\n"
6732 "------ %d or so are included here.\n", statbuf.st_size, max);
6733               }
6734             }
6735           }
6736
6737         fprintf(f, "\n");
6738         fflush(f);
6739         transport_filter_argv = NULL;   /* Just in case */
6740         return_path = sender_address;   /* In case not previously set */
6741         transport_write_message(NULL, fileno(f), topt,
6742           bounce_return_size_limit, NULL, NULL, NULL, NULL, NULL, 0);
6743         }
6744
6745       /* Write final text and close the template file if one is open */
6746
6747       if (emf != NULL)
6748         {
6749         emf_text = next_emf(emf, US"final");
6750         if (emf_text != NULL) fprintf(f, "%s", CS emf_text);
6751         (void)fclose(emf);
6752         }
6753
6754       /* Close the file, which should send an EOF to the child process
6755       that is receiving the message. Wait for it to finish. */
6756
6757       (void)fclose(f);
6758       rc = child_close(pid, 0);     /* Waits for child to close, no timeout */
6759
6760       /* In the test harness, let the child do it's thing first. */
6761
6762       if (running_in_test_harness) millisleep(500);
6763
6764       /* If the process failed, there was some disaster in setting up the
6765       error message. Unless the message is very old, ensure that addr_defer
6766       is non-null, which will have the effect of leaving the message on the
6767       spool. The failed addresses will get tried again next time. However, we
6768       don't really want this to happen too often, so freeze the message unless
6769       there are some genuine deferred addresses to try. To do this we have
6770       to call spool_write_header() here, because with no genuine deferred
6771       addresses the normal code below doesn't get run. */
6772
6773       if (rc != 0)
6774         {
6775         uschar *s = US"";
6776         if (now - received_time < retry_maximum_timeout && addr_defer == NULL)
6777           {
6778           addr_defer = (address_item *)(+1);
6779           deliver_freeze = TRUE;
6780           deliver_frozen_at = time(NULL);
6781           /* Panic-dies on error */
6782           (void)spool_write_header(message_id, SW_DELIVERING, NULL);
6783           s = US" (frozen)";
6784           }
6785         deliver_msglog("Process failed (%d) when writing error message "
6786           "to %s%s", rc, bounce_recipient, s);
6787         log_write(0, LOG_MAIN, "Process failed (%d) when writing error message "
6788           "to %s%s", rc, bounce_recipient, s);
6789         }
6790
6791       /* The message succeeded. Ensure that the recipients that failed are
6792       now marked finished with on the spool and their parents updated. */
6793
6794       else
6795         {
6796         for (addr = handled_addr; addr != NULL; addr = addr->next)
6797           {
6798           address_done(addr, logtod);
6799           child_done(addr, logtod);
6800           }
6801         /* Panic-dies on error */
6802         (void)spool_write_header(message_id, SW_DELIVERING, NULL);
6803         }
6804       }
6805     }
6806   }
6807
6808 disable_logging = FALSE;  /* In case left set */
6809
6810 /* Come here from the mua_wrapper case if routing goes wrong */
6811
6812 DELIVERY_TIDYUP:
6813
6814 /* If there are now no deferred addresses, we are done. Preserve the
6815 message log if so configured, and we are using them. Otherwise, sling it.
6816 Then delete the message itself. */
6817
6818 if (addr_defer == NULL)
6819   {
6820   if (message_logs)
6821     {
6822     sprintf(CS spoolname, "%s/msglog/%s/%s", spool_directory, message_subdir,
6823       id);
6824     if (preserve_message_logs)
6825       {
6826       int rc;
6827       sprintf(CS big_buffer, "%s/msglog.OLD/%s", spool_directory, id);
6828       if ((rc = Urename(spoolname, big_buffer)) < 0)
6829         {
6830         (void)directory_make(spool_directory, US"msglog.OLD",
6831           MSGLOG_DIRECTORY_MODE, TRUE);
6832         rc = Urename(spoolname, big_buffer);
6833         }
6834       if (rc < 0)
6835         log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to move %s to the "
6836           "msglog.OLD directory", spoolname);
6837       }
6838     else
6839       {
6840       if (Uunlink(spoolname) < 0)
6841         log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to unlink %s: %s",
6842                   spoolname, strerror(errno));
6843       }
6844     }
6845
6846   /* Remove the two message files. */
6847
6848   sprintf(CS spoolname, "%s/input/%s/%s-D", spool_directory, message_subdir, id);
6849   if (Uunlink(spoolname) < 0)
6850     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to unlink %s: %s",
6851       spoolname, strerror(errno));
6852   sprintf(CS spoolname, "%s/input/%s/%s-H", spool_directory, message_subdir, id);
6853   if (Uunlink(spoolname) < 0)
6854     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to unlink %s: %s",
6855       spoolname, strerror(errno));
6856
6857   /* Log the end of this message, with queue time if requested. */
6858
6859   if ((log_extra_selector & LX_queue_time_overall) != 0)
6860     log_write(0, LOG_MAIN, "Completed QT=%s",
6861       readconf_printtime(time(NULL) - received_time));
6862   else
6863     log_write(0, LOG_MAIN, "Completed");
6864
6865   /* Unset deliver_freeze so that we won't try to move the spool files further down */
6866   deliver_freeze = FALSE;
6867   }
6868
6869 /* If there are deferred addresses, we are keeping this message because it is
6870 not yet completed. Lose any temporary files that were catching output from
6871 pipes for any of the deferred addresses, handle one-time aliases, and see if
6872 the message has been on the queue for so long that it is time to send a warning
6873 message to the sender, unless it is a mailer-daemon. If all deferred addresses
6874 have the same domain, we can set deliver_domain for the expansion of
6875 delay_warning_ condition - if any of them are pipes, files, or autoreplies, use
6876 the parent's domain.
6877
6878 If all the deferred addresses have an error number that indicates "retry time
6879 not reached", skip sending the warning message, because it won't contain the
6880 reason for the delay. It will get sent at the next real delivery attempt.
6881 However, if at least one address has tried, we'd better include all of them in
6882 the message.
6883
6884 If we can't make a process to send the message, don't worry.
6885
6886 For mailing list expansions we want to send the warning message to the
6887 mailing list manager. We can't do a perfect job here, as some addresses may
6888 have different errors addresses, but if we take the errors address from
6889 each deferred address it will probably be right in most cases.
6890
6891 If addr_defer == +1, it means there was a problem sending an error message
6892 for failed addresses, and there were no "real" deferred addresses. The value
6893 was set just to keep the message on the spool, so there is nothing to do here.
6894 */
6895
6896 else if (addr_defer != (address_item *)(+1))
6897   {
6898   address_item *addr;
6899   uschar *recipients = US"";
6900   BOOL delivery_attempted = FALSE;
6901
6902   deliver_domain = testflag(addr_defer, af_pfr)?
6903     addr_defer->parent->domain : addr_defer->domain;
6904
6905   for (addr = addr_defer; addr != NULL; addr = addr->next)
6906     {
6907     address_item *otaddr;
6908
6909     if (addr->basic_errno > ERRNO_RETRY_BASE) delivery_attempted = TRUE;
6910
6911     if (deliver_domain != NULL)
6912       {
6913       uschar *d = (testflag(addr, af_pfr))? addr->parent->domain : addr->domain;
6914
6915       /* The domain may be unset for an address that has never been routed
6916       because the system filter froze the message. */
6917
6918       if (d == NULL || Ustrcmp(d, deliver_domain) != 0) deliver_domain = NULL;
6919       }
6920
6921     if (addr->return_filename != NULL) Uunlink(addr->return_filename);
6922
6923     /* Handle the case of one-time aliases. If any address in the ancestry
6924     of this one is flagged, ensure it is in the recipients list, suitably
6925     flagged, and that its parent is marked delivered. */
6926
6927     for (otaddr = addr; otaddr != NULL; otaddr = otaddr->parent)
6928       if (otaddr->onetime_parent != NULL) break;
6929
6930     if (otaddr != NULL)
6931       {
6932       int i;
6933       int t = recipients_count;
6934
6935       for (i = 0; i < recipients_count; i++)
6936         {
6937         uschar *r = recipients_list[i].address;
6938         if (Ustrcmp(otaddr->onetime_parent, r) == 0) t = i;
6939         if (Ustrcmp(otaddr->address, r) == 0) break;
6940         }
6941
6942       /* Didn't find the address already in the list, and did find the
6943       ultimate parent's address in the list. After adding the recipient,
6944       update the errors address in the recipients list. */
6945
6946       if (i >= recipients_count && t < recipients_count)
6947         {
6948         DEBUG(D_deliver) debug_printf("one_time: adding %s in place of %s\n",
6949           otaddr->address, otaddr->parent->address);
6950         receive_add_recipient(otaddr->address, t);
6951         recipients_list[recipients_count-1].errors_to = otaddr->p.errors_address;
6952         tree_add_nonrecipient(otaddr->parent->address);
6953         update_spool = TRUE;
6954         }
6955       }
6956
6957     /* Except for error messages, ensure that either the errors address for
6958     this deferred address or, if there is none, the sender address, is on the
6959     list of recipients for a warning message. */
6960
6961     if (sender_address[0] != 0)
6962       {
6963       if (addr->p.errors_address == NULL)
6964         {
6965         if (Ustrstr(recipients, sender_address) == NULL)
6966           recipients = string_sprintf("%s%s%s", recipients,
6967             (recipients[0] == 0)? "" : ",", sender_address);
6968         }
6969       else
6970         {
6971         if (Ustrstr(recipients, addr->p.errors_address) == NULL)
6972           recipients = string_sprintf("%s%s%s", recipients,
6973             (recipients[0] == 0)? "" : ",", addr->p.errors_address);
6974         }
6975       }
6976     }
6977
6978   /* Send a warning message if the conditions are right. If the condition check
6979   fails because of a lookup defer, there is nothing we can do. The warning
6980   is not sent. Another attempt will be made at the next delivery attempt (if
6981   it also defers). */
6982
6983   if (!queue_2stage && delivery_attempted &&
6984       delay_warning[1] > 0 && sender_address[0] != 0 &&
6985        (delay_warning_condition == NULL ||
6986           expand_check_condition(delay_warning_condition,
6987             US"delay_warning", US"option")))
6988     {
6989     int count;
6990     int show_time;
6991     int queue_time = time(NULL) - received_time;
6992
6993     /* When running in the test harness, there's an option that allows us to
6994     fudge this time so as to get repeatability of the tests. Take the first
6995     time off the list. In queue runs, the list pointer gets updated in the
6996     calling process. */
6997
6998     if (running_in_test_harness && fudged_queue_times[0] != 0)
6999       {
7000       int qt = readconf_readtime(fudged_queue_times, '/', FALSE);
7001       if (qt >= 0)
7002         {
7003         DEBUG(D_deliver) debug_printf("fudged queue_times = %s\n",
7004           fudged_queue_times);
7005         queue_time = qt;
7006         }
7007       }
7008
7009     /* See how many warnings we should have sent by now */
7010
7011     for (count = 0; count < delay_warning[1]; count++)
7012       if (queue_time < delay_warning[count+2]) break;
7013
7014     show_time = delay_warning[count+1];
7015
7016     if (count >= delay_warning[1])
7017       {
7018       int extra;
7019       int last_gap = show_time;
7020       if (count > 1) last_gap -= delay_warning[count];
7021       extra = (queue_time - delay_warning[count+1])/last_gap;
7022       show_time += last_gap * extra;
7023       count += extra;
7024       }
7025
7026     DEBUG(D_deliver)
7027       {
7028       debug_printf("time on queue = %s\n", readconf_printtime(queue_time));
7029       debug_printf("warning counts: required %d done %d\n", count,
7030         warning_count);
7031       }
7032
7033     /* We have computed the number of warnings there should have been by now.
7034     If there haven't been enough, send one, and up the count to what it should
7035     have been. */
7036
7037     if (warning_count < count)
7038       {
7039       header_line *h;
7040       int fd;
7041       pid_t pid = child_open_exim(&fd);
7042
7043       if (pid > 0)
7044         {
7045         uschar *wmf_text;
7046         FILE *wmf = NULL;
7047         FILE *f = fdopen(fd, "wb");
7048
7049         if (warn_message_file != NULL)
7050           {
7051           wmf = Ufopen(warn_message_file, "rb");
7052           if (wmf == NULL)
7053             log_write(0, LOG_MAIN|LOG_PANIC, "Failed to open %s for warning "
7054               "message texts: %s", warn_message_file, strerror(errno));
7055           }
7056
7057         warnmsg_recipients = recipients;
7058         warnmsg_delay = (queue_time < 120*60)?
7059           string_sprintf("%d minutes", show_time/60):
7060           string_sprintf("%d hours", show_time/3600);
7061
7062         if (errors_reply_to != NULL)
7063           fprintf(f, "Reply-To: %s\n", errors_reply_to);
7064         fprintf(f, "Auto-Submitted: auto-replied\n");
7065         moan_write_from(f);
7066         fprintf(f, "To: %s\n", recipients);
7067
7068         wmf_text = next_emf(wmf, US"header");
7069         if (wmf_text != NULL)
7070           fprintf(f, "%s\n", wmf_text);
7071         else
7072           fprintf(f, "Subject: Warning: message %s delayed %s\n\n",
7073             message_id, warnmsg_delay);
7074
7075         wmf_text = next_emf(wmf, US"intro");
7076         if (wmf_text != NULL) fprintf(f, "%s", CS wmf_text); else
7077           {
7078           fprintf(f,
7079 "This message was created automatically by mail delivery software.\n");
7080
7081           if (Ustrcmp(recipients, sender_address) == 0)
7082             fprintf(f,
7083 "A message that you sent has not yet been delivered to one or more of its\n"
7084 "recipients after more than ");
7085
7086           else fprintf(f,
7087 "A message sent by\n\n  <%s>\n\n"
7088 "has not yet been delivered to one or more of its recipients after more than \n",
7089           sender_address);
7090
7091           fprintf(f, "%s on the queue on %s.\n\n", warnmsg_delay,
7092             primary_hostname);
7093           fprintf(f, "The message identifier is:     %s\n", message_id);
7094
7095           for (h = header_list; h != NULL; h = h->next)
7096             {
7097             if (strncmpic(h->text, US"Subject:", 8) == 0)
7098               fprintf(f, "The subject of the message is: %s", h->text + 9);
7099             else if (strncmpic(h->text, US"Date:", 5) == 0)
7100               fprintf(f, "The date of the message is:    %s", h->text + 6);
7101             }
7102           fprintf(f, "\n");
7103
7104           fprintf(f, "The address%s to which the message has not yet been "
7105             "delivered %s:\n",
7106             (addr_defer->next == NULL)? "" : "es",
7107             (addr_defer->next == NULL)? "is": "are");
7108           }
7109
7110         /* List the addresses, with error information if allowed */
7111
7112         fprintf(f, "\n");
7113         while (addr_defer != NULL)
7114           {
7115           address_item *addr = addr_defer;
7116           addr_defer = addr->next;
7117           if (print_address_information(addr, f, US"  ", US"\n    ", US""))
7118             print_address_error(addr, f, US"Delay reason: ");
7119           fprintf(f, "\n");
7120           }
7121         fprintf(f, "\n");
7122
7123         /* Final text */
7124
7125         if (wmf != NULL)
7126           {
7127           wmf_text = next_emf(wmf, US"final");
7128           if (wmf_text != NULL) fprintf(f, "%s", CS wmf_text);
7129           (void)fclose(wmf);
7130           }
7131         else
7132           {
7133           fprintf(f,
7134 "No action is required on your part. Delivery attempts will continue for\n"
7135 "some time, and this warning may be repeated at intervals if the message\n"
7136 "remains undelivered. Eventually the mail delivery software will give up,\n"
7137 "and when that happens, the message will be returned to you.\n");
7138           }
7139
7140         /* Close and wait for child process to complete, without a timeout.
7141         If there's an error, don't update the count. */
7142
7143         (void)fclose(f);
7144         if (child_close(pid, 0) == 0)
7145           {
7146           warning_count = count;
7147           update_spool = TRUE;    /* Ensure spool rewritten */
7148           }
7149         }
7150       }
7151     }
7152
7153   /* Clear deliver_domain */
7154
7155   deliver_domain = NULL;
7156
7157   /* If this was a first delivery attempt, unset the first time flag, and
7158   ensure that the spool gets updated. */
7159
7160   if (deliver_firsttime)
7161     {
7162     deliver_firsttime = FALSE;
7163     update_spool = TRUE;
7164     }
7165
7166   /* If delivery was frozen and freeze_tell is set, generate an appropriate
7167   message, unless the message is a local error message (to avoid loops). Then
7168   log the freezing. If the text in "frozen_info" came from a system filter,
7169   it has been escaped into printing characters so as not to mess up log lines.
7170   For the "tell" message, we turn \n back into newline. Also, insert a newline
7171   near the start instead of the ": " string. */
7172
7173   if (deliver_freeze)
7174     {
7175     if (freeze_tell != NULL && freeze_tell[0] != 0 && !local_error_message)
7176       {
7177       uschar *s = string_copy(frozen_info);
7178       uschar *ss = Ustrstr(s, " by the system filter: ");
7179
7180       if (ss != NULL)
7181         {
7182         ss[21] = '.';
7183         ss[22] = '\n';
7184         }
7185
7186       ss = s;
7187       while (*ss != 0)
7188         {
7189         if (*ss == '\\' && ss[1] == 'n')
7190           {
7191           *ss++ = ' ';
7192           *ss++ = '\n';
7193           }
7194         else ss++;
7195         }
7196       moan_tell_someone(freeze_tell, addr_defer, US"Message frozen",
7197         "Message %s has been frozen%s.\nThe sender is <%s>.\n", message_id,
7198         s, sender_address);
7199       }
7200
7201     /* Log freezing just before we update the -H file, to minimize the chance
7202     of a race problem. */
7203
7204     deliver_msglog("*** Frozen%s\n", frozen_info);
7205     log_write(0, LOG_MAIN, "Frozen%s", frozen_info);
7206     }
7207
7208   /* If there have been any updates to the non-recipients list, or other things
7209   that get written to the spool, we must now update the spool header file so
7210   that it has the right information for the next delivery attempt. If there
7211   was more than one address being delivered, the header_change update is done
7212   earlier, in case one succeeds and then something crashes. */
7213
7214   DEBUG(D_deliver)
7215     debug_printf("delivery deferred: update_spool=%d header_rewritten=%d\n",
7216       update_spool, header_rewritten);
7217
7218   if (update_spool || header_rewritten)
7219     /* Panic-dies on error */
7220     (void)spool_write_header(message_id, SW_DELIVERING, NULL);
7221   }
7222
7223 /* Finished with the message log. If the message is complete, it will have
7224 been unlinked or renamed above. */
7225
7226 if (message_logs) (void)fclose(message_log);
7227
7228 /* Now we can close and remove the journal file. Its only purpose is to record
7229 successfully completed deliveries asap so that this information doesn't get
7230 lost if Exim (or the machine) crashes. Forgetting about a failed delivery is
7231 not serious, as trying it again is not harmful. The journal might not be open
7232 if all addresses were deferred at routing or directing. Nevertheless, we must
7233 remove it if it exists (may have been lying around from a crash during the
7234 previous delivery attempt). We don't remove the journal if a delivery
7235 subprocess failed to pass back delivery information; this is controlled by
7236 the remove_journal flag. When the journal is left, we also don't move the
7237 message off the main spool if frozen and the option is set. It should get moved
7238 at the next attempt, after the journal has been inspected. */
7239
7240 if (journal_fd >= 0) (void)close(journal_fd);
7241
7242 if (remove_journal)
7243   {
7244   sprintf(CS spoolname, "%s/input/%s/%s-J", spool_directory, message_subdir, id);
7245   if (Uunlink(spoolname) < 0 && errno != ENOENT)
7246     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to unlink %s: %s", spoolname,
7247       strerror(errno));
7248
7249   /* Move the message off the spool if reqested */
7250
7251   #ifdef SUPPORT_MOVE_FROZEN_MESSAGES
7252   if (deliver_freeze && move_frozen_messages)
7253     (void)spool_move_message(id, message_subdir, US"", US"F");
7254   #endif
7255   }
7256
7257 /* Closing the data file frees the lock; if the file has been unlinked it
7258 will go away. Otherwise the message becomes available for another process
7259 to try delivery. */
7260
7261 (void)close(deliver_datafile);
7262 deliver_datafile = -1;
7263 DEBUG(D_deliver) debug_printf("end delivery of %s\n", id);
7264
7265 /* It is unlikely that there will be any cached resources, since they are
7266 released after routing, and in the delivery subprocesses. However, it's
7267 possible for an expansion for something afterwards (for example,
7268 expand_check_condition) to do a lookup. We must therefore be sure everything is
7269 released. */
7270
7271 search_tidyup();
7272 acl_where = ACL_WHERE_UNKNOWN;
7273 return final_yield;
7274 }
7275
7276 /* vi: aw ai sw=2
7277 */
7278 /* End of deliver.c */