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