Commit message: Events: raise msg:fail:internal & msg:complete for -Mrm.  Bug 2310
CVE: CVE-2019-10149
CWE: CWE-78
Vulnerability description: A flaw was found in Exim versions 4.87 to 4.91 (inclusive). Improper validation of recipient address in deliver_message() function in /src/deliver.c may lead to remote command execution.

Project: exim
File: queue.c

queue_check_only(void)
{
int sep = 0;
struct stat statbuf;
const uschar *s;
uschar *ss;
uschar buffer[1024];

if (queue_only_file == NULL) return;

s = queue_only_file;
while ((ss = string_nextinlist(&s, &sep, buffer, sizeof(buffer))) != NULL)
  {
  if (Ustrncmp(ss, "smtp", 4) == 0)
    {
    ss += 4;
    if (Ustat(ss, &statbuf) == 0)
      {
      f.queue_smtp = TRUE;
      DEBUG(D_receive) debug_printf("queue_smtp set because %s exists\n", ss);
      }
    }
  else
    {
    if (Ustat(ss, &statbuf) == 0)
      {
      queue_only = TRUE;
      DEBUG(D_receive) debug_printf("queue_only set because %s exists\n", ss);
      }
    }
  }
}

Project: exim
File: queue.c

queue_count(void)
{
int subcount;
int count = 0;
queue_filename *f = NULL;
uschar subdirs[64];
f = queue_get_spool_list(
        -1,             /* entire queue */
        subdirs,        /* for holding sub list */
        &subcount,      /* for subcount */
        FALSE);         /* not random */
for (; f != NULL; f = f->next) count++;
fprintf(stdout, "%d\n", count);
}

Project: exim
File: deliver.c

par_read_pipe(int poffset, BOOL eop)
{
host_item *h;
pardata *p = parlist + poffset;
address_item *addrlist = p->addrlist;
address_item *addr = p->addr;
pid_t pid = p->pid;
int fd = p->fd;

uschar *msg = p->msg;
BOOL done = p->done;

/* Loop through all items, reading from the pipe when necessary. The pipe
used to be non-blocking. But I do not see a reason for using non-blocking I/O
here, as the preceding select() tells us, if data is available for reading.

A read() on a "selected" handle should never block, but(!) it may return
less data then we expected. (The buffer size we pass to read() shouldn't be
understood as a "request", but as a "limit".)

Each separate item is written to the pipe in a timely manner. But, especially for
larger items, the read(2) may already return partial data from the write(2).

The write is atomic mostly (depending on the amount written), but atomic does
not imply "all or noting", it just is "not intermixed" with other writes on the
same channel (pipe).

*/

DEBUG(D_deliver) debug_printf("reading pipe for subprocess %d (%s)\n",
  (int)p->pid, eop? "ended" : "not ended yet");

while (!done)
  {
  retry_item *r, **rp;
  uschar pipeheader[PIPE_HEADER_SIZE+1];
  uschar *id = &pipeheader[0];
  uschar *subid = &pipeheader[1];
  uschar *ptr = big_buffer;
  size_t required = PIPE_HEADER_SIZE; /* first the pipehaeder, later the data */
  ssize_t got;

  DEBUG(D_deliver) debug_printf(
    "expect %lu bytes (pipeheader) from tpt process %d\n", (u_long)required, pid);

  /* We require(!) all the PIPE_HEADER_SIZE bytes here, as we know,
  they're written in a timely manner, so waiting for the write shouldn't hurt a lot.
  If we get less, we can assume the subprocess do be done and do not expect any further
  information from it. */

  if ((got = readn(fd, pipeheader, required)) != required)
    {
    msg = string_sprintf("got " SSIZE_T_FMT " of %d bytes (pipeheader) "
      "from transport process %d for transport %s",
      got, PIPE_HEADER_SIZE, pid, addr->transport->driver_name);
    done = TRUE;
    break;
    }

  pipeheader[PIPE_HEADER_SIZE] = '\0';
  DEBUG(D_deliver)
    debug_printf("got %ld bytes (pipeheader) from transport process %d\n",
      (long) got, pid);

  {
  /* If we can't decode the pipeheader, the subprocess seems to have a
  problem, we do not expect any furher information from it. */
  char *endc;
  required = Ustrtol(pipeheader+2, &endc, 10);
  if (*endc)
    {
    msg = string_sprintf("failed to read pipe "
      "from transport process %d for transport %s: error decoding size from header",
      pid, addr->transport->driver_name);
    done = TRUE;
    break;
    }
  }

  DEBUG(D_deliver)
    debug_printf("expect %lu bytes (pipedata) from transport process %d\n",
      (u_long)required, pid);

  /* Same as above, the transport process will write the bytes announced
  in a timely manner, so we can just wait for the bytes, getting less than expected
  is considered a problem of the subprocess, we do not expect anything else from it. */
  if ((got = readn(fd, big_buffer, required)) != required)
    {
    msg = string_sprintf("got only " SSIZE_T_FMT " of " SIZE_T_FMT
      " bytes (pipedata) from transport process %d for transport %s",
      got, required, pid, addr->transport->driver_name);
    done = TRUE;
    break;
    }

  /* Handle each possible type of item, assuming the complete item is
  available in store. */

  switch (*id)
    {
    /* Host items exist only if any hosts were marked unusable. Match
    up by checking the IP address. */

    case 'H':
      for (h = addrlist->host_list; h; h = h->next)
	{
	if (!h->address || Ustrcmp(h->address, ptr+2) != 0) continue;
	h->status = ptr[0];
	h->why = ptr[1];
	}
      ptr += 2;
      while (*ptr++);
      break;

    /* Retry items are sent in a preceding R item for each address. This is
    kept separate to keep each message short enough to guarantee it won't
    be split in the pipe. Hopefully, in the majority of cases, there won't in
    fact be any retry items at all.

    The complete set of retry items might include an item to delete a
    routing retry if there was a previous routing delay. However, routing
    retries are also used when a remote transport identifies an address error.
    In that case, there may also be an "add" item for the same key. Arrange
    that a "delete" item is dropped in favour of an "add" item. */

    case 'R':
      if (!addr) goto ADDR_MISMATCH;

      DEBUG(D_deliver|D_retry)
	debug_printf("reading retry information for %s from subprocess\n",
	  ptr+1);

      /* Cut out any "delete" items on the list. */

      for (rp = &addr->retries; (r = *rp); rp = &r->next)
	if (Ustrcmp(r->key, ptr+1) == 0)           /* Found item with same key */
	  {
	  if (!(r->flags & rf_delete)) break;	   /* It was not "delete" */
	  *rp = r->next;                           /* Excise a delete item */
	  DEBUG(D_deliver|D_retry)
	    debug_printf("  existing delete item dropped\n");
	  }

      /* We want to add a delete item only if there is no non-delete item;
      however we still have to step ptr through the data. */

      if (!r || !(*ptr & rf_delete))
	{
	r = store_get(sizeof(retry_item));
	r->next = addr->retries;
	addr->retries = r;
	r->flags = *ptr++;
	r->key = string_copy(ptr);
	while (*ptr++);
	memcpy(&r->basic_errno, ptr, sizeof(r->basic_errno));
	ptr += sizeof(r->basic_errno);
	memcpy(&r->more_errno, ptr, sizeof(r->more_errno));
	ptr += sizeof(r->more_errno);
	r->message = *ptr ? string_copy(ptr) : NULL;
	DEBUG(D_deliver|D_retry) debug_printf("  added %s item\n",
	    r->flags & rf_delete ? "delete" : "retry");
	}

      else
	{
	DEBUG(D_deliver|D_retry)
	  debug_printf("  delete item not added: non-delete item exists\n");
	ptr++;
	while(*ptr++);
	ptr += sizeof(r->basic_errno) + sizeof(r->more_errno);
	}

      while(*ptr++);
      break;

    /* Put the amount of data written into the parlist block */

    case 'S':
      memcpy(&(p->transport_count), ptr, sizeof(transport_count));
      ptr += sizeof(transport_count);
      break;

    /* Address items are in the order of items on the address chain. We
    remember the current address value in case this function is called
    several times to empty the pipe in stages. Information about delivery
    over TLS is sent in a preceding X item for each address. We don't put
    it in with the other info, in order to keep each message short enough to
    guarantee it won't be split in the pipe. */

#ifdef SUPPORT_TLS
    case 'X':
      if (!addr) goto ADDR_MISMATCH;          /* Below, in 'A' handler */
      switch (*subid)
	{
	case '1':
	  addr->cipher = NULL;
	  addr->peerdn = NULL;

	  if (*ptr)
	    addr->cipher = string_copy(ptr);
	  while (*ptr++);
	  if (*ptr)
	    addr->peerdn = string_copy(ptr);
	  break;

	case '2':
	  if (*ptr)
	    (void) tls_import_cert(ptr, &addr->peercert);
	  else
	    addr->peercert = NULL;
	  break;

	case '3':
	  if (*ptr)
	    (void) tls_import_cert(ptr, &addr->ourcert);
	  else
	    addr->ourcert = NULL;
	  break;

# ifndef DISABLE_OCSP
	case '4':
	  addr->ocsp = *ptr ? *ptr - '0' : OCSP_NOT_REQ;
	  break;
# endif
	}
      while (*ptr++);
      break;
#endif	/*SUPPORT_TLS*/

    case 'C':	/* client authenticator information */
      switch (*subid)
	{
	case '1': addr->authenticator = *ptr ? string_copy(ptr) : NULL; break;
	case '2': addr->auth_id = *ptr ? string_copy(ptr) : NULL;	break;
	case '3': addr->auth_sndr = *ptr ? string_copy(ptr) : NULL;	break;
	}
      while (*ptr++);
      break;

#ifndef DISABLE_PRDR
    case 'P':
      setflag(addr, af_prdr_used);
      break;
#endif

    case 'L':
      switch (*subid)
	{
	case 1: setflag(addr, af_pipelining); break;
	}
      break;

    case 'K':
      setflag(addr, af_chunking_used);
      break;

    case 'T':
      setflag(addr, af_tcp_fastopen_conn);
      if (*subid > '0') setflag(addr, af_tcp_fastopen);
      break;

    case 'D':
      if (!addr) goto ADDR_MISMATCH;
      memcpy(&(addr->dsn_aware), ptr, sizeof(addr->dsn_aware));
      ptr += sizeof(addr->dsn_aware);
      DEBUG(D_deliver) debug_printf("DSN read: addr->dsn_aware = %d\n", addr->dsn_aware);
      break;

    case 'A':
      if (!addr)
	{
	ADDR_MISMATCH:
	msg = string_sprintf("address count mismatch for data read from pipe "
	  "for transport process %d for transport %s", pid,
	    addrlist->transport->driver_name);
	done = TRUE;
	break;
	}

      switch (*subid)
	{
  #ifdef SUPPORT_SOCKS
	case '2':	/* proxy information; must arrive before A0 and applies to that addr XXX oops*/
	  proxy_session = TRUE;	/*XXX should this be cleared somewhere? */
	  if (*ptr == 0)
	    ptr++;
	  else
	    {
	    proxy_local_address = string_copy(ptr);
	    while(*ptr++);
	    memcpy(&proxy_local_port, ptr, sizeof(proxy_local_port));
	    ptr += sizeof(proxy_local_port);
	    }
	  break;
  #endif

  #ifdef EXPERIMENTAL_DSN_INFO
	case '1':	/* must arrive before A0, and applies to that addr */
			/* Two strings: smtp_greeting and helo_response */
	  addr->smtp_greeting = string_copy(ptr);
	  while(*ptr++);
	  addr->helo_response = string_copy(ptr);
	  while(*ptr++);
	  break;
  #endif

	case '0':
	  DEBUG(D_deliver) debug_printf("A0 %s tret %d\n", addr->address, *ptr);
	  addr->transport_return = *ptr++;
	  addr->special_action = *ptr++;
	  memcpy(&addr->basic_errno, ptr, sizeof(addr->basic_errno));
	  ptr += sizeof(addr->basic_errno);
	  memcpy(&addr->more_errno, ptr, sizeof(addr->more_errno));
	  ptr += sizeof(addr->more_errno);
	  memcpy(&addr->delivery_usec, ptr, sizeof(addr->delivery_usec));
	  ptr += sizeof(addr->delivery_usec);
	  memcpy(&addr->flags, ptr, sizeof(addr->flags));
	  ptr += sizeof(addr->flags);
	  addr->message = *ptr ? string_copy(ptr) : NULL;
	  while(*ptr++);
	  addr->user_message = *ptr ? string_copy(ptr) : NULL;
	  while(*ptr++);

	  /* Always two strings for host information, followed by the port number and DNSSEC mark */

	  if (*ptr)
	    {
	    h = store_get(sizeof(host_item));
	    h->name = string_copy(ptr);
	    while (*ptr++);
	    h->address = string_copy(ptr);
	    while(*ptr++);
	    memcpy(&h->port, ptr, sizeof(h->port));
	    ptr += sizeof(h->port);
	    h->dnssec = *ptr == '2' ? DS_YES
		      : *ptr == '1' ? DS_NO
		      : DS_UNK;
	    ptr++;
	    addr->host_used = h;
	    }
	  else ptr++;

	  /* Finished with this address */

	  addr = addr->next;
	  break;
	}
      break;

    /* Local interface address/port */
    case 'I':
      if (*ptr) sending_ip_address = string_copy(ptr);
      while (*ptr++) ;
      if (*ptr) sending_port = atoi(CS ptr);
      while (*ptr++) ;
      break;

    /* Z marks the logical end of the data. It is followed by '0' if
    continue_transport was NULL at the end of transporting, otherwise '1'.
    We need to know when it becomes NULL during a delivery down a passed SMTP
    channel so that we don't try to pass anything more down it. Of course, for
    most normal messages it will remain NULL all the time. */

    case 'Z':
      if (*ptr == '0')
	{
	continue_transport = NULL;
	continue_hostname = NULL;
	}
      done = TRUE;
      DEBUG(D_deliver) debug_printf("Z0%c item read\n", *ptr);
      break;

    /* Anything else is a disaster. */

    default:
      msg = string_sprintf("malformed data (%d) read from pipe for transport "
	"process %d for transport %s", ptr[-1], pid,
	  addr->transport->driver_name);
      done = TRUE;
      break;
    }
  }

/* The done flag is inspected externally, to determine whether or not to
call the function again when the process finishes. */

p->done = done;

/* If the process hadn't finished, and we haven't seen the end of the data
or if we suffered a disaster, update the rest of the state, and return FALSE to
indicate "not finished". */

if (!eop && !done)
  {
  p->addr = addr;
  p->msg = msg;
  return FALSE;
  }

/* Close our end of the pipe, to prevent deadlock if the far end is still
pushing stuff into it. */

(void)close(fd);
p->fd = -1;

/* If we have finished without error, but haven't had data for every address,
something is wrong. */

if (!msg && addr)
  msg = string_sprintf("insufficient address data read from pipe "
    "for transport process %d for transport %s", pid,
      addr->transport->driver_name);

/* If an error message is set, something has gone wrong in getting back
the delivery data. Put the message into each address and freeze it. */

if (msg)
  for (addr = addrlist; addr; addr = addr->next)
    {
    addr->transport_return = DEFER;
    addr->special_action = SPECIAL_FREEZE;
    addr->message = msg;
    log_write(0, LOG_MAIN|LOG_PANIC, "Delivery status for %s: %s\n", addr->address, addr->message);
    }

/* Return TRUE to indicate we have got all we need from this process, even
if it hasn't actually finished yet. */

return TRUE;
}

Project: exim
File: queue.c

queue_get_spool_list(int subdiroffset, uschar *subdirs, int *subcount,
  BOOL randomize)
{
int i;
int flags = 0;
int resetflags = -1;
int subptr;
queue_filename *yield = NULL;
queue_filename *last = NULL;
struct dirent *ent;
DIR *dd;
uschar buffer[256];
queue_filename *root[LOG2_MAXNODES];

/* When randomizing, the file names are added to the start or end of the list
according to the bits of the flags variable. Get a collection of bits from the
current time. Use the bottom 16 and just keep re-using them if necessary. When
not randomizing, initialize the sublists for the bottom-up merge sort. */

if (randomize)
  resetflags = time(NULL) & 0xFFFF;
else
   for (i = 0; i < LOG2_MAXNODES; i++)
     root[i] = NULL;

/* If processing the full queue, or just the top-level, start at the base
directory, and initialize the first subdirectory name (as none). Otherwise,
start at the sub-directory offset. */

if (subdiroffset <= 0)
  {
  i = 0;
  subdirs[0] = 0;
  *subcount = 0;
  }
else
  i = subdiroffset;

/* Set up prototype for the directory name. */

spool_pname_buf(buffer, sizeof(buffer));
buffer[sizeof(buffer) - 3] = 0;
subptr = Ustrlen(buffer);
buffer[subptr+2] = 0;               /* terminator for lengthened name */

/* This loop runs at least once, for the main or given directory, and then as
many times as necessary to scan any subdirectories encountered in the main
directory, if they are to be scanned at this time. */

for (; i <= *subcount; i++)
  {
  int count = 0;
  int subdirchar = subdirs[i];      /* 0 for main directory */

  if (subdirchar != 0)
    {
    buffer[subptr] = '/';
    buffer[subptr+1] = subdirchar;
    }

  DEBUG(D_queue_run) debug_printf("looking in %s\n", buffer);
  if (!(dd = opendir(CS buffer)))
    continue;

  /* Now scan the directory. */

  while ((ent = readdir(dd)))
    {
    uschar *name = US ent->d_name;
    int len = Ustrlen(name);

    /* Count entries */

    count++;

    /* If we find a single alphameric sub-directory in the base directory,
    add it to the list for subsequent scans. */

    if (i == 0 && len == 1 && isalnum(*name))
      {
      *subcount = *subcount + 1;
      subdirs[*subcount] = *name;
      continue;
      }

    /* Otherwise, if it is a header spool file, add it to the list */

    if (len == SPOOL_NAME_LENGTH &&
        Ustrcmp(name + SPOOL_NAME_LENGTH - 2, "-H") == 0)
      {
      queue_filename *next =
        store_get(sizeof(queue_filename) + Ustrlen(name));
      Ustrcpy(next->text, name);
      next->dir_uschar = subdirchar;

      /* Handle the creation of a randomized list. The first item becomes both
      the top and bottom of the list. Subsequent items are inserted either at
      the top or the bottom, randomly. This is, I argue, faster than doing a
      sort by allocating a random number to each item, and it also saves having
      to store the number with each item. */

      if (randomize)
        if (!yield)
          {
          next->next = NULL;
          yield = last = next;
          }
        else
          {
          if (flags == 0)
	    flags = resetflags;
          if ((flags & 1) == 0)
            {
            next->next = yield;
            yield = next;
            }
          else
            {
            next->next = NULL;
            last->next = next;
            last = next;
            }
          flags = flags >> 1;
          }

      /* Otherwise do a bottom-up merge sort based on the name. */

      else
        {
        int j;
        next->next = NULL;
        for (j = 0; j < LOG2_MAXNODES; j++)
          if (root[j])
            {
            next = merge_queue_lists(next, root[j]);
            root[j] = j == LOG2_MAXNODES - 1 ? next : NULL;
            }
          else
            {
            root[j] = next;
            break;
            }
        }
      }
    }

  /* Finished with this directory */

  closedir(dd);

  /* If we have just scanned a sub-directory, and it was empty (count == 2
  implies just "." and ".." entries), and Exim is no longer configured to
  use sub-directories, attempt to get rid of it. At the same time, try to
  get rid of any corresponding msglog subdirectory. These are just cosmetic
  tidying actions, so just ignore failures. If we are scanning just a single
  sub-directory, break the loop. */

  if (i != 0)
    {
    if (!split_spool_directory && count <= 2)
      {
      uschar subdir[2];

      rmdir(CS buffer);
      subdir[0] = subdirchar; subdir[1] = 0;
      rmdir(CS spool_dname(US"msglog", subdir));
      }
    if (subdiroffset > 0) break;    /* Single sub-directory */
    }

  /* If we have just scanned the base directory, and subdiroffset is 0,
  we do not want to continue scanning the sub-directories. */

  else if (subdiroffset == 0)
    break;
  }    /* Loop for multiple subdirectories */

/* When using a bottom-up merge sort, do the final merging of the sublists.
Then pass back the final list of file items. */

if (!randomize)
  for (i = 0; i < LOG2_MAXNODES; ++i)
    yield = merge_queue_lists(yield, root[i]);

return yield;
}

Project: exim
File: deliver.c

