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