int flb_gzip_uncompress(void *in_data, size_t in_len,
                        void **out_data, size_t *out_len)
{
    int status;
    uint8_t *p;
    void *out_buf;
    size_t out_size = 0;
    void *zip_data;
    size_t zip_len;
    unsigned char flg;
    unsigned int xlen, hcrc;
    unsigned int dlen, crc;
    mz_ulong crc_out;
    mz_stream stream;
    const unsigned char *start;

    /* Minimal length: header + crc32 */
    if (in_len < 18) {
        flb_error("[gzip] unexpected content length");
        return -1;
    }

    /* Magic bytes */
    p = in_data;
    if (p[0] != 0x1F || p[1] != 0x8B) {
        flb_error("[gzip] invalid magic bytes");
        return -1;
    }

    if (p[2] != 8) {
        flb_error("[gzip] invalid method");
        return -1;
    }

    /* Flag byte */
    flg = p[3];

    /* Reserved bits */
    if (flg & 0xE0) {
        flb_error("[gzip] invalid flag");
        return -1;
    }

    /* Skip base header of 10 bytes */
    start = p + FLB_GZIP_HEADER_OFFSET;

    /* Skip extra data if present */
    if (flg & FEXTRA) {
        xlen = read_le16(start);
        if (xlen > in_len - 12) {
            flb_error("[gzip] invalid gzip data");
            return -1;
        }
        start += xlen + 2;
    }

    /* Skip file name if present */
    if (flg & FNAME) {
        do {
            if (start - p >= in_len) {
                flb_error("[gzip] invalid gzip data (FNAME)");
                return -1;
            }
        } while (*start++);
    }

    /* Skip file comment if present */
    if (flg & FCOMMENT) {
        do {
            if (start - p >= in_len) {
                flb_error("[gzip] invalid gzip data (FCOMMENT)");
                return -1;
            }
        } while (*start++);
    }

    /* Check header crc if present */
    if (flg & FHCRC) {
        if (start - p > in_len - 2) {
            flb_error("[gzip] invalid gzip data (FHRC)");
            return -1;
        }

        hcrc = read_le16(start);
        crc = mz_crc32(MZ_CRC32_INIT, p, start - p) & 0x0000FFFF;
        if (hcrc != crc) {
            flb_error("[gzip] invalid gzip header CRC");
            return -1;
        }
        start += 2;
    }

    /* Get decompressed length */
    dlen = read_le32(&p[in_len - 4]);

    /* Get CRC32 checksum of original data */
    crc = read_le32(&p[in_len - 8]);

    /* Decompress data */
    if ((p + in_len) - p < 8) {
        flb_error("[gzip] invalid gzip CRC32 checksum");
        return -1;
    }

    /* Allocate outgoing buffer */
    out_buf = flb_malloc(dlen);
    if (!out_buf) {
        flb_errno();
        return -1;
    }
    out_size = dlen;

    /* Map zip content */
    zip_data = (uint8_t *) start;
    zip_len = (p + in_len) - start - 8;

    memset(&stream, 0, sizeof(stream));
    stream.next_in = zip_data;
    stream.avail_in = zip_len;
    stream.next_out = out_buf;
    stream.avail_out = out_size;

    status = mz_inflateInit2(&stream, -Z_DEFAULT_WINDOW_BITS);
    if (status != MZ_OK) {
        flb_free(out_buf);
        return -1;
    }

    status = mz_inflate(&stream, MZ_FINISH);
    if (status != MZ_STREAM_END) {
        mz_inflateEnd(&stream);
        flb_free(out_buf);
        return -1;
    }

    if (stream.total_out != dlen) {
        mz_inflateEnd(&stream);
        flb_free(out_buf);
        flb_error("[gzip] invalid gzip data size");
        return -1;
    }

    /* terminate the stream, it's not longer required */
    mz_inflateEnd(&stream);

    /* Validate message CRC vs inflated data CRC */
    crc_out = mz_crc32(MZ_CRC32_INIT, out_buf, dlen);
    if (crc_out != crc) {
        flb_free(out_buf);
        flb_error("[gzip] invalid GZip checksum (CRC32)");
        return -1;
    }

    /* set the uncompressed data */
    *out_len = dlen;
    *out_data = out_buf;

    return 0;
}


processor_errfd(struct io *io, int evt, void *arg)
{
	const char	*name = arg;
	char		*line = NULL;
	ssize_t		 len;

	switch (evt) {
	case IO_DATAIN:
		while ((line = io_getline(io, &len)) != NULL)
			log_warnx("%s: %s", name, line);
	}
}

smtpd's filter state machine can prematurely release resources
leading to a crash.  From gilles@

struct filter

struct filter_session

static void	filter_protocol_internal(struct filter_session *, uint64_t *, uint64_t, enum filter_phase, const char *);

static void	filter_protocol(uint64_t, enum filter_phase, const char *);

static void	filter_protocol_next(uint64_t, uint64_t, enum filter_phase);

static void	filter_protocol_query(struct filter *, uint64_t, uint64_t, const char *, const char *);

static void	filter_data_internal(struct filter_session *, uint64_t, uint64_t, const char *);

static void	filter_data(uint64_t, const char *);

static void	filter_data_next(uint64_t, uint64_t, const char *);

static void	filter_data_query(struct filter *, uint64_t, uint64_t, const char *);