deliver_message(uschar *id, BOOL forced, BOOL give_up)
{
int i, rc;
int final_yield = DELIVER_ATTEMPTED_NORMAL;
time_t now = time(NULL);
address_item *addr_last = NULL;
uschar *filter_message = NULL;
int process_recipients = RECIP_ACCEPT;
open_db dbblock;
open_db *dbm_file;
extern int acl_where;

uschar *info = queue_run_pid == (pid_t)0
  ? string_sprintf("delivering %s", id)
  : string_sprintf("delivering %s (queue run pid %d)", id, queue_run_pid);

/* If the D_process_info bit is on, set_process_info() will output debugging
information. If not, we want to show this initial information if D_deliver or
D_queue_run is set or in verbose mode. */

set_process_info("%s", info);

if (  !(debug_selector & D_process_info)
   && (debug_selector & (D_deliver|D_queue_run|D_v))
   )
  debug_printf("%s\n", info);

/* Ensure that we catch any subprocesses that are created. Although Exim
sets SIG_DFL as its initial default, some routes through the code end up
here with it set to SIG_IGN - cases where a non-synchronous delivery process
has been forked, but no re-exec has been done. We use sigaction rather than
plain signal() on those OS where SA_NOCLDWAIT exists, because we want to be
sure it is turned off. (There was a problem on AIX with this.) */

#ifdef SA_NOCLDWAIT
  {
  struct sigaction act;
  act.sa_handler = SIG_DFL;
  sigemptyset(&(act.sa_mask));
  act.sa_flags = 0;
  sigaction(SIGCHLD, &act, NULL);
  }
#else
signal(SIGCHLD, SIG_DFL);
#endif

/* Make the forcing flag available for routers and transports, set up the
global message id field, and initialize the count for returned files and the
message size. This use of strcpy() is OK because the length id is checked when
it is obtained from a command line (the -M or -q options), and otherwise it is
known to be a valid message id. */

Ustrcpy(message_id, id);
f.deliver_force = forced;
return_count = 0;
message_size = 0;

/* Initialize some flags */

update_spool = FALSE;
remove_journal = TRUE;

/* Set a known context for any ACLs we call via expansions */
acl_where = ACL_WHERE_DELIVERY;

/* Reset the random number generator, so that if several delivery processes are
started from a queue runner that has already used random numbers (for sorting),
they don't all get the same sequence. */

random_seed = 0;

/* Open and lock the message's data file. Exim locks on this one because the
header file may get replaced as it is re-written during the delivery process.
Any failures cause messages to be written to the log, except for missing files
while queue running - another process probably completed delivery. As part of
opening the data file, message_subdir gets set. */

if ((deliver_datafile = spool_open_datafile(id)) < 0)
  return continue_closedown();  /* yields DELIVER_NOT_ATTEMPTED */

/* The value of message_size at this point has been set to the data length,
plus one for the blank line that notionally precedes the data. */

/* Now read the contents of the header file, which will set up the headers in
store, and also the list of recipients and the tree of non-recipients and
assorted flags. It updates message_size. If there is a reading or format error,
give up; if the message has been around for sufficiently long, remove it. */

  {
  uschar * spoolname = string_sprintf("%s-H", id);
  if ((rc = spool_read_header(spoolname, TRUE, TRUE)) != spool_read_OK)
    {
    if (errno == ERRNO_SPOOLFORMAT)
      {
      struct stat statbuf;
      if (Ustat(spool_fname(US"input", message_subdir, spoolname, US""),
		&statbuf) == 0)
	log_write(0, LOG_MAIN, "Format error in spool file %s: "
	  "size=" OFF_T_FMT, spoolname, statbuf.st_size);
      else
	log_write(0, LOG_MAIN, "Format error in spool file %s", spoolname);
      }
    else
      log_write(0, LOG_MAIN, "Error reading spool file %s: %s", spoolname,
	strerror(errno));

    /* If we managed to read the envelope data, received_time contains the
    time the message was received. Otherwise, we can calculate it from the
    message id. */

    if (rc != spool_read_hdrerror)
      {
      received_time.tv_sec = received_time.tv_usec = 0;
      /*XXX subsec precision?*/
      for (i = 0; i < 6; i++)
	received_time.tv_sec = received_time.tv_sec * BASE_62 + tab62[id[i] - '0'];
      }

    /* If we've had this malformed message too long, sling it. */

    if (now - received_time.tv_sec > keep_malformed)
      {
      Uunlink(spool_fname(US"msglog", message_subdir, id, US""));
      Uunlink(spool_fname(US"input", message_subdir, id, US"-D"));
      Uunlink(spool_fname(US"input", message_subdir, id, US"-H"));
      Uunlink(spool_fname(US"input", message_subdir, id, US"-J"));
      log_write(0, LOG_MAIN, "Message removed because older than %s",
	readconf_printtime(keep_malformed));
      }

    (void)close(deliver_datafile);
    deliver_datafile = -1;
    return continue_closedown();   /* yields DELIVER_NOT_ATTEMPTED */
    }
  }

/* The spool header file has been read. Look to see if there is an existing
journal file for this message. If there is, it means that a previous delivery
attempt crashed (program or host) before it could update the spool header file.
Read the list of delivered addresses from the journal and add them to the
nonrecipients tree. Then update the spool file. We can leave the journal in
existence, as it will get further successful deliveries added to it in this
run, and it will be deleted if this function gets to its end successfully.
Otherwise it might be needed again. */

  {
  uschar * fname = spool_fname(US"input", message_subdir, id, US"-J");
  FILE * jread;

  if (  (journal_fd = Uopen(fname, O_RDWR|O_APPEND
#ifdef O_CLOEXEC
				    | O_CLOEXEC
#endif
#ifdef O_NOFOLLOW
				    | O_NOFOLLOW
#endif
	, SPOOL_MODE)) >= 0
     && lseek(journal_fd, 0, SEEK_SET) == 0
     && (jread = fdopen(journal_fd, "rb"))
     )
    {
    while (Ufgets(big_buffer, big_buffer_size, jread))
      {
      int n = Ustrlen(big_buffer);
      big_buffer[n-1] = 0;
      tree_add_nonrecipient(big_buffer);
      DEBUG(D_deliver) debug_printf("Previously delivered address %s taken from "
	"journal file\n", big_buffer);
      }
    rewind(jread);
    if ((journal_fd = dup(fileno(jread))) < 0)
      journal_fd = fileno(jread);
    else
      (void) fclose(jread);	/* Try to not leak the FILE resource */

    /* Panic-dies on error */
    (void)spool_write_header(message_id, SW_DELIVERING, NULL);
    }
  else if (errno != ENOENT)
    {
    log_write(0, LOG_MAIN|LOG_PANIC, "attempt to open journal for reading gave: "
      "%s", strerror(errno));
    return continue_closedown();   /* yields DELIVER_NOT_ATTEMPTED */
    }

  /* A null recipients list indicates some kind of disaster. */

  if (!recipients_list)
    {
    (void)close(deliver_datafile);
    deliver_datafile = -1;
    log_write(0, LOG_MAIN, "Spool error: no recipients for %s", fname);
    return continue_closedown();   /* yields DELIVER_NOT_ATTEMPTED */
    }
  }


/* Handle a message that is frozen. There are a number of different things that
can happen, but in the default situation, unless forced, no delivery is
attempted. */

if (f.deliver_freeze)
  {
#ifdef SUPPORT_MOVE_FROZEN_MESSAGES
  /* Moving to another directory removes the message from Exim's view. Other
  tools must be used to deal with it. Logging of this action happens in
  spool_move_message() and its subfunctions. */

  if (  move_frozen_messages
     && spool_move_message(id, message_subdir, US"", US"F")
     )
    return continue_closedown();   /* yields DELIVER_NOT_ATTEMPTED */
#endif

  /* For all frozen messages (bounces or not), timeout_frozen_after sets the
  maximum time to keep messages that are frozen. Thaw if we reach it, with a
  flag causing all recipients to be failed. The time is the age of the
  message, not the time since freezing. */

  if (timeout_frozen_after > 0 && message_age >= timeout_frozen_after)
    {
    log_write(0, LOG_MAIN, "cancelled by timeout_frozen_after");
    process_recipients = RECIP_FAIL_TIMEOUT;
    }

  /* For bounce messages (and others with no sender), thaw if the error message
  ignore timer is exceeded. The message will be discarded if this delivery
  fails. */

  else if (!*sender_address && message_age >= ignore_bounce_errors_after)
    log_write(0, LOG_MAIN, "Unfrozen by errmsg timer");

  /* If this is a bounce message, or there's no auto thaw, or we haven't
  reached the auto thaw time yet, and this delivery is not forced by an admin
  user, do not attempt delivery of this message. Note that forced is set for
  continuing messages down the same channel, in order to skip load checking and
  ignore hold domains, but we don't want unfreezing in that case. */

  else
    {
    if (  (  sender_address[0] == 0
	  || auto_thaw <= 0
	  || now <= deliver_frozen_at + auto_thaw
          )
       && (  !forced || !f.deliver_force_thaw
	  || !f.admin_user || continue_hostname
       )  )
      {
      (void)close(deliver_datafile);
      deliver_datafile = -1;
      log_write(L_skip_delivery, LOG_MAIN, "Message is frozen");
      return continue_closedown();   /* yields DELIVER_NOT_ATTEMPTED */
      }

    /* If delivery was forced (by an admin user), assume a manual thaw.
    Otherwise it's an auto thaw. */

    if (forced)
      {
      f.deliver_manual_thaw = TRUE;
      log_write(0, LOG_MAIN, "Unfrozen by forced delivery");
      }
    else log_write(0, LOG_MAIN, "Unfrozen by auto-thaw");
    }

  /* We get here if any of the rules for unfreezing have triggered. */

  f.deliver_freeze = FALSE;
  update_spool = TRUE;
  }


/* Open the message log file if we are using them. This records details of
deliveries, deferments, and failures for the benefit of the mail administrator.
The log is not used by exim itself to track the progress of a message; that is
done by rewriting the header spool file. */

if (message_logs)
  {
  uschar * fname = spool_fname(US"msglog", message_subdir, id, US"");
  uschar * error;
  int fd;

  if ((fd = open_msglog_file(fname, SPOOL_MODE, &error)) < 0)
    {
    log_write(0, LOG_MAIN|LOG_PANIC, "Couldn't %s message log %s: %s", error,
      fname, strerror(errno));
    return continue_closedown();   /* yields DELIVER_NOT_ATTEMPTED */
    }

  /* Make a C stream out of it. */

  if (!(message_log = fdopen(fd, "a")))
    {
    log_write(0, LOG_MAIN|LOG_PANIC, "Couldn't fdopen message log %s: %s",
      fname, strerror(errno));
    return continue_closedown();   /* yields DELIVER_NOT_ATTEMPTED */
    }
  }


/* If asked to give up on a message, log who did it, and set the action for all
the addresses. */

if (give_up)
  {
  struct passwd *pw = getpwuid(real_uid);
  log_write(0, LOG_MAIN, "cancelled by %s",
      pw ? US pw->pw_name : string_sprintf("uid %ld", (long int)real_uid));
  process_recipients = RECIP_FAIL;
  }

/* Otherwise, if there are too many Received: headers, fail all recipients. */

else if (received_count > received_headers_max)
  process_recipients = RECIP_FAIL_LOOP;

/* Otherwise, if a system-wide, address-independent message filter is
specified, run it now, except in the case when we are failing all recipients as
a result of timeout_frozen_after. If the system filter yields "delivered", then
ignore the true recipients of the message. Failure of the filter file is
logged, and the delivery attempt fails. */

else if (system_filter && process_recipients != RECIP_FAIL_TIMEOUT)
  {
  int rc;
  int filtertype;
  ugid_block ugid;
  redirect_block redirect;

  if (system_filter_uid_set)
    {
    ugid.uid = system_filter_uid;
    ugid.gid = system_filter_gid;
    ugid.uid_set = ugid.gid_set = TRUE;
    }
  else
    {
    ugid.uid_set = ugid.gid_set = FALSE;
    }

  return_path = sender_address;
  f.enable_dollar_recipients = TRUE;   /* Permit $recipients in system filter */
  f.system_filtering = TRUE;

  /* Any error in the filter file causes a delivery to be abandoned. */

  redirect.string = system_filter;
  redirect.isfile = TRUE;
  redirect.check_owner = redirect.check_group = FALSE;
  redirect.owners = NULL;
  redirect.owngroups = NULL;
  redirect.pw = NULL;
  redirect.modemask = 0;

  DEBUG(D_deliver|D_filter) debug_printf("running system filter\n");

  rc = rda_interpret(
    &redirect,              /* Where the data is */
    RDO_DEFER |             /* Turn on all the enabling options */
      RDO_FAIL |            /* Leave off all the disabling options */
      RDO_FILTER |
      RDO_FREEZE |
      RDO_REALLOG |
      RDO_REWRITE,
    NULL,                   /* No :include: restriction (not used in filter) */
    NULL,                   /* No sieve vacation directory (not sieve!) */
    NULL,                   /* No sieve enotify mailto owner (not sieve!) */
    NULL,                   /* No sieve user address (not sieve!) */
    NULL,                   /* No sieve subaddress (not sieve!) */
    &ugid,                  /* uid/gid data */
    &addr_new,              /* Where to hang generated addresses */
    &filter_message,        /* Where to put error message */
    NULL,                   /* Don't skip syntax errors */
    &filtertype,            /* Will always be set to FILTER_EXIM for this call */
    US"system filter");     /* For error messages */

  DEBUG(D_deliver|D_filter) debug_printf("system filter returned %d\n", rc);

  if (rc == FF_ERROR || rc == FF_NONEXIST)
    {
    (void)close(deliver_datafile);
    deliver_datafile = -1;
    log_write(0, LOG_MAIN|LOG_PANIC, "Error in system filter: %s",
      string_printing(filter_message));
    return continue_closedown();   /* yields DELIVER_NOT_ATTEMPTED */
    }

  /* Reset things. If the filter message is an empty string, which can happen
  for a filter "fail" or "freeze" command with no text, reset it to NULL. */

  f.system_filtering = FALSE;
  f.enable_dollar_recipients = FALSE;
  if (filter_message && filter_message[0] == 0) filter_message = NULL;

  /* Save the values of the system filter variables so that user filters
  can use them. */

  memcpy(filter_sn, filter_n, sizeof(filter_sn));

  /* The filter can request that delivery of the original addresses be
  deferred. */

  if (rc == FF_DEFER)
    {
    process_recipients = RECIP_DEFER;
    deliver_msglog("Delivery deferred by system filter\n");
    log_write(0, LOG_MAIN, "Delivery deferred by system filter");
    }

  /* The filter can request that a message be frozen, but this does not
  take place if the message has been manually thawed. In that case, we must
  unset "delivered", which is forced by the "freeze" command to make -bF
  work properly. */

  else if (rc == FF_FREEZE && !f.deliver_manual_thaw)
    {
    f.deliver_freeze = TRUE;
    deliver_frozen_at = time(NULL);
    process_recipients = RECIP_DEFER;
    frozen_info = string_sprintf(" by the system filter%s%s",
      filter_message ? US": " : US"",
      filter_message ? filter_message : US"");
    }

  /* The filter can request that a message be failed. The error message may be
  quite long - it is sent back to the sender in the bounce - but we don't want
  to fill up the log with repetitions of it. If it starts with << then the text
  between << and >> is written to the log, with the rest left for the bounce
  message. */

  else if (rc == FF_FAIL)
    {
    uschar *colon = US"";
    uschar *logmsg = US"";
    int loglen = 0;

    process_recipients = RECIP_FAIL_FILTER;

    if (filter_message)
      {
      uschar *logend;
      colon = US": ";
      if (  filter_message[0] == '<'
         && filter_message[1] == '<'
	 && (logend = Ustrstr(filter_message, ">>"))
	 )
        {
        logmsg = filter_message + 2;
        loglen = logend - logmsg;
        filter_message = logend + 2;
        if (filter_message[0] == 0) filter_message = NULL;
        }
      else
        {
        logmsg = filter_message;
        loglen = Ustrlen(filter_message);
        }
      }

    log_write(0, LOG_MAIN, "cancelled by system filter%s%.*s", colon, loglen,
      logmsg);
    }

  /* Delivery can be restricted only to those recipients (if any) that the
  filter specified. */

  else if (rc == FF_DELIVERED)
    {
    process_recipients = RECIP_IGNORE;
    if (addr_new)
      log_write(0, LOG_MAIN, "original recipients ignored (system filter)");
    else
      log_write(0, LOG_MAIN, "=> discarded (system filter)");
    }

  /* If any new addresses were created by the filter, fake up a "parent"
  for them. This is necessary for pipes, etc., which are expected to have
  parents, and it also gives some sensible logging for others. Allow
  pipes, files, and autoreplies, and run them as the filter uid if set,
  otherwise as the current uid. */

  if (addr_new)
    {
    int uid = (system_filter_uid_set)? system_filter_uid : geteuid();
    int gid = (system_filter_gid_set)? system_filter_gid : getegid();

    /* The text "system-filter" is tested in transport_set_up_command() and in
    set_up_shell_command() in the pipe transport, to enable them to permit
    $recipients, so don't change it here without also changing it there. */

    address_item *p = addr_new;
    address_item *parent = deliver_make_addr(US"system-filter", FALSE);

    parent->domain = string_copylc(qualify_domain_recipient);
    parent->local_part = US"system-filter";

    /* As part of this loop, we arrange for addr_last to end up pointing
    at the final address. This is used if we go on to add addresses for the
    original recipients. */

    while (p)
      {
      if (parent->child_count == USHRT_MAX)
        log_write(0, LOG_MAIN|LOG_PANIC_DIE, "system filter generated more "
          "than %d delivery addresses", USHRT_MAX);
      parent->child_count++;
      p->parent = parent;

      if (testflag(p, af_pfr))
        {
        uschar *tpname;
        uschar *type;
        p->uid = uid;
        p->gid = gid;
        setflag(p, af_uid_set);
        setflag(p, af_gid_set);
        setflag(p, af_allow_file);
        setflag(p, af_allow_pipe);
        setflag(p, af_allow_reply);

        /* Find the name of the system filter's appropriate pfr transport */

        if (p->address[0] == '|')
          {
          type = US"pipe";
          tpname = system_filter_pipe_transport;
          address_pipe = p->address;
          }
        else if (p->address[0] == '>')
          {
          type = US"reply";
          tpname = system_filter_reply_transport;
          }
        else
          {
          if (p->address[Ustrlen(p->address)-1] == '/')
            {
            type = US"directory";
            tpname = system_filter_directory_transport;
            }
          else
            {
            type = US"file";
            tpname = system_filter_file_transport;
            }
          address_file = p->address;
          }

        /* Now find the actual transport, first expanding the name. We have
        set address_file or address_pipe above. */

        if (tpname)
          {
          uschar *tmp = expand_string(tpname);
          address_file = address_pipe = NULL;
          if (!tmp)
            p->message = string_sprintf("failed to expand \"%s\" as a "
              "system filter transport name", tpname);
          tpname = tmp;
          }
        else
          p->message = string_sprintf("system_filter_%s_transport is unset",
            type);

        if (tpname)
          {
          transport_instance *tp;
          for (tp = transports; tp; tp = tp->next)
            if (Ustrcmp(tp->name, tpname) == 0)
              {
              p->transport = tp;
              break;
              }
          if (!tp)
            p->message = string_sprintf("failed to find \"%s\" transport "
              "for system filter delivery", tpname);
          }

        /* If we couldn't set up a transport, defer the delivery, putting the
        error on the panic log as well as the main log. */

        if (!p->transport)
          {
          address_item *badp = p;
          p = p->next;
          if (!addr_last) addr_new = p; else addr_last->next = p;
          badp->local_part = badp->address;   /* Needed for log line */
          post_process_one(badp, DEFER, LOG_MAIN|LOG_PANIC, EXIM_DTYPE_ROUTER, 0);
          continue;
          }
        }    /* End of pfr handling */

      /* Either a non-pfr delivery, or we found a transport */

      DEBUG(D_deliver|D_filter)
        debug_printf("system filter added %s\n", p->address);

      addr_last = p;
      p = p->next;
      }    /* Loop through all addr_new addresses */
    }
  }


/* Scan the recipients list, and for every one that is not in the non-
recipients tree, add an addr item to the chain of new addresses. If the pno
value is non-negative, we must set the onetime parent from it. This which
points to the relevant entry in the recipients list.

This processing can be altered by the setting of the process_recipients
variable, which is changed if recipients are to be ignored, failed, or
deferred. This can happen as a result of system filter activity, or if the -Mg
option is used to fail all of them.

Duplicate addresses are handled later by a different tree structure; we can't
just extend the non-recipients tree, because that will be re-written to the
spool if the message is deferred, and in any case there are casing
complications for local addresses. */

if (process_recipients != RECIP_IGNORE)
  for (i = 0; i < recipients_count; i++)
    if (!tree_search(tree_nonrecipients, recipients_list[i].address))
      {
      recipient_item *r = recipients_list + i;
      address_item *new = deliver_make_addr(r->address, FALSE);
      new->prop.errors_address = r->errors_to;
#ifdef SUPPORT_I18N
      if ((new->prop.utf8_msg = message_smtputf8))
	{
	new->prop.utf8_downcvt =       message_utf8_downconvert == 1;
	new->prop.utf8_downcvt_maybe = message_utf8_downconvert == -1;
	DEBUG(D_deliver) debug_printf("utf8, downconvert %s\n",
	  new->prop.utf8_downcvt ? "yes"
	  : new->prop.utf8_downcvt_maybe ? "ifneeded"
	  : "no");
	}
#endif

      if (r->pno >= 0)
        new->onetime_parent = recipients_list[r->pno].address;

      /* If DSN support is enabled, set the dsn flags and the original receipt
         to be passed on to other DSN enabled MTAs */
      new->dsn_flags = r->dsn_flags & rf_dsnflags;
      new->dsn_orcpt = r->orcpt;
      DEBUG(D_deliver) debug_printf("DSN: set orcpt: %s  flags: %d\n",
	new->dsn_orcpt ? new->dsn_orcpt : US"", new->dsn_flags);

      switch (process_recipients)
        {
        /* RECIP_DEFER is set when a system filter freezes a message. */

        case RECIP_DEFER:
	  new->next = addr_defer;
	  addr_defer = new;
	  break;


        /* RECIP_FAIL_FILTER is set when a system filter has obeyed a "fail"
        command. */

        case RECIP_FAIL_FILTER:
	  new->message =
	    filter_message ? filter_message : US"delivery cancelled";
	  setflag(new, af_pass_message);
	  goto RECIP_QUEUE_FAILED;   /* below */


        /* RECIP_FAIL_TIMEOUT is set when a message is frozen, but is older
        than the value in timeout_frozen_after. Treat non-bounce messages
        similarly to -Mg; for bounce messages we just want to discard, so
        don't put the address on the failed list. The timeout has already
        been logged. */

        case RECIP_FAIL_TIMEOUT:
	  new->message  = US"delivery cancelled; message timed out";
	  goto RECIP_QUEUE_FAILED;   /* below */


        /* RECIP_FAIL is set when -Mg has been used. */

        case RECIP_FAIL:
	  new->message  = US"delivery cancelled by administrator";
	  /* Fall through */

        /* Common code for the failure cases above. If this is not a bounce
        message, put the address on the failed list so that it is used to
        create a bounce. Otherwise do nothing - this just discards the address.
        The incident has already been logged. */

        RECIP_QUEUE_FAILED:
	  if (sender_address[0])
	    {
	    new->next = addr_failed;
	    addr_failed = new;
	    }
        break;


        /* RECIP_FAIL_LOOP is set when there are too many Received: headers
        in the message. Process each address as a routing failure; if this
        is a bounce message, it will get frozen. */

        case RECIP_FAIL_LOOP:
	  new->message = US"Too many \"Received\" headers - suspected mail loop";
	  post_process_one(new, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);
	  break;


        /* Value should be RECIP_ACCEPT; take this as the safe default. */

        default:
	  if (!addr_new) addr_new = new; else addr_last->next = new;
	  addr_last = new;
	  break;
        }

#ifndef DISABLE_EVENT
      if (process_recipients != RECIP_ACCEPT)
	{
	uschar * save_local =  deliver_localpart;
	const uschar * save_domain = deliver_domain;
	uschar * addr = new->address, * errmsg = NULL;
	int start, end, dom;

	if (!parse_extract_address(addr, &errmsg, &start, &end, &dom, TRUE))
	  log_write(0, LOG_MAIN|LOG_PANIC,
                "failed to parse address '%.100s': %s\n", addr, errmsg);
	else
	  {
	  deliver_localpart =
	    string_copyn(addr+start, dom ? (dom-1) - start : end - start);
	  deliver_domain = dom ? CUS string_copyn(addr+dom, end - dom) : CUS"";

	  event_raise(event_action, US"msg:fail:internal", new->message);

	  deliver_localpart = save_local;
	  deliver_domain = save_domain;
	  }
	}
#endif
      }

DEBUG(D_deliver)
  {
  address_item *p;
  debug_printf("Delivery address list:\n");
  for (p = addr_new; p; p = p->next)
    debug_printf("  %s %s\n", p->address,
      p->onetime_parent ? p->onetime_parent : US"");
  }

/* Set up the buffers used for copying over the file when delivering. */

deliver_in_buffer = store_malloc(DELIVER_IN_BUFFER_SIZE);
deliver_out_buffer = store_malloc(DELIVER_OUT_BUFFER_SIZE);



/* Until there are no more new addresses, handle each one as follows:

 . If this is a generated address (indicated by the presence of a parent
   pointer) then check to see whether it is a pipe, file, or autoreply, and
   if so, handle it directly here. The router that produced the address will
   have set the allow flags into the address, and also set the uid/gid required.
   Having the routers generate new addresses and then checking them here at
   the outer level is tidier than making each router do the checking, and
   means that routers don't need access to the failed address queue.

 . Break up the address into local part and domain, and make lowercased
   versions of these strings. We also make unquoted versions of the local part.

 . Handle the percent hack for those domains for which it is valid.

 . For child addresses, determine if any of the parents have the same address.
   If so, generate a different string for previous delivery checking. Without
   this code, if the address spqr generates spqr via a forward or alias file,
   delivery of the generated spqr stops further attempts at the top level spqr,
   which is not what is wanted - it may have generated other addresses.

 . Check on the retry database to see if routing was previously deferred, but
   only if in a queue run. Addresses that are to be routed are put on the
   addr_route chain. Addresses that are to be deferred are put on the
   addr_defer chain. We do all the checking first, so as not to keep the
   retry database open any longer than necessary.

 . Now we run the addresses through the routers. A router may put the address
   on either the addr_local or the addr_remote chain for local or remote
   delivery, respectively, or put it on the addr_failed chain if it is
   undeliveable, or it may generate child addresses and put them on the
   addr_new chain, or it may defer an address. All the chain anchors are
   passed as arguments so that the routers can be called for verification
   purposes as well.

 . If new addresses have been generated by the routers, da capo.
*/

f.header_rewritten = FALSE;          /* No headers rewritten yet */
while (addr_new)           /* Loop until all addresses dealt with */
  {
  address_item *addr, *parent;

  /* Failure to open the retry database is treated the same as if it does
  not exist. In both cases, dbm_file is NULL. */

  if (!(dbm_file = dbfn_open(US"retry", O_RDONLY, &dbblock, FALSE)))
    DEBUG(D_deliver|D_retry|D_route|D_hints_lookup)
      debug_printf("no retry data available\n");

  /* Scan the current batch of new addresses, to handle pipes, files and
  autoreplies, and determine which others are ready for routing. */

  while (addr_new)
    {
    int rc;
    uschar *p;
    tree_node *tnode;
    dbdata_retry *domain_retry_record;
    dbdata_retry *address_retry_record;

    addr = addr_new;
    addr_new = addr->next;

    DEBUG(D_deliver|D_retry|D_route)
      {
      debug_printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
      debug_printf("Considering: %s\n", addr->address);
      }

    /* Handle generated address that is a pipe or a file or an autoreply. */

    if (testflag(addr, af_pfr))
      {
      /* If an autoreply in a filter could not generate a syntactically valid
      address, give up forthwith. Set af_ignore_error so that we don't try to
      generate a bounce. */

      if (testflag(addr, af_bad_reply))
        {
        addr->basic_errno = ERRNO_BADADDRESS2;
        addr->local_part = addr->address;
        addr->message =
          US"filter autoreply generated syntactically invalid recipient";
        addr->prop.ignore_error = TRUE;
        (void) post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);
        continue;   /* with the next new address */
        }

      /* If two different users specify delivery to the same pipe or file or
      autoreply, there should be two different deliveries, so build a unique
      string that incorporates the original address, and use this for
      duplicate testing and recording delivery, and also for retrying. */

      addr->unique =
        string_sprintf("%s:%s", addr->address, addr->parent->unique +
          (testflag(addr->parent, af_homonym)? 3:0));

      addr->address_retry_key = addr->domain_retry_key =
        string_sprintf("T:%s", addr->unique);

      /* If a filter file specifies two deliveries to the same pipe or file,
      we want to de-duplicate, but this is probably not wanted for two mail
      commands to the same address, where probably both should be delivered.
      So, we have to invent a different unique string in that case. Just
      keep piling '>' characters on the front. */

      if (addr->address[0] == '>')
        {
        while (tree_search(tree_duplicates, addr->unique))
          addr->unique = string_sprintf(">%s", addr->unique);
        }

      else if ((tnode = tree_search(tree_duplicates, addr->unique)))
        {
        DEBUG(D_deliver|D_route)
          debug_printf("%s is a duplicate address: discarded\n", addr->address);
        addr->dupof = tnode->data.ptr;
        addr->next = addr_duplicate;
        addr_duplicate = addr;
        continue;
        }

      DEBUG(D_deliver|D_route) debug_printf("unique = %s\n", addr->unique);

      /* Check for previous delivery */

      if (tree_search(tree_nonrecipients, addr->unique))
        {
        DEBUG(D_deliver|D_route)
          debug_printf("%s was previously delivered: discarded\n", addr->address);
        child_done(addr, tod_stamp(tod_log));
        continue;
        }

      /* Save for checking future duplicates */

      tree_add_duplicate(addr->unique, addr);

      /* Set local part and domain */

      addr->local_part = addr->address;
      addr->domain = addr->parent->domain;

      /* Ensure that the delivery is permitted. */

      if (testflag(addr, af_file))
        {
        if (!testflag(addr, af_allow_file))
          {
          addr->basic_errno = ERRNO_FORBIDFILE;
          addr->message = US"delivery to file forbidden";
          (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);
          continue;   /* with the next new address */
          }
        }
      else if (addr->address[0] == '|')
        {
        if (!testflag(addr, af_allow_pipe))
          {
          addr->basic_errno = ERRNO_FORBIDPIPE;
          addr->message = US"delivery to pipe forbidden";
          (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);
          continue;   /* with the next new address */
          }
        }
      else if (!testflag(addr, af_allow_reply))
        {
        addr->basic_errno = ERRNO_FORBIDREPLY;
        addr->message = US"autoreply forbidden";
        (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);
        continue;     /* with the next new address */
        }

      /* If the errno field is already set to BADTRANSPORT, it indicates
      failure to expand a transport string, or find the associated transport,
      or an unset transport when one is required. Leave this test till now so
      that the forbid errors are given in preference. */

      if (addr->basic_errno == ERRNO_BADTRANSPORT)
        {
        (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);
        continue;
        }

      /* Treat /dev/null as a special case and abandon the delivery. This
      avoids having to specify a uid on the transport just for this case.
      Arrange for the transport name to be logged as "**bypassed**". */

      if (Ustrcmp(addr->address, "/dev/null") == 0)
        {
        uschar *save = addr->transport->name;
        addr->transport->name = US"**bypassed**";
        (void)post_process_one(addr, OK, LOG_MAIN, EXIM_DTYPE_TRANSPORT, '=');
        addr->transport->name = save;
        continue;   /* with the next new address */
        }

      /* Pipe, file, or autoreply delivery is to go ahead as a normal local
      delivery. */

      DEBUG(D_deliver|D_route)
        debug_printf("queued for %s transport\n", addr->transport->name);
      addr->next = addr_local;
      addr_local = addr;
      continue;       /* with the next new address */
      }

    /* Handle normal addresses. First, split up into local part and domain,
    handling the %-hack if necessary. There is the possibility of a defer from
    a lookup in percent_hack_domains. */

    if ((rc = deliver_split_address(addr)) == DEFER)
      {
      addr->message = US"cannot check percent_hack_domains";
      addr->basic_errno = ERRNO_LISTDEFER;
      (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_NONE, 0);
      continue;
      }

    /* Check to see if the domain is held. If so, proceed only if the
    delivery was forced by hand. */

    deliver_domain = addr->domain;  /* set $domain */
    if (  !forced && hold_domains
       && (rc = match_isinlist(addr->domain, (const uschar **)&hold_domains, 0,
           &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE,
           NULL)) != FAIL
       )
      {
      if (rc == DEFER)
        {
        addr->message = US"hold_domains lookup deferred";
        addr->basic_errno = ERRNO_LISTDEFER;
        }
      else
        {
        addr->message = US"domain is held";
        addr->basic_errno = ERRNO_HELD;
        }
      (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_NONE, 0);
      continue;
      }

    /* Now we can check for duplicates and previously delivered addresses. In
    order to do this, we have to generate a "unique" value for each address,
    because there may be identical actual addresses in a line of descendents.
    The "unique" field is initialized to the same value as the "address" field,
    but gets changed here to cope with identically-named descendents. */

    for (parent = addr->parent; parent; parent = parent->parent)
      if (strcmpic(addr->address, parent->address) == 0) break;

    /* If there's an ancestor with the same name, set the homonym flag. This
    influences how deliveries are recorded. Then add a prefix on the front of
    the unique address. We use \n\ where n starts at 0 and increases each time.
    It is unlikely to pass 9, but if it does, it may look odd but will still
    work. This means that siblings or cousins with the same names are treated
    as duplicates, which is what we want. */

    if (parent)
      {
      setflag(addr, af_homonym);
      if (parent->unique[0] != '\\')
        addr->unique = string_sprintf("\\0\\%s", addr->address);
      else
        addr->unique = string_sprintf("\\%c\\%s", parent->unique[1] + 1,
          addr->address);
      }

    /* Ensure that the domain in the unique field is lower cased, because
    domains are always handled caselessly. */

    p = Ustrrchr(addr->unique, '@');
    while (*p != 0) { *p = tolower(*p); p++; }

    DEBUG(D_deliver|D_route) debug_printf("unique = %s\n", addr->unique);

    if (tree_search(tree_nonrecipients, addr->unique))
      {
      DEBUG(D_deliver|D_route)
        debug_printf("%s was previously delivered: discarded\n", addr->unique);
      child_done(addr, tod_stamp(tod_log));
      continue;
      }

    /* Get the routing retry status, saving the two retry keys (with and
    without the local part) for subsequent use. If there is no retry record for
    the standard address routing retry key, we look for the same key with the
    sender attached, because this form is used by the smtp transport after a
    4xx response to RCPT when address_retry_include_sender is true. */

    addr->domain_retry_key = string_sprintf("R:%s", addr->domain);
    addr->address_retry_key = string_sprintf("R:%s@%s", addr->local_part,
      addr->domain);

    if (dbm_file)
      {
      domain_retry_record = dbfn_read(dbm_file, addr->domain_retry_key);
      if (  domain_retry_record
         && now - domain_retry_record->time_stamp > retry_data_expire
	 )
        domain_retry_record = NULL;    /* Ignore if too old */

      address_retry_record = dbfn_read(dbm_file, addr->address_retry_key);
      if (  address_retry_record
         && now - address_retry_record->time_stamp > retry_data_expire
	 )
        address_retry_record = NULL;   /* Ignore if too old */

      if (!address_retry_record)
        {
        uschar *altkey = string_sprintf("%s:<%s>", addr->address_retry_key,
          sender_address);
        address_retry_record = dbfn_read(dbm_file, altkey);
        if (  address_retry_record
	   && now - address_retry_record->time_stamp > retry_data_expire)
          address_retry_record = NULL;   /* Ignore if too old */
        }
      }
    else
      domain_retry_record = address_retry_record = NULL;

    DEBUG(D_deliver|D_retry)
      {
      if (!domain_retry_record)
        debug_printf("no domain retry record\n");
      if (!address_retry_record)
        debug_printf("no address retry record\n");
      }

    /* If we are sending a message down an existing SMTP connection, we must
    assume that the message which created the connection managed to route
    an address to that connection. We do not want to run the risk of taking
    a long time over routing here, because if we do, the server at the other
    end of the connection may time it out. This is especially true for messages
    with lots of addresses. For this kind of delivery, queue_running is not
    set, so we would normally route all addresses. We take a pragmatic approach
    and defer routing any addresses that have any kind of domain retry record.
    That is, we don't even look at their retry times. It doesn't matter if this
    doesn't work occasionally. This is all just an optimization, after all.

    The reason for not doing the same for address retries is that they normally
    arise from 4xx responses, not DNS timeouts. */

    if (continue_hostname && domain_retry_record)
      {
      addr->message = US"reusing SMTP connection skips previous routing defer";
      addr->basic_errno = ERRNO_RRETRY;
      (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);
      }

    /* If we are in a queue run, defer routing unless there is no retry data or
    we've passed the next retry time, or this message is forced. In other
    words, ignore retry data when not in a queue run.

    However, if the domain retry time has expired, always allow the routing
    attempt. If it fails again, the address will be failed. This ensures that
    each address is routed at least once, even after long-term routing
    failures.

    If there is an address retry, check that too; just wait for the next
    retry time. This helps with the case when the temporary error on the
    address was really message-specific rather than address specific, since
    it allows other messages through.

    We also wait for the next retry time if this is a message sent down an
    existing SMTP connection (even though that will be forced). Otherwise there
    will be far too many attempts for an address that gets a 4xx error. In
    fact, after such an error, we should not get here because, the host should
    not be remembered as one this message needs. However, there was a bug that
    used to cause this to  happen, so it is best to be on the safe side.

    Even if we haven't reached the retry time in the hints, there is one more
    check to do, which is for the ultimate address timeout. We only do this
    check if there is an address retry record and there is not a domain retry
    record; this implies that previous attempts to handle the address had the
    retry_use_local_parts option turned on. We use this as an approximation
    for the destination being like a local delivery, for example delivery over
    LMTP to an IMAP message store. In this situation users are liable to bump
    into their quota and thereby have intermittently successful deliveries,
    which keep the retry record fresh, which can lead to us perpetually
    deferring messages. */

    else if (  (  f.queue_running && !f.deliver_force
	       || continue_hostname
	       )
            && (  (  domain_retry_record
		  && now < domain_retry_record->next_try
		  && !domain_retry_record->expired
		  )
	       || (  address_retry_record
		  && now < address_retry_record->next_try
	       )  )
            && (  domain_retry_record
	       || !address_retry_record
	       || !retry_ultimate_address_timeout(addr->address_retry_key,
				 addr->domain, address_retry_record, now)
	    )  )
      {
      addr->message = US"retry time not reached";
      addr->basic_errno = ERRNO_RRETRY;
      (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);
      }

    /* The domain is OK for routing. Remember if retry data exists so it
    can be cleaned up after a successful delivery. */

    else
      {
      if (domain_retry_record || address_retry_record)
        setflag(addr, af_dr_retry_exists);
      addr->next = addr_route;
      addr_route = addr;
      DEBUG(D_deliver|D_route)
        debug_printf("%s: queued for routing\n", addr->address);
      }
    }

  /* The database is closed while routing is actually happening. Requests to
  update it are put on a chain and all processed together at the end. */

  if (dbm_file) dbfn_close(dbm_file);

  /* If queue_domains is set, we don't even want to try routing addresses in
  those domains. During queue runs, queue_domains is forced to be unset.
  Optimize by skipping this pass through the addresses if nothing is set. */

  if (!f.deliver_force && queue_domains)
    {
    address_item *okaddr = NULL;
    while (addr_route)
      {
      address_item *addr = addr_route;
      addr_route = addr->next;

      deliver_domain = addr->domain;  /* set $domain */
      if ((rc = match_isinlist(addr->domain, (const uschar **)&queue_domains, 0,
            &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE, NULL))
              != OK)
        if (rc == DEFER)
          {
          addr->basic_errno = ERRNO_LISTDEFER;
          addr->message = US"queue_domains lookup deferred";
          (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);
          }
        else
          {
          addr->next = okaddr;
          okaddr = addr;
          }
      else
        {
        addr->basic_errno = ERRNO_QUEUE_DOMAIN;
        addr->message = US"domain is in queue_domains";
        (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);
        }
      }

    addr_route = okaddr;
    }

  /* Now route those addresses that are not deferred. */

  while (addr_route)
    {
    int rc;
    address_item *addr = addr_route;
    const uschar *old_domain = addr->domain;
    uschar *old_unique = addr->unique;
    addr_route = addr->next;
    addr->next = NULL;

    /* Just in case some router parameter refers to it. */

    if (!(return_path = addr->prop.errors_address))
      return_path = sender_address;

    /* If a router defers an address, add a retry item. Whether or not to
    use the local part in the key is a property of the router. */

    if ((rc = route_address(addr, &addr_local, &addr_remote, &addr_new,
         &addr_succeed, v_none)) == DEFER)
      retry_add_item(addr,
        addr->router->retry_use_local_part
        ? string_sprintf("R:%s@%s", addr->local_part, addr->domain)
	: string_sprintf("R:%s", addr->domain),
	0);

    /* Otherwise, if there is an existing retry record in the database, add
    retry items to delete both forms. We must also allow for the possibility
    of a routing retry that includes the sender address. Since the domain might
    have been rewritten (expanded to fully qualified) as a result of routing,
    ensure that the rewritten form is also deleted. */

    else if (testflag(addr, af_dr_retry_exists))
      {
      uschar *altkey = string_sprintf("%s:<%s>", addr->address_retry_key,
        sender_address);
      retry_add_item(addr, altkey, rf_delete);
      retry_add_item(addr, addr->address_retry_key, rf_delete);
      retry_add_item(addr, addr->domain_retry_key, rf_delete);
      if (Ustrcmp(addr->domain, old_domain) != 0)
        retry_add_item(addr, string_sprintf("R:%s", old_domain), rf_delete);
      }

    /* DISCARD is given for :blackhole: and "seen finish". The event has been
    logged, but we need to ensure the address (and maybe parents) is marked
    done. */

    if (rc == DISCARD)
      {
      address_done(addr, tod_stamp(tod_log));
      continue;  /* route next address */
      }

    /* The address is finished with (failed or deferred). */

    if (rc != OK)
      {
      (void)post_process_one(addr, rc, LOG_MAIN, EXIM_DTYPE_ROUTER, 0);
      continue;  /* route next address */
      }

    /* The address has been routed. If the router changed the domain, it will
    also have changed the unique address. We have to test whether this address
    has already been delivered, because it's the unique address that finally
    gets recorded. */

    if (  addr->unique != old_unique
       && tree_search(tree_nonrecipients, addr->unique) != 0
       )
      {
      DEBUG(D_deliver|D_route) debug_printf("%s was previously delivered: "
        "discarded\n", addr->address);
      if (addr_remote == addr) addr_remote = addr->next;
      else if (addr_local == addr) addr_local = addr->next;
      }

    /* If the router has same_domain_copy_routing set, we are permitted to copy
    the routing for any other addresses with the same domain. This is an
    optimisation to save repeated DNS lookups for "standard" remote domain
    routing. The option is settable only on routers that generate host lists.
    We play it very safe, and do the optimization only if the address is routed
    to a remote transport, there are no header changes, and the domain was not
    modified by the router. */

    if (  addr_remote == addr
       && addr->router->same_domain_copy_routing
       && !addr->prop.extra_headers
       && !addr->prop.remove_headers
       && old_domain == addr->domain
       )
      {
      address_item **chain = &addr_route;
      while (*chain)
        {
        address_item *addr2 = *chain;
        if (Ustrcmp(addr2->domain, addr->domain) != 0)
          {
          chain = &(addr2->next);
          continue;
          }

        /* Found a suitable address; take it off the routing list and add it to
        the remote delivery list. */

        *chain = addr2->next;
        addr2->next = addr_remote;
        addr_remote = addr2;

        /* Copy the routing data */

        addr2->domain = addr->domain;
        addr2->router = addr->router;
        addr2->transport = addr->transport;
        addr2->host_list = addr->host_list;
        addr2->fallback_hosts = addr->fallback_hosts;
        addr2->prop.errors_address = addr->prop.errors_address;
        copyflag(addr2, addr, af_hide_child);
        copyflag(addr2, addr, af_local_host_removed);

        DEBUG(D_deliver|D_route)
          debug_printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"
                       "routing %s\n"
                       "Routing for %s copied from %s\n",
            addr2->address, addr2->address, addr->address);
        }
      }
    }  /* Continue with routing the next address. */
  }    /* Loop to process any child addresses that the routers created, and
          any rerouted addresses that got put back on the new chain. */


