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

smtp_getbuf(unsigned * len)
{
unsigned size;
uschar * buf;

if (smtp_inptr >= smtp_inend)
  if (!smtp_refill(*len))
    { *len = 0; return NULL; }

if ((size = smtp_inend - smtp_inptr) > *len) size = *len;
buf = smtp_inptr;
smtp_inptr += size;
*len = size;
return buf;
}

Project: exim
File: deliver.c

print_dsn_diagnostic_code(const address_item *addr, FILE *f)
{
uschar *s = testflag(addr, af_pass_message) ? addr->message : NULL;

/* af_pass_message and addr->message set ? print remote host answer */
if (s)
  {
  DEBUG(D_deliver)
    debug_printf("DSN Diagnostic-Code: addr->message = %s\n", addr->message);

  /* search first ": ". we assume to find the remote-MTA answer there */
  if (!(s = Ustrstr(addr->message, ": ")))
    return;				/* not found, bail out */
  s += 2;  /* skip ": " */
  fprintf(f, "Diagnostic-Code: smtp; ");
  }
/* no message available. do nothing */
else return;

while (*s)
  if (*s == '\\' && s[1] == 'n')
    {
    fputs("\n ", f);    /* as defined in RFC 3461 */
    s += 2;
    }
  else
    fputc(*s++, f);

fputc('\n', f);
}

Project: exim
File: host.c

host_remove_duplicates(host_item *host, host_item **lastptr)
{
while (host != *lastptr)
  {
  if (host->address != NULL)
    {
    host_item *h = host;
    while (h != *lastptr)
      {
      if (h->next->address != NULL &&
          Ustrcmp(h->next->address, host->address) == 0)
        {
        DEBUG(D_host_lookup) debug_printf("duplicate IP address %s (MX=%d) "
          "removed\n", host->address, h->next->mx);
        if (h->next == *lastptr) *lastptr = h;
        h->next = h->next->next;
        }
      else h = h->next;
      }
    }
  /* If the last item was removed, host may have become == *lastptr */
  if (host != *lastptr) host = host->next;
  }
}

Project: exim
File: deliver.c

deliver_set_expansions(address_item *addr)
{
if (!addr)
  {
  const uschar ***p = address_expansions;
  while (*p) **p++ = NULL;
  return;
  }

/* Exactly what gets set depends on whether there is one or more addresses, and
what they contain. These first ones are always set, taking their values from
the first address. */

if (!addr->host_list)
  {
  deliver_host = deliver_host_address = US"";
  deliver_host_port = 0;
  }
else
  {
  deliver_host = addr->host_list->name;
  deliver_host_address = addr->host_list->address;
  deliver_host_port = addr->host_list->port;
  }

deliver_recipients = addr;
deliver_address_data = addr->prop.address_data;
deliver_domain_data = addr->prop.domain_data;
deliver_localpart_data = addr->prop.localpart_data;

/* These may be unset for multiple addresses */

deliver_domain = addr->domain;
self_hostname = addr->self_hostname;

#ifdef EXPERIMENTAL_BRIGHTMAIL
bmi_deliver = 1;    /* deliver by default */
bmi_alt_location = NULL;
bmi_base64_verdict = NULL;
bmi_base64_tracker_verdict = NULL;
#endif

/* If there's only one address we can set everything. */

if (!addr->next)
  {
  address_item *addr_orig;

  deliver_localpart = addr->local_part;
  deliver_localpart_prefix = addr->prefix;
  deliver_localpart_suffix = addr->suffix;

  for (addr_orig = addr; addr_orig->parent; addr_orig = addr_orig->parent) ;
  deliver_domain_orig = addr_orig->domain;

  /* Re-instate any prefix and suffix in the original local part. In all
  normal cases, the address will have a router associated with it, and we can
  choose the caseful or caseless version accordingly. However, when a system
  filter sets up a pipe, file, or autoreply delivery, no router is involved.
  In this case, though, there won't be any prefix or suffix to worry about. */

  deliver_localpart_orig = !addr_orig->router
    ? addr_orig->local_part
    : addr_orig->router->caseful_local_part
    ? addr_orig->cc_local_part
    : addr_orig->lc_local_part;

  /* If there's a parent, make its domain and local part available, and if
  delivering to a pipe or file, or sending an autoreply, get the local
  part from the parent. For pipes and files, put the pipe or file string
  into address_pipe and address_file. */

  if (addr->parent)
    {
    deliver_domain_parent = addr->parent->domain;
    deliver_localpart_parent = !addr->parent->router
      ? addr->parent->local_part
      : addr->parent->router->caseful_local_part
      ? addr->parent->cc_local_part
      : addr->parent->lc_local_part;

    /* File deliveries have their own flag because they need to be picked out
    as special more often. */

    if (testflag(addr, af_pfr))
      {
      if (testflag(addr, af_file))	    address_file = addr->local_part;
      else if (deliver_localpart[0] == '|') address_pipe = addr->local_part;
      deliver_localpart = addr->parent->local_part;
      deliver_localpart_prefix = addr->parent->prefix;
      deliver_localpart_suffix = addr->parent->suffix;
      }
    }

#ifdef EXPERIMENTAL_BRIGHTMAIL
    /* Set expansion variables related to Brightmail AntiSpam */
    bmi_base64_verdict = bmi_get_base64_verdict(deliver_localpart_orig, deliver_domain_orig);
    bmi_base64_tracker_verdict = bmi_get_base64_tracker_verdict(bmi_base64_verdict);
    /* get message delivery status (0 - don't deliver | 1 - deliver) */
    bmi_deliver = bmi_get_delivery_status(bmi_base64_verdict);
    /* if message is to be delivered, get eventual alternate location */
    if (bmi_deliver == 1)
      bmi_alt_location = bmi_get_alt_location(bmi_base64_verdict);
#endif

  }

/* For multiple addresses, don't set local part, and leave the domain and
self_hostname set only if it is the same for all of them. It is possible to
have multiple pipe and file addresses, but only when all addresses have routed
to the same pipe or file. */

else
  {
  address_item *addr2;
  if (testflag(addr, af_pfr))
    {
    if (testflag(addr, af_file))	 address_file = addr->local_part;
    else if (addr->local_part[0] == '|') address_pipe = addr->local_part;
    }
  for (addr2 = addr->next; addr2; addr2 = addr2->next)
    {
    if (deliver_domain && Ustrcmp(deliver_domain, addr2->domain) != 0)
      deliver_domain = NULL;
    if (  self_hostname
       && (  !addr2->self_hostname
          || Ustrcmp(self_hostname, addr2->self_hostname) != 0
       )  )
      self_hostname = NULL;
    if (!deliver_domain && !self_hostname) break;
    }
  }
}

Project: exim

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

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

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

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

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

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

/* Now loop for each remote delivery */

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

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

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

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

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

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

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

  if (previously_transported(addr, FALSE)) continue;

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

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

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

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

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

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


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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

  deliver_set_expansions(addr);

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

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

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

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

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

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

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

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

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

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

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

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

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

    if (ok)
      {
      smtp_transport_options_block * ob;

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

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

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

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

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

      continue;
      }

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

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

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

  transport_filter_argv = NULL;

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

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

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

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

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

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

    par_reduce(parmax - 1, fallback);
    }

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

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

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

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

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

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

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

  search_tidyup();

  if ((pid = fork()) == 0)
    {
    int fd = pfd[pipe_write];
    host_item *h;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    search_tidyup();

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

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

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

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

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

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

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

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

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

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

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

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

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

      if (testflag(addr, af_pipelining))
#ifdef EXPERIMENTAL_PIPE_CONNECT
	if (testflag(addr, af_early_pipe))
	  rmt_dlv_checked_write(fd, 'L', '2', NULL, 0);
	else
#endif
	  rmt_dlv_checked_write(fd, 'L', '1', NULL, 0);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  (void)close(pfd[pipe_write]);

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

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

  /* Fork failed; defer with error message */

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

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

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

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

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

  if (continue_transport) par_reduce(0, fallback);

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

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

  continue;

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

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

par_reduce(0, fallback);
return TRUE;
}

Project: exim

macros_trusted(BOOL opt_D_used)
{
#ifdef WHITELIST_D_MACROS
macro_item *m;
uschar *whitelisted, *end, *p, **whites, **w;
int white_count, i, n;
size_t len;
BOOL prev_char_item, found;
#endif

if (!opt_D_used)
  return TRUE;
#ifndef WHITELIST_D_MACROS
return FALSE;
#else

/* We only trust -D overrides for some invoking users:
root, the exim run-time user, the optional config owner user.
I don't know why config-owner would be needed, but since they can own the
config files anyway, there's no security risk to letting them override -D. */
if ( ! ((real_uid == root_uid)
     || (real_uid == exim_uid)
#ifdef CONFIGURE_OWNER
     || (real_uid == config_uid)
#endif
   ))
  {
  debug_printf("macros_trusted rejecting macros for uid %d\n", (int) real_uid);
  return FALSE;
  }

/* Get a list of macros which are whitelisted */
whitelisted = string_copy_malloc(US WHITELIST_D_MACROS);
prev_char_item = FALSE;
white_count = 0;
for (p = whitelisted; *p != '\0'; ++p)
  {
  if (*p == ':' || isspace(*p))
    {
    *p = '\0';
    if (prev_char_item)
      ++white_count;
    prev_char_item = FALSE;
    continue;
    }
  if (!prev_char_item)
    prev_char_item = TRUE;
  }
end = p;
if (prev_char_item)
  ++white_count;
if (!white_count)
  return FALSE;
whites = store_malloc(sizeof(uschar *) * (white_count+1));
for (p = whitelisted, i = 0; (p != end) && (i < white_count); ++p)
  {
  if (*p != '\0')
    {
    whites[i++] = p;
    if (i == white_count)
      break;
    while (*p != '\0' && p < end)
      ++p;
    }
  }
whites[i] = NULL;

/* The list of commandline macros should be very short.
Accept the N*M complexity. */
for (m = macros_user; m; m = m->next) if (m->command_line)
  {
  found = FALSE;
  for (w = whites; *w; ++w)
    if (Ustrcmp(*w, m->name) == 0)
      {
      found = TRUE;
      break;
      }
  if (!found)
    return FALSE;
  if (!m->replacement)
    continue;
  if ((len = m->replen) == 0)
    continue;
  n = pcre_exec(regex_whitelisted_macro, NULL, CS m->replacement, len,
   0, PCRE_EOPT, NULL, 0);
  if (n < 0)
    {
    if (n != PCRE_ERROR_NOMATCH)
      debug_printf("macros_trusted checking %s returned %d\n", m->name, n);
    return FALSE;
    }
  }
DEBUG(D_any) debug_printf("macros_trusted overridden to true by whitelisting\n");
return TRUE;
#endif
}

Project: exim

transport_write_reset(int options)
{
if (!(options & topt_continuation)) chunk_ptr = deliver_out_buffer;
nl_partial_match = -1;
nl_check_length = nl_escape_length = 0;
}

Project: exim

host_fake_gethostbyname(const uschar *name, int af, int *error_num)
{
#if HAVE_IPV6
int alen = (af == AF_INET)? sizeof(struct in_addr):sizeof(struct in6_addr);
#else
int alen = sizeof(struct in_addr);
#endif

int ipa;
const uschar *lname = name;
uschar *adds;
uschar **alist;
struct hostent *yield;
dns_answer dnsa;
dns_scan dnss;
dns_record *rr;

DEBUG(D_host_lookup)
  debug_printf("using host_fake_gethostbyname for %s (%s)\n", name,
    (af == AF_INET)? "IPv4" : "IPv6");

/* Handle unqualified "localhost" */

if (Ustrcmp(name, "localhost") == 0)
  lname = (af == AF_INET)? US"127.0.0.1" : US"::1";

/* Handle a literal IP address */

ipa = string_is_ip_address(lname, NULL);
if (ipa != 0)
  {
  if ((ipa == 4 && af == AF_INET) ||
      (ipa == 6 && af == AF_INET6))
    {
    int i, n;
    int x[4];
    yield = store_get(sizeof(struct hostent));
    alist = store_get(2 * sizeof(char *));
    adds  = store_get(alen);
    yield->h_name = CS name;
    yield->h_aliases = NULL;
    yield->h_addrtype = af;
    yield->h_length = alen;
    yield->h_addr_list = CSS alist;
    *alist++ = adds;
    n = host_aton(lname, x);
    for (i = 0; i < n; i++)
      {
      int y = x[i];
      *adds++ = (y >> 24) & 255;
      *adds++ = (y >> 16) & 255;
      *adds++ = (y >> 8) & 255;
      *adds++ = y & 255;
      }
    *alist = NULL;
    }

  /* Wrong kind of literal address */

  else
    {
    *error_num = HOST_NOT_FOUND;
    return NULL;
    }
  }

/* Handle a host name */

else
  {
  int type = (af == AF_INET)? T_A:T_AAAA;
  int rc = dns_lookup_timerwrap(&dnsa, lname, type, NULL);
  int count = 0;

  lookup_dnssec_authenticated = NULL;

  switch(rc)
    {
    case DNS_SUCCEED: break;
    case DNS_NOMATCH: *error_num = HOST_NOT_FOUND; return NULL;
    case DNS_NODATA:  *error_num = NO_DATA; return NULL;
    case DNS_AGAIN:   *error_num = TRY_AGAIN; return NULL;
    default:
    case DNS_FAIL:    *error_num = NO_RECOVERY; return NULL;
    }

  for (rr = dns_next_rr(&dnsa, &dnss, RESET_ANSWERS);
       rr;
       rr = dns_next_rr(&dnsa, &dnss, RESET_NEXT))
    if (rr->type == type)
      count++;

  yield = store_get(sizeof(struct hostent));
  alist = store_get((count + 1) * sizeof(char *));
  adds  = store_get(count *alen);

  yield->h_name = CS name;
  yield->h_aliases = NULL;
  yield->h_addrtype = af;
  yield->h_length = alen;
  yield->h_addr_list = CSS alist;

  for (rr = dns_next_rr(&dnsa, &dnss, RESET_ANSWERS);
       rr;
       rr = dns_next_rr(&dnsa, &dnss, RESET_NEXT))
    {
    int i, n;
    int x[4];
    dns_address *da;
    if (rr->type != type) continue;
    if (!(da = dns_address_from_rr(&dnsa, rr))) break;
    *alist++ = adds;
    n = host_aton(da->address, x);
    for (i = 0; i < n; i++)
      {
      int y = x[i];
      *adds++ = (y >> 24) & 255;
      *adds++ = (y >> 16) & 255;
      *adds++ = (y >> 8) & 255;
      *adds++ = y & 255;
      }
    }
  *alist = NULL;
  }

return yield;
}

Project: exim

