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