Commit message: Recast more internal string routines to use growable-strings
CVE: CVE-2019-16928
Vulnerability description: Exim 4.92 through 4.92.2 allows remote code execution, a different vulnerability than CVE-2019-15846. There is a heap-based buffer overflow in string_vformat in string.c involving a long EHLO command.

Project: exim

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. */

if (id != 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_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 ? "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 ? "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 = fd;
    tctx.options = topt_add_return_path | topt_no_body;
    /*XXX hmm, retval ignored.
    Could error for any number of reasons, and they are not handled. */
    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 & ~rf_notify_failure)
     )
    {
    addr = addr_failed;
    addr_failed = addr->next;
    if (addr->return_filename) Uunlink(addr->return_filename);

#ifndef DISABLE_EVENT
    msg_event_raise(US"msg:fail:delivery", addr);
#endif
    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;

	/*XXX no checking for failure!  buggy! */
	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)
        || addr_defer->dsn_flags & 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 */
	/*XXX no checking for failure!  buggy! */
        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: host.c

inet_ntoa(struct in_addr sa)
{
static uschar addr[20];
sprintf(addr, "%d.%d.%d.%d",
        (US &sa.s_addr)[0],
        (US &sa.s_addr)[1],
        (US &sa.s_addr)[2],
        (US &sa.s_addr)[3]);
  return addr;
}

Project: exim

transport_update_waiting(host_item *hostlist, uschar *tpname)
{
const uschar *prevname = US"";
host_item *host;
open_db dbblock;
open_db *dbm_file;

DEBUG(D_transport) debug_printf("updating wait-%s database\n", tpname);

/* Open the database for this transport */

if (!(dbm_file = dbfn_open(string_sprintf("wait-%.200s", tpname),
		      O_RDWR, &dbblock, TRUE)))
  return;

/* Scan the list of hosts for which this message is waiting, and ensure
that the message id is in each host record. */

for (host = hostlist; host; host = host->next)
  {
  BOOL already = FALSE;
  dbdata_wait *host_record;
  uschar *s;
  int i, host_length;
  uschar buffer[256];

  /* Skip if this is the same host as we just processed; otherwise remember
  the name for next time. */

  if (Ustrcmp(prevname, host->name) == 0) continue;
  prevname = host->name;

  /* Look up the host record; if there isn't one, make an empty one. */

  if (!(host_record = dbfn_read(dbm_file, host->name)))
    {
    host_record = store_get(sizeof(dbdata_wait) + MESSAGE_ID_LENGTH);
    host_record->count = host_record->sequence = 0;
    }

  /* Compute the current length */

  host_length = host_record->count * MESSAGE_ID_LENGTH;

  /* Search the record to see if the current message is already in it. */

  for (s = host_record->text; s < host_record->text + host_length;
       s += MESSAGE_ID_LENGTH)
    if (Ustrncmp(s, message_id, MESSAGE_ID_LENGTH) == 0)
      { already = TRUE; break; }

  /* If we haven't found this message in the main record, search any
  continuation records that exist. */

  for (i = host_record->sequence - 1; i >= 0 && !already; i--)
    {
    dbdata_wait *cont;
    sprintf(CS buffer, "%.200s:%d", host->name, i);
    if ((cont = dbfn_read(dbm_file, buffer)))
      {
      int clen = cont->count * MESSAGE_ID_LENGTH;
      for (s = cont->text; s < cont->text + clen; s += MESSAGE_ID_LENGTH)
        if (Ustrncmp(s, message_id, MESSAGE_ID_LENGTH) == 0)
          { already = TRUE; break; }
      }
    }

  /* If this message is already in a record, no need to update. */

  if (already)
    {
    DEBUG(D_transport) debug_printf("already listed for %s\n", host->name);
    continue;
    }


  /* If this record is full, write it out with a new name constructed
  from the sequence number, increase the sequence number, and empty
  the record. */

  if (host_record->count >= WAIT_NAME_MAX)
    {
    sprintf(CS buffer, "%.200s:%d", host->name, host_record->sequence);
    dbfn_write(dbm_file, buffer, host_record, sizeof(dbdata_wait) + host_length);
    host_record->sequence++;
    host_record->count = 0;
    host_length = 0;
    }

  /* If this record is not full, increase the size of the record to
  allow for one new message id. */

  else
    {
    dbdata_wait *newr =
      store_get(sizeof(dbdata_wait) + host_length + MESSAGE_ID_LENGTH);
    memcpy(newr, host_record, sizeof(dbdata_wait) + host_length);
    host_record = newr;
    }

  /* Now add the new name on the end */

  memcpy(host_record->text + host_length, message_id, MESSAGE_ID_LENGTH);
  host_record->count++;
  host_length += MESSAGE_ID_LENGTH;

  /* Update the database */

  dbfn_write(dbm_file, host->name, host_record, sizeof(dbdata_wait) + host_length);
  DEBUG(D_transport) debug_printf("added to list for %s\n", host->name);
  }

/* All now done */

dbfn_close(dbm_file);
}

Project: exim

function_store_get(size_t size)
{
return store_get((int)size);
}

Project: exim

wouldblock_reading(void)
{
int fd, rc;
fd_set fds;
struct timeval tzero;

#ifdef SUPPORT_TLS
if (tls_in.active.sock >= 0)
 return !tls_could_read();
#endif

if (smtp_inptr < smtp_inend)
  return FALSE;

fd = fileno(smtp_in);
FD_ZERO(&fds);
FD_SET(fd, &fds);
tzero.tv_sec = 0;
tzero.tv_usec = 0;
rc = select(fd + 1, (SELECT_ARG2_TYPE *)&fds, NULL, NULL, &tzero);

if (rc <= 0) return TRUE;     /* Not ready to read */
rc = smtp_getc(GETC_BUFFER_UNLIMITED);
if (rc < 0) return TRUE;      /* End of file or error */

smtp_ungetc(rc);
return FALSE;
}

Project: exim

host_and_ident(BOOL useflag)
{
if (sender_fullhost == NULL)
  {
  (void)string_format(big_buffer, big_buffer_size, "%s%s", useflag? "U=" : "",
     (sender_ident == NULL)? US"unknown" : sender_ident);
  }
else
  {
  uschar *flag = useflag? US"H=" : US"";
  uschar *iface = US"";
  if (LOGGING(incoming_interface) && interface_address != NULL)
    iface = string_sprintf(" I=[%s]:%d", interface_address, interface_port);
  if (sender_ident == NULL)
    (void)string_format(big_buffer, big_buffer_size, "%s%s%s",
      flag, sender_fullhost, iface);
  else
    (void)string_format(big_buffer, big_buffer_size, "%s%s%s U=%s",
      flag, sender_fullhost, iface, sender_ident);
  }
return big_buffer;
}

Project: exim

exim_wait_tick(struct timeval *then_tv, int resolution)
{
struct timeval now_tv;
long int now_true_usec;

(void)gettimeofday(&now_tv, NULL);
now_true_usec = now_tv.tv_usec;
now_tv.tv_usec = (now_true_usec/resolution) * resolution;

if (exim_tvcmp(&now_tv, then_tv) <= 0)
  {
  struct itimerval itval;
  itval.it_interval.tv_sec = 0;
  itval.it_interval.tv_usec = 0;
  itval.it_value.tv_sec = then_tv->tv_sec - now_tv.tv_sec;
  itval.it_value.tv_usec = then_tv->tv_usec + resolution - now_true_usec;

  /* We know that, overall, "now" is less than or equal to "then". Therefore, a
  negative value for the microseconds is possible only in the case when "now"
  is more than a second less than "then". That means that itval.it_value.tv_sec
  is greater than zero. The following correction is therefore safe. */

  if (itval.it_value.tv_usec < 0)
    {
    itval.it_value.tv_usec += 1000000;
    itval.it_value.tv_sec -= 1;
    }

  DEBUG(D_transport|D_receive)
    {
    if (!f.running_in_test_harness)
      {
      debug_printf("tick check: " TIME_T_FMT ".%06lu " TIME_T_FMT ".%06lu\n",
        then_tv->tv_sec, (long) then_tv->tv_usec,
       	now_tv.tv_sec, (long) now_tv.tv_usec);
      debug_printf("waiting " TIME_T_FMT ".%06lu\n",
        itval.it_value.tv_sec, (long) itval.it_value.tv_usec);
      }
    }

  milliwait(&itval);
  }
}

Project: exim

smtp_reset(void *reset_point)
{
recipients_list = NULL;
rcpt_count = rcpt_defer_count = rcpt_fail_count =
  raw_recipients_count = recipients_count = recipients_list_max = 0;
message_linecount = 0;
message_size = -1;
acl_added_headers = NULL;
acl_removed_headers = NULL;
f.queue_only_policy = FALSE;
rcpt_smtp_response = NULL;
fl.rcpt_smtp_response_same = TRUE;
fl.rcpt_in_progress = FALSE;
f.deliver_freeze = FALSE;                              /* Can be set by ACL */
freeze_tell = freeze_tell_config;                    /* Can be set by ACL */
fake_response = OK;                                  /* Can be set by ACL */
#ifdef WITH_CONTENT_SCAN
f.no_mbox_unspool = FALSE;                             /* Can be set by ACL */
#endif
f.submission_mode = FALSE;                             /* Can be set by ACL */
f.suppress_local_fixups = f.suppress_local_fixups_default; /* Can be set by ACL */
f.active_local_from_check = local_from_check;          /* Can be set by ACL */
f.active_local_sender_retain = local_sender_retain;    /* Can be set by ACL */
sending_ip_address = NULL;
return_path = sender_address = NULL;
sender_data = NULL;				     /* Can be set by ACL */
deliver_localpart_parent = deliver_localpart_orig = NULL;
deliver_domain_parent = deliver_domain_orig = NULL;
callout_address = NULL;
submission_name = NULL;                              /* Can be set by ACL */
raw_sender = NULL;                  /* After SMTP rewrite, before qualifying */
sender_address_unrewritten = NULL;  /* Set only after verify rewrite */
sender_verified_list = NULL;        /* No senders verified */
memset(sender_address_cache, 0, sizeof(sender_address_cache));
memset(sender_domain_cache, 0, sizeof(sender_domain_cache));

authenticated_sender = NULL;
#ifdef EXPERIMENTAL_BRIGHTMAIL
bmi_run = 0;
bmi_verdicts = NULL;
#endif
dnslist_domain = dnslist_matched = NULL;
#ifdef SUPPORT_SPF
spf_header_comment = spf_received = spf_result = spf_smtp_comment = NULL;
spf_result_guessed = FALSE;
#endif
#ifndef DISABLE_DKIM
dkim_cur_signer = dkim_signers =
dkim_signing_domain = dkim_signing_selector = dkim_signatures = NULL;
dkim_cur_signer = dkim_signers = dkim_signing_domain = dkim_signing_selector = NULL;
f.dkim_disable_verify = FALSE;
dkim_collect_input = 0;
dkim_verify_overall = dkim_verify_status = dkim_verify_reason = NULL;
dkim_key_length = 0;
dkim_verify_signers = US"$dkim_signers";
#endif
#ifdef EXPERIMENTAL_DMARC
f.dmarc_has_been_checked = f.dmarc_disable_verify = f.dmarc_enable_forensic = FALSE;
dmarc_domain_policy = dmarc_status = dmarc_status_text =
dmarc_used_domain = NULL;
#endif
#ifdef EXPERIMENTAL_ARC
arc_state = arc_state_reason = NULL;
#endif
dsn_ret = 0;
dsn_envid = NULL;
deliver_host = deliver_host_address = NULL;	/* Can be set by ACL */
#ifndef DISABLE_PRDR
prdr_requested = FALSE;
#endif
#ifdef SUPPORT_I18N
message_smtputf8 = FALSE;
#endif
body_linecount = body_zerocount = 0;

sender_rate = sender_rate_limit = sender_rate_period = NULL;
ratelimiters_mail = NULL;           /* Updated by ratelimit ACL condition */
                   /* Note that ratelimiters_conn persists across resets. */

/* Reset message ACL variables */

acl_var_m = NULL;

/* The message body variables use malloc store. They may be set if this is
not the first message in an SMTP session and the previous message caused them
to be referenced in an ACL. */

if (message_body)
  {
  store_free(message_body);
  message_body = NULL;
  }

if (message_body_end)
  {
  store_free(message_body_end);
  message_body_end = NULL;
  }

/* Warning log messages are also saved in malloc store. They are saved to avoid
repetition in the same message, but it seems right to repeat them for different
messages. */

while (acl_warn_logged)
  {
  string_item *this = acl_warn_logged;
  acl_warn_logged = acl_warn_logged->next;
  store_free(this);
  }
store_reset(reset_point);
}

Project: exim

qualify_recipient(uschar ** recipient, uschar * smtp_cmd_data, uschar * tag)
{
int rd;
if (f.allow_unqualified_recipient || strcmpic(*recipient, US"postmaster") == 0)
  {
  DEBUG(D_receive) debug_printf("unqualified address %s accepted\n",
    *recipient);
  rd = Ustrlen(recipient) + 1;
  *recipient = rewrite_address_qualify(*recipient, TRUE);
  return rd;
  }
smtp_printf("501 %s: recipient address must contain a domain\r\n", FALSE,
  smtp_cmd_data);
log_write(L_smtp_syntax_error,
  LOG_MAIN|LOG_REJECT, "unqualified %s rejected: <%s> %s%s",
  tag, *recipient, host_and_ident(TRUE), host_lookup_msg);
return 0;
}

Project: exim