host_scan_for_local_hosts(host_item *host, host_item **lastptr, BOOL *removed)
{
int yield = HOST_FIND_FAILED;
host_item *last = *lastptr;
host_item *prev = NULL;
host_item *h;

if (removed != NULL) *removed = FALSE;

if (local_interface_data == NULL) local_interface_data = host_find_interfaces();

for (h = host; h != last->next; h = h->next)
  {
  #ifndef STAND_ALONE
  if (hosts_treat_as_local != NULL)
    {
    int rc;
    const uschar *save = deliver_domain;
    deliver_domain = h->name;   /* set $domain */
    rc = match_isinlist(string_copylc(h->name), CUSS &hosts_treat_as_local, 0,
      &domainlist_anchor, NULL, MCL_DOMAIN, TRUE, NULL);
    deliver_domain = save;
    if (rc == OK) goto FOUND_LOCAL;
    }
  #endif

  /* It seems that on many operating systems, 0.0.0.0 is treated as a synonym
  for 127.0.0.1 and refers to the local host. We therefore force it always to
  be treated as local. */

  if (h->address != NULL)
    {
    ip_address_item *ip;
    if (Ustrcmp(h->address, "0.0.0.0") == 0) goto FOUND_LOCAL;
    for (ip = local_interface_data; ip != NULL; ip = ip->next)
      if (Ustrcmp(h->address, ip->address) == 0) goto FOUND_LOCAL;
    yield = HOST_FOUND;  /* At least one remote address has been found */
    }

  /* Update prev to point to the last host item before any that have
  the same MX value as the one we have just considered. */

  if (h->next == NULL || h->next->mx != h->mx) prev = h;
  }

return yield;  /* No local hosts found: return HOST_FOUND or HOST_FIND_FAILED */

/* A host whose IP address matches a local IP address, or whose name matches
something in hosts_treat_as_local has been found. */

FOUND_LOCAL:

if (prev == NULL)
  {
  HDEBUG(D_host_lookup) debug_printf((h->mx >= 0)?
    "local host has lowest MX\n" :
    "local host found for non-MX address\n");
  return HOST_FOUND_LOCAL;
  }

HDEBUG(D_host_lookup)
  {
  debug_printf("local host in host list - removed hosts:\n");
  for (h = prev->next; h != last->next; h = h->next)
    debug_printf("  %s %s %d\n", h->name, h->address, h->mx);
  }

if (removed != NULL) *removed = TRUE;
prev->next = last->next;
*lastptr = prev;
return yield;
}

Project: exim

