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