acl_read(uschar *(*func)(void), uschar **error)
{
acl_block *yield = NULL;
acl_block **lastp = &yield;
acl_block *this = NULL;
acl_condition_block *cond;
acl_condition_block **condp = NULL;
uschar *s;

*error = NULL;

while ((s = (*func)()) != NULL)
  {
  int v, c;
  BOOL negated = FALSE;
  uschar *saveline = s;
  uschar name[64];

  /* Conditions (but not verbs) are allowed to be negated by an initial
  exclamation mark. */

  while (isspace(*s)) s++;
  if (*s == '!')
    {
    negated = TRUE;
    s++;
    }

  /* Read the name of a verb or a condition, or the start of a new ACL, which
  can be started by a name, or by a macro definition. */

  s = readconf_readname(name, sizeof(name), s);
  if (*s == ':' || (isupper(name[0]) && *s == '=')) return yield;

  /* If a verb is unrecognized, it may be another condition or modifier that
  continues the previous verb. */

  if ((v = acl_checkname(name, verbs, nelem(verbs))) < 0)
    {
    if (this == NULL)
      {
      *error = string_sprintf("unknown ACL verb \"%s\" in \"%s\"", name,
        saveline);
      return NULL;
      }
    }

  /* New verb */

  else
    {
    if (negated)
      {
      *error = string_sprintf("malformed ACL line \"%s\"", saveline);
      return NULL;
      }
    this = store_get(sizeof(acl_block));
    *lastp = this;
    lastp = &(this->next);
    this->next = NULL;
    this->verb = v;
    this->condition = NULL;
    condp = &(this->condition);
    if (*s == 0) continue;               /* No condition on this line */
    if (*s == '!')
      {
      negated = TRUE;
      s++;
      }
    s = readconf_readname(name, sizeof(name), s);  /* Condition name */
    }

  /* Handle a condition or modifier. */

  if ((c = acl_checkcondition(name, conditions, nelem(conditions))) < 0)
    {
    *error = string_sprintf("unknown ACL condition/modifier in \"%s\"",
      saveline);
    return NULL;
    }

  /* The modifiers may not be negated */

  if (negated && conditions[c].is_modifier)
    {
    *error = string_sprintf("ACL error: negation is not allowed with "
      "\"%s\"", conditions[c].name);
    return NULL;
    }

  /* ENDPASS may occur only with ACCEPT or DISCARD. */

  if (c == ACLC_ENDPASS &&
      this->verb != ACL_ACCEPT &&
      this->verb != ACL_DISCARD)
    {
    *error = string_sprintf("ACL error: \"%s\" is not allowed with \"%s\"",
      conditions[c].name, verbs[this->verb]);
    return NULL;
    }

  cond = store_get(sizeof(acl_condition_block));
  cond->next = NULL;
  cond->type = c;
  cond->u.negated = negated;

  *condp = cond;
  condp = &(cond->next);

  /* The "set" modifier is different in that its argument is "name=value"
  rather than just a value, and we can check the validity of the name, which
  gives us a variable name to insert into the data block. The original ACL
  variable names were acl_c0 ... acl_c9 and acl_m0 ... acl_m9. This was
  extended to 20 of each type, but after that people successfully argued for
  arbitrary names. In the new scheme, the names must start with acl_c or acl_m.
  After that, we allow alphanumerics and underscores, but the first character
  after c or m must be a digit or an underscore. This retains backwards
  compatibility. */

  if (c == ACLC_SET)
#ifndef DISABLE_DKIM
    if (  Ustrncmp(s, "dkim_verify_status", 18) == 0
       || Ustrncmp(s, "dkim_verify_reason", 18) == 0)
      {
      uschar * endptr = s+18;

      if (isalnum(*endptr))
	{
	*error = string_sprintf("invalid variable name after \"set\" in ACL "
	  "modifier \"set %s\" "
	  "(only \"dkim_verify_status\" or \"dkim_verify_reason\" permitted)",
	  s);
	return NULL;
	}
      cond->u.varname = string_copyn(s, 18);
      s = endptr;
      while (isspace(*s)) s++;
      }
    else
#endif
    {
    uschar *endptr;

    if (Ustrncmp(s, "acl_c", 5) != 0 &&
        Ustrncmp(s, "acl_m", 5) != 0)
      {
      *error = string_sprintf("invalid variable name after \"set\" in ACL "
        "modifier \"set %s\" (must start \"acl_c\" or \"acl_m\")", s);
      return NULL;
      }

    endptr = s + 5;
    if (!isdigit(*endptr) && *endptr != '_')
      {
      *error = string_sprintf("invalid variable name after \"set\" in ACL "
        "modifier \"set %s\" (digit or underscore must follow acl_c or acl_m)",
        s);
      return NULL;
      }

    while (*endptr != 0 && *endptr != '=' && !isspace(*endptr))
      {
      if (!isalnum(*endptr) && *endptr != '_')
        {
        *error = string_sprintf("invalid character \"%c\" in variable name "
          "in ACL modifier \"set %s\"", *endptr, s);
        return NULL;
        }
      endptr++;
      }

    cond->u.varname = string_copyn(s + 4, endptr - s - 4);
    s = endptr;
    while (isspace(*s)) s++;
    }

  /* For "set", we are now positioned for the data. For the others, only
  "endpass" has no data */

  if (c != ACLC_ENDPASS)
    {
    if (*s++ != '=')
      {
      *error = string_sprintf("\"=\" missing after ACL \"%s\" %s", name,
        conditions[c].is_modifier ? US"modifier" : US"condition");
      return NULL;
      }
    while (isspace(*s)) s++;
    cond->arg = string_copy(s);
    }
  }

return yield;
}

Project: exim

setup_proxy_protocol_host()
{
union {
  struct {
    uschar line[108];
  } v1;
  struct {
    uschar sig[12];
    uint8_t ver_cmd;
    uint8_t fam;
    uint16_t len;
    union {
      struct { /* TCP/UDP over IPv4, len = 12 */
        uint32_t src_addr;
        uint32_t dst_addr;
        uint16_t src_port;
        uint16_t dst_port;
      } ip4;
      struct { /* TCP/UDP over IPv6, len = 36 */
        uint8_t  src_addr[16];
        uint8_t  dst_addr[16];
        uint16_t src_port;
        uint16_t dst_port;
      } ip6;
      struct { /* AF_UNIX sockets, len = 216 */
        uschar   src_addr[108];
        uschar   dst_addr[108];
      } unx;
    } addr;
  } v2;
} hdr;

/* Temp variables used in PPv2 address:port parsing */
uint16_t tmpport;
char tmpip[INET_ADDRSTRLEN];
struct sockaddr_in tmpaddr;
char tmpip6[INET6_ADDRSTRLEN];
struct sockaddr_in6 tmpaddr6;

/* We can't read "all data until end" because while SMTP is
server-speaks-first, the TLS handshake is client-speaks-first, so for
TLS-on-connect ports the proxy protocol header will usually be immediately
followed by a TLS handshake, and with N TLS libraries, we can't reliably
reinject data for reading by those.  So instead we first read "enough to be
safely read within the header, and figure out how much more to read".
For v1 we will later read to the end-of-line, for v2 we will read based upon
the stated length.

The v2 sig is 12 octets, and another 4 gets us the length, so we know how much
data is needed total.  For v1, where the line looks like:
PROXY TCPn L3src L3dest SrcPort DestPort \r\n

However, for v1 there's also `PROXY UNKNOWN\r\n` which is only 15 octets.
We seem to support that.  So, if we read 14 octets then we can tell if we're
v2 or v1.  If we're v1, we can continue reading as normal.

If we're v2, we can't slurp up the entire header.  We need the length in the
15th & 16th octets, then to read everything after that.

So to safely handle v1 and v2, with client-sent-first supported correctly,
we have to do a minimum of 3 read calls, not 1.  Eww.
*/

#define PROXY_INITIAL_READ 14
#define PROXY_V2_HEADER_SIZE 16
#if PROXY_INITIAL_READ > PROXY_V2_HEADER_SIZE
# error Code bug in sizes of data to read for proxy usage
#endif

int get_ok = 0;
int size, ret;
int fd = fileno(smtp_in);
const char v2sig[12] = "\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A";
uschar * iptype;  /* To display debug info */
struct timeval tv;
struct timeval tvtmp;
socklen_t vslen = sizeof(struct timeval);
BOOL yield = FALSE;

/* Save current socket timeout values */
get_ok = getsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, CS &tvtmp, &vslen);

/* Proxy Protocol host must send header within a short time
(default 3 seconds) or it's considered invalid */
tv.tv_sec  = PROXY_NEGOTIATION_TIMEOUT_SEC;
tv.tv_usec = PROXY_NEGOTIATION_TIMEOUT_USEC;
if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, CS &tv, sizeof(tv)) < 0)
  goto bad;

do
  {
  /* The inbound host was declared to be a Proxy Protocol host, so
  don't do a PEEK into the data, actually slurp up enough to be
  "safe". Can't take it all because TLS-on-connect clients follow
  immediately with TLS handshake. */
  ret = recv(fd, &hdr, PROXY_INITIAL_READ, 0);
  }
  while (ret == -1 && errno == EINTR);

if (ret == -1)
  goto proxyfail;

/* For v2, handle reading the length, and then the rest. */
if ((ret == PROXY_INITIAL_READ) && (memcmp(&hdr.v2, v2sig, sizeof(v2sig)) == 0))
  {
  int retmore;
  uint8_t ver;

  /* First get the length fields. */
  do
    {
    retmore = recv(fd, (uschar*)&hdr + ret, PROXY_V2_HEADER_SIZE - PROXY_INITIAL_READ, 0);
    } while (retmore == -1 && errno == EINTR);
  if (retmore == -1)
    goto proxyfail;
  ret += retmore;

  ver = (hdr.v2.ver_cmd & 0xf0) >> 4;

  /* May 2014: haproxy combined the version and command into one byte to
  allow two full bytes for the length field in order to proxy SSL
  connections.  SSL Proxy is not supported in this version of Exim, but
  must still separate values here. */

  if (ver != 0x02)
    {
    DEBUG(D_receive) debug_printf("Invalid Proxy Protocol version: %d\n", ver);
    goto proxyfail;
    }

  /* The v2 header will always be 16 bytes per the spec. */
  size = 16 + ntohs(hdr.v2.len);
  DEBUG(D_receive) debug_printf("Detected PROXYv2 header, size %d (limit %d)\n",
      size, (int)sizeof(hdr));

  /* We should now have 16 octets (PROXY_V2_HEADER_SIZE), and we know the total
  amount that we need.  Double-check that the size is not unreasonable, then
  get the rest. */
  if (size > sizeof(hdr))
    {
    DEBUG(D_receive) debug_printf("PROXYv2 header size unreasonably large; security attack?\n");
    goto proxyfail;
    }

  do
    {
    do
      {
      retmore = recv(fd, (uschar*)&hdr + ret, size-ret, 0);
      } while (retmore == -1 && errno == EINTR);
    if (retmore == -1)
      goto proxyfail;
    ret += retmore;
    DEBUG(D_receive) debug_printf("PROXYv2: have %d/%d required octets\n", ret, size);
    } while (ret < size);

  } /* end scope for getting rest of data for v2 */

/* At this point: if PROXYv2, we've read the exact size required for all data;
if PROXYv1 then we've read "less than required for any valid line" and should
read the rest". */

if (ret >= 16 && memcmp(&hdr.v2, v2sig, 12) == 0)
  {
  uint8_t cmd = (hdr.v2.ver_cmd & 0x0f);

  switch (cmd)
    {
    case 0x01: /* PROXY command */
      switch (hdr.v2.fam)
        {
        case 0x11:  /* TCPv4 address type */
          iptype = US"IPv4";
          tmpaddr.sin_addr.s_addr = hdr.v2.addr.ip4.src_addr;
          inet_ntop(AF_INET, &tmpaddr.sin_addr, CS &tmpip, sizeof(tmpip));
          if (!string_is_ip_address(US tmpip, NULL))
            {
            DEBUG(D_receive) debug_printf("Invalid %s source IP\n", iptype);
            goto proxyfail;
            }
          proxy_local_address = sender_host_address;
          sender_host_address = string_copy(US tmpip);
          tmpport             = ntohs(hdr.v2.addr.ip4.src_port);
          proxy_local_port    = sender_host_port;
          sender_host_port    = tmpport;
          /* Save dest ip/port */
          tmpaddr.sin_addr.s_addr = hdr.v2.addr.ip4.dst_addr;
          inet_ntop(AF_INET, &tmpaddr.sin_addr, CS &tmpip, sizeof(tmpip));
          if (!string_is_ip_address(US tmpip, NULL))
            {
            DEBUG(D_receive) debug_printf("Invalid %s dest port\n", iptype);
            goto proxyfail;
            }
          proxy_external_address = string_copy(US tmpip);
          tmpport              = ntohs(hdr.v2.addr.ip4.dst_port);
          proxy_external_port  = tmpport;
          goto done;
        case 0x21:  /* TCPv6 address type */
          iptype = US"IPv6";
          memmove(tmpaddr6.sin6_addr.s6_addr, hdr.v2.addr.ip6.src_addr, 16);
          inet_ntop(AF_INET6, &tmpaddr6.sin6_addr, CS &tmpip6, sizeof(tmpip6));
          if (!string_is_ip_address(US tmpip6, NULL))
            {
            DEBUG(D_receive) debug_printf("Invalid %s source IP\n", iptype);
            goto proxyfail;
            }
          proxy_local_address = sender_host_address;
          sender_host_address = string_copy(US tmpip6);
          tmpport             = ntohs(hdr.v2.addr.ip6.src_port);
          proxy_local_port    = sender_host_port;
          sender_host_port    = tmpport;
          /* Save dest ip/port */
          memmove(tmpaddr6.sin6_addr.s6_addr, hdr.v2.addr.ip6.dst_addr, 16);
          inet_ntop(AF_INET6, &tmpaddr6.sin6_addr, CS &tmpip6, sizeof(tmpip6));
          if (!string_is_ip_address(US tmpip6, NULL))
            {
            DEBUG(D_receive) debug_printf("Invalid %s dest port\n", iptype);
            goto proxyfail;
            }
          proxy_external_address = string_copy(US tmpip6);
          tmpport              = ntohs(hdr.v2.addr.ip6.dst_port);
          proxy_external_port  = tmpport;
          goto done;
        default:
          DEBUG(D_receive)
            debug_printf("Unsupported PROXYv2 connection type: 0x%02x\n",
                         hdr.v2.fam);
          goto proxyfail;
        }
      /* Unsupported protocol, keep local connection address */
      break;
    case 0x00: /* LOCAL command */
      /* Keep local connection address for LOCAL */
      iptype = US"local";
      break;
    default:
      DEBUG(D_receive)
        debug_printf("Unsupported PROXYv2 command: 0x%x\n", cmd);
      goto proxyfail;
    }
  }