smtp_setup_msg(void)
{
int done = 0;
BOOL toomany = FALSE;
BOOL discarded = FALSE;
BOOL last_was_rej_mail = FALSE;
BOOL last_was_rcpt = FALSE;
void *reset_point = store_get(0);

DEBUG(D_receive) debug_printf("smtp_setup_msg entered\n");

/* Reset for start of new message. We allow one RSET not to be counted as a
nonmail command, for those MTAs that insist on sending it between every
message. Ditto for EHLO/HELO and for STARTTLS, to allow for going in and out of
TLS between messages (an Exim client may do this if it has messages queued up
for the host). Note: we do NOT reset AUTH at this point. */

smtp_reset(reset_point);
message_ended = END_NOTSTARTED;

chunking_state = f.chunking_offered ? CHUNKING_OFFERED : CHUNKING_NOT_OFFERED;

cmd_list[CMD_LIST_RSET].is_mail_cmd = TRUE;
cmd_list[CMD_LIST_HELO].is_mail_cmd = TRUE;
cmd_list[CMD_LIST_EHLO].is_mail_cmd = TRUE;
#ifdef SUPPORT_TLS
cmd_list[CMD_LIST_STARTTLS].is_mail_cmd = TRUE;
#endif

/* Set the local signal handler for SIGTERM - it tries to end off tidily */

had_command_sigterm = 0;
os_non_restarting_signal(SIGTERM, command_sigterm_handler);

/* Batched SMTP is handled in a different function. */

if (smtp_batched_input) return smtp_setup_batch_msg();

/* 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)
  {
  const uschar **argv;
  uschar *etrn_command;
  uschar *etrn_serialize_key;
  uschar *errmess;
  uschar *log_msg, *smtp_code;
  uschar *user_msg = NULL;
  uschar *recipient = NULL;
  uschar *hello = NULL;
  uschar *s, *ss;
  BOOL was_rej_mail = FALSE;
  BOOL was_rcpt = FALSE;
  void (*oldsignal)(int);
  pid_t pid;
  int start, end, sender_domain, recipient_domain;
  int rc;
  int c;
  auth_instance *au;
  uschar *orcpt = NULL;
  int dsn_flags;
  gstring * g;

#ifdef AUTH_TLS
  /* Check once per STARTTLS or SSL-on-connect for a TLS AUTH */
  if (  tls_in.active.sock >= 0
     && tls_in.peercert
     && tls_in.certificate_verified
     && cmd_list[CMD_LIST_TLS_AUTH].is_mail_cmd
     )
    {
    cmd_list[CMD_LIST_TLS_AUTH].is_mail_cmd = FALSE;

    for (au = auths; au; au = au->next)
      if (strcmpic(US"tls", au->driver_name) == 0)
	{
	if (  acl_smtp_auth
	   && (rc = acl_check(ACL_WHERE_AUTH, NULL, acl_smtp_auth,
		      &user_msg, &log_msg)) != OK
	   )
	  done = smtp_handle_acl_fail(ACL_WHERE_AUTH, rc, user_msg, log_msg);
	else
	  {
	  smtp_cmd_data = NULL;

	  if (smtp_in_auth(au, &s, &ss) == OK)
	    { DEBUG(D_auth) debug_printf("tls auth succeeded\n"); }
	  else
	    { DEBUG(D_auth) debug_printf("tls auth not succeeded\n"); }
	  }
	break;
	}
    }
#endif

#ifdef TCP_QUICKACK
  if (smtp_in)		/* Avoid pure-ACKs while in cmd pingpong phase */
    (void) setsockopt(fileno(smtp_in), IPPROTO_TCP, TCP_QUICKACK,
	    US &off, sizeof(off));
#endif

  switch(smtp_read_command(
#ifdef EXPERIMENTAL_PIPE_CONNECT
	  !fl.pipe_connect_acceptable,
#else
	  TRUE,
#endif
	  GETC_BUFFER_UNLIMITED))
    {
    /* The AUTH command is not permitted to occur inside a transaction, and may
    occur successfully only once per connection. Actually, that isn't quite
    true. When TLS is started, all previous information about a connection must
    be discarded, so a new AUTH is permitted at that time.

    AUTH may only be used when it has been advertised. However, it seems that
    there are clients that send AUTH when it hasn't been advertised, some of
    them even doing this after HELO. And there are MTAs that accept this. Sigh.
    So there's a get-out that allows this to happen.

    AUTH is initially labelled as a "nonmail command" so that one occurrence
    doesn't get counted. We change the label here so that multiple failing
    AUTHS will eventually hit the nonmail threshold. */

    case AUTH_CMD:
      HAD(SCH_AUTH);
      authentication_failed = TRUE;
      cmd_list[CMD_LIST_AUTH].is_mail_cmd = FALSE;

      if (!fl.auth_advertised && !f.allow_auth_unadvertised)
	{
	done = synprot_error(L_smtp_protocol_error, 503, NULL,
	  US"AUTH command used when not advertised");
	break;
	}
      if (sender_host_authenticated)
	{
	done = synprot_error(L_smtp_protocol_error, 503, NULL,
	  US"already authenticated");
	break;
	}
      if (sender_address)
	{
	done = synprot_error(L_smtp_protocol_error, 503, NULL,
	  US"not permitted in mail transaction");
	break;
	}

      /* Check the ACL */

      if (  acl_smtp_auth
	 && (rc = acl_check(ACL_WHERE_AUTH, NULL, acl_smtp_auth,
		    &user_msg, &log_msg)) != OK
	 )
	{
	done = smtp_handle_acl_fail(ACL_WHERE_AUTH, rc, user_msg, log_msg);
	break;
	}

      /* Find the name of the requested authentication mechanism. */

      s = smtp_cmd_data;
      while ((c = *smtp_cmd_data) != 0 && !isspace(c))
	{
	if (!isalnum(c) && c != '-' && c != '_')
	  {
	  done = synprot_error(L_smtp_syntax_error, 501, NULL,
	    US"invalid character in authentication mechanism name");
	  goto COMMAND_LOOP;
	  }
	smtp_cmd_data++;
	}

      /* If not at the end of the line, we must be at white space. Terminate the
      name and move the pointer on to any data that may be present. */

      if (*smtp_cmd_data != 0)
	{
	*smtp_cmd_data++ = 0;
	while (isspace(*smtp_cmd_data)) smtp_cmd_data++;
	}

      /* Search for an authentication mechanism which is configured for use
      as a server and which has been advertised (unless, sigh, allow_auth_
      unadvertised is set). */

      for (au = auths; au; au = au->next)
	if (strcmpic(s, au->public_name) == 0 && au->server &&
	    (au->advertised || f.allow_auth_unadvertised))
	  break;

      if (au)
	{
	c = smtp_in_auth(au, &s, &ss);

	smtp_printf("%s\r\n", FALSE, s);
	if (c != OK)
	  log_write(0, LOG_MAIN|LOG_REJECT, "%s authenticator failed for %s: %s",
	    au->name, host_and_ident(FALSE), ss);
	}
      else
	done = synprot_error(L_smtp_protocol_error, 504, NULL,
	  string_sprintf("%s authentication mechanism not supported", s));

      break;  /* AUTH_CMD */

    /* The HELO/EHLO commands are permitted to appear in the middle of a
    session as well as at the beginning. They have the effect of a reset in
    addition to their other functions. Their absence at the start cannot be
    taken to be an error.

    RFC 2821 says:

      If the EHLO command is not acceptable to the SMTP server, 501, 500,
      or 502 failure replies MUST be returned as appropriate.  The SMTP
      server MUST stay in the same state after transmitting these replies
      that it was in before the EHLO was received.

    Therefore, we do not do the reset until after checking the command for
    acceptability. This change was made for Exim release 4.11. Previously
    it did the reset first. */

    case HELO_CMD:
      HAD(SCH_HELO);
      hello = US"HELO";
      fl.esmtp = FALSE;
      goto HELO_EHLO;

    case EHLO_CMD:
      HAD(SCH_EHLO);
      hello = US"EHLO";
      fl.esmtp = TRUE;

    HELO_EHLO:      /* Common code for HELO and EHLO */
      cmd_list[CMD_LIST_HELO].is_mail_cmd = FALSE;
      cmd_list[CMD_LIST_EHLO].is_mail_cmd = FALSE;

      /* Reject the HELO if its argument was invalid or non-existent. A
      successful check causes the argument to be saved in malloc store. */

      if (!check_helo(smtp_cmd_data))
	{
	smtp_printf("501 Syntactically invalid %s argument(s)\r\n", FALSE, hello);

	log_write(0, LOG_MAIN|LOG_REJECT, "rejected %s from %s: syntactically "
	  "invalid argument(s): %s", hello, host_and_ident(FALSE),
	  *smtp_cmd_argument == 0 ? US"(no argument given)" :
			     string_printing(smtp_cmd_argument));

	if (++synprot_error_count > smtp_max_synprot_errors)
	  {
	  log_write(0, LOG_MAIN|LOG_REJECT, "SMTP call from %s dropped: too many "
	    "syntax or protocol errors (last command was \"%s\")",
	    host_and_ident(FALSE), string_printing(smtp_cmd_buffer));
	  done = 1;
	  }

	break;
	}

      /* If sender_host_unknown is true, we have got here via the -bs interface,
      not called from inetd. Otherwise, we are running an IP connection and the
      host address will be set. If the helo name is the primary name of this
      host and we haven't done a reverse lookup, force one now. If helo_required
      is set, ensure that the HELO name matches the actual host. If helo_verify
      is set, do the same check, but softly. */

      if (!f.sender_host_unknown)
	{
	BOOL old_helo_verified = f.helo_verified;
	uschar *p = smtp_cmd_data;

	while (*p != 0 && !isspace(*p)) { *p = tolower(*p); p++; }
	*p = 0;

	/* Force a reverse lookup if HELO quoted something in helo_lookup_domains
	because otherwise the log can be confusing. */

	if (  !sender_host_name
	   && (deliver_domain = sender_helo_name,  /* set $domain */
	       match_isinlist(sender_helo_name, CUSS &helo_lookup_domains, 0,
		&domainlist_anchor, NULL, MCL_DOMAIN, TRUE, NULL)) == OK)
	  (void)host_name_lookup();

	/* Rebuild the fullhost info to include the HELO name (and the real name
	if it was looked up.) */

	host_build_sender_fullhost();  /* Rebuild */
	set_process_info("handling%s incoming connection from %s",
	  tls_in.active.sock >= 0 ? " TLS" : "", host_and_ident(FALSE));

	/* Verify if configured. This doesn't give much security, but it does
	make some people happy to be able to do it. If helo_required is set,
	(host matches helo_verify_hosts) failure forces rejection. If helo_verify
	is set (host matches helo_try_verify_hosts), it does not. This is perhaps
	now obsolescent, since the verification can now be requested selectively
	at ACL time. */

	f.helo_verified = f.helo_verify_failed = sender_helo_dnssec = FALSE;
	if (fl.helo_required || fl.helo_verify)
	  {
	  BOOL tempfail = !smtp_verify_helo();
	  if (!f.helo_verified)
	    {
	    if (fl.helo_required)
	      {
	      smtp_printf("%d %s argument does not match calling host\r\n", FALSE,
		tempfail? 451 : 550, hello);
	      log_write(0, LOG_MAIN|LOG_REJECT, "%srejected \"%s %s\" from %s",
		tempfail? "temporarily " : "",
		hello, sender_helo_name, host_and_ident(FALSE));
	      f.helo_verified = old_helo_verified;
	      break;                   /* End of HELO/EHLO processing */
	      }
	    HDEBUG(D_all) debug_printf("%s verification failed but host is in "
	      "helo_try_verify_hosts\n", hello);
	    }
	  }
	}

#ifdef SUPPORT_SPF
      /* set up SPF context */
      spf_init(sender_helo_name, sender_host_address);
#endif

      /* Apply an ACL check if one is defined; afterwards, recheck
      synchronization in case the client started sending in a delay. */

      if (acl_smtp_helo)
	if ((rc = acl_check(ACL_WHERE_HELO, NULL, acl_smtp_helo,
		  &user_msg, &log_msg)) != OK)
	  {
	  done = smtp_handle_acl_fail(ACL_WHERE_HELO, rc, user_msg, log_msg);
	  if (sender_helo_name)
	    {
	    store_free(sender_helo_name);
	    sender_helo_name = NULL;
	    }
	  host_build_sender_fullhost();  /* Rebuild */
	  break;
	  }
#ifdef EXPERIMENTAL_PIPE_CONNECT
	else if (!fl.pipe_connect_acceptable && !check_sync())
#else
	else if (!check_sync())
#endif
	  goto SYNC_FAILURE;

      /* Generate an OK reply. The default string includes the ident if present,
      and also the IP address if present. Reflecting back the ident is intended
      as a deterrent to mail forgers. For maximum efficiency, and also because
      some broken systems expect each response to be in a single packet, arrange
      that the entire reply is sent in one write(). */

      fl.auth_advertised = FALSE;
      f.smtp_in_pipelining_advertised = FALSE;
#ifdef SUPPORT_TLS
      fl.tls_advertised = FALSE;
# ifdef EXPERIMENTAL_REQUIRETLS
      fl.requiretls_advertised = FALSE;
# endif
#endif
      fl.dsn_advertised = FALSE;
#ifdef SUPPORT_I18N
      fl.smtputf8_advertised = FALSE;
#endif

      smtp_code = US"250 ";        /* Default response code plus space*/
      if (!user_msg)
	{
	s = string_sprintf("%.3s %s Hello %s%s%s",
	  smtp_code,
	  smtp_active_hostname,
	  sender_ident ? sender_ident : US"",
	  sender_ident ? US" at " : US"",
	  sender_host_name ? sender_host_name : sender_helo_name);
	g = string_cat(NULL, s);

	if (sender_host_address)
	  {
	  g = string_catn(g, US" [", 2);
	  g = string_cat (g, sender_host_address);
	  g = string_catn(g, US"]", 1);
	  }
	}

      /* A user-supplied EHLO greeting may not contain more than one line. Note
      that the code returned by smtp_message_code() includes the terminating
      whitespace character. */

      else
	{
	char *ss;
	int codelen = 4;
	smtp_message_code(&smtp_code, &codelen, &user_msg, NULL, TRUE);
	s = string_sprintf("%.*s%s", codelen, smtp_code, user_msg);
	if ((ss = strpbrk(CS s, "\r\n")) != NULL)
	  {
	  log_write(0, LOG_MAIN|LOG_PANIC, "EHLO/HELO response must not contain "
	    "newlines: message truncated: %s", string_printing(s));
	  *ss = 0;
	  }
	g = string_cat(NULL, s);
	}

      g = string_catn(g, US"\r\n", 2);

      /* If we received EHLO, we must create a multiline response which includes
      the functions supported. */

      if (fl.esmtp)
	{
	g->s[3] = '-';

	/* I'm not entirely happy with this, as an MTA is supposed to check
	that it has enough room to accept a message of maximum size before
	it sends this. However, there seems little point in not sending it.
	The actual size check happens later at MAIL FROM time. By postponing it
	till then, VRFY and EXPN can be used after EHLO when space is short. */

	if (thismessage_size_limit > 0)
	  {
	  sprintf(CS big_buffer, "%.3s-SIZE %d\r\n", smtp_code,
	    thismessage_size_limit);
	  g = string_cat(g, big_buffer);
	  }
	else
	  {
	  g = string_catn(g, smtp_code, 3);
	  g = string_catn(g, US"-SIZE\r\n", 7);
	  }

	/* Exim does not do protocol conversion or data conversion. It is 8-bit
	clean; if it has an 8-bit character in its hand, it just sends it. It
	cannot therefore specify 8BITMIME and remain consistent with the RFCs.
	However, some users want this option simply in order to stop MUAs
	mangling messages that contain top-bit-set characters. It is therefore
	provided as an option. */

	if (accept_8bitmime)
	  {
	  g = string_catn(g, smtp_code, 3);
	  g = string_catn(g, US"-8BITMIME\r\n", 11);
	  }

	/* Advertise DSN support if configured to do so. */
	if (verify_check_host(&dsn_advertise_hosts) != FAIL)
	  {
	  g = string_catn(g, smtp_code, 3);
	  g = string_catn(g, US"-DSN\r\n", 6);
	  fl.dsn_advertised = TRUE;
	  }

	/* Advertise ETRN/VRFY/EXPN if there's are ACL checking whether a host is
	permitted to issue them; a check is made when any host actually tries. */

	if (acl_smtp_etrn)
	  {
	  g = string_catn(g, smtp_code, 3);
	  g = string_catn(g, US"-ETRN\r\n", 7);
	  }
	if (acl_smtp_vrfy)
	  {
	  g = string_catn(g, smtp_code, 3);
	  g = string_catn(g, US"-VRFY\r\n", 7);
	  }
	if (acl_smtp_expn)
	  {
	  g = string_catn(g, smtp_code, 3);
	  g = string_catn(g, US"-EXPN\r\n", 7);
	  }

	/* Exim is quite happy with pipelining, so let the other end know that
	it is safe to use it, unless advertising is disabled. */

	if (  f.pipelining_enable
	   && verify_check_host(&pipelining_advertise_hosts) == OK)
	  {
	  g = string_catn(g, smtp_code, 3);
	  g = string_catn(g, US"-PIPELINING\r\n", 13);
	  sync_cmd_limit = NON_SYNC_CMD_PIPELINING;
	  f.smtp_in_pipelining_advertised = TRUE;

#ifdef EXPERIMENTAL_PIPE_CONNECT
	  if (fl.pipe_connect_acceptable)
	    {
	    f.smtp_in_early_pipe_advertised = TRUE;
	    g = string_catn(g, smtp_code, 3);
	    g = string_catn(g, US"-" EARLY_PIPE_FEATURE_NAME "\r\n", EARLY_PIPE_FEATURE_LEN+3);
	    }
#endif
	  }


	/* If any server authentication mechanisms are configured, advertise
	them if the current host is in auth_advertise_hosts. The problem with
	advertising always is that some clients then require users to
	authenticate (and aren't configurable otherwise) even though it may not
	be necessary (e.g. if the host is in host_accept_relay).

	RFC 2222 states that SASL mechanism names contain only upper case
	letters, so output the names in upper case, though we actually recognize
	them in either case in the AUTH command. */

	if (  auths
#ifdef AUTH_TLS
	   && !sender_host_authenticated
#endif
	   && verify_check_host(&auth_advertise_hosts) == OK
	   )
	  {
	  auth_instance *au;
	  BOOL first = TRUE;
	  for (au = auths; au; au = au->next)
	    {
	    au->advertised = FALSE;
	    if (au->server)
	      {
	      DEBUG(D_auth+D_expand) debug_printf_indent(
		"Evaluating advertise_condition for %s athenticator\n",
		au->public_name);
	      if (  !au->advertise_condition
		 || expand_check_condition(au->advertise_condition, au->name,
			US"authenticator")
		 )
		{
		int saveptr;
		if (first)
		  {
		  g = string_catn(g, smtp_code, 3);
		  g = string_catn(g, US"-AUTH", 5);
		  first = FALSE;
		  fl.auth_advertised = TRUE;
		  }
		saveptr = g->ptr;
		g = string_catn(g, US" ", 1);
		g = string_cat (g, au->public_name);
		while (++saveptr < g->ptr) g->s[saveptr] = toupper(g->s[saveptr]);
		au->advertised = TRUE;
		}
	      }
	    }

	  if (!first) g = string_catn(g, US"\r\n", 2);
	  }

	/* RFC 3030 CHUNKING */

	if (verify_check_host(&chunking_advertise_hosts) != FAIL)
	  {
	  g = string_catn(g, smtp_code, 3);
	  g = string_catn(g, US"-CHUNKING\r\n", 11);
	  f.chunking_offered = TRUE;
	  chunking_state = CHUNKING_OFFERED;
	  }

	/* Advertise TLS (Transport Level Security) aka SSL (Secure Socket Layer)
	if it has been included in the binary, and the host matches
	tls_advertise_hosts. We must *not* advertise if we are already in a
	secure connection. */

#ifdef SUPPORT_TLS
	if (tls_in.active.sock < 0 &&
	    verify_check_host(&tls_advertise_hosts) != FAIL)
	  {
	  g = string_catn(g, smtp_code, 3);
	  g = string_catn(g, US"-STARTTLS\r\n", 11);
	  fl.tls_advertised = TRUE;
	  }

# ifdef EXPERIMENTAL_REQUIRETLS
	/* Advertise REQUIRETLS only once we are in a secure connection */
	if (  tls_in.active.sock >= 0
	   && verify_check_host(&tls_advertise_requiretls) != FAIL)
	  {
	  g = string_catn(g, smtp_code, 3);
	  g = string_catn(g, US"-REQUIRETLS\r\n", 13);
	  fl.requiretls_advertised = TRUE;
	  }
# endif
#endif

#ifndef DISABLE_PRDR
	/* Per Recipient Data Response, draft by Eric A. Hall extending RFC */
	if (prdr_enable)
	  {
	  g = string_catn(g, smtp_code, 3);
	  g = string_catn(g, US"-PRDR\r\n", 7);
	  }
#endif

#ifdef SUPPORT_I18N
	if (  accept_8bitmime
	   && verify_check_host(&smtputf8_advertise_hosts) != FAIL)
	  {
	  g = string_catn(g, smtp_code, 3);
	  g = string_catn(g, US"-SMTPUTF8\r\n", 11);
	  fl.smtputf8_advertised = TRUE;
	  }
#endif

	/* Finish off the multiline reply with one that is always available. */

	g = string_catn(g, smtp_code, 3);
	g = string_catn(g, US" HELP\r\n", 7);
	}

      /* Terminate the string (for debug), write it, and note that HELO/EHLO
      has been seen. */

#ifdef SUPPORT_TLS
      if (tls_in.active.sock >= 0)
	(void)tls_write(NULL, g->s, g->ptr,
# ifdef EXPERIMENTAL_PIPE_CONNECT
			fl.pipe_connect_acceptable && pipeline_connect_sends());
# else
			FALSE);
# endif
      else
#endif

	{
	int i = fwrite(g->s, 1, g->ptr, smtp_out); i = i; /* compiler quietening */
	}
      DEBUG(D_receive)
	{
	uschar *cr;

	(void) string_from_gstring(g);
	while ((cr = Ustrchr(g->s, '\r')) != NULL)   /* lose CRs */
	  memmove(cr, cr + 1, (g->ptr--) - (cr - g->s));
	debug_printf("SMTP>> %s", g->s);
	}
      fl.helo_seen = TRUE;

      /* Reset the protocol and the state, abandoning any previous message. */
      received_protocol =
	(sender_host_address ? protocols : protocols_local)
	  [ (fl.esmtp
	    ? pextend + (sender_host_authenticated ? pauthed : 0)
	    : pnormal)
	  + (tls_in.active.sock >= 0 ? pcrpted : 0)
	  ];
      cancel_cutthrough_connection(TRUE, US"sent EHLO response");
      smtp_reset(reset_point);
      toomany = FALSE;
      break;   /* HELO/EHLO */


    /* The MAIL 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:
      HAD(SCH_MAIL);
      smtp_mailcmd_count++;              /* Count for limit and ratelimit */
      was_rej_mail = TRUE;               /* Reset if accepted */
      env_mail_type_t * mail_args;       /* Sanity check & validate args */

      if (fl.helo_required && !fl.helo_seen)
	{
	smtp_printf("503 HELO or EHLO required\r\n", FALSE);
	log_write(0, LOG_MAIN|LOG_REJECT, "rejected MAIL from %s: no "
	  "HELO/EHLO given", host_and_ident(FALSE));
	break;
	}

      if (sender_address)
	{
	done = synprot_error(L_smtp_protocol_error, 503, NULL,
	  US"sender already given");
	break;
	}

      if (!*smtp_cmd_data)
	{
	done = synprot_error(L_smtp_protocol_error, 501, NULL,
	  US"MAIL must have an address operand");
	break;
	}

      /* Check to see if the limit for messages per connection would be
      exceeded by accepting further messages. */

      if (smtp_accept_max_per_connection > 0 &&
	  smtp_mailcmd_count > smtp_accept_max_per_connection)
	{
	smtp_printf("421 too many messages in this connection\r\n", FALSE);
	log_write(0, LOG_MAIN|LOG_REJECT, "rejected MAIL command %s: too many "
	  "messages in one connection", host_and_ident(TRUE));
	break;
	}

      /* Reset for start of message - even if this is going to fail, we
      obviously need to throw away any previous data. */

      cancel_cutthrough_connection(TRUE, US"MAIL received");
      smtp_reset(reset_point);
      toomany = FALSE;
      sender_data = recipient_data = NULL;

      /* Loop, checking for ESMTP additions to the MAIL FROM command. */

      if (fl.esmtp) for(;;)
	{
	uschar *name, *value, *end;
	unsigned long int size;
	BOOL arg_error = FALSE;

	if (!extract_option(&name, &value)) break;

	for (mail_args = env_mail_type_list;
	     mail_args->value != ENV_MAIL_OPT_NULL;
	     mail_args++
	    )
	  if (strcmpic(name, mail_args->name) == 0)
	    break;
	if (mail_args->need_value && strcmpic(value, US"") == 0)
	  break;

	switch(mail_args->value)
	  {
	  /* Handle SIZE= by reading the value. We don't do the check till later,
	  in order to be able to log the sender address on failure. */
	  case ENV_MAIL_OPT_SIZE:
	    if (((size = Ustrtoul(value, &end, 10)), *end == 0))
	      {
	      if ((size == ULONG_MAX && errno == ERANGE) || size > INT_MAX)
		size = INT_MAX;
	      message_size = (int)size;
	      }
	    else
	      arg_error = TRUE;
	    break;

	  /* If this session was initiated with EHLO and accept_8bitmime is set,
	  Exim will have indicated that it supports the BODY=8BITMIME option. In
	  fact, it does not support this according to the RFCs, in that it does not
	  take any special action for forwarding messages containing 8-bit
	  characters. That is why accept_8bitmime is not the default setting, but
	  some sites want the action that is provided. We recognize both "8BITMIME"
	  and "7BIT" as body types, but take no action. */
	  case ENV_MAIL_OPT_BODY:
	    if (accept_8bitmime) {
	      if (strcmpic(value, US"8BITMIME") == 0)
		body_8bitmime = 8;
	      else if (strcmpic(value, US"7BIT") == 0)
		body_8bitmime = 7;
	      else
		{
		body_8bitmime = 0;
		done = synprot_error(L_smtp_syntax_error, 501, NULL,
		  US"invalid data for BODY");
		goto COMMAND_LOOP;
		}
	      DEBUG(D_receive) debug_printf("8BITMIME: %d\n", body_8bitmime);
	      break;
	    }
	    arg_error = TRUE;
	    break;

	  /* Handle the two DSN options, but only if configured to do so (which
	  will have caused "DSN" to be given in the EHLO response). The code itself
	  is included only if configured in at build time. */

	  case ENV_MAIL_OPT_RET:
	    if (fl.dsn_advertised)
	      {
	      /* Check if RET has already been set */
	      if (dsn_ret > 0)
		{
		done = synprot_error(L_smtp_syntax_error, 501, NULL,
		  US"RET can be specified once only");
		goto COMMAND_LOOP;
		}
	      dsn_ret = strcmpic(value, US"HDRS") == 0
		? dsn_ret_hdrs
		: strcmpic(value, US"FULL") == 0
		? dsn_ret_full
		: 0;
	      DEBUG(D_receive) debug_printf("DSN_RET: %d\n", dsn_ret);
	      /* Check for invalid invalid value, and exit with error */
	      if (dsn_ret == 0)
		{
		done = synprot_error(L_smtp_syntax_error, 501, NULL,
		  US"Value for RET is invalid");
		goto COMMAND_LOOP;
		}
	      }
	    break;
	  case ENV_MAIL_OPT_ENVID:
	    if (fl.dsn_advertised)
	      {
	      /* Check if the dsn envid has been already set */
	      if (dsn_envid)
		{
		done = synprot_error(L_smtp_syntax_error, 501, NULL,
		  US"ENVID can be specified once only");
		goto COMMAND_LOOP;
		}
	      dsn_envid = string_copy(value);
	      DEBUG(D_receive) debug_printf("DSN_ENVID: %s\n", dsn_envid);
	      }
	    break;

	  /* Handle the AUTH extension. If the value given is not "<>" and either
	  the ACL says "yes" or there is no ACL but the sending host is
	  authenticated, we set it up as the authenticated sender. However, if the
	  authenticator set a condition to be tested, we ignore AUTH on MAIL unless
	  the condition is met. The value of AUTH is an xtext, which means that +,
	  = and cntrl chars are coded in hex; however "<>" is unaffected by this
	  coding. */
	  case ENV_MAIL_OPT_AUTH:
	    if (Ustrcmp(value, "<>") != 0)
	      {
	      int rc;
	      uschar *ignore_msg;

	      if (auth_xtextdecode(value, &authenticated_sender) < 0)
		{
		/* Put back terminator overrides for error message */
		value[-1] = '=';
		name[-1] = ' ';
		done = synprot_error(L_smtp_syntax_error, 501, NULL,
		  US"invalid data for AUTH");
		goto COMMAND_LOOP;
		}
	      if (!acl_smtp_mailauth)
		{
		ignore_msg = US"client not authenticated";
		rc = sender_host_authenticated ? OK : FAIL;
		}
	      else
		{
		ignore_msg = US"rejected by ACL";
		rc = acl_check(ACL_WHERE_MAILAUTH, NULL, acl_smtp_mailauth,
		  &user_msg, &log_msg);
		}

	      switch (rc)
		{
		case OK:
		  if (authenticated_by == NULL ||
		      authenticated_by->mail_auth_condition == NULL ||
		      expand_check_condition(authenticated_by->mail_auth_condition,
			  authenticated_by->name, US"authenticator"))
		    break;     /* Accept the AUTH */

		  ignore_msg = US"server_mail_auth_condition failed";
		  if (authenticated_id != NULL)
		    ignore_msg = string_sprintf("%s: authenticated ID=\"%s\"",
		      ignore_msg, authenticated_id);

		/* Fall through */

		case FAIL:
		  authenticated_sender = NULL;
		  log_write(0, LOG_MAIN, "ignoring AUTH=%s from %s (%s)",
		    value, host_and_ident(TRUE), ignore_msg);
		  break;

		/* Should only get DEFER or ERROR here. Put back terminator
		overrides for error message */

		default:
		  value[-1] = '=';
		  name[-1] = ' ';
		  (void)smtp_handle_acl_fail(ACL_WHERE_MAILAUTH, rc, user_msg,
		    log_msg);
		  goto COMMAND_LOOP;
		}
	      }
	      break;

#ifndef DISABLE_PRDR
	  case ENV_MAIL_OPT_PRDR:
	    if (prdr_enable)
	      prdr_requested = TRUE;
	    break;
#endif

#ifdef SUPPORT_I18N
	  case ENV_MAIL_OPT_UTF8:
	    if (!fl.smtputf8_advertised)
	      {
	      done = synprot_error(L_smtp_syntax_error, 501, NULL,
		US"SMTPUTF8 used when not advertised");
	      goto COMMAND_LOOP;
	      }

	    DEBUG(D_receive) debug_printf("smtputf8 requested\n");
	    message_smtputf8 = allow_utf8_domains = TRUE;
	    if (Ustrncmp(received_protocol, US"utf8", 4) != 0)
	      {
	      int old_pool = store_pool;
	      store_pool = POOL_PERM;
	      received_protocol = string_sprintf("utf8%s", received_protocol);
	      store_pool = old_pool;
	      }
	    break;
#endif

#if defined(SUPPORT_TLS) && defined(EXPERIMENTAL_REQUIRETLS)
	  case ENV_MAIL_OPT_REQTLS:
	    {
	    uschar * r, * t;

	    if (!fl.requiretls_advertised)
	      {
	      done = synprot_error(L_smtp_syntax_error, 555, NULL,
		US"unadvertised MAIL option: REQUIRETLS");
	      goto COMMAND_LOOP;
	      }

	    DEBUG(D_receive) debug_printf("requiretls requested\n");
	    tls_requiretls = REQUIRETLS_MSG;

	    r = string_copy_malloc(received_protocol);
	    if ((t = Ustrrchr(r, 's'))) *t = 'S';
	    received_protocol = r;
	    }
	    break;
#endif

	  /* No valid option. Stick back the terminator characters and break
	  the loop.  Do the name-terminator second as extract_option sets
	  value==name when it found no equal-sign.
	  An error for a malformed address will occur. */
	  case ENV_MAIL_OPT_NULL:
	    value[-1] = '=';
	    name[-1] = ' ';
	    arg_error = TRUE;
	    break;

	  default:  assert(0);
	  }
	/* Break out of for loop if switch() had bad argument or
	   when start of the email address is reached */
	if (arg_error) break;
	}

#if defined(SUPPORT_TLS) && defined(EXPERIMENTAL_REQUIRETLS)
      if (tls_requiretls & REQUIRETLS_MSG)
	{
	/* Ensure headers-only bounces whether a RET option was given or not. */

	DEBUG(D_receive) if (dsn_ret == dsn_ret_full)
	  debug_printf("requiretls override: dsn_ret_full -> dsn_ret_hdrs\n");
	dsn_ret = dsn_ret_hdrs;
	}
#endif

      /* If we have passed the threshold for rate limiting, apply the current
      delay, and update it for next time, provided this is a limited host. */

      if (smtp_mailcmd_count > smtp_rlm_threshold &&
	  verify_check_host(&smtp_ratelimit_hosts) == OK)
	{
	DEBUG(D_receive) debug_printf("rate limit MAIL: delay %.3g sec\n",
	  smtp_delay_mail/1000.0);
	millisleep((int)smtp_delay_mail);
	smtp_delay_mail *= smtp_rlm_factor;
	if (smtp_delay_mail > (double)smtp_rlm_limit)
	  smtp_delay_mail = (double)smtp_rlm_limit;
	}

      /* Now extract the address, first applying any SMTP-time rewriting. The
      TRUE flag allows "<>" as a sender address. */

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

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

      if (!raw_sender)
	{
	done = synprot_error(L_smtp_syntax_error, 501, smtp_cmd_data, errmess);
	break;
	}

      sender_address = raw_sender;

      /* If there is a configured size limit for mail, check that this message
      doesn't exceed it. The check is postponed to this point so that the sender
      can be logged. */

      if (thismessage_size_limit > 0 && message_size > thismessage_size_limit)
	{
	smtp_printf("552 Message size exceeds maximum permitted\r\n", FALSE);
	log_write(L_size_reject,
	    LOG_MAIN|LOG_REJECT, "rejected MAIL FROM:<%s> %s: "
	    "message too big: size%s=%d max=%d",
	    sender_address,
	    host_and_ident(TRUE),
	    (message_size == INT_MAX)? ">" : "",
	    message_size,
	    thismessage_size_limit);
	sender_address = NULL;
	break;
	}

      /* Check there is enough space on the disk unless configured not to.
      When smtp_check_spool_space is set, the check is for thismessage_size_limit
      plus the current message - i.e. we accept the message only if it won't
      reduce the space below the threshold. Add 5000 to the size to allow for
      overheads such as the Received: line and storing of recipients, etc.
      By putting the check here, even when SIZE is not given, it allow VRFY
      and EXPN etc. to be used when space is short. */

      if (!receive_check_fs(
	   (smtp_check_spool_space && message_size >= 0)?
	      message_size + 5000 : 0))
	{
	smtp_printf("452 Space shortage, please try later\r\n", FALSE);
	sender_address = NULL;
	break;
	}

      /* If sender_address is unqualified, reject it, unless this is a locally
      generated message, or the sending host or net is permitted to send
      unqualified addresses - typically local machines behaving as MUAs -
      in which case just qualify the address. The flag is set above at the start
      of the SMTP connection. */

      if (!sender_domain && *sender_address)
	if (f.allow_unqualified_sender)
	  {
	  sender_domain = Ustrlen(sender_address) + 1;
	  sender_address = rewrite_address_qualify(sender_address, FALSE);
	  DEBUG(D_receive) debug_printf("unqualified address %s accepted\n",
	    raw_sender);
	  }
	else
	  {
	  smtp_printf("501 %s: sender address must contain a domain\r\n", FALSE,
	    smtp_cmd_data);
	  log_write(L_smtp_syntax_error,
	    LOG_MAIN|LOG_REJECT,
	    "unqualified sender rejected: <%s> %s%s",
	    raw_sender,
	    host_and_ident(TRUE),
	    host_lookup_msg);
	  sender_address = NULL;
	  break;
	  }

      /* Apply an ACL check if one is defined, before responding. Afterwards,
      when pipelining is not advertised, do another sync check in case the ACL
      delayed and the client started sending in the meantime. */

      if (acl_smtp_mail)
	{
	rc = acl_check(ACL_WHERE_MAIL, NULL, acl_smtp_mail, &user_msg, &log_msg);
	if (rc == OK && !f.smtp_in_pipelining_advertised && !check_sync())
	  goto SYNC_FAILURE;
	}
      else
	rc = OK;

      if (rc == OK || rc == DISCARD)
	{
	BOOL more = pipeline_response();

	if (!user_msg)
	  smtp_printf("%s%s%s", more, US"250 OK",
		    #ifndef DISABLE_PRDR
		      prdr_requested ? US", PRDR Requested" : US"",
		    #else
		      US"",
		    #endif
		      US"\r\n");
	else
	  {
	#ifndef DISABLE_PRDR
	  if (prdr_requested)
	     user_msg = string_sprintf("%s%s", user_msg, US", PRDR Requested");
	#endif
	  smtp_user_msg(US"250", user_msg);
	  }
	smtp_delay_rcpt = smtp_rlr_base;
	f.recipients_discarded = (rc == DISCARD);
	was_rej_mail = FALSE;
	}
      else
	{
	done = smtp_handle_acl_fail(ACL_WHERE_MAIL, rc, user_msg, log_msg);
	sender_address = NULL;
	}
      break;


    /* The RCPT command requires an address as an operand. There may be any
    number of RCPT commands, specifying multiple recipients. We build them all
    into a data structure. The start/end values given by parse_extract_address
    are not used, as we keep only the extracted address. */

    case RCPT_CMD:
      HAD(SCH_RCPT);
      rcpt_count++;
      was_rcpt = fl.rcpt_in_progress = TRUE;

      /* There must be a sender address; if the sender was rejected and
      pipelining was advertised, we assume the client was pipelining, and do not
      count this as a protocol error. Reset was_rej_mail so that further RCPTs
      get the same treatment. */

      if (sender_address == NULL)
	{
	if (f.smtp_in_pipelining_advertised && last_was_rej_mail)
	  {
	  smtp_printf("503 sender not yet given\r\n", FALSE);
	  was_rej_mail = TRUE;
	  }
	else
	  {
	  done = synprot_error(L_smtp_protocol_error, 503, NULL,
	    US"sender not yet given");
	  was_rcpt = FALSE;             /* Not a valid RCPT */
	  }
	rcpt_fail_count++;
	break;
	}

      /* Check for an operand */

      if (smtp_cmd_data[0] == 0)
	{
	done = synprot_error(L_smtp_syntax_error, 501, NULL,
	  US"RCPT must have an address operand");
	rcpt_fail_count++;
	break;
	}

      /* Set the DSN flags orcpt and dsn_flags from the session*/
      orcpt = NULL;
      dsn_flags = 0;

      if (fl.esmtp) for(;;)
	{
	uschar *name, *value;

	if (!extract_option(&name, &value))
	  break;

	if (fl.dsn_advertised && strcmpic(name, US"ORCPT") == 0)
	  {
	  /* Check whether orcpt has been already set */
	  if (orcpt)
	    {
	    done = synprot_error(L_smtp_syntax_error, 501, NULL,
	      US"ORCPT can be specified once only");
	    goto COMMAND_LOOP;
	    }
	  orcpt = string_copy(value);
	  DEBUG(D_receive) debug_printf("DSN orcpt: %s\n", orcpt);
	  }

	else if (fl.dsn_advertised && strcmpic(name, US"NOTIFY") == 0)
	  {
	  /* Check if the notify flags have been already set */
	  if (dsn_flags > 0)
	    {
	    done = synprot_error(L_smtp_syntax_error, 501, NULL,
		US"NOTIFY can be specified once only");
	    goto COMMAND_LOOP;
	    }
	  if (strcmpic(value, US"NEVER") == 0)
	    dsn_flags |= rf_notify_never;
	  else
	    {
	    uschar *p = value;
	    while (*p != 0)
	      {
	      uschar *pp = p;
	      while (*pp != 0 && *pp != ',') pp++;
	      if (*pp == ',') *pp++ = 0;
	      if (strcmpic(p, US"SUCCESS") == 0)
		{
		DEBUG(D_receive) debug_printf("DSN: Setting notify success\n");
		dsn_flags |= rf_notify_success;
		}
	      else if (strcmpic(p, US"FAILURE") == 0)
		{
		DEBUG(D_receive) debug_printf("DSN: Setting notify failure\n");
		dsn_flags |= rf_notify_failure;
		}
	      else if (strcmpic(p, US"DELAY") == 0)
		{
		DEBUG(D_receive) debug_printf("DSN: Setting notify delay\n");
		dsn_flags |= rf_notify_delay;
		}
	      else
		{
		/* Catch any strange values */
		done = synprot_error(L_smtp_syntax_error, 501, NULL,
		  US"Invalid value for NOTIFY parameter");
		goto COMMAND_LOOP;
		}
	      p = pp;
	      }
	      DEBUG(D_receive) debug_printf("DSN Flags: %x\n", dsn_flags);
	    }
	  }

	/* Unknown option. Stick back the terminator characters and break
	the loop. An error for a malformed address will occur. */

	else
	  {
	  DEBUG(D_receive) debug_printf("Invalid RCPT option: %s : %s\n", name, value);
	  name[-1] = ' ';
	  value[-1] = '=';
	  break;
	  }
	}

      /* Apply SMTP rewriting then extract the working 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;

      if (!(recipient = parse_extract_address(recipient, &errmess, &start, &end,
	&recipient_domain, FALSE)))
	{
	done = synprot_error(L_smtp_syntax_error, 501, smtp_cmd_data, errmess);
	rcpt_fail_count++;
	break;
	}

      /* If the recipient address is unqualified, reject it, unless this is a
      locally generated message. However, unqualified addresses are permitted
      from a configured list of hosts and nets - typically when behaving as
      MUAs rather than MTAs. Sad that SMTP is used for both types of traffic,
      really. The flag is set at the start of the SMTP connection.

      RFC 1123 talks about supporting "the reserved mailbox postmaster"; I always
      assumed this meant "reserved local part", but the revision of RFC 821 and
      friends now makes it absolutely clear that it means *mailbox*. Consequently
      we must always qualify this address, regardless. */

      if (!recipient_domain)
	if (!(recipient_domain = qualify_recipient(&recipient, smtp_cmd_data,
				    US"recipient")))
	  {
	  rcpt_fail_count++;
	  break;
	  }

      /* Check maximum allowed */

      if (rcpt_count > recipients_max && recipients_max > 0)
	{
	if (recipients_max_reject)
	  {
	  rcpt_fail_count++;
	  smtp_printf("552 too many recipients\r\n", FALSE);
	  if (!toomany)
	    log_write(0, LOG_MAIN|LOG_REJECT, "too many recipients: message "
	      "rejected: sender=<%s> %s", sender_address, host_and_ident(TRUE));
	  }
	else
	  {
	  rcpt_defer_count++;
	  smtp_printf("452 too many recipients\r\n", FALSE);
	  if (!toomany)
	    log_write(0, LOG_MAIN|LOG_REJECT, "too many recipients: excess "
	      "temporarily rejected: sender=<%s> %s", sender_address,
	      host_and_ident(TRUE));
	  }

	toomany = TRUE;
	break;
	}

      /* If we have passed the threshold for rate limiting, apply the current
      delay, and update it for next time, provided this is a limited host. */

      if (rcpt_count > smtp_rlr_threshold &&
	  verify_check_host(&smtp_ratelimit_hosts) == OK)
	{
	DEBUG(D_receive) debug_printf("rate limit RCPT: delay %.3g sec\n",
	  smtp_delay_rcpt/1000.0);
	millisleep((int)smtp_delay_rcpt);
	smtp_delay_rcpt *= smtp_rlr_factor;
	if (smtp_delay_rcpt > (double)smtp_rlr_limit)
	  smtp_delay_rcpt = (double)smtp_rlr_limit;
	}

      /* If the MAIL ACL discarded all the recipients, we bypass ACL checking
      for them. Otherwise, check the access control list for this recipient. As
      there may be a delay in this, re-check for a synchronization error
      afterwards, unless pipelining was advertised. */

      if (f.recipients_discarded)
	rc = DISCARD;
      else
	if (  (rc = acl_check(ACL_WHERE_RCPT, recipient, acl_smtp_rcpt, &user_msg,
		      &log_msg)) == OK
	   && !f.smtp_in_pipelining_advertised && !check_sync())
	  goto SYNC_FAILURE;

      /* The ACL was happy */

      if (rc == OK)
	{
	BOOL more = pipeline_response();

	if (user_msg)
	  smtp_user_msg(US"250", user_msg);
	else
	  smtp_printf("250 Accepted\r\n", more);
	receive_add_recipient(recipient, -1);

	/* Set the dsn flags in the recipients_list */
	recipients_list[recipients_count-1].orcpt = orcpt;
	recipients_list[recipients_count-1].dsn_flags = dsn_flags;

	DEBUG(D_receive) debug_printf("DSN: orcpt: %s  flags: %d\n",
	  recipients_list[recipients_count-1].orcpt,
	  recipients_list[recipients_count-1].dsn_flags);
	}

      /* The recipient was discarded */

      else if (rc == DISCARD)
	{
	if (user_msg)
	  smtp_user_msg(US"250", user_msg);
	else
	  smtp_printf("250 Accepted\r\n", FALSE);
	rcpt_fail_count++;
	discarded = TRUE;
	log_write(0, LOG_MAIN|LOG_REJECT, "%s F=<%s> RCPT %s: "
	  "discarded by %s ACL%s%s", host_and_ident(TRUE),
	  sender_address_unrewritten? sender_address_unrewritten : sender_address,
	  smtp_cmd_argument, f.recipients_discarded? "MAIL" : "RCPT",
	  log_msg ? US": " : US"", log_msg ? log_msg : US"");
	}

      /* Either the ACL failed the address, or it was deferred. */

      else
	{
	if (rc == FAIL) rcpt_fail_count++; else rcpt_defer_count++;
	done = smtp_handle_acl_fail(ACL_WHERE_RCPT, rc, user_msg, log_msg);
	}
      break;


    /* The DATA command is legal only if it follows successful MAIL FROM
    and RCPT TO commands. However, if pipelining is advertised, a bad DATA is
    not counted as a protocol error if it follows RCPT (which must have been
    rejected if there are no recipients.) This function is complete when a
    valid DATA command is encountered.

    Note concerning the code used: RFC 2821 says this:

     -  If there was no MAIL, or no RCPT, command, or all such commands
        were rejected, the server MAY return a "command out of sequence"
        (503) or "no valid recipients" (554) reply in response to the
        DATA command.

    The example in the pipelining RFC 2920 uses 554, but I use 503 here
    because it is the same whether pipelining is in use or not.

    If all the RCPT commands that precede DATA provoked the same error message
    (often indicating some kind of system error), it is helpful to include it
    with the DATA rejection (an idea suggested by Tony Finch). */

    case BDAT_CMD:
      {
      int n;

      HAD(SCH_BDAT);
      if (chunking_state != CHUNKING_OFFERED)
	{
	done = synprot_error(L_smtp_protocol_error, 503, NULL,
	  US"BDAT command used when CHUNKING not advertised");
	break;
	}

      /* grab size, endmarker */

      if (sscanf(CS smtp_cmd_data, "%u %n", &chunking_datasize, &n) < 1)
	{
	done = synprot_error(L_smtp_protocol_error, 501, NULL,
	  US"missing size for BDAT command");
	break;
	}
      chunking_state = strcmpic(smtp_cmd_data+n, US"LAST") == 0
	? CHUNKING_LAST : CHUNKING_ACTIVE;
      chunking_data_left = chunking_datasize;
      DEBUG(D_receive) debug_printf("chunking state %d, %d bytes\n",
				    (int)chunking_state, chunking_data_left);

      /* push the current receive_* function on the "stack", and
      replace them by bdat_getc(), which in turn will use the lwr_receive_*
      functions to do the dirty work. */
      lwr_receive_getc = receive_getc;
      lwr_receive_getbuf = receive_getbuf;
      lwr_receive_ungetc = receive_ungetc;

      receive_getc = bdat_getc;
      receive_ungetc = bdat_ungetc;

      f.dot_ends = FALSE;

      goto DATA_BDAT;
      }

    case DATA_CMD:
      HAD(SCH_DATA);
      f.dot_ends = TRUE;

    DATA_BDAT:		/* Common code for DATA and BDAT */
#ifdef EXPERIMENTAL_PIPE_CONNECT
      fl.pipe_connect_acceptable = FALSE;
#endif
      if (!discarded && recipients_count <= 0)
	{
	if (fl.rcpt_smtp_response_same && rcpt_smtp_response != NULL)
	  {
	  uschar *code = US"503";
	  int len = Ustrlen(rcpt_smtp_response);
	  smtp_respond(code, 3, FALSE, US"All RCPT commands were rejected with "
	    "this error:");
	  /* Responses from smtp_printf() will have \r\n on the end */
	  if (len > 2 && rcpt_smtp_response[len-2] == '\r')
	    rcpt_smtp_response[len-2] = 0;
	  smtp_respond(code, 3, FALSE, rcpt_smtp_response);
	  }
	if (f.smtp_in_pipelining_advertised && last_was_rcpt)
	  smtp_printf("503 Valid RCPT command must precede %s\r\n", FALSE,
	    smtp_names[smtp_connection_had[smtp_ch_index-1]]);
	else
	  done = synprot_error(L_smtp_protocol_error, 503, NULL,
	    smtp_connection_had[smtp_ch_index-1] == SCH_DATA
	    ? US"valid RCPT command must precede DATA"
	    : US"valid RCPT command must precede BDAT");

	if (chunking_state > CHUNKING_OFFERED)
	  bdat_flush_data();
	break;
	}

      if (toomany && recipients_max_reject)
	{
	sender_address = NULL;  /* This will allow a new MAIL without RSET */
	sender_address_unrewritten = NULL;
	smtp_printf("554 Too many recipients\r\n", FALSE);
	break;
	}

      if (chunking_state > CHUNKING_OFFERED)
	rc = OK;			/* No predata ACL or go-ahead output for BDAT */
      else
	{
	/* If there is an ACL, re-check the synchronization afterwards, since the
	ACL may have delayed.  To handle cutthrough delivery enforce a dummy call
	to get the DATA command sent. */

	if (acl_smtp_predata == NULL && cutthrough.cctx.sock < 0)
	  rc = OK;
	else
	  {
	  uschar * acl = acl_smtp_predata ? acl_smtp_predata : US"accept";
	  f.enable_dollar_recipients = TRUE;
	  rc = acl_check(ACL_WHERE_PREDATA, NULL, acl, &user_msg,
	    &log_msg);
	  f.enable_dollar_recipients = FALSE;
	  if (rc == OK && !check_sync())
	    goto SYNC_FAILURE;

	  if (rc != OK)
	    {	/* Either the ACL failed the address, or it was deferred. */
	    done = smtp_handle_acl_fail(ACL_WHERE_PREDATA, rc, user_msg, log_msg);
	    break;
	    }
	  }

	if (user_msg)
	  smtp_user_msg(US"354", user_msg);
	else
	  smtp_printf(
	    "354 Enter message, ending with \".\" on a line by itself\r\n", FALSE);
	}

#ifdef TCP_QUICKACK
      if (smtp_in)	/* all ACKs needed to ramp window up for bulk data */
	(void) setsockopt(fileno(smtp_in), IPPROTO_TCP, TCP_QUICKACK,
		US &on, sizeof(on));
#endif
      done = 3;
      message_ended = END_NOTENDED;   /* Indicate in middle of data */

      break;


    case VRFY_CMD:
      {
      uschar * address;

      HAD(SCH_VRFY);

      if (!(address = parse_extract_address(smtp_cmd_data, &errmess,
            &start, &end, &recipient_domain, FALSE)))
	{
	smtp_printf("501 %s\r\n", FALSE, errmess);
	break;
	}

      if (!recipient_domain)
	if (!(recipient_domain = qualify_recipient(&address, smtp_cmd_data,
				    US"verify")))
	  break;

      if ((rc = acl_check(ACL_WHERE_VRFY, address, acl_smtp_vrfy,
		    &user_msg, &log_msg)) != OK)
	done = smtp_handle_acl_fail(ACL_WHERE_VRFY, rc, user_msg, log_msg);
      else
	{
	uschar * s = NULL;
	address_item * addr = deliver_make_addr(address, FALSE);

	switch(verify_address(addr, NULL, vopt_is_recipient | vopt_qualify, -1,
	       -1, -1, NULL, NULL, NULL))
	  {
	  case OK:
	    s = string_sprintf("250 <%s> is deliverable", address);
	    break;

	  case DEFER:
	    s = (addr->user_message != NULL)?
	      string_sprintf("451 <%s> %s", address, addr->user_message) :
	      string_sprintf("451 Cannot resolve <%s> at this time", address);
	    break;

	  case FAIL:
	    s = (addr->user_message != NULL)?
	      string_sprintf("550 <%s> %s", address, addr->user_message) :
	      string_sprintf("550 <%s> is not deliverable", address);
	    log_write(0, LOG_MAIN, "VRFY failed for %s %s",
	      smtp_cmd_argument, host_and_ident(TRUE));
	    break;
	  }

	smtp_printf("%s\r\n", FALSE, s);
	}
      break;
      }


    case EXPN_CMD:
      HAD(SCH_EXPN);
      rc = acl_check(ACL_WHERE_EXPN, NULL, acl_smtp_expn, &user_msg, &log_msg);
      if (rc != OK)
	done = smtp_handle_acl_fail(ACL_WHERE_EXPN, rc, user_msg, log_msg);
      else
	{
	BOOL save_log_testing_mode = f.log_testing_mode;
	f.address_test_mode = f.log_testing_mode = TRUE;
	(void) verify_address(deliver_make_addr(smtp_cmd_data, FALSE),
	  smtp_out, vopt_is_recipient | vopt_qualify | vopt_expn, -1, -1, -1,
	  NULL, NULL, NULL);
	f.address_test_mode = FALSE;
	f.log_testing_mode = save_log_testing_mode;    /* true for -bh */
	}
      break;


    #ifdef SUPPORT_TLS

    case STARTTLS_CMD:
      HAD(SCH_STARTTLS);
      if (!fl.tls_advertised)
	{
	done = synprot_error(L_smtp_protocol_error, 503, NULL,
	  US"STARTTLS command used when not advertised");
	break;
	}

      /* Apply an ACL check if one is defined */

      if (  acl_smtp_starttls
	 && (rc = acl_check(ACL_WHERE_STARTTLS, NULL, acl_smtp_starttls,
		    &user_msg, &log_msg)) != OK
	 )
	{
	done = smtp_handle_acl_fail(ACL_WHERE_STARTTLS, rc, user_msg, log_msg);
	break;
	}

      /* RFC 2487 is not clear on when this command may be sent, though it
      does state that all information previously obtained from the client
      must be discarded if a TLS session is started. It seems reasonable to
      do an implied RSET when STARTTLS is received. */

      incomplete_transaction_log(US"STARTTLS");
      cancel_cutthrough_connection(TRUE, US"STARTTLS received");
      smtp_reset(reset_point);
      toomany = FALSE;
      cmd_list[CMD_LIST_STARTTLS].is_mail_cmd = FALSE;

      /* There's an attack where more data is read in past the STARTTLS command
      before TLS is negotiated, then assumed to be part of the secure session
      when used afterwards; we use segregated input buffers, so are not
      vulnerable, but we want to note when it happens and, for sheer paranoia,
      ensure that the buffer is "wiped".
      Pipelining sync checks will normally have protected us too, unless disabled
      by configuration. */

      if (receive_smtp_buffered())
	{
	DEBUG(D_any)
	  debug_printf("Non-empty input buffer after STARTTLS; naive attack?\n");
	if (tls_in.active.sock < 0)
	  smtp_inend = smtp_inptr = smtp_inbuffer;
	/* and if TLS is already active, tls_server_start() should fail */
	}

      /* There is nothing we value in the input buffer and if TLS is successfully
      negotiated, we won't use this buffer again; if TLS fails, we'll just read
      fresh content into it.  The buffer contains arbitrary content from an
      untrusted remote source; eg: NOOP <shellcode>\r\nSTARTTLS\r\n
      It seems safest to just wipe away the content rather than leave it as a
      target to jump to. */

      memset(smtp_inbuffer, 0, IN_BUFFER_SIZE);

      /* Attempt to start up a TLS session, and if successful, discard all
      knowledge that was obtained previously. At least, that's what the RFC says,
      and that's what happens by default. However, in order to work round YAEB,
      there is an option to remember the esmtp state. Sigh.

      We must allow for an extra EHLO command and an extra AUTH command after
      STARTTLS that don't add to the nonmail command count. */

      s = NULL;
      if ((rc = tls_server_start(tls_require_ciphers, &s)) == OK)
	{
	if (!tls_remember_esmtp)
	  fl.helo_seen = fl.esmtp = fl.auth_advertised = f.smtp_in_pipelining_advertised = FALSE;
	cmd_list[CMD_LIST_EHLO].is_mail_cmd = TRUE;
	cmd_list[CMD_LIST_AUTH].is_mail_cmd = TRUE;
	cmd_list[CMD_LIST_TLS_AUTH].is_mail_cmd = TRUE;
	if (sender_helo_name)
	  {
	  store_free(sender_helo_name);
	  sender_helo_name = NULL;
	  host_build_sender_fullhost();  /* Rebuild */
	  set_process_info("handling incoming TLS connection from %s",
	    host_and_ident(FALSE));
	  }
	received_protocol =
	  (sender_host_address ? protocols : protocols_local)
	    [ (fl.esmtp
	      ? pextend + (sender_host_authenticated ? pauthed : 0)
	      : pnormal)
	    + (tls_in.active.sock >= 0 ? pcrpted : 0)
	    ];

	sender_host_auth_pubname = sender_host_authenticated = NULL;
	authenticated_id = NULL;
	sync_cmd_limit = NON_SYNC_CMD_NON_PIPELINING;
	DEBUG(D_tls) debug_printf("TLS active\n");
	break;     /* Successful STARTTLS */
	}
      else
	(void) smtp_log_tls_fail(s);

      /* Some local configuration problem was discovered before actually trying
      to do a TLS handshake; give a temporary error. */

      if (rc == DEFER)
	{
	smtp_printf("454 TLS currently unavailable\r\n", FALSE);
	break;
	}

      /* Hard failure. Reject everything except QUIT or closed connection. One
      cause for failure is a nested STARTTLS, in which case tls_in.active remains
      set, but we must still reject all incoming commands.  Another is a handshake
      failure - and there may some encrypted data still in the pipe to us, which we
      see as garbage commands. */

      DEBUG(D_tls) debug_printf("TLS failed to start\n");
      while (done <= 0) switch(smtp_read_command(FALSE, GETC_BUFFER_UNLIMITED))
	{
	case EOF_CMD:
	  log_write(L_smtp_connection, LOG_MAIN, "%s closed by EOF",
	    smtp_get_connection_info());
	  smtp_notquit_exit(US"tls-failed", NULL, NULL);
	  done = 2;
	  break;

	/* It is perhaps arguable as to which exit ACL should be called here,
	but as it is probably a situation that almost never arises, it
	probably doesn't matter. We choose to call the real QUIT ACL, which in
	some sense is perhaps "right". */

	case QUIT_CMD:
	  user_msg = NULL;
	  if (  acl_smtp_quit
	     && ((rc = acl_check(ACL_WHERE_QUIT, NULL, acl_smtp_quit, &user_msg,
				&log_msg)) == ERROR))
	      log_write(0, LOG_MAIN|LOG_PANIC, "ACL for QUIT returned ERROR: %s",
		log_msg);
	  if (user_msg)
	    smtp_respond(US"221", 3, TRUE, user_msg);
	  else
	    smtp_printf("221 %s closing connection\r\n", FALSE, smtp_active_hostname);
	  log_write(L_smtp_connection, LOG_MAIN, "%s closed by QUIT",
	    smtp_get_connection_info());
	  done = 2;
	  break;

	default:
	  smtp_printf("554 Security failure\r\n", FALSE);
	  break;
	}
      tls_close(NULL, TLS_SHUTDOWN_NOWAIT);
      break;
    #endif


    /* The ACL for QUIT is provided for gathering statistical information or
    similar; it does not affect the response code, but it can supply a custom
    message. */

    case QUIT_CMD:
      smtp_quit_handler(&user_msg, &log_msg);
      done = 2;
      break;


    case RSET_CMD:
      smtp_rset_handler();
      cancel_cutthrough_connection(TRUE, US"RSET received");
      smtp_reset(reset_point);
      toomany = FALSE;
      break;


    case NOOP_CMD:
      HAD(SCH_NOOP);
      smtp_printf("250 OK\r\n", FALSE);
      break;


    /* Show ETRN/EXPN/VRFY if there's an ACL for checking hosts; if actually
    used, a check will be done for permitted hosts. Show STARTTLS only if not
    already in a TLS session and if it would be advertised in the EHLO
    response. */

    case HELP_CMD:
      HAD(SCH_HELP);
      smtp_printf("214-Commands supported:\r\n", TRUE);
	{
	uschar buffer[256];
	buffer[0] = 0;
	Ustrcat(buffer, " AUTH");
	#ifdef SUPPORT_TLS
	if (tls_in.active.sock < 0 &&
	    verify_check_host(&tls_advertise_hosts) != FAIL)
	  Ustrcat(buffer, " STARTTLS");
	#endif
	Ustrcat(buffer, " HELO EHLO MAIL RCPT DATA BDAT");
	Ustrcat(buffer, " NOOP QUIT RSET HELP");
	if (acl_smtp_etrn != NULL) Ustrcat(buffer, " ETRN");
	if (acl_smtp_expn != NULL) Ustrcat(buffer, " EXPN");
	if (acl_smtp_vrfy != NULL) Ustrcat(buffer, " VRFY");
	smtp_printf("214%s\r\n", FALSE, buffer);
	}
      break;


    case EOF_CMD:
      incomplete_transaction_log(US"connection lost");
      smtp_notquit_exit(US"connection-lost", US"421",
	US"%s lost input connection", smtp_active_hostname);

      /* Don't log by default unless in the middle of a message, as some mailers
      just drop the call rather than sending QUIT, and it clutters up the logs.
      */

      if (sender_address || recipients_count > 0)
	log_write(L_lost_incoming_connection, LOG_MAIN,
	  "unexpected %s while reading SMTP command from %s%s%s D=%s",
	  f.sender_host_unknown ? "EOF" : "disconnection",
	  f.tcp_in_fastopen_logged
	  ? US""
	  : f.tcp_in_fastopen
	  ? f.tcp_in_fastopen_data ? US"TFO* " : US"TFO "
	  : US"",
	  host_and_ident(FALSE), smtp_read_error,
	  string_timesince(&smtp_connection_start)
	  );

      else
	log_write(L_smtp_connection, LOG_MAIN, "%s %slost%s D=%s",
	  smtp_get_connection_info(),
	  f.tcp_in_fastopen && !f.tcp_in_fastopen_logged ? US"TFO " : US"",
	  smtp_read_error,
	  string_timesince(&smtp_connection_start)
	  );

      done = 1;
      break;


    case ETRN_CMD:
      HAD(SCH_ETRN);
      if (sender_address)
	{
	done = synprot_error(L_smtp_protocol_error, 503, NULL,
	  US"ETRN is not permitted inside a transaction");
	break;
	}

      log_write(L_etrn, LOG_MAIN, "ETRN %s received from %s", smtp_cmd_argument,
	host_and_ident(FALSE));

      if ((rc = acl_check(ACL_WHERE_ETRN, NULL, acl_smtp_etrn,
		  &user_msg, &log_msg)) != OK)
	{
	done = smtp_handle_acl_fail(ACL_WHERE_ETRN, rc, user_msg, log_msg);
	break;
	}

      /* Compute the serialization key for this command. */

      etrn_serialize_key = string_sprintf("etrn-%s\n", smtp_cmd_data);

      /* If a command has been specified for running as a result of ETRN, we
      permit any argument to ETRN. If not, only the # standard form is permitted,
      since that is strictly the only kind of ETRN that can be implemented
      according to the RFC. */

      if (smtp_etrn_command)
	{
	uschar *error;
	BOOL rc;
	etrn_command = smtp_etrn_command;
	deliver_domain = smtp_cmd_data;
	rc = transport_set_up_command(&argv, smtp_etrn_command, TRUE, 0, NULL,
	  US"ETRN processing", &error);
	deliver_domain = NULL;
	if (!rc)
	  {
	  log_write(0, LOG_MAIN|LOG_PANIC, "failed to set up ETRN command: %s",
	    error);
	  smtp_printf("458 Internal failure\r\n", FALSE);
	  break;
	  }
	}

      /* Else set up to call Exim with the -R option. */

      else
	{
	if (*smtp_cmd_data++ != '#')
	  {
	  done = synprot_error(L_smtp_syntax_error, 501, NULL,
	    US"argument must begin with #");
	  break;
	  }
	etrn_command = US"exim -R";
	argv = CUSS child_exec_exim(CEE_RETURN_ARGV, TRUE, NULL, TRUE,
	  *queue_name ? 4 : 2,
	  US"-R", smtp_cmd_data,
	  US"-MCG", queue_name);
	}

      /* If we are host-testing, don't actually do anything. */

      if (host_checking)
	{
	HDEBUG(D_any)
	  {
	  debug_printf("ETRN command is: %s\n", etrn_command);
	  debug_printf("ETRN command execution skipped\n");
	  }
	if (user_msg == NULL) smtp_printf("250 OK\r\n", FALSE);
	  else smtp_user_msg(US"250", user_msg);
	break;
	}


      /* If ETRN queue runs are to be serialized, check the database to
      ensure one isn't already running. */

      if (smtp_etrn_serialize && !enq_start(etrn_serialize_key, 1))
	{
	smtp_printf("458 Already processing %s\r\n", FALSE, smtp_cmd_data);
	break;
	}

      /* Fork a child process and run the command. We don't want to have to
      wait for the process at any point, so set SIGCHLD to SIG_IGN before
      forking. It should be set that way anyway for external incoming SMTP,
      but we save and restore to be tidy. If serialization is required, we
      actually run the command in yet another process, so we can wait for it
      to complete and then remove the serialization lock. */

      oldsignal = signal(SIGCHLD, SIG_IGN);

      if ((pid = fork()) == 0)
	{
	smtp_input = FALSE;       /* This process is not associated with the */
	(void)fclose(smtp_in);    /* SMTP call any more. */
	(void)fclose(smtp_out);

	signal(SIGCHLD, SIG_DFL);      /* Want to catch child */

	/* If not serializing, do the exec right away. Otherwise, fork down
	into another process. */

	if (!smtp_etrn_serialize || (pid = fork()) == 0)
	  {
	  DEBUG(D_exec) debug_print_argv(argv);
	  exim_nullstd();                   /* Ensure std{in,out,err} exist */
	  execv(CS argv[0], (char *const *)argv);
	  log_write(0, LOG_MAIN|LOG_PANIC_DIE, "exec of \"%s\" (ETRN) failed: %s",
	    etrn_command, strerror(errno));
	  _exit(EXIT_FAILURE);         /* paranoia */
	  }

	/* Obey this if smtp_serialize and the 2nd fork yielded non-zero. That
	is, we are in the first subprocess, after forking again. All we can do
	for a failing fork is to log it. Otherwise, wait for the 2nd process to
	complete, before removing the serialization. */

	if (pid < 0)
	  log_write(0, LOG_MAIN|LOG_PANIC, "2nd fork for serialized ETRN "
	    "failed: %s", strerror(errno));
	else
	  {
	  int status;
	  DEBUG(D_any) debug_printf("waiting for serialized ETRN process %d\n",
	    (int)pid);
	  (void)wait(&status);
	  DEBUG(D_any) debug_printf("serialized ETRN process %d ended\n",
	    (int)pid);
	  }

	enq_end(etrn_serialize_key);
	_exit(EXIT_SUCCESS);
	}

      /* Back in the top level SMTP process. Check that we started a subprocess
      and restore the signal state. */

      if (pid < 0)
	{
	log_write(0, LOG_MAIN|LOG_PANIC, "fork of process for ETRN failed: %s",
	  strerror(errno));
	smtp_printf("458 Unable to fork process\r\n", FALSE);
	if (smtp_etrn_serialize) enq_end(etrn_serialize_key);
	}
      else
	{
	if (user_msg == NULL) smtp_printf("250 OK\r\n", FALSE);
	  else smtp_user_msg(US"250", user_msg);
	}

      signal(SIGCHLD, oldsignal);
      break;


    case BADARG_CMD:
      done = synprot_error(L_smtp_syntax_error, 501, NULL,
	US"unexpected argument data");
      break;


    /* This currently happens only for NULLs, but could be extended. */

    case BADCHAR_CMD:
      done = synprot_error(L_smtp_syntax_error, 0, NULL,       /* Just logs */
	US"NUL character(s) present (shown as '?')");
      smtp_printf("501 NUL characters are not allowed in SMTP commands\r\n",
		  FALSE);
      break;


    case BADSYN_CMD:
    SYNC_FAILURE:
      if (smtp_inend >= smtp_inbuffer + IN_BUFFER_SIZE)
	smtp_inend = smtp_inbuffer + IN_BUFFER_SIZE - 1;
      c = smtp_inend - smtp_inptr;
      if (c > 150) c = 150;	/* limit logged amount */
      smtp_inptr[c] = 0;
      incomplete_transaction_log(US"sync failure");
      log_write(0, LOG_MAIN|LOG_REJECT, "SMTP protocol synchronization error "
	"(next input sent too soon: pipelining was%s advertised): "
	"rejected \"%s\" %s next input=\"%s\"",
	f.smtp_in_pipelining_advertised ? "" : " not",
	smtp_cmd_buffer, host_and_ident(TRUE),
	string_printing(smtp_inptr));
      smtp_notquit_exit(US"synchronization-error", US"554",
	US"SMTP synchronization error");
      done = 1;   /* Pretend eof - drops connection */
      break;


    case TOO_MANY_NONMAIL_CMD:
      s = smtp_cmd_buffer;
      while (*s != 0 && !isspace(*s)) s++;
      incomplete_transaction_log(US"too many non-mail commands");
      log_write(0, LOG_MAIN|LOG_REJECT, "SMTP call from %s dropped: too many "
	"nonmail commands (last was \"%.*s\")",  host_and_ident(FALSE),
	(int)(s - smtp_cmd_buffer), smtp_cmd_buffer);
      smtp_notquit_exit(US"bad-commands", US"554", US"Too many nonmail commands");
      done = 1;   /* Pretend eof - drops connection */
      break;

#ifdef SUPPORT_PROXY
    case PROXY_FAIL_IGNORE_CMD:
      smtp_printf("503 Command refused, required Proxy negotiation failed\r\n", FALSE);
      break;
#endif

    default:
      if (unknown_command_count++ >= smtp_max_unknown_commands)
	{
	log_write(L_smtp_syntax_error, LOG_MAIN,
	  "SMTP syntax error in \"%s\" %s %s",
	  string_printing(smtp_cmd_buffer), host_and_ident(TRUE),
	  US"unrecognized command");
	incomplete_transaction_log(US"unrecognized command");
	smtp_notquit_exit(US"bad-commands", US"500",
	  US"Too many unrecognized commands");
	done = 2;
	log_write(0, LOG_MAIN|LOG_REJECT, "SMTP call from %s dropped: too many "
	  "unrecognized commands (last was \"%s\")", host_and_ident(FALSE),
	  string_printing(smtp_cmd_buffer));
	}
      else
	done = synprot_error(L_smtp_syntax_error, 500, NULL,
	  US"unrecognized command");
      break;
    }

  /* This label is used by goto's inside loops that want to break out to
  the end of the command-processing loop. */

  COMMAND_LOOP:
  last_was_rej_mail = was_rej_mail;     /* Remember some last commands for */
  last_was_rcpt = was_rcpt;             /* protocol error handling */
  continue;
  }

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

