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