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