Project: exim

smtp_sock_connect(host_item * host, int host_af, int port, uschar * interface,
  transport_instance * tb, int timeout, const blob * early_data)
{
smtp_transport_options_block * ob =
  (smtp_transport_options_block *)tb->options_block;
const uschar * dscp = ob->dscp;
int dscp_value;
int dscp_level;
int dscp_option;
int sock;
int save_errno = 0;
const blob * fastopen_blob = NULL;


#ifndef DISABLE_EVENT
deliver_host_address = host->address;
deliver_host_port = port;
if (event_raise(tb->event_action, US"tcp:connect", NULL)) return -1;
#endif

if ((sock = ip_socket(SOCK_STREAM, host_af)) < 0) return -1;

/* Set TCP_NODELAY; Exim does its own buffering. */

if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, US &on, sizeof(on)))
  HDEBUG(D_transport|D_acl|D_v)
    debug_printf_indent("failed to set NODELAY: %s ", strerror(errno));

/* Set DSCP value, if we can. For now, if we fail to set the value, we don't
bomb out, just log it and continue in default traffic class. */

if (dscp && dscp_lookup(dscp, host_af, &dscp_level, &dscp_option, &dscp_value))
  {
  HDEBUG(D_transport|D_acl|D_v)
    debug_printf_indent("DSCP \"%s\"=%x ", dscp, dscp_value);
  if (setsockopt(sock, dscp_level, dscp_option, &dscp_value, sizeof(dscp_value)) < 0)
    HDEBUG(D_transport|D_acl|D_v)
      debug_printf_indent("failed to set DSCP: %s ", strerror(errno));
  /* If the kernel supports IPv4 and IPv6 on an IPv6 socket, we need to set the
  option for both; ignore failures here */
  if (host_af == AF_INET6 &&
      dscp_lookup(dscp, AF_INET, &dscp_level, &dscp_option, &dscp_value))
    (void) setsockopt(sock, dscp_level, dscp_option, &dscp_value, sizeof(dscp_value));
  }

