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