Merge branch 'CHUNKING'
[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_catn(s, sp, pp, US" DS", 3);
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_catn(s, &size, &ptr, US" PRDR", 5);
1143 #endif
1144
1145 if (addr->flags & af_chunking_used)
1146 s = string_catn(s, &size, &ptr, US" K", 2);
1147 }
1148
1149 /* confirmation message (SMTP (host_used) and LMTP (driver_name)) */
1150
1151 if ( LOGGING(smtp_confirmation)
1152 && addr->message
1153 && (addr->host_used || Ustrcmp(addr->transport->driver_name, "lmtp") == 0)
1154 )
1155 {
1156 unsigned i;
1157 unsigned lim = big_buffer_size < 1024 ? big_buffer_size : 1024;
1158 uschar *p = big_buffer;
1159 uschar *ss = addr->message;
1160 *p++ = '\"';
1161 for (i = 0; i < lim && ss[i] != 0; i++) /* limit logged amount */
1162 {
1163 if (ss[i] == '\"' || ss[i] == '\\') *p++ = '\\'; /* quote \ and " */
1164 *p++ = ss[i];
1165 }
1166 *p++ = '\"';
1167 *p = 0;
1168 s = string_append(s, &size, &ptr, 2, US" C=", big_buffer);
1169 }
1170
1171 /* Time on queue and actual time taken to deliver */
1172
1173 if (LOGGING(queue_time))
1174 s = string_append(s, &size, &ptr, 2, US" QT=",
1175 readconf_printtime( (int) ((long)time(NULL) - (long)received_time)) );
1176
1177 if (LOGGING(deliver_time))
1178 s = string_append(s, &size, &ptr, 2, US" DT=",
1179 readconf_printtime(addr->more_errno));
1180
1181 /* string_cat() always leaves room for the terminator. Release the
1182 store we used to build the line after writing it. */
1183
1184 s[ptr] = 0;
1185 log_write(0, flags, "%s", s);
1186
1187 #ifndef DISABLE_EVENT
1188 if (!msg) msg_event_raise(US"msg:delivery", addr);
1189 #endif
1190
1191 store_reset(reset_point);
1192 return;
1193 }
1194
1195
1196
1197 static void
1198 deferral_log(address_item * addr, uschar * now,
1199 int logflags, uschar * driver_name, uschar * driver_kind)
1200 {
1201 int size = 256; /* Used for a temporary, */
1202 int ptr = 0; /* expanding buffer, for */
1203 uschar * s; /* building log lines; */
1204 void * reset_point; /* released afterwards. */
1205
1206 uschar ss[32];
1207
1208 /* Build up the line that is used for both the message log and the main
1209 log. */
1210
1211 s = reset_point = store_get(size);
1212
1213 /* Create the address string for logging. Must not do this earlier, because
1214 an OK result may be changed to FAIL when a pipe returns text. */
1215
1216 s = string_log_address(s, &size, &ptr, addr, LOGGING(all_parents), FALSE);
1217
1218 if (*queue_name)
1219 s = string_append(s, &size, &ptr, 2, US" Q=", queue_name);
1220
1221 /* Either driver_name contains something and driver_kind contains
1222 " router" or " transport" (note the leading space), or driver_name is
1223 a null string and driver_kind contains "routing" without the leading
1224 space, if all routing has been deferred. When a domain has been held,
1225 so nothing has been done at all, both variables contain null strings. */
1226
1227 if (driver_name)
1228 {
1229 if (driver_kind[1] == 't' && addr->router)
1230 s = string_append(s, &size, &ptr, 2, US" R=", addr->router->name);
1231 Ustrcpy(ss, " ?=");
1232 ss[1] = toupper(driver_kind[1]);
1233 s = string_append(s, &size, &ptr, 2, ss, driver_name);
1234 }
1235 else if (driver_kind)
1236 s = string_append(s, &size, &ptr, 2, US" ", driver_kind);
1237
1238 /*XXX need an s+s+p sprintf */
1239 sprintf(CS ss, " defer (%d)", addr->basic_errno);
1240 s = string_cat(s, &size, &ptr, ss);
1241
1242 if (addr->basic_errno > 0)
1243 s = string_append(s, &size, &ptr, 2, US": ",
1244 US strerror(addr->basic_errno));
1245
1246 if (addr->host_used)
1247 {
1248 s = string_append(s, &size, &ptr, 5,
1249 US" H=", addr->host_used->name,
1250 US" [", addr->host_used->address, US"]");
1251 if (LOGGING(outgoing_port))
1252 {
1253 int port = addr->host_used->port;
1254 s = string_append(s, &size, &ptr, 2,
1255 US":", port == PORT_NONE ? US"25" : string_sprintf("%d", port));
1256 }
1257 }
1258
1259 if (addr->message)
1260 s = string_append(s, &size, &ptr, 2, US": ", addr->message);
1261
1262 s[ptr] = 0;
1263
1264 /* Log the deferment in the message log, but don't clutter it
1265 up with retry-time defers after the first delivery attempt. */
1266
1267 if (deliver_firsttime || addr->basic_errno > ERRNO_RETRY_BASE)
1268 deliver_msglog("%s %s\n", now, s);
1269
1270 /* Write the main log and reset the store.
1271 For errors of the type "retry time not reached" (also remotes skipped
1272 on queue run), logging is controlled by L_retry_defer. Note that this kind
1273 of error number is negative, and all the retry ones are less than any
1274 others. */
1275
1276
1277 log_write(addr->basic_errno <= ERRNO_RETRY_BASE ? L_retry_defer : 0, logflags,
1278 "== %s", s);
1279
1280 store_reset(reset_point);
1281 return;
1282 }
1283
1284
1285
1286 static void
1287 failure_log(address_item * addr, uschar * driver_kind, uschar * now)
1288 {
1289 int size = 256; /* Used for a temporary, */
1290 int ptr = 0; /* expanding buffer, for */
1291 uschar * s; /* building log lines; */
1292 void * reset_point; /* released afterwards. */
1293
1294 /* Build up the log line for the message and main logs */
1295
1296 s = reset_point = store_get(size);
1297
1298 /* Create the address string for logging. Must not do this earlier, because
1299 an OK result may be changed to FAIL when a pipe returns text. */
1300
1301 s = string_log_address(s, &size, &ptr, addr, LOGGING(all_parents), FALSE);
1302
1303 if (LOGGING(sender_on_delivery))
1304 s = string_append(s, &size, &ptr, 3, US" F=<", sender_address, US">");
1305
1306 if (*queue_name)
1307 s = string_append(s, &size, &ptr, 2, US" Q=", queue_name);
1308
1309 /* Return path may not be set if no delivery actually happened */
1310
1311 if (used_return_path && LOGGING(return_path_on_delivery))
1312 s = string_append(s, &size, &ptr, 3, US" P=<", used_return_path, US">");
1313
1314 if (addr->router)
1315 s = string_append(s, &size, &ptr, 2, US" R=", addr->router->name);
1316 if (addr->transport)
1317 s = string_append(s, &size, &ptr, 2, US" T=", addr->transport->name);
1318
1319 if (addr->host_used)
1320 s = d_hostlog(s, &size, &ptr, addr);
1321
1322 #ifdef SUPPORT_TLS
1323 s = d_tlslog(s, &size, &ptr, addr);
1324 #endif
1325
1326 if (addr->basic_errno > 0)
1327 s = string_append(s, &size, &ptr, 2, US": ", US strerror(addr->basic_errno));
1328
1329 if (addr->message)
1330 s = string_append(s, &size, &ptr, 2, US": ", addr->message);
1331
1332 s[ptr] = 0;
1333
1334 /* Do the logging. For the message log, "routing failed" for those cases,
1335 just to make it clearer. */
1336
1337 if (driver_kind)
1338 deliver_msglog("%s %s failed for %s\n", now, driver_kind, s);
1339 else
1340 deliver_msglog("%s %s\n", now, s);
1341
1342 log_write(0, LOG_MAIN, "** %s", s);
1343
1344 #ifndef DISABLE_EVENT
1345 msg_event_raise(US"msg:fail:delivery", addr);
1346 #endif
1347
1348 store_reset(reset_point);
1349 return;
1350 }
1351
1352
1353
1354 /*************************************************
1355 * Actions at the end of handling an address *
1356 *************************************************/
1357
1358 /* This is a function for processing a single address when all that can be done
1359 with it has been done.
1360
1361 Arguments:
1362 addr points to the address block
1363 result the result of the delivery attempt
1364 logflags flags for log_write() (LOG_MAIN and/or LOG_PANIC)
1365 driver_type indicates which type of driver (transport, or router) was last
1366 to process the address
1367 logchar '=' or '-' for use when logging deliveries with => or ->
1368
1369 Returns: nothing
1370 */
1371
1372 static void
1373 post_process_one(address_item *addr, int result, int logflags, int driver_type,
1374 int logchar)
1375 {
1376 uschar *now = tod_stamp(tod_log);
1377 uschar *driver_kind = NULL;
1378 uschar *driver_name = NULL;
1379
1380 DEBUG(D_deliver) debug_printf("post-process %s (%d)\n", addr->address, result);
1381
1382 /* Set up driver kind and name for logging. Disable logging if the router or
1383 transport has disabled it. */
1384
1385 if (driver_type == DTYPE_TRANSPORT)
1386 {
1387 if (addr->transport)
1388 {
1389 driver_name = addr->transport->name;
1390 driver_kind = US" transport";
1391 disable_logging = addr->transport->disable_logging;
1392 }
1393 else driver_kind = US"transporting";
1394 }
1395 else if (driver_type == DTYPE_ROUTER)
1396 {
1397 if (addr->router)
1398 {
1399 driver_name = addr->router->name;
1400 driver_kind = US" router";
1401 disable_logging = addr->router->disable_logging;
1402 }
1403 else driver_kind = US"routing";
1404 }
1405
1406 /* If there's an error message set, ensure that it contains only printing
1407 characters - it should, but occasionally things slip in and this at least
1408 stops the log format from getting wrecked. We also scan the message for an LDAP
1409 expansion item that has a password setting, and flatten the password. This is a
1410 fudge, but I don't know a cleaner way of doing this. (If the item is badly
1411 malformed, it won't ever have gone near LDAP.) */
1412
1413 if (addr->message)
1414 {
1415 const uschar * s = string_printing(addr->message);
1416
1417 /* deconst cast ok as string_printing known to have alloc'n'copied */
1418 addr->message = expand_hide_passwords(US s);
1419 }
1420
1421 /* If we used a transport that has one of the "return_output" options set, and
1422 if it did in fact generate some output, then for return_output we treat the
1423 message as failed if it was not already set that way, so that the output gets
1424 returned to the sender, provided there is a sender to send it to. For
1425 return_fail_output, do this only if the delivery failed. Otherwise we just
1426 unlink the file, and remove the name so that if the delivery failed, we don't
1427 try to send back an empty or unwanted file. The log_output options operate only
1428 on a non-empty file.
1429
1430 In any case, we close the message file, because we cannot afford to leave a
1431 file-descriptor for one address while processing (maybe very many) others. */
1432
1433 if (addr->return_file >= 0 && addr->return_filename)
1434 {
1435 BOOL return_output = FALSE;
1436 struct stat statbuf;
1437 (void)EXIMfsync(addr->return_file);
1438
1439 /* If there is no output, do nothing. */
1440
1441 if (fstat(addr->return_file, &statbuf) == 0 && statbuf.st_size > 0)
1442 {
1443 transport_instance *tb = addr->transport;
1444
1445 /* Handle logging options */
1446
1447 if ( tb->log_output
1448 || result == FAIL && tb->log_fail_output
1449 || result == DEFER && tb->log_defer_output
1450 )
1451 {
1452 uschar *s;
1453 FILE *f = Ufopen(addr->return_filename, "rb");
1454 if (!f)
1455 log_write(0, LOG_MAIN|LOG_PANIC, "failed to open %s to log output "
1456 "from %s transport: %s", addr->return_filename, tb->name,
1457 strerror(errno));
1458 else
1459 if ((s = US Ufgets(big_buffer, big_buffer_size, f)))
1460 {
1461 uschar *p = big_buffer + Ustrlen(big_buffer);
1462 const uschar * sp;
1463 while (p > big_buffer && isspace(p[-1])) p--;
1464 *p = 0;
1465 sp = string_printing(big_buffer);
1466 log_write(0, LOG_MAIN, "<%s>: %s transport output: %s",
1467 addr->address, tb->name, sp);
1468 }
1469 (void)fclose(f);
1470 }
1471
1472 /* Handle returning options, but only if there is an address to return
1473 the text to. */
1474
1475 if (sender_address[0] != 0 || addr->prop.errors_address)
1476 if (tb->return_output)
1477 {
1478 addr->transport_return = result = FAIL;
1479 if (addr->basic_errno == 0 && !addr->message)
1480 addr->message = US"return message generated";
1481 return_output = TRUE;
1482 }
1483 else
1484 if (tb->return_fail_output && result == FAIL) return_output = TRUE;
1485 }
1486
1487 /* Get rid of the file unless it might be returned, but close it in
1488 all cases. */
1489
1490 if (!return_output)
1491 {
1492 Uunlink(addr->return_filename);
1493 addr->return_filename = NULL;
1494 addr->return_file = -1;
1495 }
1496
1497 (void)close(addr->return_file);
1498 }
1499
1500 /* The success case happens only after delivery by a transport. */
1501
1502 if (result == OK)
1503 {
1504 addr->next = addr_succeed;
1505 addr_succeed = addr;
1506
1507 /* Call address_done() to ensure that we don't deliver to this address again,
1508 and write appropriate things to the message log. If it is a child address, we
1509 call child_done() to scan the ancestors and mark them complete if this is the
1510 last child to complete. */
1511
1512 address_done(addr, now);
1513 DEBUG(D_deliver) debug_printf("%s delivered\n", addr->address);
1514
1515 if (!addr->parent)
1516 deliver_msglog("%s %s: %s%s succeeded\n", now, addr->address,
1517 driver_name, driver_kind);
1518 else
1519 {
1520 deliver_msglog("%s %s <%s>: %s%s succeeded\n", now, addr->address,
1521 addr->parent->address, driver_name, driver_kind);
1522 child_done(addr, now);
1523 }
1524
1525 /* Certificates for logging (via events) */
1526 #ifdef SUPPORT_TLS
1527 tls_out.ourcert = addr->ourcert;
1528 addr->ourcert = NULL;
1529 tls_out.peercert = addr->peercert;
1530 addr->peercert = NULL;
1531
1532 tls_out.cipher = addr->cipher;
1533 tls_out.peerdn = addr->peerdn;
1534 tls_out.ocsp = addr->ocsp;
1535 # ifdef EXPERIMENTAL_DANE
1536 tls_out.dane_verified = testflag(addr, af_dane_verified);
1537 # endif
1538 #endif
1539
1540 delivery_log(LOG_MAIN, addr, logchar, NULL);
1541
1542 #ifdef SUPPORT_TLS
1543 tls_free_cert(&tls_out.ourcert);
1544 tls_free_cert(&tls_out.peercert);
1545 tls_out.cipher = NULL;
1546 tls_out.peerdn = NULL;
1547 tls_out.ocsp = OCSP_NOT_REQ;
1548 # ifdef EXPERIMENTAL_DANE
1549 tls_out.dane_verified = FALSE;
1550 # endif
1551 #endif
1552 }
1553
1554
1555 /* Soft failure, or local delivery process failed; freezing may be
1556 requested. */
1557
1558 else if (result == DEFER || result == PANIC)
1559 {
1560 if (result == PANIC) logflags |= LOG_PANIC;
1561
1562 /* This puts them on the chain in reverse order. Do not change this, because
1563 the code for handling retries assumes that the one with the retry
1564 information is last. */
1565
1566 addr->next = addr_defer;
1567 addr_defer = addr;
1568
1569 /* The only currently implemented special action is to freeze the
1570 message. Logging of this is done later, just before the -H file is
1571 updated. */
1572
1573 if (addr->special_action == SPECIAL_FREEZE)
1574 {
1575 deliver_freeze = TRUE;
1576 deliver_frozen_at = time(NULL);
1577 update_spool = TRUE;
1578 }
1579
1580 /* If doing a 2-stage queue run, we skip writing to either the message
1581 log or the main log for SMTP defers. */
1582
1583 if (!queue_2stage || addr->basic_errno != 0)
1584 deferral_log(addr, now, logflags, driver_name, driver_kind);
1585 }
1586
1587
1588 /* Hard failure. If there is an address to which an error message can be sent,
1589 put this address on the failed list. If not, put it on the deferred list and
1590 freeze the mail message for human attention. The latter action can also be
1591 explicitly requested by a router or transport. */
1592
1593 else
1594 {
1595 /* If this is a delivery error, or a message for which no replies are
1596 wanted, and the message's age is greater than ignore_bounce_errors_after,
1597 force the af_ignore_error flag. This will cause the address to be discarded
1598 later (with a log entry). */
1599
1600 if (sender_address[0] == 0 && message_age >= ignore_bounce_errors_after)
1601 setflag(addr, af_ignore_error);
1602
1603 /* Freeze the message if requested, or if this is a bounce message (or other
1604 message with null sender) and this address does not have its own errors
1605 address. However, don't freeze if errors are being ignored. The actual code
1606 to ignore occurs later, instead of sending a message. Logging of freezing
1607 occurs later, just before writing the -H file. */
1608
1609 if ( !testflag(addr, af_ignore_error)
1610 && ( addr->special_action == SPECIAL_FREEZE
1611 || (sender_address[0] == 0 && !addr->prop.errors_address)
1612 ) )
1613 {
1614 frozen_info = addr->special_action == SPECIAL_FREEZE
1615 ? US""
1616 : sender_local && !local_error_message
1617 ? US" (message created with -f <>)"
1618 : US" (delivery error message)";
1619 deliver_freeze = TRUE;
1620 deliver_frozen_at = time(NULL);
1621 update_spool = TRUE;
1622
1623 /* The address is put on the defer rather than the failed queue, because
1624 the message is being retained. */
1625
1626 addr->next = addr_defer;
1627 addr_defer = addr;
1628 }
1629
1630 /* Don't put the address on the nonrecipients tree yet; wait until an
1631 error message has been successfully sent. */
1632
1633 else
1634 {
1635 addr->next = addr_failed;
1636 addr_failed = addr;
1637 }
1638
1639 failure_log(addr, driver_name ? NULL : driver_kind, now);
1640 }
1641
1642 /* Ensure logging is turned on again in all cases */
1643
1644 disable_logging = FALSE;
1645 }
1646
1647
1648
1649
1650 /*************************************************
1651 * Address-independent error *
1652 *************************************************/
1653
1654 /* This function is called when there's an error that is not dependent on a
1655 particular address, such as an expansion string failure. It puts the error into
1656 all the addresses in a batch, logs the incident on the main and panic logs, and
1657 clears the expansions. It is mostly called from local_deliver(), but can be
1658 called for a remote delivery via findugid().
1659
1660 Arguments:
1661 logit TRUE if (MAIN+PANIC) logging required
1662 addr the first of the chain of addresses
1663 code the error code
1664 format format string for error message, or NULL if already set in addr
1665 ... arguments for the format
1666
1667 Returns: nothing
1668 */
1669
1670 static void
1671 common_error(BOOL logit, address_item *addr, int code, uschar *format, ...)
1672 {
1673 address_item *addr2;
1674 addr->basic_errno = code;
1675
1676 if (format)
1677 {
1678 va_list ap;
1679 uschar buffer[512];
1680 va_start(ap, format);
1681 if (!string_vformat(buffer, sizeof(buffer), CS format, ap))
1682 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1683 "common_error expansion was longer than " SIZE_T_FMT, sizeof(buffer));
1684 va_end(ap);
1685 addr->message = string_copy(buffer);
1686 }
1687
1688 for (addr2 = addr->next; addr2; addr2 = addr2->next)
1689 {
1690 addr2->basic_errno = code;
1691 addr2->message = addr->message;
1692 }
1693
1694 if (logit) log_write(0, LOG_MAIN|LOG_PANIC, "%s", addr->message);
1695 deliver_set_expansions(NULL);
1696 }
1697
1698
1699
1700
1701 /*************************************************
1702 * Check a "never users" list *
1703 *************************************************/
1704
1705 /* This function is called to check whether a uid is on one of the two "never
1706 users" lists.
1707
1708 Arguments:
1709 uid the uid to be checked
1710 nusers the list to be scanned; the first item in the list is the count
1711
1712 Returns: TRUE if the uid is on the list
1713 */
1714
1715 static BOOL
1716 check_never_users(uid_t uid, uid_t *nusers)
1717 {
1718 int i;
1719 if (!nusers) return FALSE;
1720 for (i = 1; i <= (int)(nusers[0]); i++) if (nusers[i] == uid) return TRUE;
1721 return FALSE;
1722 }
1723
1724
1725
1726 /*************************************************
1727 * Find uid and gid for a transport *
1728 *************************************************/
1729
1730 /* This function is called for both local and remote deliveries, to find the
1731 uid/gid under which to run the delivery. The values are taken preferentially
1732 from the transport (either explicit or deliver_as_creator), then from the
1733 address (i.e. the router), and if nothing is set, the exim uid/gid are used. If
1734 the resulting uid is on the "never_users" or the "fixed_never_users" list, a
1735 panic error is logged, and the function fails (which normally leads to delivery
1736 deferral).
1737
1738 Arguments:
1739 addr the address (possibly a chain)
1740 tp the transport
1741 uidp pointer to uid field
1742 gidp pointer to gid field
1743 igfp pointer to the use_initgroups field
1744
1745 Returns: FALSE if failed - error has been set in address(es)
1746 */
1747
1748 static BOOL
1749 findugid(address_item *addr, transport_instance *tp, uid_t *uidp, gid_t *gidp,
1750 BOOL *igfp)
1751 {
1752 uschar *nuname;
1753 BOOL gid_set = FALSE;
1754
1755 /* Default initgroups flag comes from the transport */
1756
1757 *igfp = tp->initgroups;
1758
1759 /* First see if there's a gid on the transport, either fixed or expandable.
1760 The expanding function always logs failure itself. */
1761
1762 if (tp->gid_set)
1763 {
1764 *gidp = tp->gid;
1765 gid_set = TRUE;
1766 }
1767 else if (tp->expand_gid)
1768 {
1769 if (!route_find_expanded_group(tp->expand_gid, tp->name, US"transport", gidp,
1770 &(addr->message)))
1771 {
1772 common_error(FALSE, addr, ERRNO_GIDFAIL, NULL);
1773 return FALSE;
1774 }
1775 gid_set = TRUE;
1776 }
1777
1778 /* If the transport did not set a group, see if the router did. */
1779
1780 if (!gid_set && testflag(addr, af_gid_set))
1781 {
1782 *gidp = addr->gid;
1783 gid_set = TRUE;
1784 }
1785
1786 /* Pick up a uid from the transport if one is set. */
1787
1788 if (tp->uid_set) *uidp = tp->uid;
1789
1790 /* Otherwise, try for an expandable uid field. If it ends up as a numeric id,
1791 it does not provide a passwd value from which a gid can be taken. */
1792
1793 else if (tp->expand_uid)
1794 {
1795 struct passwd *pw;
1796 if (!route_find_expanded_user(tp->expand_uid, tp->name, US"transport", &pw,
1797 uidp, &(addr->message)))
1798 {
1799 common_error(FALSE, addr, ERRNO_UIDFAIL, NULL);
1800 return FALSE;
1801 }
1802 if (!gid_set && pw)
1803 {
1804 *gidp = pw->pw_gid;
1805 gid_set = TRUE;
1806 }
1807 }
1808
1809 /* If the transport doesn't set the uid, test the deliver_as_creator flag. */
1810
1811 else if (tp->deliver_as_creator)
1812 {
1813 *uidp = originator_uid;
1814 if (!gid_set)
1815 {
1816 *gidp = originator_gid;
1817 gid_set = TRUE;
1818 }
1819 }
1820
1821 /* Otherwise see if the address specifies the uid and if so, take it and its
1822 initgroups flag. */
1823
1824 else if (testflag(addr, af_uid_set))
1825 {
1826 *uidp = addr->uid;
1827 *igfp = testflag(addr, af_initgroups);
1828 }
1829
1830 /* Nothing has specified the uid - default to the Exim user, and group if the
1831 gid is not set. */
1832
1833 else
1834 {
1835 *uidp = exim_uid;
1836 if (!gid_set)
1837 {
1838 *gidp = exim_gid;
1839 gid_set = TRUE;
1840 }
1841 }
1842
1843 /* If no gid is set, it is a disaster. We default to the Exim gid only if
1844 defaulting to the Exim uid. In other words, if the configuration has specified
1845 a uid, it must also provide a gid. */
1846
1847 if (!gid_set)
1848 {
1849 common_error(TRUE, addr, ERRNO_GIDFAIL, US"User set without group for "
1850 "%s transport", tp->name);
1851 return FALSE;
1852 }
1853
1854 /* Check that the uid is not on the lists of banned uids that may not be used
1855 for delivery processes. */
1856
1857 nuname = check_never_users(*uidp, never_users)
1858 ? US"never_users"
1859 : check_never_users(*uidp, fixed_never_users)
1860 ? US"fixed_never_users"
1861 : NULL;
1862 if (nuname)
1863 {
1864 common_error(TRUE, addr, ERRNO_UIDFAIL, US"User %ld set for %s transport "
1865 "is on the %s list", (long int)(*uidp), tp->name, nuname);
1866 return FALSE;
1867 }
1868
1869 /* All is well */
1870
1871 return TRUE;
1872 }
1873
1874
1875
1876
1877 /*************************************************
1878 * Check the size of a message for a transport *
1879 *************************************************/
1880
1881 /* Checks that the message isn't too big for the selected transport.
1882 This is called only when it is known that the limit is set.
1883
1884 Arguments:
1885 tp the transport
1886 addr the (first) address being delivered
1887
1888 Returns: OK
1889 DEFER expansion failed or did not yield an integer
1890 FAIL message too big
1891 */
1892
1893 int
1894 check_message_size(transport_instance *tp, address_item *addr)
1895 {
1896 int rc = OK;
1897 int size_limit;
1898
1899 deliver_set_expansions(addr);
1900 size_limit = expand_string_integer(tp->message_size_limit, TRUE);
1901 deliver_set_expansions(NULL);
1902
1903 if (expand_string_message)
1904 {
1905 rc = DEFER;
1906 addr->message = size_limit == -1
1907 ? string_sprintf("failed to expand message_size_limit "
1908 "in %s transport: %s", tp->name, expand_string_message)
1909 : string_sprintf("invalid message_size_limit "
1910 "in %s transport: %s", tp->name, expand_string_message);
1911 }
1912 else if (size_limit > 0 && message_size > size_limit)
1913 {
1914 rc = FAIL;
1915 addr->message =
1916 string_sprintf("message is too big (transport limit = %d)",
1917 size_limit);
1918 }
1919
1920 return rc;
1921 }
1922
1923
1924
1925 /*************************************************
1926 * Transport-time check for a previous delivery *
1927 *************************************************/
1928
1929 /* Check that this base address hasn't previously been delivered to its routed
1930 transport. If it has been delivered, mark it done. The check is necessary at
1931 delivery time in order to handle homonymic addresses correctly in cases where
1932 the pattern of redirection changes between delivery attempts (so the unique
1933 fields change). Non-homonymic previous delivery is detected earlier, at routing
1934 time (which saves unnecessary routing).
1935
1936 Arguments:
1937 addr the address item
1938 testing TRUE if testing wanted only, without side effects
1939
1940 Returns: TRUE if previously delivered by the transport
1941 */
1942
1943 static BOOL
1944 previously_transported(address_item *addr, BOOL testing)
1945 {
1946 (void)string_format(big_buffer, big_buffer_size, "%s/%s",
1947 addr->unique + (testflag(addr, af_homonym)? 3:0), addr->transport->name);
1948
1949 if (tree_search(tree_nonrecipients, big_buffer) != 0)
1950 {
1951 DEBUG(D_deliver|D_route|D_transport)
1952 debug_printf("%s was previously delivered (%s transport): discarded\n",
1953 addr->address, addr->transport->name);
1954 if (!testing) child_done(addr, tod_stamp(tod_log));
1955 return TRUE;
1956 }
1957
1958 return FALSE;
1959 }
1960
1961
1962
1963 /******************************************************
1964 * Check for a given header in a header string *
1965 ******************************************************/
1966
1967 /* This function is used when generating quota warnings. The configuration may
1968 specify any header lines it likes in quota_warn_message. If certain of them are
1969 missing, defaults are inserted, so we need to be able to test for the presence
1970 of a given header.
1971
1972 Arguments:
1973 hdr the required header name
1974 hstring the header string
1975
1976 Returns: TRUE the header is in the string
1977 FALSE the header is not in the string
1978 */
1979
1980 static BOOL
1981 contains_header(uschar *hdr, uschar *hstring)
1982 {
1983 int len = Ustrlen(hdr);
1984 uschar *p = hstring;
1985 while (*p != 0)
1986 {
1987 if (strncmpic(p, hdr, len) == 0)
1988 {
1989 p += len;
1990 while (*p == ' ' || *p == '\t') p++;
1991 if (*p == ':') return TRUE;
1992 }
1993 while (*p != 0 && *p != '\n') p++;
1994 if (*p == '\n') p++;
1995 }
1996 return FALSE;
1997 }
1998
1999
2000
2001
2002 /*************************************************
2003 * Perform a local delivery *
2004 *************************************************/
2005
2006 /* Each local delivery is performed in a separate process which sets its
2007 uid and gid as specified. This is a safer way than simply changing and
2008 restoring using seteuid(); there is a body of opinion that seteuid() cannot be
2009 used safely. From release 4, Exim no longer makes any use of it. Besides, not
2010 all systems have seteuid().
2011
2012 If the uid/gid are specified in the transport_instance, they are used; the
2013 transport initialization must ensure that either both or neither are set.
2014 Otherwise, the values associated with the address are used. If neither are set,
2015 it is a configuration error.
2016
2017 The transport or the address may specify a home directory (transport over-
2018 rides), and if they do, this is set as $home. If neither have set a working
2019 directory, this value is used for that as well. Otherwise $home is left unset
2020 and the cwd is set to "/" - a directory that should be accessible to all users.
2021
2022 Using a separate process makes it more complicated to get error information
2023 back. We use a pipe to pass the return code and also an error code and error
2024 text string back to the parent process.
2025
2026 Arguments:
2027 addr points to an address block for this delivery; for "normal" local
2028 deliveries this is the only address to be delivered, but for
2029 pseudo-remote deliveries (e.g. by batch SMTP to a file or pipe)
2030 a number of addresses can be handled simultaneously, and in this
2031 case addr will point to a chain of addresses with the same
2032 characteristics.
2033
2034 shadowing TRUE if running a shadow transport; this causes output from pipes
2035 to be ignored.
2036
2037 Returns: nothing
2038 */
2039
2040 static void
2041 deliver_local(address_item *addr, BOOL shadowing)
2042 {
2043 BOOL use_initgroups;
2044 uid_t uid;
2045 gid_t gid;
2046 int status, len, rc;
2047 int pfd[2];
2048 pid_t pid;
2049 uschar *working_directory;
2050 address_item *addr2;
2051 transport_instance *tp = addr->transport;
2052
2053 /* Set up the return path from the errors or sender address. If the transport
2054 has its own return path setting, expand it and replace the existing value. */
2055
2056 if(addr->prop.errors_address)
2057 return_path = addr->prop.errors_address;
2058 #ifdef EXPERIMENTAL_SRS
2059 else if (addr->prop.srs_sender)
2060 return_path = addr->prop.srs_sender;
2061 #endif
2062 else
2063 return_path = sender_address;
2064
2065 if (tp->return_path)
2066 {
2067 uschar *new_return_path = expand_string(tp->return_path);
2068 if (!new_return_path)
2069 {
2070 if (!expand_string_forcedfail)
2071 {
2072 common_error(TRUE, addr, ERRNO_EXPANDFAIL,
2073 US"Failed to expand return path \"%s\" in %s transport: %s",
2074 tp->return_path, tp->name, expand_string_message);
2075 return;
2076 }
2077 }
2078 else return_path = new_return_path;
2079 }
2080
2081 /* For local deliveries, one at a time, the value used for logging can just be
2082 set directly, once and for all. */
2083
2084 used_return_path = return_path;
2085
2086 /* Sort out the uid, gid, and initgroups flag. If an error occurs, the message
2087 gets put into the address(es), and the expansions are unset, so we can just
2088 return. */
2089
2090 if (!findugid(addr, tp, &uid, &gid, &use_initgroups)) return;
2091
2092 /* See if either the transport or the address specifies a home directory. A
2093 home directory set in the address may already be expanded; a flag is set to
2094 indicate that. In other cases we must expand it. */
2095
2096 if ( (deliver_home = tp->home_dir) /* Set in transport, or */
2097 || ( (deliver_home = addr->home_dir) /* Set in address and */
2098 && !testflag(addr, af_home_expanded) /* not expanded */
2099 ) )
2100 {
2101 uschar *rawhome = deliver_home;
2102 deliver_home = NULL; /* in case it contains $home */
2103 if (!(deliver_home = expand_string(rawhome)))
2104 {
2105 common_error(TRUE, addr, ERRNO_EXPANDFAIL, US"home directory \"%s\" failed "
2106 "to expand for %s transport: %s", rawhome, tp->name,
2107 expand_string_message);
2108 return;
2109 }
2110 if (*deliver_home != '/')
2111 {
2112 common_error(TRUE, addr, ERRNO_NOTABSOLUTE, US"home directory path \"%s\" "
2113 "is not absolute for %s transport", deliver_home, tp->name);
2114 return;
2115 }
2116 }
2117
2118 /* See if either the transport or the address specifies a current directory,
2119 and if so, expand it. If nothing is set, use the home directory, unless it is
2120 also unset in which case use "/", which is assumed to be a directory to which
2121 all users have access. It is necessary to be in a visible directory for some
2122 operating systems when running pipes, as some commands (e.g. "rm" under Solaris
2123 2.5) require this. */
2124
2125 working_directory = tp->current_dir ? tp->current_dir : addr->current_dir;
2126 if (working_directory)
2127 {
2128 uschar *raw = working_directory;
2129 if (!(working_directory = expand_string(raw)))
2130 {
2131 common_error(TRUE, addr, ERRNO_EXPANDFAIL, US"current directory \"%s\" "
2132 "failed to expand for %s transport: %s", raw, tp->name,
2133 expand_string_message);
2134 return;
2135 }
2136 if (*working_directory != '/')
2137 {
2138 common_error(TRUE, addr, ERRNO_NOTABSOLUTE, US"current directory path "
2139 "\"%s\" is not absolute for %s transport", working_directory, tp->name);
2140 return;
2141 }
2142 }
2143 else working_directory = deliver_home ? deliver_home : US"/";
2144
2145 /* If one of the return_output flags is set on the transport, create and open a
2146 file in the message log directory for the transport to write its output onto.
2147 This is mainly used by pipe transports. The file needs to be unique to the
2148 address. This feature is not available for shadow transports. */
2149
2150 if ( !shadowing
2151 && ( tp->return_output || tp->return_fail_output
2152 || tp->log_output || tp->log_fail_output || tp->log_defer_output
2153 ) )
2154 {
2155 uschar * error;
2156
2157 addr->return_filename =
2158 spool_fname(US"msglog", message_subdir, message_id,
2159 string_sprintf("-%d-%d", getpid(), return_count++));
2160
2161 if ((addr->return_file = open_msglog_file(addr->return_filename, 0400, &error)) < 0)
2162 {
2163 common_error(TRUE, addr, errno, US"Unable to %s file for %s transport "
2164 "to return message: %s", error, tp->name, strerror(errno));
2165 return;
2166 }
2167 }
2168
2169 /* Create the pipe for inter-process communication. */
2170
2171 if (pipe(pfd) != 0)
2172 {
2173 common_error(TRUE, addr, ERRNO_PIPEFAIL, US"Creation of pipe failed: %s",
2174 strerror(errno));
2175 return;
2176 }
2177
2178 /* Now fork the process to do the real work in the subprocess, but first
2179 ensure that all cached resources are freed so that the subprocess starts with
2180 a clean slate and doesn't interfere with the parent process. */
2181
2182 search_tidyup();
2183
2184 if ((pid = fork()) == 0)
2185 {
2186 BOOL replicate = TRUE;
2187
2188 /* Prevent core dumps, as we don't want them in users' home directories.
2189 HP-UX doesn't have RLIMIT_CORE; I don't know how to do this in that
2190 system. Some experimental/developing systems (e.g. GNU/Hurd) may define
2191 RLIMIT_CORE but not support it in setrlimit(). For such systems, do not
2192 complain if the error is "not supported".
2193
2194 There are two scenarios where changing the max limit has an effect. In one,
2195 the user is using a .forward and invoking a command of their choice via pipe;
2196 for these, we do need the max limit to be 0 unless the admin chooses to
2197 permit an increased limit. In the other, the command is invoked directly by
2198 the transport and is under administrator control, thus being able to raise
2199 the limit aids in debugging. So there's no general always-right answer.
2200
2201 Thus we inhibit core-dumps completely but let individual transports, while
2202 still root, re-raise the limits back up to aid debugging. We make the
2203 default be no core-dumps -- few enough people can use core dumps in
2204 diagnosis that it's reasonable to make them something that has to be explicitly requested.
2205 */
2206
2207 #ifdef RLIMIT_CORE
2208 struct rlimit rl;
2209 rl.rlim_cur = 0;
2210 rl.rlim_max = 0;
2211 if (setrlimit(RLIMIT_CORE, &rl) < 0)
2212 {
2213 # ifdef SETRLIMIT_NOT_SUPPORTED
2214 if (errno != ENOSYS && errno != ENOTSUP)
2215 # endif
2216 log_write(0, LOG_MAIN|LOG_PANIC, "setrlimit(RLIMIT_CORE) failed: %s",
2217 strerror(errno));
2218 }
2219 #endif
2220
2221 /* Reset the random number generator, so different processes don't all
2222 have the same sequence. */
2223
2224 random_seed = 0;
2225
2226 /* If the transport has a setup entry, call this first, while still
2227 privileged. (Appendfile uses this to expand quota, for example, while
2228 able to read private files.) */
2229
2230 if (addr->transport->setup)
2231 switch((addr->transport->setup)(addr->transport, addr, NULL, uid, gid,
2232 &(addr->message)))
2233 {
2234 case DEFER:
2235 addr->transport_return = DEFER;
2236 goto PASS_BACK;
2237
2238 case FAIL:
2239 addr->transport_return = PANIC;
2240 goto PASS_BACK;
2241 }
2242
2243 /* Ignore SIGINT and SIGTERM during delivery. Also ignore SIGUSR1, as
2244 when the process becomes unprivileged, it won't be able to write to the
2245 process log. SIGHUP is ignored throughout exim, except when it is being
2246 run as a daemon. */
2247
2248 signal(SIGINT, SIG_IGN);
2249 signal(SIGTERM, SIG_IGN);
2250 signal(SIGUSR1, SIG_IGN);
2251
2252 /* Close the unwanted half of the pipe, and set close-on-exec for the other
2253 half - for transports that exec things (e.g. pipe). Then set the required
2254 gid/uid. */
2255
2256 (void)close(pfd[pipe_read]);
2257 (void)fcntl(pfd[pipe_write], F_SETFD, fcntl(pfd[pipe_write], F_GETFD) |
2258 FD_CLOEXEC);
2259 exim_setugid(uid, gid, use_initgroups,
2260 string_sprintf("local delivery to %s <%s> transport=%s", addr->local_part,
2261 addr->address, addr->transport->name));
2262
2263 DEBUG(D_deliver)
2264 {
2265 address_item *batched;
2266 debug_printf(" home=%s current=%s\n", deliver_home, working_directory);
2267 for (batched = addr->next; batched; batched = batched->next)
2268 debug_printf("additional batched address: %s\n", batched->address);
2269 }
2270
2271 /* Set an appropriate working directory. */
2272
2273 if (Uchdir(working_directory) < 0)
2274 {
2275 addr->transport_return = DEFER;
2276 addr->basic_errno = errno;
2277 addr->message = string_sprintf("failed to chdir to %s", working_directory);
2278 }
2279
2280 /* If successful, call the transport */
2281
2282 else
2283 {
2284 BOOL ok = TRUE;
2285 set_process_info("delivering %s to %s using %s", message_id,
2286 addr->local_part, addr->transport->name);
2287
2288 /* Setting this global in the subprocess means we need never clear it */
2289 transport_name = addr->transport->name;
2290
2291 /* If a transport filter has been specified, set up its argument list.
2292 Any errors will get put into the address, and FALSE yielded. */
2293
2294 if (addr->transport->filter_command)
2295 {
2296 ok = transport_set_up_command(&transport_filter_argv,
2297 addr->transport->filter_command,
2298 TRUE, PANIC, addr, US"transport filter", NULL);
2299 transport_filter_timeout = addr->transport->filter_timeout;
2300 }
2301 else transport_filter_argv = NULL;
2302
2303 if (ok)
2304 {
2305 debug_print_string(addr->transport->debug_string);
2306 replicate = !(addr->transport->info->code)(addr->transport, addr);
2307 }
2308 }
2309
2310 /* Pass the results back down the pipe. If necessary, first replicate the
2311 status in the top address to the others in the batch. The label is the
2312 subject of a goto when a call to the transport's setup function fails. We
2313 pass the pointer to the transport back in case it got changed as a result of
2314 file_format in appendfile. */
2315
2316 PASS_BACK:
2317
2318 if (replicate) replicate_status(addr);
2319 for (addr2 = addr; addr2; addr2 = addr2->next)
2320 {
2321 int i;
2322 int local_part_length = Ustrlen(addr2->local_part);
2323 uschar *s;
2324 int ret;
2325
2326 if( (ret = write(pfd[pipe_write], &addr2->transport_return, sizeof(int))) != sizeof(int)
2327 || (ret = write(pfd[pipe_write], &transport_count, sizeof(transport_count))) != sizeof(transport_count)
2328 || (ret = write(pfd[pipe_write], &addr2->flags, sizeof(addr2->flags))) != sizeof(addr2->flags)
2329 || (ret = write(pfd[pipe_write], &addr2->basic_errno, sizeof(int))) != sizeof(int)
2330 || (ret = write(pfd[pipe_write], &addr2->more_errno, sizeof(int))) != sizeof(int)
2331 || (ret = write(pfd[pipe_write], &addr2->special_action, sizeof(int))) != sizeof(int)
2332 || (ret = write(pfd[pipe_write], &addr2->transport,
2333 sizeof(transport_instance *))) != sizeof(transport_instance *)
2334
2335 /* For a file delivery, pass back the local part, in case the original
2336 was only part of the final delivery path. This gives more complete
2337 logging. */
2338
2339 || (testflag(addr2, af_file)
2340 && ( (ret = write(pfd[pipe_write], &local_part_length, sizeof(int))) != sizeof(int)
2341 || (ret = write(pfd[pipe_write], addr2->local_part, local_part_length)) != local_part_length
2342 )
2343 )
2344 )
2345 log_write(0, LOG_MAIN|LOG_PANIC, "Failed writing transport results to pipe: %s\n",
2346 ret == -1 ? strerror(errno) : "short write");
2347
2348 /* Now any messages */
2349
2350 for (i = 0, s = addr2->message; i < 2; i++, s = addr2->user_message)
2351 {
2352 int message_length = s ? Ustrlen(s) + 1 : 0;
2353 if( (ret = write(pfd[pipe_write], &message_length, sizeof(int))) != sizeof(int)
2354 || message_length > 0 && (ret = write(pfd[pipe_write], s, message_length)) != message_length
2355 )
2356 log_write(0, LOG_MAIN|LOG_PANIC, "Failed writing transport results to pipe: %s\n",
2357 ret == -1 ? strerror(errno) : "short write");
2358 }
2359 }
2360
2361 /* OK, this process is now done. Free any cached resources that it opened,
2362 and close the pipe we were writing down before exiting. */
2363
2364 (void)close(pfd[pipe_write]);
2365 search_tidyup();
2366 exit(EXIT_SUCCESS);
2367 }
2368
2369 /* Back in the main process: panic if the fork did not succeed. This seems
2370 better than returning an error - if forking is failing it is probably best
2371 not to try other deliveries for this message. */
2372
2373 if (pid < 0)
2374 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Fork failed for local delivery to %s",
2375 addr->address);
2376
2377 /* Read the pipe to get the delivery status codes and error messages. Our copy
2378 of the writing end must be closed first, as otherwise read() won't return zero
2379 on an empty pipe. We check that a status exists for each address before
2380 overwriting the address structure. If data is missing, the default DEFER status
2381 will remain. Afterwards, close the reading end. */
2382
2383 (void)close(pfd[pipe_write]);
2384
2385 for (addr2 = addr; addr2; addr2 = addr2->next)
2386 {
2387 len = read(pfd[pipe_read], &status, sizeof(int));
2388 if (len > 0)
2389 {
2390 int i;
2391 uschar **sptr;
2392
2393 addr2->transport_return = status;
2394 len = read(pfd[pipe_read], &transport_count,
2395 sizeof(transport_count));
2396 len = read(pfd[pipe_read], &addr2->flags, sizeof(addr2->flags));
2397 len = read(pfd[pipe_read], &addr2->basic_errno, sizeof(int));
2398 len = read(pfd[pipe_read], &addr2->more_errno, sizeof(int));
2399 len = read(pfd[pipe_read], &addr2->special_action, sizeof(int));
2400 len = read(pfd[pipe_read], &addr2->transport,
2401 sizeof(transport_instance *));
2402
2403 if (testflag(addr2, af_file))
2404 {
2405 int local_part_length;
2406 len = read(pfd[pipe_read], &local_part_length, sizeof(int));
2407 len = read(pfd[pipe_read], big_buffer, local_part_length);
2408 big_buffer[local_part_length] = 0;
2409 addr2->local_part = string_copy(big_buffer);
2410 }
2411
2412 for (i = 0, sptr = &addr2->message; i < 2; i++, sptr = &addr2->user_message)
2413 {
2414 int message_length;
2415 len = read(pfd[pipe_read], &message_length, sizeof(int));
2416 if (message_length > 0)
2417 {
2418 len = read(pfd[pipe_read], big_buffer, message_length);
2419 big_buffer[big_buffer_size-1] = '\0'; /* guard byte */
2420 if (len > 0) *sptr = string_copy(big_buffer);
2421 }
2422 }
2423 }
2424
2425 else
2426 {
2427 log_write(0, LOG_MAIN|LOG_PANIC, "failed to read delivery status for %s "
2428 "from delivery subprocess", addr2->unique);
2429 break;
2430 }
2431 }
2432
2433 (void)close(pfd[pipe_read]);
2434
2435 /* Unless shadowing, write all successful addresses immediately to the journal
2436 file, to ensure they are recorded asap. For homonymic addresses, use the base
2437 address plus the transport name. Failure to write the journal is panic-worthy,
2438 but don't stop, as it may prove possible subsequently to update the spool file
2439 in order to record the delivery. */
2440
2441 if (!shadowing)
2442 {
2443 for (addr2 = addr; addr2; addr2 = addr2->next)
2444 if (addr2->transport_return == OK)
2445 {
2446 if (testflag(addr2, af_homonym))
2447 sprintf(CS big_buffer, "%.500s/%s\n", addr2->unique + 3, tp->name);
2448 else
2449 sprintf(CS big_buffer, "%.500s\n", addr2->unique);
2450
2451 /* In the test harness, wait just a bit to let the subprocess finish off
2452 any debug output etc first. */
2453
2454 if (running_in_test_harness) millisleep(300);
2455
2456 DEBUG(D_deliver) debug_printf("journalling %s", big_buffer);
2457 len = Ustrlen(big_buffer);
2458 if (write(journal_fd, big_buffer, len) != len)
2459 log_write(0, LOG_MAIN|LOG_PANIC, "failed to update journal for %s: %s",
2460 big_buffer, strerror(errno));
2461 }
2462
2463 /* Ensure the journal file is pushed out to disk. */
2464
2465 if (EXIMfsync(journal_fd) < 0)
2466 log_write(0, LOG_MAIN|LOG_PANIC, "failed to fsync journal: %s",
2467 strerror(errno));
2468 }
2469
2470 /* Wait for the process to finish. If it terminates with a non-zero code,
2471 freeze the message (except for SIGTERM, SIGKILL and SIGQUIT), but leave the
2472 status values of all the addresses as they are. Take care to handle the case
2473 when the subprocess doesn't seem to exist. This has been seen on one system
2474 when Exim was called from an MUA that set SIGCHLD to SIG_IGN. When that
2475 happens, wait() doesn't recognize the termination of child processes. Exim now
2476 resets SIGCHLD to SIG_DFL, but this code should still be robust. */
2477
2478 while ((rc = wait(&status)) != pid)
2479 if (rc < 0 && errno == ECHILD) /* Process has vanished */
2480 {
2481 log_write(0, LOG_MAIN, "%s transport process vanished unexpectedly",
2482 addr->transport->driver_name);
2483 status = 0;
2484 break;
2485 }
2486
2487 if ((status & 0xffff) != 0)
2488 {
2489 int msb = (status >> 8) & 255;
2490 int lsb = status & 255;
2491 int code = (msb == 0)? (lsb & 0x7f) : msb;
2492 if (msb != 0 || (code != SIGTERM && code != SIGKILL && code != SIGQUIT))
2493 addr->special_action = SPECIAL_FREEZE;
2494 log_write(0, LOG_MAIN|LOG_PANIC, "%s transport process returned non-zero "
2495 "status 0x%04x: %s %d",
2496 addr->transport->driver_name,
2497 status,
2498 msb == 0 ? "terminated by signal" : "exit code",
2499 code);
2500 }
2501
2502 /* If SPECIAL_WARN is set in the top address, send a warning message. */
2503
2504 if (addr->special_action == SPECIAL_WARN && addr->transport->warn_message)
2505 {
2506 int fd;
2507 uschar *warn_message;
2508 pid_t pid;
2509
2510 DEBUG(D_deliver) debug_printf("Warning message requested by transport\n");
2511
2512 if (!(warn_message = expand_string(addr->transport->warn_message)))
2513 log_write(0, LOG_MAIN|LOG_PANIC, "Failed to expand \"%s\" (warning "
2514 "message for %s transport): %s", addr->transport->warn_message,
2515 addr->transport->name, expand_string_message);
2516
2517 else if ((pid = child_open_exim(&fd)) > 0)
2518 {
2519 FILE *f = fdopen(fd, "wb");
2520 if (errors_reply_to && !contains_header(US"Reply-To", warn_message))
2521 fprintf(f, "Reply-To: %s\n", errors_reply_to);
2522 fprintf(f, "Auto-Submitted: auto-replied\n");
2523 if (!contains_header(US"From", warn_message))
2524 moan_write_from(f);
2525 fprintf(f, "%s", CS warn_message);
2526
2527 /* Close and wait for child process to complete, without a timeout. */
2528
2529 (void)fclose(f);
2530 (void)child_close(pid, 0);
2531 }
2532
2533 addr->special_action = SPECIAL_NONE;
2534 }
2535 }
2536
2537
2538
2539
2540 /* Check transport for the given concurrency limit. Return TRUE if over
2541 the limit (or an expansion failure), else FALSE and if there was a limit,
2542 the key for the hints database used for the concurrency count. */
2543
2544 static BOOL
2545 tpt_parallel_check(transport_instance * tp, address_item * addr, uschar ** key)
2546 {
2547 unsigned max_parallel;
2548
2549 if (!tp->max_parallel) return FALSE;
2550
2551 max_parallel = (unsigned) expand_string_integer(tp->max_parallel, TRUE);
2552 if (expand_string_message)
2553 {
2554 log_write(0, LOG_MAIN|LOG_PANIC, "Failed to expand max_parallel option "
2555 "in %s transport (%s): %s", tp->name, addr->address,
2556 expand_string_message);
2557 return TRUE;
2558 }
2559
2560 if (max_parallel > 0)
2561 {
2562 uschar * serialize_key = string_sprintf("tpt-serialize-%s", tp->name);
2563 if (!enq_start(serialize_key, max_parallel))
2564 {
2565 address_item * next;
2566 DEBUG(D_transport)
2567 debug_printf("skipping tpt %s because concurrency limit %u reached\n",
2568 tp->name, max_parallel);
2569 do
2570 {
2571 next = addr->next;
2572 addr->message = US"concurrency limit reached for transport";
2573 addr->basic_errno = ERRNO_TRETRY;
2574 post_process_one(addr, DEFER, LOG_MAIN, DTYPE_TRANSPORT, 0);
2575 } while ((addr = next));
2576 return TRUE;
2577 }
2578 *key = serialize_key;
2579 }
2580 return FALSE;
2581 }
2582
2583
2584
2585 /*************************************************
2586 * Do local deliveries *
2587 *************************************************/
2588
2589 /* This function processes the list of addresses in addr_local. True local
2590 deliveries are always done one address at a time. However, local deliveries can
2591 be batched up in some cases. Typically this is when writing batched SMTP output
2592 files for use by some external transport mechanism, or when running local
2593 deliveries over LMTP.
2594
2595 Arguments: None
2596 Returns: Nothing
2597 */
2598
2599 static void
2600 do_local_deliveries(void)
2601 {
2602 open_db dbblock;
2603 open_db *dbm_file = NULL;
2604 time_t now = time(NULL);
2605
2606 /* Loop until we have exhausted the supply of local deliveries */
2607
2608 while (addr_local)
2609 {
2610 time_t delivery_start;
2611 int deliver_time;
2612 address_item *addr2, *addr3, *nextaddr;
2613 int logflags = LOG_MAIN;
2614 int logchar = dont_deliver? '*' : '=';
2615 transport_instance *tp;
2616 uschar * serialize_key = NULL;
2617
2618 /* Pick the first undelivered address off the chain */
2619
2620 address_item *addr = addr_local;
2621 addr_local = addr->next;
2622 addr->next = NULL;
2623
2624 DEBUG(D_deliver|D_transport)
2625 debug_printf("--------> %s <--------\n", addr->address);
2626
2627 /* An internal disaster if there is no transport. Should not occur! */
2628
2629 if (!(tp = addr->transport))
2630 {
2631 logflags |= LOG_PANIC;
2632 disable_logging = FALSE; /* Jic */
2633 addr->message = addr->router
2634 ? string_sprintf("No transport set by %s router", addr->router->name)
2635 : string_sprintf("No transport set by system filter");
2636 post_process_one(addr, DEFER, logflags, DTYPE_TRANSPORT, 0);
2637 continue;
2638 }
2639
2640 /* Check that this base address hasn't previously been delivered to this
2641 transport. The check is necessary at this point to handle homonymic addresses
2642 correctly in cases where the pattern of redirection changes between delivery
2643 attempts. Non-homonymic previous delivery is detected earlier, at routing
2644 time. */
2645
2646 if (previously_transported(addr, FALSE)) continue;
2647
2648 /* There are weird cases where logging is disabled */
2649
2650 disable_logging = tp->disable_logging;
2651
2652 /* Check for batched addresses and possible amalgamation. Skip all the work
2653 if either batch_max <= 1 or there aren't any other addresses for local
2654 delivery. */
2655
2656 if (tp->batch_max > 1 && addr_local)
2657 {
2658 int batch_count = 1;
2659 BOOL uses_dom = readconf_depends((driver_instance *)tp, US"domain");
2660 BOOL uses_lp = ( testflag(addr, af_pfr)
2661 && (testflag(addr, af_file) || addr->local_part[0] == '|')
2662 )
2663 || readconf_depends((driver_instance *)tp, US"local_part");
2664 uschar *batch_id = NULL;
2665 address_item **anchor = &addr_local;
2666 address_item *last = addr;
2667 address_item *next;
2668
2669 /* Expand the batch_id string for comparison with other addresses.
2670 Expansion failure suppresses batching. */
2671
2672 if (tp->batch_id)
2673 {
2674 deliver_set_expansions(addr);
2675 batch_id = expand_string(tp->batch_id);
2676 deliver_set_expansions(NULL);
2677 if (!batch_id)
2678 {
2679 log_write(0, LOG_MAIN|LOG_PANIC, "Failed to expand batch_id option "
2680 "in %s transport (%s): %s", tp->name, addr->address,
2681 expand_string_message);
2682 batch_count = tp->batch_max;
2683 }
2684 }
2685
2686 /* Until we reach the batch_max limit, pick off addresses which have the
2687 same characteristics. These are:
2688
2689 same transport
2690 not previously delivered (see comment about 50 lines above)
2691 same local part if the transport's configuration contains $local_part
2692 or if this is a file or pipe delivery from a redirection
2693 same domain if the transport's configuration contains $domain
2694 same errors address
2695 same additional headers
2696 same headers to be removed
2697 same uid/gid for running the transport
2698 same first host if a host list is set
2699 */
2700
2701 while ((next = *anchor) && batch_count < tp->batch_max)
2702 {
2703 BOOL ok =
2704 tp == next->transport
2705 && !previously_transported(next, TRUE)
2706 && (addr->flags & (af_pfr|af_file)) == (next->flags & (af_pfr|af_file))
2707 && (!uses_lp || Ustrcmp(next->local_part, addr->local_part) == 0)
2708 && (!uses_dom || Ustrcmp(next->domain, addr->domain) == 0)
2709 && same_strings(next->prop.errors_address, addr->prop.errors_address)
2710 && same_headers(next->prop.extra_headers, addr->prop.extra_headers)
2711 && same_strings(next->prop.remove_headers, addr->prop.remove_headers)
2712 && same_ugid(tp, addr, next)
2713 && ( !addr->host_list && !next->host_list
2714 || addr->host_list
2715 && next->host_list
2716 && Ustrcmp(addr->host_list->name, next->host_list->name) == 0
2717 );
2718
2719 /* If the transport has a batch_id setting, batch_id will be non-NULL
2720 from the expansion outside the loop. Expand for this address and compare.
2721 Expansion failure makes this address ineligible for batching. */
2722
2723 if (ok && batch_id)
2724 {
2725 uschar *bid;
2726 address_item *save_nextnext = next->next;
2727 next->next = NULL; /* Expansion for a single address */
2728 deliver_set_expansions(next);
2729 next->next = save_nextnext;
2730 bid = expand_string(tp->batch_id);
2731 deliver_set_expansions(NULL);
2732 if (!bid)
2733 {
2734 log_write(0, LOG_MAIN|LOG_PANIC, "Failed to expand batch_id option "
2735 "in %s transport (%s): %s", tp->name, next->address,
2736 expand_string_message);
2737 ok = FALSE;
2738 }
2739 else ok = (Ustrcmp(batch_id, bid) == 0);
2740 }
2741
2742 /* Take address into batch if OK. */
2743
2744 if (ok)
2745 {
2746 *anchor = next->next; /* Include the address */
2747 next->next = NULL;
2748 last->next = next;
2749 last = next;
2750 batch_count++;
2751 }
2752 else anchor = &next->next; /* Skip the address */
2753 }
2754 }
2755
2756 /* We now have one or more addresses that can be delivered in a batch. Check
2757 whether the transport is prepared to accept a message of this size. If not,
2758 fail them all forthwith. If the expansion fails, or does not yield an
2759 integer, defer delivery. */
2760
2761 if (tp->message_size_limit)
2762 {
2763 int rc = check_message_size(tp, addr);
2764 if (rc != OK)
2765 {
2766 replicate_status(addr);
2767 while (addr)
2768 {
2769 addr2 = addr->next;
2770 post_process_one(addr, rc, logflags, DTYPE_TRANSPORT, 0);
2771 addr = addr2;
2772 }
2773 continue; /* With next batch of addresses */
2774 }
2775 }
2776
2777 /* If we are not running the queue, or if forcing, all deliveries will be
2778 attempted. Otherwise, we must respect the retry times for each address. Even
2779 when not doing this, we need to set up the retry key string, and determine
2780 whether a retry record exists, because after a successful delivery, a delete
2781 retry item must be set up. Keep the retry database open only for the duration
2782 of these checks, rather than for all local deliveries, because some local
2783 deliveries (e.g. to pipes) can take a substantial time. */
2784
2785 if (!(dbm_file = dbfn_open(US"retry", O_RDONLY, &dbblock, FALSE)))
2786 {
2787 DEBUG(D_deliver|D_retry|D_hints_lookup)
2788 debug_printf("no retry data available\n");
2789 }
2790
2791 addr2 = addr;
2792 addr3 = NULL;
2793 while (addr2)
2794 {
2795 BOOL ok = TRUE; /* to deliver this address */
2796 uschar *retry_key;
2797
2798 /* Set up the retry key to include the domain or not, and change its
2799 leading character from "R" to "T". Must make a copy before doing this,
2800 because the old key may be pointed to from a "delete" retry item after
2801 a routing delay. */
2802
2803 retry_key = string_copy(
2804 tp->retry_use_local_part ? addr2->address_retry_key :
2805 addr2->domain_retry_key);
2806 *retry_key = 'T';
2807
2808 /* Inspect the retry data. If there is no hints file, delivery happens. */
2809
2810 if (dbm_file)
2811 {
2812 dbdata_retry *retry_record = dbfn_read(dbm_file, retry_key);
2813
2814 /* If there is no retry record, delivery happens. If there is,
2815 remember it exists so it can be deleted after a successful delivery. */
2816
2817 if (retry_record)
2818 {
2819 setflag(addr2, af_lt_retry_exists);
2820
2821 /* A retry record exists for this address. If queue running and not
2822 forcing, inspect its contents. If the record is too old, or if its
2823 retry time has come, or if it has passed its cutoff time, delivery
2824 will go ahead. */
2825
2826 DEBUG(D_retry)
2827 {
2828 debug_printf("retry record exists: age=%s ",
2829 readconf_printtime(now - retry_record->time_stamp));
2830 debug_printf("(max %s)\n", readconf_printtime(retry_data_expire));
2831 debug_printf(" time to retry = %s expired = %d\n",
2832 readconf_printtime(retry_record->next_try - now),
2833 retry_record->expired);
2834 }
2835
2836 if (queue_running && !deliver_force)
2837 {
2838 ok = (now - retry_record->time_stamp > retry_data_expire)
2839 || (now >= retry_record->next_try)
2840 || retry_record->expired;
2841
2842 /* If we haven't reached the retry time, there is one more check
2843 to do, which is for the ultimate address timeout. */
2844
2845 if (!ok)
2846 ok = retry_ultimate_address_timeout(retry_key, addr2->domain,
2847 retry_record, now);
2848 }
2849 }
2850 else DEBUG(D_retry) debug_printf("no retry record exists\n");
2851 }
2852
2853 /* This address is to be delivered. Leave it on the chain. */
2854
2855 if (ok)
2856 {
2857 addr3 = addr2;
2858 addr2 = addr2->next;
2859 }
2860
2861 /* This address is to be deferred. Take it out of the chain, and
2862 post-process it as complete. Must take it out of the chain first,
2863 because post processing puts it on another chain. */
2864
2865 else
2866 {
2867 address_item *this = addr2;
2868 this->message = US"Retry time not yet reached";
2869 this->basic_errno = ERRNO_LRETRY;
2870 addr2 = addr3 ? (addr3->next = addr2->next)
2871 : (addr = addr2->next);
2872 post_process_one(this, DEFER, logflags, DTYPE_TRANSPORT, 0);
2873 }
2874 }
2875
2876 if (dbm_file) dbfn_close(dbm_file);
2877
2878 /* If there are no addresses left on the chain, they all deferred. Loop
2879 for the next set of addresses. */
2880
2881 if (!addr) continue;
2882
2883 /* If the transport is limited for parallellism, enforce that here.
2884 We use a hints DB entry, incremented here and decremented after
2885 the transport (and any shadow transport) completes. */
2886
2887 if (tpt_parallel_check(tp, addr, &serialize_key))
2888 {
2889 if (expand_string_message)
2890 {
2891 logflags |= LOG_PANIC;
2892 do
2893 {
2894 addr = addr->next;
2895 post_process_one(addr, DEFER, logflags, DTYPE_TRANSPORT, 0);
2896 } while ((addr = addr2));
2897 }
2898 continue; /* Loop for the next set of addresses. */
2899 }
2900
2901
2902 /* So, finally, we do have some addresses that can be passed to the
2903 transport. Before doing so, set up variables that are relevant to a
2904 single delivery. */
2905
2906 deliver_set_expansions(addr);
2907 delivery_start = time(NULL);
2908 deliver_local(addr, FALSE);
2909 deliver_time = (int)(time(NULL) - delivery_start);
2910
2911 /* If a shadow transport (which must perforce be another local transport), is
2912 defined, and its condition is met, we must pass the message to the shadow
2913 too, but only those addresses that succeeded. We do this by making a new
2914 chain of addresses - also to keep the original chain uncontaminated. We must
2915 use a chain rather than doing it one by one, because the shadow transport may
2916 batch.
2917
2918 NOTE: if the condition fails because of a lookup defer, there is nothing we
2919 can do! */
2920
2921 if ( tp->shadow
2922 && ( !tp->shadow_condition
2923 || expand_check_condition(tp->shadow_condition, tp->name, US"transport")
2924 ) )
2925 {
2926 transport_instance *stp;
2927 address_item *shadow_addr = NULL;
2928 address_item **last = &shadow_addr;
2929
2930 for (stp = transports; stp; stp = stp->next)
2931 if (Ustrcmp(stp->name, tp->shadow) == 0) break;
2932
2933 if (!stp)
2934 log_write(0, LOG_MAIN|LOG_PANIC, "shadow transport \"%s\" not found ",
2935 tp->shadow);
2936
2937 /* Pick off the addresses that have succeeded, and make clones. Put into
2938 the shadow_message field a pointer to the shadow_message field of the real
2939 address. */
2940
2941 else for (addr2 = addr; addr2; addr2 = addr2->next)
2942 if (addr2->transport_return == OK)
2943 {
2944 addr3 = store_get(sizeof(address_item));
2945 *addr3 = *addr2;
2946 addr3->next = NULL;
2947 addr3->shadow_message = (uschar *) &(addr2->shadow_message);
2948 addr3->transport = stp;
2949 addr3->transport_return = DEFER;
2950 addr3->return_filename = NULL;
2951 addr3->return_file = -1;
2952 *last = addr3;
2953 last = &(addr3->next);
2954 }
2955
2956 /* If we found any addresses to shadow, run the delivery, and stick any
2957 message back into the shadow_message field in the original. */
2958
2959 if (shadow_addr)
2960 {
2961 int save_count = transport_count;
2962
2963 DEBUG(D_deliver|D_transport)
2964 debug_printf(">>>>>>>>>>>>>>>> Shadow delivery >>>>>>>>>>>>>>>>\n");
2965 deliver_local(shadow_addr, TRUE);
2966
2967 for(; shadow_addr; shadow_addr = shadow_addr->next)
2968 {
2969 int sresult = shadow_addr->transport_return;
2970 *(uschar **)shadow_addr->shadow_message =
2971 sresult == OK
2972 ? string_sprintf(" ST=%s", stp->name)
2973 : string_sprintf(" ST=%s (%s%s%s)", stp->name,
2974 shadow_addr->basic_errno <= 0
2975 ? US""
2976 : US strerror(shadow_addr->basic_errno),
2977 shadow_addr->basic_errno <= 0 || !shadow_addr->message
2978 ? US""
2979 : US": ",
2980 shadow_addr->message
2981 ? shadow_addr->message
2982 : shadow_addr->basic_errno <= 0
2983 ? US"unknown error"
2984 : US"");
2985
2986 DEBUG(D_deliver|D_transport)
2987 debug_printf("%s shadow transport returned %s for %s\n",
2988 stp->name,
2989 sresult == OK ? "OK" :
2990 sresult == DEFER ? "DEFER" :
2991 sresult == FAIL ? "FAIL" :
2992 sresult == PANIC ? "PANIC" : "?",
2993 shadow_addr->address);
2994 }
2995
2996 DEBUG(D_deliver|D_transport)
2997 debug_printf(">>>>>>>>>>>>>>>> End shadow delivery >>>>>>>>>>>>>>>>\n");
2998
2999 transport_count = save_count; /* Restore original transport count */
3000 }
3001 }
3002
3003 /* Cancel the expansions that were set up for the delivery. */
3004
3005 deliver_set_expansions(NULL);
3006
3007 /* If the transport was parallelism-limited, decrement the hints DB record. */
3008
3009 if (serialize_key) enq_end(serialize_key);
3010
3011 /* Now we can process the results of the real transport. We must take each
3012 address off the chain first, because post_process_one() puts it on another
3013 chain. */
3014
3015 for (addr2 = addr; addr2; addr2 = nextaddr)
3016 {
3017 int result = addr2->transport_return;
3018 nextaddr = addr2->next;
3019
3020 DEBUG(D_deliver|D_transport)
3021 debug_printf("%s transport returned %s for %s\n",
3022 tp->name,
3023 result == OK ? "OK" :
3024 result == DEFER ? "DEFER" :
3025 result == FAIL ? "FAIL" :
3026 result == PANIC ? "PANIC" : "?",
3027 addr2->address);
3028
3029 /* If there is a retry_record, or if delivery is deferred, build a retry
3030 item for setting a new retry time or deleting the old retry record from
3031 the database. These items are handled all together after all addresses
3032 have been handled (so the database is open just for a short time for
3033 updating). */
3034
3035 if (result == DEFER || testflag(addr2, af_lt_retry_exists))
3036 {
3037 int flags = result == DEFER ? 0 : rf_delete;
3038 uschar *retry_key = string_copy(tp->retry_use_local_part
3039 ? addr2->address_retry_key : addr2->domain_retry_key);
3040 *retry_key = 'T';
3041 retry_add_item(addr2, retry_key, flags);
3042 }
3043
3044 /* Done with this address */
3045
3046 if (result == OK) addr2->more_errno = deliver_time;
3047 post_process_one(addr2, result, logflags, DTYPE_TRANSPORT, logchar);
3048
3049 /* If a pipe delivery generated text to be sent back, the result may be
3050 changed to FAIL, and we must copy this for subsequent addresses in the
3051 batch. */
3052
3053 if (addr2->transport_return != result)
3054 {
3055 for (addr3 = nextaddr; addr3; addr3 = addr3->next)
3056 {
3057 addr3->transport_return = addr2->transport_return;
3058 addr3->basic_errno = addr2->basic_errno;
3059 addr3->message = addr2->message;
3060 }
3061 result = addr2->transport_return;
3062 }
3063
3064 /* Whether or not the result was changed to FAIL, we need to copy the
3065 return_file value from the first address into all the addresses of the
3066 batch, so they are all listed in the error message. */
3067
3068 addr2->return_file = addr->return_file;
3069
3070 /* Change log character for recording successful deliveries. */
3071
3072 if (result == OK) logchar = '-';
3073 }
3074 } /* Loop back for next batch of addresses */
3075 }
3076
3077
3078
3079
3080 /*************************************************
3081 * Sort remote deliveries *
3082 *************************************************/
3083
3084 /* This function is called if remote_sort_domains is set. It arranges that the
3085 chain of addresses for remote deliveries is ordered according to the strings
3086 specified. Try to make this shuffling reasonably efficient by handling
3087 sequences of addresses rather than just single ones.
3088
3089 Arguments: None
3090 Returns: Nothing
3091 */
3092
3093 static void
3094 sort_remote_deliveries(void)
3095 {
3096 int sep = 0;
3097 address_item **aptr = &addr_remote;
3098 const uschar *listptr = remote_sort_domains;
3099 uschar *pattern;
3100 uschar patbuf[256];
3101
3102 while ( *aptr
3103 && (pattern = string_nextinlist(&listptr, &sep, patbuf, sizeof(patbuf)))
3104 )
3105 {
3106 address_item *moved = NULL;
3107 address_item **bptr = &moved;
3108
3109 while (*aptr)
3110 {
3111 address_item **next;
3112 deliver_domain = (*aptr)->domain; /* set $domain */
3113 if (match_isinlist(deliver_domain, (const uschar **)&pattern, UCHAR_MAX+1,
3114 &domainlist_anchor, NULL, MCL_DOMAIN, TRUE, NULL) == OK)
3115 {
3116 aptr = &(*aptr)->next;
3117 continue;
3118 }
3119
3120 next = &(*aptr)->next;
3121 while ( *next
3122 && (deliver_domain = (*next)->domain, /* Set $domain */
3123 match_isinlist(deliver_domain, (const uschar **)&pattern, UCHAR_MAX+1,
3124 &domainlist_anchor, NULL, MCL_DOMAIN, TRUE, NULL)) != OK
3125 )
3126 next = &(*next)->next;
3127
3128 /* If the batch of non-matchers is at the end, add on any that were
3129 extracted further up the chain, and end this iteration. Otherwise,
3130 extract them from the chain and hang on the moved chain. */
3131
3132 if (!*next)
3133 {
3134 *next = moved;
3135 break;
3136 }
3137
3138 *bptr = *aptr;
3139 *aptr = *next;
3140 *next = NULL;
3141 bptr = next;
3142 aptr = &(*aptr)->next;
3143 }
3144
3145 /* If the loop ended because the final address matched, *aptr will
3146 be NULL. Add on to the end any extracted non-matching addresses. If
3147 *aptr is not NULL, the loop ended via "break" when *next is null, that
3148 is, there was a string of non-matching addresses at the end. In this
3149 case the extracted addresses have already been added on the end. */
3150
3151 if (!*aptr) *aptr = moved;
3152 }
3153
3154 DEBUG(D_deliver)
3155 {
3156 address_item *addr;
3157 debug_printf("remote addresses after sorting:\n");
3158 for (addr = addr_remote; addr; addr = addr->next)
3159 debug_printf(" %s\n", addr->address);
3160 }
3161 }
3162
3163
3164
3165 /*************************************************
3166 * Read from pipe for remote delivery subprocess *
3167 *************************************************/
3168
3169 /* This function is called when the subprocess is complete, but can also be
3170 called before it is complete, in order to empty a pipe that is full (to prevent
3171 deadlock). It must therefore keep track of its progress in the parlist data
3172 block.
3173
3174 We read the pipe to get the delivery status codes and a possible error message
3175 for each address, optionally preceded by unusability data for the hosts and
3176 also by optional retry data.
3177
3178 Read in large chunks into the big buffer and then scan through, interpreting
3179 the data therein. In most cases, only a single read will be necessary. No
3180 individual item will ever be anywhere near 2500 bytes in length, so by ensuring
3181 that we read the next chunk when there is less than 2500 bytes left in the
3182 non-final chunk, we can assume each item is complete in the buffer before
3183 handling it. Each item is written using a single write(), which is atomic for
3184 small items (less than PIPE_BUF, which seems to be at least 512 in any Unix and
3185 often bigger) so even if we are reading while the subprocess is still going, we
3186 should never have only a partial item in the buffer.
3187
3188 Argument:
3189 poffset the offset of the parlist item
3190 eop TRUE if the process has completed
3191
3192 Returns: TRUE if the terminating 'Z' item has been read,
3193 or there has been a disaster (i.e. no more data needed);
3194 FALSE otherwise
3195 */
3196
3197 static BOOL
3198 par_read_pipe(int poffset, BOOL eop)
3199 {
3200 host_item *h;
3201 pardata *p = parlist + poffset;
3202 address_item *addrlist = p->addrlist;
3203 address_item *addr = p->addr;
3204 pid_t pid = p->pid;
3205 int fd = p->fd;
3206 uschar *endptr = big_buffer;
3207 uschar *ptr = endptr;
3208 uschar *msg = p->msg;
3209 BOOL done = p->done;
3210 BOOL unfinished = TRUE;
3211 /* minimum size to read is header size including id, subid and length */
3212 int required = PIPE_HEADER_SIZE;
3213
3214 /* Loop through all items, reading from the pipe when necessary. The pipe
3215 is set up to be non-blocking, but there are two different Unix mechanisms in
3216 use. Exim uses O_NONBLOCK if it is defined. This returns 0 for end of file,
3217 and EAGAIN for no more data. If O_NONBLOCK is not defined, Exim uses O_NDELAY,
3218 which returns 0 for both end of file and no more data. We distinguish the
3219 two cases by taking 0 as end of file only when we know the process has
3220 completed.
3221
3222 Each separate item is written to the pipe in a single write(), and as they are
3223 all short items, the writes will all be atomic and we should never find
3224 ourselves in the position of having read an incomplete item. "Short" in this
3225 case can mean up to about 1K in the case when there is a long error message
3226 associated with an address. */
3227
3228 DEBUG(D_deliver) debug_printf("reading pipe for subprocess %d (%s)\n",
3229 (int)p->pid, eop? "ended" : "not ended");
3230
3231 while (!done)
3232 {
3233 retry_item *r, **rp;
3234 int remaining = endptr - ptr;
3235 uschar header[PIPE_HEADER_SIZE + 1];
3236 uschar id, subid;
3237 uschar *endc;
3238
3239 /* Read (first time) or top up the chars in the buffer if necessary.
3240 There will be only one read if we get all the available data (i.e. don't
3241 fill the buffer completely). */
3242
3243 if (remaining < required && unfinished)
3244 {
3245 int len;
3246 int available = big_buffer_size - remaining;
3247
3248 if (remaining > 0) memmove(big_buffer, ptr, remaining);
3249
3250 ptr = big_buffer;
3251 endptr = big_buffer + remaining;
3252 len = read(fd, endptr, available);
3253
3254 DEBUG(D_deliver) debug_printf("read() yielded %d\n", len);
3255
3256 /* If the result is EAGAIN and the process is not complete, just
3257 stop reading any more and process what we have already. */
3258
3259 if (len < 0)
3260 {
3261 if (!eop && errno == EAGAIN) len = 0; else
3262 {
3263 msg = string_sprintf("failed to read pipe from transport process "
3264 "%d for transport %s: %s", pid, addr->transport->driver_name,
3265 strerror(errno));
3266 break;
3267 }
3268 }
3269
3270 /* If the length is zero (eof or no-more-data), just process what we
3271 already have. Note that if the process is still running and we have
3272 read all the data in the pipe (but less that "available") then we
3273 won't read any more, as "unfinished" will get set FALSE. */
3274
3275 endptr += len;
3276 remaining += len;
3277 unfinished = len == available;
3278 }
3279
3280 /* If we are at the end of the available data, exit the loop. */
3281 if (ptr >= endptr) break;
3282
3283 /* copy and read header */
3284 memcpy(header, ptr, PIPE_HEADER_SIZE);
3285 header[PIPE_HEADER_SIZE] = '\0';
3286 id = header[0];
3287 subid = header[1];
3288 required = Ustrtol(header + 2, &endc, 10) + PIPE_HEADER_SIZE; /* header + data */
3289 if (*endc)
3290 {
3291 msg = string_sprintf("failed to read pipe from transport process "
3292 "%d for transport %s: error reading size from header", pid, addr->transport->driver_name);
3293 done = TRUE;
3294 break;
3295 }
3296
3297 DEBUG(D_deliver)
3298 debug_printf("header read id:%c,subid:%c,size:%s,required:%d,remaining:%d,unfinished:%d\n",
3299 id, subid, header+2, required, remaining, unfinished);
3300
3301 /* is there room for the dataset we want to read ? */
3302 if (required > big_buffer_size - PIPE_HEADER_SIZE)
3303 {
3304 msg = string_sprintf("failed to read pipe from transport process "
3305 "%d for transport %s: big_buffer too small! required size=%d buffer size=%d", pid, addr->transport->driver_name,
3306 required, big_buffer_size - PIPE_HEADER_SIZE);
3307 done = TRUE;
3308 break;
3309 }
3310
3311 /* we wrote all datasets with atomic write() calls
3312 remaining < required only happens if big_buffer was too small
3313 to get all available data from pipe. unfinished has to be true
3314 as well. */
3315 if (remaining < required)
3316 {
3317 if (unfinished)
3318 continue;
3319 msg = string_sprintf("failed to read pipe from transport process "
3320 "%d for transport %s: required size=%d > remaining size=%d and unfinished=false",
3321 pid, addr->transport->driver_name, required, remaining);
3322 done = TRUE;
3323 break;
3324 }
3325
3326 /* step behind the header */
3327 ptr += PIPE_HEADER_SIZE;
3328
3329 /* Handle each possible type of item, assuming the complete item is
3330 available in store. */
3331
3332 switch (id)
3333 {
3334 /* Host items exist only if any hosts were marked unusable. Match
3335 up by checking the IP address. */
3336
3337 case 'H':
3338 for (h = addrlist->host_list; h; h = h->next)
3339 {
3340 if (!h->address || Ustrcmp(h->address, ptr+2) != 0) continue;
3341 h->status = ptr[0];
3342 h->why = ptr[1];
3343 }
3344 ptr += 2;
3345 while (*ptr++);
3346 break;
3347
3348 /* Retry items are sent in a preceding R item for each address. This is
3349 kept separate to keep each message short enough to guarantee it won't
3350 be split in the pipe. Hopefully, in the majority of cases, there won't in
3351 fact be any retry items at all.
3352
3353 The complete set of retry items might include an item to delete a
3354 routing retry if there was a previous routing delay. However, routing
3355 retries are also used when a remote transport identifies an address error.
3356 In that case, there may also be an "add" item for the same key. Arrange
3357 that a "delete" item is dropped in favour of an "add" item. */
3358
3359 case 'R':
3360 if (!addr) goto ADDR_MISMATCH;
3361
3362 DEBUG(D_deliver|D_retry)
3363 debug_printf("reading retry information for %s from subprocess\n",
3364 ptr+1);
3365
3366 /* Cut out any "delete" items on the list. */
3367
3368 for (rp = &(addr->retries); (r = *rp); rp = &r->next)
3369 if (Ustrcmp(r->key, ptr+1) == 0) /* Found item with same key */
3370 {
3371 if ((r->flags & rf_delete) == 0) break; /* It was not "delete" */
3372 *rp = r->next; /* Excise a delete item */
3373 DEBUG(D_deliver|D_retry)
3374 debug_printf(" existing delete item dropped\n");
3375 }
3376
3377 /* We want to add a delete item only if there is no non-delete item;
3378 however we still have to step ptr through the data. */
3379
3380 if (!r || (*ptr & rf_delete) == 0)
3381 {
3382 r = store_get(sizeof(retry_item));
3383 r->next = addr->retries;
3384 addr->retries = r;
3385 r->flags = *ptr++;
3386 r->key = string_copy(ptr);
3387 while (*ptr++);
3388 memcpy(&(r->basic_errno), ptr, sizeof(r->basic_errno));
3389 ptr += sizeof(r->basic_errno);
3390 memcpy(&(r->more_errno), ptr, sizeof(r->more_errno));
3391 ptr += sizeof(r->more_errno);
3392 r->message = (*ptr)? string_copy(ptr) : NULL;
3393 DEBUG(D_deliver|D_retry)
3394 debug_printf(" added %s item\n",
3395 ((r->flags & rf_delete) == 0)? "retry" : "delete");
3396 }
3397
3398 else
3399 {
3400 DEBUG(D_deliver|D_retry)
3401 debug_printf(" delete item not added: non-delete item exists\n");
3402 ptr++;
3403 while(*ptr++);
3404 ptr += sizeof(r->basic_errno) + sizeof(r->more_errno);
3405 }
3406
3407 while(*ptr++);
3408 break;
3409
3410 /* Put the amount of data written into the parlist block */
3411
3412 case 'S':
3413 memcpy(&(p->transport_count), ptr, sizeof(transport_count));
3414 ptr += sizeof(transport_count);
3415 break;
3416
3417 /* Address items are in the order of items on the address chain. We
3418 remember the current address value in case this function is called
3419 several times to empty the pipe in stages. Information about delivery
3420 over TLS is sent in a preceding X item for each address. We don't put
3421 it in with the other info, in order to keep each message short enough to
3422 guarantee it won't be split in the pipe. */
3423
3424 #ifdef SUPPORT_TLS
3425 case 'X':
3426 if (!addr) goto ADDR_MISMATCH; /* Below, in 'A' handler */
3427 switch (subid)
3428 {
3429 case '1':
3430 addr->cipher = NULL;
3431 addr->peerdn = NULL;
3432
3433 if (*ptr)
3434 addr->cipher = string_copy(ptr);
3435 while (*ptr++);
3436 if (*ptr)
3437 addr