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