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