tidying
[exim.git] / src / src / deliver.c
1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2016 */
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 #include <assert.h>
13
14
15 /* Data block for keeping track of subprocesses for parallel remote
16 delivery. */
17
18 typedef struct pardata {
19 address_item *addrlist; /* chain of addresses */
20 address_item *addr; /* next address data expected for */
21 pid_t pid; /* subprocess pid */
22 int fd; /* pipe fd for getting result from subprocess */
23 int transport_count; /* returned transport count value */
24 BOOL done; /* no more data needed */
25 uschar *msg; /* error message */
26 uschar *return_path; /* return_path for these addresses */
27 } pardata;
28
29 /* Values for the process_recipients variable */
30
31 enum { RECIP_ACCEPT, RECIP_IGNORE, RECIP_DEFER,
32 RECIP_FAIL, RECIP_FAIL_FILTER, RECIP_FAIL_TIMEOUT,
33 RECIP_FAIL_LOOP};
34
35 /* Mutually recursive functions for marking addresses done. */
36
37 static void child_done(address_item *, uschar *);
38 static void address_done(address_item *, uschar *);
39
40 /* Table for turning base-62 numbers into binary */
41
42 static uschar tab62[] =
43 {0,1,2,3,4,5,6,7,8,9,0,0,0,0,0,0, /* 0-9 */
44 0,10,11,12,13,14,15,16,17,18,19,20, /* A-K */
45 21,22,23,24,25,26,27,28,29,30,31,32, /* L-W */
46 33,34,35, 0, 0, 0, 0, 0, /* X-Z */
47 0,36,37,38,39,40,41,42,43,44,45,46, /* a-k */
48 47,48,49,50,51,52,53,54,55,56,57,58, /* l-w */
49 59,60,61}; /* x-z */
50
51
52 /*************************************************
53 * Local static variables *
54 *************************************************/
55
56 /* addr_duplicate is global because it needs to be seen from the Envelope-To
57 writing code. */
58
59 static address_item *addr_defer = NULL;
60 static address_item *addr_failed = NULL;
61 static address_item *addr_fallback = NULL;
62 static address_item *addr_local = NULL;
63 static address_item *addr_new = NULL;
64 static address_item *addr_remote = NULL;
65 static address_item *addr_route = NULL;
66 static address_item *addr_succeed = NULL;
67 static address_item *addr_dsntmp = NULL;
68 static address_item *addr_senddsn = NULL;
69
70 static FILE *message_log = NULL;
71 static BOOL update_spool;
72 static BOOL remove_journal;
73 static int parcount = 0;
74 static pardata *parlist = NULL;
75 static int return_count;
76 static uschar *frozen_info = US"";
77 static uschar *used_return_path = NULL;
78
79
80
81 /*************************************************
82 * Make a new address item *
83 *************************************************/
84
85 /* This function gets the store and initializes with default values. The
86 transport_return value defaults to DEFER, so that any unexpected failure to
87 deliver does not wipe out the message. The default unique string is set to a
88 copy of the address, so that its domain can be lowercased.
89
90 Argument:
91 address the RFC822 address string
92 copy force a copy of the address
93
94 Returns: a pointer to an initialized address_item
95 */
96
97 address_item *
98 deliver_make_addr(uschar *address, BOOL copy)
99 {
100 address_item *addr = store_get(sizeof(address_item));
101 *addr = address_defaults;
102 if (copy) address = string_copy(address);
103 addr->address = address;
104 addr->unique = string_copy(address);
105 return addr;
106 }
107
108
109
110
111 /*************************************************
112 * Set expansion values for an address *
113 *************************************************/
114
115 /* Certain expansion variables are valid only when handling an address or
116 address list. This function sets them up or clears the values, according to its
117 argument.
118
119 Arguments:
120 addr the address in question, or NULL to clear values
121 Returns: nothing
122 */
123
124 void
125 deliver_set_expansions(address_item *addr)
126 {
127 if (!addr)
128 {
129 const uschar ***p = address_expansions;
130 while (*p) **p++ = NULL;
131 return;
132 }
133
134 /* Exactly what gets set depends on whether there is one or more addresses, and
135 what they contain. These first ones are always set, taking their values from
136 the first address. */
137
138 if (!addr->host_list)
139 {
140 deliver_host = deliver_host_address = US"";
141 deliver_host_port = 0;
142 }
143 else
144 {
145 deliver_host = addr->host_list->name;
146 deliver_host_address = addr->host_list->address;
147 deliver_host_port = addr->host_list->port;
148 }
149
150 deliver_recipients = addr;
151 deliver_address_data = addr->prop.address_data;
152 deliver_domain_data = addr->prop.domain_data;
153 deliver_localpart_data = addr->prop.localpart_data;
154
155 /* These may be unset for multiple addresses */
156
157 deliver_domain = addr->domain;
158 self_hostname = addr->self_hostname;
159
160 #ifdef EXPERIMENTAL_BRIGHTMAIL
161 bmi_deliver = 1; /* deliver by default */
162 bmi_alt_location = NULL;
163 bmi_base64_verdict = NULL;
164 bmi_base64_tracker_verdict = NULL;
165 #endif
166
167 /* If there's only one address we can set everything. */
168
169 if (!addr->next)
170 {
171 address_item *addr_orig;
172
173 deliver_localpart = addr->local_part;
174 deliver_localpart_prefix = addr->prefix;
175 deliver_localpart_suffix = addr->suffix;
176
177 for (addr_orig = addr; addr_orig->parent; addr_orig = addr_orig->parent) ;
178 deliver_domain_orig = addr_orig->domain;
179
180 /* Re-instate any prefix and suffix in the original local part. In all
181 normal cases, the address will have a router associated with it, and we can
182 choose the caseful or caseless version accordingly. However, when a system
183 filter sets up a pipe, file, or autoreply delivery, no router is involved.
184 In this case, though, there won't be any prefix or suffix to worry about. */
185
186 deliver_localpart_orig = !addr_orig->router
187 ? addr_orig->local_part
188 : addr_orig->router->caseful_local_part
189 ? addr_orig->cc_local_part
190 : addr_orig->lc_local_part;
191
192 /* If there's a parent, make its domain and local part available, and if
193 delivering to a pipe or file, or sending an autoreply, get the local
194 part from the parent. For pipes and files, put the pipe or file string
195 into address_pipe and address_file. */
196
197 if (addr->parent)
198 {
199 deliver_domain_parent = addr->parent->domain;
200 deliver_localpart_parent = !addr->parent->router
201 ? addr->parent->local_part
202 : addr->parent->router->caseful_local_part
203 ? addr->parent->cc_local_part
204 : addr->parent->lc_local_part;
205
206 /* File deliveries have their own flag because they need to be picked out
207 as special more often. */
208
209 if (testflag(addr, af_pfr))
210 {
211 if (testflag(addr, af_file)) address_file = addr->local_part;
212 else if (deliver_localpart[0] == '|') address_pipe = addr->local_part;
213 deliver_localpart = addr->parent->local_part;
214 deliver_localpart_prefix = addr->parent->prefix;
215 deliver_localpart_suffix = addr->parent->suffix;
216 }
217 }
218
219 #ifdef EXPERIMENTAL_BRIGHTMAIL
220 /* Set expansion variables related to Brightmail AntiSpam */
221 bmi_base64_verdict = bmi_get_base64_verdict(deliver_localpart_orig, deliver_domain_orig);
222 bmi_base64_tracker_verdict = bmi_get_base64_tracker_verdict(bmi_base64_verdict);
223 /* get message delivery status (0 - don't deliver | 1 - deliver) */
224 bmi_deliver = bmi_get_delivery_status(bmi_base64_verdict);
225 /* if message is to be delivered, get eventual alternate location */
226 if (bmi_deliver == 1)
227 bmi_alt_location = bmi_get_alt_location(bmi_base64_verdict);
228 #endif
229
230 }
231
232 /* For multiple addresses, don't set local part, and leave the domain and
233 self_hostname set only if it is the same for all of them. It is possible to
234 have multiple pipe and file addresses, but only when all addresses have routed
235 to the same pipe or file. */
236
237 else
238 {
239 address_item *addr2;
240 if (testflag(addr, af_pfr))
241 {
242 if (testflag(addr, af_file)) address_file = addr->local_part;
243 else if (addr->local_part[0] == '|') address_pipe = addr->local_part;
244 }
245 for (addr2 = addr->next; addr2; addr2 = addr2->next)
246 {
247 if (deliver_domain && Ustrcmp(deliver_domain, addr2->domain) != 0)
248 deliver_domain = NULL;
249 if ( self_hostname
250 && ( !addr2->self_hostname
251 || Ustrcmp(self_hostname, addr2->self_hostname) != 0
252 ) )
253 self_hostname = NULL;
254 if (!deliver_domain && !self_hostname) break;
255 }
256 }
257 }
258
259
260
261
262 /*************************************************
263 * Open a msglog file *
264 *************************************************/
265
266 /* This function is used both for normal message logs, and for files in the
267 msglog directory that are used to catch output from pipes. Try to create the
268 directory if it does not exist. From release 4.21, normal message logs should
269 be created when the message is received.
270
271 Argument:
272 filename the file name
273 mode the mode required
274 error used for saying what failed
275
276 Returns: a file descriptor, or -1 (with errno set)
277 */
278
279 static int
280 open_msglog_file(uschar *filename, int mode, uschar **error)
281 {
282 int fd = Uopen(filename, O_WRONLY|O_APPEND|O_CREAT, mode);
283
284 if (fd < 0 && errno == ENOENT)
285 {
286 (void)directory_make(spool_directory,
287 spool_sname(US"msglog", message_subdir),
288 MSGLOG_DIRECTORY_MODE, TRUE);
289 fd = Uopen(filename, O_WRONLY|O_APPEND|O_CREAT, mode);
290 }
291
292 /* Set the close-on-exec flag and change the owner to the exim uid/gid (this
293 function is called as root). Double check the mode, because the group setting
294 doesn't always get set automatically. */
295
296 if (fd >= 0)
297 {
298 (void)fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
299 if (fchown(fd, exim_uid, exim_gid) < 0)
300 {
301 *error = US"chown";
302 return -1;
303 }
304 if (fchmod(fd, mode) < 0)
305 {
306 *error = US"chmod";
307 return -1;
308 }
309 }
310 else *error = US"create";
311
312 return fd;
313 }
314
315
316
317
318 /*************************************************
319 * Write to msglog if required *
320 *************************************************/
321
322 /* Write to the message log, if configured. This function may also be called
323 from transports.
324
325 Arguments:
326 format a string format
327
328 Returns: nothing
329 */
330
331 void
332 deliver_msglog(const char *format, ...)
333 {
334 va_list ap;
335 if (!message_logs) return;
336 va_start(ap, format);
337 vfprintf(message_log, format, ap);
338 fflush(message_log);
339 va_end(ap);
340 }
341
342
343
344
345 /*************************************************
346 * Replicate status for batch *
347 *************************************************/
348
349 /* When a transport handles a batch of addresses, it may treat them
350 individually, or it may just put the status in the first one, and return FALSE,
351 requesting that the status be copied to all the others externally. This is the
352 replication function. As well as the status, it copies the transport pointer,
353 which may have changed if appendfile passed the addresses on to a different
354 transport.
355
356 Argument: pointer to the first address in a chain
357 Returns: nothing
358 */
359
360 static void
361 replicate_status(address_item *addr)
362 {
363 address_item *addr2;
364 for (addr2 = addr->next; addr2; addr2 = addr2->next)
365 {
366 addr2->transport = addr->transport;
367 addr2->transport_return = addr->transport_return;
368 addr2->basic_errno = addr->basic_errno;
369 addr2->more_errno = addr->more_errno;
370 addr2->special_action = addr->special_action;
371 addr2->message = addr->message;
372 addr2->user_message = addr->user_message;
373 }
374 }
375
376
377
378 /*************************************************
379 * Compare lists of hosts *
380 *************************************************/
381
382 /* This function is given two pointers to chains of host items, and it yields
383 TRUE if the lists refer to the same hosts in the same order, except that
384
385 (1) Multiple hosts with the same non-negative MX values are permitted to appear
386 in different orders. Round-robinning nameservers can cause this to happen.
387
388 (2) Multiple hosts with the same negative MX values less than MX_NONE are also
389 permitted to appear in different orders. This is caused by randomizing
390 hosts lists.
391
392 This enables Exim to use a single SMTP transaction for sending to two entirely
393 different domains that happen to end up pointing at the same hosts.
394
395 Arguments:
396 one points to the first host list
397 two points to the second host list
398
399 Returns: TRUE if the lists refer to the same host set
400 */
401
402 static BOOL
403 same_hosts(host_item *one, host_item *two)
404 {
405 while (one && two)
406 {
407 if (Ustrcmp(one->name, two->name) != 0)
408 {
409 int mx = one->mx;
410 host_item *end_one = one;
411 host_item *end_two = two;
412
413 /* Batch up only if there was no MX and the list was not randomized */
414
415 if (mx == MX_NONE) return FALSE;
416
417 /* Find the ends of the shortest sequence of identical MX values */
418
419 while ( end_one->next && end_one->next->mx == mx
420 && end_two->next && end_two->next->mx == mx)
421 {
422 end_one = end_one->next;
423 end_two = end_two->next;
424 }
425
426 /* If there aren't any duplicates, there's no match. */
427
428 if (end_one == one) return FALSE;
429
430 /* For each host in the 'one' sequence, check that it appears in the 'two'
431 sequence, returning FALSE if not. */
432
433 for (;;)
434 {
435 host_item *hi;
436 for (hi = two; hi != end_two->next; hi = hi->next)
437 if (Ustrcmp(one->name, hi->name) == 0) break;
438 if (hi == end_two->next) return FALSE;
439 if (one == end_one) break;
440 one = one->next;
441 }
442
443 /* All the hosts in the 'one' sequence were found in the 'two' sequence.
444 Ensure both are pointing at the last host, and carry on as for equality. */
445
446 two = end_two;
447 }
448
449 /* Hosts matched */
450
451 one = one->next;
452 two = two->next;
453 }
454
455 /* True if both are NULL */
456
457 return (one == two);
458 }
459
460
461
462 /*************************************************
463 * Compare header lines *
464 *************************************************/
465
466 /* This function is given two pointers to chains of header items, and it yields
467 TRUE if they are the same header texts in the same order.
468
469 Arguments:
470 one points to the first header list
471 two points to the second header list
472
473 Returns: TRUE if the lists refer to the same header set
474 */
475
476 static BOOL
477 same_headers(header_line *one, header_line *two)
478 {
479 for (;; one = one->next, two = two->next)
480 {
481 if (one == two) return TRUE; /* Includes the case where both NULL */
482 if (!one || !two) return FALSE;
483 if (Ustrcmp(one->text, two->text) != 0) return FALSE;
484 }
485 }
486
487
488
489 /*************************************************
490 * Compare string settings *
491 *************************************************/
492
493 /* This function is given two pointers to strings, and it returns
494 TRUE if they are the same pointer, or if the two strings are the same.
495
496 Arguments:
497 one points to the first string
498 two points to the second string
499
500 Returns: TRUE or FALSE
501 */
502
503 static BOOL
504 same_strings(uschar *one, uschar *two)
505 {
506 if (one == two) return TRUE; /* Includes the case where both NULL */
507 if (!one || !two) return FALSE;
508 return (Ustrcmp(one, two) == 0);
509 }
510
511
512
513 /*************************************************
514 * Compare uid/gid for addresses *
515 *************************************************/
516
517 /* This function is given a transport and two addresses. It yields TRUE if the
518 uid/gid/initgroups settings for the two addresses are going to be the same when
519 they are delivered.
520
521 Arguments:
522 tp the transort
523 addr1 the first address
524 addr2 the second address
525
526 Returns: TRUE or FALSE
527 */
528
529 static BOOL
530 same_ugid(transport_instance *tp, address_item *addr1, address_item *addr2)
531 {
532 if ( !tp->uid_set && !tp->expand_uid
533 && !tp->deliver_as_creator
534 && ( testflag(addr1, af_uid_set) != testflag(addr2, af_gid_set)
535 || ( testflag(addr1, af_uid_set)
536 && ( addr1->uid != addr2->uid
537 || testflag(addr1, af_initgroups) != testflag(addr2, af_initgroups)
538 ) ) ) )
539 return FALSE;
540
541 if ( !tp->gid_set && !tp->expand_gid
542 && ( testflag(addr1, af_gid_set) != testflag(addr2, af_gid_set)
543 || ( testflag(addr1, af_gid_set)
544 && addr1->gid != addr2->gid
545 ) ) )
546 return FALSE;
547
548 return TRUE;
549 }
550
551
552
553
554 /*************************************************
555 * Record that an address is complete *
556 *************************************************/
557
558 /* This function records that an address is complete. This is straightforward
559 for most addresses, where the unique address is just the full address with the
560 domain lower cased. For homonyms (addresses that are the same as one of their
561 ancestors) their are complications. Their unique addresses have \x\ prepended
562 (where x = 0, 1, 2...), so that de-duplication works correctly for siblings and
563 cousins.
564
565 Exim used to record the unique addresses of homonyms as "complete". This,
566 however, fails when the pattern of redirection varies over time (e.g. if taking
567 unseen copies at only some times of day) because the prepended numbers may vary
568 from one delivery run to the next. This problem is solved by never recording
569 prepended unique addresses as complete. Instead, when a homonymic address has
570 actually been delivered via a transport, we record its basic unique address
571 followed by the name of the transport. This is checked in subsequent delivery
572 runs whenever an address is routed to a transport.
573
574 If the completed address is a top-level one (has no parent, which means it
575 cannot be homonymic) we also add the original address to the non-recipients
576 tree, so that it gets recorded in the spool file and therefore appears as
577 "done" in any spool listings. The original address may differ from the unique
578 address in the case of the domain.
579
580 Finally, this function scans the list of duplicates, marks as done any that
581 match this address, and calls child_done() for their ancestors.
582
583 Arguments:
584 addr address item that has been completed
585 now current time as a string
586
587 Returns: nothing
588 */
589
590 static void
591 address_done(address_item *addr, uschar *now)
592 {
593 address_item *dup;
594
595 update_spool = TRUE; /* Ensure spool gets updated */
596
597 /* Top-level address */
598
599 if (!addr->parent)
600 {
601 tree_add_nonrecipient(addr->unique);
602 tree_add_nonrecipient(addr->address);
603 }
604
605 /* Homonymous child address */
606
607 else if (testflag(addr, af_homonym))
608 {
609 if (addr->transport)
610 tree_add_nonrecipient(
611 string_sprintf("%s/%s", addr->unique + 3, addr->transport->name));
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; dup = dup->next)
622 if (Ustrcmp(addr->unique, dup->unique) == 0)
623 {
624 tree_add_nonrecipient(dup->unique);
625 child_done(dup, now);
626 }
627 }
628
629
630
631
632 /*************************************************
633 * Decrease counts in parents and mark done *
634 *************************************************/
635
636 /* This function is called when an address is complete. If there is a parent
637 address, its count of children is decremented. If there are still other
638 children outstanding, the function exits. Otherwise, if the count has become
639 zero, address_done() is called to mark the parent and its duplicates complete.
640 Then loop for any earlier ancestors.
641
642 Arguments:
643 addr points to the completed address item
644 now the current time as a string, for writing to the message log
645
646 Returns: nothing
647 */
648
649 static void
650 child_done(address_item *addr, uschar *now)
651 {
652 address_item *aa;
653 while (addr->parent)
654 {
655 addr = addr->parent;
656 if ((addr->child_count -= 1) > 0) return; /* Incomplete parent */
657 address_done(addr, now);
658
659 /* Log the completion of all descendents only when there is no ancestor with
660 the same original address. */
661
662 for (aa = addr->parent; aa; aa = aa->parent)
663 if (Ustrcmp(aa->address, addr->address) == 0) break;
664 if (aa) continue;
665
666 deliver_msglog("%s %s: children all complete\n", now, addr->address);
667 DEBUG(D_deliver) debug_printf("%s: children all complete\n", addr->address);
668 }
669 }
670
671
672
673 /*************************************************
674 * Delivery logging support functions *
675 *************************************************/
676
677 /* The LOGGING() checks in d_log_interface() are complicated for backwards
678 compatibility. When outgoing interface logging was originally added, it was
679 conditional on just incoming_interface (which is off by default). The
680 outgoing_interface option is on by default to preserve this behaviour, but
681 you can enable incoming_interface and disable outgoing_interface to get I=
682 fields on incoming lines only.
683
684 Arguments:
685 s The log line buffer
686 sizep Pointer to the buffer size
687 ptrp Pointer to current index into buffer
688 addr The address to be logged
689
690 Returns: New value for s
691 */
692
693 static uschar *
694 d_log_interface(uschar *s, int *sizep, int *ptrp)
695 {
696 if (LOGGING(incoming_interface) && LOGGING(outgoing_interface)
697 && sending_ip_address)
698 {
699 s = string_append(s, sizep, ptrp, 2, US" I=[", sending_ip_address);
700 s = LOGGING(outgoing_port)
701 ? string_append(s, sizep, ptrp, 2, US"]:",
702 string_sprintf("%d", sending_port))
703 : string_catn(s, sizep, ptrp, US"]", 1);
704 }
705 return s;
706 }
707
708
709
710 static uschar *
711 d_hostlog(uschar * s, int * sp, int * pp, address_item * addr)
712 {
713 host_item * h = addr->host_used;
714
715 s = string_append(s, sp, pp, 2, US" H=", h->name);
716
717 if (LOGGING(dnssec) && h->dnssec == DS_YES)
718 s = string_cat(s, sp, pp, US" DS");
719
720 s = string_append(s, sp, pp, 3, US" [", h->address, US"]");
721
722 if (LOGGING(outgoing_port))
723 s = string_append(s, sp, pp, 2, US":", string_sprintf("%d", h->port));
724
725 #ifdef SUPPORT_SOCKS
726 if (LOGGING(proxy) && proxy_local_address)
727 {
728 s = string_append(s, sp, pp, 3, US" PRX=[", proxy_local_address, US"]");
729 if (LOGGING(outgoing_port))
730 s = string_append(s, sp, pp, 2, US":", string_sprintf("%d",
731 proxy_local_port));
732 }
733 #endif
734
735 return d_log_interface(s, sp, pp);
736 }
737
738
739
740
741
742 #ifdef SUPPORT_TLS
743 static uschar *
744 d_tlslog(uschar * s, int * sizep, int * ptrp, address_item * addr)
745 {
746 if (LOGGING(tls_cipher) && addr->cipher)
747 s = string_append(s, sizep, ptrp, 2, US" X=", addr->cipher);
748 if (LOGGING(tls_certificate_verified) && addr->cipher)
749 s = string_append(s, sizep, ptrp, 2, US" CV=",
750 testflag(addr, af_cert_verified)
751 ?
752 #ifdef EXPERIMENTAL_DANE
753 testflag(addr, af_dane_verified)
754 ? "dane"
755 :
756 #endif
757 "yes"
758 : "no");
759 if (LOGGING(tls_peerdn) && addr->peerdn)
760 s = string_append(s, sizep, ptrp, 3, US" DN=\"",
761 string_printing(addr->peerdn), US"\"");
762 return s;
763 }
764 #endif
765
766
767
768
769 #ifndef DISABLE_EVENT
770 uschar *
771 event_raise(uschar * action, const uschar * event, uschar * ev_data)
772 {
773 uschar * s;
774 if (action)
775 {
776 DEBUG(D_deliver)
777 debug_printf("Event(%s): event_action=|%s| delivery_IP=%s\n",
778 event,
779 action, deliver_host_address);
780
781 event_name = event;
782 event_data = ev_data;
783
784 if (!(s = expand_string(action)) && *expand_string_message)
785 log_write(0, LOG_MAIN|LOG_PANIC,
786 "failed to expand event_action %s in %s: %s\n",
787 event, transport_name, expand_string_message);
788
789 event_name = event_data = NULL;
790
791 /* If the expansion returns anything but an empty string, flag for
792 the caller to modify his normal processing
793 */
794 if (s && *s)
795 {
796 DEBUG(D_deliver)
797 debug_printf("Event(%s): event_action returned \"%s\"\n", event, s);
798 return s;
799 }
800 }
801 return NULL;
802 }
803
804 void
805 msg_event_raise(const uschar * event, const address_item * addr)
806 {
807 const uschar * save_domain = deliver_domain;
808 uschar * save_local = deliver_localpart;
809 const uschar * save_host = deliver_host;
810 const uschar * save_address = deliver_host_address;
811 const int save_port = deliver_host_port;
812
813 if (!addr->transport)
814 return;
815
816 router_name = addr->router ? addr->router->name : NULL;
817 transport_name = addr->transport->name;
818 deliver_domain = addr->domain;
819 deliver_localpart = addr->local_part;
820 deliver_host = addr->host_used ? addr->host_used->name : NULL;
821
822 (void) event_raise(addr->transport->event_action, event,
823 addr->host_used
824 || Ustrcmp(addr->transport->driver_name, "smtp") == 0
825 || Ustrcmp(addr->transport->driver_name, "lmtp") == 0
826 ? addr->message : NULL);
827
828 deliver_host_port = save_port;
829 deliver_host_address = save_address;
830 deliver_host = save_host;
831 deliver_localpart = save_local;
832 deliver_domain = save_domain;
833 router_name = transport_name = NULL;
834 }
835 #endif /*DISABLE_EVENT*/
836
837
838
839 /******************************************************************************/
840
841
842 /*************************************************
843 * Generate local prt for logging *
844 *************************************************/
845
846 /* This function is a subroutine for use in string_log_address() below.
847
848 Arguments:
849 addr the address being logged
850 yield the current dynamic buffer pointer
851 sizeptr points to current size
852 ptrptr points to current insert pointer
853
854 Returns: the new value of the buffer pointer
855 */
856
857 static uschar *
858 string_get_localpart(address_item *addr, uschar *yield, int *sizeptr,
859 int *ptrptr)
860 {
861 uschar * s;
862
863 s = addr->prefix;
864 if (testflag(addr, af_include_affixes) && s)
865 {
866 #ifdef SUPPORT_I18N
867 if (testflag(addr, af_utf8_downcvt))
868 s = string_localpart_utf8_to_alabel(s, NULL);
869 #endif
870 yield = string_cat(yield, sizeptr, ptrptr, s);
871 }
872
873 s = addr->local_part;
874 #ifdef SUPPORT_I18N
875 if (testflag(addr, af_utf8_downcvt))
876 s = string_localpart_utf8_to_alabel(s, NULL);
877 #endif
878 yield = string_cat(yield, sizeptr, ptrptr, s);
879
880 s = addr->suffix;
881 if (testflag(addr, af_include_affixes) && s)
882 {
883 #ifdef SUPPORT_I18N
884 if (testflag(addr, af_utf8_downcvt))
885 s = string_localpart_utf8_to_alabel(s, NULL);
886 #endif
887 yield = string_cat(yield, sizeptr, ptrptr, s);
888 }
889
890 return yield;
891 }
892
893
894 /*************************************************
895 * Generate log address list *
896 *************************************************/
897
898 /* This function generates a list consisting of an address and its parents, for
899 use in logging lines. For saved onetime aliased addresses, the onetime parent
900 field is used. If the address was delivered by a transport with rcpt_include_
901 affixes set, the af_include_affixes bit will be set in the address. In that
902 case, we include the affixes here too.
903
904 Arguments:
905 str points to start of growing string, or NULL
906 size points to current allocation for string
907 ptr points to offset for append point; updated on exit
908 addr bottom (ultimate) address
909 all_parents if TRUE, include all parents
910 success TRUE for successful delivery
911
912 Returns: a growable string in dynamic store
913 */
914
915 static uschar *
916 string_log_address(uschar * str, int * size, int * ptr,
917 address_item *addr, BOOL all_parents, BOOL success)
918 {
919 BOOL add_topaddr = TRUE;
920 address_item *topaddr;
921
922 /* Find the ultimate parent */
923
924 for (topaddr = addr; topaddr->parent; topaddr = topaddr->parent) ;
925
926 /* We start with just the local part for pipe, file, and reply deliveries, and
927 for successful local deliveries from routers that have the log_as_local flag
928 set. File deliveries from filters can be specified as non-absolute paths in
929 cases where the transport is goin to complete the path. If there is an error
930 before this happens (expansion failure) the local part will not be updated, and
931 so won't necessarily look like a path. Add extra text for this case. */
932
933 if ( testflag(addr, af_pfr)
934 || ( success
935 && addr->router && addr->router->log_as_local
936 && addr->transport && addr->transport->info->local
937 ) )
938 {
939 if (testflag(addr, af_file) && addr->local_part[0] != '/')
940 str = string_catn(str, size, ptr, CUS"save ", 5);
941 str = string_get_localpart(addr, str, size, ptr);
942 }
943
944 /* Other deliveries start with the full address. It we have split it into local
945 part and domain, use those fields. Some early failures can happen before the
946 splitting is done; in those cases use the original field. */
947
948 else
949 {
950 uschar * cmp = str + *ptr;
951
952 if (addr->local_part)
953 {
954 const uschar * s;
955 str = string_get_localpart(addr, str, size, ptr);
956 str = string_catn(str, size, ptr, US"@", 1);
957 s = addr->domain;
958 #ifdef SUPPORT_I18N
959 if (testflag(addr, af_utf8_downcvt))
960 s = string_localpart_utf8_to_alabel(s, NULL);
961 #endif
962 str = string_cat(str, size, ptr, s);
963 }
964 else
965 str = string_cat(str, size, ptr, addr->address);
966
967 /* If the address we are going to print is the same as the top address,
968 and all parents are not being included, don't add on the top address. First
969 of all, do a caseless comparison; if this succeeds, do a caseful comparison
970 on the local parts. */
971
972 str[*ptr] = 0;
973 if ( strcmpic(cmp, topaddr->address) == 0
974 && Ustrncmp(cmp, topaddr->address, Ustrchr(cmp, '@') - cmp) == 0
975 && !addr->onetime_parent
976 && (!all_parents || !addr->parent || addr->parent == topaddr)
977 )
978 add_topaddr = FALSE;
979 }
980
981 /* If all parents are requested, or this is a local pipe/file/reply, and
982 there is at least one intermediate parent, show it in brackets, and continue
983 with all of them if all are wanted. */
984
985 if ( (all_parents || testflag(addr, af_pfr))
986 && addr->parent
987 && addr->parent != topaddr)
988 {
989 uschar *s = US" (";
990 address_item *addr2;
991 for (addr2 = addr->parent; addr2 != topaddr; addr2 = addr2->parent)
992 {
993 str = string_catn(str, size, ptr, s, 2);
994 str = string_cat (str, size, ptr, addr2->address);
995 if (!all_parents) break;
996 s = US", ";
997 }
998 str = string_catn(str, size, ptr, US")", 1);
999 }
1000
1001 /* Add the top address if it is required */
1002
1003 if (add_topaddr)
1004 str = string_append(str, size, ptr, 3,
1005 US" <",
1006 addr->onetime_parent ? addr->onetime_parent : topaddr->address,
1007 US">");
1008
1009 return str;
1010 }
1011
1012
1013 /******************************************************************************/
1014
1015
1016
1017 /* If msg is NULL this is a delivery log and logchar is used. Otherwise
1018 this is a nonstandard call; no two-character delivery flag is written
1019 but sender-host and sender are prefixed and "msg" is inserted in the log line.
1020
1021 Arguments:
1022 flags passed to log_write()
1023 */
1024 void
1025 delivery_log(int flags, address_item * addr, int logchar, uschar * msg)
1026 {
1027 int size = 256; /* Used for a temporary, */
1028 int ptr = 0; /* expanding buffer, for */
1029 uschar * s; /* building log lines; */
1030 void * reset_point; /* released afterwards. */
1031
1032 /* Log the delivery on the main log. We use an extensible string to build up
1033 the log line, and reset the store afterwards. Remote deliveries should always
1034 have a pointer to the host item that succeeded; local deliveries can have a
1035 pointer to a single host item in their host list, for use by the transport. */
1036
1037 #ifndef DISABLE_EVENT
1038 /* presume no successful remote delivery */
1039 lookup_dnssec_authenticated = NULL;
1040 #endif
1041
1042 s = reset_point = store_get(size);
1043
1044 if (msg)
1045 s = string_append(s, &size, &ptr, 2, host_and_ident(TRUE), US" ");
1046 else
1047 {
1048 s[ptr++] = logchar;
1049 s = string_catn(s, &size, &ptr, US"> ", 2);
1050 }
1051 s = string_log_address(s, &size, &ptr, addr, LOGGING(all_parents), TRUE);
1052
1053 if (LOGGING(sender_on_delivery) || msg)
1054 s = string_append(s, &size, &ptr, 3, US" F=<",
1055 #ifdef SUPPORT_I18N
1056 testflag(addr, af_utf8_downcvt)
1057 ? string_address_utf8_to_alabel(sender_address, NULL)
1058 :
1059 #endif
1060 sender_address,
1061 US">");
1062
1063 if (*queue_name)
1064 s = string_append(s, &size, &ptr, 2, US" Q=", queue_name);
1065
1066 #ifdef EXPERIMENTAL_SRS
1067 if(addr->prop.srs_sender)
1068 s = string_append(s, &size, &ptr, 3, US" SRS=<", addr->prop.srs_sender, US">");
1069 #endif
1070
1071 /* You might think that the return path must always be set for a successful
1072 delivery; indeed, I did for some time, until this statement crashed. The case
1073 when it is not set is for a delivery to /dev/null which is optimised by not
1074 being run at all. */
1075
1076 if (used_return_path && LOGGING(return_path_on_delivery))
1077 s = string_append(s, &size, &ptr, 3, US" P=<", used_return_path, US">");
1078
1079 if (msg)
1080 s = string_append(s, &size, &ptr, 2, US" ", msg);
1081
1082 /* For a delivery from a system filter, there may not be a router */
1083 if (addr->router)
1084 s = string_append(s, &size, &ptr, 2, US" R=", addr->router->name);
1085
1086 s = string_append(s, &size, &ptr, 2, US" T=", addr->transport->name);
1087
1088 if (LOGGING(delivery_size))
1089 s = string_append(s, &size, &ptr, 2, US" S=",
1090 string_sprintf("%d", transport_count));
1091
1092 /* Local delivery */
1093
1094 if (addr->transport->info->local)
1095 {
1096 if (addr->host_list)
1097 s = string_append(s, &size, &ptr, 2, US" H=", addr->host_list->name);
1098 s = d_log_interface(s, &size, &ptr);
1099 if (addr->shadow_message)
1100 s = string_cat(s, &size, &ptr, addr->shadow_message);
1101 }
1102
1103 /* Remote delivery */
1104
1105 else
1106 {
1107 if (addr->host_used)
1108 {
1109 s = d_hostlog(s, &size, &ptr, addr);
1110 if (continue_sequence > 1)
1111 s = string_catn(s, &size, &ptr, US"*", 1);
1112
1113 #ifndef DISABLE_EVENT
1114 deliver_host_address = addr->host_used->address;
1115 deliver_host_port = addr->host_used->port;
1116 deliver_host = addr->host_used->name;
1117
1118 /* DNS lookup status */
1119 lookup_dnssec_authenticated = addr->host_used->dnssec==DS_YES ? US"yes"
1120 : addr->host_used->dnssec==DS_NO ? US"no"
1121 : NULL;
1122 #endif
1123 }
1124
1125 #ifdef SUPPORT_TLS
1126 s = d_tlslog(s, &size, &ptr, addr);
1127 #endif
1128
1129 if (addr->authenticator)
1130 {
1131 s = string_append(s, &size, &ptr, 2, US" A=", addr->authenticator);
1132 if (addr->auth_id)
1133 {
1134 s = string_append(s, &size, &ptr, 2, US":", addr->auth_id);
1135 if (LOGGING(smtp_mailauth) && addr->auth_sndr)
1136 s = string_append(s, &size, &ptr, 2, US":", addr->auth_sndr);
1137 }
1138 }
1139
1140 #ifndef DISABLE_PRDR
1141 if (addr->flags & af_prdr_used)
1142 s = string_append(s, &size, &ptr, 1, US" PRDR");
1143 #endif
1144 }
1145
1146 /* confirmation message (SMTP (host_used) and LMTP (driver_name)) */
1147
1148 if ( LOGGING(smtp_confirmation)
1149 && addr->message
1150 && (addr->host_used || Ustrcmp(addr->transport->driver_name, "lmtp") == 0)
1151 )
1152 {
1153 unsigned i;
1154 unsigned lim = big_buffer_size < 1024 ? big_buffer_size : 1024;
1155 uschar *p = big_buffer;
1156 uschar *ss = addr->message;
1157 *p++ = '\"';
1158 for (i = 0; i < lim && ss[i] != 0; i++) /* limit logged amount */
1159 {
1160 if (ss[i] == '\"' || ss[i] == '\\') *p++ = '\\'; /* quote \ and " */
1161 *p++ = ss[i];
1162 }
1163 *p++ = '\"';
1164 *p = 0;
1165 s = string_append(s, &size, &ptr, 2, US" C=", big_buffer);
1166 }
1167
1168 /* Time on queue and actual time taken to deliver */
1169
1170 if (LOGGING(queue_time))
1171 s = string_append(s, &size, &ptr, 2, US" QT=",
1172 readconf_printtime( (int) ((long)time(NULL) - (long)received_time)) );
1173
1174 if (LOGGING(deliver_time))
1175 s = string_append(s, &size, &ptr, 2, US" DT=",
1176 readconf_printtime(addr->more_errno));
1177
1178 /* string_cat() always leaves room for the terminator. Release the
1179 store we used to build the line after writing it. */
1180
1181 s[ptr] = 0;
1182 log_write(0, flags, "%s", s);
1183
1184 #ifndef DISABLE_EVENT
1185 if (!msg) msg_event_raise(US"msg:delivery", addr);
1186 #endif
1187
1188 store_reset(reset_point);
1189 return;
1190 }
1191
1192
1193
1194 static void
1195 deferral_log(address_item * addr, uschar * now,
1196 int logflags, uschar * driver_name, uschar * driver_kind)
1197 {
1198 int size = 256; /* Used for a temporary, */
1199 int ptr = 0; /* expanding buffer, for */
1200 uschar * s; /* building log lines; */
1201 void * reset_point; /* released afterwards. */
1202
1203 uschar ss[32];
1204
1205 /* Build up the line that is used for both the message log and the main
1206 log. */
1207
1208 s = reset_point = store_get(size);
1209
1210 /* Create the address string for logging. Must not do this earlier, because
1211 an OK result may be changed to FAIL when a pipe returns text. */
1212
1213 s = string_log_address(s, &size, &ptr, addr, LOGGING(all_parents), FALSE);
1214
1215 if (*queue_name)
1216 s = string_append(s, &size, &ptr, 2, US" Q=", queue_name);
1217
1218 /* Either driver_name contains something and driver_kind contains
1219 " router" or " transport" (note the leading space), or driver_name is
1220 a null string and driver_kind contains "routing" without the leading
1221 space, if all routing has been deferred. When a domain has been held,
1222 so nothing has been done at all, both variables contain null strings. */
1223
1224 if (driver_name)
1225 {
1226 if (driver_kind[1] == 't' && addr->router)
1227 s = string_append(s, &size, &ptr, 2, US" R=", addr->router->name);
1228 Ustrcpy(ss, " ?=");
1229 ss[1] = toupper(driver_kind[1]);
1230 s = string_append(s, &size, &ptr, 2, ss, driver_name);
1231 }
1232 else if (driver_kind)
1233 s = string_append(s, &size, &ptr, 2, US" ", driver_kind);
1234
1235 /*XXX need an s+s+p sprintf */
1236 sprintf(CS ss, " defer (%d)", addr->basic_errno);
1237 s = string_cat(s, &size, &ptr, ss);
1238
1239 if (addr->basic_errno > 0)
1240 s = string_append(s, &size, &ptr, 2, US": ",
1241 US strerror(addr->basic_errno));
1242
1243 if (addr->host_used)
1244 {
1245 s = string_append(s, &size, &ptr, 5,
1246 US" H=", addr->host_used->name,
1247 US" [", addr->host_used->address, US"]");
1248 if (LOGGING(outgoing_port))
1249 {
1250 int port = addr->host_used->port;
1251 s = string_append(s, &size, &ptr, 2,
1252 US":", port == PORT_NONE ? US"25" : string_sprintf("%d", port));
1253 }
1254 }
1255
1256 if (addr->message)
1257 s = string_append(s, &size, &ptr, 2, US": ", addr->message);
1258
1259 s[ptr] = 0;
1260
1261 /* Log the deferment in the message log, but don't clutter it
1262 up with retry-time defers after the first delivery attempt. */
1263
1264 if (deliver_firsttime || addr->basic_errno > ERRNO_RETRY_BASE)
1265 deliver_msglog("%s %s\n", now, s);
1266
1267 /* Write the main log and reset the store.
1268 For errors of the type "retry time not reached" (also remotes skipped
1269 on queue run), logging is controlled by L_retry_defer. Note that this kind
1270 of error number is negative, and all the retry ones are less than any
1271 others. */
1272
1273
1274 log_write(addr->basic_errno <= ERRNO_RETRY_BASE ? L_retry_defer : 0, logflags,
1275 "== %s", s);
1276
1277 store_reset(reset_point);
1278 return;
1279 }
1280
1281
1282
1283 static void
1284 failure_log(address_item * addr, uschar * driver_kind, uschar * now)
1285 {
1286 int size = 256; /* Used for a temporary, */
1287 int ptr = 0; /* expanding buffer, for */
1288 uschar * s; /* building log lines; */
1289 void * reset_point; /* released afterwards. */
1290
1291 /* Build up the log line for the message and main logs */
1292
1293 s = reset_point = store_get(size);
1294
1295 /* Create the address string for logging. Must not do this earlier, because
1296 an OK result may be changed to FAIL when a pipe returns text. */
1297
1298 s = string_log_address(s, &size, &ptr, addr, LOGGING(all_parents), FALSE);
1299
1300 if (LOGGING(sender_on_delivery))
1301 s = string_append(s, &size, &ptr, 3, US" F=<", sender_address, US">");
1302
1303 if (*queue_name)
1304 s = string_append(s, &size, &ptr, 2, US" Q=", queue_name);
1305
1306 /* Return path may not be set if no delivery actually happened */
1307
1308 if (used_return_path && LOGGING(return_path_on_delivery))
1309 s = string_append(s, &size, &ptr, 3, US" P=<", used_return_path, US">");
1310
1311 if (addr->router)
1312 s = string_append(s, &size, &ptr, 2, US" R=", addr->router->name);
1313 if (addr->transport)
1314 s = string_append(s, &size, &ptr, 2, US" T=", addr->transport->name);
1315
1316 if (addr->host_used)
1317 s = d_hostlog(s, &size, &ptr, addr);
1318
1319 #ifdef SUPPORT_TLS
1320 s = d_tlslog(s, &size, &ptr, addr);
1321 #endif
1322
1323 if (addr->basic_errno > 0)
1324 s = string_append(s, &size, &ptr, 2, US": ", US strerror(addr->basic_errno));
1325
1326 if (addr->message)
1327 s = string_append(s, &size, &ptr, 2, US": ", addr->message);
1328
1329 s[ptr] = 0;
1330
1331 /* Do the logging. For the message log, "routing failed" for those cases,
1332 just to make it clearer. */
1333
1334 if (driver_kind)
1335 deliver_msglog("%s %s failed for %s\n", now, driver_kind, s);
1336 else
1337 deliver_msglog("%s %s\n", now, s);
1338
1339 log_write(0, LOG_MAIN, "** %s", s);
1340
1341 #ifndef DISABLE_EVENT
1342 msg_event_raise(US"msg:fail:delivery", addr);
1343 #endif
1344
1345 store_reset(reset_point);
1346 return;
1347 }
1348
1349
1350
1351 /*************************************************
1352 * Actions at the end of handling an address *
1353 *************************************************/
1354
1355 /* This is a function for processing a single address when all that can be done
1356 with it has been done.
1357
1358 Arguments:
1359 addr points to the address block
1360 result the result of the delivery attempt
1361 logflags flags for log_write() (LOG_MAIN and/or LOG_PANIC)
1362 driver_type indicates which type of driver (transport, or router) was last
1363 to process the address
1364 logchar '=' or '-' for use when logging deliveries with => or ->
1365
1366 Returns: nothing
1367 */
1368
1369 static void
1370 post_process_one(address_item *addr, int result, int logflags, int driver_type,
1371 int logchar)
1372 {
1373 uschar *now = tod_stamp(tod_log);
1374 uschar *driver_kind = NULL;
1375 uschar *driver_name = NULL;
1376
1377 DEBUG(D_deliver) debug_printf("post-process %s (%d)\n", addr->address, result);
1378
1379 /* Set up driver kind and name for logging. Disable logging if the router or
1380 transport has disabled it. */
1381
1382 if (driver_type == DTYPE_TRANSPORT)
1383 {
1384 if (addr->transport)
1385 {
1386 driver_name = addr->transport->name;
1387 driver_kind = US" transport";
1388 disable_logging = addr->transport->disable_logging;
1389 }
1390 else driver_kind = US"transporting";
1391 }
1392 else if (driver_type == DTYPE_ROUTER)
1393 {
1394 if (addr->router)
1395 {
1396 driver_name = addr->router->name;
1397 driver_kind = US" router";
1398 disable_logging = addr->router->disable_logging;
1399 }
1400 else driver_kind = US"routing";
1401 }
1402
1403 /* If there's an error message set, ensure that it contains only printing
1404 characters - it should, but occasionally things slip in and this at least
1405 stops the log format from getting wrecked. We also scan the message for an LDAP
1406 expansion item that has a password setting, and flatten the password. This is a
1407 fudge, but I don't know a cleaner way of doing this. (If the item is badly
1408 malformed, it won't ever have gone near LDAP.) */
1409
1410 if (addr->message)
1411 {
1412 const uschar * s = string_printing(addr->message);
1413
1414 /* deconst cast ok as string_printing known to have alloc'n'copied */
1415 addr->message = expand_hide_passwords(US s);
1416 }
1417
1418 /* If we used a transport that has one of the "return_output" options set, and
1419 if it did in fact generate some output, then for return_output we treat the
1420 message as failed if it was not already set that way, so that the output gets
1421 returned to the sender, provided there is a sender to send it to. For
1422 return_fail_output, do this only if the delivery failed. Otherwise we just
1423 unlink the file, and remove the name so that if the delivery failed, we don't
1424 try to send back an empty or unwanted file. The log_output options operate only
1425 on a non-empty file.
1426
1427 In any case, we close the message file, because we cannot afford to leave a
1428 file-descriptor for one address while processing (maybe very many) others. */
1429
1430 if (addr->return_file >= 0 && addr->return_filename)
1431 {
1432 BOOL return_output = FALSE;
1433 struct stat statbuf;
1434 (void)EXIMfsync(addr->return_file);
1435
1436 /* If there is no output, do nothing. */
1437
1438 if (fstat(addr->return_file, &statbuf) == 0 && statbuf.st_size > 0)
1439 {
1440 transport_instance *tb = addr->transport;
1441
1442 /* Handle logging options */
1443
1444 if ( tb->log_output
1445 || result == FAIL && tb->log_fail_output
1446 || result == DEFER && tb->log_defer_output
1447 )
1448 {
1449 uschar *s;
1450 FILE *f = Ufopen(addr->return_filename, "rb");
1451 if (!f)
1452 log_write(0, LOG_MAIN|LOG_PANIC, "failed to open %s to log output "
1453 "from %s transport: %s", addr->return_filename, tb->name,
1454 strerror(errno));
1455 else
1456 if ((s = US Ufgets(big_buffer, big_buffer_size, f)))
1457 {
1458 uschar *p = big_buffer + Ustrlen(big_buffer);
1459 const uschar * sp;
1460 while (p > big_buffer && isspace(p[-1])) p--;
1461 *p = 0;
1462 sp = string_printing(big_buffer);
1463 log_write(0, LOG_MAIN, "<%s>: %s transport output: %s",
1464 addr->address, tb->name, sp);
1465 }
1466 (void)fclose(f);
1467 }
1468
1469 /* Handle returning options, but only if there is an address to return
1470 the text to. */
1471
1472 if (sender_address[0] != 0 || addr->prop.errors_address)
1473 if (tb->return_output)
1474 {
1475 addr->transport_return = result = FAIL;
1476 if (addr->basic_errno == 0 && !addr->message)
1477 addr->message = US"return message generated";
1478 return_output = TRUE;
1479 }
1480 else
1481 if (tb->return_fail_output && result == FAIL) return_output = TRUE;
1482 }
1483
1484 /* Get rid of the file unless it might be returned, but close it in
1485 all cases. */
1486
1487 if (!return_output)
1488 {
1489 Uunlink(addr->return_filename);
1490 addr->return_filename = NULL;
1491 addr->return_file = -1;
1492 }
1493
1494 (void)close(addr->return_file);
1495 }
1496
1497 /* The success case happens only after delivery by a transport. */
1498
1499 if (result == OK)
1500 {
1501 addr->next = addr_succeed;
1502 addr_succeed = addr;
1503
1504 /* Call address_done() to ensure that we don't deliver to this address again,
1505 and write appropriate things to the message log. If it is a child address, we
1506 call child_done() to scan the ancestors and mark them complete if this is the
1507 last child to complete. */
1508
1509 address_done(addr, now);
1510 DEBUG(D_deliver) debug_printf("%s delivered\n", addr->address);
1511
1512 if (!addr->parent)
1513 deliver_msglog("%s %s: %s%s succeeded\n", now, addr->address,
1514 driver_name, driver_kind);
1515 else
1516 {
1517 deliver_msglog("%s %s <%s>: %s%s succeeded\n", now, addr->address,
1518 addr->parent->address, driver_name, driver_kind);
1519 child_done(addr, now);
1520 }
1521
1522 /* Certificates for logging (via events) */
1523 #ifdef SUPPORT_TLS
1524 tls_out.ourcert = addr->ourcert;
1525 addr->ourcert = NULL;
1526 tls_out.peercert = addr->peercert;
1527 addr->peercert = NULL;
1528
1529 tls_out.cipher = addr->cipher;
1530 tls_out.peerdn = addr->peerdn;
1531 tls_out.ocsp = addr->ocsp;
1532 # ifdef EXPERIMENTAL_DANE
1533 tls_out.dane_verified = testflag(addr, af_dane_verified);
1534 # endif
1535 #endif
1536
1537 delivery_log(LOG_MAIN, addr, logchar, NULL);
1538
1539 #ifdef SUPPORT_TLS
1540 tls_free_cert(&tls_out.ourcert);
1541 tls_free_cert(&tls_out.peercert);
1542 tls_out.cipher = NULL;
1543 tls_out.peerdn = NULL;
1544 tls_out.ocsp = OCSP_NOT_REQ;
1545 # ifdef EXPERIMENTAL_DANE
1546 tls_out.dane_verified = FALSE;
1547 # endif
1548 #endif
1549 }
1550
1551
1552 /* Soft failure, or local delivery process failed; freezing may be
1553 requested. */
1554
1555 else if (result == DEFER || result == PANIC)
1556 {
1557 if (result == PANIC) logflags |= LOG_PANIC;
1558
1559 /* This puts them on the chain in reverse order. Do not change this, because
1560 the code for handling retries assumes that the one with the retry
1561 information is last. */
1562
1563 addr->next = addr_defer;
1564 addr_defer = addr;
1565
1566 /* The only currently implemented special action is to freeze the
1567 message. Logging of this is done later, just before the -H file is
1568 updated. */
1569
1570 if (addr->special_action == SPECIAL_FREEZE)
1571 {
1572 deliver_freeze = TRUE;
1573 deliver_frozen_at = time(NULL);
1574 update_spool = TRUE;
1575 }
1576
1577 /* If doing a 2-stage queue run, we skip writing to either the message
1578 log or the main log for SMTP defers. */
1579
1580 if (!queue_2stage || addr->basic_errno != 0)
1581 deferral_log(addr, now, logflags, driver_name, driver_kind);
1582 }
1583
1584
1585 /* Hard failure. If there is an address to which an error message can be sent,
1586 put this address on the failed list. If not, put it on the deferred list and
1587 freeze the mail message for human attention. The latter action can also be
1588 explicitly requested by a router or transport. */
1589
1590 else
1591 {
1592 /* If this is a delivery error, or a message for which no replies are
1593 wanted, and the message's age is greater than ignore_bounce_errors_after,
1594 force the af_ignore_error flag. This will cause the address to be discarded
1595 later (with a log entry). */
1596
1597 if (sender_address[0] == 0 && message_age >= ignore_bounce_errors_after)
1598 setflag(addr, af_ignore_error);
1599
1600 /* Freeze the message if requested, or if this is a bounce message (or other
1601 message with null sender) and this address does not have its own errors
1602 address. However, don't freeze if errors are being ignored. The actual code
1603 to ignore occurs later, instead of sending a message. Logging of freezing
1604 occurs later, just before writing the -H file. */
1605
1606 if ( !testflag(addr, af_ignore_error)
1607 && ( addr->special_action == SPECIAL_FREEZE
1608 || (sender_address[0] == 0 && !addr->prop.errors_address)
1609 ) )
1610 {
1611 frozen_info = addr->special_action == SPECIAL_FREEZE
1612 ? US""
1613 : sender_local && !local_error_message
1614 ? US" (message created with -f <>)"
1615 : US" (delivery error message)";
1616 deliver_freeze = TRUE;
1617 deliver_frozen_at = time(NULL);
1618 update_spool = TRUE;
1619
1620 /* The address is put on the defer rather than the failed queue, because
1621 the message is being retained. */
1622
1623 addr->next = addr_defer;
1624 addr_defer = addr;
1625 }
1626
1627 /* Don't put the address on the nonrecipients tree yet; wait until an
1628 error message has been successfully sent. */
1629
1630 else
1631 {
1632 addr->next = addr_failed;
1633 addr_failed = addr;
1634 }
1635
1636 failure_log(addr, driver_name ? NULL : driver_kind, now);
1637 }
1638
1639 /* Ensure logging is turned on again in all cases */
1640
1641 disable_logging = FALSE;
1642 }
1643
1644
1645
1646
1647 /*************************************************
1648 * Address-independent error *
1649 *************************************************/
1650
1651 /* This function is called when there's an error that is not dependent on a
1652 particular address, such as an expansion string failure. It puts the error into
1653 all the addresses in a batch, logs the incident on the main and panic logs, and
1654 clears the expansions. It is mostly called from local_deliver(), but can be
1655 called for a remote delivery via findugid().
1656
1657 Arguments:
1658 logit TRUE if (MAIN+PANIC) logging required
1659 addr the first of the chain of addresses
1660 code the error code
1661 format format string for error message, or NULL if already set in addr
1662 ... arguments for the format
1663
1664 Returns: nothing
1665 */
1666
1667 static void
1668 common_error(BOOL logit, address_item *addr, int code, uschar *format, ...)
1669 {
1670 address_item *addr2;
1671 addr->basic_errno = code;
1672
1673 if (format)
1674 {
1675 va_list ap;
1676 uschar buffer[512];
1677 va_start(ap, format);
1678 if (!string_vformat(buffer, sizeof(buffer), CS format, ap))
1679 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1680 "common_error expansion was longer than " SIZE_T_FMT, sizeof(buffer));
1681 va_end(ap);
1682 addr->message = string_copy(buffer);
1683 }
1684
1685 for (addr2 = addr->next; addr2; addr2 = addr2->next)
1686 {
1687 addr2->basic_errno = code;
1688 addr2->message = addr->message;
1689 }
1690
1691 if (logit) log_write(0, LOG_MAIN|LOG_PANIC, "%s", addr->message);
1692 deliver_set_expansions(NULL);
1693 }
1694
1695
1696
1697
1698 /*************************************************
1699 * Check a "never users" list *
1700 *************************************************/
1701
1702 /* This function is called to check whether a uid is on one of the two "never
1703 users" lists.
1704
1705 Arguments:
1706 uid the uid to be checked
1707 nusers the list to be scanned; the first item in the list is the count
1708
1709 Returns: TRUE if the uid is on the list
1710 */
1711
1712 static BOOL
1713 check_never_users(uid_t uid, uid_t *nusers)
1714 {
1715 int i;
1716 if (!nusers) return FALSE;
1717 for (i = 1; i <= (int)(nusers[0]); i++) if (nusers[i] == uid) return TRUE;
1718 return FALSE;
1719 }
1720
1721
1722
1723 /*************************************************
1724 * Find uid and gid for a transport *
1725 *************************************************/
1726
1727 /* This function is called for both local and remote deliveries, to find the
1728 uid/gid under which to run the delivery. The values are taken preferentially
1729 from the transport (either explicit or deliver_as_creator), then from the
1730 address (i.e. the router), and if nothing is set, the exim uid/gid are used. If
1731 the resulting uid is on the "never_users" or the "fixed_never_users" list, a
1732 panic error is logged, and the function fails (which normally leads to delivery
1733 deferral).
1734
1735 Arguments:
1736 addr the address (possibly a chain)
1737 tp the transport
1738 uidp pointer to uid field
1739 gidp pointer to gid field
1740 igfp pointer to the use_initgroups field
1741
1742 Returns: FALSE if failed - error has been set in address(es)
1743 */
1744
1745 static BOOL
1746 findugid(address_item *addr, transport_instance *tp, uid_t *uidp, gid_t *gidp,
1747 BOOL *igfp)
1748 {
1749 uschar *nuname;
1750 BOOL gid_set = FALSE;
1751
1752 /* Default initgroups flag comes from the transport */
1753
1754 *igfp = tp->initgroups;
1755
1756 /* First see if there's a gid on the transport, either fixed or expandable.
1757 The expanding function always logs failure itself. */
1758
1759 if (tp->gid_set)
1760 {
1761 *gidp = tp->gid;
1762 gid_set = TRUE;
1763 }
1764 else if (tp->expand_gid)
1765 {
1766 if (!route_find_expanded_group(tp->expand_gid, tp->name, US"transport", gidp,
1767 &(addr->message)))
1768 {
1769 common_error(FALSE, addr, ERRNO_GIDFAIL, NULL);
1770 return FALSE;
1771 }
1772 gid_set = TRUE;
1773 }
1774
1775 /* If the transport did not set a group, see if the router did. */
1776
1777 if (!gid_set && testflag(addr, af_gid_set))
1778 {
1779 *gidp = addr->gid;
1780 gid_set = TRUE;
1781 }
1782
1783 /* Pick up a uid from the transport if one is set. */
1784
1785 if (tp->uid_set) *uidp = tp->uid;
1786
1787 /* Otherwise, try for an expandable uid field. If it ends up as a numeric id,
1788 it does not provide a passwd value from which a gid can be taken. */
1789
1790 else if (tp->expand_uid)
1791 {
1792 struct passwd *pw;
1793 if (!route_find_expanded_user(tp->expand_uid, tp->name, US"transport", &pw,
1794 uidp, &(addr->message)))
1795 {
1796 common_error(FALSE, addr, ERRNO_UIDFAIL, NULL);
1797 return FALSE;
1798 }
1799 if (!gid_set && pw)
1800 {
1801 *gidp = pw->pw_gid;
1802 gid_set = TRUE;
1803 }
1804 }
1805
1806 /* If the transport doesn't set the uid, test the deliver_as_creator flag. */
1807
1808 else if (tp->deliver_as_creator)
1809 {
1810 *uidp = originator_uid;
1811 if (!gid_set)
1812 {
1813 *gidp = originator_gid;
1814 gid_set = TRUE;
1815 }
1816 }
1817
1818 /* Otherwise see if the address specifies the uid and if so, take it and its
1819 initgroups flag. */
1820
1821 else if (testflag(addr, af_uid_set))
1822 {
1823 *uidp = addr->uid;
1824 *igfp = testflag(addr, af_initgroups);
1825 }
1826
1827 /* Nothing has specified the uid - default to the Exim user, and group if the
1828 gid is not set. */
1829
1830 else
1831 {
1832 *uidp = exim_uid;
1833 if (!gid_set)
1834 {
1835 *gidp = exim_gid;
1836 gid_set = TRUE;
1837 }
1838 }
1839
1840 /* If no gid is set, it is a disaster. We default to the Exim gid only if
1841 defaulting to the Exim uid. In other words, if the configuration has specified
1842 a uid, it must also provide a gid. */
1843
1844 if (!gid_set)
1845 {
1846 common_error(TRUE, addr, ERRNO_GIDFAIL, US"User set without group for "
1847 "%s transport", tp->name);
1848 return FALSE;
1849 }
1850
1851 /* Check that the uid is not on the lists of banned uids that may not be used
1852 for delivery processes. */
1853
1854 nuname = check_never_users(*uidp, never_users)
1855 ? US"never_users"
1856 : check_never_users(*uidp, fixed_never_users)
1857 ? US"fixed_never_users"
1858 : NULL;
1859 if (nuname)
1860 {
1861 common_error(TRUE, addr, ERRNO_UIDFAIL, US"User %ld set for %s transport "
1862 "is on the %s list", (long int)(*uidp), tp->name, nuname);
1863 return FALSE;
1864 }
1865
1866 /* All is well */
1867
1868 return TRUE;
1869 }
1870
1871
1872
1873
1874 /*************************************************
1875 * Check the size of a message for a transport *
1876 *************************************************/
1877
1878 /* Checks that the message isn't too big for the selected transport.
1879 This is called only when it is known that the limit is set.
1880
1881 Arguments:
1882 tp the transport
1883 addr the (first) address being delivered
1884
1885 Returns: OK
1886 DEFER expansion failed or did not yield an integer
1887 FAIL message too big
1888 */
1889
1890 int
1891 check_message_size(transport_instance *tp, address_item *addr)
1892 {
1893 int rc = OK;
1894 int size_limit;
1895
1896 deliver_set_expansions(addr);
1897 size_limit = expand_string_integer(tp->message_size_limit, TRUE);
1898 deliver_set_expansions(NULL);
1899
1900 if (expand_string_message)
1901 {
1902 rc = DEFER;
1903 addr->message = size_limit == -1
1904 ? string_sprintf("failed to expand message_size_limit "
1905 "in %s transport: %s", tp->name, expand_string_message)
1906 : string_sprintf("invalid message_size_limit "
1907 "in %s transport: %s", tp->name, expand_string_message);
1908 }
1909 else if (size_limit > 0 && message_size > size_limit)
1910 {
1911 rc = FAIL;
1912 addr->message =
1913 string_sprintf("message is too big (transport limit = %d)",
1914 size_limit);
1915 }
1916
1917 return rc;
1918 }
1919
1920
1921
1922 /*************************************************
1923 * Transport-time check for a previous delivery *
1924 *************************************************/
1925
1926 /* Check that this base address hasn't previously been delivered to its routed
1927 transport. If it has been delivered, mark it done. The check is necessary at
1928 delivery time in order to handle homonymic addresses correctly in cases where
1929 the pattern of redirection changes between delivery attempts (so the unique
1930 fields change). Non-homonymic previous delivery is detected earlier, at routing
1931 time (which saves unnecessary routing).
1932
1933 Arguments:
1934 addr the address item
1935 testing TRUE if testing wanted only, without side effects
1936
1937 Returns: TRUE if previously delivered by the transport
1938 */
1939
1940 static BOOL
1941 previously_transported(address_item *addr, BOOL testing)
1942 {
1943 (void)string_format(big_buffer, big_buffer_size, "%s/%s",
1944 addr->unique + (testflag(addr, af_homonym)? 3:0), addr->transport->name);
1945
1946 if (tree_search(tree_nonrecipients, big_buffer) != 0)
1947 {
1948 DEBUG(D_deliver|D_route|D_transport)
1949 debug_printf("%s was previously delivered (%s transport): discarded\n",
1950 addr->address, addr->transport->name);
1951 if (!testing) child_done(addr, tod_stamp(tod_log));
1952 return TRUE;
1953 }
1954
1955 return FALSE;
1956 }
1957
1958
1959
1960 /******************************************************
1961 * Check for a given header in a header string *
1962 ******************************************************/
1963
1964 /* This function is used when generating quota warnings. The configuration may
1965 specify any header lines it likes in quota_warn_message. If certain of them are
1966 missing, defaults are inserted, so we need to be able to test for the presence
1967 of a given header.
1968
1969 Arguments:
1970 hdr the required header name
1971 hstring the header string
1972
1973 Returns: TRUE the header is in the string
1974 FALSE the header is not in the string
1975 */
1976
1977 static BOOL
1978 contains_header(uschar *hdr, uschar *hstring)
1979 {
1980 int len = Ustrlen(hdr);
1981 uschar *p = hstring;
1982 while (*p != 0)
1983 {
1984 if (strncmpic(p, hdr, len) == 0)
1985 {
1986 p += len;
1987 while (*p == ' ' || *p == '\t') p++;
1988 if (*p == ':') return TRUE;
1989 }
1990 while (*p != 0 && *p != '\n') p++;
1991 if (*p == '\n') p++;
1992 }
1993 return FALSE;
1994 }
1995
1996
1997
1998
1999 /*************************************************
2000 * Perform a local delivery *
2001 *************************************************/
2002
2003 /* Each local delivery is performed in a separate process which sets its
2004 uid and gid as specified. This is a safer way than simply changing and
2005 restoring using seteuid(); there is a body of opinion that seteuid() cannot be
2006 used safely. From release 4, Exim no longer makes any use of it. Besides, not
2007 all systems have seteuid().
2008
2009 If the uid/gid are specified in the transport_instance, they are used; the
2010 transport initialization must ensure that either both or neither are set.
2011 Otherwise, the values associated with the address are used. If neither are set,
2012 it is a configuration error.
2013
2014 The transport or the address may specify a home directory (transport over-
2015 rides), and if they do, this is set as $home. If neither have set a working
2016 directory, this value is used for that as well. Otherwise $home is left unset
2017 and the cwd is set to "/" - a directory that should be accessible to all users.
2018
2019 Using a separate process makes it more complicated to get error information
2020 back. We use a pipe to pass the return code and also an error code and error
2021 text string back to the parent process.
2022
2023 Arguments:
2024 addr points to an address block for this delivery; for "normal" local
2025 deliveries this is the only address to be delivered, but for
2026 pseudo-remote deliveries (e.g. by batch SMTP to a file or pipe)
2027 a number of addresses can be handled simultaneously, and in this
2028 case addr will point to a chain of addresses with the same
2029 characteristics.
2030
2031 shadowing TRUE if running a shadow transport; this causes output from pipes
2032 to be ignored.
2033
2034 Returns: nothing
2035 */
2036
2037 static void
2038 deliver_local(address_item *addr, BOOL shadowing)
2039 {
2040 BOOL use_initgroups;
2041 uid_t uid;
2042 gid_t gid;
2043 int status, len, rc;
2044 int pfd[2];
2045 pid_t pid;
2046 uschar *working_directory;
2047 address_item *addr2;
2048 transport_instance *tp = addr->transport;
2049
2050 /* Set up the return path from the errors or sender address. If the transport
2051 has its own return path setting, expand it and replace the existing value. */
2052
2053 if(addr->prop.errors_address)
2054 return_path = addr->prop.errors_address;
2055 #ifdef EXPERIMENTAL_SRS
2056 else if (addr->prop.srs_sender)
2057 return_path = addr->prop.srs_sender;
2058 #endif
2059 else
2060 return_path = sender_address;
2061
2062 if (tp->return_path)
2063 {
2064 uschar *new_return_path = expand_string(tp->return_path);
2065 if (!new_return_path)
2066 {
2067 if (!expand_string_forcedfail)
2068 {
2069 common_error(TRUE, addr, ERRNO_EXPANDFAIL,
2070 US"Failed to expand return path \"%s\" in %s transport: %s",
2071 tp->return_path, tp->name, expand_string_message);
2072 return;
2073 }
2074 }
2075 else return_path = new_return_path;
2076 }
2077
2078 /* For local deliveries, one at a time, the value used for logging can just be
2079 set directly, once and for all. */
2080
2081 used_return_path = return_path;
2082
2083 /* Sort out the uid, gid, and initgroups flag. If an error occurs, the message
2084 gets put into the address(es), and the expansions are unset, so we can just
2085 return. */
2086
2087 if (!findugid(addr, tp, &uid, &gid, &use_initgroups)) return;
2088
2089 /* See if either the transport or the address specifies a home directory. A
2090 home directory set in the address may already be expanded; a flag is set to
2091 indicate that. In other cases we must expand it. */
2092
2093 if ( (deliver_home = tp->home_dir) /* Set in transport, or */
2094 || ( (deliver_home = addr->home_dir) /* Set in address and */
2095 && !testflag(addr, af_home_expanded) /* not expanded */
2096 ) )
2097 {
2098 uschar *rawhome = deliver_home;
2099 deliver_home = NULL; /* in case it contains $home */
2100 if (!(deliver_home = expand_string(rawhome)))
2101 {
2102 common_error(TRUE, addr, ERRNO_EXPANDFAIL, US"home directory \"%s\" failed "
2103 "to expand for %s transport: %s", rawhome, tp->name,
2104 expand_string_message);
2105 return;
2106 }
2107 if (*deliver_home != '/')
2108 {
2109 common_error(TRUE, addr, ERRNO_NOTABSOLUTE, US"home directory path \"%s\" "
2110 "is not absolute for %s transport", deliver_home, tp->name);
2111 return;
2112 }
2113 }
2114
2115 /* See if either the transport or the address specifies a current directory,
2116 and if so, expand it. If nothing is set, use the home directory, unless it is
2117 also unset in which case use "/", which is assumed to be a directory to which
2118 all users have access. It is necessary to be in a visible directory for some
2119 operating systems when running pipes, as some commands (e.g. "rm" under Solaris
2120 2.5) require this. */
2121
2122 working_directory = tp->current_dir ? tp->current_dir : addr->current_dir;
2123 if (working_directory)
2124 {
2125 uschar *raw = working_directory;
2126 if (!(working_directory = expand_string(raw)))
2127 {
2128 common_error(TRUE, addr, ERRNO_EXPANDFAIL, US"current directory \"%s\" "
2129 "failed to expand for %s transport: %s", raw, tp->name,
2130 expand_string_message);
2131 return;
2132 }
2133 if (*working_directory != '/')
2134 {
2135 common_error(TRUE, addr, ERRNO_NOTABSOLUTE, US"current directory path "
2136 "\"%s\" is not absolute for %s transport", working_directory, tp->name);
2137 return;
2138 }
2139 }
2140 else working_directory = deliver_home ? deliver_home : US"/";
2141
2142 /* If one of the return_output flags is set on the transport, create and open a
2143 file in the message log directory for the transport to write its output onto.
2144 This is mainly used by pipe transports. The file needs to be unique to the
2145 address. This feature is not available for shadow transports. */
2146
2147 if ( !shadowing
2148 && ( tp->return_output || tp->return_fail_output
2149 || tp->log_output || tp->log_fail_output || tp->log_defer_output
2150 ) )
2151 {
2152 uschar * error;
2153
2154 addr->return_filename =
2155 spool_fname(US"msglog", message_subdir, message_id,
2156 string_sprintf("-%d-%d", getpid(), return_count++));
2157
2158 if ((addr->return_file = open_msglog_file(addr->return_filename, 0400, &error)) < 0)
2159 {
2160 common_error(TRUE, addr, errno, US"Unable to %s file for %s transport "
2161 "to return message: %s", error, tp->name, strerror(errno));
2162 return;
2163 }
2164 }
2165
2166 /* Create the pipe for inter-process communication. */
2167
2168 if (pipe(pfd) != 0)
2169 {
2170 common_error(TRUE, addr, ERRNO_PIPEFAIL, US"Creation of pipe failed: %s",
2171 strerror(errno));
2172 return;
2173 }
2174
2175 /* Now fork the process to do the real work in the subprocess, but first
2176 ensure that all cached resources are freed so that the subprocess starts with
2177 a clean slate and doesn't interfere with the parent process. */
2178
2179 search_tidyup();
2180
2181 if ((pid = fork()) == 0)
2182 {
2183 BOOL replicate = TRUE;
2184
2185 /* Prevent core dumps, as we don't want them in users' home directories.
2186 HP-UX doesn't have RLIMIT_CORE; I don't know how to do this in that
2187 system. Some experimental/developing systems (e.g. GNU/Hurd) may define
2188 RLIMIT_CORE but not support it in setrlimit(). For such systems, do not
2189 complain if the error is "not supported".
2190
2191 There are two scenarios where changing the max limit has an effect. In one,
2192 the user is using a .forward and invoking a command of their choice via pipe;
2193 for these, we do need the max limit to be 0 unless the admin chooses to
2194 permit an increased limit. In the other, the command is invoked directly by
2195 the transport and is under administrator control, thus being able to raise
2196 the limit aids in debugging. So there's no general always-right answer.
2197
2198 Thus we inhibit core-dumps completely but let individual transports, while
2199 still root, re-raise the limits back up to aid debugging. We make the
2200 default be no core-dumps -- few enough people can use core dumps in
2201 diagnosis that it's reasonable to make them something that has to be explicitly requested.
2202 */
2203
2204 #ifdef RLIMIT_CORE
2205 struct rlimit rl;
2206 rl.rlim_cur = 0;
2207 rl.rlim_max = 0;
2208 if (setrlimit(RLIMIT_CORE, &rl) < 0)
2209 {
2210 # ifdef SETRLIMIT_NOT_SUPPORTED
2211 if (errno != ENOSYS && errno != ENOTSUP)
2212 # endif
2213 log_write(0, LOG_MAIN|LOG_PANIC, "setrlimit(RLIMIT_CORE) failed: %s",
2214 strerror(errno));
2215 }
2216 #endif
2217
2218 /* Reset the random number generator, so different processes don't all
2219 have the same sequence. */
2220
2221 random_seed = 0;
2222
2223 /* If the transport has a setup entry, call this first, while still
2224 privileged. (Appendfile uses this to expand quota, for example, while
2225 able to read private files.) */
2226
2227 if (addr->transport->setup)
2228 switch((addr->transport->setup)(addr->transport, addr, NULL, uid, gid,
2229 &(addr->message)))
2230 {
2231 case DEFER:
2232 addr->transport_return = DEFER;
2233 goto PASS_BACK;
2234
2235 case FAIL:
2236 addr->transport_return = PANIC;
2237 goto PASS_BACK;
2238 }
2239
2240 /* Ignore SIGINT and SIGTERM during delivery. Also ignore SIGUSR1, as
2241 when the process becomes unprivileged, it won't be able to write to the
2242 process log. SIGHUP is ignored throughout exim, except when it is being
2243 run as a daemon. */
2244
2245 signal(SIGINT, SIG_IGN);
2246 signal(SIGTERM, SIG_IGN);
2247 signal(SIGUSR1, SIG_IGN);
2248
2249 /* Close the unwanted half of the pipe, and set close-on-exec for the other
2250 half - for transports that exec things (e.g. pipe). Then set the required
2251 gid/uid. */
2252
2253 (void)close(pfd[pipe_read]);
2254 (void)fcntl(pfd[pipe_write], F_SETFD, fcntl(pfd[pipe_write], F_GETFD) |
2255 FD_CLOEXEC);
2256 exim_setugid(uid, gid, use_initgroups,
2257 string_sprintf("local delivery to %s <%s> transport=%s", addr->local_part,
2258 addr->address, addr->transport->name));
2259
2260 DEBUG(D_deliver)
2261 {
2262 address_item *batched;
2263 debug_printf(" home=%s current=%s\n", deliver_home, working_directory);
2264 for (batched = addr->next; batched; batched = batched->next)
2265 debug_printf("additional batched address: %s\n", batched->address);
2266 }
2267
2268 /* Set an appropriate working directory. */
2269
2270 if (Uchdir(working_directory) < 0)
2271 {
2272 addr->transport_return = DEFER;
2273 addr->basic_errno = errno;
2274 addr->message = string_sprintf("failed to chdir to %s", working_directory);
2275 }
2276
2277 /* If successful, call the transport */
2278
2279 else
2280 {
2281 BOOL ok = TRUE;
2282 set_process_info("delivering %s to %s using %s", message_id,
2283 addr->local_part, addr->transport->name);
2284
2285 /* Setting this global in the subprocess means we need never clear it */
2286 transport_name = addr->transport->name;
2287
2288 /* If a transport filter has been specified, set up its argument list.
2289 Any errors will get put into the address, and FALSE yielded. */
2290
2291 if (addr->transport->filter_command)
2292 {
2293 ok = transport_set_up_command(&transport_filter_argv,
2294 addr->transport->filter_command,
2295 TRUE, PANIC, addr, US"transport filter", NULL);
2296 transport_filter_timeout = addr->transport->filter_timeout;
2297 }
2298 else transport_filter_argv = NULL;
2299
2300 if (ok)
2301 {
2302 debug_print_string(addr->transport->debug_string);
2303 replicate = !(addr->transport->info->code)(addr->transport, addr);
2304 }
2305 }
2306
2307 /* Pass the results back down the pipe. If necessary, first replicate the
2308 status in the top address to the others in the batch. The label is the
2309 subject of a goto when a call to the transport's setup function fails. We
2310 pass the pointer to the transport back in case it got changed as a result of
2311 file_format in appendfile. */
2312
2313 PASS_BACK:
2314
2315 if (replicate) replicate_status(addr);
2316 for (addr2 = addr; addr2; addr2 = addr2->next)
2317 {
2318 int i;
2319 int local_part_length = Ustrlen(addr2->local_part);
2320 uschar *s;
2321 int ret;
2322
2323 if( (ret = write(pfd[pipe_write], &addr2->transport_return, sizeof(int))) != sizeof(int)
2324 || (ret = write(pfd[pipe_write], &transport_count, sizeof(transport_count))) != sizeof(transport_count)
2325 || (ret = write(pfd[pipe_write], &addr2->flags, sizeof(addr2->flags))) != sizeof(addr2->flags)
2326 || (ret = write(pfd[pipe_write], &addr2->basic_errno, sizeof(int))) != sizeof(int)
2327 || (ret = write(pfd[pipe_write], &addr2->more_errno, sizeof(int))) != sizeof(int)
2328 || (ret = write(pfd[pipe_write], &addr2->special_action, sizeof(int))) != sizeof(int)
2329 || (ret = write(pfd[pipe_write], &addr2->transport,
2330 sizeof(transport_instance *))) != sizeof(transport_instance *)
2331
2332 /* For a file delivery, pass back the local part, in case the original
2333 was only part of the final delivery path. This gives more complete
2334 logging. */
2335
2336 || (testflag(addr2, af_file)
2337 && ( (ret = write(pfd[pipe_write], &local_part_length, sizeof(int))) != sizeof(int)
2338 || (ret = write(pfd[pipe_write], addr2->local_part, local_part_length)) != local_part_length
2339 )
2340 )
2341 )
2342 log_write(0, LOG_MAIN|LOG_PANIC, "Failed writing transport results to pipe: %s\n",
2343 ret == -1 ? strerror(errno) : "short write");
2344
2345 /* Now any messages */
2346
2347 for (i = 0, s = addr2->message; i < 2; i++, s = addr2->user_message)
2348 {
2349 int message_length = s ? Ustrlen(s) + 1 : 0;
2350 if( (ret = write(pfd[pipe_write], &message_length, sizeof(int))) != sizeof(int)
2351 || message_length > 0 && (ret = write(pfd[pipe_write], s, message_length)) != message_length
2352 )
2353 log_write(0, LOG_MAIN|LOG_PANIC, "Failed writing transport results to pipe: %s\n",
2354 ret == -1 ? strerror(errno) : "short write");
2355 }
2356 }
2357
2358 /* OK, this process is now done. Free any cached resources that it opened,
2359 and close the pipe we were writing down before exiting. */
2360
2361 (void)close(pfd[pipe_write]);
2362 search_tidyup();
2363 exit(EXIT_SUCCESS);
2364 }
2365
2366 /* Back in the main process: panic if the fork did not succeed. This seems
2367 better than returning an error - if forking is failing it is probably best
2368 not to try other deliveries for this message. */
2369
2370 if (pid < 0)
2371 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Fork failed for local delivery to %s",
2372 addr->address);
2373
2374 /* Read the pipe to get the delivery status codes and error messages. Our copy
2375 of the writing end must be closed first, as otherwise read() won't return zero
2376 on an empty pipe. We check that a status exists for each address before
2377 overwriting the address structure. If data is missing, the default DEFER status
2378 will remain. Afterwards, close the reading end. */
2379
2380 (void)close(pfd[pipe_write]);
2381
2382 for (addr2 = addr; addr2; addr2 = addr2->next)
2383 {
2384 len = read(pfd[pipe_read], &status, sizeof(int));
2385 if (len > 0)
2386 {
2387 int i;
2388 uschar **sptr;
2389
2390 addr2->transport_return = status;
2391 len = read(pfd[pipe_read], &transport_count,
2392 sizeof(transport_count));
2393 len = read(pfd[pipe_read], &addr2->flags, sizeof(addr2->flags));
2394 len = read(pfd[pipe_read], &addr2->basic_errno, sizeof(int));
2395 len = read(pfd[pipe_read], &addr2->more_errno, sizeof(int));
2396 len = read(pfd[pipe_read], &addr2->special_action, sizeof(int));
2397 len = read(pfd[pipe_read], &addr2->transport,
2398 sizeof(transport_instance *));
2399
2400 if (testflag(addr2, af_file))
2401 {
2402 int local_part_length;
2403 len = read(pfd[pipe_read], &local_part_length, sizeof(int));
2404 len = read(pfd[pipe_read], big_buffer, local_part_length);
2405 big_buffer[local_part_length] = 0;
2406 addr2->local_part = string_copy(big_buffer);
2407 }
2408
2409 for (i = 0, sptr = &addr2->message; i < 2; i++, sptr = &addr2->user_message)
2410 {
2411 int message_length;
2412 len = read(pfd[pipe_read], &message_length, sizeof(int));
2413 if (message_length > 0)
2414 {
2415 len = read(pfd[pipe_read], big_buffer, message_length);
2416 big_buffer[big_buffer_size-1] = '\0'; /* guard byte */
2417 if (len > 0) *sptr = string_copy(big_buffer);
2418 }
2419 }
2420 }
2421
2422 else
2423 {
2424 log_write(0, LOG_MAIN|LOG_PANIC, "failed to read delivery status for %s "
2425 "from delivery subprocess", addr2->unique);
2426 break;
2427 }
2428 }
2429
2430 (void)close(pfd[pipe_read]);
2431
2432 /* Unless shadowing, write all successful addresses immediately to the journal
2433 file, to ensure they are recorded asap. For homonymic addresses, use the base
2434 address plus the transport name. Failure to write the journal is panic-worthy,
2435 but don't stop, as it may prove possible subsequently to update the spool file
2436 in order to record the delivery. */
2437
2438 if (!shadowing)
2439 {
2440 for (addr2 = addr; addr2; addr2 = addr2->next)
2441 if (addr2->transport_return == OK)
2442 {
2443 if (testflag(addr2, af_homonym))
2444 sprintf(CS big_buffer, "%.500s/%s\n", addr2->unique + 3, tp->name);
2445 else
2446 sprintf(CS big_buffer, "%.500s\n", addr2->unique);
2447
2448 /* In the test harness, wait just a bit to let the subprocess finish off
2449 any debug output etc first. */
2450
2451 if (running_in_test_harness) millisleep(300);
2452
2453 DEBUG(D_deliver) debug_printf("journalling %s", big_buffer);
2454 len = Ustrlen(big_buffer);
2455 if (write(journal_fd, big_buffer, len) != len)
2456 log_write(0, LOG_MAIN|LOG_PANIC, "failed to update journal for %s: %s",
2457 big_buffer, strerror(errno));
2458 }
2459
2460 /* Ensure the journal file is pushed out to disk. */
2461
2462 if (EXIMfsync(journal_fd) < 0)
2463 log_write(0, LOG_MAIN|LOG_PANIC, "failed to fsync journal: %s",
2464 strerror(errno));
2465 }
2466
2467 /* Wait for the process to finish. If it terminates with a non-zero code,
2468 freeze the message (except for SIGTERM, SIGKILL and SIGQUIT), but leave the
2469 status values of all the addresses as they are. Take care to handle the case
2470 when the subprocess doesn't seem to exist. This has been seen on one system
2471 when Exim was called from an MUA that set SIGCHLD to SIG_IGN. When that
2472 happens, wait() doesn't recognize the termination of child processes. Exim now
2473 resets SIGCHLD to SIG_DFL, but this code should still be robust. */
2474
2475 while ((rc = wait(&status)) != pid)
2476 if (rc < 0 && errno == ECHILD) /* Process has vanished */
2477 {
2478 log_write(0, LOG_MAIN, "%s transport process vanished unexpectedly",
2479 addr->transport->driver_name);
2480 status = 0;
2481 break;
2482 }
2483
2484 if ((status & 0xffff) != 0)
2485 {
2486 int msb = (status >> 8) & 255;
2487 int lsb = status & 255;
2488 int code = (msb == 0)? (lsb & 0x7f) : msb;
2489 if (msb != 0 || (code != SIGTERM && code != SIGKILL && code != SIGQUIT))
2490 addr->special_action = SPECIAL_FREEZE;
2491 log_write(0, LOG_MAIN|LOG_PANIC, "%s transport process returned non-zero "
2492 "status 0x%04x: %s %d",
2493 addr->transport->driver_name,
2494 status,
2495 msb == 0 ? "terminated by signal" : "exit code",
2496 code);
2497 }
2498
2499 /* If SPECIAL_WARN is set in the top address, send a warning message. */
2500
2501 if (addr->special_action == SPECIAL_WARN && addr->transport->warn_message)
2502 {
2503 int fd;
2504 uschar *warn_message;
2505 pid_t pid;
2506
2507 DEBUG(D_deliver) debug_printf("Warning message requested by transport\n");
2508
2509 if (!(warn_message = expand_string(addr->transport->warn_message)))
2510 log_write(0, LOG_MAIN|LOG_PANIC, "Failed to expand \"%s\" (warning "
2511 "message for %s transport): %s", addr->transport->warn_message,
2512 addr->transport->name, expand_string_message);
2513
2514 else if ((pid = child_open_exim(&fd)) > 0)
2515 {
2516 FILE *f = fdopen(fd, "wb");
2517 if (errors_reply_to && !contains_header(US"Reply-To", warn_message))
2518 fprintf(f, "Reply-To: %s\n", errors_reply_to);
2519 fprintf(f, "Auto-Submitted: auto-replied\n");
2520 if (!contains_header(US"From", warn_message))
2521 moan_write_from(f);
2522 fprintf(f, "%s", CS warn_message);
2523
2524 /* Close and wait for child process to complete, without a timeout. */
2525
2526 (void)fclose(f);
2527 (void)child_close(pid, 0);
2528 }
2529
2530 addr->special_action = SPECIAL_NONE;
2531 }
2532 }
2533
2534
2535
2536
2537 /* Check transport for the given concurrency limit. Return TRUE if over
2538 the limit (or an expansion failure), else FALSE and if there was a limit,
2539 the key for the hints database used for the concurrency count. */
2540
2541 static BOOL
2542 tpt_parallel_check(transport_instance * tp, address_item * addr, uschar ** key)
2543 {
2544 unsigned max_parallel;
2545
2546 if (!tp->max_parallel) return FALSE;
2547
2548 max_parallel = (unsigned) expand_string_integer(tp->max_parallel, TRUE);
2549 if (expand_string_message)
2550 {
2551 log_write(0, LOG_MAIN|LOG_PANIC, "Failed to expand max_parallel option "
2552 "in %s transport (%s): %s", tp->name, addr->address,
2553 expand_string_message);
2554 return TRUE;
2555 }
2556
2557 if (max_parallel > 0)
2558 {
2559 uschar * serialize_key = string_sprintf("tpt-serialize-%s", tp->name);
2560 if (!enq_start(serialize_key, max_parallel))
2561 {
2562 address_item * next;
2563 DEBUG(D_transport)
2564 debug_printf("skipping tpt %s because concurrency limit %u reached\n",
2565 tp->name, max_parallel);
2566 do
2567 {
2568 next = addr->next;
2569 addr->message = US"concurrency limit reached for transport";
2570 addr->basic_errno = ERRNO_TRETRY;
2571 post_process_one(addr, DEFER, LOG_MAIN, DTYPE_TRANSPORT, 0);
2572 } while ((addr = next));
2573 return TRUE;
2574 }
2575 *key = serialize_key;
2576 }
2577 return FALSE;
2578 }
2579
2580
2581
2582 /*************************************************
2583 * Do local deliveries *
2584 *************************************************/
2585
2586 /* This function processes the list of addresses in addr_local. True local
2587 deliveries are always done one address at a time. However, local deliveries can
2588 be batched up in some cases. Typically this is when writing batched SMTP output
2589 files for use by some external transport mechanism, or when running local
2590 deliveries over LMTP.
2591
2592 Arguments: None
2593 Returns: Nothing
2594 */
2595
2596 static void
2597 do_local_deliveries(void)
2598 {
2599 open_db dbblock;
2600 open_db *dbm_file = NULL;
2601 time_t now = time(NULL);
2602
2603 /* Loop until we have exhausted the supply of local deliveries */
2604
2605 while (addr_local)
2606 {
2607 time_t delivery_start;
2608 int deliver_time;
2609 address_item *addr2, *addr3, *nextaddr;
2610 int logflags = LOG_MAIN;
2611 int logchar = dont_deliver? '*' : '=';
2612 transport_instance *tp;
2613 uschar * serialize_key = NULL;
2614
2615 /* Pick the first undelivered address off the chain */
2616
2617 address_item *addr = addr_local;
2618 addr_local = addr->next;
2619 addr->next = NULL;
2620
2621 DEBUG(D_deliver|D_transport)
2622 debug_printf("--------> %s <--------\n", addr->address);
2623
2624 /* An internal disaster if there is no transport. Should not occur! */
2625
2626 if (!(tp = addr->transport))
2627 {
2628 logflags |= LOG_PANIC;
2629 disable_logging = FALSE; /* Jic */
2630 addr->message = addr->router
2631 ? string_sprintf("No transport set by %s router", addr->router->name)
2632 : string_sprintf("No transport set by system filter");
2633 post_process_one(addr, DEFER, logflags, DTYPE_TRANSPORT, 0);
2634 continue;
2635 }
2636
2637 /* Check that this base address hasn't previously been delivered to this
2638 transport. The check is necessary at this point to handle homonymic addresses
2639 correctly in cases where the pattern of redirection changes between delivery
2640 attempts. Non-homonymic previous delivery is detected earlier, at routing
2641 time. */
2642
2643 if (previously_transported(addr, FALSE)) continue;
2644
2645 /* There are weird cases where logging is disabled */
2646
2647 disable_logging = tp->disable_logging;
2648
2649 /* Check for batched addresses and possible amalgamation. Skip all the work
2650 if either batch_max <= 1 or there aren't any other addresses for local
2651 delivery. */
2652
2653 if (tp->batch_max > 1 && addr_local)
2654 {
2655 int batch_count = 1;
2656 BOOL uses_dom = readconf_depends((driver_instance *)tp, US"domain");
2657 BOOL uses_lp = ( testflag(addr, af_pfr)
2658 && (testflag(addr, af_file) || addr->local_part[0] == '|')
2659 )
2660 || readconf_depends((driver_instance *)tp, US"local_part");
2661 uschar *batch_id = NULL;
2662 address_item **anchor = &addr_local;
2663 address_item *last = addr;
2664 address_item *next;
2665
2666 /* Expand the batch_id string for comparison with other addresses.
2667 Expansion failure suppresses batching. */
2668
2669 if (tp->batch_id)
2670 {
2671 deliver_set_expansions(addr);
2672 batch_id = expand_string(tp->batch_id);
2673 deliver_set_expansions(NULL);
2674 if (!batch_id)
2675 {
2676 log_write(0, LOG_MAIN|LOG_PANIC, "Failed to expand batch_id option "
2677 "in %s transport (%s): %s", tp->name, addr->address,
2678 expand_string_message);
2679 batch_count = tp->batch_max;
2680 }
2681 }
2682
2683 /* Until we reach the batch_max limit, pick off addresses which have the
2684 same characteristics. These are:
2685
2686 same transport
2687 not previously delivered (see comment about 50 lines above)
2688 same local part if the transport's configuration contains $local_part
2689 or if this is a file or pipe delivery from a redirection
2690 same domain if the transport's configuration contains $domain
2691 same errors address
2692 same additional headers
2693 same headers to be removed
2694 same uid/gid for running the transport
2695 same first host if a host list is set
2696 */
2697
2698 while ((next = *anchor) && batch_count < tp->batch_max)
2699 {
2700 BOOL ok =
2701 tp == next->transport
2702 && !previously_transported(next, TRUE)
2703 && (addr->flags & (af_pfr|af_file)) == (next->flags & (af_pfr|af_file))
2704 && (!uses_lp || Ustrcmp(next->local_part, addr->local_part) == 0)
2705 && (!uses_dom || Ustrcmp(next->domain, addr->domain) == 0)
2706 && same_strings(next->prop.errors_address, addr->prop.errors_address)
2707 && same_headers(next->prop.extra_headers, addr->prop.extra_headers)
2708 && same_strings(next->prop.remove_headers, addr->prop.remove_headers)
2709 && same_ugid(tp, addr, next)
2710 && ( !addr->host_list && !next->host_list
2711 || addr->host_list
2712 && next->host_list
2713 && Ustrcmp(addr->host_list->name, next->host_list->name) == 0
2714 );
2715
2716 /* If the transport has a batch_id setting, batch_id will be non-NULL
2717 from the expansion outside the loop. Expand for this address and compare.
2718 Expansion failure makes this address ineligible for batching. */
2719
2720 if (ok && batch_id)
2721 {
2722 uschar *bid;
2723 address_item *save_nextnext = next->next;
2724 next->next = NULL; /* Expansion for a single address */
2725 deliver_set_expansions(next);
2726 next->next = save_nextnext;
2727 bid = expand_string(tp->batch_id);
2728 deliver_set_expansions(NULL);
2729 if (!bid)
2730 {
2731 log_write(0, LOG_MAIN|LOG_PANIC, "Failed to expand batch_id option "
2732 "in %s transport (%s): %s", tp->name, next->address,
2733 expand_string_message);
2734 ok = FALSE;
2735 }
2736 else ok = (Ustrcmp(batch_id, bid) == 0);
2737 }
2738
2739 /* Take address into batch if OK. */
2740
2741 if (ok)
2742 {
2743 *anchor = next->next; /* Include the address */
2744 next->next = NULL;
2745 last->next = next;
2746 last = next;
2747 batch_count++;
2748 }
2749 else anchor = &next->next; /* Skip the address */
2750 }
2751 }
2752
2753 /* We now have one or more addresses that can be delivered in a batch. Check
2754 whether the transport is prepared to accept a message of this size. If not,
2755 fail them all forthwith. If the expansion fails, or does not yield an
2756 integer, defer delivery. */
2757
2758 if (tp->message_size_limit)
2759 {
2760 int rc = check_message_size(tp, addr);
2761 if (rc != OK)
2762 {
2763 replicate_status(addr);
2764 while (addr)
2765 {
2766 addr2 = addr->next;
2767 post_process_one(addr, rc, logflags, DTYPE_TRANSPORT, 0);
2768 addr = addr2;
2769 }
2770 continue; /* With next batch of addresses */
2771 }
2772 }
2773
2774 /* If we are not running the queue, or if forcing, all deliveries will be
2775 attempted. Otherwise, we must respect the retry times for each address. Even
2776 when not doing this, we need to set up the retry key string, and determine
2777 whether a retry record exists, because after a successful delivery, a delete
2778 retry item must be set up. Keep the retry database open only for the duration
2779 of these checks, rather than for all local deliveries, because some local
2780 deliveries (e.g. to pipes) can take a substantial time. */
2781
2782 if (!(dbm_file = dbfn_open(US"retry", O_RDONLY, &dbblock, FALSE)))
2783 {
2784 DEBUG(D_deliver|D_retry|D_hints_lookup)
2785 debug_printf("no retry data available\n");
2786 }
2787
2788 addr2 = addr;
2789 addr3 = NULL;
2790 while (addr2)
2791 {
2792 BOOL ok = TRUE; /* to deliver this address */
2793 uschar *retry_key;
2794
2795 /* Set up the retry key to include the domain or not, and change its
2796 leading character from "R" to "T". Must make a copy before doing this,
2797 because the old key may be pointed to from a "delete" retry item after
2798 a routing delay. */
2799
2800 retry_key = string_copy(
2801 tp->retry_use_local_part ? addr2->address_retry_key :
2802 addr2->domain_retry_key);
2803 *retry_key = 'T';
2804
2805 /* Inspect the retry data. If there is no hints file, delivery happens. */
2806
2807 if (dbm_file)
2808 {
2809 dbdata_retry *retry_record = dbfn_read(dbm_file, retry_key);
2810
2811 /* If there is no retry record, delivery happens. If there is,
2812 remember it exists so it can be deleted after a successful delivery. */
2813
2814 if (retry_record)
2815 {
2816 setflag(addr2, af_lt_retry_exists);
2817
2818 /* A retry record exists for this address. If queue running and not
2819 forcing, inspect its contents. If the record is too old, or if its
2820 retry time has come, or if it has passed its cutoff time, delivery
2821 will go ahead. */
2822
2823 DEBUG(D_retry)
2824 {
2825 debug_printf("retry record exists: age=%s ",
2826 readconf_printtime(now - retry_record->time_stamp));
2827 debug_printf("(max %s)\n", readconf_printtime(retry_data_expire));
2828 debug_printf(" time to retry = %s expired = %d\n",
2829 readconf_printtime(retry_record->next_try - now),
2830 retry_record->expired);
2831 }
2832
2833 if (queue_running && !deliver_force)
2834 {
2835 ok = (now - retry_record->time_stamp > retry_data_expire)
2836 || (now >= retry_record->next_try)
2837 || retry_record->expired;
2838
2839 /* If we haven't reached the retry time, there is one more check
2840 to do, which is for the ultimate address timeout. */
2841
2842 if (!ok)
2843 ok = retry_ultimate_address_timeout(retry_key, addr2->domain,
2844 retry_record, now);
2845 }
2846 }
2847 else DEBUG(D_retry) debug_printf("no retry record exists\n");
2848 }
2849
2850 /* This address is to be delivered. Leave it on the chain. */
2851
2852 if (ok)
2853 {
2854 addr3 = addr2;
2855 addr2 = addr2->next;
2856 }
2857
2858 /* This address is to be deferred. Take it out of the chain, and
2859 post-process it as complete. Must take it out of the chain first,
2860 because post processing puts it on another chain. */
2861
2862 else
2863 {
2864 address_item *this = addr2;
2865 this->message = US"Retry time not yet reached";
2866 this->basic_errno = ERRNO_LRETRY;
2867 addr2 = addr3 ? (addr3->next = addr2->next)
2868 : (addr = addr2->next);
2869 post_process_one(this, DEFER, logflags, DTYPE_TRANSPORT, 0);
2870 }
2871 }
2872
2873 if (dbm_file) dbfn_close(dbm_file);
2874
2875 /* If there are no addresses left on the chain, they all deferred. Loop
2876 for the next set of addresses. */
2877
2878 if (!addr) continue;
2879
2880 /* If the transport is limited for parallellism, enforce that here.
2881 We use a hints DB entry, incremented here and decremented after
2882 the transport (and any shadow transport) completes. */
2883
2884 if (tpt_parallel_check(tp, addr, &serialize_key))
2885 {
2886 if (expand_string_message)
2887 {
2888 logflags |= LOG_PANIC;
2889 do
2890 {
2891 addr = addr->next;
2892 post_process_one(addr, DEFER, logflags, DTYPE_TRANSPORT, 0);
2893 } while ((addr = addr2));
2894 }
2895 continue; /* Loop for the next set of addresses. */
2896 }
2897
2898
2899 /* So, finally, we do have some addresses that can be passed to the
2900 transport. Before doing so, set up variables that are relevant to a
2901 single delivery. */
2902
2903 deliver_set_expansions(addr);
2904 delivery_start = time(NULL);
2905 deliver_local(addr, FALSE);
2906 deliver_time = (int)(time(NULL) - delivery_start);
2907
2908 /* If a shadow transport (which must perforce be another local transport), is
2909 defined, and its condition is met, we must pass the message to the shadow
2910 too, but only those addresses that succeeded. We do this by making a new
2911 chain of addresses - also to keep the original chain uncontaminated. We must
2912 use a chain rather than doing it one by one, because the shadow transport may
2913 batch.
2914
2915 NOTE: if the condition fails because of a lookup defer, there is nothing we
2916 can do! */
2917
2918 if ( tp->shadow
2919 && ( !tp->shadow_condition
2920 || expand_check_condition(tp->shadow_condition, tp->name, US"transport")
2921 ) )
2922 {
2923 transport_instance *stp;
2924 address_item *shadow_addr = NULL;
2925 address_item **last = &shadow_addr;
2926
2927 for (stp = transports; stp; stp = stp->next)
2928 if (Ustrcmp(stp->name, tp->shadow) == 0) break;
2929
2930 if (!stp)
2931 log_write(0, LOG_MAIN|LOG_PANIC, "shadow transport \"%s\" not found ",
2932 tp->shadow);
2933
2934 /* Pick off the addresses that have succeeded, and make clones. Put into
2935 the shadow_message field a pointer to the shadow_message field of the real
2936 address. */
2937
2938 else for (addr2 = addr; addr2; addr2 = addr2->next)
2939 if (addr2->transport_return == OK)
2940 {
2941 addr3 = store_get(sizeof(address_item));
2942 *addr3 = *addr2;
2943 addr3->next = NULL;
2944 addr3->shadow_message = (uschar *) &(addr2->shadow_message);
2945 addr3->transport = stp;
2946 addr3->transport_return = DEFER;
2947 addr3->return_filename = NULL;
2948 addr3->return_file = -1;
2949 *last = addr3;
2950 last = &(addr3->next);
2951 }
2952
2953 /* If we found any addresses to shadow, run the delivery, and stick any
2954 message back into the shadow_message field in the original. */
2955
2956 if (shadow_addr)
2957 {
2958 int save_count = transport_count;
2959
2960 DEBUG(D_deliver|D_transport)
2961 debug_printf(">>>>>>>>>>>>>>>> Shadow delivery >>>>>>>>>>>>>>>>\n");
2962 deliver_local(shadow_addr, TRUE);
2963
2964 for(; shadow_addr; shadow_addr = shadow_addr->next)
2965 {
2966 int sresult = shadow_addr->transport_return;
2967 *(uschar **)shadow_addr->shadow_message =
2968 sresult == OK
2969 ? string_sprintf(" ST=%s", stp->name)
2970 : string_sprintf(" ST=%s (%s%s%s)", stp->name,
2971 shadow_addr->basic_errno <= 0
2972 ? US""
2973 : US strerror(shadow_addr->basic_errno),
2974 shadow_addr->basic_errno <= 0 || !shadow_addr->message
2975 ? US""
2976 : US": ",
2977 shadow_addr->message
2978 ? shadow_addr->message
2979 : shadow_addr->basic_errno <= 0
2980 ? US"unknown error"
2981 : US"");
2982
2983 DEBUG(D_deliver|D_transport)
2984 debug_printf("%s shadow transport returned %s for %s\n",
2985 stp->name,
2986 sresult == OK ? "OK" :
2987 sresult == DEFER ? "DEFER" :
2988 sresult == FAIL ? "FAIL" :
2989 sresult == PANIC ? "PANIC" : "?",
2990 shadow_addr->address);
2991 }
2992
2993 DEBUG(D_deliver|D_transport)
2994 debug_printf(">>>>>>>>>>>>>>>> End shadow delivery >>>>>>>>>>>>>>>>\n");
2995
2996 transport_count = save_count; /* Restore original transport count */
2997 }
2998 }
2999
3000 /* Cancel the expansions that were set up for the delivery. */
3001
3002 deliver_set_expansions(NULL);
3003
3004 /* If the transport was parallelism-limited, decrement the hints DB record. */
3005
3006 if (serialize_key) enq_end(serialize_key);
3007
3008 /* Now we can process the results of the real transport. We must take each
3009 address off the chain first, because post_process_one() puts it on another
3010 chain. */
3011
3012 for (addr2 = addr; addr2; addr2 = nextaddr)
3013 {
3014 int result = addr2->transport_return;
3015 nextaddr = addr2->next;
3016
3017 DEBUG(D_deliver|D_transport)
3018 debug_printf("%s transport returned %s for %s\n",
3019 tp->name,
3020 result == OK ? "OK" :
3021 result == DEFER ? "DEFER" :
3022 result == FAIL ? "FAIL" :
3023 result == PANIC ? "PANIC" : "?",
3024 addr2->address);
3025
3026 /* If there is a retry_record, or if delivery is deferred, build a retry
3027 item for setting a new retry time or deleting the old retry record from
3028 the database. These items are handled all together after all addresses
3029 have been handled (so the database is open just for a short time for
3030 updating). */
3031
3032 if (result == DEFER || testflag(addr2, af_lt_retry_exists))
3033 {
3034 int flags = result == DEFER ? 0 : rf_delete;
3035 uschar *retry_key = string_copy(tp->retry_use_local_part
3036 ? addr2->address_retry_key : addr2->domain_retry_key);
3037 *retry_key = 'T';
3038 retry_add_item(addr2, retry_key, flags);
3039 }
3040
3041 /* Done with this address */
3042
3043 if (result == OK) addr2->more_errno = deliver_time;
3044 post_process_one(addr2, result, logflags, DTYPE_TRANSPORT, logchar);
3045
3046 /* If a pipe delivery generated text to be sent back, the result may be
3047 changed to FAIL, and we must copy this for subsequent addresses in the
3048 batch. */
3049
3050 if (addr2->transport_return != result)
3051 {
3052 for (addr3 = nextaddr; addr3; addr3 = addr3->next)
3053 {
3054 addr3->transport_return = addr2->transport_return;
3055 addr3->basic_errno = addr2->basic_errno;
3056 addr3->message = addr2->message;
3057 }
3058 result = addr2->transport_return;
3059 }
3060
3061 /* Whether or not the result was changed to FAIL, we need to copy the
3062 return_file value from the first address into all the addresses of the
3063 batch, so they are all listed in the error message. */
3064
3065 addr2->return_file = addr->return_file;
3066
3067 /* Change log character for recording successful deliveries. */
3068
3069 if (result == OK) logchar = '-';
3070 }
3071 } /* Loop back for next batch of addresses */
3072 }
3073
3074
3075
3076
3077 /*************************************************
3078 * Sort remote deliveries *
3079 *************************************************/
3080
3081 /* This function is called if remote_sort_domains is set. It arranges that the
3082 chain of addresses for remote deliveries is ordered according to the strings
3083 specified. Try to make this shuffling reasonably efficient by handling
3084 sequences of addresses rather than just single ones.
3085
3086 Arguments: None
3087 Returns: Nothing
3088 */
3089
3090 static void
3091 sort_remote_deliveries(void)
3092 {
3093 int sep = 0;
3094 address_item **aptr = &addr_remote;
3095 const uschar *listptr = remote_sort_domains;
3096 uschar *pattern;
3097 uschar patbuf[256];
3098
3099 while ( *aptr
3100 && (pattern = string_nextinlist(&listptr, &sep, patbuf, sizeof(patbuf)))
3101 )
3102 {
3103 address_item *moved = NULL;
3104 address_item **bptr = &moved;
3105
3106 while (*aptr)
3107 {
3108 address_item **next;
3109 deliver_domain = (*aptr)->domain; /* set $domain */
3110 if (match_isinlist(deliver_domain, (const uschar **)&pattern, UCHAR_MAX+1,
3111 &domainlist_anchor, NULL, MCL_DOMAIN, TRUE, NULL) == OK)
3112 {
3113 aptr = &(*aptr)->next;
3114 continue;
3115 }
3116
3117 next = &(*aptr)->next;
3118 while ( *next
3119 && (deliver_domain = (*next)->domain, /* Set $domain */
3120 match_isinlist(deliver_domain, (const uschar **)&pattern, UCHAR_MAX+1,
3121 &domainlist_anchor, NULL, MCL_DOMAIN, TRUE, NULL)) != OK
3122 )
3123 next = &(*next)->next;
3124
3125 /* If the batch of non-matchers is at the end, add on any that were
3126 extracted further up the chain, and end this iteration. Otherwise,
3127 extract them from the chain and hang on the moved chain. */
3128
3129 if (!*next)
3130 {
3131 *next = moved;
3132 break;
3133 }
3134
3135 *bptr = *aptr;
3136 *aptr = *next;
3137 *next = NULL;
3138 bptr = next;
3139 aptr = &(*aptr)->next;
3140 }
3141
3142 /* If the loop ended because the final address matched, *aptr will
3143 be NULL. Add on to the end any extracted non-matching addresses. If
3144 *aptr is not NULL, the loop ended via "break" when *next is null, that
3145 is, there was a string of non-matching addresses at the end. In this
3146 case the extracted addresses have already been added on the end. */
3147
3148 if (!*aptr) *aptr = moved;
3149 }
3150
3151 DEBUG(D_deliver)
3152 {
3153 address_item *addr;
3154 debug_printf("remote addresses after sorting:\n");
3155 for (addr = addr_remote; addr; addr = addr->next)
3156 debug_printf(" %s\n", addr->address);
3157 }
3158 }
3159
3160
3161
3162 /*************************************************
3163 * Read from pipe for remote delivery subprocess *
3164 *************************************************/
3165
3166 /* This function is called when the subprocess is complete, but can also be
3167 called before it is complete, in order to empty a pipe that is full (to prevent
3168 deadlock). It must therefore keep track of its progress in the parlist data
3169 block.
3170
3171 We read the pipe to get the delivery status codes and a possible error message
3172 for each address, optionally preceded by unusability data for the hosts and
3173 also by optional retry data.
3174
3175 Read in large chunks into the big buffer and then scan through, interpreting
3176 the data therein. In most cases, only a single read will be necessary. No
3177 individual item will ever be anywhere near 2500 bytes in length, so by ensuring
3178 that we read the next chunk when there is less than 2500 bytes left in the
3179 non-final chunk, we can assume each item is complete in the buffer before
3180 handling it. Each item is written using a single write(), which is atomic for
3181 small items (less than PIPE_BUF, which seems to be at least 512 in any Unix and
3182 often bigger) so even if we are reading while the subprocess is still going, we
3183 should never have only a partial item in the buffer.
3184
3185 Argument:
3186 poffset the offset of the parlist item
3187 eop TRUE if the process has completed
3188
3189 Returns: TRUE if the terminating 'Z' item has been read,
3190 or there has been a disaster (i.e. no more data needed);
3191 FALSE otherwise
3192 */
3193
3194 static BOOL
3195 par_read_pipe(int poffset, BOOL eop)
3196 {
3197 host_item *h;
3198 pardata *p = parlist + poffset;
3199 address_item *addrlist = p->addrlist;
3200 address_item *addr = p->addr;
3201 pid_t pid = p->pid;
3202 int fd = p->fd;
3203 uschar *endptr = big_buffer;
3204 uschar *ptr = endptr;
3205 uschar *msg = p->msg;
3206 BOOL done = p->done;
3207 BOOL unfinished = TRUE;
3208 /* minimum size to read is header size including id, subid and length */
3209 int required = PIPE_HEADER_SIZE;
3210
3211 /* Loop through all items, reading from the pipe when necessary. The pipe
3212 is set up to be non-blocking, but there are two different Unix mechanisms in
3213 use. Exim uses O_NONBLOCK if it is defined. This returns 0 for end of file,
3214 and EAGAIN for no more data. If O_NONBLOCK is not defined, Exim uses O_NDELAY,
3215 which returns 0 for both end of file and no more data. We distinguish the
3216 two cases by taking 0 as end of file only when we know the process has
3217 completed.
3218
3219 Each separate item is written to the pipe in a single write(), and as they are
3220 all short items, the writes will all be atomic and we should never find
3221 ourselves in the position of having read an incomplete item. "Short" in this
3222 case can mean up to about 1K in the case when there is a long error message
3223 associated with an address. */
3224
3225 DEBUG(D_deliver) debug_printf("reading pipe for subprocess %d (%s)\n",
3226 (int)p->pid, eop? "ended" : "not ended");
3227
3228 while (!done)
3229 {
3230 retry_item *r, **rp;
3231 int remaining = endptr - ptr;
3232 uschar header[PIPE_HEADER_SIZE + 1];
3233 uschar id, subid;
3234 uschar *endc;
3235
3236 /* Read (first time) or top up the chars in the buffer if necessary.
3237 There will be only one read if we get all the available data (i.e. don't
3238 fill the buffer completely). */
3239
3240 if (remaining < required && unfinished)
3241 {
3242 int len;
3243 int available = big_buffer_size - remaining;
3244
3245 if (remaining > 0) memmove(big_buffer, ptr, remaining);
3246
3247 ptr = big_buffer;
3248 endptr = big_buffer + remaining;
3249 len = read(fd, endptr, available);
3250
3251 DEBUG(D_deliver) debug_printf("read() yielded %d\n", len);
3252
3253 /* If the result is EAGAIN and the process is not complete, just
3254 stop reading any more and process what we have already. */
3255
3256 if (len < 0)
3257 {
3258 if (!eop && errno == EAGAIN) len = 0; else
3259 {
3260 msg = string_sprintf("failed to read pipe from transport process "
3261 "%d for transport %s: %s", pid, addr->transport->driver_name,
3262 strerror(errno));
3263 break;
3264 }
3265 }
3266
3267 /* If the length is zero (eof or no-more-data), just process what we
3268 already have. Note that if the process is still running and we have
3269 read all the data in the pipe (but less that "available") then we
3270 won't read any more, as "unfinished" will get set FALSE. */
3271
3272 endptr += len;
3273 remaining += len;
3274 unfinished = len == available;
3275 }
3276
3277 /* If we are at the end of the available data, exit the loop. */
3278 if (ptr >= endptr) break;
3279
3280 /* copy and read header */
3281 memcpy(header, ptr, PIPE_HEADER_SIZE);
3282 header[PIPE_HEADER_SIZE] = '\0';
3283 id = header[0];
3284 subid = header[1];
3285 required = Ustrtol(header + 2, &endc, 10) + PIPE_HEADER_SIZE; /* header + data */
3286 if (*endc)
3287 {
3288 msg = string_sprintf("failed to read pipe from transport process "
3289 "%d for transport %s: error reading size from header", pid, addr->transport->driver_name);
3290 done = TRUE;
3291 break;
3292 }
3293
3294 DEBUG(D_deliver)
3295 debug_printf("header read id:%c,subid:%c,size:%s,required:%d,remaining:%d,unfinished:%d\n",
3296 id, subid, header+2, required, remaining, unfinished);
3297
3298 /* is there room for the dataset we want to read ? */
3299 if (required > big_buffer_size - PIPE_HEADER_SIZE)
3300 {
3301 msg = string_sprintf("failed to read pipe from transport process "
3302 "%d for transport %s: big_buffer too small! required size=%d buffer size=%d", pid, addr->transport->driver_name,
3303 required, big_buffer_size - PIPE_HEADER_SIZE);
3304 done = TRUE;
3305 break;
3306 }
3307
3308 /* we wrote all datasets with atomic write() calls
3309 remaining < required only happens if big_buffer was too small
3310 to get all available data from pipe. unfinished has to be true
3311 as well. */
3312 if (remaining < required)
3313 {
3314 if (unfinished)
3315 continue;
3316 msg = string_sprintf("failed to read pipe from transport process "
3317 "%d for transport %s: required size=%d > remaining size=%d and unfinished=false",
3318 pid, addr->transport->driver_name, required, remaining);
3319 done = TRUE;
3320 break;
3321 }
3322
3323 /* step behind the header */
3324 ptr += PIPE_HEADER_SIZE;
3325
3326 /* Handle each possible type of item, assuming the complete item is
3327 available in store. */
3328
3329 switch (id)
3330 {
3331 /* Host items exist only if any hosts were marked unusable. Match
3332 up by checking the IP address. */
3333
3334 case 'H':
3335 for (h = addrlist->host_list; h; h = h->next)
3336 {
3337 if (!h->address || Ustrcmp(h->address, ptr+2) != 0) continue;
3338 h->status = ptr[0];
3339 h->why = ptr[1];
3340 }
3341 ptr += 2;
3342 while (*ptr++);
3343 break;
3344
3345 /* Retry items are sent in a preceding R item for each address. This is
3346 kept separate to keep each message short enough to guarantee it won't
3347 be split in the pipe. Hopefully, in the majority of cases, there won't in
3348 fact be any retry items at all.
3349
3350 The complete set of retry items might include an item to delete a
3351 routing retry if there was a previous routing delay. However, routing
3352 retries are also used when a remote transport identifies an address error.
3353 In that case, there may also be an "add" item for the same key. Arrange
3354 that a "delete" item is dropped in favour of an "add" item. */
3355
3356 case 'R':
3357 if (!addr) goto ADDR_MISMATCH;
3358
3359 DEBUG(D_deliver|D_retry)
3360 debug_printf("reading retry information for %s from subprocess\n",
3361 ptr+1);
3362
3363 /* Cut out any "delete" items on the list. */
3364
3365 for (rp = &(addr->retries); (r = *rp); rp = &r->next)
3366 if (Ustrcmp(r->key, ptr+1) == 0) /* Found item with same key */
3367 {
3368 if ((r->flags & rf_delete) == 0) break; /* It was not "delete" */
3369 *rp = r->next; /* Excise a delete item */
3370 DEBUG(D_deliver|D_retry)
3371 debug_printf(" existing delete item dropped\n");
3372 }
3373
3374 /* We want to add a delete item only if there is no non-delete item;
3375 however we still have to step ptr through the data. */
3376
3377 if (!r || (*ptr & rf_delete) == 0)
3378 {
3379 r = store_get(sizeof(retry_item));
3380 r->next = addr->retries;
3381 addr->retries = r;
3382 r->flags = *ptr++;
3383 r->key = string_copy(ptr);
3384 while (*ptr++);
3385 memcpy(&(r->basic_errno), ptr, sizeof(r->basic_errno));
3386 ptr += sizeof(r->basic_errno);
3387 memcpy(&(r->more_errno), ptr, sizeof(r->more_errno));
3388 ptr += sizeof(r->more_errno);
3389 r->message = (*ptr)? string_copy(ptr) : NULL;
3390 DEBUG(D_deliver|D_retry)
3391 debug_printf(" added %s item\n",
3392 ((r->flags & rf_delete) == 0)? "retry" : "delete");
3393 }
3394
3395 else
3396 {
3397 DEBUG(D_deliver|D_retry)
3398 debug_printf(" delete item not added: non-delete item exists\n");
3399 ptr++;
3400 while(*ptr++);
3401 ptr += sizeof(r->basic_errno) + sizeof(r->more_errno);
3402 }
3403
3404 while(*ptr++);
3405 break;
3406
3407 /* Put the amount of data written into the parlist block */
3408
3409 case 'S':
3410 memcpy(&(p->transport_count), ptr, sizeof(transport_count));
3411 ptr += sizeof(transport_count);
3412 break;
3413
3414 /* Address items are in the order of items on the address chain. We
3415 remember the current address value in case this function is called
3416 several times to empty the pipe in stages. Information about delivery
3417 over TLS is sent in a preceding X item for each address. We don't put
3418 it in with the other info, in order to keep each message short enough to
3419 guarantee it won't be split in the pipe. */
3420
3421 #ifdef SUPPORT_TLS
3422 case 'X':
3423 if (!addr) goto ADDR_MISMATCH; /* Below, in 'A' handler */
3424 switch (subid)
3425 {
3426 case '1':
3427 addr->cipher = NULL;
3428 addr->peerdn = NULL;
3429
3430 if (*ptr)
3431 addr->cipher = string_copy(ptr);
3432 while (*ptr++);
3433 if (*ptr)
3434 addr->peerdn = string_copy(ptr);
3435 break;
3436
3437 case '2':
3438 if (*