static int	filter_builtins_notimpl(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_connect(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_helo(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_mail_from(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_rcpt_to(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_data(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_commit(struct filter_session *, struct filter *, uint64_t, const char *);

static void	filter_result_proceed(uint64_t);

static void	filter_result_junk(uint64_t);

static void	filter_result_rewrite(uint64_t, const char *);

static void	filter_result_reject(uint64_t, const char *);

static void	filter_result_disconnect(uint64_t, const char *);

static void	filter_session_io(struct io *, int, void *);

void		lka_filter_process_response(const char *, const char *);

struct filter_session {
	uint64_t	id;
	struct io	*io;

	char *lastparam;

	char *filter_name;
	struct sockaddr_storage ss_src;
	struct sockaddr_storage ss_dest;
	char *rdns;
	int fcrdns;

	char *helo;
	char *username;
	char *mail_from;

	enum filter_phase	phase;
}


filter_builtins_global(struct filter_session *fs, struct filter *filter, uint64_t reqid)
{
	return filter_check_fcrdns(filter, fs->fcrdns) ||
	    filter_check_rdns(filter, fs->rdns) ||
	    filter_check_rdns_table(filter, K_DOMAIN, fs->rdns) ||
	    filter_check_rdns_regex(filter, fs->rdns) ||
	    filter_check_src_table(filter, K_NETADDR, ss_to_text(&fs->ss_src)) ||
	    filter_check_src_regex(filter, ss_to_text(&fs->ss_src)) ||
	    filter_check_helo_table(filter, K_DOMAIN, fs->helo) ||
	    filter_check_helo_regex(filter, fs->helo) ||
	    filter_check_auth(filter, fs->username) ||
	    filter_check_auth_table(filter, K_STRING, fs->username) ||
	    filter_check_auth_table(filter, K_CREDENTIALS, fs->username) ||
	    filter_check_auth_regex(filter, fs->username) ||
	    filter_check_mail_from_table(filter, K_MAILADDR, fs->mail_from) ||
	    filter_check_mail_from_regex(filter, fs->mail_from);
}

struct filter

struct filter_session

static void	filter_protocol_internal(struct filter_session *, uint64_t *, uint64_t, enum filter_phase, const char *);

static void	filter_protocol(uint64_t, enum filter_phase, const char *);

static void	filter_protocol_next(uint64_t, uint64_t, enum filter_phase);

static void	filter_protocol_query(struct filter *, uint64_t, uint64_t, const char *, const char *);

static void	filter_data_internal(struct filter_session *, uint64_t, uint64_t, const char *);

static void	filter_data(uint64_t, const char *);

static void	filter_data_next(uint64_t, uint64_t, const char *);

static void	filter_data_query(struct filter *, uint64_t, uint64_t, const char *);

static int	filter_builtins_notimpl(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_connect(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_helo(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_mail_from(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_rcpt_to(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_data(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_commit(struct filter_session *, struct filter *, uint64_t, const char *);

static void	filter_result_proceed(uint64_t);

static void	filter_result_junk(uint64_t);

static void	filter_result_rewrite(uint64_t, const char *);

static void	filter_result_reject(uint64_t, const char *);

static void	filter_result_disconnect(uint64_t, const char *);

static void	filter_session_io(struct io *, int, void *);

struct filter_session {
	uint64_t	id;
	struct io	*io;

	char *lastparam;

	char *filter_name;
	struct sockaddr_storage ss_src;
	struct sockaddr_storage ss_dest;
	char *rdns;
	int fcrdns;

	char *helo;
	char *username;
	char *mail_from;

	enum filter_phase	phase;
}


filter_data_next(uint64_t token, uint64_t reqid, const char *line)
{
	struct filter_session  *fs;

	/* session can legitimately disappear on a resume */
	if ((fs = tree_get(&sessions, reqid)) == NULL)
		return;

	filter_data_internal(fs, token, reqid, line);
}


filter_protocol(uint64_t reqid, enum filter_phase phase, const char *param)
{
	struct filter_session  *fs;
	uint64_t		token = 0;
	char		       *nparam = NULL;

	fs = tree_xget(&sessions, reqid);

	switch (phase) {
	case FILTER_HELO:
	case FILTER_EHLO:
		free(fs->helo);
		fs->helo = xstrdup(param);
		break;
	case FILTER_MAIL_FROM:
		free(fs->mail_from);
		fs->mail_from = xstrdup(param + 1);
		*strchr(fs->mail_from, '>') = '\0';
		param = fs->mail_from;

		break;
	case FILTER_RCPT_TO:
		nparam = xstrdup(param + 1);
		*strchr(nparam, '>') = '\0';
		param = nparam;
		break;
	case FILTER_STARTTLS:
		/* TBD */
		break;
	default:
		break;
	}

	free(fs->lastparam);
	fs->lastparam = xstrdup(param);

	filter_protocol_internal(fs, &token, reqid, phase, param);
	if (nparam)
		free(nparam);
}


lka_proc_forked(const char *name, uint32_t subsystems, int fd)
{
	struct processor_instance	*processor;

	if (!processors_inited) {
		dict_init(&processors);
		processors_inited = 1;
	}

	processor = xcalloc(1, sizeof *processor);
	processor->name = xstrdup(name);
	processor->io = io_new();
	processor->subsystems = subsystems;

	io_set_nonblocking(fd);

	io_set_fd(processor->io, fd);
	io_set_callback(processor->io, processor_io, processor->name);
	dict_xset(&processors, name, processor);
}

struct filter

struct filter_session

static void	filter_protocol_internal(struct filter_session *, uint64_t *, uint64_t, enum filter_phase, const char *);

static void	filter_protocol(uint64_t, enum filter_phase, const char *);

static void	filter_protocol_query(struct filter *, uint64_t, uint64_t, const char *, const char *);

static void	filter_data_internal(struct filter_session *, uint64_t, uint64_t, const char *);

static void	filter_data(uint64_t, const char *);

static void	filter_data_next(uint64_t, uint64_t, const char *);

static void	filter_data_query(struct filter *, uint64_t, uint64_t, const char *);

static int	filter_builtins_notimpl(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_connect(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_helo(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_mail_from(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_rcpt_to(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_data(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_commit(struct filter_session *, struct filter *, uint64_t, const char *);

static void	filter_result_rewrite(uint64_t, const char *);

static void	filter_result_reject(uint64_t, const char *);

static void	filter_result_disconnect(uint64_t, const char *);

static void	filter_session_io(struct io *, int, void *);

void		lka_filter_process_response(const char *, const char *);

struct filter_session {
	uint64_t	id;
	struct io	*io;

	char *lastparam;

	char *filter_name;
	struct sockaddr_storage ss_src;
	struct sockaddr_storage ss_dest;
	char *rdns;
	int fcrdns;

	char *helo;
	char *username;
	char *mail_from;

	enum filter_phase	phase;
}

static struct filter_exec {
	enum filter_phase	phase;
	const char	       *phase_name;
	int		       (*func)(struct filter_session *, struct filter *, uint64_t, const char *);
} filter_execs[FILTER_PHASES_COUNT] = {
	{ FILTER_CONNECT,	"connect",	filter_builtins_connect },
	{ FILTER_HELO,		"helo",		filter_builtins_helo },
	{ FILTER_EHLO,		"ehlo",		filter_builtins_helo },
	{ FILTER_STARTTLS,     	"starttls",	filter_builtins_notimpl },
	{ FILTER_AUTH,     	"auth",		filter_builtins_notimpl },
	{ FILTER_MAIL_FROM,    	"mail-from",	filter_builtins_mail_from },
	{ FILTER_RCPT_TO,    	"rcpt-to",	filter_builtins_rcpt_to },
	{ FILTER_DATA,    	"data",		filter_builtins_data },
	{ FILTER_DATA_LINE,    	"data-line",   	filter_builtins_notimpl },
	{ FILTER_RSET,    	"rset",		filter_builtins_notimpl },
	{ FILTER_QUIT,    	"quit",		filter_builtins_notimpl },
	{ FILTER_NOOP,    	"noop",		filter_builtins_notimpl },
	{ FILTER_HELP,    	"help",		filter_builtins_notimpl },
	{ FILTER_WIZ,    	"wiz",		filter_builtins_notimpl },
	{ FILTER_COMMIT,    	"commit",      	filter_builtins_commit },
};


processor_io(struct io *io, int evt, void *arg)
{
	struct processor_instance *processor;
	const char		*name = arg;
	char			*line = NULL;
	ssize_t			 len;

	switch (evt) {
	case IO_DATAIN:
		while ((line = io_getline(io, &len)) != NULL) {
			if (strncmp("register|", line, 9) == 0) {
				processor_register(name, line);
				continue;
			}

			processor = dict_xget(&processors, name);
			if (!processor->ready)
				fatalx("Non-register message before register|"
				    "ready: %s", line);
			else if (strncmp(line, "filter-result|", 14) == 0 ||
			    strncmp(line, "filter-dataline|", 16) == 0)
				lka_filter_process_response(name, line);
			else if (strncmp(line, "report|", 7) == 0)
				lka_report_proc(name, line);
			else
				fatalx("Invalid filter message type: %s", line);
		}
	}
}


filter_result_rewrite(uint64_t reqid, const char *param)
{
	m_create(p_pony, IMSG_FILTER_SMTP_PROTOCOL, 0, 0, -1);
	m_add_id(p_pony, reqid);
	m_add_int(p_pony, FILTER_REWRITE);
	m_add_string(p_pony, param);
	m_close(p_pony);
}

static void	filter_protocol_internal(struct filter_session *, uint64_t *, uint64_t, enum filter_phase, const char *);

static void	filter_protocol(uint64_t, enum filter_phase, const char *);

static void	filter_protocol_next(uint64_t, uint64_t, enum filter_phase);

static void	filter_protocol_query(struct filter *, uint64_t, uint64_t, const char *, const char *);

static void	filter_data_internal(struct filter_session *, uint64_t, uint64_t, const char *);

static void	filter_data(uint64_t, const char *);

static void	filter_data_next(uint64_t, uint64_t, const char *);

static void	filter_data_query(struct filter *, uint64_t, uint64_t, const char *);

static int	filter_builtins_notimpl(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_connect(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_helo(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_mail_from(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_rcpt_to(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_data(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_commit(struct filter_session *, struct filter *, uint64_t, const char *);

static void	filter_result_proceed(uint64_t);

static void	filter_result_junk(uint64_t);

static void	filter_result_rewrite(uint64_t, const char *);

static void	filter_result_reject(uint64_t, const char *);

static void	filter_result_disconnect(uint64_t, const char *);

void		lka_filter_process_response(const char *, const char *);

struct filter_session {
	uint64_t	id;
	struct io	*io;

	char *lastparam;

	char *filter_name;
	struct sockaddr_storage ss_src;
	struct sockaddr_storage ss_dest;
	char *rdns;
	int fcrdns;

	char *helo;
	char *username;
	char *mail_from;

	enum filter_phase	phase;
}


lka_report_smtp_link_identify(const char *direction, struct timeval *tv,
    uint64_t reqid, const char *method, const char *heloname)
{
	report_smtp_broadcast(reqid, direction, tv, "link-identify", "%s|%s\n",
	    method, heloname);
}


lka_filter_proc_in_session(uint64_t reqid, const char *proc)
{
	struct filter_session	*fs;
	struct filter		*filter;
	size_t			 i;

	if ((fs = tree_get(&sessions, reqid)) == NULL)
		return 0;

	filter = dict_get(&filters, fs->filter_name);
	if (filter == NULL || (filter->proc == NULL && filter->chain == NULL))
		return 0;

	if (filter->proc)
		return strcmp(filter->proc, proc) == 0 ? 1 : 0;

	for (i = 0; i < filter->chain_size; i++)
		if (filter->chain[i]->proc &&
		    strcmp(filter->chain[i]->proc, proc) == 0)
			return 1;

	return 0;
}


lka_report_smtp_link_auth(const char *direction, struct timeval *tv, uint64_t reqid,
    const char *username, const char *result)
{
	struct filter_session *fs;

	if (strcmp(result, "pass") == 0) {
		fs = tree_xget(&sessions, reqid);
		fs->username = xstrdup(username);
	}
	report_smtp_broadcast(reqid, direction, tv, "link-auth", "%s|%s\n",
	    username, result);
}


lka_filter_end(uint64_t reqid)
{
	struct filter_session	*fs;

	fs = tree_xpop(&sessions, reqid);
	free(fs->rdns);
	free(fs->helo);
	free(fs->mail_from);
	free(fs->username);
	free(fs->lastparam);
	free(fs->filter_name);
	free(fs);
	log_trace(TRACE_FILTERS, "%016"PRIx64" filters session-end", reqid);
}


filter_session_io(struct io *io, int evt, void *arg)
{
	struct filter_session *fs = arg;
	char *line = NULL;
	ssize_t len;

	log_trace(TRACE_IO, "filter session: %p: %s %s", fs, io_strevent(evt),
	    io_strio(io));

	switch (evt) {
	case IO_DATAIN:
	nextline:
		line = io_getline(fs->io, &len);
		/* No complete line received */
		if (line == NULL)
			return;

		filter_data(fs->id, line);

		goto nextline;
	}
}


filter_builtins_mail_from(struct filter_session *fs, struct filter *filter, uint64_t reqid, const char *param)
{
	return filter_builtins_global(fs, filter, reqid);
}


filter_check_auth_table(struct filter *filter, enum table_service kind, const char *key)
{
	int	ret = 0;

	if (filter->config->auth_table == NULL)
		return 0;

	if (key && table_match(filter->config->auth_table, kind, key) > 0)
		ret = 1;

	return filter->config->not_auth_table < 0 ? !ret : ret;
}

struct filter

struct filter_session

static void	filter_protocol_internal(struct filter_session *, uint64_t *, uint64_t, enum filter_phase, const char *);

static void	filter_protocol(uint64_t, enum filter_phase, const char *);

static void	filter_protocol_next(uint64_t, uint64_t, enum filter_phase);

static void	filter_protocol_query(struct filter *, uint64_t, uint64_t, const char *, const char *);

static void	filter_data_internal(struct filter_session *, uint64_t, uint64_t, const char *);

static void	filter_data(uint64_t, const char *);

static void	filter_data_next(uint64_t, uint64_t, const char *);

static void	filter_data_query(struct filter *, uint64_t, uint64_t, const char *);

static int	filter_builtins_notimpl(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_connect(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_helo(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_mail_from(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_rcpt_to(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_data(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_commit(struct filter_session *, struct filter *, uint64_t, const char *);

static void	filter_result_rewrite(uint64_t, const char *);

static void	filter_result_reject(uint64_t, const char *);

static void	filter_result_disconnect(uint64_t, const char *);

static void	filter_session_io(struct io *, int, void *);

void		lka_filter_process_response(const char *, const char *);

struct filter_session {
	uint64_t	id;
	struct io	*io;

	char *lastparam;

	char *filter_name;
	struct sockaddr_storage ss_src;
	struct sockaddr_storage ss_dest;
	char *rdns;
	int fcrdns;

	char *helo;
	char *username;
	char *mail_from;

	enum filter_phase	phase;
}


filter_check_src_table(struct filter *filter, enum table_service kind, const char *key)
{
	int	ret = 0;

	if (filter->config->src_table == NULL)
		return 0;

	if (table_match(filter->config->src_table, kind, key) > 0)
		ret = 1;
	return filter->config->not_src_table < 0 ? !ret : ret;
}


lka_report_smtp_tx_commit(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid, size_t msgsz)
{
	report_smtp_broadcast(reqid, direction, tv, "tx-commit", "%08x|%zd\n",
	    msgid, msgsz);
}


lka_filter_register_hook(const char *name, const char *hook)
{
	struct dict		*subsystem;
	struct filter		*filter;
	const char	*filter_name;
	void		*iter;
	size_t	i;

	if (strncasecmp(hook, "smtp-in|", 8) == 0) {
		subsystem = &filter_smtp_in;
		hook += 8;
	}
	else
		fatalx("Invalid message direction: %s", hook);

	for (i = 0; i < nitems(filter_execs); i++)
		if (strcmp(hook, filter_execs[i].phase_name) == 0)
			break;
	if (i == nitems(filter_execs))
		fatalx("Unrecognized report name: %s", hook);

	iter = NULL;
	while (dict_iter(&filters, &iter, &filter_name, (void **)&filter))
		if (filter->proc && strcmp(name, filter->proc) == 0)
			filter->phases |= (1<<filter_execs[i].phase);
}


filter_check_rdns(struct filter *filter, const char *hostname)
{
	int	ret = 0;
	struct netaddr	netaddr;

	if (!filter->config->rdns)
		return 0;

	/* this is a hack until smtp session properly deals with lack of rdns */
	ret = strcmp("<unknown>", hostname);
	if (ret == 0)
		return filter->config->not_rdns < 0 ? !ret : ret;

	/* if text_to_netaddress succeeds,
	 * we don't have an rDNS so the filter should match
	 */
	ret = !text_to_netaddr(&netaddr, hostname);
	return filter->config->not_rdns < 0 ? !ret : ret;
}


filter_check_rcpt_to_table(struct filter *filter, enum table_service kind, const char *key)
{
	int	ret = 0;

	if (filter->config->rcpt_to_table == NULL)
		return 0;

	if (table_match(filter->config->rcpt_to_table, kind, key) > 0)
		ret = 1;
	return filter->config->not_rcpt_to_table < 0 ? !ret : ret;
}


lka_report_smtp_timeout(const char *direction, struct timeval *tv, uint64_t reqid)
{
	report_smtp_broadcast(reqid, direction, tv, "timeout", "\n");
}


filter_data_query(struct filter *filter, uint64_t token, uint64_t reqid, const char *line)
{
	int	n;
	struct timeval	tv;

	gettimeofday(&tv, NULL);

	n = io_printf(lka_proc_get_io(filter->proc),
	    "filter|%s|%lld.%06ld|smtp-in|data-line|"
	    "%016"PRIx64"|%016"PRIx64"|%s\n",
	    PROTOCOL_VERSION,
	    tv.tv_sec, tv.tv_usec,
	    reqid, token, line);
	if (n == -1)
		fatalx("failed to write to processor");
}

#define	PROTOCOL_VERSION	"0.6"

struct filter

struct filter_session

static void	filter_protocol_internal(struct filter_session *, uint64_t *, uint64_t, enum filter_phase, const char *);

static void	filter_protocol(uint64_t, enum filter_phase, const char *);

static void	filter_protocol_next(uint64_t, uint64_t, enum filter_phase);

static void	filter_protocol_query(struct filter *, uint64_t, uint64_t, const char *, const char *);

static void	filter_data_internal(struct filter_session *, uint64_t, uint64_t, const char *);

static void	filter_data(uint64_t, const char *);

static void	filter_data_next(uint64_t, uint64_t, const char *);

static void	filter_data_query(struct filter *, uint64_t, uint64_t, const char *);

static int	filter_builtins_notimpl(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_connect(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_helo(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_mail_from(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_rcpt_to(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_data(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_commit(struct filter_session *, struct filter *, uint64_t, const char *);

static void	filter_result_proceed(uint64_t);

static void	filter_result_junk(uint64_t);

static void	filter_result_rewrite(uint64_t, const char *);

static void	filter_result_reject(uint64_t, const char *);

static void	filter_result_disconnect(uint64_t, const char *);

static void	filter_session_io(struct io *, int, void *);

void		lka_filter_process_response(const char *, const char *);

struct filter_session {
	uint64_t	id;
	struct io	*io;

	char *lastparam;

	char *filter_name;
	struct sockaddr_storage ss_src;
	struct sockaddr_storage ss_dest;
	char *rdns;
	int fcrdns;

	char *helo;
	char *username;
	char *mail_from;

	enum filter_phase	phase;
}


filter_builtins_connect(struct filter_session *fs, struct filter *filter, uint64_t reqid, const char *param)
{
	return filter_builtins_global(fs, filter, reqid);
}


lka_proc_config(struct processor_instance *pi)
{
	io_printf(pi->io, "config|smtpd-version|%s\n", SMTPD_VERSION);
	io_printf(pi->io, "config|smtp-session-timeout|%d\n", SMTPD_SESSION_TIMEOUT);
	if (pi->subsystems & FILTER_SUBSYSTEM_SMTP_IN)
		io_printf(pi->io, "config|subsystem|smtp-in\n");
	if (pi->subsystems & FILTER_SUBSYSTEM_SMTP_OUT)
		io_printf(pi->io, "config|subsystem|smtp-out\n");
	io_printf(pi->io, "config|admd|%s\n",
	    env->sc_admd != NULL ? env->sc_admd : env->sc_hostname);
	io_printf(pi->io, "config|ready\n");
}

struct filter

struct filter_session

static void	filter_protocol_internal(struct filter_session *, uint64_t *, uint64_t, enum filter_phase, const char *);

static void	filter_protocol_query(struct filter *, uint64_t, uint64_t, const char *, const char *);

static void	filter_data_internal(struct filter_session *, uint64_t, uint64_t, const char *);

static void	filter_data_query(struct filter *, uint64_t, uint64_t, const char *);

static int	filter_builtins_notimpl(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_connect(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_helo(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_mail_from(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_rcpt_to(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_data(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_commit(struct filter_session *, struct filter *, uint64_t, const char *);

static void	filter_session_io(struct io *, int, void *);

struct filter_session {
	uint64_t	id;
	struct io	*io;

	char *lastparam;

	char *filter_name;
	struct sockaddr_storage ss_src;
	struct sockaddr_storage ss_dest;
	char *rdns;
	int fcrdns;

	char *helo;
	char *username;
	char *mail_from;

	enum filter_phase	phase;
}

static struct filter_exec {
	enum filter_phase	phase;
	const char	       *phase_name;
	int		       (*func)(struct filter_session *, struct filter *, uint64_t, const char *);
} filter_execs[FILTER_PHASES_COUNT] = {
	{ FILTER_CONNECT,	"connect",	filter_builtins_connect },
	{ FILTER_HELO,		"helo",		filter_builtins_helo },
	{ FILTER_EHLO,		"ehlo",		filter_builtins_helo },
	{ FILTER_STARTTLS,     	"starttls",	filter_builtins_notimpl },
	{ FILTER_AUTH,     	"auth",		filter_builtins_notimpl },
	{ FILTER_MAIL_FROM,    	"mail-from",	filter_builtins_mail_from },
	{ FILTER_RCPT_TO,    	"rcpt-to",	filter_builtins_rcpt_to },
	{ FILTER_DATA,    	"data",		filter_builtins_data },
	{ FILTER_DATA_LINE,    	"data-line",   	filter_builtins_notimpl },
	{ FILTER_RSET,    	"rset",		filter_builtins_notimpl },
	{ FILTER_QUIT,    	"quit",		filter_builtins_notimpl },
	{ FILTER_NOOP,    	"noop",		filter_builtins_notimpl },
	{ FILTER_HELP,    	"help",		filter_builtins_notimpl },
	{ FILTER_WIZ,    	"wiz",		filter_builtins_notimpl },
	{ FILTER_COMMIT,    	"commit",      	filter_builtins_commit },
};

struct filter {
	uint64_t		id;
	uint32_t		phases;
	const char	       *name;
	const char	       *proc;
	struct filter  	      **chain;
	size_t 			chain_size;
	struct filter_config   *config;
}

static struct dict filters;

struct filter_entry {
	TAILQ_ENTRY(filter_entry)	entries;
	uint64_t			id;
	const char		       *name;
}

struct filter_chain {
	TAILQ_HEAD(, filter_entry)		chain[nitems(filter_execs)];
}

static struct dict	filter_smtp_in;


lka_report_smtp_link_connect(const char *direction, struct timeval *tv, uint64_t reqid, const char *rdns,
    int fcrdns,
    const struct sockaddr_storage *ss_src,
    const struct sockaddr_storage *ss_dest)
{
	struct filter_session *fs;
	char	src[NI_MAXHOST + 5];
	char	dest[NI_MAXHOST + 5];
	uint16_t	src_port = 0;
	uint16_t	dest_port = 0;
	const char     *fcrdns_str;

	if (ss_src->ss_family == AF_INET)
		src_port = ntohs(((const struct sockaddr_in *)ss_src)->sin_port);
	else if (ss_src->ss_family == AF_INET6)
		src_port = ntohs(((const struct sockaddr_in6 *)ss_src)->sin6_port);

	if (ss_dest->ss_family == AF_INET)
		dest_port = ntohs(((const struct sockaddr_in *)ss_dest)->sin_port);
	else if (ss_dest->ss_family == AF_INET6)
		dest_port = ntohs(((const struct sockaddr_in6 *)ss_dest)->sin6_port);

	if (strcmp(ss_to_text(ss_src), "local") == 0) {
		(void)snprintf(src, sizeof src, "unix:%s", SMTPD_SOCKET);
		(void)snprintf(dest, sizeof dest, "unix:%s", SMTPD_SOCKET);
	} else {
		(void)snprintf(src, sizeof src, "%s:%d", ss_to_text(ss_src), src_port);
		(void)snprintf(dest, sizeof dest, "%s:%d", ss_to_text(ss_dest), dest_port);
	}

	switch (fcrdns) {
	case 1:
		fcrdns_str = "pass";
		break;
	case 0:
		fcrdns_str = "fail";
		break;
	default:
		fcrdns_str = "error";
		break;
	}

	fs = tree_xget(&sessions, reqid);
	fs->rdns = xstrdup(rdns);
	fs->fcrdns = fcrdns;
	fs->ss_src = *ss_src;
	fs->ss_dest = *ss_dest;

	report_smtp_broadcast(reqid, direction, tv, "link-connect",
	    "%s|%s|%s|%s\n", rdns, fcrdns_str, src, dest);
}


lka_filter_ready(void)
{
	struct filter  	*filter;
	struct filter  	*subfilter;
	const char	*filter_name;
	struct filter_entry	*filter_entry;
	struct filter_chain	*filter_chain;
	void		*iter;
	size_t		i;
	size_t		j;

	/* all filters are ready, actually build the filter chains */
	iter = NULL;
	while (dict_iter(&filters, &iter, &filter_name, (void **)&filter)) {
		filter_chain = xcalloc(1, sizeof *filter_chain);
		for (i = 0; i < nitems(filter_execs); i++)
			TAILQ_INIT(&filter_chain->chain[i]);
		dict_set(&filter_chains, filter_name, filter_chain);

		if (filter->chain) {
			for (i = 0; i < filter->chain_size; i++) {
				subfilter = filter->chain[i];
				for (j = 0; j < nitems(filter_execs); ++j) {
					if (subfilter->phases & (1<<j)) {
						filter_entry = xcalloc(1, sizeof *filter_entry);
						filter_entry->id = generate_uid();
						filter_entry->name = subfilter->name;
						TAILQ_INSERT_TAIL(&filter_chain->chain[j],
						    filter_entry, entries);
					}
				}
			}
			continue;
		}

		for (i = 0; i < nitems(filter_execs); ++i) {
			if (filter->phases & (1<<i)) {
				filter_entry = xcalloc(1, sizeof *filter_entry);
				filter_entry->id = generate_uid();
				filter_entry->name = filter_name;
				TAILQ_INSERT_TAIL(&filter_chain->chain[i],
				    filter_entry, entries);
			}
		}
	}
}


filter_check_src_regex(struct filter *filter, const char *key)
{
	int	ret = 0;

	if (filter->config->src_regex == NULL)
		return 0;

	if (table_match(filter->config->src_regex, K_REGEX, key) > 0)
		ret = 1;
	return filter->config->not_src_regex < 0 ? !ret : ret;
}


filter_check_rdns_table(struct filter *filter, enum table_service kind, const char *key)
{
	int	ret = 0;

	if (filter->config->rdns_table == NULL)
		return 0;

	if (table_match(filter->config->rdns_table, kind, key) > 0)
		ret = 1;

	return filter->config->not_rdns_table < 0 ? !ret : ret;
}


filter_builtins_commit(struct filter_session *fs, struct filter *filter, uint64_t reqid, const char *param)
{
	return filter_builtins_global(fs, filter, reqid);
}


lka_report_init(void)
{
	struct reporters	*tailq;
	size_t			 i;

	dict_init(&report_smtp_in);
	dict_init(&report_smtp_out);

	for (i = 0; i < nitems(smtp_events); ++i) {
		tailq = xcalloc(1, sizeof (struct reporters));
		TAILQ_INIT(tailq);
		dict_xset(&report_smtp_in, smtp_events[i].event, tailq);

		tailq = xcalloc(1, sizeof (struct reporters));
		TAILQ_INIT(tailq);
		dict_xset(&report_smtp_out, smtp_events[i].event, tailq);
	}
}


filter_check_mail_from_regex(struct filter *filter, const char *key)
{
	int	ret = 0;

	if (filter->config->mail_from_regex == NULL)
		return 0;

	if (table_match(filter->config->mail_from_regex, K_REGEX, key) > 0)
		ret = 1;
	return filter->config->not_mail_from_regex < 0 ? !ret : ret;
}


filter_result_proceed(uint64_t reqid)
{
	m_create(p_pony, IMSG_FILTER_SMTP_PROTOCOL, 0, 0, -1);
	m_add_id(p_pony, reqid);
	m_add_int(p_pony, FILTER_PROCEED);
	m_close(p_pony);
}

static void	filter_protocol_internal(struct filter_session *, uint64_t *, uint64_t, enum filter_phase, const char *);

static void	filter_protocol(uint64_t, enum filter_phase, const char *);

static void	filter_protocol_next(uint64_t, uint64_t, enum filter_phase);

static void	filter_protocol_query(struct filter *, uint64_t, uint64_t, const char *, const char *);

static void	filter_data_internal(struct filter_session *, uint64_t, uint64_t, const char *);

static void	filter_data(uint64_t, const char *);

static void	filter_data_next(uint64_t, uint64_t, const char *);

static void	filter_data_query(struct filter *, uint64_t, uint64_t, const char *);

static int	filter_builtins_notimpl(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_connect(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_helo(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_mail_from(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_rcpt_to(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_data(struct filter_session *, struct filter *, uint64_t, const char *);

static int	filter_builtins_commit(struct filter_session *, struct filter *, uint64_t, const char *);

static void	filter_result_proceed(uint64_t);

static void	filter_result_junk(uint64_t);

static void	filter_result_rewrite(uint64_t, const char *);

static void	filter_result_reject(uint64_t, const char *);

static void	filter_result_disconnect(uint64_t, const char *);

struct filter_session {
	uint64_t	id;
	struct io	*io;

	char *lastparam;

	char *filter_name;
	struct sockaddr_storage ss_src;
	struct sockaddr_storage ss_dest;
	char *rdns;
	int fcrdns;

	char *helo;
	char *username;
	char *mail_from;

	enum filter_phase	phase;
}

static struct filter_exec {
	enum filter_phase	phase;
	const char	       *phase_name;
	int		       (*func)(struct filter_session *, struct filter *, uint64_t, const char *);
} filter_execs[FILTER_PHASES_COUNT] = {
	{ FILTER_CONNECT,	"connect",	filter_builtins_connect },
	{ FILTER_HELO,		"helo",		filter_builtins_helo },
	{ FILTER_EHLO,		"ehlo",		filter_builtins_helo },
	{ FILTER_STARTTLS,     	"starttls",	filter_builtins_notimpl },
	{ FILTER_AUTH,     	"auth",		filter_builtins_notimpl },
	{ FILTER_MAIL_FROM,    	"mail-from",	filter_builtins_mail_from },
	{ FILTER_RCPT_TO,    	"rcpt-to",	filter_builtins_rcpt_to },
	{ FILTER_DATA,    	"data",		filter_builtins_data },
	{ FILTER_DATA_LINE,    	"data-line",   	filter_builtins_notimpl },
	{ FILTER_RSET,    	"rset",		filter_builtins_notimpl },
	{ FILTER_QUIT,    	"quit",		filter_builtins_notimpl },
	{ FILTER_NOOP,    	"noop",		filter_builtins_notimpl },
	{ FILTER_HELP,    	"help",		filter_builtins_notimpl },
	{ FILTER_WIZ,    	"wiz",		filter_builtins_notimpl },
	{ FILTER_COMMIT,    	"commit",      	filter_builtins_commit },
};


lka_filter_data_end(uint64_t reqid)
{
	struct filter_session	*fs;

	fs = tree_xget(&sessions, reqid);
	if (fs->io) {
		io_free(fs->io);
		fs->io = NULL;
	}
	log_trace(TRACE_FILTERS, "%016"PRIx64" filters data-end", reqid);
}


filter_builtins_helo(struct filter_session *fs, struct filter *filter, uint64_t reqid, const char *param)
{
	return filter_builtins_global(fs, filter, reqid);
}


lka_report_smtp_tx_rcpt(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid, const char *address, int ok)
{
	const char *result;

	switch (ok) {
	case 1:
		result = "ok";
		break;
	case 0:
		result = "permfail";
		break;
	default:
		result = "tempfail";
		break;
	}
	report_smtp_broadcast(reqid, direction, tv, "tx-rcpt", "%08x|%s|%s\n",
	    msgid, result, address);
}


lka_filter_begin(uint64_t reqid, const char *filter_name)
{
	struct filter_session	*fs;

	if (!filters_inited) {
		tree_init(&sessions);
		filters_inited = 1;
	}

	fs = xcalloc(1, sizeof (struct filter_session));
	fs->id = reqid;
	fs->filter_name = xstrdup(filter_name);
	tree_xset(&sessions, fs->id, fs);

	log_trace(TRACE_FILTERS, "%016"PRIx64" filters session-begin", reqid);
}


filter_result_reject(uint64_t reqid, const char *message)
{
	m_create(p_pony, IMSG_FILTER_SMTP_PROTOCOL, 0, 0, -1);
	m_add_id(p_pony, reqid);
	m_add_int(p_pony, FILTER_REJECT);
	m_add_string(p_pony, message);
	m_close(p_pony);
}


lka_report_smtp_tx_mail(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid, const char *address, int ok)
{
	const char *result;

	switch (ok) {
	case 1:
		result = "ok";
		break;
	case 0:
		result = "permfail";
		break;
	default:
		result = "tempfail";
		break;
	}
	report_smtp_broadcast(reqid, direction, tv, "tx-mail", "%08x|%s|%s\n",
	    msgid, result, address);
}


lka_report_smtp_tx_begin(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid)
{
	report_smtp_broadcast(reqid, direction, tv, "tx-begin", "%08x\n",
	    msgid);
}


filter_protocol_next(uint64_t token, uint64_t reqid, enum filter_phase phase)
{
	struct filter_session  *fs;

	/* session can legitimately disappear on a resume */
	if ((fs = tree_get(&sessions, reqid)) == NULL)
		return;

	filter_protocol_internal(fs, &token, reqid, phase, fs->lastparam);
}


filter_check_helo_table(struct filter *filter, enum table_service kind, const char *key)
{
	int	ret = 0;

	if (filter->config->helo_table == NULL)
		return 0;

	if (table_match(filter->config->helo_table, kind, key) > 0)
		ret = 1;
	return filter->config->not_helo_table < 0 ? !ret : ret;
}


filter_builtins_rcpt_to(struct filter_session *fs, struct filter *filter, uint64_t reqid, const char *param)
{
	return filter_builtins_global(fs, filter, reqid) ||
	    filter_check_rcpt_to_table(filter, K_MAILADDR, param) ||
	    filter_check_rcpt_to_regex(filter, param);
}


filter_builtins_data(struct filter_session *fs, struct filter *filter, uint64_t reqid, const char *param)
{
	return filter_builtins_global(fs, filter, reqid);
}


lka_report_smtp_tx_reset(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid)
{
	report_smtp_broadcast(reqid, direction, tv, "tx-reset", "%08x\n",
	    msgid);
}


lka_filter_process_response(const char *name, const char *line)
{
	uint64_t reqid;
	uint64_t token;
	char buffer[LINE_MAX];
	char *ep = NULL;
	char *kind = NULL;
	char *qid = NULL;
	/*char *phase = NULL;*/
	char *response = NULL;
	char *parameter = NULL;
	struct filter_session *fs;

	(void)strlcpy(buffer, line, sizeof buffer);
	if ((ep = strchr(buffer, '|')) == NULL)
		fatalx("Missing token: %s", line);
	ep[0] = '\0';

	kind = buffer;

	qid = ep+1;
	if ((ep = strchr(qid, '|')) == NULL)
		fatalx("Missing reqid: %s", line);
	ep[0] = '\0';

	reqid = strtoull(qid, &ep, 16);
	if (qid[0] == '\0' || *ep != '\0')
		fatalx("Invalid reqid: %s", line);
	if (errno == ERANGE && reqid == ULLONG_MAX)
		fatal("Invalid reqid: %s", line);

	qid = ep+1;
	if ((ep = strchr(qid, '|')) == NULL)
		fatal("Missing directive: %s", line);
	ep[0] = '\0';

	token = strtoull(qid, &ep, 16);
	if (qid[0] == '\0' || *ep != '\0')
		fatalx("Invalid token: %s", line);
	if (errno == ERANGE && token == ULLONG_MAX)
		fatal("Invalid token: %s", line);

	response = ep+1;

	/* session can legitimately disappear on a resume */
	if ((fs = tree_get(&sessions, reqid)) == NULL)
		return;

	if (strcmp(kind, "filter-dataline") == 0) {
		if (fs->phase != FILTER_DATA_LINE)
			fatalx("filter-dataline out of dataline phase");
		filter_data_next(token, reqid, response);
		return;
	}
	if (fs->phase == FILTER_DATA_LINE)
		fatalx("filter-result in dataline phase");

	if ((ep = strchr(response, '|'))) {
		parameter = ep + 1;
		ep[0] = '\0';
	}

	if (strcmp(response, "proceed") == 0) {
		if (parameter != NULL)
			fatalx("Unexpected parameter after proceed: %s", line);
		filter_protocol_next(token, reqid, 0);
		return;
	} else if (strcmp(response, "junk") == 0) {
		if (parameter != NULL)
			fatalx("Unexpected parameter after junk: %s", line);
		if (fs->phase == FILTER_COMMIT)
			fatalx("filter-reponse junk after DATA");
		filter_result_junk(reqid);
		return;
	} else {
		if (parameter == NULL)
			fatalx("Missing parameter: %s", line);

		if (strcmp(response, "rewrite") == 0)
			filter_result_rewrite(reqid, parameter);
		else if (strcmp(response, "reject") == 0)
			filter_result_reject(reqid, parameter);
		else if (strcmp(response, "disconnect") == 0)
			filter_result_disconnect(reqid, parameter);
		else
			fatalx("Invalid directive: %s", line);
	}
}


filter_result_junk(uint64_t reqid)
{
	m_create(p_pony, IMSG_FILTER_SMTP_PROTOCOL, 0, 0, -1);
	m_add_id(p_pony, reqid);
	m_add_int(p_pony, FILTER_JUNK);
	m_close(p_pony);
}


filter_check_auth_regex(struct filter *filter, const char *key)
{
	int	ret = 0;

	if (filter->config->auth_regex == NULL)
		return 0;

	if (key && table_match(filter->config->auth_regex, K_REGEX, key) > 0)
		ret = 1;
	return filter->config->not_auth_regex < 0 ? !ret : ret;
}


filter_data_internal(struct filter_session *fs, uint64_t token, uint64_t reqid, const char *line)
{
	struct filter_chain	*filter_chain;
	struct filter_entry	*filter_entry;
	struct filter		*filter;

	if (!token)
		fs->phase = FILTER_DATA_LINE;
	if (fs->phase != FILTER_DATA_LINE)
		fatalx("misbehaving filter");

	/* based on token, identify the filter_entry we should apply  */
	filter_chain = dict_get(&filter_chains, fs->filter_name);
	filter_entry = TAILQ_FIRST(&filter_chain->chain[fs->phase]);
	if (token) {
		TAILQ_FOREACH(filter_entry, &filter_chain->chain[fs->phase], entries)
		    if (filter_entry->id == token)
			    break;
		if (filter_entry == NULL)
			fatalx("misbehaving filter");
		filter_entry = TAILQ_NEXT(filter_entry, entries);
	}

	/* no filter_entry, we either had none or reached end of chain */
	if (filter_entry == NULL) {
		io_printf(fs->io, "%s\n", line);
		return;
	}

	/* pass data to the filter */
	filter = dict_get(&filters, filter_entry->name);
	filter_data_query(filter, filter_entry->id, reqid, line);
}


lka_report_smtp_link_greeting(const char *direction, uint64_t reqid,
    struct timeval *tv, const char *domain)
{
	report_smtp_broadcast(reqid, direction, tv, "link-greeting", "%s\n",
	    domain);
}


lka_filter_data_begin(uint64_t reqid)
{
	struct filter_session  *fs;
	int	sp[2];
	int	fd = -1;

	fs = tree_xget(&sessions, reqid);

	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, sp) == -1)
		goto end;
	io_set_nonblocking(sp[0]);
	io_set_nonblocking(sp[1]);
	fd = sp[0];
	fs->io = io_new();
	io_set_fd(fs->io, sp[1]);
	io_set_callback(fs->io, filter_session_io, fs);

end:
	m_create(p_pony, IMSG_FILTER_SMTP_DATA_BEGIN, 0, 0, fd);
	m_add_id(p_pony, reqid);
	m_add_int(p_pony, fd != -1 ? 1 : 0);
	m_close(p_pony);
	log_trace(TRACE_FILTERS, "%016"PRIx64" filters data-begin fd=%d", reqid, fd);
}


lka_report_proc(const char *name, const char *line)
{
	char buffer[LINE_MAX];
	struct timeval tv;
	char *ep, *sp, *direction;
	uint64_t reqid;

	if (strlcpy(buffer, line + 7, sizeof(buffer)) >= sizeof(buffer))
		fatalx("Invalid report: line too long: %s", line);

	errno = 0;
	tv.tv_sec = strtoll(buffer, &ep, 10);
	if (ep[0] != '.' || errno != 0)
		fatalx("Invalid report: invalid time: %s", line);
	sp = ep + 1;
	tv.tv_usec = strtol(sp, &ep, 10);
	if (ep[0] != '|' || errno != 0)
		fatalx("Invalid report: invalid time: %s", line);
	if (ep - sp != 6)
		fatalx("Invalid report: invalid time: %s", line);

	direction = ep + 1;
	if (strncmp(direction, "smtp-in|", 8) == 0) {
		direction[7] = '\0';
		direction += 7;
#if 0
	} else if (strncmp(direction, "smtp-out|", 9) == 0) {
		direction[8] = '\0';
		direction += 8;
#endif
	} else
		fatalx("Invalid report: invalid direction: %s", line);

	reqid = strtoull(sp, &ep, 16);
	if (ep[0] != '|' || errno != 0)
		fatalx("Invalid report: invalid reqid: %s", line);
	sp = ep + 1;

	lka_report_filter_report(reqid, name, 0, direction, &tv, sp);
}


lka_filter_protocol(uint64_t reqid, enum filter_phase phase, const char *param)
{
	filter_protocol(reqid, phase, param);
}


filter_check_rcpt_to_regex(struct filter *filter, const char *key)
{
	int	ret = 0;

	if (filter->config->rcpt_to_regex == NULL)
		return 0;

	if (table_match(filter->config->rcpt_to_regex, K_REGEX, key) > 0)
		ret = 1;
	return filter->config->not_rcpt_to_regex < 0 ? !ret : ret;
}


processor_register(const char *name, const char *line)
{
	struct processor_instance *processor;

	processor = dict_xget(&processors, name);

	if (strcmp(line, "register|ready") == 0) {
		processor->ready = 1;
		return;
	}

	if (strncmp(line, "register|report|", 16) == 0) {
		lka_report_register_hook(name, line+16);
		return;
	}

	if (strncmp(line, "register|filter|", 16) == 0) {
		lka_filter_register_hook(name, line+16);
		return;
	}

	fatalx("Invalid register line received: %s", line);
}


report_smtp_broadcast(uint64_t reqid, const char *direction, struct timeval *tv, const char *event,
    const char *format, ...)
{
	va_list		ap;
	struct dict	*d;
	struct reporters	*tailq;
	struct reporter_proc	*rp;

	if (strcmp("smtp-in", direction) == 0)
		d = &report_smtp_in;

	else if (strcmp("smtp-out", direction) == 0)
		d = &report_smtp_out;

	else
		fatalx("unexpected direction: %s", direction);

	tailq = dict_xget(d, event);
	TAILQ_FOREACH(rp, tailq, entries) {
		if (!lka_filter_proc_in_session(reqid, rp->name))
			continue;

		va_start(ap, format);
		if (io_printf(lka_proc_get_io(rp->name),
		    "report|%s|%lld.%06ld|%s|%s|%016"PRIx64"%s",
		    PROTOCOL_VERSION, tv->tv_sec, tv->tv_usec, direction,
		    event, reqid, format[0] != '\n' ? "|" : "") == -1 ||
		    io_vprintf(lka_proc_get_io(rp->name), format, ap) == -1)
			fatalx("failed to write to processor");
		va_end(ap);
	}
}


lka_proc_ready(void)
{
	void	*iter;
	struct processor_instance	*pi;

	iter = NULL;
	while (dict_iter(&processors, &iter, NULL, (void **)&pi))
		if (!pi->ready)
			return 0;
	return 1;
}


filter_builtins_notimpl(struct filter_session *fs, struct filter *filter, uint64_t reqid, const char *param)
{
	return 0;
}


filter_check_fcrdns(struct filter *filter, int fcrdns)
{
	int	ret = 0;

	if (!filter->config->fcrdns)
		return 0;

	ret = fcrdns == 1;
	return filter->config->not_fcrdns < 0 ? !ret : ret;
}


filter_check_mail_from_table(struct filter *filter, enum table_service kind, const char *key)
{
	int	ret = 0;

	if (filter->config->mail_from_table == NULL)
		return 0;

	if (table_match(filter->config->mail_from_table, kind, key) > 0)
		ret = 1;
	return filter->config->not_mail_from_table < 0 ? !ret : ret;
}


filter_protocol_query(struct filter *filter, uint64_t token, uint64_t reqid, const char *phase, const char *param)
{
	int	n;
	struct filter_session	*fs;
	struct timeval	tv;

	gettimeofday(&tv, NULL);

	fs = tree_xget(&sessions, reqid);
	if (strcmp(phase, "connect") == 0)
		n = io_printf(lka_proc_get_io(filter->proc),
		    "filter|%s|%lld.%06ld|smtp-in|%s|%016"PRIx64"|%016"PRIx64"|%s|%s\n",
		    PROTOCOL_VERSION,
		    tv.tv_sec, tv.tv_usec,
		    phase, reqid, token, fs->rdns, param);
	else
		n = io_printf(lka_proc_get_io(filter->proc),
		    "filter|%s|%lld.%06ld|smtp-in|%s|%016"PRIx64"|%016"PRIx64"|%s\n",
		    PROTOCOL_VERSION,
		    tv.tv_sec, tv.tv_usec,
		    phase, reqid, token, param);
	if (n == -1)
		fatalx("failed to write to processor");
}


lka_report_smtp_link_disconnect(const char *direction, struct timeval *tv, uint64_t reqid)
{
	report_smtp_broadcast(reqid, direction, tv, "link-disconnect", "\n");
}


lka_report_smtp_tx_data(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid, int ok)
{
	const char *result;

	switch (ok) {
	case 1:
		result = "ok";
		break;
	case 0:
		result = "permfail";
		break;
	default:
		result = "tempfail";
		break;
	}
	report_smtp_broadcast(reqid, direction, tv, "tx-data", "%08x|%s\n",
	    msgid, result);
}


filter_result_disconnect(uint64_t reqid, const char *message)
{
	m_create(p_pony, IMSG_FILTER_SMTP_PROTOCOL, 0, 0, -1);
	m_add_id(p_pony, reqid);
	m_add_int(p_pony, FILTER_DISCONNECT);
	m_add_string(p_pony, message);
	m_close(p_pony);
}


filter_check_helo_regex(struct filter *filter, const char *key)
{
	int	ret = 0;

	if (filter->config->helo_regex == NULL)
		return 0;

	if (table_match(filter->config->helo_regex, K_REGEX, key) > 0)
		ret = 1;
	return filter->config->not_helo_regex < 0 ? !ret : ret;
}


lka_report_register_hook(const char *name, const char *hook)
{
	struct dict	*subsystem;
	struct reporter_proc	*rp;
	struct reporters	*tailq;
	void *iter;
	size_t	i;

	if (strncmp(hook, "smtp-in|", 8) == 0) {
		subsystem = &report_smtp_in;
		hook += 8;
	}
	else if (strncmp(hook, "smtp-out|", 9) == 0) {
		subsystem = &report_smtp_out;
		hook += 9;
	}
	else
		fatalx("Invalid message direction: %s", hook);

	if (strcmp(hook, "*") == 0) {
		iter = NULL;
		while (dict_iter(subsystem, &iter, NULL, (void **)&tailq)) {
			rp = xcalloc(1, sizeof *rp);
			rp->name = xstrdup(name);
			TAILQ_INSERT_TAIL(tailq, rp, entries);
		}
		return;
	}

	for (i = 0; i < nitems(smtp_events); i++)
		if (strcmp(hook, smtp_events[i].event) == 0)
			break;
	if (i == nitems(smtp_events))
		fatalx("Unrecognized report name: %s", hook);

	tailq = dict_get(subsystem, hook);
	rp = xcalloc(1, sizeof *rp);
	rp->name = xstrdup(name);
	TAILQ_INSERT_TAIL(tailq, rp, entries);
}


filter_protocol_internal(struct filter_session *fs, uint64_t *token, uint64_t reqid, enum filter_phase phase, const char *param)
{
	struct filter_chain	*filter_chain;
	struct filter_entry	*filter_entry;
	struct filter		*filter;
	struct timeval		 tv;
	const char		*phase_name = filter_execs[phase].phase_name;
	int			 resume = 1;

	if (!*token) {
		fs->phase = phase;
		resume = 0;
	}

	/* XXX - this sanity check requires a protocol change, stub for now */
	phase = fs->phase;
	if (fs->phase != phase)
		fatalx("misbehaving filter");

	/* based on token, identify the filter_entry we should apply  */
	filter_chain = dict_get(&filter_chains, fs->filter_name);
	filter_entry = TAILQ_FIRST(&filter_chain->chain[fs->phase]);
	if (*token) {
		TAILQ_FOREACH(filter_entry, &filter_chain->chain[fs->phase], entries)
		    if (filter_entry->id == *token)
			    break;
		if (filter_entry == NULL)
			fatalx("misbehaving filter");
		filter_entry = TAILQ_NEXT(filter_entry, entries);
	}

	/* no filter_entry, we either had none or reached end of chain */
	if (filter_entry == NULL) {
		log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, resume=%s, "
		    "action=proceed",
		    fs->id, phase_name, resume ? "y" : "n");
		filter_result_proceed(reqid);
		return;
	}

	/* process param with current filter_entry */
	*token = filter_entry->id;
	filter = dict_get(&filters, filter_entry->name);
	if (filter->proc) {
		log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, "
		    "resume=%s, action=deferred, filter=%s",
		    fs->id, phase_name, resume ? "y" : "n",
		    filter->name);
		filter_protocol_query(filter, filter_entry->id, reqid,
		    filter_execs[fs->phase].phase_name, param);
		return;	/* deferred response */
	}

	if (filter_execs[fs->phase].func(fs, filter, reqid, param)) {
		if (filter->config->rewrite) {
			log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, "
			    "resume=%s, action=rewrite, filter=%s, query=%s, response=%s",
			    fs->id, phase_name, resume ? "y" : "n",
			    filter->name,
			    param,
			    filter->config->rewrite);
			    filter_result_rewrite(reqid, filter->config->rewrite);
			return;
		}
		else if (filter->config->disconnect) {
			log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, "
			    "resume=%s, action=disconnect, filter=%s, query=%s, response=%s",
			    fs->id, phase_name, resume ? "y" : "n",
			    filter->name,
			    param,
			    filter->config->disconnect);
			filter_result_disconnect(reqid, filter->config->disconnect);
			return;
		}
		else if (filter->config->junk) {
			log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, "
			    "resume=%s, action=junk, filter=%s, query=%s",
			    fs->id, phase_name, resume ? "y" : "n",
			    filter->name,
			    param);
			filter_result_junk(reqid);
			return;
		} else if (filter->config->report) {
			log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, "
			    "resume=%s, action=report, filter=%s, query=%s response=%s",
			    fs->id, phase_name, resume ? "y" : "n",
			    filter->name,
			    param, filter->config->report);

			gettimeofday(&tv, NULL);
			lka_report_filter_report(fs->id, filter->name, 1,
			    "smtp-in", &tv, filter->config->report);
		} else if (filter->config->bypass) {
			log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, "
			    "resume=%s, action=bypass, filter=%s, query=%s",
			    fs->id, phase_name, resume ? "y" : "n",
			    filter->name,
			    param);
			filter_result_proceed(reqid);
			return;
		} else {
			log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, "
			    "resume=%s, action=reject, filter=%s, query=%s, response=%s",
			    fs->id, phase_name, resume ? "y" : "n",
			    filter->name,
			    param,
			    filter->config->reject);
			filter_result_reject(reqid, filter->config->reject);
			return;
		}
	}

	log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, "
	    "resume=%s, action=proceed, filter=%s, query=%s",
	    fs->id, phase_name, resume ? "y" : "n",
	    filter->name,
	    param);

	/* filter_entry resulted in proceed, try next filter */
	filter_protocol_internal(fs, token, reqid, phase, param);
	return;
}


filter_check_auth(struct filter *filter, const char *username)
{
	int ret = 0;

	if (!filter->config->auth)
		return 0;

	ret = username ? 1 : 0;

	return filter->config->not_auth < 0 ? !ret : ret;
}


filter_check_rdns_regex(struct filter *filter, const char *key)
{
	int	ret = 0;

	if (filter->config->rdns_regex == NULL)
		return 0;

	if (table_match(filter->config->rdns_regex, K_REGEX, key) > 0)
		ret = 1;
	return filter->config->not_rdns_regex < 0 ? !ret : ret;
}


lka_report_smtp_tx_rollback(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid)
{
	report_smtp_broadcast(reqid, direction, tv, "tx-rollback", "%08x\n",
	    msgid);
}


lka_proc_get_io(const char *name)
{
	struct processor_instance *processor;

	processor = dict_xget(&processors, name);

	return processor->io;
}


lka_report_filter_report(uint64_t reqid, const char *name, int builtin,
    const char *direction, struct timeval *tv, const char *message)
{
	report_smtp_broadcast(reqid, direction, tv, "filter-report",
	    "%s|%s|%s\n", builtin ? "builtin" : "proc",
	    name, message);
}


lka_filter_init(void)
{
	void		*iter;
	const char	*name;
	struct filter  	*filter;
	struct filter_config	*filter_config;
	size_t		i;
	char		 buffer[LINE_MAX];	/* for traces */

	dict_init(&filters);
	dict_init(&filter_chains);

	/* first pass, allocate and init individual filters */
	iter = NULL;
	while (dict_iter(env->sc_filters_dict, &iter, &name, (void **)&filter_config)) {
		switch (filter_config->filter_type) {
		case FILTER_TYPE_BUILTIN:
			filter = xcalloc(1, sizeof(*filter));
			filter->name = name;
			filter->phases |= (1<<filter_config->phase);
			filter->config = filter_config;
			dict_set(&filters, name, filter);
			log_trace(TRACE_FILTERS, "filters init type=builtin, name=%s, hooks=%08x",
			    name, filter->phases);
			break;

		case FILTER_TYPE_PROC:
			filter = xcalloc(1, sizeof(*filter));
			filter->name = name;
			filter->proc = filter_config->proc;
			filter->config = filter_config;
			dict_set(&filters, name, filter);
			log_trace(TRACE_FILTERS, "filters init type=proc, name=%s, proc=%s",
			    name, filter_config->proc);
			break;

		case FILTER_TYPE_CHAIN:
			break;
		}
	}

	/* second pass, allocate and init filter chains but don't build yet */
	iter = NULL;
	while (dict_iter(env->sc_filters_dict, &iter, &name, (void **)&filter_config)) {
		switch (filter_config->filter_type) {
		case FILTER_TYPE_CHAIN:
			filter = xcalloc(1, sizeof(*filter));
			filter->name = name;
			filter->chain = xcalloc(filter_config->chain_size, sizeof(void **));
			filter->chain_size = filter_config->chain_size;
			filter->config = filter_config;

			buffer[0] = '\0';
			for (i = 0; i < filter->chain_size; ++i) {
				filter->chain[i] = dict_xget(&filters, filter_config->chain[i]);
				if (i)
					(void)strlcat(buffer, ", ", sizeof buffer);
				(void)strlcat(buffer, filter->chain[i]->name, sizeof buffer);
			}
			log_trace(TRACE_FILTERS, "filters init type=chain, name=%s { %s }", name, buffer);

			dict_set(&filters, name, filter);
			break;

		case FILTER_TYPE_BUILTIN:
		case FILTER_TYPE_PROC:
			break;
		}
	}
}


lka_report_smtp_tx_envelope(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid, uint64_t evpid)
{
	report_smtp_broadcast(reqid, direction, tv, "tx-envelope",
	    "%08x|%016"PRIx64"\n", msgid, evpid);
}


filter_data(uint64_t reqid, const char *line)
{
	struct filter_session  *fs;

	fs = tree_xget(&sessions, reqid);

	filter_data_internal(fs, 0, reqid, line);
}


lka_report_smtp_protocol_server(const char *direction, struct timeval *tv, uint64_t reqid, const char *response)
{
	report_smtp_broadcast(reqid, direction, tv, "protocol-server", "%s\n",
	    response);
}


lka_proc_errfd(const char *name, int fd)
{
	struct processor_instance	*processor;

	processor = dict_xget(&processors, name);

	io_set_nonblocking(fd);

	processor->errfd = io_new();
	io_set_fd(processor->errfd, fd);
	io_set_callback(processor->errfd, processor_errfd, processor->name);

	lka_proc_config(processor);
}


lka_report_smtp_filter_response(const char *direction, struct timeval *tv, uint64_t reqid,
    int phase, int response, const char *param)
{
	const char *phase_name;
	const char *response_name;

	switch (phase) {
	case FILTER_CONNECT:
		phase_name = "connected";
		break;
	case FILTER_HELO:
		phase_name = "helo";
		break;
	case FILTER_EHLO:
		phase_name = "ehlo";
		break;
	case FILTER_STARTTLS:
		phase_name = "tls";
		break;
	case FILTER_AUTH:
		phase_name = "auth";
		break;
	case FILTER_MAIL_FROM:
		phase_name = "mail-from";
		break;
	case FILTER_RCPT_TO:
		phase_name = "rcpt-to";
		break;
	case FILTER_DATA:
		phase_name = "data";
		break;
	case FILTER_DATA_LINE:
		phase_name = "data-line";
		break;
	case FILTER_RSET:
		phase_name = "rset";
		break;
	case FILTER_QUIT:
		phase_name = "quit";
		break;
	case FILTER_NOOP:
		phase_name = "noop";
		break;
	case FILTER_HELP:
		phase_name = "help";
		break;
	case FILTER_WIZ:
		phase_name = "wiz";
		break;
	case FILTER_COMMIT:
		phase_name = "commit";
		break;
	default:
		phase_name = "";
	}

	switch (response) {
	case FILTER_PROCEED:
		response_name = "proceed";
		break;
	case FILTER_JUNK:
		response_name = "junk";
		break;
	case FILTER_REWRITE:
		response_name = "rewrite";
		break;
	case FILTER_REJECT:
		response_name = "reject";
		break;
	case FILTER_DISCONNECT:
		response_name = "disconnect";
		break;
	default:
		response_name = "";
	}

	report_smtp_broadcast(reqid, direction, tv, "filter-response",
	    "%s|%s%s%s\n", phase_name, response_name, param ? "|" : "",
	    param ? param : "");
}


lka_report_smtp_protocol_client(const char *direction, struct timeval *tv, uint64_t reqid, const char *command)
{
	report_smtp_broadcast(reqid, direction, tv, "protocol-client", "%s\n",
	    command);
}


lka_report_smtp_link_tls(const char *direction, struct timeval *tv, uint64_t reqid, const char *ciphers)
{
	report_smtp_broadcast(reqid, direction, tv, "link-tls", "%s\n",
	    ciphers);
}


ipmi_set_alert_enable(struct ipmi_intf *intf, uint8_t channel, uint8_t enable)
{
	struct channel_access_t channel_access;
	int ccode = 0;
	memset(&channel_access, 0, sizeof(channel_access));
	channel_access.channel = channel;
	ccode = _ipmi_get_channel_access(intf, &channel_access, 0);
	if (eval_ccode(ccode) != 0) {
		lprintf(LOG_ERR,
				"Unable to Get Channel Access(non-volatile) for channel %d",
				channel);
		return (-1);
	}
	if (enable != 0) {
		channel_access.alerting = 1;
	} else {
		channel_access.alerting = 0;
	}
	/* non-volatile */
	ccode = _ipmi_set_channel_access(intf, channel_access, 1, 0);
	if (eval_ccode(ccode) != 0) {
		lprintf(LOG_ERR,
				"Unable to Set Channel Access(non-volatile) for channel %d",
				channel);
		return (-1);
	}
	/* volatile */
	ccode = _ipmi_set_channel_access(intf, channel_access, 2, 0);
	if (eval_ccode(ccode) != 0) {
		lprintf(LOG_ERR,
				"Unable to Set Channel Access(volatile) for channel %d",
				channel);
		return (-1);
	}
	printf("PEF alerts for channel %d %s.\n",
			channel,
			(enable) ? "enabled" : "disabled");
	return 0;
}

lanp: Fix buffer overflows in get_lan_param_select

Partial fix for CVE-2020-5208, see
https://github.com/ipmitool/ipmitool/security/advisories/GHSA-g659-9qxw-p7cp

The `get_lan_param_select` function is missing a validation check on the
response’s `data_len`, which it then returns to caller functions, where
stack buffer overflow can occur.


set_lan_param_wait(struct ipmi_intf * intf, uint8_t chan,
		   int param, uint8_t * data, int len)
{
	struct lan_param * p;
	int retry = 10;		/* 10 retries */

	lprintf(LOG_DEBUG, "Waiting for Set LAN Parameter to complete...");
	if (verbose > 1)
		printbuf(data, len, "SET DATA");

	for (;;) {
		p = get_lan_param(intf, chan, param);
		if (!p) {
			sleep(IPMI_LANP_TIMEOUT);
			if (retry-- == 0)
				return -1;
			continue;
		}
		if (verbose > 1)
			printbuf(p->data, p->data_len, "READ DATA");
		if (p->data_len != len) {
			sleep(IPMI_LANP_TIMEOUT);
			if (retry-- == 0) {
				lprintf(LOG_WARNING, "Mismatched data lengths: %d != %d",
				       p->data_len, len);
				return -1;
			}
			continue;
		}
		if (memcmp(data, p->data, len) != 0) {
			sleep(IPMI_LANP_TIMEOUT);
			if (retry-- == 0) {
				lprintf(LOG_WARNING, "LAN Parameter Data does not match!  "
				       "Write may have failed.");
				return -1;
			}
			continue;
		}
		break;
	}
	return 0;
}


get_cmdline_cipher_suite_priv_data(char * arg, uint8_t * buf)
{
	int i, ret = 0;

	if (strlen(arg) != 15)
	{
		lprintf(LOG_ERR, "Invalid privilege specification length: %d",
			strlen(arg));
		return -1;
	}

	/*
	 * The first byte is reserved (0).  The rest of the buffer is setup
	 * so that each nibble holds the maximum privilege level available for
	 * that cipher suite number.  The number of nibbles (15) matches the number
	 * of fixed cipher suite IDs.  This command documentation mentions 16 IDs
	 * but table 22-19 shows that there are only 15 (0-14).
	 *
	 * data 1 - reserved
	 * data 2 - maximum priv level for first (LSN) and second (MSN) ciphers
	 * data 3 - maximum priv level for third (LSN) and fourth (MSN) ciphers
	 * data 9 - maximum priv level for 15th (LSN) cipher.
	 */
	memset(buf, 0, 9);
	for (i = 0; i < 15; ++i)
	{
		unsigned char priv_level = IPMI_SESSION_PRIV_ADMIN;

		switch (arg[i])
		{
		case 'X':
			priv_level = IPMI_SESSION_PRIV_UNSPECIFIED; /* 0 */
			break;
		case 'c':
			priv_level = IPMI_SESSION_PRIV_CALLBACK;    /* 1 */
			break;
		case 'u':
			priv_level = IPMI_SESSION_PRIV_USER;        /* 2 */
			break;
		case 'o':
			priv_level = IPMI_SESSION_PRIV_OPERATOR;    /* 3 */
			break;
		case 'a':
			priv_level = IPMI_SESSION_PRIV_ADMIN;       /* 4 */
			break;
		case 'O':
			priv_level = IPMI_SESSION_PRIV_OEM;         /* 5 */
			break;
		default:
			lprintf(LOG_ERR, "Invalid privilege specification char: %c",
				arg[i]);
			ret = -1;
			break;
		}

		if (ret != 0)
			break;
		else
		{
			if ((i + 1) % 2)
			{
				// Odd number cipher suites will be in the LSN
				buf[1 + (i / 2)] += priv_level;
			}
			else
			{
				// Even number cipher suites will be in the MSN
				buf[1 + (i / 2)] += (priv_level << 4);
			}
		}
	}

	return ret;
}


ipmi_lan_set_password(struct ipmi_intf *intf,
		uint8_t user_id, const char *password)
{
	int ccode = 0;
	ccode = _ipmi_set_user_password(intf, user_id,
			IPMI_PASSWORD_SET_PASSWORD, password, 0);
	if (eval_ccode(ccode) != 0) {
		lprintf(LOG_ERR, "Unable to Set LAN Password for user %d",
				user_id);
		return (-1);
	}
	/* adjust our session password
	 * or we will no longer be able to communicate with BMC
	 */
	ipmi_intf_session_set_password(intf, (char *)password);
	printf("Password %s for user %d\n",
	       password ? "set" : "cleared", user_id);

	return 0;
}


is_lan_channel(struct ipmi_intf * intf, uint8_t chan)
{
	uint8_t medium;

	if (chan < 1 || chan > IPMI_CHANNEL_NUMBER_MAX)
		return 0;

	medium = ipmi_get_channel_medium(intf, chan);

	if (medium == IPMI_CHANNEL_MEDIUM_LAN ||
	    medium == IPMI_CHANNEL_MEDIUM_LAN_OTHER)
		return 1;

	return 0;
}


ipmi_lanp_lock(struct ipmi_intf * intf, uint8_t chan)
{
	uint8_t val = IPMI_LANP_WRITE_LOCK;
	int retry = 3;

	for (;;) {
		int state = ipmi_lanp_lock_state(intf, chan);
		if (state == -1)
			break;
		if (state == val)
			break;
		if (retry-- == 0)
			break;
		__set_lan_param(intf, chan, IPMI_LANP_SET_IN_PROGRESS,
				&val, 1, 0);
	}
}


ipmi_lan_stats_clear(struct ipmi_intf * intf, uint8_t chan)
{
	int rc = 0;
	struct ipmi_rs * rsp;
	struct ipmi_rq req;
	uint8_t msg_data[2];

	if (!is_lan_channel(intf, chan)) {
		lprintf(LOG_ERR, "Channel %d is not a LAN channel", chan);
		return -1;
	}

	/* From here, we are ready to get the stats */
	msg_data[0] = chan;
	msg_data[1] = 1;   /* Clear */

	memset(&req, 0, sizeof(req));
	req.msg.netfn    = IPMI_NETFN_TRANSPORT;
	req.msg.cmd      = IPMI_LAN_GET_STAT;
	req.msg.data     = msg_data;
	req.msg.data_len = 2;

	rsp = intf->sendrecv(intf, &req);
	if (!rsp) {
		lprintf(LOG_INFO, "Get LAN Stats command failed");
		return (-1);
	}

	if (rsp->ccode) {
		lprintf(LOG_INFO, "Get LAN Stats command failed: %s",
			val2str(rsp->ccode, completion_code_vals));
		return (-1);
	}

	return rc;
}


find_lan_channel(struct ipmi_intf * intf, uint8_t start)
{
	uint8_t chan = 0;

	for (chan = start; chan < IPMI_CHANNEL_NUMBER_MAX; chan++) {
		if (is_lan_channel(intf, chan)) {
			return chan;
		}
	}
	return 0;
}


ipmi_lan_set_vlan_id(struct ipmi_intf *intf,  uint8_t chan, char *string)
{
	struct lan_param *p;
	uint8_t data[2];
	int rc = -1;

	if (!string) { /* request to disable VLAN */
		lprintf(LOG_DEBUG, "Get current VLAN ID from BMC.");
		p = get_lan_param(intf, chan, IPMI_LANP_VLAN_ID);
		if (p && p->data && p->data_len > 1) {
			int id = ((p->data[1] & 0x0f) << 8) + p->data[0];
			if (IPMI_LANP_VLAN_DISABLE == id) {
				printf("VLAN is already disabled for channel %"
				       PRIu8 "\n", chan);
				rc = 0;
				goto out;
			}
			if (!IPMI_LANP_IS_VLAN_VALID(id)) {
				lprintf(LOG_ERR,
				        "Retrieved VLAN ID %i is out of "
				        "range <%d..%d>.",
				        id,
				        IPMI_LANP_VLAN_ID_MIN,
				        IPMI_LANP_VLAN_ID_MAX);
				goto out;
			}
			data[0] = p->data[0];
			data[1] = p->data[1] & 0x0F;
		} else {
			data[0] = 0;
			data[1] = 0;
		}
	}
	else {
		int id = 0;
		if (str2int(string, &id) != 0) {
			lprintf(LOG_ERR,
			        "Given VLAN ID '%s' is invalid.",
			        string);
			goto out;
		}

		if (!IPMI_LANP_IS_VLAN_VALID(id)) {
			lprintf(LOG_NOTICE,
			        "VLAN ID must be between %d and %d.",
			        IPMI_LANP_VLAN_ID_MIN,
			        IPMI_LANP_VLAN_ID_MAX);
			goto out;
		}
		else {
			data[0] = (uint8_t)id;
			data[1] = (uint8_t)(id >> 8) | 0x80;
		}
	}
	rc = set_lan_param(intf, chan, IPMI_LANP_VLAN_ID, data, 2);

out:
	return rc;
}


static char priv_level_to_char(unsigned char priv_level)
{
	char ret = 'X';

	switch (priv_level)
	{
	case IPMI_SESSION_PRIV_CALLBACK:
		ret = 'c';
		break;
	case IPMI_SESSION_PRIV_USER:
		ret = 'u';
		break;
	case IPMI_SESSION_PRIV_OPERATOR:
		ret = 'o';
		break;
	case IPMI_SESSION_PRIV_ADMIN:
		ret = 'a';
		break;
	case IPMI_SESSION_PRIV_OEM:
		ret = 'O';
		break;
	}

 	return ret;
}


__set_lan_param(struct ipmi_intf * intf, uint8_t chan,
		int param, uint8_t * data, int len, int wait)
{
	struct ipmi_rs * rsp;
	struct ipmi_rq req;
	uint8_t msg_data[32];

	if (param < 0)
		return -1;

	msg_data[0] = chan;
	msg_data[1] = param;

	memcpy(&msg_data[2], data, len);
	memset(&req, 0, sizeof(req));
	req.msg.netfn = IPMI_NETFN_TRANSPORT;
	req.msg.cmd = IPMI_LAN_SET_CONFIG;
	req.msg.data = msg_data;
	req.msg.data_len = len+2;

	rsp = intf->sendrecv(intf, &req);
	if (!rsp) {
		lprintf(LOG_ERR, "Set LAN Parameter failed");
		return -1;
	}
	if (rsp->ccode && wait) {
		lprintf(LOG_DEBUG, "Warning: Set LAN Parameter failed: %s",
			val2str(rsp->ccode, completion_code_vals));
		if (rsp->ccode == 0xcc) {
			/* retry hack for invalid data field ccode */
			int retry = 10;		/* 10 retries */
			lprintf(LOG_DEBUG, "Retrying...");
			for (;;) {
				if (retry-- == 0)
					break;
				sleep(IPMI_LANP_TIMEOUT);
				rsp = intf->sendrecv(intf, &req);
				if (!rsp || rsp->ccode)
					continue;
				return set_lan_param_wait(intf, chan, param, data, len);
			}
		}
		else if (rsp->ccode != 0xff) {
			/* let 0xff ccode continue */
			return -1;
		}
	}

	if (!wait)
		return 0;
	return set_lan_param_wait(intf, chan, param, data, len);
}


ipmi_lan_alert_set(struct ipmi_intf * intf, uint8_t chan, uint8_t alert,
		   int argc, char ** argv)
{
	struct lan_param * p;
	uint8_t data[32], temp[32];
	int rc = 0;

	if (argc < 2) {
		print_lan_alert_set_usage();
		return (-1);
	}

	if (strncmp(argv[0], "help", 4) == 0 ||
	    strncmp(argv[1], "help", 4) == 0) {
		print_lan_alert_set_usage();
		return 0;
	}

	memset(data, 0, sizeof(data));
	memset(temp, 0, sizeof(temp));

	/* alert destination ip address */
	if (strncasecmp(argv[0], "ipaddr", 6) == 0 &&
	    (get_cmdline_ipaddr(argv[1], temp) == 0)) {
		/* get current parameter */
		p = get_lan_param_select(intf, chan, IPMI_LANP_DEST_ADDR, alert);
		if (!p) {
			return (-1);
		}
		memcpy(data, p->data, __min(p->data_len, sizeof(data)));
		/* set new ipaddr */
		memcpy(data+3, temp, 4);
		printf("Setting LAN Alert %d IP Address to %d.%d.%d.%d\n", alert,
		       data[3], data[4], data[5], data[6]);
		rc = set_lan_param_nowait(intf, chan, IPMI_LANP_DEST_ADDR, data, p->data_len);
	}
	/* alert destination mac address */
	else if (strncasecmp(argv[0], "macaddr", 7) == 0 &&
		 (str2mac(argv[1], temp) == 0)) {
		/* get current parameter */
		p = get_lan_param_select(intf, chan, IPMI_LANP_DEST_ADDR, alert);
		if (!p) {
			return (-1);
		}
		memcpy(data, p->data, __min(p->data_len, sizeof(data)));
		/* set new macaddr */
		memcpy(data+7, temp, 6);
		printf("Setting LAN Alert %d MAC Address to "
		       "%s\n", alert, mac2str(&data[7]));
		rc = set_lan_param_nowait(intf, chan, IPMI_LANP_DEST_ADDR, data, p->data_len);
	}
	/* alert destination gateway selector */
	else if (strncasecmp(argv[0], "gateway", 7) == 0) {
		/* get current parameter */
		p = get_lan_param_select(intf, chan, IPMI_LANP_DEST_ADDR, alert);
		if (!p) {
			return (-1);
		}
		memcpy(data, p->data, __min(p->data_len, sizeof(data)));

		if (strncasecmp(argv[1], "def", 3) == 0 ||
		    strncasecmp(argv[1], "default", 7) == 0) {
			printf("Setting LAN Alert %d to use Default Gateway\n", alert);
			data[2] = 0;
		}
		else if (strncasecmp(argv[1], "bak", 3) == 0 ||
			 strncasecmp(argv[1], "backup", 6) == 0) {
			printf("Setting LAN Alert %d to use Backup Gateway\n", alert);
			data[2] = 1;
		}
		else {
			print_lan_alert_set_usage();
			return -1;
		}

		rc = set_lan_param_nowait(intf, chan, IPMI_LANP_DEST_ADDR, data, p->data_len);
	}
	/* alert acknowledgement */
	else if (strncasecmp(argv[0], "ack", 3) == 0) {
		/* get current parameter */
		p = get_lan_param_select(intf, chan, IPMI_LANP_DEST_TYPE, alert);
		if (!p) {
			return (-1);
		}
		memcpy(data, p->data, __min(p->data_len, sizeof(data)));

		if (strncasecmp(argv[1], "on", 2) == 0 ||
		    strncasecmp(argv[1], "yes", 3) == 0) {
			printf("Setting LAN Alert %d to Acknowledged\n", alert);
			data[1] |= 0x80;
		}
		else if (strncasecmp(argv[1], "off", 3) == 0 ||
			 strncasecmp(argv[1], "no", 2) == 0) {
			printf("Setting LAN Alert %d to Unacknowledged\n", alert);
			data[1] &= ~0x80;
		}
		else {
			print_lan_alert_set_usage();
			return -1;
		}
		rc = set_lan_param_nowait(intf, chan, IPMI_LANP_DEST_TYPE, data, p->data_len);
	}
	/* alert destination type */
	else if (strncasecmp(argv[0], "type", 4) == 0) {
		/* get current parameter */
		p = get_lan_param_select(intf, chan, IPMI_LANP_DEST_TYPE, alert);
		if (!p) {
			return (-1);
		}
		memcpy(data, p->data, __min(p->data_len, sizeof(data)));

		if (strncasecmp(argv[1], "pet", 3) == 0) {
			printf("Setting LAN Alert %d destination to PET Trap\n", alert);
			data[1] &= ~0x07;
		}
		else if (strncasecmp(argv[1], "oem1", 4) == 0) {
			printf("Setting LAN Alert %d destination to OEM 1\n", alert);
			data[1] &= ~0x07;
			data[1] |= 0x06;
		}
		else if (strncasecmp(argv[1], "oem2", 4) == 0) {
			printf("Setting LAN Alert %d destination to OEM 2\n", alert);
			data[1] |= 0x07;
		}
		else {
			print_lan_alert_set_usage();
			return -1;
		}
		rc = set_lan_param_nowait(intf, chan, IPMI_LANP_DEST_TYPE, data, p->data_len);
	}
	/* alert acknowledge timeout or retry interval */
	else if (strncasecmp(argv[0], "time", 4) == 0) {
		/* get current parameter */
		p = get_lan_param_select(intf, chan, IPMI_LANP_DEST_TYPE, alert);
		if (!p) {
			return (-1);
		}
		memcpy(data, p->data, __min(p->data_len, sizeof(data)));

		if (str2uchar(argv[1], &data[2]) != 0) {
			lprintf(LOG_ERR, "Invalid time: %s", argv[1]);
			return (-1);
		}
		printf("Setting LAN Alert %d timeout/retry to %d seconds\n", alert, data[2]);
		rc = set_lan_param_nowait(intf, chan, IPMI_LANP_DEST_TYPE, data, p->data_len);
	}
	/* number of retries */
	else if (strncasecmp(argv[0], "retry", 5) == 0) {
		/* get current parameter */
		p = get_lan_param_select(intf, chan, IPMI_LANP_DEST_TYPE, alert);
		if (!p) {
			return (-1);
		}
		memcpy(data, p->data, __min(p->data_len, sizeof(data)));

		if (str2uchar(argv[1], &data[3]) != 0) {
			lprintf(LOG_ERR, "Invalid retry: %s", argv[1]);
			return (-1);
		}
		data[3] = data[3] & 0x7;
		printf("Setting LAN Alert %d number of retries to %d\n", alert, data[3]);
		rc = set_lan_param_nowait(intf, chan, IPMI_LANP_DEST_TYPE, data, p->data_len);
	}
	else {
		print_lan_alert_set_usage();
		return -1;
	}

	return rc;
}


lan_set_arp_generate(struct ipmi_intf * intf,
		     uint8_t chan, uint8_t ctl)
{
	struct lan_param *lp;
	uint8_t data;

	lp = get_lan_param(intf, chan, IPMI_LANP_BMC_ARP);
	if (!lp)
		return -1;
	if (!lp->data)
		return -1;
	data = lp->data[0];

	/* set arp generate bitflag */
	if (ctl == 0)
		data &= ~0x1;
	else
		data |= 0x1;

	printf("%sabling BMC-generated Gratuitous ARPs\n", ctl ? "En" : "Dis");
	return set_lan_param(intf, chan, IPMI_LANP_BMC_ARP, &data, 1);
}


ipmi_set_user_access(struct ipmi_intf *intf, uint8_t channel, uint8_t user_id)
{
	struct user_access_t user_access;
	int ccode = 0;
	memset(&user_access, 0, sizeof(user_access));
	user_access.channel = channel;
	user_access.user_id = user_id;
	user_access.privilege_limit = 0x04;

	ccode = _ipmi_set_user_access(intf, &user_access, 1);
	if (eval_ccode(ccode) != 0) {
		lprintf(LOG_ERR, "Set User Access for channel %d failed",
				channel);
		return (-1);
	} else {
		printf("Set User Access for channel %d was successful.",
				channel);
		return 0;
	}
}


ipmi_set_channel_access(struct ipmi_intf *intf, uint8_t channel,
		uint8_t enable)
{
	struct channel_access_t channel_access;
	int ccode = 0;
	memset(&channel_access, 0, sizeof(channel_access));
	channel_access.channel = channel;
	/* Get Non-Volatile Channel Access first */
	ccode = _ipmi_get_channel_access(intf, &channel_access, 0);
	if (eval_ccode(ccode) != 0) {
		lprintf(LOG_ERR,
				"Unable to Get Channel Access(non-volatile) for channel %d",
				channel);
		return (-1);
	}

	if (enable != 0) {
		channel_access.access_mode = 2;
	} else {
		channel_access.access_mode = 0;
	}
	channel_access.privilege_limit = 0x04;
	ccode = _ipmi_set_channel_access(intf, channel_access, 1, 1);
	if (eval_ccode(ccode) != 0) {
		lprintf(LOG_ERR,
				"Unable to Set Channel Access(non-volatile) for channel %d",
				channel);
		return (-1);
	}

	memset(&channel_access, 0, sizeof(channel_access));
	channel_access.channel = channel;
	/* Get Volatile Channel Access */
	ccode = _ipmi_get_channel_access(intf, &channel_access, 1);
	if (eval_ccode(ccode) != 0) {
		lprintf(LOG_ERR,
				"Unable to Get Channel Access(volatile) for channel %d",
				channel);
		return (-1);
	}

	if (enable != 0) {
		channel_access.access_mode = 2;
	} else {
		channel_access.access_mode = 0;
	}
	channel_access.privilege_limit = 0x04;
	ccode = _ipmi_set_channel_access(intf, channel_access, 2, 2);
	if (eval_ccode(ccode) != 0) {
		lprintf(LOG_ERR,
				"Unable to Set Channel Access(volatile) for channel %d",
				channel);
		return (-1);
	}

	/* can't send close session if access off so abort instead */
	if (enable == 0) {
		intf->abort = 1;
	}
	printf("Set Channel Access for channel %d was successful.\n",
			channel);
	return 0;
}


print_lan_set_defgw_usage(void)
{
	lprintf(LOG_NOTICE,
"LAN set default gateway Commands: ipaddr, macaddr");
}


print_lan_usage(void)
{
	lprintf(LOG_NOTICE,
"LAN Commands:");
	lprintf(LOG_NOTICE,
"		   print [<channel number>]");
	lprintf(LOG_NOTICE,
"		   set <channel number> <command> <parameter>");
	lprintf(LOG_NOTICE,
"		   alert print <channel number> <alert destination>");
	lprintf(LOG_NOTICE,
"		   alert set <channel number> <alert destination> <command> <parameter>");
	lprintf(LOG_NOTICE,
"		   stats get [<channel number>]");
	lprintf(LOG_NOTICE,
"		   stats clear [<channel number>]");
}


get_cmdline_ipaddr(char * arg, uint8_t * buf)
{
	uint32_t ip1, ip2, ip3, ip4;
	if (sscanf(arg,
				"%" PRIu32 ".%" PRIu32 ".%" PRIu32 ".%" PRIu32,
				&ip1, &ip2, &ip3, &ip4) != 4) {
		lprintf(LOG_ERR, "Invalid IP address: %s", arg);
		return (-1);
	}
	if (ip1 > UINT8_MAX || ip2 > UINT8_MAX
			|| ip3 > UINT8_MAX || ip4 > UINT8_MAX) {
		lprintf(LOG_ERR, "Invalid IP address: %s", arg);
		return (-1);
	}
	buf[0] = (uint8_t)ip1;
	buf[1] = (uint8_t)ip2;
	buf[2] = (uint8_t)ip3;
	buf[3] = (uint8_t)ip4;
	return 0;
}


print_lan_set_bad_pass_thresh_usage(void)
{
	lprintf(LOG_NOTICE,
"lan set <channel> bad_pass_thresh <thresh_num> <1|0> <reset_interval> <lockout_interval>\n"
"        <thresh_num>         Bad Password Threshold number.\n"
"        <1|0>                1 = generate a Session Audit sensor event.\n"
"                             0 = do not generate an event.\n"
"        <reset_interval>     Attempt Count Reset Interval. In tens of seconds.\n"
"        <lockount_interval>  User Lockout Interval. In tens of seconds.");
}


print_lan_set_access_usage(void)
{
	lprintf(LOG_NOTICE,
"lan set access <on|off>");
}


ipmi_lanp_unlock(struct ipmi_intf * intf, uint8_t chan)
{
	uint8_t val = IPMI_LANP_WRITE_COMMIT;
	int rc;

	rc = __set_lan_param(intf, chan, IPMI_LANP_SET_IN_PROGRESS, &val, 1, 0);
	if (rc < 0) {
		lprintf(LOG_DEBUG, "LAN Parameter Commit not supported");
	}

	val = IPMI_LANP_WRITE_UNLOCK;
	__set_lan_param(intf, chan, IPMI_LANP_SET_IN_PROGRESS, &val, 1, 0);
}


print_lan_set_arp_usage(void)
{
	lprintf(LOG_NOTICE,
"lan set <channel> arp respond <on|off>");
	lprintf(LOG_NOTICE,
"lan set <channel> arp generate <on|off>");
	lprintf(LOG_NOTICE,
"lan set <channel> arp interval <seconds>");
	lprintf(LOG_NOTICE,
"");
	lprintf(LOG_NOTICE,
"example: lan set 7 arp gratuitous off");
}


get_lan_param_select(struct ipmi_intf * intf, uint8_t chan, int param, int select)
{
	struct lan_param * p = NULL;
	struct ipmi_rs * rsp;
	struct ipmi_rq req;
	int i = 0;
	uint8_t msg_data[4];

	for (i = 0; ipmi_lan_params[i].cmd != (-1); i++) {
		if (ipmi_lan_params[i].cmd == param) {
			p = &ipmi_lan_params[i];
			break;
		}
	}

	if (!p) {
		lprintf(LOG_INFO, "Get LAN Parameter failed: Unknown parameter.");
		return NULL;
	}

	msg_data[0] = chan;
	msg_data[1] = p->cmd;
	msg_data[2] = select;
	msg_data[3] = 0;

	memset(&req, 0, sizeof(req));
	req.msg.netfn    = IPMI_NETFN_TRANSPORT;
	req.msg.cmd      = IPMI_LAN_GET_CONFIG;
	req.msg.data     = msg_data;
	req.msg.data_len = 4;

	rsp = intf->sendrecv(intf, &req);
	if (!rsp) {
		lprintf(LOG_INFO, "Get LAN Parameter '%s' command failed", p->desc);
		return NULL;
	}

	switch (rsp->ccode)
	{
	case 0x00: /* successful */
		break;

	case 0x80: /* parameter not supported */
	case 0xc9: /* parameter out of range */
	case 0xcc: /* invalid data field in request */

		/* these completion codes usually mean parameter not supported */
		lprintf(LOG_INFO, "Get LAN Parameter '%s' command failed: %s",
			p->desc, val2str(rsp->ccode, completion_code_vals));
		p->data = NULL;
		p->data_len = 0;
		return p;

	default:

		/* other completion codes are treated as error */
		lprintf(LOG_INFO, "Get LAN Parameter '%s' command failed: %s",
			p->desc, val2str(rsp->ccode, completion_code_vals));
		return NULL;
	}

	p->data = rsp->data + 1;
	p->data_len = rsp->data_len - 1;

	return p;
}


lan_set_arp_interval(struct ipmi_intf * intf, uint8_t chan, uint8_t ival)
{
	struct lan_param *lp;
	uint8_t interval = 0;
	int rc = 0;

	lp = get_lan_param(intf, chan, IPMI_LANP_GRAT_ARP);
	if (!lp)
		return -1;
	if (!lp->data)
		return -1;

	if (ival != 0) {
		if (((UINT8_MAX - 1) / 2) < ival) {
			lprintf(LOG_ERR, "Given ARP interval '%u' is too big.", ival);
			return (-1);
		}
		interval = (ival * 2) - 1;
		rc = set_lan_param(intf, chan, IPMI_LANP_GRAT_ARP, &interval, 1);
	} else {
		interval = lp->data[0];
	}

	printf("BMC-generated Gratuitous ARP interval:  %.1f seconds\n",
	       (float)((interval + 1) / 2));

	return rc;
}


ipmi_lan_alert_print_all(struct ipmi_intf * intf, uint8_t channel)
{
	int j, ndest;
	struct lan_param * p;

	p = get_lan_param(intf, channel, IPMI_LANP_NUM_DEST);
	if (!p)
		return -1;
	if (!p->data)
		return -1;
	ndest = p->data[0] & 0xf;

	for (j=0; j<=ndest; j++) {
		ipmi_lan_alert_print(intf, channel, j);
	}

	return 0;
}


set_lan_param(struct ipmi_intf * intf, uint8_t chan,
	      int param, uint8_t * data, int len)
{
	int rc;
	ipmi_lanp_lock(intf, chan);
	rc = __set_lan_param(intf, chan, param, data, len, 1);
	ipmi_lanp_unlock(intf, chan);
	return rc;
}


print_lan_set_cipher_privs_usage(void)
{
	lprintf(LOG_NOTICE,
"lan set <channel> cipher_privs XXXXXXXXXXXXXXX");
	lprintf(LOG_NOTICE,
"    X = Cipher Suite Unused");
	lprintf(LOG_NOTICE,
"    c = CALLBACK");
	lprintf(LOG_NOTICE,
"    u = USER");
	lprintf(LOG_NOTICE,
"    o = OPERATOR");
	lprintf(LOG_NOTICE,
"    a = ADMIN");
	lprintf(LOG_NOTICE,
"    O = OEM");
	lprintf(LOG_NOTICE,
"");
}


print_lan_set_vlan_usage(void)
{
	lprintf(LOG_NOTICE,
"lan set <channel> vlan id <id>");
	lprintf(LOG_NOTICE,
"lan set <channel> vlan id off");
	lprintf(LOG_NOTICE,
"lan set <channel> vlan priority <priority>");
}


ipmi_lan_alert_print(struct ipmi_intf * intf, uint8_t channel, uint8_t alert)
{
# define PTYPE_LEN	4
# define PADDR_LEN	13
	struct lan_param *lp_ptr = NULL;
	int isack = 0;
	uint8_t ptype[PTYPE_LEN];
	uint8_t paddr[PADDR_LEN];

	lp_ptr = get_lan_param_select(intf, channel, IPMI_LANP_DEST_TYPE, alert);
	if (!lp_ptr || !lp_ptr->data
			|| lp_ptr->data_len < PTYPE_LEN) {
		return (-1);
	}
	memcpy(ptype, lp_ptr->data, PTYPE_LEN);

	lp_ptr = get_lan_param_select(intf, channel, IPMI_LANP_DEST_ADDR, alert);
	if (!lp_ptr || !lp_ptr->data || lp_ptr->data_len < PADDR_LEN) {
		return (-1);
	}
	memcpy(paddr, lp_ptr->data, PADDR_LEN);

	printf("%-24s: %d\n", "Alert Destination",
			ptype[0]);

	if (ptype[1] & 0x80) {
		isack = 1;
	}
	printf("%-24s: %s\n", "Alert Acknowledge",
			isack ? "Acknowledged" : "Unacknowledged");

	printf("%-24s: ", "Destination Type");
	switch (ptype[1] & 0x7) {
	case 0:
		printf("PET Trap\n");
		break;
	case 6:
		printf("OEM 1\n");
		break;
	case 7:
		printf("OEM 2\n");
		break;
	default:
		printf("Unknown\n");
		break;
	}

	printf("%-24s: %d\n",
			isack ? "Acknowledge Timeout" : "Retry Interval",
			ptype[2]);

	printf("%-24s: %d\n", "Number of Retries",
			ptype[3] & 0x7);

	if ((paddr[1] & 0xf0) != 0) {
		/* unknown address format */
		printf("\n");
		return 0;
	}

	printf("%-24s: %s\n", "Alert Gateway",
			(paddr[2] & 1) ? "Backup" : "Default");

	printf("%-24s: %d.%d.%d.%d\n", "Alert IP Address",
			paddr[3], paddr[4], paddr[5], paddr[6]);

	printf("%-24s: %s\n", "Alert MAC Address",
			mac2str(&paddr[7]));

	printf("\n");
	return 0;
}


ipmi_lan_print(struct ipmi_intf * intf, uint8_t chan)
{
	struct lan_param * p;

	if (chan < 1 || chan > IPMI_CHANNEL_NUMBER_MAX) {
		lprintf(LOG_ERR, "Invalid Channel %d", chan);
		return -1;
	}

	/* find type of channel and only accept 802.3 LAN */
	if (!is_lan_channel(intf, chan)) {
		lprintf(LOG_ERR, "Channel %d is not a LAN channel", chan);
		return -1;
	}

	p = get_lan_param(intf, chan, IPMI_LANP_SET_IN_PROGRESS);
	if (!p)
		return -1;
	if (p->data) {
		printf("%-24s: ", p->desc);
		p->data[0] &= 3;
		switch (p->data[0]) {
		case 0:
			printf("Set Complete\n");
			break;
		case 1:
			printf("Set In Progress\n");
			break;
		case 2:
			printf("Commit Write\n");
			break;
		case 3:
			printf("Reserved\n");
			break;
		default:
			printf("Unknown\n");
		}
	}

	p = get_lan_param(intf, chan, IPMI_LANP_AUTH_TYPE);
	if (!p)
		return -1;
	if (p->data) {
		printf("%-24s: %s%s%s%s%s\n", p->desc,
		       (p->data[0] & 1<<IPMI_SESSION_AUTHTYPE_NONE) ? "NONE " : "",
		       (p->data[0] & 1<<IPMI_SESSION_AUTHTYPE_MD2) ? "MD2 " : "",
		       (p->data[0] & 1<<IPMI_SESSION_AUTHTYPE_MD5) ? "MD5 " : "",
		       (p->data[0] & 1<<IPMI_SESSION_AUTHTYPE_PASSWORD) ? "PASSWORD " : "",
		       (p->data[0] & 1<<IPMI_SESSION_AUTHTYPE_OEM) ? "OEM " : "");
	}

	p = get_lan_param(intf, chan, IPMI_LANP_AUTH_TYPE_ENABLE);
	if (!p)
		return -1;
	if (p->data) {
		printf("%-24s: Callback : %s%s%s%s%s\n", p->desc,
		       (p->data[0] & 1<<IPMI_SESSION_AUTHTYPE_NONE) ? "NONE " : "",
		       (p->data[0] & 1<<IPMI_SESSION_AUTHTYPE_MD2) ? "MD2 " : "",
		       (p->data[0] & 1<<IPMI_SESSION_AUTHTYPE_MD5) ? "MD5 " : "",
		       (p->data[0] & 1<<IPMI_SESSION_AUTHTYPE_PASSWORD) ? "PASSWORD " : "",
		       (p->data[0] & 1<<IPMI_SESSION_AUTHTYPE_OEM) ? "OEM " : "");
		printf("%-24s: User     : %s%s%s%s%s\n", "",
		       (p->data[1] & 1<<IPMI_SESSION_AUTHTYPE_NONE) ? "NONE " : "",
		       (p->data[1] & 1<<IPMI_SESSION_AUTHTYPE_MD2) ? "MD2 " : "",
		       (p->data[1] & 1<<IPMI_SESSION_AUTHTYPE_MD5) ? "MD5 " : "",
		       (p->data[1] & 1<<IPMI_SESSION_AUTHTYPE_PASSWORD) ? "PASSWORD " : "",
		       (p->data[1] & 1<<IPMI_SESSION_AUTHTYPE_OEM) ? "OEM " : "");
		printf("%-24s: Operator : %s%s%s%s%s\n", "",
		       (p->data[2] & 1<<IPMI_SESSION_AUTHTYPE_NONE) ? "NONE " : "",
		       (p->data[2] & 1<<IPMI_SESSION_AUTHTYPE_MD2) ? "MD2 " : "",
		       (p->data[2] & 1<<IPMI_SESSION_AUTHTYPE_MD5) ? "MD5 " : "",
		       (p->data[2] & 1<<IPMI_SESSION_AUTHTYPE_PASSWORD) ? "PASSWORD " : "",
		       (p->data[2] & 1<<IPMI_SESSION_AUTHTYPE_OEM) ? "OEM " : "");
		printf("%-24s: Admin    : %s%s%s%s%s\n", "",
		       (p->data[3] & 1<<IPMI_SESSION_AUTHTYPE_NONE) ? "NONE " : "",
		       (p->data[3] & 1<<IPMI_SESSION_AUTHTYPE_MD2) ? "MD2 " : "",
		       (p->data[3] & 1<<IPMI_SESSION_AUTHTYPE_MD5) ? "MD5 " : "",
		       (p->data[3] & 1<<IPMI_SESSION_AUTHTYPE_PASSWORD) ? "PASSWORD " : "",
		       (p->data[3] & 1<<IPMI_SESSION_AUTHTYPE_OEM) ? "OEM " : "");
		printf("%-24s: OEM      : %s%s%s%s%s\n", "",
		       (p->data[4] & 1<<IPMI_SESSION_AUTHTYPE_NONE) ? "NONE " : "",
		       (p->data[4] & 1<<IPMI_SESSION_AUTHTYPE_MD2) ? "MD2 " : "",
		       (p->data[4] & 1<<IPMI_SESSION_AUTHTYPE_MD5) ? "MD5 " : "",
		       (p->data[4] & 1<<IPMI_SESSION_AUTHTYPE_PASSWORD) ? "PASSWORD " : "",
		       (p->data[4] & 1<<IPMI_SESSION_AUTHTYPE_OEM) ? "OEM " : "");
	}

	p = get_lan_param(intf, chan, IPMI_LANP_IP_ADDR_SRC);
	if (!p)
		return -1;
	if (p->data) {
		printf("%-24s: ", p->desc);
		p->data[0] &= 0xf;
		switch (p->data[0]) {
		case 0:
			printf("Unspecified\n");
			break;
		case 1:
			printf("Static Address\n");
			break;
		case 2:
			printf("DHCP Address\n");
			break;
		case 3:
			printf("BIOS Assigned Address\n");
			break;
		default:
			printf("Other\n");
			break;
		}
	}

	p = get_lan_param(intf, chan, IPMI_LANP_IP_ADDR);
	if (!p)
		return -1;
	if (p->data)
		printf("%-24s: %d.%d.%d.%d\n", p->desc,
		       p->data[0], p->data[1], p->data[2], p->data[3]);

	p = get_lan_param(intf, chan, IPMI_LANP_SUBNET_MASK);
	if (!p)
		return -1;
	if (p->data)
		printf("%-24s: %d.%d.%d.%d\n", p->desc,
		       p->data[0], p->data[1], p->data[2], p->data[3]);

	p = get_lan_param(intf, chan, IPMI_LANP_MAC_ADDR);
	if (!p)
		return -1;
	if (p->data)
		printf("%-24s: %s\n", p->desc, mac2str(p->data));

	p = get_lan_param(intf, chan, IPMI_LANP_SNMP_STRING);
	if (!p)
		return -1;
	if (p->data)
		printf("%-24s: %s\n", p->desc, p->data);

	p = get_lan_param(intf, chan, IPMI_LANP_IP_HEADER);
	if (!p)
		return -1;
	if (p->data)
		printf("%-24s: TTL=0x%02x Flags=0x%02x Precedence=0x%02x TOS=0x%02x\n",
		       p->desc, p->data[0], p->data[1] & 0xe0, p->data[2] & 0xe0, p->data[2] & 0x1e);

	p = get_lan_param(intf, chan, IPMI_LANP_BMC_ARP);
	if (!p)
		return -1;
	if (p->data)
		printf("%-24s: ARP Responses %sabled, Gratuitous ARP %sabled\n", p->desc,
		       (p->data[0] & 2) ? "En" : "Dis", (p->data[0] & 1) ? "En" : "Dis");

	p = get_lan_param(intf, chan, IPMI_LANP_GRAT_ARP);
	if (!p)
		return -1;
	if (p->data)
		printf("%-24s: %.1f seconds\n", p->desc, (float)((p->data[0] + 1) / 2));

	p = get_lan_param(intf, chan, IPMI_LANP_DEF_GATEWAY_IP);
	if (!p)
		return -1;
	if (p->data)
		printf("%-24s: %d.%d.%d.%d\n", p->desc,
		       p->data[0], p->data[1], p->data[2], p->data[3]);

	p = get_lan_param(intf, chan, IPMI_LANP_DEF_GATEWAY_MAC);
	if (!p)
		return -1;
	if (p->data)
		printf("%-24s: %s\n", p->desc, mac2str(p->data));

	p = get_lan_param(intf, chan, IPMI_LANP_BAK_GATEWAY_IP);
	if (!p)
		return -1;
	if (p->data)
		printf("%-24s: %d.%d.%d.%d\n", p->desc,
		       p->data[0], p->data[1], p->data[2], p->data[3]);

	p = get_lan_param(intf, chan, IPMI_LANP_BAK_GATEWAY_MAC);
	if (!p)
		return -1;
	if (p->data)
		printf("%-24s: %s\n", p->desc, mac2str(p->data));

	p = get_lan_param(intf, chan, IPMI_LANP_VLAN_ID);
	if (p && p->data) {
		int id = ((p->data[1] & 0x0f) << 8) + p->data[0];
		if (p->data[1] & 0x80)
			printf("%-24s: %d\n", p->desc, id);
		else
			printf("%-24s: Disabled\n", p->desc);
	}

	p = get_lan_param(intf, chan, IPMI_LANP_VLAN_PRIORITY);
	if (p && p->data)
		printf("%-24s: %d\n", p->desc, p->data[0] & 0x07);

	/* Determine supported Cipher Suites -- Requires two calls */
	p = get_lan_param(intf, chan, IPMI_LANP_RMCP_CIPHER_SUPPORT);
	if (!p)
		return -1;
	else if (p->data)
	{
		unsigned char cipher_suite_count = p->data[0];
		p = get_lan_param(intf, chan, IPMI_LANP_RMCP_CIPHERS);
		if (!p)
			return -1;

		printf("%-24s: ", p->desc);

		/* Now we're dangerous.  There are only 15 fixed cipher
		   suite IDs, but the spec allows for 16 in the return data.*/
		if (p->data && p->data_len <= 17)
		{
			unsigned int i;
			for (i = 0; (i < 16) && (i < cipher_suite_count); ++i)
			{
				printf("%s%d",
				       (i > 0? ",": ""),
				       p->data[i + 1]);
			}
			printf("\n");
		}
		else
		{
			printf("None\n");
		}
	}

	/* RMCP+ Messaging Cipher Suite Privilege Levels */
	/* These are the privilege levels for the 15 fixed cipher suites */
	p = get_lan_param(intf, chan, IPMI_LANP_RMCP_PRIV_LEVELS);
	if (!p)
		return -1;
	if (p->data && 9 == p->data_len)
	{
		printf("%-24s: %c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n", p->desc,
		       priv_level_to_char(p->data[1] & 0x0F),
		       priv_level_to_char(p->data[1] >> 4),
		       priv_level_to_char(p->data[2] & 0x0F),
		       priv_level_to_char(p->data[2] >> 4),
		       priv_level_to_char(p->data[3] & 0x0F),
		       priv_level_to_char(p->data[3] >> 4),
		       priv_level_to_char(p->data[4] & 0x0F),
		       priv_level_to_char(p->data[4] >> 4),
		       priv_level_to_char(p->data[5] & 0x0F),
		       priv_level_to_char(p->data[5] >> 4),
		       priv_level_to_char(p->data[6] & 0x0F),
		       priv_level_to_char(p->data[6] >> 4),
		       priv_level_to_char(p->data[7] & 0x0F),
		       priv_level_to_char(p->data[7] >> 4),
		       priv_level_to_char(p->data[8] & 0x0F));

		/* Now print a legend */
		printf("%-24s: %s\n", "", "    X=Cipher Suite Unused");
		printf("%-24s: %s\n", "", "    c=CALLBACK");
		printf("%-24s: %s\n", "", "    u=USER");
		printf("%-24s: %s\n", "", "    o=OPERATOR");
		printf("%-24s: %s\n", "", "    a=ADMIN");
		printf("%-24s: %s\n", "", "    O=OEM");
	}
	else
		printf("%-24s: Not Available\n", p->desc);

	/* Bad Password Threshold */
	p = get_lan_param(intf, chan, IPMI_LANP_BAD_PASS_THRESH);
	if (!p)
		return -1;
	if (p->data && 6 == p->data_len) {
		int tmp;

		printf("%-24s: %d\n", p->desc, p->data[1]);
		printf("%-24s: %s\n", "Invalid password disable",
				p->data[0] & 1 ? "yes" : "no" );
		tmp = p->data[2] + (p->data[3] << 8);
		printf("%-24s: %d\n", "Attempt Count Reset Int.", tmp * 10);
		tmp = p->data[4] + (p->data[5] << 8);
		printf("%-24s: %d\n", "User Lockout Interval", tmp * 10);
	} else {
		printf("%-24s: Not Available\n", p->desc);
	}

	return 0;
}


print_lan_set_snmp_usage(void)
{
	lprintf(LOG_NOTICE,
"lan set <channel> snmp <community string>");
}


print_lan_alert_print_usage(void)
{
	lprintf(LOG_NOTICE,
"");
	lprintf(LOG_NOTICE,
"usage: lan alert print [channel number] [alert destination]");
	lprintf(LOG_NOTICE,
"");
	lprintf(LOG_NOTICE,
"Default will print all alerts for the first found LAN channel");
}


get_lan_param(struct ipmi_intf * intf, uint8_t chan, int param)
{
	return get_lan_param_select(intf, chan, param, 0);
}


ipmi_lan_set_auth(struct ipmi_intf * intf, uint8_t chan, char * level, char * types)
{
	uint8_t data[5];
	uint8_t authtype = 0;
	char * p;
	struct lan_param * lp;

	if (!level || !types)
		return -1;

	lp = get_lan_param(intf, chan, IPMI_LANP_AUTH_TYPE_ENABLE);
	if (!lp)
		return -1;
	if (!lp->data)
		return -1;

	lprintf(LOG_DEBUG, "%-24s: callback=0x%02x user=0x%02x operator=0x%02x admin=0x%02x oem=0x%02x",
		lp->desc, lp->data[0], lp->data[1], lp->data[2], lp->data[3], lp->data[4]);

	memset(data, 0, 5);
	memcpy(data, lp->data, 5);

	p = types;
	while (p) {
		if (strncasecmp(p, "none", 4) == 0)
			authtype |= 1 << IPMI_SESSION_AUTHTYPE_NONE;
		else if (strncasecmp(p, "md2", 3) == 0)
			authtype |= 1 << IPMI_SESSION_AUTHTYPE_MD2;
		else if (strncasecmp(p, "md5", 3) == 0)
			authtype |= 1 << IPMI_SESSION_AUTHTYPE_MD5;
		else if ((strncasecmp(p, "password", 8) == 0) ||
			 (strncasecmp(p, "key", 3) == 0))
			authtype |= 1 << IPMI_SESSION_AUTHTYPE_KEY;
		else if (strncasecmp(p, "oem", 3) == 0)
			authtype |= 1 << IPMI_SESSION_AUTHTYPE_OEM;
		else
			lprintf(LOG_WARNING, "Invalid authentication type: %s", p);
		p = strchr(p, ',');
		if (p)
			p++;
	}

	p = level;
	while (p) {
		if (strncasecmp(p, "callback", 8) == 0)
			data[0] = authtype;
		else if (strncasecmp(p, "user", 4) == 0)
			data[1] = authtype;
		else if (strncasecmp(p, "operator", 8) == 0)
			data[2] = authtype;
		else if (strncasecmp(p, "admin", 5) == 0)
			data[3] = authtype;
		else
			lprintf(LOG_WARNING, "Invalid authentication level: %s", p);
		p = strchr(p, ',');
		if (p)
			p++;
	}

	if (verbose > 1)
		printbuf(data, 5, "authtype data");

	return set_lan_param(intf, chan, IPMI_LANP_AUTH_TYPE_ENABLE, data, 5);
}


print_lan_set_auth_usage(void)
{
	lprintf(LOG_NOTICE,
"lan set <channel> auth <level> <type,type,...>");
	lprintf(LOG_NOTICE,
"  level = CALLBACK, USER, OPERATOR, ADMIN");
	lprintf(LOG_NOTICE,
"  types = NONE, MD2, MD5, PASSWORD, OEM");
	lprintf(LOG_NOTICE,
"example: lan set 7 auth ADMIN PASSWORD,MD5");
}


ipmi_lan_stats_get(struct ipmi_intf * intf, uint8_t chan)
{
	int rc = 0;
	struct ipmi_rs * rsp;
	struct ipmi_rq req;
	uint8_t msg_data[2];
	uint16_t statsTemp;

	if (!is_lan_channel(intf, chan)) {
		lprintf(LOG_ERR, "Channel %d is not a LAN channel", chan);
		return -1;
	}

	/* From here, we are ready to get the stats */

	msg_data[0] = chan;
	msg_data[1] = 0;   /* Don't clear */

	memset(&req, 0, sizeof(req));
	req.msg.netfn    = IPMI_NETFN_TRANSPORT;
	req.msg.cmd      = IPMI_LAN_GET_STAT;
	req.msg.data     = msg_data;
	req.msg.data_len = 2;

	rsp = intf->sendrecv(intf, &req);
	if (!rsp) {
		lprintf(LOG_ERR, "Get LAN Stats command failed");
		return (-1);
	}

	if (rsp->ccode) {
		lprintf(LOG_ERR, "Get LAN Stats command failed: %s",
			val2str(rsp->ccode, completion_code_vals));
		return (-1);
	}

	if (verbose > 1) {
		uint8_t counter;
		printf("--- Rx Stats ---\n");
		for (counter=0; counter<18; counter+=2) {
			printf("%02X", *(rsp->data + counter));
			printf(" %02X - ", *(rsp->data + counter+1));
		}
		printf("\n");
	}

	statsTemp = ((*(rsp->data + 0)) << 8) | (*(rsp->data + 1));
	printf("IP Rx Packet              : %d\n", statsTemp);

	statsTemp = ((*(rsp->data + 2)) << 8) | (*(rsp->data + 3));
	printf("IP Rx Header Errors       : %u\n", statsTemp);

	statsTemp = ((*(rsp->data + 4)) << 8) | (*(rsp->data + 5));
	printf("IP Rx Address Errors      : %u\n", statsTemp);

	statsTemp = ((*(rsp->data + 6)) << 8) | (*(rsp->data + 7));
	printf("IP Rx Fragmented          : %u\n", statsTemp);

	statsTemp = ((*(rsp->data + 8)) << 8) | (*(rsp->data + 9));
	printf("IP Tx Packet              : %u\n", statsTemp);

	statsTemp = ((*(rsp->data +10)) << 8) | (*(rsp->data +11));
	printf("UDP Rx Packet             : %u\n", statsTemp);

	statsTemp = ((*(rsp->data + 12)) << 8) | (*(rsp->data + 13));
	printf("RMCP Rx Valid             : %u\n", statsTemp);

	statsTemp = ((*(rsp->data + 14)) << 8) | (*(rsp->data + 15));
	printf("UDP Proxy Packet Received : %u\n", statsTemp);

	statsTemp = ((*(rsp->data + 16)) << 8) | (*(rsp->data + 17));
	printf("UDP Proxy Packet Dropped  : %u\n", statsTemp);

	return rc;
}