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