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