else if (ret >= 8 && memcmp(hdr.v1.line, "PROXY", 5) == 0)
  {
  uschar *p;
  uschar *end;
  uschar *sp;     /* Utility variables follow */
  int     tmp_port;
  int     r2;
  char   *endc;

  /* get the rest of the line */
  r2 = swallow_until_crlf(fd, (uschar*)&hdr, ret, sizeof(hdr)-ret);
  if (r2 == -1)
    goto proxyfail;
  ret += r2;

  p = string_copy(hdr.v1.line);
  end = memchr(p, '\r', ret - 1);

  if (!end || (end == (uschar*)&hdr + ret) || end[1] != '\n')
    {
    DEBUG(D_receive) debug_printf("Partial or invalid PROXY header\n");
    goto proxyfail;
    }
  *end = '\0'; /* Terminate the string */
  size = end + 2 - p; /* Skip header + CRLF */
  DEBUG(D_receive) debug_printf("Detected PROXYv1 header\n");
  DEBUG(D_receive) debug_printf("Bytes read not within PROXY header: %d\n", ret - size);
  /* Step through the string looking for the required fields. Ensure
  strict adherence to required formatting, exit for any error. */
  p += 5;
  if (!isspace(*(p++)))
    {
    DEBUG(D_receive) debug_printf("Missing space after PROXY command\n");
    goto proxyfail;
    }
  if (!Ustrncmp(p, CCS"TCP4", 4))
    iptype = US"IPv4";
  else if (!Ustrncmp(p,CCS"TCP6", 4))
    iptype = US"IPv6";
  else if (!Ustrncmp(p,CCS"UNKNOWN", 7))
    {
    iptype = US"Unknown";
    goto done;
    }
  else
    {
    DEBUG(D_receive) debug_printf("Invalid TCP type\n");
    goto proxyfail;
    }

  p += Ustrlen(iptype);
  if (!isspace(*(p++)))
    {
    DEBUG(D_receive) debug_printf("Missing space after TCP4/6 command\n");
    goto proxyfail;
    }
  /* Find the end of the arg */
  if ((sp = Ustrchr(p, ' ')) == NULL)
    {
    DEBUG(D_receive)
      debug_printf("Did not find proxied src %s\n", iptype);
    goto proxyfail;
    }
  *sp = '\0';
  if(!string_is_ip_address(p, NULL))
    {
    DEBUG(D_receive)
      debug_printf("Proxied src arg is not an %s address\n", iptype);
    goto proxyfail;
    }
  proxy_local_address = sender_host_address;
  sender_host_address = p;
  p = sp + 1;
  if ((sp = Ustrchr(p, ' ')) == NULL)
    {
    DEBUG(D_receive)
      debug_printf("Did not find proxy dest %s\n", iptype);
    goto proxyfail;
    }
  *sp = '\0';
  if(!string_is_ip_address(p, NULL))
    {
    DEBUG(D_receive)
      debug_printf("Proxy dest arg is not an %s address\n", iptype);
    goto proxyfail;
    }
  proxy_external_address = p;
  p = sp + 1;
  if ((sp = Ustrchr(p, ' ')) == NULL)
    {
    DEBUG(D_receive) debug_printf("Did not find proxied src port\n");
    goto proxyfail;
    }
  *sp = '\0';
  tmp_port = strtol(CCS p, &endc, 10);
  if (*endc || tmp_port == 0)
    {
    DEBUG(D_receive)
      debug_printf("Proxied src port '%s' not an integer\n", p);
    goto proxyfail;
    }
  proxy_local_port = sender_host_port;
  sender_host_port = tmp_port;
  p = sp + 1;
  if ((sp = Ustrchr(p, '\0')) == NULL)
    {
    DEBUG(D_receive) debug_printf("Did not find proxy dest port\n");
    goto proxyfail;
    }
  tmp_port = strtol(CCS p, &endc, 10);
  if (*endc || tmp_port == 0)
    {
    DEBUG(D_receive)
      debug_printf("Proxy dest port '%s' not an integer\n", p);
    goto proxyfail;
    }
  proxy_external_port = tmp_port;
  /* Already checked for /r /n above. Good V1 header received. */
  }
else
  {
  /* Wrong protocol */
  DEBUG(D_receive) debug_printf("Invalid proxy protocol version negotiation\n");
  (void) swallow_until_crlf(fd, (uschar*)&hdr, ret, sizeof(hdr)-ret);
  goto proxyfail;
  }

done:
  DEBUG(D_receive)
    debug_printf("Valid %s sender from Proxy Protocol header\n", iptype);
  yield = proxy_session;

/* Don't flush any potential buffer contents. Any input on proxyfail
should cause a synchronization failure */

proxyfail:
  restore_socket_timeout(fd, get_ok, &tvtmp, vslen);

bad:
  if (yield)
    {
    sender_host_name = NULL;
    (void) host_name_lookup();
    host_build_sender_fullhost();
    }
  else
    {
    f.proxy_session_failed = TRUE;
    DEBUG(D_receive)
      debug_printf("Failure to extract proxied host, only QUIT allowed\n");
    }

return;
}

Project: exim

transport_write_message(transport_ctx * tctx, int size_limit)
{
BOOL last_filter_was_NL = TRUE;
BOOL save_spool_file_wireformat = f.spool_file_wireformat;
int rc, len, yield, fd_read, fd_write, save_errno;
int pfd[2] = {-1, -1};
pid_t filter_pid, write_pid;

f.transport_filter_timed_out = FALSE;

/* If there is no filter command set up, call the internal function that does
the actual work, passing it the incoming fd, and return its result. */

if (  !transport_filter_argv
   || !*transport_filter_argv
   || !**transport_filter_argv
   )
  return internal_transport_write_message(tctx, size_limit);

/* Otherwise the message must be written to a filter process and read back
before being written to the incoming fd. First set up the special processing to
be done during the copying. */

nl_partial_match = -1;

if (tctx->check_string && tctx->escape_string)
  {
  nl_check = tctx->check_string;
  nl_check_length = Ustrlen(nl_check);
  nl_escape = tctx->escape_string;
  nl_escape_length = Ustrlen(nl_escape);
  }
else nl_check_length = nl_escape_length = 0;

/* Start up a subprocess to run the command. Ensure that our main fd will
be closed when the subprocess execs, but remove the flag afterwards.
(Otherwise, if this is a TCP/IP socket, it can't get passed on to another
process to deliver another message.) We get back stdin/stdout file descriptors.
If the process creation failed, give an error return. */

fd_read = -1;
fd_write = -1;
save_errno = 0;
yield = FALSE;
write_pid = (pid_t)(-1);

  {
  int bits = fcntl(tctx->u.fd, F_GETFD);
  (void)fcntl(tctx->u.fd, F_SETFD, bits | FD_CLOEXEC);
  filter_pid = child_open(USS transport_filter_argv, NULL, 077,
   &fd_write, &fd_read, FALSE);
  (void)fcntl(tctx->u.fd, F_SETFD, bits & ~FD_CLOEXEC);
  }
if (filter_pid < 0) goto TIDY_UP;      /* errno set */

DEBUG(D_transport)
  debug_printf("process %d running as transport filter: fd_write=%d fd_read=%d\n",
    (int)filter_pid, fd_write, fd_read);

/* Fork subprocess to write the message to the filter, and return the result
via a(nother) pipe. While writing to the filter, we do not do the CRLF,
smtp dots, or check string processing. */

if (pipe(pfd) != 0) goto TIDY_UP;      /* errno set */
if ((write_pid = fork()) == 0)
  {
  BOOL rc;
  (void)close(fd_read);
  (void)close(pfd[pipe_read]);
  nl_check_length = nl_escape_length = 0;

  tctx->u.fd = fd_write;
  tctx->check_string = tctx->escape_string = NULL;
  tctx->options &= ~(topt_use_crlf | topt_end_dot | topt_use_bdat);

  rc = internal_transport_write_message(tctx, size_limit);

  save_errno = errno;
  if (  write(pfd[pipe_write], (void *)&rc, sizeof(BOOL))
        != sizeof(BOOL)
     || write(pfd[pipe_write], (void *)&save_errno, sizeof(int))
        != sizeof(int)
     || write(pfd[pipe_write], (void *)&tctx->addr->more_errno, sizeof(int))
        != sizeof(int)
     || write(pfd[pipe_write], (void *)&tctx->addr->delivery_usec, sizeof(int))
        != sizeof(int)
     )
    rc = FALSE;	/* compiler quietening */
  _exit(0);
  }
save_errno = errno;

/* Parent process: close our copy of the writing subprocess' pipes. */

(void)close(pfd[pipe_write]);
(void)close(fd_write);
fd_write = -1;

/* Writing process creation failed */

if (write_pid < 0)
  {
  errno = save_errno;    /* restore */
  goto TIDY_UP;
  }

/* When testing, let the subprocess get going */

if (f.running_in_test_harness) millisleep(250);

DEBUG(D_transport)
  debug_printf("process %d writing to transport filter\n", (int)write_pid);

/* Copy the message from the filter to the output fd. A read error leaves len
== -1 and errno set. We need to apply a timeout to the read, to cope with
the case when the filter gets stuck, but it can be quite a long one. The
default is 5m, but this is now configurable. */

DEBUG(D_transport) debug_printf("copying from the filter\n");

/* Copy the output of the filter, remembering if the last character was NL. If
no data is returned, that counts as "ended with NL" (default setting of the
variable is TRUE).  The output should always be unix-format as we converted
any wireformat source on writing input to the filter. */

f.spool_file_wireformat = FALSE;
chunk_ptr = deliver_out_buffer;

for (;;)
  {
  sigalrm_seen = FALSE;
  ALARM(transport_filter_timeout);
  len = read(fd_read, deliver_in_buffer, DELIVER_IN_BUFFER_SIZE);
  ALARM_CLR(0);
  if (sigalrm_seen)
    {
    errno = ETIMEDOUT;
    f.transport_filter_timed_out = TRUE;
    goto TIDY_UP;
    }

  /* If the read was successful, write the block down the original fd,
  remembering whether it ends in \n or not. */

  if (len > 0)
    {
    if (!write_chunk(tctx, deliver_in_buffer, len)) goto TIDY_UP;
    last_filter_was_NL = (deliver_in_buffer[len-1] == '\n');
    }

  /* Otherwise, break the loop. If we have hit EOF, set yield = TRUE. */

  else
    {
    if (len == 0) yield = TRUE;
    break;
    }
  }

/* Tidying up code. If yield = FALSE there has been an error and errno is set
to something. Ensure the pipes are all closed and the processes are removed. If
there has been an error, kill the processes before waiting for them, just to be
sure. Also apply a paranoia timeout. */

TIDY_UP:
f.spool_file_wireformat = save_spool_file_wireformat;
save_errno = errno;

(void)close(fd_read);
if (fd_write > 0) (void)close(fd_write);

if (!yield)
  {
  if (filter_pid > 0) kill(filter_pid, SIGKILL);
  if (write_pid > 0)  kill(write_pid, SIGKILL);
  }

/* Wait for the filter process to complete. */

DEBUG(D_transport) debug_printf("waiting for filter process\n");
if (filter_pid > 0 && (rc = child_close(filter_pid, 30)) != 0 && yield)
  {
  yield = FALSE;
  save_errno = ERRNO_FILTER_FAIL;
  tctx->addr->more_errno = rc;
  DEBUG(D_transport) debug_printf("filter process returned %d\n", rc);
  }

/* Wait for the writing process to complete. If it ends successfully,
read the results from its pipe, provided we haven't already had a filter
process failure. */

DEBUG(D_transport) debug_printf("waiting for writing process\n");
if (write_pid > 0)
  {
  rc = child_close(write_pid, 30);
  if (yield)
    if (rc == 0)
      {
      BOOL ok;
      if (read(pfd[pipe_read], (void *)&ok, sizeof(BOOL)) != sizeof(BOOL))
	{
	DEBUG(D_transport)
	  debug_printf("pipe read from writing process: %s\n", strerror(errno));
	save_errno = ERRNO_FILTER_FAIL;
        yield = FALSE;
	}
      else if (!ok)
        {
	int dummy = read(pfd[pipe_read], (void *)&save_errno, sizeof(int));
        dummy = read(pfd[pipe_read], (void *)&tctx->addr->more_errno, sizeof(int));
        dummy = read(pfd[pipe_read], (void *)&tctx->addr->delivery_usec, sizeof(int));
	dummy = dummy;		/* compiler quietening */
        yield = FALSE;
        }
      }
    else
      {
      yield = FALSE;
      save_errno = ERRNO_FILTER_FAIL;
      tctx->addr->more_errno = rc;
      DEBUG(D_transport) debug_printf("writing process returned %d\n", rc);
      }
  }
(void)close(pfd[pipe_read]);

/* If there have been no problems we can now add the terminating "." if this is
SMTP output, turning off escaping beforehand. If the last character from the
filter was not NL, insert a NL to make the SMTP protocol work. */

if (yield)
  {
  nl_check_length = nl_escape_length = 0;
  f.spool_file_wireformat = FALSE;
  if (  tctx->options & topt_end_dot
     && ( last_filter_was_NL
        ? !write_chunk(tctx, US".\n", 2)
	: !write_chunk(tctx, US"\n.\n", 3)
     )  )
    yield = FALSE;

  /* Write out any remaining data in the buffer. */

  else
    yield = (len = chunk_ptr - deliver_out_buffer) <= 0
	  || transport_write_block(tctx, deliver_out_buffer, len, FALSE);
  }
else
  errno = save_errno;      /* From some earlier error */

DEBUG(D_transport)
  {
  debug_printf("end of filtering transport writing: yield=%d\n", yield);
  if (!yield)
    debug_printf("errno=%d more_errno=%d\n", errno, tctx->addr->more_errno);
  }

return yield;
}

