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