/* Debugging: show the results of the routing */

DEBUG(D_deliver|D_retry|D_route)
  {
  address_item *p;
  debug_printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
  debug_printf("After routing:\n  Local deliveries:\n");
  for (p = addr_local; p; p = p->next)
    debug_printf("    %s\n", p->address);

  debug_printf("  Remote deliveries:\n");
  for (p = addr_remote; p; p = p->next)
    debug_printf("    %s\n", p->address);

  debug_printf("  Failed addresses:\n");
  for (p = addr_failed; p; p = p->next)
    debug_printf("    %s\n", p->address);

  debug_printf("  Deferred addresses:\n");
  for (p = addr_defer; p; p = p->next)
    debug_printf("    %s\n", p->address);
  }

/* Free any resources that were cached during routing. */

search_tidyup();
route_tidyup();

/* These two variables are set only during routing, after check_local_user.
Ensure they are not set in transports. */

local_user_gid = (gid_t)(-1);
local_user_uid = (uid_t)(-1);

/* Check for any duplicate addresses. This check is delayed until after
routing, because the flexibility of the routing configuration means that
identical addresses with different parentage may end up being redirected to
different addresses. Checking for duplicates too early (as we previously used
to) makes this kind of thing not work. */

do_duplicate_check(&addr_local);
do_duplicate_check(&addr_remote);

/* When acting as an MUA wrapper, we proceed only if all addresses route to a
remote transport. The check that they all end up in one transaction happens in
the do_remote_deliveries() function. */

if (  mua_wrapper
   && (addr_local || addr_failed || addr_defer)
   )
  {
  address_item *addr;
  uschar *which, *colon, *msg;

  if (addr_local)
    {
    addr = addr_local;
    which = US"local";
    }
  else if (addr_defer)
    {
    addr = addr_defer;
    which = US"deferred";
    }
  else
    {
    addr = addr_failed;
    which = US"failed";
    }

  while (addr->parent) addr = addr->parent;

  if (addr->message)
    {
    colon = US": ";
    msg = addr->message;
    }
  else colon = msg = US"";

  /* We don't need to log here for a forced failure as it will already
  have been logged. Defer will also have been logged, but as a defer, so we do
  need to do the failure logging. */

  if (addr != addr_failed)
    log_write(0, LOG_MAIN, "** %s routing yielded a %s delivery",
      addr->address, which);

  /* Always write an error to the caller */

  fprintf(stderr, "routing %s yielded a %s delivery%s%s\n", addr->address,
    which, colon, msg);

  final_yield = DELIVER_MUA_FAILED;
  addr_failed = addr_defer = NULL;   /* So that we remove the message */
  goto DELIVERY_TIDYUP;
  }


/* If this is a run to continue deliveries to an external channel that is
already set up, defer any local deliveries. */

if (continue_transport)
  {
  if (addr_defer)
    {
    address_item *addr = addr_defer;
    while (addr->next) addr = addr->next;
    addr->next = addr_local;
    }
  else
    addr_defer = addr_local;
  addr_local = NULL;
  }


/* Because address rewriting can happen in the routers, we should not really do
ANY deliveries until all addresses have been routed, so that all recipients of
the message get the same headers. However, this is in practice not always
possible, since sometimes remote addresses give DNS timeouts for days on end.
The pragmatic approach is to deliver what we can now, saving any rewritten
headers so that at least the next lot of recipients benefit from the rewriting
that has already been done.

If any headers have been rewritten during routing, update the spool file to
remember them for all subsequent deliveries. This can be delayed till later if
there is only address to be delivered - if it succeeds the spool write need not
happen. */

if (  f.header_rewritten
   && (  addr_local && (addr_local->next || addr_remote)
      || addr_remote && addr_remote->next
   )  )
  {
  /* Panic-dies on error */
  (void)spool_write_header(message_id, SW_DELIVERING, NULL);
  f.header_rewritten = FALSE;
  }


/* If there are any deliveries to be and we do not already have the journal
file, create it. This is used to record successful deliveries as soon as
possible after each delivery is known to be complete. A file opened with
O_APPEND is used so that several processes can run simultaneously.

The journal is just insurance against crashes. When the spool file is
ultimately updated at the end of processing, the journal is deleted. If a
journal is found to exist at the start of delivery, the addresses listed
therein are added to the non-recipients. */

