/*
**  Copyright (c) 2005-2009 Sendmail, Inc. and its suppliers.
**	All rights reserved.
**
**  Copyright (c) 2009-2015, The Trusted Domain Project.  All rights reserved.
**
**  Copyright (c) 2026, PhoenixDKIM contributors. All rights reserved.
*/

#include "build-config.h"
#include "build-version.h"

#ifndef _POSIX_PTHREAD_SEMANTICS
# define _POSIX_PTHREAD_SEMANTICS
#endif /* ! _POSIX_PTHREAD_SEMANTICS */

/* system includes */
#include <sys/types.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/wait.h>
#ifdef HAVE_ISO_LIMITS_ISO_H
# include <iso/limits_iso.h>
#endif /* HAVE_ISO_LIMITS_ISO_H */
#ifdef HAVE_LIMITS_H
# include <limits.h>
#endif /* HAVE_LIMITS_H */
#ifdef __linux__
# include <sys/prctl.h>
#endif /* __linux__ */
#ifdef USE_LUA
# include <netinet/in.h>
# include <arpa/inet.h>
#endif /* USE_LUA */
#ifdef AF_INET6
# include <arpa/inet.h>
#endif /* AF_INET6 */
#ifdef HAVE_STDBOOL_H
# include <stdbool.h>
#endif /* HAVE_STDBOOL_H */
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>
#include <sysexits.h>
#include <errno.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <math.h>
#include <assert.h>
#include <ctype.h>
#include <fcntl.h>
#include <pthread.h>
#include <netdb.h>
#include <signal.h>
#include <regex.h>

#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/pem.h>

#ifdef HAVE_LIBCURL
# include <curl/curl.h>
#endif /* HAVE_LIBCURL */

#ifdef HAVE_LIBSYSTEMD
# include <systemd/sd-daemon.h>
#endif /* HAVE_LIBSYSTEMD */

#ifdef HAVE_PATHS_H
# include <paths.h>
#endif /* HAVE_PATHS_H */
#ifndef _PATH_DEVNULL
# define _PATH_DEVNULL		"/dev/null"
#endif /* ! _PATH_DEVNULL */

/* libmilter includes */
#include "libmilter/mfapi.h"

#ifdef USE_LUA
/* LUA includes */
# include <lua.h>
#endif /* USE_LUA */


/* libopendkim includes */
#include "dkim.h"

/* libbsd if found */
#ifdef USE_BSD_H
# include <bsd/string.h>
#endif /* USE_BSD_H */

/* libstrl if needed */
#ifdef USE_STRL_H
# include <strl.h>
#endif /* USE_STRL_H */

/* opendkim includes */
#include "config.h"
#include "opendkim-db.h"
#include "opendkim-config.h"
#include "opendkim-crypto.h"
#ifdef USE_LUA
# define DKIMF_LUA_PROTOTYPES
#endif /* USE_LUA */
#include "opendkim.h"
#include "opendkim-ar.h"
#include "opendkim-arf.h"
#include "opendkim-dns.h"
#ifdef USE_LUA
# include "opendkim-lua.h"
#endif /* USE_LUA */
#include "util.h"
#include "test.h"

/* macros */
#define CMDLINEOPTS	"Ab:c:d:De:fF:Ggk:lL:no:p:P:Qrs:S:t:T:u:vVWx:X?"

#ifndef MIN
# define MIN(x,y)	((x) < (y) ? (x) : (y))
#endif /* ! MIN */

#define	DKIMF_MILTER_ACCEPT	0
#define	DKIMF_MILTER_REJECT	1
#define	DKIMF_MILTER_TEMPFAIL	2
#define	DKIMF_MILTER_DISCARD	3
#define	DKIMF_MILTER_QUARANTINE	4
#define	DKIMF_MILTER_NEUTRAL	5

/*
**  ADDRLIST -- address list
*/

struct addrlist
{
	char *		a_addr;			/* address */
	struct addrlist * a_next;		/* next record */
};

/*
**  HANDLING -- message handling requests
*/

struct handling
{
	int		hndl_nosig;		/* no signature */
	int		hndl_badsig;		/* bad signature */
	int		hndl_nokey;		/* no key in DNS */
	int		hndl_dnserr;		/* DNS error */
	int		hndl_internal;		/* internal error */
	int		hndl_security;		/* security concerns */
	int		hndl_siggen;		/* sig generation errors */
	int		hndl_weakalg;		/* deprecated signing algorithm */
};

struct handling defaults =
{
	DKIMF_MILTER_ACCEPT,			/* nosig */
	DKIMF_MILTER_ACCEPT,			/* badsig */
	DKIMF_MILTER_ACCEPT,			/* nokey */
	DKIMF_MILTER_TEMPFAIL,			/* dnserr */
	DKIMF_MILTER_TEMPFAIL,			/* internal */
	DKIMF_MILTER_TEMPFAIL,			/* security */
	DKIMF_MILTER_REJECT,			/* siggen */
	DKIMF_MILTER_NEUTRAL			/* weakalg */
};

/*
**  LUA_GLOBAL -- linked list of Lua globals
*/

struct lua_global
{
	int		lg_type;
	char *		lg_name;
	void *		lg_value;
	struct lua_global * lg_next;
};

/*
**  CONFIG -- configuration data
*/

struct dkimf_config
{
	_Bool		conf_disablecryptoinit;	/* initialize SSL libs? */
	_Bool		conf_weaksyntax;	/* do weaker syntax checking */
	_Bool		conf_passmalformed;	/* pass malformed messages */
	_Bool		conf_logresults;	/* log all results */
	_Bool		conf_dnsconnect;	/* request TCP mode from DNS */
	_Bool		conf_capture;		/* capture unknown errors */
	_Bool		conf_restrace;		/* resolver tracing? */
	_Bool		conf_acceptdk;		/* accept DK keys? */
	_Bool		conf_addswhdr;		/* add identifying header? */
	_Bool		conf_blen;		/* use "l=" when signing */
	_Bool		conf_ztags;		/* use "z=" when signing */
	_Bool		conf_alwaysaddar;	/* always add Auth-Results:? */
	_Bool		conf_reqreports;	/* request reports */
	_Bool		conf_sendreports;	/* signature failure reports */
	_Bool		conf_reqhdrs;		/* required header checks */
	_Bool		conf_authservidwithjobid; /* use jobids in A-R headers */
	_Bool		conf_subdomains;	/* sign subdomains */
	_Bool		conf_remsigs;		/* remove current signatures? */
	_Bool		conf_remarall;		/* remove all matching ARs? */
	_Bool		conf_keepar;		/* keep our ARs? */
	_Bool		conf_dolog;		/* syslog interesting stuff? */
	_Bool		conf_dolog_success;	/* syslog successes too? */
	_Bool		conf_milterv2;		/* using milter v2? */
	_Bool		conf_fixcrlf;		/* fix bare CRs and LFs? */
	_Bool		conf_logwhy;		/* log mode decision logic */
	_Bool		conf_allowsha1only;	/* allow rsa-sha1 verifying */
	_Bool		conf_stricthdrs;	/* strict header checks */
	_Bool		conf_keeptmpfiles;	/* keep temporary files */
	_Bool		conf_multisig;		/* multiple signatures */
	_Bool		conf_enablecores;	/* enable coredumps */
	_Bool		conf_noheaderb;		/* suppress "header.b" */
	_Bool		conf_safekeys;		/* check key permissions */
	_Bool		conf_checksigningtable; /* check keys on dkimf_config_load */
	_Bool		conf_resignall;		/* resign unverified mail */
	unsigned int	conf_mode;		/* operating mode */
	unsigned int	conf_refcnt;		/* reference count */
	unsigned int	conf_dnstimeout;	/* DNS timeout */
	unsigned int	conf_maxhdrsz;		/* max header bytes */
	unsigned int	conf_maxverify;		/* max sigs to verify */
	unsigned int	conf_minkeybits;	/* min key size (bits) */
	unsigned int	conf_boguskey;		/* bogus key action */
	unsigned int	conf_unprotectedkey;	/* unprotected key action */
	int		conf_clockdrift;	/* tolerable clock drift */
	int		conf_sigmintype;	/* signature minimum type */
	size_t		conf_sigmin;		/* signature minimum */
	size_t		conf_keylen;		/* size of secret key */
#ifdef USE_LUA
	size_t		conf_screenfuncsz;	/* screening function size */
	size_t		conf_setupfuncsz;	/* setup function size */
	size_t		conf_finalfuncsz;	/* final function size */
#endif /* USE_LUA */
	ssize_t		conf_signbytes;		/* bytes to sign */
	dkim_canon_t 	conf_hdrcanon;		/* canon. method for headers */
	dkim_canon_t 	conf_bodycanon;		/* canon. method for body */
	unsigned long	conf_sigttl;		/* signature TTLs */
	dkim_alg_t	conf_signalg;		/* signing algorithm */
	struct config *	conf_data;		/* configuration data */
#ifdef HAVE_LIBCURL
	char *		conf_smtpuri;		/* outgoing mail URI */
#endif /* HAVE_LIBCURL */
	char *		conf_authservid;	/* authserv-id */
	char *		conf_keyfile;		/* key file for single key */
	char *		conf_keytable;		/* key table */
	char *		conf_signtable;		/* signing table */
	char *		conf_peerfile;		/* peer file */
	char *		conf_internalfile;	/* internal hosts file */
	char *		conf_externalfile;	/* external hosts file */
	char *		conf_exemptfile;	/* exempt domains file */
	char *		conf_tmpdir;		/* temp directory */
	char *		conf_omitlist;		/* omit header list */
	char *		conf_domlist;		/* signing domain list */
	char *		conf_signalgstr;	/* signature algorithm string */
	char *		conf_modestr;		/* mode string */
	char *		conf_canonstr;		/* canonicalization(s) string */
	char *		conf_siglimit;		/* signing limits */
	char *		conf_chroot;		/* chroot(2) directory */
	const char *	conf_selectcanonhdr;	/* canon select header name */
	u_char *	conf_selector;		/* key selector */
	char *		conf_resign;		/* resign mail to */
	char *		conf_sendermacro;	/* macro containing sender */
	char *		conf_testdnsdata;	/* test DNS data */
	char *		conf_identityhdr;	/* identity header */
	_Bool		conf_rmidentityhdr;	/* remove identity header */
	char *		conf_diagdir;		/* diagnostics directory */
	char *		conf_reportaddr;	/* report sender address */
	char *		conf_reportaddrbcc;	/* report repcipient address as bcc */
	const char *	conf_mtacommand;	/* MTA command (reports) */
	char *		conf_redirect;		/* redirect failures to */
#ifdef USE_LUA
	char *		conf_screenscript;	/* Lua script: screening */
	void *		conf_screenfunc;	/* Lua function: screening */
	char *		conf_setupscript;	/* Lua script: setup */
	void *		conf_setupfunc;		/* Lua function: setup */
	char *		conf_finalscript;	/* Lua script: final */
	void *		conf_finalfunc;		/* Lua function: final */
#endif /* USE_LUA */
	unsigned char *	conf_seckey;		/* secret key data (owned) */
	char *		conf_nslist;		/* replacement NS list */
	char *		conf_trustanchorpath;	/* trust anchor file */
	char *		conf_resolverconfig;	/* resolver config file */
	DKIMF_DB	conf_testdnsdb;		/* test TXT records */
	DKIMF_DB	conf_bldb;		/* l= recipients (DB) */
	DKIMF_DB	conf_domainsdb;		/* domains to sign (DB) */
	DKIMF_DB	conf_omithdrdb;		/* headers to omit (DB) */
	char **		conf_omithdrs;		/* headers to omit (array) */
	DKIMF_DB	conf_signhdrsdb;	/* headers to sign (DB) */
	char **		conf_signhdrs;		/* headers to sign (array) */
	DKIMF_DB	conf_senderhdrsdb;	/* sender headers (DB) */
	char **		conf_senderhdrs;	/* sender headers (array) */
	DKIMF_DB	conf_mtasdb;		/* MTA ports to sign (DB) */
	char **		conf_mtas;		/* MTA ports to sign (array) */
	DKIMF_DB	conf_remardb;		/* A-R removal list (DB) */
	char **		conf_remar;		/* A-R removal list (array) */
	DKIMF_DB	conf_mbsdb;		/* must-be-signed hdrs (DB) */
	char **		conf_mbs;		/* must-be-signed (array) */
	DKIMF_DB	conf_oversigndb;	/* fields to over-sign (DB) */
	char **		conf_oversignhdrs;	/*   "    "     "    (array) */
	DKIMF_DB	conf_dontsigntodb;	/* don't-sign-to addrs (DB) */
	DKIMF_DB	conf_thirdpartydb;	/* trustsigsfrom DB */
	DKIMF_DB	conf_macrosdb;		/* macros/values (DB) */
	char **		conf_macros;		/* macros/values to check */
	regex_t **	conf_nosignpats;	/* do-not-sign patterns */
	DKIMF_DB	conf_peerdb;		/* DB of "peers" */
	DKIMF_DB	conf_internal;		/* DB of "internal" hosts */
	DKIMF_DB	conf_exignore;		/* "external ignore" host DB */
	DKIMF_DB	conf_exemptdb;		/* exempt domains DB */
	DKIMF_DB	conf_keytabledb;	/* key table DB */
	DKIMF_DB	conf_signtabledb;	/* signing table DB */
	DKIMF_DB	conf_resigndb;		/* resigning addresses */
	DKIM_LIB *	conf_libopendkim;	/* DKIM library handle */
	struct handling	conf_handling;		/* message handling */
};

/*
**  MSGCTX -- message context, containing transaction-specific data
*/

typedef struct msgctx * msgctx;
struct msgctx
{
	_Bool		mctx_internal;		/* internal source? */
	_Bool		mctx_bldbdone;		/* BodyLengthDB applied? */
	_Bool		mctx_eom;		/* in EOM? (enables progress) */
	_Bool		mctx_addheader;		/* Authentication-Results: */
	_Bool		mctx_headeronly;	/* in EOM, only add headers */
	_Bool		mctx_ltag;		/* sign with l= tag? */
	_Bool		mctx_capture;		/* capture message? */
	_Bool		mctx_susp;		/* suspicious message? */
	_Bool		mctx_resign;		/* arrange to re-sign */
#ifdef USE_LUA
	int		mctx_mresult;		/* SMFI status code */
#endif /* USE_LUA */
	int		mctx_status;		/* status to report back */
	dkim_canon_t	mctx_hdrcanon;		/* header canonicalization */
	dkim_canon_t	mctx_bodycanon;		/* body canonicalization */
	dkim_alg_t	mctx_signalg;		/* signature algorithm */
	int		mctx_queryalg;		/* query algorithm */
	size_t		mctx_hdrbytes;		/* header space accumulated */
	struct dkimf_dstring * mctx_tmpstr;	/* temporary string */
	const u_char *	mctx_jobid;		/* job ID */
	u_char *	mctx_laddr;		/* address triggering l= */
	DKIM *		mctx_dkimv;		/* verification handle */
	struct Header *	mctx_hqhead;		/* header queue head */
	struct Header *	mctx_hqtail;		/* header queue tail */
	struct signreq * mctx_srhead;		/* signature request head */
	struct signreq * mctx_srtail;		/* signature request tail */
	struct addrlist * mctx_rcptlist;	/* recipient list */
	struct lua_global * mctx_luaglobalh;	/* Lua global list */
	struct lua_global * mctx_luaglobalt;	/* Lua global list */
	unsigned char	mctx_envfrom[MAXADDRESS + 1];
						/* envelope sender */
	unsigned char	mctx_domain[DKIM_MAXHOSTNAMELEN + 1];
						/* primary domain */
	unsigned char	mctx_dkimar[DKIM_MAXHEADER + 1];
						/* DKIM Auth-Results content */
};

/*
**  CONNCTX -- connection context, containing thread-specific data
*/

typedef struct connctx * connctx;
struct connctx
{
	_Bool		cctx_milterv2;		/* milter v2 available */
	_Bool		cctx_noleadspc;		/* no leading spaces */
	char		cctx_host[DKIM_MAXHOSTNAMELEN + 1];
						/* hostname */
	struct sockaddr_storage	cctx_ip;	/* IP info */
	struct dkimf_config * cctx_config;	/* configuration in use */
	struct msgctx *	cctx_msg;		/* message context */
};

/*
**  LOOKUP -- lookup table
*/

struct lookup
{
	const char *	str;
	int		code;
};

#define	HNDL_DEFAULT		0
#define	HNDL_NOSIGNATURE	1
#define	HNDL_BADSIGNATURE	2
#define	HNDL_DNSERROR		3
#define	HNDL_INTERNAL		4
#define	HNDL_SECURITY		5
#define	HNDL_NOKEY		6
#define	HNDL_POLICYERROR	7
#define	HNDL_SIGGEN		9
#define	HNDL_WEAKALG		10

#define	DKIMF_MODE_SIGNER	0x01
#define	DKIMF_MODE_VERIFIER	0x02
#define	DKIMF_MODE_DEFAULT	(DKIMF_MODE_SIGNER|DKIMF_MODE_VERIFIER)

#define	DKIMF_STATUS_GOOD	0
#define	DKIMF_STATUS_BAD	1
#define	DKIMF_STATUS_NOKEY	2
#define	DKIMF_STATUS_KEYFAIL	3
#define	DKIMF_STATUS_REVOKED	4
#define	DKIMF_STATUS_NOSIGNATURE 5
#define	DKIMF_STATUS_BADFORMAT	6
#define	DKIMF_STATUS_PARTIAL	7
#define	DKIMF_STATUS_VERIFYERR	8
#define	DKIMF_STATUS_UNKNOWN	9
#define	DKIMF_STATUS_WEAKALG	10

#define SIGMIN_BYTES		0
#define SIGMIN_PERCENT		1
#define SIGMIN_MAXADD		2

#define	DELIMITER		"\001"

struct lookup dkimf_params[] =
{
	{ "badsignature",	HNDL_BADSIGNATURE },
	{ "default",		HNDL_DEFAULT },
	{ "dnserror",		HNDL_DNSERROR },
	{ "internalerror",	HNDL_INTERNAL },
	{ "keynotfound",	HNDL_NOKEY },
	{ "nosignature",	HNDL_NOSIGNATURE },
	{ "security",		HNDL_SECURITY },
	{ "signatureerror",	HNDL_SIGGEN },
	{ "weakalgorithm",	HNDL_WEAKALG },
	{ NULL,			-1 },
};

struct lookup dkimf_values[] =
{
	{ "a",			DKIMF_MILTER_ACCEPT },
	{ "accept",		DKIMF_MILTER_ACCEPT },
	{ "d",			DKIMF_MILTER_DISCARD },
	{ "discard",		DKIMF_MILTER_DISCARD },
	{ "n",			DKIMF_MILTER_NEUTRAL },
	{ "neutral",		DKIMF_MILTER_NEUTRAL },
#ifdef SMFIF_QUARANTINE
	{ "q",			DKIMF_MILTER_QUARANTINE },
	{ "quarantine",		DKIMF_MILTER_QUARANTINE },
#endif /* SMFIF_QUARANTINE */
	{ "r",			DKIMF_MILTER_REJECT },
	{ "reject",		DKIMF_MILTER_REJECT },
	{ "t",			DKIMF_MILTER_TEMPFAIL },
	{ "tempfail",		DKIMF_MILTER_TEMPFAIL },
	{ NULL,			-1 },
};

struct lookup dkimf_canon[] =
{
	{ "relaxed",		DKIM_CANON_RELAXED },
	{ "simple",		DKIM_CANON_SIMPLE },
	{ NULL,			-1 },
};

struct lookup dkimf_sign[] =
{
	{ "rsa-sha256",		DKIM_SIGN_RSASHA256 },
	#ifdef DKIM_SIGN_ED25519SHA256
	{ "ed25519-sha256",	DKIM_SIGN_ED25519SHA256 },
	#endif
	{ NULL,			-1 },
};

struct lookup log_facilities[] =
{
	{ "auth",		LOG_AUTH },
	{ "cron",		LOG_CRON },
	{ "daemon",		LOG_DAEMON },
	{ "kern",		LOG_KERN },
	{ "lpr",		LOG_LPR },
	{ "mail",		LOG_MAIL },
	{ "news",		LOG_NEWS },
	{ "security",		LOG_AUTH },       /* DEPRECATED */
	{ "syslog",		LOG_SYSLOG },
	{ "user",		LOG_USER },
	{ "uucp",		LOG_UUCP },
	{ "local0",		LOG_LOCAL0 },
	{ "local1",		LOG_LOCAL1 },
	{ "local2",		LOG_LOCAL2 },
	{ "local3",		LOG_LOCAL3 },
	{ "local4",		LOG_LOCAL4 },
	{ "local5",		LOG_LOCAL5 },
	{ "local6",		LOG_LOCAL6 },
	{ "local7",		LOG_LOCAL7 },
	{ NULL,			-1 }
};

#define DKIMF_KEYACTIONS_NONE	0
#define DKIMF_KEYACTIONS_NEUTRAL 1
#define DKIMF_KEYACTIONS_FAIL	2

struct lookup dkimf_keyactions[] =
{
	{ "none",		DKIMF_KEYACTIONS_NONE },
	{ "neutral",		DKIMF_KEYACTIONS_NEUTRAL },
	{ "fail",		DKIMF_KEYACTIONS_FAIL },
	{ NULL,			-1 },
};

struct lookup dkimf_statusstrings[] =
{
	{ "no error",				DKIMF_STATUS_GOOD },
	{ "bad signature",			DKIMF_STATUS_BAD },
	{ "key retrieval failed",		DKIMF_STATUS_NOKEY },
	{ "key retrieval timeout",		DKIMF_STATUS_KEYFAIL },
	{ "key revoked",			DKIMF_STATUS_REVOKED },
	{ "no signature",			DKIMF_STATUS_NOSIGNATURE },
	{ "bad message/signature format",	DKIMF_STATUS_BADFORMAT },
	{ "invalid partial signature",		DKIMF_STATUS_PARTIAL },
	{ "verification error",			DKIMF_STATUS_VERIFYERR },
	{ "unknown error",			DKIMF_STATUS_UNKNOWN },
	{ "deprecated signature algorithm",	DKIMF_STATUS_WEAKALG },
	{ NULL,					-1 }
};

/* PROTOTYPES */
#ifdef LEAK_TRACKING
void dkimf_debug_free(void *, char *, int);
void *dkim_debug_malloc(size_t, char *, int);
void *dkim_debug_realloc(void *, size_t, char *, int);

# define free(x)	dkimf_debug_free((x), __FILE__, __LINE__)
# define malloc(x)	dkimf_debug_malloc((x), __FILE__, __LINE__)
# define realloc(x,y)	dkimf_debug_realloc((x), (y), __FILE__, __LINE__)
#endif /* LEAK_TRACKING */

sfsistat mlfi_abort(SMFICTX *);
sfsistat mlfi_body(SMFICTX *, u_char *, size_t);
sfsistat mlfi_close(SMFICTX *);
sfsistat mlfi_connect(SMFICTX *, char *, _SOCK_ADDR *);
sfsistat mlfi_envfrom(SMFICTX *, char **);
sfsistat mlfi_envrcpt(SMFICTX *, char **);
sfsistat mlfi_eoh(SMFICTX *);
sfsistat mlfi_eom(SMFICTX *);
sfsistat mlfi_header(SMFICTX *, char *, char *);
sfsistat mlfi_negotiate(SMFICTX *, unsigned long, unsigned long,
                                        unsigned long, unsigned long,
                                        unsigned long *, unsigned long *,
                                        unsigned long *, unsigned long *);

static int dkimf_add_signrequest(struct dkimf_config *,
                                      struct msgctx *, DKIMF_DB,
                                      const char *, const char *, ssize_t);
sfsistat dkimf_addheader(SMFICTX *, const char *, const char *);
sfsistat dkimf_addrcpt(SMFICTX *, char *);
static int dkimf_apply_signtable(struct dkimf_config *, struct msgctx *,
                                      DKIMF_DB, DKIMF_DB,
                                      unsigned char *, unsigned char *, char *,
                                      size_t, _Bool);
sfsistat dkimf_chgheader(SMFICTX *, char *, int, char *);
static void dkimf_cleanup(SMFICTX *);
static void dkimf_config_reload(void);
sfsistat dkimf_delrcpt(SMFICTX *, char *);
static Header dkimf_findheader(msgctx, const char *, int);
static int dkimf_lookup_strtoint(const char *, struct lookup *);
void *dkimf_getpriv(SMFICTX *);
char *dkimf_getsymval(SMFICTX *, const char *);
sfsistat dkimf_insheader(SMFICTX *, int, const char *, const char *);
sfsistat dkimf_quarantine(SMFICTX *, const char *);
void dkimf_sendprogress(const void *);
sfsistat dkimf_setpriv(SMFICTX *, void *);
sfsistat dkimf_setreply(SMFICTX *, const char *, const char *, const char *);
static void dkimf_sigreport(connctx, struct dkimf_config *, const char *);

/* GLOBALS */
_Bool dolog;					/* logging? (exported) */
_Bool reload;					/* reload requested */
_Bool no_i_whine;				/* noted ${i} is undefined */
_Bool testmode;					/* test mode */
_Bool allowdeprecated;				/* allow deprecated config values */
_Bool init_checksigningtable;			/* initializing value for CheckSigningTable */
_Bool use_cf_checksigningtable;			/* use CheckSigningTable from config file? */
_Bool die;					/* global "die" flag */
int diesig;					/* signal to distribute */
int thread_count;				/* thread count */
char *progname;					/* program name */
char *sock;					/* listening socket */
const char *conffile;				/* configuration file */
struct dkimf_config *curconf;			/* current configuration */
char reportcmd[BUFRSZ + 1];			/* reporting command */
/* user@host: each part bounded by DKIM_MAXHOSTNAMELEN (same value as LOGIN_NAME_MAX on Linux) */
char reportaddr[2 * DKIM_MAXHOSTNAMELEN + 2];	/* reporting address */
char myhostname[DKIM_MAXHOSTNAMELEN + 1];	/* hostname */
pthread_mutex_t conf_lock;			/* config lock */
pthread_mutex_t pwdb_lock;			/* passwd/group lock */

/* Other useful definitions */
#define CRLF			"\r\n"		/* CRLF */

/* MACROS */
#define	JOBID(x)	((x) == NULL ? JOBIDUNKNOWN : (const char *) (x))
#define	TRYFREE(x)	do { \
				if ((x) != NULL) \
				{ \
					free(x); \
					(x) = NULL; \
				} \
			} while (0)
#define	DKIMF_EOHMACROS	"i {daemon_name} {auth_type} {auth_authen}"



/*
**  ==================================================================
**  BEGIN private section
*/

/*
**  DKIMF_GETPRIV -- wrapper for smfi_getpriv()
**
**  Parameters:
**  	ctx -- milter (or test) context
**
**  Return value:
**  	The stored private pointer, or NULL.
*/

void *
dkimf_getpriv(SMFICTX *ctx)
{
	assert(ctx != NULL);

	if (testmode)
		return dkimf_test_getpriv((void *) ctx);
	else
		return smfi_getpriv(ctx);
}

/*
**  DKIMF_SETPRIV -- wrapper for smfi_setpriv()
**
**  Parameters:
**  	ctx -- milter (or test) context
**
**  Return value:
**  	An sfsistat.
*/

sfsistat
dkimf_setpriv(SMFICTX *ctx, void *ptr)
{
	assert(ctx != NULL);

	if (testmode)
		return dkimf_test_setpriv((void *) ctx, ptr);
	else
		return smfi_setpriv(ctx, ptr);
}

/*
**  DKIMF_INSHEADER -- wrapper for smfi_insheader()
**
**  Parameters:
**  	ctx -- milter (or test) context
**  	idx -- index at which to insert
**  	hname -- header name
**  	hvalue -- header value
**
**  Return value:
**  	An sfsistat.
*/

sfsistat
dkimf_insheader(SMFICTX *ctx, int idx, const char *hname, const char *hvalue)
{
	assert(ctx != NULL);
	assert(hname != NULL);
	assert(hvalue != NULL);

	if (testmode)
	{
		return dkimf_test_insheader(ctx, idx, hname, hvalue);
	}
	else
	{
		/*
		**  libmilter's smfi_insheader takes the header name and
		**  value as char *; libmilter never writes through these
		**  pointers -- cast away const on our caller's read-only
		**  strings.
		*/

		return smfi_insheader(ctx, idx, (char *) hname, (char *) hvalue);
	}
}

/*
**  DKIMF_CHGHEADER -- wrapper for smfi_chgheader()
**
**  Parameters:
**  	ctx -- milter (or test) context
**  	hname -- header name
**  	idx -- index of header to be changed
**  	hvalue -- header value
**
**  Return value:
**  	An sfsistat.
*/

sfsistat
dkimf_chgheader(SMFICTX *ctx, char *hname, int idx, char *hvalue)
{
	assert(ctx != NULL);
	assert(hname != NULL);

	if (testmode)
		return dkimf_test_chgheader(ctx, hname, idx, hvalue);
	else
		return smfi_chgheader(ctx, hname, idx, hvalue);
}

/*
**  DKIMF_QUARANTINE -- wrapper for smfi_quarantine()
**
**  Parameters:
**  	ctx -- milter (or test) context
**  	reason -- quarantine reason
**
**  Return value:
**  	An sfsistat.
*/

sfsistat
dkimf_quarantine(SMFICTX *ctx, const char *reason)
{
	assert(ctx != NULL);

	if (testmode)
	{
		return dkimf_test_quarantine(ctx, reason);
	}
#ifdef SMFIF_QUARANTINE
	else
	{
		/*
		**  libmilter's smfi_quarantine takes the reason as char *;
		**  libmilter never writes through this pointer -- cast away
		**  const on our caller's read-only string.
		*/

		return smfi_quarantine(ctx, (char *) reason);
	}
#endif /* SMFIF_QUARANTINE */
}

/*
**  DKIMF_ADDHEADER -- wrapper for smfi_addheader()
**
**  Parameters:
**  	ctx -- milter (or test) context
**  	hname -- header name
**  	hvalue -- header value
**
**  Return value:
**  	An sfsistat.
*/

sfsistat
dkimf_addheader(SMFICTX *ctx, const char *hname, const char *hvalue)
{
	assert(ctx != NULL);
	assert(hname != NULL);
	assert(hvalue != NULL);

	if (testmode)
	{
		return dkimf_test_addheader(ctx, hname, hvalue);
	}
	else
	{
		/*
		**  libmilter's smfi_addheader takes the header name and
		**  value as char *; libmilter never writes through these
		**  pointers -- cast away const on our caller's read-only
		**  strings.
		*/

		return smfi_addheader(ctx, (char *) hname, (char *) hvalue);
	}
}

/*
**  DKIMF_ADDRCPT -- wrapper for smfi_addrcpt()
**
**  Parameters:
**  	ctx -- milter (or test) context
**  	addr -- address to add
**
**  Return value:
**  	An sfsistat.
*/

sfsistat
dkimf_addrcpt(SMFICTX *ctx, char *addr)
{
	assert(ctx != NULL);
	assert(addr != NULL);

	if (testmode)
		return dkimf_test_addrcpt(ctx, addr);
	else
		return smfi_addrcpt(ctx, addr);
}

/*
**  DKIMF_DELRCPT -- wrapper for smfi_delrcpt()
**
**  Parameters:
**  	ctx -- milter (or test) context
**  	addr -- address to delete
**
**  Return value:
**  	An sfsistat.
*/

sfsistat
dkimf_delrcpt(SMFICTX *ctx, char *addr)
{
	assert(ctx != NULL);
	assert(addr != NULL);

	if (testmode)
		return dkimf_test_delrcpt(ctx, addr);
	else
		return smfi_delrcpt(ctx, addr);
}

/*
**  DKIMF_SETREPLY -- wrapper for smfi_setreply()
**
**  Parameters:
**  	ctx -- milter (or test) context
**  	rcode -- SMTP reply code
**  	xcode -- SMTP enhanced status code
**  	replytxt -- reply text
**
**  Return value:
**  	An sfsistat.
*/

sfsistat
dkimf_setreply(SMFICTX *ctx, const char *rcode, const char *xcode,
               const char *replytxt)
{
	assert(ctx != NULL);

	if (testmode)
	{
		return dkimf_test_setreply(ctx, rcode, xcode, replytxt);
	}
	else
	{
		/*
		**  libmilter's smfi_setreply takes the SMTP reply code,
		**  enhanced status code, and reply text as char *;
		**  libmilter never writes through these pointers -- cast
		**  away const on our caller's read-only strings.
		*/

		return smfi_setreply(ctx, (char *) rcode, (char *) xcode,
		                     (char *) replytxt);
	}
}

/*
**  DKIMF_GETSYMVAL -- wrapper for smfi_getsymval()
**
**  Parameters:
**  	ctx -- milter (or test) context
**  	sym -- symbol to retrieve
**
**  Return value:
**  	Pointer to the value of the requested MTA symbol.
*/

char *
dkimf_getsymval(SMFICTX *ctx, const char *sym)
{
	assert(ctx != NULL);
	assert(sym != NULL);

	if (testmode)
	{
		return dkimf_test_getsymval(ctx, sym);
	}
	else
	{
		/*
		**  libmilter's smfi_getsymval takes the symbol name as
		**  char *; libmilter never writes through this pointer --
		**  cast away const on our caller's read-only string.
		*/

		return smfi_getsymval(ctx, (char *) sym);
	}
}

#ifdef USE_LUA
/*
**  LUA ACCESSOR FUNCTIONS
**
**  These are the C sides of the utility functions that will be made available
**  to users via Lua to write their own policy scripts.
**
**  NAMES:
**  	Should all start "dkimf_xs_" (for DKIM filter accessors)
**
**  PARAMETERS:
**  	Should all accept nothing more than a single Lua state handle.
**  	Lua accessor and utility functions are used to pull parameters off
**  	the stack.
**
**  RETURN VALUES:
**  	Should all return the number of things they want to return via
**  	the Lua stack.  Generally accessors return one thing, and utility
**  	functions either return a result or a Lua "nil", which means
**  	at least one thing is always returned.
**
**  STACK:
**  	All functions should first evaluate the stack to see that it's what
**  	they expect in terms of number and types of elements.  The first
**  	stack item should always be expected to be a "light user data"
**  	(handle pointer) to a (SMFICTX).  If there are no errors,
**  	collect all the values and pop them.  The context pointer may come in
**  	NULL, in which case the script is being called during configuration
**  	verification; if so, return an appropriate dummy value from your
**  	function, if applicable, such as the name of the function or 0 or
**  	something matching what the script would expect back from
**  	the function such that the rest of the test will complete.
*/

/*
**  DKIMF_IMPORT_GLOBALS -- add globals to a Lua state
**
**  Parameters:
**  	ctx -- filter context
**  	l -- Lua state
**
**  Return value:
**  	None.
*/

void
dkimf_import_globals(void *p, lua_State *l)
{
	SMFICTX *ctx;
	struct connctx *cc;
	struct msgctx *mctx;
	struct lua_global *lg;

	if (p == NULL)
		return;

	ctx = (SMFICTX *) p;
	cc = (struct connctx *) dkimf_getpriv(ctx);
	mctx = cc->cctx_msg;

	lg = mctx->mctx_luaglobalh;
	while (lg != NULL)
	{
		switch (lg->lg_type)
		{
		  case LUA_TNIL:
			lua_pushnil(l);
			lua_setglobal(l, lg->lg_name);
			break;

		  case LUA_TNUMBER:
		  {
			lua_Number x;

			memcpy(&x, lg->lg_value, sizeof x);
			lua_pushnumber(l, x);
			lua_setglobal(l, lg->lg_name);
			break;
		  }

		  case LUA_TBOOLEAN:
			lua_pushboolean(l, (int)(long) lg->lg_value);
			lua_setglobal(l, lg->lg_name);
			break;

		  case LUA_TSTRING:
			lua_pushstring(l, (char *) lg->lg_value);
			lua_setglobal(l, lg->lg_name);
			break;

		  default:
			assert(0);
		}

		lg = lg->lg_next;
	}
}

/*
**  DKIMF_XS_SIGNFOR -- sign as if the mail came from a specified user
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_signfor(lua_State *l)
{
	_Bool multi = FALSE;
	int top;
	int status;
	SMFICTX *ctx;
	unsigned char *user = NULL;
	unsigned char *domain = NULL;
	struct connctx *cc;
	struct msgctx *msg;
	struct dkimf_config *conf;
	char addr[MAXADDRESS + 1];
	char errkey[BUFRSZ + 1];

	top = lua_gettop(l);
	if (top != 2 && top != 3)
	{
		lua_pushstring(l,
		               "odkim.signfor(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_isuserdata(l, 1) ||
	         !lua_isstring(l, 2) ||
	         (top == 3 && !lua_isboolean(l, 3)))
	{
		lua_pushstring(l, "odkim.signfor(): invalid argument");
		lua_error(l);
	}

	lua_pop(l, top);

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	if (ctx == NULL)
	{
		lua_pushnil(l);
		return 1;
	}

	strlcpy(addr, lua_tostring(l, 2), sizeof addr);

	if (top == 3)
		multi = lua_toboolean(l, 3);

	cc = (struct connctx *) dkimf_getpriv(ctx);
	msg = cc->cctx_msg;
	conf = cc->cctx_config;

	if (conf->conf_signtabledb == NULL ||
	    conf->conf_keytabledb == NULL)
	{
		lua_pushnil(l);
		return 1;
	}

	status = dkim_mail_parse((u_char *) addr, &user, &domain);
	if (status != 0 || user == NULL || domain == NULL)
	{
		lua_pushstring(l, "odkim.signfor(): can't parse address");
		lua_error(l);
	}

	status = dkimf_apply_signtable(conf, msg, conf->conf_keytabledb,
	                               conf->conf_signtabledb,
	                               user, domain, errkey, sizeof errkey,
	                               multi);
	if (status == -2 || status == -3)
	{
		lua_pushfstring(l, "odkim.signfor(): error processing key '%s'",
		                errkey);
		lua_error(l);
	}
	else if (status == -1)
	{
		lua_pushstring(l, "odkim.signfor(): can't read signing table");
		lua_error(l);
	}
	else
	{
		lua_pushnumber(l, status);
		return 1;
	}

	/* lua_error() does not return; this satisfies the compiler */
	return 0;
}

/*
**  DKIMF_XS_EXPORT -- export a global for use in later scripts
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_export(lua_State *l)
{
	int c;
	int top;
	int type;
	struct lua_global *lg;
	SMFICTX *ctx;
	struct connctx *cc;
	struct msgctx *msg;

	top = lua_gettop(l);

	if (top < 3 || top % 2 != 1)
	{
		lua_pushstring(l,
		               "odkim.export(): incorrect argument count");
		lua_error(l);
	}

	for (c = 2; c < top; c += 2)
	{
		if (!lua_isstring(l, c) ||
		    (!lua_isnil(l, c + 1) &&
		     !lua_isstring(l, c + 1) &&
		     !lua_isnumber(l, c + 1) &&
		     !lua_isboolean(l, c + 1)))
		{
			lua_pushstring(l,
			               "odkim.export(): incorrect argument type");
			lua_error(l);
		}
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	if (ctx == NULL)
	{
		lua_pop(l, top);
		return 0;
	}
	cc = (struct connctx *) dkimf_getpriv(ctx);
	msg = cc->cctx_msg;

	for (c = 2; c < top; c += 2)
	{
		type = lua_type(l, c + 1);

		if (type != LUA_TNIL &&
		    type != LUA_TNUMBER &&
		    type != LUA_TBOOLEAN &&
		    type != LUA_TSTRING)
			continue;

		lg = (struct lua_global *) malloc(sizeof *lg);
		if (lg != NULL)
		{
			lg->lg_name = strdup(lua_tostring(l, c));
			if (lg->lg_name == NULL)
			{
				free(lg);
				continue;
			}

			lg->lg_type = type;

			lg->lg_next = NULL;

			if (msg->mctx_luaglobalh == NULL)
				msg->mctx_luaglobalh = lg;
			else
				msg->mctx_luaglobalt->lg_next = lg;

			msg->mctx_luaglobalt = lg;

			switch (lg->lg_type)
			{
			  case LUA_TNIL:
				lg->lg_value = NULL;
				break;

			  case LUA_TNUMBER:
				lg->lg_value = malloc(sizeof(lua_Number));
				if (lg->lg_value != NULL)
				{
					lua_Number x;

					x = lua_tonumber(l, c + 1);
					memcpy(lg->lg_value, &x, sizeof x);
				}
				break;

			  case LUA_TBOOLEAN:
				if (lua_toboolean(l, c + 1))
					lg->lg_value = (void *) 1;
				else
					lg->lg_value = (void *) 0;
				break;

			  case LUA_TSTRING:
				lg->lg_value = strdup(lua_tostring(l, c + 1));
				break;
			}
		}
	}

	lua_pop(l, top);

	return 0;
}


/*
**  DKIMF_XS_XTAG -- add an extension tag
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_xtag(lua_State *l)
{
	SMFICTX *ctx;
	const char *tag = NULL;
	const char *value = NULL;

	if (lua_gettop(l) != 3)
	{
		lua_pushstring(l,
		               "odkim.xtag(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_isuserdata(l, 1) ||
	         !lua_isstring(l, 2) ||
	         !lua_isstring(l, 3))
	{
		lua_pushstring(l,
		               "odkim.xtag(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	tag = lua_tostring(l, 2);
	value = lua_tostring(l, 3);
	lua_pop(l, 3);

	if (ctx != NULL)
	{
		int n = 0;
		int status;
		struct connctx *cc;
		struct msgctx *dfc;
		struct signreq *sr;

		cc = (struct connctx *) dkimf_getpriv(ctx);
		dfc = cc->cctx_msg;

		for (sr = dfc->mctx_srhead; sr != NULL; sr = sr->srq_next)
		{
			status = dkim_add_xtag(sr->srq_dkim, tag, value);
			if (status != DKIM_STAT_OK)
			{
				lua_pushnumber(l, -1);
				return 1;
			}

			n++;
		}

		lua_pushnumber(l, n);
		return 1;
	}
	else
	{
		lua_pushnumber(l, 0);
		return 1;
	}
}

/*
**  DKIMF_XS_PARSEFIELD -- parse an address field into its components
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_parsefield(lua_State *l)
{
	unsigned char *user = NULL;
	unsigned char *domain = NULL;
	unsigned char field[DKIM_MAXHEADER + 1];

	if (lua_gettop(l) != 1)
	{
		lua_pushstring(l,
		               "odkim.parse_field(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_isstring(l, 1))
	{
		lua_pushstring(l,
		               "odkim.parse_field(): incorrect argument type");
		lua_error(l);
	}

	strlcpy((char *) field, lua_tostring(l, 1), sizeof field);
	lua_pop(l, 1);

	if (dkim_mail_parse(field, &user, &domain) != 0 ||
	    user == NULL || domain == NULL)
	{
		lua_pushnil(l);
		return 1;
	}

	lua_pushstring(l, (char *) user);
	lua_pushstring(l, (char *) domain);
	return 2;
}

/*
**  DKIMF_XS_LOG -- log a string
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_log(lua_State *l)
{
	SMFICTX *ctx;
	const char *logstring;

	if (lua_gettop(l) != 2)
	{
		lua_pushstring(l, "odkim.log(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1) ||
	         !lua_isstring(l, 2))
	{
		lua_pushstring(l, "odkim.log(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	logstring = lua_tostring(l, 2);
	lua_pop(l, 2);

	if (ctx != NULL)
	{
		struct connctx *cc;

		cc = (struct connctx *) dkimf_getpriv(ctx);
		if (cc->cctx_config->conf_dolog)
			syslog(LOG_INFO, "%s", logstring);
	}

	lua_pushnil(l);

	return 1;
}

/*
**  DKIMF_XS_FROMDOMAIN -- retrieve From: domain
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_fromdomain(lua_State *l)
{
	SMFICTX *ctx;
	struct connctx *cc;
	struct msgctx *dfc;

	assert(l != NULL);

	if (lua_gettop(l) != 1)
	{
		lua_pushstring(l,
		               "odkim.get_fromdomain(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1))
	{
		lua_pushstring(l,
		               "odkim.get_fromdomain(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	lua_pop(l, 1);

	if (ctx == NULL)
	{
		lua_pushstring(l, "dkimf_xs_fromdomain");
	}
	else
	{
		cc = (struct connctx *) dkimf_getpriv(ctx);
		dfc = cc->cctx_msg;
		lua_pushstring(l, (char *) dfc->mctx_domain);
	}

	return 1;
}

/*
**  DKIMF_XS_CLIENTHOST -- retrieve client hostname
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_clienthost(lua_State *l)
{
	SMFICTX *ctx;
	struct connctx *cc;

	assert(l != NULL);

	if (lua_gettop(l) != 1)
	{
		lua_pushstring(l,
		               "odkim.get_clienthost(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1))
	{
		lua_pushstring(l,
		               "odkim.get_clienthost(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	lua_pop(l, 1);

	if (ctx == NULL)
	{
		lua_pushstring(l, "dkimf_xs_clienthost");
	}
	else
	{
		cc = (struct connctx *) dkimf_getpriv(ctx);

		lua_pushstring(l, cc->cctx_host);
	}

	return 1;
}

/*
**  DKIMF_XS_CLIENTIP -- retrieve client IP address
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_clientip(lua_State *l)
{
	SMFICTX *ctx;
	struct connctx *cc;

	assert(l != NULL);

	if (lua_gettop(l) != 1)
	{
		lua_pushstring(l,
		               "odkim.get_clientip(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1))
	{
		lua_pushstring(l,
		               "odkim.get_clientip(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	lua_pop(l, 1);

	if (ctx == NULL)
	{
		lua_pushstring(l, "dkimf_xs_clientip");
	}
	else
	{
		char ipbuf[BUFRSZ + 1];

		memset(ipbuf, '\0', sizeof ipbuf);

		cc = (struct connctx *) dkimf_getpriv(ctx);

#ifdef AF_INET6
		if (cc->cctx_ip.ss_family == AF_INET6)
		{
			struct sockaddr_in6 *sa;

			sa = (struct sockaddr_in6 *) &cc->cctx_ip;

			if (inet_ntop(AF_INET6, &sa->sin6_addr,
			              ipbuf, sizeof ipbuf) == NULL)
			{
				lua_pushnil(l);
			}
			else
			{
				lua_pushstring(l, ipbuf);
			}
		}
		else
#endif /* AF_INET6 */
#ifdef AF_INET
		if (cc->cctx_ip.ss_family == AF_INET)
		{
			struct sockaddr_in *sa;

			sa = (struct sockaddr_in *) &cc->cctx_ip;

			if (inet_ntop(AF_INET, &sa->sin_addr,
			              ipbuf, sizeof ipbuf) == NULL)
			{
				lua_pushnil(l);
			}
			else
			{
				lua_pushstring(l, ipbuf);
			}
		}
		else
#endif /* AF_INET */
		{
			lua_pushnil(l);
		}
	}

	return 1;
}

/*
**  DKIMF_XS_REQUESTSIG -- request a signature
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_requestsig(lua_State *l)
{
	int top;
	ssize_t signlen = (ssize_t) -1;
	SMFICTX *ctx;
	const char *keyname = NULL;
	const char *ident = NULL;
	struct connctx *cc;
	struct msgctx *dfc;
	struct dkimf_config *conf;

	assert(l != NULL);

	top = lua_gettop(l);

	if (top == 0 || top > 4)
	{
		lua_pushstring(l, "odkim.sign(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1) ||
	         (top > 1 && !lua_isstring(l, 2)) ||
	         (top > 2 && !lua_isstring(l, 3) && !lua_isnumber(l, 3)) ||
	         (top > 3 && !lua_isstring(l, 4) && !lua_isnumber(l, 4)))
	{
		lua_pushstring(l, "odkim.sign(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	if (ctx != NULL)
	{
		int c;

		cc = (struct connctx *) dkimf_getpriv(ctx);
		dfc = cc->cctx_msg;
		conf = cc->cctx_config;

		for (c = 2; c <= top; c++)
		{
			if (c == 2)
			{
				keyname = lua_tostring(l, 2);
			}
			else if (lua_type(l, c) == LUA_TNUMBER)
			{
				if (signlen != (ssize_t) -1)
				{
					lua_pushstring(l,
					               "odkim.sign(): incorrect argument type");
					lua_error(l);
				}
				signlen = (ssize_t) lua_tonumber(l, c);
			}
			else
			{
				if (ident != NULL)
				{
					lua_pushstring(l,
					               "odkim.sign(): incorrect argument type");
					lua_error(l);
				}
				ident = lua_tostring(l, c);
			}
		}
	}

	lua_pop(l, top);

	if (ident != NULL && ident[0] == '\0')
		ident = NULL;

	if (ctx == NULL)
	{
		lua_pushnumber(l, 0);

		return 1;
	}

	if (conf->conf_keytabledb == NULL && keyname != NULL)
	{
		lua_pushstring(l, "odkim.sign(): request requires KeyTable");
		lua_error(l);
	}

	/* try to get the key */
	if (keyname != NULL)
	{
		switch (dkimf_add_signrequest(conf, dfc, conf->conf_keytabledb,
		                              keyname,
		                              ident,
		                              signlen))
		{
		  case 3:
			if (conf->conf_dolog)
			{
				syslog(LOG_ERR,
				       "key '%s' could not be applied",
				       keyname);
			}
			lua_pushnumber(l, 0);
			return 1;

		  case 2:
			if (conf->conf_dolog)
			{
				syslog(LOG_ERR, "key '%s' could not be loaded",
				       keyname);
			}
			lua_pushnumber(l, 0);
			return 1;

		  case 1:
			if (conf->conf_dolog)
				syslog(LOG_ERR, "key '%s' not found", keyname);
			lua_pushnumber(l, 0);
			return 1;

		  case -1:
			if (conf->conf_dolog)
			{
				syslog(LOG_ERR, "error requesting key '%s'",
				       keyname);
			}
			lua_pushnumber(l, 0);
			return 1;
		}
	}
	else if (dkimf_add_signrequest(conf, dfc, NULL, NULL, ident,
	                               (ssize_t) -1) != 0)
	{
		if (conf->conf_dolog)
			syslog(LOG_ERR, "failed to load/apply default key");

		lua_pushnumber(l, 0);

		return 1;
	}

	dfc->mctx_signalg = conf->conf_signalg;

	lua_pushnumber(l, 1);

	return 1;
}

/*
**  DKIMF_XS_REPLACEHEADER -- replace a header field's value
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_replaceheader(lua_State *l)
{
	int idx;
	const char *hdrname;
	const char *newval;
	SMFICTX *ctx;
	struct connctx *cc;
	struct msgctx *dfc;
	Header hdr;

	assert(l != NULL);

	if (lua_gettop(l) != 4)
	{
		lua_pushstring(l,
		               "odkim.replace_header(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1) ||
	         !lua_isstring(l, 2) ||
	         !lua_isnumber(l, 3) ||
	         !lua_isstring(l, 4))
	{
		lua_pushstring(l,
		               "odkim.replace_header(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	hdrname = lua_tostring(l, 2);
	idx = (int) lua_tonumber(l, 3);
	newval = lua_tostring(l, 4);

	if (ctx != NULL)
	{
		cc = (struct connctx *) dkimf_getpriv(ctx);
		dfc = cc->cctx_msg;
	}

	lua_pop(l, 3);

	if (ctx == NULL)
	{
		if (idx == 0)
			lua_pushstring(l, "dkimf_xs_replaceheader");
		else
			lua_pushnil(l);
		return 1;
	}

	hdr = dkimf_findheader(dfc, hdrname, idx);
	if (hdr == NULL)
	{
		lua_pushnil(l);
		return 1;
	}
	else
	{
		char *tmp;

		if (ctx != NULL && cc->cctx_noleadspc)
		{
			size_t len;

			len = strlen(newval);
			tmp = malloc(len + 2);
			if (tmp == NULL)
			{
				lua_pushnil(l);
				return 1;
			}

			tmp[0] = ' ';
			memcpy(&tmp[1], newval, len + 1);
		}
		else
		{
			tmp = strdup(newval);
			if (tmp == NULL)
			{
				lua_pushnil(l);
				return 1;
			}
		}

		free(hdr->hdr_val);
		hdr->hdr_val = tmp;

		return 0;
	}
}

/*
**  DKIMF_XS_GETENVFROM -- request envelope sender
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_getenvfrom(lua_State *l)
{
	SMFICTX *ctx;
	struct connctx *cc;
	struct msgctx *dfc;

	assert(l != NULL);

	if (lua_gettop(l) != 1)
	{
		lua_pushstring(l,
		               "odkim.get_envfrom(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1))
	{
		lua_pushstring(l,
		               "odkim.get_envfrom(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);

	if (ctx != NULL)
	{
		cc = (struct connctx *) dkimf_getpriv(ctx);
		dfc = cc->cctx_msg;
	}

	lua_pop(l, 1);

	if (ctx == NULL)
		lua_pushstring(l, "dkimf_xs_getenvfrom");
	else
		lua_pushstring(l, (char *) dfc->mctx_envfrom);
	return 1;
}

/*
**  DKIMF_XS_GETHEADER -- request a header value
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_getheader(lua_State *l)
{
	int idx;
	const char *hdrname;
	SMFICTX *ctx;
	struct connctx *cc;
	struct msgctx *dfc;
	Header hdr;

	assert(l != NULL);

	if (lua_gettop(l) != 3)
	{
		lua_pushstring(l,
		               "odkim.get_header(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1) ||
	         !lua_isstring(l, 2) || !lua_isnumber(l, 3))
	{
		lua_pushstring(l,
		               "odkim.get_header(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	hdrname = lua_tostring(l, 2);
	idx = (int) lua_tonumber(l, 3);

	if (ctx != NULL)
	{
		cc = (struct connctx *) dkimf_getpriv(ctx);
		dfc = cc->cctx_msg;
	}

	lua_pop(l, 3);

	if (ctx == NULL)
	{
		if (idx == 0)
			lua_pushstring(l, "dkimf_xs_getheader");
		else
			lua_pushnil(l);
		return 1;
	}

	hdr = dkimf_findheader(dfc, hdrname, idx);
	if (hdr == NULL)
	{
		lua_pushnil(l);
		return 1;
	}
	else
	{
		lua_pushstring(l, hdr->hdr_val);
		return 1;
	}
}

/*
**  DKIMF_XS_INTERNALIP -- see if the client's IP address is "internal"
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_internalip(lua_State *l)
{
	SMFICTX *ctx;
	struct connctx *cc;
	struct dkimf_config *conf;

	assert(l != NULL);

	if (lua_gettop(l) != 1)
	{
		lua_pushstring(l,
		               "odkim.internal_ip(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1))
	{
		lua_pushstring(l,
		               "odkim.internal_ip(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	lua_pop(l, 1);

	if (ctx == NULL)
	{
		lua_pushnumber(l, 1);

		return 1;
	}

	cc = (struct connctx *) dkimf_getpriv(ctx);
	conf = cc->cctx_config;

	if (conf->conf_internal == NULL)
	{
		lua_pushnumber(l, 0);
	}
	else
	{
		_Bool internal;

		internal = dkimf_checkhost(conf->conf_internal, cc->cctx_host);
		internal = internal || dkimf_checkip(conf->conf_internal,
		                                     (struct sockaddr *) &cc->cctx_ip);

		lua_pushnumber(l, internal ? 1 : 0);
	}

	return 1;
}

/*
**  DKIMF_XS_DBOPEN -- open a DB handle
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_dbopen(lua_State *l)
{
	unsigned int flags = DKIMF_DB_FLAG_READONLY;
	int status;
	DKIMF_DB db;
	char *name;
	const char *err = NULL;
	struct dkimf_lua_gc *gc;

	assert(l != NULL);

	if (lua_gettop(l) != 1 && lua_gettop(l) != 2)
	{
		lua_pushstring(l,
		               "odkim.db_open(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_isstring(l, 1) ||
	         (lua_gettop(l) == 2 && !lua_isboolean(l, 2)))
	{
		lua_pushstring(l,
		               "odkim.db_open(): incorrect argument type");
		lua_error(l);
	}

	name = (char *)lua_tostring(l, 1);
	if (lua_gettop(l) == 2 && lua_toboolean(l, 2))
		flags |= DKIMF_DB_FLAG_ICASE;
	lua_pop(l, lua_gettop(l));

	status = dkimf_db_open(&db, name, flags, NULL, &err);

	if (status != 0)
	{
		if (err != NULL)
		{
			lua_pushfstring(l, "%s: odkim.db_open(): %s", name,
			                err);
		}
		else
		{
			lua_pushfstring(l, "%s: odkim.db_open() failed", name);
		}
		lua_error(l);
	}

	lua_getglobal(l, DKIMF_GC);
	gc = (struct dkimf_lua_gc *) lua_touserdata(l, 1);
	lua_pop(l, 1);
	dkimf_lua_gc_add(gc, db, DKIMF_LUA_GC_DB);

	lua_pushlightuserdata(l, db);

	return 1;
}

/*
**  DKIMF_XS_DBCLOSE -- close a DB handle
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_dbclose(lua_State *l)
{
	DKIMF_DB db;
	struct dkimf_lua_gc *gc;

	assert(l != NULL);

	if (lua_gettop(l) != 1)
	{
		lua_pushstring(l,
		               "odkim.db_close(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1))
	{
		lua_pushstring(l,
		               "odkim.db_close(): incorrect argument type");
		lua_error(l);
	}

	db = (DKIMF_DB) lua_touserdata(l, 1);

	lua_pop(l, 1);

	if (db == NULL)
	{
		lua_pushnumber(l, 0);
		return 1;
	}

	(void) dkimf_db_close(db);

	lua_getglobal(l, DKIMF_GC);
	gc = (struct dkimf_lua_gc *) lua_touserdata(l, 1);
	lua_pop(l, 1);
	dkimf_lua_gc_remove(gc, (void *) db);

	lua_pushnumber(l, 1);

	return 1;
}

/*
**  DKIMF_XS_DBHANDLE -- retrieve a DB handle
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_dbhandle(lua_State *l)
{
	int code;
	SMFICTX *ctx;
	struct connctx *cc;
	struct dkimf_config *conf;

	assert(l != NULL);

	if (lua_gettop(l) != 2)
	{
		lua_pushstring(l,
		               "odkim.get_dbhandle(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1) || !lua_isnumber(l, 2))
	{
		lua_pushstring(l,
		               "odkim.get_dbhandle(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);

	if (ctx == NULL)
	{
		lua_pop(l, 2);
		lua_pushnil(l);
		return 1;
	}

	cc = (struct connctx *) dkimf_getpriv(ctx);
	conf = cc->cctx_config;

	code = (int) lua_tonumber(l, 1);
	lua_pop(l, 2);

	switch (code)
	{
	  case DB_DOMAINS:
		if (conf->conf_domainsdb == NULL)
			lua_pushnil(l);
		else
			lua_pushlightuserdata(l, conf->conf_domainsdb);
		break;

	  case DB_THIRDPARTY:
		if (conf->conf_thirdpartydb == NULL)
			lua_pushnil(l);
		else
			lua_pushlightuserdata(l, conf->conf_thirdpartydb);
		break;

	  case DB_DONTSIGNTO:
		if (conf->conf_dontsigntodb == NULL)
			lua_pushnil(l);
		else
			lua_pushlightuserdata(l, conf->conf_dontsigntodb);
		break;

	  case DB_MTAS:
		if (conf->conf_mtasdb == NULL)
			lua_pushnil(l);
		else
			lua_pushlightuserdata(l, conf->conf_mtasdb);
		break;

	  case DB_MACROS:
		if (conf->conf_macrosdb == NULL)
			lua_pushnil(l);
		else
			lua_pushlightuserdata(l, conf->conf_macrosdb);
		break;

	  case DB_SIGNINGTABLE:
		if (conf->conf_signtabledb == NULL)
			lua_pushnil(l);
		else
			lua_pushlightuserdata(l, conf->conf_signtabledb);
		break;

	  default:
		lua_pushnil(l);
		break;
	}

	return 1;
}

/*
**  DKIMF_XS_RCPTCOUNT -- retrieve recipient count
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_rcptcount(lua_State *l)
{
	int rcnt;
	SMFICTX *ctx;
	struct connctx *cc;
	struct msgctx *dfc;
	struct addrlist *addr;

	assert(l != NULL);

	if (lua_gettop(l) != 1)
	{
		lua_pushstring(l,
		               "odkim.rcpt_count(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1))
	{
		lua_pushstring(l,
		               "odkim.rcpt_count(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	lua_pop(l, 1);

	if (ctx == NULL)
	{
		lua_pushnumber(l, 1);
		return 1;
	}

	cc = (struct connctx *) dkimf_getpriv(ctx);
	dfc = cc->cctx_msg;

	rcnt = 0;
	
	for (addr = dfc->mctx_rcptlist; addr != NULL; addr = addr->a_next)
		rcnt++;

	lua_pushnumber(l, rcnt);

	return 1;
}

/*
**  DKIMF_XS_RCPT -- retrieve an envelope recipient
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_rcpt(lua_State *l)
{
	int rcnt;
	SMFICTX *ctx;
	struct connctx *cc;
	struct msgctx *dfc;
	struct addrlist *addr;

	assert(l != NULL);

	if (lua_gettop(l) != 2)
	{
		lua_pushstring(l,
		               "odkim.get_rcpt(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1) || !lua_isnumber(l, 2))
	{
		lua_pushstring(l,
		               "odkim.get_rcpt(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	rcnt = (int) lua_tonumber(l, 1);
	lua_pop(l, 2);

	if (ctx == NULL)
	{
		lua_pushstring(l, "dkimf_xs_rcpt");
		return 1;
	}
	
	cc = (struct connctx *) dkimf_getpriv(ctx);
	dfc = cc->cctx_msg;

	addr = dfc->mctx_rcptlist;
	while (rcnt > 0 && addr != NULL)
	{
		addr = addr->a_next;
		rcnt--;
	}

	if (addr == NULL)
		lua_pushnil(l);
	else
		lua_pushstring(l, addr->a_addr);

	return 1;
}

/*
**  DKIMF_XS_RCPTARRAY -- retrieve all recipients into a Lua array
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_rcptarray(lua_State *l)
{
	SMFICTX *ctx;
	struct connctx *cc;
	struct msgctx *dfc;

	assert(l != NULL);

	if (lua_gettop(l) != 1)
	{
		lua_pushstring(l,
		               "odkim.get_rcptarray(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1))
	{
		lua_pushstring(l,
		               "odkim.get_rcptarray(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	lua_pop(l, 1);

	lua_newtable(l);

	if (ctx == NULL)
	{
		lua_pushnumber(l, 1);
		lua_pushstring(l, "dkimf_xs_rcptarray");
		lua_settable(l, -3);
	}
	else
	{
		int idx;
		struct addrlist *addr;

		cc = (struct connctx *) dkimf_getpriv(ctx);
		dfc = cc->cctx_msg;

		for (addr = dfc->mctx_rcptlist, idx = 1;
		     addr != NULL;
		     addr = addr->a_next, idx++)
		{
			lua_pushnumber(l, idx);
			lua_pushstring(l, addr->a_addr);
			lua_settable(l, -3);
		}
	}

	return 1;
}

/*
**  DKIMF_XS_DBQUERY -- check for a record in a database
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_dbquery(lua_State *l)
{
	int status;
	_Bool exists;
	DKIMF_DB db;
	const char *str;

	assert(l != NULL);

	if (lua_gettop(l) != 2)
	{
		lua_pushstring(l,
		               "odkim.db_check(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1) ||
	         !lua_isstring(l, 2))
	{
		lua_pushstring(l,
		               "odkim.db_check(): incorrect argument type");
		lua_error(l);
	}

	db = (DKIMF_DB) lua_touserdata(l, 1);
	str = lua_tostring(l, 2);
	lua_pop(l, 2);

	if (db == NULL || str == NULL)
	{
		lua_pushnil(l);
		return 1;
	}

	exists = FALSE;
	status = dkimf_db_get(db, (char *) str, 0, NULL, 0, &exists);
	if (status == 0)
		lua_pushnumber(l, exists ? 1 : 0);
	else
		lua_pushnil(l);

	return 1;
}

/*
**  DKIMF_XS_SETPARTIAL -- request l= tags
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_setpartial(lua_State *l)
{
	SMFICTX *ctx;

	assert(l != NULL);

	if (lua_gettop(l) != 1)
	{
		lua_pushstring(l,
		               "odkim.use_ltag(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1))
	{
		lua_pushstring(l,
		               "odkim.use_ltag(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	lua_pop(l, 1);

	if (ctx != NULL)
	{
		struct connctx *cc;
		struct msgctx *dfc;

		cc = (struct connctx *) dkimf_getpriv(ctx);
		dfc = cc->cctx_msg;
		dfc->mctx_ltag = TRUE;
	}

	lua_pushnil(l);

	return 1;
}

/*
**  DKIMF_XS_VERIFY -- set up verification
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_verify(lua_State *l)
{
	SMFICTX *ctx;
	struct connctx *cc;
	struct msgctx *dfc;
	struct dkimf_config *conf;

	assert(l != NULL);

	if (lua_gettop(l) != 1)
	{
		lua_pushstring(l,
		               "odkim.verify(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1))
	{
		lua_pushstring(l,
		               "odkim.verify(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	lua_pop(l, 1);

	if (ctx != NULL)
	{
		cc = (struct connctx *) dkimf_getpriv(ctx);
		dfc = cc->cctx_msg;
		conf = cc->cctx_config;

		if (dfc->mctx_dkimv == NULL)
		{
			DKIM_STAT status;

			dfc->mctx_dkimv = dkim_verify(conf->conf_libopendkim,
			                              dfc->mctx_jobid, NULL,
			                              &status);

			if (dfc->mctx_dkimv == NULL)
			{
				lua_pushstring(l, dkim_getresultstr(status));
				return 1;
			}
		}
	}

	lua_pushnil(l);
	return 1;
}

/*
**  DKIMF_XS_GETSIGARRAY -- get signature handle array
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_getsigarray(lua_State *l)
{
	SMFICTX *ctx;

	assert(l != NULL);

	if (lua_gettop(l) != 1)
	{
		lua_pushstring(l,
		               "odkim.get_sigarray(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1))
	{
		lua_pushstring(l,
		               "odkim.get_sigarray(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	lua_pop(l, 1);

	if (ctx != NULL)
	{
		struct connctx *cc;
		struct msgctx *dfc;

		cc = (struct connctx *) dkimf_getpriv(ctx);
		dfc = cc->cctx_msg;

		if (dfc->mctx_dkimv == NULL)
		{
			lua_pushnumber(l, 0);
		}
		else
		{
			int nsigs;
			DKIM_STAT status;
			DKIM_SIGINFO **sigs;

			status = dkim_getsiglist(dfc->mctx_dkimv,
			                         &sigs, &nsigs);
			if (status != DKIM_STAT_OK)
			{
				lua_pushnil(l);
			}
			else
			{
				int c;

				lua_newtable(l);

				for (c = 0; c < nsigs; c++)
				{
					lua_pushnumber(l, c + 1);
					lua_pushlightuserdata(l, sigs[c]);
					lua_settable(l, -3);
				}
			}
		}
	}
	else
	{
		lua_pushnil(l);
	}
	
	return 1;
}

/*
**  DKIMF_XS_GETSIGCOUNT -- get signature count
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_getsigcount(lua_State *l)
{
	SMFICTX *ctx;
	struct connctx *cc;
	struct msgctx *dfc;

	assert(l != NULL);

	if (lua_gettop(l) != 1)
	{
		lua_pushstring(l,
		               "odkim.get_sigcount(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1))
	{
		lua_pushstring(l,
		               "odkim.get_sigcount(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	lua_pop(l, 1);

	if (ctx != NULL)
	{
		cc = (struct connctx *) dkimf_getpriv(ctx);
		dfc = cc->cctx_msg;

		if (dfc->mctx_dkimv == NULL)
		{
			lua_pushnumber(l, 0);
		}
		else
		{
			DKIM_STAT status;
			int nsigs;
			DKIM_SIGINFO **sigs;

			status = dkim_getsiglist(dfc->mctx_dkimv,
			                         &sigs, &nsigs);
			if (status != DKIM_STAT_OK)
				lua_pushnil(l);
			else
				lua_pushnumber(l, nsigs);
		}
	}
	else
	{
		lua_pushnumber(l, 1);
	}
	
	return 1;
}

/*
**  DKIMF_XS_GETSIGHANDLE -- get signature handle
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_getsighandle(lua_State *l)
{
	int idx;
	int nsigs;
	DKIM_STAT status;
	SMFICTX *ctx;
	DKIM_SIGINFO **sigs;
	struct connctx *cc;
	struct msgctx *dfc;

	assert(l != NULL);

	if (lua_gettop(l) != 2)
	{
		lua_pushstring(l,
		               "odkim.get_sighandle(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1) ||
	         !lua_isnumber(l, 2))
	{
		lua_pushstring(l,
		               "odkim.get_sighandle(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	idx = (int) lua_tonumber(l, 2);
	lua_pop(l, 2);

	if (ctx == NULL)
	{
		lua_pushlightuserdata(l, NULL);
		return 1;
	}

	cc = (struct connctx *) dkimf_getpriv(ctx);
	dfc = cc->cctx_msg;

	if (dfc->mctx_dkimv == NULL)
	{
		lua_pushnil(l);
		return 1;
	}

	status = dkim_getsiglist(dfc->mctx_dkimv, &sigs, &nsigs);
	if (status != DKIM_STAT_OK)
	{
		lua_pushnil(l);
		return 1;
	}

	if (idx < 0 || idx >= nsigs)
	{
		lua_pushstring(l, "odkim.get_sighandle(): invalid request");
		lua_error(l);
	}

	lua_pushlightuserdata(l, sigs[idx]);

	return 1;
}

/*
**  DKIMF_XS_GETSIGDOMAIN -- get signature's signing domain ("d=")
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_getsigdomain(lua_State *l)
{
	DKIM_SIGINFO *sig;

	assert(l != NULL);

	if (lua_gettop(l) != 1)
	{
		lua_pushstring(l,
		               "odkim.sig_getdomain(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1))
	{
		lua_pushstring(l,
		               "odkim.sig_getdomain(): incorrect argument type");
		lua_error(l);
	}

	sig = (DKIM_SIGINFO *) lua_touserdata(l, 1);
	lua_pop(l, 1);

	if (sig == NULL)
		lua_pushlightuserdata(l, NULL);
	else
		lua_pushstring(l, (char *) dkim_sig_getdomain(sig));

	return 1;
}

/*
**  DKIMF_XS_SIGIGNORE -- ignore a signature and its result
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_sigignore(lua_State *l)
{
	DKIM_SIGINFO *sig;

	assert(l != NULL);

	if (lua_gettop(l) != 1)
	{
		lua_pushstring(l,
		               "odkim.sig_getdomain(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1))
	{
		lua_pushstring(l,
		               "odkim.sig_getdomain(): incorrect argument type");
		lua_error(l);
	}

	sig = (DKIM_SIGINFO *) lua_touserdata(l, 1);
	lua_pop(l, 1);

	if (sig != NULL)
		dkim_sig_ignore(sig);

	lua_pushnil(l);

	return 1;
}

/*
**  DKIMF_XS_GETSIGIDENTITY -- get signature's signing identity ("i=")
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_getsigidentity(lua_State *l)
{
	DKIM_STAT status;
	DKIM_SIGINFO *sig;
	u_char addr[MAXADDRESS + 1];

	assert(l != NULL);

	if (lua_gettop(l) != 1)
	{
		lua_pushstring(l,
		               "odkim.sig_getidentity(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1))
	{
		lua_pushstring(l,
		               "odkim.sig_getidentity(): incorrect argument type");
		lua_error(l);
	}

	sig = (DKIM_SIGINFO *) lua_touserdata(l, 1);
	lua_pop(l, 1);

	if (sig == NULL)
	{
		lua_pushstring(l, "dkimf_xs_getsigidentity");
		return 1;
	}

	memset(addr, '\0', sizeof addr);
	status = dkim_sig_getidentity(NULL, sig, addr, sizeof addr - 1);
	if (status != DKIM_STAT_OK)
		lua_pushnil(l);
	else
		lua_pushstring(l, (char *) addr);

	return 1;
}

/*
**  DKIMF_XS_GETSYMVAL -- get MTA symbol
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_getsymval(lua_State *l)
{
	char *name;
	char *sym;
	SMFICTX *ctx;

	assert(l != NULL);

	if (lua_gettop(l) != 2)
	{
		lua_pushstring(l,
		               "odkim.get_mtasymbol(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1) ||
	         !lua_isstring(l, 2))
	{
		lua_pushstring(l,
		               "odkim.get_mtasymbol(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	name = (char *) lua_tostring(l, 2);
	lua_pop(l, 2);

	if (ctx == NULL)
	{
		lua_pushstring(l, "dkimf_xs_getmtasymbol");
	}
	else
	{
		sym = dkimf_getsymval(ctx, name);
		if (sym == NULL)
			lua_pushnil(l);
		else
			lua_pushstring(l, sym);
	}

	return 1;
}

/*
**  DKIMF_XS_SIGRESULT -- get signature's result code
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_sigresult(lua_State *l)
{
	DKIM_SIGINFO *sig;

	assert(l != NULL);

	if (lua_gettop(l) != 1)
	{
		lua_pushstring(l,
		               "odkim.sig_result(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1))
	{
		lua_pushstring(l,
		               "odkim.sig_result(): incorrect argument type");
		lua_error(l);
	}

	sig = (DKIM_SIGINFO *) lua_touserdata(l, 1);
	lua_pop(l, 1);

	if (sig == NULL)
		lua_pushnumber(l, 0);
	else
		lua_pushnumber(l, dkim_sig_geterror(sig));

	return 1;
}

/*
**  DKIMF_XS_SIGBHRESULT -- get signature's body hash result code
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_sigbhresult(lua_State *l)
{
	DKIM_SIGINFO *sig;

	assert(l != NULL);

	if (lua_gettop(l) != 1)
	{
		lua_pushstring(l,
		               "odkim.sig_bhresult(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1))
	{
		lua_pushstring(l,
		               "odkim.sig_bhresult(): incorrect argument type");
		lua_error(l);
	}

	sig = (DKIM_SIGINFO *) lua_touserdata(l, 1);
	lua_pop(l, 1);

	if (sig == NULL)
		lua_pushnumber(l, 0);
	else
		lua_pushnumber(l, dkim_sig_getbh(sig));

	return 1;
}

/*
**  DKIMF_XS_BODYLENGTH -- return total body length
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_bodylength(lua_State *l)
{
	ssize_t body;
	DKIM_STAT status;
	SMFICTX *ctx;
	DKIM_SIGINFO *sig;
	struct connctx *cc;

	assert(l != NULL);

	if (lua_gettop(l) != 2)
	{
		lua_pushstring(l,
		               "odkim.sig_bodylength(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1) ||
	         !lua_islightuserdata(l, 2))
	{
		lua_pushstring(l,
		               "odkim.sig_bodylength(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	sig = (DKIM_SIGINFO *) lua_touserdata(l, 2);
	lua_pop(l, 2);

	if (ctx == NULL)
	{
		lua_pushnumber(l, 100);
		return 1;
	}

	cc = (struct connctx *) dkimf_getpriv(ctx);
	if (cc->cctx_msg == NULL || cc->cctx_msg->mctx_dkimv == NULL)
	{
		lua_pushnil(l);
		return 1;
	}

	status = dkim_sig_getcanonlen(cc->cctx_msg->mctx_dkimv, sig, &body,
	                              NULL, NULL);
	if (status != DKIM_STAT_OK)
		lua_pushnil(l);
	else
		lua_pushnumber(l, (lua_Number) body); /* ssize_t → double at Lua boundary */

	return 1;
}

/*
**  DKIMF_XS_CANONLENGTH -- return length canonicalized by a signature
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_canonlength(lua_State *l)
{
	ssize_t cl;
	DKIM_STAT status;
	SMFICTX *ctx;
	DKIM_SIGINFO *sig;
	struct connctx *cc;

	assert(l != NULL);

	if (lua_gettop(l) != 2)
	{
		lua_pushstring(l,
		               "odkim.sig_canonlength(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1) ||
	         !lua_islightuserdata(l, 2))
	{
		lua_pushstring(l,
		               "odkim.sig_canonlength(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	sig = (DKIM_SIGINFO *) lua_touserdata(l, 2);
	lua_pop(l, 2);

	if (ctx == NULL)
	{
		lua_pushnumber(l, 100);
		return 1;
	}

	cc = (struct connctx *) dkimf_getpriv(ctx);
	if (cc->cctx_msg == NULL || cc->cctx_msg->mctx_dkimv == NULL)
	{
		lua_pushnil(l);
		return 1;
	}

	status = dkim_sig_getcanonlen(cc->cctx_msg->mctx_dkimv, sig, NULL,
	                              &cl, NULL);
	if (status != DKIM_STAT_OK)
		lua_pushnil(l);
	else
		lua_pushnumber(l, (lua_Number) cl); /* ssize_t → double at Lua boundary */

	return 1;
}

/*
**  DKIMF_XS_ADDHEADER -- add a header field
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_addheader(lua_State *l)
{
	char *name;
	char *value;
	SMFICTX *ctx;

	assert(l != NULL);

	if (lua_gettop(l) != 3)
	{
		lua_pushstring(l,
		               "odkim.add_header(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1) ||
	         !lua_isstring(l, 2) ||
	         !lua_isstring(l, 3))
	{
		lua_pushstring(l,
		               "odkim.add_header(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	name = (char *) lua_tostring(l, 2);
	value = (char *) lua_tostring(l, 3);
	lua_pop(l, 3);

	if (ctx == NULL)
		lua_pushnil(l);
	else if (dkimf_insheader(ctx, 0, name, value) == MI_SUCCESS)
		lua_pushnumber(l, 1);
	else
		lua_pushnil(l);

	return 1;
}

/*
**  DKIMF_XS_DELHEADER -- delete a header field
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_delheader(lua_State *l)
{
	int idx;
	char *name;
	SMFICTX *ctx;

	assert(l != NULL);

	if (lua_gettop(l) != 3)
	{
		lua_pushstring(l,
		               "odkim.del_header(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1) ||
	         !lua_isstring(l, 2) ||
	         !lua_isnumber(l, 3))
	{
		lua_pushstring(l,
		               "odkim.del_header(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	name = (char *) lua_tostring(l, 2);
	idx = (int) lua_tonumber(l, 3); /* header-occurrence index fits in int */
	lua_pop(l, 3);

	if (ctx == NULL)
		lua_pushnil(l);
	else if (dkimf_chgheader(ctx, name, idx + 1, NULL) == MI_SUCCESS)
		lua_pushnumber(l, 1);
	else
		lua_pushnil(l);

	return 1;
}

/*
**  DKIMF_XS_ADDRCPT -- add a recipient
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_addrcpt(lua_State *l)
{
	char *addr;
	SMFICTX *ctx;

	assert(l != NULL);

	if (lua_gettop(l) != 2)
	{
		lua_pushstring(l,
		               "odkim.add_rcpt(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1) ||
	         !lua_isstring(l, 2))
	{
		lua_pushstring(l, "odkim.add_rcpt(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	addr = (char *) lua_tostring(l, 2);
	lua_pop(l, 2);

	if (ctx == NULL)
		lua_pushnumber(l, 1);
	else if (dkimf_addrcpt(ctx, addr) == MI_SUCCESS)
		lua_pushnumber(l, 1);
	else
		lua_pushnil(l);

	return 1;
}

/*
**  DKIMF_XS_DELRCPT -- delete a recipient
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_delrcpt(lua_State *l)
{
	char *addr;
	struct addrlist *a;
	SMFICTX *ctx;
	struct connctx *cc;
	struct msgctx *dfc;
	struct dkimf_config *conf;

	assert(l != NULL);

	if (lua_gettop(l) != 2)
	{
		lua_pushstring(l,
		               "odkim.delete_rcpt(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1) ||
	         !lua_isstring(l, 2))
	{
		lua_pushstring(l,
		               "odkim.delete_rcpt(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	addr = (char *) lua_tostring(l, 2);
	lua_pop(l, 2);

	if (ctx == NULL)
	{
		lua_pushnumber(l, 1);
		return 1;
	}

	cc = (struct connctx *) dkimf_getpriv(ctx);
	conf = cc->cctx_config;
	dfc = cc->cctx_msg;

	/* see if this is a known recipient */
	for (a = dfc->mctx_rcptlist; a != NULL; a = a->a_next)
	{
		if (strcasecmp(a->a_addr, addr) == 0)
			break;
	}

	/* if not found, report error */
	if (a == NULL)
	{
		lua_pushnil(l);
		return 1;
	}

	/* delete and replace with a header field */
	if (dkimf_delrcpt(ctx, a->a_addr) != MI_SUCCESS)
	{
		if (conf->conf_dolog)
		{
			syslog(LOG_ERR, "%s: smfi_delrcpt() failed",
			       dfc->mctx_jobid);
		}
	}
	else
	{
		char header[MAXADDRESS + 8];

		(void) snprintf(header, sizeof header, "rfc822;%s", a->a_addr);
		if (dkimf_addheader(ctx, ORCPTHEADER, header) != MI_SUCCESS)
		{
			if (conf->conf_dolog)
			{
				syslog(LOG_ERR, "%s: smfi_addheader() failed",
				       dfc->mctx_jobid);
			}
		}
	}

	lua_pushnumber(l, 1);

	return 1;
}

/*
**  DKIMF_XS_RESIGN -- set up for re-signing
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_resign(lua_State *l)
{
	SMFICTX *ctx;
	struct connctx *cc;
	struct msgctx *dfc;

	assert(l != NULL);

	if (lua_gettop(l) != 1)
	{
		lua_pushstring(l, "odkim.resign(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1))
	{
		lua_pushstring(l, "odkim.resign(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	lua_pop(l, 1);

	if (ctx == NULL)
	{
		lua_pushnumber(l, 1);
		return 1;
	}

	cc = (struct connctx *) dkimf_getpriv(ctx);
	dfc = cc->cctx_msg;

	dfc->mctx_resign = TRUE;

	lua_pushnumber(l, 1);

	return 1;
}

/*
**  DKIMF_XS_SETREPLY -- set SMTP reply text
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_setreply(lua_State *l)
{
	SMFICTX *ctx;
	char *rcode = NULL;
	char *xcode = NULL;
	char *message = NULL;

	assert(l != NULL);

	if (lua_gettop(l) != 4)
	{
		lua_pushstring(l,
		               "odkim.set_reply(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1) ||
	         !lua_isstring(l, 2) ||
	         !lua_isstring(l, 3) ||
	         !lua_isstring(l, 4))
	{
		lua_pushstring(l,
		               "odkim.set_reply(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	rcode = (char *) lua_tostring(l, 2);
	xcode = (char *) lua_tostring(l, 3);
	message = (char *) lua_tostring(l, 4);
	lua_pop(l, 4);

	if (ctx == NULL)
	{
		lua_pushnumber(l, 1);
		return 1;
	}

	if (strlen(xcode) == 0)
		xcode = NULL;

	if (dkimf_setreply(ctx, rcode, xcode, message) == MI_FAILURE)
		lua_pushnil(l);
	else
		lua_pushnumber(l, 1);

	return 1;
}

/*
**  DKIMF_XS_QUARANTINE -- request quarantine
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_quarantine(lua_State *l)
{
	SMFICTX *ctx;
	char *message = NULL;

	assert(l != NULL);

	if (lua_gettop(l) != 2)
	{
		lua_pushstring(l,
		               "odkim.quarantine(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1) ||
	         !lua_isstring(l, 2))
	{
		lua_pushstring(l,
		               "odkim.quarantine(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	message = (char *) lua_tostring(l, 2);
	lua_pop(l, 2);

	if (ctx == NULL)
		lua_pushnumber(l, 1);
	else if (dkimf_quarantine(ctx, message) == MI_FAILURE)
		lua_pushnil(l);
	else
		lua_pushnumber(l, 1);

	return 1;
}

/*
**  DKIMF_XS_SETRESULT -- set milter result
**
**  Parameters:
**  	l -- Lua state
**
**  Return value:
**  	Number of stack items pushed.
*/

int
dkimf_xs_setresult(lua_State *l)
{
	SMFICTX *ctx;
	int mresult;

	assert(l != NULL);

	if (lua_gettop(l) != 2)
	{
		lua_pushstring(l,
		               "odkim.set_result(): incorrect argument count");
		lua_error(l);
	}
	else if (!lua_islightuserdata(l, 1) ||
	         !lua_isnumber(l, 2))
	{
		lua_pushstring(l,
		               "odkim.set_result(): incorrect argument type");
		lua_error(l);
	}

	ctx = (SMFICTX *) lua_touserdata(l, 1);
	mresult = (int) lua_tonumber(l, 2);
	lua_pop(l, 2);

	if (ctx == NULL)
	{
		lua_pushnumber(l, 1);
	}
	else if (mresult == SMFIS_TEMPFAIL ||
	         mresult == SMFIS_ACCEPT ||
	         mresult == SMFIS_DISCARD ||
	         mresult == SMFIS_REJECT)
	{
		struct msgctx *dfc;
		struct connctx *cc;

		cc = (struct connctx *) dkimf_getpriv(ctx);
		dfc = cc->cctx_msg;

		dfc->mctx_mresult = mresult;
		lua_pushnumber(l, 1);
	}
	else
	{
		lua_pushnil(l);
	}

	return 1;
}

#endif /* USE_LUA */


/*
**  DKIMF_ADD_AR_FIELDS -- add Authentication-Results header fields
**
**  Parameters:
**  	dfc -- filter context
**  	conf -- configuration handle
**  	ctx -- milter context
**
**  Return value:
**  	None.
*/

static void
dkimf_add_ar_fields(struct msgctx *dfc, struct dkimf_config *conf,
                    SMFICTX *ctx)
{
	assert(dfc != NULL);
	assert(conf != NULL);
	assert(ctx != NULL);

	if (dkimf_insheader(ctx, 0, AUTHRESULTSHDR,
	                    (char *) dfc->mctx_dkimar) == MI_FAILURE)
	{
		if (conf->conf_dolog)
		{
			syslog(LOG_ERR, "%s: %s header add failed",
			       dfc->mctx_jobid, AUTHRESULTSHDR);
		}
	}
}

/*
**  DKIMF_DB_ERROR -- syslog errors related to db retrieval
**
**  Parameters:
**  	db -- the db
**      key -- what was looked up
**
**  Return value:
**  	None.
*/

static void
dkimf_db_error(DKIMF_DB db, const char *key)
{
	char errbuf[BUFRSZ];

	assert(db != NULL);
	assert(key != NULL);

	(void) dkimf_db_strerror(db, errbuf, sizeof errbuf);

	syslog(LOG_ERR, "error looking up \"%s\" in database: %s",
	       key, errbuf);
}


/*
**  DKIMF_INIT_SYSLOG -- initialize syslog()
**
**  Parameters:
**  	facility -- name of the syslog facility to use when logging;
**  	            can be NULL to request the default
**
**  Return value:
**  	None.
*/

static void
dkimf_init_syslog(char *name, char *facility)
{
#ifdef LOG_MAIL
	int code;
	struct lookup *p = NULL;

	closelog();

	code = LOG_MAIL;
	if (facility != NULL)
	{
		for (p = log_facilities; p != NULL; p++)
		{
			if (strcasecmp(p->str, facility) == 0)
			{
				code = p->code;
				break;
			}
		}
	}

	openlog(name != NULL ? name : progname, LOG_PID, code);
#else /* LOG_MAIL */
	closelog();

	openlog(name != NULL ? name : progname, LOG_PID);
#endif /* LOG_MAIL */
}

/*
**  DKIMF_RESTART_CHECK -- initialize/check restart rate information
**
**  Parameters:
**  	n -- size of restart rate array to initialize/enforce
**  	t -- maximum time range for restarts (0 == init)
**
**  Return value:
**  	TRUE -- OK to continue
**  	FALSE -- error
*/

static _Bool
dkimf_restart_check(int n, time_t t)
{
	static int idx;				/* last filled slot */
	static int alen;			/* allocated length */
	static time_t *list;

	if (t == 0)
	{
		size_t nbytes = (size_t) n * sizeof(time_t);

		list = (time_t *) malloc(nbytes);

		if (list == NULL)
			return FALSE;

		memset(list, '\0', nbytes);

		idx = 0;
		alen = n;

		return TRUE;
	}
	else
	{
		int which;

		time_t now;

		(void) time(&now);

		which = (idx - 1) % alen;
		if (which == -1)
			which = alen - 1;

		if (list[which] != 0 &&
		    list[which] + t > now)
			return FALSE;

		list[which] = now;
		idx++;

		return TRUE;
	}
}

/*
**  DKIMF_REPTOKEN -- replace a token in an input string with another string
**
**  Parameters:
**  	out -- output buffer
**  	outlen -- output buffer length
**  	in -- input string
**  	sub -- substitution string
**
**  Return value:
**  	Bytes of output; may be larger than "outlen" if "out" was too small.
*/

static size_t
dkimf_reptoken(u_char *out, size_t outlen, u_char *in, u_char *sub)
{
	size_t ret = 0;
	u_char *p;
	u_char *q;
	u_char *end;

	assert(out != NULL);
	assert(in != NULL);
	assert(sub != NULL);

	memset(out, '\0', outlen);

	q = out;
	end = q + outlen - 1;

	for (p = in; *p != '\0'; p++)
	{
		if (*p == '%')
		{
			size_t c;

			c = strlcpy((char *) q, (char *) sub, outlen - ret);
			q += c;
			ret += c;
		}
		else
		{
			if (q < end)
			{
				*q = *p;
				q++;
				ret++;
			}
		}
	}

	return ret;
}

/*
**  DKIMF_CHECKFSNODE -- check a filesystem node for safety
**
**  Parameters:
**  	path -- path of the node to check
**  	myuid -- executing user's effective uid
**  	myname -- executing user's login
**  	ino -- evaluated inode (returned)
**  	err -- error buffer
**  	errlen -- error buffer length
**
**  Return value:
**  	1 -- node is safe to use
**  	0 -- node is not safe to use
**  	-1 -- error (check errno)
**
**  Notes:
**  	"Safe" here means the target file cannot be read or written by anyone
**  	other than the executing user and the superuser.  The entire directory
**  	tree is checked from the root down after resolution of symlinks and
**  	references to "." and ".." looking for errant "write" bits on
**   	directories and the file itself.
**
**  	To prevent attacks through symbolic links, this function also returns
**  	the inode of the object it evaluated if that object was a file.  Thus,
**  	if the caller first opens the file but doesn't read from it, then the
**  	returned inode can be compared to the inode of the opened descriptor
**  	to ensure that what was opened was safe at the time open() was called.
**  	An inode of -1 is reported if some directory above the target was
**  	sufficiently locked down that the inode comparison isn't necessary.
**
**  	This still isn't bulletproof; there's a race between the time of the
**  	open() call and the result returned by this function.  I'm not sure if
**	that can be improved.
*/

static int
dkimf_checkfsnode(const char *path, uid_t myuid, char *myname, ino_t *ino,
                  char *err, size_t errlen)
{
	int status;
	struct passwd *pw;
	struct group *gr;
	struct stat s;

	assert(path != NULL);
	assert(myname != NULL);
	assert(ino != NULL);

	status = stat(path, &s);
	if (status != 0)
		return -1;

	if (S_ISREG(s.st_mode))
	{

		/* owned by root or by me */
		if (s.st_uid != 0 && s.st_uid != myuid)
		{
			if (err != NULL)
			{
				(void) snprintf(err, errlen,
				         "%s is not owned by the executing uid (%d)%s",
				         path, myuid,
				         myuid != 0 ? " or the superuser"
				                    : "");
			}
			return 0;
		}

		/* if group read/write, the group is only me and/or root */
		if ((s.st_mode & (S_IRGRP|S_IWGRP)) != 0)
		{
			int c;

			/* check if anyone else has this file's gid */
			pthread_mutex_lock(&pwdb_lock);
			setpwent();
			for (pw = getpwent(); pw != NULL; pw = getpwent())
			{
				if (pw->pw_uid != myuid &&
				    pw->pw_uid != 0 &&
				    s.st_gid == pw->pw_gid)
				{
					if (err != NULL)
					{
						gr = getgrgid(s.st_gid);
						(void) snprintf(err, errlen,
						         "%s is in group \"%s\" (gid %u) which has multiple users (e.g., \"%s\")",
						         path,
						         gr != NULL ? gr->gr_name : "unknown",
						         (unsigned int) s.st_gid,
						         pw->pw_name);
					}
					endpwent();
					pthread_mutex_unlock(&pwdb_lock);
					return 0;
				}
			}
			endpwent();

			/* check if this group contains anyone else */
			gr = getgrgid(s.st_gid);
			if (gr == NULL)
			{
				pthread_mutex_unlock(&pwdb_lock);
				return -1;
			}

			for (c = 0; gr->gr_mem[c] != NULL; c++)
			{
				if (strcmp(gr->gr_mem[c], myname) != 0 &&
				    strcmp(gr->gr_mem[c], SUPERUSER) != 0)
				{
					if (err != NULL)
					{
						(void) snprintf(err, errlen,
						         "%s is in group \"%s\" (gid %u) which has multiple users (e.g., \"%s\")",
						         path, gr->gr_name,
						         (unsigned int) s.st_gid,
						         gr->gr_mem[c]);
					}
					pthread_mutex_unlock(&pwdb_lock);
					return 0;
				}
			}

			pthread_mutex_unlock(&pwdb_lock);
		}

		/* not read/write by others */
		if ((s.st_mode & (S_IROTH|S_IWOTH)) != 0)
		{
			if (err != NULL)
			{
				(void) snprintf(err, errlen,
				         "%s can be read or written by other users",
				         path);
			}

			return 0;
		}

		*ino = s.st_ino;
	}
	else if (S_ISDIR(s.st_mode))
	{
		/* other write needs to be off */
		if ((s.st_mode & S_IWOTH) != 0)
		{
			if (err != NULL)
			{
				(void) snprintf(err, errlen,
				         "%s can be read or written by other users",
				         path);
			}
			return 0;
		}

		/* group write needs to be super-user or me only */
		if ((s.st_mode & S_IWGRP) != 0)
		{
			int c;

			/* check if anyone else has this file's gid */
			pthread_mutex_lock(&pwdb_lock);
			setpwent();
			for (pw = getpwent(); pw != NULL; pw = getpwent())
			{
				if (pw->pw_uid != myuid &&
				    pw->pw_uid != 0 &&
				    s.st_gid == pw->pw_gid)
				{
					if (err != NULL)
					{
						gr = getgrgid(s.st_gid);
						(void) snprintf(err, errlen,
						         "%s is in group \"%s\" (gid %u) which has multiple users (e.g., \"%s\")",
						         path,
						         gr != NULL ? gr->gr_name : "unknown",
						         (unsigned int) s.st_gid,
						         pw->pw_name);
					}

					endpwent();
					pthread_mutex_unlock(&pwdb_lock);
					return 0;
				}
			}
			endpwent();

			/* check if this group contains anyone else */
			gr = getgrgid(s.st_gid);
			if (gr == NULL)
			{
				pthread_mutex_unlock(&pwdb_lock);
				return -1;
			}

			for (c = 0; gr->gr_mem[c] != NULL; c++)
			{
				if (strcmp(gr->gr_mem[c], myname) != 0 &&
				    strcmp(gr->gr_mem[c], SUPERUSER) != 0)
				{
					if (err != NULL)
					{
						(void) snprintf(err, errlen,
						         "%s is in group \"%s\" (gid %u) which has multiple users (e.g., \"%s\")",
						         path, gr->gr_name,
						         (unsigned int) s.st_gid,
						         gr->gr_mem[c]);
					}

					pthread_mutex_unlock(&pwdb_lock);
					return 0;
				}
			}

			pthread_mutex_unlock(&pwdb_lock);
		}

		/* owner write needs to be super-user or me only */
		if ((s.st_mode & S_IWUSR) != 0 &&
		    (s.st_uid != 0 && s.st_uid != myuid))
		{
			if (err != NULL)
			{
				(void) snprintf(err, errlen,
				         "%s is writeable and owned by uid %u which is not the executing uid (%u)%s",
				         path, s.st_uid, myuid,
				         myuid != 0 ? " or the superuser"
				                    : "");
			}

			return 0;
		}

		/* if nobody else can execute below here, that's good enough */
		if ((s.st_mode & (S_IXGRP|S_IXOTH)) == 0)
		{
			*ino = (ino_t) -1;
			return 1;
		}
	}

	return 1;
}

/*
**  DKIMF_SECUREFILE -- determine whether a file at a specific path is "safe"
**
**  Parameters:
**  	path -- path to evaluate
**  	ino -- inode of evaluated object
** 	myuid -- user to impersonate (-1 means "me")
**  	err -- error buffer
**  	errlen -- bytes available at "err"
**
**  Return value:
**  	As for dkimf_checkfsnode().
**
**  Notes:
**  	If realpath() is available, this function checks the entire resolved
**  	filesystem tree from the root to the target file to ensure there are no
**  	permissions that would allow someone else on the system to either read
**  	or replace the file being evaluated.  (It's designed to check private
**  	key files.)  Without realpath(), only the target filename is checked.
*/

static int
dkimf_securefile(const char *path, ino_t *ino, uid_t myuid, char *err,
                 size_t errlen)
{
	int status;
	struct passwd *pw;
#ifdef HAVE_REALPATH
	char *p;
	char *q;
	char real[MAXPATHLEN + 1];
	char partial[MAXPATHLEN + 1];
	char myname[BUFRSZ + 1];
#endif /* HAVE_REALPATH */

	assert(path != NULL);
	assert(ino != NULL);

	/* figure out who I am */
	pthread_mutex_lock(&pwdb_lock);

	if (myuid == (uid_t) -1)
		pw = getpwuid(geteuid());
	else
		pw = getpwuid(myuid);

	if (pw == NULL)
	{
		pthread_mutex_unlock(&pwdb_lock);
		return -1;
	}

	if (myuid == (uid_t) -1)
		myuid = pw->pw_uid;

#ifdef HAVE_REALPATH
	strlcpy(myname, pw->pw_name, sizeof myname);
	pthread_mutex_unlock(&pwdb_lock);

	p = realpath(path, real);
	if (p == NULL)
		return -1;

	/*
	**  Check each node in the tree to ensure that:
	**  1) The file itself is read-write only by the executing user and the
	**  	super-user;
	**  2) No directory above the file is writeable by anyone other than
	**  	the executing user and the super-user.
	*/

	partial[0] = '/';
	partial[1] = '\0';

# ifdef HAVE_STRSEP
	q = real;
	while ((p = strsep(&q, "/")) != NULL)
# else /* HAVE_STRSEP */
	q = NULL;
	for (p = strtok_r(real, "/", &q);
	     p != NULL;
	     p = strtok_r(NULL, "/", &q))
# endif /* HAVE_STRSEP */
	{
		strlcat(partial, p, sizeof partial);
		status = dkimf_checkfsnode((const char *) partial,
		                           myuid, myname, ino, err, errlen);
		if (status != 1)
			return status;

		if (partial[1] != '\0')
			strlcat(partial, "/", sizeof partial); 
	}

	return 1;
#else /* HAVE_REALPATH */
	struct stat s;

	pthread_mutex_unlock(&pwdb_lock);

	status = stat(path, &s);
	if (status != 0)
		return -1;

	/* we don't own it and neither does the super-user; bad */
	if (s.st_uid != myuid && s.st_uid != 0)
		return 0;

	/* world readable/writeable; bad */
	if ((s.st_mode & (S_IROTH|S_IWOTH)) != 0)
		return 0;

	/* group read/write is bad if others are in that group */
	if ((s.st_mode & (S_IRGRP|S_IWGRP)) != 0)
	{
		int c;
		struct group *gr;

		/* get the file's group entry */
		pthread_mutex_lock(&pwdb_lock);
		gr = getgrgid(s.st_gid);
		if (gr == NULL)
		{
			pthread_mutex_unlock(&pwdb_lock);
			return -1;
		}

		for (c = 0; gr->gr_mem[c] != NULL; c++)
		{
			if (strcmp(gr->gr_mem[c], pw->pw_name) != 0)
			{
				pthread_mutex_unlock(&pwdb_lock);
				return 0;
			}
		}

		setpwent();
		while ((pw = getpwent()) != NULL)
		{
			if (pw->pw_uid != myuid && pw->pw_gid == s.st_gid)
			{
				endpwent();
				pthread_mutex_unlock(&pwdb_lock);
				return 0;
			}
		}
		endpwent();

		pthread_mutex_unlock(&pwdb_lock);
	}
		
	/* guess we're okay... */
	*ino = s.st_ino;
	return 1;
#endif /* HAVE_REALPATH */
}

/*
**  DKIMF_LOADKEY -- resolve a key
**
**  Parameters:
**  	buf -- key buffer
**  	buflen -- pointer to key buffer's length (updated)
**  	insecure -- key is insecure (returned)
**  	error -- buffer to receive error string
**  	errlen -- bytes available at "error"
**
**  Return value:
**  	TRUE on successful load, false otherwise.
**
**  Notes:
**  	The caller might pass a key or a filename in "buf".  If we think it's a
**  	filename, replace the contents of "buf" with what we find in that file.
*/

static _Bool
dkimf_loadkey(char *buf, size_t *buflen, _Bool *insecure, char *error,
              size_t errlen)
{
	ino_t ino;

	assert(buf != NULL);
	assert(buflen != NULL);

	if (buf[0] == '/' || (buf[0] == '.' && buf[1] == '/') ||
	    (buf[0] == '.' && buf[1] == '.' && buf[2] == '/'))
	{
		int fd;
		int status;
		ssize_t rlen;
		struct stat s;

		fd = open(buf, O_RDONLY);
		if (fd < 0)
		{
			if (error != NULL)
				strlcpy(error, strerror(errno), errlen);
			return FALSE;
		}

		status = fstat(fd, &s);
		if (status != 0 || !S_ISREG(s.st_mode))
		{
			if (error != NULL)
			{
				if (!S_ISREG(s.st_mode))
				{
					strlcpy(error, "Not a regular file",
					        errlen);
				}
				else
				{
					strlcpy(error, strerror(errno),
					        errlen);
				}
			}
			close(fd);
			return FALSE;
		}

		if (!dkimf_securefile(buf, &ino, (uid_t) -1, error, errlen) ||
		    (ino != (ino_t) -1 && ino != s.st_ino))
			*insecure = TRUE;
		else
			*insecure = FALSE;

		*buflen = MIN((size_t) s.st_size, *buflen);
		rlen = read(fd, buf, *buflen);
		close(fd);

		/* read() returns -1 on error; treat short reads (or any
		 * negative rlen) as failure rather than silently casting */
		if (rlen < 0 || (size_t) rlen < *buflen)
			return FALSE;
	}

	return TRUE;
}

/*
**  DKIMF_KEYTYPE -- determine the crypto type of a loaded private key
**
**  Parameters:
**  	keydata -- key material (PEM text or DER)
**  	keylen -- length of the key material
**
**  Return value:
**  	0 -- RSA
**  	1 -- Ed25519
**  	-1 -- unknown or unparseable
**
**  Notes:
**  	Used only to validate an optional KeyTable signing-algorithm field
**  	against the actual key.  libopendkim independently derives the signing
**  	algorithm from the key material at signing time, and that remains
**  	authoritative; this is a configuration sanity check, not key loading.
*/

static int
dkimf_keytype(const char *keydata, size_t keylen)
{
	int id;
	BIO *bio;
	EVP_PKEY *pkey;

	assert(keydata != NULL);

	/* PEM is NUL-terminated text; use its real length, not the buffer's */
	if (strncmp(keydata, "-----", 5) == 0)
	{
		keylen = strlen(keydata);
		bio = BIO_new_mem_buf(keydata, (int) keylen); /* key << INT_MAX */
		if (bio == NULL)
			return -1;
		pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
	}
	else
	{
		bio = BIO_new_mem_buf(keydata, (int) keylen); /* key << INT_MAX */
		if (bio == NULL)
			return -1;
		pkey = d2i_PrivateKey_bio(bio, NULL);
	}

	BIO_free(bio);

	if (pkey == NULL)
		return -1;

	id = EVP_PKEY_id(pkey);
	EVP_PKEY_free(pkey);

	switch (id)
	{
	  case EVP_PKEY_RSA:
		return 0;

#ifdef EVP_PKEY_ED25519
	  case EVP_PKEY_ED25519:
		return 1;
#endif /* EVP_PKEY_ED25519 */

	  default:
		return -1;
	}
}

/*
**  DKIMF_ADD_SIGNREQUEST -- add a signing request
**
**  Parameters:
**  	dfc -- message context
**  	keytable -- table from which to get key
**  	keyname -- name of private key to use
**  	signer -- signer identity to use
**  	signlen -- signature length
**
**  Return value:
**  	3 -- substitution token provided but domain not provided
**  	2 -- requested key could not be loaded
**  	1 -- requested key not found
**  	0 -- requested key added
**  	-1 -- requested key found but add failed (memory? or format)
*/

static int
dkimf_add_signrequest(struct dkimf_config *conf, struct msgctx *dfc,
                      DKIMF_DB keytable, const char *keyname,
                      const char *signer, ssize_t signlen)
{
	_Bool found = FALSE;
	size_t keydatasz = 0;
	struct signreq *new;
	struct dkimf_db_data dbd[4];
	char keydata[MAXBUFRSZ + 1];
	char domain[DKIM_MAXHOSTNAMELEN + 1];
	char selector[BUFRSZ + 1];
	char algorithm[BUFRSZ + 1];
	char err[BUFRSZ + 1];

	assert(conf != NULL);
	assert(dfc != NULL);

	/*
	**  Error out if we want the default key but the key or selector were
	**  not provided.
	*/

	if (keyname == NULL)
	{
		if (conf->conf_seckey == NULL ||
		    conf->conf_selector == NULL)
			return 1;
	}

	if (keytable != NULL)
	{
		_Bool insecure;

		assert(keyname != NULL);

		memset(domain, '\0', sizeof domain);
		memset(selector, '\0', sizeof selector);
		memset(keydata, '\0', sizeof keydata);
		memset(algorithm, '\0', sizeof algorithm);

		dbd[0].dbdata_buffer = domain;
		dbd[0].dbdata_buflen = sizeof domain - 1;
		dbd[0].dbdata_flags = DKIMF_DB_DATA_OPTIONAL;
		dbd[1].dbdata_buffer = selector;
		dbd[1].dbdata_buflen = sizeof selector - 1;
		dbd[1].dbdata_flags = DKIMF_DB_DATA_OPTIONAL;
		dbd[2].dbdata_buffer = keydata;
		dbd[2].dbdata_buflen = sizeof keydata - 1;
		dbd[2].dbdata_flags = DKIMF_DB_DATA_OPTIONAL;
		dbd[3].dbdata_buffer = algorithm;
		dbd[3].dbdata_buflen = sizeof algorithm - 1;
		dbd[3].dbdata_flags = DKIMF_DB_DATA_OPTIONAL;

		if (dkimf_db_get(keytable, keyname, strlen(keyname),
		                 dbd, 4, &found) != 0)
		{
			memset(err, '\0', sizeof err);
			(void) dkimf_db_strerror(keytable, err, sizeof err);

			if (dolog)
			{
				if (err[0] != '\0')
				{
					syslog(LOG_ERR,
					       "key '%s': dkimf_db_get(): %s",
					       keyname, err);
				}
				else
				{
					syslog(LOG_ERR,
					       "key '%s': dkimf_db_get() failed",
					       keyname);
				}
			}

			return -1;
		}

		if (!found)
			return 1;

		if (dbd[0].dbdata_buflen == 0 ||
		    dbd[0].dbdata_buflen == (size_t) -1 ||
		    dbd[1].dbdata_buflen == 0 ||
		    dbd[1].dbdata_buflen == (size_t) -1 ||
		    dbd[2].dbdata_buflen == 0 ||
		    dbd[2].dbdata_buflen == (size_t) -1)
		{
			if (dolog)
			{
				syslog(LOG_ERR,
				       "KeyTable entry for '%s' corrupt: %s field is empty or missing",
				       keyname,
				       (dbd[0].dbdata_buflen == 0 || dbd[0].dbdata_buflen == (size_t) -1) ? "domain" :
				       (dbd[1].dbdata_buflen == 0 || dbd[1].dbdata_buflen == (size_t) -1) ? "selector" :
				       "key");
			}

			return 2;
		}

		if (domain[0] == '%' && domain[1] == '\0' &&
		    dfc->mctx_domain[0] == '\0')
		{
			if (dolog)
			{
				syslog(LOG_ERR,
				       "KeyTable entry for '%s' cannot be resolved",
				       keyname);
			}

			return 3;
		}

		if (keydata[0] == '/')
		{
			u_char *d;
			u_char tmpdata[MAXBUFRSZ + 1];

			memset(tmpdata, '\0', sizeof tmpdata);

			if (domain[0] == '%' && domain[1] == '\0')
				d = dfc->mctx_domain;
			else
				d = (u_char *) domain;

			dkimf_reptoken(tmpdata, sizeof tmpdata,
			               (u_char *) keydata, d);

			memcpy(keydata, tmpdata, sizeof keydata);
		}

		keydatasz = sizeof keydata - 1;
		insecure = FALSE;
		if (!dkimf_loadkey(dbd[2].dbdata_buffer, &keydatasz,
		                   &insecure, err, sizeof err))
		{
			if (dolog)
			{
				syslog(LOG_ERR, "can't load key from %s: %s",
				       dbd[2].dbdata_buffer, err);
			}

			return 2;
		}

		if (insecure)
		{
			if (dolog)
			{
				int sev;

				sev = (conf->conf_safekeys ? LOG_ERR
				                           : LOG_WARNING);

				syslog(sev, "%s: key data is not secure: %s",
				       keyname, err);
			}

			if (conf->conf_safekeys)
				return 2;
		}

		/*
		**  An optional fourth KeyTable field may name a signing
		**  algorithm (for compatibility with configs written for
		**  upstream OpenDKIM).  We do not use it to select the
		**  algorithm -- libopendkim derives that from the key material
		**  itself, which is authoritative -- but if it is present and
		**  contradicts the actual key, warn so the admin can fix the
		**  table.  Signing still proceeds with the key-derived
		**  algorithm.
		*/

		if (algorithm[0] != '\0' &&
		    dbd[3].dbdata_buflen != 0 &&
		    dbd[3].dbdata_buflen != (size_t) -1)
		{
			int declared;
			int keytype;
			_Bool declared_ed25519 = FALSE;

			declared = dkimf_lookup_strtoint(algorithm, dkimf_sign);
			keytype = dkimf_keytype(dbd[2].dbdata_buffer, keydatasz);

#ifdef DKIM_SIGN_ED25519SHA256
			declared_ed25519 = (declared == DKIM_SIGN_ED25519SHA256);
#endif /* DKIM_SIGN_ED25519SHA256 */

			if (declared == -1)
			{
				if (dolog)
				{
					syslog(LOG_WARNING,
					       "key '%s': unrecognized signing algorithm '%s' in KeyTable; signing with key-derived algorithm",
					       keyname, algorithm);
				}
			}
			else if (keytype != -1 &&
			         declared_ed25519 != (keytype == 1))
			{
				if (dolog)
				{
					syslog(LOG_WARNING,
					       "key '%s': KeyTable algorithm '%s' does not match the key type; signing with key-derived algorithm",
					       keyname, algorithm);
				}
			}
		}
	}

	new = malloc(sizeof *new);
	if (new == NULL)
		return -1;

	new->srq_next = NULL;
	new->srq_dkim = NULL;
	new->srq_domain = NULL;
	new->srq_selector = NULL;
	new->srq_keydata = NULL;
	new->srq_keydatalen = 0;
	new->srq_signlen = signlen;
	if (signer != NULL && signer[0] != '\0')
		new->srq_signer = (u_char *) strdup(signer);
	else
		new->srq_signer = NULL;

	if (keytable != NULL)
	{
		if (domain[0] == '%' && domain[1] == '\0')
			new->srq_domain = (u_char *) strdup((char *) dfc->mctx_domain);
		else
			new->srq_domain = (u_char *) strdup((char *) domain);

		new->srq_selector = (u_char *) strdup((char *) selector);
		new->srq_keydata = (void *) malloc(keydatasz + 1);
		if (new->srq_keydata == NULL)
		{
			TRYFREE(new->srq_signer);
			TRYFREE(new->srq_domain);
			TRYFREE(new->srq_selector);
			free(new);
			return -1;
		}
		new->srq_keydatalen = keydatasz + 1;
		memset(new->srq_keydata, '\0', keydatasz + 1);
		memcpy(new->srq_keydata, dbd[2].dbdata_buffer, keydatasz);
	}

	if (dfc->mctx_srtail != NULL)
		dfc->mctx_srtail->srq_next = new;

	if (dfc->mctx_srhead == NULL)
		dfc->mctx_srhead = new;

	dfc->mctx_srtail = new;

	return 0;
}

/*
**  DKIMF_MSR_HEADER -- process headers for multiple signing requests
**
**  Parameters:
**  	srh -- head of the signature request list
**  	last -- last handle processed (returned on error)
**  	header -- header field name and value
**  	headerlen -- number of bytes at "header"
**
**  Return value:
**  	A DKIM_STAT_* constant, either DKIM_STAT_OK if all of them passed
**  	or some other constant if one of them failed.
*/

static DKIM_STAT
dkimf_msr_header(struct signreq *sr, DKIM **last, u_char *header,
                 size_t headerlen)
{
	DKIM_STAT status;

	assert(sr != NULL);
	assert(header != NULL);

	while (sr != NULL)
	{
		status = dkim_header(sr->srq_dkim, header, headerlen);
		if (status != DKIM_STAT_OK)
		{
			if (last != NULL)
				*last = sr->srq_dkim;
			return status;
		}
		sr = sr->srq_next;
	}

	return DKIM_STAT_OK;
}

/*
**  DKIMF_MSR_EOH -- process end-of-headers for multiple signing requests
**
**  Parameters:
**  	srh -- head of the signature request list
** 	last -- last DKIM handle processed (returned on error)
**
**  Return value:
**  	A DKIM_STAT_* constant, either DKIM_STAT_OK if all of them passed
**  	or some other constant if one of them failed.
*/

static DKIM_STAT
dkimf_msr_eoh(struct signreq *sr, DKIM **last)
{
	DKIM_STAT status;

	assert(sr != NULL);

	while (sr != NULL)
	{
		status = dkim_eoh(sr->srq_dkim);
		if (status != DKIM_STAT_OK)
		{
			if (last != NULL)
				*last = sr->srq_dkim;
			return status;
		}
		sr = sr->srq_next;
	}

	return DKIM_STAT_OK;
}

/*
**  DKIMF_MSR_BODY -- process a body chunk for multiple signing requests
**
**  Parameters:
**  	srh -- head of the signature request list
**  	last -- last DKIM handle processed (returned on error)
**  	body -- body chunk
**  	bodylen -- body length
**
**  Return value:
**  	A DKIM_STAT_* constant, either DKIM_STAT_OK if all of them passed
**  	or some other constant if one of them failed.
*/

static DKIM_STAT
dkimf_msr_body(struct signreq *sr, DKIM **last, u_char *body, size_t bodylen)
{
	DKIM_STAT status;

	assert(sr != NULL);
	assert(body != NULL);

	while (sr != NULL)
	{
		status = dkim_body(sr->srq_dkim, body, bodylen);
		if (status != DKIM_STAT_OK)
		{
			if (last != NULL)
				*last = sr->srq_dkim;
			return status;
		}

		sr = sr->srq_next;
	}

	return DKIM_STAT_OK;
}

/*
**  DKIMF_MSR_MINBODY -- determine minimum body required to satisfy all
**                       all open canonicalizations
**
**  Parameters:
**  	srh -- head of the signature request list
**
**  Return value:
**  	Maximum of all dkim_minbody() returns.
*/

static u_long
dkimf_msr_minbody(struct signreq *sr)
{
	u_long mb = 0;
	u_long ret = 0;

	assert(sr != NULL);

	while (sr != NULL)
	{
		ret = dkim_minbody(sr->srq_dkim);
		if (ret > mb)
			mb = ret;
		sr = sr->srq_next;
	}

	return mb;;
}

/*
**  DKIMF_MSR_EOM -- process end-of-message for multiple signing requests
**
**  Parameters:
**  	srh -- head of the signature request list
**  	last -- last DKIM handle processed (returned)
**
**  Return value:
**  	A DKIM_STAT_* constant, either DKIM_STAT_OK if all of them passed
**  	or some other constant if one of them failed.
*/

static DKIM_STAT
dkimf_msr_eom(struct signreq *sr, DKIM **last)
{
	_Bool testkey;
	DKIM_STAT status;

	assert(sr != NULL);

	while (sr != NULL)
	{
		status = dkim_eom(sr->srq_dkim, &testkey);
		if (status != DKIM_STAT_OK)
		{
			if (last != NULL)
				*last = sr->srq_dkim;
			return status;
		}
		sr = sr->srq_next;
	}

	return DKIM_STAT_OK;
}

/*
**  DKIMF_PRESCREEN -- check signatures against third-party limitations
**
**  Parameters:
**  	dkim -- DKIM handle
**  	sigs -- array of signatures
**  	nsigs -- size of signature array
**
**  Return value:
**  	DKIM_CBSTAT_CONTINUE
*/

static DKIM_CBSTAT
dkimf_prescreen(DKIM *dkim, DKIM_SIGINFO **sigs, int nsigs)
{
	int c;
	unsigned int ni = 0;
	u_char *domain;
	u_char *sdomain;
	SMFICTX *ctx;
	connctx cc;
	msgctx dfc;
	struct dkimf_config *conf;

	ctx = (SMFICTX *) dkim_get_user_context(dkim);
	cc = (connctx) dkimf_getpriv(ctx);
	conf = cc->cctx_config;
	dfc = cc->cctx_msg;
	domain = dkim_getdomain(dkim);

	if (conf->conf_maxverify > 0)
	{
		int n;
		_Bool *ig = NULL;

		ig = (_Bool *) malloc(sizeof(_Bool) * (size_t) nsigs);
		if (ig == NULL)
			return DKIM_CBSTAT_ERROR;

		/* mark everything to be ignored */
		for (c = 0; c < nsigs; c++)
			ig[c] = TRUE;

		n = (int) conf->conf_maxverify;

		if (conf->conf_thirdpartydb != NULL)
		{
			_Bool found;

			/* unmark sigs that are explicitly trusted */
			for (c = 0; c < nsigs; c++)
			{
				sdomain = dkim_sig_getdomain(sigs[c]);

				found = FALSE;

				if (dkimf_db_get(conf->conf_thirdpartydb,
				                 (char *) sdomain, 0, NULL, 0,
				                 &found) != 0)
				{
					free(ig);
					return DKIM_CBSTAT_ERROR;
				}

				if (found)
				{
					ig[c] = FALSE;
					n--;
				}
			}
		}

		/* unmark from the top down any that don't exceed the limit */
		for (c = 0; c < nsigs && n > 0; c++)
		{
			if (ig[c])
			{
				n--;
				ig[c] = FALSE;
			}
		}

		/* mark what's left to be ignored */
		for (c = 0; c < nsigs; c++)
		{
			if (ig[c])
			{
				dkim_sig_ignore(sigs[c]);
				ni++;
			}
		}

		if (conf->conf_dolog && ni > 0)
		{
			syslog(LOG_INFO, "%s: ignoring %u signature%s",
			       dkim_getid(dkim), ni, ni == 1 ? "" : "s");
		}

		free(ig);

		return DKIM_CBSTAT_CONTINUE;
	}

	/* ignore signatures which are neither first-party nor trusted */
	for (c = 0; c < nsigs; c++)
	{
		sdomain = dkim_sig_getdomain(sigs[c]);

		/* author domain */
		if (strcasecmp((char *) sdomain, (char *) domain) == 0)
			continue;

		/* trusted third party domain */
		if (conf->conf_thirdpartydb != NULL)
		{
			_Bool found = FALSE;

			if (dkimf_db_get(conf->conf_thirdpartydb,
			                    (char *) sdomain, 0, NULL, 0,
			                    &found) != 0)
				return DKIM_CBSTAT_ERROR;

			if (found)
				continue;
		}

		/* neither; arrange to ignore it */
		dkim_sig_ignore(sigs[c]);

		if (conf->conf_dolog)
		{
			syslog(LOG_INFO, "%s: ignoring signature from %s",
			       dfc->mctx_jobid, sdomain);
		}
	}

	return DKIM_CBSTAT_CONTINUE;
}

/*
**  DKIMF_ARFTYPE -- return ARF message type to report
**
**  Parameters:
**  	dfc -- DKIM filter context
**
**  Return value:
**  	An ARF_TYPE_* constant.
*/

static int
dkimf_arftype(msgctx dfc)
{
	assert(dfc != NULL);

	if (dfc->mctx_susp)
		return ARF_TYPE_FRAUD;
	else
		return ARF_TYPE_AUTHFAIL;
}

/*
**  DKIMF_ARFDKIM -- return an appropriate ARF DKIM failure code
**
**  Parameters:
**  	dfc -- DKIM filter context
**
**  Return value:
**  	An ARF_DKIMF_* constant.
*/

static int
dkimf_arfdkim(msgctx dfc)
{
	DKIM_SIGINFO *sig;

	assert(dfc != NULL);

	sig = dkim_getsignature(dfc->mctx_dkimv);
	if (sig == NULL)
		return ARF_DKIMF_UNKNOWN;

	if (dkim_sig_getbh(sig) == DKIM_SIGBH_MISMATCH)
		return ARF_DKIMF_BODYHASH;

	switch (dkim_sig_geterror(sig))
	{
	  case DKIM_SIGERROR_BADSIG:
		return ARF_DKIMF_SIGNATURE;

	  case DKIM_SIGERROR_KEYREVOKED:
		return ARF_DKIMF_REVOKED;

	  case DKIM_SIGERROR_VERSION:
	  case DKIM_SIGERROR_INVALID_HC:
	  case DKIM_SIGERROR_INVALID_BC:
	  case DKIM_SIGERROR_MISSING_A:
	  case DKIM_SIGERROR_INVALID_A:
	  case DKIM_SIGERROR_MISSING_H:
	  case DKIM_SIGERROR_INVALID_L:
	  case DKIM_SIGERROR_INVALID_Q:
	  case DKIM_SIGERROR_INVALID_QO:
	  case DKIM_SIGERROR_MISSING_D:
	  case DKIM_SIGERROR_EMPTY_D:
	  case DKIM_SIGERROR_MISSING_S:
	  case DKIM_SIGERROR_EMPTY_S:
	  case DKIM_SIGERROR_MISSING_B:
	  case DKIM_SIGERROR_EMPTY_B:
	  case DKIM_SIGERROR_CORRUPT_B:
	  case DKIM_SIGERROR_DNSSYNTAX:
	  case DKIM_SIGERROR_MISSING_BH:
	  case DKIM_SIGERROR_EMPTY_BH:
	  case DKIM_SIGERROR_CORRUPT_BH:
	  case DKIM_SIGERROR_MULTIREPLY:
	  case DKIM_SIGERROR_EMPTY_H:
	  case DKIM_SIGERROR_INVALID_H:
	  case DKIM_SIGERROR_TOOLARGE_L:
	  case DKIM_SIGERROR_KEYVERSION:
	  case DKIM_SIGERROR_KEYUNKNOWNHASH:
	  case DKIM_SIGERROR_KEYTYPEMISSING:
	  case DKIM_SIGERROR_KEYTYPEUNKNOWN:
		return ARF_DKIMF_SYNTAX;

	  default:
		return ARF_DKIMF_OTHER;
	}
}

/*
**  DKIMF_REPORTADDR -- set reporting address
**
**  Parameters:
**  	conf -- current configuration
**
**  Return value:
**  	None.
*/

static void
dkimf_reportaddr(struct dkimf_config *conf)
{
	uid_t uid;
	struct passwd *pw;

	assert(conf != NULL);

	/* --- configured address --- */
	if (conf->conf_reportaddr != NULL)
	{
		int status;
		u_char *user;
		u_char *domain;
		u_char env[MAXADDRESS + 1];

		strlcpy(reportaddr, conf->conf_reportaddr, sizeof reportaddr);
		strlcpy((char *) env, conf->conf_reportaddr, sizeof env);

		status = dkim_mail_parse(env, &user, &domain);
		if (status == 0 && user != NULL && domain != NULL)
		{
			int n = snprintf(reportcmd, sizeof reportcmd,
							 "%s -t -f%s@%s",
					conf->conf_mtacommand, user, domain);

			if (n >= 0 && (size_t)n < sizeof reportcmd)
				return;

			if (dolog)
				syslog(LOG_ERR,
					   "reportcmd truncated; using default");
		}
		else
		{
			if (dolog)
				syslog(LOG_ERR,
					   "error parsing ReportAddress; using default");
		}
	}

	/* --- fallback --- */
	uid = geteuid();
	pw = getpwuid(uid);

	if (pw == NULL)
	{
		int n = snprintf(reportaddr, sizeof reportaddr,
						 "%u@%s", uid, myhostname);

		if (n < 0 || (size_t)n >= sizeof reportaddr)
		{
			if (dolog)
				syslog(LOG_ERR, "reportaddr truncated");
			return;
		}
	}
	else
	{
		int n = snprintf(reportaddr, sizeof reportaddr,
						 "%s@%s", pw->pw_name, myhostname);

		if (n < 0 || (size_t)n >= sizeof reportaddr)
		{
			if (dolog)
				syslog(LOG_ERR, "reportaddr truncated");
			return;
		}
	}

	{
		int n = snprintf(reportcmd, sizeof reportcmd,
						 "%s -t -f%s",
				   conf->conf_mtacommand, reportaddr);

		if (n < 0 || (size_t)n >= sizeof reportcmd)
		{
			if (dolog)
				syslog(LOG_ERR, "reportcmd truncated");
			return;
		}
	}
}

/*
**  DKIMF_LOOKUP_STRTOINT -- look up the integer code for a config option
**                           or value
**
**  Parameters:
**  	opt -- option to look up
**  	table -- lookup table to use
**
**  Return value:
**  	Integer version of the option, or -1 on error.
*/

static int
dkimf_lookup_strtoint(const char *opt, struct lookup *table)
{
	int c;

	for (c = 0; ; c++)
	{
		if (table[c].str == NULL ||
		    strcasecmp(opt, table[c].str) == 0)
			return table[c].code;
	}
}

/*
**  DKIMF_LOOKUP_INTTOSTR -- look up the string matching an internal code
**
**  Parameters:
**  	code -- code to look up
**  	table -- lookup table to use
**
**  Return value:
**  	String version of the option, or NULL on error.
*/

static const char *
dkimf_lookup_inttostr(int code, struct lookup *table)
{
	int c;

	for (c = 0; ; c++)
	{
		if (table[c].code == -1 || table[c].code == code)
			return table[c].str;
	}

	assert(0);
	/* NOTREACHED */
}

/*
**  DKIMF_GETDKIM -- retrieve DKIM handle in use
**
**  Parameters:
**  	vp -- opaque pointer (from test.c)
**
**  Return value:
**  	DKIM handle in use, or NULL.
*/

DKIM *
dkimf_getdkim(void *vp)
{
	struct connctx *cc;

	assert(vp != NULL);

	cc = vp;
	if (cc->cctx_msg != NULL)
		return cc->cctx_msg->mctx_dkimv;
	else
		return NULL;
}

/*
**  DKIMF_GETSRLIST -- retrieve signing request list
**
**  Parameters:
**  	vp -- opaque pointer (from test.c)
**
**  Return value:
**  	Head of the signing request list.
*/

struct signreq *
dkimf_getsrlist(void *vp)
{
	struct connctx *cc;

	assert(vp != NULL);

	cc = vp;
	if (cc->cctx_msg != NULL)
		return cc->cctx_msg->mctx_srhead;
	else
		return NULL;
}

/*
**  DKIMF_SIGHANDLER -- signal handler
**
**  Parameters:
**  	sig -- signal received
**
**  Return value:
**  	None.
*/

static void
dkimf_sighandler(int sig)
{
	if (sig == SIGINT || sig == SIGTERM || sig == SIGHUP)
	{
		diesig = sig;
		die = TRUE;
	}
	else if (sig == SIGUSR1 && !die)
	{
		if (conffile != NULL)
			reload = TRUE;
	}
}

/*
**  DKIMF_RELOADER -- reload signal thread
**
**  Parameters:
**  	vp -- void pointer required by thread API but not used
**
**  Return value:
**  	NULL.
*/

static void *
dkimf_reloader(/* UNUSED */ void *vp)
{
	int sig;
	sigset_t mask;

	(void) vp;

	(void) pthread_detach(pthread_self());

	sigemptyset(&mask);
	sigaddset(&mask, SIGUSR1);

	while (!die)
	{
		(void) sigwait(&mask, &sig);

		if (conffile != NULL)
			reload = TRUE;
	}

	return NULL;
}

#ifdef HAVE_LIBSYSTEMD
/*
**  DKIMF_WATCHDOG -- systemd watchdog keep-alive thread
**
**  Runs in its own thread so that the watchdog is fed independently of the
**  milter worker threads.  A request that blocks on slow DNS, an oversized
**  header set, or anything else therefore cannot starve the keep-alive and
**  trip a spurious restart; only an actual hang of the whole process (this
**  thread included) lets the timer expire.
**
**  Parameters:
**  	vp -- void pointer required by thread API but not used
**
**  Return value:
**  	NULL.
*/

static void *
dkimf_watchdog(/* UNUSED */ void *vp)
{
	uint64_t usec = 0;
	unsigned int interval;

	(void) vp;

	(void) pthread_detach(pthread_self());

	/*
	**  Nothing to do unless the unit set WatchdogSec=; sd_watchdog_enabled()
	**  returns <= 0 otherwise and the thread simply exits.
	*/
	if (sd_watchdog_enabled(0, &usec) <= 0)
		return NULL;

	/*
	**  Feed the watchdog at half the configured interval, as systemd
	**  recommends, with a one-second floor so a tiny WatchdogSec cannot
	**  spin this thread.  usec is the full interval in microseconds.
	*/
	interval = (unsigned int) (usec / 2 / 1000000ULL);
	if (interval < 1)
		interval = 1;

	while (!die)
	{
		(void) sd_notify(0, "WATCHDOG=1");
		(void) sleep(interval);
	}

	return NULL;
}
#endif /* HAVE_LIBSYSTEMD */

/*
**  DKIMF_KILLCHILD -- kill child process
**
**  Parameters:
**  	pid -- process ID to signal
**  	sig -- signal to use
**  	do_log -- log it?
**
**  Return value:
**  	None.
*/

static void
dkimf_killchild(pid_t pid, int sig, _Bool do_log)
{
	if (kill(pid, sig) == -1 && do_log)
	{
		syslog(LOG_ERR, "kill(%d, %d): %s", pid, sig,
		       strerror(errno));
	}
}

/*
**  DKIMF_ZAPKEY -- clobber the copy of the private key
**
**  Parameters:
**  	conf -- configuration handle in which to clobber the key
**
**  Return value:
**  	None.
*/

static void
dkimf_zapkey(struct dkimf_config *conf)
{
	assert(conf != NULL);

	if (conf->conf_seckey != NULL)
	{
		memset(conf->conf_seckey, '\0', conf->conf_keylen);
		free(conf->conf_seckey);
		conf->conf_seckey = NULL;
	}
}

/*
**  DKIMF_CONFIG_NEW -- get a new configuration handle
**
**  Parameters:
**  	None.
**
**  Return value:
**  	A new configuration handle, or NULL on error.
*/

static struct dkimf_config *
dkimf_config_new(void)
{
	struct dkimf_config *new;

	new = (struct dkimf_config *) malloc(sizeof(struct dkimf_config));
	if (new == NULL)
		return NULL;

	memset(new, '\0', sizeof(struct dkimf_config));
	new->conf_hdrcanon = DKIM_CANON_DEFAULT;
	new->conf_bodycanon = DKIM_CANON_DEFAULT;
	new->conf_dnstimeout = DEFTIMEOUT;
	new->conf_maxverify = DEFMAXVERIFY;
	new->conf_maxhdrsz = DEFMAXHDRSZ;
	new->conf_signbytes = -1L;
	new->conf_sigmintype = SIGMIN_BYTES;
	new->conf_safekeys = TRUE;
	new->conf_mtacommand = SENDMAIL_PATH;
	new->conf_selectcanonhdr = SELECTCANONHDR;
	new->conf_checksigningtable = init_checksigningtable;

	memcpy(&new->conf_handling, &defaults, sizeof new->conf_handling);

	return new;
}

/*
**  DKIMF_CONFIG_FREE -- destroy a configuration handle
**
**  Parameters:
**  	conf -- pointer to the configuration handle to be destroyed
**
**  Return value:
**  	None.
*/

static void
dkimf_config_free(struct dkimf_config *conf)
{
	assert(conf != NULL);
	if (conf->conf_refcnt != 0)
	{
		syslog(LOG_CRIT,
		       "dkimf_config_free: conf_refcnt = %u, expected 0",
		       conf->conf_refcnt);
		return;
	}

	dkimf_zapkey(conf);

	if (conf->conf_libopendkim != NULL)
		dkim_close(conf->conf_libopendkim);

	if (conf->conf_testdnsdb != NULL)
		dkimf_db_close(conf->conf_testdnsdb);

	if (conf->conf_domainsdb != NULL)
		dkimf_db_close(conf->conf_domainsdb);

	if (conf->conf_bldb != NULL)
		dkimf_db_close(conf->conf_bldb);

	if (conf->conf_domlist != NULL)
		free(conf->conf_domlist);

	if (conf->conf_omithdrdb != NULL)
		dkimf_db_close(conf->conf_omithdrdb);

	if (conf->conf_thirdpartydb != NULL)
		dkimf_db_close(conf->conf_thirdpartydb);

	if (conf->conf_signhdrsdb != NULL)
		dkimf_db_close(conf->conf_signhdrsdb);

	if (conf->conf_senderhdrsdb != NULL)
		dkimf_db_close(conf->conf_senderhdrsdb);

	if (conf->conf_oversigndb != NULL)
		dkimf_db_close(conf->conf_oversigndb);

	if (conf->conf_mtasdb != NULL)
		dkimf_db_close(conf->conf_mtasdb);

	if (conf->conf_macrosdb != NULL)
		dkimf_db_close(conf->conf_macrosdb);

	if (conf->conf_mbsdb != NULL)
		dkimf_db_close(conf->conf_mbsdb);

	if (conf->conf_dontsigntodb != NULL)
		dkimf_db_close(conf->conf_dontsigntodb);

	if (conf->conf_remardb != NULL)
		dkimf_db_close(conf->conf_remardb);

	if (conf->conf_authservid != NULL)
		free(conf->conf_authservid);

	if (conf->conf_peerdb != NULL)
		dkimf_db_close(conf->conf_peerdb);

	if (conf->conf_internal != NULL)
		dkimf_db_close(conf->conf_internal);

	if (conf->conf_exignore != NULL)
		dkimf_db_close(conf->conf_exignore);

	if (conf->conf_exemptdb != NULL)
		dkimf_db_close(conf->conf_exemptdb);



	if (conf->conf_nosignpats != NULL)
	{
		int n;

		for (n = 0; conf->conf_nosignpats[n] != NULL; n++)
			regfree(conf->conf_nosignpats[n]);

		free(conf->conf_nosignpats);
	}

	if (conf->conf_resigndb != NULL)
		dkimf_db_close(conf->conf_resigndb);


#ifdef USE_LUA
	if (conf->conf_setupscript != NULL)
		free(conf->conf_setupscript);
	if (conf->conf_setupfunc != NULL)
		free(conf->conf_setupfunc);
	if (conf->conf_screenscript != NULL)
		free(conf->conf_screenscript);
	if (conf->conf_screenfunc != NULL)
		free(conf->conf_screenfunc);
	if (conf->conf_finalscript != NULL)
		free(conf->conf_finalscript);
	if (conf->conf_finalfunc != NULL)
		free(conf->conf_finalfunc);
#endif /* USE_LUA */

	if (conf->conf_keytabledb != NULL)
		dkimf_db_close(conf->conf_keytabledb);
	if (conf->conf_signtabledb != NULL)
		dkimf_db_close(conf->conf_signtabledb);

	if (conf->conf_data != NULL)
		config_free(conf->conf_data);

	free(conf);
}

/*
**  DKIMF_PARSEHANDLER -- parse a handler
**
**  Parameters:
**  	cfg -- configuration data structure to check
**  	name -- handler name
**  	hndl -- handler structure to update
**  	err -- error buffer
**  	errlen -- bytes available at "err"
**
**  Return value:
**  	TRUE if no error, FALSE if error.
*/

static _Bool
dkimf_parsehandler(struct config *cfg, const char *name, struct handling *hndl,
                   char *err, size_t errlen)
{
	int action;
	char *val = NULL;

	assert(name != NULL);
	assert(strncasecmp(name, "on-", 3) == 0);
	assert(hndl != NULL);
	assert(err != NULL);

	if (cfg == NULL)
		return TRUE;

	(void) config_get(cfg, name, &val, sizeof val);

	if (val == NULL)
		return TRUE;

	action = dkimf_lookup_strtoint(val, dkimf_values);
	if (action == -1) {
		(void) snprintf(err, errlen, "invalid handling value \"%s\"", val);
		return -1;
	}

	switch (dkimf_lookup_strtoint(name + 3, dkimf_params))
	{
	  case HNDL_DEFAULT:
		hndl->hndl_nosig = action;
		hndl->hndl_badsig = action;
		hndl->hndl_dnserr = action;
		hndl->hndl_internal = action;
		hndl->hndl_security = action;
		hndl->hndl_nokey = action;
		hndl->hndl_siggen = action;
		return TRUE;

	  case HNDL_NOSIGNATURE:
		hndl->hndl_nosig = action;
		return TRUE;

	  case HNDL_BADSIGNATURE:
		hndl->hndl_badsig = action;
		return TRUE;

	  case HNDL_DNSERROR:
		hndl->hndl_dnserr = action;
		return TRUE;

	  case HNDL_INTERNAL:
		hndl->hndl_internal = action;
		return TRUE;

	  case HNDL_SECURITY:
		hndl->hndl_security = action;
		return TRUE;

	  case HNDL_NOKEY:
		hndl->hndl_nokey = action;
		return TRUE;

	  case HNDL_SIGGEN:
		hndl->hndl_siggen = action;
		return TRUE;

	  case HNDL_WEAKALG:
		/*
		**  RFC 8301: rsa-sha1 must never be treated as a valid result,
		**  so "accept" (which would report dkim=pass) is not a legal
		**  disposition here.  On-WeakAlgorithm selects only what to do
		**  with the message; the signature is always refused.
		*/
		if (action == DKIMF_MILTER_ACCEPT)
		{
			(void) snprintf(err, errlen,
			                "On-WeakAlgorithm does not allow \"accept\"; rsa-sha1 cannot be trusted (RFC 8301)");
			return FALSE;
		}
		hndl->hndl_weakalg = action;
		return TRUE;

	  default:
		(void) snprintf(err, errlen, "unknown handling key \"%s\"", name);
		return FALSE;
	}
}

/*
**  DKIMF_CONFIG_LOAD -- load a configuration handle based on file content
**
**  Parameters:
**  	data -- configuration data loaded from config file
**  	conf -- configuration structure to load
**  	err -- where to write errors
**  	errlen -- bytes available at "err"
**  	become -- pretend we're the named user (can be NULL)
**
**  Return value:
**  	0 -- success
**  	!0 -- error
**
**  Side effects:
**  	openlog() may be called by this function
*/

static int
dkimf_config_load(struct config *data, struct dkimf_config *conf,
                  char *err, size_t errlen, char *become)
{
	int maxsign;
	u_int dbflags = 0;
	char *str;
	char confstr[BUFRSZ + 1];
	char basedir[MAXPATHLEN + 1];

	assert(conf != NULL);
	assert(err != NULL);

	memset(basedir, '\0', sizeof basedir);
	memset(confstr, '\0', sizeof confstr);

	if (data != NULL)
	{
		int tmpint;

		if (use_cf_checksigningtable)
		{
			(void) config_get(data, "CheckSigningTable",
			                  &conf->conf_checksigningtable,
			                  sizeof conf->conf_checksigningtable);
		}
		(void) config_get(data, "DNSConnect",
		                  &conf->conf_dnsconnect,
		                  sizeof conf->conf_dnsconnect);

		(void) config_get(data, "ResolverTracing",
		                  &conf->conf_restrace,
		                  sizeof conf->conf_restrace);

		(void) config_get(data, "AlwaysAddARHeader",
		                  &conf->conf_alwaysaddar,
		                  sizeof conf->conf_alwaysaddar);

		str = NULL;
		(void) config_get(data, "AuthservID", &str, sizeof str);
		if (str != NULL)
		{
			if (strcmp(str, "HOSTNAME") == 0)
				conf->conf_authservid = strdup(myhostname);
			else	
				conf->conf_authservid = strdup(str);
		}

		(void) config_get(data, "AuthservIDWithJobID",
		                  &conf->conf_authservidwithjobid,
		                  sizeof conf->conf_authservidwithjobid);

#ifdef HAVE_LIBCURL
		(void) config_get(data, "SMTPURI", &conf->conf_smtpuri,
		                  sizeof conf->conf_smtpuri);
#endif /* HAVE_LIBCURL */

		str = NULL;
		(void) config_get(data, "BaseDirectory", &str, sizeof str);
		if (str != NULL)
			strlcpy(basedir, str, sizeof basedir);

		if (conf->conf_canonstr == NULL)
		{
			(void) config_get(data, "Canonicalization",
			                  &conf->conf_canonstr,
			                  sizeof conf->conf_canonstr);
		}

		(void) config_get(data, "ClockDrift", &conf->conf_clockdrift,
		                  sizeof conf->conf_clockdrift);


		(void) config_get(data, "Diagnostics", &conf->conf_ztags,
		                  sizeof conf->conf_ztags);

		(void) config_get(data, "DiagnosticDirectory",
		                  &conf->conf_diagdir,
		                  sizeof conf->conf_diagdir);

		(void) config_get(data, "RedirectFailuresTo",
		                  &conf->conf_redirect,
		                  sizeof conf->conf_redirect);

		(void) config_get(data, "ResignMailTo",
		                  &conf->conf_resign,
		                  sizeof conf->conf_resign);
		(void) config_get(data, "ResignAll",
		                  &conf->conf_resignall,
		                  sizeof conf->conf_resignall);

		if (conf->conf_dnstimeout == DEFTIMEOUT)
		{
			(void) config_get(data, "DNSTimeout",
			                  &conf->conf_dnstimeout,
			                  sizeof conf->conf_dnstimeout);
		}

		(void) config_get(data, "EnableCoredumps",
		                  &conf->conf_enablecores,
		                  sizeof conf->conf_enablecores);

		(void) config_get(data, "MinimumKeyBits",
		                  &conf->conf_minkeybits,
		                  sizeof conf->conf_minkeybits);

		(void) config_get(data, "RequestReports",
		                  &conf->conf_reqreports,
		                  sizeof conf->conf_reqreports);

		(void) config_get(data, "RequireSafeKeys",
		                  &conf->conf_safekeys,
		                  sizeof conf->conf_safekeys);

		(void) config_get(data, "TestDNSData",
		                  &conf->conf_testdnsdata,
		                  sizeof conf->conf_testdnsdata);

		(void) config_get(data, "NoHeaderB",
		                  &conf->conf_noheaderb,
		                  sizeof conf->conf_noheaderb);

		(void) config_get(data, "FixCRLF",
		                  &conf->conf_fixcrlf,
		                  sizeof conf->conf_fixcrlf);

		(void) config_get(data, "KeepTemporaryFiles",
		                  &conf->conf_keeptmpfiles,
		                  sizeof conf->conf_keeptmpfiles);

		(void) config_get(data, "StrictHeaders",
		                  &conf->conf_stricthdrs,
		                  sizeof conf->conf_stricthdrs);

		(void) config_get(data, "TemporaryDirectory",
		                  &conf->conf_tmpdir,
		                  sizeof conf->conf_tmpdir);

		(void) config_get(data, "MaximumHeaders", &conf->conf_maxhdrsz,
		                  sizeof conf->conf_maxhdrsz);

		(void) config_get(data, "MaximumSignaturesToVerify",
		                  &conf->conf_maxverify,
		                  sizeof conf->conf_maxverify);

		(void) config_get(data, "IdentityHeader",
				  &conf->conf_identityhdr,
				  sizeof conf->conf_identityhdr);

		(void) config_get(data, "IdentityHeaderRemove",
		                  &conf->conf_rmidentityhdr,
		                  sizeof conf->conf_rmidentityhdr);

		if (conf->conf_siglimit == NULL)
		{
			(void) config_get(data, "Minimum",
			                  &conf->conf_siglimit,
			                  sizeof conf->conf_siglimit);
		}

		if (conf->conf_modestr == NULL)
		{
			(void) config_get(data, "Mode", &conf->conf_modestr,
			                  sizeof conf->conf_modestr);
		}

		if (!dkimf_parsehandler(data, "On-Default",
		                        &conf->conf_handling, err, errlen) ||
		    !dkimf_parsehandler(data, "On-BadSignature",
		                        &conf->conf_handling, err, errlen) ||
		    !dkimf_parsehandler(data, "On-DNSError",
		                        &conf->conf_handling, err, errlen) ||
		    !dkimf_parsehandler(data, "On-KeyNotFound",
		                        &conf->conf_handling, err, errlen) ||
		    !dkimf_parsehandler(data, "On-InternalError",
		                        &conf->conf_handling, err, errlen) ||
		    !dkimf_parsehandler(data, "On-NoSignature",
		                        &conf->conf_handling, err, errlen) ||
		    !dkimf_parsehandler(data, "On-PolicyError",
		                        &conf->conf_handling, err, errlen) ||
		    !dkimf_parsehandler(data, "On-Security",
		                        &conf->conf_handling, err, errlen) ||
		    !dkimf_parsehandler(data, "On-SignatureError",
		                        &conf->conf_handling, err, errlen) ||
		    !dkimf_parsehandler(data, "On-WeakAlgorithm",
		                        &conf->conf_handling, err, errlen))
			return -1;

		(void) config_get(data, "RemoveARAll", &conf->conf_remarall,
		                  sizeof conf->conf_remarall);

		(void) config_get(data, "KeepAuthResults", &conf->conf_keepar,
		                  sizeof conf->conf_keepar);

		(void) config_get(data, "RemoveOldSignatures",
		                  &conf->conf_remsigs,
		                  sizeof conf->conf_remsigs);

		if (!conf->conf_reqhdrs)
		{
			(void) config_get(data, "RequiredHeaders",
			                  &conf->conf_reqhdrs,
			                  sizeof conf->conf_reqhdrs);
		}

		if (conf->conf_selector == NULL)
		{
			(void) config_get(data, "Selector",
			                  &conf->conf_selector,
			                  sizeof conf->conf_selector);
		}

		if (conf->conf_sendermacro == NULL)
		{
			(void) config_get(data, "SenderMacro",
			                  &conf->conf_sendermacro,
			                  sizeof conf->conf_sendermacro);
		}

		if (!conf->conf_sendreports)
		{
			(void) config_get(data, "SendReports",
			                  &conf->conf_sendreports,
			                  sizeof conf->conf_sendreports);
		}
		(void) config_get(data, "MTACommand",
		                  &conf->conf_mtacommand,
		                  sizeof conf->conf_mtacommand);

		(void) config_get(data, "ReportAddress",
		                  &conf->conf_reportaddr,
		                  sizeof conf->conf_reportaddr);

		(void) config_get(data, "ReportBccAddress",
		                  &conf->conf_reportaddrbcc,
		                  sizeof conf->conf_reportaddrbcc);

		if (conf->conf_signalgstr == NULL)
		{
			(void) config_get(data, "SignatureAlgorithm",
			                  &conf->conf_signalgstr,
			                  sizeof conf->conf_signalgstr);
		}

		tmpint = 0;
		(void) config_get(data, "SignatureTTL", &tmpint,
		                  sizeof tmpint);
		if (tmpint != 0)
			conf->conf_sigttl = (unsigned long) tmpint;

		if (!conf->conf_subdomains)
		{
			(void) config_get(data, "SubDomains",
			                  &conf->conf_subdomains,
			                  sizeof conf->conf_subdomains);
		}

		if (!conf->conf_dolog)
		{
			(void) config_get(data, "Syslog", &conf->conf_dolog,
			                  sizeof conf->conf_dolog);
		}

		if (!conf->conf_logwhy)
		{
			(void) config_get(data, "LogWhy", &conf->conf_logwhy,
			                  sizeof conf->conf_logwhy);
		}

		(void) config_get(data, "LogResults", &conf->conf_logresults,
		                  sizeof conf->conf_logresults);

		(void) config_get(data, "MultipleSignatures",
		                  &conf->conf_multisig,
		                  sizeof conf->conf_multisig);

		(void) config_get(data, "SyslogSuccess",
		                  &conf->conf_dolog_success,
		                  sizeof conf->conf_dolog_success);

		(void) config_get(data, "WeakSyntaxChecks",
		                  &conf->conf_weaksyntax,
		                  sizeof conf->conf_weaksyntax);


		(void) config_get(data, "IgnoreMalformedMail",
		                  &conf->conf_passmalformed,
		                  sizeof conf->conf_passmalformed);

		(void) config_get(data, "DisableCryptoInit",
		                  &conf->conf_disablecryptoinit,
		                  sizeof conf->conf_disablecryptoinit);

		if (!conf->conf_addswhdr)
		{
			(void) config_get(data, "X-Header",
			                  &conf->conf_addswhdr,
			                  sizeof conf->conf_addswhdr);

			if (conf->conf_addswhdr)
			{
				if (conf->conf_dolog)
				{
					syslog(LOG_WARNING,
					       "\"X-Header\" deprecated; use \"SoftwareHeader\" instead");
				}
			}
			else
			{
				(void) config_get(data, "SoftwareHeader",
				                  &conf->conf_addswhdr,
				                  sizeof conf->conf_addswhdr);
			}
		}

		(void) config_get(data, "DomainKeysCompat",
		                  &conf->conf_acceptdk,
		                  sizeof conf->conf_acceptdk);

		(void) config_get(data, "CaptureUnknownErrors",
		                  &conf->conf_capture,
		                  sizeof conf->conf_capture);

#ifndef SMFIF_QUARANTINE
		if (conf->conf_capture)
		{
			strlcpy(err,
			        "quarantining not supported (required for CaptureUnknownErrors",
			        errlen);

			return -1;
		}
#endif /* SMFIF_QUARANTINE */

		(void) config_get(data, "AllowSHA1Only",
		                  &conf->conf_allowsha1only,
		                  sizeof conf->conf_allowsha1only);

		(void) config_get(data, "Nameservers",
		                  &conf->conf_nslist,
		                  sizeof conf->conf_nslist);

		(void) config_get(data, "TrustAnchorFile",
		                  &conf->conf_trustanchorpath,
		                  sizeof conf->conf_trustanchorpath);

		if (conf->conf_trustanchorpath != NULL &&
		    access(conf->conf_trustanchorpath, R_OK) != 0)
		{
			(void) snprintf(err, errlen, "%s: %s",
			         conf->conf_trustanchorpath, strerror(errno));
			return -1;
		}

		(void) config_get(data, "ResolverConfiguration",
		                  &conf->conf_resolverconfig,
		                  sizeof conf->conf_resolverconfig);

		str = NULL;
		(void) config_get(data, "BogusKey", &str, sizeof str);
		if (str != NULL)
		{
			int c;

			c = dkimf_lookup_strtoint(str, dkimf_keyactions);
			if (c == -1)
			{
				(void) snprintf(err, errlen,
				         "unknown key action '%s'", str);
				return -1;
			}

			conf->conf_boguskey = (unsigned int) c;
		}
		else
		{
			conf->conf_boguskey = DKIMF_KEYACTIONS_FAIL;
		}

		str = NULL;
		(void) config_get(data, "UnprotectedKey", &str, sizeof str);
		if (str != NULL)
		{
			int c;

			c = dkimf_lookup_strtoint(str, dkimf_keyactions);
			if (c == -1)
			{
				(void) snprintf(err, errlen,
				         "unknown key action '%s'", str);
				return -1;
			}

			conf->conf_unprotectedkey = (unsigned int) c;
		}
		else
		{
			conf->conf_unprotectedkey = DKIMF_KEYACTIONS_NONE;
		}

#ifdef USE_LUA
		str = NULL;
		(void) config_get(data, "SetupPolicyScript", &str, sizeof str);
		if (str != NULL)
		{
			int fd;
			ssize_t rlen;
			struct stat s;
			struct dkimf_lua_script_result lres;

			fd = open(str, O_RDONLY, 0);
			if (fd < 0)
			{
				(void) snprintf(err, errlen, "%s: open(): %s", str,
				         strerror(errno));
				return -1;
			}

			if (fstat(fd, &s) == -1)
			{
				(void) snprintf(err, errlen, "%s: fstat(): %s", str,
				         strerror(errno));
				close(fd);
				return -1;
			}

			conf->conf_setupscript = malloc((size_t) s.st_size + 1);
			if (conf->conf_setupscript == NULL)
			{
				(void) snprintf(err, errlen, "malloc(): %s",
				         strerror(errno));
				close(fd);
				return -1;
			}

			memset(conf->conf_setupscript, '\0', (size_t) s.st_size + 1);
			rlen = read(fd, conf->conf_setupscript, (size_t) s.st_size);
			if (rlen == -1)
			{
				(void) snprintf(err, errlen, "%s: read(): %s",
				         str, strerror(errno));
				close(fd);
				return -1;
			}
			else if (rlen < s.st_size)
			{
				(void) snprintf(err, errlen, "%s: early EOF",
				         str);
				close(fd);
				return -1;
			}

			close(fd);

			memset(&lres, '\0', sizeof lres);
			if (dkimf_lua_setup_hook(NULL, conf->conf_setupscript,
			                         0, str, &lres,
			                         &conf->conf_setupfunc,
			                         &conf->conf_setupfuncsz) != 0)
			{
				strlcpy(err, lres.lrs_error, errlen);
				free((void *)(uintptr_t) lres.lrs_error);
				return -1;
			}
		}

		str = NULL;
		(void) config_get(data, "ScreenPolicyScript",
		                  &str, sizeof str);
		if (str != NULL)
		{
			int fd;
			ssize_t rlen;
			struct stat s;
			struct dkimf_lua_script_result lres;

			fd = open(str, O_RDONLY, 0);
			if (fd < 0)
			{
				(void) snprintf(err, errlen, "%s: open(): %s", str,
				         strerror(errno));
				return -1;
			}

			if (fstat(fd, &s) == -1)
			{
				(void) snprintf(err, errlen, "%s: fstat(): %s", str,
				         strerror(errno));
				close(fd);
				return -1;
			}

			conf->conf_screenscript = malloc((size_t) s.st_size + 1);
			if (conf->conf_screenscript == NULL)
			{
				(void) snprintf(err, errlen, "malloc(): %s",
				         strerror(errno));
				close(fd);
				return -1;
			}

			memset(conf->conf_screenscript, '\0', (size_t) s.st_size + 1);
			rlen = read(fd, conf->conf_screenscript, (size_t) s.st_size);
			if (rlen == -1)
			{
				(void) snprintf(err, errlen, "%s: read(): %s",
				         str, strerror(errno));
				close(fd);
				return -1;
			}
			else if (rlen < s.st_size)
			{
				(void) snprintf(err, errlen, "%s: early EOF",
				         str);
				close(fd);
				return -1;
			}

			close(fd);

			memset(&lres, '\0', sizeof lres);
			if (dkimf_lua_screen_hook(NULL,
			                          conf->conf_screenscript, 0,
			                          str, &lres,
			                          &conf->conf_screenfunc,
			                          &conf->conf_screenfuncsz) != 0)
			{
				strlcpy(err, lres.lrs_error, errlen);
				free((void *)(uintptr_t) lres.lrs_error);
				return -1;
			}
		}

		str = NULL;
		(void) config_get(data, "FinalPolicyScript", &str, sizeof str);
		if (str != NULL)
		{
			int fd;
			ssize_t rlen;
			struct stat s;
			struct dkimf_lua_script_result lres;

			fd = open(str, O_RDONLY, 0);
			if (fd < 0)
			{
				(void) snprintf(err, errlen, "%s: open(): %s", str,
				         strerror(errno));
				return -1;
			}

			if (fstat(fd, &s) == -1)
			{
				(void) snprintf(err, errlen, "%s: fstat(): %s", str,
				         strerror(errno));
				close(fd);
				return -1;
			}

			conf->conf_finalscript = malloc((size_t) s.st_size + 1);
			if (conf->conf_finalscript == NULL)
			{
				(void) snprintf(err, errlen, "malloc(): %s",
				         strerror(errno));
				close(fd);
				return -1;
			}

			memset(conf->conf_finalscript, '\0', (size_t) s.st_size + 1);
			rlen = read(fd, conf->conf_finalscript, (size_t) s.st_size);
			if (rlen == -1)
			{
				(void) snprintf(err, errlen, "%s: read(): %s",
				         str, strerror(errno));
				close(fd);
				return -1;
			}
			else if (rlen < s.st_size)
			{
				(void) snprintf(err, errlen, "%s: early EOF",
				         str);
				close(fd);
				return -1;
			}

			close(fd);

			memset(&lres, '\0', sizeof lres);
			if (dkimf_lua_final_hook(NULL, conf->conf_finalscript,
			                         0, str, &lres,
			                         &conf->conf_finalfunc,
			                         &conf->conf_finalfuncsz) != 0)
			{
				strlcpy(err, lres.lrs_error, errlen);
				free((void *)(uintptr_t) lres.lrs_error);
				return -1;
			}
		}
#endif /* USE_LUA */

		if (become == NULL)
		{
			(void) config_get(data, "Userid", &become,
			                  sizeof become);
		}
	}

	if (basedir[0] != '\0')
	{
		if (chdir(basedir) != 0)
		{
			(void) snprintf(err, errlen, "%s: chdir(): %s",
			         basedir, strerror(errno));
			return -1;
		}
	}

	str = NULL;
	if (conf->conf_peerfile != NULL)
	{
		str = conf->conf_peerfile;
	}
	else if (data != NULL)
	{
		(void) config_get(data, "PeerList", &str, sizeof str);
	}
	if (str != NULL && !testmode)
	{
		int status;
		const char *dberr = NULL;

		status = dkimf_db_open(&conf->conf_peerdb, str,
		                       (dbflags | 
		                        DKIMF_DB_FLAG_ICASE |
		                        DKIMF_DB_FLAG_READONLY),
		                       NULL, &dberr);
		if (status != 0)
		{
			(void) snprintf(err, errlen, "%s: dkimf_db_open(): %s",
			         str, dberr);
			return -1;
		}
	}

	if (conf->conf_testdnsdata != NULL)
	{
		int status;
		const char *dberr = NULL;

		status = dkimf_db_open(&conf->conf_testdnsdb,
		                       conf->conf_testdnsdata,
		                       (dbflags | 
		                        DKIMF_DB_FLAG_ICASE |
		                        DKIMF_DB_FLAG_READONLY),
		                       NULL, &dberr);
		if (status != 0)
		{
			(void) snprintf(err, errlen, "%s: dkimf_db_open(): %s",
			         str, dberr);
			return -1;
		}
	}

	/* internal list */
	str = NULL;
	if (conf->conf_internalfile != NULL)
	{
		str = conf->conf_internalfile;
	}
	else if (data != NULL)
	{
		(void) config_get(data, "InternalHosts", &str, sizeof str);
	}
	if (str != NULL)
	{
		int status;
		const char *dberr = NULL;

		status = dkimf_db_open(&conf->conf_internal, str,
		                       (dbflags | 
		                        DKIMF_DB_FLAG_ICASE |
		                        DKIMF_DB_FLAG_READONLY),
		                       NULL, &dberr);
		if (status != 0)
		{
			(void) snprintf(err, errlen, "%s: dkimf_db_open(): %s",
			         str, dberr);
			return -1;
		}
	}
	else
	{
		int status;
		const char *dberr = NULL;
		char internal[] = DEFINTERNAL;

		status = dkimf_db_open(&conf->conf_internal, internal,
		                       (dbflags |
		                        DKIMF_DB_FLAG_ICASE |
		                        DKIMF_DB_FLAG_READONLY),
		                       NULL, &dberr);
		if (status != 0)
		{
			(void) snprintf(err, errlen, "%s: dkimf_db_open(): %s",
			         internal, dberr);
			return -1;
		}
	}

	/* external ignore list */
	str = NULL;
	if (conf->conf_externalfile != NULL)
	{
		str = conf->conf_externalfile;
	}
	else if (data != NULL)
	{
		(void) config_get(data, "ExternalIgnoreList", &str,
		                  sizeof str);
	}
	if (str != NULL && !testmode)
	{
		int status;
		const char *dberr = NULL;

		status = dkimf_db_open(&conf->conf_exignore, str,
		                       (dbflags | 
		                        DKIMF_DB_FLAG_ICASE |
		                        DKIMF_DB_FLAG_READONLY),
		                       NULL, &dberr);
		if (status != 0)
		{
			(void) snprintf(err, errlen, "%s: dkimf_db_open(): %s",
			         str, dberr);
			return -1;
		}
	}

	/* exempt domains list */
	str = NULL;
	if (conf->conf_exemptfile != NULL)
	{
		str = conf->conf_exemptfile;
	}
	else if (data != NULL)
	{
		(void) config_get(data, "ExemptDomains", &str, sizeof str);
	}
	if (str != NULL && !testmode)
	{
		int status;
		const char *dberr = NULL;

		status = dkimf_db_open(&conf->conf_exemptdb, str,
		                       (dbflags | 
		                        DKIMF_DB_FLAG_ICASE |
		                        DKIMF_DB_FLAG_READONLY),
		                       NULL, &dberr);
		if (status != 0)
		{
			(void) snprintf(err, errlen, "%s: dkimf_db_open(): %s",
			         str, dberr);
			return -1;
		}
	}

	/* BodyLengthDB */
	str = NULL;
	if (data != NULL)
		(void) config_get(data, "BodyLengthDB", &str, sizeof str);
	if (str != NULL)
	{
		int status;
		const char *dberr = NULL;

		status = dkimf_db_open(&conf->conf_bldb, str,
		                       (dbflags | 
		                        DKIMF_DB_FLAG_ICASE |
		                        DKIMF_DB_FLAG_READONLY),
		                       NULL, &dberr);
		if (status != 0)
		{
			(void) snprintf(err, errlen, "%s: dkimf_db_open(): %s",
			         str, dberr);
			return -1;
		}
	}

	str = NULL;
	if (data != NULL)
		(void) config_get(data, "SignHeaders", &str, sizeof str);
	if (str != NULL)
	{
		int status;
		const char *dberr = NULL;

		status = dkimf_db_open(&conf->conf_signhdrsdb, str,
		                       (dbflags | 
		                        DKIMF_DB_FLAG_ICASE |
		                        DKIMF_DB_FLAG_READONLY),
		                       NULL, &dberr);
		if (status != 0)
		{
			(void) snprintf(err, errlen, "%s: dkimf_db_open(): %s",
			         str, dberr);
			return -1;
		}
	}

	str = NULL;
	if (data != NULL)
		(void) config_get(data, "RemoveARFrom", &str, sizeof str);
	if (str != NULL)
	{
		int status;
		const char *dberr = NULL;

		status = dkimf_db_open(&conf->conf_remardb, str,
		                       (dbflags | 
		                        DKIMF_DB_FLAG_ICASE |
		                        DKIMF_DB_FLAG_READONLY),
		                       NULL, &dberr);
		if (status != 0)
		{
			(void) snprintf(err, errlen, "%s: dkimf_db_open(): %s",
			         str, dberr);
			return -1;
		}
	}

	str = NULL;
	if (data != NULL)
		(void) config_get(data, "DontSignMailTo", &str, sizeof str);
	if (str != NULL)
	{
		int status;
		const char *dberr = NULL;

		status = dkimf_db_open(&conf->conf_dontsigntodb, str,
		                       (dbflags | 
		                        DKIMF_DB_FLAG_ICASE |
		                        DKIMF_DB_FLAG_READONLY),
		                       NULL, &dberr);
		if (status != 0)
		{
			(void) snprintf(err, errlen, "%s: dkimf_db_open(): %s",
			         str, dberr);
			return -1;
		}
	}

	str = NULL;
	if (data != NULL)
		(void) config_get(data, "MustBeSigned", &str, sizeof str);
	if (str != NULL)
	{
		int status;
		const char *dberr = NULL;

		status = dkimf_db_open(&conf->conf_mbsdb, str,
		                       (dbflags |
		                        DKIMF_DB_FLAG_ICASE |
		                        DKIMF_DB_FLAG_READONLY),
		                       NULL, &dberr);
		if (status != 0)
		{
			(void) snprintf(err, errlen, "%s: dkimf_db_open(): %s",
			         str, dberr);
			return -1;
		}
	}

	str = NULL;
	if (conf->conf_omitlist != NULL)
	{
		str = conf->conf_omitlist;
	}
	else if (data != NULL)
	{
		(void) config_get(data, "OmitHeaders", &str, sizeof str);
	}
	if (str != NULL)
	{
		int status;
		const char *dberr = NULL;

		status = dkimf_db_open(&conf->conf_omithdrdb, str,
		                       (dbflags |
		                        DKIMF_DB_FLAG_ICASE |
		                        DKIMF_DB_FLAG_READONLY),
		                       NULL, &dberr);
		if (status != 0)
		{
			(void) snprintf(err, errlen, "%s: dkimf_db_open(): %s",
			         str, dberr);
			return -1;
		}
	}

	str = NULL;
	if (data != NULL)
	{
		(void) config_get(data, "MTA", &str, sizeof str);
	}
	if (str != NULL)
	{
		int status;
		const char *dberr = NULL;

		status = dkimf_db_open(&conf->conf_mtasdb, str,
		                       (dbflags | DKIMF_DB_FLAG_READONLY),
		                       NULL, &dberr);
		if (status != 0)
		{
			(void) snprintf(err, errlen, "%s: dkimf_db_open(): %s",
			         str, dberr);
			return -1;
		}

		status = dkimf_db_mkarray(conf->conf_mtasdb, &conf->conf_mtas,
		                          NULL);
		if (status == -1)
			return -1;
	}

	str = NULL;
	if (data != NULL)
		(void) config_get(data, "OverSignHeaders", &str, sizeof str);
	if (str != NULL)
	{
		int status;
		const char *dberr = NULL;

		status = dkimf_db_open(&conf->conf_oversigndb, str,
		                       (dbflags |
		                        DKIMF_DB_FLAG_ICASE |
		                        DKIMF_DB_FLAG_READONLY),
		                       NULL, &dberr);
		if (status != 0)
		{
			(void) snprintf(err, errlen, "%s: dkimf_db_open(): %s",
			         str, dberr);
			return -1;
		}
	}

	str = NULL;
	if (data != NULL)
		(void) config_get(data, "SenderHeaders", &str, sizeof str);
	if (str != NULL)
	{
		int status;
		const char *dberr = NULL;

		status = dkimf_db_open(&conf->conf_senderhdrsdb, str,
		                       (dbflags |
		                        DKIMF_DB_FLAG_ICASE |
		                        DKIMF_DB_FLAG_READONLY),
		                       NULL, &dberr);
		if (status != 0)
		{
			(void) snprintf(err, errlen, "%s: dkimf_db_open(): %s",
			         str, dberr);
			return -1;
		}

		status = dkimf_db_mkarray(conf->conf_senderhdrsdb,
		                          &conf->conf_senderhdrs,
		                          NULL);
		if (status == -1)
			return -1;
	}


	if (data != NULL)
	{
		(void) config_get(data, "SigningTable", &conf->conf_signtable,
		                  sizeof conf->conf_signtable);

		if (conf->conf_signtable != NULL)
		{
			int status;
			const char *dberr = NULL;

			status = dkimf_db_open(&conf->conf_signtabledb,
			                       conf->conf_signtable,
			                       (dbflags |
			                        DKIMF_DB_FLAG_ICASE |
			                        DKIMF_DB_FLAG_ASCIIONLY |
			                        DKIMF_DB_FLAG_READONLY),
			                       NULL, &dberr);
			if (status != 0)
			{
				(void) snprintf(err, errlen,
				         "%s: dkimf_db_open(): %s",
				         conf->conf_signtable, dberr);
				return -1;
			}
		}
	}

	if (data != NULL)
	{
		(void) config_get(data, "KeyTable", &conf->conf_keytable,
		                  sizeof conf->conf_keytable);

		if (conf->conf_keytable == NULL)
		{
			(void) config_get(data, "KeyFile", &conf->conf_keyfile,
			                  sizeof conf->conf_keyfile);
		}
		else
		{
			int status;
			const char *dberr = NULL;
			char *ignored_keyfile = NULL;

			(void) config_get(data, "KeyFile", &ignored_keyfile,
			                  sizeof ignored_keyfile);
			if (ignored_keyfile != NULL)
			{
				syslog(LOG_WARNING,
				       "KeyFile is ignored when KeyTable is set");
			}

			status = dkimf_db_open(&conf->conf_keytabledb,
			                       conf->conf_keytable,
			                       (dbflags |
			                        DKIMF_DB_FLAG_READONLY), NULL,
			                       &dberr);
			if (status != 0)
			{
				(void) snprintf(err, errlen,
				         "%s: dkimf_db_open(): %s",
				         conf->conf_keytable, dberr);
				return -1;
			}

			conf->conf_selector = NULL;
		}
	}

	if (conf->conf_signtabledb != NULL && conf->conf_keytabledb == NULL)
	{
		(void) snprintf(err, errlen, "use of SigningTable requires KeyTable");
		return -1;
	}

	str = NULL;
	if (data != NULL)
	{
		(void) config_get(data, "TrustSignaturesFrom", &str,
		                  sizeof str);
	}
	if (str != NULL)
	{
		int status;
		const char *dberr = NULL;

		status = dkimf_db_open(&conf->conf_thirdpartydb, str,
		                       (dbflags | DKIMF_DB_FLAG_ICASE |
		                        DKIMF_DB_FLAG_READONLY),
		                       NULL, &dberr);
		if (status != 0)
		{
			(void) snprintf(err, errlen, "%s: dkimf_db_open(): %s",
			         str, dberr);
			return -1;
		}
	}

	str = NULL;
	if (conf->conf_resign != NULL)
	{
		str = conf->conf_resign;
	}
	else if (data != NULL)
	{
		(void) config_get(data, "ResignMailTo", &str, sizeof str);
	}
	if (str != NULL)
	{
		int status;
		const char *dberr = NULL;

		status = dkimf_db_open(&conf->conf_resigndb, str,
		                       (dbflags | DKIMF_DB_FLAG_ICASE |
		                        DKIMF_DB_FLAG_READONLY),
		                       NULL, &dberr);
		if (status != 0)
		{
			(void) snprintf(err, errlen, "%s: dkimf_db_open(): %s",
			         str, dberr);
			return -1;
		}
	}


	str = NULL;
	if (conf->conf_domlist != NULL)
	{
		str = conf->conf_domlist;
	}
	else if (data != NULL)
	{
		(void) config_get(data, "Domain", &str, sizeof str);
	}
	if (str != NULL && conf->conf_keytabledb == NULL)
	{
		int status;
		const char *dberr = NULL;

		status = dkimf_db_open(&conf->conf_domainsdb, str,
		                       (dbflags | DKIMF_DB_FLAG_READONLY |
		                        DKIMF_DB_FLAG_ICASE),
		                       NULL, &dberr);
		if (status != 0)
		{
			(void) snprintf(err, errlen, "%s: dkimf_db_open(): %s",
			         str, dberr);
			return -1;
		}
	}

	str = NULL;
	if (data != NULL)
	{
		(void) config_get(data, "MacroList", &str, sizeof str);
	}
	if (str != NULL)
	{
		int status;
		int dbtype;
		const char *dberr = NULL;

		status = dkimf_db_open(&conf->conf_macrosdb, str,
		                       (dbflags | DKIMF_DB_FLAG_READONLY |
		                        DKIMF_DB_FLAG_VALLIST |
		                        DKIMF_DB_FLAG_MATCHBOTH), NULL,
		                       &dberr);
		if (status != 0)
		{
			(void) snprintf(err, errlen, "%s: dkimf_db_open(): %s",
			         str, dberr);
			return -1;
		}

		dbtype = dkimf_db_type(conf->conf_macrosdb);
		if (dbtype != DKIMF_DB_TYPE_FILE &&
		    dbtype != DKIMF_DB_TYPE_CSL)
		{
			(void) snprintf(err, errlen,
			         "%s: invalid data set type for MacroList",
			         str);
			return -1;
		}

		(void) dkimf_db_mkarray(conf->conf_macrosdb,
		                        &conf->conf_macros, NULL);
	}

	if (conf->conf_signalgstr != NULL)
	{
		conf->conf_signalg = dkimf_lookup_strtoint(conf->conf_signalgstr,
		                                           dkimf_sign);
		if (conf->conf_signalg == -1)
		{
			(void) snprintf(err, errlen,
			         "unknown signing algorithm \"%s\"",
			         conf->conf_signalgstr);
			return -1;
		}
	}
	else
	{
		conf->conf_signalg = DKIM_SIGN_DEFAULT;
	}

	if (conf->conf_canonstr != NULL)
	{
		char *p;

		p = strchr(conf->conf_canonstr, '/');
		if (p == NULL)
		{
			conf->conf_hdrcanon = dkimf_lookup_strtoint(conf->conf_canonstr,
			                                            dkimf_canon);
			if (conf->conf_hdrcanon == -1)
			{
				(void) snprintf(err, errlen,
				         "unknown canonicalization algorithm \"%s\"",
				         conf->conf_canonstr);
				return -1;
			}

			conf->conf_bodycanon = DKIM_CANON_DEFAULT;
		}
		else
		{
			*p = '\0';

			conf->conf_hdrcanon = dkimf_lookup_strtoint(conf->conf_canonstr,
			                                            dkimf_canon);
			if (conf->conf_hdrcanon == -1)
			{
				(void) snprintf(err, errlen,
				         "unknown canonicalization algorithm \"%s\"",
				         conf->conf_canonstr);
				return -1;
			}

			conf->conf_bodycanon = dkimf_lookup_strtoint(p + 1,
			                                             dkimf_canon);
			if (conf->conf_bodycanon == -1)
			{
				(void) snprintf(err, errlen,
				         "unknown canonicalization algorithm \"%s\"",
				         p + 1);
				return -1;
			}

			*p = '/';
		}
	}

	str = NULL;
	if (conf->conf_siglimit != NULL)
	{
		str = conf->conf_siglimit;
	}
	else if (data != NULL)
	{
		(void) config_get(data, "Minimum", &str, sizeof str);
	}
	if (str != NULL)
	{
		unsigned long tmpl;
		char *p;

		errno = 0;

		if (str[0] == '-')
		{
			tmpl = ULONG_MAX;
			errno = ERANGE;
		}

		tmpl = strtoul(str, &p, 10);
		if (tmpl > UINT_MAX || errno != 0)
		{
			(void) snprintf(err, errlen, "illegal value for \"Minimum\"");
			return -1;
		}

		conf->conf_sigmin = (unsigned int) tmpl;

		if (*p == '%')
		{
			if (conf->conf_sigmin > 100)
			{
				(void) snprintf(err, errlen,
				         "illegal value for \"Minimum\"");
				return -1;
			}

			conf->conf_sigmintype = SIGMIN_PERCENT;
		}
		else if (*p == '+')
		{
			conf->conf_sigmintype = SIGMIN_MAXADD;
		}
		else if (*p != '\0')
		{
			(void) snprintf(err, errlen, "illegal value for \"Minimum\"");
			return -1;
		}
	}

	maxsign = -1;
	if (data != NULL)
	{
		(void) config_get(data, "MaximumSignedBytes", &maxsign,
		                  sizeof maxsign);
	}
	if (maxsign != -1)
	{
		conf->conf_signbytes = (long) maxsign;
		conf->conf_blen = TRUE;
	}

	if (conf->conf_modestr == NULL)
	{
		conf->conf_mode = (testmode ? DKIMF_MODE_VERIFIER
		                            : DKIMF_MODE_DEFAULT);
	}
	else
	{
		char *p;

		conf->conf_mode = 0;

		for (p = conf->conf_modestr; *p != '\0'; p++)
		{
			switch (*p)
			{
			  case 's':
				conf->conf_mode |= DKIMF_MODE_SIGNER;
				break;

			  case 'v':
				conf->conf_mode |= DKIMF_MODE_VERIFIER;
				break;

			  default:
				(void) snprintf(err, errlen, "unknown mode \"%c\"",
				         *p);
				return -1;
			}
		}
	}


	dkimf_reportaddr(conf);

	/* load the secret key, if one was specified */
	if (conf->conf_keyfile != NULL)
	{
		int status;
		int fd;
		ssize_t rlen;
		ino_t ino;
		uid_t asuser = (uid_t) -1;
		u_char *s33krit;
		struct stat s;

		fd = open(conf->conf_keyfile, O_RDONLY, 0);
		if (fd < 0)
		{
			if (conf->conf_dolog)
			{
				int saveerrno;

				saveerrno = errno;

				syslog(LOG_ERR, "%s: open(): %s",
				       conf->conf_keyfile,
				       strerror(errno));

				errno = saveerrno;
			}

			(void) snprintf(err, errlen, "%s: open(): %s",
			         conf->conf_keyfile, strerror(errno));
			return -1;
		}

		status = fstat(fd, &s);
		if (status != 0)
		{
			if (conf->conf_dolog)
			{
				int saveerrno;

				saveerrno = errno;

				syslog(LOG_ERR, "%s: stat(): %s",
				       conf->conf_keyfile,
				       strerror(errno));

				errno = saveerrno;
			}

			(void) snprintf(err, errlen, "%s: stat(): %s",
			         conf->conf_keyfile, strerror(errno));
			close(fd);
			return -1;
		}
		else if (!S_ISREG(s.st_mode))
		{
			(void) snprintf(err, errlen, "%s: open(): Not a regular file",
			         conf->conf_keyfile);
			close(fd);
			return -1;
		}

		if (become != NULL)
		{
			struct passwd *pw;
			char *p;
			char tmp[BUFRSZ + 1];

			strlcpy(tmp, become, sizeof tmp);

			p = strchr(tmp, ':');
			if (p != NULL)
				*p = '\0';

			pw = getpwnam(tmp);
			if (pw == NULL)
			{
				(void) snprintf(err, errlen, "%.64s: no such user", tmp);
				close(fd);
				return -1;
			}

			asuser = pw->pw_uid;
		}

		if (!dkimf_securefile(conf->conf_keyfile, &ino, asuser,
		                      err, errlen) ||
		    (ino != (ino_t) -1 && ino != s.st_ino))
		{
			if (conf->conf_dolog)
			{
				int sev;

				sev = (conf->conf_safekeys ? LOG_ERR
				                           : LOG_WARNING);

				syslog(sev, "%s: key data is not secure: %s",
				       conf->conf_keyfile, err);
			}

			if (conf->conf_safekeys)
				return -1;
		}

		s33krit = malloc((size_t) s.st_size + 1);
		if (s33krit == NULL)
		{
			if (conf->conf_dolog)
			{
				int saveerrno;

				saveerrno = errno;

				syslog(LOG_ERR, "malloc(): %s", 
				       strerror(errno));

				errno = saveerrno;
			}

			(void) snprintf(err, errlen, "malloc(): %s", strerror(errno));
			return -1;
		}

		conf->conf_keylen = (size_t) s.st_size + 1;

		rlen = read(fd, s33krit, (size_t) s.st_size + 1);
		if (rlen == (ssize_t) -1)
		{
			if (conf->conf_dolog)
			{
				int saveerrno;

				saveerrno = errno;

				syslog(LOG_ERR, "%s: read(): %s",
				       conf->conf_keyfile,
				       strerror(errno));

				errno = saveerrno;
			}

			(void) snprintf(err, errlen, "%s: read(): %s",
			         conf->conf_keyfile, strerror(errno));
			close(fd);
			free(s33krit);
			return -1;
		}
		else if (rlen != s.st_size)
		{
			if (conf->conf_dolog)
			{
				syslog(LOG_ERR, "%s: read() wrong size (%lu)",
				       conf->conf_keyfile, (u_long) rlen);
			}

			(void) snprintf(err, errlen, "%s: read() wrong size (%lu)",
			         conf->conf_keyfile, (u_long) rlen);
			close(fd);
			free(s33krit);
			return -1;
		}

		close(fd);
		s33krit[s.st_size] = '\0';
		conf->conf_seckey = s33krit;
	}

	/* confirm signing mode parameters */
	if ((conf->conf_mode & DKIMF_MODE_SIGNER) != 0)
	{
		if ((conf->conf_selector != NULL &&
		     conf->conf_keyfile == NULL) ||
		    (conf->conf_selector == NULL &&
		     conf->conf_keyfile != NULL))
		{
			(void) snprintf(err, errlen,
			         "KeyFile and Selector must both be defined or both be undefined");
			return -1;
		}

		if (conf->conf_domainsdb != NULL &&
		    (conf->conf_selector == NULL ||
		     conf->conf_keyfile == NULL))
		{
			(void) snprintf(err, errlen,
			         "Domain requires KeyFile and Selector");
			return -1;
		}

		if (conf->conf_signtable != NULL &&
		    conf->conf_keytable == NULL)
		{
			(void) snprintf(err, errlen,
			         "SigningTable requires KeyTable");
			return -1;
		}

#ifdef USE_LUA
		if (conf->conf_keytable != NULL &&
		    conf->conf_signtable == NULL &&
		    conf->conf_setupscript == NULL)
		{
			(void) snprintf(err, errlen,
			         "KeyTable requires either SigningTable or SetupPolicyScript");
			return -1;
		}
#else /* USE_LUA */
		if (conf->conf_keytable != NULL &&
		    conf->conf_signtable == NULL)
		{
			(void) snprintf(err, errlen,
			         "KeyTable requires SigningTable");
			return -1;
		}
#endif /* USE_LUA */

		/*
		**  Verify that the SingingTable doesn't reference any
		**  missing KeyTable entries.
		*/

		if (conf->conf_signtabledb != NULL  &&
			conf->conf_checksigningtable != FALSE &&
			dkimf_db_type(conf->conf_signtabledb) != DKIMF_DB_TYPE_REFILE)
		{
			_Bool first = TRUE;
			_Bool found;
			struct dkimf_db_data dbd[3];
			char keyname[BUFRSZ + 1];
			char domain[BUFRSZ + 1];
			char selector[BUFRSZ + 1];
			char keydata[BUFRSZ + 1];
			char signer[BUFRSZ + 1];

			dbd[0].dbdata_flags = 0;
			
			memset(keyname, '\0', sizeof keyname);

			dbd[0].dbdata_buffer = keyname;
			dbd[0].dbdata_buflen = sizeof keyname - 1;
			dbd[0].dbdata_flags = 0;
			dbd[1].dbdata_buffer = signer;
			dbd[1].dbdata_buflen = sizeof signer - 1;
			dbd[1].dbdata_flags = DKIMF_DB_DATA_OPTIONAL;

			int _walkret;
			while ((_walkret = dkimf_db_walk(conf->conf_signtabledb, first,
                                                         NULL, NULL, dbd, 2)) == 0)
			{
				first = FALSE;
				found = FALSE;
				dbd[0].dbdata_buffer = domain;
				dbd[0].dbdata_buflen = sizeof domain - 1;
				dbd[0].dbdata_flags = 0;
				dbd[1].dbdata_buffer = selector;
				dbd[1].dbdata_buflen = sizeof selector - 1;
				dbd[1].dbdata_flags = 0;
				dbd[2].dbdata_buffer = keydata;
				dbd[2].dbdata_buflen = sizeof keydata - 1;
				dbd[2].dbdata_flags = DKIMF_DB_DATA_BINARY;

				if (dkimf_db_get(conf->conf_keytabledb,	
				                 keyname, strlen(keyname),
				                 dbd, 3, &found) != 0 ||
				    !found ||
				    dbd[0].dbdata_buflen == 0 ||
				    dbd[1].dbdata_buflen == 0 ||
				    dbd[2].dbdata_buflen == 0)
				{
					(void) snprintf(err, errlen,
					         "no KeyTable entry found for signing key \"%s\" (from SigningTable)",
					         keyname);
					return -1;
				}

				memset(keyname, '\0', sizeof keyname);

				dbd[0].dbdata_buffer = keyname;
				dbd[0].dbdata_buflen = sizeof keyname - 1;
				dbd[0].dbdata_flags = 0;
				dbd[1].dbdata_buffer = signer;
				dbd[1].dbdata_buflen = sizeof signer - 1;
				dbd[1].dbdata_flags = DKIMF_DB_DATA_OPTIONAL;
			}
			if (_walkret == -1)
                        {
                                (void) snprintf(err, errlen, "error walking SigningTable");
                                return -1;
                        }
		}
	}

	/* activate logging if requested */
	if (conf->conf_dolog)
	{
		char *log_name = NULL;
		char *log_facility = NULL;

		if (data != NULL)
		{
			(void) config_get(data, "SyslogName", &log_name,
			                  sizeof log_name);
			(void) config_get(data, "SyslogFacility", &log_facility,
			                  sizeof log_facility);
		}

		dkimf_init_syslog(log_name, log_facility);
	}

	return 0;
}

/*
**  DKIMF_DNS_INIT -- initialize and configure the DNS service in the
**                    DKIM library
**
**  Parameters:
**  	lib -- DKIM library
**  	conf -- configuration handle
**  	err -- error string (returned)
**
**  Return value:
**  	TRUE on success, FALSE otherwise
*/

static _Bool
dkimf_dns_init(DKIM_LIB *lib, struct dkimf_config *conf, const char **err)
{
	int status;

	assert(lib != NULL);
	assert(conf != NULL);
	assert(err != NULL);

	status = dkim_dns_init(lib);
	if (status == DKIM_DNS_INVALID)
	{
		return TRUE;
	}
	else if (status == DKIM_DNS_ERROR)
	{
		if (err != NULL)
			*err = "failed to initialize resolver";

		return FALSE;
	}

	if (conf->conf_nslist != NULL)
	{
		status = dkimf_dns_setnameservers(lib,
						  conf->conf_nslist);
		if (status != DKIM_STAT_OK)
		{
			if (err != NULL)
				*err = "failed to set nameserver list";
			return FALSE;
		}
	}

	if (conf->conf_trustanchorpath != NULL)
	{
		if (access(conf->conf_trustanchorpath, R_OK) != 0)
		{
			if (err != NULL)
				*err = "can't access unbound trust anchor";
			return FALSE;
		}

		status = dkimf_dns_trustanchor(lib,
					       conf->conf_trustanchorpath);
		if (status != DKIM_STAT_OK)
		{
			if (err != NULL)
				*err = "failed to add trust anchor";
			return FALSE;
		}
	}

	if (conf->conf_resolverconfig != NULL)
	{
		status = dkimf_dns_config(lib, conf->conf_resolverconfig);
		if (status != DKIM_DNS_SUCCESS)
		{
			if (err != NULL)
				*err = "failed to add resolver configuration file";
	
			return FALSE;
		}
	}

	return TRUE;
}

/*
**  DKIMF_CONFIG_SETLIB -- set library options based on configuration file
**
**  Parameters:
**  	conf -- DKIM filter configuration data
**  	err -- error string (returned; may be NULL)
**
**  Return value:
**  	TRUE on success, FALSE otherwise.
*/

static _Bool
dkimf_config_setlib(struct dkimf_config *conf, const char **err)
{
	DKIM_STAT status;
	u_int opts;
	DKIM_LIB *lib;
	assert(conf != NULL);

	lib = conf->conf_libopendkim;
	if (lib == NULL)
	{
		lib = dkim_init(NULL, NULL);
		if (lib == NULL)
		{
			if (err != NULL)
				*err = "failed to initialize DKIM library";
			return FALSE;
		}

		conf->conf_libopendkim = lib;
	}

	(void) dkim_getopt(lib, DKIM_OPTS_FLAGS,
	                    &opts, sizeof opts);
	opts |= (DKIM_LIBFLAGS_ACCEPTV05 | DKIM_LIBFLAGS_DROPSIGNER);
	if (conf->conf_weaksyntax)
		opts |= DKIM_LIBFLAGS_BADSIGHANDLES;
	/*
	**  RFC 8301: rsa-sha1 MUST NOT be used for verifying.  Tell the library
	**  to short-circuit such signatures so they can never report "pass";
	**  On-WeakAlgorithm then selects only the message disposition applied in
	**  mlfi_eom().
	*/
	opts |= DKIM_LIBFLAGS_NOSHA1VERIFY;
	(void) dkim_setopt(lib, DKIM_OPTS_FLAGS,
	                    &opts, sizeof opts);

	/* set the DNS callback */
	(void) dkim_set_dns_callback(lib, dkimf_sendprogress, CBINTERVAL);

	if (conf->conf_minkeybits != 0)
	{
		(void) dkim_setopt(lib, DKIM_OPTS_MINKEYBITS,
		                    &conf->conf_minkeybits,
		                    sizeof conf->conf_minkeybits);
	}

	if (conf->conf_testdnsdb != NULL)
	{
		(void) dkimf_filedns_setup(lib, conf->conf_testdnsdb);
	}
	else
	{
#ifdef USE_UNBOUND
		(void) dkimf_unbound_setup(lib);
#endif /* USE_UNBOUND */

		if (!dkimf_dns_init(lib, conf, err))
			return FALSE;
		else
			dkim_dns_close(lib);
	}

	(void) dkim_setopt(lib, DKIM_OPTS_TIMEOUT,
	                    &conf->conf_dnstimeout,
	                    sizeof conf->conf_dnstimeout);

	if (conf->conf_clockdrift != 0)
	{
		uint64_t drift = (uint64_t) conf->conf_clockdrift;

		status = dkim_setopt(lib,
		                      DKIM_OPTS_CLOCKDRIFT, &drift,
		                      sizeof drift);

		if (status != DKIM_STAT_OK)
		{
			if (err != NULL)
				*err = "failed to set DKIM clock drift limit";
			return FALSE;
		}
	}

	if (conf->conf_sigttl != 0)
	{
		uint64_t sigtime = conf->conf_sigttl;

		status = dkim_setopt(lib,
		                      DKIM_OPTS_SIGNATURETTL, &sigtime,
		                      sizeof sigtime);

		if (status != DKIM_STAT_OK)
		{
			if (err != NULL)
				*err = "failed to set DKIM signature TTL";
			return FALSE;
		}
	}

	if (conf->conf_sendreports || conf->conf_keeptmpfiles ||
	    conf->conf_stricthdrs || conf->conf_blen || conf->conf_ztags ||
	    conf->conf_fixcrlf)
	{
		status = dkim_getopt(conf->conf_libopendkim,
		                      DKIM_OPTS_FLAGS, &opts, sizeof opts);

		if (status != DKIM_STAT_OK)
		{
			if (err != NULL)
				*err = "failed to retrieve DKIM library options";
			return FALSE;
		}

		if (conf->conf_sendreports || conf->conf_keeptmpfiles)
			opts |= DKIM_LIBFLAGS_TMPFILES;
		if (conf->conf_keeptmpfiles)
			opts |= DKIM_LIBFLAGS_KEEPFILES;
		if (conf->conf_blen)
			opts |= DKIM_LIBFLAGS_SIGNLEN;
		if (conf->conf_ztags)
			opts |= DKIM_LIBFLAGS_ZTAGS;
		if (conf->conf_fixcrlf)
			opts |= DKIM_LIBFLAGS_FIXCRLF;
		if (conf->conf_acceptdk)
			opts |= DKIM_LIBFLAGS_ACCEPTDK;
		if (conf->conf_stricthdrs)
			opts |= DKIM_LIBFLAGS_STRICTHDRS;

		status = dkim_setopt(conf->conf_libopendkim,
		                      DKIM_OPTS_FLAGS, &opts, sizeof opts);

		if (status != DKIM_STAT_OK)
		{
			if (err != NULL)
				*err = "failed to set DKIM library options";
			return FALSE;
		}
	}

	if (conf->conf_oversigndb != NULL)
	{
		status = dkimf_db_mkarray(conf->conf_oversigndb,
		                          &conf->conf_oversignhdrs, NULL);
		if (status == -1)
		{
			if (err != NULL)
				*err = "failed to generate DB array";
			return FALSE;
		}

		status = dkim_setopt(conf->conf_libopendkim,
		                      DKIM_OPTS_OVERSIGNHDRS,
		                      conf->conf_oversignhdrs,
		                      sizeof conf->conf_oversignhdrs);

		if (status != DKIM_STAT_OK)
		{
			if (err != NULL)
				*err = "failed to set DKIM library options";
			return FALSE;
		}
	}

	if (conf->conf_mbsdb != NULL)
	{
		status = dkimf_db_mkarray(conf->conf_mbsdb, &conf->conf_mbs,
		                          NULL);
		if (status == -1)
		{
			if (err != NULL)
				*err = "failed to generate DB array";
			return FALSE;
		}

		status = dkim_setopt(conf->conf_libopendkim,
		                      DKIM_OPTS_MUSTBESIGNED,
		                      conf->conf_mbs, sizeof conf->conf_mbs);

		if (status != DKIM_STAT_OK)
		{
			if (err != NULL)
				*err = "failed to set DKIM library options";
			return FALSE;
		}
	}

	if (conf->conf_omithdrdb != NULL)
	{
		status = dkimf_db_mkarray(conf->conf_omithdrdb,
		                          &conf->conf_omithdrs,
		                          (const char **) dkim_should_not_signhdrs);
		if (status == -1)
		{
			if (err != NULL)
				*err = "failed to generate DB array";
			return FALSE;
		}

		status = dkim_setopt(conf->conf_libopendkim,
		                      DKIM_OPTS_SKIPHDRS,
		                      conf->conf_omithdrs,
		                      sizeof conf->conf_omithdrs);

		if (status != DKIM_STAT_OK)
		{
			if (err != NULL)
				*err = "failed to set DKIM library options";
			return FALSE;
		}
	}
	else
	{
		status = dkim_setopt(conf->conf_libopendkim,
		                      DKIM_OPTS_SKIPHDRS,
		                      (void *) dkim_should_not_signhdrs,
		                      sizeof (u_char **));

		if (status != DKIM_STAT_OK)
		{
			if (err != NULL)
				*err = "failed to set DKIM library options";
			return FALSE;
		}
	}

	if (conf->conf_signhdrsdb != NULL)
	{
		status = dkimf_db_mkarray(conf->conf_signhdrsdb,
		                          &conf->conf_signhdrs,
		                          (const char **) dkim_should_signhdrs);
		if (status == -1)
		{
			if (err != NULL)
				*err = "failed to set DKIM library options";
			return FALSE;
		}

		status = dkim_setopt(conf->conf_libopendkim,
		                      DKIM_OPTS_SIGNHDRS, conf->conf_signhdrs,
		                      sizeof conf->conf_signhdrs);

		if (status != DKIM_STAT_OK)
		{
			if (err != NULL)
				*err = "failed to set DKIM library options";
			return FALSE;
		}
	}
	else
	{
		status = dkim_setopt(conf->conf_libopendkim,
		                      DKIM_OPTS_SIGNHDRS,
		                      (void *) dkim_should_signhdrs,
		                      sizeof (u_char **));

		if (status != DKIM_STAT_OK)
		{
			if (err != NULL)
				*err = "failed to set DKIM library options";
			return FALSE;
		}
	}

	status = dkim_setopt(conf->conf_libopendkim,
	                      DKIM_OPTS_TMPDIR,
	                      (void *) conf->conf_tmpdir,
	                      sizeof conf->conf_tmpdir);

	if (status != DKIM_STAT_OK)
	{
		if (err != NULL)
			*err = "failed to set DKIM library options";
		return FALSE;
	}

	status = dkim_set_prescreen(conf->conf_libopendkim, dkimf_prescreen);
	if (status != DKIM_STAT_OK)
	{
		if (err != NULL)
			*err = "failed to set DKIM prescreen function";
		return FALSE;
	}

	return TRUE;
}

/*
**  DKIMF_CONFIG_RELOAD -- reload configuration if requested
**
**  Parameters:
**   	None.
**
**  Return value:
**  	None.
**
**  Side effects:
**  	If a reload was requested and is successful, "curconf" now points
**  	to a new configuration handle.
*/

static void
dkimf_config_reload(void)
{
	struct dkimf_config *new;
	char errbuf[BUFRSZ + 1];

	pthread_mutex_lock(&conf_lock);

	if (!reload)
	{
		pthread_mutex_unlock(&conf_lock);
		return;
	}

	if (conffile == NULL)
	{
		if (curconf->conf_dolog)
			syslog(LOG_ERR, "ignoring reload signal");

		reload = FALSE;

		pthread_mutex_unlock(&conf_lock);
		return;
	}

	new = dkimf_config_new();
	if (new == NULL)
	{
		if (curconf->conf_dolog)
			syslog(LOG_ERR, "malloc(): %s", strerror(errno));
	}
	else
	{
		_Bool err = FALSE;
		u_int line;
		struct config *cfg;
		const char *missing;
		const char *errstr = NULL;
		char *deprecated = NULL;
		char path[MAXPATHLEN + 1];

		strlcpy(path, conffile, sizeof path);

		cfg = config_load(conffile, dkimf_config, &line,
		                  path, sizeof path, &deprecated);

		if (cfg == NULL)
		{
			if (curconf->conf_dolog)
			{
				syslog(LOG_ERR,
				       "%s: configuration error at line %u: %s",
				        path, line, config_error());
			}
			dkimf_config_free(new);
			err = TRUE;
		}

		if (deprecated != NULL)
		{
			const char *action = "aborting";
			if (allowdeprecated)
				action = "continuing";

			if (curconf->conf_dolog)
			{
				syslog(LOG_WARNING,
				       "%s: settings found for deprecated value(s): %s; %s",
				        path, deprecated, action);
			}

			if (!allowdeprecated)
			{
				config_free(cfg);
				dkimf_config_free(new);
				err = TRUE;
			}
		}

		if (!err)
		{
			missing = config_check(cfg, dkimf_config);
			if (missing != NULL)
			{
				if (curconf->conf_dolog)
				{
					syslog(LOG_ERR,
					        "%s: required parameter \"%s\" missing",
					        conffile, missing);
				}
				config_free(cfg);
				dkimf_config_free(new);
				err = TRUE;
			}
		}

		if (!err && dkimf_config_load(cfg, new, errbuf,
		                              sizeof errbuf, NULL) != 0)
		{
			if (curconf->conf_dolog)
				syslog(LOG_ERR, "%s: %s", conffile, errbuf);
			config_free(cfg);
			dkimf_config_free(new);
			err = TRUE;
		}

		if (!err && !dkimf_config_setlib(new, &errstr))
		{
			if (curconf->conf_dolog)
			{
				syslog(LOG_WARNING,
				       "can't configure DKIM library: %s; continuing",
				       errstr);
			}
			config_free(cfg);
			dkimf_config_free(new);
			err = TRUE;
		}

		if (!err)
		{
			if (curconf->conf_refcnt == 0)
				dkimf_config_free(curconf);

			dolog = new->conf_dolog;
			curconf = new;
			new->conf_data = cfg;

			if (new->conf_dolog)
			{
				syslog(LOG_INFO,
				       "configuration reloaded from %s",
				       conffile);
			}
		}
	}

	reload = FALSE;

	pthread_mutex_unlock(&conf_lock);

	return;
}

/*
**  DKIMF_CHECKBLDB -- determine if an envelope recipient is one for which
**                     signing should be done with body length tags
**
**  Parameters:
**  	db -- DB handle
**  	to -- the recipient header
**  	jobid -- string of job ID for logging
**
**  Return value:
**  	TRUE iff the recipient email was found in the body length database.
*/

static _Bool
dkimf_checkbldb(DKIMF_DB db, char *to, const char *jobid)
{
	int c;
	_Bool exists = FALSE;
	DKIM_STAT status;
	char *domain;
	char *user;
	char *p;
	char addr[MAXADDRESS + 1];
	char dbaddr[MAXADDRESS + 1];

	strlcpy(addr, to, sizeof addr);
	status = dkim_mail_parse((u_char *) addr, (u_char **) &user,
	                         (u_char **) &domain);
	if (status != 0 || user == NULL || domain == NULL)
	{
		if (dolog)
		{
			syslog(LOG_INFO, "%s: can't parse %s: header",
			       jobid, to);
		}

		return FALSE;
	}

	for (p = domain; ; p = strchr(p + 1, '.'))
	{
		for (c = 0; c < 2; c++)
		{
			if (c == 1 && p == NULL)
			{
				dbaddr[0] = '*';
				dbaddr[1] = '\0';
			}
			else if (snprintf(dbaddr, sizeof dbaddr, "%s@%s",
			                  c == 0 ? user : "*",
			                  p == NULL ? "*" : p) >= (int) sizeof dbaddr)
			{
				if (dolog)
				{
					syslog(LOG_ERR,
					       "%s: overflow parsing \"%s\"",
					       jobid, to);
				}

				return FALSE;
			}

			status = dkimf_db_get(db, dbaddr, 0, NULL, 0, &exists);
			if (status == 0)
			{
				if (exists)
					return TRUE;
			}
			else if (dolog)
			{
				dkimf_db_error(db, dbaddr);
			}
		}

		if (p == NULL)
			break;
	}

	return FALSE;
}

/*
**  DKIMF_STDIO -- set up the base descriptors to go nowhere
**
**  Parameters:
**  	None.
**
**  Return value:
**  	None.
*/

static void
dkimf_stdio(void)
{
	int devnull;

	/* this only fails silently, but that's OK */
	devnull = open(_PATH_DEVNULL, O_RDWR, 0);
	if (devnull != -1)
	{
		(void) dup2(devnull, 0);
		(void) dup2(devnull, 1);
		(void) dup2(devnull, 2);
		if (devnull > 2)
			(void) close(devnull);
	}

	(void) setsid();
}

/*
**  DKIMF_SENDPROGRESS -- tell the MTA "we're working on it!"
**
**  Parameters:
**  	ctx -- context
**
**  Return value:
**  	None (yet).
*/

void
dkimf_sendprogress(const void *ctx)
{
	if (ctx != NULL)
	{
		struct connctx *cc;
		struct msgctx *dfc;

		/*
		**  The dns_callback signature delivers ctx as const void *;
		**  the value stored there is a live SMFICTX * that smfi
		**  entry points mutate -- cast away const to recover the
		**  original pointer type.
		*/
		cc = (struct connctx *) dkimf_getpriv((SMFICTX *) ctx);
		dfc = cc->cctx_msg;

		if (dfc->mctx_eom)
		{
			if (testmode)
				(void) dkimf_test_progress((SMFICTX *) ctx);
#ifdef HAVE_SMFI_PROGRESS
			else
				(void) smfi_progress((SMFICTX *) ctx);
#endif /* HAVE_SMFI_PROGRESS */
		}
	}
}

/*
**  DKIMF_INITCONTEXT -- initialize filter context
**
**  Parameters:
**  	conf -- pointer to the configuration for this connection
**
**  Return value:
**  	A pointer to an allocated and initialized filter context, or NULL
**  	on failure.
**
**  Side effects:
**  	Crop circles near Birmingham.
*/

static msgctx
dkimf_initcontext(struct dkimf_config *conf)
{
	msgctx ctx;

	assert(conf != NULL);

	ctx = (msgctx) malloc(sizeof(struct msgctx));
	if (ctx == NULL)
		return NULL;

	(void) memset(ctx, '\0', sizeof(struct msgctx));

	ctx->mctx_status = DKIMF_STATUS_UNKNOWN;
	ctx->mctx_hdrcanon = conf->conf_hdrcanon;
	ctx->mctx_bodycanon = conf->conf_bodycanon;
	ctx->mctx_signalg = DKIM_SIGN_DEFAULT;
	ctx->mctx_queryalg = DKIM_QUERY_DEFAULT;

	return ctx;
}

/*
**  DKIMF_LOG_SSL_ERRORS -- log any queued SSL library errors
**
**  Parameters:
**  	dkim -- DKIM handle
**  	sig -- signature handle
**  	jobid -- job ID to include in log messages
**
**  Return value:
**  	None.
*/

static void
dkimf_log_ssl_errors(DKIM *dkim, DKIM_SIGINFO *sig, const char *jobid)
{
	char *selector;
	char *domain;
	const char *errbuf;

	assert(dkim != NULL);
	assert(jobid != NULL);

	if (sig != NULL)
	{
		domain = (char *) dkim_sig_getdomain(sig);
		selector = (char *) dkim_sig_getselector(sig);
		errbuf = dkim_sig_getsslbuf(sig);
	}
	else
	{
		domain = NULL;
		selector = NULL;
		errbuf = dkim_getsslbuf(dkim);
	}

	if (errbuf != NULL)
	{
		if (selector != NULL && domain != NULL)
		{
			syslog(LOG_INFO, "%s: s=%s d=%s SSL %s", jobid,
			       selector, domain, errbuf);
		}
		else
		{
			syslog(LOG_INFO, "%s: SSL %s", jobid, errbuf);
		}
	}
}

/*
**  DKIMF_CLEANUP -- release local resources related to a message
**
**  Parameters:
**  	ctx -- milter context
**
**  Return value:
**  	None.
*/

static void
dkimf_cleanup(SMFICTX *ctx)
{
	msgctx dfc;
	connctx cc;

	assert(ctx != NULL);

	cc = (connctx) dkimf_getpriv(ctx);

	if (cc == NULL)
		return;

	dfc = cc->cctx_msg;

	/* release memory, reset state */
	if (dfc != NULL)
	{
		if (dfc->mctx_hqhead != NULL)
		{
			Header hdr;
			Header prev;

			hdr = dfc->mctx_hqhead;
			while (hdr != NULL)
			{
				TRYFREE(hdr->hdr_hdr);
				TRYFREE(hdr->hdr_val);
				prev = hdr;
				hdr = hdr->hdr_next;
				TRYFREE(prev);
			}
		}

		if (dfc->mctx_rcptlist != NULL)
		{
			struct addrlist *addr;
			struct addrlist *next;

			addr = dfc->mctx_rcptlist;
			while (addr != NULL)
			{
				next = addr->a_next;

				TRYFREE(addr->a_addr);
				TRYFREE(addr);

				addr = next;
			}
		}

		if (dfc->mctx_srhead != NULL)
		{
			struct signreq *sr;
			struct signreq *next;

			sr = dfc->mctx_srhead;
			while (sr != NULL)
			{
				next = sr->srq_next;

				if (sr->srq_dkim != NULL)
					dkim_free(sr->srq_dkim);
				if (sr->srq_keydata != NULL)
				{
					memset(sr->srq_keydata, '\0',
					       sr->srq_keydatalen);
					free(sr->srq_keydata);
					sr->srq_keydata = NULL;
				}
				TRYFREE(sr->srq_domain);
				TRYFREE(sr->srq_selector);
				TRYFREE(sr->srq_signer);
				TRYFREE(sr);

				sr = next;
			}
		}

		if (dfc->mctx_dkimv != NULL)
			dkim_free(dfc->mctx_dkimv);


		if (dfc->mctx_tmpstr != NULL)
			dkimf_dstring_free(dfc->mctx_tmpstr);

#ifdef USE_LUA
		if (dfc->mctx_luaglobalh != NULL)
		{
			struct lua_global *cur;
			struct lua_global *next;

			cur = dfc->mctx_luaglobalh;
			while (cur != NULL)
			{
				next = cur->lg_next;

				if (cur->lg_type == LUA_TNUMBER ||
				    cur->lg_type == LUA_TSTRING)
					free(cur->lg_value);

				free(cur->lg_name);
				free(cur);

				cur = next;
			}
		}
#endif /* USE_LUA */

		free(dfc);
		cc->cctx_msg = NULL;
	}
}

/*
**  DKIMF_MILTERCODE -- apply an internal result code to libmilter
**
**  Parameters:
**  	ctx -- milter context
**  	dmc -- DKIMF_MILTER_* code
**  	str -- quarantine string (optional)
**
**  Return value:
**  	An SMFIS_* constant.
*/

static sfsistat
dkimf_miltercode(SMFICTX *ctx, int dmc, char *str)
{
	assert(ctx != NULL);

	switch (dmc)
	{
	  case DKIMF_MILTER_ACCEPT:
		return SMFIS_ACCEPT;

	  case DKIMF_MILTER_DISCARD:
		return SMFIS_DISCARD;

	  case DKIMF_MILTER_QUARANTINE:
		(void) dkimf_quarantine(ctx, str == NULL ? progname : str);
		return SMFIS_ACCEPT;

	  case DKIMF_MILTER_NEUTRAL:
		/*
		**  "neutral" delivers the message; the downgraded result is
		**  recorded separately in the Authentication-Results field.
		*/
		return SMFIS_ACCEPT;

	  case DKIMF_MILTER_REJECT:
		return SMFIS_REJECT;

	  case DKIMF_MILTER_TEMPFAIL:
		return SMFIS_TEMPFAIL;
	}

	/* NOTREACHED */
	return SMFIS_ACCEPT;
}

/*
**  DKIMF_LIBSTATUS -- process a final status returned from libopendkim
**
**  Parameters:
**  	ctx -- milter context
**  	dkim -- DKIM handle producing the status
**  	where -- what function reported the error
**  	status -- status returned by a libdk call (DKIM_STAT_*)
**
**  Return value:
**   	An smfistat value to be returned to libmilter.
*/

static sfsistat
dkimf_libstatus(SMFICTX *ctx, DKIM *dkim, const char *where, int status)
{
	int retcode = SMFIS_CONTINUE;
	msgctx dfc;
	connctx cc;
	DKIM_SIGINFO *sig;
	const char *rcode = NULL;
	const char *xcode = NULL;
	const char *replytxt = NULL;
	struct dkimf_config *conf;
	u_char smtpprefix[BUFRSZ];

	assert(ctx != NULL);

	cc = dkimf_getpriv(ctx);
	assert(cc != NULL);
	dfc = cc->cctx_msg;
	assert(dfc != NULL);
	conf = cc->cctx_config;

	memset(smtpprefix, '\0', sizeof smtpprefix);

	switch (status)
	{
	  case DKIM_STAT_OK:
		retcode = SMFIS_CONTINUE;
		break;

	  case DKIM_STAT_INTERNAL:
		retcode = dkimf_miltercode(ctx,
		                           conf->conf_handling.hndl_internal,
		                           NULL);
		if (conf->conf_capture)
			dfc->mctx_capture = TRUE;
		if (conf->conf_dolog)
		{
			const char *err = NULL;
			const char *sslerr = NULL;

			if (dkim != NULL)
				err = dkim_geterror(dkim);
			if (err == NULL)
				err = strerror(errno);
			sslerr = dkim_getsslbuf(dkim);

			syslog(LOG_ERR,
			       "%s: %s%sinternal error from libopendkim: %s%s%s",
			       JOBID(dfc->mctx_jobid),
			       where == NULL ? "" : where,
			       where == NULL ? "" : ": ", err,
			       sslerr == NULL ? "" : " ",
			       sslerr == NULL ? "" : sslerr);
		}
		replytxt = "internal DKIM error";
		break;

	  case DKIM_STAT_BADSIG:
		assert(dkim != NULL);
		retcode = dkimf_miltercode(ctx,
		                           conf->conf_handling.hndl_badsig,
		                           NULL);
		if (conf->conf_dolog)
		{
			syslog(LOG_NOTICE, "%s: bad signature data",
			       JOBID(dfc->mctx_jobid));
		}
		replytxt = "bad DKIM signature data";

		memset(smtpprefix, '\0', sizeof smtpprefix);
		sig = dkim_getsignature(dkim);
		(void) dkim_sig_getreportinfo(dkim, sig,
		                              NULL, 0,
		                              NULL, 0,
		                              NULL, 0,
		                              smtpprefix, sizeof smtpprefix,
		                              NULL);

		break;

	  case DKIM_STAT_NOSIG:
		retcode = dkimf_miltercode(ctx,
		                           conf->conf_handling.hndl_nosig,
		                           NULL);
		if (conf->conf_dolog)
		{
			if (conf->conf_logwhy || retcode != SMFIS_ACCEPT)
			{
				syslog(retcode == SMFIS_ACCEPT ? LOG_DEBUG
				                               : LOG_NOTICE,
				       "%s: no signature data",
				       JOBID(dfc->mctx_jobid));
			}
		}
		replytxt = "no DKIM signature data";
		break;

	  case DKIM_STAT_NORESOURCE:
		retcode = dkimf_miltercode(ctx,
		                           conf->conf_handling.hndl_internal,
		                           NULL);
		if (conf->conf_capture)
			dfc->mctx_capture = TRUE;
		if (conf->conf_dolog)
		{
			const char *err = NULL;

			if (dkim != NULL)
				err = dkim_geterror(dkim);
			if (err == NULL)
				err = strerror(errno);

			syslog(LOG_ERR, "%s: %s%sresource unavailable: %s",
			       JOBID(dfc->mctx_jobid),
			       where == NULL ? "" : where,
			       where == NULL ? "" : ": ", err);
		}
		replytxt = "resource unavailable";
		break;

	  case DKIM_STAT_CANTVRFY:
		retcode = dkimf_miltercode(ctx,
		                           conf->conf_handling.hndl_badsig,
		                           NULL);
		if (conf->conf_dolog && dkim != NULL)
		{
			const char *err = NULL;
			err = dkim_geterror(dkim);
			if (err == NULL)
				err = "unknown cause";

			syslog(LOG_ERR, "%s: signature processing failed: %s",
				JOBID(dfc->mctx_jobid), err);
		}
		replytxt = "DKIM signature processing failed";
		break;

	  case DKIM_STAT_REVOKED:
		retcode = dkimf_miltercode(ctx,
		                           conf->conf_handling.hndl_badsig,
		                           NULL);
		if (conf->conf_dolog)
		{
			u_char *selector = NULL;
			u_char *domain = NULL;

			sig = dkim_getsignature(dkim);
			if (sig != NULL)
			{
				selector = dkim_sig_getselector(sig);
				domain = dkim_sig_getdomain(sig);
			}

			if (selector != NULL && domain != NULL)
			{
				syslog(LOG_NOTICE,
				       "%s: key revoked (s=%s, d=%s)",
				       JOBID(dfc->mctx_jobid), selector,
				       domain);
			}
		}
		break;

	  case DKIM_STAT_KEYFAIL:
	  case DKIM_STAT_NOKEY:
		if (status == DKIM_STAT_KEYFAIL)
		{
			retcode = dkimf_miltercode(ctx,
			                           conf->conf_handling.hndl_dnserr,
			                           NULL);
			replytxt = "DKIM key retrieval timeout";
		}
		else
		{
			retcode = dkimf_miltercode(ctx,
			                           conf->conf_handling.hndl_nokey,
			                           NULL);
			replytxt = "DKIM key retrieval failed";
		}

		if (conf->conf_dolog)
		{
			const char *err = NULL;
			const char *keymsg;
			u_char *selector = NULL;
			u_char *domain = NULL;

			keymsg = (status == DKIM_STAT_KEYFAIL)
			         ? "key retrieval timeout"
			         : "key retrieval failed";

			err = dkim_geterror(dkim);

			sig = dkim_getsignature(dkim);
			if (sig != NULL)
			{
				selector = dkim_sig_getselector(sig);
				domain = dkim_sig_getdomain(sig);
			}

			if (selector != NULL && domain != NULL)
			{
				syslog(LOG_ERR,
				       "%s: %s (s=%s, d=%s)%s%s",
				       JOBID(dfc->mctx_jobid), keymsg, selector,
				       domain,
				       err == NULL ? "" : ": ",
				       err == NULL ? "" : err);
			}
			else
			{
				syslog(LOG_ERR, "%s: %s%s%s",
				       JOBID(dfc->mctx_jobid), keymsg,
				       err == NULL ? "" : ": ",
				       err == NULL ? "" : err);
			}
		}
		break;

	  case DKIM_STAT_SYNTAX:
		retcode = dkimf_miltercode(ctx,
		                           conf->conf_handling.hndl_badsig,
		                           NULL);
		if (conf->conf_dolog)
		{
			const char *err = NULL;

			if (dkim != NULL)
				err = dkim_geterror(dkim);
			if (err == NULL)
				err = "unspecified";

			syslog(LOG_ERR, "%s: syntax error: %s",
			       JOBID(dfc->mctx_jobid), err);
		}
		replytxt = "DKIM signature syntax error";
		break;

	  case DKIM_STAT_SIGGEN:
		retcode = dkimf_miltercode(ctx,
		                           conf->conf_handling.hndl_siggen,
		                           NULL);

		if (conf->conf_dolog)
		{
			const char *err = NULL;

			if (dkim != NULL)
				err = dkim_geterror(dkim);
			if (err == NULL)
				err = "unspecified";

			syslog(LOG_ERR, "%s: signature generation error: %s",
			       JOBID(dfc->mctx_jobid), err);
		}

		replytxt = "DKIM signing error";
		break;
	}

	switch (retcode)
	{
	  case SMFIS_REJECT:
		rcode = "550";
		xcode = "5.7.0";
		break;

	  case SMFIS_TEMPFAIL:
		rcode = "451";
		if (status == DKIM_STAT_KEYFAIL || status == DKIM_STAT_NOKEY)
			xcode = "4.7.5";
		else
			xcode = "4.7.0";
		break;

	  default:
		break;
	}

	if (rcode != NULL && xcode != NULL && replytxt != NULL)
	{
		char replybuf[BUFRSZ];

		if (smtpprefix[0] == '\0')
		{
			strlcpy(replybuf, replytxt, sizeof replybuf);
		}
		else
		{
			snprintf(replybuf, sizeof replybuf, "%s: %s",
			         smtpprefix, replytxt);
		}

		(void) dkimf_setreply(ctx, rcode, xcode, replybuf);
	}

	return retcode;
}

/*
**  DKIMF_FINDHEADER -- find a header
**
**  Parameters:
**  	dfc -- filter context
**  	hname -- name of the header of interest
**  	instance -- which instance is wanted (0 = first)
**
**  Return value:
**  	Header handle, or NULL if not found.
**
**  Notes:
**  	Negative values of "instance" search backwards from the end.
*/

static Header
dkimf_findheader(msgctx dfc, const char *hname, int instance)
{
	Header hdr;

	assert(dfc != NULL);
	assert(hname != NULL);

	if (instance < 0)
		hdr = dfc->mctx_hqtail;
	else
		hdr = dfc->mctx_hqhead;

	while (hdr != NULL)
	{
		if (strcasecmp(hdr->hdr_hdr, hname) == 0)
		{
			if (instance == 0 || instance == -1)
				return hdr;
			else if (instance > 0)
				instance--;
			else
				instance++;
		}

		if (instance < 0)
			hdr = hdr->hdr_prev;
		else
			hdr = hdr->hdr_next;
	}

	return NULL;
}

/*
**  DKIMF_APPLY_SIGNTABLE -- apply the signing table to a message
**
**  Parameters:
**  	conf -- per-connection configuration snapshot (for signrequest)
**  	dfc -- message context
**  	keydb -- database handle for key table
**  	signdb -- database handle for signing table
**  	user -- userid (local-part)
**  	domain -- domain
**  	errkey -- where to write the name of a key that failed
**  	errlen -- bytes available at "errkey"
**  	multisig -- apply multiple signature logic
**
**  Return value:
**  	>= 0 -- number of signatures added
** 	-1 -- signing table read error
**  	-2 -- unknown key
**  	-3 -- key load error
*/

static int
dkimf_apply_signtable(struct dkimf_config *conf, struct msgctx *dfc,
                      DKIMF_DB keydb, DKIMF_DB signdb,
                      unsigned char *user, unsigned char *domain, char *errkey,
                      size_t errlen, _Bool multisig)
{
	_Bool found;
	int nfound = 0;
	char keyname[BUFRSZ + 1];
	u_char tmp[BUFRSZ + 1];

	assert(conf != NULL);
	assert(dfc != NULL);
	assert(keydb != NULL);
	assert(signdb != NULL);
	assert(user != NULL);
	assert(domain != NULL);

	if (dkimf_db_type(signdb) == DKIMF_DB_TYPE_REFILE)
	{
		int status;
		void *ctx = NULL;
		struct dkimf_db_data dbd[2];
		char addr[MAXADDRESS + 1];
		u_char signer[MAXADDRESS + 1];

		snprintf(addr, sizeof addr, "%s@%s", user, domain);

		memset(&dbd, '\0', sizeof dbd);
		dbd[0].dbdata_buffer = keyname;
		dbd[1].dbdata_buffer = (char *) signer;
		dbd[1].dbdata_flags = DKIMF_DB_DATA_OPTIONAL;

		/* walk RE set, find match(es), make request(s) */
		for (;;)
		{
			memset(keyname, '\0', sizeof keyname);
			dbd[0].dbdata_buflen = sizeof keyname - 1;
			memset(signer, '\0', sizeof signer);
			dbd[1].dbdata_buflen = sizeof signer - 1;

			status = dkimf_db_rewalk(signdb, addr, dbd, 2, &ctx);
			if (status == -1)
				return -1;
			else if (status == 1)
				break;

			if (keyname[0] == '%' && keyname[1] == '\0')
				strlcpy(keyname, (char *) domain, sizeof keyname);

			dkimf_reptoken(tmp, sizeof tmp, signer, domain);
			status = dkimf_add_signrequest(conf, dfc, keydb, keyname,
			                               (char *) tmp,
			                               (ssize_t) -1);
			if (status != 0 && errkey != NULL)
				strlcpy(errkey, keyname, errlen);
			if (status == 1)
				return -2;
			else if (status == 2 || status == 3 || status == -1)
				return -3;

			nfound++;

			if (!multisig)
				return nfound;
		}
	}
	else
	{
		int status;
		char *p;
		char tmpaddr[MAXADDRESS + 1];
		u_char signer[MAXADDRESS + 1];
		struct dkimf_db_data req[2];

		memset(&req, '\0', sizeof req);

		memset(keyname, '\0', sizeof keyname);
		memset(signer, '\0', sizeof signer);
		req[0].dbdata_buffer = keyname;
		req[0].dbdata_buflen = sizeof keyname - 1;
		req[1].dbdata_buffer = (char *) signer;
		req[1].dbdata_buflen = sizeof signer - 1;
		req[1].dbdata_flags = DKIMF_DB_DATA_OPTIONAL;

		/* first try full "user@host" */
		snprintf(tmpaddr, sizeof tmpaddr, "%s@%s", user, domain);

		found = FALSE;
		status = dkimf_db_get(signdb, tmpaddr, strlen(tmpaddr),
		                      req, 2, &found);
		if (status != 0 ||
		    (found && (req[0].dbdata_buflen == 0 ||
		               req[0].dbdata_buflen == (size_t) -1)))
		{
			if (status != 0 && dolog)
				dkimf_db_error(signdb, tmpaddr);
			return -1;
		}
		else if (found)
		{
			if (keyname[0] == '%' && keyname[1] == '\0')
				strlcpy(keyname, (char *) domain, sizeof keyname);

			dkimf_reptoken(tmp, sizeof tmp, signer, domain);

			status = dkimf_add_signrequest(conf, dfc, keydb, keyname,
			                               (char *) tmp,
			                               (ssize_t) -1);
			if (status != 0 && errkey != NULL)
				strlcpy(errkey, keyname, errlen);
			if (status == 1)
				return -2;
			else if (status == 2 || status == 3 || status == -1)
				return -3;

			nfound++;

			if (!multisig)
				return nfound;
		}

		/* now just "host" */
		found = FALSE;
		req[0].dbdata_buflen = sizeof keyname - 1;
		req[1].dbdata_buflen = sizeof signer - 1;
		memset(keyname, '\0', sizeof keyname);
		memset(signer, '\0', sizeof signer);
		status = dkimf_db_get(signdb, domain, strlen((char *) domain),
		                      req, 2, &found);
		if (status != 0 ||
		    (found && (req[0].dbdata_buflen == 0 ||
		               req[0].dbdata_buflen == (size_t) -1)))
		{
			if (status != 0 && dolog)
				dkimf_db_error(signdb, (char *) domain);
			return -1;
		}
		else if (found)
		{
			if (keyname[0] == '%' && keyname[1] == '\0')
				strlcpy(keyname, (char *) domain, sizeof keyname);

			dkimf_reptoken(tmp, sizeof tmp, signer, domain);

			status = dkimf_add_signrequest(conf, dfc, keydb, keyname,
			                               (char *) tmp,
			                               (ssize_t) -1);
			if (status != 0 && errkey != NULL)
				strlcpy(errkey, keyname, errlen);
			if (status == 1)
				return -2;
			else if (status == 2 || status == 3 || status == -1)
				return -3;

			nfound++;

			if (!multisig)
				return nfound;
		}

		/* next "user@.domain" and ".domain", degrading */
		for (p = strchr((char *) domain, '.');
		     p != NULL;
		     p = strchr(p + 1, '.'))
		{
			snprintf(tmpaddr, sizeof tmpaddr, "%s@%s",
			         user, p);

			found = FALSE;
			req[0].dbdata_buflen = sizeof keyname - 1;
			req[1].dbdata_buflen = sizeof signer - 1;
			memset(keyname, '\0', sizeof keyname);
			memset(signer, '\0', sizeof signer);
			status = dkimf_db_get(signdb, tmpaddr, strlen(tmpaddr),
			                      req, 2, &found);
			if (status != 0 ||
			    (found && (req[0].dbdata_buflen == 0 ||
			               req[0].dbdata_buflen == (size_t) -1)))
			{
				if (status != 0 && dolog)
					dkimf_db_error(signdb, tmpaddr);
				return -1;
			}
			else if (found)
			{
				if (keyname[0] == '%' && keyname[1] == '\0')
				{
					strlcpy(keyname, (char *) domain,
					        sizeof keyname);
				}

				dkimf_reptoken(tmp, sizeof tmp, signer,
				               domain);

				status = dkimf_add_signrequest(conf, dfc, keydb,
				                               keyname,
				                               (char *) tmp,
				                               (ssize_t) -1);
				if (status != 0 && errkey != NULL)
					strlcpy(errkey, keyname, errlen);
				if (status == 1)
					return -2;
				else if (status == 2 || status == 3 ||
				         status == -1)
					return -3;

				nfound++;

				if (!multisig)
					return nfound;
			}

			found = FALSE;
			req[0].dbdata_buflen = sizeof keyname - 1;
			req[1].dbdata_buflen = sizeof signer - 1;
			memset(keyname, '\0', sizeof keyname);
			memset(signer, '\0', sizeof signer);
			status = dkimf_db_get(signdb, p, strlen(p),
			                      req, 2, &found);
			if (status != 0 ||
			    (found && (req[0].dbdata_buflen == 0 ||
			               req[0].dbdata_buflen == (size_t) -1)))
			{
				if (status != 0 && dolog)
					dkimf_db_error(signdb, p);
				return -1;
			}
			else if (found)
			{
				if (keyname[0] == '%' && keyname[1] == '\0')
				{
					strlcpy(keyname, (char *) domain,
					        sizeof keyname);
				}

				dkimf_reptoken(tmp, sizeof tmp, signer,
				               domain);

				status = dkimf_add_signrequest(conf, dfc, keydb,
				                               keyname,
				                               (char *) tmp,
				                               (ssize_t) -1);
				if (status != 0 && errkey != NULL)
					strlcpy(errkey, keyname, errlen);
				if (status == 1)
					return -2;
				else if (status == 2 || status == 3 ||
				         status == -1)
					return -3;

				nfound++;

				if (!multisig)
					return nfound;
			}
		}

		/* now "user@*" */
		snprintf(tmpaddr, sizeof tmpaddr, "%s@*", user);

		found = FALSE;
		req[0].dbdata_buflen = sizeof keyname - 1;
		req[1].dbdata_buflen = sizeof signer - 1;
		memset(keyname, '\0', sizeof keyname);
		memset(signer, '\0', sizeof signer);
		status = dkimf_db_get(signdb, tmpaddr, strlen(tmpaddr),
		                      req, 2, &found);
		if (status != 0 ||
		    (found && (req[0].dbdata_buflen == 0 ||
		               req[0].dbdata_buflen == (size_t) -1)))
		{
			if (status != 0 && dolog)
				dkimf_db_error(signdb, tmpaddr);
			return -1;
		}
		else if (found)
		{
			if (keyname[0] == '%' && keyname[1] == '\0')
				strlcpy(keyname, (char *) domain, sizeof keyname);

			dkimf_reptoken(tmp, sizeof tmp, signer, domain);

			status = dkimf_add_signrequest(conf, dfc, keydb, keyname,
			                               (char *) tmp,
			                               (ssize_t) -1);
			if (status != 0 && errkey != NULL)
				strlcpy(errkey, keyname, errlen);
			if (status == 1)
				return -2;
			else if (status == 2 || status == 3 || status == -1)
				return -3;

			nfound++;

			if (!multisig)
				return nfound;
		}

		/* finally just "*" */
		found = FALSE;
		req[0].dbdata_buflen = sizeof keyname - 1;
		req[1].dbdata_buflen = sizeof signer - 1;
		memset(keyname, '\0', sizeof keyname);
		memset(signer, '\0', sizeof signer);
		status = dkimf_db_get(signdb, "*", 1, req, 2, &found);
		if (status != 0 ||
		    (found && (req[0].dbdata_buflen == 0 ||
		               req[0].dbdata_buflen == (size_t) -1)))
		{
			if (status != 0 && dolog)
				dkimf_db_error(signdb, "*");
			return -1;
		}
		else if (found)
		{
			if (keyname[0] == '%' && keyname[1] == '\0')
				strlcpy(keyname, (char *) domain, sizeof keyname);

			dkimf_reptoken(tmp, sizeof tmp, signer, domain);

			status = dkimf_add_signrequest(conf, dfc, keydb, keyname,
			                               (char *) tmp,
			                               (ssize_t) -1);
			if (status != 0 && errkey != NULL)
				strlcpy(errkey, keyname, errlen);
			if (status == 1)
				return -2;
			else if (status == 2 || status == 3 || status == -1)
				return -3;

			nfound++;

			if (!multisig)
				return nfound;
		}
	}

	return nfound;
}

/*
**  DKIMF_SIGREPORT -- generate a report on signature failure (if possible)
**
**  Parameters:
**   	cc -- connection context
**  	conf -- current configuration object
**  	hostname -- hostname to use for reporting MTA
**
**  Return value:
**  	None.
*/

static void
dkimf_sigreport(connctx cc, struct dkimf_config *conf, const char *hostname)
{
	_Bool sendreport = FALSE;
	int bfd = -1;
	int hfd = -1;
	int status;
	int arftype = ARF_TYPE_UNKNOWN;
	int arfdkim = ARF_DKIMF_UNKNOWN;
	u_int pct = 100;
	u_int rn;
	time_t now;
	DKIM_STAT repstatus;
	char *p;
	char *last;
	FILE *out;
	msgctx dfc;
	DKIM_SIGINFO *sig;
	struct Header *hdr;
	struct tm tm;
	char ipstr[DKIM_MAXHOSTNAMELEN + 1];
	char opts[BUFRSZ];
	char fmt[BUFRSZ];
	u_char addr[MAXADDRESS + 1];

	assert(cc != NULL);

	dfc = cc->cctx_msg;

	assert(dfc->mctx_dkimv != NULL);
	assert(conf != NULL);
	assert(hostname != NULL);

	memset(addr, '\0', sizeof addr);
	memset(opts, '\0', sizeof opts);

	sig = dkim_getsignature(dfc->mctx_dkimv);

	/* if no report is possible, just skip it */
	repstatus = dkim_sig_getreportinfo(dfc->mctx_dkimv, sig,
	                                   &hfd, &bfd,
	                                   (u_char *) addr, sizeof addr,
	                                   (u_char *) opts, sizeof opts,
	                                   NULL, 0, &pct);
	if (repstatus != DKIM_STAT_OK || addr[0] == '\0')
		return;

	if (pct < 100)
	{
		rn = (u_int)(random() % 100);
		if (rn > pct)
			return;
	}

	/* ignore any domain name in "r=" */
	p = strchr((char *) addr, '@');
	if (p != NULL)
		*p = '\0';

	/* ensure the event being reported was requested */
	if (opts[0] == '\0')
	{
		sendreport = TRUE;
	}
	else
	{
		for (p = strtok_r(opts, ":", &last);
		     p != NULL;
		     p = strtok_r(NULL, ":", &last))
		{
			if (strcasecmp(p, ARF_OPTIONS_DKIM_ALL) == 0)
			{
				sendreport = TRUE;
				break;
			}
			else if (strcasecmp(p, ARF_OPTIONS_DKIM_SYNTAX) == 0)
			{
				int err;

				err = dkim_sig_geterror(sig);

				if (err == DKIM_SIGERROR_TIMESTAMPS ||
				    err == DKIM_SIGERROR_INVALID_HC ||
				    err == DKIM_SIGERROR_INVALID_BC ||
				    err == DKIM_SIGERROR_MISSING_A ||
				    err == DKIM_SIGERROR_INVALID_A ||
				    err == DKIM_SIGERROR_MISSING_H ||
				    err == DKIM_SIGERROR_INVALID_L ||
				    err == DKIM_SIGERROR_INVALID_Q ||
				    err == DKIM_SIGERROR_INVALID_QO ||
				    err == DKIM_SIGERROR_MISSING_D ||
				    err == DKIM_SIGERROR_EMPTY_D ||
				    err == DKIM_SIGERROR_MISSING_S ||
				    err == DKIM_SIGERROR_EMPTY_S ||
				    err == DKIM_SIGERROR_MISSING_B ||
				    err == DKIM_SIGERROR_EMPTY_B ||
				    err == DKIM_SIGERROR_CORRUPT_B ||
				    err == DKIM_SIGERROR_MISSING_BH ||
				    err == DKIM_SIGERROR_EMPTY_BH ||
				    err == DKIM_SIGERROR_CORRUPT_BH ||
				    err == DKIM_SIGERROR_EMPTY_H ||
				    err == DKIM_SIGERROR_INVALID_H ||
				    err == DKIM_SIGERROR_TOOLARGE_L ||
				    err == DKIM_SIGERROR_MISSING_V ||
				    err == DKIM_SIGERROR_EMPTY_V)
				{
					sendreport = TRUE;
					break;
				}
			}
			else if (strcasecmp(p, ARF_OPTIONS_DKIM_EXPIRED) == 0)
			{
				if (dkim_sig_geterror(sig) == DKIM_SIGERROR_EXPIRED)
				{
					sendreport = TRUE;
					break;
				}
			}
			else if (strcasecmp(p, ARF_OPTIONS_DKIM_VERIFY) == 0)
			{
				if (dkim_sig_geterror(sig) == DKIM_SIGERROR_BADSIG ||
				    dkim_sig_getbh(sig) == DKIM_SIGBH_MISMATCH)
				{
					sendreport = TRUE;
					break;
				}
			}
			else if (strcasecmp(p, ARF_OPTIONS_DKIM_DNS) == 0)
			{
				int err;

				err = dkim_sig_geterror(sig);

				if (err == DKIM_SIGERROR_NOKEY ||
				    err == DKIM_SIGERROR_DNSSYNTAX ||
				    err == DKIM_SIGERROR_KEYFAIL ||
				    err == DKIM_SIGERROR_KEYDECODE ||
				    err == DKIM_SIGERROR_MULTIREPLY)
				{
					sendreport = TRUE;
					break;
				}
			}
			else if (strcasecmp(p, ARF_OPTIONS_DKIM_POLICY) == 0)
			{
				int err;

				err = dkim_sig_geterror(sig);

				if (err == DKIM_SIGERROR_MBSFAILED)
				{
					sendreport = TRUE;
					break;
				}
			}
			else if (strcasecmp(p, ARF_OPTIONS_DKIM_OTHER) == 0)
			{
				int err;

				err = dkim_sig_geterror(sig);

				if (err == DKIM_SIGERROR_SUBDOMAIN ||
				    err == DKIM_SIGERROR_KEYVERSION ||
				    err == DKIM_SIGERROR_KEYUNKNOWNHASH ||
				    err == DKIM_SIGERROR_KEYHASHMISMATCH ||
				    err == DKIM_SIGERROR_NOTEMAILKEY ||
				    err == DKIM_SIGERROR_KEYTYPEMISSING ||
				    err == DKIM_SIGERROR_KEYTYPEUNKNOWN ||
				    err == DKIM_SIGERROR_KEYREVOKED)
				{
					sendreport = TRUE;
					break;
				}
			}
		}
	}

	if (!sendreport)
		return;

#ifdef HAVE_LIBCURL
	if (conf->conf_smtpuri != NULL)
	{
		int fd;
		char path[MAXPATHLEN + 1];

		snprintf(path, sizeof path, "%s/%s.XXXXXX", conf->conf_tmpdir,
		         progname);

		fd = mkstemp(path);
		if (fd < 0)
		{
			if (conf->conf_dolog)
			{
				syslog(LOG_ERR, "%s: mkstemp(): %s",
				       dfc->mctx_jobid, strerror(errno));
			}

			return;
		}

		unlink(path);

		out = fdopen(fd, "w");
		if (out == NULL)
		{
			if (conf->conf_dolog)
			{
				syslog(LOG_ERR, "%s: fdopen(): %s",
				       dfc->mctx_jobid, strerror(errno));
			}
	
			close(fd);
			return;
		}
	}
	else
	{
		out = popen(reportcmd, "w");
		if (out == NULL)
		{
			if (conf->conf_dolog)
			{
				syslog(LOG_ERR, "%s: popen(): %s",
				       dfc->mctx_jobid, strerror(errno));
			}
	
			return;
		}
	}
#else /* HAVE_LIBCURL */
	out = popen(reportcmd, "w");
	if (out == NULL)
	{
		if (conf->conf_dolog)
		{
			syslog(LOG_ERR, "%s: popen(): %s",
			       dfc->mctx_jobid, strerror(errno));
		}

		return;
	}
#endif /* HAVE_LIBCURL */

	/* determine the type of ARF failure and, if needed, a DKIM fail code */
	arftype = dkimf_arftype(dfc);
	if (arftype == ARF_TYPE_AUTHFAIL)
		arfdkim = dkimf_arfdkim(dfc);

	/* From: */
	fprintf(out, "From: %s\n", reportaddr);

	/* To: */
	fprintf(out, "To: %s@%s\n", addr, dkim_sig_getdomain(sig));

	/* Bcc: */
	if (conf->conf_reportaddrbcc != NULL)
		fprintf(out, "Bcc: %s\n", conf->conf_reportaddrbcc);

	/* Date: */
	memset(fmt, '\0', sizeof fmt);
	(void) time(&now);
	(void) localtime_r(&now, &tm);
	(void) strftime(fmt, sizeof fmt, "%a, %e %b %Y %H:%M:%S %z (%Z)", &tm);
	fprintf(out, "Date: %s\n", fmt);

	/* Subject: */
	fprintf(out, "Subject: DKIM failure report for %s\n",
	        dfc->mctx_jobid);

	/* MIME stuff */
	fprintf(out, "MIME-Version: 1.0\n");
	fprintf(out,
	        "Content-Type: multipart/report; report-type=feedback-report;\n\tboundary=\"dkimreport/%s/%s\"",
	        hostname, dfc->mctx_jobid);

	/* ok, now then... */
	fprintf(out, "\n");

	/* first part: a text blob explaining what this is */
	fprintf(out, "--dkimreport/%s/%s\n", hostname, dfc->mctx_jobid);
	fprintf(out, "Content-Type: text/plain\n");
	fprintf(out, "\n");
	fprintf(out, "DKIM failure report for job %s on %s\n\n",
	        dfc->mctx_jobid, hostname);
	fprintf(out,
	        "The canonicalized form of the failed message's header and body are\nattached.\n");
	fprintf(out, "\n");

	/* second part: formatted gunk */
	memset(ipstr, '\0', sizeof ipstr);

	switch (cc->cctx_ip.ss_family)
	{
	  case AF_INET:
	  {
		struct sockaddr_in sin4;

		memcpy(&sin4, &cc->cctx_ip, sizeof sin4);

		(void) inet_ntop(AF_INET, &sin4.sin_addr, ipstr, sizeof ipstr);

		break;
	  }

#ifdef AF_INET6
	  case AF_INET6:
	  {
		struct sockaddr_in6 sin6;

		memcpy(&sin6, &cc->cctx_ip, sizeof sin6);

		(void) inet_ntop(AF_INET6, &sin6.sin6_addr, ipstr, sizeof ipstr);

		break;
	  }
#endif /* AF_INET6 */
	}

	hdr = dkimf_findheader(dfc, "Message-ID", 0);

	fprintf(out, "--dkimreport/%s/%s\n", hostname, dfc->mctx_jobid);
	fprintf(out, "Content-Type: message/feedback-report\n");
	fprintf(out, "\n");
	fprintf(out, "User-Agent: %s/%s\n", DKIMF_PRODUCTNS, DKIMF_VERSION);
	fprintf(out, "Version: %s\n", ARF_VERSION);
	fprintf(out, "Original-Envelope-Id: %s\n", dfc->mctx_jobid);
	fprintf(out, "Original-Mail-From: %s\n", dfc->mctx_envfrom);
	fprintf(out, "Reporting-MTA: %s\n", hostname);
	fprintf(out, "Source-IP: %s\n", ipstr);
	fprintf(out, "Message-ID:%s%s\n",
	        cc->cctx_noleadspc ? "" : " ",
	        hdr == NULL ? "(none)" : hdr->hdr_val);
	fprintf(out, "Arrival-Date: %s\n", fmt);
	fprintf(out, "Reported-Domain: %s\n", dkim_sig_getdomain(sig));
	fprintf(out, "Delivery-Result: other\n");
	fprintf(out, "Feedback-Type: %s\n", arf_type_string(arftype));
	if (arftype == ARF_TYPE_AUTHFAIL)
	{
		fprintf(out, "Auth-Failure: ");
		if (dkim_sig_getbh(sig) == DKIM_SIGBH_MISMATCH)
		{
			fprintf(out, "bodyhash\n");
		}
		else
		{
			const char *tmperror;

			switch (dkim_sig_geterror(sig))
			{
			  case DKIM_SIGERROR_KEYREVOKED:
				fprintf(out, "revoked\n");
				break;

			  default:
				tmperror = dkim_sig_geterrorstr(dkim_sig_geterror(sig));
				fprintf(out, "signature");
				if (tmperror != NULL)
					fprintf(out, " (%s)", tmperror);
				fprintf(out, "\n");
				break;
			}
		}

		memset(addr, '\0', sizeof addr);
		dkim_sig_getidentity(dfc->mctx_dkimv, sig, addr,
		                     sizeof addr - 1);

		/* fprintf(out, "Authentication-Results: %s\n", ...); */
		fprintf(out, "DKIM-Failure: %s\n",
		        arf_dkim_failure_string(arfdkim));
		fprintf(out, "DKIM-Domain: %s\n", dkim_sig_getdomain(sig));
		fprintf(out, "DKIM-Selector: %s\n", dkim_sig_getselector(sig));
		fprintf(out, "DKIM-Identity: %s\n", addr);
		if (hfd != -1)
		{
			fprintf(out, "DKIM-Canonicalized-Header: ");
			(void) dkimf_base64_encode_file(hfd, out, 4, 75, 27);
			fprintf(out, "\n");
		}
		if (bfd != -1)
		{
			fprintf(out, "DKIM-Canonicalized-Body: ");
			(void) dkimf_base64_encode_file(bfd, out, 4, 75, 25);
			fprintf(out, "\n");
		}
	}

	fprintf(out, "\n");

	/* third part: header block */
	fprintf(out, "--dkimreport/%s/%s\n", hostname, dfc->mctx_jobid);
	fprintf(out, "Content-Type: text/rfc822-headers\n");
	fprintf(out, "\n");

	for (hdr = dfc->mctx_hqhead; hdr != NULL; hdr = hdr->hdr_next)
	{
		fprintf(out, "%s:%s%s\n", hdr->hdr_hdr,
		        cc->cctx_noleadspc ? "" : " ", hdr->hdr_val);
	}

	/* end */
	fprintf(out, "\n--dkimreport/%s/%s--\n", hostname, dfc->mctx_jobid);

	/* send it */
#ifdef HAVE_LIBCURL
	if (conf->conf_smtpuri != NULL)
	{
		CURLcode curl_rc;
		CURL *curl;
		struct curl_slist *rcpts = NULL;
		char dest[MAXADDRESS + 1];

		(void) fseek(out, SEEK_SET, 0);

		curl = curl_easy_init();
		if (curl == NULL)
		{
			if (conf->conf_dolog)
			{
				syslog(LOG_ERR, "%s: curl_easy_init() failed",
				       dfc->mctx_jobid);
			}
		}
		else
		{
			curl_rc = curl_easy_setopt(curl, CURLOPT_URL,
			                           conf->conf_smtpuri);

			if (curl_rc == CURLE_OK)
			{
				curl_rc = curl_easy_setopt(curl, CURLOPT_READDATA,
				                           out);
			}

			if (curl_rc == CURLE_OK)
			{
				curl_rc = curl_easy_setopt(curl, CURLOPT_MAIL_FROM,
				                           reportaddr);
			}

			if (curl_rc == CURLE_OK)
			{
				int n;

				n = snprintf(dest, sizeof dest, "%s@%s", addr,
				             dkim_sig_getdomain(sig));

				if (n < 0 || (size_t) n >= sizeof dest)
				{
					/* truncated recipient: don't send to a
					   malformed address */
					if (conf->conf_dolog)
					{
						syslog(LOG_ERR,
						       "%s: report recipient address too long; report not sent",
						       dfc->mctx_jobid);
					}

					curl_rc = CURLE_BAD_FUNCTION_ARGUMENT;
				}
				else
				{
					rcpts = curl_slist_append(rcpts, dest);
					curl_rc = curl_easy_setopt(curl,
					                           CURLOPT_MAIL_RCPT,
					                           rcpts);
				}
			}

			if (curl_rc != CURLE_OK)
			{
				if (conf->conf_dolog)
				{
					syslog(LOG_ERR,
					       "%s: curl_easy_setopt() failed",
					       dfc->mctx_jobid);
				}
			}
			else
			{
				curl_rc = curl_easy_perform(curl);
				if (curl_rc != CURLE_OK && conf->conf_dolog)
				{
					syslog(LOG_ERR,
					       "%s: curl_easy_perform() to %s failed: %s",
					       dfc->mctx_jobid, dest,
					       curl_easy_strerror(curl_rc));
				}
			}

			curl_slist_free_all(rcpts);

			curl_easy_cleanup(curl);
		}
	}
	else
	{
		status = pclose(out);
		if (status != 0 && conf->conf_dolog)
		{
			syslog(LOG_ERR, "%s: pclose(): returned status %d",
			       dfc->mctx_jobid, status);
		}
	}
#else /* HAVE_LIBCURL */
	status = pclose(out);
	if (status != 0 && conf->conf_dolog)
	{
		syslog(LOG_ERR, "%s: pclose(): returned status %d",
		       dfc->mctx_jobid, status);
	}
#endif /* HAVE_LIBCURL */
}

/*
**  DKIMF_AR_ALL_SIGS -- append Authentication-Results items for all signatures
**
**  Parameters:
**  	hdr -- header buffer
** 	hdrlen -- size of header buffer
**  	dkim -- DKIM verification handle
**  	conf -- config object
**  	status -- message context status (may be updated)
**
**  Return value:
**  	FALSE iff the filter should reject the message based on results.
*/

static void
dkimf_ar_all_sigs(char *hdr, size_t hdrlen, DKIM *dkim,
                  struct dkimf_config *conf, int *status)
{
	int nsigs;
	DKIM_STAT dstatus;
	DKIM_SIGINFO **sigs;

	assert(hdr != NULL);
	assert(dkim != NULL);
	assert(conf != NULL);
	assert(status != NULL);

	dstatus = dkim_getsiglist(dkim, &sigs, &nsigs);
	if (dstatus == DKIM_STAT_OK)
	{
		int c;
		int sigerror;
		DKIM_STAT ts;
		u_int keybits;
		size_t ssl;
		const char *result;
		const char *dnssec;
		char *domain;
		char *selector;
		char *algorithm;
		char ss[BUFRSZ + 1];
		char val[MAXADDRESS + 1];
		char comment[BUFRSZ + 1];

		for (c = 0; c < nsigs; c++)
		{
			unsigned int sigflag;
			dnssec = NULL;

			memset(comment, '\0', sizeof comment);

			sigerror = dkim_sig_geterror(sigs[c]);

			if (dkim_sig_getkeysize(sigs[c],
			                        &keybits) != DKIM_STAT_OK)
				keybits = 0;

			if (conf->conf_noheaderb)
			{
				ts = -1;
			}
			else
			{
				ssl = sizeof ss - 1;
				ts = dkim_get_sigsubstring(dkim, sigs[c], ss,
				                           &ssl);
			}

			sigflag = dkim_sig_getflags(sigs[c]);
			if (sigflag & DKIM_SIGFLAG_IGNORE)
			{
				result = "policy";
			}
			else if ((sigflag & DKIM_SIGFLAG_PASSED) != 0 &&
			    dkim_sig_getbh(sigs[c]) == DKIM_SIGBH_MATCH)
			{
				result = "pass";
			}
			else if (sigerror == DKIM_SIGERROR_MULTIREPLY ||
			         sigerror == DKIM_SIGERROR_KEYFAIL ||
			         sigerror == DKIM_SIGERROR_DNSSYNTAX)
			{
				result = "temperror";
			}
			else if (sigerror == DKIM_SIGERROR_KEYTOOSMALL)
			{
				const char *err;

				result = "policy";

				err = dkim_sig_geterrorstr(dkim_sig_geterror(sigs[c]));
				if (err != NULL)
				{
					snprintf(comment, sizeof comment,
					         " reason=\"%s\"", err);
				}
			}
			else if (sigerror == DKIM_SIGERROR_WEAKALG)
			{
				const char *err;

				/*
				**  RFC 8301: the library short-circuited this
				**  rsa-sha1 signature, so it never verified.
				**  Report it as "neutral" rather than "fail";
				**  the On-WeakAlgorithm disposition is applied in
				**  mlfi_eom().
				*/

				result = "neutral";

				err = dkim_sig_geterrorstr(sigerror);
				if (err != NULL)
				{
					snprintf(comment, sizeof comment,
					         " reason=\"%s\"", err);
				}
			}
			else if ((sigflag & DKIM_SIGFLAG_PROCESSED) != 0 &&
			         ((sigflag & DKIM_SIGFLAG_PASSED) == 0 ||
			          dkim_sig_getbh(sigs[c]) != DKIM_SIGBH_MATCH))
			{
				const char *err;

				result = "fail";

				err = dkim_sig_geterrorstr(dkim_sig_geterror(sigs[c]));
				if (err != NULL)
				{
					snprintf(comment, sizeof comment,
					         " reason=\"%s\"", err);
				}
			}
			/*
			**  dkim_sig_geterror() returns int while the sentinel
			**  macros are u_int (see dkim.h); cast locally to keep
			**  the compare u_int == u_int.
			*/
			else if ((u_int) sigerror != DKIM_SIGERROR_UNKNOWN &&
			         (u_int) sigerror != DKIM_SIGERROR_OK)
			{
				result = "permerror";
			}
			else
			{
				result = "neutral";
			}

			dnssec = NULL;

			switch (dkim_sig_getdnssec(sigs[c]))
			{
			  case DKIM_DNSSEC_UNKNOWN:
				break;

			  case DKIM_DNSSEC_INSECURE:
				dnssec = "insecure";
				if (conf->conf_unprotectedkey == DKIMF_KEYACTIONS_FAIL)
				{
					*status = DKIMF_STATUS_BAD;
					result = "policy";
				}
				else if (conf->conf_unprotectedkey == DKIMF_KEYACTIONS_NEUTRAL)
				{
					*status = DKIMF_STATUS_VERIFYERR;
					result = "neutral";
				}
				break;

			  case DKIM_DNSSEC_BOGUS:
				dnssec = "bogus";
				if (conf->conf_boguskey == DKIMF_KEYACTIONS_FAIL)
				{
					*status = DKIMF_STATUS_BAD;
				}
				else if (conf->conf_boguskey == DKIMF_KEYACTIONS_NEUTRAL)
				{
					*status = DKIMF_STATUS_VERIFYERR;
					result = "neutral";
				}
				syslog(LOG_WARNING,
				       "%s: DNSSEC validation failed (bogus) for key record of signature from %s (selector %s); possible attack",
				       dkim_getid(dkim),
				       dkim_sig_getdomain(sigs[c]),
				       dkim_sig_getselector(sigs[c]));
				break;

			  case DKIM_DNSSEC_SECURE:
				dnssec = "secure";
				break;
			}

			size_t n = 0;
			int r;

			memset(val, '\0', sizeof val);

			(void)dkim_sig_getidentity(dkim, sigs[c],
									(u_char *) val,
									sizeof val - 1);

			domain = (char *) dkim_sig_getdomain(sigs[c]);
			selector = (char *) dkim_sig_getselector(sigs[c]);
			algorithm = (char *) dkim_sig_getalgorithm(sigs[c]);

			#define APPEND(...) do {                            \
				if (n >= hdrlen)                                \
					break;                                      \
                                                                \
				r = snprintf(hdr + n, hdrlen - n, __VA_ARGS__); \
                                                                \
				if (r < 0)                                      \
				{                                               \
					n = hdrlen;                                 \
					break;                                      \
				}                                               \
                                                                \
				if ((size_t)r >= hdrlen - n)                    \
				{                                               \
					n = hdrlen;                                 \
					break;                                      \
				}                                               \
                                                                \
				n += (size_t) r;                                \
			} while (0)

			APPEND("%s%sdkim=%s%s (%u-bit key%s%s) header.d=%s header.i=%s header.a=%s header.s=%s%s%s%s",
				c == 0 ? "" : ";",
				DELIMITER, result, comment,
				keybits,
				dnssec == NULL ? "" : ", ",
				dnssec == NULL ? "" : dnssec,
				domain, val, algorithm, selector,
				ts == DKIM_STAT_OK ? " header.b=\"" : "",
				ts == DKIM_STAT_OK ? ss : "",
				ts == DKIM_STAT_OK ? "\"" : "");

			#undef APPEND
		}
	}
}

/*
**  END private section
**  ==================================================================
**  BEGIN milter section
*/

#if SMFI_VERSION >= 0x01000000
/*
**  MLFI_NEGOTIATE -- handler called on new SMTP connection to negotiate
**                    MTA options
**
**  Parameters:
**  	ctx -- milter context
**	f0  -- actions offered by the MTA
**	f1  -- protocol steps offered by the MTA
**	f2  -- reserved for future extensions
**	f3  -- reserved for future extensions
**	pf0 -- actions requested by the milter
**	pf1 -- protocol steps requested by the milter
**	pf2 -- reserved for future extensions
**	pf3 -- reserved for future extensions
**
**  Return value:
**  	An SMFIS_* constant.
*/

sfsistat
mlfi_negotiate(SMFICTX *ctx,
	unsigned long f0, unsigned long f1,
	unsigned long f2, unsigned long f3,
	unsigned long *pf0, unsigned long *pf1,
	unsigned long *pf2, unsigned long *pf3)
{
	unsigned long reqactions = SMFIF_ADDHDRS;
# if defined(SMFIF_SETSYMLIST) && defined(HAVE_SMFI_SETSYMLIST)
	unsigned long wantactions = (SMFIF_SETSYMLIST);
# else /* defined(SMFIF_SETSYMLIST) && defined(HAVE_SMFI_SETSYMLIST) */
	unsigned long wantactions = 0;
# endif /* defined(SMFIF_SETSYMLIST) && defined(HAVE_SMFI_SETSYMLIST) */
	unsigned long protosteps = (SMFIP_NOHELO |
	                            SMFIP_NOUNKNOWN |
	                            SMFIP_NODATA |
	                            SMFIP_SKIP );
	connctx cc;
	struct dkimf_config *conf;

	(void) f2;
	(void) f3;

	dkimf_config_reload();

	/* initialize connection context */
	cc = malloc(sizeof(struct connctx));
	if (cc == NULL)
	{
		if (curconf->conf_dolog)
		{
			syslog(LOG_ERR, "mlfi_negotiate(): malloc(): %s",
			       strerror(errno));
		}

		return SMFIS_TEMPFAIL;
	}

	memset(cc, '\0', sizeof(struct connctx));

	pthread_mutex_lock(&conf_lock);

	cc->cctx_config = curconf;
	curconf->conf_refcnt++;
	conf = curconf;

	pthread_mutex_unlock(&conf_lock);

	/* verify the actions we need are available */
	if (conf->conf_remarall ||
	    !conf->conf_keepar ||
	    conf->conf_rmidentityhdr ||
# ifdef USE_LUA
	    conf->conf_finalscript != NULL ||
# endif /* USE_LUA */
	    conf->conf_remsigs)
		reqactions |= SMFIF_CHGHDRS;

# ifdef SMFIF_QUARANTINE
#  ifdef USE_LUA
	if (conf->conf_capture || conf->conf_finalscript != NULL)
#  else /* USE_LUA */
	if (conf->conf_capture)
#  endif /* USE_LUA */
		reqactions |= SMFIF_QUARANTINE;
# endif /* SMFIF_QUARANTINE */

# ifdef USE_LUA
	if (conf->conf_redirect != NULL || conf->conf_finalscript != NULL)
# else /* USE_LUA */
	if (conf->conf_redirect != NULL)
# endif /* USE_LUA */
	{
		reqactions |= SMFIF_ADDRCPT;
		reqactions |= SMFIF_DELRCPT;
	}

	if ((f0 & reqactions) != reqactions)
	{
		if (conf->conf_dolog)
		{
			syslog(LOG_ERR,
			       "mlfi_negotiate(): required milter action(s) not available (got 0x%lx, need 0x%lx)",
			       f0, reqactions);
		}

		pthread_mutex_lock(&conf_lock);
		conf->conf_refcnt--;
		pthread_mutex_unlock(&conf_lock);

		free(cc);

		return SMFIS_REJECT;
	}

	/* also try to get some nice features */
	wantactions = (wantactions & f0);

	/* set the actions we want */
	*pf0 = (reqactions | wantactions);

	/* disable as many protocol steps we don't need as are available */
	*pf1 = (protosteps & f1);

# ifdef SMFIP_HDR_LEADSPC
	/* request preservation of leading spaces if possible */
	if ((f1 & SMFIP_HDR_LEADSPC) != 0)
	{
		if (cc != NULL)
		{
			cc->cctx_noleadspc = TRUE;
			*pf1 |= SMFIP_HDR_LEADSPC;
		}
	}
# endif /* SMFIP_HDR_LEADSPC */

	*pf2 = 0;
	*pf3 = 0;

	/* request macros if able */
# if defined(SMFIF_SETSYMLIST) && defined(HAVE_SMFI_SETSYMLIST)
	if (conf->conf_macros != NULL && (wantactions & SMFIF_SETSYMLIST) != 0)
	{
		int c;
		char macrolist[BUFRSZ];

		memset(macrolist, '\0', sizeof macrolist);

		strlcpy(macrolist, DKIMF_EOHMACROS, sizeof macrolist);

		for (c = 0; conf->conf_macros[c] != NULL; c++)
		{
			if (macrolist[0] != '\0')
				strlcat(macrolist, " ", sizeof macrolist);

			if (strlcat(macrolist, conf->conf_macros[c],
			            sizeof macrolist) >= sizeof macrolist)
			{
				if (conf->conf_dolog)
				{
					syslog(LOG_ERR,
					       "mlfi_negotiate(): macro list overflow");
				}

				pthread_mutex_lock(&conf_lock);
				conf->conf_refcnt--;
				pthread_mutex_unlock(&conf_lock);

				free(cc);

				return SMFIS_REJECT;
			}
		}

		if (smfi_setsymlist(ctx, SMFIM_EOH, macrolist) != MI_SUCCESS)
		{
			if (conf->conf_dolog)
				syslog(LOG_ERR, "smfi_setsymlist() failed");

			pthread_mutex_lock(&conf_lock);
			conf->conf_refcnt--;
			pthread_mutex_unlock(&conf_lock);

			free(cc);

			return SMFIS_REJECT;
		}
	}
# endif /* defined(SMFIF_SETSYMLIST) && defined(HAVE_SMFI_SETSYMLIST) */

	/* set "milterv2" flag if SMFIP_SKIP was available */
	if ((f1 & SMFIP_SKIP) != 0)
		cc->cctx_milterv2 = TRUE;

	(void) dkimf_setpriv(ctx, cc);

	return SMFIS_CONTINUE;
}
#endif /* SMFI_VERSION >= 0x01000000 */

/*
**  MLFI_CONNECT -- connection handler
**
**  Parameters:
**  	ctx -- milter context
**  	host -- hostname
**  	ip -- address, in in_addr form
**
**  Return value:
**  	An SMFIS_* constant.
*/

sfsistat
mlfi_connect(SMFICTX *ctx, char *host, _SOCK_ADDR *ip)
{
	const char *err = NULL;
	connctx cc;
	struct dkimf_config *conf;

	dkimf_config_reload();

	/* Snapshot curconf and bump its refcnt before dereferencing any
	   field, so a concurrent reload that drops the previous curconf
	   to refcnt 0 cannot free it out from under this thread. */
	pthread_mutex_lock(&conf_lock);
	conf = curconf;
	conf->conf_refcnt++;
	pthread_mutex_unlock(&conf_lock);

	if (!dkimf_dns_init(conf->conf_libopendkim, conf, &err))
	{
		if (conf->conf_dolog)
			syslog(LOG_ERR, "can't initialize resolver: %s", err);

		pthread_mutex_lock(&conf_lock);
		conf->conf_refcnt--;
		if (conf->conf_refcnt == 0 && conf != curconf)
			dkimf_config_free(conf);
		pthread_mutex_unlock(&conf_lock);

		return SMFIS_TEMPFAIL;
	}

	/* copy hostname and IP information to a connection context */
	cc = dkimf_getpriv(ctx);
	if (cc == NULL)
	{
		cc = malloc(sizeof(struct connctx));
		if (cc == NULL)
		{
			if (conf->conf_dolog)
			{
				syslog(LOG_ERR, "%s malloc(): %s", host,
				       strerror(errno));
			}

			pthread_mutex_lock(&conf_lock);
			conf->conf_refcnt--;
			if (conf->conf_refcnt == 0 && conf != curconf)
				dkimf_config_free(conf);
			pthread_mutex_unlock(&conf_lock);

			/* XXX result should depend on On-InternalError */
			return SMFIS_TEMPFAIL;
		}

		memset(cc, '\0', sizeof(struct connctx));

		/* refcnt was already taken on the snapshot above; that
		   refcnt is now owned by cc and will be released by
		   mlfi_close. */
		cc->cctx_config = conf;

		dkimf_setpriv(ctx, cc);
	}
	else
	{
		/* cc already holds a refcnt on its cctx_config (taken in
		   mlfi_negotiate). Drop the snapshot refcnt we just took
		   and continue with cc's existing config. */
		pthread_mutex_lock(&conf_lock);
		conf->conf_refcnt--;
		if (conf->conf_refcnt == 0 && conf != curconf)
			dkimf_config_free(conf);
		pthread_mutex_unlock(&conf_lock);

		conf = cc->cctx_config;
	}

	/* if the client is on an ignored host, then ignore it */
	if (conf->conf_peerdb != NULL)
	{
		/* try hostname, if available */
		if (host != NULL && host[0] != '\0' && host[0] != '[')
		{
			dkimf_lowercase((u_char *) host);
			if (dkimf_checkhost(conf->conf_peerdb, host))
				return SMFIS_ACCEPT;
		}

		/* try IP address, if available */
		if (ip != NULL && (ip->sa_family == AF_INET
#ifdef AF_INET6
			|| ip->sa_family == AF_INET6
#endif /* AF_INET6 */
			))
		{
			if (dkimf_checkip(conf->conf_peerdb, ip))
				return SMFIS_ACCEPT;
		}
	}

	if (host != NULL)
		strlcpy(cc->cctx_host, host, sizeof cc->cctx_host);

	if (ip == NULL)
	{
		struct sockaddr_in sin;

		memset(&sin, '\0', sizeof sin);
		sin.sin_family = AF_INET;
		sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);

		memcpy(&cc->cctx_ip, &sin, sizeof sin);
	}
	else if (ip->sa_family == AF_INET)
	{
		memcpy(&cc->cctx_ip, ip, sizeof(struct sockaddr_in));
	}
#ifdef AF_INET6
	else if (ip->sa_family == AF_INET6)
	{
		memcpy(&cc->cctx_ip, ip, sizeof(struct sockaddr_in6));
	}
#endif /* AF_INET6 */

	cc->cctx_msg = NULL;

	return SMFIS_CONTINUE;
}

#if SMFI_VERSION == 2
/*
**  MLFI_HELO -- handler for HELO/EHLO command (start of message)
**
**  Parameters:
**  	ctx -- milter context
**  	helo -- HELO/EHLO parameter
**
**  Return value:
**  	An SMFIS_* constant.
*/

sfsistat
mlfi_helo(SMFICTX *ctx, char *helo)
{
	assert(ctx != NULL);
	assert(helo != NULL);

	return SMFIS_CONTINUE;
}
#endif /* SMFI_VERSION == 2 */

/*
**  MLFI_ENVFROM -- handler for MAIL FROM command (start of message)
**
**  Parameters:
**  	ctx -- milter context
**  	envfrom -- envelope from arguments
**
**  Return value:
**  	An SMFIS_* constant.
*/

sfsistat
mlfi_envfrom(SMFICTX *ctx, char **envfrom)
{
	connctx cc;
	msgctx dfc;
	struct dkimf_config *conf;

	assert(ctx != NULL);
	assert(envfrom != NULL);

	cc = (connctx) dkimf_getpriv(ctx);
	assert(cc != NULL);
	conf = cc->cctx_config;

	/*
	**  Initialize a filter context.
	*/

	dkimf_cleanup(ctx);
	dfc = dkimf_initcontext(conf);
	if (dfc == NULL)
	{
		if (conf->conf_dolog)
		{
			syslog(LOG_INFO,
			       "message requeueing (internal error)");
		}

		dkimf_cleanup(ctx);
		return SMFIS_TEMPFAIL;
	}

	if (envfrom[0] != NULL)
	{
		size_t len;
		unsigned char *p;
		unsigned char *q;

		strlcpy((char *) dfc->mctx_envfrom, envfrom[0],
		        sizeof dfc->mctx_envfrom);

		len = strlen((char *) dfc->mctx_envfrom);
		p = dfc->mctx_envfrom;
		q = dfc->mctx_envfrom + len - 1;

		while (len >= 2 && *p == '<' && *q == '>')
		{
			p++;
			q--;
			len -= 2;
		}

		if (p != dfc->mctx_envfrom)
		{
			*(q + 1) = '\0';
			memmove(dfc->mctx_envfrom, p, len + 1);
		}
	}

	/*
	**  Save it in this thread's private space.
	*/

	cc->cctx_msg = dfc;

	/*
	**  Continue processing.
	*/

	return SMFIS_CONTINUE;
}

/*
**  MLFI_ENVRCPT -- handler for RCPT TO command
**
**  Parameters:
**  	ctx -- milter context
**  	envrcpt -- envelope rcpt to arguments
**
**  Return value:
**  	SMFIS_CONTINUE
*/

sfsistat
mlfi_envrcpt(SMFICTX *ctx, char **envrcpt)
{
	char *copy;
	connctx cc;
	msgctx dfc;
	struct dkimf_config *conf;
	char addr[MAXADDRESS + 1];

	assert(ctx != NULL);
	assert(envrcpt != NULL);

	cc = (connctx) dkimf_getpriv(ctx);
	assert(cc != NULL);
	dfc = cc->cctx_msg;
	assert(dfc != NULL);
	conf = cc->cctx_config;

	if (conf->conf_dontsigntodb != NULL
	    || conf->conf_bldb != NULL
	    || conf->conf_redirect != NULL
	    || conf->conf_resigndb != NULL
#ifdef USE_LUA
	    || conf->conf_setupscript != NULL
	    || conf->conf_screenscript != NULL
	    || conf->conf_finalscript != NULL
#endif /* USE_LUA */
	   )
	{
		strlcpy(addr, envrcpt[0], sizeof addr);
		dkimf_stripbrackets(addr);
	}

	if (conf->conf_dontsigntodb != NULL
	    || conf->conf_bldb != NULL
	    || conf->conf_redirect != NULL
	    || conf->conf_resigndb != NULL
#ifdef USE_LUA
	    || conf->conf_setupscript != NULL
	    || conf->conf_screenscript != NULL
	    || conf->conf_finalscript != NULL
#endif /* USE_LUA */
	   )
	{
		struct addrlist *a;

		copy = strdup(addr);
		if (copy == NULL)
		{
			if (conf->conf_dolog)
			{
				syslog(LOG_ERR,
				       "message requeueing (internal error)");
			}

			free(copy);
			dkimf_cleanup(ctx);
			return SMFIS_TEMPFAIL;
		}

		a = (struct addrlist *) malloc(sizeof(struct addrlist));
		if (a == NULL)
		{
			if (conf->conf_dolog)
			{
				syslog(LOG_ERR,
				       "message requeueing (internal error)");
			}

			free(copy);
			dkimf_cleanup(ctx);
			return SMFIS_TEMPFAIL;
		}

		a->a_next = dfc->mctx_rcptlist;
		a->a_addr = copy;

		dfc->mctx_rcptlist = a;
	}

	return SMFIS_CONTINUE;
}

/*
**  MLFI_HEADER -- handler for mail headers; stores the header in a vector
**                 of headers for later perusal, removing RFC822 comment
**                 substrings
**
**  Parameters:
**  	ctx -- milter context
**  	headerf -- header
**  	headerv -- value
**
**  Return value:
**  	An SMFIS_* constant.
*/

sfsistat
mlfi_header(SMFICTX *ctx, char *headerf, char *headerv)
{
	msgctx dfc;
	connctx cc;
	Header newhdr;
	struct dkimf_config *conf;

	assert(ctx != NULL);
	assert(headerf != NULL);
	assert(headerv != NULL);

	cc = (connctx) dkimf_getpriv(ctx);
	assert(cc != NULL);
	dfc = cc->cctx_msg;
	assert(dfc != NULL);
	conf = cc->cctx_config;

	/* check for too much header data */
	if (conf->conf_maxhdrsz > 0 &&
	    dfc->mctx_hdrbytes + strlen(headerf) + strlen(headerv) + 2 > conf->conf_maxhdrsz)
	{
		if (conf->conf_dolog)
			syslog(LOG_NOTICE,
			       "%s: too much header data (header '%s' would exceed limit of %u bytes)",
			       dfc->mctx_jobid, headerf, conf->conf_maxhdrsz);

		(void) dkimf_setreply(ctx, "552", "5.3.4",
		                      "header size exceeds maximum");

		return dkimf_miltercode(ctx,
		                        conf->conf_handling.hndl_security,
		                        NULL);
	}

	/*
	**  Completely ignore a field name containing a semicolon; this is
	**  strangely legal by RFC5322, but completely incompatible with DKIM.
	*/

	if (strchr(headerf, ';') != NULL)
	{
		if (conf->conf_dolog)
		{
			syslog(LOG_NOTICE, "ignoring header field '%s'",
			       headerf);
		}

		return SMFIS_CONTINUE;
	}

	newhdr = (Header) malloc(sizeof(struct Header));
	if (newhdr == NULL)
	{
		if (conf->conf_dolog)
			syslog(LOG_ERR, "malloc(): %s", strerror(errno));

		dkimf_cleanup(ctx);
		return SMFIS_TEMPFAIL;
	}

	(void) memset(newhdr, '\0', sizeof(struct Header));

	newhdr->hdr_hdr = strdup(headerf);

	if (dfc->mctx_tmpstr == NULL)
	{
		dfc->mctx_tmpstr = dkimf_dstring_new(BUFRSZ, 0);
		if (dfc->mctx_tmpstr == NULL)
		{
			if (conf->conf_dolog)
				syslog(LOG_ERR, "dkimf_dstring_new() failed");

			TRYFREE(newhdr->hdr_hdr);
			free(newhdr);

			dkimf_cleanup(ctx);

			return SMFIS_TEMPFAIL;
		}
	}
	else
	{
		dkimf_dstring_blank(dfc->mctx_tmpstr);
	}

	if (!cc->cctx_noleadspc)
	{
		/*
		**  The sendmail MTA does some minor header rewriting on
		**  outgoing mail.  This makes things slightly prettier for
		**  the MUA, but these changes are made after this filter has
		**  already generated and added a signature.  As a result,
		**  verification of the signature will fail because what got
		**  signed isn't the same as what actually goes out.  This
		**  chunk of code attempts to compensate by arranging to
		**  feed to the canonicalization algorithms the headers
		**  exactly as the MTA will modify them, so verification
		**  should still work.
		**  
		**  This is based on experimentation and on reading
		**  sendmail/headers.c, and may require more tweaking before
		**  it's precisely right.  There are other munges the
		**  sendmail MTA makes which are not (yet) addressed by this
		**  code.
		**
		**  This should not be used with sendmail 8.14 and later as
		**  it is not required; that version of sendmail and
		**  libmilter handles the munging correctly (by suppressing
		**  it).
		*/

		char *p;

		p = headerv;
		while (isascii(*p) && isspace(*p))
			p++;

		dkimf_dstring_copy(dfc->mctx_tmpstr, (u_char *) p);
	}
	else
	{
		dkimf_dstring_copy(dfc->mctx_tmpstr, (u_char *) headerv);
	}


	newhdr->hdr_val = strdup((char *) dkimf_dstring_get(dfc->mctx_tmpstr));

	newhdr->hdr_next = NULL;
	newhdr->hdr_prev = dfc->mctx_hqtail;

	if (newhdr->hdr_hdr == NULL || newhdr->hdr_val == NULL)
	{
		if (conf->conf_dolog)
			syslog(LOG_ERR, "malloc(): %s", strerror(errno));

		TRYFREE(newhdr->hdr_hdr);
		TRYFREE(newhdr->hdr_val);
		TRYFREE(newhdr);
		dkimf_cleanup(ctx);
		return SMFIS_TEMPFAIL;
	}

	dfc->mctx_hdrbytes += strlen(newhdr->hdr_hdr) + 1;
	dfc->mctx_hdrbytes += strlen(newhdr->hdr_val) + 1;

	if (dfc->mctx_hqhead == NULL)
		dfc->mctx_hqhead = newhdr;

	if (dfc->mctx_hqtail != NULL)
		dfc->mctx_hqtail->hdr_next = newhdr;

	dfc->mctx_hqtail = newhdr;

	if (strcasecmp(headerf, conf->conf_selectcanonhdr) == 0)
	{
		int c;
		char *slash;

		slash = strchr(headerv, '/');
		if (slash != NULL)
		{
			*slash = '\0';

			c = dkimf_lookup_strtoint(headerv, dkimf_canon);
			if (c != -1)
				dfc->mctx_hdrcanon = (dkim_canon_t) c;
			c = dkimf_lookup_strtoint(slash + 1, dkimf_canon);
			if (c != -1)
				dfc->mctx_bodycanon = (dkim_canon_t) c;

			*slash = '/';
		}
		else
		{
			c = dkimf_lookup_strtoint(headerv, dkimf_canon);
			if (c != -1)
				dfc->mctx_hdrcanon = (dkim_canon_t) c;
		}

		/* XXX -- eat this header? */
	}

	return SMFIS_CONTINUE;
}

/*
**  MLFI_EOH -- handler called when there are no more headers
**
**  Parameters:
**  	ctx -- milter context
**
**  Return value:
**  	An SMFIS_* constant.
*/

sfsistat
mlfi_eoh(SMFICTX *ctx)
{
	char last;
	_Bool setidentity = FALSE;
	_Bool domainok;
	_Bool originok;
	_Bool didfrom = FALSE;
	_Bool msgsigned = FALSE;
	int c;
	DKIM_STAT status;
	sfsistat ms = SMFIS_CONTINUE;
	connctx cc;
	msgctx dfc;
	DKIM *lastdkim;
	char *p;
	char *macrosender = NULL;
	u_char *user;
	u_char *domain;
	struct dkimf_config *conf;
	struct dkimf_dstring *addr;
	Header from = NULL;
	Header hdr;

	assert(ctx != NULL);

	cc = (connctx) dkimf_getpriv(ctx);
	assert(cc != NULL);
	dfc = cc->cctx_msg;
	assert(dfc != NULL);
	conf = cc->cctx_config;

	/*
	**  Determine the message ID for logging.
	*/

	dfc->mctx_jobid = (const u_char *) dkimf_getsymval(ctx, "i");
	if (dfc->mctx_jobid == NULL || dfc->mctx_jobid[0] == '\0')
		dfc->mctx_jobid = (const u_char *) JOBIDUNKNOWN;

	/* find the Sender: or From: header */
	addr = dkimf_dstring_new(BUFRSZ, 0);

	if (conf->conf_sendermacro != NULL)
	{
		macrosender = dkimf_getsymval(ctx, conf->conf_sendermacro);
		if (macrosender != NULL)
			dkimf_dstring_copy(addr, (u_char *) macrosender);
	}

  	if (dkimf_dstring_len(addr) == 0)
	{
		for (c = 0; conf->conf_senderhdrs != NULL &&
                            conf->conf_senderhdrs[c] != NULL; c++)
		{
			if (strcasecmp("from", conf->conf_senderhdrs[c]) == 0)
				didfrom = TRUE;

			from = dkimf_findheader(dfc, conf->conf_senderhdrs[c],
			                        0);
			if (from != NULL)
				break;
		}

		if (from == NULL && !didfrom)
			from = dkimf_findheader(dfc, "from", 0);
	}
  
  	if (from != NULL)
		dkimf_dstring_copy(addr, (u_char *) from->hdr_val);

	if (dkimf_dstring_len(addr) == 0)
	{
		if (conf->conf_dolog)
		{
			syslog(LOG_INFO,
			       "%s: can't determine message sender; accepting",
			       dfc->mctx_jobid);
		}

		if ((conf->conf_mode & DKIMF_MODE_VERIFIER) != 0)
		{
			dfc->mctx_addheader = TRUE;
			dfc->mctx_headeronly = TRUE;
			dfc->mctx_status = DKIMF_STATUS_BADFORMAT;
		}
		dkimf_dstring_free(addr);
		return SMFIS_CONTINUE;
	}

	status = dkim_mail_parse(dkimf_dstring_get(addr), &user, &domain);


	if ((conf->conf_mode & DKIMF_MODE_SIGNER) != 0 &&
	    (status != 0 || user == NULL || domain == NULL ||
	     user[0] == '\0' || domain[0] == '\0'))
	{
		if (conf->conf_dolog)
		{
			if (macrosender != NULL)
			{
				syslog(LOG_INFO,
				       "%s: can't parse macro %s header value '%s'",
				       dfc->mctx_jobid, conf->conf_sendermacro,
				       macrosender);
			}
			else
			if (from != NULL)
			{
				syslog(LOG_INFO,
				       "%s: can't parse %s: header value '%s'",
				       dfc->mctx_jobid, from->hdr_hdr,
				       from->hdr_val);
			}
		}

		if ((conf->conf_mode & DKIMF_MODE_VERIFIER) != 0)
		{
			dfc->mctx_addheader = TRUE;
			dfc->mctx_headeronly = TRUE;
			dfc->mctx_status = DKIMF_STATUS_BADFORMAT;
		}
		dkimf_dstring_free(addr);
		return SMFIS_CONTINUE;
	}

	if (domain != NULL)
	{
		strlcpy((char *) dfc->mctx_domain, (char *) domain,
		        sizeof dfc->mctx_domain);
		dkimf_lowercase(dfc->mctx_domain);
	}

	/* if it's exempt, bail out */
	if (conf->conf_exemptdb != NULL && dfc->mctx_domain[0] != '\0')
	{
		_Bool match = FALSE;

		status = dkimf_db_get(conf->conf_exemptdb,
		                      dfc->mctx_domain, 0, NULL, 0,
		                      &match);
		if (status != 0)
		{
			if (dolog)
			{
				dkimf_db_error(conf->conf_exemptdb,
				               (char *) dfc->mctx_domain);
			}

			dkimf_dstring_free(addr);
			return SMFIS_TEMPFAIL;
		}

		if (match)
		{
			if (conf->conf_logwhy)
			{
				syslog(LOG_INFO,
				       "%s: domain '%s' exempted, accepting",
				       dfc->mctx_jobid, dfc->mctx_domain);
			}

			dkimf_cleanup(ctx);
			dkimf_dstring_free(addr);
			return SMFIS_ACCEPT;
		}
	}

	/* apply BodyLengthDB if signing */
	if (conf->conf_bldb != NULL && !dfc->mctx_bldbdone)
	{
		struct addrlist *a;

		for (a = dfc->mctx_rcptlist; a != NULL; a = a->a_next)
		{
	    		if (dkimf_checkbldb(conf->conf_bldb, a->a_addr,
			                    (const char *) dfc->mctx_jobid))
			{
				dfc->mctx_ltag = TRUE;
				dfc->mctx_laddr = (u_char *) a->a_addr;
				break;
			}
		}

		dfc->mctx_bldbdone = TRUE;
	}

	/* assume we're not signing */
	dfc->mctx_signalg = DKIM_SIGN_UNKNOWN;
	domainok = FALSE;
	originok = FALSE;

	msgsigned = (dkimf_findheader(dfc, DKIM_SIGNHEADER, 0) != NULL);

	/* check to see if it's a destination for which we resign */
	if (conf->conf_resigndb != NULL)
	{
		bool match = FALSE;
		char *at;
		char *dot;
		struct addrlist *a;
		char resignkey[BUFRSZ + 1];
		struct dkimf_db_data dbd;

		memset(resignkey, '\0', sizeof resignkey);

		dbd.dbdata_buffer = resignkey;
		dbd.dbdata_buflen = sizeof resignkey;
		dbd.dbdata_flags = 0;

		for (a = dfc->mctx_rcptlist; a != NULL; a = a->a_next)
		{
			/* full recipient address */
			if (dkimf_db_get(conf->conf_resigndb, a->a_addr, 0,
			                 &dbd, 1, &match) != 0)
			{
				if (dolog)
				{
					dkimf_db_error(conf->conf_resigndb,
					               a->a_addr);
				}
				continue;
			}

			if (match)
			{
				domainok = TRUE;
				originok = TRUE;
				dfc->mctx_resign = TRUE;
				break;
			}

			/* hostname only */
			at = strchr(a->a_addr, '@');
			if (at == NULL)
				continue;

			status = dkimf_db_get(conf->conf_resigndb,
			                      at + 1, 0, &dbd, 1,
			                      &match);

			if (status != 0)
			{
				if (dolog)
				{
					dkimf_db_error(conf->conf_resigndb,
					               at + 1);
				}
				continue;
			}

			if (match)
			{
				domainok = TRUE;
				originok = TRUE;
				dfc->mctx_resign = TRUE;
				break;
			}

			/* iterate through ".domain" possibilities */
			for (dot = strchr(at, '.');
			     dot != NULL;
			     dot = strchr(dot + 1, '.'))
			{
				status = dkimf_db_get(conf->conf_resigndb,
				                      dot, 0, &dbd, 1,
				                      &match);
				if (status != 0)
				{
					if (dolog)
					{
						dkimf_db_error(conf->conf_resigndb,
					                       dot);
					}

					continue;
				}

				if (match)
					break;
			}

			if (match)
			{
				domainok = TRUE;
				originok = TRUE;
				dfc->mctx_resign = TRUE;
				break;
			}
		}

		if (match)
		{
			if (conf->conf_keytabledb == NULL ||
			    resignkey[0] == '\0')
			{
				status = dkimf_add_signrequest(conf, dfc, NULL,
				                               NULL, NULL,
				                               (ssize_t) -1);

				if (status != 0)
				{
					if (dolog)
					{
						syslog(LOG_ERR,
						       "%s: failed to add signature for default key",
						       dfc->mctx_jobid);
					}

					dkimf_dstring_free(addr);
					return SMFIS_TEMPFAIL;
				}
			}
			else
			{
				status = dkimf_add_signrequest(conf, dfc,
				                               conf->conf_keytabledb,
				                               resignkey,
				                               NULL,
				                               (ssize_t) -1);

				if (status != 0)
				{
					if (dolog)
					{
						syslog(LOG_ERR,
						       "%s: failed to add signature for key '%s'",
						       dfc->mctx_jobid,
						       resignkey);
					}

					dkimf_dstring_free(addr);
					return SMFIS_TEMPFAIL;
				}
			}
		}
	}

	/* see if it came in on an authorized MSA/MTA connection */
	if (conf->conf_mtasdb != NULL)
	{
		char *mtaname;
		char *host;

		mtaname = dkimf_getsymval(ctx, "{daemon_name}");
		host = dkimf_getsymval(ctx, "j");
		status = 0;

		if (mtaname != NULL)
		{
			status = dkimf_db_get(conf->conf_mtasdb, mtaname, 0,
			                      NULL, 0, &originok);
			if (status != 0 && dolog)
				dkimf_db_error(conf->conf_mtasdb, mtaname);
		}

		if (!originok && status == 0 && conf->conf_logwhy)
		{
			syslog(LOG_INFO,
			       "%s: no MTA name match (host=%s, MTA=%s)",
			       dfc->mctx_jobid, host,
			       mtaname == NULL ? "?" : mtaname);
		}
	}

	/* see if macro tests passed */
	if (conf->conf_macrosdb != NULL)
	{
		_Bool done = FALSE;
		int n;
		char *val;
		char name[BUFRSZ + 1];
		struct dkimf_db_data dbd;

		if (dfc->mctx_tmpstr == NULL)
		{
			dfc->mctx_tmpstr = dkimf_dstring_new(BUFRSZ, 0);
			if (dfc->mctx_tmpstr == NULL)
			{
				if (conf->conf_dolog)
				{
					syslog(LOG_ERR,
					       "%s: dkimf_dstring_new() failed",
					       dfc->mctx_jobid);
				}

				dkimf_cleanup(ctx);
				dkimf_dstring_free(addr);
				return SMFIS_TEMPFAIL;
			}
		}

		for (n = 0; !done && conf->conf_macros[n] != NULL; n++)
		{
			/* retrieve the macro */
			snprintf(name, sizeof name, "{%s}",
			         conf->conf_macros[n]);
			val = dkimf_getsymval(ctx, name);

			/* short-circuit if the macro's not set */
			if (val == NULL)
				continue;

			memset(&dbd, '\0', sizeof dbd);
			dbd.dbdata_buffer = val;
			dbd.dbdata_buflen = strlen(val) + 1;
			dbd.dbdata_flags = 0;

			status = dkimf_db_get(conf->conf_macrosdb,
			                      conf->conf_macros[n], 0,
			                      &dbd, 1, &originok);
			if (status != 0 && dolog)
				dkimf_db_error(conf->conf_macrosdb, name);
		}

		if (!originok && conf->conf_logwhy)
		{
			syslog(LOG_INFO, "%s: no macros match",
			       dfc->mctx_jobid);
		}
	}

	/* see if it came from an internal or authenticated source */
	if (!originok)
	{
		_Bool internal;

		char *authtype;

		internal = dkimf_checkhost(conf->conf_internal, cc->cctx_host);
		internal = internal || dkimf_checkip(conf->conf_internal,
		                                     (struct sockaddr *) &cc->cctx_ip);

		authtype = dkimf_getsymval(ctx, "{auth_authen}");
        if (authtype == NULL || authtype[0] == '\0') 
            authtype = dkimf_getsymval(ctx, "{auth_type}"); // Fallback

		if ((authtype != NULL && authtype[0] != '\0') || internal)
			originok = TRUE;

		if (!originok && conf->conf_logwhy)
		{
			if (!internal)
			{
				char ipbuf[BUFRSZ];

				dkimf_ipstring(ipbuf, sizeof ipbuf,
				               &cc->cctx_ip);
				syslog(LOG_INFO, "%s: %s [%s] not internal",
				       dfc->mctx_jobid, cc->cctx_host,
				       ipbuf);
			}

			if (authtype == NULL || authtype[0] == '\0')
			{
				syslog(LOG_INFO, "%s: not authenticated",
				       dfc->mctx_jobid);
			}
		}
	}

	/* is it a domain we sign for? */
	if (!domainok && conf->conf_domainsdb != NULL)
	{
		status = dkimf_db_get(conf->conf_domainsdb, dfc->mctx_domain,
		                      0, NULL, 0, &domainok);

		if (!domainok)
		{
			/* check for "*" for back-compatibility */
			status = dkimf_db_get(conf->conf_domainsdb, "*",
			                      0, NULL, 0, &domainok);
			if (status != 0 && dolog)
				dkimf_db_error(conf->conf_domainsdb, "*");
		}

		if (!domainok && conf->conf_logwhy)
		{
			syslog(LOG_INFO,
			       "%s: no signing domain match for '%s'",
			       dfc->mctx_jobid, dfc->mctx_domain);
		}

		if (conf->conf_subdomains && !domainok)
		{
			for (p = strchr((char *) dfc->mctx_domain, '.');
			     p != NULL && !domainok;
			     p = strchr(p, '.'))
			{
				p++;
				if (*p == '\0')
					break;

				status = dkimf_db_get(conf->conf_domainsdb, p,
				                      0, NULL, 0,
				                      &domainok);
				if (status != 0)
				{
					if (dolog)
					{
						dkimf_db_error(conf->conf_domainsdb,
						               p);
					}

					continue;
				}

				if (domainok)
				{
					/* p points into mctx_domain; use memmove */
					memmove(dfc->mctx_domain, p,
					        strlen(p) + 1);
					break;
				}
			}

			if (domainok)
				setidentity = TRUE;
		}

		if (!domainok && conf->conf_logwhy)
		{
			syslog(LOG_INFO,
			       "%s: no signing subdomain match for '%s'",
			       dfc->mctx_jobid, dfc->mctx_domain);
		}
	}

	/* warn if the domain was OK but didn't come from a safe source */
	if (domainok && !originok)
	{
		if (conf->conf_dolog &&
		    !dkimf_checkhost(conf->conf_exignore, cc->cctx_host) &&
		    !dkimf_checkip(conf->conf_exignore,
		                   (struct sockaddr *) &cc->cctx_ip))
		{
			syslog(LOG_NOTICE,
			       "%s: external host %s attempted to send as %s",
			       dfc->mctx_jobid, cc->cctx_host,
			       dfc->mctx_domain);
		}
	}

	/* still no key selected; check the signing table (if any) */
	if (originok && dfc->mctx_srhead == NULL &&
	    (user != NULL && dfc->mctx_domain[0] != '\0') && 
	    conf->conf_keytabledb != NULL && conf->conf_signtabledb != NULL)
	{
		int found;
		char errkey[BUFRSZ + 1];

		memset(errkey, '\0', sizeof errkey);
		found = dkimf_apply_signtable(conf, dfc, conf->conf_keytabledb,
		                              conf->conf_signtabledb,
		                              user, dfc->mctx_domain,
		                              errkey, sizeof errkey,
		                              conf->conf_multisig);

		if (found < 0)
		{
			if (conf->conf_dolog)
			{
				switch (found)
				{
				  case -1:
					syslog(LOG_ERR,
					       "%s: error reading signing table",
					       dfc->mctx_jobid);
					break;

				  case -2:
					syslog(LOG_ERR,
					       "%s: signing table references unknown key '%s'",
					       dfc->mctx_jobid, errkey);
					break;

				  case -3:
					syslog(LOG_ERR,
					       "%s: error loading key '%s'",
					       dfc->mctx_jobid, errkey);
					break;

				  default:
					assert(0);
				}
			}

			dkimf_dstring_free(addr);
			return SMFIS_TEMPFAIL;
		}
		else if (found > 0)
		{
			domainok = TRUE;
		}

		if (!domainok && conf->conf_logwhy)
		{
			syslog(LOG_INFO,
			       "%s: no signing table match for '%s@%s'",
			       dfc->mctx_jobid, user, dfc->mctx_domain);
		}
	}

	/* don't need the sender field anymore */
	dkimf_dstring_free(addr);

	/* set signing mode if the tests passed */
	if (domainok && originok)
	{
		dfc->mctx_signalg = conf->conf_signalg;
		dfc->mctx_addheader = TRUE;
	}

	/* remember internal state */
	dfc->mctx_internal = originok;

#ifdef USE_LUA
	/* invoke the setup script if defined */
	if (conf->conf_setupscript != NULL)
	{
		_Bool dofree = TRUE;
		struct dkimf_lua_script_result lres;

		memset(&lres, '\0', sizeof lres);

		dfc->mctx_mresult = SMFIS_CONTINUE;

		status = dkimf_lua_setup_hook(ctx, conf->conf_setupfunc,
		                              conf->conf_setupfuncsz,
		                              "setup script", &lres,
		                              NULL, NULL);

		if (status != 0)
		{
			if (conf->conf_dolog)
			{
				if (lres.lrs_error == NULL)
				{
					dofree = FALSE;

					switch (status)
					{
					  case 2:
						lres.lrs_error = "processing error";
						break;

					  case 1:
						lres.lrs_error = "syntax error";
						break;

					  case -1:
						lres.lrs_error = "memory allocation error";
						break;

					  default:
						lres.lrs_error = "unknown error";
						break;
					}
				}

				syslog(LOG_ERR,
				       "%s: dkimf_lua_setup_hook() failed: %s",
				       dfc->mctx_jobid, lres.lrs_error);
			}

			if (dofree)
				free((void *)(uintptr_t) lres.lrs_error);

			return SMFIS_TEMPFAIL;
		}

		if (dfc->mctx_mresult != SMFIS_CONTINUE)
			return dfc->mctx_mresult;
	}
#endif /* USE_LUA */

	/* create a default signing request if there was a domain match */
	if (domainok && originok && dfc->mctx_srhead == NULL)
	{
		status = dkimf_add_signrequest(conf, dfc, NULL, NULL, NULL,
		                               (ssize_t) -1);

		if (status != 0)
		{
			if (dolog)
			{
				syslog(LOG_ERR,
				       "%s: failed to add default signing request",
				       dfc->mctx_jobid);
			}

			return SMFIS_TEMPFAIL;
		}
	}

	/*
	**  If we're not operating in the role matching the required operation,
	**  just accept the message and be done with it.
	*/

	/* signing requests with signing mode disabled */
	if (dfc->mctx_srhead != NULL && 
	    (conf->conf_mode & DKIMF_MODE_SIGNER) == 0)
		return SMFIS_ACCEPT;

	/* verify request with verify mode disabled */
	if ((dfc->mctx_srhead == NULL || dfc->mctx_resign) &&
	    (conf->conf_mode & DKIMF_MODE_VERIFIER) == 0)
		return SMFIS_ACCEPT;

	/* check for "DontSignMailTo" */
	if (dfc->mctx_srhead != NULL && conf->conf_dontsigntodb != NULL)
	{
		_Bool found;
		struct addrlist *a;

		a = dfc->mctx_rcptlist;

		while (a != NULL)
		{
			found = FALSE;
			status = dkimf_db_get(conf->conf_dontsigntodb,
			                      a->a_addr, 0, NULL, 0,
			                      &found);
			if (found)
			{
				if (conf->conf_dolog)
				{
					syslog(LOG_INFO,
					       "%s: skipping signing of mail to '%s'",
					       dfc->mctx_jobid,
					       a->a_addr);
				}

				return SMFIS_ACCEPT;
			}
			else if (status != 0)
			{
				if (conf->conf_dolog)
				{
					syslog(LOG_ERR,
					       "%s: dkimf_db_get() failed",
					       dfc->mctx_jobid);
				}

				return SMFIS_TEMPFAIL;
			}

			a = a->a_next;
		}
	}

	/* if we're not signing, or we are resigning, grab a verify handle */
	if (dfc->mctx_srhead == NULL || dfc->mctx_resign)
	{
		dfc->mctx_dkimv = dkim_verify(conf->conf_libopendkim,
		                              dfc->mctx_jobid, NULL,
		                              &status);

		if (dfc->mctx_dkimv == NULL && status != DKIM_STAT_OK)
		{
			return dkimf_libstatus(ctx, NULL, "dkim_verify()",
			                       status);
		}
	}

	if (!msgsigned)
	{
		/*
		**  If the message was unsigned, we're just signing and not
		**  resigning.
		*/

		dfc->mctx_resign = FALSE;
	}

	/* create all required signing handles */
	if (dfc->mctx_srhead != NULL)
	{
		ssize_t signlen;
		u_char *sdomain;
		u_char *selector;
		struct signreq *sr;
		dkim_sigkey_t keydata;

		if (conf->conf_dolog && dfc->mctx_laddr != NULL)
		{
			syslog(LOG_INFO,
				"%s: BodyLengthDB matched %s, signing with l= requested",
				dfc->mctx_jobid, dfc->mctx_laddr);
		}

		for (sr = dfc->mctx_srhead; sr != NULL; sr = sr->srq_next)
		{
			if (sr->srq_signlen == (ssize_t) -1)
				signlen = conf->conf_signbytes;
			else
				signlen = sr->srq_signlen;

			if (sr->srq_keydata != NULL)
			{
				keydata = sr->srq_keydata;
				selector = sr->srq_selector;
				if (sr->srq_domain != NULL)
					sdomain = sr->srq_domain;
				else
					sdomain = dfc->mctx_domain;
			}
			else
			{
				sdomain = dfc->mctx_domain;
				keydata = (dkim_sigkey_t) conf->conf_seckey;
				selector = conf->conf_selector;
			}

			sr->srq_dkim = dkim_sign(conf->conf_libopendkim,
			                         dfc->mctx_jobid,
			                         NULL, keydata, selector,
			                         sdomain,
			                         dfc->mctx_hdrcanon,
			                         dfc->mctx_bodycanon,
			                         dfc->mctx_signalg,
			                         signlen, &status);

			if (sr->srq_dkim == NULL || status != DKIM_STAT_OK)
			{
				return dkimf_libstatus(ctx, NULL,
				                       "dkim_sign()",
				                       status);
			}

			if (conf->conf_reqreports)
			{
				status = dkim_add_xtag(sr->srq_dkim,
				                       DKIM_REPORTTAG,
				                       DKIM_REPORTTAGVAL);

				if (status != DKIM_STAT_OK && dolog)
				{
					syslog(LOG_ERR,
					       "%s dkim_add_xtag() for \"%s\" failed",
					       dfc->mctx_jobid,
					       DKIM_REPORTTAG);
				}
			}

			(void) dkim_set_user_context(sr->srq_dkim, ctx);

			if (sr->srq_signer != NULL)
			{
				(void) dkim_set_signer(sr->srq_dkim,
				                       sr->srq_signer);
			}

			if (dfc->mctx_resign && dfc->mctx_dkimv != NULL)
			{
				status = dkim_resign(sr->srq_dkim,
				                     dfc->mctx_dkimv,
				                     FALSE);
				if (status != DKIM_STAT_OK)
				{
					return dkimf_libstatus(ctx, NULL,
					                       "dkim_resign()",
					                       status);
				}
			}
		}
	}

	/* if requested, verify RFC5322-required headers (RFC5322 3.6) */
	if (conf->conf_reqhdrs)
	{
		const char *msg = NULL;

		/* exactly one From: */
		if (dkimf_findheader(dfc, "From", 0) == NULL)
			msg = "message has no From field";

		if (dkimf_findheader(dfc, "From", 1) != NULL)
			msg = "message has multiple From fields";

		/* exactly one Date: */
		if (dkimf_findheader(dfc, "Date", 0) == NULL)
			msg = "message has no Date field";

		if (dkimf_findheader(dfc, "Date", 1) != NULL)
			msg = "message has multiple Date fields";

		/* no more than one Reply-To: */
		if (dkimf_findheader(dfc, "Reply-To", 1) != NULL)
			msg = "message has multiple Reply-To fields";

		/* no more than one To: */
		if (dkimf_findheader(dfc, "To", 1) != NULL)
			msg = "message has multiple To fields";

		/* no more than one Cc: */
		if (dkimf_findheader(dfc, "Cc", 1) != NULL)
			msg = "message has multiple Cc fields";

		/* no more than one Bcc: */
		if (dkimf_findheader(dfc, "Bcc", 1) != NULL)
			msg = "message has multiple Bcc fields";

		/* no more than one Message-Id: */
		if (dkimf_findheader(dfc, "Message-Id", 1) != NULL)
			msg = "message has multiple Message-Id fields";

		/* no more than one In-Reply-To: */
		if (dkimf_findheader(dfc, "In-Reply-To", 1) != NULL)
			msg = "message has multiple In-Reply-To fields";

		/* no more than one References: */
		if (dkimf_findheader(dfc, "References", 1) != NULL)
			msg = "message has multiple References fields";

		/* no more than one Subject: */
		if (dkimf_findheader(dfc, "Subject", 1) != NULL)
			msg = "message has multiple Subject fields";

		if (msg != NULL)
		{
			if (conf->conf_dolog)
			{
				syslog(LOG_INFO,
				       "%s: RFC5322 header requirement error: %s",
				       dfc->mctx_jobid, msg);
			}

			if (dkimf_setreply(ctx, "550", "5.0.0",
			                   msg) != MI_SUCCESS &&
			    conf->conf_dolog)
			{
				syslog(LOG_NOTICE,
				       "%s: smfi_setreply() failed",
				       dfc->mctx_jobid);
			}
			dkimf_cleanup(ctx);
			return SMFIS_REJECT;
		}
	}

	if (conf->conf_identityhdr != NULL)
		setidentity = TRUE;

	if (dfc->mctx_srhead != NULL && setidentity)
	{
		u_char identity[MAXADDRESS + 1];
		_Bool idset = FALSE;

		if (conf->conf_identityhdr != NULL)
		{
			u_char *iuser = NULL;
			u_char *idomain = NULL;

			hdr = dkimf_findheader(dfc, conf->conf_identityhdr, 0);
			if (hdr != NULL)
			{
				status = dkim_mail_parse((u_char *) hdr->hdr_val,
				                         &iuser, &idomain);
				if (status == 0 && idomain != NULL)
				{
					snprintf((char *) identity,
					         sizeof identity,
						 "%s@%s",
						 iuser == NULL ? ""
					                       : (char *) iuser,
						 idomain);
					idset = TRUE;
				}
			}

			if (!idset && conf->conf_dolog)
			{
				syslog(LOG_INFO,
				       "%s: cannot find identity header %s",
				       dfc->mctx_jobid,
				       conf->conf_identityhdr);
			}
		}

		if (!idset)
		{
			int n;

			n = snprintf((char *) identity, sizeof identity, "@%s",
							dfc->mctx_domain);

			if (n < 0 || (size_t)n >= sizeof identity)
			{
				if (dolog)
					syslog(LOG_ERR, "identity truncated");

				return SMFIS_TEMPFAIL;
			}
		}

		if (dfc->mctx_srhead != NULL)
		{
			struct signreq *sr;

			for (sr = dfc->mctx_srhead;
			     sr != NULL;
			     sr = sr->srq_next)
			{
				if (dkim_get_signer(sr->srq_dkim) == NULL)
				{
					dkim_set_signer(sr->srq_dkim,
					                identity);
				}
			}
		}
	}

	if (dfc->mctx_ltag && dfc->mctx_srhead != NULL)
	{
		struct signreq *sr;

		for (sr = dfc->mctx_srhead;
		     sr != NULL;
		     sr = sr->srq_next)
			dkim_setpartial(sr->srq_dkim, TRUE);
	}


	/* run the headers */
	for (hdr = dfc->mctx_hqhead; hdr != NULL; hdr = hdr->hdr_next)
	{
		if (dfc->mctx_tmpstr == NULL)
		{
			dfc->mctx_tmpstr = dkimf_dstring_new(BUFRSZ, 0);
			if (dfc->mctx_tmpstr == NULL)
			{
				if (conf->conf_dolog)
				{
					syslog(LOG_ERR,
					       "%s: dkimf_dstring_new() failed",
					       dfc->mctx_jobid);
				}

				return SMFIS_TEMPFAIL;
			}
		}
		else
		{
			dkimf_dstring_blank(dfc->mctx_tmpstr);
		}

		/*
		**  Skip headers we know we're going to delete before
		**  signing here (e.g. identity header when set to remove).
		*/

		/*
		**  XXX -- may need to skip some/all Authentication-Results
		**  header fields here, especially in the re-signing case
		*/

		if (conf->conf_identityhdr != NULL &&
		    conf->conf_rmidentityhdr &&
		    dfc->mctx_srhead != NULL &&
		    strcasecmp(conf->conf_identityhdr, hdr->hdr_hdr) == 0)
			continue;

		dkimf_dstring_copy(dfc->mctx_tmpstr, (u_char *) hdr->hdr_hdr);
		dkimf_dstring_cat1(dfc->mctx_tmpstr, ':');
		if (!cc->cctx_noleadspc)
			dkimf_dstring_cat1(dfc->mctx_tmpstr, ' ');

		last = '\0';

		/* do milter-ized continuation conversion */
		for (p = hdr->hdr_val; *p != '\0'; p++)
		{
			if (*p == '\n' && last != '\r')
				dkimf_dstring_cat1(dfc->mctx_tmpstr, '\r');

			dkimf_dstring_cat1(dfc->mctx_tmpstr, *p);

			last = *p;
		}

		if (dfc->mctx_srhead != NULL)
		{
			DKIM *dkim;

			status = dkimf_msr_header(dfc->mctx_srhead, &dkim,
				                  dkimf_dstring_get(dfc->mctx_tmpstr),
				                  (size_t) dkimf_dstring_len(dfc->mctx_tmpstr));
			if (status != DKIM_STAT_OK)
			{
				ms = dkimf_libstatus(ctx, dkim,
				                     "dkim_header()", status);
				break;
			}
		}

		if (dfc->mctx_dkimv != NULL)
		{
			status = dkim_header(dfc->mctx_dkimv,
			                     (u_char *) dkimf_dstring_get(dfc->mctx_tmpstr),
			                     (size_t) dkimf_dstring_len(dfc->mctx_tmpstr));

			if (status != DKIM_STAT_OK)
			{
				ms = dkimf_libstatus(ctx, dfc->mctx_dkimv,
				                     "dkim_header()", status);
			}
		}
	}

	/* return any error status from earlier */
	if (ms != SMFIS_CONTINUE)
		return ms;

	/* signal end of headers to libopendkim */
	lastdkim = NULL;
	status = DKIM_STAT_OK;
	if (dfc->mctx_srhead != NULL && !dfc->mctx_resign)
		status = dkimf_msr_eoh(dfc->mctx_srhead, &lastdkim);
	if (status == DKIM_STAT_OK && dfc->mctx_dkimv != NULL)
	{
		(void) dkim_set_user_context(dfc->mctx_dkimv, ctx);
		lastdkim = dfc->mctx_dkimv;
		status = dkim_eoh(dfc->mctx_dkimv);
	}

#ifdef USE_LUA
	if (conf->conf_screenscript != NULL)
	{
		int hkstat;
		_Bool dofree = TRUE;
		struct dkimf_lua_script_result lres;

		memset(&lres, '\0', sizeof lres);

		hkstat = dkimf_lua_screen_hook(ctx, conf->conf_screenfunc,
		                               conf->conf_screenfuncsz,
		                               "screen script", &lres,
		                               NULL, NULL);

		if (hkstat != 0)
		{
			if (conf->conf_dolog)
			{
				if (lres.lrs_error == NULL)
				{
					dofree = FALSE;

					switch (hkstat)
					{
					  case 2:
						lres.lrs_error = "processing error";
						break;

					  case 1:
						lres.lrs_error = "syntax error";
						break;

					  case -1:
						lres.lrs_error = "memory allocation error";
						break;

					  default:
						lres.lrs_error = "unknown error";
						break;
					}
				}

				syslog(LOG_ERR,
				       "%s: dkimf_lua_screen_hook() failed: %s",
				       dfc->mctx_jobid, lres.lrs_error);
			}

			if (dofree)
				free((void *)(uintptr_t) lres.lrs_error);

			return SMFIS_TEMPFAIL;
		}
	}
#endif /* USE_LUA */

	switch (status)
	{
	  case DKIM_STAT_REVOKED:
		dfc->mctx_status = DKIMF_STATUS_REVOKED;
		dfc->mctx_addheader = TRUE;
		return SMFIS_CONTINUE;

	  case DKIM_STAT_BADSIG:
		dfc->mctx_status = DKIMF_STATUS_BAD;
		dfc->mctx_addheader = TRUE;
		return SMFIS_CONTINUE;

	  case DKIM_STAT_NOSIG:
		dfc->mctx_status = DKIMF_STATUS_NOSIGNATURE;
		if (conf->conf_alwaysaddar)
			dfc->mctx_addheader = TRUE;
		return SMFIS_CONTINUE;

	  case DKIM_STAT_KEYFAIL:
		dfc->mctx_status = DKIMF_STATUS_KEYFAIL;
		dfc->mctx_addheader = TRUE;
		return SMFIS_CONTINUE;

	  case DKIM_STAT_NOKEY:
		dfc->mctx_status = DKIMF_STATUS_NOKEY;
		dfc->mctx_addheader = TRUE;
		return SMFIS_CONTINUE;

	  case DKIM_STAT_SYNTAX:
		dfc->mctx_status = DKIMF_STATUS_BADFORMAT;
		dfc->mctx_addheader = TRUE;
		dfc->mctx_headeronly = TRUE;
		return SMFIS_CONTINUE;

	  /* XXX -- other codes? */

	  case DKIM_STAT_OK:
		return SMFIS_CONTINUE;

	  default:
		return dkimf_libstatus(ctx, lastdkim, "dkim_eoh()", status);
	}
}

/*
**  MLFI_BODY -- handler for an arbitrary body block
**
**  Parameters:
**  	ctx -- milter context
**  	bodyp -- body block
**  	bodylen -- amount of data available at bodyp
**
**  Return value:
**  	An SMFIS_* constant.
**
**  Description:
**  	This function reads the body chunks passed by the MTA and
**  	stores them for later wrapping, if needed.
*/

sfsistat
mlfi_body(SMFICTX *ctx, u_char *bodyp, size_t bodylen)
{
	int status;
	DKIM *last;
	msgctx dfc;
	connctx cc;

	assert(ctx != NULL);
	assert(bodyp != NULL);

	cc = (connctx) dkimf_getpriv(ctx);
	assert(cc != NULL);
	dfc = cc->cctx_msg;
	assert(dfc != NULL);

	/*
	**  No need to do anything if the body was empty.
	*/

	if (bodylen == 0)
		return SMFIS_CONTINUE;

	/*
	**  Tell the filter to skip it if we don't care about the body.
	*/

	if (dfc->mctx_headeronly)
	{
#ifdef SMFIS_SKIP
		if (cc->cctx_milterv2)
			return SMFIS_SKIP;
		else
			return SMFIS_CONTINUE;
#else /* SMFIS_SKIP */
			return SMFIS_CONTINUE;
#endif /* SMFIS_SKIP */
	}

	last = NULL;
	status = DKIM_STAT_OK;
	if (dfc->mctx_srhead != NULL &&
	    (!dfc->mctx_resign || dfc->mctx_dkimv == NULL))
	{
		status = dkimf_msr_body(dfc->mctx_srhead, &last,
		                        bodyp, bodylen);
	}
	if (status == DKIM_STAT_OK && dfc->mctx_dkimv != NULL)
	{
		last = dfc->mctx_dkimv;
		status = dkim_body(dfc->mctx_dkimv, bodyp, bodylen);
	}

	if (status != DKIM_STAT_OK)
		return dkimf_libstatus(ctx, last, "dkim_body()", status);

#ifdef SMFIS_SKIP
	if (cc->cctx_milterv2 &&
	    (dfc->mctx_srhead == NULL ||
	     dkimf_msr_minbody(dfc->mctx_srhead) == 0) &&
	    (dfc->mctx_dkimv == NULL ||
	     dkim_minbody(dfc->mctx_dkimv) == 0))
		return SMFIS_SKIP;
#endif /* SMFIS_SKIP */

	return SMFIS_CONTINUE;
}

/*
**  MLFI_EOM -- handler called at the end of the message; we can now decide
**              based on the configuration if and how to add the text
**              to this message, then release resources
**
**  Parameters:
**  	ctx -- milter context
**
**  Return value:
**  	An SMFIS_* constant.
*/

sfsistat
mlfi_eom(SMFICTX *ctx)
{
	_Bool testkey = FALSE;
	int status = DKIM_STAT_OK;
	int c;
	sfsistat ret = SMFIS_ACCEPT;
	connctx cc;
	msgctx dfc;
	DKIM *lastdkim = NULL;
	const char *authservid;
	const char *hostname;
	struct dkimf_config *conf;
	DKIM_SIGINFO *sig = NULL;
	Header hdr;
	char header[DKIM_MAXHEADER + sizeof(AUTHRESULTSHDR) + 2];

	assert(ctx != NULL);

	cc = (connctx) dkimf_getpriv(ctx);
	assert(cc != NULL);
	dfc = cc->cctx_msg;
	assert(dfc != NULL);
	conf = cc->cctx_config;

	dfc->mctx_eom = TRUE;

	/*
	**  If necessary, try again to get the job ID in case it came down
	**  later than expected (e.g. postfix).
	*/

	if (strcmp((const char *) dfc->mctx_jobid, JOBIDUNKNOWN) == 0)
	{
		dfc->mctx_jobid = (const u_char *) dkimf_getsymval(ctx, "i");
		if (dfc->mctx_jobid == NULL || dfc->mctx_jobid[0] == '\0')
		{
			if (no_i_whine && conf->conf_dolog)
			{
				syslog(LOG_WARNING,
				       "WARNING: symbol 'i' not available");
				no_i_whine = FALSE;
			}
			dfc->mctx_jobid = (const u_char *) JOBIDUNKNOWN;
		}
	}

	/* get hostname; used in the X header and in new MIME boundaries */
	hostname = dkimf_getsymval(ctx, "j");
	if (hostname == NULL)
		hostname = HOSTUNKNOWN;

	/* select authserv-id to use when generating result headers */
	authservid = conf->conf_authservid;
	if (authservid == NULL)
		authservid = hostname;

	/* if this was totally malformed, add a header field and stop */
	if (dfc->mctx_headeronly)
	{
		/* allow for override */
		if (conf->conf_passmalformed)
			return SMFIS_ACCEPT;

		/*
		** Default to "permerror" so a release build (NDEBUG, assert
		** no-op) still emits a defined value if mctx_status holds a
		** code that should not reach this branch.
		*/
		const char *ar = "permerror";

		switch (dfc->mctx_status)
		{
		  case DKIMF_STATUS_BAD:
			ar = "fail";
			break;

		  case DKIMF_STATUS_NOKEY:
		  case DKIMF_STATUS_BADFORMAT:
			ar = "permerror";
			break;

		  case DKIMF_STATUS_NOSIGNATURE:
			ar = "none";
			break;

		  case DKIMF_STATUS_GOOD:
		  case DKIMF_STATUS_REVOKED:
		  case DKIMF_STATUS_PARTIAL:
		  case DKIMF_STATUS_VERIFYERR:
		  case DKIMF_STATUS_UNKNOWN:
		  default:
			assert(0);
			/* NOTREACHED */
		}

		int n;

		n = snprintf(header, sizeof header,
					 "%s%s; dkim=%s (%s)",
					 cc->cctx_noleadspc ? " " : "",
					 authservid, ar,
			   dkimf_lookup_inttostr(dfc->mctx_status,
									 dkimf_statusstrings));

		if (n < 0 || (size_t)n >= sizeof header)
		{
			if (dolog)
				syslog(LOG_WARNING,
					   "mlfi_eom: Authentication-Results header truncated");

			header[sizeof(header) - 1] = '\0';
		}

		if (dkimf_insheader(ctx, 0, AUTHRESULTSHDR,
		                    header) == MI_FAILURE)
		{
			if (conf->conf_dolog)
			{
				syslog(LOG_ERR,
				       "%s: %s header add failed",
				       dfc->mctx_jobid,
				       AUTHRESULTSHDR);
			}

			return SMFIS_TEMPFAIL;
		}

		return SMFIS_ACCEPT;
	}

	/* remove old signatures when signing */
	if (conf->conf_remsigs && dfc->mctx_srhead != NULL)
	{
		for (hdr = dfc->mctx_hqhead; hdr != NULL; hdr = hdr->hdr_next)
		{
			if (strcasecmp(hdr->hdr_hdr, DKIM_SIGNHEADER) == 0)
			{
				if (dkimf_chgheader(ctx, hdr->hdr_hdr,
				                    0, NULL) != MI_SUCCESS)
				{
					if (conf->conf_dolog)
					{
						syslog(LOG_WARNING,
						       "failed to remove %s: header",
						       hdr->hdr_hdr);
					}
				}
			}
		}
	}

	/* remove identity header if such was requested when signing */
	if (conf->conf_rmidentityhdr && conf->conf_identityhdr != NULL &&
	    dfc->mctx_srhead != NULL)
	{
		hdr = dkimf_findheader(dfc, conf->conf_identityhdr, 0);
		if (hdr != NULL)
		{
			if (dkimf_chgheader(ctx, conf->conf_identityhdr,
			                    0, NULL) != MI_SUCCESS)
			{
				if (conf->conf_dolog)
				{
					syslog(LOG_WARNING,
						"failed to remove %s: header",
						conf->conf_identityhdr);
				}
			}
		}
	}
					
	/* log something if the message was multiply signed */
	if (dfc->mctx_dkimv != NULL && conf->conf_dolog)
	{
		int nsigs;
		DKIM_SIGINFO **sigs;

		lastdkim = dfc->mctx_dkimv;
		status = dkim_getsiglist(dfc->mctx_dkimv, &sigs, &nsigs);
		if (status == DKIM_STAT_OK && nsigs > 1)
		{
			const u_char *d;

			if (dfc->mctx_tmpstr == NULL)
			{
				dfc->mctx_tmpstr = dkimf_dstring_new(BUFRSZ, 0);

				if (dfc->mctx_tmpstr == NULL)
				{
					syslog(LOG_WARNING,
					       "%s: dkimf_dstring_new() failed",
					       dfc->mctx_jobid);

					return SMFIS_TEMPFAIL;
				}
			}
			else
			{
				dkimf_dstring_blank(dfc->mctx_tmpstr);
			}

			dkimf_dstring_cat(dfc->mctx_tmpstr, dfc->mctx_jobid);
			dkimf_dstring_cat(dfc->mctx_tmpstr,
			                  (const u_char *) ": message has signatures from ");

			for (c = 0; c < nsigs; c++)
			{
				if (c != 0)
				{
					dkimf_dstring_cat(dfc->mctx_tmpstr,
					                  (const u_char *) ", ");
				}

				d = dkim_sig_getdomain(sigs[c]);
				if (d == NULL)
					d = (const u_char *) NULLDOMAIN;

				dkimf_dstring_cat(dfc->mctx_tmpstr, d);
			}

			syslog(LOG_INFO, "%s",
			       dkimf_dstring_get(dfc->mctx_tmpstr));
		}
	}

	/*
	**  Remove all Authentication-Results: headers as per configuration
	**  options when verifying.
	*/

	if (dfc->mctx_dkimv != NULL && !conf->conf_keepar)
	{
		/* nars = number of Authentication-Results: headers */
		int nars;
		struct authres *ares;

		ares = (struct authres *) malloc(sizeof(struct authres));
		if (ares == NULL)
		{
			syslog(LOG_WARNING,
			       "%s: malloc(): %s", dfc->mctx_jobid,
			       strerror(errno));

			return SMFIS_TEMPFAIL;
		}

		/* count Authentication-Results: headers so we can use a
		stable 1-based instance index while deleting from the tail */
		nars = 0;
		for (hdr = dfc->mctx_hqhead; hdr != NULL; hdr = hdr->hdr_next)
		{
			if (strcasecmp(hdr->hdr_hdr, AUTHRESULTSHDR) == 0)
				nars++;
		}

		c = nars;
		for (hdr = dfc->mctx_hqtail; hdr != NULL; hdr = hdr->hdr_prev)
		{
			memset(ares, '\0', sizeof(struct authres));

			if (strcasecmp(hdr->hdr_hdr, AUTHRESULTSHDR) == 0)
			{
				_Bool dkimres = FALSE;
				_Bool hostmatch = FALSE;
				int arstat;
				char *slash;

				/* work from highest index downward so earlier
				instance numbers remain valid after deletion */
				/* parse the header */
				arstat = ares_parse((u_char *) hdr->hdr_val,
				                    ares);
				if (arstat == -1)
				{
					if (conf->conf_dolog)
					{
						syslog(LOG_WARNING,
						       "%s: failed to parse %s: header field",
						       dfc->mctx_jobid,
						       hdr->hdr_hdr);
					}

					continue;
				}

				/* method match? */
				if (conf->conf_remarall)
				{
					dkimres = TRUE;
				}
				else
				{
					int d;

					for (d = 0; d < ares->ares_count; d++)
					{
						if (ares->ares_result[d].result_method == ARES_METHOD_DKIM)
							dkimres = TRUE;
					}
				}

				/* hostname match? */
				slash = strchr((char *) ares->ares_host, '/');
				if (slash != NULL)
					*slash = '\0';

				/* strip a single trailing root-label dot so a
				   fully-qualified authserv-id (e.g. "host.") is
				   not compared as a distinct string against the
				   locally configured authservid */
				{
					size_t hlen = strlen((char *) ares->ares_host);
					if (hlen > 0 &&
					    ares->ares_host[hlen - 1] == '.')
						ares->ares_host[hlen - 1] = '\0';
				}

				if (conf->conf_remardb != NULL)
				{
					status = dkimf_db_get(conf->conf_remardb,
					                      ares->ares_host,
					                      0, NULL, 0,
					                      &hostmatch);
					if (status != 0 && dolog)
					{
						dkimf_db_error(conf->conf_remardb,
						               (char *) ares->ares_host);
					}
				}
				else
				{
					if (strcasecmp(authservid,
					               (char *) ares->ares_host) == 0)
						hostmatch = TRUE;
				}

				/* delete if we found both */
				if (dkimres && hostmatch)
				{
					if (dkimf_chgheader(ctx, hdr->hdr_hdr,
					                    c,
					                    NULL) != MI_SUCCESS)
{
					if (conf->conf_dolog)
						{
							syslog(LOG_WARNING,
							       "failed to remove %s: header",
							       hdr->hdr_hdr);
						}
					}
				}

				c--;
			}
		}

		free(ares);
	}

	/* complete verification if started */
	if (dfc->mctx_dkimv != NULL)
	{
		/*
		**  Signal end-of-message to DKIM
		*/

		status = dkim_eom(dfc->mctx_dkimv, &testkey);
		lastdkim = dfc->mctx_dkimv;

		if (conf->conf_logresults && conf->conf_dolog)
		{
			int nsigs;
			DKIM_STAT lstatus;
			DKIM_SIGINFO **sigs;

			if (dfc->mctx_tmpstr == NULL)
			{
				dfc->mctx_tmpstr = dkimf_dstring_new(BUFRSZ,
				                                     0);

				if (dfc->mctx_tmpstr == NULL)
				{
					syslog(LOG_WARNING,
					       "%s: dkimf_dstring_new() failed",
					       dfc->mctx_jobid);

					return SMFIS_TEMPFAIL;
				}
			}
			else
			{
				dkimf_dstring_blank(dfc->mctx_tmpstr);
			}

			lstatus = dkim_getsiglist(dfc->mctx_dkimv,
			                          &sigs, &nsigs);

			if (lstatus == DKIM_STAT_OK)
			{
				DKIM_SIGERROR err;
				size_t len;
				const char *domain;
				const char *selector;
				const char *errstr;
				char substr[BUFRSZ];

				for (c = 0; c < nsigs; c++)
				{
					domain = (const char *) dkim_sig_getdomain(sigs[c]);
					selector = (const char *) dkim_sig_getselector(sigs[c]);
					err = dkim_sig_geterror(sigs[c]);
					errstr = dkim_sig_geterrorstr(err);

					memset(substr, '\0', sizeof substr);
					len = sizeof substr;

					lstatus = dkim_get_sigsubstring(dfc->mctx_dkimv,
					                                sigs[c],
					                                substr,
					                                &len);

					if (lstatus == DKIM_STAT_OK &&
					    domain != NULL &&
					    selector != NULL &&
					    errstr != NULL)
					{
						if (dkimf_dstring_len(dfc->mctx_tmpstr) > 0)
						{
							dkimf_dstring_catn(dfc->mctx_tmpstr,
							                   (const u_char *) "; ",
							                   2);
						}

						dkimf_dstring_printf(dfc->mctx_tmpstr,
						                     "signature=%s domain=%s selector=%s result=\"%s\"",
						                     substr,
						                     domain,
						                     selector,
						                     errstr);
					}
				}

				if (dkimf_dstring_len(dfc->mctx_tmpstr) > 0)
				{
					syslog(LOG_INFO, "%s: %s",
					       dfc->mctx_jobid,
					       dkimf_dstring_get(dfc->mctx_tmpstr));
				}
			}
		}

		/*
		**  RFC 8301: if the determinative signature declares the
		**  deprecated rsa-sha1 algorithm, the library short-circuited
		**  its verification (DKIM_LIBFLAGS_NOSHA1VERIFY) and marked it
		**  DKIM_SIGERROR_WEAKALG instead of producing a pass/fail.
		**  Record this as its own status so the configured
		**  On-WeakAlgorithm disposition is applied below, regardless of
		**  the truncated DKIM_STAT_* the verification returned.
		*/

		if (dfc->mctx_dkimv != NULL)
		{
			sig = dkim_getsignature(dfc->mctx_dkimv);
			if (sig != NULL &&
			    dkim_sig_geterror(sig) == DKIM_SIGERROR_WEAKALG)
			{
				if (conf->conf_dolog)
				{
					syslog(LOG_NOTICE,
					       "%s: signature uses deprecated algorithm rsa-sha1",
					       dfc->mctx_jobid);
				}

				dfc->mctx_addheader = TRUE;
				dfc->mctx_status = DKIMF_STATUS_WEAKALG;
			}
		}

		if (dfc->mctx_status != DKIMF_STATUS_WEAKALG)
		switch (status)
		{
		  case DKIM_STAT_OK:
			if (dkimf_findheader(dfc, DKIM_SIGNHEADER, 0) != NULL)
			{
				if (conf->conf_dolog_success)
				{
					syslog(LOG_INFO,
					       "%s: DKIM verification successful",
					       dfc->mctx_jobid);
				}

				dfc->mctx_addheader = TRUE;
				dfc->mctx_status = DKIMF_STATUS_GOOD;
			}
			break;

		  case DKIM_STAT_CANTVRFY:
			dfc->mctx_addheader = TRUE;
			dfc->mctx_status = DKIMF_STATUS_VERIFYERR;
			break;

		  case DKIM_STAT_BADSIG:
			dfc->mctx_addheader = TRUE;
			dfc->mctx_status = DKIMF_STATUS_BAD;
			break;

		  case DKIM_STAT_NOSIG:
			if (conf->conf_alwaysaddar)
			{
				dfc->mctx_addheader = TRUE;
				dfc->mctx_status = DKIMF_STATUS_NOSIGNATURE;
			}
			break;

		  case DKIM_STAT_KEYFAIL:
			dfc->mctx_addheader = TRUE;
			dfc->mctx_status = DKIMF_STATUS_KEYFAIL;
			break;

		  case DKIM_STAT_NOKEY:
			dfc->mctx_addheader = TRUE;
			dfc->mctx_status = DKIMF_STATUS_NOKEY;
			break;

		  case DKIM_STAT_REVOKED:
			dfc->mctx_addheader = TRUE;
			dfc->mctx_status = DKIMF_STATUS_REVOKED;
			break;

		  default:
			if (conf->conf_dolog)
			{
				lastdkim = dfc->mctx_dkimv;
				sig = dkim_getsignature(dfc->mctx_dkimv);
				dkimf_log_ssl_errors(lastdkim, sig,
				                     (const char *) dfc->mctx_jobid);
			}

			ret = dkimf_libstatus(ctx, dfc->mctx_dkimv,
			                      "dkim_eom()", status);

#ifdef SMFIF_QUARANTINE
			if (dfc->mctx_capture)
			{
				if (dkimf_quarantine(ctx,
				                     "capture requested") != MI_SUCCESS)
				{
					if (conf->conf_dolog)
					{
						syslog(LOG_ERR,
						       "%s: smfi_quarantine() failed",
						       dfc->mctx_jobid);
					}
				}

				ret = SMFIS_ACCEPT;
			}
#endif /* ! SMFIF_QUARANTINE */
			break;
		}

		if (conf->conf_diagdir != NULL &&
		    dfc->mctx_status == DKIMF_STATUS_BAD)
		{
			int nhdrs;
			dkim_canon_t canon;
			u_char *ohdrs[MAXHDRCNT];

			nhdrs = MAXHDRCNT;
			memset(ohdrs, '\0', sizeof ohdrs);

			sig = dkim_getsignature(dfc->mctx_dkimv);

			(void) dkim_sig_getcanons(sig, &canon, NULL);

			status = dkim_ohdrs(dfc->mctx_dkimv, sig,
			                    ohdrs, &nhdrs);
			if (status == DKIM_STAT_OK && nhdrs > 0)
			{
				FILE *f;
				char dpath[MAXPATHLEN + 1];

				snprintf(dpath, sizeof dpath, "%s/%s",
				         conf->conf_diagdir, dfc->mctx_jobid);

				f = fopen(dpath, "w");
				if (f == NULL)
				{
					if (conf->conf_dolog)
					{
						syslog(LOG_ERR,
						       "%s: %s: fopen(): %s",
						       dfc->mctx_jobid,
						       dpath, strerror(errno));
					}
				}
				else
				{
					fprintf(f, "z tag headers:\n\n");

					for (c = 0; c < nhdrs; c++)
						fprintf(f, "%s\n", ohdrs[c]);

					fprintf(f, "--------------------\n\n");
					fprintf(f, "Received headers:\n\n");

					for (hdr = dfc->mctx_hqhead;
					     hdr != NULL;
					     hdr = hdr->hdr_next)
					{
						fprintf(f, "%s:%s%s\n",
						        hdr->hdr_hdr,
						        cc->cctx_noleadspc ? ""
						                           : " ",
						        hdr->hdr_val);
					}


					fclose(f);
				}
			}
		}	

		if (dfc->mctx_status == DKIMF_STATUS_GOOD)
		{
			if (conf->conf_sigmin > 0)
			{
				ssize_t canonlen;
				ssize_t bodylen;

				sig = dkim_getsignature(dfc->mctx_dkimv);
				(void) dkim_sig_getcanonlen(dfc->mctx_dkimv,
				                            sig, &bodylen,
				                            &canonlen, NULL);

				/* empty body is never treated as partial;
				 * canonlen/bodylen use -1 as "unset" sentinel */
				if (bodylen > 0 && canonlen >= 0)
				{
					if (conf->conf_sigmintype == SIGMIN_PERCENT)
					{
						size_t signpct;

						signpct = (size_t)(100 * canonlen) / (size_t) bodylen;

						if (signpct < conf->conf_sigmin)
							dfc->mctx_status = DKIMF_STATUS_PARTIAL;
					}
					else if (conf->conf_sigmintype == SIGMIN_MAXADD)
					{
						/*
						**  canonlen/bodylen are ssize_t
						**  with -1 as the "unset"
						**  sentinel; guard before
						**  casting to size_t.
						*/
						if (canonlen >= 0 && bodylen >= 0 &&
						    (size_t) canonlen + conf->conf_sigmin <
						    (size_t) bodylen)
							dfc->mctx_status = DKIMF_STATUS_PARTIAL;
					}
					else
					{
						size_t required;

						required = MIN(conf->conf_sigmin,
						               (size_t) bodylen);

						/* same guard as MAXADD above */
						if (canonlen >= 0 &&
						    (size_t) canonlen < required)
							dfc->mctx_status = DKIMF_STATUS_PARTIAL;
					}
				}
			}
		}


		if (dfc->mctx_addheader)
		{
			u_char val[MAXADDRESS + 1];

			/*
			**  Record DKIM and ADSP results in an
			**  Authentication-Results: header field.
			*/

			memset(val, '\0', sizeof val);
			memset(header, '\0', sizeof header);

			if (conf->conf_authservidwithjobid &&
			    dfc->mctx_jobid != NULL)
			{
				/*
				**  RFC 8601, Section 2.2 requires the
				**  authserv-id to be a token or a
				**  quoted-string.  Appending the job ID after
				**  a "/" introduces a tspecial (RFC 2045,
				**  Section 5.1) that may not appear in a bare
				**  token, so emit the combined value as a
				**  quoted-string.
				*/
				snprintf(header, sizeof header, "%s\"%s/%s\"",
				         cc->cctx_noleadspc ? " " : "",
				         authservid,
				         (const char *) dfc->mctx_jobid);
			}
			else
			{
				snprintf(header, sizeof header, "%s%s",
				         cc->cctx_noleadspc ? " " : "",
				         authservid);
			}

			strlcat(header, ";", sizeof header);
			strlcat(header, DELIMITER, sizeof header);

			if (dfc->mctx_status == DKIMF_STATUS_GOOD ||
			    dfc->mctx_status == DKIMF_STATUS_BAD ||
			    dfc->mctx_status == DKIMF_STATUS_REVOKED ||
			    dfc->mctx_status == DKIMF_STATUS_PARTIAL ||
			    dfc->mctx_status == DKIMF_STATUS_NOKEY ||
			    dfc->mctx_status == DKIMF_STATUS_KEYFAIL ||
			    dfc->mctx_status == DKIMF_STATUS_VERIFYERR ||
			    dfc->mctx_status == DKIMF_STATUS_WEAKALG)
			{
				dkimf_ar_all_sigs(header, sizeof header,
				                  dfc->mctx_dkimv,
				                  conf, &dfc->mctx_status);
			}
			else if (dfc->mctx_status == DKIMF_STATUS_NOSIGNATURE)
			{
				strlcat(header, "dkim=none",
				        sizeof header);
			}

			/* if we generated either, pretty it up */
			if (header[0] != '\0')
			{
				_Bool first;
				int len;
				char *p;
				char *last;
				char tmphdr[DKIM_MAXHEADER + 1];

				c = sizeof AUTHRESULTSHDR + 2;
				first = TRUE;
				memset(tmphdr, '\0', sizeof tmphdr);

				for (p = strtok_r(header,
				                  DELIMITER, &last);
				     p != NULL;
				     p = strtok_r(NULL, DELIMITER,
				                  &last))
				{
					len = (int) strlen(p); /* token bounded by DKIM_MAXHEADER */

					if (!first)
					{
						if (c + len >= DKIM_HDRMARGIN)
						{
							strlcat(tmphdr,
							        "\n\t",
							        sizeof tmphdr);
							c = 8;
						}
						else
						{
							strlcat(tmphdr,
							        " ",
							        sizeof tmphdr);
						}
					}

					strlcat(tmphdr, p,
					        sizeof tmphdr);
					first = FALSE;
					c += len;
				}

				strlcpy((char *) dfc->mctx_dkimar,
				        tmphdr,
				        sizeof dfc->mctx_dkimar);

				dkimf_add_ar_fields(dfc, conf, ctx);

			if (dfc->mctx_resign)
			{
				snprintf(header, sizeof header,
				         "%s: %s",
				         AUTHRESULTSHDR,
				         dfc->mctx_dkimar);

				status = dkimf_msr_header(dfc->mctx_srhead,
				                          &lastdkim,
				                          (u_char *) header,
				                          strlen(header));
				if (status != DKIM_STAT_OK)
				{
					return dkimf_libstatus(ctx,
					                       lastdkim,
					                       "dkim_header()",
					                       status);
				}

				status = dkimf_msr_eoh(dfc->mctx_srhead,
				                       &lastdkim);

				if (status != DKIM_STAT_OK)
				{
					return dkimf_libstatus(ctx,
					                       lastdkim,
					                       "dkim_eoh()",
					                       status);
				}
			}
			}
		}


		/* send an ARF message for DKIM? */
		if (dfc->mctx_status == DKIMF_STATUS_BAD &&
		    conf->conf_sendreports)
			dkimf_sigreport(cc, conf, hostname);


		if (conf->conf_redirect != NULL &&
		    dfc->mctx_status == DKIMF_STATUS_BAD)
		{
			struct addrlist *a;

			/* convert all recipients to headers */
			for (a = dfc->mctx_rcptlist;
			     a != NULL;
			     a = a->a_next)
			{
				if (dkimf_delrcpt(ctx,
				                  a->a_addr) != MI_SUCCESS)
				{
					if (conf->conf_dolog)
					{
						syslog(LOG_ERR,
						       "%s: smfi_delrcpt() failed",
						       dfc->mctx_jobid);
					}

					return SMFIS_TEMPFAIL;
				}

				snprintf(header, sizeof header,
				         "rfc822;%s", a->a_addr);
				if (dkimf_addheader(ctx, ORCPTHEADER,
				                    header) != MI_SUCCESS)
				{
					if (conf->conf_dolog)
					{
						syslog(LOG_ERR,
						       "%s: smfi_addheader() failed",
						       dfc->mctx_jobid);
					}

					return SMFIS_TEMPFAIL;
				}
			}

			/* add our recipient */
			if (dkimf_addrcpt(ctx,
			                  conf->conf_redirect) != MI_SUCCESS)
			{
				if (conf->conf_dolog)
				{
					syslog(LOG_ERR,
					       "%s: smfi_addrcpt() failed",
					       dfc->mctx_jobid);
				}

				return SMFIS_TEMPFAIL;
			}
		}
	}

#ifdef USE_LUA
	if (conf->conf_finalscript != NULL)
	{
		_Bool dofree = TRUE;
		struct dkimf_lua_script_result lres;

		memset(&lres, '\0', sizeof lres);

		dfc->mctx_mresult = SMFIS_CONTINUE;

		status = dkimf_lua_final_hook(ctx, conf->conf_finalfunc,
		                              conf->conf_finalfuncsz,
		                              "final script", &lres,
		                              NULL, NULL);

		if (status != 0)
		{
			if (conf->conf_dolog)
			{
				if (lres.lrs_error == NULL)
				{
					dofree = FALSE;

					switch (status)
					{
					  case 2:
						lres.lrs_error = "processing error";
						break;

					  case 1:
						lres.lrs_error = "syntax error";
						break;

					  case -1:
						lres.lrs_error = "memory allocation error";
						break;

					  default:
						lres.lrs_error = "unknown error";
						break;
					}
				}

				syslog(LOG_ERR,
				       "%s: dkimf_lua_final_hook() failed: %s",
				       dfc->mctx_jobid, lres.lrs_error);
			}

			if (dofree)
				free((void *)(uintptr_t) lres.lrs_error);

			return SMFIS_TEMPFAIL;
		}

		if (dfc->mctx_mresult != SMFIS_CONTINUE &&
		    dfc->mctx_mresult != SMFIS_ACCEPT)
			return dfc->mctx_mresult;
	}
#endif /* USE_LUA */

	/* complete signing if requested */
	if (dfc->mctx_srhead != NULL &&
	    (!dfc->mctx_resign || conf->conf_resignall ||
	     dfc->mctx_status == DKIMF_STATUS_GOOD))
	{
		size_t len;
		u_char *start;
		struct signreq *sr;

		status = dkimf_msr_eom(dfc->mctx_srhead, &lastdkim);
		if (status != DKIM_STAT_OK)
		{
			dkimf_log_ssl_errors(lastdkim, NULL,
			                     (const char *) dfc->mctx_jobid);
			return dkimf_libstatus(ctx, lastdkim, "dkim_eom()",
			                       status);
		}

		if (dfc->mctx_tmpstr == NULL)
		{
			dfc->mctx_tmpstr = dkimf_dstring_new(BUFRSZ, 0);

			if (dfc->mctx_tmpstr == NULL)
			{
				syslog(LOG_WARNING,
				       "%s: dkimf_dstring_new() failed",
				       dfc->mctx_jobid);

				return SMFIS_TEMPFAIL;
			}
		}
		else
		{
			dkimf_dstring_blank(dfc->mctx_tmpstr);
		}

		for (sr = dfc->mctx_srhead;
		     sr != NULL;
		     sr = sr->srq_next)
		{
			dkimf_dstring_blank(dfc->mctx_tmpstr);
			if (cc->cctx_noleadspc)
				dkimf_dstring_cat1(dfc->mctx_tmpstr, ' ');

			lastdkim = sr->srq_dkim;
			status = dkim_getsighdr_d(sr->srq_dkim,
		                                  strlen(DKIM_SIGNHEADER) + 2,
		                                  &start, &len);
			if (status != DKIM_STAT_OK)
			{
				if (conf->conf_dolog)
				{
					syslog(LOG_ERR,
					       "%s: dkim_getsighdr() failed",
					       dfc->mctx_jobid);
				}

				return SMFIS_TEMPFAIL;
			}

			/* XXX -- check "len" for oversize? */

			dkimf_stripcr((char *) start);
			dkimf_dstring_cat(dfc->mctx_tmpstr, start);

			if (dkimf_insheader(ctx, 0, DKIM_SIGNHEADER,
			                    (char *) dkimf_dstring_get(dfc->mctx_tmpstr)) == MI_FAILURE)
			{
				if (conf->conf_dolog)
				{
					syslog(LOG_ERR,
					       "%s: %s header add failed",
					       dfc->mctx_jobid,
					       DKIM_SIGNHEADER);
				}
			}
			else if (conf->conf_dolog_success)
			{
				char *d;
				char *s;

				if (sr->srq_domain != NULL)
					d = (char *) sr->srq_domain;
				else
					d = (char *) dfc->mctx_domain;

				if (sr->srq_selector != NULL)
					s = (char *) sr->srq_selector;
				else
					s = (char *) conf->conf_selector;

				syslog(LOG_INFO,
				       "%s: %s field added (s=%s, d=%s)",
				       dfc->mctx_jobid, DKIM_SIGNHEADER, s, d);
			}
		}

	}

	/*
	**  Identify the filter, if requested.
	*/

	if (conf->conf_addswhdr)
	{
		char xfhdr[DKIM_MAXHEADER + 1];

		memset(xfhdr, '\0', sizeof xfhdr);

		if (strcasecmp(hostname, myhostname) == 0)
		{
			snprintf(xfhdr, DKIM_MAXHEADER, "%s%s v%s %s %s",
			         cc->cctx_noleadspc ? " " : "",
			         DKIMF_PRODUCT, DKIMF_VERSION, hostname,
			         dfc->mctx_jobid != NULL ? dfc->mctx_jobid
			                                 : (const u_char *) JOBIDUNKNOWN);
		}
		else
		{
			snprintf(xfhdr, DKIM_MAXHEADER, "%s%s v%s %s via %s %s",
			         cc->cctx_noleadspc ? " " : "",
			         DKIMF_PRODUCT, DKIMF_VERSION, hostname,
			         myhostname,
			         dfc->mctx_jobid != NULL ? dfc->mctx_jobid
			                                 : (const u_char *) JOBIDUNKNOWN);
		}

		if (dkimf_insheader(ctx, 0, SWHEADERNAME, xfhdr) != MI_SUCCESS)
		{
			if (conf->conf_dolog)
			{
				syslog(LOG_ERR, "%s: %s header add failed",
				       dfc->mctx_jobid, SWHEADERNAME);
			}

			dkimf_cleanup(ctx);
			return SMFIS_TEMPFAIL;
		}
	}

	if (lastdkim != NULL)
		dkimf_log_ssl_errors(lastdkim, sig, (const char *) dfc->mctx_jobid);

	/*
	**  If we got this far, we're ready to complete.
	*/

	/* translate the stored status */
	switch (dfc->mctx_status)
	{
	  case DKIMF_STATUS_GOOD:
		break;

	  case DKIMF_STATUS_BAD:
		ret = dkimf_libstatus(ctx, lastdkim, "mlfi_eom()",
		                      DKIM_STAT_BADSIG);
		if ((ret == SMFIS_REJECT || ret == SMFIS_TEMPFAIL ||
		     ret == SMFIS_DISCARD) &&
		    testkey)
			ret = SMFIS_ACCEPT;
		break;

	  case DKIMF_STATUS_NOKEY:
		ret = dkimf_libstatus(ctx, lastdkim, "mlfi_eom()",
		                      DKIM_STAT_NOKEY);
		break;

	  case DKIMF_STATUS_KEYFAIL:
		ret = dkimf_libstatus(ctx, lastdkim, "mlfi_eom()",
		                      DKIM_STAT_KEYFAIL);
		break;

	  case DKIMF_STATUS_REVOKED:
		ret = dkimf_libstatus(ctx, lastdkim, "mlfi_eom()",
		                      DKIM_STAT_REVOKED);
		break;

	  case DKIMF_STATUS_NOSIGNATURE:
		if (!dfc->mctx_addheader)
		{
			ret = dkimf_libstatus(ctx, lastdkim, "mlfi_eom()",
			                      DKIM_STAT_NOSIG);
		}
		break;

	  case DKIMF_STATUS_BADFORMAT:
		ret = SMFIS_ACCEPT;
		break;

	  case DKIMF_STATUS_WEAKALG:
		/*
		**  RFC 8301: apply the On-WeakAlgorithm disposition to a
		**  deprecated (rsa-sha1) signature.  "neutral" (the default)
		**  resolves to SMFIS_ACCEPT, so the message is delivered while
		**  the Authentication-Results field already reports it as such.
		**  The "t=y" testing key flag bypasses the hard dispositions,
		**  mirroring On-BadSignature.
		*/
		ret = dkimf_miltercode(ctx, conf->conf_handling.hndl_weakalg,
		                       NULL);
		if ((ret == SMFIS_REJECT || ret == SMFIS_TEMPFAIL ||
		     ret == SMFIS_DISCARD) &&
		    testkey)
			ret = SMFIS_ACCEPT;
		break;

	  case DKIMF_STATUS_UNKNOWN:
		break;

	  default:
		if (status != DKIM_STAT_OK)
			ret = dkimf_libstatus(ctx, NULL, "mlfi_eom()", status);
		break;
	}

	return ret;
}

/*
**  MLFI_ABORT -- handler called if an earlier filter in the filter process
**                rejects the message
**
**  Parameters:
**  	ctx -- milter context
**
**  Return value:
**  	An SMFIS_* constant.
*/

sfsistat
mlfi_abort(SMFICTX *ctx)
{
	dkimf_cleanup(ctx);
	return SMFIS_CONTINUE;
}

/*
**  MLFI_CLOSE -- handler called on connection shutdown
**
**  Parameters:
**  	ctx -- milter context
**
**  Return value:
**  	An SMFIS_* constant.
*/

sfsistat
mlfi_close(SMFICTX *ctx)
{
	connctx cc;

	dkimf_cleanup(ctx);

	cc = (connctx) dkimf_getpriv(ctx);
	if (cc != NULL)
	{
		pthread_mutex_lock(&conf_lock);

		cc->cctx_config->conf_refcnt--;

		if (cc->cctx_config->conf_refcnt == 0 &&
		    cc->cctx_config != curconf)
			dkimf_config_free(cc->cctx_config);

		pthread_mutex_unlock(&conf_lock);

		free(cc);
		dkimf_setpriv(ctx, NULL);
	}

	return SMFIS_CONTINUE;
}

/*
**  smfilter -- the milter module description
*/

struct smfiDesc smfilter =
{
	/*
	**  libmilter's xxfi_name is char *; libmilter never writes
	**  through this pointer -- cast away const on our string literal.
	*/

	(char *) DKIMF_PRODUCT,	/* filter name */
	SMFI_VERSION,	/* version code -- do not change */
	0,		/* flags; updated in main() */
	mlfi_connect,	/* connection info filter */
#if SMFI_VERSION == 2
	mlfi_helo,	/* SMTP HELO command filter */
#else /* SMFI_VERSION == 2 */
	NULL,		/* SMTP HELO command filter */
#endif /* SMFI_VERSION == 2 */
	mlfi_envfrom,	/* envelope sender filter */
	mlfi_envrcpt,	/* envelope recipient filter */
	mlfi_header,	/* header filter */
	mlfi_eoh,	/* end of header */
	mlfi_body,	/* body block filter */
	mlfi_eom,	/* end of message */
	mlfi_abort,	/* message aborted */
	mlfi_close,	/* shutdown */
#if SMFI_VERSION > 2
	NULL,		/* unrecognised command */
#endif
#if SMFI_VERSION > 3
	NULL,		/* DATA */
#endif
#if SMFI_VERSION >= 0x01000000
	mlfi_negotiate	/* negotiation callback */
#endif
};

/*
**  USAGE -- print a usage message and return the appropriate exit status
**
**  Parameters:
**  	None.
**
**  Return value:
**  	EX_USAGE.
*/

static int
usage(void)
{
	fprintf(stderr, "%s: usage: %s -p socketfile [options]\n"
	                "\t-A          \tauto-restart\n"
	                "\t-b modes    \tselect operating modes\n"
	                "\t-c canon    \tcanonicalization to use when signing\n"
	                "\t-G          \tforce walk SigningTable when loading config\n"
	                "\t-d domlist  \tdomains to sign\n"
	                "\t-D          \talso sign subdomains\n"
	                "\t-e name     \textract configuration value and exit\n"
	                "\t-f          \tdon't fork-and-exit\n"
	                "\t-F time     \tfixed timestamp to use when signing (test mode only)\n"
	                "\t-g          \tdo not walk SigningTable when loading config\n"
	                "\t-k keyfile  \tlocation of secret key file\n"
	                "\t-l          \tlog activity to system log\n"
	                "\t-L limit    \tsignature limit requirements\n"
	                "\t-n          \tcheck configuration and exit\n"
			"\t-o hdrlist  \tlist of headers to omit from signing\n"
			"\t-P pidfile  \tfile into which to write process ID\n"
	                "\t-q          \tquarantine messages that fail to verify\n"
		        "\t-Q          \tquery test mode\n"
	                "\t-r          \trequire basic RFC5322 header compliance\n"
	                "\t-s selector \tselector to use when signing\n"
	                "\t-S signalg  \tsignature algorithm to use when signing\n"
			"\t-t testfile \tevaluate RFC5322 message in \"testfile\"\n"
			"\t-T timeout  \tDNS timeout (seconds)\n"
	                "\t-u userid   \tchange to specified userid\n"
	                "\t-v          \tincrease verbosity during testing\n"
	                "\t-V          \tprint version number and terminate\n"
	                "\t-W          \t\"why?!\" mode (log sign/verify decision logic)\n"
	                "\t-x conffile \tread configuration from conffile\n",
	        progname, progname);
	return EX_USAGE;
}

/*
**  MAIN -- program mainline
**
**  Process command line arguments and call the milter mainline.
*/

int
main(int argc, char **argv)
{
	_Bool autorestart = FALSE;
	_Bool gotp = FALSE;
	_Bool dofork = TRUE;
	_Bool stricttest = FALSE;
	_Bool configonly = FALSE;
	_Bool querytest = FALSE;
	int c;
	int status;
	int n;
	int verbose = 0;
	int maxrestarts = 0;
	int maxrestartrate_n = 0;
	int filemask = -1;
	int mdebug = 0;
#ifdef HAVE_SMFI_VERSION
	u_int mvmajor;
	u_int mvminor;
	u_int mvrelease;
#endif /* HAVE_SMFI_VERSION */
	time_t now;
	gid_t gid = (gid_t) -1;
	sigset_t sigset;
	uint64_t fixedtime = (uint64_t) -1;
	time_t maxrestartrate_t = 0;
	pthread_t rt;
	unsigned long tmpl;
	const char *args = CMDLINEOPTS;
	FILE *f;
	struct passwd *pw = NULL;
	struct group *gr = NULL;
	char *become = NULL;
	char *chrootdir = NULL;
	char *extract = NULL;
	char *p;
	const char *liberr = NULL;
	char *pidfile = NULL;
	char *testfile = NULL;
	char *testpubkeys = NULL;
	struct config *cfg = NULL;
	char *end;
	char argstr[MAXARGV];
	char err[BUFRSZ + 1];

	/* initialize */
	reload = FALSE;
	testmode = FALSE;
	sock = NULL;
	no_i_whine = TRUE;
	conffile = NULL;
	init_checksigningtable = TRUE;
	use_cf_checksigningtable = TRUE;

	memset(myhostname, '\0', sizeof myhostname);
	(void) gethostname(myhostname, sizeof myhostname);

	progname = (p = strrchr(argv[0], '/')) == NULL ? argv[0] : p + 1;

	(void) time(&now);
	srandom((unsigned int) now);

	curconf = dkimf_config_new();
	if (curconf == NULL)
	{
		fprintf(stderr, "%s: malloc(): %s\n", progname,
		        strerror(errno));

		return EX_OSERR;
	}

	/* process command line options */
	while ((c = getopt(argc, argv, args)) != -1)
	{
		switch (c)
		{
		  case 'A':
			autorestart = TRUE;
			break;

		  case 'b':
			if (optarg == NULL || *optarg == '\0')
				return usage();
			curconf->conf_modestr = optarg;
			break;

		  case 'c':
			if (optarg == NULL || *optarg == '\0')
				return usage();
			curconf->conf_canonstr = optarg;
			break;

		  case 'd':
			if (optarg == NULL || *optarg == '\0')
				return usage();
			curconf->conf_domlist = strdup(optarg);
			if (curconf->conf_domlist == NULL)
			{
				fprintf(stderr, "%s: strdup(): %s\n", progname,
				        strerror(errno));
				return EX_SOFTWARE;
			}
			break;

		  case 'D':
			curconf->conf_subdomains = TRUE;
			break;

		  case 'e':
			extract = optarg;
			break;

		  case 'f':
			dofork = FALSE;
			break;

		  case 'F':
			if (optarg == NULL || *optarg == '\0')
				return usage();
			errno = 0;
			if (optarg[0] == '-')
			{
				errno = ERANGE;
				fixedtime = ULONG_MAX;
			}
			else
			{
				fixedtime = strtoul(optarg, &p, 10);
			}

			if (fixedtime == (uint64_t) ULONG_MAX ||
			    errno != 0 ||
			    *p != '\0')
			{
				fprintf(stderr, "%s: invalid time value\n",
				        progname);
				return EX_USAGE;
			}
			break;

		  case 'g':
			use_cf_checksigningtable = FALSE;
			init_checksigningtable = FALSE;
			curconf->conf_checksigningtable = FALSE;
			break;

		  case 'G':
			use_cf_checksigningtable = FALSE;
			init_checksigningtable = TRUE;
			curconf->conf_checksigningtable = TRUE;
			break;

		  case 'k':
			if (optarg == NULL || *optarg == '\0')
				return usage();
			curconf->conf_keyfile = optarg;
			break;

		  case 'l':
			curconf->conf_dolog = TRUE;
			break;

		  case 'L':
			if (optarg == NULL || *optarg == '\0')
				return usage();
			curconf->conf_siglimit = optarg;
			break;

		  case 'n':
			configonly = TRUE;
			break;

		  case 'o':
			if (optarg == NULL || *optarg == '\0')
				return usage();
			curconf->conf_omitlist = optarg;
			break;

		  case 'p':
			if (optarg == NULL || *optarg == '\0')
				return usage();
			sock = optarg;
			(void) smfi_setconn(optarg);
			gotp = TRUE;
			break;

		  case 'P':
			if (optarg == NULL || *optarg == '\0')
				return usage();
			pidfile = optarg;
			break;

		  case 'Q':
			querytest = TRUE;
			testmode = TRUE;
			break;

		  case 'r':
			curconf->conf_reqhdrs = TRUE;
			break;

		  case 's':
			if (optarg == NULL || *optarg == '\0')
				return usage();
			curconf->conf_selector = (u_char *) optarg;
			break;

		  case 'S':
			if (optarg == NULL || *optarg == '\0')
				return usage();
			curconf->conf_signalgstr = optarg;
			break;

		  case 't':
			if (optarg == NULL || *optarg == '\0')
				return usage();
			testmode = TRUE;
			testfile = optarg;
			break;

		  case 'T':
			if (optarg == NULL || *optarg == '\0')
				return usage();
			errno = 0;
			if (optarg[0] == '-')
			{
				errno = ERANGE;
				tmpl = ULONG_MAX;
			}
			else
			{
				tmpl = strtoul(optarg, &p, 10);
			}

			if (tmpl == ULONG_MAX || errno != 0 || *p != '\0')
			{
				fprintf(stderr, "%s: invalid value for -%c\n",
				        progname, c);
				return EX_USAGE;
			}

			curconf->conf_dnstimeout = (unsigned int) tmpl;

			break;

		  case 'u':
			if (optarg == NULL || *optarg == '\0')
				return usage();
			become = optarg;
			break;

		  case 'v':
			verbose++;
			break;

		  case 'V':
			if (!dkimf_config_setlib(curconf, &liberr))
			{
				fprintf(stderr,
				        "%s: can't configure DKIM library: %s\n",
				        progname, liberr);

				return EX_SOFTWARE;
			}

			printf("%s: %s v%s\n", progname, DKIMF_PRODUCT,
			       DKIMF_VERSION);
			printf("\tCompiled with %s\n",
			       OpenSSL_version(OPENSSL_VERSION));
			printf("\tSMFI_VERSION 0x%x\n", SMFI_VERSION);
#ifdef HAVE_SMFI_VERSION
			(void) smfi_version(&mvmajor, &mvminor, &mvrelease);
			printf("\tlibmilter version %d.%d.%d\n",
			       mvmajor, mvminor, mvrelease);
#endif /* HAVE_SMFI_VERSION */
			printf("\tSupported signing algorithms:\n");
			for (c = 0; dkimf_sign[c].str != NULL; c++)
			{
				if (dkimf_sign[c].code != DKIM_SIGN_RSASHA256 ||
	    			    dkim_libfeature(curconf->conf_libopendkim,
				                    DKIM_FEATURE_SHA256))
					printf("\t\t%s\n", dkimf_sign[c].str);
			}
			printf("\tSupported canonicalization algorithms:\n");
			for (c = 0; dkimf_canon[c].str != NULL; c++)
				printf("\t\t%s\n", dkimf_canon[c].str);
			printf("\tConfigured with: %s\n", CONFIGURE_ARGS);
			dkimf_optlist(stdout);
			return EX_OK;

		  case 'W':
			curconf->conf_logwhy = TRUE;
			break;

		  case 'x':
			if (optarg == NULL || *optarg == '\0')
				return usage();
			else
				conffile = optarg;
			break;

		  case 'X':
			allowdeprecated = TRUE;
			break;

		  default:
			return usage();
		}
	}

	if (optind != argc)
		return usage();

	if ((dkim_ssl_version() >> 8) != (OPENSSL_VERSION_NUMBER >> 8))
	{
		fprintf(stderr,
		        "%s: incompatible SSL versions (library = 0x%09lx, filter = %09lx)\n",
		        progname, dkim_ssl_version(),
		        (unsigned long) OPENSSL_VERSION_NUMBER);

		return EX_SOFTWARE;
	}

	/* if there's a default config file readable, use it */
	if (conffile == NULL && access(DEFCONFFILE, R_OK) == 0)
	{
		conffile = DEFCONFFILE;
		if (verbose > 1)
		{
			fprintf(stderr, "%s: using default configfile %s\n",
				progname, DEFCONFFILE);
		}
	}

	if (conffile != NULL)
	{
		u_int line = 0;
		const char *missing;
		char *deprecated = NULL;
		char path[MAXPATHLEN + 1];

		cfg = config_load(conffile, dkimf_config,
		                  &line, path, sizeof path, &deprecated);

		if (cfg == NULL)
		{
			fprintf(stderr,
			        "%s: %s: configuration error at line %u: %s\n",
			        progname, path, line,
			        config_error());
			dkimf_config_free(curconf);
			return EX_CONFIG;
		}

		missing = config_check(cfg, dkimf_config);
		if (missing != NULL)
		{
			fprintf(stderr,
			        "%s: %s: required parameter \"%s\" missing\n",
			        progname, conffile, missing);
			config_free(cfg);
			dkimf_config_free(curconf);
			return EX_CONFIG;
		}

		if (deprecated != NULL)
		{
			const char *action = "aborting";
			if (allowdeprecated)
				action = "continuing";

			fprintf(stderr,
			        "%s: %s: settings found for deprecated value(s): %s; %s\n",
			        progname, conffile, deprecated, action);

			if (!allowdeprecated)
			{
				config_free(cfg);
				dkimf_config_free(curconf);
				return EX_CONFIG;
			}
		}
	}

	if (dkimf_config_load(cfg, curconf, err, sizeof err, become) != 0)
	{
		if (conffile == NULL)
			conffile = "(stdin)";
		fprintf(stderr, "%s: %s: %s\n", progname, conffile, err);
		config_free(cfg);
		dkimf_config_free(curconf);
		return EX_CONFIG;
	}

	if (configonly)
	{
		config_free(cfg);
		dkimf_config_free(curconf);
		return EX_OK;
	}

	if (extract)
	{
		int ret = EX_OK;

		if (cfg != NULL)
		{
			if (!config_validname(dkimf_config, extract))
				ret = EX_DATAERR;
			else if (config_dump(cfg, stdout, extract) == 0)
				ret = EX_CONFIG;
			config_free(cfg);
			dkimf_config_free(curconf);
		}
		return ret;
	}

	dolog = curconf->conf_dolog;
	curconf->conf_data = cfg;

	if (querytest)
	{
		_Bool exists = FALSE;
		DKIMF_DB dbtest;
		DKIMF_DBDATA dbdp;
		char dbname[BUFRSZ + 1];
		char query[BUFRSZ + 1];
		char **result;

		if (isatty(0))
		{
			fprintf(stdout, "%s: enter data set description\n",
			        progname);
			fprintf(stdout, "\tcsl:entry1[,entry2[,...]]\n"
			                "\tfile:path\n"
			                "\trefile:path\n"
#ifdef USE_LUA
			                "\tlua:path\n"
#endif /* USE_LUA */
#ifdef USE_MDB
			                "\tmdb:path\n"
#endif /* USE_MDB */
			                "> ");
		}

		memset(dbname, '\0', sizeof dbname);
		if (fgets(dbname, BUFRSZ, stdin) != dbname)
		{
			fprintf(stderr, "%s: fgets(): %s\n", progname,
			        strerror(errno));
			return EX_OSERR;
		}

		p = strchr(dbname, '\n');
		if (p != NULL)
			*p = '\0';

		for (p = dbname; isspace(*p); p++)
			continue;
		if (p != dbname)
			memmove(dbname, p, strlen(p) + 1);

		status = dkimf_db_open(&dbtest, dbname,
		                       (DKIMF_DB_FLAG_READONLY |
		                        DKIMF_DB_FLAG_ASCIIONLY),
		                       NULL, &liberr);
		if (status != 0)
		{
			fprintf(stderr, "%s: %s: dkimf_db_open(): %s\n",
			        progname, dbname, liberr);
			return EX_SOFTWARE;
		}

		for (;;)
		{
			if (isatty(0))
			{
				fprintf(stdout,
				        "%s: enter 'query/n' where 'n' is number of fields to request\n> ",
				        progname);
			}

			memset(query, '\0', sizeof query);
			if (fgets(query, BUFRSZ, stdin) != query)
				break;

			p = strchr(query, '\n');
			if (p != NULL)
				*p = '\0';

			if (dkimf_isblank(query))
				continue;

			p = strchr(query, '/');
			if (p == NULL)
			{
				(void) dkimf_db_close(dbtest);
				fprintf(stderr, "%s: invalid query '%s'\n",
				        progname, query);
				return EX_USAGE;
			}

			n = atoi(p + 1);
			if (n < 0)
			{
				(void) dkimf_db_close(dbtest);
				fprintf(stderr, "%s: invalid query '%s'\n",
				        progname, query);
				return EX_USAGE;
			}
	
			result = (char **) malloc(sizeof(char *) * (size_t) n);
			if (result == NULL)
			{
				fprintf(stderr, "%s: malloc(): %s\n", progname,
				        strerror(errno));
				return EX_OSERR;
			}

			for (c = 0; c < n; c++)
			{
				result[c] = (char *) malloc(BUFRSZ + 1);
				if (result[c] == NULL)
				{
					fprintf(stderr, "%s: malloc(): %s\n",
					        progname, strerror(errno));
					free(result);
					return EX_OSERR;
				}
				memset(result[c], '\0', BUFRSZ + 1);
			}

			dbdp = (DKIMF_DBDATA) malloc(sizeof(struct dkimf_db_data) * (size_t) n);
			if (dbdp == NULL)
			{
				fprintf(stderr, "%s: malloc(): %s\n", progname,
				        strerror(errno));
				free(result);
				return EX_OSERR;
			}

			for (c = 0; c < n; c++)
			{
				dbdp[c].dbdata_buffer = result[c];
				dbdp[c].dbdata_buflen = BUFRSZ;
				dbdp[c].dbdata_flags = 0;
			}

			*p = '\0';

			status = dkimf_db_get(dbtest, query, strlen(query),
			                      dbdp, (unsigned int) n, &exists);

			if (status != 0)
			{
				char errbuf[BUFRSZ + 1];

				memset(errbuf, '\0', sizeof errbuf);

				dkimf_db_strerror(dbtest, errbuf,
				                  sizeof errbuf);

				fprintf(stderr,
				        "%s: dkimf_db_get() returned %d: \"%s\"\n",
				        progname, status, errbuf);
			}
			else if (!exists)
			{
				fprintf(stdout,
				        "%s: dkimf_db_get(): record not found\n",
				        progname);
			}
			else
			{
				for (c = 0; c < n; c++)
				{
					if (dbdp[c].dbdata_buflen == 0)
						fprintf(stdout, "<empty>\n");
					else if (dbdp[c].dbdata_buflen == (size_t) -1)
						fprintf(stdout, "<absent>\n");
					else
						fprintf(stdout, "'%s'\n", result[c]);
				}
			}

			for (c = 0; c < n; c++)
				free(result[c]);
			free(result);
			free(dbdp);
		}

		fprintf(stdout, "\n");

		dkimf_db_close(dbtest);

		return 0;
	}

	if (testmode && curconf->conf_modestr == NULL)
		curconf->conf_mode = DKIMF_MODE_VERIFIER;

	/*
	**  Use values found in the configuration file, if any.  Note that
	**  these are operational parameters for the filter (e.g which socket
	**  to use which userid to become, etc.) and aren't reloaded upon a
	**  reload signal.  Reloadable values are handled via the
	**  dkimf_config_load() function, which has already been called.
	*/

	if (cfg != NULL)
	{
		if (!autorestart)
		{
			(void) config_get(cfg, "AutoRestart", &autorestart,
			                  sizeof autorestart);
		}

		if (autorestart)
		{
			char *rate = NULL;

			(void) config_get(cfg, "AutoRestartCount",
			                  &maxrestarts, sizeof maxrestarts);

			(void) config_get(cfg, "AutoRestartRate", &rate,
			                  sizeof rate);

			if (rate != NULL)
			{
				time_t t;
				char *q;

				p = strchr(rate, '/');
				if (p == NULL)
				{
					fprintf(stderr,
					        "%s: AutoRestartRate invalid\n",
					        progname);
					config_free(cfg);
					return EX_CONFIG;
				}

				*p = '\0';
				n = (int) strtol(rate, &q, 10); /* restart rate bounded by int */
				if (n < 0 || *q != '\0')
				{
					fprintf(stderr,
					        "%s: AutoRestartRate invalid\n",
					        progname);
					config_free(cfg);
					return EX_CONFIG;
				}

				t = (time_t) strtoul(p + 1, &q, 10);
				switch (*q)
				{
				  case 'd':
				  case 'D':
					t *= 86400;
					break;

				  case 'h':
				  case 'H':
					t *= 3600;
					break;

				  case 'm':
				  case 'M':
					t *= 60;
					break;

				  case '\0':
				  case 's':
				  case 'S':
					break;

				  default:
					t = 0;
					break;
				}

				if (*q != '\0' && *(q + 1) != '\0')
					t = 0;

				if (t == 0)
				{
					fprintf(stderr,
					        "%s: AutoRestartRate invalid\n",
					        progname);
					config_free(cfg);
					return EX_CONFIG;
				}

				maxrestartrate_n = n;
				maxrestartrate_t = t;
			}
		}

		if (dofork)
		{
			(void) config_get(cfg, "Background", &dofork,
			                  sizeof dofork);
		}

		(void) config_get(cfg, "TestPublicKeys",
		                  &testpubkeys, sizeof testpubkeys);

		(void) config_get(cfg, "StrictTestMode", &stricttest,
		                  sizeof stricttest);

		(void) config_get(cfg, "MilterDebug", &mdebug, sizeof mdebug);

		if (!gotp)
		{
			(void) config_get(cfg, "Socket", &sock, sizeof sock);
			if (sock != NULL)
			{
				gotp = TRUE;
				(void) smfi_setconn(sock);
			}
		}

		if (pidfile == NULL)
		{
			(void) config_get(cfg, "PidFile", &pidfile,
			                  sizeof pidfile);
		}

		(void) config_get(cfg, "UMask", &filemask, sizeof filemask);

		if (become == NULL)
		{
			(void) config_get(cfg, "Userid", &become,
			                  sizeof become);
		}

		(void) config_get(cfg, "ChangeRootDirectory", &chrootdir,
		                  sizeof chrootdir);
	}

#ifndef SMFIF_QUARANTINE
	if (quarantine)
	{
		fprintf(stderr, "%s: quarantine service not available\n",
		        progname);
		return EX_SOFTWARE;
	}
#endif /* ! SMFIF_QUARANTINE */

	if (!gotp && !testmode)
	{
		fprintf(stderr, "%s: milter socket must be specified\n",
		        progname);
		if (argc == 1)
			fprintf(stderr, "\t(use \"-?\" for help)\n");
		return EX_CONFIG;
	}

	/* suppress a bunch of things if we're in test mode */
	if (testmode)
	{
		curconf->conf_dolog = FALSE;
		curconf->conf_sendreports = FALSE;
		autorestart = FALSE;
		dofork = FALSE;
		become = NULL;
		pidfile = NULL;
		chrootdir = NULL;
	}

	dkimf_setmaxfd();

	/* prepare to change user if appropriate */
	if (become != NULL)
	{
		char *colon;

		/* see if there was a group specified; if so, validate */
		colon = strchr(become, ':');
		if (colon != NULL)
		{
			*colon = '\0';

			gr = getgrnam(colon + 1);
			if (gr == NULL)
			{
				char *q;

				gid = (gid_t) strtol(colon + 1, &q, 10);
				if (*q == '\0')
					gr = getgrgid(gid);

				if (gr == NULL)
				{
					if (curconf->conf_dolog)
					{
						syslog(LOG_ERR,
						       "no such group or gid '%s'",
						       colon + 1);
					}

					fprintf(stderr,
					        "%s: no such group '%s'\n",
					        progname, colon + 1);

					return EX_DATAERR;
				}
			}
		}

		/* validate the user */
		pw = getpwnam(become);
		if (pw == NULL)
		{
			char *q;
			uid_t uid;

			uid = (uid_t) strtoul(become, &q, 10);
			if (*q == '\0')
				pw = getpwuid(uid);

			if (pw == NULL)
			{
				if (curconf->conf_dolog)
				{
					syslog(LOG_ERR,
					       "no such user or uid '%s'",
					       become);
				}

				fprintf(stderr, "%s: no such user '%s'\n",
				        progname, become);

				return EX_DATAERR;
			}
		}

		if (gr == NULL)
			gid = pw->pw_gid;
		else
			gid = gr->gr_gid;

		(void) endpwent();
	}

	/* change root if requested */
	if (chrootdir != NULL)
	{
		/* warn if doing so as root without then giving up root */
		if (become == NULL && getuid() == 0)
		{
			if (curconf->conf_dolog)
			{
				syslog(LOG_WARNING,
				       "using ChangeRootDirectory without Userid not advised");
			}

			fprintf(stderr,
			        "%s: use of ChangeRootDirectory without Userid not advised\n",
			        progname);
		}

		/* change to the new root first */
		if (chdir(chrootdir) != 0)
		{
			if (curconf->conf_dolog)
			{
				syslog(LOG_ERR, "%s: chdir(): %s",
				       chrootdir, strerror(errno));
			}

			fprintf(stderr, "%s: %s: chdir(): %s\n", progname,
			        chrootdir, strerror(errno));
			return EX_OSERR;
		}

		/* now change the root */
		if (chroot(chrootdir) != 0)
		{
			if (curconf->conf_dolog)
			{
				syslog(LOG_ERR, "%s: chroot(): %s",
				       chrootdir, strerror(errno));
			}

			fprintf(stderr, "%s: %s: chroot(): %s\n", progname,
			        chrootdir, strerror(errno));
			return EX_OSERR;
		}
	}

	if (curconf->conf_enablecores)
	{
		_Bool enabled = FALSE;

#ifdef __linux__
		if (prctl(PR_SET_DUMPABLE, 1) == -1)
		{
			if (curconf->conf_dolog)
			{
				syslog(LOG_ERR, "prctl(): %s",
				       strerror(errno));
			}

			fprintf(stderr, "%s: prctl(): %s\n",
			        progname, strerror(errno));
		}
		else
		{
			enabled = TRUE;
		}
#endif /* __linux__ */

		if (!enabled)
		{
			if (curconf->conf_dolog)
			{
				syslog(LOG_WARNING,
				       "can't enable coredumps; continuing");
			}

			fprintf(stderr,
			        "%s: can't enable coredumps; continuing\n",
			        progname);
		}
	}

	die = FALSE;

	if (autorestart)
	{
		_Bool quitloop = FALSE;
		int restarts = 0;
		pid_t pid;
		pid_t wpid;
		struct sigaction sa;

		if (dofork)
		{
			pid = fork();
			switch (pid)
			{
			  case -1:
				if (curconf->conf_dolog)
				{
					int saveerrno;

					saveerrno = errno;

					syslog(LOG_ERR, "fork(): %s",
					       strerror(errno));

					errno = saveerrno;
				}

				fprintf(stderr, "%s: fork(): %s\n",
				        progname, strerror(errno));

				dkimf_zapkey(curconf);
				return EX_OSERR;

			  case 0:
				dkimf_stdio();
				break;

			  default:
				dkimf_zapkey(curconf);
				return EX_OK;
			}
		}

		if (pidfile != NULL)
		{
			f = fopen(pidfile, "w");
			if (f != NULL)
			{
				fprintf(f, "%ld\n", (long) getpid());
				(void) fclose(f);
			}
			else
			{
				if (curconf->conf_dolog)
				{
					syslog(LOG_ERR,
					       "can't write pid to %s: %s",
					       pidfile, strerror(errno));
				}
			}
		}

		sa.sa_handler = dkimf_sighandler;
		/* XXX -- HAHAHAH => sa.sa_sigaction = NULL; */
		sigemptyset(&sa.sa_mask);
		sigaddset(&sa.sa_mask, SIGHUP);
		sigaddset(&sa.sa_mask, SIGINT);
		sigaddset(&sa.sa_mask, SIGTERM);
		sigaddset(&sa.sa_mask, SIGUSR1);
		sa.sa_flags = 0;

		if (sigaction(SIGHUP, &sa, NULL) != 0 ||
		    sigaction(SIGINT, &sa, NULL) != 0 ||
		    sigaction(SIGTERM, &sa, NULL) != 0 ||
		    sigaction(SIGUSR1, &sa, NULL) != 0)
		{
			if (curconf->conf_dolog)
			{
				syslog(LOG_ERR, "[parent] sigaction(): %s",
				       strerror(errno));
			}
		}

		/* now enact the user change */
		if (become != NULL)
		{
			/* make all the process changes */
			if (getuid() != pw->pw_uid)
			{
				/*
				**  Seed the supplementary group list using the
				**  user's primary group from the password
				**  database (pw_gid), so it is always present.
				**  Passing the configured group here instead
				**  would only include the primary group if it
				**  also appears as a named entry in /etc/group,
				**  which is not guaranteed, and could silently
				**  deny access to files owned by it.  setgid()
				**  below still applies the configured gid.
				*/
				if (initgroups(pw->pw_name, pw->pw_gid) != 0)
				{
					if (curconf->conf_dolog)
						syslog(LOG_ERR, "initgroups(): %s", strerror(errno));
					fprintf(stderr, "%s: initgroups(): %s", progname, strerror(errno));
					return EX_NOPERM;
				}
				else if (setgid(gid) != 0)
				{
					if (curconf->conf_dolog)
						syslog(LOG_ERR, "setgid(): %s", strerror(errno));
					fprintf(stderr, "%s: setgid(): %s", progname, strerror(errno));
					return EX_NOPERM;
				}
				else if (setuid(pw->pw_uid) != 0)
				{
					if (curconf->conf_dolog)
						syslog(LOG_ERR, "setuid(): %s", strerror(errno));
					fprintf(stderr, "%s: setuid(): %s", progname, strerror(errno));
					return EX_NOPERM;
				}
			}
		}

		if (maxrestartrate_n > 0)
			dkimf_restart_check(maxrestartrate_n, 0);

		while (!quitloop)
		{
			status = dkimf_socket_cleanup(sock);
			if (status != 0)
			{
				if (curconf->conf_dolog)
				{
					syslog(LOG_ERR,
					       "[parent] socket cleanup failed: %s",
					       strerror(status));
				}
				return EX_UNAVAILABLE;
			}

			pid = fork();
			switch (pid)
			{
			  case -1:
				if (curconf->conf_dolog)
				{
					syslog(LOG_ERR, "fork(): %s",
					       strerror(errno));
				}

				dkimf_zapkey(curconf);
				return EX_OSERR;

			  case 0:
				sa.sa_handler = SIG_DFL;

				if (sigaction(SIGHUP, &sa, NULL) != 0 ||
				    sigaction(SIGINT, &sa, NULL) != 0 ||
				    sigaction(SIGTERM, &sa, NULL) != 0)
				{
					if (curconf->conf_dolog)
					{
						syslog(LOG_ERR,
						       "[child] sigaction(): %s",
						       strerror(errno));
					}
				}

				quitloop = TRUE;
				break;

			  default:
				for (;;)
				{
					wpid = wait(&status);

					if (wpid == -1 && errno == EINTR)
					{
						if (die)
						{
							dkimf_killchild(pid,
							                diesig,
							                curconf->conf_dolog);
							dkimf_zapkey(curconf);

							while (wpid != pid)
								wpid = wait(&status);

							if (pidfile != NULL)
								(void) unlink(pidfile);

							exit(EX_OK);
						}
						else if (reload)
						{
							dkimf_killchild(pid,
							                SIGUSR1,
							                curconf->conf_dolog);

							reload = FALSE;

							continue;
						}
					}

					if (pid != wpid)
						continue;

					if (wpid != -1 && curconf->conf_dolog)
					{
						if (WIFSIGNALED(status))
						{
							syslog(LOG_NOTICE,
							       "terminated with signal %d, restarting",
							       WTERMSIG(status));
						}
						else if (WIFEXITED(status))
						{
							if (WEXITSTATUS(status) == EX_CONFIG ||
							    WEXITSTATUS(status) == EX_SOFTWARE)
							{
								syslog(LOG_NOTICE,
								       "exited with status %d",
								       WEXITSTATUS(status));
								quitloop = TRUE;
							}
							else
							{
								syslog(LOG_NOTICE,
								       "exited with status %d, restarting",
								       WEXITSTATUS(status));
							}
						}
					}

					if (conffile != NULL)
						reload = TRUE;

					break;
				}
				break;
			}

			if (maxrestarts > 0 && restarts >= maxrestarts)
			{
				if (curconf->conf_dolog)
				{
					syslog(LOG_ERR,
					       "maximum restart count exceeded");
				}

				return EX_UNAVAILABLE;
			}

			if (maxrestartrate_n > 0 &&
			    maxrestartrate_t > 0 &&
			    !dkimf_restart_check(0, maxrestartrate_t))
			{
				if (curconf->conf_dolog)
				{
					syslog(LOG_ERR,
					       "maximum restart rate exceeded");
				}

				return EX_UNAVAILABLE;
			}

			restarts++;
		}
	}

	if (!autorestart && dofork)
	{
		pid_t pid;

		pid = fork();
		switch (pid)
		{
		  case -1:
			if (curconf->conf_dolog)
			{
				int saveerrno;

				saveerrno = errno;

				syslog(LOG_ERR, "fork(): %s", strerror(errno));

				errno = saveerrno;
			}

			fprintf(stderr, "%s: fork(): %s\n", progname,
			        strerror(errno));

			dkimf_zapkey(curconf);

			return EX_OSERR;

		  case 0:
			dkimf_stdio();
			break;

		  default:
			dkimf_zapkey(curconf);
			return EX_OK;
		}
	}

	/* write out the pid */
	if (!autorestart && pidfile != NULL)
	{
		f = fopen(pidfile, "w");
		if (f != NULL)
		{
			fprintf(f, "%ld\n", (long) getpid());
			(void) fclose(f);
		}
		else
		{
			if (curconf->conf_dolog)
			{
				syslog(LOG_ERR, "can't write pid to %s: %s",
				       pidfile, strerror(errno));
			}
		}
	}

	/*
	**  Block SIGUSR1 for use of our reload thread, and SIGHUP, SIGINT
	**  and SIGTERM for use of libmilter's signal handling thread.
	*/

	sigemptyset(&sigset);
	sigaddset(&sigset, SIGUSR1);
	sigaddset(&sigset, SIGHUP);
	sigaddset(&sigset, SIGTERM);
	sigaddset(&sigset, SIGINT);
	status = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
	if (status != 0)
	{
		if (curconf->conf_dolog)
		{
			syslog(LOG_ERR, "pthread_sigprocmask(): %s",
			       strerror(status));
		}

		fprintf(stderr, "%s: pthread_sigprocmask(): %s\n", progname,
		        strerror(status));

		dkimf_zapkey(curconf);

		return EX_OSERR;
	}

	/* now enact the user change */
	if (!autorestart && become != NULL)
	{
		/* make all the process changes */
		if (getuid() != pw->pw_uid)
		{
			/*
			**  Seed the supplementary group list using the user's
			**  primary group from the password database (pw_gid),
			**  so it is always present.  Passing the configured
			**  group here instead would only include the primary
			**  group if it also appears as a named entry in
			**  /etc/group, which is not guaranteed, and could
			**  silently deny access to files owned by it.  setgid()
			**  below still applies the configured gid.
			*/
			if (initgroups(pw->pw_name, pw->pw_gid) != 0)
			{
				if (curconf->conf_dolog)
					syslog(LOG_ERR, "initgroups(): %s", strerror(errno));
				fprintf(stderr, "%s: initgroups(): %s", progname, strerror(errno));
				return EX_NOPERM;
			}
			else if (setgid(gid) != 0)
			{
				if (curconf->conf_dolog)
					syslog(LOG_ERR, "setgid(): %s", strerror(errno));
				fprintf(stderr, "%s: setgid(): %s", progname, strerror(errno));
				return EX_NOPERM;
			}
			else if (setuid(pw->pw_uid) != 0)
			{
				if (curconf->conf_dolog)
					syslog(LOG_ERR, "setuid(): %s", strerror(errno));
				fprintf(stderr, "%s: setuid(): %s", progname, strerror(errno));
				return EX_NOPERM;
			}
		}
	}

	/* initialize DKIM library */
	if (!dkimf_config_setlib(curconf, &liberr))
	{
		if (curconf->conf_dolog)
			syslog(LOG_ERR, "can't configure DKIM library: %s",
			       liberr);
		fprintf(stderr, "%s: can't configure DKIM library: %s",
		        progname, liberr);
		return EX_SOFTWARE;
	}

	if (filemask != -1)
		(void) umask((mode_t) filemask);

	if (mdebug > 0)
		(void) smfi_setdbg(mdebug);

	if (!testmode)
	{
		/* try to clean up the socket */
		status = dkimf_socket_cleanup(sock);
		if (status != 0)
		{
			if (curconf->conf_dolog)
			{
				syslog(LOG_ERR, "socket cleanup failed: %s",
				       strerror(status));
			}

			fprintf(stderr, "%s: socket cleanup failed: %s\n",
			        progname, strerror(status));

			dkimf_zapkey(curconf);

			if (!autorestart && pidfile != NULL)
				(void) unlink(pidfile);

			return EX_UNAVAILABLE;
		}

		smfilter.xxfi_flags = SMFIF_ADDHDRS;

#ifdef USE_LUA
		if (curconf->conf_redirect != NULL ||
		    curconf->conf_finalscript != NULL)
#else /* USE_LUA */
		if (curconf->conf_redirect != NULL)
#endif /* USE_LUA */
		{
			smfilter.xxfi_flags |= SMFIF_ADDRCPT;
			smfilter.xxfi_flags |= SMFIF_DELRCPT;
		}

#ifdef SMFIF_SETSYMLIST
		smfilter.xxfi_flags |= SMFIF_SETSYMLIST;
#endif /* SMFIF_SETSYMLIST */

		if (curconf->conf_remarall ||
		    !curconf->conf_keepar ||
		    curconf->conf_rmidentityhdr ||
#ifdef USE_LUA
		    curconf->conf_finalscript != NULL ||
#endif /* USE_LUA */
		    curconf->conf_remsigs)
			smfilter.xxfi_flags |= SMFIF_CHGHDRS;
#ifdef SMFIF_QUARANTINE
#ifdef USE_LUA
		if (curconf->conf_capture || curconf->conf_finalscript != NULL)
#else /* USE_LUA */
		if (curconf->conf_capture)
#endif /* USE_LUA */
			smfilter.xxfi_flags |= SMFIF_QUARANTINE;
#endif /* SMFIF_QUARANTINE */

		/* register with the milter interface */
		if (smfi_register(smfilter) == MI_FAILURE)
		{
			if (curconf->conf_dolog)
				syslog(LOG_ERR, "smfi_register() failed");

			fprintf(stderr, "%s: smfi_register() failed\n",
			        progname);

			dkimf_zapkey(curconf);

			if (!autorestart && pidfile != NULL)
				(void) unlink(pidfile);

			return EX_UNAVAILABLE;
		}

#ifdef HAVE_SMFI_OPENSOCKET
		/* try to establish the milter socket */
		if (smfi_opensocket(FALSE) == MI_FAILURE)
		{
			if (curconf->conf_dolog)
				syslog(LOG_ERR, "smfi_opensocket() failed");

			fprintf(stderr, "%s: smfi_opensocket() failed\n",
			        progname);

			dkimf_zapkey(curconf);

			return EX_UNAVAILABLE;
		}
#endif /* HAVE_SMFI_OPENSOCKET */
	}

	/* initialize libcrypto mutexes */
	if (!curconf->conf_disablecryptoinit)
	{
		status = dkimf_crypto_init();
		if (status != 0)
		{
			fprintf(stderr,
			        "%s: error initializing crypto library: %s\n",
			        progname, strerror(status));
		}
	}

	if ((curconf->conf_mode & DKIMF_MODE_VERIFIER) != 0 &&
	    !dkim_libfeature(curconf->conf_libopendkim, DKIM_FEATURE_SHA256))
	{
		if (curconf->conf_allowsha1only)
		{
			if (dolog)
			{
				syslog(LOG_WARNING,
				       "WARNING: verifier mode operating without rsa-sha256 support");
			}
		}
		else
		{
			if (dolog)
			{
				syslog(LOG_ERR,
				       "verifier mode operating without rsa-sha256 support; terminating");
			}

			fprintf(stderr,
			        "%s: verify mode requires rsa-sha256 support\n",
			        progname);

			if (!autorestart && pidfile != NULL)
				(void) unlink(pidfile);

			return EX_CONFIG;
		}
	}

	/* set up for test mode if selected */
	if (testpubkeys != NULL)
	{
		dkim_query_t qtype = DKIM_QUERY_FILE;

		(void) dkim_setopt(curconf->conf_libopendkim,
		                    DKIM_OPTS_QUERYMETHOD,
		                    &qtype, sizeof qtype);
		(void) dkim_setopt(curconf->conf_libopendkim,
		                    DKIM_OPTS_QUERYINFO,
		                    testpubkeys, strlen(testpubkeys));
	}

	pthread_mutex_init(&conf_lock, NULL);
	pthread_mutex_init(&pwdb_lock, NULL);

	/* perform test mode */
	if (testfile != NULL)
	{
		status = dkimf_testfiles(curconf->conf_libopendkim, testfile,
		                         fixedtime, stricttest, verbose);
		dkim_close(curconf->conf_libopendkim);
		return status;
	}

	memset(argstr, '\0', sizeof argstr);
	end = &argstr[sizeof argstr - 1];
	n = sizeof argstr;
	for (c = 1, p = argstr; c < argc && p < end; c++)
	{
		if (strchr(argv[c], ' ') != NULL)
		{
			status = snprintf(p, (size_t) n, "%s \"%s\"",
			                  c == 1 ? "args:" : "",
			                  argv[c]);
		}
		else
		{
			status = snprintf(p, (size_t) n, "%s %s",
			                  c == 1 ? "args:" : "",
			                  argv[c]);
		}

		p += status;
		n -= status;
	}

	if (curconf->conf_dolog)
	{
		syslog(LOG_INFO, "%s v%s starting%s%s%s", DKIMF_PRODUCT,
		       DKIMF_VERSION,
		       argstr[0] == '\0' ? "" : " (",
		       argstr,
		       argstr[0] == '\0' ? "" : ")");
	}

	/* spawn the SIGUSR1 handler */
	status = pthread_create(&rt, NULL, dkimf_reloader, NULL);
	if (status != 0)
	{
		if (curconf->conf_dolog)
		{
			syslog(LOG_ERR, "pthread_create(): %s",
			       strerror(status));
		}

		if (!autorestart && pidfile != NULL)
			(void) unlink(pidfile);

		return EX_OSERR;
	}

#ifdef HAVE_LIBSYSTEMD
	/*
	**  Start the watchdog keep-alive thread, but only when the unit
	**  actually set WatchdogSec=.  If it did and the thread cannot be
	**  created, refuse to start: running unsupervised would let systemd
	**  kill us at every interval in a silent restart loop, so failing
	**  loudly here lets the start limiter surface the problem instead.
	**  When no watchdog is configured the thread is simply not spawned.
	*/
	{
		uint64_t wdog_usec = 0;

		if (sd_watchdog_enabled(0, &wdog_usec) > 0)
		{
			pthread_t wt;

			status = pthread_create(&wt, NULL, dkimf_watchdog,
			                        NULL);
			if (status != 0)
			{
				if (curconf->conf_dolog)
				{
					syslog(LOG_ERR,
					       "pthread_create() for watchdog: %s",
					       strerror(status));
				}

				fprintf(stderr,
				        "%s: pthread_create() for watchdog: %s\n",
				        progname, strerror(status));

				if (!autorestart && pidfile != NULL)
					(void) unlink(pidfile);

				return EX_OSERR;
			}
		}
	}

	/*
	**  smfi_opensocket() above already bound and listened on the milter
	**  socket, and every fallible startup step (config, the rsa-sha256
	**  capability check, the reloader thread) has now succeeded, so the
	**  service is genuinely ready to accept connections from the MTA.
	**  This is the last point before smfi_main() blocks, which is exactly
	**  where readiness should be announced: signalling any earlier would
	**  risk telling systemd READY=1 only to then exit non-zero.  Under
	**  Type=notify this unblocks units ordered after us; it is a harmless
	**  no-op when the daemon was not started by systemd.
	*/
	(void) sd_notify(0, "READY=1");
#endif /* HAVE_LIBSYSTEMD */

	/* call the milter mainline */
	errno = 0;
	status = smfi_main();

	if (curconf->conf_dolog)
	{
		syslog(LOG_INFO,
		       "%s v%s terminating with status %d, errno = %d",
		       DKIMF_PRODUCT, DKIMF_VERSION, status, errno);
	}

	dkimf_zapkey(curconf);

	/* tell the reloader thread to die */
	die = TRUE;
	(void) raise(SIGUSR1);

	if (!autorestart && pidfile != NULL)
		(void) unlink(pidfile);

	dkimf_crypto_free();

	dkimf_config_free(curconf);

	return status;
}