/* Bind to a specific interface if requested. Caller must ensure the interface
is the same type (IPv4 or IPv6) as the outgoing address. */

if (interface && ip_bind(sock, host_af, interface, 0) < 0)
  {
  save_errno = errno;
  HDEBUG(D_transport|D_acl|D_v)
    debug_printf_indent("unable to bind outgoing SMTP call to %s: %s", interface,
    strerror(errno));
  }

/* Connect to the remote host, and add keepalive to the socket before returning
it, if requested.  If the build supports TFO, request it - and if the caller
requested some early-data then include that in the TFO request.  If there is
early-data but no TFO support, send it after connecting. */

else
  {
#ifdef TCP_FASTOPEN
  if (verify_check_given_host(CUSS &ob->hosts_try_fastopen, host) == OK)
    fastopen_blob = early_data ? early_data : &tcp_fastopen_nodata;
#endif

  if (ip_connect(sock, host_af, host->address, port, timeout, fastopen_blob) < 0)
    save_errno = errno;
  else if (early_data && !fastopen_blob && early_data->data && early_data->len)
    {
    HDEBUG(D_transport|D_acl|D_v)
      debug_printf("sending %ld nonTFO early-data\n", (long)early_data->len);

#ifdef TCP_QUICKACK
    (void) setsockopt(sock, IPPROTO_TCP, TCP_QUICKACK, US &off, sizeof(off));
#endif
    if (send(sock, early_data->data, early_data->len, 0) < 0)
      save_errno = errno;
    }
  }