if (addr_local || addr_remote)
  {
  if (journal_fd < 0)
    {
    uschar * fname = spool_fname(US"input", message_subdir, id, US"-J");

    if ((journal_fd = Uopen(fname,
#ifdef O_CLOEXEC
			O_CLOEXEC |
#endif
			O_WRONLY|O_APPEND|O_CREAT|O_EXCL, SPOOL_MODE)) < 0)
      {
      log_write(0, LOG_MAIN|LOG_PANIC, "Couldn't open journal file %s: %s",
	fname, strerror(errno));
      return DELIVER_NOT_ATTEMPTED;
      }

    /* Set the close-on-exec flag, make the file owned by Exim, and ensure
    that the mode is correct - the group setting doesn't always seem to get
    set automatically. */

    if(  fchown(journal_fd, exim_uid, exim_gid)
      || fchmod(journal_fd, SPOOL_MODE)
#ifndef O_CLOEXEC
      || fcntl(journal_fd, F_SETFD, fcntl(journal_fd, F_GETFD) | FD_CLOEXEC)
#endif
      )
      {
      int ret = Uunlink(fname);
      log_write(0, LOG_MAIN|LOG_PANIC, "Couldn't set perms on journal file %s: %s",
	fname, strerror(errno));
      if(ret  &&  errno != ENOENT)
	log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to unlink %s: %s",
	  fname, strerror(errno));
      return DELIVER_NOT_ATTEMPTED;
      }
    }
  }
else if (journal_fd >= 0)
  {
  close(journal_fd);
  journal_fd = -1;
  }



/* Now we can get down to the business of actually doing deliveries. Local
deliveries are done first, then remote ones. If ever the problems of how to
handle fallback transports are figured out, this section can be put into a loop
for handling fallbacks, though the uid switching will have to be revised. */

/* Precompile a regex that is used to recognize a parameter in response
to an LHLO command, if is isn't already compiled. This may be used on both
local and remote LMTP deliveries. */

if (!regex_IGNOREQUOTA)
  regex_IGNOREQUOTA =
    regex_must_compile(US"\\n250[\\s\\-]IGNOREQUOTA(\\s|\\n|$)", FALSE, TRUE);

/* Handle local deliveries */

if (addr_local)
  {
  DEBUG(D_deliver|D_transport)
    debug_printf(">>>>>>>>>>>>>>>> Local deliveries >>>>>>>>>>>>>>>>\n");
  do_local_deliveries();
  f.disable_logging = FALSE;
  }

/* If queue_run_local is set, we do not want to attempt any remote deliveries,
so just queue them all. */

if (f.queue_run_local)
  while (addr_remote)
    {
    address_item *addr = addr_remote;
    addr_remote = addr->next;
    addr->next = NULL;
    addr->basic_errno = ERRNO_LOCAL_ONLY;
    addr->message = US"remote deliveries suppressed";
    (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_TRANSPORT, 0);
    }

/* Handle remote deliveries */

if (addr_remote)
  {
  DEBUG(D_deliver|D_transport)
    debug_printf(">>>>>>>>>>>>>>>> Remote deliveries >>>>>>>>>>>>>>>>\n");

  /* Precompile some regex that are used to recognize parameters in response
  to an EHLO command, if they aren't already compiled. */

  deliver_init();

  /* Now sort the addresses if required, and do the deliveries. The yield of
  do_remote_deliveries is FALSE when mua_wrapper is set and all addresses
  cannot be delivered in one transaction. */

  if (remote_sort_domains) sort_remote_deliveries();
  if (!do_remote_deliveries(FALSE))
    {
    log_write(0, LOG_MAIN, "** mua_wrapper is set but recipients cannot all "
      "be delivered in one transaction");
    fprintf(stderr, "delivery to smarthost failed (configuration problem)\n");

    final_yield = DELIVER_MUA_FAILED;
    addr_failed = addr_defer = NULL;   /* So that we remove the message */
    goto DELIVERY_TIDYUP;
    }

  /* See if any of the addresses that failed got put on the queue for delivery
  to their fallback hosts. We do it this way because often the same fallback
  host is used for many domains, so all can be sent in a single transaction
  (if appropriately configured). */

  if (addr_fallback && !mua_wrapper)
    {
    DEBUG(D_deliver) debug_printf("Delivering to fallback hosts\n");
    addr_remote = addr_fallback;
    addr_fallback = NULL;
    if (remote_sort_domains) sort_remote_deliveries();
    do_remote_deliveries(TRUE);
    }
  f.disable_logging = FALSE;
  }


/* All deliveries are now complete. Ignore SIGTERM during this tidying up
phase, to minimize cases of half-done things. */

DEBUG(D_deliver)
  debug_printf(">>>>>>>>>>>>>>>> deliveries are done >>>>>>>>>>>>>>>>\n");
cancel_cutthrough_connection(TRUE, US"deliveries are done");

/* Root privilege is no longer needed */

exim_setugid(exim_uid, exim_gid, FALSE, US"post-delivery tidying");

set_process_info("tidying up after delivering %s", message_id);
signal(SIGTERM, SIG_IGN);

/* When we are acting as an MUA wrapper, the smtp transport will either have
succeeded for all addresses, or failed them all in normal cases. However, there
are some setup situations (e.g. when a named port does not exist) that cause an
immediate exit with deferral of all addresses. Convert those into failures. We
do not ever want to retry, nor do we want to send a bounce message. */

if (mua_wrapper)
  {
  if (addr_defer)
    {
    address_item *addr, *nextaddr;
    for (addr = addr_defer; addr; addr = nextaddr)
      {
      log_write(0, LOG_MAIN, "** %s mua_wrapper forced failure for deferred "
        "delivery", addr->address);
      nextaddr = addr->next;
      addr->next = addr_failed;
      addr_failed = addr;
      }
    addr_defer = NULL;
    }

  /* Now all should either have succeeded or failed. */

  if (!addr_failed)
    final_yield = DELIVER_MUA_SUCCEEDED;
  else
    {
    host_item * host;
    uschar *s = addr_failed->user_message;

    if (!s) s = addr_failed->message;

    fprintf(stderr, "Delivery failed: ");
    if (addr_failed->basic_errno > 0)
      {
      fprintf(stderr, "%s", strerror(addr_failed->basic_errno));
      if (s) fprintf(stderr, ": ");
      }
    if ((host = addr_failed->host_used))
      fprintf(stderr, "H=%s [%s]: ", host->name, host->address);
    if (s)
      fprintf(stderr, "%s", CS s);
    else if (addr_failed->basic_errno <= 0)
      fprintf(stderr, "unknown error");
    fprintf(stderr, "\n");

    final_yield = DELIVER_MUA_FAILED;
    addr_failed = NULL;
    }
  }

/* In a normal configuration, we now update the retry database. This is done in
one fell swoop at the end in order not to keep opening and closing (and
locking) the database. The code for handling retries is hived off into a
separate module for convenience. We pass it the addresses of the various
chains, because deferred addresses can get moved onto the failed chain if the
retry cutoff time has expired for all alternative destinations. Bypass the
updating of the database if the -N flag is set, which is a debugging thing that
prevents actual delivery. */

else if (!f.dont_deliver)
  retry_update(&addr_defer, &addr_failed, &addr_succeed);

/* Send DSN for successful messages if requested */
addr_senddsn = NULL;

for (addr_dsntmp = addr_succeed; addr_dsntmp; addr_dsntmp = addr_dsntmp->next)
  {
  /* af_ignore_error not honored here. it's not an error */
  DEBUG(D_deliver) debug_printf("DSN: processing router : %s\n"
      "DSN: processing successful delivery address: %s\n"
      "DSN: Sender_address: %s\n"
      "DSN: orcpt: %s  flags: %d\n"
      "DSN: envid: %s  ret: %d\n"
      "DSN: Final recipient: %s\n"
      "DSN: Remote SMTP server supports DSN: %d\n",
      addr_dsntmp->router ? addr_dsntmp->router->name : US"(unknown)",
      addr_dsntmp->address,
      sender_address,
      addr_dsntmp->dsn_orcpt ? addr_dsntmp->dsn_orcpt : US"NULL",
      addr_dsntmp->dsn_flags,
      dsn_envid ? dsn_envid : US"NULL", dsn_ret,
      addr_dsntmp->address,
      addr_dsntmp->dsn_aware
      );

  /* send report if next hop not DSN aware or a router flagged "last DSN hop"
     and a report was requested */
  if (  (  addr_dsntmp->dsn_aware != dsn_support_yes
	|| addr_dsntmp->dsn_flags & rf_dsnlasthop
        )
     && addr_dsntmp->dsn_flags & rf_dsnflags
     && addr_dsntmp->dsn_flags & rf_notify_success
     )
    {
    /* copy and relink address_item and send report with all of them at once later */
    address_item * addr_next = addr_senddsn;
    addr_senddsn = store_get(sizeof(address_item));
    *addr_senddsn = *addr_dsntmp;
    addr_senddsn->next = addr_next;
    }
  else
    DEBUG(D_deliver) debug_printf("DSN: not sending DSN success message\n");
  }

if (addr_senddsn)
  {
  pid_t pid;
  int fd;

  /* create exim process to send message */
  pid = child_open_exim(&fd);

  DEBUG(D_deliver) debug_printf("DSN: child_open_exim returns: %d\n", pid);

  if (pid < 0)  /* Creation of child failed */
    {
    log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Process %d (parent %d) failed to "
      "create child process to send failure message: %s", getpid(),
      getppid(), strerror(errno));

    DEBUG(D_deliver) debug_printf("DSN: child_open_exim failed\n");
    }
  else  /* Creation of child succeeded */
    {
    FILE *f = fdopen(fd, "wb");
    /* header only as required by RFC. only failure DSN needs to honor RET=FULL */
    uschar * bound;
    transport_ctx tctx = {{0}};

    DEBUG(D_deliver)
      debug_printf("sending error message to: %s\n", sender_address);

    /* build unique id for MIME boundary */
    bound = string_sprintf(TIME_T_FMT "-eximdsn-%d", time(NULL), rand());
    DEBUG(D_deliver) debug_printf("DSN: MIME boundary: %s\n", bound);

    if (errors_reply_to)
      fprintf(f, "Reply-To: %s\n", errors_reply_to);

    fprintf(f, "Auto-Submitted: auto-generated\n"
	"From: Mail Delivery System <Mailer-Daemon@%s>\n"
	"To: %s\n"
	"Subject: Delivery Status Notification\n"
	"Content-Type: multipart/report; report-type=delivery-status; boundary=%s\n"
	"MIME-Version: 1.0\n\n"

	"--%s\n"
	"Content-type: text/plain; charset=us-ascii\n\n"

	"This message was created automatically by mail delivery software.\n"
	" ----- The following addresses had successful delivery notifications -----\n",
      qualify_domain_sender, sender_address, bound, bound);

    for (addr_dsntmp = addr_senddsn; addr_dsntmp;
	 addr_dsntmp = addr_dsntmp->next)
      fprintf(f, "<%s> (relayed %s)\n\n",
	addr_dsntmp->address,
	(addr_dsntmp->dsn_flags & rf_dsnlasthop) == 1
	  ? "via non DSN router"
	  : addr_dsntmp->dsn_aware == dsn_support_no
	  ? "to non-DSN-aware mailer"
	  : "via non \"Remote SMTP\" router"
	);

    fprintf(f, "--%s\n"
	"Content-type: message/delivery-status\n\n"
	"Reporting-MTA: dns; %s\n",
      bound, smtp_active_hostname);

    if (dsn_envid)
      {			/* must be decoded from xtext: see RFC 3461:6.3a */
      uschar *xdec_envid;
      if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0)
        fprintf(f, "Original-Envelope-ID: %s\n", dsn_envid);
      else
        fprintf(f, "X-Original-Envelope-ID: error decoding xtext formatted ENVID\n");
      }
    fputc('\n', f);

    for (addr_dsntmp = addr_senddsn;
	 addr_dsntmp;
	 addr_dsntmp = addr_dsntmp->next)
      {
      if (addr_dsntmp->dsn_orcpt)
        fprintf(f,"Original-Recipient: %s\n", addr_dsntmp->dsn_orcpt);

      fprintf(f, "Action: delivered\n"
	  "Final-Recipient: rfc822;%s\n"
	  "Status: 2.0.0\n",
	addr_dsntmp->address);

      if (addr_dsntmp->host_used && addr_dsntmp->host_used->name)
        fprintf(f, "Remote-MTA: dns; %s\nDiagnostic-Code: smtp; 250 Ok\n\n",
	  addr_dsntmp->host_used->name);
      else
	fprintf(f, "Diagnostic-Code: X-Exim; relayed via non %s router\n\n",
	  (addr_dsntmp->dsn_flags & rf_dsnlasthop) == 1 ? "DSN" : "SMTP");
      }

    fprintf(f, "--%s\nContent-type: text/rfc822-headers\n\n", bound);

    fflush(f);
    transport_filter_argv = NULL;   /* Just in case */
    return_path = sender_address;   /* In case not previously set */

    /* Write the original email out */

    tctx.u.fd = fileno(f);
    tctx.options = topt_add_return_path | topt_no_body;
    transport_write_message(&tctx, 0);
    fflush(f);

    fprintf(f,"\n--%s--\n", bound);

    fflush(f);
    fclose(f);
    rc = child_close(pid, 0);     /* Waits for child to close, no timeout */
    }
  }

/* If any addresses failed, we must send a message to somebody, unless
af_ignore_error is set, in which case no action is taken. It is possible for
several messages to get sent if there are addresses with different
requirements. */

while (addr_failed)
  {
  pid_t pid;
  int fd;
  uschar *logtod = tod_stamp(tod_log);
  address_item *addr;
  address_item *handled_addr = NULL;
  address_item **paddr;
  address_item *msgchain = NULL;
  address_item **pmsgchain = &msgchain;

  /* There are weird cases when logging is disabled in the transport. However,
  there may not be a transport (address failed by a router). */

  f.disable_logging = FALSE;
  if (addr_failed->transport)
    f.disable_logging = addr_failed->transport->disable_logging;

  DEBUG(D_deliver)
    debug_printf("processing failed address %s\n", addr_failed->address);

  /* There are only two ways an address in a bounce message can get here:

  (1) When delivery was initially deferred, but has now timed out (in the call
      to retry_update() above). We can detect this by testing for
      af_retry_timedout. If the address does not have its own errors address,
      we arrange to ignore the error.

  (2) If delivery failures for bounce messages are being ignored. We can detect
      this by testing for af_ignore_error. This will also be set if a bounce
      message has been autothawed and the ignore_bounce_errors_after time has
      passed. It might also be set if a router was explicitly configured to
      ignore errors (errors_to = "").

  If neither of these cases obtains, something has gone wrong. Log the
  incident, but then ignore the error. */

  if (sender_address[0] == 0 && !addr_failed->prop.errors_address)
    {
    if (  !testflag(addr_failed, af_retry_timedout)
       && !addr_failed->prop.ignore_error)
      log_write(0, LOG_MAIN|LOG_PANIC, "internal error: bounce message "
        "failure is neither frozen nor ignored (it's been ignored)");

    addr_failed->prop.ignore_error = TRUE;
    }

  /* If the first address on the list has af_ignore_error set, just remove
  it from the list, throw away any saved message file, log it, and
  mark the recipient done. */

  if (  addr_failed->prop.ignore_error
     || (  addr_failed->dsn_flags & rf_dsnflags
        && (addr_failed->dsn_flags & rf_notify_failure) != rf_notify_failure
     )  )
    {
    addr = addr_failed;
    addr_failed = addr->next;
    if (addr->return_filename) Uunlink(addr->return_filename);

    log_write(0, LOG_MAIN, "%s%s%s%s: error ignored",
      addr->address,
      !addr->parent ? US"" : US" <",
      !addr->parent ? US"" : addr->parent->address,
      !addr->parent ? US"" : US">");

    address_done(addr, logtod);
    child_done(addr, logtod);
    /* Panic-dies on error */
    (void)spool_write_header(message_id, SW_DELIVERING, NULL);
    }

  /* Otherwise, handle the sending of a message. Find the error address for
  the first address, then send a message that includes all failed addresses
  that have the same error address. Note the bounce_recipient is a global so
  that it can be accessed by $bounce_recipient while creating a customized
  error message. */

  else
    {
    if (!(bounce_recipient = addr_failed->prop.errors_address))
      bounce_recipient = sender_address;

    /* Make a subprocess to send a message */

    if ((pid = child_open_exim(&fd)) < 0)
      log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Process %d (parent %d) failed to "
        "create child process to send failure message: %s", getpid(),
        getppid(), strerror(errno));

    /* Creation of child succeeded */

    else
      {
      int ch, rc;
      int filecount = 0;
      int rcount = 0;
      uschar *bcc, *emf_text;
      FILE * fp = fdopen(fd, "wb");
      FILE * emf = NULL;
      BOOL to_sender = strcmpic(sender_address, bounce_recipient) == 0;
      int max = (bounce_return_size_limit/DELIVER_IN_BUFFER_SIZE + 1) *
        DELIVER_IN_BUFFER_SIZE;
      uschar * bound;
      uschar *dsnlimitmsg;
      uschar *dsnnotifyhdr;
      int topt;

      DEBUG(D_deliver)
        debug_printf("sending error message to: %s\n", bounce_recipient);

      /* Scan the addresses for all that have the same errors address, removing
      them from the addr_failed chain, and putting them on msgchain. */

      paddr = &addr_failed;
      for (addr = addr_failed; addr; addr = *paddr)
        if (Ustrcmp(bounce_recipient, addr->prop.errors_address
	      ? addr->prop.errors_address : sender_address) == 0)
          {                          /* The same - dechain */
          *paddr = addr->next;
          *pmsgchain = addr;
          addr->next = NULL;
          pmsgchain = &(addr->next);
          }
        else
          paddr = &addr->next;        /* Not the same; skip */

      /* Include X-Failed-Recipients: for automatic interpretation, but do
      not let any one header line get too long. We do this by starting a
      new header every 50 recipients. Omit any addresses for which the
      "hide_child" flag is set. */

      for (addr = msgchain; addr; addr = addr->next)
        {
        if (testflag(addr, af_hide_child)) continue;
        if (rcount >= 50)
          {
          fprintf(fp, "\n");
          rcount = 0;
          }
        fprintf(fp, "%s%s",
          rcount++ == 0
	  ? "X-Failed-Recipients: "
	  : ",\n  ",
          testflag(addr, af_pfr) && addr->parent
	  ? string_printing(addr->parent->address)
	  : string_printing(addr->address));
        }
      if (rcount > 0) fprintf(fp, "\n");

      /* Output the standard headers */

      if (errors_reply_to)
        fprintf(fp, "Reply-To: %s\n", errors_reply_to);
      fprintf(fp, "Auto-Submitted: auto-replied\n");
      moan_write_from(fp);
      fprintf(fp, "To: %s\n", bounce_recipient);

      /* generate boundary string and output MIME-Headers */
      bound = string_sprintf(TIME_T_FMT "-eximdsn-%d", time(NULL), rand());

      fprintf(fp, "Content-Type: multipart/report;"
	    " report-type=delivery-status; boundary=%s\n"
	  "MIME-Version: 1.0\n",
	bound);

      /* Open a template file if one is provided. Log failure to open, but
      carry on - default texts will be used. */

      if (bounce_message_file)
        if (!(emf = Ufopen(bounce_message_file, "rb")))
          log_write(0, LOG_MAIN|LOG_PANIC, "Failed to open %s for error "
            "message texts: %s", bounce_message_file, strerror(errno));

      /* Quietly copy to configured additional addresses if required. */

      if ((bcc = moan_check_errorcopy(bounce_recipient)))
	fprintf(fp, "Bcc: %s\n", bcc);

      /* The texts for the message can be read from a template file; if there
      isn't one, or if it is too short, built-in texts are used. The first
      emf text is a Subject: and any other headers. */

      if ((emf_text = next_emf(emf, US"header")))
	fprintf(fp, "%s\n", emf_text);
      else
        fprintf(fp, "Subject: Mail delivery failed%s\n\n",
          to_sender? ": returning message to sender" : "");

      /* output human readable part as text/plain section */
      fprintf(fp, "--%s\n"
	  "Content-type: text/plain; charset=us-ascii\n\n",
	bound);

      if ((emf_text = next_emf(emf, US"intro")))
	fprintf(fp, "%s", CS emf_text);
      else
        {
        fprintf(fp,
/* This message has been reworded several times. It seems to be confusing to
somebody, however it is worded. I have retreated to the original, simple
wording. */
"This message was created automatically by mail delivery software.\n");

        if (bounce_message_text)
	  fprintf(fp, "%s", CS bounce_message_text);
        if (to_sender)
          fprintf(fp,
"\nA message that you sent could not be delivered to one or more of its\n"
"recipients. This is a permanent error. The following address(es) failed:\n");
        else
          fprintf(fp,
"\nA message sent by\n\n  <%s>\n\n"
"could not be delivered to one or more of its recipients. The following\n"
"address(es) failed:\n", sender_address);
        }
      fputc('\n', fp);

      /* Process the addresses, leaving them on the msgchain if they have a
      file name for a return message. (There has already been a check in
      post_process_one() for the existence of data in the message file.) A TRUE
      return from print_address_information() means that the address is not
      hidden. */

      paddr = &msgchain;
      for (addr = msgchain; addr; addr = *paddr)
        {
        if (print_address_information(addr, fp, US"  ", US"\n    ", US""))
          print_address_error(addr, fp, US"");

        /* End the final line for the address */

        fputc('\n', fp);

        /* Leave on msgchain if there's a return file. */

        if (addr->return_file >= 0)
          {
          paddr = &(addr->next);
          filecount++;
          }

        /* Else save so that we can tick off the recipient when the
        message is sent. */

        else
          {
          *paddr = addr->next;
          addr->next = handled_addr;
          handled_addr = addr;
          }
        }

      fputc('\n', fp);

      /* Get the next text, whether we need it or not, so as to be
      positioned for the one after. */

      emf_text = next_emf(emf, US"generated text");

      /* If there were any file messages passed by the local transports,
      include them in the message. Then put the address on the handled chain.
      In the case of a batch of addresses that were all sent to the same
      transport, the return_file field in all of them will contain the same
      fd, and the return_filename field in the *last* one will be set (to the
      name of the file). */

      if (msgchain)
        {
        address_item *nextaddr;

        if (emf_text)
	  fprintf(fp, "%s", CS emf_text);
	else
          fprintf(fp,
            "The following text was generated during the delivery "
            "attempt%s:\n", (filecount > 1)? "s" : "");

        for (addr = msgchain; addr; addr = nextaddr)
          {
          FILE *fm;
          address_item *topaddr = addr;

          /* List all the addresses that relate to this file */

	  fputc('\n', fp);
          while(addr)                   /* Insurance */
            {
            print_address_information(addr, fp, US"------ ",  US"\n       ",
              US" ------\n");
            if (addr->return_filename) break;
            addr = addr->next;
            }
	  fputc('\n', fp);

          /* Now copy the file */

          if (!(fm = Ufopen(addr->return_filename, "rb")))
            fprintf(fp, "    +++ Exim error... failed to open text file: %s\n",
              strerror(errno));
          else
            {
            while ((ch = fgetc(fm)) != EOF) fputc(ch, fp);
            (void)fclose(fm);
            }
          Uunlink(addr->return_filename);

          /* Can now add to handled chain, first fishing off the next
          address on the msgchain. */

          nextaddr = addr->next;
          addr->next = handled_addr;
          handled_addr = topaddr;
          }
	fputc('\n', fp);
        }

      /* output machine readable part */
#ifdef SUPPORT_I18N
      if (message_smtputf8)
	fprintf(fp, "--%s\n"
	    "Content-type: message/global-delivery-status\n\n"
	    "Reporting-MTA: dns; %s\n",
	  bound, smtp_active_hostname);
      else
#endif
	fprintf(fp, "--%s\n"
	    "Content-type: message/delivery-status\n\n"
	    "Reporting-MTA: dns; %s\n",
	  bound, smtp_active_hostname);

      if (dsn_envid)
	{
        /* must be decoded from xtext: see RFC 3461:6.3a */
        uschar *xdec_envid;
        if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0)
          fprintf(fp, "Original-Envelope-ID: %s\n", dsn_envid);
        else
          fprintf(fp, "X-Original-Envelope-ID: error decoding xtext formatted ENVID\n");
        }
      fputc('\n', fp);

      for (addr = handled_addr; addr; addr = addr->next)
        {
	host_item * hu;
        fprintf(fp, "Action: failed\n"
	    "Final-Recipient: rfc822;%s\n"
	    "Status: 5.0.0\n",
	    addr->address);
        if ((hu = addr->host_used) && hu->name)
	  {
	  fprintf(fp, "Remote-MTA: dns; %s\n", hu->name);
#ifdef EXPERIMENTAL_DSN_INFO
	  {
	  const uschar * s;
	  if (hu->address)
	    {
	    uschar * p = hu->port == 25
	      ? US"" : string_sprintf(":%d", hu->port);
	    fprintf(fp, "Remote-MTA: X-ip; [%s]%s\n", hu->address, p);
	    }
	  if ((s = addr->smtp_greeting) && *s)
	    fprintf(fp, "X-Remote-MTA-smtp-greeting: X-str; %s\n", s);
	  if ((s = addr->helo_response) && *s)
	    fprintf(fp, "X-Remote-MTA-helo-response: X-str; %s\n", s);
	  if ((s = addr->message) && *s)
	    fprintf(fp, "X-Exim-Diagnostic: X-str; %s\n", s);
	  }
#endif
	  print_dsn_diagnostic_code(addr, fp);
	  }
	fputc('\n', fp);
        }

      /* Now copy the message, trying to give an intelligible comment if
      it is too long for it all to be copied. The limit isn't strictly
      applied because of the buffering. There is, however, an option
      to suppress copying altogether. */

      emf_text = next_emf(emf, US"copy");

      /* add message body
         we ignore the intro text from template and add
         the text for bounce_return_size_limit at the end.

         bounce_return_message is ignored
         in case RET= is defined we honor these values
         otherwise bounce_return_body is honored.

         bounce_return_size_limit is always honored.
      */

      fprintf(fp, "--%s\n", bound);

      dsnlimitmsg = US"X-Exim-DSN-Information: Due to administrative limits only headers are returned";
      dsnnotifyhdr = NULL;
      topt = topt_add_return_path;

      /* RET=HDRS? top priority */
      if (dsn_ret == dsn_ret_hdrs)
        topt |= topt_no_body;
      else
	{
	struct stat statbuf;

        /* no full body return at all? */
        if (!bounce_return_body)
          {
          topt |= topt_no_body;
          /* add header if we overrule RET=FULL */
          if (dsn_ret == dsn_ret_full)
            dsnnotifyhdr = dsnlimitmsg;
          }
	/* line length limited... return headers only if oversize */
        /* size limited ... return headers only if limit reached */
	else if (  max_received_linelength > bounce_return_linesize_limit
		|| (  bounce_return_size_limit > 0
		   && fstat(deliver_datafile, &statbuf) == 0
		   && statbuf.st_size > max
		)  )
	  {
	  topt |= topt_no_body;
	  dsnnotifyhdr = dsnlimitmsg;
          }
	}

#ifdef SUPPORT_I18N
      if (message_smtputf8)
	fputs(topt & topt_no_body ? "Content-type: message/global-headers\n\n"
				  : "Content-type: message/global\n\n",
	      fp);
      else
#endif
	fputs(topt & topt_no_body ? "Content-type: text/rfc822-headers\n\n"
				  : "Content-type: message/rfc822\n\n",
	      fp);

      fflush(fp);
      transport_filter_argv = NULL;   /* Just in case */
      return_path = sender_address;   /* In case not previously set */
	{			      /* Dummy transport for headers add */
	transport_ctx tctx = {{0}};
	transport_instance tb = {0};

	tctx.u.fd = fileno(fp);
	tctx.tblock = &tb;
	tctx.options = topt;
	tb.add_headers = dsnnotifyhdr;

	transport_write_message(&tctx, 0);
	}
      fflush(fp);

      /* we never add the final text. close the file */
      if (emf)
        (void)fclose(emf);

      fprintf(fp, "\n--%s--\n", bound);

      /* Close the file, which should send an EOF to the child process
      that is receiving the message. Wait for it to finish. */

      (void)fclose(fp);
      rc = child_close(pid, 0);     /* Waits for child to close, no timeout */

      /* In the test harness, let the child do it's thing first. */

      if (f.running_in_test_harness) millisleep(500);

      /* If the process failed, there was some disaster in setting up the
      error message. Unless the message is very old, ensure that addr_defer
      is non-null, which will have the effect of leaving the message on the
      spool. The failed addresses will get tried again next time. However, we
      don't really want this to happen too often, so freeze the message unless
      there are some genuine deferred addresses to try. To do this we have
      to call spool_write_header() here, because with no genuine deferred
      addresses the normal code below doesn't get run. */

      if (rc != 0)
        {
        uschar *s = US"";
        if (now - received_time.tv_sec < retry_maximum_timeout && !addr_defer)
          {
          addr_defer = (address_item *)(+1);
          f.deliver_freeze = TRUE;
          deliver_frozen_at = time(NULL);
          /* Panic-dies on error */
          (void)spool_write_header(message_id, SW_DELIVERING, NULL);
          s = US" (frozen)";
          }
        deliver_msglog("Process failed (%d) when writing error message "
          "to %s%s", rc, bounce_recipient, s);
        log_write(0, LOG_MAIN, "Process failed (%d) when writing error message "
          "to %s%s", rc, bounce_recipient, s);
        }

      /* The message succeeded. Ensure that the recipients that failed are
      now marked finished with on the spool and their parents updated. */

      else
        {
        for (addr = handled_addr; addr; addr = addr->next)
          {
          address_done(addr, logtod);
          child_done(addr, logtod);
          }
        /* Panic-dies on error */
        (void)spool_write_header(message_id, SW_DELIVERING, NULL);
        }
      }
    }
  }

