1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
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 */
10 /* General functions concerned with transportation, and generic options for all
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)
22 optionlist optionlist_transports[] = {
24 { "*expand_group", opt_stringptr|opt_hidden|opt_public,
26 { "*expand_user", opt_stringptr|opt_hidden|opt_public,
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,
34 { "*set_user", opt_bool|opt_hidden|opt_public,
36 { "body_only", opt_bool|opt_public,
38 { "current_directory", opt_stringptr|opt_public,
40 { "debug_print", opt_stringptr | opt_public,
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) },
51 { "event_action", opt_stringptr | opt_public,
54 { "group", opt_expand_gid|opt_public,
56 { "headers_add", opt_stringptr|opt_public|opt_rep_str,
58 { "headers_only", opt_bool|opt_public,
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,
66 { "initgroups", opt_bool|opt_public,
68 { "max_parallel", opt_stringptr|opt_public,
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,
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,
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,
92 int optionlist_transports_size = nelem(optionlist_transports);
96 # include "macro_predef.h"
99 options_transports(void)
103 options_from_list(optionlist_transports, nelem(optionlist_transports), US"TRANSPORTS", NULL);
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)
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);
115 #else /*!MACRO_PREDEF*/
117 /* Structure for keeping list of addresses that have been added to
118 Envelope-To:, in order to avoid duplication. */
126 /* Static data for write_chunk() */
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 */
136 /*************************************************
137 * Initialize transport list *
138 *************************************************/
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
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++)
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;
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,
170 /* Now scan the configured transports and check inconsistencies. A shadow
171 transport is permitted only for local transports. */
173 for (transport_instance * t = transports; t; t = t->drinst.next)
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);
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",
189 /*************************************************
190 * Write block of data *
191 *************************************************/
194 tpt_write(int fd, uschar * block, int len, BOOL more, int options)
198 tls_out.active.sock == fd
199 ? tls_write(tls_out.active.tls_ctx, block, len, more) :
202 more && !(options & topt_not_socket) ? send(fd, block, len, MSG_MORE) :
204 write(fd, block, len);
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).
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
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.
223 The write() function is also interruptible; the Solaris 2.6 man page says:
225 If write() is interrupted by a signal before it writes any
226 data, it will return -1 with errno set to EINTR.
228 If write() is interrupted by a signal after it successfully
229 writes some data, it will return the number of bytes written.
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
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
245 Returns: TRUE on success, FALSE on failure (with errno preserved);
246 transport_count is incremented by the number of bytes written
250 transport_write_block_fd(transport_ctx * tctx, uschar * block, int len, BOOL more)
253 int local_timeout = transport_write_timeout;
257 /* This loop is for handling incomplete writes and other retries. In most
258 normal cases, it is only ever executed once. */
260 for (int i = 0; i < 100; i++)
263 debug_printf("writing data block fd=%d size=%d timeout=%d%s\n",
264 fd, len, local_timeout, more ? " (more expected)" : "");
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. */
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
277 if (transport_write_timeout <= 0) /* No timeout wanted */
279 rc = tpt_write(fd, block, len, more, tctx->options);
282 else /* Timeout wanted. */
284 sigalrm_seen = FALSE;
285 ALARM(local_timeout);
286 rc = tpt_write(fd, block, len, more, tctx->options);
288 local_timeout = ALARM_CLR(0);
296 if (rc >= 0 || errno != ENOTCONN || connretry <= 0)
299 poll_one_fd(fd, POLLOUT, -1); /* could set timeout? retval check? */
303 /* Hopefully, the most common case is success, so test that first. */
305 if (rc == len) { transport_count += len; return TRUE; }
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. */
314 transport_count += rc;
315 DEBUG(D_transport) debug_printf("write incomplete (%d)\n", rc);
316 goto CHECK_TIMEOUT; /* A few lines below */
319 /* A negative return code with an EINTR error is another form of
320 incomplete write, zero bytes having been written */
322 if (save_errno == EINTR)
325 debug_printf("write interrupted before anything written\n");
326 goto CHECK_TIMEOUT; /* A few lines below */
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. */
332 if (save_errno == EAGAIN)
335 debug_printf("write temporarily locked out, waiting 1 sec\n");
338 /* Before continuing to try another write, check that we haven't run out of
342 if (transport_write_timeout > 0 && local_timeout <= 0)
350 /* Otherwise there's been an error */
352 DEBUG(D_transport) debug_printf("writing error %d: %s\n", save_errno,
353 strerror(save_errno));
358 /* We've tried and tried and tried but still failed */
360 errno = ERRNO_WRITEINCOMPLETE;
366 transport_write_block(transport_ctx * tctx, uschar *block, int len, BOOL more)
368 if (!(tctx->options & topt_output_string))
369 return transport_write_block_fd(tctx, block, len, more);
371 /* Write to expanding-string. NOTE: not NUL-terminated */
374 tctx->u.msg = string_get(1024);
376 tctx->u.msg = string_catn(tctx->u.msg, block, len);
383 /*************************************************
384 * Write formatted string *
385 *************************************************/
387 /* This is called by various transports. It is a convenience function.
392 ... arguments for format
394 Returns: the yield of transport_write_block()
398 transport_write_string(int fd, const char *format, ...)
400 transport_ctx tctx = {{0}};
401 gstring gs = { .size = big_buffer_size, .ptr = 0, .s = big_buffer };
404 /* Use taint-unchecked routines for writing into big_buffer, trusting
405 that the result will never be expanded. */
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");
412 return transport_write_block(&tctx, gs.s, gs.ptr, FALSE);
419 transport_write_reset(int options)
421 if (!(options & topt_continuation)) chunk_ptr = deliver_out_buffer;
422 nl_partial_match = -1;
423 nl_check_length = nl_escape_length = 0;
428 /*************************************************
429 * Write character chunk *
430 *************************************************/
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.
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.
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
446 In addition, the static nl_xxx variables must be set as required.
448 Returns: TRUE on success, FALSE on failure (with errno preserved)
452 write_chunk(transport_ctx * tctx, const uschar * chunk, int len)
454 const uschar * start = chunk;
455 const uschar * end = chunk + len;
456 int mlen = DELIVER_OUT_BUFFER_SIZE - nl_escape_length - 2;
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
465 if (nl_partial_match >= 0)
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)
471 Ustrncpy(chunk_ptr, nl_escape, nl_escape_length);
472 chunk_ptr += nl_escape_length;
473 start += nl_check_length - nl_partial_match;
476 /* The partial match was a false one. Insert the characters carried over
477 from the previous chunk. */
479 else if (nl_partial_match > 0)
481 Ustrncpy(chunk_ptr, nl_check, nl_partial_match);
482 chunk_ptr += nl_partial_match;
485 nl_partial_match = -1;
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
492 for (const uschar * ptr = start; ptr < end; ptr++)
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
500 if ((len = chunk_ptr - deliver_out_buffer) > mlen)
502 DEBUG(D_transport) debug_printf("flushing headers buffer\n");
504 /* If CHUNKING, prefix with BDAT (size) NON-LAST. Also, reap responses
505 from previous SMTP commands. */
507 if (tctx->options & topt_use_bdat && tctx->chunk_cb)
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
516 if (!transport_write_block(tctx, deliver_out_buffer, len, FALSE))
518 chunk_ptr = deliver_out_buffer;
521 /* Remove CR before NL if required */
523 if ( *ptr == '\r' && ptr[1] == '\n'
524 && !(tctx->options & topt_use_crlf)
525 && f.spool_file_wireformat
529 if ((ch = *ptr) == '\n')
531 int left = end - ptr - 1; /* count of chars left after NL */
533 /* Insert CR before NL if required */
535 if (tctx->options & topt_use_crlf && !f.spool_file_wireformat)
538 transport_newlines++;
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. */
545 if (nl_check_length > 0)
547 if (left >= nl_check_length &&
548 Ustrncmp(ptr+1, nl_check, nl_check_length) == 0)
550 Ustrncpy(chunk_ptr, nl_escape, nl_escape_length);
551 chunk_ptr += nl_escape_length;
552 ptr += nl_check_length;
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. */
559 else if (left <= 0) nl_partial_match = 0;
561 else if (Ustrncmp(ptr+1, nl_check, left) == 0)
563 nl_partial_match = left;
569 /* Not a NL character */
571 else *chunk_ptr++ = ch;
580 /*************************************************
581 * Generate address for RCPT TO *
582 *************************************************/
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
592 addr the address item
593 include_affixes TRUE if affixes are to be included
599 transport_rcpt_address(address_item *addr, BOOL include_affixes)
606 setflag(addr, af_include_affixes); /* Affects logged => line */
607 return addr->address;
612 if (!addr->prefix) return addr->address;
613 return addr->address + Ustrlen(addr->prefix);
616 at = Ustrrchr(addr->address, '@');
617 plen = addr->prefix ? Ustrlen(addr->prefix) : 0;
618 slen = Ustrlen(addr->suffix);
620 return string_sprintf("%.*s@%s", (int)(at - addr->address - plen - slen),
621 addr->address + plen, at + 1);
625 /*************************************************
626 * Output Envelope-To: address & scan duplicates *
627 *************************************************/
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.
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
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
644 After handling duplication, this function outputs the progenitor of the given
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
655 Returns: FALSE if writing failed
659 write_env_to(address_item *p, struct aci **pplist, struct aci **pdlist,
660 BOOL *first, transport_ctx * tctx)
665 /* Do nothing if we have already handled this address. If not, remember it
666 so that we don't handle it again. */
668 for (ppp = *pdlist; ppp; ppp = ppp->next) if (p == ppp->ptr) return TRUE;
670 ppp = store_get(sizeof(struct aci), GET_UNTAINTED);
675 /* Now scan up the ancestry, checking for duplicates at each generation. */
677 for (pp = p;; pp = pp->parent)
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))
684 if (!pp->parent) break;
687 /* Check to see if we have already output the progenitor. */
689 for (ppp = *pplist; ppp; ppp = ppp->next) if (pp == ppp->ptr) break;
690 if (ppp) return TRUE;
692 /* Remember what we have output, and output it. */
694 ppp = store_get(sizeof(struct aci), GET_UNTAINTED);
699 if (!*first && !write_chunk(tctx, US",\n ", 3)) return FALSE;
701 return write_chunk(tctx, pp->address, Ustrlen(pp->address));
707 /* Add/remove/rewrite headers, and send them plus the empty-line separator.
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)
718 Returns: TRUE on success; FALSE on failure.
721 transport_headers_send(transport_ctx * tctx,
722 BOOL (*sendfn)(transport_ctx * tctx, const uschar * s, int len))
725 transport_instance * tblock = tctx ? tctx->tblock : NULL;
726 address_item * addr = tctx ? tctx->addr : NULL;
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. */
735 for (header_line * h = header_list; h; h = h->next) if (h->type != htype_old)
737 BOOL include_header = TRUE;
739 list = tblock ? tblock->remove_headers : NULL;
740 for (int i = 0; i < 2; i++) /* For remove_headers && addr->prop.remove_headers */
744 int sep = ':'; /* This is specified as a colon-separated list */
746 while ((s = string_nextinlist(&list, &sep, NULL, 0)))
751 if (!(s = expand_string(s)) && !f.expand_string_forcedfail)
753 errno = ERRNO_CHHEADER_FAIL;
756 len = s ? Ustrlen(s) : 0;
757 if (len && s[len-1] == '*') /* trailing glob */
759 if (strncmpic(h->text, s, len-1) == 0) break;
763 if (strncmpic(h->text, s, len) != 0) continue;
765 while (*ss == ' ' || *ss == '\t') ss++;
766 if (*ss == ':') break;
769 if (s) { include_header = FALSE; break; }
771 if (addr) list = addr->prop.remove_headers;
774 /* If this header is to be output, try to rewrite it if there are rewriting
780 if (tblock && tblock->rewrite_rules)
782 rmark reset_point = store_mark();
785 if ((hh = rewrite_header(h, NULL, NULL, tblock->rewrite_rules,
786 tblock->rewrite_existflags, FALSE)))
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 */
796 /* Either no rewriting rules, or it didn't get rewritten */
799 if (tctx->options & topt_truncate_headers && len > 998) len = 998;
800 if (!sendfn(tctx, h->text, len)) return FALSE;
806 DEBUG(D_transport) debug_printf("removed header line:\n %s---\n", h->text);
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.
817 Headers added to an address by a router are guaranteed to end with a newline.
822 header_line * hprev = addr->prop.extra_headers, * hnext, * h;
824 for (int i = 0; i < 2; i++)
825 for (h = hprev, hprev = NULL; h; h = hnext)
832 if (!sendfn(tctx, h->text, h->slen)) return FALSE;
834 debug_printf("added header line(s):\n %s---\n", h->text);
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. */
846 if (tblock && (list = CUS tblock->add_headers))
851 while ((s = string_nextinlist(&list, &sep, NULL, 0)))
852 if ((s = expand_string(s)))
854 int len = Ustrlen(s);
857 if (!sendfn(tctx, s, len)) return FALSE;
858 if (s[len-1] != '\n' && !sendfn(tctx, US"\n", 1))
862 debug_printf("added header line:\n %s", s);
863 if (s[len-1] != '\n') debug_printf("\n");
864 debug_printf("---\n");
868 else if (!f.expand_string_forcedfail)
869 { errno = ERRNO_CHHEADER_FAIL; return FALSE; }
872 /* Separate headers from body with a blank line */
874 return sendfn(tctx, US"\n", 1);
878 /*************************************************
879 * Write the message *
880 *************************************************/
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.
886 . If add_return_path is TRUE, a "return-path:" header is added to the message,
887 containing the envelope sender's address.
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.
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.
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.
899 . If use_crlf is true, newlines are turned into CRLF (SMTP output).
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.
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
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.
943 internal_transport_write_message(transport_ctx * tctx, int size_limit)
947 /* Initialize pointer in output buffer. */
949 transport_write_reset(tctx->options);
951 /* Set up the data for start-of-line data checking and escaping */
953 if (tctx->check_string && tctx->escape_string)
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);
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. */
965 if (!(tctx->options & topt_escape_headers))
966 nl_check_length = -nl_check_length;
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. */
972 if (!(tctx->options & topt_no_headers))
974 BOOL save_wireformat = f.spool_file_wireformat;
975 f.spool_file_wireformat = FALSE;
977 /* Add return-path: if requested. */
979 if (tctx->options & topt_add_return_path)
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;
987 /* Add envelope-to: if requested */
989 if (tctx->options & topt_add_envelope_to)
992 struct aci *plist = NULL;
993 struct aci *dlist = NULL;
994 rmark reset_point = store_mark();
996 if (!write_chunk(tctx, US"Envelope-to: ", 13)) goto bad;
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. */
1002 for (address_item * p = tctx->addr; p; p = p->next)
1003 if (!write_env_to(p, &plist, &dlist, &first, tctx))
1006 /* Add a final newline and reset the store used for tracking duplicates */
1008 if (!write_chunk(tctx, US"\n", 1)) goto bad;
1009 store_reset(reset_point);
1012 /* Add delivery-date: if requested. */
1014 if (tctx->options & topt_add_delivery_date)
1016 uschar * s = tod_stamp(tod_full);
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;
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. */
1029 if (!transport_headers_send(tctx, &write_chunk))
1032 f.spool_file_wireformat = save_wireformat;
1036 f.spool_file_wireformat = save_wireformat;
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
1051 if (tctx->options & topt_use_bdat)
1056 if ((hsize = chunk_ptr - deliver_out_buffer) < 0)
1058 if (!(tctx->options & topt_no_body))
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)
1064 size = hsize + fsize;
1065 if (tctx->options & topt_use_crlf && !f.spool_file_wireformat)
1066 size += body_linecount; /* account for CRLF-expansion */
1068 /* With topt_use_bdat we never do dot-stuffing; no need to
1069 account for any expansion due to that. */
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. */
1078 if (size > DELIVER_OUT_BUFFER_SIZE && hsize > 0)
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
1087 chunk_ptr = deliver_out_buffer;
1091 /* Emit a LAST datachunk command, and unmark the context for further
1094 if (tctx->chunk_cb(tctx, size, tc_chunk_last) != OK)
1096 tctx->options &= ~topt_use_bdat;
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. */
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. */
1112 if ( f.spool_file_wireformat
1113 && !(tctx->options & (topt_no_body | topt_end_dot))
1115 && tls_out.active.sock != tctx->u.fd
1119 off_t offset = spool_data_start_offset(message_id);
1121 /* Write out any header data in the buffer */
1123 if ((len = chunk_ptr - deliver_out_buffer) > 0)
1125 if (!transport_write_block(tctx, deliver_out_buffer, len, TRUE))
1130 DEBUG(D_transport) debug_printf("using sendfile for body\n");
1134 if ((copied = os_sendfile(tctx->u.fd, deliver_datafile, &offset, size)) <= 0) break;
1140 DEBUG(D_transport) debug_printf("cannot use sendfile for body: no support\n");
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");
1151 if (!(tctx->options & topt_no_body))
1153 unsigned long size = size_limit > 0 ? size_limit : ULONG_MAX;
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)
1159 while ( (len = MIN(DELIVER_IN_BUFFER_SIZE, size)) > 0
1160 && (len = read(deliver_datafile, deliver_in_buffer, len)) > 0)
1162 if (!write_chunk(tctx, deliver_in_buffer, len))
1167 /* A read error on the body will have left len == -1 and errno set. */
1169 if (len != 0) return FALSE;
1172 /* Finished with the check string, and spool-format consideration */
1174 nl_check_length = nl_escape_length = 0;
1175 f.spool_file_wireformat = FALSE;
1177 /* If requested, add a terminating "." line (SMTP output). */
1179 if (tctx->options & topt_end_dot)
1181 smtp_debug_cmd(US".", 0);
1182 if (!write_chunk(tctx, US".\n", 2))
1186 /* Write out any remaining data in the buffer before returning. */
1188 return (len = chunk_ptr - deliver_out_buffer) <= 0
1189 || transport_write_block(tctx, deliver_out_buffer, len,
1190 !!(tctx->options & topt_no_flush));
1196 /*************************************************
1197 * External interface to write the message *
1198 *************************************************/
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
1207 Arguments: as for internal_transport_write_message() above
1209 Returns: TRUE on success; FALSE (with errno) for any failure
1210 transport_count is incremented by the number of bytes written
1214 transport_write_message(transport_ctx * tctx, int size_limit)
1216 BOOL last_filter_was_NL = TRUE;
1217 BOOL save_spool_file_wireformat = f.spool_file_wireformat;
1219 int rc, len, fd_read, fd_write, save_errno;
1220 int pfd[2] = {-1, -1};
1221 pid_t filter_pid, write_pid;
1223 f.transport_filter_timed_out = FALSE;
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. */
1228 if ( !transport_filter_argv
1229 || !*transport_filter_argv
1230 || !**transport_filter_argv
1232 return internal_transport_write_message(tctx, size_limit);
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. */
1238 nl_partial_match = -1;
1240 if (tctx->check_string && tctx->escape_string)
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);
1247 else nl_check_length = nl_escape_length = 0;
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. */
1259 write_pid = (pid_t)(-1);
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);
1268 if (filter_pid < 0) goto TIDY_UP; /* errno set */
1271 debug_printf("process %d running as transport filter: fd_write=%d fd_read=%d\n",
1272 (int)filter_pid, fd_write, fd_read);
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. */
1278 if (pipe(pfd) != 0) goto TIDY_UP; /* errno set */
1279 if ((write_pid = exim_fork(US"tpt-filter-writer")) == 0)
1282 (void)close(fd_read);
1283 (void)close(pfd[pipe_read]);
1284 nl_check_length = nl_escape_length = 0;
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);
1290 rc = internal_transport_write_message(tctx, size_limit);
1293 if ( write(pfd[pipe_write], (void *)&rc, sizeof(BOOL))
1295 || write(pfd[pipe_write], (void *)&save_errno, sizeof(int))
1297 || write(pfd[pipe_write], (void *)&tctx->addr->more_errno, sizeof(int))
1299 || write(pfd[pipe_write], (void *)&tctx->addr->delivery_time, sizeof(struct timeval))
1300 != sizeof(struct timeval)
1302 rc = FALSE; /* compiler quietening */
1303 exim_underbar_exit(EXIT_SUCCESS);
1307 /* Parent process: close our copy of the writing subprocess' pipes. */
1309 (void)close(pfd[pipe_write]);
1310 (void)close(fd_write);
1313 /* Writing process creation failed */
1317 errno = save_errno; /* restore */
1321 /* When testing, let the subprocess get going */
1323 testharness_pause_ms(250);
1326 debug_printf("process %d writing to transport filter\n", (int)write_pid);
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. */
1333 DEBUG(D_transport) debug_printf("copying from the filter\n");
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. */
1340 f.spool_file_wireformat = FALSE;
1341 chunk_ptr = deliver_out_buffer;
1345 sigalrm_seen = FALSE;
1346 ALARM(transport_filter_timeout);
1347 len = read(fd_read, deliver_in_buffer, DELIVER_IN_BUFFER_SIZE);
1351 DEBUG(D_transport) debug_printf("timed out reading from filter\n");
1353 f.transport_filter_timed_out = TRUE;
1357 /* If the read was successful, write the block down the original fd,
1358 remembering whether it ends in \n or not. */
1362 if (!write_chunk(tctx, deliver_in_buffer, len)) goto TIDY_UP;
1363 last_filter_was_NL = (deliver_in_buffer[len-1] == '\n');
1366 /* Otherwise, break the loop. If we have hit EOF, set yield = TRUE. */
1370 if (len == 0) yield = TRUE;
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. */
1381 f.spool_file_wireformat = save_spool_file_wireformat;
1384 (void)close(fd_read);
1385 if (fd_write > 0) (void)close(fd_write);
1389 if (filter_pid > 0) kill(filter_pid, SIGKILL);
1390 if (write_pid > 0) kill(write_pid, SIGKILL);
1393 /* Wait for the filter process to complete. */
1395 DEBUG(D_transport) debug_printf("waiting for filter process\n");
1396 if (filter_pid > 0 && (rc = child_close(filter_pid, 30)) != 0 && yield)
1399 save_errno = ERRNO_FILTER_FAIL;
1400 tctx->addr->more_errno = rc;
1401 DEBUG(D_transport) debug_printf("filter process returned %d\n", rc);
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
1408 DEBUG(D_transport) debug_printf("waiting for writing process\n");
1411 rc = child_close(write_pid, 30);
1416 if (read(pfd[pipe_read], (void *)&ok, sizeof(BOOL)) != sizeof(BOOL))
1419 debug_printf("pipe read from writing process: %s\n", strerror(errno));
1420 save_errno = ERRNO_FILTER_FAIL;
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));
1434 save_errno = ERRNO_FILTER_FAIL;
1435 tctx->addr->more_errno = rc;
1436 DEBUG(D_transport) debug_printf("writing process returned %d\n", rc);
1439 (void)close(pfd[pipe_read]);
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. */
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)
1454 { smtp_debug_cmd(US".", 0); yield = FALSE; }
1456 /* Write out any remaining data in the buffer. */
1459 yield = (len = chunk_ptr - deliver_out_buffer) <= 0
1460 || transport_write_block(tctx, deliver_out_buffer, len, FALSE);
1463 errno = save_errno; /* From some earlier error */
1467 debug_printf("end of filtering transport writing: yield=%d\n", yield);
1469 debug_printf(" errno=%d more_errno=%d\n", errno, tctx->addr->more_errno);
1479 /*************************************************
1480 * Update waiting database *
1481 *************************************************/
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.
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.
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.
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
1505 Old records should eventually get swept up by the exim_tidydb utility.
1508 hostlist list of hosts that this message could be sent to
1509 tpname name of the transport
1515 transport_update_waiting(host_item * hostlist, const uschar * tpname)
1517 const uschar * prevname = US"";
1518 open_db dbblock, * dbp;
1520 if (!is_new_message_id(message_id))
1522 DEBUG(D_transport) debug_printf("message_id %s is not new format; "
1523 "skipping wait-%s database update\n", message_id, tpname);
1527 DEBUG(D_transport) debug_printf("updating wait-%s database\n", tpname);
1529 /* Open the database (or transaction) for this transport */
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))
1538 /* Scan the list of hosts for which this message is waiting, and ensure
1539 that the message id is in each host record. */
1541 for (host_item * host = hostlist; host; host = host->next)
1543 BOOL already = FALSE;
1544 dbdata_wait * host_record;
1548 /* Skip if this is the same host as we just processed; otherwise remember
1549 the name for next time. */
1551 if (Ustrcmp(prevname, host->name) == 0) continue;
1552 prevname = host->name;
1554 /* Look up the host record; if there isn't one, make an empty one. */
1556 if (!(host_record = dbfn_read(dbp, host->name)))
1558 host_record = store_get(sizeof(dbdata_wait) + MESSAGE_ID_LENGTH, GET_UNTAINTED);
1559 host_record->count = host_record->sequence = 0;
1562 /* Compute the current length */
1564 host_length = host_record->count * MESSAGE_ID_LENGTH;
1566 /* Search the record to see if the current message is already in it. */
1568 for (uschar * s = host_record->text; s < host_record->text + host_length;
1569 s += MESSAGE_ID_LENGTH)
1571 /* If any ID is seen which is not new-format, wipe the record and
1572 any continuations */
1574 if (!is_new_message_id(s))
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);
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));
1585 host_record->count = host_record->sequence = 0;
1588 if (Ustrncmp(s, message_id, MESSAGE_ID_LENGTH) == 0)
1589 { already = TRUE; break; }
1592 /* If we haven't found this message in the main record, search any
1593 continuation records that exist. */
1595 for (int i = host_record->sequence - 1; i >= 0 && !already; i--)
1598 sprintf(CS buffer, "%.200s:%d", host->name, i);
1599 if ((cont = dbfn_read(dbp, buffer)))
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; }
1608 /* If this message is already in a record, no need to update. */
1612 DEBUG(D_transport) debug_printf("already listed for %s\n", host->name);
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. */
1622 if (host_record->count >= WAIT_NAME_MAX)
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);
1630 host_record->sequence++;
1631 host_record->count = 0;
1635 /* If this record is not full, increase the size of the record to
1636 allow for one new message id. */
1641 store_get(sizeof(dbdata_wait) + host_length + MESSAGE_ID_LENGTH, GET_UNTAINTED);
1642 memcpy(newr, host_record, sizeof(dbdata_wait) + host_length);
1646 /* Now add the new name on the end */
1648 memcpy(host_record->text + host_length, message_id, MESSAGE_ID_LENGTH);
1649 host_record->count++;
1650 host_length += MESSAGE_ID_LENGTH;
1652 /* Update the database */
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);
1661 if (continue_wait_db)
1662 dbfn_transaction_commit(dbp);
1670 /*************************************************
1671 * Test for waiting messages *
1672 *************************************************/
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.
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
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
1695 Returns: TRUE if new_message_id set; FALSE otherwise
1698 typedef struct msgq_s
1700 uschar message_id [MESSAGE_ID_LENGTH + 1];
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)
1709 dbdata_wait * host_record;
1711 open_db dbblock, * dbp;
1714 struct stat statbuf;
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);
1724 /* Do nothing if we have hit the maximum number that can be sent down one
1727 if (connection_max_messages >= 0) local_message_max = connection_max_messages;
1728 if (local_message_max > 0 && continue_sequence >= local_message_max)
1731 debug_printf_indent("max messages for one connection reached: returning\n");
1735 /* Open the waiting information database. */
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))
1744 debug_printf_indent("no messages waiting for %s\n", hostname);
1748 /* See if there is a record for this host; if not, there's nothing to do. */
1750 if (!(host_record = dbfn_read(dbp, hostname)))
1753 debug_printf_indent("no messages waiting for %s\n", hostname);
1757 /* If the data in the record looks corrupt, just log something and
1758 don't try to use it. */
1760 if (host_record->count > WAIT_NAME_MAX)
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);
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.
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. */
1776 host_length = host_record->count * MESSAGE_ID_LENGTH;
1781 int msgq_count = 0, msgq_actual = 0;
1782 BOOL bFound = FALSE, bContinuation = FALSE;
1784 /* create an array to read entire message queue into memory for processing */
1786 msgq = store_get(sizeof(msgq_t) * host_record->count, GET_UNTAINTED);
1787 msgq_actual = msgq_count = host_record->count;
1789 for (i = 0; i < host_record->count; ++i)
1791 /* If any ID is seen which is not new-format, wipe the record and
1792 any continuations */
1794 if (!is_new_message_id(host_record->text + (i * MESSAGE_ID_LENGTH)))
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));
1806 msgq[i].bKeep = TRUE;
1808 Ustrncpy_nt(msgq[i].message_id, host_record->text + (i * MESSAGE_ID_LENGTH),
1810 msgq[i].message_id[MESSAGE_ID_LENGTH] = 0;
1813 /* first thing remove current message id if it exists */
1814 /*XXX but what if it has un-sent addrs? */
1816 for (i = 0; i < msgq_count; ++i)
1817 if (Ustrcmp(msgq[i].message_id, message_id) == 0)
1819 msgq[i].bKeep = FALSE;
1823 /* now find the next acceptable message_id */
1825 for (i = 0; i < msgq_count; i++) if (msgq[i].bKeep)
1828 uschar * mid = msgq[i].message_id;
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))
1835 Ustrcpy_nt(new_message_id, mid);
1836 msgq[i].bKeep = FALSE;
1843 for (msgq_actual = 0, i = 0; i < msgq_count; ++i)
1847 /* reassemble the host record, based on removed message ids, from in
1850 if (msgq_actual <= 0)
1853 host_record->count = 0;
1857 host_length = msgq_actual * MESSAGE_ID_LENGTH;
1858 host_record->count = msgq_actual;
1860 if (msgq_actual < msgq_count)
1863 for (new_count = 0, i = 0; i < msgq_count; ++i)
1865 Ustrncpy(&host_record->text[new_count++ * MESSAGE_ID_LENGTH],
1866 msgq[i].message_id, MESSAGE_ID_LENGTH);
1868 host_record->text[new_count * MESSAGE_ID_LENGTH] = 0;
1872 /* Check for a continuation record. */
1874 while (host_length <= 0)
1876 dbdata_wait * newr = NULL;
1879 /* Search for a continuation */
1881 for (int i = host_record->sequence - 1; i >= 0 && !newr; i--)
1883 sprintf(CS buffer, "%.200s:%d", hostname, i);
1884 newr = dbfn_read(dbp, buffer);
1887 /* If no continuation, delete the current and break the loop */
1891 dbfn_delete(dbp, hostname);
1895 /* Else replace the current with the continuation */
1897 dbfn_delete(dbp, buffer);
1899 host_length = host_record->count * MESSAGE_ID_LENGTH;
1901 bContinuation = TRUE;
1904 if (bFound) /* Usual exit from main loop */
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. */
1911 if (host_length <= 0)
1913 DEBUG(D_transport) debug_printf_indent("waiting messages already delivered\n");
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.
1923 Ustrcpy(new_message_id, message_id);
1926 } /* we need to process a continuation record */
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. */
1933 if (host_length > 0)
1935 host_record->count = host_length/MESSAGE_ID_LENGTH;
1936 dbfn_write(dbp, hostname, host_record, (int)sizeof(dbdata_wait) + host_length);
1939 if (continue_wait_db)
1940 dbfn_transaction_commit(dbp);
1947 debug_printf("transport_check_waiting: TRUE (found %s)\n", new_message_id);
1952 if (continue_wait_db)
1953 dbfn_transaction_commit(dbp);
1959 {acl_level--; debug_printf("transport_check_waiting: FALSE\n"); }
1963 /*************************************************
1964 * Deliver waiting message down same socket *
1965 *************************************************/
1967 /* Just the regain-root-privilege exec portion */
1969 transport_do_pass_socket(const uschar * transport_name, const uschar * hostname,
1970 const uschar * hostaddress, uschar * id, int socket_fd)
1973 const uschar **argv;
1976 if (smtp_peer_options & OPTION_TLS) i += 6;
1978 #ifndef DISABLE_ESMTP_LIMITS
1979 if (continue_limit_mail || continue_limit_rcpt || continue_limit_rcptdom)
1982 if (queue_run_pid != (pid_t)0) i += 3;
1983 #ifdef SUPPORT_SOCKS
1984 if (proxy_session) i += 5;
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. */
1990 argv = CUSS child_exec_exim(CEE_RETURN_ARGV, TRUE, &i, FALSE, 0);
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";
1998 if (smtp_peer_options & OPTION_TLS)
1999 if (tls_out.active.sock >= 0 || continue_proxy_cipher)
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;
2010 tls_out.dane_verified ? US"-MCr" :
2013 argv[i++] = tls_out.sni;
2017 argv[i++] = US"-MCT";
2020 #ifndef DISABLE_ESMTP_LIMITS
2021 if (continue_limit_mail || continue_limit_rcpt || continue_limit_rcptdom)
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);
2030 if (queue_run_pid != (pid_t)0)
2032 argv[i++] = US"-MCQ";
2033 argv[i++] = string_sprintf("%d", queue_run_pid);
2034 argv[i++] = string_sprintf("%d", queue_run_pipe);
2037 #ifdef SUPPORT_SOCKS
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);
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);
2056 /* Arrange for the channel to be on stdin. */
2060 (void)dup2(socket_fd, 0);
2061 (void)close(socket_fd);
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);
2069 DEBUG(D_any) debug_printf("execv failed: %s\n", strerror(errno));
2070 _exit(errno); /* Note: must be _exit(), NOT exit() */
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. */
2082 arg_is_tainted(const uschar * s, int argn, address_item * addr,
2083 const uschar * etext, uschar ** errptr)
2087 uschar * msg = string_sprintf("Tainted arg %d for %s command: '%s'",
2091 addr->transport_return = FAIL;
2092 addr->message = msg;
2101 /*************************************************
2102 * Set up direct (non-shell) command *
2103 *************************************************/
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.
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
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
2123 Returns: TRUE if all went well; otherwise an error will be
2124 set in the first address and FALSE returned
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)
2132 const uschar ** argv, * s;
2133 int address_count = 0, argcount = 0, max_args;
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. */
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);
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. */
2150 Uskip_whitespace(&s);
2152 for (; *s && argcount < max_args; argcount++)
2156 int n = Ustrcspn(++s, "'");
2157 argv[argcount] = string_copyn(s, n);
2158 if (*(s += n) == '\'') s++;
2161 argv[argcount] = string_dequote(CUSS &s);
2162 Uskip_whitespace(&s);
2165 argv[argcount] = NULL;
2167 /* If *s != 0 we have run out of argument slots. */
2171 uschar *msg = string_sprintf("Too many arguments in command \"%s\" in "
2175 addr->transport_return = FAIL;
2176 addr->message = msg;
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.
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.
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
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]));
2205 if (flags & TSUC_EXPAND_ARGS)
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? */
2210 for (int i = 0; argv[i]; i++)
2212 DEBUG(D_expand) debug_printf_indent("arg %d\n", i);
2214 /* Handle special fudge for passing an address list */
2217 (Ustrcmp(argv[i], "$pipe_addresses") == 0 ||
2218 Ustrcmp(argv[i], "${pipe_addresses}") == 0))
2222 if (argcount + address_count - 1 > max_args)
2224 addr->transport_return = FAIL;
2225 addr->message = string_sprintf("Too many arguments to command \"%s\" "
2226 "in %s", cmd, etext);
2230 additional = address_count - 1;
2232 memmove(argv + i + 1 + additional, argv + i + 1,
2233 (argcount - i)*sizeof(uschar *));
2235 for (address_item * ad = addr; ad; ad = ad->next)
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. */
2244 DEBUG(D_transport) if (is_tainted(ad->address))
2245 debug_printf("tainted element '%s' from $pipe_addresses\n", ad->address);
2247 argv[i++] = ad->address;
2251 /* Subtract one since we replace $pipe_addresses */
2256 /* Handle special case of $address_pipe when af_force_command is set */
2258 else if (addr && testflag(addr,af_force_command) &&
2259 (Ustrcmp(argv[i], "$address_pipe") == 0 ||
2260 Ustrcmp(argv[i], "${address_pipe}") == 0))
2262 int address_pipe_argcount = 0;
2263 int address_pipe_max_args;
2264 uschar **address_pipe_argv;
2266 /* We can never have more then the argv we will be loading into */
2267 address_pipe_max_args = max_args - argcount + 1;
2270 debug_printf("address_pipe_max_args=%d\n", address_pipe_max_args);
2272 /* We allocate an additional for (uschar *)0 */
2273 address_pipe_argv = store_get((address_pipe_max_args+1)*sizeof(uschar *), GET_UNTAINTED);
2275 /* +1 because addr->local_part[0] == '|' since af_force_command is set */
2276 s = expand_cstring(addr->local_part + 1);
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);
2287 Uskip_whitespace(&s); /* strip leading space */
2289 while (*s && address_pipe_argcount < address_pipe_max_args)
2293 int n = Ustrcspn(++s, "'");
2294 argv[argcount] = string_copyn(s, n);
2295 if (*(s += n) == '\'') s++;
2298 address_pipe_argv[address_pipe_argcount++] = string_dequote(CUSS &s);
2299 Uskip_whitespace(&s); /* strip space after arg */
2302 address_pipe_argv[address_pipe_argcount] = NULL;
2304 /* If *s != 0 we have run out of argument slots. */
2307 uschar *msg = string_sprintf("Too many arguments in $address_pipe "
2308 "\"%s\" in %s", addr->local_part + 1, etext);
2311 addr->transport_return = FAIL;
2312 addr->message = msg;
2318 /* address_pipe_argcount - 1
2319 because we are replacing $address_pipe in the argument list
2320 with the first thing it expands to */
2322 if (argcount + address_pipe_argcount - 1 > max_args)
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);
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] */
2337 if (address_pipe_argcount > 1)
2339 /* current position + additional args */
2340 argv + i + address_pipe_argcount,
2341 /* current position + 1 (for the (uschar *)0 at the end) */
2343 /* -1 for the (uschar *)0 at the end)*/
2344 (argcount - i)*sizeof(uschar *)
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] */
2350 for (int address_pipe_i = 0;
2351 address_pipe_argv[address_pipe_i];
2352 address_pipe_i++, argcount++)
2354 uschar * s = address_pipe_argv[address_pipe_i];
2355 if (arg_is_tainted(s, i, addr, etext, errptr)) return FALSE;
2359 /* Subtract one since we replace $address_pipe */
2364 /* Handle normal expansion string */
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;
2376 uschar *msg = string_sprintf("Expansion of \"%s\" "
2377 "from command \"%s\" in %s failed: %s",
2378 argv[i], cmd, etext, expand_string_message);
2381 addr->transport_return = expand_failed;
2382 addr->message = msg;
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 */
2392 debug_printf("SPECIFIC TESTSUITE EXEMPTION: tainted arg '%s'\n",
2395 else if ( !(flags & TSUC_ALLOW_TAINTED_ARGS)
2396 && arg_is_tainted(expanded_arg, i, addr, etext, errptr))
2398 argv[i] = expanded_arg;
2404 debug_printf("direct command after expansion:\n");
2405 for (int i = 0; argv[i]; i++)
2407 debug_printf(" argv[%d] = '%s'\n", i, string_printing(argv[i]));
2408 debug_print_taint(argv[i]);
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 */
2423 transport_current_name(void)
2425 if (!transport_name) return NULL;
2426 return string_sprintf(" (transport %s, %s %d)", transport_name, driver_srcfile, driver_srcline);
2429 #endif /*!MACRO_PREDEF*/
2432 /* End of transport.c */