Fix mariadb/mysql macro confusion
[exim.git] / src / src / transport.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/* General functions concerned with transportation, and generic options for all
9transports. */
10
11
12#include "exim.h"
13
059ec3d9
PH
14/* Generic options for transports, all of which live inside transport_instance
15data blocks and which therefore have the opt_public flag set. Note that there
16are other options living inside this structure which can be set only from
17certain transports. */
18
19optionlist optionlist_transports[] = {
f2ed27cf 20 /* name type value */
059ec3d9
PH
21 { "*expand_group", opt_stringptr|opt_hidden|opt_public,
22 (void *)offsetof(transport_instance, expand_gid) },
23 { "*expand_user", opt_stringptr|opt_hidden|opt_public,
24 (void *)offsetof(transport_instance, expand_uid) },
25 { "*headers_rewrite_flags", opt_int|opt_public|opt_hidden,
26 (void *)offsetof(transport_instance, rewrite_existflags) },
27 { "*headers_rewrite_rules", opt_void|opt_public|opt_hidden,
28 (void *)offsetof(transport_instance, rewrite_rules) },
29 { "*set_group", opt_bool|opt_hidden|opt_public,
30 (void *)offsetof(transport_instance, gid_set) },
31 { "*set_user", opt_bool|opt_hidden|opt_public,
32 (void *)offsetof(transport_instance, uid_set) },
33 { "body_only", opt_bool|opt_public,
34 (void *)offsetof(transport_instance, body_only) },
35 { "current_directory", opt_stringptr|opt_public,
36 (void *)offsetof(transport_instance, current_dir) },
37 { "debug_print", opt_stringptr | opt_public,
38 (void *)offsetof(transport_instance, debug_string) },
39 { "delivery_date_add", opt_bool|opt_public,
40 (void *)(offsetof(transport_instance, delivery_date_add)) },
41 { "disable_logging", opt_bool|opt_public,
42 (void *)(offsetof(transport_instance, disable_logging)) },
43 { "driver", opt_stringptr|opt_public,
44 (void *)offsetof(transport_instance, driver_name) },
45 { "envelope_to_add", opt_bool|opt_public,
46 (void *)(offsetof(transport_instance, envelope_to_add)) },
0cbf2b82 47#ifndef DISABLE_EVENT
774ef2d7
JH
48 { "event_action", opt_stringptr | opt_public,
49 (void *)offsetof(transport_instance, event_action) },
50#endif
059ec3d9
PH
51 { "group", opt_expand_gid|opt_public,
52 (void *)offsetof(transport_instance, gid) },
846726c5 53 { "headers_add", opt_stringptr|opt_public|opt_rep_str,
059ec3d9
PH
54 (void *)offsetof(transport_instance, add_headers) },
55 { "headers_only", opt_bool|opt_public,
56 (void *)offsetof(transport_instance, headers_only) },
846726c5 57 { "headers_remove", opt_stringptr|opt_public|opt_rep_str,
059ec3d9
PH
58 (void *)offsetof(transport_instance, remove_headers) },
59 { "headers_rewrite", opt_rewrite|opt_public,
60 (void *)offsetof(transport_instance, headers_rewrite) },
61 { "home_directory", opt_stringptr|opt_public,
62 (void *)offsetof(transport_instance, home_dir) },
63 { "initgroups", opt_bool|opt_public,
64 (void *)offsetof(transport_instance, initgroups) },
fa41615d
JH
65 { "max_parallel", opt_stringptr|opt_public,
66 (void *)offsetof(transport_instance, max_parallel) },
059ec3d9
PH
67 { "message_size_limit", opt_stringptr|opt_public,
68 (void *)offsetof(transport_instance, message_size_limit) },
69 { "rcpt_include_affixes", opt_bool|opt_public,
70 (void *)offsetof(transport_instance, rcpt_include_affixes) },
71 { "retry_use_local_part", opt_bool|opt_public,
72 (void *)offsetof(transport_instance, retry_use_local_part) },
73 { "return_path", opt_stringptr|opt_public,
74 (void *)(offsetof(transport_instance, return_path)) },
75 { "return_path_add", opt_bool|opt_public,
76 (void *)(offsetof(transport_instance, return_path_add)) },
77 { "shadow_condition", opt_stringptr|opt_public,
78 (void *)offsetof(transport_instance, shadow_condition) },
79 { "shadow_transport", opt_stringptr|opt_public,
80 (void *)offsetof(transport_instance, shadow) },
81 { "transport_filter", opt_stringptr|opt_public,
82 (void *)offsetof(transport_instance, filter_command) },
83 { "transport_filter_timeout", opt_time|opt_public,
84 (void *)offsetof(transport_instance, filter_timeout) },
85 { "user", opt_expand_uid|opt_public,
86 (void *)offsetof(transport_instance, uid) }
87};
88
c0b9d3e8 89int optionlist_transports_size = nelem(optionlist_transports);
059ec3d9 90
d185889f
JH
91#ifdef MACRO_PREDEF
92
93# include "macro_predef.h"
059ec3d9 94
c0b9d3e8 95void
d185889f 96options_transports(void)
c0b9d3e8
JH
97{
98struct transport_info * ti;
d185889f 99uschar buf[64];
c0b9d3e8 100
d185889f 101options_from_list(optionlist_transports, nelem(optionlist_transports), US"TRANSPORTS", NULL);
c0b9d3e8
JH
102
103for (ti = transports_available; ti->driver_name[0]; ti++)
4945f557 104 {
cab0c277 105 spf(buf, sizeof(buf), US"_DRIVER_TRANSPORT_%T", ti->driver_name);
d185889f
JH
106 builtin_macro_create(buf);
107 options_from_list(ti->options, (unsigned)*ti->options_count, US"TRANSPORT", ti->driver_name);
4945f557 108 }
383832ef 109}
c0b9d3e8 110
d185889f
JH
111#else /*!MACRO_PREDEF*/
112
113/* Structure for keeping list of addresses that have been added to
114Envelope-To:, in order to avoid duplication. */
115
116struct aci {
117 struct aci *next;
118 address_item *ptr;
119 };
120
121
122/* Static data for write_chunk() */
123
124static uschar *chunk_ptr; /* chunk pointer */
125static uschar *nl_check; /* string to look for at line start */
126static int nl_check_length; /* length of same */
127static uschar *nl_escape; /* string to insert */
128static int nl_escape_length; /* length of same */
129static int nl_partial_match; /* length matched at chunk end */
130
131
059ec3d9
PH
132/*************************************************
133* Initialize transport list *
134*************************************************/
135
136/* Read the transports section of the configuration file, and set up a chain of
137transport instances according to its contents. Each transport has generic
138options and may also have its own private options. This function is only ever
139called when transports == NULL. We use generic code in readconf to do most of
140the work. */
141
142void
143transport_init(void)
144{
145transport_instance *t;
146
147readconf_driver_init(US"transport",
148 (driver_instance **)(&transports), /* chain anchor */
149 (driver_info *)transports_available, /* available drivers */
150 sizeof(transport_info), /* size of info block */
151 &transport_defaults, /* default values for generic options */
152 sizeof(transport_instance), /* size of instance block */
153 optionlist_transports, /* generic options */
154 optionlist_transports_size);
155
156/* Now scan the configured transports and check inconsistencies. A shadow
157transport is permitted only for local transports. */
158
7b4c8c1f 159for (t = transports; t; t = t->next)
059ec3d9 160 {
7b4c8c1f
JH
161 if (!t->info->local && t->shadow)
162 log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
163 "shadow transport not allowed on non-local transport %s", t->name);
059ec3d9
PH
164
165 if (t->body_only && t->headers_only)
166 log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
167 "%s transport: body_only and headers_only are mutually exclusive",
168 t->name);
169 }
170}
171
172
173
174/*************************************************
175* Write block of data *
176*************************************************/
177
178/* Subroutine called by write_chunk() and at the end of the message actually
179to write a data block. Also called directly by some transports to write
180additional data to the file descriptor (e.g. prefix, suffix).
181
182If a transport wants data transfers to be timed, it sets a non-zero value in
183transport_write_timeout. A non-zero transport_write_timeout causes a timer to
184be set for each block of data written from here. If time runs out, then write()
185fails and provokes an error return. The caller can then inspect sigalrm_seen to
186check for a timeout.
187
188On some systems, if a quota is exceeded during the write, the yield is the
189number of bytes written rather than an immediate error code. This also happens
190on some systems in other cases, for example a pipe that goes away because the
191other end's process terminates (Linux). On other systems, (e.g. Solaris 2) you
192get the error codes the first time.
193
194The write() function is also interruptible; the Solaris 2.6 man page says:
195
196 If write() is interrupted by a signal before it writes any
197 data, it will return -1 with errno set to EINTR.
198
199 If write() is interrupted by a signal after it successfully
200 writes some data, it will return the number of bytes written.
201
202To handle these cases, we want to restart the write() to output the remainder
203of the data after a non-negative return from write(), except after a timeout.
204In the error cases (EDQUOT, EPIPE) no bytes get written the second time, and a
205proper error then occurs. In principle, after an interruption, the second
206write() could suffer the same fate, but we do not want to continue for
207evermore, so stick a maximum repetition count on the loop to act as a
208longstop.
209
210Arguments:
42055a33 211 tctx transport context: file descriptor or string to write to
059ec3d9
PH
212 block block of bytes to write
213 len number of bytes to write
925ac8e4 214 more further data expected soon
059ec3d9
PH
215
216Returns: TRUE on success, FALSE on failure (with errno preserved);
217 transport_count is incremented by the number of bytes written
218*/
219
42055a33
JH
220static BOOL
221transport_write_block_fd(transport_ctx * tctx, uschar *block, int len, BOOL more)
059ec3d9
PH
222{
223int i, rc, save_errno;
958541e9 224int local_timeout = transport_write_timeout;
42055a33 225int fd = tctx->u.fd;
958541e9
PH
226
227/* This loop is for handling incomplete writes and other retries. In most
228normal cases, it is only ever executed once. */
059ec3d9
PH
229
230for (i = 0; i < 100; i++)
231 {
232 DEBUG(D_transport)
42055a33
JH
233 debug_printf("writing data block fd=%d size=%d timeout=%d%s\n",
234 fd, len, local_timeout, more ? " (more expected)" : "");
059ec3d9 235
958541e9
PH
236 /* This code makes use of alarm() in order to implement the timeout. This
237 isn't a very tidy way of doing things. Using non-blocking I/O with select()
238 provides a neater approach. However, I don't know how to do this when TLS is
239 in use. */
059ec3d9 240
958541e9
PH
241 if (transport_write_timeout <= 0) /* No timeout wanted */
242 {
42055a33
JH
243 rc =
244#ifdef SUPPORT_TLS
925ac8e4 245 tls_out.active == fd ? tls_write(FALSE, block, len, more) :
42055a33
JH
246#endif
247#ifdef MSG_MORE
248 more ? send(fd, block, len, MSG_MORE) :
249#endif
250 write(fd, block, len);
958541e9
PH
251 save_errno = errno;
252 }
059ec3d9 253
958541e9 254 /* Timeout wanted. */
059ec3d9 255
958541e9 256 else
059ec3d9 257 {
958541e9 258 alarm(local_timeout);
42055a33
JH
259
260 rc =
59932f7d 261#ifdef SUPPORT_TLS
925ac8e4 262 tls_out.active == fd ? tls_write(FALSE, block, len, more) :
42055a33
JH
263#endif
264#ifdef MSG_MORE
265 more ? send(fd, block, len, MSG_MORE) :
59932f7d 266#endif
42055a33
JH
267 write(fd, block, len);
268
958541e9
PH
269 save_errno = errno;
270 local_timeout = alarm(0);
059ec3d9
PH
271 if (sigalrm_seen)
272 {
273 errno = ETIMEDOUT;
274 return FALSE;
275 }
276 }
277
278 /* Hopefully, the most common case is success, so test that first. */
279
280 if (rc == len) { transport_count += len; return TRUE; }
281
958541e9
PH
282 /* A non-negative return code is an incomplete write. Try again for the rest
283 of the block. If we have exactly hit the timeout, give up. */
059ec3d9
PH
284
285 if (rc >= 0)
286 {
287 len -= rc;
288 block += rc;
289 transport_count += rc;
290 DEBUG(D_transport) debug_printf("write incomplete (%d)\n", rc);
958541e9 291 goto CHECK_TIMEOUT; /* A few lines below */
059ec3d9
PH
292 }
293
294 /* A negative return code with an EINTR error is another form of
295 incomplete write, zero bytes having been written */
296
297 if (save_errno == EINTR)
298 {
299 DEBUG(D_transport)
300 debug_printf("write interrupted before anything written\n");
958541e9 301 goto CHECK_TIMEOUT; /* A few lines below */
059ec3d9
PH
302 }
303
304 /* A response of EAGAIN from write() is likely only in the case of writing
305 to a FIFO that is not swallowing the data as fast as Exim is writing it. */
306
307 if (save_errno == EAGAIN)
308 {
309 DEBUG(D_transport)
310 debug_printf("write temporarily locked out, waiting 1 sec\n");
311 sleep(1);
958541e9
PH
312
313 /* Before continuing to try another write, check that we haven't run out of
314 time. */
315
316 CHECK_TIMEOUT:
317 if (transport_write_timeout > 0 && local_timeout <= 0)
318 {
319 errno = ETIMEDOUT;
320 return FALSE;
321 }
059ec3d9
PH
322 continue;
323 }
324
325 /* Otherwise there's been an error */
326
327 DEBUG(D_transport) debug_printf("writing error %d: %s\n", save_errno,
328 strerror(save_errno));
329 errno = save_errno;
330 return FALSE;
331 }
332
333/* We've tried and tried and tried but still failed */
334
335errno = ERRNO_WRITEINCOMPLETE;
336return FALSE;
337}
338
339
42055a33
JH
340BOOL
341transport_write_block(transport_ctx * tctx, uschar *block, int len, BOOL more)
342{
343if (!(tctx->options & topt_output_string))
344 return transport_write_block_fd(tctx, block, len, more);
345
346/* Write to expanding-string. NOTE: not NUL-terminated */
347
348if (!tctx->u.msg)
349 {
350 tctx->u.msg = store_get(tctx->msg_size = 1024);
351 tctx->msg_ptr = 0;
352 }
353
354tctx->u.msg = string_catn(tctx->u.msg, &tctx->msg_size, &tctx->msg_ptr, block, len);
355return TRUE;
356}
357
358
059ec3d9
PH
359
360
361/*************************************************
362* Write formatted string *
363*************************************************/
364
365/* This is called by various transports. It is a convenience function.
366
367Arguments:
368 fd file descriptor
369 format string format
370 ... arguments for format
371
372Returns: the yield of transport_write_block()
373*/
374
375BOOL
1ba28e2b 376transport_write_string(int fd, const char *format, ...)
059ec3d9 377{
cab0c277 378transport_ctx tctx = {{0}};
059ec3d9
PH
379va_list ap;
380va_start(ap, format);
381if (!string_vformat(big_buffer, big_buffer_size, format, ap))
382 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "overlong formatted string in transport");
383va_end(ap);
42055a33
JH
384tctx.u.fd = fd;
385return transport_write_block(&tctx, big_buffer, Ustrlen(big_buffer), FALSE);
059ec3d9
PH
386}
387
388
389
390
42055a33
JH
391void
392transport_write_reset(int options)
393{
394if (!(options & topt_continuation)) chunk_ptr = deliver_out_buffer;
395nl_partial_match = -1;
396nl_check_length = nl_escape_length = 0;
397}
398
399
400
059ec3d9
PH
401/*************************************************
402* Write character chunk *
403*************************************************/
404
405/* Subroutine used by transport_write_message() to scan character chunks for
406newlines and act appropriately. The object is to minimise the number of writes.
407The output byte stream is buffered up in deliver_out_buffer, which is written
408only when it gets full, thus minimizing write operations and TCP packets.
409
410Static data is used to handle the case when the last character of the previous
411chunk was NL, or matched part of the data that has to be escaped.
412
413Arguments:
42055a33
JH
414 tctx transport context - processing to be done during output,
415 and file descriptor to write to
059ec3d9
PH
416 chunk pointer to data to write
417 len length of data to write
059ec3d9
PH
418
419In addition, the static nl_xxx variables must be set as required.
420
421Returns: TRUE on success, FALSE on failure (with errno preserved)
422*/
423
42055a33
JH
424BOOL
425write_chunk(transport_ctx * tctx, uschar *chunk, int len)
059ec3d9
PH
426{
427uschar *start = chunk;
428uschar *end = chunk + len;
ff5aac2b 429uschar *ptr;
059ec3d9
PH
430int mlen = DELIVER_OUT_BUFFER_SIZE - nl_escape_length - 2;
431
432/* The assumption is made that the check string will never stretch over move
433than one chunk since the only time there are partial matches is when copying
434the body in large buffers. There is always enough room in the buffer for an
435escape string, since the loop below ensures this for each character it
436processes, and it won't have stuck in the escape string if it left a partial
437match. */
438
439if (nl_partial_match >= 0)
440 {
441 if (nl_check_length > 0 && len >= nl_check_length &&
442 Ustrncmp(start, nl_check + nl_partial_match,
443 nl_check_length - nl_partial_match) == 0)
444 {
445 Ustrncpy(chunk_ptr, nl_escape, nl_escape_length);
446 chunk_ptr += nl_escape_length;
447 start += nl_check_length - nl_partial_match;
448 }
449
450 /* The partial match was a false one. Insert the characters carried over
451 from the previous chunk. */
452
453 else if (nl_partial_match > 0)
454 {
455 Ustrncpy(chunk_ptr, nl_check, nl_partial_match);
456 chunk_ptr += nl_partial_match;
457 }
458
459 nl_partial_match = -1;
460 }
461
462/* Now process the characters in the chunk. Whenever we hit a newline we check
463for possible escaping. The code for the non-NL route should be as fast as
464possible. */
465
466for (ptr = start; ptr < end; ptr++)
467 {
6d5c916c 468 int ch, len;
059ec3d9
PH
469
470 /* Flush the buffer if it has reached the threshold - we want to leave enough
471 room for the next uschar, plus a possible extra CR for an LF, plus the escape
472 string. */
473
6d5c916c 474 if ((len = chunk_ptr - deliver_out_buffer) > mlen)
059ec3d9 475 {
58fc5fb2
JH
476 DEBUG(D_transport) debug_printf("flushing headers buffer\n");
477
6d5c916c
JH
478 /* If CHUNKING, prefix with BDAT (size) NON-LAST. Also, reap responses
479 from previous SMTP commands. */
480
d315eda1 481 if (tctx->options & topt_use_bdat && tctx->chunk_cb)
58fc5fb2 482 {
d2aa036b 483 if ( tctx->chunk_cb(tctx, (unsigned)len, 0) != OK
42055a33 484 || !transport_write_block(tctx, deliver_out_buffer, len, FALSE)
d2aa036b 485 || tctx->chunk_cb(tctx, 0, tc_reap_prev) != OK
58fc5fb2
JH
486 )
487 return FALSE;
488 }
489 else
42055a33 490 if (!transport_write_block(tctx, deliver_out_buffer, len, FALSE))
6d5c916c 491 return FALSE;
059ec3d9
PH
492 chunk_ptr = deliver_out_buffer;
493 }
494
328c5688
JH
495 /* Remove CR before NL if required */
496
497 if ( *ptr == '\r' && ptr[1] == '\n'
d315eda1 498 && !(tctx->options & topt_use_crlf)
328c5688
JH
499 && spool_file_wireformat
500 )
501 ptr++;
502
059ec3d9
PH
503 if ((ch = *ptr) == '\n')
504 {
505 int left = end - ptr - 1; /* count of chars left after NL */
506
507 /* Insert CR before NL if required */
508
d315eda1 509 if (tctx->options & topt_use_crlf && !spool_file_wireformat)
328c5688 510 *chunk_ptr++ = '\r';
059ec3d9 511 *chunk_ptr++ = '\n';
332f5cf3 512 transport_newlines++;
059ec3d9
PH
513
514 /* The check_string test (formerly "from hack") replaces the specific
515 string at the start of a line with an escape string (e.g. "From " becomes
516 ">From " or "." becomes "..". It is a case-sensitive test. The length
517 check above ensures there is always enough room to insert this string. */
518
519 if (nl_check_length > 0)
520 {
521 if (left >= nl_check_length &&
522 Ustrncmp(ptr+1, nl_check, nl_check_length) == 0)
523 {
524 Ustrncpy(chunk_ptr, nl_escape, nl_escape_length);
525 chunk_ptr += nl_escape_length;
526 ptr += nl_check_length;
527 }
528
529 /* Handle the case when there isn't enough left to match the whole
530 check string, but there may be a partial match. We remember how many
531 characters matched, and finish processing this chunk. */
532
533 else if (left <= 0) nl_partial_match = 0;
534
535 else if (Ustrncmp(ptr+1, nl_check, left) == 0)
536 {
537 nl_partial_match = left;
538 ptr = end;
539 }
540 }
541 }
542
543 /* Not a NL character */
544
545 else *chunk_ptr++ = ch;
546 }
547
548return TRUE;
549}
550
551
552
553
554/*************************************************
555* Generate address for RCPT TO *
556*************************************************/
557
558/* This function puts together an address for RCPT to, using the caseful
559version of the local part and the caseful version of the domain. If there is no
560prefix or suffix, or if affixes are to be retained, we can just use the
561original address. Otherwise, if there is a prefix but no suffix we can use a
562pointer into the original address. If there is a suffix, however, we have to
563build a new string.
564
565Arguments:
566 addr the address item
567 include_affixes TRUE if affixes are to be included
568
569Returns: a string
570*/
571
572uschar *
573transport_rcpt_address(address_item *addr, BOOL include_affixes)
574{
575uschar *at;
576int plen, slen;
577
578if (include_affixes)
579 {
580 setflag(addr, af_include_affixes); /* Affects logged => line */
581 return addr->address;
582 }
583
584if (addr->suffix == NULL)
585 {
586 if (addr->prefix == NULL) return addr->address;
587 return addr->address + Ustrlen(addr->prefix);
588 }
589
590at = Ustrrchr(addr->address, '@');
591plen = (addr->prefix == NULL)? 0 : Ustrlen(addr->prefix);
592slen = Ustrlen(addr->suffix);
593
594return string_sprintf("%.*s@%s", (at - addr->address - plen - slen),
595 addr->address + plen, at + 1);
596}
597
598
599/*************************************************
600* Output Envelope-To: address & scan duplicates *
601*************************************************/
602
603/* This function is called from internal_transport_write_message() below, when
604generating an Envelope-To: header line. It checks for duplicates of the given
605address and its ancestors. When one is found, this function calls itself
606recursively, to output the envelope address of the duplicate.
607
608We want to avoid duplication in the list, which can arise for example when
609A->B,C and then both B and C alias to D. This can also happen when there are
610unseen drivers in use. So a list of addresses that have been output is kept in
611the plist variable.
612
613It is also possible to have loops in the address ancestry/duplication graph,
614for example if there are two top level addresses A and B and we have A->B,C and
615B->A. To break the loop, we use a list of processed addresses in the dlist
616variable.
617
618After handling duplication, this function outputs the progenitor of the given
619address.
620
621Arguments:
622 p the address we are interested in
623 pplist address of anchor of the list of addresses not to output
624 pdlist address of anchor of the list of processed addresses
625 first TRUE if this is the first address; set it FALSE afterwards
6d5c916c 626 tctx transport context - processing to be done during output
42055a33 627 and the file descriptor to write to
059ec3d9
PH
628
629Returns: FALSE if writing failed
630*/
631
632static BOOL
633write_env_to(address_item *p, struct aci **pplist, struct aci **pdlist,
42055a33 634 BOOL *first, transport_ctx * tctx)
059ec3d9
PH
635{
636address_item *pp;
637struct aci *ppp;
638
639/* Do nothing if we have already handled this address. If not, remember it
640so that we don't handle it again. */
641
ff5aac2b 642for (ppp = *pdlist; ppp; ppp = ppp->next) if (p == ppp->ptr) return TRUE;
059ec3d9
PH
643
644ppp = store_get(sizeof(struct aci));
645ppp->next = *pdlist;
646*pdlist = ppp;
647ppp->ptr = p;
648
649/* Now scan up the ancestry, checking for duplicates at each generation. */
650
651for (pp = p;; pp = pp->parent)
652 {
653 address_item *dup;
ff5aac2b
JH
654 for (dup = addr_duplicate; dup; dup = dup->next)
655 if (dup->dupof == pp) /* a dup of our address */
42055a33 656 if (!write_env_to(dup, pplist, pdlist, first, tctx))
ff5aac2b
JH
657 return FALSE;
658 if (!pp->parent) break;
059ec3d9
PH
659 }
660
661/* Check to see if we have already output the progenitor. */
662
ff5aac2b
JH
663for (ppp = *pplist; ppp; ppp = ppp->next) if (pp == ppp->ptr) break;
664if (ppp) return TRUE;
059ec3d9
PH
665
666/* Remember what we have output, and output it. */
667
668ppp = store_get(sizeof(struct aci));
669ppp->next = *pplist;
670*pplist = ppp;
671ppp->ptr = pp;
672
42055a33 673if (!*first && !write_chunk(tctx, US",\n ", 3)) return FALSE;
059ec3d9 674*first = FALSE;
42055a33 675return write_chunk(tctx, pp->address, Ustrlen(pp->address));
059ec3d9
PH
676}
677
678
679
680
4c04137d 681/* Add/remove/rewrite headers, and send them plus the empty-line separator.
511a6c14
JH
682
683Globals:
684 header_list
685
686Arguments:
687 addr (chain of) addresses (for extra headers), or NULL;
688 only the first address is used
44bc8f0c 689 tctx transport context
59932f7d 690 sendfn function for output (transport or verify)
511a6c14
JH
691
692Returns: TRUE on success; FALSE on failure.
693*/
694BOOL
42055a33
JH
695transport_headers_send(transport_ctx * tctx,
696 BOOL (*sendfn)(transport_ctx * tctx, uschar * s, int len))
511a6c14
JH
697{
698header_line *h;
6b46ecc6 699const uschar *list;
6d5c916c
JH
700transport_instance * tblock = tctx ? tctx->tblock : NULL;
701address_item * addr = tctx ? tctx->addr : NULL;
511a6c14
JH
702
703/* Then the message's headers. Don't write any that are flagged as "old";
704that means they were rewritten, or are a record of envelope rewriting, or
705were removed (e.g. Bcc). If remove_headers is not null, skip any headers that
76146973
JH
706match any entries therein. It is a colon-sep list; expand the items
707separately and squash any empty ones.
d43cbe25 708Then check addr->prop.remove_headers too, provided that addr is not NULL. */
511a6c14 709
ff5aac2b 710for (h = header_list; h; h = h->next) if (h->type != htype_old)
511a6c14
JH
711 {
712 int i;
511a6c14
JH
713 BOOL include_header = TRUE;
714
fb6833e0 715 list = tblock ? tblock->remove_headers : NULL;
d43cbe25 716 for (i = 0; i < 2; i++) /* For remove_headers && addr->prop.remove_headers */
511a6c14
JH
717 {
718 if (list)
719 {
720 int sep = ':'; /* This is specified as a colon-separated list */
721 uschar *s, *ss;
8bc732e8 722 while ((s = string_nextinlist(&list, &sep, NULL, 0)))
511a6c14 723 {
76146973
JH
724 int len;
725
726 if (i == 0)
727 if (!(s = expand_string(s)) && !expand_string_forcedfail)
728 {
729 errno = ERRNO_CHHEADER_FAIL;
730 return FALSE;
731 }
d4ff61d1 732 len = s ? Ustrlen(s) : 0;
511a6c14
JH
733 if (strncmpic(h->text, s, len) != 0) continue;
734 ss = h->text + len;
735 while (*ss == ' ' || *ss == '\t') ss++;
736 if (*ss == ':') break;
737 }
6b46ecc6 738 if (s) { include_header = FALSE; break; }
511a6c14 739 }
6b46ecc6 740 if (addr) list = addr->prop.remove_headers;
511a6c14
JH
741 }
742
743 /* If this header is to be output, try to rewrite it if there are rewriting
744 rules. */
745
746 if (include_header)
747 {
fb6833e0 748 if (tblock && tblock->rewrite_rules)
511a6c14
JH
749 {
750 void *reset_point = store_get(0);
751 header_line *hh;
752
6b46ecc6
JH
753 if ((hh = rewrite_header(h, NULL, NULL, tblock->rewrite_rules,
754 tblock->rewrite_existflags, FALSE)))
511a6c14 755 {
42055a33 756 if (!sendfn(tctx, hh->text, hh->slen)) return FALSE;
511a6c14
JH
757 store_reset(reset_point);
758 continue; /* With the next header line */
759 }
760 }
761
762 /* Either no rewriting rules, or it didn't get rewritten */
763
42055a33 764 if (!sendfn(tctx, h->text, h->slen)) return FALSE;
511a6c14
JH
765 }
766
767 /* Header removed */
768
769 else
511a6c14 770 DEBUG(D_transport) debug_printf("removed header line:\n%s---\n", h->text);
511a6c14
JH
771 }
772
773/* Add on any address-specific headers. If there are multiple addresses,
774they will all have the same headers in order to be batched. The headers
775are chained in reverse order of adding (so several addresses from the
776same alias might share some of them) but we want to output them in the
777opposite order. This is a bit tedious, but there shouldn't be very many
778of them. We just walk the list twice, reversing the pointers each time,
779but on the second time, write out the items.
780
781Headers added to an address by a router are guaranteed to end with a newline.
782*/
783
784if (addr)
785 {
786 int i;
d43cbe25 787 header_line *hprev = addr->prop.extra_headers;
511a6c14
JH
788 header_line *hnext;
789 for (i = 0; i < 2; i++)
ff5aac2b 790 for (h = hprev, hprev = NULL; h; h = hnext)
511a6c14
JH
791 {
792 hnext = h->next;
793 h->next = hprev;
794 hprev = h;
795 if (i == 1)
796 {
42055a33 797 if (!sendfn(tctx, h->text, h->slen)) return FALSE;
511a6c14
JH
798 DEBUG(D_transport)
799 debug_printf("added header line(s):\n%s---\n", h->text);
800 }
801 }
511a6c14
JH
802 }
803
76146973
JH
804/* If a string containing additional headers exists it is a newline-sep
805list. Expand each item and write out the result. This is done last so that
806if it (deliberately or accidentally) isn't in header format, it won't mess
807up any other headers. An empty string or a forced expansion failure are
808noops. An added header string from a transport may not end with a newline;
809add one if it does not. */
511a6c14 810
fb6833e0 811if (tblock && (list = CUS tblock->add_headers))
511a6c14 812 {
76146973
JH
813 int sep = '\n';
814 uschar * s;
815
6b46ecc6 816 while ((s = string_nextinlist(&list, &sep, NULL, 0)))
ff5aac2b 817 if ((s = expand_string(s)))
76146973
JH
818 {
819 int len = Ustrlen(s);
820 if (len > 0)
511a6c14 821 {
42055a33
JH
822 if (!sendfn(tctx, s, len)) return FALSE;
823 if (s[len-1] != '\n' && !sendfn(tctx, US"\n", 1))
76146973
JH
824 return FALSE;
825 DEBUG(D_transport)
826 {
827 debug_printf("added header line:\n%s", s);
828 if (s[len-1] != '\n') debug_printf("\n");
829 debug_printf("---\n");
830 }
511a6c14
JH
831 }
832 }
ff5aac2b
JH
833 else if (!expand_string_forcedfail)
834 { errno = ERRNO_CHHEADER_FAIL; return FALSE; }
511a6c14
JH
835 }
836
837/* Separate headers from body with a blank line */
838
42055a33 839return sendfn(tctx, US"\n", 1);
511a6c14
JH
840}
841
842
059ec3d9
PH
843/*************************************************
844* Write the message *
845*************************************************/
846
847/* This function writes the message to the given file descriptor. The headers
848are in the in-store data structure, and the rest of the message is in the open
849file descriptor deliver_datafile. Make sure we start it at the beginning.
850
851. If add_return_path is TRUE, a "return-path:" header is added to the message,
852 containing the envelope sender's address.
853
854. If add_envelope_to is TRUE, a "envelope-to:" header is added to the message,
855 giving the top-level envelope address that caused this delivery to happen.
856
857. If add_delivery_date is TRUE, a "delivery-date:" header is added to the
858 message. It gives the time and date that delivery took place.
859
860. If check_string is not null, the start of each line is checked for that
861 string. If it is found, it is replaced by escape_string. This used to be
862 the "from hack" for files, and "smtp_dots" for escaping SMTP dots.
863
864. If use_crlf is true, newlines are turned into CRLF (SMTP output).
865
866The yield is TRUE if all went well, and FALSE if not. Exit *immediately* after
867any writing or reading error, leaving the code in errno intact. Error exits
868can include timeouts for certain transports, which are requested by setting
869transport_write_timeout non-zero.
870
871Arguments:
6b46ecc6 872 tctx
42055a33
JH
873 (fd, msg) Either and fd, to write the message to,
874 or a string: if null write message to allocated space
875 otherwire take content as headers.
6b46ecc6
JH
876 addr (chain of) addresses (for extra headers), or NULL;
877 only the first address is used
878 tblock optional transport instance block (NULL signifies NULL/0):
879 add_headers a string containing one or more headers to add; it is
880 expanded, and must be in correct RFC 822 format as
881 it is transmitted verbatim; NULL => no additions,
882 and so does empty string or forced expansion fail
883 remove_headers a colon-separated list of headers to remove, or NULL
884 rewrite_rules chain of header rewriting rules
885 rewrite_existflags flags for the rewriting rules
886 options bit-wise options:
887 add_return_path if TRUE, add a "return-path" header
888 add_envelope_to if TRUE, add a "envelope-to" header
889 add_delivery_date if TRUE, add a "delivery-date" header
890 use_crlf if TRUE, turn NL into CR LF
891 end_dot if TRUE, send a terminating "." line at the end
892 no_headers if TRUE, omit the headers
893 no_body if TRUE, omit the body
2d14f397
JH
894 check_string a string to check for at the start of lines, or NULL
895 escape_string a string to insert in front of any check string
896 size_limit if > 0, this is a limit to the size of message written;
6b46ecc6
JH
897 it is used when returning messages to their senders,
898 and is approximate rather than exact, owing to chunk
899 buffering
059ec3d9
PH
900
901Returns: TRUE on success; FALSE (with errno) on failure.
902 In addition, the global variable transport_count
903 is incremented by the number of bytes written.
904*/
905
d315eda1 906static BOOL
42055a33 907internal_transport_write_message(transport_ctx * tctx, int size_limit)
059ec3d9 908{
328c5688 909int len, size = 0;
059ec3d9
PH
910
911/* Initialize pointer in output buffer. */
912
42055a33 913transport_write_reset(tctx->options);
059ec3d9
PH
914
915/* Set up the data for start-of-line data checking and escaping */
916
6b46ecc6 917if (tctx->check_string && tctx->escape_string)
059ec3d9 918 {
6b46ecc6 919 nl_check = tctx->check_string;
059ec3d9 920 nl_check_length = Ustrlen(nl_check);
6b46ecc6 921 nl_escape = tctx->escape_string;
059ec3d9
PH
922 nl_escape_length = Ustrlen(nl_escape);
923 }
059ec3d9 924
328c5688
JH
925/* Whether the escaping mechanism is applied to headers or not is controlled by
926an option (set for SMTP, not otherwise). Negate the length if not wanted till
927after the headers. */
928
929if (!(tctx->options & topt_escape_headers))
930 nl_check_length = -nl_check_length;
931
059ec3d9 932/* Write the headers if required, including any that have to be added. If there
328c5688
JH
933are header rewriting rules, apply them. The datasource is not the -D spoolfile
934so temporarily hide the global that adjusts for its format. */
059ec3d9 935
6b46ecc6 936if (!(tctx->options & topt_no_headers))
059ec3d9 937 {
328c5688
JH
938 BOOL save_wireformat = spool_file_wireformat;
939 spool_file_wireformat = FALSE;
42055a33 940
059ec3d9
PH
941 /* Add return-path: if requested. */
942
6b46ecc6 943 if (tctx->options & topt_add_return_path)
059ec3d9
PH
944 {
945 uschar buffer[ADDRESS_MAXLENGTH + 20];
ff5aac2b 946 int n = sprintf(CS buffer, "Return-path: <%.*s>\n", ADDRESS_MAXLENGTH,
059ec3d9 947 return_path);
328c5688 948 if (!write_chunk(tctx, buffer, n)) goto bad;
059ec3d9
PH
949 }
950
951 /* Add envelope-to: if requested */
952
6b46ecc6 953 if (tctx->options & topt_add_envelope_to)
059ec3d9
PH
954 {
955 BOOL first = TRUE;
956 address_item *p;
957 struct aci *plist = NULL;
958 struct aci *dlist = NULL;
959 void *reset_point = store_get(0);
960
328c5688 961 if (!write_chunk(tctx, US"Envelope-to: ", 13)) goto bad;
059ec3d9
PH
962
963 /* Pick up from all the addresses. The plist and dlist variables are
964 anchors for lists of addresses already handled; they have to be defined at
4c04137d 965 this level because write_env_to() calls itself recursively. */
059ec3d9 966
6b46ecc6 967 for (p = tctx->addr; p; p = p->next)
328c5688 968 if (!write_env_to(p, &plist, &dlist, &first, tctx)) goto bad;
059ec3d9
PH
969
970 /* Add a final newline and reset the store used for tracking duplicates */
971
328c5688 972 if (!write_chunk(tctx, US"\n", 1)) goto bad;
059ec3d9
PH
973 store_reset(reset_point);
974 }
975
976 /* Add delivery-date: if requested. */
977
6b46ecc6 978 if (tctx->options & topt_add_delivery_date)
059ec3d9 979 {
a5ffa9b4
JH
980 uschar * s = tod_stamp(tod_full);
981
982 if ( !write_chunk(tctx, US"Delivery-date: ", 15)
983 || !write_chunk(tctx, s, Ustrlen(s))
984 || !write_chunk(tctx, US"\n", 1)) goto bad;
059ec3d9
PH
985 }
986
987 /* Then the message's headers. Don't write any that are flagged as "old";
988 that means they were rewritten, or are a record of envelope rewriting, or
989 were removed (e.g. Bcc). If remove_headers is not null, skip any headers that
d43cbe25 990 match any entries therein. Then check addr->prop.remove_headers too, provided that
059ec3d9 991 addr is not NULL. */
6b46ecc6 992
42055a33 993 if (!transport_headers_send(tctx, &write_chunk))
328c5688
JH
994 {
995bad:
996 spool_file_wireformat = save_wireformat;
511a6c14 997 return FALSE;
328c5688
JH
998 }
999
1000 spool_file_wireformat = save_wireformat;
059ec3d9
PH
1001 }
1002
58fc5fb2
JH
1003/* When doing RFC3030 CHUNKING output, work out how much data would be in a
1004last-BDAT, consisting of the current write_chunk() output buffer fill
59932f7d
JH
1005(optimally, all of the headers - but it does not matter if we already had to
1006flush that buffer with non-last BDAT prependix) plus the amount of body data
58fc5fb2 1007(as expanded for CRLF lines). Then create and write BDAT(s), and ensure
e027f545
JH
1008that further use of write_chunk() will not prepend BDATs.
1009The first BDAT written will also first flush any outstanding MAIL and RCPT
1010commands which were buffered thans to PIPELINING.
1011Commands go out (using a send()) from a different buffer to data (using a
1012write()). They might not end up in the same TCP segment, which is
1013suboptimal. */
59932f7d 1014
65de12cc 1015if (tctx->options & topt_use_bdat)
59932f7d 1016 {
e027f545 1017 off_t fsize;
328c5688 1018 int hsize;
e027f545
JH
1019
1020 if ((hsize = chunk_ptr - deliver_out_buffer) < 0)
1021 hsize = 0;
65de12cc 1022 if (!(tctx->options & topt_no_body))
59932f7d
JH
1023 {
1024 if ((fsize = lseek(deliver_datafile, 0, SEEK_END)) < 0) return FALSE;
1025 fsize -= SPOOL_DATA_START_OFFSET;
1026 if (size_limit > 0 && fsize > size_limit)
1027 fsize = size_limit;
e027f545 1028 size = hsize + fsize;
328c5688 1029 if (tctx->options & topt_use_crlf && !spool_file_wireformat)
59932f7d 1030 size += body_linecount; /* account for CRLF-expansion */
42055a33
JH
1031
1032 /* With topt_use_bdat we never do dot-stuffing; no need to
1033 account for any expansion due to that. */
59932f7d
JH
1034 }
1035
e027f545
JH
1036 /* If the message is large, emit first a non-LAST chunk with just the
1037 headers, and reap the command responses. This lets us error out early
1038 on RCPT rejects rather than sending megabytes of data. Include headers
1039 on the assumption they are cheap enough and some clever implementations
1040 might errorcheck them too, on-the-fly, and reject that chunk. */
1041
1042 if (size > DELIVER_OUT_BUFFER_SIZE && hsize > 0)
1043 {
58fc5fb2 1044 DEBUG(D_transport)
4c04137d 1045 debug_printf("sending small initial BDAT; hsize=%d\n", hsize);
d2aa036b 1046 if ( tctx->chunk_cb(tctx, hsize, 0) != OK
42055a33 1047 || !transport_write_block(tctx, deliver_out_buffer, hsize, FALSE)
d2aa036b 1048 || tctx->chunk_cb(tctx, 0, tc_reap_prev) != OK
e027f545
JH
1049 )
1050 return FALSE;
1051 chunk_ptr = deliver_out_buffer;
1052 size -= hsize;
1053 }
1054
d2aa036b
JH
1055 /* Emit a LAST datachunk command, and unmark the context for further
1056 BDAT commands. */
59932f7d 1057
d2aa036b 1058 if (tctx->chunk_cb(tctx, size, tc_chunk_last) != OK)
511a6c14 1059 return FALSE;
6d5c916c 1060 tctx->options &= ~topt_use_bdat;
059ec3d9
PH
1061 }
1062
1063/* If the body is required, ensure that the data for check strings (formerly
1064the "from hack") is enabled by negating the length if necessary. (It will be
1065negative in cases where it isn't to apply to the headers). Then ensure the body
1066is positioned at the start of its file (following the message id), then write
1067it, applying the size limit if required. */
1068
328c5688
JH
1069/* If we have a wireformat -D file (CRNL lines, non-dotstuffed, no ending dot)
1070and we want to send a body without dotstuffing or ending-dot, in-clear,
1071then we can just dump it using sendfile.
1072This should get used for CHUNKING output and also for writing the -K file for
1073dkim signing, when we had CHUNKING input. */
1074
7d758a6a 1075#ifdef OS_SENDFILE
328c5688
JH
1076if ( spool_file_wireformat
1077 && !(tctx->options & (topt_no_body | topt_end_dot))
1078 && !nl_check_length
1079 && tls_out.active != tctx->u.fd
1080 )
1081 {
1082 ssize_t copied = 0;
1083 off_t offset = SPOOL_DATA_START_OFFSET;
1084
1085 /* Write out any header data in the buffer */
1086
1087 if ((len = chunk_ptr - deliver_out_buffer) > 0)
1088 {
1089 if (!transport_write_block(tctx, deliver_out_buffer, len, TRUE))
1090 return FALSE;
1091 size -= len;
1092 }
1093
1094 DEBUG(D_transport) debug_printf("using sendfile for body\n");
1095
1096 while(size > 0)
1097 {
7d758a6a 1098 if ((copied = os_sendfile(tctx->u.fd, deliver_datafile, &offset, size)) <= 0) break;
328c5688
JH
1099 size -= copied;
1100 }
1101 return copied >= 0;
1102 }
1103#else
1104DEBUG(D_transport) debug_printf("cannot use sendfile for body: no support\n");
1105#endif
1106
1107DEBUG(D_transport)
1108 if (!(tctx->options & topt_no_body))
1109 debug_printf("cannot use sendfile for body: %s\n",
1110 !spool_file_wireformat ? "spoolfile not wireformat"
1111 : tctx->options & topt_end_dot ? "terminating dot wanted"
1112 : nl_check_length ? "dot- or From-stuffing wanted"
1113 : "TLS output wanted");
1114
6b46ecc6 1115if (!(tctx->options & topt_no_body))
059ec3d9 1116 {
e027f545
JH
1117 int size = size_limit;
1118
059ec3d9
PH
1119 nl_check_length = abs(nl_check_length);
1120 nl_partial_match = 0;
d4ff61d1
JH
1121 if (lseek(deliver_datafile, SPOOL_DATA_START_OFFSET, SEEK_SET) < 0)
1122 return FALSE;
59932f7d
JH
1123 while ( (len = MAX(DELIVER_IN_BUFFER_SIZE, size)) > 0
1124 && (len = read(deliver_datafile, deliver_in_buffer, len)) > 0)
059ec3d9 1125 {
42055a33 1126 if (!write_chunk(tctx, deliver_in_buffer, len))
59932f7d 1127 return FALSE;
e027f545 1128 size -= len;
059ec3d9
PH
1129 }
1130
059ec3d9
PH
1131 /* A read error on the body will have left len == -1 and errno set. */
1132
1133 if (len != 0) return FALSE;
c0940526 1134 }
059ec3d9 1135
c0940526 1136/* Finished with the check string */
059ec3d9 1137
c0940526
PP
1138nl_check_length = nl_escape_length = 0;
1139
1140/* If requested, add a terminating "." line (SMTP output). */
1141
42055a33 1142if (tctx->options & topt_end_dot && !write_chunk(tctx, US".\n", 2))
c0940526 1143 return FALSE;
059ec3d9
PH
1144
1145/* Write out any remaining data in the buffer before returning. */
1146
1147return (len = chunk_ptr - deliver_out_buffer) <= 0 ||
42055a33 1148 transport_write_block(tctx, deliver_out_buffer, len, FALSE);
f7572e5a 1149}
80a47a2c 1150
f7572e5a
TK
1151
1152
328c5688 1153
059ec3d9
PH
1154/*************************************************
1155* External interface to write the message *
1156*************************************************/
1157
1158/* If there is no filtering required, call the internal function above to do
1159the real work, passing over all the arguments from this function. Otherwise,
1160set up a filtering process, fork another process to call the internal function
1161to write to the filter, and in this process just suck from the filter and write
42055a33
JH
1162down the fd in the transport context. At the end, tidy up the pipes and the
1163processes.
059ec3d9
PH
1164
1165Arguments: as for internal_transport_write_message() above
1166
1167Returns: TRUE on success; FALSE (with errno) for any failure
1168 transport_count is incremented by the number of bytes written
1169*/
1170
1171BOOL
42055a33 1172transport_write_message(transport_ctx * tctx, int size_limit)
059ec3d9 1173{
059ec3d9 1174BOOL last_filter_was_NL = TRUE;
328c5688 1175BOOL save_spool_file_wireformat = spool_file_wireformat;
059ec3d9 1176int rc, len, yield, fd_read, fd_write, save_errno;
806c3df9 1177int pfd[2] = {-1, -1};
059ec3d9 1178pid_t filter_pid, write_pid;
6b46ecc6 1179
2e2a30b4
PH
1180transport_filter_timed_out = FALSE;
1181
059ec3d9
PH
1182/* If there is no filter command set up, call the internal function that does
1183the actual work, passing it the incoming fd, and return its result. */
1184
6ff55e50
JH
1185if ( !transport_filter_argv
1186 || !*transport_filter_argv
1187 || !**transport_filter_argv
1188 )
42055a33 1189 return internal_transport_write_message(tctx, size_limit);
059ec3d9
PH
1190
1191/* Otherwise the message must be written to a filter process and read back
1192before being written to the incoming fd. First set up the special processing to
1193be done during the copying. */
1194
059ec3d9
PH
1195nl_partial_match = -1;
1196
6b46ecc6 1197if (tctx->check_string && tctx->escape_string)
059ec3d9 1198 {
6b46ecc6 1199 nl_check = tctx->check_string;
059ec3d9 1200 nl_check_length = Ustrlen(nl_check);
6b46ecc6 1201 nl_escape = tctx->escape_string;
059ec3d9
PH
1202 nl_escape_length = Ustrlen(nl_escape);
1203 }
1204else nl_check_length = nl_escape_length = 0;
1205
1206/* Start up a subprocess to run the command. Ensure that our main fd will
1207be closed when the subprocess execs, but remove the flag afterwards.
1208(Otherwise, if this is a TCP/IP socket, it can't get passed on to another
1209process to deliver another message.) We get back stdin/stdout file descriptors.
1210If the process creation failed, give an error return. */
1211
1212fd_read = -1;
1213fd_write = -1;
1214save_errno = 0;
1215yield = FALSE;
1216write_pid = (pid_t)(-1);
1217
92b0827a 1218 {
42055a33
JH
1219 int bits = fcntl(tctx->u.fd, F_GETFD);
1220 (void)fcntl(tctx->u.fd, F_SETFD, bits | FD_CLOEXEC);
92b0827a
JH
1221 filter_pid = child_open(USS transport_filter_argv, NULL, 077,
1222 &fd_write, &fd_read, FALSE);
42055a33 1223 (void)fcntl(tctx->u.fd, F_SETFD, bits & ~FD_CLOEXEC);
92b0827a 1224 }
059ec3d9
PH
1225if (filter_pid < 0) goto TIDY_UP; /* errno set */
1226
1227DEBUG(D_transport)
fb6833e0 1228 debug_printf("process %d running as transport filter: fd_write=%d fd_read=%d\n",
059ec3d9
PH
1229 (int)filter_pid, fd_write, fd_read);
1230
1231/* Fork subprocess to write the message to the filter, and return the result
1232via a(nother) pipe. While writing to the filter, we do not do the CRLF,
1233smtp dots, or check string processing. */
1234
1235if (pipe(pfd) != 0) goto TIDY_UP; /* errno set */
1236if ((write_pid = fork()) == 0)
1237 {
1238 BOOL rc;
f1e894f3
PH
1239 (void)close(fd_read);
1240 (void)close(pfd[pipe_read]);
059ec3d9 1241 nl_check_length = nl_escape_length = 0;
6b46ecc6 1242
42055a33 1243 tctx->u.fd = fd_write;
fb6833e0 1244 tctx->check_string = tctx->escape_string = NULL;
65de12cc 1245 tctx->options &= ~(topt_use_crlf | topt_end_dot | topt_use_bdat);
6b46ecc6 1246
42055a33 1247 rc = internal_transport_write_message(tctx, size_limit);
6b46ecc6 1248
059ec3d9 1249 save_errno = errno;
1ac6b2e7
JH
1250 if ( write(pfd[pipe_write], (void *)&rc, sizeof(BOOL))
1251 != sizeof(BOOL)
1252 || write(pfd[pipe_write], (void *)&save_errno, sizeof(int))
1253 != sizeof(int)
6b46ecc6 1254 || write(pfd[pipe_write], (void *)&tctx->addr->more_errno, sizeof(int))
1ac6b2e7 1255 != sizeof(int)
32dfdf8b
JH
1256 || write(pfd[pipe_write], (void *)&tctx->addr->delivery_usec, sizeof(int))
1257 != sizeof(int)
1ac6b2e7
JH
1258 )
1259 rc = FALSE; /* compiler quietening */
059ec3d9
PH
1260 _exit(0);
1261 }
1262save_errno = errno;
1263
1264/* Parent process: close our copy of the writing subprocess' pipes. */
1265
f1e894f3
PH
1266(void)close(pfd[pipe_write]);
1267(void)close(fd_write);
059ec3d9
PH
1268fd_write = -1;
1269
1270/* Writing process creation failed */
1271
1272if (write_pid < 0)
1273 {
1274 errno = save_errno; /* restore */
1275 goto TIDY_UP;
1276 }
1277
1278/* When testing, let the subprocess get going */
1279
1280if (running_in_test_harness) millisleep(250);
1281
1282DEBUG(D_transport)
1283 debug_printf("process %d writing to transport filter\n", (int)write_pid);
1284
1285/* Copy the message from the filter to the output fd. A read error leaves len
1286== -1 and errno set. We need to apply a timeout to the read, to cope with
1287the case when the filter gets stuck, but it can be quite a long one. The
1288default is 5m, but this is now configurable. */
1289
1290DEBUG(D_transport) debug_printf("copying from the filter\n");
1291
1292/* Copy the output of the filter, remembering if the last character was NL. If
1293no data is returned, that counts as "ended with NL" (default setting of the
328c5688
JH
1294variable is TRUE). The output should always be unix-format as we converted
1295any wireformat source on writing input to the filter. */
059ec3d9 1296
328c5688 1297spool_file_wireformat = FALSE;
059ec3d9
PH
1298chunk_ptr = deliver_out_buffer;
1299
1300for (;;)
1301 {
1302 sigalrm_seen = FALSE;
1303 alarm(transport_filter_timeout);
1304 len = read(fd_read, deliver_in_buffer, DELIVER_IN_BUFFER_SIZE);
1305 alarm(0);
1306 if (sigalrm_seen)
1307 {
1308 errno = ETIMEDOUT;
2e2a30b4 1309 transport_filter_timed_out = TRUE;
059ec3d9
PH
1310 goto TIDY_UP;
1311 }
1312
1313 /* If the read was successful, write the block down the original fd,
1314 remembering whether it ends in \n or not. */
1315
1316 if (len > 0)
1317 {
42055a33 1318 if (!write_chunk(tctx, deliver_in_buffer, len)) goto TIDY_UP;
059ec3d9
PH
1319 last_filter_was_NL = (deliver_in_buffer[len-1] == '\n');
1320 }
1321
1322 /* Otherwise, break the loop. If we have hit EOF, set yield = TRUE. */
1323
1324 else
1325 {
1326 if (len == 0) yield = TRUE;
1327 break;
1328 }
1329 }
1330
1331/* Tidying up code. If yield = FALSE there has been an error and errno is set
1332to something. Ensure the pipes are all closed and the processes are removed. If
1333there has been an error, kill the processes before waiting for them, just to be
1334sure. Also apply a paranoia timeout. */
1335
1336TIDY_UP:
328c5688 1337spool_file_wireformat = save_spool_file_wireformat;
059ec3d9
PH
1338save_errno = errno;
1339
f1e894f3
PH
1340(void)close(fd_read);
1341if (fd_write > 0) (void)close(fd_write);
059ec3d9
PH
1342
1343if (!yield)
1344 {
1345 if (filter_pid > 0) kill(filter_pid, SIGKILL);
1346 if (write_pid > 0) kill(write_pid, SIGKILL);
1347 }
1348
1349/* Wait for the filter process to complete. */
1350
1351DEBUG(D_transport) debug_printf("waiting for filter process\n");
1352if (filter_pid > 0 && (rc = child_close(filter_pid, 30)) != 0 && yield)
1353 {
1354 yield = FALSE;
1355 save_errno = ERRNO_FILTER_FAIL;
6b46ecc6 1356 tctx->addr->more_errno = rc;
059ec3d9
PH
1357 DEBUG(D_transport) debug_printf("filter process returned %d\n", rc);
1358 }
1359
1360/* Wait for the writing process to complete. If it ends successfully,
8e669ac1 1361read the results from its pipe, provided we haven't already had a filter
35af9f61 1362process failure. */
059ec3d9
PH
1363
1364DEBUG(D_transport) debug_printf("waiting for writing process\n");
1365if (write_pid > 0)
1366 {
35af9f61
PH
1367 rc = child_close(write_pid, 30);
1368 if (yield)
8e669ac1 1369 if (rc == 0)
35af9f61
PH
1370 {
1371 BOOL ok;
4dc2379a
JH
1372 if (read(pfd[pipe_read], (void *)&ok, sizeof(BOOL)) != sizeof(BOOL))
1373 {
1374 DEBUG(D_transport)
1375 debug_printf("pipe read from writing process: %s\n", strerror(errno));
1376 save_errno = ERRNO_FILTER_FAIL;
1377 yield = FALSE;
1378 }
1379 else if (!ok)
35af9f61 1380 {
4dc2379a 1381 int dummy = read(pfd[pipe_read], (void *)&save_errno, sizeof(int));
32dfdf8b
JH
1382 dummy = read(pfd[pipe_read], (void *)&tctx->addr->more_errno, sizeof(int));
1383 dummy = read(pfd[pipe_read], (void *)&tctx->addr->delivery_usec, sizeof(int));
cab0c277 1384 dummy = dummy; /* compiler quietening */
35af9f61
PH
1385 yield = FALSE;
1386 }
1387 }
1388 else
059ec3d9 1389 {
059ec3d9 1390 yield = FALSE;
35af9f61 1391 save_errno = ERRNO_FILTER_FAIL;
6b46ecc6 1392 tctx->addr->more_errno = rc;
35af9f61 1393 DEBUG(D_transport) debug_printf("writing process returned %d\n", rc);
059ec3d9 1394 }
059ec3d9 1395 }
f1e894f3 1396(void)close(pfd[pipe_read]);
059ec3d9
PH
1397
1398/* If there have been no problems we can now add the terminating "." if this is
1399SMTP output, turning off escaping beforehand. If the last character from the
1400filter was not NL, insert a NL to make the SMTP protocol work. */
1401
1402if (yield)
1403 {
1404 nl_check_length = nl_escape_length = 0;
6b46ecc6 1405 if ( tctx->options & topt_end_dot
ff5aac2b 1406 && ( last_filter_was_NL
42055a33
JH
1407 ? !write_chunk(tctx, US".\n", 2)
1408 : !write_chunk(tctx, US"\n.\n", 3)
ff5aac2b 1409 ) )
059ec3d9 1410 yield = FALSE;
059ec3d9
PH
1411
1412 /* Write out any remaining data in the buffer. */
1413
1414 else
ff5aac2b 1415 yield = (len = chunk_ptr - deliver_out_buffer) <= 0
42055a33 1416 || transport_write_block(tctx, deliver_out_buffer, len, FALSE);
059ec3d9 1417 }
ff5aac2b
JH
1418else
1419 errno = save_errno; /* From some earlier error */
059ec3d9
PH
1420
1421DEBUG(D_transport)
1422 {
1423 debug_printf("end of filtering transport writing: yield=%d\n", yield);
1424 if (!yield)
6b46ecc6 1425 debug_printf("errno=%d more_errno=%d\n", errno, tctx->addr->more_errno);
059ec3d9
PH
1426 }
1427
1428return yield;
1429}
1430
1431
1432
1433
1434
1435/*************************************************
1436* Update waiting database *
1437*************************************************/
1438
1439/* This is called when an address is deferred by remote transports that are
1440capable of sending more than one message over one connection. A database is
1441maintained for each transport, keeping track of which messages are waiting for
1442which hosts. The transport can then consult this when eventually a successful
1443delivery happens, and if it finds that another message is waiting for the same
1444host, it can fire up a new process to deal with it using the same connection.
1445
1446The database records are keyed by host name. They can get full if there are
1447lots of messages waiting, and so there is a continuation mechanism for them.
1448
1449Each record contains a list of message ids, packed end to end without any
1450zeros. Each one is MESSAGE_ID_LENGTH bytes long. The count field says how many
1451in this record, and the sequence field says if there are any other records for
1452this host. If the sequence field is 0, there are none. If it is 1, then another
1453record with the name <hostname>:0 exists; if it is 2, then two other records
1454with sequence numbers 0 and 1 exist, and so on.
1455
1456Currently, an exhaustive search of all continuation records has to be done to
1457determine whether to add a message id to a given record. This shouldn't be
1458too bad except in extreme cases. I can't figure out a *simple* way of doing
1459better.
1460
1461Old records should eventually get swept up by the exim_tidydb utility.
1462
1463Arguments:
f6c332bd 1464 hostlist list of hosts that this message could be sent to
059ec3d9
PH
1465 tpname name of the transport
1466
1467Returns: nothing
1468*/
1469
1470void
1471transport_update_waiting(host_item *hostlist, uschar *tpname)
1472{
55414b25 1473const uschar *prevname = US"";
059ec3d9
PH
1474host_item *host;
1475open_db dbblock;
1476open_db *dbm_file;
1477
7a0743eb
PH
1478DEBUG(D_transport) debug_printf("updating wait-%s database\n", tpname);
1479
059ec3d9
PH
1480/* Open the database for this transport */
1481
36d295f1
JH
1482if (!(dbm_file = dbfn_open(string_sprintf("wait-%.200s", tpname),
1483 O_RDWR, &dbblock, TRUE)))
1484 return;
059ec3d9
PH
1485
1486/* Scan the list of hosts for which this message is waiting, and ensure
f6c332bd 1487that the message id is in each host record. */
059ec3d9 1488
36d295f1 1489for (host = hostlist; host; host = host->next)
059ec3d9
PH
1490 {
1491 BOOL already = FALSE;
1492 dbdata_wait *host_record;
1493 uschar *s;
1494 int i, host_length;
36d295f1 1495 uschar buffer[256];
059ec3d9 1496
059ec3d9
PH
1497 /* Skip if this is the same host as we just processed; otherwise remember
1498 the name for next time. */
1499
1500 if (Ustrcmp(prevname, host->name) == 0) continue;
1501 prevname = host->name;
1502
1503 /* Look up the host record; if there isn't one, make an empty one. */
1504
36d295f1 1505 if (!(host_record = dbfn_read(dbm_file, host->name)))
059ec3d9
PH
1506 {
1507 host_record = store_get(sizeof(dbdata_wait) + MESSAGE_ID_LENGTH);
1508 host_record->count = host_record->sequence = 0;
1509 }
1510
1511 /* Compute the current length */
1512
1513 host_length = host_record->count * MESSAGE_ID_LENGTH;
1514
1515 /* Search the record to see if the current message is already in it. */
1516
1517 for (s = host_record->text; s < host_record->text + host_length;
1518 s += MESSAGE_ID_LENGTH)
059ec3d9
PH
1519 if (Ustrncmp(s, message_id, MESSAGE_ID_LENGTH) == 0)
1520 { already = TRUE; break; }
059ec3d9
PH
1521
1522 /* If we haven't found this message in the main record, search any
1523 continuation records that exist. */
1524
1525 for (i = host_record->sequence - 1; i >= 0 && !already; i--)
1526 {
1527 dbdata_wait *cont;
1528 sprintf(CS buffer, "%.200s:%d", host->name, i);
36d295f1 1529 if ((cont = dbfn_read(dbm_file, buffer)))
059ec3d9
PH
1530 {
1531 int clen = cont->count * MESSAGE_ID_LENGTH;
1532 for (s = cont->text; s < cont->text + clen; s += MESSAGE_ID_LENGTH)
059ec3d9
PH
1533 if (Ustrncmp(s, message_id, MESSAGE_ID_LENGTH) == 0)
1534 { already = TRUE; break; }
059ec3d9
PH
1535 }
1536 }
1537
1538 /* If this message is already in a record, no need to update. */
1539
7a0743eb
PH
1540 if (already)
1541 {
1542 DEBUG(D_transport) debug_printf("already listed for %s\n", host->name);
1543 continue;
1544 }
059ec3d9
PH
1545
1546
1547 /* If this record is full, write it out with a new name constructed
1548 from the sequence number, increase the sequence number, and empty
1549 the record. */
1550
1551 if (host_record->count >= WAIT_NAME_MAX)
1552 {
1553 sprintf(CS buffer, "%.200s:%d", host->name, host_record->sequence);
1554 dbfn_write(dbm_file, buffer, host_record, sizeof(dbdata_wait) + host_length);
1555 host_record->sequence++;
1556 host_record->count = 0;
1557 host_length = 0;
1558 }
1559
1560 /* If this record is not full, increase the size of the record to
1561 allow for one new message id. */
1562
1563 else
1564 {
1565 dbdata_wait *newr =
1566 store_get(sizeof(dbdata_wait) + host_length + MESSAGE_ID_LENGTH);
1567 memcpy(newr, host_record, sizeof(dbdata_wait) + host_length);
1568 host_record = newr;
1569 }
1570
1571 /* Now add the new name on the end */
1572
1573 memcpy(host_record->text + host_length, message_id, MESSAGE_ID_LENGTH);
1574 host_record->count++;
1575 host_length += MESSAGE_ID_LENGTH;
1576
1577 /* Update the database */
1578
1579 dbfn_write(dbm_file, host->name, host_record, sizeof(dbdata_wait) + host_length);
7a0743eb 1580 DEBUG(D_transport) debug_printf("added to list for %s\n", host->name);
059ec3d9
PH
1581 }
1582
1583/* All now done */
1584
1585dbfn_close(dbm_file);
1586}
1587
1588
1589
1590
1591/*************************************************
1592* Test for waiting messages *
1593*************************************************/
1594
1595/* This function is called by a remote transport which uses the previous
1596function to remember which messages are waiting for which remote hosts. It's
1597called after a successful delivery and its job is to check whether there is
1598another message waiting for the same host. However, it doesn't do this if the
1599current continue sequence is greater than the maximum supplied as an argument,
1600or greater than the global connection_max_messages, which, if set, overrides.
1601
1602Arguments:
1603 transport_name name of the transport
1604 hostname name of the host
1605 local_message_max maximum number of messages down one connection
1606 as set by the caller transport
1607 new_message_id set to the message id of a waiting message
1608 more set TRUE if there are yet more messages waiting
a39bd74d
JB
1609 oicf_func function to call to validate if it is ok to send
1610 to this message_id from the current instance.
1611 oicf_data opaque data for oicf_func
059ec3d9
PH
1612
1613Returns: TRUE if new_message_id set; FALSE otherwise
1614*/
1615
a39bd74d
JB
1616typedef struct msgq_s
1617{
1618 uschar message_id [MESSAGE_ID_LENGTH + 1];
1619 BOOL bKeep;
1620} msgq_t;
1621
059ec3d9 1622BOOL
55414b25 1623transport_check_waiting(const uschar *transport_name, const uschar *hostname,
a39bd74d 1624 int local_message_max, uschar *new_message_id, BOOL *more, oicf oicf_func, void *oicf_data)
059ec3d9
PH
1625{
1626dbdata_wait *host_record;
0539a19d 1627int host_length;
059ec3d9
PH
1628open_db dbblock;
1629open_db *dbm_file;
059ec3d9 1630
a39bd74d 1631int i;
a39bd74d 1632struct stat statbuf;
a39bd74d 1633
059ec3d9
PH
1634*more = FALSE;
1635
1636DEBUG(D_transport)
1637 {
1638 debug_printf("transport_check_waiting entered\n");
1639 debug_printf(" sequence=%d local_max=%d global_max=%d\n",
1640 continue_sequence, local_message_max, connection_max_messages);
1641 }
1642
1643/* Do nothing if we have hit the maximum number that can be send down one
1644connection. */
1645
1646if (connection_max_messages >= 0) local_message_max = connection_max_messages;
1647if (local_message_max > 0 && continue_sequence >= local_message_max)
1648 {
1649 DEBUG(D_transport)
1650 debug_printf("max messages for one connection reached: returning\n");
1651 return FALSE;
1652 }
1653
1654/* Open the waiting information database. */
1655
36d295f1
JH
1656if (!(dbm_file = dbfn_open(string_sprintf("wait-%.200s", transport_name),
1657 O_RDWR, &dbblock, TRUE)))
1658 return FALSE;
059ec3d9
PH
1659
1660/* See if there is a record for this host; if not, there's nothing to do. */
1661
789f8a4f 1662if (!(host_record = dbfn_read(dbm_file, hostname)))
059ec3d9
PH
1663 {
1664 dbfn_close(dbm_file);
1665 DEBUG(D_transport) debug_printf("no messages waiting for %s\n", hostname);
1666 return FALSE;
1667 }
1668
1669/* If the data in the record looks corrupt, just log something and
1670don't try to use it. */
1671
1672if (host_record->count > WAIT_NAME_MAX)
1673 {
1674 dbfn_close(dbm_file);
1675 log_write(0, LOG_MAIN|LOG_PANIC, "smtp-wait database entry for %s has bad "
1676 "count=%d (max=%d)", hostname, host_record->count, WAIT_NAME_MAX);
1677 return FALSE;
1678 }
1679
1680/* Scan the message ids in the record from the end towards the beginning,
1681until one is found for which a spool file actually exists. If the record gets
1682emptied, delete it and continue with any continuation records that may exist.
1683*/
1684
a39bd74d
JB
1685/* For Bug 1141, I refactored this major portion of the routine, it is risky
1686but the 1 off will remain without it. This code now allows me to SKIP over
1687a message I do not want to send out on this run. */
059ec3d9 1688
a39bd74d
JB
1689host_length = host_record->count * MESSAGE_ID_LENGTH;
1690
1691while (1)
059ec3d9 1692 {
789f8a4f
JH
1693 msgq_t *msgq;
1694 int msgq_count = 0;
1695 int msgq_actual = 0;
1696 BOOL bFound = FALSE;
1697 BOOL bContinuation = FALSE;
1698
a39bd74d 1699 /* create an array to read entire message queue into memory for processing */
059ec3d9 1700
40c90bca 1701 msgq = store_malloc(sizeof(msgq_t) * host_record->count);
a39bd74d
JB
1702 msgq_count = host_record->count;
1703 msgq_actual = msgq_count;
059ec3d9 1704
a39bd74d 1705 for (i = 0; i < host_record->count; ++i)
059ec3d9 1706 {
a39bd74d
JB
1707 msgq[i].bKeep = TRUE;
1708
1709 Ustrncpy(msgq[i].message_id, host_record->text + (i * MESSAGE_ID_LENGTH),
059ec3d9 1710 MESSAGE_ID_LENGTH);
a39bd74d
JB
1711 msgq[i].message_id[MESSAGE_ID_LENGTH] = 0;
1712 }
1713
1714 /* first thing remove current message id if it exists */
059ec3d9 1715
a39bd74d
JB
1716 for (i = 0; i < msgq_count; ++i)
1717 if (Ustrcmp(msgq[i].message_id, message_id) == 0)
1718 {
1719 msgq[i].bKeep = FALSE;
1720 break;
1721 }
1722
1723 /* now find the next acceptable message_id */
1724
a39bd74d
JB
1725 for (i = msgq_count - 1; i >= 0; --i) if (msgq[i].bKeep)
1726 {
41313d92
JH
1727 uschar subdir[2];
1728
1729 subdir[0] = split_spool_directory ? msgq[i].message_id[5] : 0;
1730 subdir[1] = 0;
059ec3d9 1731
41313d92
JH
1732 if (Ustat(spool_fname(US"input", subdir, msgq[i].message_id, US"-D"),
1733 &statbuf) != 0)
a39bd74d
JB
1734 msgq[i].bKeep = FALSE;
1735 else if (!oicf_func || oicf_func(msgq[i].message_id, oicf_data))
059ec3d9 1736 {
a39bd74d
JB
1737 Ustrcpy(new_message_id, msgq[i].message_id);
1738 msgq[i].bKeep = FALSE;
1739 bFound = TRUE;
059ec3d9
PH
1740 break;
1741 }
1742 }
1743
a39bd74d
JB
1744 /* re-count */
1745 for (msgq_actual = 0, i = 0; i < msgq_count; ++i)
1746 if (msgq[i].bKeep)
1747 msgq_actual++;
1748
1749 /* reassemble the host record, based on removed message ids, from in
789f8a4f 1750 memory queue */
a39bd74d
JB
1751
1752 if (msgq_actual <= 0)
1753 {
1754 host_length = 0;
1755 host_record->count = 0;
1756 }
1757 else
1758 {
1759 host_length = msgq_actual * MESSAGE_ID_LENGTH;
1760 host_record->count = msgq_actual;
1761
1762 if (msgq_actual < msgq_count)
1763 {
1764 int new_count;
1765 for (new_count = 0, i = 0; i < msgq_count; ++i)
1766 if (msgq[i].bKeep)
1767 Ustrncpy(&host_record->text[new_count++ * MESSAGE_ID_LENGTH],
1768 msgq[i].message_id, MESSAGE_ID_LENGTH);
1769
1770 host_record->text[new_count * MESSAGE_ID_LENGTH] = 0;
1771 }
1772 }
1773
36d295f1 1774 /* Check for a continuation record. */
a39bd74d 1775
059ec3d9
PH
1776 while (host_length <= 0)
1777 {
1778 int i;
a39bd74d 1779 dbdata_wait * newr = NULL;
36d295f1 1780 uschar buffer[256];
059ec3d9
PH
1781
1782 /* Search for a continuation */
1783
a39bd74d 1784 for (i = host_record->sequence - 1; i >= 0 && !newr; i--)
059ec3d9
PH
1785 {
1786 sprintf(CS buffer, "%.200s:%d", hostname, i);
1787 newr = dbfn_read(dbm_file, buffer);
1788 }
1789
1790 /* If no continuation, delete the current and break the loop */
1791
a39bd74d 1792 if (!newr)
059ec3d9
PH
1793 {
1794 dbfn_delete(dbm_file, hostname);
1795 break;
1796 }
1797
1798 /* Else replace the current with the continuation */
1799
1800 dbfn_delete(dbm_file, buffer);
1801 host_record = newr;
1802 host_length = host_record->count * MESSAGE_ID_LENGTH;
059ec3d9 1803
a39bd74d
JB
1804 bContinuation = TRUE;
1805 }
059ec3d9 1806
789f8a4f
JH
1807 if (bFound) /* Usual exit from main loop */
1808 {
40c90bca 1809 store_free (msgq);
a39bd74d 1810 break;
789f8a4f 1811 }
059ec3d9
PH
1812
1813 /* If host_length <= 0 we have emptied a record and not found a good message,
1814 and there are no continuation records. Otherwise there is a continuation
1815 record to process. */
1816
1817 if (host_length <= 0)
1818 {
1819 dbfn_close(dbm_file);
1820 DEBUG(D_transport) debug_printf("waiting messages already delivered\n");
1821 return FALSE;
1822 }
a39bd74d
JB
1823
1824 /* we were not able to find an acceptable message, nor was there a
1825 * continuation record. So bug out, outer logic will clean this up.
1826 */
1827
1828 if (!bContinuation)
1829 {
789f8a4f 1830 Ustrcpy(new_message_id, message_id);
a39bd74d
JB
1831 dbfn_close(dbm_file);
1832 return FALSE;
1833 }
a39bd74d 1834
40c90bca 1835 store_free(msgq);
789f8a4f 1836 } /* we need to process a continuation record */
059ec3d9
PH
1837
1838/* Control gets here when an existing message has been encountered; its
1839id is in new_message_id, and host_length is the revised length of the
1840host record. If it is zero, the record has been removed. Update the
1841record if required, close the database, and return TRUE. */
1842
1843if (host_length > 0)
1844 {
1845 host_record->count = host_length/MESSAGE_ID_LENGTH;
a39bd74d 1846
059ec3d9
PH
1847 dbfn_write(dbm_file, hostname, host_record, (int)sizeof(dbdata_wait) + host_length);
1848 *more = TRUE;
1849 }
1850
1851dbfn_close(dbm_file);
1852return TRUE;
1853}
1854
059ec3d9
PH
1855/*************************************************
1856* Deliver waiting message down same socket *
1857*************************************************/
1858
57cc2785
JH
1859/* Just the regain-root-privilege exec portion */
1860void
1861transport_do_pass_socket(const uschar *transport_name, const uschar *hostname,
1862 const uschar *hostaddress, uschar *id, int socket_fd)
1863{
57cc2785
JH
1864int i = 20;
1865const uschar **argv;
1866
1867/* Set up the calling arguments; use the standard function for the basics,
1868but we have a number of extras that may be added. */
1869
1870argv = CUSS child_exec_exim(CEE_RETURN_ARGV, TRUE, &i, FALSE, 0);
1871
1872if (smtp_authenticated) argv[i++] = US"-MCA";
14de8063
JH
1873if (smtp_peer_options & OPTION_CHUNKING) argv[i++] = US"-MCK";
1874if (smtp_peer_options & OPTION_DSN) argv[i++] = US"-MCD";
1875if (smtp_peer_options & OPTION_PIPE) argv[i++] = US"-MCP";
1876if (smtp_peer_options & OPTION_SIZE) argv[i++] = US"-MCS";
57cc2785 1877#ifdef SUPPORT_TLS
14de8063 1878if (smtp_peer_options & OPTION_TLS)
57cc2785
JH
1879 if (tls_out.active >= 0 || continue_proxy_cipher)
1880 {
1881 argv[i++] = US"-MCt";
1882 argv[i++] = sending_ip_address;
1883 argv[i++] = string_sprintf("%d", sending_port);
1884 argv[i++] = tls_out.active >= 0 ? tls_out.cipher : continue_proxy_cipher;
1885 }
1886 else
1887 argv[i++] = US"-MCT";
1888#endif
1889
1890if (queue_run_pid != (pid_t)0)
1891 {
1892 argv[i++] = US"-MCQ";
1893 argv[i++] = string_sprintf("%d", queue_run_pid);
1894 argv[i++] = string_sprintf("%d", queue_run_pipe);
1895 }
1896
1897argv[i++] = US"-MC";
1898argv[i++] = US transport_name;
1899argv[i++] = US hostname;
1900argv[i++] = US hostaddress;
1901argv[i++] = string_sprintf("%d", continue_sequence + 1);
1902argv[i++] = id;
1903argv[i++] = NULL;
1904
1905/* Arrange for the channel to be on stdin. */
1906
1907if (socket_fd != 0)
1908 {
1909 (void)dup2(socket_fd, 0);
1910 (void)close(socket_fd);
1911 }
1912
1913DEBUG(D_exec) debug_print_argv(argv);
1914exim_nullstd(); /* Ensure std{out,err} exist */
1915execv(CS argv[0], (char *const *)argv);
1916
1917DEBUG(D_any) debug_printf("execv failed: %s\n", strerror(errno));
1918_exit(errno); /* Note: must be _exit(), NOT exit() */
1919}
1920
1921
1922
059ec3d9
PH
1923/* Fork a new exim process to deliver the message, and do a re-exec, both to
1924get a clean delivery process, and to regain root privilege in cases where it
1925has been given away.
1926
1927Arguments:
1928 transport_name to pass to the new process
1929 hostname ditto
1930 hostaddress ditto
1931 id the new message to process
1932 socket_fd the connected socket
1933
1934Returns: FALSE if fork fails; TRUE otherwise
1935*/
1936
1937BOOL
55414b25
JH
1938transport_pass_socket(const uschar *transport_name, const uschar *hostname,
1939 const uschar *hostaddress, uschar *id, int socket_fd)
059ec3d9
PH
1940{
1941pid_t pid;
1942int status;
1943
1944DEBUG(D_transport) debug_printf("transport_pass_socket entered\n");
1945
1946if ((pid = fork()) == 0)
1947 {
059ec3d9
PH
1948 /* Disconnect entirely from the parent process. If we are running in the
1949 test harness, wait for a bit to allow the previous process time to finish,
1950 write the log, etc., so that the output is always in the same order for
1951 automatic comparison. */
1952
b7d3afcf
JH
1953 if ((pid = fork()) != 0)
1954 {
1955 DEBUG(D_transport) debug_printf("transport_pass_socket succeeded (final-pid %d)\n", pid);
1956 _exit(EXIT_SUCCESS);
1957 }
ed0e9820 1958 if (running_in_test_harness) sleep(1);
059ec3d9 1959
57cc2785
JH
1960 transport_do_pass_socket(transport_name, hostname, hostaddress,
1961 id, socket_fd);
059ec3d9
PH
1962 }
1963
1964/* If the process creation succeeded, wait for the first-level child, which
1965immediately exits, leaving the second level process entirely disconnected from
1966this one. */
1967
1968if (pid > 0)
1969 {
1970 int rc;
1971 while ((rc = wait(&status)) != pid && (rc >= 0 || errno != ECHILD));
b7d3afcf 1972 DEBUG(D_transport) debug_printf("transport_pass_socket succeeded (inter-pid %d)\n", pid);
059ec3d9
PH
1973 return TRUE;
1974 }
1975else
1976 {
1977 DEBUG(D_transport) debug_printf("transport_pass_socket failed to fork: %s\n",
1978 strerror(errno));
1979 return FALSE;
1980 }
1981}
1982
1983
1984
1985/*************************************************
1986* Set up direct (non-shell) command *
1987*************************************************/
1988
1989/* This function is called when a command line is to be parsed and executed
1990directly, without the use of /bin/sh. It is called by the pipe transport,
1991the queryprogram router, and also from the main delivery code when setting up a
1992transport filter process. The code for ETRN also makes use of this; in that
1993case, no addresses are passed.
1994
1995Arguments:
1996 argvptr pointer to anchor for argv vector
55414b25 1997 cmd points to the command string (modified IN PLACE)
059ec3d9
PH
1998 expand_arguments true if expansion is to occur
1999 expand_failed error value to set if expansion fails; not relevant if
2000 addr == NULL
2001 addr chain of addresses, or NULL
2002 etext text for use in error messages
2003 errptr where to put error message if addr is NULL;
2004 otherwise it is put in the first address
2005
2006Returns: TRUE if all went well; otherwise an error will be
2007 set in the first address and FALSE returned
2008*/
2009
2010BOOL
55414b25
JH
2011transport_set_up_command(const uschar ***argvptr, uschar *cmd,
2012 BOOL expand_arguments, int expand_failed, address_item *addr,
2013 uschar *etext, uschar **errptr)
059ec3d9
PH
2014{
2015address_item *ad;
55414b25 2016const uschar **argv;
059ec3d9
PH
2017uschar *s, *ss;
2018int address_count = 0;
2019int argcount = 0;
2020int i, max_args;
2021
2022/* Get store in which to build an argument list. Count the number of addresses
2023supplied, and allow for that many arguments, plus an additional 60, which
2024should be enough for anybody. Multiple addresses happen only when the local
2025delivery batch option is set. */
2026
2027for (ad = addr; ad != NULL; ad = ad->next) address_count++;
2028max_args = address_count + 60;
2029*argvptr = argv = store_get((max_args+1)*sizeof(uschar *));
2030
2031/* Split the command up into arguments terminated by white space. Lose
2032trailing space at the start and end. Double-quoted arguments can contain \\ and
2033\" escapes and so can be handled by the standard function; single-quoted
2034arguments are verbatim. Copy each argument into a new string. */
2035
2036s = cmd;
2037while (isspace(*s)) s++;
2038
2039while (*s != 0 && argcount < max_args)
2040 {
2041 if (*s == '\'')
2042 {
2043 ss = s + 1;
2044 while (*ss != 0 && *ss != '\'') ss++;
2045 argv[argcount++] = ss = store_get(ss - s++);
2046 while (*s != 0 && *s != '\'') *ss++ = *s++;
2047 if (*s != 0) s++;
2048 *ss++ = 0;
2049 }
55414b25 2050 else argv[argcount++] = string_copy(string_dequote(CUSS &s));
059ec3d9
PH
2051 while (isspace(*s)) s++;
2052 }
2053
5903c6ff 2054argv[argcount] = US 0;
059ec3d9
PH
2055
2056/* If *s != 0 we have run out of argument slots. */
2057
2058if (*s != 0)
2059 {
2060 uschar *msg = string_sprintf("Too many arguments in command \"%s\" in "
2061 "%s", cmd, etext);
2062 if (addr != NULL)
2063 {
2064 addr->transport_return = FAIL;
2065 addr->message = msg;
2066 }
2067 else *errptr = msg;
2068 return FALSE;
2069 }
2070
2071/* Expand each individual argument if required. Expansion happens for pipes set
2072up in filter files and with directly-supplied commands. It does not happen if
2073the pipe comes from a traditional .forward file. A failing expansion is a big
2074disaster if the command came from Exim's configuration; if it came from a user
2075it is just a normal failure. The expand_failed value is used as the error value
2076to cater for these two cases.
2077
2078An argument consisting just of the text "$pipe_addresses" is treated specially.
2079It is not passed to the general expansion function. Instead, it is replaced by
2080a number of arguments, one for each address. This avoids problems with shell
2081metacharacters and spaces in addresses.
2082
2083If the parent of the top address has an original part of "system-filter", this
2084pipe was set up by the system filter, and we can permit the expansion of
2085$recipients. */
2086
2087DEBUG(D_transport)
2088 {
2089 debug_printf("direct command:\n");
5903c6ff 2090 for (i = 0; argv[i] != US 0; i++)
059ec3d9
PH
2091 debug_printf(" argv[%d] = %s\n", i, string_printing(argv[i]));
2092 }
2093
2094if (expand_arguments)
2095 {
2096 BOOL allow_dollar_recipients = addr != NULL &&
2097 addr->parent != NULL &&
2098 Ustrcmp(addr->parent->address, "system-filter") == 0;
2099
5903c6ff 2100 for (i = 0; argv[i] != US 0; i++)
059ec3d9
PH
2101 {
2102
2103 /* Handle special fudge for passing an address list */
2104
2105 if (addr != NULL &&
2106 (Ustrcmp(argv[i], "$pipe_addresses") == 0 ||
2107 Ustrcmp(argv[i], "${pipe_addresses}") == 0))
2108 {
2109 int additional;
2110
2111 if (argcount + address_count - 1 > max_args)
2112 {
2113 addr->transport_return = FAIL;
2114 addr->message = string_sprintf("Too many arguments to command \"%s\" "
2115 "in %s", cmd, etext);
2116 return FALSE;
2117 }
2118
2119 additional = address_count - 1;
2120 if (additional > 0)
2121 memmove(argv + i + 1 + additional, argv + i + 1,
2122 (argcount - i)*sizeof(uschar *));
2123
09792322
NK
2124 for (ad = addr; ad != NULL; ad = ad->next) {
2125 argv[i++] = ad->address;
2126 argcount++;
2127 }
2128
700d22f3
PP
2129 /* Subtract one since we replace $pipe_addresses */
2130 argcount--;
2131 i--;
09792322
NK
2132 }
2133
2134 /* Handle special case of $address_pipe when af_force_command is set */
2135
2136 else if (addr != NULL && testflag(addr,af_force_command) &&
2137 (Ustrcmp(argv[i], "$address_pipe") == 0 ||
2138 Ustrcmp(argv[i], "${address_pipe}") == 0))
2139 {
2140 int address_pipe_i;
2141 int address_pipe_argcount = 0;
2142 int address_pipe_max_args;
2143 uschar **address_pipe_argv;
2144
2145 /* We can never have more then the argv we will be loading into */
2146 address_pipe_max_args = max_args - argcount + 1;
2147
2148 DEBUG(D_transport)
700d22f3 2149 debug_printf("address_pipe_max_args=%d\n", address_pipe_max_args);
09792322
NK
2150
2151 /* We allocate an additional for (uschar *)0 */
2152 address_pipe_argv = store_get((address_pipe_max_args+1)*sizeof(uschar *));
2153
2154 /* +1 because addr->local_part[0] == '|' since af_force_command is set */
2155 s = expand_string(addr->local_part + 1);
2156
700d22f3
PP
2157 if (s == NULL || *s == '\0')
2158 {
2159 addr->transport_return = FAIL;
2160 addr->message = string_sprintf("Expansion of \"%s\" "
2161 "from command \"%s\" in %s failed: %s",
2162 (addr->local_part + 1), cmd, etext, expand_string_message);
09792322 2163 return FALSE;
700d22f3 2164 }
09792322
NK
2165
2166 while (isspace(*s)) s++; /* strip leading space */
2167
2168 while (*s != 0 && address_pipe_argcount < address_pipe_max_args)
2169 {
2170 if (*s == '\'')
2171 {
2172 ss = s + 1;
2173 while (*ss != 0 && *ss != '\'') ss++;
2174 address_pipe_argv[address_pipe_argcount++] = ss = store_get(ss - s++);
2175 while (*s != 0 && *s != '\'') *ss++ = *s++;
2176 if (*s != 0) s++;
2177 *ss++ = 0;
2178 }
55414b25
JH
2179 else address_pipe_argv[address_pipe_argcount++] =
2180 string_copy(string_dequote(CUSS &s));
09792322
NK
2181 while (isspace(*s)) s++; /* strip space after arg */
2182 }
2183
5903c6ff 2184 address_pipe_argv[address_pipe_argcount] = US 0;
09792322
NK
2185
2186 /* If *s != 0 we have run out of argument slots. */
2187 if (*s != 0)
2188 {
2189 uschar *msg = string_sprintf("Too many arguments in $address_pipe "
2190 "\"%s\" in %s", addr->local_part + 1, etext);
2191 if (addr != NULL)
2192 {
2193 addr->transport_return = FAIL;
2194 addr->message = msg;
2195 }
2196 else *errptr = msg;
2197 return FALSE;
2198 }
2199
700d22f3
PP
2200 /* address_pipe_argcount - 1
2201 * because we are replacing $address_pipe in the argument list
2202 * with the first thing it expands to */
09792322
NK
2203 if (argcount + address_pipe_argcount - 1 > max_args)
2204 {
2205 addr->transport_return = FAIL;
2206 addr->message = string_sprintf("Too many arguments to command "
2207 "\"%s\" after expanding $address_pipe in %s", cmd, etext);
2208 return FALSE;
2209 }
2210
2211 /* If we are not just able to replace the slot that contained
2212 * $address_pipe (address_pipe_argcount == 1)
700d22f3 2213 * We have to move the existing argv by address_pipe_argcount - 1
09792322
NK
2214 * Visually if address_pipe_argcount == 2:
2215 * [argv 0][argv 1][argv 2($address_pipe)][argv 3][0]
700d22f3 2216 * [argv 0][argv 1][ap_arg0][ap_arg1][old argv 3][0]
09792322
NK
2217 */
2218 if (address_pipe_argcount > 1)
2219 memmove(
4c04137d 2220 /* current position + additional args */
09792322
NK
2221 argv + i + address_pipe_argcount,
2222 /* current position + 1 (for the (uschar *)0 at the end) */
2223 argv + i + 1,
2224 /* -1 for the (uschar *)0 at the end)*/
2225 (argcount - i)*sizeof(uschar *)
2226 );
2227
2228 /* Now we fill in the slots we just moved argv out of
2229 * [argv 0][argv 1][argv 2=pipeargv[0]][argv 3=pipeargv[1]][old argv 3][0]
2230 */
700d22f3 2231 for (address_pipe_i = 0;
5903c6ff 2232 address_pipe_argv[address_pipe_i] != US 0;
700d22f3
PP
2233 address_pipe_i++)
2234 {
2235 argv[i++] = address_pipe_argv[address_pipe_i];
2236 argcount++;
09792322
NK
2237 }
2238
700d22f3
PP
2239 /* Subtract one since we replace $address_pipe */
2240 argcount--;
2241 i--;
059ec3d9
PH
2242 }
2243
2244 /* Handle normal expansion string */
2245
2246 else
2247 {
55414b25 2248 const uschar *expanded_arg;
059ec3d9 2249 enable_dollar_recipients = allow_dollar_recipients;
55414b25 2250 expanded_arg = expand_cstring(argv[i]);
059ec3d9
PH
2251 enable_dollar_recipients = FALSE;
2252
2253 if (expanded_arg == NULL)
2254 {
2255 uschar *msg = string_sprintf("Expansion of \"%s\" "
2256 "from command \"%s\" in %s failed: %s",
2257 argv[i], cmd, etext, expand_string_message);
2258 if (addr != NULL)
2259 {
2260 addr->transport_return = expand_failed;
2261 addr->message = msg;
2262 }
2263 else *errptr = msg;
2264 return FALSE;
2265 }
2266 argv[i] = expanded_arg;
2267 }
2268 }
2269
2270 DEBUG(D_transport)
2271 {
2272 debug_printf("direct command after expansion:\n");
5903c6ff 2273 for (i = 0; argv[i] != US 0; i++)
059ec3d9
PH
2274 debug_printf(" argv[%d] = %s\n", i, string_printing(argv[i]));
2275 }
2276 }
2277
2278return TRUE;
2279}
2280
d185889f 2281#endif /*!MACRO_PREDEF*/
511a6c14
JH
2282/* vi: aw ai sw=2
2283*/
059ec3d9 2284/* End of transport.c */