Project: exim

debug_print_argv(const uschar ** argv)
{
debug_printf("exec");
while (*argv) debug_printf(" %.256s", *argv++);
debug_printf("\n");
}

Project: exim

acl_check_condition(int verb, acl_condition_block *cb, int where,
  address_item *addr, int level, BOOL *epp, uschar **user_msgptr,
  uschar **log_msgptr, int *basic_errno)
{
uschar *user_message = NULL;
uschar *log_message = NULL;
int rc = OK;
#ifdef WITH_CONTENT_SCAN
int sep = -'/';
#endif

for (; cb; cb = cb->next)
  {
  const uschar *arg;
  int control_type;

  /* The message and log_message items set up messages to be used in
  case of rejection. They are expanded later. */

  if (cb->type == ACLC_MESSAGE)
    {
    HDEBUG(D_acl) debug_printf_indent("  message: %s\n", cb->arg);
    user_message = cb->arg;
    continue;
    }

  if (cb->type == ACLC_LOG_MESSAGE)
    {
    HDEBUG(D_acl) debug_printf_indent("l_message: %s\n", cb->arg);
    log_message = cb->arg;
    continue;
    }

  /* The endpass "condition" just sets a flag to show it occurred. This is
  checked at compile time to be on an "accept" or "discard" item. */

  if (cb->type == ACLC_ENDPASS)
    {
    *epp = TRUE;
    continue;
    }

  /* For other conditions and modifiers, the argument is expanded now for some
  of them, but not for all, because expansion happens down in some lower level
  checking functions in some cases. */

  if (!conditions[cb->type].expand_at_top)
    arg = cb->arg;
  else if (!(arg = expand_string(cb->arg)))
    {
    if (f.expand_string_forcedfail) continue;
    *log_msgptr = string_sprintf("failed to expand ACL string \"%s\": %s",
      cb->arg, expand_string_message);
    return f.search_find_defer ? DEFER : ERROR;
    }

  /* Show condition, and expanded condition if it's different */

  HDEBUG(D_acl)
    {
    int lhswidth = 0;
    debug_printf_indent("check %s%s %n",
      (!conditions[cb->type].is_modifier && cb->u.negated)? "!":"",
      conditions[cb->type].name, &lhswidth);

    if (cb->type == ACLC_SET)
      {
#ifndef DISABLE_DKIM
      if (  Ustrcmp(cb->u.varname, "dkim_verify_status") == 0
	 || Ustrcmp(cb->u.varname, "dkim_verify_reason") == 0)
	{
	debug_printf("%s ", cb->u.varname);
	lhswidth += 19;
	}
      else
#endif
	{
	debug_printf("acl_%s ", cb->u.varname);
	lhswidth += 5 + Ustrlen(cb->u.varname);
	}
      }

    debug_printf("= %s\n", cb->arg);

    if (arg != cb->arg)
      debug_printf("%.*s= %s\n", lhswidth,
      US"                             ", CS arg);
    }

  /* Check that this condition makes sense at this time */

  if ((conditions[cb->type].forbids & (1 << where)) != 0)
    {
    *log_msgptr = string_sprintf("cannot %s %s condition in %s ACL",
      conditions[cb->type].is_modifier ? "use" : "test",
      conditions[cb->type].name, acl_wherenames[where]);
    return ERROR;
    }

  /* Run the appropriate test for each condition, or take the appropriate
  action for the remaining modifiers. */

  switch(cb->type)
    {
    case ACLC_ADD_HEADER:
    setup_header(arg);
    break;

    /* A nested ACL that returns "discard" makes sense only for an "accept" or
    "discard" verb. */

    case ACLC_ACL:
      rc = acl_check_wargs(where, addr, arg, user_msgptr, log_msgptr);
      if (rc == DISCARD && verb != ACL_ACCEPT && verb != ACL_DISCARD)
        {
        *log_msgptr = string_sprintf("nested ACL returned \"discard\" for "
          "\"%s\" command (only allowed with \"accept\" or \"discard\")",
          verbs[verb]);
        return ERROR;
        }
    break;

    case ACLC_AUTHENTICATED:
      rc = sender_host_authenticated ? match_isinlist(sender_host_authenticated,
	      &arg, 0, NULL, NULL, MCL_STRING, TRUE, NULL) : FAIL;
    break;

    #ifdef EXPERIMENTAL_BRIGHTMAIL
    case ACLC_BMI_OPTIN:
      {
      int old_pool = store_pool;
      store_pool = POOL_PERM;
      bmi_current_optin = string_copy(arg);
      store_pool = old_pool;
      }
    break;
    #endif

    case ACLC_CONDITION:
    /* The true/false parsing here should be kept in sync with that used in
    expand.c when dealing with ECOND_BOOL so that we don't have too many
    different definitions of what can be a boolean. */
    if (*arg == '-'
	? Ustrspn(arg+1, "0123456789") == Ustrlen(arg+1)    /* Negative number */
	: Ustrspn(arg,   "0123456789") == Ustrlen(arg))     /* Digits, or empty */
      rc = (Uatoi(arg) == 0)? FAIL : OK;
    else
      rc = (strcmpic(arg, US"no") == 0 ||
            strcmpic(arg, US"false") == 0)? FAIL :
           (strcmpic(arg, US"yes") == 0 ||
            strcmpic(arg, US"true") == 0)? OK : DEFER;
    if (rc == DEFER)
      *log_msgptr = string_sprintf("invalid \"condition\" value \"%s\"", arg);
    break;

    case ACLC_CONTINUE:    /* Always succeeds */
    break;

    case ACLC_CONTROL:
      {
      const uschar *p = NULL;
      control_type = decode_control(arg, &p, where, log_msgptr);

      /* Check if this control makes sense at this time */

      if (controls_list[control_type].forbids & (1 << where))
	{
	*log_msgptr = string_sprintf("cannot use \"control=%s\" in %s ACL",
	  controls_list[control_type].name, acl_wherenames[where]);
	return ERROR;
	}

      switch(control_type)
	{
	case CONTROL_AUTH_UNADVERTISED:
	f.allow_auth_unadvertised = TRUE;
	break;

	#ifdef EXPERIMENTAL_BRIGHTMAIL
	case CONTROL_BMI_RUN:
	bmi_run = 1;
	break;
	#endif

	#ifndef DISABLE_DKIM
	case CONTROL_DKIM_VERIFY:
	f.dkim_disable_verify = TRUE;
	#ifdef EXPERIMENTAL_DMARC
	/* Since DKIM was blocked, skip DMARC too */
	f.dmarc_disable_verify = TRUE;
	f.dmarc_enable_forensic = FALSE;
	#endif
	break;
	#endif

	#ifdef EXPERIMENTAL_DMARC
	case CONTROL_DMARC_VERIFY:
	f.dmarc_disable_verify = TRUE;
	break;

	case CONTROL_DMARC_FORENSIC:
	f.dmarc_enable_forensic = TRUE;
	break;
	#endif

	case CONTROL_DSCP:
	if (*p == '/')
	  {
	  int fd, af, level, optname, value;
	  /* If we are acting on stdin, the setsockopt may fail if stdin is not
	  a socket; we can accept that, we'll just debug-log failures anyway. */
	  fd = fileno(smtp_in);
	  af = ip_get_address_family(fd);
	  if (af < 0)
	    {
	    HDEBUG(D_acl)
	      debug_printf_indent("smtp input is probably not a socket [%s], not setting DSCP\n",
		  strerror(errno));
	    break;
	    }
	  if (dscp_lookup(p+1, af, &level, &optname, &value))
	    {
	    if (setsockopt(fd, level, optname, &value, sizeof(value)) < 0)
	      {
	      HDEBUG(D_acl) debug_printf_indent("failed to set input DSCP[%s]: %s\n",
		  p+1, strerror(errno));
	      }
	    else
	      {
	      HDEBUG(D_acl) debug_printf_indent("set input DSCP to \"%s\"\n", p+1);
	      }
	    }
	  else
	    {
	    *log_msgptr = string_sprintf("unrecognised DSCP value in \"control=%s\"", arg);
	    return ERROR;
	    }
	  }
	else
	  {
	  *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
	  return ERROR;
	  }
	break;

	case CONTROL_ERROR:
	return ERROR;

	case CONTROL_CASEFUL_LOCAL_PART:
	deliver_localpart = addr->cc_local_part;
	break;

	case CONTROL_CASELOWER_LOCAL_PART:
	deliver_localpart = addr->lc_local_part;
	break;

	case CONTROL_ENFORCE_SYNC:
	smtp_enforce_sync = TRUE;
	break;

	case CONTROL_NO_ENFORCE_SYNC:
	smtp_enforce_sync = FALSE;
	break;

	#ifdef WITH_CONTENT_SCAN
	case CONTROL_NO_MBOX_UNSPOOL:
	f.no_mbox_unspool = TRUE;
	break;
	#endif

	case CONTROL_NO_MULTILINE:
	f.no_multiline_responses = TRUE;
	break;

	case CONTROL_NO_PIPELINING:
	f.pipelining_enable = FALSE;
	break;

	case CONTROL_NO_DELAY_FLUSH:
	f.disable_delay_flush = TRUE;
	break;

	case CONTROL_NO_CALLOUT_FLUSH:
	f.disable_callout_flush = TRUE;
	break;

	case CONTROL_FAKEREJECT:
	cancel_cutthrough_connection(TRUE, US"fakereject");
	case CONTROL_FAKEDEFER:
	fake_response = (control_type == CONTROL_FAKEDEFER) ? DEFER : FAIL;
	if (*p == '/')
	  {
	  const uschar *pp = p + 1;
	  while (*pp != 0) pp++;
	  fake_response_text = expand_string(string_copyn(p+1, pp-p-1));
	  p = pp;
	  }
	 else
	  {
	  /* Explicitly reset to default string */
	  fake_response_text = US"Your message has been rejected but is being kept for evaluation.\nIf it was a legitimate message, it may still be delivered to the target recipient(s).";
	  }
	break;

	case CONTROL_FREEZE:
	f.deliver_freeze = TRUE;
	deliver_frozen_at = time(NULL);
	freeze_tell = freeze_tell_config;       /* Reset to configured value */
	if (Ustrncmp(p, "/no_tell", 8) == 0)
	  {
	  p += 8;
	  freeze_tell = NULL;
	  }
	if (*p != 0)
	  {
	  *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
	  return ERROR;
	  }
	cancel_cutthrough_connection(TRUE, US"item frozen");
	break;

	case CONTROL_QUEUE_ONLY:
	f.queue_only_policy = TRUE;
	cancel_cutthrough_connection(TRUE, US"queueing forced");
	break;

#if defined(SUPPORT_TLS) && defined(EXPERIMENTAL_REQUIRETLS)
	case CONTROL_REQUIRETLS:
	tls_requiretls |= REQUIRETLS_MSG;
	break;
#endif
	case CONTROL_SUBMISSION:
	originator_name = US"";
	f.submission_mode = TRUE;
	while (*p == '/')
	  {
	  if (Ustrncmp(p, "/sender_retain", 14) == 0)
	    {
	    p += 14;
	    f.active_local_sender_retain = TRUE;
	    f.active_local_from_check = FALSE;
	    }
	  else if (Ustrncmp(p, "/domain=", 8) == 0)
	    {
	    const uschar *pp = p + 8;
	    while (*pp != 0 && *pp != '/') pp++;
	    submission_domain = string_copyn(p+8, pp-p-8);
	    p = pp;
	    }
	  /* The name= option must be last, because it swallows the rest of
	  the string. */
	  else if (Ustrncmp(p, "/name=", 6) == 0)
	    {
	    const uschar *pp = p + 6;
	    while (*pp != 0) pp++;
	    submission_name = string_copy(parse_fix_phrase(p+6, pp-p-6,
	      big_buffer, big_buffer_size));
	    p = pp;
	    }
	  else break;
	  }
	if (*p != 0)
	  {
	  *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
	  return ERROR;
	  }
	break;

	case CONTROL_DEBUG:
	  {
	  uschar * debug_tag = NULL;
	  uschar * debug_opts = NULL;
	  BOOL kill = FALSE;

	  while (*p == '/')
	    {
	    const uschar * pp = p+1;
	    if (Ustrncmp(pp, "tag=", 4) == 0)
	      {
	      for (pp += 4; *pp && *pp != '/';) pp++;
	      debug_tag = string_copyn(p+5, pp-p-5);
	      }
	    else if (Ustrncmp(pp, "opts=", 5) == 0)
	      {
	      for (pp += 5; *pp && *pp != '/';) pp++;
	      debug_opts = string_copyn(p+6, pp-p-6);
	      }
	    else if (Ustrncmp(pp, "kill", 4) == 0)
	      {
	      for (pp += 4; *pp && *pp != '/';) pp++;
	      kill = TRUE;
	      }
	    else
	      while (*pp && *pp != '/') pp++;
	    p = pp;
	    }

	    if (kill)
	      debug_logging_stop();
	    else
	      debug_logging_activate(debug_tag, debug_opts);
	  }
	break;

	case CONTROL_SUPPRESS_LOCAL_FIXUPS:
	f.suppress_local_fixups = TRUE;
	break;

	case CONTROL_CUTTHROUGH_DELIVERY:
	{
	uschar * ignored = NULL;
#ifndef DISABLE_PRDR
	if (prdr_requested)
#else
	if (0)
#endif
	  /* Too hard to think about for now.  We might in future cutthrough
	  the case where both sides handle prdr and this-node prdr acl
	  is "accept" */
	  ignored = US"PRDR active";
	else
	  {
	  if (f.deliver_freeze)
	    ignored = US"frozen";
	  else if (f.queue_only_policy)
	    ignored = US"queue-only";
	  else if (fake_response == FAIL)
	    ignored = US"fakereject";
	  else
	    {
	    if (rcpt_count == 1)
	      {
	      cutthrough.delivery = TRUE;	/* control accepted */
	      while (*p == '/')
		{
		const uschar * pp = p+1;
		if (Ustrncmp(pp, "defer=", 6) == 0)
		  {
		  pp += 6;
		  if (Ustrncmp(pp, "pass", 4) == 0) cutthrough.defer_pass = TRUE;
		  /* else if (Ustrncmp(pp, "spool") == 0) ;	default */
		  }
		else
		  while (*pp && *pp != '/') pp++;
		p = pp;
		}
	      }
	    else
	      ignored = US"nonfirst rcpt";
	    }
	  }
	DEBUG(D_acl) if (ignored)
	  debug_printf(" cutthrough request ignored on %s item\n", ignored);
	}
	break;

#ifdef SUPPORT_I18N
	case CONTROL_UTF8_DOWNCONVERT:
	if (*p == '/')
	  {
	  if (p[1] == '1')
	    {
	    message_utf8_downconvert = 1;
	    addr->prop.utf8_downcvt = TRUE;
	    addr->prop.utf8_downcvt_maybe = FALSE;
	    p += 2;
	    break;
	    }
	  if (p[1] == '0')
	    {
	    message_utf8_downconvert = 0;
	    addr->prop.utf8_downcvt = FALSE;
	    addr->prop.utf8_downcvt_maybe = FALSE;
	    p += 2;
	    break;
	    }
	  if (p[1] == '-' && p[2] == '1')
	    {
	    message_utf8_downconvert = -1;
	    addr->prop.utf8_downcvt = FALSE;
	    addr->prop.utf8_downcvt_maybe = TRUE;
	    p += 3;
	    break;
	    }
	  *log_msgptr = US"bad option value for control=utf8_downconvert";
	  }
	else
	  {
	  message_utf8_downconvert = 1;
	  addr->prop.utf8_downcvt = TRUE;
	  addr->prop.utf8_downcvt_maybe = FALSE;
	  break;
	  }
	return ERROR;
#endif

	}
      break;
      }

    #ifdef EXPERIMENTAL_DCC
    case ACLC_DCC:
      {
      /* Separate the regular expression and any optional parameters. */
      const uschar * list = arg;
      uschar *ss = string_nextinlist(&list, &sep, big_buffer, big_buffer_size);
      /* Run the dcc backend. */
      rc = dcc_process(&ss);
      /* Modify return code based upon the existence of options. */
      while ((ss = string_nextinlist(&list, &sep, big_buffer, big_buffer_size)))
        if (strcmpic(ss, US"defer_ok") == 0 && rc == DEFER)
          rc = FAIL;   /* FAIL so that the message is passed to the next ACL */
      }
    break;
    #endif

    #ifdef WITH_CONTENT_SCAN
    case ACLC_DECODE:
    rc = mime_decode(&arg);
    break;
    #endif

    case ACLC_DELAY:
      {
      int delay = readconf_readtime(arg, 0, FALSE);
      if (delay < 0)
        {
        *log_msgptr = string_sprintf("syntax error in argument for \"delay\" "
          "modifier: \"%s\" is not a time value", arg);
        return ERROR;
        }
      else
        {
        HDEBUG(D_acl) debug_printf_indent("delay modifier requests %d-second delay\n",
          delay);
        if (host_checking)
          {
          HDEBUG(D_acl)
            debug_printf_indent("delay skipped in -bh checking mode\n");
          }

	/* NOTE 1: Remember that we may be
        dealing with stdin/stdout here, in addition to TCP/IP connections.
        Also, delays may be specified for non-SMTP input, where smtp_out and
        smtp_in will be NULL. Whatever is done must work in all cases.

        NOTE 2: The added feature of flushing the output before a delay must
        apply only to SMTP input. Hence the test for smtp_out being non-NULL.
        */

        else
          {
          if (smtp_out && !f.disable_delay_flush)
	    mac_smtp_fflush();

#if !defined(NO_POLL_H) && defined (POLLRDHUP)
	    {
	    struct pollfd p;
	    nfds_t n = 0;
	    if (smtp_out)
	      {
	      p.fd = fileno(smtp_out);
	      p.events = POLLRDHUP;
	      n = 1;
	      }
	    if (poll(&p, n, delay*1000) > 0)
	      HDEBUG(D_acl) debug_printf_indent("delay cancelled by peer close\n");
	    }
#else
	  /* Lacking POLLRDHUP it appears to be impossible to detect that a
	  TCP/IP connection has gone away without reading from it. This means
	  that we cannot shorten the delay below if the client goes away,
	  because we cannot discover that the client has closed its end of the
	  connection. (The connection is actually in a half-closed state,
	  waiting for the server to close its end.) It would be nice to be able
	  to detect this state, so that the Exim process is not held up
	  unnecessarily. However, it seems that we can't. The poll() function
	  does not do the right thing, and in any case it is not always
	  available.  */

          while (delay > 0) delay = sleep(delay);
#endif
          }
        }
      }
    break;

    #ifndef DISABLE_DKIM
    case ACLC_DKIM_SIGNER:
    if (dkim_cur_signer)
      rc = match_isinlist(dkim_cur_signer,
                          &arg,0,NULL,NULL,MCL_STRING,TRUE,NULL);
    else
      rc = FAIL;
    break;

    case ACLC_DKIM_STATUS:
    rc = match_isinlist(dkim_verify_status,
                        &arg,0,NULL,NULL,MCL_STRING,TRUE,NULL);
    break;
    #endif

    #ifdef EXPERIMENTAL_DMARC
    case ACLC_DMARC_STATUS:
    if (!f.dmarc_has_been_checked)
      dmarc_process();
    f.dmarc_has_been_checked = TRUE;
    /* used long way of dmarc_exim_expand_query() in case we need more
     * view into the process in the future. */
    rc = match_isinlist(dmarc_exim_expand_query(DMARC_VERIFY_STATUS),
                        &arg,0,NULL,NULL,MCL_STRING,TRUE,NULL);
    break;
    #endif

    case ACLC_DNSLISTS:
    rc = verify_check_dnsbl(where, &arg, log_msgptr);
    break;

    case ACLC_DOMAINS:
    rc = match_isinlist(addr->domain, &arg, 0, &domainlist_anchor,
      addr->domain_cache, MCL_DOMAIN, TRUE, CUSS &deliver_domain_data);
    break;

    /* The value in tls_cipher is the full cipher name, for example,
    TLSv1:DES-CBC3-SHA:168, whereas the values to test for are just the
    cipher names such as DES-CBC3-SHA. But program defensively. We don't know
    what may in practice come out of the SSL library - which at the time of
    writing is poorly documented. */

    case ACLC_ENCRYPTED:
    if (tls_in.cipher == NULL) rc = FAIL; else
      {
      uschar *endcipher = NULL;
      uschar *cipher = Ustrchr(tls_in.cipher, ':');
      if (cipher == NULL) cipher = tls_in.cipher; else
        {
        endcipher = Ustrchr(++cipher, ':');
        if (endcipher != NULL) *endcipher = 0;
        }
      rc = match_isinlist(cipher, &arg, 0, NULL, NULL, MCL_STRING, TRUE, NULL);
      if (endcipher != NULL) *endcipher = ':';
      }
    break;

    /* Use verify_check_this_host() instead of verify_check_host() so that
    we can pass over &host_data to catch any looked up data. Once it has been
    set, it retains its value so that it's still there if another ACL verb
    comes through here and uses the cache. However, we must put it into
    permanent store in case it is also expected to be used in a subsequent
    message in the same SMTP connection. */

    case ACLC_HOSTS:
    rc = verify_check_this_host(&arg, sender_host_cache, NULL,
      (sender_host_address == NULL)? US"" : sender_host_address,
      CUSS &host_data);
    if (rc == DEFER) *log_msgptr = search_error_message;
    if (host_data) host_data = string_copy_malloc(host_data);
    break;

    case ACLC_LOCAL_PARTS:
    rc = match_isinlist(addr->cc_local_part, &arg, 0,
      &localpartlist_anchor, addr->localpart_cache, MCL_LOCALPART, TRUE,
      CUSS &deliver_localpart_data);
    break;

    case ACLC_LOG_REJECT_TARGET:
      {
      int logbits = 0;
      int sep = 0;
      const uschar *s = arg;
      uschar *ss;
      while ((ss = string_nextinlist(&s, &sep, big_buffer, big_buffer_size)))
        {
        if (Ustrcmp(ss, "main") == 0) logbits |= LOG_MAIN;
        else if (Ustrcmp(ss, "panic") == 0) logbits |= LOG_PANIC;
        else if (Ustrcmp(ss, "reject") == 0) logbits |= LOG_REJECT;
        else
          {
          logbits |= LOG_MAIN|LOG_REJECT;
          log_write(0, LOG_MAIN|LOG_PANIC, "unknown log name \"%s\" in "
            "\"log_reject_target\" in %s ACL", ss, acl_wherenames[where]);
          }
        }
      log_reject_target = logbits;
      }
    break;

    case ACLC_LOGWRITE:
      {
      int logbits = 0;
      const uschar *s = arg;
      if (*s == ':')
        {
        s++;
        while (*s != ':')
          {
          if (Ustrncmp(s, "main", 4) == 0)
            { logbits |= LOG_MAIN; s += 4; }
          else if (Ustrncmp(s, "panic", 5) == 0)
            { logbits |= LOG_PANIC; s += 5; }
          else if (Ustrncmp(s, "reject", 6) == 0)
            { logbits |= LOG_REJECT; s += 6; }
          else
            {
            logbits = LOG_MAIN|LOG_PANIC;
            s = string_sprintf(":unknown log name in \"%s\" in "
              "\"logwrite\" in %s ACL", arg, acl_wherenames[where]);
            }
          if (*s == ',') s++;
          }
        s++;
        }
      while (isspace(*s)) s++;

      if (logbits == 0) logbits = LOG_MAIN;
      log_write(0, logbits, "%s", string_printing(s));
      }
    break;

    #ifdef WITH_CONTENT_SCAN
    case ACLC_MALWARE:			/* Run the malware backend. */
      {
      /* Separate the regular expression and any optional parameters. */
      const uschar * list = arg;
      uschar *ss = string_nextinlist(&list, &sep, big_buffer, big_buffer_size);
      uschar *opt;
      BOOL defer_ok = FALSE;
      int timeout = 0;

      while ((opt = string_nextinlist(&list, &sep, NULL, 0)))
        if (strcmpic(opt, US"defer_ok") == 0)
	  defer_ok = TRUE;
	else if (  strncmpic(opt, US"tmo=", 4) == 0
		&& (timeout = readconf_readtime(opt+4, '\0', FALSE)) < 0
		)
	  {
	  *log_msgptr = string_sprintf("bad timeout value in '%s'", opt);
	  return ERROR;
	  }

      rc = malware(ss, timeout);
      if (rc == DEFER && defer_ok)
	rc = FAIL;	/* FAIL so that the message is passed to the next ACL */
      }
    break;

    case ACLC_MIME_REGEX:
    rc = mime_regex(&arg);
    break;
    #endif

    case ACLC_QUEUE:
    if (Ustrchr(arg, '/'))
      {
      *log_msgptr = string_sprintf(
	      "Directory separator not permitted in queue name: '%s'", arg);
      return ERROR;
      }
    queue_name = string_copy_malloc(arg);
    break;

    case ACLC_RATELIMIT:
    rc = acl_ratelimit(arg, where, log_msgptr);
    break;

    case ACLC_RECIPIENTS:
    rc = match_address_list(CUS addr->address, TRUE, TRUE, &arg, NULL, -1, 0,
      CUSS &recipient_data);
    break;

    #ifdef WITH_CONTENT_SCAN
    case ACLC_REGEX:
    rc = regex(&arg);
    break;
    #endif

    case ACLC_REMOVE_HEADER:
    setup_remove_header(arg);
    break;

    case ACLC_SENDER_DOMAINS:
      {
      uschar *sdomain;
      sdomain = Ustrrchr(sender_address, '@');
      sdomain = sdomain ? sdomain + 1 : US"";
      rc = match_isinlist(sdomain, &arg, 0, &domainlist_anchor,
        sender_domain_cache, MCL_DOMAIN, TRUE, NULL);
      }
    break;

    case ACLC_SENDERS:
    rc = match_address_list(CUS sender_address, TRUE, TRUE, &arg,
      sender_address_cache, -1, 0, CUSS &sender_data);
    break;

    /* Connection variables must persist forever */

    case ACLC_SET:
      {
      int old_pool = store_pool;
      if (  cb->u.varname[0] == 'c'
#ifndef DISABLE_DKIM
         || cb->u.varname[0] == 'd'
#endif
#ifndef DISABLE_EVENT
	 || event_name		/* An event is being delivered */
#endif
	 )
        store_pool = POOL_PERM;
#ifndef DISABLE_DKIM	/* Overwriteable dkim result variables */
      if (Ustrcmp(cb->u.varname, "dkim_verify_status") == 0)
	dkim_verify_status = string_copy(arg);
      else if (Ustrcmp(cb->u.varname, "dkim_verify_reason") == 0)
	dkim_verify_reason = string_copy(arg);
      else
#endif
	acl_var_create(cb->u.varname)->data.ptr = string_copy(arg);
      store_pool = old_pool;
      }
    break;

#ifdef WITH_CONTENT_SCAN
    case ACLC_SPAM:
      {
      /* Separate the regular expression and any optional parameters. */
      const uschar * list = arg;
      uschar *ss = string_nextinlist(&list, &sep, big_buffer, big_buffer_size);

      rc = spam(CUSS &ss);
      /* Modify return code based upon the existence of options. */
      while ((ss = string_nextinlist(&list, &sep, big_buffer, big_buffer_size)))
        if (strcmpic(ss, US"defer_ok") == 0 && rc == DEFER)
          rc = FAIL;	/* FAIL so that the message is passed to the next ACL */
      }
    break;
#endif

#ifdef SUPPORT_SPF
    case ACLC_SPF:
      rc = spf_process(&arg, sender_address, SPF_PROCESS_NORMAL);
    break;
    case ACLC_SPF_GUESS:
      rc = spf_process(&arg, sender_address, SPF_PROCESS_GUESS);
    break;
#endif

    case ACLC_UDPSEND:
    rc = acl_udpsend(arg, log_msgptr);
    break;

    /* If the verb is WARN, discard any user message from verification, because
    such messages are SMTP responses, not header additions. The latter come
    only from explicit "message" modifiers. However, put the user message into
    $acl_verify_message so it can be used in subsequent conditions or modifiers
    (until something changes it). */

    case ACLC_VERIFY:
    rc = acl_verify(where, addr, arg, user_msgptr, log_msgptr, basic_errno);
    if (*user_msgptr)
      acl_verify_message = *user_msgptr;
    if (verb == ACL_WARN) *user_msgptr = NULL;
    break;

    default:
    log_write(0, LOG_MAIN|LOG_PANIC_DIE, "internal ACL error: unknown "
      "condition %d", cb->type);
    break;
    }

  /* If a condition was negated, invert OK/FAIL. */

  if (!conditions[cb->type].is_modifier && cb->u.negated)
    if (rc == OK) rc = FAIL;
    else if (rc == FAIL || rc == FAIL_DROP) rc = OK;

  if (rc != OK) break;   /* Conditions loop */
  }


/* If the result is the one for which "message" and/or "log_message" are used,
handle the values of these modifiers. If there isn't a log message set, we make
it the same as the user message.

"message" is a user message that will be included in an SMTP response. Unless
it is empty, it overrides any previously set user message.

"log_message" is a non-user message, and it adds to any existing non-user
message that is already set.

Most verbs have but a single return for which the messages are relevant, but
for "discard", it's useful to have the log message both when it succeeds and
when it fails. For "accept", the message is used in the OK case if there is no
"endpass", but (for backwards compatibility) in the FAIL case if "endpass" is
present. */

if (*epp && rc == OK) user_message = NULL;

if ((BIT(rc) & msgcond[verb]) != 0)
  {
  uschar *expmessage;
  uschar *old_user_msgptr = *user_msgptr;
  uschar *old_log_msgptr = (*log_msgptr != NULL)? *log_msgptr : old_user_msgptr;

  /* If the verb is "warn", messages generated by conditions (verification or
  nested ACLs) are always discarded. This also happens for acceptance verbs
  when they actually do accept. Only messages specified at this level are used.
  However, the value of an existing message is available in $acl_verify_message
  during expansions. */

  if (verb == ACL_WARN ||
      (rc == OK && (verb == ACL_ACCEPT || verb == ACL_DISCARD)))
    *log_msgptr = *user_msgptr = NULL;

  if (user_message)
    {
    acl_verify_message = old_user_msgptr;
    expmessage = expand_string(user_message);
    if (!expmessage)
      {
      if (!f.expand_string_forcedfail)
        log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand ACL message \"%s\": %s",
          user_message, expand_string_message);
      }
    else if (expmessage[0] != 0) *user_msgptr = expmessage;
    }

  if (log_message)
    {
    acl_verify_message = old_log_msgptr;
    expmessage = expand_string(log_message);
    if (!expmessage)
      {
      if (!f.expand_string_forcedfail)
        log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand ACL message \"%s\": %s",
          log_message, expand_string_message);
      }
    else if (expmessage[0] != 0)
      {
      *log_msgptr = (*log_msgptr == NULL)? expmessage :
        string_sprintf("%s: %s", expmessage, *log_msgptr);
      }
    }

  /* If no log message, default it to the user message */

  if (!*log_msgptr) *log_msgptr = *user_msgptr;
  }

