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