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