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