acl_verify_message = NULL;
return rc;
}

Project: exim

host_ntoa(int type, const void *arg, uschar *buffer, int *portptr)
{
uschar *yield;

/* The new world. It is annoying that we have to fish out the address from
different places in the block, depending on what kind of address it is. It
is also a pain that inet_ntop() returns a const uschar *, whereas the IPv4
function inet_ntoa() returns just uschar *, and some picky compilers insist
on warning if one assigns a const uschar * to a uschar *. Hence the casts. */

#if HAVE_IPV6
uschar addr_buffer[46];
if (type < 0)
  {
  int family = ((struct sockaddr *)arg)->sa_family;
  if (family == AF_INET6)
    {
    struct sockaddr_in6 *sk = (struct sockaddr_in6 *)arg;
    yield = US inet_ntop(family, &(sk->sin6_addr), CS addr_buffer,
      sizeof(addr_buffer));
    if (portptr != NULL) *portptr = ntohs(sk->sin6_port);
    }
  else
    {
    struct sockaddr_in *sk = (struct sockaddr_in *)arg;
    yield = US inet_ntop(family, &(sk->sin_addr), CS addr_buffer,
      sizeof(addr_buffer));
    if (portptr != NULL) *portptr = ntohs(sk->sin_port);
    }
  }
else
  {
  yield = US inet_ntop(type, arg, CS addr_buffer, sizeof(addr_buffer));
  }

/* If the result is a mapped IPv4 address, show it in V4 format. */

if (Ustrncmp(yield, "::ffff:", 7) == 0) yield += 7;

#else  /* HAVE_IPV6 */

/* The old world */

if (type < 0)
  {
  yield = US inet_ntoa(((struct sockaddr_in *)arg)->sin_addr);
  if (portptr != NULL) *portptr = ntohs(((struct sockaddr_in *)arg)->sin_port);
  }
else
  yield = US inet_ntoa(*((struct in_addr *)arg));
#endif

/* If there is no buffer, put the string into some new store. */

if (buffer == NULL) return string_copy(yield);

/* Callers of this function with a non-NULL buffer must ensure that it is
large enough to hold an IPv6 address, namely, at least 46 bytes. That's what
makes this use of strcpy() OK. */

Ustrcpy(buffer, yield);
return buffer;
}