/* Either bind() or connect() failed */

if (save_errno != 0)
  {
  HDEBUG(D_transport|D_acl|D_v)
    {
    debug_printf_indent("failed: %s", CUstrerror(save_errno));
    if (save_errno == ETIMEDOUT)
      debug_printf(" (timeout=%s)", readconf_printtime(timeout));
    debug_printf("\n");
    }
  (void)close(sock);
  errno = save_errno;
  return -1;
  }

/* Both bind() and connect() succeeded, and any early-data */

else
  {
  union sockaddr_46 interface_sock;
  EXIM_SOCKLEN_T size = sizeof(interface_sock);

  HDEBUG(D_transport|D_acl|D_v) debug_printf_indent("connected\n");
  if (getsockname(sock, (struct sockaddr *)(&interface_sock), &size) == 0)
    sending_ip_address = host_ntoa(-1, &interface_sock, NULL, &sending_port);
  else
    {
    log_write(0, LOG_MAIN | ((errno == ECONNRESET)? 0 : LOG_PANIC),
      "getsockname() failed: %s", strerror(errno));
    close(sock);
    return -1;
    }

  if (ob->keepalive) ip_keepalive(sock, host->address, TRUE);
#ifdef TCP_FASTOPEN
  tfo_out_check(sock);
#endif
  return sock;
  }
}