f.disable_logging = FALSE;  /* In case left set */

/* Come here from the mua_wrapper case if routing goes wrong */

DELIVERY_TIDYUP:

/* If there are now no deferred addresses, we are done. Preserve the
message log if so configured, and we are using them. Otherwise, sling it.
Then delete the message itself. */

if (!addr_defer)
  {
  uschar * fname;

  if (message_logs)
    {
    fname = spool_fname(US"msglog", message_subdir, id, US"");
    if (preserve_message_logs)
      {
      int rc;
      uschar * moname = spool_fname(US"msglog.OLD", US"", id, US"");

      if ((rc = Urename(fname, moname)) < 0)
        {
        (void)directory_make(spool_directory,
			      spool_sname(US"msglog.OLD", US""),
			      MSGLOG_DIRECTORY_MODE, TRUE);
        rc = Urename(fname, moname);
        }
      if (rc < 0)
        log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to move %s to the "
          "msglog.OLD directory", fname);
      }
    else
      if (Uunlink(fname) < 0)
        log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to unlink %s: %s",
		  fname, strerror(errno));
    }

  /* Remove the two message files. */

  fname = spool_fname(US"input", message_subdir, id, US"-D");
  if (Uunlink(fname) < 0)
    log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to unlink %s: %s",
      fname, strerror(errno));
  fname = spool_fname(US"input", message_subdir, id, US"-H");
  if (Uunlink(fname) < 0)
    log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to unlink %s: %s",
      fname, strerror(errno));

  /* Log the end of this message, with queue time if requested. */

  if (LOGGING(queue_time_overall))
    log_write(0, LOG_MAIN, "Completed QT=%s", string_timesince(&received_time));
  else
    log_write(0, LOG_MAIN, "Completed");

  /* Unset deliver_freeze so that we won't try to move the spool files further down */
  f.deliver_freeze = FALSE;

#ifndef DISABLE_EVENT
  (void) event_raise(event_action, US"msg:complete", NULL);
#endif
  }

/* If there are deferred addresses, we are keeping this message because it is
not yet completed. Lose any temporary files that were catching output from
pipes for any of the deferred addresses, handle one-time aliases, and see if
the message has been on the queue for so long that it is time to send a warning
message to the sender, unless it is a mailer-daemon. If all deferred addresses
have the same domain, we can set deliver_domain for the expansion of
delay_warning_ condition - if any of them are pipes, files, or autoreplies, use
the parent's domain.

If all the deferred addresses have an error number that indicates "retry time
not reached", skip sending the warning message, because it won't contain the
reason for the delay. It will get sent at the next real delivery attempt.
However, if at least one address has tried, we'd better include all of them in
the message.

If we can't make a process to send the message, don't worry.

For mailing list expansions we want to send the warning message to the
mailing list manager. We can't do a perfect job here, as some addresses may
have different errors addresses, but if we take the errors address from
each deferred address it will probably be right in most cases.

If addr_defer == +1, it means there was a problem sending an error message
for failed addresses, and there were no "real" deferred addresses. The value
was set just to keep the message on the spool, so there is nothing to do here.
*/

else if (addr_defer != (address_item *)(+1))
  {
  address_item *addr;
  uschar *recipients = US"";
  BOOL delivery_attempted = FALSE;

  deliver_domain = testflag(addr_defer, af_pfr)
    ? addr_defer->parent->domain : addr_defer->domain;

  for (addr = addr_defer; addr; addr = addr->next)
    {
    address_item *otaddr;

    if (addr->basic_errno > ERRNO_RETRY_BASE) delivery_attempted = TRUE;

    if (deliver_domain)
      {
      const uschar *d = testflag(addr, af_pfr)
	? addr->parent->domain : addr->domain;

      /* The domain may be unset for an address that has never been routed
      because the system filter froze the message. */

      if (!d || Ustrcmp(d, deliver_domain) != 0)
        deliver_domain = NULL;
      }

    if (addr->return_filename) Uunlink(addr->return_filename);

    /* Handle the case of one-time aliases. If any address in the ancestry
    of this one is flagged, ensure it is in the recipients list, suitably
    flagged, and that its parent is marked delivered. */

    for (otaddr = addr; otaddr; otaddr = otaddr->parent)
      if (otaddr->onetime_parent) break;

    if (otaddr)
      {
      int i;
      int t = recipients_count;

      for (i = 0; i < recipients_count; i++)
        {
        uschar *r = recipients_list[i].address;
        if (Ustrcmp(otaddr->onetime_parent, r) == 0) t = i;
        if (Ustrcmp(otaddr->address, r) == 0) break;
        }

      /* Didn't find the address already in the list, and did find the
      ultimate parent's address in the list, and they really are different
      (i.e. not from an identity-redirect). After adding the recipient,
      update the errors address in the recipients list. */

      if (  i >= recipients_count && t < recipients_count
         && Ustrcmp(otaddr->address, otaddr->parent->address) != 0)
        {
        DEBUG(D_deliver) debug_printf("one_time: adding %s in place of %s\n",
          otaddr->address, otaddr->parent->address);
        receive_add_recipient(otaddr->address, t);
        recipients_list[recipients_count-1].errors_to = otaddr->prop.errors_address;
        tree_add_nonrecipient(otaddr->parent->address);
        update_spool = TRUE;
        }
      }

    /* Except for error messages, ensure that either the errors address for
    this deferred address or, if there is none, the sender address, is on the
    list of recipients for a warning message. */

    if (sender_address[0])
      {
      uschar * s = addr->prop.errors_address;
      if (!s) s = sender_address;
      if (Ustrstr(recipients, s) == NULL)
	recipients = string_sprintf("%s%s%s", recipients,
	  recipients[0] ? "," : "", s);
      }
    }

  /* Send a warning message if the conditions are right. If the condition check
  fails because of a lookup defer, there is nothing we can do. The warning
  is not sent. Another attempt will be made at the next delivery attempt (if
  it also defers). */

  if (  !f.queue_2stage
     && delivery_attempted
     && (  ((addr_defer->dsn_flags & rf_dsnflags) == 0)
        || (addr_defer->dsn_flags & rf_notify_delay) == rf_notify_delay
	)
     && delay_warning[1] > 0
     && sender_address[0] != 0
     && (  !delay_warning_condition
        || expand_check_condition(delay_warning_condition,
            US"delay_warning", US"option")
	)
     )
    {
    int count;
    int show_time;
    int queue_time = time(NULL) - received_time.tv_sec;

    /* When running in the test harness, there's an option that allows us to
    fudge this time so as to get repeatability of the tests. Take the first
    time off the list. In queue runs, the list pointer gets updated in the
    calling process. */

    if (f.running_in_test_harness && fudged_queue_times[0] != 0)
      {
      int qt = readconf_readtime(fudged_queue_times, '/', FALSE);
      if (qt >= 0)
        {
        DEBUG(D_deliver) debug_printf("fudged queue_times = %s\n",
          fudged_queue_times);
        queue_time = qt;
        }
      }

    /* See how many warnings we should have sent by now */

    for (count = 0; count < delay_warning[1]; count++)
      if (queue_time < delay_warning[count+2]) break;

    show_time = delay_warning[count+1];

    if (count >= delay_warning[1])
      {
      int extra;
      int last_gap = show_time;
      if (count > 1) last_gap -= delay_warning[count];
      extra = (queue_time - delay_warning[count+1])/last_gap;
      show_time += last_gap * extra;
      count += extra;
      }

    DEBUG(D_deliver)
      {
      debug_printf("time on queue = %s\n", readconf_printtime(queue_time));
      debug_printf("warning counts: required %d done %d\n", count,
        warning_count);
      }

    /* We have computed the number of warnings there should have been by now.
    If there haven't been enough, send one, and up the count to what it should
    have been. */

    if (warning_count < count)
      {
      header_line *h;
      int fd;
      pid_t pid = child_open_exim(&fd);

      if (pid > 0)
        {
        uschar *wmf_text;
        FILE *wmf = NULL;
        FILE *f = fdopen(fd, "wb");
	uschar * bound;
	transport_ctx tctx = {{0}};

        if (warn_message_file)
          if (!(wmf = Ufopen(warn_message_file, "rb")))
            log_write(0, LOG_MAIN|LOG_PANIC, "Failed to open %s for warning "
              "message texts: %s", warn_message_file, strerror(errno));

        warnmsg_recipients = recipients;
        warnmsg_delay = queue_time < 120*60
	  ? string_sprintf("%d minutes", show_time/60)
	  : string_sprintf("%d hours", show_time/3600);

        if (errors_reply_to)
          fprintf(f, "Reply-To: %s\n", errors_reply_to);
        fprintf(f, "Auto-Submitted: auto-replied\n");
        moan_write_from(f);
        fprintf(f, "To: %s\n", recipients);

        /* generated boundary string and output MIME-Headers */
        bound = string_sprintf(TIME_T_FMT "-eximdsn-%d", time(NULL), rand());

        fprintf(f, "Content-Type: multipart/report;"
	    " report-type=delivery-status; boundary=%s\n"
	    "MIME-Version: 1.0\n",
	  bound);

        if ((wmf_text = next_emf(wmf, US"header")))
          fprintf(f, "%s\n", wmf_text);
        else
          fprintf(f, "Subject: Warning: message %s delayed %s\n\n",
            message_id, warnmsg_delay);

        /* output human readable part as text/plain section */
        fprintf(f, "--%s\n"
	    "Content-type: text/plain; charset=us-ascii\n\n",
	  bound);

        if ((wmf_text = next_emf(wmf, US"intro")))
	  fprintf(f, "%s", CS wmf_text);
	else
          {
          fprintf(f,
"This message was created automatically by mail delivery software.\n");

          if (Ustrcmp(recipients, sender_address) == 0)
            fprintf(f,
"A message that you sent has not yet been delivered to one or more of its\n"
"recipients after more than ");

          else
	    fprintf(f,
"A message sent by\n\n  <%s>\n\n"
"has not yet been delivered to one or more of its recipients after more than \n",
	      sender_address);

          fprintf(f, "%s on the queue on %s.\n\n"
	      "The message identifier is:     %s\n",
	    warnmsg_delay, primary_hostname, message_id);

          for (h = header_list; h; h = h->next)
            if (strncmpic(h->text, US"Subject:", 8) == 0)
              fprintf(f, "The subject of the message is: %s", h->text + 9);
            else if (strncmpic(h->text, US"Date:", 5) == 0)
              fprintf(f, "The date of the message is:    %s", h->text + 6);
          fputc('\n', f);

          fprintf(f, "The address%s to which the message has not yet been "
            "delivered %s:\n",
            !addr_defer->next ? "" : "es",
            !addr_defer->next ? "is": "are");
          }

        /* List the addresses, with error information if allowed */

        /* store addr_defer for machine readable part */
        address_item *addr_dsndefer = addr_defer;
        fputc('\n', f);
        while (addr_defer)
          {
          address_item *addr = addr_defer;
          addr_defer = addr->next;
          if (print_address_information(addr, f, US"  ", US"\n    ", US""))
            print_address_error(addr, f, US"Delay reason: ");
          fputc('\n', f);
          }
        fputc('\n', f);

        /* Final text */

        if (wmf)
          {
          if ((wmf_text = next_emf(wmf, US"final")))
	    fprintf(f, "%s", CS wmf_text);
          (void)fclose(wmf);
          }
        else
          {
          fprintf(f,
"No action is required on your part. Delivery attempts will continue for\n"
"some time, and this warning may be repeated at intervals if the message\n"
"remains undelivered. Eventually the mail delivery software will give up,\n"
"and when that happens, the message will be returned to you.\n");
          }

        /* output machine readable part */
        fprintf(f, "\n--%s\n"
	    "Content-type: message/delivery-status\n\n"
	    "Reporting-MTA: dns; %s\n",
	  bound,
	  smtp_active_hostname);


        if (dsn_envid)
	  {
          /* must be decoded from xtext: see RFC 3461:6.3a */
          uschar *xdec_envid;
          if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0)
            fprintf(f,"Original-Envelope-ID: %s\n", dsn_envid);
          else
            fprintf(f,"X-Original-Envelope-ID: error decoding xtext formatted ENVID\n");
          }
        fputc('\n', f);

        for ( ; addr_dsndefer; addr_dsndefer = addr_dsndefer->next)
          {
          if (addr_dsndefer->dsn_orcpt)
            fprintf(f, "Original-Recipient: %s\n", addr_dsndefer->dsn_orcpt);

          fprintf(f, "Action: delayed\n"
	      "Final-Recipient: rfc822;%s\n"
	      "Status: 4.0.0\n",
	    addr_dsndefer->address);
          if (addr_dsndefer->host_used && addr_dsndefer->host_used->name)
            {
            fprintf(f, "Remote-MTA: dns; %s\n",
		    addr_dsndefer->host_used->name);
            print_dsn_diagnostic_code(addr_dsndefer, f);
            }
	  fputc('\n', f);
          }

        fprintf(f, "--%s\n"
	    "Content-type: text/rfc822-headers\n\n",
	  bound);

        fflush(f);
        /* header only as required by RFC. only failure DSN needs to honor RET=FULL */
	tctx.u.fd = fileno(f);
        tctx.options = topt_add_return_path | topt_no_body;
        transport_filter_argv = NULL;   /* Just in case */
        return_path = sender_address;   /* In case not previously set */

        /* Write the original email out */
        transport_write_message(&tctx, 0);
        fflush(f);

        fprintf(f,"\n--%s--\n", bound);

        fflush(f);

        /* Close and wait for child process to complete, without a timeout.
        If there's an error, don't update the count. */

        (void)fclose(f);
        if (child_close(pid, 0) == 0)
          {
          warning_count = count;
          update_spool = TRUE;    /* Ensure spool rewritten */
          }
        }
      }
    }

  /* Clear deliver_domain */

  deliver_domain = NULL;

  /* If this was a first delivery attempt, unset the first time flag, and
  ensure that the spool gets updated. */

  if (f.deliver_firsttime)
    {
    f.deliver_firsttime = FALSE;
    update_spool = TRUE;
    }

  /* If delivery was frozen and freeze_tell is set, generate an appropriate
  message, unless the message is a local error message (to avoid loops). Then
  log the freezing. If the text in "frozen_info" came from a system filter,
  it has been escaped into printing characters so as not to mess up log lines.
  For the "tell" message, we turn \n back into newline. Also, insert a newline
  near the start instead of the ": " string. */

  if (f.deliver_freeze)
    {
    if (freeze_tell && freeze_tell[0] != 0 && !f.local_error_message)
      {
      uschar *s = string_copy(frozen_info);
      uschar *ss = Ustrstr(s, " by the system filter: ");

      if (ss != NULL)
        {
        ss[21] = '.';
        ss[22] = '\n';
        }

      ss = s;
      while (*ss != 0)
        {
        if (*ss == '\\' && ss[1] == 'n')
          {
          *ss++ = ' ';
          *ss++ = '\n';
          }
        else ss++;
        }
      moan_tell_someone(freeze_tell, addr_defer, US"Message frozen",
        "Message %s has been frozen%s.\nThe sender is <%s>.\n", message_id,
        s, sender_address);
      }

    /* Log freezing just before we update the -H file, to minimize the chance
    of a race problem. */

    deliver_msglog("*** Frozen%s\n", frozen_info);
    log_write(0, LOG_MAIN, "Frozen%s", frozen_info);
    }

  /* If there have been any updates to the non-recipients list, or other things
  that get written to the spool, we must now update the spool header file so
  that it has the right information for the next delivery attempt. If there
  was more than one address being delivered, the header_change update is done
  earlier, in case one succeeds and then something crashes. */

  DEBUG(D_deliver)
    debug_printf("delivery deferred: update_spool=%d header_rewritten=%d\n",
      update_spool, f.header_rewritten);

  if (update_spool || f.header_rewritten)
    /* Panic-dies on error */
    (void)spool_write_header(message_id, SW_DELIVERING, NULL);
  }

/* Finished with the message log. If the message is complete, it will have
been unlinked or renamed above. */

if (message_logs) (void)fclose(message_log);

/* Now we can close and remove the journal file. Its only purpose is to record
successfully completed deliveries asap so that this information doesn't get
lost if Exim (or the machine) crashes. Forgetting about a failed delivery is
not serious, as trying it again is not harmful. The journal might not be open
if all addresses were deferred at routing or directing. Nevertheless, we must
remove it if it exists (may have been lying around from a crash during the
previous delivery attempt). We don't remove the journal if a delivery
subprocess failed to pass back delivery information; this is controlled by
the remove_journal flag. When the journal is left, we also don't move the
message off the main spool if frozen and the option is set. It should get moved
at the next attempt, after the journal has been inspected. */

if (journal_fd >= 0) (void)close(journal_fd);

if (remove_journal)
  {
  uschar * fname = spool_fname(US"input", message_subdir, id, US"-J");

  if (Uunlink(fname) < 0 && errno != ENOENT)
    log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to unlink %s: %s", fname,
      strerror(errno));

  /* Move the message off the spool if requested */

#ifdef SUPPORT_MOVE_FROZEN_MESSAGES
  if (f.deliver_freeze && move_frozen_messages)
    (void)spool_move_message(id, message_subdir, US"", US"F");
#endif
  }

/* Closing the data file frees the lock; if the file has been unlinked it
will go away. Otherwise the message becomes available for another process
to try delivery. */

(void)close(deliver_datafile);
deliver_datafile = -1;
DEBUG(D_deliver) debug_printf("end delivery of %s\n", id);

