Exemple #1
0
BOOL
pipe_transport_entry(
  transport_instance *tblock,      /* data for this instantiation */
  address_item *addr)              /* address(es) we are working on */
{
pid_t pid, outpid;
int fd_in, fd_out, rc;
int envcount = 0;
int envsep = 0;
int expand_fail;
pipe_transport_options_block *ob =
  (pipe_transport_options_block *)(tblock->options_block);
int timeout = ob->timeout;
BOOL written_ok = FALSE;
BOOL expand_arguments;
const uschar **argv;
uschar *envp[50];
const uschar *envlist = ob->environment;
uschar *cmd, *ss;
uschar *eol = (ob->use_crlf)? US"\r\n" : US"\n";

DEBUG(D_transport) debug_printf("%s transport entered\n", tblock->name);

/* Set up for the good case */

addr->transport_return = OK;
addr->basic_errno = 0;

/* Pipes are not accepted as general addresses, but they can be generated from
.forward files or alias files. In those cases, the pfr flag is set, and the
command to be obeyed is pointed to by addr->local_part; it starts with the pipe
symbol. In other cases, the command is supplied as one of the pipe transport's
options. */

if (testflag(addr, af_pfr) && addr->local_part[0] == '|')
  {
  if (ob->force_command)
    {
    /* Enables expansion of $address_pipe into seperate arguments */
    setflag(addr, af_force_command);
    cmd = ob->cmd;
    expand_arguments = TRUE;
    expand_fail = PANIC;
    }
  else
    {
    cmd = addr->local_part + 1;
    while (isspace(*cmd)) cmd++;
    expand_arguments = testflag(addr, af_expand_pipe);
    expand_fail = FAIL;
    }
  }
else
  {
  cmd = ob->cmd;
  expand_arguments = TRUE;
  expand_fail = PANIC;
  }

/* If no command has been supplied, we are in trouble.
 * We also check for an empty string since it may be
 * coming from addr->local_part[0] == '|'
 */

if (cmd == NULL || *cmd == '\0')
  {
  addr->transport_return = DEFER;
  addr->message = string_sprintf("no command specified for %s transport",
    tblock->name);
  return FALSE;
  }

/* When a pipe is set up by a filter file, there may be values for $thisaddress
and numerical the variables in existence. These are passed in
addr->pipe_expandn for use here. */

if (expand_arguments && addr->pipe_expandn != NULL)
  {
  uschar **ss = addr->pipe_expandn;
  expand_nmax = -1;
  if (*ss != NULL) filter_thisaddress = *ss++;
  while (*ss != NULL)
    {
    expand_nstring[++expand_nmax] = *ss;
    expand_nlength[expand_nmax] = Ustrlen(*ss++);
    }
  }

/* The default way of processing the command is to split it up into arguments
here, and run it directly. This offers some security advantages. However, there
are installations that want by default to run commands under /bin/sh always, so
there is an option to do that. */

if (ob->use_shell)
  {
  if (!set_up_shell_command(&argv, cmd, expand_arguments, expand_fail, addr,
    tblock->name)) return FALSE;
  }
else if (!set_up_direct_command(&argv, cmd, expand_arguments, expand_fail, addr,
  tblock->name, ob)) return FALSE;

expand_nmax = -1;           /* Reset */
filter_thisaddress = NULL;

/* Set up the environment for the command. */

envp[envcount++] = string_sprintf("LOCAL_PART=%s", deliver_localpart);
envp[envcount++] = string_sprintf("LOGNAME=%s", deliver_localpart);
envp[envcount++] = string_sprintf("USER=%s", deliver_localpart);
envp[envcount++] = string_sprintf("LOCAL_PART_PREFIX=%#s",
  deliver_localpart_prefix);
envp[envcount++] = string_sprintf("LOCAL_PART_SUFFIX=%#s",
  deliver_localpart_suffix);
envp[envcount++] = string_sprintf("DOMAIN=%s", deliver_domain);
envp[envcount++] = string_sprintf("HOME=%#s", deliver_home);
envp[envcount++] = string_sprintf("MESSAGE_ID=%s", message_id);
envp[envcount++] = string_sprintf("PATH=%s", ob->path);
envp[envcount++] = string_sprintf("RECIPIENT=%#s%#s%#s@%#s",
  deliver_localpart_prefix, deliver_localpart, deliver_localpart_suffix,
  deliver_domain);
envp[envcount++] = string_sprintf("QUALIFY_DOMAIN=%s", qualify_domain_sender);
envp[envcount++] = string_sprintf("SENDER=%s", sender_address);
envp[envcount++] = US"SHELL=/bin/sh";

if (addr->host_list != NULL)
  envp[envcount++] = string_sprintf("HOST=%s", addr->host_list->name);

if (timestamps_utc) envp[envcount++] = US"TZ=UTC";
else if (timezone_string != NULL && timezone_string[0] != 0)
  envp[envcount++] = string_sprintf("TZ=%s", timezone_string);

/* Add any requested items */

if (envlist)
  {
  envlist = expand_cstring(envlist);
  if (envlist == NULL)
    {
    addr->transport_return = DEFER;
    addr->message = string_sprintf("failed to expand string \"%s\" "
      "for %s transport: %s", ob->environment, tblock->name,
      expand_string_message);
    return FALSE;
    }
  }

while ((ss = string_nextinlist(&envlist, &envsep, big_buffer, big_buffer_size))
       != NULL)
   {
   if (envcount > sizeof(envp)/sizeof(uschar *) - 2)
     {
     addr->transport_return = DEFER;
     addr->message = string_sprintf("too many environment settings for "
       "%s transport", tblock->name);
     return FALSE;
     }
   envp[envcount++] = string_copy(ss);
   }

envp[envcount] = NULL;

/* If the -N option is set, can't do any more. */

if (dont_deliver)
  {
  DEBUG(D_transport)
    debug_printf("*** delivery by %s transport bypassed by -N option",
      tblock->name);
  return FALSE;
  }


/* Handling the output from the pipe is tricky. If a file for catching this
output is provided, we could in theory just hand that fd over to the process,
but this isn't very safe because it might loop and carry on writing for
ever (which is exactly what happened in early versions of Exim). Therefore we
use the standard child_open() function, which creates pipes. We can then read
our end of the output pipe and count the number of bytes that come through,
chopping the sub-process if it exceeds some limit.

However, this means we want to run a sub-process with both its input and output
attached to pipes. We can't handle that easily from a single parent process
using straightforward code such as the transport_write_message() function
because the subprocess might not be reading its input because it is trying to
write to a full output pipe. The complication of redesigning the world to
handle this is too great - simpler just to run another process to do the
reading of the output pipe. */


/* As this is a local transport, we are already running with the required
uid/gid and current directory. Request that the new process be a process group
leader, so we can kill it and all its children on a timeout. */

if ((pid = child_open(USS argv, envp, ob->umask, &fd_in, &fd_out, TRUE)) < 0)
  {
  addr->transport_return = DEFER;
  addr->message = string_sprintf(
    "Failed to create child process for %s transport: %s", tblock->name,
      strerror(errno));
  return FALSE;
  }

/* Now fork a process to handle the output that comes down the pipe. */

if ((outpid = fork()) < 0)
  {
  addr->basic_errno = errno;
  addr->transport_return = DEFER;
  addr->message = string_sprintf(
    "Failed to create process for handling output in %s transport",
      tblock->name);
  (void)close(fd_in);
  (void)close(fd_out);
  return FALSE;
  }

/* This is the code for the output-handling subprocess. Read from the pipe
in chunks, and write to the return file if one is provided. Keep track of
the number of bytes handled. If the limit is exceeded, try to kill the
subprocess group, and in any case close the pipe and exit, which should cause
the subprocess to fail. */

if (outpid == 0)
  {
  int count = 0;
  (void)close(fd_in);
  set_process_info("reading output from |%s", cmd);
  while ((rc = read(fd_out, big_buffer, big_buffer_size)) > 0)
    {
    if (addr->return_file >= 0)
      if(write(addr->return_file, big_buffer, rc) != rc)
        DEBUG(D_transport) debug_printf("Problem writing to return_file\n");
    count += rc;
    if (count > ob->max_output)
      {
      DEBUG(D_transport) debug_printf("Too much output from pipe - killed\n");
      if (addr->return_file >= 0)
	{
        uschar *message = US"\n\n*** Too much output - remainder discarded ***\n";
        rc = Ustrlen(message);
        if(write(addr->return_file, message, rc) != rc)
          DEBUG(D_transport) debug_printf("Problem writing to return_file\n");
	}
      killpg(pid, SIGKILL);
      break;
      }
    }
  (void)close(fd_out);
  _exit(0);
  }

(void)close(fd_out);  /* Not used in this process */


/* Carrying on now with the main parent process. Attempt to write the message
to it down the pipe. It is a fallacy to think that you can detect write errors
when the sub-process fails to read the pipe. The parent process may complete
writing and close the pipe before the sub-process completes. We could sleep a
bit here to let the sub-process get going, but it may still not complete. So we
ignore all writing errors. (When in the test harness, we do do a short sleep so
any debugging output is likely to be in the same order.) */

if (running_in_test_harness) millisleep(500);

DEBUG(D_transport) debug_printf("Writing message to pipe\n");

/* Arrange to time out writes if there is a timeout set. */

if (timeout > 0)
  {
  sigalrm_seen = FALSE;
  transport_write_timeout = timeout;
  }

/* Reset the counter of bytes written */

transport_count = 0;

/* First write any configured prefix information */

if (ob->message_prefix != NULL)
  {
  uschar *prefix = expand_string(ob->message_prefix);
  if (prefix == NULL)
    {
    addr->transport_return = search_find_defer? DEFER : PANIC;
    addr->message = string_sprintf("Expansion of \"%s\" (prefix for %s "
      "transport) failed: %s", ob->message_prefix, tblock->name,
      expand_string_message);
    return FALSE;
    }
  if (!transport_write_block(fd_in, prefix, Ustrlen(prefix)))
    goto END_WRITE;
  }

/* If the use_bsmtp option is set, we need to write SMTP prefix information.
The various different values for batching are handled outside; if there is more
than one address available here, all must be included. Force SMTP dot-handling.
*/

if (ob->use_bsmtp)
  {
  address_item *a;

  if (!transport_write_string(fd_in, "MAIL FROM:<%s>%s", return_path, eol))
    goto END_WRITE;

  for (a = addr; a != NULL; a = a->next)
    {
    if (!transport_write_string(fd_in,
        "RCPT TO:<%s>%s",
        transport_rcpt_address(a, tblock->rcpt_include_affixes),
        eol))
      goto END_WRITE;
    }

  if (!transport_write_string(fd_in, "DATA%s", eol)) goto END_WRITE;
  }

/* Now the actual message - the options were set at initialization time */

if (!transport_write_message(addr, fd_in, ob->options, 0, tblock->add_headers,
  tblock->remove_headers, ob->check_string, ob->escape_string,
  tblock->rewrite_rules, tblock->rewrite_existflags))
    goto END_WRITE;

/* Now any configured suffix */

if (ob->message_suffix != NULL)
  {
  uschar *suffix = expand_string(ob->message_suffix);
  if (suffix == NULL)
    {
    addr->transport_return = search_find_defer? DEFER : PANIC;
    addr->message = string_sprintf("Expansion of \"%s\" (suffix for %s "
      "transport) failed: %s", ob->message_suffix, tblock->name,
      expand_string_message);
    return FALSE;
    }
  if (!transport_write_block(fd_in, suffix, Ustrlen(suffix)))
    goto END_WRITE;
  }

/* If local_smtp, write the terminating dot. */

if (ob->use_bsmtp && !transport_write_string(fd_in, ".%s", eol))
  goto END_WRITE;

/* Flag all writing completed successfully. */

written_ok = TRUE;

/* Come here if there are errors during writing. */

END_WRITE:

/* OK, the writing is now all done. Close the pipe. */

(void) close(fd_in);

/* Handle errors during writing. For timeouts, set the timeout for waiting for
the child process to 1 second. If the process at the far end of the pipe died
without reading all of it, we expect an EPIPE error, which should be ignored.
We used also to ignore WRITEINCOMPLETE but the writing function is now cleverer
at handling OS where the death of a pipe doesn't give EPIPE immediately. See
comments therein. */

if (!written_ok)
  {
  if (errno == ETIMEDOUT)
    {
    addr->message = string_sprintf("%stimeout while writing to pipe",
      transport_filter_timed_out? "transport filter " : "");
    addr->transport_return = ob->timeout_defer? DEFER : FAIL;
    timeout = 1;
    }
  else if (errno == EPIPE)
    {
    debug_printf("transport error EPIPE ignored\n");
    }
  else
    {
    addr->transport_return = PANIC;
    addr->basic_errno = errno;
    if (errno == ERRNO_CHHEADER_FAIL)
      addr->message =
        string_sprintf("Failed to expand headers_add or headers_remove: %s",
          expand_string_message);
    else if (errno == ERRNO_FILTER_FAIL)
      addr->message = string_sprintf("Transport filter process failed (%d)%s",
      addr->more_errno,
      (addr->more_errno == EX_EXECFAILED)? ": unable to execute command" : "");
    else if (errno == ERRNO_WRITEINCOMPLETE)
      addr->message = string_sprintf("Failed repeatedly to write data");
    else
      addr->message = string_sprintf("Error %d", errno);
    return FALSE;
    }
  }

/* Wait for the child process to complete and take action if the returned
status is nonzero. The timeout will be just 1 second if any of the writes
above timed out. */

if ((rc = child_close(pid, timeout)) != 0)
  {
  uschar *tmsg = (addr->message == NULL)? US"" :
    string_sprintf(" (preceded by %s)", addr->message);

  /* The process did not complete in time; kill its process group and fail
  the delivery. It appears to be necessary to kill the output process too, as
  otherwise it hangs on for some time if the actual pipe process is sleeping.
  (At least, that's what I observed on Solaris 2.5.1.) Since we are failing
  the delivery, that shouldn't cause any problem. */

  if (rc == -256)
    {
    killpg(pid, SIGKILL);
    kill(outpid, SIGKILL);
    addr->transport_return = ob->timeout_defer? DEFER : FAIL;
    addr->message = string_sprintf("pipe delivery process timed out%s", tmsg);
    }

  /* Wait() failed. */

  else if (rc == -257)
    {
    addr->transport_return = PANIC;
    addr->message = string_sprintf("Wait() failed for child process of %s "
      "transport: %s%s", tblock->name, strerror(errno), tmsg);
    }

  /* Since the transport_filter timed out we assume it has sent the child process
  a malformed or incomplete data stream.  Kill off the child process
  and prevent checking its exit status as it will has probably exited in error.
  This prevents the transport_filter timeout message from getting overwritten
  by the exit error which is not the cause of the problem. */

  else if (transport_filter_timed_out)
    {
    killpg(pid, SIGKILL);
    kill(outpid, SIGKILL);
    }

  /* Either the process completed, but yielded a non-zero (necessarily
  positive) status, or the process was terminated by a signal (rc will contain
  the negation of the signal number). Treat killing by signal as failure unless
  status is being ignored. By default, the message is bounced back, unless
  freeze_signal is set, in which case it is frozen instead. */

  else if (rc < 0)
    {
    if (ob->freeze_signal)
      {
      addr->transport_return = DEFER;
      addr->special_action = SPECIAL_FREEZE;
      addr->message = string_sprintf("Child process of %s transport (running "
        "command \"%s\") was terminated by signal %d (%s)%s", tblock->name, cmd,
        -rc, os_strsignal(-rc), tmsg);
      }
    else if (!ob->ignore_status)
      {
      addr->transport_return = FAIL;
      addr->message = string_sprintf("Child process of %s transport (running "
        "command \"%s\") was terminated by signal %d (%s)%s", tblock->name, cmd,
        -rc, os_strsignal(-rc), tmsg);
      }
    }

  /* For positive values (process terminated with non-zero status), we need a
  status code to request deferral. A number of systems contain the following
  line in sysexits.h:

      #define EX_TEMPFAIL 75

  with the description

      EX_TEMPFAIL -- temporary failure, indicating something that
         is not really an error.  In sendmail, this means
         that a mailer (e.g.) could not create a connection,
         and the request should be reattempted later.

  Based on this, we use exit code EX_TEMPFAIL as a default to mean "defer" when
  not ignoring the returned status. However, there is now an option that
  contains a list of temporary codes, with TEMPFAIL and CANTCREAT as defaults.

  Another case that needs special treatment is if execve() failed (typically
  the command that was given is a non-existent path). By default this is
  treated as just another failure, but if freeze_exec_fail is set, the reaction
  is to freeze the message rather than bounce the address. Exim used to signal
  this failure with EX_UNAVAILABLE, which is definined in many systems as

      #define EX_UNAVAILABLE  69

  with the description

      EX_UNAVAILABLE -- A service is unavailable.  This can occur
            if a support program or file does not exist.  This
            can also be used as a catchall message when something
            you wanted to do doesn't work, but you don't know why.

  However, this can be confused with a command that actually returns 69 because
  something *it* wanted is unavailable. At release 4.21, Exim was changed to
  use return code 127 instead, because this is what the shell returns when it
  is unable to exec a command. We define it as EX_EXECFAILED, and use it in
  child.c to signal execve() failure and other unexpected failures such as
  setuid() not working - though that won't be the case here because we aren't
  changing uid. */

  else
    {
    /* Always handle execve() failure specially if requested to */

    if (ob->freeze_exec_fail && (rc == EX_EXECFAILED))
      {
      addr->transport_return = DEFER;
      addr->special_action = SPECIAL_FREEZE;
      addr->message = string_sprintf("pipe process failed to exec \"%s\"%s",
        cmd, tmsg);
      }

    /* Otherwise take action only if not ignoring status */

    else if (!ob->ignore_status)
      {
      uschar *ss;
      int size, ptr, i;

      /* If temp_errors is "*" all codes are temporary. Initializion checks
      that it's either "*" or a list of numbers. If not "*", scan the list of
      temporary failure codes; if any match, the result is DEFER. */

      if (ob->temp_errors[0] == '*')
        addr->transport_return = DEFER;

      else
        {
        const uschar *s = ob->temp_errors;
        uschar *p;
        uschar buffer[64];
        int sep = 0;

        addr->transport_return = FAIL;
        while ((p = string_nextinlist(&s,&sep,buffer,sizeof(buffer))))
          if (rc == Uatoi(p)) { addr->transport_return = DEFER; break; }
        }

      /* Ensure the message contains the expanded command and arguments. This
      doesn't have to be brilliantly efficient - it is an error situation. */

      addr->message = string_sprintf("Child process of %s transport returned "
        "%d", tblock->name, rc);

      ptr = Ustrlen(addr->message);
      size = ptr + 1;

      /* If the return code is > 128, it often means that a shell command
      was terminated by a signal. */

      ss = (rc > 128)?
        string_sprintf("(could mean shell command ended by signal %d (%s))",
          rc-128, os_strsignal(rc-128)) :
        US os_strexit(rc);

      if (*ss != 0)
        {
        addr->message = string_cat(addr->message, &size, &ptr, US" ", 1);
        addr->message = string_cat(addr->message, &size, &ptr,
          ss, Ustrlen(ss));
        }

      /* Now add the command and arguments */

      addr->message = string_cat(addr->message, &size, &ptr,
        US" from command:", 14);

      for (i = 0; i < sizeof(argv)/sizeof(int *) && argv[i] != NULL; i++)
        {
        BOOL quote = FALSE;
        addr->message = string_cat(addr->message, &size, &ptr, US" ", 1);
        if (Ustrpbrk(argv[i], " \t") != NULL)
          {
          quote = TRUE;
          addr->message = string_cat(addr->message, &size, &ptr, US"\"", 1);
          }
        addr->message = string_cat(addr->message, &size, &ptr, argv[i],
          Ustrlen(argv[i]));
        if (quote)
          addr->message = string_cat(addr->message, &size, &ptr, US"\"", 1);
        }

      /* Add previous filter timeout message, if present. */

      if (*tmsg != 0)
        addr->message = string_cat(addr->message, &size, &ptr, tmsg,
          Ustrlen(tmsg));

      addr->message[ptr] = 0;  /* Ensure concatenated string terminated */
      }
    }
  }

/* Ensure all subprocesses (in particular, the output handling process)
are complete before we pass this point. */

while (wait(&rc) >= 0);

DEBUG(D_transport) debug_printf("%s transport yielded %d\n", tblock->name,
  addr->transport_return);

/* If there has been a problem, the message in addr->message contains details
of the pipe command. We don't want to expose these to the world, so we set up
something bland to return to the sender. */

if (addr->transport_return != OK)
  addr->user_message = US"local delivery failed";

return FALSE;
}
Exemple #2
0
uschar *
dkim_exim_sign(int dkim_fd, uschar * dkim_private_key,
		const uschar * dkim_domain, uschar * dkim_selector,
		uschar * dkim_canon, uschar * dkim_sign_headers)
{
int sep = 0;
uschar *seen_items = NULL;
int seen_items_size = 0;
int seen_items_offset = 0;
uschar itembuf[256];
uschar *dkim_canon_expanded;
uschar *dkim_sign_headers_expanded;
uschar *dkim_private_key_expanded;
pdkim_ctx *ctx = NULL;
uschar *rc = NULL;
uschar *sigbuf = NULL;
int sigsize = 0;
int sigptr = 0;
pdkim_signature *signature;
int pdkim_canon;
int pdkim_rc;
int sread;
char buf[4096];
int save_errno = 0;
int old_pool = store_pool;

store_pool = POOL_MAIN;

if (!(dkim_domain = expand_cstring(dkim_domain)))
  {
  /* expansion error, do not send message. */
  log_write(0, LOG_MAIN | LOG_PANIC, "failed to expand "
	     "dkim_domain: %s", expand_string_message);
  rc = NULL;
  goto CLEANUP;
  }

/* Set $dkim_domain expansion variable to each unique domain in list. */

while ((dkim_signing_domain = string_nextinlist(&dkim_domain, &sep,
				   itembuf, sizeof(itembuf))))
  {
  if (!dkim_signing_domain || dkim_signing_domain[0] == '\0')
    continue;

  /* Only sign once for each domain, no matter how often it
  appears in the expanded list. */

  if (seen_items)
    {
    const uschar *seen_items_list = seen_items;
    if (match_isinlist(dkim_signing_domain,
			&seen_items_list, 0, NULL, NULL, MCL_STRING, TRUE,
			NULL) == OK)
      continue;

    seen_items =
      string_append(seen_items, &seen_items_size, &seen_items_offset, 1, ":");
    }

  seen_items =
    string_append(seen_items, &seen_items_size, &seen_items_offset, 1,
		 dkim_signing_domain);
  seen_items[seen_items_offset] = '\0';

  /* Set up $dkim_selector expansion variable. */

  if (!(dkim_signing_selector = expand_string(dkim_selector)))
    {
    log_write(0, LOG_MAIN | LOG_PANIC, "failed to expand "
	       "dkim_selector: %s", expand_string_message);
    rc = NULL;
    goto CLEANUP;
    }

  /* Get canonicalization to use */

  dkim_canon_expanded = dkim_canon ? expand_string(dkim_canon) : US"relaxed";
  if (!dkim_canon_expanded)
    {
    /* expansion error, do not send message. */
    log_write(0, LOG_MAIN | LOG_PANIC, "failed to expand "
	       "dkim_canon: %s", expand_string_message);
    rc = NULL;
    goto CLEANUP;
    }

  if (Ustrcmp(dkim_canon_expanded, "relaxed") == 0)
    pdkim_canon = PDKIM_CANON_RELAXED;
  else if (Ustrcmp(dkim_canon_expanded, "simple") == 0)
    pdkim_canon = PDKIM_CANON_SIMPLE;
  else
    {
    log_write(0, LOG_MAIN,
	       "DKIM: unknown canonicalization method '%s', defaulting to 'relaxed'.\n",
	       dkim_canon_expanded);
    pdkim_canon = PDKIM_CANON_RELAXED;
    }

  dkim_sign_headers_expanded = NULL;
  if (dkim_sign_headers)
    if (!(dkim_sign_headers_expanded = expand_string(dkim_sign_headers)))
      {
      log_write(0, LOG_MAIN | LOG_PANIC, "failed to expand "
		 "dkim_sign_headers: %s", expand_string_message);
      rc = NULL;
      goto CLEANUP;
      }
    			/* else pass NULL, which means default header list */

  /* Get private key to use. */

  if (!(dkim_private_key_expanded = expand_string(dkim_private_key)))
    {
    log_write(0, LOG_MAIN | LOG_PANIC, "failed to expand "
	       "dkim_private_key: %s", expand_string_message);
    rc = NULL;
    goto CLEANUP;
    }

  if (  Ustrlen(dkim_private_key_expanded) == 0
     || Ustrcmp(dkim_private_key_expanded, "0") == 0
     || Ustrcmp(dkim_private_key_expanded, "false") == 0
     )
    continue;		/* don't sign, but no error */

  if (dkim_private_key_expanded[0] == '/')
    {
    int privkey_fd = 0;

    /* Looks like a filename, load the private key. */

    memset(big_buffer, 0, big_buffer_size);
    privkey_fd = open(CS dkim_private_key_expanded, O_RDONLY);
    if (privkey_fd < 0)
      {
      log_write(0, LOG_MAIN | LOG_PANIC, "unable to open "
		 "private key file for reading: %s",
		 dkim_private_key_expanded);
      rc = NULL;
      goto CLEANUP;
      }

    if (read(privkey_fd, big_buffer, big_buffer_size - 2) < 0)
      {
      log_write(0, LOG_MAIN|LOG_PANIC, "unable to read private key file: %s",
		 dkim_private_key_expanded);
      rc = NULL;
      goto CLEANUP;
      }

    (void) close(privkey_fd);
    dkim_private_key_expanded = big_buffer;
    }

  ctx = pdkim_init_sign(PDKIM_INPUT_SMTP,
			 (char *) dkim_signing_domain,
			 (char *) dkim_signing_selector,
			 (char *) dkim_private_key_expanded);
  pdkim_set_debug_stream(ctx, debug_file);
  pdkim_set_optional(ctx,
		      (char *) dkim_sign_headers_expanded,
		      NULL,
		      pdkim_canon,
		      pdkim_canon, -1, PDKIM_ALGO_RSA_SHA256, 0, 0);

  lseek(dkim_fd, 0, SEEK_SET);

  while ((sread = read(dkim_fd, &buf, 4096)) > 0)
    if (pdkim_feed(ctx, buf, sread) != PDKIM_OK)
      {
      rc = NULL;
      goto CLEANUP;
      }

  /* Handle failed read above. */
  if (sread == -1)
    {
    debug_printf("DKIM: Error reading -K file.\n");
    save_errno = errno;
    rc = NULL;
    goto CLEANUP;
    }

  if ((pdkim_rc = pdkim_feed_finish(ctx, &signature)) != PDKIM_OK)
    {
    log_write(0, LOG_MAIN|LOG_PANIC, "DKIM: signing failed (RC %d)", pdkim_rc);
    rc = NULL;
    goto CLEANUP;
    }

  sigbuf = string_append(sigbuf, &sigsize, &sigptr, 2,
			  US signature->signature_header, US"\r\n");

  pdkim_free_ctx(ctx);
  ctx = NULL;
  }

if (sigbuf)
  {
  sigbuf[sigptr] = '\0';
  rc = sigbuf;
  }
else
  rc = US"";

CLEANUP:
if (ctx)
  pdkim_free_ctx(ctx);
store_pool = old_pool;
errno = save_errno;
return rc;
}