Project: exim

show_exim_information(enum commandline_info request, FILE *stream)
{
const uschar **pp;

switch(request)
  {
  case CMDINFO_NONE:
    fprintf(stream, "Oops, something went wrong.\n");
    return;
  case CMDINFO_HELP:
    fprintf(stream,
"The -bI: flag takes a string indicating which information to provide.\n"
"If the string is not recognised, you'll get this help (on stderr).\n"
"\n"
"  exim -bI:help    this information\n"
"  exim -bI:dscp    list of known dscp value keywords\n"
"  exim -bI:sieve   list of supported sieve extensions\n"
);
    return;
  case CMDINFO_SIEVE:
    for (pp = exim_sieve_extension_list; *pp; ++pp)
      fprintf(stream, "%s\n", *pp);
    return;
  case CMDINFO_DSCP:
    dscp_list_to_stream(stream);
    return;
  }
}

Project: exim

smtp_data_timeout_exit(void)
{
log_write(L_lost_incoming_connection,
  LOG_MAIN, "SMTP data timeout (message abandoned) on connection from %s F=<%s>",
  sender_fullhost ? sender_fullhost : US"local process", sender_address);
receive_bomb_out(US"data-timeout", US"SMTP incoming data timeout");
/* Does not return */
}

Project: exim
File: deliver.c

deliver_msglog(const char *format, ...)
{
va_list ap;
if (!message_logs) return;
va_start(ap, format);
vfprintf(message_log, format, ap);
fflush(message_log);
va_end(ap);
}

Project: exim

header_checkname(void *h, char *name, int len)
{
h = h;            /* Keep picky compilers happy */
name = name;
len = len;
return 0;
}

Project: exim

set_process_info(const char *format, ...)
{
gstring gs = { .size = PROCESS_INFO_SIZE - 2, .ptr = 0, .s = process_info };
gstring * g;
int len;
va_list ap;

g = string_fmt_append(&gs, "%5d ", (int)getpid());
len = g->ptr;
va_start(ap, format);
if (!string_vformat(g, FALSE, format, ap))
  {
  gs.ptr = len;
  g = string_cat(&gs, US"**** string overflowed buffer ****");
  }
g = string_catn(g, US"\n", 1);
string_from_gstring(g);
process_info_len = g->ptr;
DEBUG(D_process_info) debug_printf("set_process_info: %s", process_info);
va_end(ap);
}

Project: exim

smtp_setup_batch_msg(void)
{
int done = 0;
void *reset_point = store_get(0);

/* Save the line count at the start of each transaction - single commands
like HELO and RSET count as whole transactions. */

bsmtp_transaction_linecount = receive_linecount;

if ((receive_feof)()) return 0;   /* Treat EOF as QUIT */

cancel_cutthrough_connection(TRUE, US"smtp_setup_batch_msg");
smtp_reset(reset_point);                /* Reset for start of message */

/* Deal with SMTP commands. This loop is exited by setting done to a POSITIVE
value. The values are 2 larger than the required yield of the function. */

while (done <= 0)
  {
  uschar *errmess;
  uschar *recipient = NULL;
  int start, end, sender_domain, recipient_domain;

  switch(smtp_read_command(FALSE, GETC_BUFFER_UNLIMITED))
    {
    /* The HELO/EHLO commands set sender_address_helo if they have
    valid data; otherwise they are ignored, except that they do
    a reset of the state. */

    case HELO_CMD:
    case EHLO_CMD:

      check_helo(smtp_cmd_data);
      /* Fall through */

    case RSET_CMD:
      cancel_cutthrough_connection(TRUE, US"RSET received");
      smtp_reset(reset_point);
      bsmtp_transaction_linecount = receive_linecount;
      break;


    /* The MAIL FROM command requires an address as an operand. All we
    do here is to parse it for syntactic correctness. The form "<>" is
    a special case which converts into an empty string. The start/end
    pointers in the original are not used further for this address, as
    it is the canonical extracted address which is all that is kept. */

    case MAIL_CMD:
      smtp_mailcmd_count++;              /* Count for no-mail log */
      if (sender_address != NULL)
	/* The function moan_smtp_batch() does not return. */
	moan_smtp_batch(smtp_cmd_buffer, "503 Sender already given");

      if (smtp_cmd_data[0] == 0)
	/* The function moan_smtp_batch() does not return. */
	moan_smtp_batch(smtp_cmd_buffer, "501 MAIL FROM must have an address operand");

      /* Reset to start of message */

      cancel_cutthrough_connection(TRUE, US"MAIL received");
      smtp_reset(reset_point);

      /* Apply SMTP rewrite */

      raw_sender = ((rewrite_existflags & rewrite_smtp) != 0)?
	rewrite_one(smtp_cmd_data, rewrite_smtp|rewrite_smtp_sender, NULL, FALSE,
	  US"", global_rewrite_rules) : smtp_cmd_data;

      /* Extract the address; the TRUE flag allows <> as valid */

      raw_sender =
	parse_extract_address(raw_sender, &errmess, &start, &end, &sender_domain,
	  TRUE);

      if (!raw_sender)
	/* The function moan_smtp_batch() does not return. */
	moan_smtp_batch(smtp_cmd_buffer, "501 %s", errmess);

      sender_address = string_copy(raw_sender);

      /* Qualify unqualified sender addresses if permitted to do so. */

      if (  !sender_domain
         && sender_address[0] != 0 && sender_address[0] != '@')
	if (f.allow_unqualified_sender)
	  {
	  sender_address = rewrite_address_qualify(sender_address, FALSE);
	  DEBUG(D_receive) debug_printf("unqualified address %s accepted "
	    "and rewritten\n", raw_sender);
	  }
	/* The function moan_smtp_batch() does not return. */
	else
	  moan_smtp_batch(smtp_cmd_buffer, "501 sender address must contain "
	    "a domain");
      break;


    /* The RCPT TO command requires an address as an operand. All we do
    here is to parse it for syntactic correctness. There may be any number
    of RCPT TO commands, specifying multiple senders. We build them all into
    a data structure that is in argc/argv format. The start/end values
    given by parse_extract_address are not used, as we keep only the
    extracted address. */

    case RCPT_CMD:
      if (!sender_address)
	/* The function moan_smtp_batch() does not return. */
	moan_smtp_batch(smtp_cmd_buffer, "503 No sender yet given");

      if (smtp_cmd_data[0] == 0)
	/* The function moan_smtp_batch() does not return. */
	moan_smtp_batch(smtp_cmd_buffer,
	  "501 RCPT TO must have an address operand");

      /* Check maximum number allowed */

      if (recipients_max > 0 && recipients_count + 1 > recipients_max)
	/* The function moan_smtp_batch() does not return. */
	moan_smtp_batch(smtp_cmd_buffer, "%s too many recipients",
	  recipients_max_reject? "552": "452");

      /* Apply SMTP rewrite, then extract address. Don't allow "<>" as a
      recipient address */

      recipient = rewrite_existflags & rewrite_smtp
	? rewrite_one(smtp_cmd_data, rewrite_smtp, NULL, FALSE, US"",
		      global_rewrite_rules)
	: smtp_cmd_data;

      recipient = parse_extract_address(recipient, &errmess, &start, &end,
	&recipient_domain, FALSE);

      if (!recipient)
	/* The function moan_smtp_batch() does not return. */
	moan_smtp_batch(smtp_cmd_buffer, "501 %s", errmess);

      /* If the recipient address is unqualified, qualify it if permitted. Then
      add it to the list of recipients. */

      if (!recipient_domain)
	if (f.allow_unqualified_recipient)
	  {
	  DEBUG(D_receive) debug_printf("unqualified address %s accepted\n",
	    recipient);
	  recipient = rewrite_address_qualify(recipient, TRUE);
	  }
	/* The function moan_smtp_batch() does not return. */
	else
	  moan_smtp_batch(smtp_cmd_buffer,
	    "501 recipient address must contain a domain");

      receive_add_recipient(recipient, -1);
      break;


    /* The DATA command is legal only if it follows successful MAIL FROM
    and RCPT TO commands. This function is complete when a valid DATA
    command is encountered. */

    case DATA_CMD:
      if (!sender_address || recipients_count <= 0)
	/* The function moan_smtp_batch() does not return. */
	if (!sender_address)
	  moan_smtp_batch(smtp_cmd_buffer,
	    "503 MAIL FROM:<sender> command must precede DATA");
	else
	  moan_smtp_batch(smtp_cmd_buffer,
	    "503 RCPT TO:<recipient> must precede DATA");
      else
	{
	done = 3;                      /* DATA successfully achieved */
	message_ended = END_NOTENDED;  /* Indicate in middle of message */
	}
      break;


    /* The VRFY, EXPN, HELP, ETRN, and NOOP commands are ignored. */

    case VRFY_CMD:
    case EXPN_CMD:
    case HELP_CMD:
    case NOOP_CMD:
    case ETRN_CMD:
      bsmtp_transaction_linecount = receive_linecount;
      break;


    case EOF_CMD:
    case QUIT_CMD:
      done = 2;
      break;


    case BADARG_CMD:
      /* The function moan_smtp_batch() does not return. */
      moan_smtp_batch(smtp_cmd_buffer, "501 Unexpected argument data");
      break;


    case BADCHAR_CMD:
      /* The function moan_smtp_batch() does not return. */
      moan_smtp_batch(smtp_cmd_buffer, "501 Unexpected NULL in SMTP command");
      break;


    default:
      /* The function moan_smtp_batch() does not return. */
      moan_smtp_batch(smtp_cmd_buffer, "500 Command unrecognized");
      break;
    }
  }

return done - 2;  /* Convert yield values */
}