/* It is unlikely that there will be any cached resources, since they are
released after routing, and in the delivery subprocesses. However, it's
possible for an expansion for something afterwards (for example,
expand_check_condition) to do a lookup. We must therefore be sure everything is
released. */

search_tidyup();
acl_where = ACL_WHERE_UNKNOWN;
return final_yield;
}

Project: exim
File: queue.c

spool_fname(const uschar * purpose, const uschar * subdir, const uschar * fname,
       	const uschar * suffix)
{
return string_sprintf("%s/%s/%s/%s/%s%s",
	spool_directory, queue_name, purpose, subdir, fname, suffix);
}

Project: exim
File: queue.c

queue_list(int option, uschar **list, int count)
{
int i;
int subcount;
int now = (int)time(NULL);
void *reset_point;
queue_filename * qf = NULL;
uschar subdirs[64];

/* If given a list of messages, build a chain containing their ids. */

if (count > 0)
  {
  queue_filename *last = NULL;
  for (i = 0; i < count; i++)
    {
    queue_filename *next =
      store_get(sizeof(queue_filename) + Ustrlen(list[i]) + 2);
    sprintf(CS next->text, "%s-H", list[i]);
    next->dir_uschar = '*';
    next->next = NULL;
    if (i == 0) qf = next; else last->next = next;
    last = next;
    }
  }

/* Otherwise get a list of the entire queue, in order if necessary. */

else
  qf = queue_get_spool_list(
          -1,             /* entire queue */
          subdirs,        /* for holding sub list */
          &subcount,      /* for subcount */
          option >= 8);   /* randomize if required */

if (option >= 8) option -= 8;

/* Now scan the chain and print information, resetting store used
each time. */

for (reset_point = store_get(0);
    qf;
    spool_clear_header_globals(), store_reset(reset_point), qf = qf->next
    )
  {
  int rc, save_errno;
  int size = 0;
  BOOL env_read;

  message_size = 0;
  message_subdir[0] = qf->dir_uschar;
  rc = spool_read_header(qf->text, FALSE, count <= 0);
  if (rc == spool_read_notopen && errno == ENOENT && count <= 0)
    continue;
  save_errno = errno;

  env_read = (rc == spool_read_OK || rc == spool_read_hdrerror);

  if (env_read)
    {
    int ptr;
    FILE *jread;
    struct stat statbuf;
    uschar * fname = spool_fname(US"input", message_subdir, qf->text, US"");

    ptr = Ustrlen(fname)-1;
    fname[ptr] = 'D';

    /* Add the data size to the header size; don't count the file name
    at the start of the data file, but add one for the notional blank line
    that precedes the data. */

    if (Ustat(fname, &statbuf) == 0)
      size = message_size + statbuf.st_size - SPOOL_DATA_START_OFFSET + 1;
    i = (now - received_time.tv_sec)/60;  /* minutes on queue */
    if (i > 90)
      {
      i = (i + 30)/60;
      if (i > 72) printf("%2dd ", (i + 12)/24); else printf("%2dh ", i);
      }
    else printf("%2dm ", i);

    /* Collect delivered addresses from any J file */

    fname[ptr] = 'J';
    if ((jread = Ufopen(fname, "rb")))
      {
      while (Ufgets(big_buffer, big_buffer_size, jread) != NULL)
        {
        int n = Ustrlen(big_buffer);
        big_buffer[n-1] = 0;
        tree_add_nonrecipient(big_buffer);
        }
      (void)fclose(jread);
      }
    }

  fprintf(stdout, "%s ", string_format_size(size, big_buffer));
  for (i = 0; i < 16; i++) fputc(qf->text[i], stdout);

  if (env_read && sender_address)
    {
    printf(" <%s>", sender_address);
    if (f.sender_set_untrusted) printf(" (%s)", originator_login);
    }

  if (rc != spool_read_OK)
    {
    printf("\n    ");
    if (save_errno == ERRNO_SPOOLFORMAT)
      {
      struct stat statbuf;
      uschar * fname = spool_fname(US"input", message_subdir, qf->text, US"");

      if (Ustat(fname, &statbuf) == 0)
        printf("*** spool format error: size=" OFF_T_FMT " ***",
          statbuf.st_size);
      else printf("*** spool format error ***");
      }
    else printf("*** spool read error: %s ***", strerror(save_errno));
    if (rc != spool_read_hdrerror)
      {
      printf("\n\n");
      continue;
      }
    }

  if (f.deliver_freeze) printf(" *** frozen ***");

  printf("\n");

  if (recipients_list)
    {
    for (i = 0; i < recipients_count; i++)
      {
      tree_node *delivered =
        tree_search(tree_nonrecipients, recipients_list[i].address);
      if (!delivered || option != 1)
        printf("        %s %s\n",
	  delivered ? "D" : " ", recipients_list[i].address);
      if (delivered) delivered->data.val = TRUE;
      }
    if (option == 2 && tree_nonrecipients)
      queue_list_extras(tree_nonrecipients);
    printf("\n");
    }
  }
}

Project: exim
File: deliver.c

do_remote_deliveries(BOOL fallback)
{
int parmax;
int delivery_count;
int poffset;

parcount = 0;    /* Number of executing subprocesses */

/* When sending down an existing channel, only do one delivery at a time.
We use a local variable (parmax) to hold the maximum number of processes;
this gets reduced from remote_max_parallel if we can't create enough pipes. */

if (continue_transport) remote_max_parallel = 1;
parmax = remote_max_parallel;

/* If the data for keeping a list of processes hasn't yet been
set up, do so. */

if (!parlist)
  {
  parlist = store_get(remote_max_parallel * sizeof(pardata));
  for (poffset = 0; poffset < remote_max_parallel; poffset++)
    parlist[poffset].pid = 0;
  }

/* Now loop for each remote delivery */

for (delivery_count = 0; addr_remote; delivery_count++)
  {
  pid_t pid;
  uid_t uid;
  gid_t gid;
  int pfd[2];
  int address_count = 1;
  int address_count_max;
  BOOL multi_domain;
  BOOL use_initgroups;
  BOOL pipe_done = FALSE;
  transport_instance *tp;
  address_item **anchor = &addr_remote;
  address_item *addr = addr_remote;
  address_item *last = addr;
  address_item *next;
  uschar * panicmsg;
  uschar * serialize_key = NULL;

  /* Pull the first address right off the list. */

  addr_remote = addr->next;
  addr->next = NULL;

  DEBUG(D_deliver|D_transport)
    debug_printf("--------> %s <--------\n", addr->address);

  /* If no transport has been set, there has been a big screw-up somewhere. */

  if (!(tp = addr->transport))
    {
    f.disable_logging = FALSE;  /* Jic */
    panicmsg = US"No transport set by router";
    goto panic_continue;
    }

  /* Check that this base address hasn't previously been delivered to this
  transport. The check is necessary at this point to handle homonymic addresses
  correctly in cases where the pattern of redirection changes between delivery
  attempts. Non-homonymic previous delivery is detected earlier, at routing
  time. */

  if (previously_transported(addr, FALSE)) continue;

  /* Force failure if the message is too big. */

  if (tp->message_size_limit)
    {
    int rc = check_message_size(tp, addr);
    if (rc != OK)
      {
      addr->transport_return = rc;
      remote_post_process(addr, LOG_MAIN, NULL, fallback);
      continue;
      }
    }

  /* Get the flag which specifies whether the transport can handle different
  domains that nevertheless resolve to the same set of hosts. If it needs
  expanding, get variables set: $address_data, $domain_data, $localpart_data,
  $host, $host_address, $host_port. */
  if (tp->expand_multi_domain)
    deliver_set_expansions(addr);

  if (exp_bool(addr, US"transport", tp->name, D_transport,
		US"multi_domain", tp->multi_domain, tp->expand_multi_domain,
		&multi_domain) != OK)
    {
    deliver_set_expansions(NULL);
    panicmsg = addr->message;
    goto panic_continue;
    }

  /* Get the maximum it can handle in one envelope, with zero meaning
  unlimited, which is forced for the MUA wrapper case. */

  address_count_max = tp->max_addresses;
  if (address_count_max == 0 || mua_wrapper) address_count_max = 999999;


  /************************************************************************/
  /*****    This is slightly experimental code, but should be safe.   *****/

  /* The address_count_max value is the maximum number of addresses that the
  transport can send in one envelope. However, the transport must be capable of
  dealing with any number of addresses. If the number it gets exceeds its
  envelope limitation, it must send multiple copies of the message. This can be
  done over a single connection for SMTP, so uses less resources than making
  multiple connections. On the other hand, if remote_max_parallel is greater
  than one, it is perhaps a good idea to use parallel processing to move the
  message faster, even if that results in multiple simultaneous connections to
  the same host.

  How can we come to some compromise between these two ideals? What we do is to
  limit the number of addresses passed to a single instance of a transport to
  the greater of (a) its address limit (rcpt_max for SMTP) and (b) the total
  number of addresses routed to remote transports divided by
  remote_max_parallel. For example, if the message has 100 remote recipients,
  remote max parallel is 2, and rcpt_max is 10, we'd never send more than 50 at
  once. But if rcpt_max is 100, we could send up to 100.

  Of course, not all the remotely addresses in a message are going to go to the
  same set of hosts (except in smarthost configurations), so this is just a
  heuristic way of dividing up the work.

  Furthermore (1), because this may not be wanted in some cases, and also to
  cope with really pathological cases, there is also a limit to the number of
  messages that are sent over one connection. This is the same limit that is
  used when sending several different messages over the same connection.
  Continue_sequence is set when in this situation, to the number sent so
  far, including this message.

  Furthermore (2), when somebody explicitly sets the maximum value to 1, it
  is probably because they are using VERP, in which case they want to pass only
  one address at a time to the transport, in order to be able to use
  $local_part and $domain in constructing a new return path. We could test for
  the use of these variables, but as it is so likely they will be used when the
  maximum is 1, we don't bother. Just leave the value alone. */

  if (  address_count_max != 1
     && address_count_max < remote_delivery_count/remote_max_parallel
     )
    {
    int new_max = remote_delivery_count/remote_max_parallel;
    int message_max = tp->connection_max_messages;
    if (connection_max_messages >= 0) message_max = connection_max_messages;
    message_max -= continue_sequence - 1;
    if (message_max > 0 && new_max > address_count_max * message_max)
      new_max = address_count_max * message_max;
    address_count_max = new_max;
    }

  /************************************************************************/


  /* Pick off all addresses which have the same transport, errors address,
  destination, and extra headers. In some cases they point to the same host
  list, but we also need to check for identical host lists generated from
  entirely different domains. The host list pointers can be NULL in the case
  where the hosts are defined in the transport. There is also a configured
  maximum limit of addresses that can be handled at once (see comments above
  for how it is computed).
  If the transport does not handle multiple domains, enforce that also,
  and if it might need a per-address check for this, re-evaluate it.
  */

  while ((next = *anchor) && address_count < address_count_max)
    {
    BOOL md;
    if (  (multi_domain || Ustrcmp(next->domain, addr->domain) == 0)
       && tp == next->transport
       && same_hosts(next->host_list, addr->host_list)
       && same_strings(next->prop.errors_address, addr->prop.errors_address)
       && same_headers(next->prop.extra_headers, addr->prop.extra_headers)
       && same_ugid(tp, next, addr)
       && (  next->prop.remove_headers == addr->prop.remove_headers
	  || (  next->prop.remove_headers
	     && addr->prop.remove_headers
	     && Ustrcmp(next->prop.remove_headers, addr->prop.remove_headers) == 0
	  )  )
       && (  !multi_domain
	  || (  (
		(void)(!tp->expand_multi_domain || ((void)deliver_set_expansions(next), 1)),
	        exp_bool(addr,
		    US"transport", next->transport->name, D_transport,
		    US"multi_domain", next->transport->multi_domain,
		    next->transport->expand_multi_domain, &md) == OK
	        )
	     && md
       )  )  )
      {
      *anchor = next->next;
      next->next = NULL;
      next->first = addr;  /* remember top one (for retry processing) */
      last->next = next;
      last = next;
      address_count++;
      }
    else anchor = &(next->next);
    deliver_set_expansions(NULL);
    }

  /* If we are acting as an MUA wrapper, all addresses must go in a single
  transaction. If not, put them back on the chain and yield FALSE. */

  if (mua_wrapper && addr_remote)
    {
    last->next = addr_remote;
    addr_remote = addr;
    return FALSE;
    }

  /* If the transport is limited for parallellism, enforce that here.
  The hints DB entry is decremented in par_reduce(), when we reap the
  transport process. */

  if (tpt_parallel_check(tp, addr, &serialize_key))
    if ((panicmsg = expand_string_message))
      goto panic_continue;
    else
      continue;			/* Loop for the next set of addresses. */

  /* Set up the expansion variables for this set of addresses */

  deliver_set_expansions(addr);

  /* Ensure any transport-set auth info is fresh */
  addr->authenticator = addr->auth_id = addr->auth_sndr = NULL;

  /* Compute the return path, expanding a new one if required. The old one
  must be set first, as it might be referred to in the expansion. */

  if(addr->prop.errors_address)
    return_path = addr->prop.errors_address;
#ifdef EXPERIMENTAL_SRS
  else if(addr->prop.srs_sender)
    return_path = addr->prop.srs_sender;
#endif
  else
    return_path = sender_address;

  if (tp->return_path)
    {
    uschar *new_return_path = expand_string(tp->return_path);
    if (new_return_path)
      return_path = new_return_path;
    else if (!f.expand_string_forcedfail)
      {
      panicmsg = string_sprintf("Failed to expand return path \"%s\": %s",
	tp->return_path, expand_string_message);
      goto enq_continue;
      }
    }

  /* Find the uid, gid, and use_initgroups setting for this transport. Failure
  logs and sets up error messages, so we just post-process and continue with
  the next address. */

  if (!findugid(addr, tp, &uid, &gid, &use_initgroups))
    {
    panicmsg = NULL;
    goto enq_continue;
    }

  /* If this transport has a setup function, call it now so that it gets
  run in this process and not in any subprocess. That way, the results of
  any setup that are retained by the transport can be reusable. One of the
  things the setup does is to set the fallback host lists in the addresses.
  That is why it is called at this point, before the continue delivery
  processing, because that might use the fallback hosts. */

  if (tp->setup)
    (void)((tp->setup)(addr->transport, addr, NULL, uid, gid, NULL));

  /* If we have a connection still open from a verify stage (lazy-close)
  treat it as if it is a continued connection (apart from the counter used
  for the log line mark). */

  if (cutthrough.cctx.sock >= 0 && cutthrough.callout_hold_only)
    {
    DEBUG(D_deliver)
      debug_printf("lazy-callout-close: have conn still open from verification\n");
    continue_transport = cutthrough.transport;
    continue_hostname = string_copy(cutthrough.host.name);
    continue_host_address = string_copy(cutthrough.host.address);
    continue_sequence = 1;
    sending_ip_address = cutthrough.snd_ip;
    sending_port = cutthrough.snd_port;
    smtp_peer_options = cutthrough.peer_options;
    }

  /* If this is a run to continue delivery down an already-established
  channel, check that this set of addresses matches the transport and
  the channel. If it does not, defer the addresses. If a host list exists,
  we must check that the continue host is on the list. Otherwise, the
  host is set in the transport. */

  f.continue_more = FALSE;           /* In case got set for the last lot */
  if (continue_transport)
    {
    BOOL ok = Ustrcmp(continue_transport, tp->name) == 0;

    /* If the transport is about to override the host list do not check
    it here but take the cost of running the transport process to discover
    if the continued_hostname connection is suitable.  This is a layering
    violation which is unfortunate as it requires we haul in the smtp
    include file. */

    if (ok)
      {
      smtp_transport_options_block * ob;

      if (  !(  Ustrcmp(tp->info->driver_name, "smtp") == 0
	     && (ob = (smtp_transport_options_block *)tp->options_block)
	     && ob->hosts_override && ob->hosts
	     )
	 && addr->host_list
	 )
	{
	host_item * h;
	ok = FALSE;
	for (h = addr->host_list; h; h = h->next)
	  if (Ustrcmp(h->name, continue_hostname) == 0)
  /*XXX should also check port here */
	    { ok = TRUE; break; }
	}
      }

    /* Addresses not suitable; defer or queue for fallback hosts (which
    might be the continue host) and skip to next address. */

    if (!ok)
      {
      DEBUG(D_deliver) debug_printf("not suitable for continue_transport (%s)\n",
	Ustrcmp(continue_transport, tp->name) != 0
	? string_sprintf("tpt %s vs %s", continue_transport, tp->name)
	: string_sprintf("no host matching %s", continue_hostname));
      if (serialize_key) enq_end(serialize_key);

      if (addr->fallback_hosts && !fallback)
        {
	for (next = addr; ; next = next->next)
          {
          next->host_list = next->fallback_hosts;
          DEBUG(D_deliver) debug_printf("%s queued for fallback host(s)\n", next->address);
          if (!next->next) break;
          }
        next->next = addr_fallback;
        addr_fallback = addr;
        }

      else
	{
	for (next = addr; ; next = next->next)
	  {
	  DEBUG(D_deliver) debug_printf(" %s to def list\n", next->address);
          if (!next->next) break;
	  }
	next->next = addr_defer;
	addr_defer = addr;
	}

      continue;
      }

    /* Set a flag indicating whether there are further addresses that list
    the continued host. This tells the transport to leave the channel open,
    but not to pass it to another delivery process. We'd like to do that
    for non-continue_transport cases too but the knowlege of which host is
    connected to is too hard to manage.  Perhaps we need a finer-grain
    interface to the transport. */

    for (next = addr_remote; next && !f.continue_more; next = next->next)
      {
      host_item *h;
      for (h = next->host_list; h; h = h->next)
        if (Ustrcmp(h->name, continue_hostname) == 0)
          { f.continue_more = TRUE; break; }
      }
    }

  /* The transports set up the process info themselves as they may connect
  to more than one remote machine. They also have to set up the filter
  arguments, if required, so that the host name and address are available
  for expansion. */

  transport_filter_argv = NULL;

  /* Create the pipe for inter-process communication. If pipe creation
  fails, it is probably because the value of remote_max_parallel is so
  large that too many file descriptors for pipes have been created. Arrange
  to wait for a process to finish, and then try again. If we still can't
  create a pipe when all processes have finished, break the retry loop. */

  while (!pipe_done)
    {
    if (pipe(pfd) == 0) pipe_done = TRUE;
      else if (parcount > 0) parmax = parcount;
        else break;

    /* We need to make the reading end of the pipe non-blocking. There are
    two different options for this. Exim is cunningly (I hope!) coded so
    that it can use either of them, though it prefers O_NONBLOCK, which
    distinguishes between EOF and no-more-data. */

/* The data appears in a timely manner and we already did a select on
all pipes, so I do not see a reason to use non-blocking IO here

#ifdef O_NONBLOCK
    (void)fcntl(pfd[pipe_read], F_SETFL, O_NONBLOCK);
#else
    (void)fcntl(pfd[pipe_read], F_SETFL, O_NDELAY);
#endif
*/

    /* If the maximum number of subprocesses already exist, wait for a process
    to finish. If we ran out of file descriptors, parmax will have been reduced
    from its initial value of remote_max_parallel. */

    par_reduce(parmax - 1, fallback);
    }

  /* If we failed to create a pipe and there were no processes to wait
  for, we have to give up on this one. Do this outside the above loop
  so that we can continue the main loop. */

  if (!pipe_done)
    {
    panicmsg = string_sprintf("unable to create pipe: %s", strerror(errno));
    goto enq_continue;
    }

  /* Find a free slot in the pardata list. Must do this after the possible
  waiting for processes to finish, because a terminating process will free
  up a slot. */

  for (poffset = 0; poffset < remote_max_parallel; poffset++)
    if (parlist[poffset].pid == 0)
      break;

  /* If there isn't one, there has been a horrible disaster. */

  if (poffset >= remote_max_parallel)
    {
    (void)close(pfd[pipe_write]);
    (void)close(pfd[pipe_read]);
    panicmsg = US"Unexpectedly no free subprocess slot";
    goto enq_continue;
    }

  /* Now fork a subprocess to do the remote delivery, but before doing so,
  ensure that any cached resources are released so as not to interfere with
  what happens in the subprocess. */

  search_tidyup();


  if ((pid = fork()) == 0)
    {
    int fd = pfd[pipe_write];
    host_item *h;
    DEBUG(D_deliver) debug_selector |= D_pid;  // hs12

    /* Setting this global in the subprocess means we need never clear it */
    transport_name = tp->name;

    /* There are weird circumstances in which logging is disabled */
    f.disable_logging = tp->disable_logging;

    /* Show pids on debug output if parallelism possible */

    if (parmax > 1 && (parcount > 0 || addr_remote))
      {
      DEBUG(D_any|D_v) debug_selector |= D_pid;
      DEBUG(D_deliver) debug_printf("Remote delivery process started\n");
      }

    /* Reset the random number generator, so different processes don't all
    have the same sequence. In the test harness we want different, but
    predictable settings for each delivery process, so do something explicit
    here rather they rely on the fixed reset in the random number function. */

    random_seed = f.running_in_test_harness ? 42 + 2*delivery_count : 0;

    /* Set close-on-exec on the pipe so that it doesn't get passed on to
    a new process that may be forked to do another delivery down the same
    SMTP connection. */

    (void)fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);

    /* Close open file descriptors for the pipes of other processes
    that are running in parallel. */

    for (poffset = 0; poffset < remote_max_parallel; poffset++)
      if (parlist[poffset].pid != 0) (void)close(parlist[poffset].fd);

    /* This process has inherited a copy of the file descriptor
    for the data file, but its file pointer is shared with all the
    other processes running in parallel. Therefore, we have to re-open
    the file in order to get a new file descriptor with its own
    file pointer. We don't need to lock it, as the lock is held by
    the parent process. There doesn't seem to be any way of doing
    a dup-with-new-file-pointer. */

    (void)close(deliver_datafile);
    {
    uschar * fname = spool_fname(US"input", message_subdir, message_id, US"-D");

    if ((deliver_datafile = Uopen(fname,
#ifdef O_CLOEXEC
					O_CLOEXEC |
#endif
					O_RDWR | O_APPEND, 0)) < 0)
      log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Failed to reopen %s for remote "
        "parallel delivery: %s", fname, strerror(errno));
    }

    /* Set the close-on-exec flag */
#ifndef O_CLOEXEC
    (void)fcntl(deliver_datafile, F_SETFD, fcntl(deliver_datafile, F_GETFD) |
      FD_CLOEXEC);
#endif

    /* Set the uid/gid of this process; bombs out on failure. */

    exim_setugid(uid, gid, use_initgroups,
      string_sprintf("remote delivery to %s with transport=%s",
        addr->address, tp->name));

    /* Close the unwanted half of this process' pipe, set the process state,
    and run the transport. Afterwards, transport_count will contain the number
    of bytes written. */

    (void)close(pfd[pipe_read]);
    set_process_info("delivering %s using %s", message_id, tp->name);
    debug_print_string(tp->debug_string);
    if (!(tp->info->code)(addr->transport, addr)) replicate_status(addr);

    set_process_info("delivering %s (just run %s for %s%s in subprocess)",
      message_id, tp->name, addr->address, addr->next ? ", ..." : "");

    /* Ensure any cached resources that we used are now released */

    search_tidyup();

    /* Pass the result back down the pipe. This is a lot more information
    than is needed for a local delivery. We have to send back the error
    status for each address, the usability status for each host that is
    flagged as unusable, and all the retry items. When TLS is in use, we
    send also the cipher and peerdn information. Each type of information
    is flagged by an identifying byte, and is then in a fixed format (with
    strings terminated by zeros), and there is a final terminator at the
    end. The host information and retry information is all attached to
    the first address, so that gets sent at the start. */

    /* Host unusability information: for most success cases this will
    be null. */

    for (h = addr->host_list; h; h = h->next)
      {
      if (!h->address || h->status < hstatus_unusable) continue;
      sprintf(CS big_buffer, "%c%c%s", h->status, h->why, h->address);
      rmt_dlv_checked_write(fd, 'H', '0', big_buffer, Ustrlen(big_buffer+2) + 3);
      }

    /* The number of bytes written. This is the same for each address. Even
    if we sent several copies of the message down the same connection, the
    size of each one is the same, and it's that value we have got because
    transport_count gets reset before calling transport_write_message(). */

    memcpy(big_buffer, &transport_count, sizeof(transport_count));
    rmt_dlv_checked_write(fd, 'S', '0', big_buffer, sizeof(transport_count));

    /* Information about what happened to each address. Four item types are
    used: an optional 'X' item first, for TLS information, then an optional "C"
    item for any client-auth info followed by 'R' items for any retry settings,
    and finally an 'A' item for the remaining data. */

    for(; addr; addr = addr->next)
      {
      uschar *ptr;
      retry_item *r;

      /* The certificate verification status goes into the flags */
      if (tls_out.certificate_verified) setflag(addr, af_cert_verified);
#ifdef SUPPORT_DANE
      if (tls_out.dane_verified)        setflag(addr, af_dane_verified);
#endif

      /* Use an X item only if there's something to send */
#ifdef SUPPORT_TLS
      if (addr->cipher)
        {
        ptr = big_buffer + sprintf(CS big_buffer, "%.128s", addr->cipher) + 1;
        if (!addr->peerdn)
	  *ptr++ = 0;
	else
          ptr += sprintf(CS ptr, "%.512s", addr->peerdn) + 1;

        rmt_dlv_checked_write(fd, 'X', '1', big_buffer, ptr - big_buffer);
        }
      else if (continue_proxy_cipher)
	{
        ptr = big_buffer + sprintf(CS big_buffer, "%.128s", continue_proxy_cipher) + 1;
	*ptr++ = 0;
        rmt_dlv_checked_write(fd, 'X', '1', big_buffer, ptr - big_buffer);
	}

      if (addr->peercert)
	{
        ptr = big_buffer;
	if (!tls_export_cert(ptr, big_buffer_size-2, addr->peercert))
	  while(*ptr++);
	else
	  *ptr++ = 0;
        rmt_dlv_checked_write(fd, 'X', '2', big_buffer, ptr - big_buffer);
	}
      if (addr->ourcert)
	{
        ptr = big_buffer;
	if (!tls_export_cert(ptr, big_buffer_size-2, addr->ourcert))
	  while(*ptr++);
	else
	  *ptr++ = 0;
        rmt_dlv_checked_write(fd, 'X', '3', big_buffer, ptr - big_buffer);
	}
# ifndef DISABLE_OCSP
      if (addr->ocsp > OCSP_NOT_REQ)
	{
	ptr = big_buffer + sprintf(CS big_buffer, "%c", addr->ocsp + '0') + 1;
        rmt_dlv_checked_write(fd, 'X', '4', big_buffer, ptr - big_buffer);
	}
# endif
#endif	/*SUPPORT_TLS*/

      if (client_authenticator)
        {
	ptr = big_buffer + sprintf(CS big_buffer, "%.64s", client_authenticator) + 1;
        rmt_dlv_checked_write(fd, 'C', '1', big_buffer, ptr - big_buffer);
	}
      if (client_authenticated_id)
        {
        ptr = big_buffer + sprintf(CS big_buffer, "%.64s", client_authenticated_id) + 1;
        rmt_dlv_checked_write(fd, 'C', '2', big_buffer, ptr - big_buffer);
	}
      if (client_authenticated_sender)
        {
        ptr = big_buffer + sprintf(CS big_buffer, "%.64s", client_authenticated_sender) + 1;
        rmt_dlv_checked_write(fd, 'C', '3', big_buffer, ptr - big_buffer);
	}

#ifndef DISABLE_PRDR
      if (testflag(addr, af_prdr_used))
	rmt_dlv_checked_write(fd, 'P', '0', NULL, 0);
#endif

      if (testflag(addr, af_pipelining))
	  rmt_dlv_checked_write(fd, 'L', '1', NULL, 0);

      if (testflag(addr, af_chunking_used))
	rmt_dlv_checked_write(fd, 'K', '0', NULL, 0);

      if (testflag(addr, af_tcp_fastopen_conn))
	rmt_dlv_checked_write(fd, 'T',
	  testflag(addr, af_tcp_fastopen) ? '1' : '0', NULL, 0);

      memcpy(big_buffer, &addr->dsn_aware, sizeof(addr->dsn_aware));
      rmt_dlv_checked_write(fd, 'D', '0', big_buffer, sizeof(addr->dsn_aware));

      /* Retry information: for most success cases this will be null. */

      for (r = addr->retries; r; r = r->next)
        {
        sprintf(CS big_buffer, "%c%.500s", r->flags, r->key);
        ptr = big_buffer + Ustrlen(big_buffer+2) + 3;
        memcpy(ptr, &r->basic_errno, sizeof(r->basic_errno));
        ptr += sizeof(r->basic_errno);
        memcpy(ptr, &r->more_errno, sizeof(r->more_errno));
        ptr += sizeof(r->more_errno);
        if (!r->message) *ptr++ = 0; else
          {
          sprintf(CS ptr, "%.512s", r->message);
          while(*ptr++);
          }
        rmt_dlv_checked_write(fd, 'R', '0', big_buffer, ptr - big_buffer);
        }

#ifdef SUPPORT_SOCKS
      if (LOGGING(proxy) && proxy_session)
	{
	ptr = big_buffer;
	if (proxy_local_address)
	  {
	  DEBUG(D_deliver) debug_printf("proxy_local_address '%s'\n", proxy_local_address);
	  ptr = big_buffer + sprintf(CS ptr, "%.128s", proxy_local_address) + 1;
	  DEBUG(D_deliver) debug_printf("proxy_local_port %d\n", proxy_local_port);
	  memcpy(ptr, &proxy_local_port, sizeof(proxy_local_port));
	  ptr += sizeof(proxy_local_port);
	  }
	else
	  *ptr++ = '\0';
	rmt_dlv_checked_write(fd, 'A', '2', big_buffer, ptr - big_buffer);
	}
#endif

#ifdef EXPERIMENTAL_DSN_INFO
/*um, are they really per-addr?  Other per-conn stuff is not (auth, tls).  But host_used is! */
      if (addr->smtp_greeting)
	{
	DEBUG(D_deliver) debug_printf("smtp_greeting '%s'\n", addr->smtp_greeting);
	ptr = big_buffer + sprintf(CS big_buffer, "%.128s", addr->smtp_greeting) + 1;
	if (addr->helo_response)
	  {
	  DEBUG(D_deliver) debug_printf("helo_response '%s'\n", addr->helo_response);
	  ptr += sprintf(CS ptr, "%.128s", addr->helo_response) + 1;
	  }
	else
	  *ptr++ = '\0';
        rmt_dlv_checked_write(fd, 'A', '1', big_buffer, ptr - big_buffer);
	}
#endif

      /* The rest of the information goes in an 'A0' item. */

      sprintf(CS big_buffer, "%c%c", addr->transport_return, addr->special_action);
      ptr = big_buffer + 2;
      memcpy(ptr, &addr->basic_errno, sizeof(addr->basic_errno));
      ptr += sizeof(addr->basic_errno);
      memcpy(ptr, &addr->more_errno, sizeof(addr->more_errno));
      ptr += sizeof(addr->more_errno);
      memcpy(ptr, &addr->delivery_usec, sizeof(addr->delivery_usec));
      ptr += sizeof(addr->delivery_usec);
      memcpy(ptr, &addr->flags, sizeof(addr->flags));
      ptr += sizeof(addr->flags);

      if (!addr->message) *ptr++ = 0; else
        ptr += sprintf(CS ptr, "%.1024s", addr->message) + 1;

      if (!addr->user_message) *ptr++ = 0; else
        ptr += sprintf(CS ptr, "%.1024s", addr->user_message) + 1;

      if (!addr->host_used) *ptr++ = 0; else
        {
        ptr += sprintf(CS ptr, "%.256s", addr->host_used->name) + 1;
        ptr += sprintf(CS ptr, "%.64s", addr->host_used->address) + 1;
        memcpy(ptr, &addr->host_used->port, sizeof(addr->host_used->port));
        ptr += sizeof(addr->host_used->port);

        /* DNS lookup status */
	*ptr++ = addr->host_used->dnssec==DS_YES ? '2'
	       : addr->host_used->dnssec==DS_NO ? '1' : '0';

        }
      rmt_dlv_checked_write(fd, 'A', '0', big_buffer, ptr - big_buffer);
      }

    /* Local interface address/port */
#ifdef EXPERIMENTAL_DSN_INFO
    if (sending_ip_address)
#else
    if (LOGGING(incoming_interface) && sending_ip_address)
#endif
      {
      uschar * ptr;
      ptr = big_buffer + sprintf(CS big_buffer, "%.128s", sending_ip_address) + 1;
      ptr += sprintf(CS ptr, "%d", sending_port) + 1;
      rmt_dlv_checked_write(fd, 'I', '0', big_buffer, ptr - big_buffer);
      }

    /* Add termination flag, close the pipe, and that's it. The character
    after 'Z' indicates whether continue_transport is now NULL or not.
    A change from non-NULL to NULL indicates a problem with a continuing
    connection. */

    big_buffer[0] = continue_transport ? '1' : '0';
    rmt_dlv_checked_write(fd, 'Z', '0', big_buffer, 1);
    (void)close(fd);
    exit(EXIT_SUCCESS);
    }

  /* Back in the mainline: close the unwanted half of the pipe. */

  (void)close(pfd[pipe_write]);

  /* If we have a connection still open from a verify stage (lazy-close)
  release its TLS library context (if any) as responsibility was passed to
  the delivery child process. */

  if (cutthrough.cctx.sock >= 0 && cutthrough.callout_hold_only)
    {
#ifdef SUPPORT_TLS
    if (cutthrough.is_tls)
      tls_close(cutthrough.cctx.tls_ctx, TLS_NO_SHUTDOWN);
#endif
    (void) close(cutthrough.cctx.sock);
    release_cutthrough_connection(US"passed to transport proc");
    }

  /* Fork failed; defer with error message */

  if (pid == -1)
    {
    (void)close(pfd[pipe_read]);
    panicmsg = string_sprintf("fork failed for remote delivery to %s: %s",
        addr->domain, strerror(errno));
    goto enq_continue;
    }

  /* Fork succeeded; increment the count, and remember relevant data for
  when the process finishes. */

  parcount++;
  parlist[poffset].addrlist = parlist[poffset].addr = addr;
  parlist[poffset].pid = pid;
  parlist[poffset].fd = pfd[pipe_read];
  parlist[poffset].done = FALSE;
  parlist[poffset].msg = NULL;
  parlist[poffset].return_path = return_path;

  /* If the process we've just started is sending a message down an existing
  channel, wait for it now. This ensures that only one such process runs at
  once, whatever the value of remote_max parallel. Otherwise, we might try to
  send two or more messages simultaneously down the same channel. This could
  happen if there are different domains that include the same host in otherwise
  different host lists.

  Also, if the transport closes down the channel, this information gets back
  (continue_transport gets set to NULL) before we consider any other addresses
  in this message. */

  if (continue_transport) par_reduce(0, fallback);

  /* Otherwise, if we are running in the test harness, wait a bit, to let the
  newly created process get going before we create another process. This should
  ensure repeatability in the tests. We only need to wait a tad. */

  else if (f.running_in_test_harness) millisleep(500);

  continue;