Project: exim

function_store_malloc(size_t size)
{
return store_malloc((int)size);
}

Project: exim

failure_log(address_item * addr, uschar * driver_kind, uschar * now)
{
void * reset_point;
gstring * g = reset_point = string_get(256);

#ifndef DISABLE_EVENT
/* Message failures for which we will send a DSN get their event raised
later so avoid doing it here. */

if (  !addr->prop.ignore_error
   && !(addr->dsn_flags & (rf_dsnflags & ~rf_notify_failure))
   )
  msg_event_raise(US"msg:fail:delivery", addr);
#endif

/* Build up the log line for the message and main logs */

/* Create the address string for logging. Must not do this earlier, because
an OK result may be changed to FAIL when a pipe returns text. */

g = string_log_address(g, addr, LOGGING(all_parents), FALSE);

if (LOGGING(sender_on_delivery))
  g = string_append(g, 3, US" F=<", sender_address, US">");

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

/* Return path may not be set if no delivery actually happened */

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

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

if (addr->host_used)
  g = d_hostlog(g, addr);

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

if (addr->basic_errno > 0)
  g = string_append(g, 2, US": ", US strerror(addr->basic_errno));

if (addr->message)
  g = string_append(g, 2, US": ", addr->message);

(void) string_from_gstring(g);

/* Do the logging. For the message log, "routing failed" for those cases,
just to make it clearer. */

if (driver_kind)
  deliver_msglog("%s %s failed for %s\n", now, driver_kind, g->s);
else
  deliver_msglog("%s %s\n", now, g->s);

log_write(0, LOG_MAIN, "** %s", g->s);

store_reset(reset_point);
return;
}

Project: exim

smtp_notquit_exit(uschar *reason, uschar *code, uschar *defaultrespond, ...)
{
int rc;
uschar *user_msg = NULL;
uschar *log_msg = NULL;

/* Check for recursive acll */

if (fl.smtp_exit_function_called)
  {
  log_write(0, LOG_PANIC, "smtp_notquit_exit() called more than once (%s)",
    reason);
  return;
  }
fl.smtp_exit_function_called = TRUE;

/* Call the not-QUIT ACL, if there is one, unless no reason is given. */

if (acl_smtp_notquit && reason)
  {
  smtp_notquit_reason = reason;
  if ((rc = acl_check(ACL_WHERE_NOTQUIT, NULL, acl_smtp_notquit, &user_msg,
		      &log_msg)) == ERROR)
    log_write(0, LOG_MAIN|LOG_PANIC, "ACL for not-QUIT returned ERROR: %s",
      log_msg);
  }

/* If the connection was dropped, we certainly are no longer talking TLS */
tls_in.active.sock = -1;

/* Write an SMTP response if we are expected to give one. As the default
responses are all internal, they should always fit in the buffer, but code a
warning, just in case. Note that string_vformat() still leaves a complete
string, even if it is incomplete. */

if (code && defaultrespond)
  {
  if (user_msg)
    smtp_respond(code, 3, TRUE, user_msg);
  else
    {
    gstring * g;
    va_list ap;

    va_start(ap, defaultrespond);
    g = string_vformat(NULL, TRUE, CS defaultrespond, ap);
    va_end(ap);
    smtp_printf("%s %s\r\n", FALSE, code, string_from_gstring(g));
    }
  mac_smtp_fflush();
  }
}

Project: exim

header_checkname(header_line *h, BOOL is_resent)
{
uschar *text = h->text;
header_name *bot = header_names;
header_name *top = header_names + header_names_size;

if (is_resent) text += 7;

while (bot < top)
  {
  header_name *mid = bot + (top - bot)/2;
  int c = strncmpic(text, mid->name, mid->len);

  if (c == 0)
    {
    uschar *s = text + mid->len;
    while (isspace(*s)) s++;
    if (*s == ':')
      return (!is_resent || mid->allow_resent)? mid->htype : htype_other;
    c = 1;
    }

  if (c > 0) bot = mid + 1; else top = mid;
  }

return htype_other;
}

Project: exim

acl_check_wargs(int where, address_item *addr, const uschar *s,
  uschar **user_msgptr, uschar **log_msgptr)
{
uschar * tmp;
uschar * tmp_arg[9];	/* must match acl_arg[] */
uschar * sav_arg[9];	/* must match acl_arg[] */
int sav_narg;
uschar * name;
int i;
int ret;

if (!(tmp = string_dequote(&s)) || !(name = expand_string(tmp)))
  goto bad;

for (i = 0; i < 9; i++)
  {
  while (*s && isspace(*s)) s++;
  if (!*s) break;
  if (!(tmp = string_dequote(&s)) || !(tmp_arg[i] = expand_string(tmp)))
    {
    tmp = name;
    goto bad;
    }
  }

sav_narg = acl_narg;
acl_narg = i;
for (i = 0; i < acl_narg; i++)
  {
  sav_arg[i] = acl_arg[i];
  acl_arg[i] = tmp_arg[i];
  }
while (i < 9)
  {
  sav_arg[i] = acl_arg[i];
  acl_arg[i++] = NULL;
  }

acl_level++;
ret = acl_check_internal(where, addr, name, user_msgptr, log_msgptr);
acl_level--;

acl_narg = sav_narg;
for (i = 0; i < 9; i++) acl_arg[i] = sav_arg[i];
return ret;

bad:
if (f.expand_string_forcedfail) return ERROR;
*log_msgptr = string_sprintf("failed to expand ACL string \"%s\": %s",
  tmp, expand_string_message);
return f.search_find_defer ? DEFER : ERROR;
}

Project: exim

int auth_heimdal_gssapi_client(auth_instance *ablock, void * sx,
  int timeout, uschar *buffer, int buffsize) {return 0;}

Project: exim
File: deliver.c

remote_post_process(address_item *addr, int logflags, uschar *msg,
  BOOL fallback)
{
host_item *h;

/* If any host addresses were found to be unusable, add them to the unusable
tree so that subsequent deliveries don't try them. */

for (h = addr->host_list; h; h = h->next)
  if (h->address)
    if (h->status >= hstatus_unusable) tree_add_unusable(h);

/* Now handle each address on the chain. The transport has placed '=' or '-'
into the special_action field for each successful delivery. */

while (addr)
  {
  address_item *next = addr->next;

  /* If msg == NULL (normal processing) and the result is DEFER and we are
  processing the main hosts and there are fallback hosts available, put the
  address on the list for fallback delivery. */

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

  /* If msg is set (=> unexpected problem), set it in the address before
  doing the ordinary post processing. */

  else
    {
    if (msg)
      {
      addr->message = msg;
      addr->transport_return = DEFER;
      }
    (void)post_process_one(addr, addr->transport_return, logflags,
      EXIM_DTYPE_TRANSPORT, addr->special_action);
    }

  /* Next address */

  addr = next;
  }

/* If we have just delivered down a passed SMTP channel, and that was
the last address, the channel will have been closed down. Now that
we have logged that delivery, set continue_sequence to 1 so that
any subsequent deliveries don't get "*" incorrectly logged. */

if (!continue_transport) continue_sequence = 1;
}

Project: exim

smtp_rset_handler(void)
{
HAD(SCH_RSET);
incomplete_transaction_log(US"RSET");
smtp_printf("250 Reset OK\r\n", FALSE);
cmd_list[CMD_LIST_RSET].is_mail_cmd = FALSE;
}

Project: exim

smtp_in_auth(auth_instance *au, uschar ** s, uschar ** ss)
{
const uschar *set_id = NULL;
int rc, i;

/* Run the checking code, passing the remainder of the command line as
data. Initials the $auth<n> variables as empty. Initialize $0 empty and set
it as the only set numerical variable. The authenticator may set $auth<n>
and also set other numeric variables. The $auth<n> variables are preferred
nowadays; the numerical variables remain for backwards compatibility.

Afterwards, have a go at expanding the set_id string, even if
authentication failed - for bad passwords it can be useful to log the
userid. On success, require set_id to expand and exist, and put it in
authenticated_id. Save this in permanent store, as the working store gets
reset at HELO, RSET, etc. */

for (i = 0; i < AUTH_VARS; i++) auth_vars[i] = NULL;
expand_nmax = 0;
expand_nlength[0] = 0;   /* $0 contains nothing */

rc = (au->info->servercode)(au, smtp_cmd_data);
if (au->set_id) set_id = expand_string(au->set_id);
expand_nmax = -1;        /* Reset numeric variables */
for (i = 0; i < AUTH_VARS; i++) auth_vars[i] = NULL;   /* Reset $auth<n> */

/* The value of authenticated_id is stored in the spool file and printed in
log lines. It must not contain binary zeros or newline characters. In
normal use, it never will, but when playing around or testing, this error
can (did) happen. To guard against this, ensure that the id contains only
printing characters. */

if (set_id) set_id = string_printing(set_id);

/* For the non-OK cases, set up additional logging data if set_id
is not empty. */

if (rc != OK)
  set_id = set_id && *set_id
    ? string_sprintf(" (set_id=%s)", set_id) : US"";

/* Switch on the result */

switch(rc)
  {
  case OK:
  if (!au->set_id || set_id)    /* Complete success */
    {
    if (set_id) authenticated_id = string_copy_malloc(set_id);
    sender_host_authenticated = au->name;
    sender_host_auth_pubname  = au->public_name;
    authentication_failed = FALSE;
    authenticated_fail_id = NULL;   /* Impossible to already be set? */

    received_protocol =
      (sender_host_address ? protocols : protocols_local)
	[pextend + pauthed + (tls_in.active.sock >= 0 ? pcrpted:0)];
    *s = *ss = US"235 Authentication succeeded";
    authenticated_by = au;
    break;
    }

  /* Authentication succeeded, but we failed to expand the set_id string.
  Treat this as a temporary error. */

  auth_defer_msg = expand_string_message;
  /* Fall through */

  case DEFER:
  if (set_id) authenticated_fail_id = string_copy_malloc(set_id);
  *s = string_sprintf("435 Unable to authenticate at present%s",
    auth_defer_user_msg);
  *ss = string_sprintf("435 Unable to authenticate at present%s: %s",
    set_id, auth_defer_msg);
  break;

  case BAD64:
  *s = *ss = US"501 Invalid base64 data";
  break;

  case CANCELLED:
  *s = *ss = US"501 Authentication cancelled";
  break;

  case UNEXPECTED:
  *s = *ss = US"553 Initial data not expected";
  break;

  case FAIL:
  if (set_id) authenticated_fail_id = string_copy_malloc(set_id);
  *s = US"535 Incorrect authentication data";
  *ss = string_sprintf("535 Incorrect authentication data%s", set_id);
  break;

  default:
  if (set_id) authenticated_fail_id = string_copy_malloc(set_id);
  *s = US"435 Internal error";
  *ss = string_sprintf("435 Internal error%s: return %d from authentication "
    "check", set_id, rc);
  break;
  }

return rc;
}

Project: exim

deliver_init(void)
{
#ifdef EXIM_TFO_PROBE
tfo_probe();
#else
f.tcp_fastopen_ok = TRUE;
#endif


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

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

if (!regex_AUTH) regex_AUTH =
  regex_must_compile(AUTHS_REGEX, FALSE, TRUE);

#ifdef SUPPORT_TLS
if (!regex_STARTTLS) regex_STARTTLS =
  regex_must_compile(US"\\n250[\\s\\-]STARTTLS(\\s|\\n|$)", FALSE, TRUE);

# ifdef EXPERIMENTAL_REQUIRETLS
if (!regex_REQUIRETLS) regex_REQUIRETLS =
  regex_must_compile(US"\\n250[\\s\\-]REQUIRETLS(\\s|\\n|$)", FALSE, TRUE);
# endif
#endif

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

#ifndef DISABLE_PRDR
if (!regex_PRDR) regex_PRDR =
  regex_must_compile(US"\\n250[\\s\\-]PRDR(\\s|\\n|$)", FALSE, TRUE);
#endif

#ifdef SUPPORT_I18N
if (!regex_UTF8) regex_UTF8 =
  regex_must_compile(US"\\n250[\\s\\-]SMTPUTF8(\\s|\\n|$)", FALSE, TRUE);
#endif

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

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

#ifdef EXPERIMENTAL_PIPE_CONNECT
if (!regex_EARLY_PIPE) regex_EARLY_PIPE =
  regex_must_compile(US"\\n250[\\s\\-]" EARLY_PIPE_FEATURE_NAME "(\\s|\\n|$)", FALSE, TRUE);
#endif
}

Project: exim

