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