enq_continue:
  if (serialize_key) enq_end(serialize_key);
panic_continue:
  remote_post_process(addr, LOG_MAIN|LOG_PANIC, panicmsg, fallback);
  continue;
  }

/* Reached the end of the list of addresses. Wait for all the subprocesses that
are still running and post-process their addresses. */

par_reduce(0, fallback);
return TRUE;
}

Project: exim
File: queue.c

spool_pname_buf(uschar * buf, int len)
{
snprintf(CS buf, len, "%s/%s/input", spool_directory, queue_name);
}

Project: exim
File: queue.c

static void queue_list_extras(tree_node *p)
{
if (p->left != NULL) queue_list_extras(p->left);
if (!p->data.val) printf("       +D %s\n", p->name);
if (p->right != NULL) queue_list_extras(p->right);
}

Project: exim
File: queue.c

queue_action(uschar *id, int action, uschar **argv, int argc, int recipients_arg)
{
int i, j;
BOOL yield = TRUE;
BOOL removed = FALSE;
struct passwd *pw;
uschar *doing = NULL;
uschar *username;
uschar *errmsg;
uschar spoolname[32];

/* Set the global message_id variable, used when re-writing spool files. This
also causes message ids to be added to log messages. */

Ustrcpy(message_id, id);

/* The "actions" that just list the files do not require any locking to be
done. Only admin users may read the spool files. */

if (action >= MSG_SHOW_BODY)
  {
  int fd, i, rc;
  uschar *subdirectory, *suffix;

  if (!f.admin_user)
    {
    printf("Permission denied\n");
    return FALSE;
    }

  if (recipients_arg < argc)
    {
    printf("*** Only one message can be listed at once\n");
    return FALSE;
    }

  if (action == MSG_SHOW_BODY)
    {
    subdirectory = US"input";
    suffix = US"-D";
    }
  else if (action == MSG_SHOW_HEADER)
    {
    subdirectory = US"input";
    suffix = US"-H";
    }
  else
    {
    subdirectory = US"msglog";
    suffix = US"";
    }

  for (i = 0; i < 2; i++)
    {
    message_subdir[0] = split_spool_directory == (i == 0) ? id[5] : 0;
    if ((fd = Uopen(spool_fname(subdirectory, message_subdir, id, suffix),
		    O_RDONLY, 0)) >= 0)
      break;
    if (i == 0)
      continue;

    printf("Failed to open %s file for %s%s: %s\n", subdirectory, id, suffix,
      strerror(errno));
    if (action == MSG_SHOW_LOG && !message_logs)
      printf("(No message logs are being created because the message_logs "
        "option is false.)\n");
    return FALSE;
    }

  while((rc = read(fd, big_buffer, big_buffer_size)) > 0)
    rc = write(fileno(stdout), big_buffer, rc);

  (void)close(fd);
  return TRUE;
  }

/* For actions that actually act, open and lock the data file to ensure that no
other process is working on this message. If the file does not exist, continue
only if the action is remove and the user is an admin user, to allow for
tidying up broken states. */

if ((deliver_datafile = spool_open_datafile(id)) < 0)
  if (errno == ENOENT)
    {
    yield = FALSE;
    printf("Spool data file for %s does not exist\n", id);
    if (action != MSG_REMOVE || !f.admin_user) return FALSE;
    printf("Continuing, to ensure all files removed\n");
    }
  else
    {
    if (errno == 0) printf("Message %s is locked\n", id);
      else printf("Couldn't open spool file for %s: %s\n", id,
        strerror(errno));
    return FALSE;
    }

/* Read the spool header file for the message. Again, continue after an
error only in the case of deleting by an administrator. Setting the third
argument false causes it to look both in the main spool directory and in
the appropriate subdirectory, and set message_subdir according to where it
found the message. */

sprintf(CS spoolname, "%s-H", id);
if (spool_read_header(spoolname, TRUE, FALSE) != spool_read_OK)
  {
  yield = FALSE;
  if (errno != ERRNO_SPOOLFORMAT)
    printf("Spool read error for %s: %s\n", spoolname, strerror(errno));
  else
    printf("Spool format error for %s\n", spoolname);
  if (action != MSG_REMOVE || !f.admin_user)
    {
    (void)close(deliver_datafile);
    deliver_datafile = -1;
    return FALSE;
    }
  printf("Continuing to ensure all files removed\n");
  }

/* Check that the user running this process is entitled to operate on this
message. Only admin users may freeze/thaw, add/cancel recipients, or otherwise
mess about, but the original sender is permitted to remove a message. That's
why we leave this check until after the headers are read. */

if (!f.admin_user && (action != MSG_REMOVE || real_uid != originator_uid))
  {
  printf("Permission denied\n");
  (void)close(deliver_datafile);
  deliver_datafile = -1;
  return FALSE;
  }

/* Set up the user name for logging. */

pw = getpwuid(real_uid);
username = (pw != NULL)?
  US pw->pw_name : string_sprintf("uid %ld", (long int)real_uid);

/* Take the necessary action. */

if (action != MSG_SHOW_COPY) printf("Message %s ", id);

switch(action)
  {
  case MSG_SHOW_COPY:
    {
    transport_ctx tctx = {{0}};
    deliver_in_buffer = store_malloc(DELIVER_IN_BUFFER_SIZE);
    deliver_out_buffer = store_malloc(DELIVER_OUT_BUFFER_SIZE);
    tctx.u.fd = 1;
    transport_write_message(&tctx, 0);
    break;
    }


  case MSG_FREEZE:
  if (f.deliver_freeze)
    {
    yield = FALSE;
    printf("is already frozen\n");
    }
  else
    {
    f.deliver_freeze = TRUE;
    f.deliver_manual_thaw = FALSE;
    deliver_frozen_at = time(NULL);
    if (spool_write_header(id, SW_MODIFYING, &errmsg) >= 0)
      {
      printf("is now frozen\n");
      log_write(0, LOG_MAIN, "frozen by %s", username);
      }
    else
      {
      yield = FALSE;
      printf("could not be frozen: %s\n", errmsg);
      }
    }
  break;


  case MSG_THAW:
  if (!f.deliver_freeze)
    {
    yield = FALSE;
    printf("is not frozen\n");
    }
  else
    {
    f.deliver_freeze = FALSE;
    f.deliver_manual_thaw = TRUE;
    if (spool_write_header(id, SW_MODIFYING, &errmsg) >= 0)
      {
      printf("is no longer frozen\n");
      log_write(0, LOG_MAIN, "unfrozen by %s", username);
      }
    else
      {
      yield = FALSE;
      printf("could not be unfrozen: %s\n", errmsg);
      }
    }
  break;


  /* We must ensure all files are removed from both the input directory
  and the appropriate subdirectory, to clean up cases when there are odd
  files left lying around in odd places. In the normal case message_subdir
  will have been set correctly by spool_read_header, but as this is a rare
  operation, just run everything twice. */

  case MSG_REMOVE:
    {
    uschar suffix[3];

    suffix[0] = '-';
    suffix[2] = 0;
    message_subdir[0] = id[5];

    for (j = 0; j < 2; message_subdir[0] = 0, j++)
      {
      uschar * fname = spool_fname(US"msglog", message_subdir, id, US"");

      DEBUG(D_any) debug_printf(" removing %s", fname);
      if (Uunlink(fname) < 0)
	{
	if (errno != ENOENT)
	  {
	  yield = FALSE;
	  printf("Error while removing %s: %s\n", fname, strerror(errno));
	  }
	else DEBUG(D_any) debug_printf(" (no file)\n");
	}
      else
	{
	removed = TRUE;
	DEBUG(D_any) debug_printf(" (ok)\n");
	}

      for (i = 0; i < 3; i++)
	{
	uschar * fname;

	suffix[1] = (US"DHJ")[i];
	fname = spool_fname(US"input", message_subdir, id, suffix);

	DEBUG(D_any) debug_printf(" removing %s", fname);
	if (Uunlink(fname) < 0)
	  {
	  if (errno != ENOENT)
	    {
	    yield = FALSE;
	    printf("Error while removing %s: %s\n", fname, strerror(errno));
	    }
	  else DEBUG(D_any) debug_printf(" (no file)\n");
	  }
	else
	  {
	  removed = TRUE;
	  DEBUG(D_any) debug_printf(" (done)\n");
	  }
	}
      }

    /* In the common case, the datafile is open (and locked), so give the
    obvious message. Otherwise be more specific. */

    if (deliver_datafile >= 0) printf("has been removed\n");
      else printf("has been removed or did not exist\n");
    if (removed)
      {
#ifndef DISABLE_EVENT
      for (i = 0; i < recipients_count; i++)
	{
	tree_node *delivered =
	  tree_search(tree_nonrecipients, recipients_list[i].address);
	if (!delivered)
	  {
	  uschar * save_local = deliver_localpart;
	  const uschar * save_domain = deliver_domain;
	  uschar * addr = recipients_list[i].address, * errmsg = NULL;
	  int start, end, dom;

	  if (!parse_extract_address(addr, &errmsg, &start, &end, &dom, TRUE))
	    log_write(0, LOG_MAIN|LOG_PANIC,
	      "failed to parse address '%.100s'\n: %s", addr, errmsg);
	  else
	    {
	    deliver_localpart =
	      string_copyn(addr+start, dom ? (dom-1) - start : end - start);
	    deliver_domain = dom
	      ? CUS string_copyn(addr+dom, end - dom) : CUS"";

	    event_raise(event_action, US"msg:fail:internal",
	      string_sprintf("message removed by %s", username));

	    deliver_localpart = save_local;
	    deliver_domain = save_domain;
	    }
	  }
	}
      (void) event_raise(event_action, US"msg:complete", NULL);
#endif
      log_write(0, LOG_MAIN, "removed by %s", username);
      log_write(0, LOG_MAIN, "Completed");
      }
    break;
    }


  case MSG_MARK_ALL_DELIVERED:
  for (i = 0; i < recipients_count; i++)
    tree_add_nonrecipient(recipients_list[i].address);

  if (spool_write_header(id, SW_MODIFYING, &errmsg) >= 0)
    {
    printf("has been modified\n");
    for (i = 0; i < recipients_count; i++)
      log_write(0, LOG_MAIN, "address <%s> marked delivered by %s",
        recipients_list[i].address, username);
    }
  else
    {
    yield = FALSE;
    printf("- could not mark all delivered: %s\n", errmsg);
    }
  break;


  case MSG_EDIT_SENDER:
  if (recipients_arg < argc - 1)
    {
    yield = FALSE;
    printf("- only one sender address can be specified\n");
    break;
    }
  doing = US"editing sender";
  /* Fall through */

  case MSG_ADD_RECIPIENT:
  if (doing == NULL) doing = US"adding recipient";
  /* Fall through */

  case MSG_MARK_DELIVERED:
  if (doing == NULL) doing = US"marking as delivered";

  /* Common code for EDIT_SENDER, ADD_RECIPIENT, & MARK_DELIVERED */

  if (recipients_arg >= argc)
    {
    yield = FALSE;
    printf("- error while %s: no address given\n", doing);
    break;
    }

  for (; recipients_arg < argc; recipients_arg++)
    {
    int start, end, domain;
    uschar *errmess;
    uschar *recipient =
      parse_extract_address(argv[recipients_arg], &errmess, &start, &end,
        &domain, (action == MSG_EDIT_SENDER));

    if (recipient == NULL)
      {
      yield = FALSE;
      printf("- error while %s:\n  bad address %s: %s\n",
        doing, argv[recipients_arg], errmess);
      }
    else if (recipient[0] != 0 && domain == 0)
      {
      yield = FALSE;
      printf("- error while %s:\n  bad address %s: "
        "domain missing\n", doing, argv[recipients_arg]);
      }
    else
      {
      if (action == MSG_ADD_RECIPIENT)
        {
#ifdef SUPPORT_I18N
	if (string_is_utf8(recipient)) allow_utf8_domains = message_smtputf8 = TRUE;
#endif
        receive_add_recipient(recipient, -1);
        log_write(0, LOG_MAIN, "recipient <%s> added by %s",
          recipient, username);
        }
      else if (action == MSG_MARK_DELIVERED)
        {
        for (i = 0; i < recipients_count; i++)
          if (Ustrcmp(recipients_list[i].address, recipient) == 0) break;
        if (i >= recipients_count)
          {
          printf("- error while %s:\n  %s is not a recipient:"
            " message not updated\n", doing, recipient);
          yield = FALSE;
          }
        else
          {
          tree_add_nonrecipient(recipients_list[i].address);
          log_write(0, LOG_MAIN, "address <%s> marked delivered by %s",
            recipient, username);
          }
        }
      else  /* MSG_EDIT_SENDER */
        {
#ifdef SUPPORT_I18N
	if (string_is_utf8(recipient)) allow_utf8_domains = message_smtputf8 = TRUE;
#endif
        sender_address = recipient;
        log_write(0, LOG_MAIN, "sender address changed to <%s> by %s",
          recipient, username);
        }
      }
    }

  if (yield)
    if (spool_write_header(id, SW_MODIFYING, &errmsg) >= 0)
      printf("has been modified\n");
    else
      {
      yield = FALSE;
      printf("- while %s: %s\n", doing, errmsg);
      }

  break;
  }

/* Closing the datafile releases the lock and permits other processes
to operate on the message (if it still exists). */

if (deliver_datafile >= 0)
  {
  (void)close(deliver_datafile);
  deliver_datafile = -1;
  }
return yield;
}