Project: exim

BOOL lmtp_transport_entry(transport_instance *tblock, address_item *addr) {return FALSE;}

Project: exim

host_find_interfaces(void)
{
ip_address_item *running_interfaces = NULL;

if (local_interface_data == NULL)
  {
  void *reset_item = store_get(0);
  ip_address_item *dlist = host_build_ifacelist(CUS local_interfaces,
    US"local_interfaces");
  ip_address_item *xlist = host_build_ifacelist(CUS extra_local_interfaces,
    US"extra_local_interfaces");
  ip_address_item *ipa;

  if (dlist == NULL) dlist = xlist; else
    {
    for (ipa = dlist; ipa->next != NULL; ipa = ipa->next);
    ipa->next = xlist;
    }

  for (ipa = dlist; ipa != NULL; ipa = ipa->next)
    {
    if (Ustrcmp(ipa->address, "0.0.0.0") == 0 ||
        Ustrcmp(ipa->address, "::0") == 0)
      {
      ip_address_item *ipa2;
      BOOL ipv6 = ipa->address[0] == ':';
      if (running_interfaces == NULL)
        running_interfaces = os_find_running_interfaces();
      for (ipa2 = running_interfaces; ipa2 != NULL; ipa2 = ipa2->next)
        {
        if ((Ustrchr(ipa2->address, ':') != NULL) == ipv6)
          local_interface_data = add_unique_interface(local_interface_data,
          ipa2);
        }
      }
    else
      {
      local_interface_data = add_unique_interface(local_interface_data, ipa);
      DEBUG(D_interface)
        {
        debug_printf("Configured local interface: address=%s", ipa->address);
        if (ipa->port != 0) debug_printf(" port=%d", ipa->port);
        debug_printf("\n");
        }
      }
    }
  store_reset(reset_item);
  }

return local_interface_data;
}

Project: exim

transport_rcpt_address(address_item *addr, BOOL include_affixes)
{
uschar *at;
int plen, slen;

if (include_affixes)
  {
  setflag(addr, af_include_affixes);  /* Affects logged => line */
  return addr->address;
  }

if (addr->suffix == NULL)
  {
  if (addr->prefix == NULL) return addr->address;
  return addr->address + Ustrlen(addr->prefix);
  }

at = Ustrrchr(addr->address, '@');
plen = (addr->prefix == NULL)? 0 : Ustrlen(addr->prefix);
slen = Ustrlen(addr->suffix);

return string_sprintf("%.*s@%s", (int)(at - addr->address - plen - slen),
   addr->address + plen, at + 1);
}

Project: exim
File: call_pam.c

static void dummy(int x) { dummy2(x-1); }

Project: exim

transport_set_up_command(const uschar ***argvptr, uschar *cmd,
  BOOL expand_arguments, int expand_failed, address_item *addr,
  uschar *etext, uschar **errptr)
{
address_item *ad;
const uschar **argv;
uschar *s, *ss;
int address_count = 0;
int argcount = 0;
int i, max_args;

/* Get store in which to build an argument list. Count the number of addresses
supplied, and allow for that many arguments, plus an additional 60, which
should be enough for anybody. Multiple addresses happen only when the local
delivery batch option is set. */

for (ad = addr; ad != NULL; ad = ad->next) address_count++;
max_args = address_count + 60;
*argvptr = argv = store_get((max_args+1)*sizeof(uschar *));

/* Split the command up into arguments terminated by white space. Lose
trailing space at the start and end. Double-quoted arguments can contain \\ and
\" escapes and so can be handled by the standard function; single-quoted
arguments are verbatim. Copy each argument into a new string. */

s = cmd;
while (isspace(*s)) s++;

while (*s != 0 && argcount < max_args)
  {
  if (*s == '\'')
    {
    ss = s + 1;
    while (*ss != 0 && *ss != '\'') ss++;
    argv[argcount++] = ss = store_get(ss - s++);
    while (*s != 0 && *s != '\'') *ss++ = *s++;
    if (*s != 0) s++;
    *ss++ = 0;
    }
  else argv[argcount++] = string_copy(string_dequote(CUSS &s));
  while (isspace(*s)) s++;
  }

argv[argcount] = US 0;

/* If *s != 0 we have run out of argument slots. */

if (*s != 0)
  {
  uschar *msg = string_sprintf("Too many arguments in command \"%s\" in "
    "%s", cmd, etext);
  if (addr != NULL)
    {
    addr->transport_return = FAIL;
    addr->message = msg;
    }
  else *errptr = msg;
  return FALSE;
  }

/* Expand each individual argument if required. Expansion happens for pipes set
up in filter files and with directly-supplied commands. It does not happen if
the pipe comes from a traditional .forward file. A failing expansion is a big
disaster if the command came from Exim's configuration; if it came from a user
it is just a normal failure. The expand_failed value is used as the error value
to cater for these two cases.

An argument consisting just of the text "$pipe_addresses" is treated specially.
It is not passed to the general expansion function. Instead, it is replaced by
a number of arguments, one for each address. This avoids problems with shell
metacharacters and spaces in addresses.

If the parent of the top address has an original part of "system-filter", this
pipe was set up by the system filter, and we can permit the expansion of
$recipients. */

DEBUG(D_transport)
  {
  debug_printf("direct command:\n");
  for (i = 0; argv[i] != US 0; i++)
    debug_printf("  argv[%d] = %s\n", i, string_printing(argv[i]));
  }

if (expand_arguments)
  {
  BOOL allow_dollar_recipients = addr != NULL &&
    addr->parent != NULL &&
    Ustrcmp(addr->parent->address, "system-filter") == 0;

  for (i = 0; argv[i] != US 0; i++)
    {

    /* Handle special fudge for passing an address list */

    if (addr != NULL &&
        (Ustrcmp(argv[i], "$pipe_addresses") == 0 ||
         Ustrcmp(argv[i], "${pipe_addresses}") == 0))
      {
      int additional;

      if (argcount + address_count - 1 > max_args)
        {
        addr->transport_return = FAIL;
        addr->message = string_sprintf("Too many arguments to command \"%s\" "
          "in %s", cmd, etext);
        return FALSE;
        }

      additional = address_count - 1;
      if (additional > 0)
        memmove(argv + i + 1 + additional, argv + i + 1,
          (argcount - i)*sizeof(uschar *));

      for (ad = addr; ad != NULL; ad = ad->next) {
          argv[i++] = ad->address;
          argcount++;
      }

      /* Subtract one since we replace $pipe_addresses */
      argcount--;
      i--;
      }

      /* Handle special case of $address_pipe when af_force_command is set */

    else if (addr != NULL && testflag(addr,af_force_command) &&
        (Ustrcmp(argv[i], "$address_pipe") == 0 ||
         Ustrcmp(argv[i], "${address_pipe}") == 0))
      {
      int address_pipe_i;
      int address_pipe_argcount = 0;
      int address_pipe_max_args;
      uschar **address_pipe_argv;

      /* We can never have more then the argv we will be loading into */
      address_pipe_max_args = max_args - argcount + 1;

      DEBUG(D_transport)
        debug_printf("address_pipe_max_args=%d\n", address_pipe_max_args);

      /* We allocate an additional for (uschar *)0 */
      address_pipe_argv = store_get((address_pipe_max_args+1)*sizeof(uschar *));

      /* +1 because addr->local_part[0] == '|' since af_force_command is set */
      s = expand_string(addr->local_part + 1);

      if (s == NULL || *s == '\0')
        {
        addr->transport_return = FAIL;
        addr->message = string_sprintf("Expansion of \"%s\" "
           "from command \"%s\" in %s failed: %s",
           (addr->local_part + 1), cmd, etext, expand_string_message);
        return FALSE;
        }

      while (isspace(*s)) s++; /* strip leading space */

      while (*s != 0 && address_pipe_argcount < address_pipe_max_args)
        {
        if (*s == '\'')
          {
          ss = s + 1;
          while (*ss != 0 && *ss != '\'') ss++;
          address_pipe_argv[address_pipe_argcount++] = ss = store_get(ss - s++);
          while (*s != 0 && *s != '\'') *ss++ = *s++;
          if (*s != 0) s++;
          *ss++ = 0;
          }
        else address_pipe_argv[address_pipe_argcount++] =
	      string_copy(string_dequote(CUSS &s));
        while (isspace(*s)) s++; /* strip space after arg */
        }

      address_pipe_argv[address_pipe_argcount] = US 0;

      /* If *s != 0 we have run out of argument slots. */
      if (*s != 0)
        {
        uschar *msg = string_sprintf("Too many arguments in $address_pipe "
          "\"%s\" in %s", addr->local_part + 1, etext);
        if (addr != NULL)
          {
          addr->transport_return = FAIL;
          addr->message = msg;
          }
        else *errptr = msg;
        return FALSE;
        }

      /* address_pipe_argcount - 1
       * because we are replacing $address_pipe in the argument list
       * with the first thing it expands to */
      if (argcount + address_pipe_argcount - 1 > max_args)
        {
        addr->transport_return = FAIL;
        addr->message = string_sprintf("Too many arguments to command "
          "\"%s\" after expanding $address_pipe in %s", cmd, etext);
        return FALSE;
        }

      /* If we are not just able to replace the slot that contained
       * $address_pipe (address_pipe_argcount == 1)
       * We have to move the existing argv by address_pipe_argcount - 1
       * Visually if address_pipe_argcount == 2:
       * [argv 0][argv 1][argv 2($address_pipe)][argv 3][0]
       * [argv 0][argv 1][ap_arg0][ap_arg1][old argv 3][0]
       */
      if (address_pipe_argcount > 1)
        memmove(
          /* current position + additional args */
          argv + i + address_pipe_argcount,
          /* current position + 1 (for the (uschar *)0 at the end) */
          argv + i + 1,
          /* -1 for the (uschar *)0 at the end)*/
          (argcount - i)*sizeof(uschar *)
        );

      /* Now we fill in the slots we just moved argv out of
       * [argv 0][argv 1][argv 2=pipeargv[0]][argv 3=pipeargv[1]][old argv 3][0]
       */
      for (address_pipe_i = 0;
           address_pipe_argv[address_pipe_i] != US 0;
           address_pipe_i++)
        {
        argv[i++] = address_pipe_argv[address_pipe_i];
        argcount++;
        }

      /* Subtract one since we replace $address_pipe */
      argcount--;
      i--;
      }

    /* Handle normal expansion string */

    else
      {
      const uschar *expanded_arg;
      f.enable_dollar_recipients = allow_dollar_recipients;
      expanded_arg = expand_cstring(argv[i]);
      f.enable_dollar_recipients = FALSE;

      if (expanded_arg == NULL)
        {
        uschar *msg = string_sprintf("Expansion of \"%s\" "
          "from command \"%s\" in %s failed: %s",
          argv[i], cmd, etext, expand_string_message);
        if (addr != NULL)
          {
          addr->transport_return = expand_failed;
          addr->message = msg;
          }
        else *errptr = msg;
        return FALSE;
        }
      argv[i] = expanded_arg;
      }
    }

  DEBUG(D_transport)
    {
    debug_printf("direct command after expansion:\n");
    for (i = 0; argv[i] != US 0; i++)
      debug_printf("  argv[%d] = %s\n", i, string_printing(argv[i]));
    }
  }

return TRUE;
}

Project: exim
File: deliver.c

same_hosts(host_item *one, host_item *two)
{
while (one && two)
  {
  if (Ustrcmp(one->name, two->name) != 0)
    {
    int mx = one->mx;
    host_item *end_one = one;
    host_item *end_two = two;

    /* Batch up only if there was no MX and the list was not randomized */

    if (mx == MX_NONE) return FALSE;

    /* Find the ends of the shortest sequence of identical MX values */

    while (  end_one->next && end_one->next->mx == mx
          && end_two->next && end_two->next->mx == mx)
      {
      end_one = end_one->next;
      end_two = end_two->next;
      }

    /* If there aren't any duplicates, there's no match. */

    if (end_one == one) return FALSE;

    /* For each host in the 'one' sequence, check that it appears in the 'two'
    sequence, returning FALSE if not. */

    for (;;)
      {
      host_item *hi;
      for (hi = two; hi != end_two->next; hi = hi->next)
        if (Ustrcmp(one->name, hi->name) == 0) break;
      if (hi == end_two->next) return FALSE;
      if (one == end_one) break;
      one = one->next;
      }

    /* All the hosts in the 'one' sequence were found in the 'two' sequence.
    Ensure both are pointing at the last host, and carry on as for equality. */

    two = end_two;
    }

  /* if the names matched but ports do not, mismatch */
  else if (one->port != two->port)
    return FALSE;

  /* Hosts matched */

  one = one->next;
  two = two->next;
  }

/* True if both are NULL */

return (one == two);
}

