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