ipfw2.c revision 332762
10SN/A/*
2662Savstepan * Copyright (c) 2002-2003 Luigi Rizzo
30SN/A * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
40SN/A * Copyright (c) 1994 Ugen J.S.Antsilevich
50SN/A *
60SN/A * Idea and grammar partially left from:
7157SN/A * Copyright (c) 1993 Daniel Boulet
80SN/A *
9157SN/A * Redistribution and use in source forms, with and without modification,
100SN/A * are permitted provided that this entire comment appears intact.
110SN/A *
120SN/A * Redistribution in binary form may occur without any restrictions.
130SN/A * Obviously, it would be nice if you gave credit where credit is due
140SN/A * but requiring it would be too onerous.
150SN/A *
160SN/A * This software is provided ``AS IS'' without any warranties of any kind.
170SN/A *
180SN/A * NEW command line interface for IP firewall facility
190SN/A *
200SN/A * $FreeBSD: stable/11/sbin/ipfw/ipfw2.c 332762 2018-04-19 10:05:12Z ae $
21157SN/A */
22157SN/A
23157SN/A#include <sys/types.h>
240SN/A#include <sys/param.h>
250SN/A#include <sys/socket.h>
260SN/A#include <sys/sockio.h>
270SN/A#include <sys/sysctl.h>
280SN/A
290SN/A#include "ipfw2.h"
300SN/A
310SN/A#include <ctype.h>
320SN/A#include <err.h>
330SN/A#include <errno.h>
340SN/A#include <grp.h>
350SN/A#include <netdb.h>
360SN/A#include <pwd.h>
370SN/A#include <stdio.h>
380SN/A#include <stdarg.h>
390SN/A#include <stdint.h>
400SN/A#include <stdlib.h>
410SN/A#include <string.h>
420SN/A#include <sysexits.h>
430SN/A#include <time.h>	/* ctime */
440SN/A#include <timeconv.h>	/* _long_to_time */
450SN/A#include <unistd.h>
460SN/A#include <fcntl.h>
470SN/A#include <stddef.h>	/* offsetof */
480SN/A
490SN/A#include <net/ethernet.h>
500SN/A#include <net/if.h>		/* only IFNAMSIZ */
510SN/A#include <netinet/in.h>
520SN/A#include <netinet/in_systm.h>	/* only n_short, n_long */
530SN/A#include <netinet/ip.h>
540SN/A#include <netinet/ip_icmp.h>
55662Savstepan#include <netinet/ip_fw.h>
560SN/A#include <netinet/tcp.h>
570SN/A#include <arpa/inet.h>
580SN/A
590SN/Astruct cmdline_opts co;	/* global options */
600SN/A
610SN/Astruct format_opts {
620SN/A	int bcwidth;
630SN/A	int pcwidth;
640SN/A	int show_counters;
650SN/A	int show_time;		/* show timestamp */
660SN/A	uint32_t set_mask;	/* enabled sets mask */
670SN/A	uint32_t flags;		/* request flags */
680SN/A	uint32_t first;		/* first rule to request */
690SN/A	uint32_t last;		/* last rule to request */
700SN/A	uint32_t dcnt;		/* number of dynamic states */
710SN/A	ipfw_obj_ctlv *tstate;	/* table state data */
720SN/A};
730SN/A
740SN/Aint resvd_set_number = RESVD_SET;
750SN/A
760SN/Aint ipfw_socket = -1;
770SN/A
780SN/A#define	CHECK_LENGTH(v, len) do {				\
790SN/A	if ((v) < (len))					\
800SN/A		errx(EX_DATAERR, "Rule too long");		\
810SN/A	} while (0)
820SN/A/*
830SN/A * Check if we have enough space in cmd buffer. Note that since
840SN/A * first 8? u32 words are reserved by reserved header, full cmd
850SN/A * buffer can't be used, so we need to protect from buffer overrun
860SN/A * only. At the beginning, cblen is less than actual buffer size by
870SN/A * size of ipfw_insn_u32 instruction + 1 u32 work. This eliminates need
880SN/A * for checking small instructions fitting in given range.
890SN/A * We also (ab)use the fact that ipfw_insn is always the first field
900SN/A * for any custom instruction.
910SN/A */
920SN/A#define	CHECK_CMDLEN	CHECK_LENGTH(cblen, F_LEN((ipfw_insn *)cmd))
930SN/A
940SN/A#define GET_UINT_ARG(arg, min, max, tok, s_x) do {			\
950SN/A	if (!av[0])							\
960SN/A		errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
970SN/A	if (_substrcmp(*av, "tablearg") == 0) {				\
980SN/A		arg = IP_FW_TARG;					\
990SN/A		break;							\
1000SN/A	}								\
1010SN/A									\
1020SN/A	{								\
1030SN/A	long _xval;							\
1040SN/A	char *end;							\
1050SN/A									\
1060SN/A	_xval = strtol(*av, &end, 10);					\
1070SN/A									\
1080SN/A	if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
1090SN/A		errx(EX_DATAERR, "%s: invalid argument: %s",		\
1100SN/A		    match_value(s_x, tok), *av);			\
1110SN/A									\
1120SN/A	if (errno == ERANGE || _xval < min || _xval > max)		\
1130SN/A		errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
1140SN/A		    match_value(s_x, tok), min, max, *av);		\
1150SN/A									\
1160SN/A	if (_xval == IP_FW_TARG)					\
1170SN/A		errx(EX_DATAERR, "%s: illegal argument value: %s",	\
1180SN/A		    match_value(s_x, tok), *av);			\
1190SN/A	arg = _xval;							\
1200SN/A	}								\
1210SN/A} while (0)
1220SN/A
1230SN/Astatic struct _s_x f_tcpflags[] = {
1240SN/A	{ "syn", TH_SYN },
1250SN/A	{ "fin", TH_FIN },
1260SN/A	{ "ack", TH_ACK },
1270SN/A	{ "psh", TH_PUSH },
1280SN/A	{ "rst", TH_RST },
1290SN/A	{ "urg", TH_URG },
1300SN/A	{ "tcp flag", 0 },
1310SN/A	{ NULL,	0 }
1320SN/A};
1330SN/A
1340SN/Astatic struct _s_x f_tcpopts[] = {
1350SN/A	{ "mss",	IP_FW_TCPOPT_MSS },
1360SN/A	{ "maxseg",	IP_FW_TCPOPT_MSS },
1370SN/A	{ "window",	IP_FW_TCPOPT_WINDOW },
1380SN/A	{ "sack",	IP_FW_TCPOPT_SACK },
1390SN/A	{ "ts",		IP_FW_TCPOPT_TS },
1400SN/A	{ "timestamp",	IP_FW_TCPOPT_TS },
1410SN/A	{ "cc",		IP_FW_TCPOPT_CC },
1420SN/A	{ "tcp option",	0 },
1430SN/A	{ NULL,	0 }
1440SN/A};
1450SN/A
1460SN/A/*
1470SN/A * IP options span the range 0 to 255 so we need to remap them
1480SN/A * (though in fact only the low 5 bits are significant).
1490SN/A */
1500SN/Astatic struct _s_x f_ipopts[] = {
1510SN/A	{ "ssrr",	IP_FW_IPOPT_SSRR},
1520SN/A	{ "lsrr",	IP_FW_IPOPT_LSRR},
1530SN/A	{ "rr",		IP_FW_IPOPT_RR},
1540SN/A	{ "ts",		IP_FW_IPOPT_TS},
1550SN/A	{ "ip option",	0 },
1560SN/A	{ NULL,	0 }
1570SN/A};
1580SN/A
1590SN/Astatic struct _s_x f_iptos[] = {
1600SN/A	{ "lowdelay",	IPTOS_LOWDELAY},
1610SN/A	{ "throughput",	IPTOS_THROUGHPUT},
1620SN/A	{ "reliability", IPTOS_RELIABILITY},
1630SN/A	{ "mincost",	IPTOS_MINCOST},
1640SN/A	{ "congestion",	IPTOS_ECN_CE},
1650SN/A	{ "ecntransport", IPTOS_ECN_ECT0},
1660SN/A	{ "ip tos option", 0},
1670SN/A	{ NULL,	0 }
1680SN/A};
1690SN/A
1700SN/Astruct _s_x f_ipdscp[] = {
1710SN/A	{ "af11", IPTOS_DSCP_AF11 >> 2 },	/* 001010 */
1720SN/A	{ "af12", IPTOS_DSCP_AF12 >> 2 },	/* 001100 */
1730SN/A	{ "af13", IPTOS_DSCP_AF13 >> 2 },	/* 001110 */
1740SN/A	{ "af21", IPTOS_DSCP_AF21 >> 2 },	/* 010010 */
1750SN/A	{ "af22", IPTOS_DSCP_AF22 >> 2 },	/* 010100 */
1760SN/A	{ "af23", IPTOS_DSCP_AF23 >> 2 },	/* 010110 */
1770SN/A	{ "af31", IPTOS_DSCP_AF31 >> 2 },	/* 011010 */
1780SN/A	{ "af32", IPTOS_DSCP_AF32 >> 2 },	/* 011100 */
1790SN/A	{ "af33", IPTOS_DSCP_AF33 >> 2 },	/* 011110 */
1800SN/A	{ "af41", IPTOS_DSCP_AF41 >> 2 },	/* 100010 */
1810SN/A	{ "af42", IPTOS_DSCP_AF42 >> 2 },	/* 100100 */
1820SN/A	{ "af43", IPTOS_DSCP_AF43 >> 2 },	/* 100110 */
1830SN/A	{ "be", IPTOS_DSCP_CS0 >> 2 }, 	/* 000000 */
1840SN/A	{ "ef", IPTOS_DSCP_EF >> 2 },	/* 101110 */
1850SN/A	{ "cs0", IPTOS_DSCP_CS0 >> 2 },	/* 000000 */
1860SN/A	{ "cs1", IPTOS_DSCP_CS1 >> 2 },	/* 001000 */
1870SN/A	{ "cs2", IPTOS_DSCP_CS2 >> 2 },	/* 010000 */
1880SN/A	{ "cs3", IPTOS_DSCP_CS3 >> 2 },	/* 011000 */
1890SN/A	{ "cs4", IPTOS_DSCP_CS4 >> 2 },	/* 100000 */
1900SN/A	{ "cs5", IPTOS_DSCP_CS5 >> 2 },	/* 101000 */
1910SN/A	{ "cs6", IPTOS_DSCP_CS6 >> 2 },	/* 110000 */
1920SN/A	{ "cs7", IPTOS_DSCP_CS7 >> 2 },	/* 100000 */
1930SN/A	{ NULL, 0 }
1940SN/A};
1950SN/A
1960SN/Astatic struct _s_x limit_masks[] = {
1970SN/A	{"all",		DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
1980SN/A	{"src-addr",	DYN_SRC_ADDR},
1990SN/A	{"src-port",	DYN_SRC_PORT},
2000SN/A	{"dst-addr",	DYN_DST_ADDR},
2010SN/A	{"dst-port",	DYN_DST_PORT},
2020SN/A	{NULL,		0}
2030SN/A};
2040SN/A
2050SN/A/*
2060SN/A * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
2070SN/A * This is only used in this code.
2080SN/A */
2090SN/A#define IPPROTO_ETHERTYPE	0x1000
2100SN/Astatic struct _s_x ether_types[] = {
2110SN/A    /*
2120SN/A     * Note, we cannot use "-:&/" in the names because they are field
2130SN/A     * separators in the type specifications. Also, we use s = NULL as
2140SN/A     * end-delimiter, because a type of 0 can be legal.
2150SN/A     */
2160SN/A	{ "ip",		0x0800 },
2170SN/A	{ "ipv4",	0x0800 },
2180SN/A	{ "ipv6",	0x86dd },
2190SN/A	{ "arp",	0x0806 },
2200SN/A	{ "rarp",	0x8035 },
2210SN/A	{ "vlan",	0x8100 },
2220SN/A	{ "loop",	0x9000 },
2230SN/A	{ "trail",	0x1000 },
2240SN/A	{ "at",		0x809b },
2250SN/A	{ "atalk",	0x809b },
2260SN/A	{ "aarp",	0x80f3 },
2270SN/A	{ "pppoe_disc",	0x8863 },
2280SN/A	{ "pppoe_sess",	0x8864 },
2290SN/A	{ "ipx_8022",	0x00E0 },
2300SN/A	{ "ipx_8023",	0x0000 },
2310SN/A	{ "ipx_ii",	0x8137 },
2320SN/A	{ "ipx_snap",	0x8137 },
2330SN/A	{ "ipx",	0x8137 },
2340SN/A	{ "ns",		0x0600 },
2350SN/A	{ NULL,		0 }
2360SN/A};
2370SN/A
2380SN/Astatic struct _s_x rule_eactions[] = {
2390SN/A	{ "nat64lsn",		TOK_NAT64LSN },
2400SN/A	{ "nat64stl",		TOK_NAT64STL },
2410SN/A	{ "nptv6",		TOK_NPTV6 },
2420SN/A	{ "tcp-setmss",		TOK_TCPSETMSS },
2430SN/A	{ NULL, 0 }	/* terminator */
2440SN/A};
2450SN/A
2460SN/Astatic struct _s_x rule_actions[] = {
2470SN/A	{ "abort6",		TOK_ABORT6 },
2480SN/A	{ "abort",		TOK_ABORT },
2490SN/A	{ "accept",		TOK_ACCEPT },
2500SN/A	{ "pass",		TOK_ACCEPT },
2510SN/A	{ "allow",		TOK_ACCEPT },
2520SN/A	{ "permit",		TOK_ACCEPT },
2530SN/A	{ "count",		TOK_COUNT },
2540SN/A	{ "pipe",		TOK_PIPE },
2550SN/A	{ "queue",		TOK_QUEUE },
2560SN/A	{ "divert",		TOK_DIVERT },
2570SN/A	{ "tee",		TOK_TEE },
2580SN/A	{ "netgraph",		TOK_NETGRAPH },
2590SN/A	{ "ngtee",		TOK_NGTEE },
2600SN/A	{ "fwd",		TOK_FORWARD },
2610SN/A	{ "forward",		TOK_FORWARD },
2620SN/A	{ "skipto",		TOK_SKIPTO },
2630SN/A	{ "deny",		TOK_DENY },
2640SN/A	{ "drop",		TOK_DENY },
2650SN/A	{ "reject",		TOK_REJECT },
2660SN/A	{ "reset6",		TOK_RESET6 },
2670SN/A	{ "reset",		TOK_RESET },
2680SN/A	{ "unreach6",		TOK_UNREACH6 },
2690SN/A	{ "unreach",		TOK_UNREACH },
2700SN/A	{ "check-state",	TOK_CHECKSTATE },
2710SN/A	{ "//",			TOK_COMMENT },
2720SN/A	{ "nat",		TOK_NAT },
2730SN/A	{ "reass",		TOK_REASS },
2740SN/A	{ "setfib",		TOK_SETFIB },
2750SN/A	{ "setdscp",		TOK_SETDSCP },
2760SN/A	{ "call",		TOK_CALL },
2770SN/A	{ "return",		TOK_RETURN },
2780SN/A	{ "eaction",		TOK_EACTION },
2790SN/A	{ "tcp-setmss",		TOK_TCPSETMSS },
2800SN/A	{ NULL, 0 }	/* terminator */
2810SN/A};
2820SN/A
2830SN/Astatic struct _s_x rule_action_params[] = {
2840SN/A	{ "altq",		TOK_ALTQ },
2850SN/A	{ "log",		TOK_LOG },
2860SN/A	{ "tag",		TOK_TAG },
2870SN/A	{ "untag",		TOK_UNTAG },
2880SN/A	{ NULL, 0 }	/* terminator */
2890SN/A};
2900SN/A
2910SN/A/*
2920SN/A * The 'lookup' instruction accepts one of the following arguments.
2930SN/A * -1 is a terminator for the list.
2940SN/A * Arguments are passed as v[1] in O_DST_LOOKUP options.
2950SN/A */
2960SN/Astatic int lookup_key[] = {
2970SN/A	TOK_DSTIP, TOK_SRCIP, TOK_DSTPORT, TOK_SRCPORT,
2980SN/A	TOK_UID, TOK_JAIL, TOK_DSCP, -1 };
2990SN/A
3000SN/Astatic struct _s_x rule_options[] = {
3010SN/A	{ "tagged",		TOK_TAGGED },
3020SN/A	{ "uid",		TOK_UID },
3030SN/A	{ "gid",		TOK_GID },
3040SN/A	{ "jail",		TOK_JAIL },
3050SN/A	{ "in",			TOK_IN },
3060SN/A	{ "limit",		TOK_LIMIT },
3070SN/A	{ "keep-state",		TOK_KEEPSTATE },
3080SN/A	{ "bridged",		TOK_LAYER2 },
3090SN/A	{ "layer2",		TOK_LAYER2 },
3100SN/A	{ "out",		TOK_OUT },
3110SN/A	{ "diverted",		TOK_DIVERTED },
3120SN/A	{ "diverted-loopback",	TOK_DIVERTEDLOOPBACK },
3130SN/A	{ "diverted-output",	TOK_DIVERTEDOUTPUT },
3140SN/A	{ "xmit",		TOK_XMIT },
3150SN/A	{ "recv",		TOK_RECV },
3160SN/A	{ "via",		TOK_VIA },
3170SN/A	{ "fragment",		TOK_FRAG },
3180SN/A	{ "frag",		TOK_FRAG },
3190SN/A	{ "fib",		TOK_FIB },
3200SN/A	{ "ipoptions",		TOK_IPOPTS },
3210SN/A	{ "ipopts",		TOK_IPOPTS },
3220SN/A	{ "iplen",		TOK_IPLEN },
3230SN/A	{ "ipid",		TOK_IPID },
3240SN/A	{ "ipprecedence",	TOK_IPPRECEDENCE },
3250SN/A	{ "dscp",		TOK_DSCP },
3260SN/A	{ "iptos",		TOK_IPTOS },
3270SN/A	{ "ipttl",		TOK_IPTTL },
3280SN/A	{ "ipversion",		TOK_IPVER },
3290SN/A	{ "ipver",		TOK_IPVER },
3300SN/A	{ "estab",		TOK_ESTAB },
3310SN/A	{ "established",	TOK_ESTAB },
3320SN/A	{ "setup",		TOK_SETUP },
3330SN/A	{ "sockarg",		TOK_SOCKARG },
3340SN/A	{ "tcpdatalen",		TOK_TCPDATALEN },
3350SN/A	{ "tcpflags",		TOK_TCPFLAGS },
3360SN/A	{ "tcpflgs",		TOK_TCPFLAGS },
3370SN/A	{ "tcpoptions",		TOK_TCPOPTS },
3380SN/A	{ "tcpopts",		TOK_TCPOPTS },
3390SN/A	{ "tcpseq",		TOK_TCPSEQ },
3400SN/A	{ "tcpack",		TOK_TCPACK },
3410SN/A	{ "tcpwin",		TOK_TCPWIN },
3420SN/A	{ "icmptype",		TOK_ICMPTYPES },
3430SN/A	{ "icmptypes",		TOK_ICMPTYPES },
3440SN/A	{ "dst-ip",		TOK_DSTIP },
3450SN/A	{ "src-ip",		TOK_SRCIP },
3460SN/A	{ "dst-port",		TOK_DSTPORT },
3470SN/A	{ "src-port",		TOK_SRCPORT },
3480SN/A	{ "proto",		TOK_PROTO },
3490SN/A	{ "MAC",		TOK_MAC },
3500SN/A	{ "mac",		TOK_MAC },
3510SN/A	{ "mac-type",		TOK_MACTYPE },
3520SN/A	{ "verrevpath",		TOK_VERREVPATH },
3530SN/A	{ "versrcreach",	TOK_VERSRCREACH },
3540SN/A	{ "antispoof",		TOK_ANTISPOOF },
3550SN/A	{ "ipsec",		TOK_IPSEC },
3560SN/A	{ "icmp6type",		TOK_ICMP6TYPES },
3570SN/A	{ "icmp6types",		TOK_ICMP6TYPES },
3580SN/A	{ "ext6hdr",		TOK_EXT6HDR},
3590SN/A	{ "flow-id",		TOK_FLOWID},
3600SN/A	{ "ipv6",		TOK_IPV6},
3610SN/A	{ "ip6",		TOK_IPV6},
3620SN/A	{ "ipv4",		TOK_IPV4},
3630SN/A	{ "ip4",		TOK_IPV4},
3640SN/A	{ "dst-ipv6",		TOK_DSTIP6},
3650SN/A	{ "dst-ip6",		TOK_DSTIP6},
3660SN/A	{ "src-ipv6",		TOK_SRCIP6},
3670SN/A	{ "src-ip6",		TOK_SRCIP6},
3680SN/A	{ "lookup",		TOK_LOOKUP},
3690SN/A	{ "flow",		TOK_FLOW},
3700SN/A	{ "//",			TOK_COMMENT },
3710SN/A
3720SN/A	{ "not",		TOK_NOT },		/* pseudo option */
3730SN/A	{ "!", /* escape ? */	TOK_NOT },		/* pseudo option */
3740SN/A	{ "or",			TOK_OR },		/* pseudo option */
3750SN/A	{ "|", /* escape */	TOK_OR },		/* pseudo option */
3760SN/A	{ "{",			TOK_STARTBRACE },	/* pseudo option */
3770SN/A	{ "(",			TOK_STARTBRACE },	/* pseudo option */
3780SN/A	{ "}",			TOK_ENDBRACE },		/* pseudo option */
3790SN/A	{ ")",			TOK_ENDBRACE },		/* pseudo option */
3800SN/A	{ NULL, 0 }	/* terminator */
3810SN/A};
3820SN/A
3830SN/Avoid bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg);
3840SN/Astatic int ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
3850SN/A    ipfw_cfg_lheader **pcfg, size_t *psize);
3860SN/Astatic int ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
3870SN/A    ipfw_cfg_lheader *cfg, size_t sz, int ac, char **av);
3880SN/Astatic void ipfw_list_tifaces(void);
3890SN/A
3900SN/Astruct tidx;
3910SN/Astatic uint16_t pack_object(struct tidx *tstate, char *name, int otype);
3920SN/Astatic uint16_t pack_table(struct tidx *tstate, char *name);
3930SN/A
3940SN/Astatic char *table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx);
3950SN/Astatic void object_sort_ctlv(ipfw_obj_ctlv *ctlv);
3960SN/Astatic char *object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx,
3970SN/A    uint16_t type);
3980SN/A
3990SN/A/*
4000SN/A * Simple string buffer API.
4010SN/A * Used to simplify buffer passing between function and for
4020SN/A * transparent overrun handling.
4030SN/A */
4040SN/A
4050SN/A/*
4060SN/A * Allocates new buffer of given size @sz.
4070SN/A *
4080SN/A * Returns 0 on success.
4090SN/A */
4100SN/Aint
4110SN/Abp_alloc(struct buf_pr *b, size_t size)
4120SN/A{
4130SN/A	memset(b, 0, sizeof(struct buf_pr));
4140SN/A
4150SN/A	if ((b->buf = calloc(1, size)) == NULL)
4160SN/A		return (ENOMEM);
4170SN/A
4180SN/A	b->ptr = b->buf;
4190SN/A	b->size = size;
4200SN/A	b->avail = b->size;
4210SN/A
4220SN/A	return (0);
4230SN/A}
4240SN/A
4250SN/Avoid
4260SN/Abp_free(struct buf_pr *b)
4270SN/A{
4280SN/A
4290SN/A	free(b->buf);
4300SN/A}
4310SN/A
4320SN/A/*
4330SN/A * Flushes buffer so new writer start from beginning.
4340SN/A */
4350SN/Avoid
4360SN/Abp_flush(struct buf_pr *b)
4370SN/A{
4380SN/A
4390SN/A	b->ptr = b->buf;
4400SN/A	b->avail = b->size;
4410SN/A	b->buf[0] = '\0';
4420SN/A}
4430SN/A
4440SN/A/*
4450SN/A * Print message specified by @format and args.
4460SN/A * Automatically manage buffer space and transparently handle
4470SN/A * buffer overruns.
4480SN/A *
4490SN/A * Returns number of bytes that should have been printed.
4500SN/A */
4510SN/Aint
4520SN/Abprintf(struct buf_pr *b, char *format, ...)
4530SN/A{
4540SN/A	va_list args;
4550SN/A	int i;
4560SN/A
4570SN/A	va_start(args, format);
4580SN/A
4590SN/A	i = vsnprintf(b->ptr, b->avail, format, args);
4600SN/A	va_end(args);
4610SN/A
4620SN/A	if (i > b->avail || i < 0) {
4630SN/A		/* Overflow or print error */
4640SN/A		b->avail = 0;
4650SN/A	} else {
4660SN/A		b->ptr += i;
4670SN/A		b->avail -= i;
4680SN/A	}
4690SN/A
4700SN/A	b->needed += i;
4710SN/A
4720SN/A	return (i);
4730SN/A}
4740SN/A
4750SN/A/*
4760SN/A * Special values printer for tablearg-aware opcodes.
4770SN/A */
4780SN/Avoid
4790SN/Abprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg)
4800SN/A{
4810SN/A
4820SN/A	if (str != NULL)
4830SN/A		bprintf(bp, "%s", str);
4840SN/A	if (arg == IP_FW_TARG)
4850SN/A		bprintf(bp, "tablearg");
4860SN/A	else
4870SN/A		bprintf(bp, "%u", arg);
4880SN/A}
4890SN/A
4900SN/A/*
4910SN/A * Helper routine to print a possibly unaligned uint64_t on
4920SN/A * various platform. If width > 0, print the value with
4930SN/A * the desired width, followed by a space;
4940SN/A * otherwise, return the required width.
4950SN/A */
4960SN/Aint
4970SN/Apr_u64(struct buf_pr *b, uint64_t *pd, int width)
4980SN/A{
4990SN/A#ifdef TCC
5000SN/A#define U64_FMT "I64"
5010SN/A#else
5020SN/A#define U64_FMT "llu"
5030SN/A#endif
5040SN/A	uint64_t u;
5050SN/A	unsigned long long d;
5060SN/A
5070SN/A	bcopy (pd, &u, sizeof(u));
5080SN/A	d = u;
5090SN/A	return (width > 0) ?
5100SN/A		bprintf(b, "%*" U64_FMT " ", width, d) :
5110SN/A		snprintf(NULL, 0, "%" U64_FMT, d) ;
5120SN/A#undef U64_FMT
5130SN/A}
5140SN/A
5150SN/A
5160SN/Avoid *
5170SN/Asafe_calloc(size_t number, size_t size)
5180SN/A{
5190SN/A	void *ret = calloc(number, size);
5200SN/A
5210SN/A	if (ret == NULL)
5220SN/A		err(EX_OSERR, "calloc");
5230SN/A	return ret;
5240SN/A}
5250SN/A
5260SN/Avoid *
5270SN/Asafe_realloc(void *ptr, size_t size)
5280SN/A{
5290SN/A	void *ret = realloc(ptr, size);
5300SN/A
5310SN/A	if (ret == NULL)
5320SN/A		err(EX_OSERR, "realloc");
5330SN/A	return ret;
5340SN/A}
5350SN/A
5360SN/A/*
5370SN/A * Compare things like interface or table names.
5380SN/A */
5390SN/Aint
5400SN/Astringnum_cmp(const char *a, const char *b)
5410SN/A{
5420SN/A	int la, lb;
5430SN/A
5440SN/A	la = strlen(a);
5450SN/A	lb = strlen(b);
5460SN/A
5470SN/A	if (la > lb)
5480SN/A		return (1);
5490SN/A	else if (la < lb)
5500SN/A		return (-01);
5510SN/A
5520SN/A	return (strcmp(a, b));
5530SN/A}
5540SN/A
555
556/*
557 * conditionally runs the command.
558 * Selected options or negative -> getsockopt
559 */
560int
561do_cmd(int optname, void *optval, uintptr_t optlen)
562{
563	int i;
564
565	if (co.test_only)
566		return 0;
567
568	if (ipfw_socket == -1)
569		ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
570	if (ipfw_socket < 0)
571		err(EX_UNAVAILABLE, "socket");
572
573	if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
574	    optname == IP_FW_ADD || optname == IP_FW3 ||
575	    optname == IP_FW_NAT_GET_CONFIG ||
576	    optname < 0 ||
577	    optname == IP_FW_NAT_GET_LOG) {
578		if (optname < 0)
579			optname = -optname;
580		i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
581			(socklen_t *)optlen);
582	} else {
583		i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
584	}
585	return i;
586}
587
588/*
589 * do_set3 - pass ipfw control cmd to kernel
590 * @optname: option name
591 * @optval: pointer to option data
592 * @optlen: option length
593 *
594 * Assumes op3 header is already embedded.
595 * Calls setsockopt() with IP_FW3 as kernel-visible opcode.
596 * Returns 0 on success or errno otherwise.
597 */
598int
599do_set3(int optname, ip_fw3_opheader *op3, size_t optlen)
600{
601
602	if (co.test_only)
603		return (0);
604
605	if (ipfw_socket == -1)
606		ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
607	if (ipfw_socket < 0)
608		err(EX_UNAVAILABLE, "socket");
609
610	op3->opcode = optname;
611
612	return (setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, optlen));
613}
614
615/*
616 * do_get3 - pass ipfw control cmd to kernel
617 * @optname: option name
618 * @optval: pointer to option data
619 * @optlen: pointer to option length
620 *
621 * Assumes op3 header is already embedded.
622 * Calls getsockopt() with IP_FW3 as kernel-visible opcode.
623 * Returns 0 on success or errno otherwise.
624 */
625int
626do_get3(int optname, ip_fw3_opheader *op3, size_t *optlen)
627{
628	int error;
629	socklen_t len;
630
631	if (co.test_only)
632		return (0);
633
634	if (ipfw_socket == -1)
635		ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
636	if (ipfw_socket < 0)
637		err(EX_UNAVAILABLE, "socket");
638
639	op3->opcode = optname;
640
641	len = *optlen;
642	error = getsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, &len);
643	*optlen = len;
644
645	return (error);
646}
647
648/**
649 * match_token takes a table and a string, returns the value associated
650 * with the string (-1 in case of failure).
651 */
652int
653match_token(struct _s_x *table, const char *string)
654{
655	struct _s_x *pt;
656	uint i = strlen(string);
657
658	for (pt = table ; i && pt->s != NULL ; pt++)
659		if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
660			return pt->x;
661	return (-1);
662}
663
664/**
665 * match_token_relaxed takes a table and a string, returns the value associated
666 * with the string for the best match.
667 *
668 * Returns:
669 * value from @table for matched records
670 * -1 for non-matched records
671 * -2 if more than one records match @string.
672 */
673int
674match_token_relaxed(struct _s_x *table, const char *string)
675{
676	struct _s_x *pt, *m;
677	int i, c;
678
679	i = strlen(string);
680	c = 0;
681
682	for (pt = table ; i != 0 && pt->s != NULL ; pt++) {
683		if (strncmp(pt->s, string, i) != 0)
684			continue;
685		m = pt;
686		c++;
687	}
688
689	if (c == 1)
690		return (m->x);
691
692	return (c > 0 ? -2: -1);
693}
694
695int
696get_token(struct _s_x *table, const char *string, const char *errbase)
697{
698	int tcmd;
699
700	if ((tcmd = match_token_relaxed(table, string)) < 0)
701		errx(EX_USAGE, "%s %s %s",
702		    (tcmd == 0) ? "invalid" : "ambiguous", errbase, string);
703
704	return (tcmd);
705}
706
707/**
708 * match_value takes a table and a value, returns the string associated
709 * with the value (NULL in case of failure).
710 */
711char const *
712match_value(struct _s_x *p, int value)
713{
714	for (; p->s != NULL; p++)
715		if (p->x == value)
716			return p->s;
717	return NULL;
718}
719
720size_t
721concat_tokens(char *buf, size_t bufsize, struct _s_x *table, char *delimiter)
722{
723	struct _s_x *pt;
724	int l;
725	size_t sz;
726
727	for (sz = 0, pt = table ; pt->s != NULL; pt++) {
728		l = snprintf(buf + sz, bufsize - sz, "%s%s",
729		    (sz == 0) ? "" : delimiter, pt->s);
730		sz += l;
731		bufsize += l;
732		if (sz > bufsize)
733			return (bufsize);
734	}
735
736	return (sz);
737}
738
739/*
740 * helper function to process a set of flags and set bits in the
741 * appropriate masks.
742 */
743int
744fill_flags(struct _s_x *flags, char *p, char **e, uint32_t *set,
745    uint32_t *clear)
746{
747	char *q;	/* points to the separator */
748	int val;
749	uint32_t *which;	/* mask we are working on */
750
751	while (p && *p) {
752		if (*p == '!') {
753			p++;
754			which = clear;
755		} else
756			which = set;
757		q = strchr(p, ',');
758		if (q)
759			*q++ = '\0';
760		val = match_token(flags, p);
761		if (val <= 0) {
762			if (e != NULL)
763				*e = p;
764			return (-1);
765		}
766		*which |= (uint32_t)val;
767		p = q;
768	}
769	return (0);
770}
771
772void
773print_flags_buffer(char *buf, size_t sz, struct _s_x *list, uint32_t set)
774{
775	char const *comma = "";
776	int i, l;
777
778	for (i = 0; list[i].x != 0; i++) {
779		if ((set & list[i].x) == 0)
780			continue;
781
782		set &= ~list[i].x;
783		l = snprintf(buf, sz, "%s%s", comma, list[i].s);
784		if (l >= sz)
785			return;
786		comma = ",";
787		buf += l;
788		sz -=l;
789	}
790}
791
792/*
793 * _substrcmp takes two strings and returns 1 if they do not match,
794 * and 0 if they match exactly or the first string is a sub-string
795 * of the second.  A warning is printed to stderr in the case that the
796 * first string is a sub-string of the second.
797 *
798 * This function will be removed in the future through the usual
799 * deprecation process.
800 */
801int
802_substrcmp(const char *str1, const char* str2)
803{
804
805	if (strncmp(str1, str2, strlen(str1)) != 0)
806		return 1;
807
808	if (strlen(str1) != strlen(str2))
809		warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
810		    str1, str2);
811	return 0;
812}
813
814/*
815 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
816 * and 0 if they match exactly or the second string is a sub-string
817 * of the first.  A warning is printed to stderr in the case that the
818 * first string does not match the third.
819 *
820 * This function exists to warn about the bizarre construction
821 * strncmp(str, "by", 2) which is used to allow people to use a shortcut
822 * for "bytes".  The problem is that in addition to accepting "by",
823 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
824 * other string beginning with "by".
825 *
826 * This function will be removed in the future through the usual
827 * deprecation process.
828 */
829int
830_substrcmp2(const char *str1, const char* str2, const char* str3)
831{
832
833	if (strncmp(str1, str2, strlen(str2)) != 0)
834		return 1;
835
836	if (strcmp(str1, str3) != 0)
837		warnx("DEPRECATED: '%s' matched '%s'",
838		    str1, str3);
839	return 0;
840}
841
842/*
843 * prints one port, symbolic or numeric
844 */
845static void
846print_port(struct buf_pr *bp, int proto, uint16_t port)
847{
848
849	if (proto == IPPROTO_ETHERTYPE) {
850		char const *s;
851
852		if (co.do_resolv && (s = match_value(ether_types, port)) )
853			bprintf(bp, "%s", s);
854		else
855			bprintf(bp, "0x%04x", port);
856	} else {
857		struct servent *se = NULL;
858		if (co.do_resolv) {
859			struct protoent *pe = getprotobynumber(proto);
860
861			se = getservbyport(htons(port), pe ? pe->p_name : NULL);
862		}
863		if (se)
864			bprintf(bp, "%s", se->s_name);
865		else
866			bprintf(bp, "%d", port);
867	}
868}
869
870static struct _s_x _port_name[] = {
871	{"dst-port",	O_IP_DSTPORT},
872	{"src-port",	O_IP_SRCPORT},
873	{"ipid",	O_IPID},
874	{"iplen",	O_IPLEN},
875	{"ipttl",	O_IPTTL},
876	{"mac-type",	O_MAC_TYPE},
877	{"tcpdatalen",	O_TCPDATALEN},
878	{"tcpwin",	O_TCPWIN},
879	{"tagged",	O_TAGGED},
880	{NULL,		0}
881};
882
883/*
884 * Print the values in a list 16-bit items of the types above.
885 * XXX todo: add support for mask.
886 */
887static void
888print_newports(struct buf_pr *bp, ipfw_insn_u16 *cmd, int proto, int opcode)
889{
890	uint16_t *p = cmd->ports;
891	int i;
892	char const *sep;
893
894	if (opcode != 0) {
895		sep = match_value(_port_name, opcode);
896		if (sep == NULL)
897			sep = "???";
898		bprintf(bp, " %s", sep);
899	}
900	sep = " ";
901	for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
902		bprintf(bp, "%s", sep);
903		print_port(bp, proto, p[0]);
904		if (p[0] != p[1]) {
905			bprintf(bp, "-");
906			print_port(bp, proto, p[1]);
907		}
908		sep = ",";
909	}
910}
911
912/*
913 * Like strtol, but also translates service names into port numbers
914 * for some protocols.
915 * In particular:
916 *	proto == -1 disables the protocol check;
917 *	proto == IPPROTO_ETHERTYPE looks up an internal table
918 *	proto == <some value in /etc/protocols> matches the values there.
919 * Returns *end == s in case the parameter is not found.
920 */
921static int
922strtoport(char *s, char **end, int base, int proto)
923{
924	char *p, *buf;
925	char *s1;
926	int i;
927
928	*end = s;		/* default - not found */
929	if (*s == '\0')
930		return 0;	/* not found */
931
932	if (isdigit(*s))
933		return strtol(s, end, base);
934
935	/*
936	 * find separator. '\\' escapes the next char.
937	 */
938	for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
939		if (*s1 == '\\' && s1[1] != '\0')
940			s1++;
941
942	buf = safe_calloc(s1 - s + 1, 1);
943
944	/*
945	 * copy into a buffer skipping backslashes
946	 */
947	for (p = s, i = 0; p != s1 ; p++)
948		if (*p != '\\')
949			buf[i++] = *p;
950	buf[i++] = '\0';
951
952	if (proto == IPPROTO_ETHERTYPE) {
953		i = match_token(ether_types, buf);
954		free(buf);
955		if (i != -1) {	/* found */
956			*end = s1;
957			return i;
958		}
959	} else {
960		struct protoent *pe = NULL;
961		struct servent *se;
962
963		if (proto != 0)
964			pe = getprotobynumber(proto);
965		setservent(1);
966		se = getservbyname(buf, pe ? pe->p_name : NULL);
967		free(buf);
968		if (se != NULL) {
969			*end = s1;
970			return ntohs(se->s_port);
971		}
972	}
973	return 0;	/* not found */
974}
975
976/*
977 * Fill the body of the command with the list of port ranges.
978 */
979static int
980fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
981{
982	uint16_t a, b, *p = cmd->ports;
983	int i = 0;
984	char *s = av;
985
986	while (*s) {
987		a = strtoport(av, &s, 0, proto);
988		if (s == av) 			/* empty or invalid argument */
989			return (0);
990
991		CHECK_LENGTH(cblen, i + 2);
992
993		switch (*s) {
994		case '-':			/* a range */
995			av = s + 1;
996			b = strtoport(av, &s, 0, proto);
997			/* Reject expressions like '1-abc' or '1-2-3'. */
998			if (s == av || (*s != ',' && *s != '\0'))
999				return (0);
1000			p[0] = a;
1001			p[1] = b;
1002			break;
1003		case ',':			/* comma separated list */
1004		case '\0':
1005			p[0] = p[1] = a;
1006			break;
1007		default:
1008			warnx("port list: invalid separator <%c> in <%s>",
1009				*s, av);
1010			return (0);
1011		}
1012
1013		i++;
1014		p += 2;
1015		av = s + 1;
1016	}
1017	if (i > 0) {
1018		if (i + 1 > F_LEN_MASK)
1019			errx(EX_DATAERR, "too many ports/ranges\n");
1020		cmd->o.len |= i + 1;	/* leave F_NOT and F_OR untouched */
1021	}
1022	return (i);
1023}
1024
1025/*
1026 * Fill the body of the command with the list of DiffServ codepoints.
1027 */
1028static void
1029fill_dscp(ipfw_insn *cmd, char *av, int cblen)
1030{
1031	uint32_t *low, *high;
1032	char *s = av, *a;
1033	int code;
1034
1035	cmd->opcode = O_DSCP;
1036	cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
1037
1038	CHECK_CMDLEN;
1039
1040	low = (uint32_t *)(cmd + 1);
1041	high = low + 1;
1042
1043	*low = 0;
1044	*high = 0;
1045
1046	while (s != NULL) {
1047		a = strchr(s, ',');
1048
1049		if (a != NULL)
1050			*a++ = '\0';
1051
1052		if (isalpha(*s)) {
1053			if ((code = match_token(f_ipdscp, s)) == -1)
1054				errx(EX_DATAERR, "Unknown DSCP code");
1055		} else {
1056			code = strtoul(s, NULL, 10);
1057			if (code < 0 || code > 63)
1058				errx(EX_DATAERR, "Invalid DSCP value");
1059		}
1060
1061		if (code >= 32)
1062			*high |= 1 << (code - 32);
1063		else
1064			*low |= 1 << code;
1065
1066		s = a;
1067	}
1068}
1069
1070static struct _s_x icmpcodes[] = {
1071      { "net",			ICMP_UNREACH_NET },
1072      { "host",			ICMP_UNREACH_HOST },
1073      { "protocol",		ICMP_UNREACH_PROTOCOL },
1074      { "port",			ICMP_UNREACH_PORT },
1075      { "needfrag",		ICMP_UNREACH_NEEDFRAG },
1076      { "srcfail",		ICMP_UNREACH_SRCFAIL },
1077      { "net-unknown",		ICMP_UNREACH_NET_UNKNOWN },
1078      { "host-unknown",		ICMP_UNREACH_HOST_UNKNOWN },
1079      { "isolated",		ICMP_UNREACH_ISOLATED },
1080      { "net-prohib",		ICMP_UNREACH_NET_PROHIB },
1081      { "host-prohib",		ICMP_UNREACH_HOST_PROHIB },
1082      { "tosnet",		ICMP_UNREACH_TOSNET },
1083      { "toshost",		ICMP_UNREACH_TOSHOST },
1084      { "filter-prohib",	ICMP_UNREACH_FILTER_PROHIB },
1085      { "host-precedence",	ICMP_UNREACH_HOST_PRECEDENCE },
1086      { "precedence-cutoff",	ICMP_UNREACH_PRECEDENCE_CUTOFF },
1087      { NULL, 0 }
1088};
1089
1090static void
1091fill_reject_code(u_short *codep, char *str)
1092{
1093	int val;
1094	char *s;
1095
1096	val = strtoul(str, &s, 0);
1097	if (s == str || *s != '\0' || val >= 0x100)
1098		val = match_token(icmpcodes, str);
1099	if (val < 0)
1100		errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
1101	*codep = val;
1102	return;
1103}
1104
1105static void
1106print_reject_code(struct buf_pr *bp, uint16_t code)
1107{
1108	char const *s;
1109
1110	if ((s = match_value(icmpcodes, code)) != NULL)
1111		bprintf(bp, "unreach %s", s);
1112	else
1113		bprintf(bp, "unreach %u", code);
1114}
1115
1116/*
1117 * Returns the number of bits set (from left) in a contiguous bitmask,
1118 * or -1 if the mask is not contiguous.
1119 * XXX this needs a proper fix.
1120 * This effectively works on masks in big-endian (network) format.
1121 * when compiled on little endian architectures.
1122 *
1123 * First bit is bit 7 of the first byte -- note, for MAC addresses,
1124 * the first bit on the wire is bit 0 of the first byte.
1125 * len is the max length in bits.
1126 */
1127int
1128contigmask(uint8_t *p, int len)
1129{
1130	int i, n;
1131
1132	for (i=0; i<len ; i++)
1133		if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
1134			break;
1135	for (n=i+1; n < len; n++)
1136		if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
1137			return -1; /* mask not contiguous */
1138	return i;
1139}
1140
1141/*
1142 * print flags set/clear in the two bitmasks passed as parameters.
1143 * There is a specialized check for f_tcpflags.
1144 */
1145static void
1146print_flags(struct buf_pr *bp, char const *name, ipfw_insn *cmd,
1147    struct _s_x *list)
1148{
1149	char const *comma = "";
1150	int i;
1151	uint8_t set = cmd->arg1 & 0xff;
1152	uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1153
1154	if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1155		bprintf(bp, " setup");
1156		return;
1157	}
1158
1159	bprintf(bp, " %s ", name);
1160	for (i=0; list[i].x != 0; i++) {
1161		if (set & list[i].x) {
1162			set &= ~list[i].x;
1163			bprintf(bp, "%s%s", comma, list[i].s);
1164			comma = ",";
1165		}
1166		if (clear & list[i].x) {
1167			clear &= ~list[i].x;
1168			bprintf(bp, "%s!%s", comma, list[i].s);
1169			comma = ",";
1170		}
1171	}
1172}
1173
1174
1175/*
1176 * Print the ip address contained in a command.
1177 */
1178static void
1179print_ip(struct buf_pr *bp, const struct format_opts *fo, ipfw_insn_ip *cmd,
1180    char const *s)
1181{
1182	struct hostent *he = NULL;
1183	struct in_addr *ia;
1184	uint32_t len = F_LEN((ipfw_insn *)cmd);
1185	uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
1186	char *t;
1187
1188	if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
1189		uint32_t d = a[1];
1190		const char *arg = "<invalid>";
1191
1192		if (d < sizeof(lookup_key)/sizeof(lookup_key[0]))
1193			arg = match_value(rule_options, lookup_key[d]);
1194		t = table_search_ctlv(fo->tstate, ((ipfw_insn *)cmd)->arg1);
1195		bprintf(bp, " lookup %s %s", arg, t);
1196		return;
1197	}
1198	bprintf(bp, "%s ", s);
1199
1200	if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
1201		bprintf(bp, "me");
1202		return;
1203	}
1204	if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
1205	    cmd->o.opcode == O_IP_DST_LOOKUP) {
1206		t = table_search_ctlv(fo->tstate, ((ipfw_insn *)cmd)->arg1);
1207		bprintf(bp, "table(%s", t);
1208		if (len == F_INSN_SIZE(ipfw_insn_u32))
1209			bprintf(bp, ",%u", *a);
1210		bprintf(bp, ")");
1211		return;
1212	}
1213	if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1214		uint32_t x, *map = (uint32_t *)&(cmd->mask);
1215		int i, j;
1216		char comma = '{';
1217
1218		x = cmd->o.arg1 - 1;
1219		x = htonl( ~x );
1220		cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1221		bprintf(bp, "%s/%d", inet_ntoa(cmd->addr),
1222			contigmask((uint8_t *)&x, 32));
1223		x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1224		x &= 0xff; /* base */
1225		/*
1226		 * Print bits and ranges.
1227		 * Locate first bit set (i), then locate first bit unset (j).
1228		 * If we have 3+ consecutive bits set, then print them as a
1229		 * range, otherwise only print the initial bit and rescan.
1230		 */
1231		for (i=0; i < cmd->o.arg1; i++)
1232			if (map[i/32] & (1<<(i & 31))) {
1233				for (j=i+1; j < cmd->o.arg1; j++)
1234					if (!(map[ j/32] & (1<<(j & 31))))
1235						break;
1236				bprintf(bp, "%c%d", comma, i+x);
1237				if (j>i+2) { /* range has at least 3 elements */
1238					bprintf(bp, "-%d", j-1+x);
1239					i = j-1;
1240				}
1241				comma = ',';
1242			}
1243		bprintf(bp, "}");
1244		return;
1245	}
1246	/*
1247	 * len == 2 indicates a single IP, whereas lists of 1 or more
1248	 * addr/mask pairs have len = (2n+1). We convert len to n so we
1249	 * use that to count the number of entries.
1250	 */
1251    for (len = len / 2; len > 0; len--, a += 2) {
1252	int mb =	/* mask length */
1253	    (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1254		32 : contigmask((uint8_t *)&(a[1]), 32);
1255	if (mb == 32 && co.do_resolv)
1256		he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
1257	if (he != NULL)		/* resolved to name */
1258		bprintf(bp, "%s", he->h_name);
1259	else if (mb == 0)	/* any */
1260		bprintf(bp, "any");
1261	else {		/* numeric IP followed by some kind of mask */
1262		ia = (struct in_addr *)&a[0];
1263		bprintf(bp, "%s", inet_ntoa(*ia));
1264		if (mb < 0) {
1265			ia = (struct in_addr *)&a[1];
1266			bprintf(bp, ":%s", inet_ntoa(*ia));
1267		} else if (mb < 32)
1268			bprintf(bp, "/%d", mb);
1269	}
1270	if (len > 1)
1271		bprintf(bp, ",");
1272    }
1273}
1274
1275/*
1276 * prints a MAC address/mask pair
1277 */
1278static void
1279format_mac(struct buf_pr *bp, uint8_t *addr, uint8_t *mask)
1280{
1281	int l = contigmask(mask, 48);
1282
1283	if (l == 0)
1284		bprintf(bp, " any");
1285	else {
1286		bprintf(bp, " %02x:%02x:%02x:%02x:%02x:%02x",
1287		    addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1288		if (l == -1)
1289			bprintf(bp, "&%02x:%02x:%02x:%02x:%02x:%02x",
1290			    mask[0], mask[1], mask[2],
1291			    mask[3], mask[4], mask[5]);
1292		else if (l < 48)
1293			bprintf(bp, "/%d", l);
1294	}
1295}
1296
1297static void
1298print_mac(struct buf_pr *bp, ipfw_insn_mac *mac)
1299{
1300
1301	bprintf(bp, " MAC");
1302	format_mac(bp, mac->addr, mac->mask);
1303	format_mac(bp, mac->addr + 6, mac->mask + 6);
1304}
1305
1306static void
1307fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1308{
1309	uint8_t type;
1310
1311	cmd->d[0] = 0;
1312	while (*av) {
1313		if (*av == ',')
1314			av++;
1315
1316		type = strtoul(av, &av, 0);
1317
1318		if (*av != ',' && *av != '\0')
1319			errx(EX_DATAERR, "invalid ICMP type");
1320
1321		if (type > 31)
1322			errx(EX_DATAERR, "ICMP type out of range");
1323
1324		cmd->d[0] |= 1 << type;
1325	}
1326	cmd->o.opcode = O_ICMPTYPE;
1327	cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1328}
1329
1330static void
1331print_icmptypes(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1332{
1333	int i;
1334	char sep= ' ';
1335
1336	bprintf(bp, " icmptypes");
1337	for (i = 0; i < 32; i++) {
1338		if ( (cmd->d[0] & (1 << (i))) == 0)
1339			continue;
1340		bprintf(bp, "%c%d", sep, i);
1341		sep = ',';
1342	}
1343}
1344
1345static void
1346print_dscp(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1347{
1348	int i = 0;
1349	uint32_t *v;
1350	char sep= ' ';
1351	const char *code;
1352
1353	bprintf(bp, " dscp");
1354	v = cmd->d;
1355	while (i < 64) {
1356		if (*v & (1 << i)) {
1357			if ((code = match_value(f_ipdscp, i)) != NULL)
1358				bprintf(bp, "%c%s", sep, code);
1359			else
1360				bprintf(bp, "%c%d", sep, i);
1361			sep = ',';
1362		}
1363
1364		if ((++i % 32) == 0)
1365			v++;
1366	}
1367}
1368
1369#define	insntod(cmd, type)	((ipfw_insn_ ## type *)(cmd))
1370struct show_state {
1371	struct ip_fw_rule	*rule;
1372	const ipfw_insn		*eaction;
1373	uint8_t			*printed;
1374	int			flags;
1375#define	HAVE_PROTO	0x0001
1376#define	HAVE_SRCIP	0x0002
1377#define	HAVE_DSTIP	0x0004
1378	int			proto;
1379	int			or_block;
1380};
1381
1382static int
1383init_show_state(struct show_state *state, struct ip_fw_rule *rule)
1384{
1385
1386	state->printed = calloc(rule->cmd_len, sizeof(uint8_t));
1387	if (state->printed == NULL)
1388		return (ENOMEM);
1389	state->rule = rule;
1390	state->eaction = NULL;
1391	state->flags = 0;
1392	state->proto = 0;
1393	state->or_block = 0;
1394	return (0);
1395}
1396
1397static void
1398free_show_state(struct show_state *state)
1399{
1400
1401	free(state->printed);
1402}
1403
1404static uint8_t
1405is_printed_opcode(struct show_state *state, const ipfw_insn *cmd)
1406{
1407
1408	return (state->printed[cmd - state->rule->cmd]);
1409}
1410
1411static void
1412mark_printed(struct show_state *state, const ipfw_insn *cmd)
1413{
1414
1415	state->printed[cmd - state->rule->cmd] = 1;
1416}
1417
1418static void
1419print_limit(struct buf_pr *bp, const ipfw_insn_limit *limit)
1420{
1421	struct _s_x *p = limit_masks;
1422	char const *comma = " ";
1423	uint8_t x;
1424
1425	bprintf(bp, " limit");
1426	for (x = limit->limit_mask; p->x != 0; p++) {
1427		if ((x & p->x) == p->x) {
1428			x &= ~p->x;
1429			bprintf(bp, "%s%s", comma, p->s);
1430			comma = ",";
1431		}
1432	}
1433	bprint_uint_arg(bp, " ", limit->conn_limit);
1434}
1435
1436static int
1437print_instruction(struct buf_pr *bp, const struct format_opts *fo,
1438    struct show_state *state, ipfw_insn *cmd)
1439{
1440	struct protoent *pe;
1441	struct passwd *pwd;
1442	struct group *grp;
1443	const char *s;
1444	double d;
1445
1446	if (is_printed_opcode(state, cmd))
1447		return (0);
1448	if ((cmd->len & F_OR) != 0 && state->or_block == 0)
1449		bprintf(bp, " {");
1450	if (cmd->opcode != O_IN && (cmd->len & F_NOT) != 0)
1451		bprintf(bp, " not");
1452
1453	switch (cmd->opcode) {
1454	case O_PROB:
1455		d = 1.0 * insntod(cmd, u32)->d[0] / 0x7fffffff;
1456		bprintf(bp, "prob %f ", d);
1457		break;
1458	case O_PROBE_STATE: /* no need to print anything here */
1459		break;
1460	case O_IP_SRC:
1461	case O_IP_SRC_LOOKUP:
1462	case O_IP_SRC_MASK:
1463	case O_IP_SRC_ME:
1464	case O_IP_SRC_SET:
1465	case O_IP_DST:
1466	case O_IP_DST_LOOKUP:
1467	case O_IP_DST_MASK:
1468	case O_IP_DST_ME:
1469	case O_IP_DST_SET:
1470		print_ip(bp, fo, insntod(cmd, ip), "");
1471		break;
1472	case O_IP6_SRC:
1473	case O_IP6_SRC_MASK:
1474	case O_IP6_SRC_ME:
1475	case O_IP6_DST:
1476	case O_IP6_DST_MASK:
1477	case O_IP6_DST_ME:
1478		print_ip6(bp, insntod(cmd, ip6), "");
1479		break;
1480	case O_FLOW6ID:
1481		print_flow6id(bp, insntod(cmd, u32));
1482		break;
1483	case O_IP_DSTPORT:
1484	case O_IP_SRCPORT:
1485		print_newports(bp, insntod(cmd, u16), state->proto,
1486		    (state->flags & (HAVE_SRCIP | HAVE_DSTIP)) ==
1487		    (HAVE_SRCIP | HAVE_DSTIP) ?  cmd->opcode: 0);
1488		break;
1489	case O_PROTO:
1490		pe = getprotobynumber(cmd->arg1);
1491		if (state->flags & HAVE_PROTO)
1492			bprintf(bp, " proto");
1493		if (pe != NULL)
1494			bprintf(bp, " %s", pe->p_name);
1495		else
1496			bprintf(bp, " %u", cmd->arg1);
1497		break;
1498	case O_MACADDR2:
1499		print_mac(bp, insntod(cmd, mac));
1500		break;
1501	case O_MAC_TYPE:
1502		print_newports(bp, insntod(cmd, u16),
1503		    IPPROTO_ETHERTYPE, cmd->opcode);
1504		break;
1505	case O_FRAG:
1506		bprintf(bp, " frag");
1507		break;
1508	case O_FIB:
1509		bprintf(bp, " fib %u", cmd->arg1);
1510		break;
1511	case O_SOCKARG:
1512		bprintf(bp, " sockarg");
1513		break;
1514	case O_IN:
1515		bprintf(bp, cmd->len & F_NOT ? " out" : " in");
1516		break;
1517	case O_DIVERTED:
1518		switch (cmd->arg1) {
1519		case 3:
1520			bprintf(bp, " diverted");
1521			break;
1522		case 2:
1523			bprintf(bp, " diverted-output");
1524			break;
1525		case 1:
1526			bprintf(bp, " diverted-loopback");
1527			break;
1528		default:
1529			bprintf(bp, " diverted-?<%u>", cmd->arg1);
1530			break;
1531		}
1532		break;
1533	case O_LAYER2:
1534		bprintf(bp, " layer2");
1535		break;
1536	case O_XMIT:
1537	case O_RECV:
1538	case O_VIA:
1539		if (cmd->opcode == O_XMIT)
1540			s = "xmit";
1541		else if (cmd->opcode == O_RECV)
1542			s = "recv";
1543		else /* if (cmd->opcode == O_VIA) */
1544			s = "via";
1545		switch (insntod(cmd, if)->name[0]) {
1546		case '\0':
1547			bprintf(bp, " %s %s", s,
1548			    inet_ntoa(insntod(cmd, if)->p.ip));
1549			break;
1550		case '\1':
1551			bprintf(bp, " %s table(%s)", s,
1552			    table_search_ctlv(fo->tstate,
1553			    insntod(cmd, if)->p.kidx));
1554			break;
1555		default:
1556			bprintf(bp, " %s %s", s,
1557			    insntod(cmd, if)->name);
1558		}
1559		break;
1560	case O_IP_FLOW_LOOKUP:
1561		s = table_search_ctlv(fo->tstate, cmd->arg1);
1562		bprintf(bp, " flow table(%s", s);
1563		if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))
1564			bprintf(bp, ",%u", insntod(cmd, u32)->d[0]);
1565		bprintf(bp, ")");
1566		break;
1567	case O_IPID:
1568	case O_IPTTL:
1569	case O_IPLEN:
1570	case O_TCPDATALEN:
1571	case O_TCPWIN:
1572		if (F_LEN(cmd) == 1) {
1573			switch (cmd->opcode) {
1574			case O_IPID:
1575				s = "ipid";
1576				break;
1577			case O_IPTTL:
1578				s = "ipttl";
1579				break;
1580			case O_IPLEN:
1581				s = "iplen";
1582				break;
1583			case O_TCPDATALEN:
1584				s = "tcpdatalen";
1585				break;
1586			case O_TCPWIN:
1587				s = "tcpwin";
1588				break;
1589			}
1590			bprintf(bp, " %s %u", s, cmd->arg1);
1591		} else
1592			print_newports(bp, insntod(cmd, u16), 0,
1593			    cmd->opcode);
1594		break;
1595	case O_IPVER:
1596		bprintf(bp, " ipver %u", cmd->arg1);
1597		break;
1598	case O_IPPRECEDENCE:
1599		bprintf(bp, " ipprecedence %u", cmd->arg1 >> 5);
1600		break;
1601	case O_DSCP:
1602		print_dscp(bp, insntod(cmd, u32));
1603		break;
1604	case O_IPOPT:
1605		print_flags(bp, "ipoptions", cmd, f_ipopts);
1606		break;
1607	case O_IPTOS:
1608		print_flags(bp, "iptos", cmd, f_iptos);
1609		break;
1610	case O_ICMPTYPE:
1611		print_icmptypes(bp, insntod(cmd, u32));
1612		break;
1613	case O_ESTAB:
1614		bprintf(bp, " established");
1615		break;
1616	case O_TCPFLAGS:
1617		print_flags(bp, "tcpflags", cmd, f_tcpflags);
1618		break;
1619	case O_TCPOPTS:
1620		print_flags(bp, "tcpoptions", cmd, f_tcpopts);
1621		break;
1622	case O_TCPACK:
1623		bprintf(bp, " tcpack %d",
1624		    ntohl(insntod(cmd, u32)->d[0]));
1625		break;
1626	case O_TCPSEQ:
1627		bprintf(bp, " tcpseq %d",
1628		    ntohl(insntod(cmd, u32)->d[0]));
1629		break;
1630	case O_UID:
1631		pwd = getpwuid(insntod(cmd, u32)->d[0]);
1632		if (pwd != NULL)
1633			bprintf(bp, " uid %s", pwd->pw_name);
1634		else
1635			bprintf(bp, " uid %u",
1636			    insntod(cmd, u32)->d[0]);
1637		break;
1638	case O_GID:
1639		grp = getgrgid(insntod(cmd, u32)->d[0]);
1640		if (grp != NULL)
1641			bprintf(bp, " gid %s", grp->gr_name);
1642		else
1643			bprintf(bp, " gid %u",
1644			    insntod(cmd, u32)->d[0]);
1645		break;
1646	case O_JAIL:
1647		bprintf(bp, " jail %d", insntod(cmd, u32)->d[0]);
1648		break;
1649	case O_VERREVPATH:
1650		bprintf(bp, " verrevpath");
1651		break;
1652	case O_VERSRCREACH:
1653		bprintf(bp, " versrcreach");
1654		break;
1655	case O_ANTISPOOF:
1656		bprintf(bp, " antispoof");
1657		break;
1658	case O_IPSEC:
1659		bprintf(bp, " ipsec");
1660		break;
1661	case O_NOP:
1662		bprintf(bp, " // %s", (char *)(cmd + 1));
1663		break;
1664	case O_KEEP_STATE:
1665		bprintf(bp, " keep-state");
1666		bprintf(bp, " :%s",
1667		    object_search_ctlv(fo->tstate, cmd->arg1,
1668		    IPFW_TLV_STATE_NAME));
1669		break;
1670	case O_LIMIT:
1671		print_limit(bp, insntod(cmd, limit));
1672		bprintf(bp, " :%s",
1673		    object_search_ctlv(fo->tstate, cmd->arg1,
1674		    IPFW_TLV_STATE_NAME));
1675		break;
1676	case O_IP6:
1677		bprintf(bp, " ip6");
1678		break;
1679	case O_IP4:
1680		bprintf(bp, " ip4");
1681		break;
1682	case O_ICMP6TYPE:
1683		print_icmp6types(bp, insntod(cmd, u32));
1684		break;
1685	case O_EXT_HDR:
1686		print_ext6hdr(bp, cmd);
1687		break;
1688	case O_TAGGED:
1689		if (F_LEN(cmd) == 1)
1690			bprint_uint_arg(bp, " tagged ", cmd->arg1);
1691		else
1692			print_newports(bp, insntod(cmd, u16),
1693				    0, O_TAGGED);
1694		break;
1695	default:
1696		bprintf(bp, " [opcode %d len %d]", cmd->opcode,
1697		    cmd->len);
1698	}
1699	if (cmd->len & F_OR) {
1700		bprintf(bp, " or");
1701		state->or_block = 1;
1702	} else if (state->or_block != 0) {
1703		bprintf(bp, " }");
1704		state->or_block = 0;
1705	}
1706	mark_printed(state, cmd);
1707
1708	return (1);
1709}
1710
1711static ipfw_insn *
1712print_opcode(struct buf_pr *bp, struct format_opts *fo,
1713    struct show_state *state, uint8_t opcode)
1714{
1715	ipfw_insn *cmd;
1716	int l;
1717
1718	for (l = state->rule->act_ofs, cmd = state->rule->cmd;
1719	    l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1720		/* We use zero opcode to print the rest of options */
1721		if (opcode != 0 && cmd->opcode != opcode)
1722			continue;
1723		/*
1724		 * Skip O_NOP, when we printing the rest
1725		 * of options, it will be handled separately.
1726		 */
1727		if (cmd->opcode == O_NOP && opcode != O_NOP)
1728			continue;
1729		if (!print_instruction(bp, fo, state, cmd))
1730			continue;
1731		return (cmd);
1732	}
1733	return (NULL);
1734}
1735
1736static void
1737print_fwd(struct buf_pr *bp, const ipfw_insn *cmd)
1738{
1739	char buf[INET6_ADDRSTRLEN + IF_NAMESIZE + 2];
1740	ipfw_insn_sa6 *sa6;
1741	ipfw_insn_sa *sa;
1742	uint16_t port;
1743
1744	if (cmd->opcode == O_FORWARD_IP) {
1745		sa = insntod(cmd, sa);
1746		port = sa->sa.sin_port;
1747		if (sa->sa.sin_addr.s_addr == INADDR_ANY)
1748			bprintf(bp, "fwd tablearg");
1749		else
1750			bprintf(bp, "fwd %s", inet_ntoa(sa->sa.sin_addr));
1751	} else {
1752		sa6 = insntod(cmd, sa6);
1753		port = sa6->sa.sin6_port;
1754		bprintf(bp, "fwd ");
1755		if (getnameinfo((const struct sockaddr *)&sa6->sa,
1756		    sizeof(struct sockaddr_in6), buf, sizeof(buf), NULL, 0,
1757		    NI_NUMERICHOST) == 0)
1758			bprintf(bp, "%s", buf);
1759	}
1760	if (port != 0)
1761		bprintf(bp, ",%u", port);
1762}
1763
1764static int
1765print_action_instruction(struct buf_pr *bp, const struct format_opts *fo,
1766    struct show_state *state, const ipfw_insn *cmd)
1767{
1768	const char *s;
1769
1770	if (is_printed_opcode(state, cmd))
1771		return (0);
1772	switch (cmd->opcode) {
1773	case O_CHECK_STATE:
1774		bprintf(bp, "check-state");
1775		if (cmd->arg1 != 0)
1776			s = object_search_ctlv(fo->tstate, cmd->arg1,
1777			    IPFW_TLV_STATE_NAME);
1778		else
1779			s = NULL;
1780		bprintf(bp, " :%s", s ? s: "any");
1781		break;
1782	case O_ACCEPT:
1783		bprintf(bp, "allow");
1784		break;
1785	case O_COUNT:
1786		bprintf(bp, "count");
1787		break;
1788	case O_DENY:
1789		bprintf(bp, "deny");
1790		break;
1791	case O_REJECT:
1792		if (cmd->arg1 == ICMP_REJECT_RST)
1793			bprintf(bp, "reset");
1794		else if (cmd->arg1 == ICMP_REJECT_ABORT)
1795			bprintf(bp, "abort");
1796		else if (cmd->arg1 == ICMP_UNREACH_HOST)
1797			bprintf(bp, "reject");
1798		else
1799			print_reject_code(bp, cmd->arg1);
1800		break;
1801	case O_UNREACH6:
1802		if (cmd->arg1 == ICMP6_UNREACH_RST)
1803			bprintf(bp, "reset6");
1804		else if (cmd->arg1 == ICMP6_UNREACH_ABORT)
1805			bprintf(bp, "abort6");
1806		else
1807			print_unreach6_code(bp, cmd->arg1);
1808		break;
1809	case O_SKIPTO:
1810		bprint_uint_arg(bp, "skipto ", cmd->arg1);
1811		break;
1812	case O_PIPE:
1813		bprint_uint_arg(bp, "pipe ", cmd->arg1);
1814		break;
1815	case O_QUEUE:
1816		bprint_uint_arg(bp, "queue ", cmd->arg1);
1817		break;
1818	case O_DIVERT:
1819		bprint_uint_arg(bp, "divert ", cmd->arg1);
1820		break;
1821	case O_TEE:
1822		bprint_uint_arg(bp, "tee ", cmd->arg1);
1823		break;
1824	case O_NETGRAPH:
1825		bprint_uint_arg(bp, "netgraph ", cmd->arg1);
1826		break;
1827	case O_NGTEE:
1828		bprint_uint_arg(bp, "ngtee ", cmd->arg1);
1829		break;
1830	case O_FORWARD_IP:
1831	case O_FORWARD_IP6:
1832		print_fwd(bp, cmd);
1833		break;
1834	case O_LOG:
1835		if (insntod(cmd, log)->max_log > 0)
1836			bprintf(bp, " log logamount %d",
1837			    insntod(cmd, log)->max_log);
1838		else
1839			bprintf(bp, " log");
1840		break;
1841	case O_ALTQ:
1842#ifndef NO_ALTQ
1843		print_altq_cmd(bp, insntod(cmd, altq));
1844#endif
1845		break;
1846	case O_TAG:
1847		bprint_uint_arg(bp, cmd->len & F_NOT ? " untag ":
1848		    " tag ", cmd->arg1);
1849		break;
1850	case O_NAT:
1851		if (cmd->arg1 != IP_FW_NAT44_GLOBAL)
1852			bprint_uint_arg(bp, "nat ", cmd->arg1);
1853		else
1854			bprintf(bp, "nat global");
1855		break;
1856	case O_SETFIB:
1857		if (cmd->arg1 == IP_FW_TARG)
1858			bprint_uint_arg(bp, "setfib ", cmd->arg1);
1859		else
1860			bprintf(bp, "setfib %u", cmd->arg1 & 0x7FFF);
1861		break;
1862	case O_EXTERNAL_ACTION:
1863		/*
1864		 * The external action can consists of two following
1865		 * each other opcodes - O_EXTERNAL_ACTION and
1866		 * O_EXTERNAL_INSTANCE. The first contains the ID of
1867		 * name of external action. The second contains the ID
1868		 * of name of external action instance.
1869		 * NOTE: in case when external action has no named
1870		 * instances support, the second opcode isn't needed.
1871		 */
1872		state->eaction = cmd;
1873		s = object_search_ctlv(fo->tstate, cmd->arg1,
1874		    IPFW_TLV_EACTION);
1875		if (match_token(rule_eactions, s) != -1)
1876			bprintf(bp, "%s", s);
1877		else
1878			bprintf(bp, "eaction %s", s);
1879		break;
1880	case O_EXTERNAL_INSTANCE:
1881		if (state->eaction == NULL)
1882			break;
1883		/*
1884		 * XXX: we need to teach ipfw(9) to rewrite opcodes
1885		 * in the user buffer on rule addition. When we add
1886		 * the rule, we specify zero TLV type for
1887		 * O_EXTERNAL_INSTANCE object. To show correct
1888		 * rule after `ipfw add` we need to search instance
1889		 * name with zero type. But when we do `ipfw show`
1890		 * we calculate TLV type using IPFW_TLV_EACTION_NAME()
1891		 * macro.
1892		 */
1893		s = object_search_ctlv(fo->tstate, cmd->arg1, 0);
1894		if (s == NULL)
1895			s = object_search_ctlv(fo->tstate,
1896			    cmd->arg1, IPFW_TLV_EACTION_NAME(
1897			    state->eaction->arg1));
1898		bprintf(bp, " %s", s);
1899		break;
1900	case O_EXTERNAL_DATA:
1901		if (state->eaction == NULL)
1902			break;
1903		/*
1904		 * Currently we support data formatting only for
1905		 * external data with datalen u16. For unknown data
1906		 * print its size in bytes.
1907		 */
1908		if (cmd->len == F_INSN_SIZE(ipfw_insn))
1909			bprintf(bp, " %u", cmd->arg1);
1910		else
1911			bprintf(bp, " %ubytes",
1912			    cmd->len * sizeof(uint32_t));
1913		break;
1914	case O_SETDSCP:
1915		if (cmd->arg1 == IP_FW_TARG) {
1916			bprintf(bp, "setdscp tablearg");
1917			break;
1918		}
1919		s = match_value(f_ipdscp, cmd->arg1 & 0x3F);
1920		if (s != NULL)
1921			bprintf(bp, "setdscp %s", s);
1922		else
1923			bprintf(bp, "setdscp %s", cmd->arg1 & 0x3F);
1924		break;
1925	case O_REASS:
1926		bprintf(bp, "reass");
1927		break;
1928	case O_CALLRETURN:
1929		if (cmd->len & F_NOT)
1930			bprintf(bp, "return");
1931		else
1932			bprint_uint_arg(bp, "call ", cmd->arg1);
1933		break;
1934	default:
1935		bprintf(bp, "** unrecognized action %d len %d ",
1936			cmd->opcode, cmd->len);
1937	}
1938	mark_printed(state, cmd);
1939
1940	return (1);
1941}
1942
1943
1944static ipfw_insn *
1945print_action(struct buf_pr *bp, struct format_opts *fo,
1946    struct show_state *state, uint8_t opcode)
1947{
1948	ipfw_insn *cmd;
1949	int l;
1950
1951	for (l = state->rule->cmd_len - state->rule->act_ofs,
1952	    cmd = ACTION_PTR(state->rule); l > 0;
1953	    l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1954		if (cmd->opcode != opcode)
1955			continue;
1956		if (!print_action_instruction(bp, fo, state, cmd))
1957			continue;
1958		return (cmd);
1959	}
1960	return (NULL);
1961}
1962
1963static void
1964print_proto(struct buf_pr *bp, struct format_opts *fo,
1965    struct show_state *state)
1966{
1967	ipfw_insn *cmd;
1968	int l, proto, ip4, ip6, tmp;
1969
1970	/* Count all O_PROTO, O_IP4, O_IP6 instructions. */
1971	proto = tmp = ip4 = ip6 = 0;
1972	for (l = state->rule->act_ofs, cmd = state->rule->cmd;
1973	    l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1974		switch (cmd->opcode) {
1975		case O_PROTO:
1976			proto++;
1977			break;
1978		case O_IP4:
1979			ip4 = 1;
1980			if (cmd->len & F_OR)
1981				ip4++;
1982			break;
1983		case O_IP6:
1984			ip6 = 1;
1985			if (cmd->len & F_OR)
1986				ip6++;
1987			break;
1988		default:
1989			continue;
1990		}
1991	}
1992	if (proto == 0 && ip4 == 0 && ip6 == 0) {
1993		state->proto = IPPROTO_IP;
1994		state->flags |= HAVE_PROTO;
1995		bprintf(bp, " ip");
1996		return;
1997	}
1998	/* To handle the case { ip4 or ip6 }, print opcode with F_OR first */
1999	cmd = NULL;
2000	if (ip4 || ip6)
2001		cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP4: O_IP6);
2002	if (cmd != NULL && (cmd->len & F_OR))
2003		cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP6: O_IP4);
2004	if (cmd == NULL || (cmd->len & F_OR))
2005		for (l = proto; l > 0; l--) {
2006			cmd = print_opcode(bp, fo, state, O_PROTO);
2007			if (cmd != NULL && (cmd->len & F_OR) == 0)
2008				break;
2009			tmp = cmd->arg1;
2010		}
2011	/* Initialize proto, it is used by print_newports() */
2012	if (tmp != 0)
2013		state->proto = tmp;
2014	else if (ip6 != 0)
2015		state->proto = IPPROTO_IPV6;
2016	else
2017		state->proto = IPPROTO_IP;
2018	state->flags |= HAVE_PROTO;
2019}
2020
2021static int
2022match_opcode(int opcode, const int opcodes[], size_t nops)
2023{
2024	int i;
2025
2026	for (i = 0; i < nops; i++)
2027		if (opcode == opcodes[i])
2028			return (1);
2029	return (0);
2030}
2031
2032static void
2033print_address(struct buf_pr *bp, struct format_opts *fo,
2034    struct show_state *state, const int opcodes[], size_t nops, int portop,
2035    int flag)
2036{
2037	ipfw_insn *cmd;
2038	int count, l, portcnt, pf;
2039
2040	count = portcnt = 0;
2041	for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2042	    l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2043		if (match_opcode(cmd->opcode, opcodes, nops))
2044			count++;
2045		else if (cmd->opcode == portop)
2046			portcnt++;
2047	}
2048	if (count == 0)
2049		bprintf(bp, " any");
2050	for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2051	    l > 0 && count > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2052		if (!match_opcode(cmd->opcode, opcodes, nops))
2053			continue;
2054		print_instruction(bp, fo, state, cmd);
2055		if ((cmd->len & F_OR) == 0)
2056			break;
2057		count--;
2058	}
2059	/*
2060	 * If several O_IP_?PORT opcodes specified, leave them to the
2061	 * options section.
2062	 */
2063	if (portcnt == 1) {
2064		for (l = state->rule->act_ofs, cmd = state->rule->cmd, pf = 0;
2065		    l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2066			if (cmd->opcode != portop) {
2067				pf = (cmd->len & F_OR);
2068				continue;
2069			}
2070			/* Print opcode iff it is not in OR block. */
2071			if (pf == 0 && (cmd->len & F_OR) == 0)
2072				print_instruction(bp, fo, state, cmd);
2073			break;
2074		}
2075	}
2076	state->flags |= flag;
2077}
2078
2079static const int action_opcodes[] = {
2080	O_CHECK_STATE, O_ACCEPT, O_COUNT, O_DENY, O_REJECT,
2081	O_UNREACH6, O_SKIPTO, O_PIPE, O_QUEUE, O_DIVERT, O_TEE,
2082	O_NETGRAPH, O_NGTEE, O_FORWARD_IP, O_FORWARD_IP6, O_NAT,
2083	O_SETFIB, O_SETDSCP, O_REASS, O_CALLRETURN,
2084	/* keep the following opcodes at the end of the list */
2085	O_EXTERNAL_ACTION, O_EXTERNAL_INSTANCE, O_EXTERNAL_DATA
2086};
2087
2088static const int modifier_opcodes[] = {
2089	O_LOG, O_ALTQ, O_TAG
2090};
2091
2092static const int src_opcodes[] = {
2093	O_IP_SRC, O_IP_SRC_LOOKUP, O_IP_SRC_MASK, O_IP_SRC_ME,
2094	O_IP_SRC_SET, O_IP6_SRC, O_IP6_SRC_MASK, O_IP6_SRC_ME
2095};
2096
2097static const int dst_opcodes[] = {
2098	O_IP_DST, O_IP_DST_LOOKUP, O_IP_DST_MASK, O_IP_DST_ME,
2099	O_IP_DST_SET, O_IP6_DST, O_IP6_DST_MASK, O_IP6_DST_ME
2100};
2101
2102static void
2103show_static_rule(struct cmdline_opts *co, struct format_opts *fo,
2104    struct buf_pr *bp, struct ip_fw_rule *rule, struct ip_fw_bcounter *cntr)
2105{
2106	struct show_state state;
2107	ipfw_insn *cmd;
2108	static int twidth = 0;
2109	int i;
2110
2111	/* Print # DISABLED or skip the rule */
2112	if ((fo->set_mask & (1 << rule->set)) == 0) {
2113		/* disabled mask */
2114		if (!co->show_sets)
2115			return;
2116		else
2117			bprintf(bp, "# DISABLED ");
2118	}
2119	if (init_show_state(&state, rule) != 0) {
2120		warn("init_show_state() failed");
2121		return;
2122	}
2123	bprintf(bp, "%05u ", rule->rulenum);
2124
2125	/* Print counters if enabled */
2126	if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2127		pr_u64(bp, &cntr->pcnt, fo->pcwidth);
2128		pr_u64(bp, &cntr->bcnt, fo->bcwidth);
2129	}
2130
2131	/* Print timestamp */
2132	if (co->do_time == TIMESTAMP_NUMERIC)
2133		bprintf(bp, "%10u ", cntr->timestamp);
2134	else if (co->do_time == TIMESTAMP_STRING) {
2135		char timestr[30];
2136		time_t t = (time_t)0;
2137
2138		if (twidth == 0) {
2139			strcpy(timestr, ctime(&t));
2140			*strchr(timestr, '\n') = '\0';
2141			twidth = strlen(timestr);
2142		}
2143		if (cntr->timestamp > 0) {
2144			t = _long_to_time(cntr->timestamp);
2145
2146			strcpy(timestr, ctime(&t));
2147			*strchr(timestr, '\n') = '\0';
2148			bprintf(bp, "%s ", timestr);
2149		} else {
2150			bprintf(bp, "%*s", twidth, " ");
2151		}
2152	}
2153
2154	/* Print set number */
2155	if (co->show_sets)
2156		bprintf(bp, "set %d ", rule->set);
2157
2158	/* Print the optional "match probability" */
2159	cmd = print_opcode(bp, fo, &state, O_PROB);
2160	/* Print rule action */
2161	for (i = 0; i < nitems(action_opcodes); i++) {
2162		cmd = print_action(bp, fo, &state, action_opcodes[i]);
2163		if (cmd == NULL)
2164			continue;
2165		/* Handle special cases */
2166		switch (cmd->opcode) {
2167		case O_CHECK_STATE:
2168			goto end;
2169		case O_EXTERNAL_ACTION:
2170		case O_EXTERNAL_INSTANCE:
2171			/* External action can have several instructions */
2172			continue;
2173		}
2174		break;
2175	}
2176	/* Print rule modifiers */
2177	for (i = 0; i < nitems(modifier_opcodes); i++)
2178		print_action(bp, fo, &state, modifier_opcodes[i]);
2179	/*
2180	 * Print rule body
2181	 */
2182	if (co->comment_only != 0)
2183		goto end;
2184	print_proto(bp, fo, &state);
2185
2186	/* Print source */
2187	bprintf(bp, " from");
2188	print_address(bp, fo, &state, src_opcodes, nitems(src_opcodes),
2189	    O_IP_SRCPORT, HAVE_SRCIP);
2190
2191	/* Print destination */
2192	bprintf(bp, " to");
2193	print_address(bp, fo, &state, dst_opcodes, nitems(dst_opcodes),
2194	    O_IP_DSTPORT, HAVE_DSTIP);
2195
2196	/* Print the rest of options */
2197	while (print_opcode(bp, fo, &state, 0))
2198		;
2199end:
2200	/* Print comment at the end */
2201	cmd = print_opcode(bp, fo, &state, O_NOP);
2202	if (co->comment_only != 0 && cmd == NULL)
2203		bprintf(bp, " // ...");
2204	bprintf(bp, "\n");
2205	free_show_state(&state);
2206}
2207
2208static void
2209show_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2210    struct buf_pr *bp, ipfw_dyn_rule *d)
2211{
2212	struct protoent *pe;
2213	struct in_addr a;
2214	uint16_t rulenum;
2215	char buf[INET6_ADDRSTRLEN];
2216
2217	if (!co->do_expired) {
2218		if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
2219			return;
2220	}
2221	bcopy(&d->rule, &rulenum, sizeof(rulenum));
2222	bprintf(bp, "%05d", rulenum);
2223	if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2224		bprintf(bp, " ");
2225		pr_u64(bp, &d->pcnt, fo->pcwidth);
2226		pr_u64(bp, &d->bcnt, fo->bcwidth);
2227		bprintf(bp, "(%ds)", d->expire);
2228	}
2229	switch (d->dyn_type) {
2230	case O_LIMIT_PARENT:
2231		bprintf(bp, " PARENT %d", d->count);
2232		break;
2233	case O_LIMIT:
2234		bprintf(bp, " LIMIT");
2235		break;
2236	case O_KEEP_STATE: /* bidir, no mask */
2237		bprintf(bp, " STATE");
2238		break;
2239	}
2240
2241	if ((pe = getprotobynumber(d->id.proto)) != NULL)
2242		bprintf(bp, " %s", pe->p_name);
2243	else
2244		bprintf(bp, " proto %u", d->id.proto);
2245
2246	if (d->id.addr_type == 4) {
2247		a.s_addr = htonl(d->id.src_ip);
2248		bprintf(bp, " %s %d", inet_ntoa(a), d->id.src_port);
2249
2250		a.s_addr = htonl(d->id.dst_ip);
2251		bprintf(bp, " <-> %s %d", inet_ntoa(a), d->id.dst_port);
2252	} else if (d->id.addr_type == 6) {
2253		bprintf(bp, " %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2254		    sizeof(buf)), d->id.src_port);
2255		bprintf(bp, " <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6,
2256		    buf, sizeof(buf)), d->id.dst_port);
2257	} else
2258		bprintf(bp, " UNKNOWN <-> UNKNOWN");
2259	if (d->kidx != 0)
2260		bprintf(bp, " :%s", object_search_ctlv(fo->tstate,
2261		    d->kidx, IPFW_TLV_STATE_NAME));
2262}
2263
2264static int
2265do_range_cmd(int cmd, ipfw_range_tlv *rt)
2266{
2267	ipfw_range_header rh;
2268	size_t sz;
2269
2270	memset(&rh, 0, sizeof(rh));
2271	memcpy(&rh.range, rt, sizeof(*rt));
2272	rh.range.head.length = sizeof(*rt);
2273	rh.range.head.type = IPFW_TLV_RANGE;
2274	sz = sizeof(rh);
2275
2276	if (do_get3(cmd, &rh.opheader, &sz) != 0)
2277		return (-1);
2278	/* Save number of matched objects */
2279	rt->new_set = rh.range.new_set;
2280	return (0);
2281}
2282
2283/*
2284 * This one handles all set-related commands
2285 * 	ipfw set { show | enable | disable }
2286 * 	ipfw set swap X Y
2287 * 	ipfw set move X to Y
2288 * 	ipfw set move rule X to Y
2289 */
2290void
2291ipfw_sets_handler(char *av[])
2292{
2293	ipfw_range_tlv rt;
2294	char *msg;
2295	size_t size;
2296	uint32_t masks[2];
2297	int i;
2298	uint16_t rulenum;
2299	uint8_t cmd;
2300
2301	av++;
2302	memset(&rt, 0, sizeof(rt));
2303
2304	if (av[0] == NULL)
2305		errx(EX_USAGE, "set needs command");
2306	if (_substrcmp(*av, "show") == 0) {
2307		struct format_opts fo;
2308		ipfw_cfg_lheader *cfg;
2309
2310		memset(&fo, 0, sizeof(fo));
2311		if (ipfw_get_config(&co, &fo, &cfg, &size) != 0)
2312			err(EX_OSERR, "requesting config failed");
2313
2314		for (i = 0, msg = "disable"; i < RESVD_SET; i++)
2315			if ((cfg->set_mask & (1<<i)) == 0) {
2316				printf("%s %d", msg, i);
2317				msg = "";
2318			}
2319		msg = (cfg->set_mask != (uint32_t)-1) ? " enable" : "enable";
2320		for (i = 0; i < RESVD_SET; i++)
2321			if ((cfg->set_mask & (1<<i)) != 0) {
2322				printf("%s %d", msg, i);
2323				msg = "";
2324			}
2325		printf("\n");
2326		free(cfg);
2327	} else if (_substrcmp(*av, "swap") == 0) {
2328		av++;
2329		if ( av[0] == NULL || av[1] == NULL )
2330			errx(EX_USAGE, "set swap needs 2 set numbers\n");
2331		rt.set = atoi(av[0]);
2332		rt.new_set = atoi(av[1]);
2333		if (!isdigit(*(av[0])) || rt.set > RESVD_SET)
2334			errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2335		if (!isdigit(*(av[1])) || rt.new_set > RESVD_SET)
2336			errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2337		i = do_range_cmd(IP_FW_SET_SWAP, &rt);
2338	} else if (_substrcmp(*av, "move") == 0) {
2339		av++;
2340		if (av[0] && _substrcmp(*av, "rule") == 0) {
2341			rt.flags = IPFW_RCFLAG_RANGE; /* move rules to new set */
2342			cmd = IP_FW_XMOVE;
2343			av++;
2344		} else
2345			cmd = IP_FW_SET_MOVE; /* Move set to new one */
2346		if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
2347				av[3] != NULL ||  _substrcmp(av[1], "to") != 0)
2348			errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2349		rulenum = atoi(av[0]);
2350		rt.new_set = atoi(av[2]);
2351		if (cmd == IP_FW_XMOVE) {
2352			rt.start_rule = rulenum;
2353			rt.end_rule = rulenum;
2354		} else
2355			rt.set = rulenum;
2356		rt.new_set = atoi(av[2]);
2357		if (!isdigit(*(av[0])) || (cmd == 3 && rt.set > RESVD_SET) ||
2358			(cmd == 2 && rt.start_rule == IPFW_DEFAULT_RULE) )
2359			errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2360		if (!isdigit(*(av[2])) || rt.new_set > RESVD_SET)
2361			errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2362		i = do_range_cmd(cmd, &rt);
2363		if (i < 0)
2364			err(EX_OSERR, "failed to move %s",
2365			    cmd == IP_FW_SET_MOVE ? "set": "rule");
2366	} else if (_substrcmp(*av, "disable") == 0 ||
2367		   _substrcmp(*av, "enable") == 0 ) {
2368		int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2369
2370		av++;
2371		masks[0] = masks[1] = 0;
2372
2373		while (av[0]) {
2374			if (isdigit(**av)) {
2375				i = atoi(*av);
2376				if (i < 0 || i > RESVD_SET)
2377					errx(EX_DATAERR,
2378					    "invalid set number %d\n", i);
2379				masks[which] |= (1<<i);
2380			} else if (_substrcmp(*av, "disable") == 0)
2381				which = 0;
2382			else if (_substrcmp(*av, "enable") == 0)
2383				which = 1;
2384			else
2385				errx(EX_DATAERR,
2386					"invalid set command %s\n", *av);
2387			av++;
2388		}
2389		if ( (masks[0] & masks[1]) != 0 )
2390			errx(EX_DATAERR,
2391			    "cannot enable and disable the same set\n");
2392
2393		rt.set = masks[0];
2394		rt.new_set = masks[1];
2395		i = do_range_cmd(IP_FW_SET_ENABLE, &rt);
2396		if (i)
2397			warn("set enable/disable: setsockopt(IP_FW_SET_ENABLE)");
2398	} else
2399		errx(EX_USAGE, "invalid set command %s\n", *av);
2400}
2401
2402void
2403ipfw_sysctl_handler(char *av[], int which)
2404{
2405	av++;
2406
2407	if (av[0] == NULL) {
2408		warnx("missing keyword to enable/disable\n");
2409	} else if (_substrcmp(*av, "firewall") == 0) {
2410		sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2411		    &which, sizeof(which));
2412		sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
2413		    &which, sizeof(which));
2414	} else if (_substrcmp(*av, "one_pass") == 0) {
2415		sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2416		    &which, sizeof(which));
2417	} else if (_substrcmp(*av, "debug") == 0) {
2418		sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2419		    &which, sizeof(which));
2420	} else if (_substrcmp(*av, "verbose") == 0) {
2421		sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2422		    &which, sizeof(which));
2423	} else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2424		sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2425		    &which, sizeof(which));
2426#ifndef NO_ALTQ
2427	} else if (_substrcmp(*av, "altq") == 0) {
2428		altq_set_enabled(which);
2429#endif
2430	} else {
2431		warnx("unrecognize enable/disable keyword: %s\n", *av);
2432	}
2433}
2434
2435typedef void state_cb(struct cmdline_opts *co, struct format_opts *fo,
2436    void *arg, void *state);
2437
2438static void
2439prepare_format_dyn(struct cmdline_opts *co, struct format_opts *fo,
2440    void *arg, void *_state)
2441{
2442	ipfw_dyn_rule *d;
2443	int width;
2444	uint8_t set;
2445
2446	d = (ipfw_dyn_rule *)_state;
2447	/* Count _ALL_ states */
2448	fo->dcnt++;
2449
2450	if (fo->show_counters == 0)
2451		return;
2452
2453	if (co->use_set) {
2454		/* skip states from another set */
2455		bcopy((char *)&d->rule + sizeof(uint16_t), &set,
2456		    sizeof(uint8_t));
2457		if (set != co->use_set - 1)
2458			return;
2459	}
2460
2461	width = pr_u64(NULL, &d->pcnt, 0);
2462	if (width > fo->pcwidth)
2463		fo->pcwidth = width;
2464
2465	width = pr_u64(NULL, &d->bcnt, 0);
2466	if (width > fo->bcwidth)
2467		fo->bcwidth = width;
2468}
2469
2470static int
2471foreach_state(struct cmdline_opts *co, struct format_opts *fo,
2472    caddr_t base, size_t sz, state_cb dyn_bc, void *dyn_arg)
2473{
2474	int ttype;
2475	state_cb *fptr;
2476	void *farg;
2477	ipfw_obj_tlv *tlv;
2478	ipfw_obj_ctlv *ctlv;
2479
2480	fptr = NULL;
2481	ttype = 0;
2482
2483	while (sz > 0) {
2484		ctlv = (ipfw_obj_ctlv *)base;
2485		switch (ctlv->head.type) {
2486		case IPFW_TLV_DYNSTATE_LIST:
2487			base += sizeof(*ctlv);
2488			sz -= sizeof(*ctlv);
2489			ttype = IPFW_TLV_DYN_ENT;
2490			fptr = dyn_bc;
2491			farg = dyn_arg;
2492			break;
2493		default:
2494			return (sz);
2495		}
2496
2497		while (sz > 0) {
2498			tlv = (ipfw_obj_tlv *)base;
2499			if (tlv->type != ttype)
2500				break;
2501
2502			fptr(co, fo, farg, tlv + 1);
2503			sz -= tlv->length;
2504			base += tlv->length;
2505		}
2506	}
2507
2508	return (sz);
2509}
2510
2511static void
2512prepare_format_opts(struct cmdline_opts *co, struct format_opts *fo,
2513    ipfw_obj_tlv *rtlv, int rcnt, caddr_t dynbase, size_t dynsz)
2514{
2515	int bcwidth, pcwidth, width;
2516	int n;
2517	struct ip_fw_bcounter *cntr;
2518	struct ip_fw_rule *r;
2519
2520	bcwidth = 0;
2521	pcwidth = 0;
2522	if (fo->show_counters != 0) {
2523		for (n = 0; n < rcnt; n++,
2524		    rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2525			cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2526			r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2527			/* skip rules from another set */
2528			if (co->use_set && r->set != co->use_set - 1)
2529				continue;
2530
2531			/* packet counter */
2532			width = pr_u64(NULL, &cntr->pcnt, 0);
2533			if (width > pcwidth)
2534				pcwidth = width;
2535
2536			/* byte counter */
2537			width = pr_u64(NULL, &cntr->bcnt, 0);
2538			if (width > bcwidth)
2539				bcwidth = width;
2540		}
2541	}
2542	fo->bcwidth = bcwidth;
2543	fo->pcwidth = pcwidth;
2544
2545	fo->dcnt = 0;
2546	if (co->do_dynamic && dynsz > 0)
2547		foreach_state(co, fo, dynbase, dynsz, prepare_format_dyn, NULL);
2548}
2549
2550static int
2551list_static_range(struct cmdline_opts *co, struct format_opts *fo,
2552    struct buf_pr *bp, ipfw_obj_tlv *rtlv, int rcnt)
2553{
2554	int n, seen;
2555	struct ip_fw_rule *r;
2556	struct ip_fw_bcounter *cntr;
2557	int c = 0;
2558
2559	for (n = seen = 0; n < rcnt; n++,
2560	    rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2561
2562		if ((fo->show_counters | fo->show_time) != 0) {
2563			cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2564			r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2565		} else {
2566			cntr = NULL;
2567			r = (struct ip_fw_rule *)(rtlv + 1);
2568		}
2569		if (r->rulenum > fo->last)
2570			break;
2571		if (co->use_set && r->set != co->use_set - 1)
2572			continue;
2573		if (r->rulenum >= fo->first && r->rulenum <= fo->last) {
2574			show_static_rule(co, fo, bp, r, cntr);
2575			printf("%s", bp->buf);
2576			c += rtlv->length;
2577			bp_flush(bp);
2578			seen++;
2579		}
2580	}
2581
2582	return (seen);
2583}
2584
2585static void
2586list_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2587    void *_arg, void *_state)
2588{
2589	uint16_t rulenum;
2590	uint8_t set;
2591	ipfw_dyn_rule *d;
2592	struct buf_pr *bp;
2593
2594	d = (ipfw_dyn_rule *)_state;
2595	bp = (struct buf_pr *)_arg;
2596
2597	bcopy(&d->rule, &rulenum, sizeof(rulenum));
2598	if (rulenum > fo->last)
2599		return;
2600	if (co->use_set) {
2601		bcopy((char *)&d->rule + sizeof(uint16_t),
2602		      &set, sizeof(uint8_t));
2603		if (set != co->use_set - 1)
2604			return;
2605	}
2606	if (rulenum >= fo->first) {
2607		show_dyn_state(co, fo, bp, d);
2608		printf("%s\n", bp->buf);
2609		bp_flush(bp);
2610	}
2611}
2612
2613static int
2614list_dyn_range(struct cmdline_opts *co, struct format_opts *fo,
2615    struct buf_pr *bp, caddr_t base, size_t sz)
2616{
2617
2618	sz = foreach_state(co, fo, base, sz, list_dyn_state, bp);
2619	return (sz);
2620}
2621
2622void
2623ipfw_list(int ac, char *av[], int show_counters)
2624{
2625	ipfw_cfg_lheader *cfg;
2626	struct format_opts sfo;
2627	size_t sz;
2628	int error;
2629	int lac;
2630	char **lav;
2631	uint32_t rnum;
2632	char *endptr;
2633
2634	if (co.test_only) {
2635		fprintf(stderr, "Testing only, list disabled\n");
2636		return;
2637	}
2638	if (co.do_pipe) {
2639		dummynet_list(ac, av, show_counters);
2640		return;
2641	}
2642
2643	ac--;
2644	av++;
2645	memset(&sfo, 0, sizeof(sfo));
2646
2647	/* Determine rule range to request */
2648	if (ac > 0) {
2649		for (lac = ac, lav = av; lac != 0; lac--) {
2650			rnum = strtoul(*lav++, &endptr, 10);
2651			if (sfo.first == 0 || rnum < sfo.first)
2652				sfo.first = rnum;
2653
2654			if (*endptr == '-')
2655				rnum = strtoul(endptr + 1, &endptr, 10);
2656			if (sfo.last == 0 || rnum > sfo.last)
2657				sfo.last = rnum;
2658		}
2659	}
2660
2661	/* get configuraion from kernel */
2662	cfg = NULL;
2663	sfo.show_counters = show_counters;
2664	sfo.show_time = co.do_time;
2665	sfo.flags = IPFW_CFG_GET_STATIC;
2666	if (co.do_dynamic != 0)
2667		sfo.flags |= IPFW_CFG_GET_STATES;
2668	if ((sfo.show_counters | sfo.show_time) != 0)
2669		sfo.flags |= IPFW_CFG_GET_COUNTERS;
2670	if (ipfw_get_config(&co, &sfo, &cfg, &sz) != 0)
2671		err(EX_OSERR, "retrieving config failed");
2672
2673	error = ipfw_show_config(&co, &sfo, cfg, sz, ac, av);
2674
2675	free(cfg);
2676
2677	if (error != EX_OK)
2678		exit(error);
2679}
2680
2681static int
2682ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
2683    ipfw_cfg_lheader *cfg, size_t sz, int ac, char *av[])
2684{
2685	caddr_t dynbase;
2686	size_t dynsz;
2687	int rcnt;
2688	int exitval = EX_OK;
2689	int lac;
2690	char **lav;
2691	char *endptr;
2692	size_t readsz;
2693	struct buf_pr bp;
2694	ipfw_obj_ctlv *ctlv, *tstate;
2695	ipfw_obj_tlv *rbase;
2696
2697	/*
2698	 * Handle tablenames TLV first, if any
2699	 */
2700	tstate = NULL;
2701	rbase = NULL;
2702	dynbase = NULL;
2703	dynsz = 0;
2704	readsz = sizeof(*cfg);
2705	rcnt = 0;
2706
2707	fo->set_mask = cfg->set_mask;
2708
2709	ctlv = (ipfw_obj_ctlv *)(cfg + 1);
2710
2711	if (cfg->flags & IPFW_CFG_GET_STATIC) {
2712		/* We've requested static rules */
2713		if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2714			object_sort_ctlv(ctlv);
2715			fo->tstate = ctlv;
2716			readsz += ctlv->head.length;
2717			ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2718			    ctlv->head.length);
2719		}
2720
2721		if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2722			rbase = (ipfw_obj_tlv *)(ctlv + 1);
2723			rcnt = ctlv->count;
2724			readsz += ctlv->head.length;
2725			ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2726			    ctlv->head.length);
2727		}
2728	}
2729
2730	if ((cfg->flags & IPFW_CFG_GET_STATES) && (readsz != sz))  {
2731		/* We may have some dynamic states */
2732		dynsz = sz - readsz;
2733		/* Skip empty header */
2734		if (dynsz != sizeof(ipfw_obj_ctlv))
2735			dynbase = (caddr_t)ctlv;
2736		else
2737			dynsz = 0;
2738	}
2739
2740	prepare_format_opts(co, fo, rbase, rcnt, dynbase, dynsz);
2741	bp_alloc(&bp, 4096);
2742
2743	/* if no rule numbers were specified, list all rules */
2744	if (ac == 0) {
2745		fo->first = 0;
2746		fo->last = IPFW_DEFAULT_RULE;
2747		list_static_range(co, fo, &bp, rbase, rcnt);
2748
2749		if (co->do_dynamic && dynsz > 0) {
2750			printf("## Dynamic rules (%d %zu):\n", fo->dcnt, dynsz);
2751			list_dyn_range(co, fo, &bp, dynbase, dynsz);
2752		}
2753
2754		bp_free(&bp);
2755		return (EX_OK);
2756	}
2757
2758	/* display specific rules requested on command line */
2759	for (lac = ac, lav = av; lac != 0; lac--) {
2760		/* convert command line rule # */
2761		fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2762		if (*endptr == '-')
2763			fo->last = strtoul(endptr + 1, &endptr, 10);
2764		if (*endptr) {
2765			exitval = EX_USAGE;
2766			warnx("invalid rule number: %s", *(lav - 1));
2767			continue;
2768		}
2769
2770		if (list_static_range(co, fo, &bp, rbase, rcnt) == 0) {
2771			/* give precedence to other error(s) */
2772			if (exitval == EX_OK)
2773				exitval = EX_UNAVAILABLE;
2774			if (fo->first == fo->last)
2775				warnx("rule %u does not exist", fo->first);
2776			else
2777				warnx("no rules in range %u-%u",
2778				    fo->first, fo->last);
2779		}
2780	}
2781
2782	if (co->do_dynamic && dynsz > 0) {
2783		printf("## Dynamic rules:\n");
2784		for (lac = ac, lav = av; lac != 0; lac--) {
2785			fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2786			if (*endptr == '-')
2787				fo->last = strtoul(endptr+1, &endptr, 10);
2788			if (*endptr)
2789				/* already warned */
2790				continue;
2791			list_dyn_range(co, fo, &bp, dynbase, dynsz);
2792		}
2793	}
2794
2795	bp_free(&bp);
2796	return (exitval);
2797}
2798
2799
2800/*
2801 * Retrieves current ipfw configuration of given type
2802 * and stores its pointer to @pcfg.
2803 *
2804 * Caller is responsible for freeing @pcfg.
2805 *
2806 * Returns 0 on success.
2807 */
2808
2809static int
2810ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
2811    ipfw_cfg_lheader **pcfg, size_t *psize)
2812{
2813	ipfw_cfg_lheader *cfg;
2814	size_t sz;
2815	int i;
2816
2817
2818	if (co->test_only != 0) {
2819		fprintf(stderr, "Testing only, list disabled\n");
2820		return (0);
2821	}
2822
2823	/* Start with some data size */
2824	sz = 4096;
2825	cfg = NULL;
2826
2827	for (i = 0; i < 16; i++) {
2828		if (cfg != NULL)
2829			free(cfg);
2830		if ((cfg = calloc(1, sz)) == NULL)
2831			return (ENOMEM);
2832
2833		cfg->flags = fo->flags;
2834		cfg->start_rule = fo->first;
2835		cfg->end_rule = fo->last;
2836
2837		if (do_get3(IP_FW_XGET, &cfg->opheader, &sz) != 0) {
2838			if (errno != ENOMEM) {
2839				free(cfg);
2840				return (errno);
2841			}
2842
2843			/* Buffer size is not enough. Try to increase */
2844			sz = sz * 2;
2845			if (sz < cfg->size)
2846				sz = cfg->size;
2847			continue;
2848		}
2849
2850		*pcfg = cfg;
2851		*psize = sz;
2852		return (0);
2853	}
2854
2855	free(cfg);
2856	return (ENOMEM);
2857}
2858
2859static int
2860lookup_host (char *host, struct in_addr *ipaddr)
2861{
2862	struct hostent *he;
2863
2864	if (!inet_aton(host, ipaddr)) {
2865		if ((he = gethostbyname(host)) == NULL)
2866			return(-1);
2867		*ipaddr = *(struct in_addr *)he->h_addr_list[0];
2868	}
2869	return(0);
2870}
2871
2872struct tidx {
2873	ipfw_obj_ntlv *idx;
2874	uint32_t count;
2875	uint32_t size;
2876	uint16_t counter;
2877	uint8_t set;
2878};
2879
2880int
2881ipfw_check_object_name(const char *name)
2882{
2883	int c, i, l;
2884
2885	/*
2886	 * Check that name is null-terminated and contains
2887	 * valid symbols only. Valid mask is:
2888	 * [a-zA-Z0-9\-_\.]{1,63}
2889	 */
2890	l = strlen(name);
2891	if (l == 0 || l >= 64)
2892		return (EINVAL);
2893	for (i = 0; i < l; i++) {
2894		c = name[i];
2895		if (isalpha(c) || isdigit(c) || c == '_' ||
2896		    c == '-' || c == '.')
2897			continue;
2898		return (EINVAL);
2899	}
2900	return (0);
2901}
2902
2903static char *default_state_name = "default";
2904static int
2905state_check_name(const char *name)
2906{
2907
2908	if (ipfw_check_object_name(name) != 0)
2909		return (EINVAL);
2910	if (strcmp(name, "any") == 0)
2911		return (EINVAL);
2912	return (0);
2913}
2914
2915static int
2916eaction_check_name(const char *name)
2917{
2918
2919	if (ipfw_check_object_name(name) != 0)
2920		return (EINVAL);
2921	/* Restrict some 'special' names */
2922	if (match_token(rule_actions, name) != -1 &&
2923	    match_token(rule_action_params, name) != -1)
2924		return (EINVAL);
2925	return (0);
2926}
2927
2928static uint16_t
2929pack_object(struct tidx *tstate, char *name, int otype)
2930{
2931	int i;
2932	ipfw_obj_ntlv *ntlv;
2933
2934	for (i = 0; i < tstate->count; i++) {
2935		if (strcmp(tstate->idx[i].name, name) != 0)
2936			continue;
2937		if (tstate->idx[i].set != tstate->set)
2938			continue;
2939		if (tstate->idx[i].head.type != otype)
2940			continue;
2941
2942		return (tstate->idx[i].idx);
2943	}
2944
2945	if (tstate->count + 1 > tstate->size) {
2946		tstate->size += 4;
2947		tstate->idx = realloc(tstate->idx, tstate->size *
2948		    sizeof(ipfw_obj_ntlv));
2949		if (tstate->idx == NULL)
2950			return (0);
2951	}
2952
2953	ntlv = &tstate->idx[i];
2954	memset(ntlv, 0, sizeof(ipfw_obj_ntlv));
2955	strlcpy(ntlv->name, name, sizeof(ntlv->name));
2956	ntlv->head.type = otype;
2957	ntlv->head.length = sizeof(ipfw_obj_ntlv);
2958	ntlv->set = tstate->set;
2959	ntlv->idx = ++tstate->counter;
2960	tstate->count++;
2961
2962	return (ntlv->idx);
2963}
2964
2965static uint16_t
2966pack_table(struct tidx *tstate, char *name)
2967{
2968
2969	if (table_check_name(name) != 0)
2970		return (0);
2971
2972	return (pack_object(tstate, name, IPFW_TLV_TBL_NAME));
2973}
2974
2975void
2976fill_table(struct _ipfw_insn *cmd, char *av, uint8_t opcode,
2977    struct tidx *tstate)
2978{
2979	uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2980	uint16_t uidx;
2981	char *p;
2982
2983	if ((p = strchr(av + 6, ')')) == NULL)
2984		errx(EX_DATAERR, "forgotten parenthesis: '%s'", av);
2985	*p = '\0';
2986	p = strchr(av + 6, ',');
2987	if (p)
2988		*p++ = '\0';
2989
2990	if ((uidx = pack_table(tstate, av + 6)) == 0)
2991		errx(EX_DATAERR, "Invalid table name: %s", av + 6);
2992
2993	cmd->opcode = opcode;
2994	cmd->arg1 = uidx;
2995	if (p) {
2996		cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
2997		d[0] = strtoul(p, NULL, 0);
2998	} else
2999		cmd->len |= F_INSN_SIZE(ipfw_insn);
3000}
3001
3002
3003/*
3004 * fills the addr and mask fields in the instruction as appropriate from av.
3005 * Update length as appropriate.
3006 * The following formats are allowed:
3007 *	me	returns O_IP_*_ME
3008 *	1.2.3.4		single IP address
3009 *	1.2.3.4:5.6.7.8	address:mask
3010 *	1.2.3.4/24	address/mask
3011 *	1.2.3.4/26{1,6,5,4,23}	set of addresses in a subnet
3012 * We can have multiple comma-separated address/mask entries.
3013 */
3014static void
3015fill_ip(ipfw_insn_ip *cmd, char *av, int cblen, struct tidx *tstate)
3016{
3017	int len = 0;
3018	uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
3019
3020	cmd->o.len &= ~F_LEN_MASK;	/* zero len */
3021
3022	if (_substrcmp(av, "any") == 0)
3023		return;
3024
3025	if (_substrcmp(av, "me") == 0) {
3026		cmd->o.len |= F_INSN_SIZE(ipfw_insn);
3027		return;
3028	}
3029
3030	if (strncmp(av, "table(", 6) == 0) {
3031		fill_table(&cmd->o, av, O_IP_DST_LOOKUP, tstate);
3032		return;
3033	}
3034
3035    while (av) {
3036	/*
3037	 * After the address we can have '/' or ':' indicating a mask,
3038	 * ',' indicating another address follows, '{' indicating a
3039	 * set of addresses of unspecified size.
3040	 */
3041	char *t = NULL, *p = strpbrk(av, "/:,{");
3042	int masklen;
3043	char md, nd = '\0';
3044
3045	CHECK_LENGTH(cblen, F_INSN_SIZE(ipfw_insn) + 2 + len);
3046
3047	if (p) {
3048		md = *p;
3049		*p++ = '\0';
3050		if ((t = strpbrk(p, ",{")) != NULL) {
3051			nd = *t;
3052			*t = '\0';
3053		}
3054	} else
3055		md = '\0';
3056
3057	if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
3058		errx(EX_NOHOST, "hostname ``%s'' unknown", av);
3059	switch (md) {
3060	case ':':
3061		if (!inet_aton(p, (struct in_addr *)&d[1]))
3062			errx(EX_DATAERR, "bad netmask ``%s''", p);
3063		break;
3064	case '/':
3065		masklen = atoi(p);
3066		if (masklen == 0)
3067			d[1] = htonl(0U);	/* mask */
3068		else if (masklen > 32)
3069			errx(EX_DATAERR, "bad width ``%s''", p);
3070		else
3071			d[1] = htonl(~0U << (32 - masklen));
3072		break;
3073	case '{':	/* no mask, assume /24 and put back the '{' */
3074		d[1] = htonl(~0U << (32 - 24));
3075		*(--p) = md;
3076		break;
3077
3078	case ',':	/* single address plus continuation */
3079		*(--p) = md;
3080		/* FALLTHROUGH */
3081	case 0:		/* initialization value */
3082	default:
3083		d[1] = htonl(~0U);	/* force /32 */
3084		break;
3085	}
3086	d[0] &= d[1];		/* mask base address with mask */
3087	if (t)
3088		*t = nd;
3089	/* find next separator */
3090	if (p)
3091		p = strpbrk(p, ",{");
3092	if (p && *p == '{') {
3093		/*
3094		 * We have a set of addresses. They are stored as follows:
3095		 *   arg1	is the set size (powers of 2, 2..256)
3096		 *   addr	is the base address IN HOST FORMAT
3097		 *   mask..	is an array of arg1 bits (rounded up to
3098		 *		the next multiple of 32) with bits set
3099		 *		for each host in the map.
3100		 */
3101		uint32_t *map = (uint32_t *)&cmd->mask;
3102		int low, high;
3103		int i = contigmask((uint8_t *)&(d[1]), 32);
3104
3105		if (len > 0)
3106			errx(EX_DATAERR, "address set cannot be in a list");
3107		if (i < 24 || i > 31)
3108			errx(EX_DATAERR, "invalid set with mask %d\n", i);
3109		cmd->o.arg1 = 1<<(32-i);	/* map length		*/
3110		d[0] = ntohl(d[0]);		/* base addr in host format */
3111		cmd->o.opcode = O_IP_DST_SET;	/* default */
3112		cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
3113		for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
3114			map[i] = 0;	/* clear map */
3115
3116		av = p + 1;
3117		low = d[0] & 0xff;
3118		high = low + cmd->o.arg1 - 1;
3119		/*
3120		 * Here, i stores the previous value when we specify a range
3121		 * of addresses within a mask, e.g. 45-63. i = -1 means we
3122		 * have no previous value.
3123		 */
3124		i = -1;	/* previous value in a range */
3125		while (isdigit(*av)) {
3126			char *s;
3127			int a = strtol(av, &s, 0);
3128
3129			if (s == av) { /* no parameter */
3130			    if (*av != '}')
3131				errx(EX_DATAERR, "set not closed\n");
3132			    if (i != -1)
3133				errx(EX_DATAERR, "incomplete range %d-", i);
3134			    break;
3135			}
3136			if (a < low || a > high)
3137			    errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
3138				a, low, high);
3139			a -= low;
3140			if (i == -1)	/* no previous in range */
3141			    i = a;
3142			else {		/* check that range is valid */
3143			    if (i > a)
3144				errx(EX_DATAERR, "invalid range %d-%d",
3145					i+low, a+low);
3146			    if (*s == '-')
3147				errx(EX_DATAERR, "double '-' in range");
3148			}
3149			for (; i <= a; i++)
3150			    map[i/32] |= 1<<(i & 31);
3151			i = -1;
3152			if (*s == '-')
3153			    i = a;
3154			else if (*s == '}')
3155			    break;
3156			av = s+1;
3157		}
3158		return;
3159	}
3160	av = p;
3161	if (av)			/* then *av must be a ',' */
3162		av++;
3163
3164	/* Check this entry */
3165	if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
3166		/*
3167		 * 'any' turns the entire list into a NOP.
3168		 * 'not any' never matches, so it is removed from the
3169		 * list unless it is the only item, in which case we
3170		 * report an error.
3171		 */
3172		if (cmd->o.len & F_NOT) {	/* "not any" never matches */
3173			if (av == NULL && len == 0) /* only this entry */
3174				errx(EX_DATAERR, "not any never matches");
3175		}
3176		/* else do nothing and skip this entry */
3177		return;
3178	}
3179	/* A single IP can be stored in an optimized format */
3180	if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
3181		cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
3182		return;
3183	}
3184	len += 2;	/* two words... */
3185	d += 2;
3186    } /* end while */
3187    if (len + 1 > F_LEN_MASK)
3188	errx(EX_DATAERR, "address list too long");
3189    cmd->o.len |= len+1;
3190}
3191
3192
3193/* n2mask sets n bits of the mask */
3194void
3195n2mask(struct in6_addr *mask, int n)
3196{
3197	static int	minimask[9] =
3198	    { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
3199	u_char		*p;
3200
3201	memset(mask, 0, sizeof(struct in6_addr));
3202	p = (u_char *) mask;
3203	for (; n > 0; p++, n -= 8) {
3204		if (n >= 8)
3205			*p = 0xff;
3206		else
3207			*p = minimask[n];
3208	}
3209	return;
3210}
3211
3212static void
3213fill_flags_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3214	struct _s_x *flags, char *p)
3215{
3216	char *e;
3217	uint32_t set = 0, clear = 0;
3218
3219	if (fill_flags(flags, p, &e, &set, &clear) != 0)
3220		errx(EX_DATAERR, "invalid flag %s", e);
3221
3222	cmd->opcode = opcode;
3223	cmd->len =  (cmd->len & (F_NOT | F_OR)) | 1;
3224	cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3225}
3226
3227
3228void
3229ipfw_delete(char *av[])
3230{
3231	ipfw_range_tlv rt;
3232	char *sep;
3233	int i, j;
3234	int exitval = EX_OK;
3235	int do_set = 0;
3236
3237	av++;
3238	NEED1("missing rule specification");
3239	if ( *av && _substrcmp(*av, "set") == 0) {
3240		/* Do not allow using the following syntax:
3241		 *	ipfw set N delete set M
3242		 */
3243		if (co.use_set)
3244			errx(EX_DATAERR, "invalid syntax");
3245		do_set = 1;	/* delete set */
3246		av++;
3247	}
3248
3249	/* Rule number */
3250	while (*av && isdigit(**av)) {
3251		i = strtol(*av, &sep, 10);
3252		j = i;
3253		if (*sep== '-')
3254			j = strtol(sep + 1, NULL, 10);
3255		av++;
3256		if (co.do_nat) {
3257			exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
3258			if (exitval) {
3259				exitval = EX_UNAVAILABLE;
3260				warn("rule %u not available", i);
3261			}
3262 		} else if (co.do_pipe) {
3263			exitval = ipfw_delete_pipe(co.do_pipe, i);
3264		} else {
3265			memset(&rt, 0, sizeof(rt));
3266			if (do_set != 0) {
3267				rt.set = i & 31;
3268				rt.flags = IPFW_RCFLAG_SET;
3269			} else {
3270				rt.start_rule = i & 0xffff;
3271				rt.end_rule = j & 0xffff;
3272				if (rt.start_rule == 0 && rt.end_rule == 0)
3273					rt.flags |= IPFW_RCFLAG_ALL;
3274				else
3275					rt.flags |= IPFW_RCFLAG_RANGE;
3276				if (co.use_set != 0) {
3277					rt.set = co.use_set - 1;
3278					rt.flags |= IPFW_RCFLAG_SET;
3279				}
3280			}
3281			i = do_range_cmd(IP_FW_XDEL, &rt);
3282			if (i != 0) {
3283				exitval = EX_UNAVAILABLE;
3284				warn("rule %u: setsockopt(IP_FW_XDEL)",
3285				    rt.start_rule);
3286			} else if (rt.new_set == 0 && do_set == 0) {
3287				exitval = EX_UNAVAILABLE;
3288				if (rt.start_rule != rt.end_rule)
3289					warnx("no rules rules in %u-%u range",
3290					    rt.start_rule, rt.end_rule);
3291				else
3292					warnx("rule %u not found",
3293					    rt.start_rule);
3294			}
3295		}
3296	}
3297	if (exitval != EX_OK)
3298		exit(exitval);
3299}
3300
3301
3302/*
3303 * fill the interface structure. We do not check the name as we can
3304 * create interfaces dynamically, so checking them at insert time
3305 * makes relatively little sense.
3306 * Interface names containing '*', '?', or '[' are assumed to be shell
3307 * patterns which match interfaces.
3308 */
3309static void
3310fill_iface(ipfw_insn_if *cmd, char *arg, int cblen, struct tidx *tstate)
3311{
3312	char *p;
3313	uint16_t uidx;
3314
3315	cmd->name[0] = '\0';
3316	cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3317
3318	CHECK_CMDLEN;
3319
3320	/* Parse the interface or address */
3321	if (strcmp(arg, "any") == 0)
3322		cmd->o.len = 0;		/* effectively ignore this command */
3323	else if (strncmp(arg, "table(", 6) == 0) {
3324		if ((p = strchr(arg + 6, ')')) == NULL)
3325			errx(EX_DATAERR, "forgotten parenthesis: '%s'", arg);
3326		*p = '\0';
3327		p = strchr(arg + 6, ',');
3328		if (p)
3329			*p++ = '\0';
3330		if ((uidx = pack_table(tstate, arg + 6)) == 0)
3331			errx(EX_DATAERR, "Invalid table name: %s", arg + 6);
3332
3333		cmd->name[0] = '\1'; /* Special value indicating table */
3334		cmd->p.kidx = uidx;
3335	} else if (!isdigit(*arg)) {
3336		strlcpy(cmd->name, arg, sizeof(cmd->name));
3337		cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3338	} else if (!inet_aton(arg, &cmd->p.ip))
3339		errx(EX_DATAERR, "bad ip address ``%s''", arg);
3340}
3341
3342static void
3343get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
3344{
3345	int i;
3346	size_t l;
3347	char *ap, *ptr, *optr;
3348	struct ether_addr *mac;
3349	const char *macset = "0123456789abcdefABCDEF:";
3350
3351	if (strcmp(p, "any") == 0) {
3352		for (i = 0; i < ETHER_ADDR_LEN; i++)
3353			addr[i] = mask[i] = 0;
3354		return;
3355	}
3356
3357	optr = ptr = strdup(p);
3358	if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
3359		l = strlen(ap);
3360		if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
3361			errx(EX_DATAERR, "Incorrect MAC address");
3362		bcopy(mac, addr, ETHER_ADDR_LEN);
3363	} else
3364		errx(EX_DATAERR, "Incorrect MAC address");
3365
3366	if (ptr != NULL) { /* we have mask? */
3367		if (p[ptr - optr - 1] == '/') { /* mask len */
3368			long ml = strtol(ptr, &ap, 10);
3369			if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
3370				errx(EX_DATAERR, "Incorrect mask length");
3371			for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
3372				mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
3373		} else { /* mask */
3374			l = strlen(ptr);
3375			if (strspn(ptr, macset) != l ||
3376			    (mac = ether_aton(ptr)) == NULL)
3377				errx(EX_DATAERR, "Incorrect mask");
3378			bcopy(mac, mask, ETHER_ADDR_LEN);
3379		}
3380	} else { /* default mask: ff:ff:ff:ff:ff:ff */
3381		for (i = 0; i < ETHER_ADDR_LEN; i++)
3382			mask[i] = 0xff;
3383	}
3384	for (i = 0; i < ETHER_ADDR_LEN; i++)
3385		addr[i] &= mask[i];
3386
3387	free(optr);
3388}
3389
3390/*
3391 * helper function, updates the pointer to cmd with the length
3392 * of the current command, and also cleans up the first word of
3393 * the new command in case it has been clobbered before.
3394 */
3395static ipfw_insn *
3396next_cmd(ipfw_insn *cmd, int *len)
3397{
3398	*len -= F_LEN(cmd);
3399	CHECK_LENGTH(*len, 0);
3400	cmd += F_LEN(cmd);
3401	bzero(cmd, sizeof(*cmd));
3402	return cmd;
3403}
3404
3405/*
3406 * Takes arguments and copies them into a comment
3407 */
3408static void
3409fill_comment(ipfw_insn *cmd, char **av, int cblen)
3410{
3411	int i, l;
3412	char *p = (char *)(cmd + 1);
3413
3414	cmd->opcode = O_NOP;
3415	cmd->len =  (cmd->len & (F_NOT | F_OR));
3416
3417	/* Compute length of comment string. */
3418	for (i = 0, l = 0; av[i] != NULL; i++)
3419		l += strlen(av[i]) + 1;
3420	if (l == 0)
3421		return;
3422	if (l > 84)
3423		errx(EX_DATAERR,
3424		    "comment too long (max 80 chars)");
3425	l = 1 + (l+3)/4;
3426	cmd->len =  (cmd->len & (F_NOT | F_OR)) | l;
3427	CHECK_CMDLEN;
3428
3429	for (i = 0; av[i] != NULL; i++) {
3430		strcpy(p, av[i]);
3431		p += strlen(av[i]);
3432		*p++ = ' ';
3433	}
3434	*(--p) = '\0';
3435}
3436
3437/*
3438 * A function to fill simple commands of size 1.
3439 * Existing flags are preserved.
3440 */
3441static void
3442fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3443{
3444	cmd->opcode = opcode;
3445	cmd->len =  ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3446	cmd->arg1 = arg;
3447}
3448
3449/*
3450 * Fetch and add the MAC address and type, with masks. This generates one or
3451 * two microinstructions, and returns the pointer to the last one.
3452 */
3453static ipfw_insn *
3454add_mac(ipfw_insn *cmd, char *av[], int cblen)
3455{
3456	ipfw_insn_mac *mac;
3457
3458	if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
3459		errx(EX_DATAERR, "MAC dst src");
3460
3461	cmd->opcode = O_MACADDR2;
3462	cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3463	CHECK_CMDLEN;
3464
3465	mac = (ipfw_insn_mac *)cmd;
3466	get_mac_addr_mask(av[0], mac->addr, mac->mask);	/* dst */
3467	get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
3468	    &(mac->mask[ETHER_ADDR_LEN])); /* src */
3469	return cmd;
3470}
3471
3472static ipfw_insn *
3473add_mactype(ipfw_insn *cmd, char *av, int cblen)
3474{
3475	if (!av)
3476		errx(EX_DATAERR, "missing MAC type");
3477	if (strcmp(av, "any") != 0) { /* we have a non-null type */
3478		fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
3479		    cblen);
3480		cmd->opcode = O_MAC_TYPE;
3481		return cmd;
3482	} else
3483		return NULL;
3484}
3485
3486static ipfw_insn *
3487add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
3488{
3489	struct protoent *pe;
3490	char *ep;
3491	int proto;
3492
3493	proto = strtol(av, &ep, 10);
3494	if (*ep != '\0' || proto <= 0) {
3495		if ((pe = getprotobyname(av)) == NULL)
3496			return NULL;
3497		proto = pe->p_proto;
3498	}
3499
3500	fill_cmd(cmd, O_PROTO, 0, proto);
3501	*protop = proto;
3502	return cmd;
3503}
3504
3505static ipfw_insn *
3506add_proto(ipfw_insn *cmd, char *av, u_char *protop)
3507{
3508	u_char proto = IPPROTO_IP;
3509
3510	if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3511		; /* do not set O_IP4 nor O_IP6 */
3512	else if (strcmp(av, "ip4") == 0)
3513		/* explicit "just IPv4" rule */
3514		fill_cmd(cmd, O_IP4, 0, 0);
3515	else if (strcmp(av, "ip6") == 0) {
3516		/* explicit "just IPv6" rule */
3517		proto = IPPROTO_IPV6;
3518		fill_cmd(cmd, O_IP6, 0, 0);
3519	} else
3520		return add_proto0(cmd, av, protop);
3521
3522	*protop = proto;
3523	return cmd;
3524}
3525
3526static ipfw_insn *
3527add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
3528{
3529	u_char proto = IPPROTO_IP;
3530
3531	if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3532		; /* do not set O_IP4 nor O_IP6 */
3533	else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3534		/* explicit "just IPv4" rule */
3535		fill_cmd(cmd, O_IP4, 0, 0);
3536	else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3537		/* explicit "just IPv6" rule */
3538		proto = IPPROTO_IPV6;
3539		fill_cmd(cmd, O_IP6, 0, 0);
3540	} else
3541		return add_proto0(cmd, av, protop);
3542
3543	*protop = proto;
3544	return cmd;
3545}
3546
3547static ipfw_insn *
3548add_srcip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3549{
3550	fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3551	if (cmd->opcode == O_IP_DST_SET)			/* set */
3552		cmd->opcode = O_IP_SRC_SET;
3553	else if (cmd->opcode == O_IP_DST_LOOKUP)		/* table */
3554		cmd->opcode = O_IP_SRC_LOOKUP;
3555	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))		/* me */
3556		cmd->opcode = O_IP_SRC_ME;
3557	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))	/* one IP */
3558		cmd->opcode = O_IP_SRC;
3559	else							/* addr/mask */
3560		cmd->opcode = O_IP_SRC_MASK;
3561	return cmd;
3562}
3563
3564static ipfw_insn *
3565add_dstip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3566{
3567	fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3568	if (cmd->opcode == O_IP_DST_SET)			/* set */
3569		;
3570	else if (cmd->opcode == O_IP_DST_LOOKUP)		/* table */
3571		;
3572	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))		/* me */
3573		cmd->opcode = O_IP_DST_ME;
3574	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))	/* one IP */
3575		cmd->opcode = O_IP_DST;
3576	else							/* addr/mask */
3577		cmd->opcode = O_IP_DST_MASK;
3578	return cmd;
3579}
3580
3581static struct _s_x f_reserved_keywords[] = {
3582	{ "altq",	TOK_OR },
3583	{ "//",		TOK_OR },
3584	{ "diverted",	TOK_OR },
3585	{ "dst-port",	TOK_OR },
3586	{ "src-port",	TOK_OR },
3587	{ "established",	TOK_OR },
3588	{ "keep-state",	TOK_OR },
3589	{ "frag",	TOK_OR },
3590	{ "icmptypes",	TOK_OR },
3591	{ "in",		TOK_OR },
3592	{ "out",	TOK_OR },
3593	{ "ip6",	TOK_OR },
3594	{ "any",	TOK_OR },
3595	{ "to",		TOK_OR },
3596	{ "via",	TOK_OR },
3597	{ "{",		TOK_OR },
3598	{ NULL, 0 }	/* terminator */
3599};
3600
3601static ipfw_insn *
3602add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
3603{
3604
3605	if (match_token(f_reserved_keywords, av) != -1)
3606		return (NULL);
3607
3608	if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
3609		/* XXX todo: check that we have a protocol with ports */
3610		cmd->opcode = opcode;
3611		return cmd;
3612	}
3613	return NULL;
3614}
3615
3616static ipfw_insn *
3617add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3618{
3619	struct in6_addr a;
3620	char *host, *ch, buf[INET6_ADDRSTRLEN];
3621	ipfw_insn *ret = NULL;
3622	int len;
3623
3624	/* Copy first address in set if needed */
3625	if ((ch = strpbrk(av, "/,")) != NULL) {
3626		len = ch - av;
3627		strlcpy(buf, av, sizeof(buf));
3628		if (len < sizeof(buf))
3629			buf[len] = '\0';
3630		host = buf;
3631	} else
3632		host = av;
3633
3634	if (proto == IPPROTO_IPV6  || strcmp(av, "me6") == 0 ||
3635	    inet_pton(AF_INET6, host, &a) == 1)
3636		ret = add_srcip6(cmd, av, cblen, tstate);
3637	/* XXX: should check for IPv4, not !IPv6 */
3638	if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3639	    inet_pton(AF_INET6, host, &a) != 1))
3640		ret = add_srcip(cmd, av, cblen, tstate);
3641	if (ret == NULL && strcmp(av, "any") != 0)
3642		ret = cmd;
3643
3644	return ret;
3645}
3646
3647static ipfw_insn *
3648add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3649{
3650	struct in6_addr a;
3651	char *host, *ch, buf[INET6_ADDRSTRLEN];
3652	ipfw_insn *ret = NULL;
3653	int len;
3654
3655	/* Copy first address in set if needed */
3656	if ((ch = strpbrk(av, "/,")) != NULL) {
3657		len = ch - av;
3658		strlcpy(buf, av, sizeof(buf));
3659		if (len < sizeof(buf))
3660			buf[len] = '\0';
3661		host = buf;
3662	} else
3663		host = av;
3664
3665	if (proto == IPPROTO_IPV6  || strcmp(av, "me6") == 0 ||
3666	    inet_pton(AF_INET6, host, &a) == 1)
3667		ret = add_dstip6(cmd, av, cblen, tstate);
3668	/* XXX: should check for IPv4, not !IPv6 */
3669	if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3670	    inet_pton(AF_INET6, host, &a) != 1))
3671		ret = add_dstip(cmd, av, cblen, tstate);
3672	if (ret == NULL && strcmp(av, "any") != 0)
3673		ret = cmd;
3674
3675	return ret;
3676}
3677
3678/*
3679 * Parse arguments and assemble the microinstructions which make up a rule.
3680 * Rules are added into the 'rulebuf' and then copied in the correct order
3681 * into the actual rule.
3682 *
3683 * The syntax for a rule starts with the action, followed by
3684 * optional action parameters, and the various match patterns.
3685 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
3686 * (generated if the rule includes a keep-state option), then the
3687 * various match patterns, log/altq actions, and the actual action.
3688 *
3689 */
3690void
3691compile_rule(char *av[], uint32_t *rbuf, int *rbufsize, struct tidx *tstate)
3692{
3693	/*
3694	 * rules are added into the 'rulebuf' and then copied in
3695	 * the correct order into the actual rule.
3696	 * Some things that need to go out of order (prob, action etc.)
3697	 * go into actbuf[].
3698	 */
3699	static uint32_t actbuf[255], cmdbuf[255];
3700	int rblen, ablen, cblen;
3701
3702	ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
3703	ipfw_insn *first_cmd;	/* first match pattern */
3704
3705	struct ip_fw_rule *rule;
3706
3707	/*
3708	 * various flags used to record that we entered some fields.
3709	 */
3710	ipfw_insn *have_state = NULL;	/* check-state or keep-state */
3711	ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
3712	size_t len;
3713
3714	int i;
3715
3716	int open_par = 0;	/* open parenthesis ( */
3717
3718	/* proto is here because it is used to fetch ports */
3719	u_char proto = IPPROTO_IP;	/* default protocol */
3720
3721	double match_prob = 1; /* match probability, default is always match */
3722
3723	bzero(actbuf, sizeof(actbuf));		/* actions go here */
3724	bzero(cmdbuf, sizeof(cmdbuf));
3725	bzero(rbuf, *rbufsize);
3726
3727	rule = (struct ip_fw_rule *)rbuf;
3728	cmd = (ipfw_insn *)cmdbuf;
3729	action = (ipfw_insn *)actbuf;
3730
3731	rblen = *rbufsize / sizeof(uint32_t);
3732	rblen -= sizeof(struct ip_fw_rule) / sizeof(uint32_t);
3733	ablen = sizeof(actbuf) / sizeof(actbuf[0]);
3734	cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
3735	cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
3736
3737#define	CHECK_RBUFLEN(len)	{ CHECK_LENGTH(rblen, len); rblen -= len; }
3738#define	CHECK_ACTLEN		CHECK_LENGTH(ablen, action->len)
3739
3740	av++;
3741
3742	/* [rule N]	-- Rule number optional */
3743	if (av[0] && isdigit(**av)) {
3744		rule->rulenum = atoi(*av);
3745		av++;
3746	}
3747
3748	/* [set N]	-- set number (0..RESVD_SET), optional */
3749	if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
3750		int set = strtoul(av[1], NULL, 10);
3751		if (set < 0 || set > RESVD_SET)
3752			errx(EX_DATAERR, "illegal set %s", av[1]);
3753		rule->set = set;
3754		tstate->set = set;
3755		av += 2;
3756	}
3757
3758	/* [prob D]	-- match probability, optional */
3759	if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
3760		match_prob = strtod(av[1], NULL);
3761
3762		if (match_prob <= 0 || match_prob > 1)
3763			errx(EX_DATAERR, "illegal match prob. %s", av[1]);
3764		av += 2;
3765	}
3766
3767	/* action	-- mandatory */
3768	NEED1("missing action");
3769	i = match_token(rule_actions, *av);
3770	av++;
3771	action->len = 1;	/* default */
3772	CHECK_ACTLEN;
3773	switch(i) {
3774	case TOK_CHECKSTATE:
3775		have_state = action;
3776		action->opcode = O_CHECK_STATE;
3777		if (*av == NULL ||
3778		    match_token(rule_options, *av) == TOK_COMMENT) {
3779			action->arg1 = pack_object(tstate,
3780			    default_state_name, IPFW_TLV_STATE_NAME);
3781			break;
3782		}
3783		if (*av[0] == ':') {
3784			if (strcmp(*av + 1, "any") == 0)
3785				action->arg1 = 0;
3786			else if (state_check_name(*av + 1) == 0)
3787				action->arg1 = pack_object(tstate, *av + 1,
3788				    IPFW_TLV_STATE_NAME);
3789			else
3790				errx(EX_DATAERR, "Invalid state name %s",
3791				    *av);
3792			av++;
3793			break;
3794		}
3795		errx(EX_DATAERR, "Invalid state name %s", *av);
3796		break;
3797
3798	case TOK_ABORT:
3799		action->opcode = O_REJECT;
3800		action->arg1 = ICMP_REJECT_ABORT;
3801		break;
3802
3803	case TOK_ABORT6:
3804		action->opcode = O_UNREACH6;
3805		action->arg1 = ICMP6_UNREACH_ABORT;
3806		break;
3807
3808	case TOK_ACCEPT:
3809		action->opcode = O_ACCEPT;
3810		break;
3811
3812	case TOK_DENY:
3813		action->opcode = O_DENY;
3814		action->arg1 = 0;
3815		break;
3816
3817	case TOK_REJECT:
3818		action->opcode = O_REJECT;
3819		action->arg1 = ICMP_UNREACH_HOST;
3820		break;
3821
3822	case TOK_RESET:
3823		action->opcode = O_REJECT;
3824		action->arg1 = ICMP_REJECT_RST;
3825		break;
3826
3827	case TOK_RESET6:
3828		action->opcode = O_UNREACH6;
3829		action->arg1 = ICMP6_UNREACH_RST;
3830		break;
3831
3832	case TOK_UNREACH:
3833		action->opcode = O_REJECT;
3834		NEED1("missing reject code");
3835		fill_reject_code(&action->arg1, *av);
3836		av++;
3837		break;
3838
3839	case TOK_UNREACH6:
3840		action->opcode = O_UNREACH6;
3841		NEED1("missing unreach code");
3842		fill_unreach6_code(&action->arg1, *av);
3843		av++;
3844		break;
3845
3846	case TOK_COUNT:
3847		action->opcode = O_COUNT;
3848		break;
3849
3850	case TOK_NAT:
3851		action->opcode = O_NAT;
3852		action->len = F_INSN_SIZE(ipfw_insn_nat);
3853		CHECK_ACTLEN;
3854		if (*av != NULL && _substrcmp(*av, "global") == 0) {
3855			action->arg1 = IP_FW_NAT44_GLOBAL;
3856			av++;
3857			break;
3858		} else
3859			goto chkarg;
3860	case TOK_QUEUE:
3861		action->opcode = O_QUEUE;
3862		goto chkarg;
3863	case TOK_PIPE:
3864		action->opcode = O_PIPE;
3865		goto chkarg;
3866	case TOK_SKIPTO:
3867		action->opcode = O_SKIPTO;
3868		goto chkarg;
3869	case TOK_NETGRAPH:
3870		action->opcode = O_NETGRAPH;
3871		goto chkarg;
3872	case TOK_NGTEE:
3873		action->opcode = O_NGTEE;
3874		goto chkarg;
3875	case TOK_DIVERT:
3876		action->opcode = O_DIVERT;
3877		goto chkarg;
3878	case TOK_TEE:
3879		action->opcode = O_TEE;
3880		goto chkarg;
3881	case TOK_CALL:
3882		action->opcode = O_CALLRETURN;
3883chkarg:
3884		if (!av[0])
3885			errx(EX_USAGE, "missing argument for %s", *(av - 1));
3886		if (isdigit(**av)) {
3887			action->arg1 = strtoul(*av, NULL, 10);
3888			if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
3889				errx(EX_DATAERR, "illegal argument for %s",
3890				    *(av - 1));
3891		} else if (_substrcmp(*av, "tablearg") == 0) {
3892			action->arg1 = IP_FW_TARG;
3893		} else if (i == TOK_DIVERT || i == TOK_TEE) {
3894			struct servent *s;
3895			setservent(1);
3896			s = getservbyname(av[0], "divert");
3897			if (s != NULL)
3898				action->arg1 = ntohs(s->s_port);
3899			else
3900				errx(EX_DATAERR, "illegal divert/tee port");
3901		} else
3902			errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
3903		av++;
3904		break;
3905
3906	case TOK_FORWARD: {
3907		/*
3908		 * Locate the address-port separator (':' or ',').
3909		 * Could be one of the following:
3910		 *	hostname:port
3911		 *	IPv4 a.b.c.d,port
3912		 *	IPv4 a.b.c.d:port
3913		 *	IPv6 w:x:y::z,port
3914		 * The ':' can only be used with hostname and IPv4 address.
3915		 * XXX-BZ Should we also support [w:x:y::z]:port?
3916		 */
3917		struct sockaddr_storage result;
3918		struct addrinfo *res;
3919		char *s, *end;
3920		int family;
3921		u_short port_number;
3922
3923		NEED1("missing forward address[:port]");
3924
3925		/*
3926		 * locate the address-port separator (':' or ',')
3927		 */
3928		s = strchr(*av, ',');
3929		if (s == NULL) {
3930			/* Distinguish between IPv4:port and IPv6 cases. */
3931			s = strchr(*av, ':');
3932			if (s && strchr(s+1, ':'))
3933				s = NULL; /* no port */
3934		}
3935
3936		port_number = 0;
3937		if (s != NULL) {
3938			/* Terminate host portion and set s to start of port. */
3939			*(s++) = '\0';
3940			i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
3941			if (s == end)
3942				errx(EX_DATAERR,
3943				    "illegal forwarding port ``%s''", s);
3944			port_number = (u_short)i;
3945		}
3946
3947		if (_substrcmp(*av, "tablearg") == 0) {
3948			family = PF_INET;
3949			((struct sockaddr_in*)&result)->sin_addr.s_addr =
3950			    INADDR_ANY;
3951		} else {
3952			/*
3953			 * Resolve the host name or address to a family and a
3954			 * network representation of the address.
3955			 */
3956			if (getaddrinfo(*av, NULL, NULL, &res))
3957				errx(EX_DATAERR, NULL);
3958			/* Just use the first host in the answer. */
3959			family = res->ai_family;
3960			memcpy(&result, res->ai_addr, res->ai_addrlen);
3961			freeaddrinfo(res);
3962		}
3963
3964 		if (family == PF_INET) {
3965			ipfw_insn_sa *p = (ipfw_insn_sa *)action;
3966
3967			action->opcode = O_FORWARD_IP;
3968			action->len = F_INSN_SIZE(ipfw_insn_sa);
3969			CHECK_ACTLEN;
3970
3971			/*
3972			 * In the kernel we assume AF_INET and use only
3973			 * sin_port and sin_addr. Remember to set sin_len as
3974			 * the routing code seems to use it too.
3975			 */
3976			p->sa.sin_len = sizeof(struct sockaddr_in);
3977			p->sa.sin_family = AF_INET;
3978			p->sa.sin_port = port_number;
3979			p->sa.sin_addr.s_addr =
3980			     ((struct sockaddr_in *)&result)->sin_addr.s_addr;
3981		} else if (family == PF_INET6) {
3982			ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
3983
3984			action->opcode = O_FORWARD_IP6;
3985			action->len = F_INSN_SIZE(ipfw_insn_sa6);
3986			CHECK_ACTLEN;
3987
3988			p->sa.sin6_len = sizeof(struct sockaddr_in6);
3989			p->sa.sin6_family = AF_INET6;
3990			p->sa.sin6_port = port_number;
3991			p->sa.sin6_flowinfo = 0;
3992			p->sa.sin6_scope_id =
3993			    ((struct sockaddr_in6 *)&result)->sin6_scope_id;
3994			bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
3995			    &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
3996		} else {
3997			errx(EX_DATAERR, "Invalid address family in forward action");
3998		}
3999		av++;
4000		break;
4001	    }
4002	case TOK_COMMENT:
4003		/* pretend it is a 'count' rule followed by the comment */
4004		action->opcode = O_COUNT;
4005		av--;		/* go back... */
4006		break;
4007
4008	case TOK_SETFIB:
4009	    {
4010		int numfibs;
4011		size_t intsize = sizeof(int);
4012
4013		action->opcode = O_SETFIB;
4014		NEED1("missing fib number");
4015		if (_substrcmp(*av, "tablearg") == 0) {
4016			action->arg1 = IP_FW_TARG;
4017		} else {
4018		        action->arg1 = strtoul(*av, NULL, 10);
4019			if (sysctlbyname("net.fibs", &numfibs, &intsize,
4020			    NULL, 0) == -1)
4021				errx(EX_DATAERR, "fibs not suported.\n");
4022			if (action->arg1 >= numfibs)  /* Temporary */
4023				errx(EX_DATAERR, "fib too large.\n");
4024			/* Add high-order bit to fib to make room for tablearg*/
4025			action->arg1 |= 0x8000;
4026		}
4027		av++;
4028		break;
4029	    }
4030
4031	case TOK_SETDSCP:
4032	    {
4033		int code;
4034
4035		action->opcode = O_SETDSCP;
4036		NEED1("missing DSCP code");
4037		if (_substrcmp(*av, "tablearg") == 0) {
4038			action->arg1 = IP_FW_TARG;
4039		} else {
4040			if (isalpha(*av[0])) {
4041				if ((code = match_token(f_ipdscp, *av)) == -1)
4042					errx(EX_DATAERR, "Unknown DSCP code");
4043				action->arg1 = code;
4044			} else
4045			        action->arg1 = strtoul(*av, NULL, 10);
4046			/*
4047			 * Add high-order bit to DSCP to make room
4048			 * for tablearg
4049			 */
4050			action->arg1 |= 0x8000;
4051		}
4052		av++;
4053		break;
4054	    }
4055
4056	case TOK_REASS:
4057		action->opcode = O_REASS;
4058		break;
4059
4060	case TOK_RETURN:
4061		fill_cmd(action, O_CALLRETURN, F_NOT, 0);
4062		break;
4063
4064	case TOK_TCPSETMSS: {
4065		u_long mss;
4066		uint16_t idx;
4067
4068		idx = pack_object(tstate, "tcp-setmss", IPFW_TLV_EACTION);
4069		if (idx == 0)
4070			errx(EX_DATAERR, "pack_object failed");
4071		fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4072		NEED1("Missing MSS value");
4073		action = next_cmd(action, &ablen);
4074		action->len = 1;
4075		CHECK_ACTLEN;
4076		mss = strtoul(*av, NULL, 10);
4077		if (mss == 0 || mss > UINT16_MAX)
4078			errx(EX_USAGE, "invalid MSS value %s", *av);
4079		fill_cmd(action, O_EXTERNAL_DATA, 0, (uint16_t)mss);
4080		av++;
4081		break;
4082	}
4083
4084	default:
4085		av--;
4086		if (match_token(rule_eactions, *av) == -1)
4087			errx(EX_DATAERR, "invalid action %s\n", *av);
4088		/*
4089		 * External actions support.
4090		 * XXX: we support only syntax with instance name.
4091		 *	For known external actions (from rule_eactions list)
4092		 *	we can handle syntax directly. But with `eaction'
4093		 *	keyword we can use only `eaction <name> <instance>'
4094		 *	syntax.
4095		 */
4096	case TOK_EACTION: {
4097		uint16_t idx;
4098
4099		NEED1("Missing eaction name");
4100		if (eaction_check_name(*av) != 0)
4101			errx(EX_DATAERR, "Invalid eaction name %s", *av);
4102		idx = pack_object(tstate, *av, IPFW_TLV_EACTION);
4103		if (idx == 0)
4104			errx(EX_DATAERR, "pack_object failed");
4105		fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4106		av++;
4107		NEED1("Missing eaction instance name");
4108		action = next_cmd(action, &ablen);
4109		action->len = 1;
4110		CHECK_ACTLEN;
4111		if (eaction_check_name(*av) != 0)
4112			errx(EX_DATAERR, "Invalid eaction instance name %s",
4113			    *av);
4114		/*
4115		 * External action instance object has TLV type depended
4116		 * from the external action name object index. Since we
4117		 * currently don't know this index, use zero as TLV type.
4118		 */
4119		idx = pack_object(tstate, *av, 0);
4120		if (idx == 0)
4121			errx(EX_DATAERR, "pack_object failed");
4122		fill_cmd(action, O_EXTERNAL_INSTANCE, 0, idx);
4123		av++;
4124		}
4125	}
4126	action = next_cmd(action, &ablen);
4127
4128	/*
4129	 * [altq queuename] -- altq tag, optional
4130	 * [log [logamount N]]	-- log, optional
4131	 *
4132	 * If they exist, it go first in the cmdbuf, but then it is
4133	 * skipped in the copy section to the end of the buffer.
4134	 */
4135	while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
4136		av++;
4137		switch (i) {
4138		case TOK_LOG:
4139		    {
4140			ipfw_insn_log *c = (ipfw_insn_log *)cmd;
4141			int l;
4142
4143			if (have_log)
4144				errx(EX_DATAERR,
4145				    "log cannot be specified more than once");
4146			have_log = (ipfw_insn *)c;
4147			cmd->len = F_INSN_SIZE(ipfw_insn_log);
4148			CHECK_CMDLEN;
4149			cmd->opcode = O_LOG;
4150			if (av[0] && _substrcmp(*av, "logamount") == 0) {
4151				av++;
4152				NEED1("logamount requires argument");
4153				l = atoi(*av);
4154				if (l < 0)
4155					errx(EX_DATAERR,
4156					    "logamount must be positive");
4157				c->max_log = l;
4158				av++;
4159			} else {
4160				len = sizeof(c->max_log);
4161				if (sysctlbyname("net.inet.ip.fw.verbose_limit",
4162				    &c->max_log, &len, NULL, 0) == -1) {
4163					if (co.test_only) {
4164						c->max_log = 0;
4165						break;
4166					}
4167					errx(1, "sysctlbyname(\"%s\")",
4168					    "net.inet.ip.fw.verbose_limit");
4169				}
4170			}
4171		    }
4172			break;
4173
4174#ifndef NO_ALTQ
4175		case TOK_ALTQ:
4176		    {
4177			ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
4178
4179			NEED1("missing altq queue name");
4180			if (have_altq)
4181				errx(EX_DATAERR,
4182				    "altq cannot be specified more than once");
4183			have_altq = (ipfw_insn *)a;
4184			cmd->len = F_INSN_SIZE(ipfw_insn_altq);
4185			CHECK_CMDLEN;
4186			cmd->opcode = O_ALTQ;
4187			a->qid = altq_name_to_qid(*av);
4188			av++;
4189		    }
4190			break;
4191#endif
4192
4193		case TOK_TAG:
4194		case TOK_UNTAG: {
4195			uint16_t tag;
4196
4197			if (have_tag)
4198				errx(EX_USAGE, "tag and untag cannot be "
4199				    "specified more than once");
4200			GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
4201			   rule_action_params);
4202			have_tag = cmd;
4203			fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
4204			av++;
4205			break;
4206		}
4207
4208		default:
4209			abort();
4210		}
4211		cmd = next_cmd(cmd, &cblen);
4212	}
4213
4214	if (have_state)	{ /* must be a check-state, we are done */
4215		if (*av != NULL &&
4216		    match_token(rule_options, *av) == TOK_COMMENT) {
4217			/* check-state has a comment */
4218			av++;
4219			fill_comment(cmd, av, cblen);
4220			cmd = next_cmd(cmd, &cblen);
4221			av[0] = NULL;
4222		}
4223		goto done;
4224	}
4225
4226#define OR_START(target)					\
4227	if (av[0] && (*av[0] == '(' || *av[0] == '{')) { 	\
4228		if (open_par)					\
4229			errx(EX_USAGE, "nested \"(\" not allowed\n"); \
4230		prev = NULL;					\
4231		open_par = 1;					\
4232		if ( (av[0])[1] == '\0') {			\
4233			av++;					\
4234		} else						\
4235			(*av)++;				\
4236	}							\
4237	target:							\
4238
4239
4240#define	CLOSE_PAR						\
4241	if (open_par) {						\
4242		if (av[0] && (					\
4243		    strcmp(*av, ")") == 0 ||			\
4244		    strcmp(*av, "}") == 0)) {			\
4245			prev = NULL;				\
4246			open_par = 0;				\
4247			av++;					\
4248		} else						\
4249			errx(EX_USAGE, "missing \")\"\n");	\
4250	}
4251
4252#define NOT_BLOCK						\
4253	if (av[0] && _substrcmp(*av, "not") == 0) {		\
4254		if (cmd->len & F_NOT)				\
4255			errx(EX_USAGE, "double \"not\" not allowed\n"); \
4256		cmd->len |= F_NOT;				\
4257		av++;						\
4258	}
4259
4260#define OR_BLOCK(target)					\
4261	if (av[0] && _substrcmp(*av, "or") == 0) {		\
4262		if (prev == NULL || open_par == 0)		\
4263			errx(EX_DATAERR, "invalid OR block");	\
4264		prev->len |= F_OR;				\
4265		av++;					\
4266		goto target;					\
4267	}							\
4268	CLOSE_PAR;
4269
4270	first_cmd = cmd;
4271
4272#if 0
4273	/*
4274	 * MAC addresses, optional.
4275	 * If we have this, we skip the part "proto from src to dst"
4276	 * and jump straight to the option parsing.
4277	 */
4278	NOT_BLOCK;
4279	NEED1("missing protocol");
4280	if (_substrcmp(*av, "MAC") == 0 ||
4281	    _substrcmp(*av, "mac") == 0) {
4282		av++;			/* the "MAC" keyword */
4283		add_mac(cmd, av);	/* exits in case of errors */
4284		cmd = next_cmd(cmd);
4285		av += 2;		/* dst-mac and src-mac */
4286		NOT_BLOCK;
4287		NEED1("missing mac type");
4288		if (add_mactype(cmd, av[0]))
4289			cmd = next_cmd(cmd);
4290		av++;			/* any or mac-type */
4291		goto read_options;
4292	}
4293#endif
4294
4295	/*
4296	 * protocol, mandatory
4297	 */
4298    OR_START(get_proto);
4299	NOT_BLOCK;
4300	NEED1("missing protocol");
4301	if (add_proto_compat(cmd, *av, &proto)) {
4302		av++;
4303		if (F_LEN(cmd) != 0) {
4304			prev = cmd;
4305			cmd = next_cmd(cmd, &cblen);
4306		}
4307	} else if (first_cmd != cmd) {
4308		errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4309	} else
4310		goto read_options;
4311    OR_BLOCK(get_proto);
4312
4313	/*
4314	 * "from", mandatory
4315	 */
4316	if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
4317		errx(EX_USAGE, "missing ``from''");
4318	av++;
4319
4320	/*
4321	 * source IP, mandatory
4322	 */
4323    OR_START(source_ip);
4324	NOT_BLOCK;	/* optional "not" */
4325	NEED1("missing source address");
4326	if (add_src(cmd, *av, proto, cblen, tstate)) {
4327		av++;
4328		if (F_LEN(cmd) != 0) {	/* ! any */
4329			prev = cmd;
4330			cmd = next_cmd(cmd, &cblen);
4331		}
4332	} else
4333		errx(EX_USAGE, "bad source address %s", *av);
4334    OR_BLOCK(source_ip);
4335
4336	/*
4337	 * source ports, optional
4338	 */
4339	NOT_BLOCK;	/* optional "not" */
4340	if ( av[0] != NULL ) {
4341		if (_substrcmp(*av, "any") == 0 ||
4342		    add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4343			av++;
4344			if (F_LEN(cmd) != 0)
4345				cmd = next_cmd(cmd, &cblen);
4346		}
4347	}
4348
4349	/*
4350	 * "to", mandatory
4351	 */
4352	if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
4353		errx(EX_USAGE, "missing ``to''");
4354	av++;
4355
4356	/*
4357	 * destination, mandatory
4358	 */
4359    OR_START(dest_ip);
4360	NOT_BLOCK;	/* optional "not" */
4361	NEED1("missing dst address");
4362	if (add_dst(cmd, *av, proto, cblen, tstate)) {
4363		av++;
4364		if (F_LEN(cmd) != 0) {	/* ! any */
4365			prev = cmd;
4366			cmd = next_cmd(cmd, &cblen);
4367		}
4368	} else
4369		errx( EX_USAGE, "bad destination address %s", *av);
4370    OR_BLOCK(dest_ip);
4371
4372	/*
4373	 * dest. ports, optional
4374	 */
4375	NOT_BLOCK;	/* optional "not" */
4376	if (av[0]) {
4377		if (_substrcmp(*av, "any") == 0 ||
4378		    add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4379			av++;
4380			if (F_LEN(cmd) != 0)
4381				cmd = next_cmd(cmd, &cblen);
4382		}
4383	}
4384
4385read_options:
4386	prev = NULL;
4387	while ( av[0] != NULL ) {
4388		char *s;
4389		ipfw_insn_u32 *cmd32;	/* alias for cmd */
4390
4391		s = *av;
4392		cmd32 = (ipfw_insn_u32 *)cmd;
4393
4394		if (*s == '!') {	/* alternate syntax for NOT */
4395			if (cmd->len & F_NOT)
4396				errx(EX_USAGE, "double \"not\" not allowed\n");
4397			cmd->len = F_NOT;
4398			s++;
4399		}
4400		i = match_token(rule_options, s);
4401		av++;
4402		switch(i) {
4403		case TOK_NOT:
4404			if (cmd->len & F_NOT)
4405				errx(EX_USAGE, "double \"not\" not allowed\n");
4406			cmd->len = F_NOT;
4407			break;
4408
4409		case TOK_OR:
4410			if (open_par == 0 || prev == NULL)
4411				errx(EX_USAGE, "invalid \"or\" block\n");
4412			prev->len |= F_OR;
4413			break;
4414
4415		case TOK_STARTBRACE:
4416			if (open_par)
4417				errx(EX_USAGE, "+nested \"(\" not allowed\n");
4418			open_par = 1;
4419			break;
4420
4421		case TOK_ENDBRACE:
4422			if (!open_par)
4423				errx(EX_USAGE, "+missing \")\"\n");
4424			open_par = 0;
4425			prev = NULL;
4426			break;
4427
4428		case TOK_IN:
4429			fill_cmd(cmd, O_IN, 0, 0);
4430			break;
4431
4432		case TOK_OUT:
4433			cmd->len ^= F_NOT; /* toggle F_NOT */
4434			fill_cmd(cmd, O_IN, 0, 0);
4435			break;
4436
4437		case TOK_DIVERTED:
4438			fill_cmd(cmd, O_DIVERTED, 0, 3);
4439			break;
4440
4441		case TOK_DIVERTEDLOOPBACK:
4442			fill_cmd(cmd, O_DIVERTED, 0, 1);
4443			break;
4444
4445		case TOK_DIVERTEDOUTPUT:
4446			fill_cmd(cmd, O_DIVERTED, 0, 2);
4447			break;
4448
4449		case TOK_FRAG:
4450			fill_cmd(cmd, O_FRAG, 0, 0);
4451			break;
4452
4453		case TOK_LAYER2:
4454			fill_cmd(cmd, O_LAYER2, 0, 0);
4455			break;
4456
4457		case TOK_XMIT:
4458		case TOK_RECV:
4459		case TOK_VIA:
4460			NEED1("recv, xmit, via require interface name"
4461				" or address");
4462			fill_iface((ipfw_insn_if *)cmd, av[0], cblen, tstate);
4463			av++;
4464			if (F_LEN(cmd) == 0)	/* not a valid address */
4465				break;
4466			if (i == TOK_XMIT)
4467				cmd->opcode = O_XMIT;
4468			else if (i == TOK_RECV)
4469				cmd->opcode = O_RECV;
4470			else if (i == TOK_VIA)
4471				cmd->opcode = O_VIA;
4472			break;
4473
4474		case TOK_ICMPTYPES:
4475			NEED1("icmptypes requires list of types");
4476			fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
4477			av++;
4478			break;
4479
4480		case TOK_ICMP6TYPES:
4481			NEED1("icmptypes requires list of types");
4482			fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
4483			av++;
4484			break;
4485
4486		case TOK_IPTTL:
4487			NEED1("ipttl requires TTL");
4488			if (strpbrk(*av, "-,")) {
4489			    if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
4490				errx(EX_DATAERR, "invalid ipttl %s", *av);
4491			} else
4492			    fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
4493			av++;
4494			break;
4495
4496		case TOK_IPID:
4497			NEED1("ipid requires id");
4498			if (strpbrk(*av, "-,")) {
4499			    if (!add_ports(cmd, *av, 0, O_IPID, cblen))
4500				errx(EX_DATAERR, "invalid ipid %s", *av);
4501			} else
4502			    fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
4503			av++;
4504			break;
4505
4506		case TOK_IPLEN:
4507			NEED1("iplen requires length");
4508			if (strpbrk(*av, "-,")) {
4509			    if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
4510				errx(EX_DATAERR, "invalid ip len %s", *av);
4511			} else
4512			    fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
4513			av++;
4514			break;
4515
4516		case TOK_IPVER:
4517			NEED1("ipver requires version");
4518			fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
4519			av++;
4520			break;
4521
4522		case TOK_IPPRECEDENCE:
4523			NEED1("ipprecedence requires value");
4524			fill_cmd(cmd, O_IPPRECEDENCE, 0,
4525			    (strtoul(*av, NULL, 0) & 7) << 5);
4526			av++;
4527			break;
4528
4529		case TOK_DSCP:
4530			NEED1("missing DSCP code");
4531			fill_dscp(cmd, *av, cblen);
4532			av++;
4533			break;
4534
4535		case TOK_IPOPTS:
4536			NEED1("missing argument for ipoptions");
4537			fill_flags_cmd(cmd, O_IPOPT, f_ipopts, *av);
4538			av++;
4539			break;
4540
4541		case TOK_IPTOS:
4542			NEED1("missing argument for iptos");
4543			fill_flags_cmd(cmd, O_IPTOS, f_iptos, *av);
4544			av++;
4545			break;
4546
4547		case TOK_UID:
4548			NEED1("uid requires argument");
4549		    {
4550			char *end;
4551			uid_t uid;
4552			struct passwd *pwd;
4553
4554			cmd->opcode = O_UID;
4555			uid = strtoul(*av, &end, 0);
4556			pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
4557			if (pwd == NULL)
4558				errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
4559			cmd32->d[0] = pwd->pw_uid;
4560			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4561			av++;
4562		    }
4563			break;
4564
4565		case TOK_GID:
4566			NEED1("gid requires argument");
4567		    {
4568			char *end;
4569			gid_t gid;
4570			struct group *grp;
4571
4572			cmd->opcode = O_GID;
4573			gid = strtoul(*av, &end, 0);
4574			grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
4575			if (grp == NULL)
4576				errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
4577			cmd32->d[0] = grp->gr_gid;
4578			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4579			av++;
4580		    }
4581			break;
4582
4583		case TOK_JAIL:
4584			NEED1("jail requires argument");
4585		    {
4586			char *end;
4587			int jid;
4588
4589			cmd->opcode = O_JAIL;
4590			jid = (int)strtol(*av, &end, 0);
4591			if (jid < 0 || *end != '\0')
4592				errx(EX_DATAERR, "jail requires prison ID");
4593			cmd32->d[0] = (uint32_t)jid;
4594			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4595			av++;
4596		    }
4597			break;
4598
4599		case TOK_ESTAB:
4600			fill_cmd(cmd, O_ESTAB, 0, 0);
4601			break;
4602
4603		case TOK_SETUP:
4604			fill_cmd(cmd, O_TCPFLAGS, 0,
4605				(TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
4606			break;
4607
4608		case TOK_TCPDATALEN:
4609			NEED1("tcpdatalen requires length");
4610			if (strpbrk(*av, "-,")) {
4611			    if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
4612				errx(EX_DATAERR, "invalid tcpdata len %s", *av);
4613			} else
4614			    fill_cmd(cmd, O_TCPDATALEN, 0,
4615				    strtoul(*av, NULL, 0));
4616			av++;
4617			break;
4618
4619		case TOK_TCPOPTS:
4620			NEED1("missing argument for tcpoptions");
4621			fill_flags_cmd(cmd, O_TCPOPTS, f_tcpopts, *av);
4622			av++;
4623			break;
4624
4625		case TOK_TCPSEQ:
4626		case TOK_TCPACK:
4627			NEED1("tcpseq/tcpack requires argument");
4628			cmd->len = F_INSN_SIZE(ipfw_insn_u32);
4629			cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
4630			cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
4631			av++;
4632			break;
4633
4634		case TOK_TCPWIN:
4635			NEED1("tcpwin requires length");
4636			if (strpbrk(*av, "-,")) {
4637			    if (!add_ports(cmd, *av, 0, O_TCPWIN, cblen))
4638				errx(EX_DATAERR, "invalid tcpwin len %s", *av);
4639			} else
4640			    fill_cmd(cmd, O_TCPWIN, 0,
4641				    strtoul(*av, NULL, 0));
4642			av++;
4643			break;
4644
4645		case TOK_TCPFLAGS:
4646			NEED1("missing argument for tcpflags");
4647			cmd->opcode = O_TCPFLAGS;
4648			fill_flags_cmd(cmd, O_TCPFLAGS, f_tcpflags, *av);
4649			av++;
4650			break;
4651
4652		case TOK_KEEPSTATE: {
4653			uint16_t uidx;
4654
4655			if (open_par)
4656				errx(EX_USAGE, "keep-state cannot be part "
4657				    "of an or block");
4658			if (have_state)
4659				errx(EX_USAGE, "only one of keep-state "
4660					"and limit is allowed");
4661			if (*av != NULL && *av[0] == ':') {
4662				if (state_check_name(*av + 1) != 0)
4663					errx(EX_DATAERR,
4664					    "Invalid state name %s", *av);
4665				uidx = pack_object(tstate, *av + 1,
4666				    IPFW_TLV_STATE_NAME);
4667				av++;
4668			} else
4669				uidx = pack_object(tstate, default_state_name,
4670				    IPFW_TLV_STATE_NAME);
4671			have_state = cmd;
4672			fill_cmd(cmd, O_KEEP_STATE, 0, uidx);
4673			break;
4674		}
4675
4676		case TOK_LIMIT: {
4677			ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
4678			int val;
4679
4680			if (open_par)
4681				errx(EX_USAGE,
4682				    "limit cannot be part of an or block");
4683			if (have_state)
4684				errx(EX_USAGE, "only one of keep-state and "
4685				    "limit is allowed");
4686			have_state = cmd;
4687
4688			cmd->len = F_INSN_SIZE(ipfw_insn_limit);
4689			CHECK_CMDLEN;
4690			cmd->opcode = O_LIMIT;
4691			c->limit_mask = c->conn_limit = 0;
4692
4693			while ( av[0] != NULL ) {
4694				if ((val = match_token(limit_masks, *av)) <= 0)
4695					break;
4696				c->limit_mask |= val;
4697				av++;
4698			}
4699
4700			if (c->limit_mask == 0)
4701				errx(EX_USAGE, "limit: missing limit mask");
4702
4703			GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
4704			    TOK_LIMIT, rule_options);
4705			av++;
4706
4707			if (*av != NULL && *av[0] == ':') {
4708				if (state_check_name(*av + 1) != 0)
4709					errx(EX_DATAERR,
4710					    "Invalid state name %s", *av);
4711				cmd->arg1 = pack_object(tstate, *av + 1,
4712				    IPFW_TLV_STATE_NAME);
4713				av++;
4714			} else
4715				cmd->arg1 = pack_object(tstate,
4716				    default_state_name, IPFW_TLV_STATE_NAME);
4717			break;
4718		}
4719
4720		case TOK_PROTO:
4721			NEED1("missing protocol");
4722			if (add_proto(cmd, *av, &proto)) {
4723				av++;
4724			} else
4725				errx(EX_DATAERR, "invalid protocol ``%s''",
4726				    *av);
4727			break;
4728
4729		case TOK_SRCIP:
4730			NEED1("missing source IP");
4731			if (add_srcip(cmd, *av, cblen, tstate)) {
4732				av++;
4733			}
4734			break;
4735
4736		case TOK_DSTIP:
4737			NEED1("missing destination IP");
4738			if (add_dstip(cmd, *av, cblen, tstate)) {
4739				av++;
4740			}
4741			break;
4742
4743		case TOK_SRCIP6:
4744			NEED1("missing source IP6");
4745			if (add_srcip6(cmd, *av, cblen, tstate)) {
4746				av++;
4747			}
4748			break;
4749
4750		case TOK_DSTIP6:
4751			NEED1("missing destination IP6");
4752			if (add_dstip6(cmd, *av, cblen, tstate)) {
4753				av++;
4754			}
4755			break;
4756
4757		case TOK_SRCPORT:
4758			NEED1("missing source port");
4759			if (_substrcmp(*av, "any") == 0 ||
4760			    add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4761				av++;
4762			} else
4763				errx(EX_DATAERR, "invalid source port %s", *av);
4764			break;
4765
4766		case TOK_DSTPORT:
4767			NEED1("missing destination port");
4768			if (_substrcmp(*av, "any") == 0 ||
4769			    add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4770				av++;
4771			} else
4772				errx(EX_DATAERR, "invalid destination port %s",
4773				    *av);
4774			break;
4775
4776		case TOK_MAC:
4777			if (add_mac(cmd, av, cblen))
4778				av += 2;
4779			break;
4780
4781		case TOK_MACTYPE:
4782			NEED1("missing mac type");
4783			if (!add_mactype(cmd, *av, cblen))
4784				errx(EX_DATAERR, "invalid mac type %s", *av);
4785			av++;
4786			break;
4787
4788		case TOK_VERREVPATH:
4789			fill_cmd(cmd, O_VERREVPATH, 0, 0);
4790			break;
4791
4792		case TOK_VERSRCREACH:
4793			fill_cmd(cmd, O_VERSRCREACH, 0, 0);
4794			break;
4795
4796		case TOK_ANTISPOOF:
4797			fill_cmd(cmd, O_ANTISPOOF, 0, 0);
4798			break;
4799
4800		case TOK_IPSEC:
4801			fill_cmd(cmd, O_IPSEC, 0, 0);
4802			break;
4803
4804		case TOK_IPV6:
4805			fill_cmd(cmd, O_IP6, 0, 0);
4806			break;
4807
4808		case TOK_IPV4:
4809			fill_cmd(cmd, O_IP4, 0, 0);
4810			break;
4811
4812		case TOK_EXT6HDR:
4813			fill_ext6hdr( cmd, *av );
4814			av++;
4815			break;
4816
4817		case TOK_FLOWID:
4818			if (proto != IPPROTO_IPV6 )
4819				errx( EX_USAGE, "flow-id filter is active "
4820				    "only for ipv6 protocol\n");
4821			fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
4822			av++;
4823			break;
4824
4825		case TOK_COMMENT:
4826			fill_comment(cmd, av, cblen);
4827			av[0]=NULL;
4828			break;
4829
4830		case TOK_TAGGED:
4831			if (av[0] && strpbrk(*av, "-,")) {
4832				if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
4833					errx(EX_DATAERR, "tagged: invalid tag"
4834					    " list: %s", *av);
4835			}
4836			else {
4837				uint16_t tag;
4838
4839				GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
4840				    TOK_TAGGED, rule_options);
4841				fill_cmd(cmd, O_TAGGED, 0, tag);
4842			}
4843			av++;
4844			break;
4845
4846		case TOK_FIB:
4847			NEED1("fib requires fib number");
4848			fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
4849			av++;
4850			break;
4851		case TOK_SOCKARG:
4852			fill_cmd(cmd, O_SOCKARG, 0, 0);
4853			break;
4854
4855		case TOK_LOOKUP: {
4856			ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
4857			int j;
4858
4859			if (!av[0] || !av[1])
4860				errx(EX_USAGE, "format: lookup argument tablenum");
4861			cmd->opcode = O_IP_DST_LOOKUP;
4862			cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
4863			i = match_token(rule_options, *av);
4864			for (j = 0; lookup_key[j] >= 0 ; j++) {
4865				if (i == lookup_key[j])
4866					break;
4867			}
4868			if (lookup_key[j] <= 0)
4869				errx(EX_USAGE, "format: cannot lookup on %s", *av);
4870			__PAST_END(c->d, 1) = j; // i converted to option
4871			av++;
4872
4873			if ((j = pack_table(tstate, *av)) == 0)
4874				errx(EX_DATAERR, "Invalid table name: %s", *av);
4875
4876			cmd->arg1 = j;
4877			av++;
4878		    }
4879			break;
4880		case TOK_FLOW:
4881			NEED1("missing table name");
4882			if (strncmp(*av, "table(", 6) != 0)
4883				errx(EX_DATAERR,
4884				    "enclose table name into \"table()\"");
4885			fill_table(cmd, *av, O_IP_FLOW_LOOKUP, tstate);
4886			av++;
4887			break;
4888
4889		default:
4890			errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
4891		}
4892		if (F_LEN(cmd) > 0) {	/* prepare to advance */
4893			prev = cmd;
4894			cmd = next_cmd(cmd, &cblen);
4895		}
4896	}
4897
4898done:
4899	/*
4900	 * Now copy stuff into the rule.
4901	 * If we have a keep-state option, the first instruction
4902	 * must be a PROBE_STATE (which is generated here).
4903	 * If we have a LOG option, it was stored as the first command,
4904	 * and now must be moved to the top of the action part.
4905	 */
4906	dst = (ipfw_insn *)rule->cmd;
4907
4908	/*
4909	 * First thing to write into the command stream is the match probability.
4910	 */
4911	if (match_prob != 1) { /* 1 means always match */
4912		dst->opcode = O_PROB;
4913		dst->len = 2;
4914		*((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
4915		dst += dst->len;
4916	}
4917
4918	/*
4919	 * generate O_PROBE_STATE if necessary
4920	 */
4921	if (have_state && have_state->opcode != O_CHECK_STATE) {
4922		fill_cmd(dst, O_PROBE_STATE, 0, have_state->arg1);
4923		dst = next_cmd(dst, &rblen);
4924	}
4925
4926	/* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
4927	for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
4928		i = F_LEN(src);
4929		CHECK_RBUFLEN(i);
4930
4931		switch (src->opcode) {
4932		case O_LOG:
4933		case O_KEEP_STATE:
4934		case O_LIMIT:
4935		case O_ALTQ:
4936		case O_TAG:
4937			break;
4938		default:
4939			bcopy(src, dst, i * sizeof(uint32_t));
4940			dst += i;
4941		}
4942	}
4943
4944	/*
4945	 * put back the have_state command as last opcode
4946	 */
4947	if (have_state && have_state->opcode != O_CHECK_STATE) {
4948		i = F_LEN(have_state);
4949		CHECK_RBUFLEN(i);
4950		bcopy(have_state, dst, i * sizeof(uint32_t));
4951		dst += i;
4952	}
4953	/*
4954	 * start action section
4955	 */
4956	rule->act_ofs = dst - rule->cmd;
4957
4958	/* put back O_LOG, O_ALTQ, O_TAG if necessary */
4959	if (have_log) {
4960		i = F_LEN(have_log);
4961		CHECK_RBUFLEN(i);
4962		bcopy(have_log, dst, i * sizeof(uint32_t));
4963		dst += i;
4964	}
4965	if (have_altq) {
4966		i = F_LEN(have_altq);
4967		CHECK_RBUFLEN(i);
4968		bcopy(have_altq, dst, i * sizeof(uint32_t));
4969		dst += i;
4970	}
4971	if (have_tag) {
4972		i = F_LEN(have_tag);
4973		CHECK_RBUFLEN(i);
4974		bcopy(have_tag, dst, i * sizeof(uint32_t));
4975		dst += i;
4976	}
4977
4978	/*
4979	 * copy all other actions
4980	 */
4981	for (src = (ipfw_insn *)actbuf; src != action; src += i) {
4982		i = F_LEN(src);
4983		CHECK_RBUFLEN(i);
4984		bcopy(src, dst, i * sizeof(uint32_t));
4985		dst += i;
4986	}
4987
4988	rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
4989	*rbufsize = (char *)dst - (char *)rule;
4990}
4991
4992static int
4993compare_ntlv(const void *_a, const void *_b)
4994{
4995	ipfw_obj_ntlv *a, *b;
4996
4997	a = (ipfw_obj_ntlv *)_a;
4998	b = (ipfw_obj_ntlv *)_b;
4999
5000	if (a->set < b->set)
5001		return (-1);
5002	else if (a->set > b->set)
5003		return (1);
5004
5005	if (a->idx < b->idx)
5006		return (-1);
5007	else if (a->idx > b->idx)
5008		return (1);
5009
5010	if (a->head.type < b->head.type)
5011		return (-1);
5012	else if (a->head.type > b->head.type)
5013		return (1);
5014
5015	return (0);
5016}
5017
5018/*
5019 * Provide kernel with sorted list of referenced objects
5020 */
5021static void
5022object_sort_ctlv(ipfw_obj_ctlv *ctlv)
5023{
5024
5025	qsort(ctlv + 1, ctlv->count, ctlv->objsize, compare_ntlv);
5026}
5027
5028struct object_kt {
5029	uint16_t	uidx;
5030	uint16_t	type;
5031};
5032static int
5033compare_object_kntlv(const void *k, const void *v)
5034{
5035	ipfw_obj_ntlv *ntlv;
5036	struct object_kt key;
5037
5038	key = *((struct object_kt *)k);
5039	ntlv = (ipfw_obj_ntlv *)v;
5040
5041	if (key.uidx < ntlv->idx)
5042		return (-1);
5043	else if (key.uidx > ntlv->idx)
5044		return (1);
5045
5046	if (key.type < ntlv->head.type)
5047		return (-1);
5048	else if (key.type > ntlv->head.type)
5049		return (1);
5050
5051	return (0);
5052}
5053
5054/*
5055 * Finds object name in @ctlv by @idx and @type.
5056 * Uses the following facts:
5057 * 1) All TLVs are the same size
5058 * 2) Kernel implementation provides already sorted list.
5059 *
5060 * Returns table name or NULL.
5061 */
5062static char *
5063object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx, uint16_t type)
5064{
5065	ipfw_obj_ntlv *ntlv;
5066	struct object_kt key;
5067
5068	key.uidx = idx;
5069	key.type = type;
5070
5071	ntlv = bsearch(&key, (ctlv + 1), ctlv->count, ctlv->objsize,
5072	    compare_object_kntlv);
5073
5074	if (ntlv != NULL)
5075		return (ntlv->name);
5076
5077	return (NULL);
5078}
5079
5080static char *
5081table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx)
5082{
5083
5084	return (object_search_ctlv(ctlv, idx, IPFW_TLV_TBL_NAME));
5085}
5086
5087/*
5088 * Adds one or more rules to ipfw chain.
5089 * Data layout:
5090 * Request:
5091 * [
5092 *   ip_fw3_opheader
5093 *   [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
5094 *   [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ] (*2) (*3)
5095 * ]
5096 * Reply:
5097 * [
5098 *   ip_fw3_opheader
5099 *   [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
5100 *   [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ]
5101 * ]
5102 *
5103 * Rules in reply are modified to store their actual ruleset number.
5104 *
5105 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
5106 * according to their idx field and there has to be no duplicates.
5107 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
5108 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
5109 */
5110void
5111ipfw_add(char *av[])
5112{
5113	uint32_t rulebuf[1024];
5114	int rbufsize, default_off, tlen, rlen;
5115	size_t sz;
5116	struct tidx ts;
5117	struct ip_fw_rule *rule;
5118	caddr_t tbuf;
5119	ip_fw3_opheader *op3;
5120	ipfw_obj_ctlv *ctlv, *tstate;
5121
5122	rbufsize = sizeof(rulebuf);
5123	memset(rulebuf, 0, rbufsize);
5124	memset(&ts, 0, sizeof(ts));
5125
5126	/* Optimize case with no tables */
5127	default_off = sizeof(ipfw_obj_ctlv) + sizeof(ip_fw3_opheader);
5128	op3 = (ip_fw3_opheader *)rulebuf;
5129	ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5130	rule = (struct ip_fw_rule *)(ctlv + 1);
5131	rbufsize -= default_off;
5132
5133	compile_rule(av, (uint32_t *)rule, &rbufsize, &ts);
5134	/* Align rule size to u64 boundary */
5135	rlen = roundup2(rbufsize, sizeof(uint64_t));
5136
5137	tbuf = NULL;
5138	sz = 0;
5139	tstate = NULL;
5140	if (ts.count != 0) {
5141		/* Some tables. We have to alloc more data */
5142		tlen = ts.count * sizeof(ipfw_obj_ntlv);
5143		sz = default_off + sizeof(ipfw_obj_ctlv) + tlen + rlen;
5144
5145		if ((tbuf = calloc(1, sz)) == NULL)
5146			err(EX_UNAVAILABLE, "malloc() failed for IP_FW_ADD");
5147		op3 = (ip_fw3_opheader *)tbuf;
5148		/* Tables first */
5149		ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5150		ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
5151		ctlv->head.length = sizeof(ipfw_obj_ctlv) + tlen;
5152		ctlv->count = ts.count;
5153		ctlv->objsize = sizeof(ipfw_obj_ntlv);
5154		memcpy(ctlv + 1, ts.idx, tlen);
5155		object_sort_ctlv(ctlv);
5156		tstate = ctlv;
5157		/* Rule next */
5158		ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
5159		ctlv->head.type = IPFW_TLV_RULE_LIST;
5160		ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5161		ctlv->count = 1;
5162		memcpy(ctlv + 1, rule, rbufsize);
5163	} else {
5164		/* Simply add header */
5165		sz = rlen + default_off;
5166		memset(ctlv, 0, sizeof(*ctlv));
5167		ctlv->head.type = IPFW_TLV_RULE_LIST;
5168		ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5169		ctlv->count = 1;
5170	}
5171
5172	if (do_get3(IP_FW_XADD, op3, &sz) != 0)
5173		err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_XADD");
5174
5175	if (!co.do_quiet) {
5176		struct format_opts sfo;
5177		struct buf_pr bp;
5178		memset(&sfo, 0, sizeof(sfo));
5179		sfo.tstate = tstate;
5180		sfo.set_mask = (uint32_t)(-1);
5181		bp_alloc(&bp, 4096);
5182		show_static_rule(&co, &sfo, &bp, rule, NULL);
5183		printf("%s", bp.buf);
5184		bp_free(&bp);
5185	}
5186
5187	if (tbuf != NULL)
5188		free(tbuf);
5189
5190	if (ts.idx != NULL)
5191		free(ts.idx);
5192}
5193
5194/*
5195 * clear the counters or the log counters.
5196 * optname has the following values:
5197 *  0 (zero both counters and logging)
5198 *  1 (zero logging only)
5199 */
5200void
5201ipfw_zero(int ac, char *av[], int optname)
5202{
5203	ipfw_range_tlv rt;
5204	char const *errstr;
5205	char const *name = optname ? "RESETLOG" : "ZERO";
5206	uint32_t arg;
5207	int failed = EX_OK;
5208
5209	optname = optname ? IP_FW_XRESETLOG : IP_FW_XZERO;
5210	av++; ac--;
5211
5212	if (ac == 0) {
5213		/* clear all entries */
5214		memset(&rt, 0, sizeof(rt));
5215		rt.flags = IPFW_RCFLAG_ALL;
5216		if (do_range_cmd(optname, &rt) < 0)
5217			err(EX_UNAVAILABLE, "setsockopt(IP_FW_X%s)", name);
5218		if (!co.do_quiet)
5219			printf("%s.\n", optname == IP_FW_XZERO ?
5220			    "Accounting cleared":"Logging counts reset");
5221
5222		return;
5223	}
5224
5225	while (ac) {
5226		/* Rule number */
5227		if (isdigit(**av)) {
5228			arg = strtonum(*av, 0, 0xffff, &errstr);
5229			if (errstr)
5230				errx(EX_DATAERR,
5231				    "invalid rule number %s\n", *av);
5232			memset(&rt, 0, sizeof(rt));
5233			rt.start_rule = arg;
5234			rt.end_rule = arg;
5235			rt.flags |= IPFW_RCFLAG_RANGE;
5236			if (co.use_set != 0) {
5237				rt.set = co.use_set - 1;
5238				rt.flags |= IPFW_RCFLAG_SET;
5239			}
5240			if (do_range_cmd(optname, &rt) != 0) {
5241				warn("rule %u: setsockopt(IP_FW_X%s)",
5242				    arg, name);
5243				failed = EX_UNAVAILABLE;
5244			} else if (rt.new_set == 0) {
5245				printf("Entry %d not found\n", arg);
5246				failed = EX_UNAVAILABLE;
5247			} else if (!co.do_quiet)
5248				printf("Entry %d %s.\n", arg,
5249				    optname == IP_FW_XZERO ?
5250					"cleared" : "logging count reset");
5251		} else {
5252			errx(EX_USAGE, "invalid rule number ``%s''", *av);
5253		}
5254		av++; ac--;
5255	}
5256	if (failed != EX_OK)
5257		exit(failed);
5258}
5259
5260void
5261ipfw_flush(int force)
5262{
5263	ipfw_range_tlv rt;
5264
5265	if (!force && !co.do_quiet) { /* need to ask user */
5266		int c;
5267
5268		printf("Are you sure? [yn] ");
5269		fflush(stdout);
5270		do {
5271			c = toupper(getc(stdin));
5272			while (c != '\n' && getc(stdin) != '\n')
5273				if (feof(stdin))
5274					return; /* and do not flush */
5275		} while (c != 'Y' && c != 'N');
5276		printf("\n");
5277		if (c == 'N')	/* user said no */
5278			return;
5279	}
5280	if (co.do_pipe) {
5281		dummynet_flush();
5282		return;
5283	}
5284	/* `ipfw set N flush` - is the same that `ipfw delete set N` */
5285	memset(&rt, 0, sizeof(rt));
5286	if (co.use_set != 0) {
5287		rt.set = co.use_set - 1;
5288		rt.flags = IPFW_RCFLAG_SET;
5289	} else
5290		rt.flags = IPFW_RCFLAG_ALL;
5291	if (do_range_cmd(IP_FW_XDEL, &rt) != 0)
5292			err(EX_UNAVAILABLE, "setsockopt(IP_FW_XDEL)");
5293	if (!co.do_quiet)
5294		printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
5295}
5296
5297static struct _s_x intcmds[] = {
5298      { "talist",	TOK_TALIST },
5299      { "iflist",	TOK_IFLIST },
5300      { "olist",	TOK_OLIST },
5301      { "vlist",	TOK_VLIST },
5302      { NULL, 0 }
5303};
5304
5305static struct _s_x otypes[] = {
5306	{ "EACTION",	IPFW_TLV_EACTION },
5307	{ "DYNSTATE",	IPFW_TLV_STATE_NAME },
5308	{ NULL, 0 }
5309};
5310
5311static const char*
5312lookup_eaction_name(ipfw_obj_ntlv *ntlv, int cnt, uint16_t type)
5313{
5314	const char *name;
5315	int i;
5316
5317	name = NULL;
5318	for (i = 0; i < cnt; i++) {
5319		if (ntlv[i].head.type != IPFW_TLV_EACTION)
5320			continue;
5321		if (IPFW_TLV_EACTION_NAME(ntlv[i].idx) != type)
5322			continue;
5323		name = ntlv[i].name;
5324		break;
5325	}
5326	return (name);
5327}
5328
5329static void
5330ipfw_list_objects(int ac, char *av[])
5331{
5332	ipfw_obj_lheader req, *olh;
5333	ipfw_obj_ntlv *ntlv;
5334	const char *name;
5335	size_t sz;
5336	int i;
5337
5338	memset(&req, 0, sizeof(req));
5339	sz = sizeof(req);
5340	if (do_get3(IP_FW_DUMP_SRVOBJECTS, &req.opheader, &sz) != 0)
5341		if (errno != ENOMEM)
5342			return;
5343
5344	sz = req.size;
5345	if ((olh = calloc(1, sz)) == NULL)
5346		return;
5347
5348	olh->size = sz;
5349	if (do_get3(IP_FW_DUMP_SRVOBJECTS, &olh->opheader, &sz) != 0) {
5350		free(olh);
5351		return;
5352	}
5353
5354	if (olh->count > 0)
5355		printf("Objects list:\n");
5356	else
5357		printf("There are no objects\n");
5358	ntlv = (ipfw_obj_ntlv *)(olh + 1);
5359	for (i = 0; i < olh->count; i++) {
5360		name = match_value(otypes, ntlv->head.type);
5361		if (name == NULL)
5362			name = lookup_eaction_name(
5363			    (ipfw_obj_ntlv *)(olh + 1), olh->count,
5364			    ntlv->head.type);
5365		if (name == NULL)
5366			printf(" kidx: %4d\ttype: %10d\tname: %s\n",
5367			    ntlv->idx, ntlv->head.type, ntlv->name);
5368		else
5369			printf(" kidx: %4d\ttype: %10s\tname: %s\n",
5370			    ntlv->idx, name, ntlv->name);
5371		ntlv++;
5372	}
5373	free(olh);
5374}
5375
5376void
5377ipfw_internal_handler(int ac, char *av[])
5378{
5379	int tcmd;
5380
5381	ac--; av++;
5382	NEED1("internal cmd required");
5383
5384	if ((tcmd = match_token(intcmds, *av)) == -1)
5385		errx(EX_USAGE, "invalid internal sub-cmd: %s", *av);
5386
5387	switch (tcmd) {
5388	case TOK_IFLIST:
5389		ipfw_list_tifaces();
5390		break;
5391	case TOK_TALIST:
5392		ipfw_list_ta(ac, av);
5393		break;
5394	case TOK_OLIST:
5395		ipfw_list_objects(ac, av);
5396		break;
5397	case TOK_VLIST:
5398		ipfw_list_values(ac, av);
5399		break;
5400	}
5401}
5402
5403static int
5404ipfw_get_tracked_ifaces(ipfw_obj_lheader **polh)
5405{
5406	ipfw_obj_lheader req, *olh;
5407	size_t sz;
5408
5409	memset(&req, 0, sizeof(req));
5410	sz = sizeof(req);
5411
5412	if (do_get3(IP_FW_XIFLIST, &req.opheader, &sz) != 0) {
5413		if (errno != ENOMEM)
5414			return (errno);
5415	}
5416
5417	sz = req.size;
5418	if ((olh = calloc(1, sz)) == NULL)
5419		return (ENOMEM);
5420
5421	olh->size = sz;
5422	if (do_get3(IP_FW_XIFLIST, &olh->opheader, &sz) != 0) {
5423		free(olh);
5424		return (errno);
5425	}
5426
5427	*polh = olh;
5428	return (0);
5429}
5430
5431static int
5432ifinfo_cmp(const void *a, const void *b)
5433{
5434	ipfw_iface_info *ia, *ib;
5435
5436	ia = (ipfw_iface_info *)a;
5437	ib = (ipfw_iface_info *)b;
5438
5439	return (stringnum_cmp(ia->ifname, ib->ifname));
5440}
5441
5442/*
5443 * Retrieves table list from kernel,
5444 * optionally sorts it and calls requested function for each table.
5445 * Returns 0 on success.
5446 */
5447static void
5448ipfw_list_tifaces()
5449{
5450	ipfw_obj_lheader *olh;
5451	ipfw_iface_info *info;
5452	int i, error;
5453
5454	if ((error = ipfw_get_tracked_ifaces(&olh)) != 0)
5455		err(EX_OSERR, "Unable to request ipfw tracked interface list");
5456
5457
5458	qsort(olh + 1, olh->count, olh->objsize, ifinfo_cmp);
5459
5460	info = (ipfw_iface_info *)(olh + 1);
5461	for (i = 0; i < olh->count; i++) {
5462		if (info->flags & IPFW_IFFLAG_RESOLVED)
5463			printf("%s ifindex: %d refcount: %u changes: %u\n",
5464			    info->ifname, info->ifindex, info->refcnt,
5465			    info->gencnt);
5466		else
5467			printf("%s ifindex: unresolved refcount: %u changes: %u\n",
5468			    info->ifname, info->refcnt, info->gencnt);
5469		info = (ipfw_iface_info *)((caddr_t)info + olh->objsize);
5470	}
5471
5472	free(olh);
5473}
5474
5475
5476
5477
5478