Project: exim

expansion_test_line(uschar * line)
{
int len;
BOOL dummy_macexp;

Ustrncpy(big_buffer, line, big_buffer_size);
big_buffer[big_buffer_size-1] = '\0';
len = Ustrlen(big_buffer);

(void) macros_expand(0, &len, &dummy_macexp);

if (isupper(big_buffer[0]))
  {
  if (macro_read_assignment(big_buffer))
    printf("Defined macro '%s'\n", mlast->name);
  }
else
  if ((line = expand_string(big_buffer))) printf("%s\n", CS line);
  else printf("Failed: %s\n", expand_string_message);
}

Project: exim

debug_logging_stop(void)
{
if (!debug_file || !debuglog_name[0]) return;

debug_selector = 0;
fclose(debug_file);
debug_file = NULL;
unlink_log(lt_debug);
}

Project: exim

header_match(uschar *name, BOOL has_addresses, BOOL cond, string_item *strings,
  int count, ...)
{
va_list ap;
string_item *s;
int i;
int slen = Ustrlen(name);

for (s = strings; s != NULL; s = s->next)
  {
  if (one_pattern_match(name, slen, has_addresses, s->text)) return cond;
  }

va_start(ap, count);
for (i = 0; i < count; i++)
  if (one_pattern_match(name, slen, has_addresses, va_arg(ap, uschar *)))
    {
    va_end(ap);
    return cond;
    }
va_end(ap);

return !cond;
}

Project: exim

header_add_backend(BOOL after, uschar *name, BOOL topnot, int type,
  const char *format, va_list ap)
{
header_line *h, *new;
header_line **hptr;

uschar *p, *q;
uschar buffer[HEADER_ADD_BUFFER_SIZE];
gstring gs = { .size = HEADER_ADD_BUFFER_SIZE, .ptr = 0, .s = buffer };

if (!header_last) return;

if (!string_vformat(&gs, FALSE, format, ap))
  log_write(0, LOG_MAIN|LOG_PANIC_DIE, "string too long in header_add: "
    "%.100s ...", string_from_gstring(&gs));
string_from_gstring(&gs);

/* Find where to insert this header */

if (!name)
  {
  if (after)
    {
    hptr = &(header_last->next);
    h = NULL;
    }
  else
    {
    hptr = &header_list;

    /* header_list->text can be NULL if we get here between when the new
    received header is allocated and when it is actually filled in. We want
    that header to be first, so skip it for now. */

    if (!header_list->text)
      hptr = &header_list->next;
    h = *hptr;
    }
  }

else
  {
  int len = Ustrlen(name);

  /* Find the first non-deleted header with the correct name. */

  for (hptr = &header_list; (h = *hptr); hptr = &h->next)
    if (header_testname(h, name, len, TRUE))
      break;

  /* Handle the case where no header is found. To insert at the bottom, nothing
  needs to be done. */

  if (!h)
    {
    if (topnot)
      {
      hptr = &header_list;
      h = header_list;
      }
    }

  /* Handle the case where a header is found. Check for more if "after" is
  true. In this case, we want to include deleted headers in the block. */

  else if (after)
    for (;;)
      {
      if (!h->next || !header_testname(h, name, len, FALSE)) break;
      hptr = &(h->next);
      h = h->next;
      }
  }

/* Loop for multiple header lines, taking care about continuations. At this
point, we have hptr pointing to the link field that will point to the new
header, and h containing the following header, or NULL. */

for (p = q = buffer; *p != 0; )
  {
  for (;;)
    {
    q = Ustrchr(q, '\n');
    if (!q) q = p + Ustrlen(p);
    if (*(++q) != ' ' && *q != '\t') break;
    }

  new = store_get(sizeof(header_line));
  new->text = string_copyn(p, q - p);
  new->slen = q - p;
  new->type = type;
  new->next = h;

  *hptr = new;
  hptr = &(new->next);

  if (!h) header_last = new;
  p = q;
  }
}

Project: exim
File: deliver.c

rmt_dlv_checked_write(int fd, char id, char subid, void * buf, ssize_t size)
{
uschar pipe_header[PIPE_HEADER_SIZE+1];
size_t total_len = PIPE_HEADER_SIZE + size;

struct iovec iov[2] = {
  { pipe_header, PIPE_HEADER_SIZE },  /* indication about the data to expect */
  { buf, size }                       /* *the* data */
};

ssize_t ret;

/* we assume that size can't get larger then BIG_BUFFER_SIZE which currently is set to 16k */
/* complain to log if someone tries with buffer sizes we can't handle*/

if (size > BIG_BUFFER_SIZE-1)
  {
  log_write(0, LOG_MAIN|LOG_PANIC_DIE,
    "Failed writing transport result to pipe: can't handle buffers > %d bytes. truncating!\n",
      BIG_BUFFER_SIZE-1);
  size = BIG_BUFFER_SIZE;
  }

/* Should we check that we do not write more than PIPE_BUF? What would
that help? */

/* convert size to human readable string prepended by id and subid */
if (PIPE_HEADER_SIZE != snprintf(CS pipe_header, PIPE_HEADER_SIZE+1, "%c%c%05ld",
    id, subid, (long)size))
  log_write(0, LOG_MAIN|LOG_PANIC_DIE, "header snprintf failed\n");

DEBUG(D_deliver) debug_printf("header write id:%c,subid:%c,size:%ld,final:%s\n",
                                 id, subid, (long)size, pipe_header);

if ((ret = writev(fd, iov, 2)) != total_len)
  log_write(0, LOG_MAIN|LOG_PANIC_DIE,
    "Failed writing transport result to pipe (%ld of %ld bytes): %s",
    (long)ret, (long)total_len, ret == -1 ? strerror(errno) : "short write");
}

Project: exim

tfo_out_check(int sock)
{
# if defined(TCP_INFO) && defined(EXIM_HAVE_TCPI_UNACKED)
struct tcp_info tinfo;
socklen_t len = sizeof(tinfo);

switch (tcp_out_fastopen)
  {
    /* This is a somewhat dubious detection method; totally undocumented so likely
    to fail in future kernels.  There seems to be no documented way.  What we really
    want to know is if the server sent smtp-banner data before our ACK of his SYN,ACK
    hit him.  What this (possibly?) detects is whether we sent a TFO cookie with our
    SYN, as distinct from a TFO request.  This gets a false-positive when the server
    key is rotated; we send the old one (which this test sees) but the server returns
    the new one and does not send its SMTP banner before we ACK his SYN,ACK.
     To force that rotation case:
     '# echo -n "00000000-00000000-00000000-0000000" >/proc/sys/net/ipv4/tcp_fastopen_key'
    The kernel seems to be counting unack'd packets. */

  case TFO_ATTEMPTED_NODATA:
    if (  getsockopt(sock, IPPROTO_TCP, TCP_INFO, &tinfo, &len) == 0
       && tinfo.tcpi_state == TCP_SYN_SENT
       && tinfo.tcpi_unacked > 1
       )
      {
      DEBUG(D_transport|D_v)
	debug_printf("TCP_FASTOPEN tcpi_unacked %d\n", tinfo.tcpi_unacked);
      tcp_out_fastopen = TFO_USED_NODATA;
      }
    break;

    /* When called after waiting for received data we should be able
    to tell if data we sent was accepted. */

  case TFO_ATTEMPTED_DATA:
    if (  getsockopt(sock, IPPROTO_TCP, TCP_INFO, &tinfo, &len) == 0
       && tinfo.tcpi_state == TCP_ESTABLISHED
       )
      if (tinfo.tcpi_options & TCPI_OPT_SYN_DATA)
	{
	DEBUG(D_transport|D_v) debug_printf("TFO: data was acked\n");
	tcp_out_fastopen = TFO_USED_DATA;
	}
      else
	{
	DEBUG(D_transport|D_v) debug_printf("TFO: had to retransmit\n");
	tcp_out_fastopen = TFO_NOT_USED;
	}
    break;
  }
# endif
}

Project: exim

smtp_buffered(void)
{
return smtp_inptr < smtp_inend;
}

Project: exim

smtp_cmd_hist(void)
{
int  i;
gstring * list = NULL;
uschar * s;

for (i = smtp_ch_index; i < SMTP_HBUFF_SIZE; i++)
  if (smtp_connection_had[i] != SCH_NONE)
    list = string_append_listele(list, ',', smtp_names[smtp_connection_had[i]]);

for (i = 0; i < smtp_ch_index; i++)
  list = string_append_listele(list, ',', smtp_names[smtp_connection_had[i]]);

s = string_from_gstring(list);
return s ? s : US"";
}

Project: exim

check_port(uschar *address)
{
int port = host_address_extract_port(address);
if (string_is_ip_address(address, NULL) == 0)
  exim_fail("exim abandoned: \"%s\" is not an IP address\n", address);
return port;
}

Project: exim

acl_var_write(uschar *name, uschar *value, void *ctx)
{
FILE *f = (FILE *)ctx;
fprintf(f, "-acl%c %s %d\n%s\n", name[0], name+1, Ustrlen(value), value);
}

Project: exim

static BOOL check_response(int *errno_value, int more_errno, uschar *buffer,
  int *yield, uschar **message)
{
*yield = '4';    /* Default setting is to give a temporary error */

/* Handle response timeout */

if (*errno_value == ETIMEDOUT)
  {
  *message = string_sprintf("LMTP timeout after %s", big_buffer);
  if (transport_count > 0)
    *message = string_sprintf("%s (%d bytes written)", *message,
      transport_count);
  *errno_value = 0;
  return FALSE;
  }

/* Handle malformed LMTP response */

if (*errno_value == ERRNO_SMTPFORMAT)
  {
  *message = string_sprintf("Malformed LMTP response after %s: %s",
    big_buffer, string_printing(buffer));
  return FALSE;
  }

/* Handle a failed filter process error; can't send QUIT as we mustn't
end the DATA. */

if (*errno_value == ERRNO_FILTER_FAIL)
  {
  *message = string_sprintf("transport filter process failed (%d)%s",
    more_errno,
    (more_errno == EX_EXECFAILED)? ": unable to execute command" : "");
  return FALSE;
  }

/* Handle a failed add_headers expansion; can't send QUIT as we mustn't
end the DATA. */

if (*errno_value == ERRNO_CHHEADER_FAIL)
  {
  *message =
    string_sprintf("failed to expand headers_add or headers_remove: %s",
      expand_string_message);
  return FALSE;
  }

/* Handle failure to write a complete data block */

if (*errno_value == ERRNO_WRITEINCOMPLETE)
  {
  *message = string_sprintf("failed to write a data block");
  return FALSE;
  }

/* Handle error responses from the remote process. */

if (buffer[0] != 0)
  {
  const uschar *s = string_printing(buffer);
  *message = string_sprintf("LMTP error after %s: %s", big_buffer, s);
  *yield = buffer[0];
  return TRUE;
  }

/* No data was read. If there is no errno, this must be the EOF (i.e.
connection closed) case, which causes deferral. Otherwise, leave the errno
value to be interpreted. In all cases, we have to assume the connection is now
dead. */

if (*errno_value == 0)
  {
  *errno_value = ERRNO_SMTPCLOSED;
  *message = string_sprintf("LMTP connection closed after %s", big_buffer);
  }

return FALSE;
}

Project: exim

write_syslog(int priority, const uschar *s)
{
int len, pass;
int linecount = 0;

if (!syslog_pid && LOGGING(pid))
  s = string_sprintf("%.*s%s", (int)pid_position[0], s, s + pid_position[1]);
if (!syslog_timestamp)
  {
  len = log_timezone ? 26 : 20;
  if (LOGGING(millisec)) len += 4;
  s += len;
  }

len = Ustrlen(s);

#ifndef NO_OPENLOG
if (!syslog_open && !f.running_in_test_harness)
  {
# ifdef SYSLOG_LOG_PID
  openlog(CS syslog_processname, LOG_PID|LOG_CONS, syslog_facility);
# else
  openlog(CS syslog_processname, LOG_CONS, syslog_facility);
# endif
  syslog_open = TRUE;
  }
#endif

/* First do a scan through the message in order to determine how many lines
it is going to end up as. Then rescan to output it. */

for (pass = 0; pass < 2; pass++)
  {
  int i;
  int tlen;
  const uschar * ss = s;
  for (i = 1, tlen = len; tlen > 0; i++)
    {
    int plen = tlen;
    uschar *nlptr = Ustrchr(ss, '\n');
    if (nlptr != NULL) plen = nlptr - ss;
#ifndef SYSLOG_LONG_LINES
    if (plen > MAX_SYSLOG_LEN) plen = MAX_SYSLOG_LEN;
#endif
    tlen -= plen;
    if (ss[plen] == '\n') tlen--;    /* chars left */

    if (pass == 0)
      linecount++;
    else if (f.running_in_test_harness)
      if (linecount == 1)
        fprintf(stderr, "SYSLOG: '%.*s'\n", plen, ss);
      else
        fprintf(stderr, "SYSLOG: '[%d%c%d] %.*s'\n", i,
          ss[plen] == '\n' && tlen != 0 ? '\\' : '/',
          linecount, plen, ss);
    else
      if (linecount == 1)
        syslog(priority, "%.*s", plen, ss);
      else
        syslog(priority, "[%d%c%d] %.*s", i,
          ss[plen] == '\n' && tlen != 0 ? '\\' : '/',
          linecount, plen, ss);

    ss += plen;
    if (*ss == '\n') ss++;
    }
  }
}

Project: exim

smtp_getc(unsigned lim)
{
if (smtp_inptr >= smtp_inend)
  if (!smtp_refill(lim))
    return EOF;
return *smtp_inptr++;
}

Project: exim

exim_tvcmp(struct timeval *t1, struct timeval *t2)
{
if (t1->tv_sec > t2->tv_sec) return +1;
if (t1->tv_sec < t2->tv_sec) return -1;
if (t1->tv_usec > t2->tv_usec) return +1;
if (t1->tv_usec < t2->tv_usec) return -1;
return 0;
}