open_log(int *fd, int type, uschar *tag)
{
uid_t euid;
BOOL ok, ok2;
uschar buffer[LOG_NAME_SIZE];

/* The names of the log files are controlled by file_path. The panic log is
written to the same directory as the main and reject logs, but its name does
not have a datestamp. The use of datestamps is indicated by %D/%M in file_path.
When opening the panic log, if %D or %M is present, we remove the datestamp
from the generated name; if it is at the start, remove a following
non-alphanumeric character as well; otherwise, remove a preceding
non-alphanumeric character. This is definitely kludgy, but it sort of does what
people want, I hope. */

ok = string_format(buffer, sizeof(buffer), CS file_path, log_names[type]);

/* Save the name of the mainlog for rollover processing. Without a datestamp,
it gets statted to see if it has been cycled. With a datestamp, the datestamp
will be compared. The static slot for saving it is the same size as buffer,
and the text has been checked above to fit, so this use of strcpy() is OK. */

if (type == lt_main && string_datestamp_offset >= 0)
  {
  Ustrcpy(mainlog_name, buffer);
  mainlog_datestamp = mainlog_name + string_datestamp_offset;
  }

/* Ditto for the reject log */

else if (type == lt_reject && string_datestamp_offset >= 0)
  {
  Ustrcpy(rejectlog_name, buffer);
  rejectlog_datestamp = rejectlog_name + string_datestamp_offset;
  }

/* and deal with the debug log (which keeps the datestamp, but does not
update it) */

else if (type == lt_debug)
  {
  Ustrcpy(debuglog_name, buffer);
  if (tag)
    {
    /* this won't change the offset of the datestamp */
    ok2 = string_format(buffer, sizeof(buffer), "%s%s",
      debuglog_name, tag);
    if (ok2)
      Ustrcpy(debuglog_name, buffer);
    }
  }

/* Remove any datestamp if this is the panic log. This is rare, so there's no
need to optimize getting the datestamp length. We remove one non-alphanumeric
char afterwards if at the start, otherwise one before. */

else if (string_datestamp_offset >= 0)
  {
  uschar * from = buffer + string_datestamp_offset;
  uschar * to = from + string_datestamp_length;

  if (from == buffer || from[-1] == '/')
    {
    if (!isalnum(*to)) to++;
    }
  else
    if (!isalnum(from[-1])) from--;

  /* This copy is ok, because we know that to is a substring of from. But
  due to overlap we must use memmove() not Ustrcpy(). */
  memmove(from, to, Ustrlen(to)+1);
  }

/* If the file name is too long, it is an unrecoverable disaster */

if (!ok)
  die(US"exim: log file path too long: aborting",
      US"Logging failure; please try later");

/* We now have the file name. Try to open an existing file. After a successful
open, arrange for automatic closure on exec(), and then return. */

*fd = Uopen(buffer,
#ifdef O_CLOEXEC
		O_CLOEXEC |
#endif
	       	O_APPEND|O_WRONLY, LOG_MODE);

if (*fd >= 0)
  {
#ifndef O_CLOEXEC
  (void)fcntl(*fd, F_SETFD, fcntl(*fd, F_GETFD) | FD_CLOEXEC);
#endif
  return;
  }

/* Open was not successful: try creating the file. If this is a root process,
we must do the creating in a subprocess set to exim:exim in order to ensure
that the file is created with the right ownership. Otherwise, there can be a
race if another Exim process is trying to write to the log at the same time.
The use of SIGUSR1 by the exiwhat utility can provoke a lot of simultaneous
writing. */

euid = geteuid();

/* If we are already running as the Exim user (even if that user is root),
we can go ahead and create in the current process. */

if (euid == exim_uid) *fd = log_create(buffer);

/* Otherwise, if we are root, do the creation in an exim:exim subprocess. If we
are neither exim nor root, creation is not attempted. */

else if (euid == root_uid) *fd = log_create_as_exim(buffer);

/* If we now have an open file, set the close-on-exec flag and return. */

if (*fd >= 0)
  {
#ifndef O_CLOEXEC
  (void)fcntl(*fd, F_SETFD, fcntl(*fd, F_GETFD) | FD_CLOEXEC);
#endif
  return;
  }

/* Creation failed. There are some circumstances in which we get here when
the effective uid is not root or exim, which is the problem. (For example, a
non-setuid binary with log_arguments set, called in certain ways.) Rather than
just bombing out, force the log to stderr and carry on if stderr is available.
*/

if (euid != root_uid && euid != exim_uid && log_stderr != NULL)
  {
  *fd = fileno(log_stderr);
  return;
  }

/* Otherwise this is a disaster. This call is deliberately ONLY to the panic
log. If possible, save a copy of the original line that was being logged. If we
are recursing (can't open the panic log either), the pointer will already be
set. */

if (!panic_save_buffer)
  if ((panic_save_buffer = US malloc(LOG_BUFFER_SIZE)))
    memcpy(panic_save_buffer, log_buffer, LOG_BUFFER_SIZE);

log_write(0, LOG_PANIC_DIE, "Cannot open %s log file \"%s\": %s: "
  "euid=%d egid=%d", log_names[type], buffer, strerror(errno), euid, getegid());
/* Never returns */
}

Project: exim

restore_socket_timeout(int fd, int get_ok, struct timeval * tvtmp, socklen_t vslen)
{
if (get_ok == 0)
  (void) setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, CS tvtmp, vslen);
}

Project: exim

check_proxy_protocol_host()
{
int rc;

if (  sender_host_address
   && (rc = verify_check_this_host(CUSS &hosts_proxy, NULL, NULL,
                           sender_host_address, NULL)) == OK)
  {
  DEBUG(D_receive)
    debug_printf("Detected proxy protocol configured host\n");
  proxy_session = TRUE;
  }
return proxy_session;
}

Project: exim
File: deliver.c

continue_closedown(void)
{
if (continue_transport)
  {
  transport_instance *t;
  for (t = transports; t; t = t->next)
    if (Ustrcmp(t->name, continue_transport) == 0)
      {
      if (t->info->closedown) (t->info->closedown)(t);
      break;
      }
  }
return DELIVER_NOT_ATTEMPTED;
}

Project: exim

host_name_lookup_byaddr(void)
{
int len;
uschar *s, *t;
struct hostent *hosts;
struct in_addr addr;
unsigned long time_msec = 0;	/* init to quieten dumb static analysis */

if (slow_lookup_log) time_msec = get_time_in_ms();

/* Lookup on IPv6 system */

#if HAVE_IPV6
if (Ustrchr(sender_host_address, ':') != NULL)
  {
  struct in6_addr addr6;
  if (inet_pton(AF_INET6, CS sender_host_address, &addr6) != 1)
    log_write(0, LOG_MAIN|LOG_PANIC_DIE, "unable to parse \"%s\" as an "
      "IPv6 address", sender_host_address);
  #if HAVE_GETIPNODEBYADDR
  hosts = getipnodebyaddr(CS &addr6, sizeof(addr6), AF_INET6, &h_errno);
  #else
  hosts = gethostbyaddr(CS &addr6, sizeof(addr6), AF_INET6);
  #endif
  }
else
  {
  if (inet_pton(AF_INET, CS sender_host_address, &addr) != 1)
    log_write(0, LOG_MAIN|LOG_PANIC_DIE, "unable to parse \"%s\" as an "
      "IPv4 address", sender_host_address);
  #if HAVE_GETIPNODEBYADDR
  hosts = getipnodebyaddr(CS &addr, sizeof(addr), AF_INET, &h_errno);
  #else
  hosts = gethostbyaddr(CS &addr, sizeof(addr), AF_INET);
  #endif
  }

/* Do lookup on IPv4 system */

#else
addr.s_addr = (S_ADDR_TYPE)inet_addr(CS sender_host_address);
hosts = gethostbyaddr(CS(&addr), sizeof(addr), AF_INET);
#endif

if (  slow_lookup_log
   && (time_msec = get_time_in_ms() - time_msec) > slow_lookup_log
   )
  log_long_lookup(US"name", sender_host_address, time_msec);

/* Failed to look up the host. */

if (hosts == NULL)
  {
  HDEBUG(D_host_lookup) debug_printf("IP address lookup failed: h_errno=%d\n",
    h_errno);
  return (h_errno == TRY_AGAIN || h_errno == NO_RECOVERY) ? DEFER : FAIL;
  }

/* It seems there are some records in the DNS that yield an empty name. We
treat this as non-existent. In some operating systems, this is returned as an
empty string; in others as a single dot. */

if (hosts->h_name == NULL || hosts->h_name[0] == 0 || hosts->h_name[0] == '.')
  {
  HDEBUG(D_host_lookup) debug_printf("IP address lookup yielded an empty name: "
    "treated as non-existent host name\n");
  return FAIL;
  }

/* Copy and lowercase the name, which is in static storage in many systems.
Put it in permanent memory. */

s = US hosts->h_name;
len = Ustrlen(s) + 1;
t = sender_host_name = store_get_perm(len);
while (*s != 0) *t++ = tolower(*s++);
*t = 0;

/* If the host has aliases, build a copy of the alias list */

if (hosts->h_aliases != NULL)
  {
  int count = 1;
  uschar **aliases, **ptr;
  for (aliases = USS hosts->h_aliases; *aliases != NULL; aliases++) count++;
  ptr = sender_host_aliases = store_get_perm(count * sizeof(uschar *));
  for (aliases = USS hosts->h_aliases; *aliases != NULL; aliases++)
    {
    uschar *s = *aliases;
    int len = Ustrlen(s) + 1;
    uschar *t = *ptr++ = store_get_perm(len);
    while (*s != 0) *t++ = tolower(*s++);
    *t = 0;
    }
  *ptr = NULL;
  }

return OK;
}

Project: exim

acl_eval(int where, uschar *s, uschar **user_msgptr, uschar **log_msgptr)
{
address_item adb;
address_item *addr = NULL;
int rc;

*user_msgptr = *log_msgptr = NULL;
sender_verified_failed = NULL;
ratelimiters_cmd = NULL;
log_reject_target = LOG_MAIN|LOG_REJECT;

if (where == ACL_WHERE_RCPT)
  {
  adb = address_defaults;
  addr = &adb;
  addr->address = expand_string(US"$local_part@$domain");
  addr->domain = deliver_domain;
  addr->local_part = deliver_localpart;
  addr->cc_local_part = deliver_localpart;
  addr->lc_local_part = deliver_localpart;
  }

acl_level++;
rc = acl_check_internal(where, addr, s, user_msgptr, log_msgptr);
acl_level--;
return rc;
}

Project: exim

one_pattern_match(uschar *name, int slen, BOOL has_addresses, uschar *pattern)
{
BOOL yield = FALSE;
header_line *h;
const pcre *re = NULL;

/* If the pattern is a regex, compile it. Bomb out if compiling fails; these
patterns are all constructed internally and should be valid. */

if (*pattern == '^') re = regex_must_compile(pattern, TRUE, FALSE);

/* Scan for the required header(s) and scan each one */

for (h = header_list; !yield && h != NULL; h = h->next)
  {
  if (h->type == htype_old || slen > h->slen ||
      strncmpic(name, h->text, slen) != 0)
    continue;

  /* If the header is a list of addresses, extract each one in turn, and scan
  it. A non-regex scan must be an exact match for the address. */

  if (has_addresses)
    {
    uschar *s = h->text + slen;

    while (!yield && *s != 0)
      {
      uschar *error, *next;
      uschar *e = parse_find_address_end(s, FALSE);
      int terminator = *e;
      int start, end, domain;

      /* Temporarily terminate the string at the address end while extracting
      the operative address within. */

      *e = 0;
      next = parse_extract_address(s, &error, &start, &end, &domain, FALSE);
      *e = terminator;

      /* Move on, ready for the next address */

      s = e;
      if (*s == ',') s++;

      /* If there is some kind of syntax error, just give up on this header
      line. */

      if (next == NULL) break;

      /* Otherwise, test for the pattern; a non-regex must be an exact match */

      yield = (re == NULL)?
        (strcmpic(next, pattern) == 0)
        :
        (pcre_exec(re, NULL, CS next, Ustrlen(next), 0, PCRE_EOPT, NULL, 0)
          >= 0);
      }
    }

  /* For headers that are not lists of addresses, scan the entire header line,
  and just require "contains" for non-regex patterns. */

  else
    {
    yield = (re == NULL)?
      (strstric(h->text, pattern, FALSE) != NULL)
      :
      (pcre_exec(re, NULL, CS h->text, h->slen, 0, PCRE_EOPT, NULL, 0) >= 0);
    }
  }

return yield;
}

Project: exim

exim_fail(const char * fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
exit(EXIT_FAILURE);
}

Project: exim

host_build_hostlist(host_item **anchor, const uschar *list, BOOL randomize)
{
int sep = 0;
int fake_mx = MX_NONE;          /* This value is actually -1 */
uschar *name;

if (list == NULL) return;
if (randomize) fake_mx--;       /* Start at -2 for randomizing */

*anchor = NULL;

while ((name = string_nextinlist(&list, &sep, NULL, 0)) != NULL)
  {
  host_item *h;

  if (name[0] == '+' && name[1] == 0)   /* "+" delimits a randomized group */
    {                                   /* ignore if not randomizing */
    if (randomize) fake_mx--;
    continue;
    }

  h = store_get(sizeof(host_item));
  h->name = name;
  h->address = NULL;
  h->port = PORT_NONE;
  h->mx = fake_mx;
  h->sort_key = randomize? (-fake_mx)*1000 + random_number(1000) : 0;
  h->status = hstatus_unknown;
  h->why = hwhy_unknown;
  h->last_try = 0;

  if (*anchor == NULL)
    {
    h->next = NULL;
    *anchor = h;
    }
  else
    {
    host_item *hh = *anchor;
    if (h->sort_key < hh->sort_key)
      {
      h->next = hh;
      *anchor = h;
      }
    else
      {
      while (hh->next != NULL && h->sort_key >= (hh->next)->sort_key)
        hh = hh->next;
      h->next = hh->next;
      hh->next = h;
      }
    }
  }
}

Project: exim

bdat_getbuf(unsigned * len)
{
uschar * buf;

if (chunking_data_left <= 0)
  { *len = 0; return NULL; }

if (*len > chunking_data_left) *len = chunking_data_left;
buf = lwr_receive_getbuf(len);	/* Either smtp_getbuf or tls_getbuf */
chunking_data_left -= *len;
return buf;
}

Project: exim

test_address(uschar *s, int flags, int *exit_value)
{
int start, end, domain;
uschar *parse_error = NULL;
uschar *address = parse_extract_address(s, &parse_error, &start, &end, &domain,
  FALSE);
if (address == NULL)
  {
  fprintf(stdout, "syntax error: %s\n", parse_error);
  *exit_value = 2;
  }
else
  {
  int rc = verify_address(deliver_make_addr(address,TRUE), stdout, flags, -1,
    -1, -1, NULL, NULL, NULL);
  if (rc == FAIL) *exit_value = 2;
    else if (rc == DEFER && *exit_value == 0) *exit_value = 1;
  }
}

Project: exim
File: deliver.c

timesince(struct timeval * diff, struct timeval * then)
{
gettimeofday(diff, NULL);
diff->tv_sec -= then->tv_sec;
if ((diff->tv_usec -= then->tv_usec) < 0)
  {
  diff->tv_sec--;
  diff->tv_usec += 1000*1000;
  }
}

Project: exim

header_testname(header_line *h, const uschar *name, int len, BOOL notdel)
{
uschar *tt;
if (h->type == '*' && notdel) return FALSE;
if (h->text == NULL || strncmpic(h->text, name, len) != 0) return FALSE;
tt = h->text + len;
while (*tt == ' ' || *tt == '\t') tt++;
return *tt == ':';
}