Project: exim
File: deliver.c

delivery_log(int flags, address_item * addr, int logchar, uschar * msg)
{
gstring * g; /* Used for a temporary, expanding buffer, for building log lines  */
void * reset_point;     /* released afterwards.  */

/* Log the delivery on the main log. We use an extensible string to build up
the log line, and reset the store afterwards. Remote deliveries should always
have a pointer to the host item that succeeded; local deliveries can have a
pointer to a single host item in their host list, for use by the transport. */

#ifndef DISABLE_EVENT
  /* presume no successful remote delivery */
  lookup_dnssec_authenticated = NULL;
#endif

g = reset_point = string_get(256);

if (msg)
  g = string_append(g, 2, host_and_ident(TRUE), US" ");
else
  {
  g->s[0] = logchar; g->ptr = 1;
  g = string_catn(g, US"> ", 2);
  }
g = string_log_address(g, addr, LOGGING(all_parents), TRUE);

if (LOGGING(sender_on_delivery) || msg)
  g = string_append(g, 3, US" F=<",
#ifdef SUPPORT_I18N
    testflag(addr, af_utf8_downcvt)
    ? string_address_utf8_to_alabel(sender_address, NULL)
    :
#endif
      sender_address,
  US">");

if (*queue_name)
  g = string_append(g, 2, US" Q=", queue_name);

#ifdef EXPERIMENTAL_SRS
if(addr->prop.srs_sender)
  g = string_append(g, 3, US" SRS=<", addr->prop.srs_sender, US">");
#endif

/* You might think that the return path must always be set for a successful
delivery; indeed, I did for some time, until this statement crashed. The case
when it is not set is for a delivery to /dev/null which is optimised by not
being run at all. */

if (used_return_path && LOGGING(return_path_on_delivery))
  g = string_append(g, 3, US" P=<", used_return_path, US">");

if (msg)
  g = string_append(g, 2, US" ", msg);

/* For a delivery from a system filter, there may not be a router */
if (addr->router)
  g = string_append(g, 2, US" R=", addr->router->name);

g = string_append(g, 2, US" T=", addr->transport->name);

if (LOGGING(delivery_size))
  g = string_append(g, 2, US" S=",
    string_sprintf("%d", transport_count));

/* Local delivery */

if (addr->transport->info->local)
  {
  if (addr->host_list)
    g = string_append(g, 2, US" H=", addr->host_list->name);
  g = d_log_interface(g);
  if (addr->shadow_message)
    g = string_cat(g, addr->shadow_message);
  }

/* Remote delivery */

else
  {
  if (addr->host_used)
    {
    g = d_hostlog(g, addr);
    if (continue_sequence > 1)
      g = string_catn(g, US"*", 1);

#ifndef DISABLE_EVENT
    deliver_host_address = addr->host_used->address;
    deliver_host_port =    addr->host_used->port;
    deliver_host =         addr->host_used->name;

    /* DNS lookup status */
    lookup_dnssec_authenticated = addr->host_used->dnssec==DS_YES ? US"yes"
			      : addr->host_used->dnssec==DS_NO ? US"no"
			      : NULL;
#endif
    }

#ifdef SUPPORT_TLS
  g = d_tlslog(g, addr);
#endif

  if (addr->authenticator)
    {
    g = string_append(g, 2, US" A=", addr->authenticator);
    if (addr->auth_id)
      {
      g = string_append(g, 2, US":", addr->auth_id);
      if (LOGGING(smtp_mailauth) && addr->auth_sndr)
        g = string_append(g, 2, US":", addr->auth_sndr);
      }
    }

  if (LOGGING(pipelining) && testflag(addr, af_pipelining))
    g = string_catn(g, US" L", 2);

#ifndef DISABLE_PRDR
  if (testflag(addr, af_prdr_used))
    g = string_catn(g, US" PRDR", 5);
#endif

  if (testflag(addr, af_chunking_used))
    g = string_catn(g, US" K", 2);
  }

/* confirmation message (SMTP (host_used) and LMTP (driver_name)) */

if (  LOGGING(smtp_confirmation)
   && addr->message
   && (addr->host_used || Ustrcmp(addr->transport->driver_name, "lmtp") == 0)
   )
  {
  unsigned i;
  unsigned lim = big_buffer_size < 1024 ? big_buffer_size : 1024;
  uschar *p = big_buffer;
  uschar *ss = addr->message;
  *p++ = '\"';
  for (i = 0; i < lim && ss[i] != 0; i++)	/* limit logged amount */
    {
    if (ss[i] == '\"' || ss[i] == '\\') *p++ = '\\'; /* quote \ and " */
    *p++ = ss[i];
    }
  *p++ = '\"';
  *p = 0;
  g = string_append(g, 2, US" C=", big_buffer);
  }

/* Time on queue and actual time taken to deliver */

if (LOGGING(queue_time))
  g = string_append(g, 2, US" QT=",
    string_timesince(&received_time));

if (LOGGING(deliver_time))
  {
  struct timeval diff = {.tv_sec = addr->more_errno, .tv_usec = addr->delivery_usec};
  g = string_append(g, 2, US" DT=", string_timediff(&diff));
  }

/* string_cat() always leaves room for the terminator. Release the
store we used to build the line after writing it. */

log_write(0, flags, "%s", string_from_gstring(g));

#ifndef DISABLE_EVENT
if (!msg) msg_event_raise(US"msg:delivery", addr);
#endif

store_reset(reset_point);
return;
}

Project: exim
File: queue.c

spool_sname(const uschar * purpose, uschar * subdir)
{
return string_sprintf("%s%s%s%s%s",
		    queue_name, *queue_name ? "/" : "",
		    purpose,
		    *subdir ? "/" : "", subdir);
}

Project: exim
File: queue.c

queue_run(uschar *start_id, uschar *stop_id, BOOL recurse)
{
BOOL force_delivery = f.queue_run_force || deliver_selectstring != NULL ||
  deliver_selectstring_sender != NULL;
const pcre *selectstring_regex = NULL;
const pcre *selectstring_regex_sender = NULL;
uschar *log_detail = NULL;
int subcount = 0;
int i;
uschar subdirs[64];

/* Cancel any specific queue domains. Turn off the flag that causes SMTP
deliveries not to happen, unless doing a 2-stage queue run, when the SMTP flag
gets set. Save the queue_runner's pid and the flag that indicates any
deliveries run directly from this process. Deliveries that are run by handing
on TCP/IP channels have queue_run_pid set, but not queue_running. */

queue_domains = NULL;
queue_smtp_domains = NULL;
f.queue_smtp = f.queue_2stage;

queue_run_pid = getpid();
f.queue_running = TRUE;

/* Log the true start of a queue run, and fancy options */

if (!recurse)
  {
  uschar extras[8];
  uschar *p = extras;

  if (f.queue_2stage) *p++ = 'q';
  if (f.queue_run_first_delivery) *p++ = 'i';
  if (f.queue_run_force) *p++ = 'f';
  if (f.deliver_force_thaw) *p++ = 'f';
  if (f.queue_run_local) *p++ = 'l';
  *p = 0;

  p = big_buffer;
  p += sprintf(CS p, "pid=%d", (int)queue_run_pid);

  if (extras[0] != 0)
    p += sprintf(CS p, " -q%s", extras);

  if (deliver_selectstring)
    p += sprintf(CS p, " -R%s %s", f.deliver_selectstring_regex? "r" : "",
      deliver_selectstring);

  if (deliver_selectstring_sender)
    p += sprintf(CS p, " -S%s %s", f.deliver_selectstring_sender_regex? "r" : "",
      deliver_selectstring_sender);

  log_detail = string_copy(big_buffer);
  if (*queue_name)
    log_write(L_queue_run, LOG_MAIN, "Start '%s' queue run: %s",
      queue_name, log_detail);
  else
    log_write(L_queue_run, LOG_MAIN, "Start queue run: %s", log_detail);
  }

/* If deliver_selectstring is a regex, compile it. */

if (deliver_selectstring && f.deliver_selectstring_regex)
  selectstring_regex = regex_must_compile(deliver_selectstring, TRUE, FALSE);

if (deliver_selectstring_sender && f.deliver_selectstring_sender_regex)
  selectstring_regex_sender =
    regex_must_compile(deliver_selectstring_sender, TRUE, FALSE);

/* If the spool is split into subdirectories, we want to process it one
directory at a time, so as to spread out the directory scanning and the
delivering when there are lots of messages involved, except when
queue_run_in_order is set.

In the random order case, this loop runs once for the main directory (handling
any messages therein), and then repeats for any subdirectories that were found.
When the first argument of queue_get_spool_list() is 0, it scans the top
directory, fills in subdirs, and sets subcount. The order of the directories is
then randomized after the first time through, before they are scanned in
subsequent iterations.

When the first argument of queue_get_spool_list() is -1 (for queue_run_in_
order), it scans all directories and makes a single message list. */

for (i = queue_run_in_order ? -1 : 0;
     i <= (queue_run_in_order ? -1 : subcount);
     i++)
  {
  queue_filename * fq;
  void *reset_point1 = store_get(0);

  DEBUG(D_queue_run)
    {
    if (i == 0)
      debug_printf("queue running main directory\n");
    else if (i == -1)
      debug_printf("queue running combined directories\n");
    else
      debug_printf("queue running subdirectory '%c'\n", subdirs[i]);
    }

  for (fq = queue_get_spool_list(i, subdirs, &subcount, !queue_run_in_order);
       fq;
       fq = fq->next)
    {
    pid_t pid;
    int status;
    int pfd[2];
    struct stat statbuf;
    uschar buffer[256];

    /* Unless deliveries are forced, if deliver_queue_load_max is non-negative,
    check that the load average is low enough to permit deliveries. */

    if (!f.queue_run_force && deliver_queue_load_max >= 0)
      if ((load_average = os_getloadavg()) > deliver_queue_load_max)
        {
        log_write(L_queue_run, LOG_MAIN, "Abandon queue run: %s (load %.2f, max %.2f)",
          log_detail,
          (double)load_average/1000.0,
          (double)deliver_queue_load_max/1000.0);
        i = subcount;                 /* Don't process other directories */
        break;
        }
      else
        DEBUG(D_load) debug_printf("load average = %.2f max = %.2f\n",
          (double)load_average/1000.0,
          (double)deliver_queue_load_max/1000.0);

    /* Skip this message unless it's within the ID limits */

    if (stop_id && Ustrncmp(fq->text, stop_id, MESSAGE_ID_LENGTH) > 0)
      continue;
    if (start_id && Ustrncmp(fq->text, start_id, MESSAGE_ID_LENGTH) < 0)
      continue;

    /* Check that the message still exists */

    message_subdir[0] = fq->dir_uschar;
    if (Ustat(spool_fname(US"input", message_subdir, fq->text, US""), &statbuf) < 0)
      continue;

    /* There are some tests that require the reading of the header file. Ensure
    the store used is scavenged afterwards so that this process doesn't keep
    growing its store. We have to read the header file again when actually
    delivering, but it's cheaper than forking a delivery process for each
    message when many are not going to be delivered. */

    if (deliver_selectstring || deliver_selectstring_sender ||
        f.queue_run_first_delivery)
      {
      BOOL wanted = TRUE;
      BOOL orig_dont_deliver = f.dont_deliver;
      void *reset_point2 = store_get(0);

      /* Restore the original setting of dont_deliver after reading the header,
      so that a setting for a particular message doesn't force it for any that
      follow. If the message is chosen for delivery, the header is read again
      in the deliver_message() function, in a subprocess. */

      if (spool_read_header(fq->text, FALSE, TRUE) != spool_read_OK) continue;
      f.dont_deliver = orig_dont_deliver;

      /* Now decide if we want to deliver this message. As we have read the
      header file, we might as well do the freeze test now, and save forking
      another process. */

      if (f.deliver_freeze && !f.deliver_force_thaw)
        {
        log_write(L_skip_delivery, LOG_MAIN, "Message is frozen");
        wanted = FALSE;
        }

      /* Check first_delivery in the case when there are no message logs. */

      else if (f.queue_run_first_delivery && !f.deliver_firsttime)
        {
        DEBUG(D_queue_run) debug_printf("%s: not first delivery\n", fq->text);
        wanted = FALSE;
        }

      /* Check for a matching address if deliver_selectstring[_sender] is set.
      If so, we do a fully delivery - don't want to omit other addresses since
      their routing might trigger re-writing etc. */

      /* Sender matching */

      else if (  deliver_selectstring_sender
	      && !(f.deliver_selectstring_sender_regex
		  ? (pcre_exec(selectstring_regex_sender, NULL,
		      CS sender_address, Ustrlen(sender_address), 0, PCRE_EOPT,
		      NULL, 0) >= 0)
		  : (strstric(sender_address, deliver_selectstring_sender, FALSE)
		      != NULL)
	      )   )
        {
        DEBUG(D_queue_run) debug_printf("%s: sender address did not match %s\n",
          fq->text, deliver_selectstring_sender);
        wanted = FALSE;
        }

      /* Recipient matching */

      else if (deliver_selectstring)
        {
        int i;
        for (i = 0; i < recipients_count; i++)
          {
          uschar *address = recipients_list[i].address;
          if (  (f.deliver_selectstring_regex
		? (pcre_exec(selectstring_regex, NULL, CS address,
		     Ustrlen(address), 0, PCRE_EOPT, NULL, 0) >= 0)
                : (strstric(address, deliver_selectstring, FALSE) != NULL)
		)
             && tree_search(tree_nonrecipients, address) == NULL
	     )
            break;
          }

        if (i >= recipients_count)
          {
          DEBUG(D_queue_run)
            debug_printf("%s: no recipient address matched %s\n",
              fq->text, deliver_selectstring);
          wanted = FALSE;
          }
        }

      /* Recover store used when reading the header */

      spool_clear_header_globals();
      store_reset(reset_point2);
      if (!wanted) continue;      /* With next message */
      }

    /* OK, got a message we want to deliver. Create a pipe which will
    serve as a means of detecting when all the processes created by the
    delivery process are finished. This is relevant when the delivery
    process passes one or more SMTP channels on to its own children. The
    pipe gets passed down; by reading on it here we detect when the last
    descendent dies by the unblocking of the read. It's a pity that for
    most of the time the pipe isn't used, but creating a pipe should be
    pretty cheap. */

    if (pipe(pfd) < 0)
      log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to create pipe in queue "
        "runner process %d: %s", queue_run_pid, strerror(errno));
    queue_run_pipe = pfd[pipe_write];  /* To ensure it gets passed on. */

    /* Make sure it isn't stdin. This seems unlikely, but just to be on the
    safe side... */

    if (queue_run_pipe == 0)
      {
      queue_run_pipe = dup(queue_run_pipe);
      (void)close(0);
      }

    /* Before forking to deliver the message, ensure any open and cached
    lookup files or databases are closed. Otherwise, closing in the subprocess
    can make the next subprocess have problems. There won't often be anything
    open here, but it is possible (e.g. if spool_directory is an expanded
    string). A single call before this loop would probably suffice, but just in
    case expansions get inserted at some point, I've taken the heavy-handed
    approach. When nothing is open, the call should be cheap. */

    search_tidyup();

    /* Now deliver the message; get the id by cutting the -H off the file
    name. The return of the process is zero if a delivery was attempted. */

    set_process_info("running queue: %s", fq->text);
    fq->text[SPOOL_NAME_LENGTH-2] = 0;
    if ((pid = fork()) == 0)
      {
      int rc;
      if (f.running_in_test_harness) millisleep(100);
      (void)close(pfd[pipe_read]);
      rc = deliver_message(fq->text, force_delivery, FALSE);
      _exit(rc == DELIVER_NOT_ATTEMPTED);
      }
    if (pid < 0)
      log_write(0, LOG_MAIN|LOG_PANIC_DIE, "fork of delivery process from "
        "queue runner %d failed\n", queue_run_pid);

    /* Close the writing end of the synchronizing pipe in this process,
    then wait for the first level process to terminate. */

    (void)close(pfd[pipe_write]);
    set_process_info("running queue: waiting for %s (%d)", fq->text, pid);
    while (wait(&status) != pid);

    /* A zero return means a delivery was attempted; turn off the force flag
    for any subsequent calls unless queue_force is set. */

    if ((status & 0xffff) == 0) force_delivery = f.queue_run_force;

    /* If the process crashed, tell somebody */

    else if ((status & 0x00ff) != 0)
      log_write(0, LOG_MAIN|LOG_PANIC,
        "queue run: process %d crashed with signal %d while delivering %s",
        (int)pid, status & 0x00ff, fq->text);

    /* Before continuing, wait till the pipe gets closed at the far end. This
    tells us that any children created by the delivery to re-use any SMTP
    channels have all finished. Since no process actually writes to the pipe,
    the mere fact that read() unblocks is enough. */

    set_process_info("running queue: waiting for children of %d", pid);
    if ((status = read(pfd[pipe_read], buffer, sizeof(buffer))) != 0)
      log_write(0, LOG_MAIN|LOG_PANIC, "queue run: %s on pipe",
		status > 0 ? "unexpected data" : "error");
    (void)close(pfd[pipe_read]);
    set_process_info("running queue");

    /* If we are in the test harness, and this is not the first of a 2-stage
    queue run, update fudged queue times. */

    if (f.running_in_test_harness && !f.queue_2stage)
      {
      uschar *fqtnext = Ustrchr(fudged_queue_times, '/');
      if (fqtnext != NULL) fudged_queue_times = fqtnext + 1;
      }
    }                                  /* End loop for list of messages */

  tree_nonrecipients = NULL;
  store_reset(reset_point1);           /* Scavenge list of messages */

  /* If this was the first time through for random order processing, and
  sub-directories have been found, randomize their order if necessary. */

  if (i == 0 && subcount > 1 && !queue_run_in_order)
    {
    int j, r;
    for (j = 1; j <= subcount; j++)
      if ((r = random_number(100)) >= 50)
        {
        int k = (r % subcount) + 1;
        int x = subdirs[j];
        subdirs[j] = subdirs[k];
        subdirs[k] = x;
        }
    }
  }                                    /* End loop for multiple directories */

/* If queue_2stage is true, we do it all again, with the 2stage flag
turned off. */

if (f.queue_2stage)
  {
  f.queue_2stage = FALSE;
  queue_run(start_id, stop_id, TRUE);
  }

/* At top level, log the end of the run. */

if (!recurse)
  if (*queue_name)
    log_write(L_queue_run, LOG_MAIN, "End '%s' queue run: %s",
      queue_name, log_detail);
  else
    log_write(L_queue_run, LOG_MAIN, "End queue run: %s", log_detail);
}

Project: exim
File: queue.c

spool_dname(const uschar * purpose, uschar * subdir)
{
return string_sprintf("%s/%s/%s/%s",
	spool_directory, queue_name, purpose, subdir);
}

Project: exim
File: deliver.c

deliver_init(void)
{
#ifdef EXIM_TFO_PROBE
tfo_probe();
#else
f.tcp_fastopen_ok = TRUE;
#endif


if (!regex_PIPELINING) regex_PIPELINING =
  regex_must_compile(US"\\n250[\\s\\-]PIPELINING(\\s|\\n|$)", FALSE, TRUE);

if (!regex_SIZE) regex_SIZE =
  regex_must_compile(US"\\n250[\\s\\-]SIZE(\\s|\\n|$)", FALSE, TRUE);

if (!regex_AUTH) regex_AUTH =
  regex_must_compile(US"\\n250[\\s\\-]AUTH\\s+([\\-\\w\\s]+)(?:\\n|$)",
    FALSE, TRUE);

#ifdef SUPPORT_TLS
if (!regex_STARTTLS) regex_STARTTLS =
  regex_must_compile(US"\\n250[\\s\\-]STARTTLS(\\s|\\n|$)", FALSE, TRUE);

# ifdef EXPERIMENTAL_REQUIRETLS
if (!regex_REQUIRETLS) regex_REQUIRETLS =
  regex_must_compile(US"\\n250[\\s\\-]REQUIRETLS(\\s|\\n|$)", FALSE, TRUE);
# endif
#endif

if (!regex_CHUNKING) regex_CHUNKING =
  regex_must_compile(US"\\n250[\\s\\-]CHUNKING(\\s|\\n|$)", FALSE, TRUE);

#ifndef DISABLE_PRDR
if (!regex_PRDR) regex_PRDR =
  regex_must_compile(US"\\n250[\\s\\-]PRDR(\\s|\\n|$)", FALSE, TRUE);
#endif

#ifdef SUPPORT_I18N
if (!regex_UTF8) regex_UTF8 =
  regex_must_compile(US"\\n250[\\s\\-]SMTPUTF8(\\s|\\n|$)", FALSE, TRUE);
#endif

if (!regex_DSN) regex_DSN  =
  regex_must_compile(US"\\n250[\\s\\-]DSN(\\s|\\n|$)", FALSE, TRUE);

if (!regex_IGNOREQUOTA) regex_IGNOREQUOTA =
  regex_must_compile(US"\\n250[\\s\\-]IGNOREQUOTA(\\s|\\n|$)", FALSE, TRUE);
}

Project: exim
File: queue.c

merge_queue_lists(queue_filename *a, queue_filename *b)
{
queue_filename *first = NULL;
queue_filename **append = &first;

while (a && b)
  {
  int d;
  if ((d = Ustrncmp(a->text, b->text, 6)) == 0)
    d = Ustrcmp(a->text + 14, b->text + 14);
  if (d < 0)
    {
    *append = a;
    append= &a->next;
    a = a->next;
    }
  else
    {
    *append = b;
    append= &b->next;
    b = b->next;
    }
  }

*append = a ? a : b;
return first;
}