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