xref: /freebsd/sbin/ipfw/ipfw2.c (revision 732a02b4e77866604a120a275c082bb6221bd2ff)
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 	if (co->do_compact != 0 && (rule->flags & IPFW_RULE_NOOPT))
2227 		goto justopts;
2228 
2229 	/* Print source */
2230 	bprintf(bp, " from");
2231 	print_address(bp, fo, &state, src_opcodes, nitems(src_opcodes),
2232 	    O_IP_SRCPORT, HAVE_SRCIP);
2233 
2234 	/* Print destination */
2235 	bprintf(bp, " to");
2236 	print_address(bp, fo, &state, dst_opcodes, nitems(dst_opcodes),
2237 	    O_IP_DSTPORT, HAVE_DSTIP);
2238 
2239 justopts:
2240 	/* Print the rest of options */
2241 	while (print_opcode(bp, fo, &state, -1))
2242 		;
2243 end:
2244 	/* Print comment at the end */
2245 	cmd = print_opcode(bp, fo, &state, O_NOP);
2246 	if (co->comment_only != 0 && cmd == NULL)
2247 		bprintf(bp, " // ...");
2248 	bprintf(bp, "\n");
2249 	free_show_state(&state);
2250 }
2251 
2252 static void
2253 show_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2254     struct buf_pr *bp, ipfw_dyn_rule *d)
2255 {
2256 	struct protoent *pe;
2257 	struct in_addr a;
2258 	uint16_t rulenum;
2259 	char buf[INET6_ADDRSTRLEN];
2260 
2261 	if (d->expire == 0 && d->dyn_type != O_LIMIT_PARENT)
2262 		return;
2263 
2264 	bcopy(&d->rule, &rulenum, sizeof(rulenum));
2265 	bprintf(bp, "%05d", rulenum);
2266 	if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2267 		bprintf(bp, " ");
2268 		pr_u64(bp, &d->pcnt, fo->pcwidth);
2269 		pr_u64(bp, &d->bcnt, fo->bcwidth);
2270 		bprintf(bp, "(%ds)", d->expire);
2271 	}
2272 	switch (d->dyn_type) {
2273 	case O_LIMIT_PARENT:
2274 		bprintf(bp, " PARENT %d", d->count);
2275 		break;
2276 	case O_LIMIT:
2277 		bprintf(bp, " LIMIT");
2278 		break;
2279 	case O_KEEP_STATE: /* bidir, no mask */
2280 		bprintf(bp, " STATE");
2281 		break;
2282 	}
2283 
2284 	if ((pe = getprotobynumber(d->id.proto)) != NULL)
2285 		bprintf(bp, " %s", pe->p_name);
2286 	else
2287 		bprintf(bp, " proto %u", d->id.proto);
2288 
2289 	if (d->id.addr_type == 4) {
2290 		a.s_addr = htonl(d->id.src_ip);
2291 		bprintf(bp, " %s %d", inet_ntoa(a), d->id.src_port);
2292 
2293 		a.s_addr = htonl(d->id.dst_ip);
2294 		bprintf(bp, " <-> %s %d", inet_ntoa(a), d->id.dst_port);
2295 	} else if (d->id.addr_type == 6) {
2296 		bprintf(bp, " %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2297 		    sizeof(buf)), d->id.src_port);
2298 		bprintf(bp, " <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6,
2299 		    buf, sizeof(buf)), d->id.dst_port);
2300 	} else
2301 		bprintf(bp, " UNKNOWN <-> UNKNOWN");
2302 	if (d->kidx != 0)
2303 		bprintf(bp, " :%s", object_search_ctlv(fo->tstate,
2304 		    d->kidx, IPFW_TLV_STATE_NAME));
2305 
2306 #define	BOTH_SYN	(TH_SYN | (TH_SYN << 8))
2307 #define	BOTH_FIN	(TH_FIN | (TH_FIN << 8))
2308 	if (co->verbose) {
2309 		bprintf(bp, " state 0x%08x%s", d->state,
2310 		    d->state ? " ": ",");
2311 		if (d->state & IPFW_DYN_ORPHANED)
2312 			bprintf(bp, "ORPHANED,");
2313 		if ((d->state & BOTH_SYN) == BOTH_SYN)
2314 			bprintf(bp, "BOTH_SYN,");
2315 		else {
2316 			if (d->state & TH_SYN)
2317 				bprintf(bp, "F_SYN,");
2318 			if (d->state & (TH_SYN << 8))
2319 				bprintf(bp, "R_SYN,");
2320 		}
2321 		if ((d->state & BOTH_FIN) == BOTH_FIN)
2322 			bprintf(bp, "BOTH_FIN,");
2323 		else {
2324 			if (d->state & TH_FIN)
2325 				bprintf(bp, "F_FIN,");
2326 			if (d->state & (TH_FIN << 8))
2327 				bprintf(bp, "R_FIN,");
2328 		}
2329 		bprintf(bp, " f_ack 0x%x, r_ack 0x%x", d->ack_fwd,
2330 		    d->ack_rev);
2331 	}
2332 }
2333 
2334 static int
2335 do_range_cmd(int cmd, ipfw_range_tlv *rt)
2336 {
2337 	ipfw_range_header rh;
2338 	size_t sz;
2339 
2340 	memset(&rh, 0, sizeof(rh));
2341 	memcpy(&rh.range, rt, sizeof(*rt));
2342 	rh.range.head.length = sizeof(*rt);
2343 	rh.range.head.type = IPFW_TLV_RANGE;
2344 	sz = sizeof(rh);
2345 
2346 	if (do_get3(cmd, &rh.opheader, &sz) != 0)
2347 		return (-1);
2348 	/* Save number of matched objects */
2349 	rt->new_set = rh.range.new_set;
2350 	return (0);
2351 }
2352 
2353 /*
2354  * This one handles all set-related commands
2355  * 	ipfw set { show | enable | disable }
2356  * 	ipfw set swap X Y
2357  * 	ipfw set move X to Y
2358  * 	ipfw set move rule X to Y
2359  */
2360 void
2361 ipfw_sets_handler(char *av[])
2362 {
2363 	ipfw_range_tlv rt;
2364 	char *msg;
2365 	size_t size;
2366 	uint32_t masks[2];
2367 	int i;
2368 	uint16_t rulenum;
2369 	uint8_t cmd;
2370 
2371 	av++;
2372 	memset(&rt, 0, sizeof(rt));
2373 
2374 	if (av[0] == NULL)
2375 		errx(EX_USAGE, "set needs command");
2376 	if (_substrcmp(*av, "show") == 0) {
2377 		struct format_opts fo;
2378 		ipfw_cfg_lheader *cfg;
2379 
2380 		memset(&fo, 0, sizeof(fo));
2381 		if (ipfw_get_config(&co, &fo, &cfg, &size) != 0)
2382 			err(EX_OSERR, "requesting config failed");
2383 
2384 		for (i = 0, msg = "disable"; i < RESVD_SET; i++)
2385 			if ((cfg->set_mask & (1<<i)) == 0) {
2386 				printf("%s %d", msg, i);
2387 				msg = "";
2388 			}
2389 		msg = (cfg->set_mask != (uint32_t)-1) ? " enable" : "enable";
2390 		for (i = 0; i < RESVD_SET; i++)
2391 			if ((cfg->set_mask & (1<<i)) != 0) {
2392 				printf("%s %d", msg, i);
2393 				msg = "";
2394 			}
2395 		printf("\n");
2396 		free(cfg);
2397 	} else if (_substrcmp(*av, "swap") == 0) {
2398 		av++;
2399 		if ( av[0] == NULL || av[1] == NULL )
2400 			errx(EX_USAGE, "set swap needs 2 set numbers\n");
2401 		rt.set = atoi(av[0]);
2402 		rt.new_set = atoi(av[1]);
2403 		if (!isdigit(*(av[0])) || rt.set > RESVD_SET)
2404 			errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2405 		if (!isdigit(*(av[1])) || rt.new_set > RESVD_SET)
2406 			errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2407 		i = do_range_cmd(IP_FW_SET_SWAP, &rt);
2408 	} else if (_substrcmp(*av, "move") == 0) {
2409 		av++;
2410 		if (av[0] && _substrcmp(*av, "rule") == 0) {
2411 			rt.flags = IPFW_RCFLAG_RANGE; /* move rules to new set */
2412 			cmd = IP_FW_XMOVE;
2413 			av++;
2414 		} else
2415 			cmd = IP_FW_SET_MOVE; /* Move set to new one */
2416 		if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
2417 				av[3] != NULL ||  _substrcmp(av[1], "to") != 0)
2418 			errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2419 		rulenum = atoi(av[0]);
2420 		rt.new_set = atoi(av[2]);
2421 		if (cmd == IP_FW_XMOVE) {
2422 			rt.start_rule = rulenum;
2423 			rt.end_rule = rulenum;
2424 		} else
2425 			rt.set = rulenum;
2426 		rt.new_set = atoi(av[2]);
2427 		if (!isdigit(*(av[0])) || (cmd == 3 && rt.set > RESVD_SET) ||
2428 			(cmd == 2 && rt.start_rule == IPFW_DEFAULT_RULE) )
2429 			errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2430 		if (!isdigit(*(av[2])) || rt.new_set > RESVD_SET)
2431 			errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2432 		i = do_range_cmd(cmd, &rt);
2433 		if (i < 0)
2434 			err(EX_OSERR, "failed to move %s",
2435 			    cmd == IP_FW_SET_MOVE ? "set": "rule");
2436 	} else if (_substrcmp(*av, "disable") == 0 ||
2437 		   _substrcmp(*av, "enable") == 0 ) {
2438 		int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2439 
2440 		av++;
2441 		masks[0] = masks[1] = 0;
2442 
2443 		while (av[0]) {
2444 			if (isdigit(**av)) {
2445 				i = atoi(*av);
2446 				if (i < 0 || i > RESVD_SET)
2447 					errx(EX_DATAERR,
2448 					    "invalid set number %d\n", i);
2449 				masks[which] |= (1<<i);
2450 			} else if (_substrcmp(*av, "disable") == 0)
2451 				which = 0;
2452 			else if (_substrcmp(*av, "enable") == 0)
2453 				which = 1;
2454 			else
2455 				errx(EX_DATAERR,
2456 					"invalid set command %s\n", *av);
2457 			av++;
2458 		}
2459 		if ( (masks[0] & masks[1]) != 0 )
2460 			errx(EX_DATAERR,
2461 			    "cannot enable and disable the same set\n");
2462 
2463 		rt.set = masks[0];
2464 		rt.new_set = masks[1];
2465 		i = do_range_cmd(IP_FW_SET_ENABLE, &rt);
2466 		if (i)
2467 			warn("set enable/disable: setsockopt(IP_FW_SET_ENABLE)");
2468 	} else
2469 		errx(EX_USAGE, "invalid set command %s\n", *av);
2470 }
2471 
2472 void
2473 ipfw_sysctl_handler(char *av[], int which)
2474 {
2475 	av++;
2476 
2477 	if (av[0] == NULL) {
2478 		warnx("missing keyword to enable/disable\n");
2479 	} else if (_substrcmp(*av, "firewall") == 0) {
2480 		sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2481 		    &which, sizeof(which));
2482 		sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
2483 		    &which, sizeof(which));
2484 	} else if (_substrcmp(*av, "one_pass") == 0) {
2485 		sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2486 		    &which, sizeof(which));
2487 	} else if (_substrcmp(*av, "debug") == 0) {
2488 		sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2489 		    &which, sizeof(which));
2490 	} else if (_substrcmp(*av, "verbose") == 0) {
2491 		sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2492 		    &which, sizeof(which));
2493 	} else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2494 		sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2495 		    &which, sizeof(which));
2496 #ifndef NO_ALTQ
2497 	} else if (_substrcmp(*av, "altq") == 0) {
2498 		altq_set_enabled(which);
2499 #endif
2500 	} else {
2501 		warnx("unrecognize enable/disable keyword: %s\n", *av);
2502 	}
2503 }
2504 
2505 typedef void state_cb(struct cmdline_opts *co, struct format_opts *fo,
2506     void *arg, void *state);
2507 
2508 static void
2509 prepare_format_dyn(struct cmdline_opts *co, struct format_opts *fo,
2510     void *arg, void *_state)
2511 {
2512 	ipfw_dyn_rule *d;
2513 	int width;
2514 	uint8_t set;
2515 
2516 	d = (ipfw_dyn_rule *)_state;
2517 	/* Count _ALL_ states */
2518 	fo->dcnt++;
2519 
2520 	if (fo->show_counters == 0)
2521 		return;
2522 
2523 	if (co->use_set) {
2524 		/* skip states from another set */
2525 		bcopy((char *)&d->rule + sizeof(uint16_t), &set,
2526 		    sizeof(uint8_t));
2527 		if (set != co->use_set - 1)
2528 			return;
2529 	}
2530 
2531 	width = pr_u64(NULL, &d->pcnt, 0);
2532 	if (width > fo->pcwidth)
2533 		fo->pcwidth = width;
2534 
2535 	width = pr_u64(NULL, &d->bcnt, 0);
2536 	if (width > fo->bcwidth)
2537 		fo->bcwidth = width;
2538 }
2539 
2540 static int
2541 foreach_state(struct cmdline_opts *co, struct format_opts *fo,
2542     caddr_t base, size_t sz, state_cb dyn_bc, void *dyn_arg)
2543 {
2544 	int ttype;
2545 	state_cb *fptr;
2546 	void *farg;
2547 	ipfw_obj_tlv *tlv;
2548 	ipfw_obj_ctlv *ctlv;
2549 
2550 	fptr = NULL;
2551 	ttype = 0;
2552 
2553 	while (sz > 0) {
2554 		ctlv = (ipfw_obj_ctlv *)base;
2555 		switch (ctlv->head.type) {
2556 		case IPFW_TLV_DYNSTATE_LIST:
2557 			base += sizeof(*ctlv);
2558 			sz -= sizeof(*ctlv);
2559 			ttype = IPFW_TLV_DYN_ENT;
2560 			fptr = dyn_bc;
2561 			farg = dyn_arg;
2562 			break;
2563 		default:
2564 			return (sz);
2565 		}
2566 
2567 		while (sz > 0) {
2568 			tlv = (ipfw_obj_tlv *)base;
2569 			if (tlv->type != ttype)
2570 				break;
2571 
2572 			fptr(co, fo, farg, tlv + 1);
2573 			sz -= tlv->length;
2574 			base += tlv->length;
2575 		}
2576 	}
2577 
2578 	return (sz);
2579 }
2580 
2581 static void
2582 prepare_format_opts(struct cmdline_opts *co, struct format_opts *fo,
2583     ipfw_obj_tlv *rtlv, int rcnt, caddr_t dynbase, size_t dynsz)
2584 {
2585 	int bcwidth, pcwidth, width;
2586 	int n;
2587 	struct ip_fw_bcounter *cntr;
2588 	struct ip_fw_rule *r;
2589 
2590 	bcwidth = 0;
2591 	pcwidth = 0;
2592 	if (fo->show_counters != 0) {
2593 		for (n = 0; n < rcnt; n++,
2594 		    rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2595 			cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2596 			r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2597 			/* skip rules from another set */
2598 			if (co->use_set && r->set != co->use_set - 1)
2599 				continue;
2600 
2601 			/* packet counter */
2602 			width = pr_u64(NULL, &cntr->pcnt, 0);
2603 			if (width > pcwidth)
2604 				pcwidth = width;
2605 
2606 			/* byte counter */
2607 			width = pr_u64(NULL, &cntr->bcnt, 0);
2608 			if (width > bcwidth)
2609 				bcwidth = width;
2610 		}
2611 	}
2612 	fo->bcwidth = bcwidth;
2613 	fo->pcwidth = pcwidth;
2614 
2615 	fo->dcnt = 0;
2616 	if (co->do_dynamic && dynsz > 0)
2617 		foreach_state(co, fo, dynbase, dynsz, prepare_format_dyn, NULL);
2618 }
2619 
2620 static int
2621 list_static_range(struct cmdline_opts *co, struct format_opts *fo,
2622     struct buf_pr *bp, ipfw_obj_tlv *rtlv, int rcnt)
2623 {
2624 	int n, seen;
2625 	struct ip_fw_rule *r;
2626 	struct ip_fw_bcounter *cntr;
2627 	int c = 0;
2628 
2629 	for (n = seen = 0; n < rcnt; n++,
2630 	    rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2631 
2632 		if ((fo->show_counters | fo->show_time) != 0) {
2633 			cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2634 			r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2635 		} else {
2636 			cntr = NULL;
2637 			r = (struct ip_fw_rule *)(rtlv + 1);
2638 		}
2639 		if (r->rulenum > fo->last)
2640 			break;
2641 		if (co->use_set && r->set != co->use_set - 1)
2642 			continue;
2643 		if (r->rulenum >= fo->first && r->rulenum <= fo->last) {
2644 			show_static_rule(co, fo, bp, r, cntr);
2645 			printf("%s", bp->buf);
2646 			c += rtlv->length;
2647 			bp_flush(bp);
2648 			seen++;
2649 		}
2650 	}
2651 
2652 	return (seen);
2653 }
2654 
2655 static void
2656 list_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2657     void *_arg, void *_state)
2658 {
2659 	uint16_t rulenum;
2660 	uint8_t set;
2661 	ipfw_dyn_rule *d;
2662 	struct buf_pr *bp;
2663 
2664 	d = (ipfw_dyn_rule *)_state;
2665 	bp = (struct buf_pr *)_arg;
2666 
2667 	bcopy(&d->rule, &rulenum, sizeof(rulenum));
2668 	if (rulenum > fo->last)
2669 		return;
2670 	if (co->use_set) {
2671 		bcopy((char *)&d->rule + sizeof(uint16_t),
2672 		      &set, sizeof(uint8_t));
2673 		if (set != co->use_set - 1)
2674 			return;
2675 	}
2676 	if (rulenum >= fo->first) {
2677 		show_dyn_state(co, fo, bp, d);
2678 		printf("%s\n", bp->buf);
2679 		bp_flush(bp);
2680 	}
2681 }
2682 
2683 static int
2684 list_dyn_range(struct cmdline_opts *co, struct format_opts *fo,
2685     struct buf_pr *bp, caddr_t base, size_t sz)
2686 {
2687 
2688 	sz = foreach_state(co, fo, base, sz, list_dyn_state, bp);
2689 	return (sz);
2690 }
2691 
2692 void
2693 ipfw_list(int ac, char *av[], int show_counters)
2694 {
2695 	ipfw_cfg_lheader *cfg;
2696 	struct format_opts sfo;
2697 	size_t sz;
2698 	int error;
2699 	int lac;
2700 	char **lav;
2701 	uint32_t rnum;
2702 	char *endptr;
2703 
2704 	if (co.test_only) {
2705 		fprintf(stderr, "Testing only, list disabled\n");
2706 		return;
2707 	}
2708 	if (co.do_pipe) {
2709 		dummynet_list(ac, av, show_counters);
2710 		return;
2711 	}
2712 
2713 	ac--;
2714 	av++;
2715 	memset(&sfo, 0, sizeof(sfo));
2716 
2717 	/* Determine rule range to request */
2718 	if (ac > 0) {
2719 		for (lac = ac, lav = av; lac != 0; lac--) {
2720 			rnum = strtoul(*lav++, &endptr, 10);
2721 			if (sfo.first == 0 || rnum < sfo.first)
2722 				sfo.first = rnum;
2723 
2724 			if (*endptr == '-')
2725 				rnum = strtoul(endptr + 1, &endptr, 10);
2726 			if (sfo.last == 0 || rnum > sfo.last)
2727 				sfo.last = rnum;
2728 		}
2729 	}
2730 
2731 	/* get configuraion from kernel */
2732 	cfg = NULL;
2733 	sfo.show_counters = show_counters;
2734 	sfo.show_time = co.do_time;
2735 	if (co.do_dynamic != 2)
2736 		sfo.flags |= IPFW_CFG_GET_STATIC;
2737 	if (co.do_dynamic != 0)
2738 		sfo.flags |= IPFW_CFG_GET_STATES;
2739 	if ((sfo.show_counters | sfo.show_time) != 0)
2740 		sfo.flags |= IPFW_CFG_GET_COUNTERS;
2741 	if (ipfw_get_config(&co, &sfo, &cfg, &sz) != 0)
2742 		err(EX_OSERR, "retrieving config failed");
2743 
2744 	error = ipfw_show_config(&co, &sfo, cfg, sz, ac, av);
2745 
2746 	free(cfg);
2747 
2748 	if (error != EX_OK)
2749 		exit(error);
2750 }
2751 
2752 static int
2753 ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
2754     ipfw_cfg_lheader *cfg, size_t sz, int ac, char *av[])
2755 {
2756 	caddr_t dynbase;
2757 	size_t dynsz;
2758 	int rcnt;
2759 	int exitval = EX_OK;
2760 	int lac;
2761 	char **lav;
2762 	char *endptr;
2763 	size_t readsz;
2764 	struct buf_pr bp;
2765 	ipfw_obj_ctlv *ctlv, *tstate;
2766 	ipfw_obj_tlv *rbase;
2767 
2768 	/*
2769 	 * Handle tablenames TLV first, if any
2770 	 */
2771 	tstate = NULL;
2772 	rbase = NULL;
2773 	dynbase = NULL;
2774 	dynsz = 0;
2775 	readsz = sizeof(*cfg);
2776 	rcnt = 0;
2777 
2778 	fo->set_mask = cfg->set_mask;
2779 
2780 	ctlv = (ipfw_obj_ctlv *)(cfg + 1);
2781 	if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2782 		object_sort_ctlv(ctlv);
2783 		fo->tstate = ctlv;
2784 		readsz += ctlv->head.length;
2785 		ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2786 	}
2787 
2788 	if (cfg->flags & IPFW_CFG_GET_STATIC) {
2789 		/* We've requested static rules */
2790 		if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2791 			rbase = (ipfw_obj_tlv *)(ctlv + 1);
2792 			rcnt = ctlv->count;
2793 			readsz += ctlv->head.length;
2794 			ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2795 			    ctlv->head.length);
2796 		}
2797 	}
2798 
2799 	if ((cfg->flags & IPFW_CFG_GET_STATES) && (readsz != sz))  {
2800 		/* We may have some dynamic states */
2801 		dynsz = sz - readsz;
2802 		/* Skip empty header */
2803 		if (dynsz != sizeof(ipfw_obj_ctlv))
2804 			dynbase = (caddr_t)ctlv;
2805 		else
2806 			dynsz = 0;
2807 	}
2808 
2809 	prepare_format_opts(co, fo, rbase, rcnt, dynbase, dynsz);
2810 	bp_alloc(&bp, 4096);
2811 
2812 	/* if no rule numbers were specified, list all rules */
2813 	if (ac == 0) {
2814 		fo->first = 0;
2815 		fo->last = IPFW_DEFAULT_RULE;
2816 		if (cfg->flags & IPFW_CFG_GET_STATIC)
2817 			list_static_range(co, fo, &bp, rbase, rcnt);
2818 
2819 		if (co->do_dynamic && dynsz > 0) {
2820 			printf("## Dynamic rules (%d %zu):\n", fo->dcnt,
2821 			    dynsz);
2822 			list_dyn_range(co, fo, &bp, dynbase, dynsz);
2823 		}
2824 
2825 		bp_free(&bp);
2826 		return (EX_OK);
2827 	}
2828 
2829 	/* display specific rules requested on command line */
2830 	for (lac = ac, lav = av; lac != 0; lac--) {
2831 		/* convert command line rule # */
2832 		fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2833 		if (*endptr == '-')
2834 			fo->last = strtoul(endptr + 1, &endptr, 10);
2835 		if (*endptr) {
2836 			exitval = EX_USAGE;
2837 			warnx("invalid rule number: %s", *(lav - 1));
2838 			continue;
2839 		}
2840 
2841 		if ((cfg->flags & IPFW_CFG_GET_STATIC) == 0)
2842 			continue;
2843 
2844 		if (list_static_range(co, fo, &bp, rbase, rcnt) == 0) {
2845 			/* give precedence to other error(s) */
2846 			if (exitval == EX_OK)
2847 				exitval = EX_UNAVAILABLE;
2848 			if (fo->first == fo->last)
2849 				warnx("rule %u does not exist", fo->first);
2850 			else
2851 				warnx("no rules in range %u-%u",
2852 				    fo->first, fo->last);
2853 		}
2854 	}
2855 
2856 	if (co->do_dynamic && dynsz > 0) {
2857 		printf("## Dynamic rules:\n");
2858 		for (lac = ac, lav = av; lac != 0; lac--) {
2859 			fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2860 			if (*endptr == '-')
2861 				fo->last = strtoul(endptr+1, &endptr, 10);
2862 			if (*endptr)
2863 				/* already warned */
2864 				continue;
2865 			list_dyn_range(co, fo, &bp, dynbase, dynsz);
2866 		}
2867 	}
2868 
2869 	bp_free(&bp);
2870 	return (exitval);
2871 }
2872 
2873 
2874 /*
2875  * Retrieves current ipfw configuration of given type
2876  * and stores its pointer to @pcfg.
2877  *
2878  * Caller is responsible for freeing @pcfg.
2879  *
2880  * Returns 0 on success.
2881  */
2882 
2883 static int
2884 ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
2885     ipfw_cfg_lheader **pcfg, size_t *psize)
2886 {
2887 	ipfw_cfg_lheader *cfg;
2888 	size_t sz;
2889 	int i;
2890 
2891 
2892 	if (co->test_only != 0) {
2893 		fprintf(stderr, "Testing only, list disabled\n");
2894 		return (0);
2895 	}
2896 
2897 	/* Start with some data size */
2898 	sz = 4096;
2899 	cfg = NULL;
2900 
2901 	for (i = 0; i < 16; i++) {
2902 		if (cfg != NULL)
2903 			free(cfg);
2904 		if ((cfg = calloc(1, sz)) == NULL)
2905 			return (ENOMEM);
2906 
2907 		cfg->flags = fo->flags;
2908 		cfg->start_rule = fo->first;
2909 		cfg->end_rule = fo->last;
2910 
2911 		if (do_get3(IP_FW_XGET, &cfg->opheader, &sz) != 0) {
2912 			if (errno != ENOMEM) {
2913 				free(cfg);
2914 				return (errno);
2915 			}
2916 
2917 			/* Buffer size is not enough. Try to increase */
2918 			sz = sz * 2;
2919 			if (sz < cfg->size)
2920 				sz = cfg->size;
2921 			continue;
2922 		}
2923 
2924 		*pcfg = cfg;
2925 		*psize = sz;
2926 		return (0);
2927 	}
2928 
2929 	free(cfg);
2930 	return (ENOMEM);
2931 }
2932 
2933 static int
2934 lookup_host (char *host, struct in_addr *ipaddr)
2935 {
2936 	struct hostent *he;
2937 
2938 	if (!inet_aton(host, ipaddr)) {
2939 		if ((he = gethostbyname(host)) == NULL)
2940 			return(-1);
2941 		*ipaddr = *(struct in_addr *)he->h_addr_list[0];
2942 	}
2943 	return(0);
2944 }
2945 
2946 struct tidx {
2947 	ipfw_obj_ntlv *idx;
2948 	uint32_t count;
2949 	uint32_t size;
2950 	uint16_t counter;
2951 	uint8_t set;
2952 };
2953 
2954 int
2955 ipfw_check_object_name(const char *name)
2956 {
2957 	int c, i, l;
2958 
2959 	/*
2960 	 * Check that name is null-terminated and contains
2961 	 * valid symbols only. Valid mask is:
2962 	 * [a-zA-Z0-9\-_\.]{1,63}
2963 	 */
2964 	l = strlen(name);
2965 	if (l == 0 || l >= 64)
2966 		return (EINVAL);
2967 	for (i = 0; i < l; i++) {
2968 		c = name[i];
2969 		if (isalpha(c) || isdigit(c) || c == '_' ||
2970 		    c == '-' || c == '.')
2971 			continue;
2972 		return (EINVAL);
2973 	}
2974 	return (0);
2975 }
2976 
2977 static char *default_state_name = "default";
2978 static int
2979 state_check_name(const char *name)
2980 {
2981 
2982 	if (ipfw_check_object_name(name) != 0)
2983 		return (EINVAL);
2984 	if (strcmp(name, "any") == 0)
2985 		return (EINVAL);
2986 	return (0);
2987 }
2988 
2989 static int
2990 eaction_check_name(const char *name)
2991 {
2992 
2993 	if (ipfw_check_object_name(name) != 0)
2994 		return (EINVAL);
2995 	/* Restrict some 'special' names */
2996 	if (match_token(rule_actions, name) != -1 &&
2997 	    match_token(rule_action_params, name) != -1)
2998 		return (EINVAL);
2999 	return (0);
3000 }
3001 
3002 static uint16_t
3003 pack_object(struct tidx *tstate, char *name, int otype)
3004 {
3005 	int i;
3006 	ipfw_obj_ntlv *ntlv;
3007 
3008 	for (i = 0; i < tstate->count; i++) {
3009 		if (strcmp(tstate->idx[i].name, name) != 0)
3010 			continue;
3011 		if (tstate->idx[i].set != tstate->set)
3012 			continue;
3013 		if (tstate->idx[i].head.type != otype)
3014 			continue;
3015 
3016 		return (tstate->idx[i].idx);
3017 	}
3018 
3019 	if (tstate->count + 1 > tstate->size) {
3020 		tstate->size += 4;
3021 		tstate->idx = realloc(tstate->idx, tstate->size *
3022 		    sizeof(ipfw_obj_ntlv));
3023 		if (tstate->idx == NULL)
3024 			return (0);
3025 	}
3026 
3027 	ntlv = &tstate->idx[i];
3028 	memset(ntlv, 0, sizeof(ipfw_obj_ntlv));
3029 	strlcpy(ntlv->name, name, sizeof(ntlv->name));
3030 	ntlv->head.type = otype;
3031 	ntlv->head.length = sizeof(ipfw_obj_ntlv);
3032 	ntlv->set = tstate->set;
3033 	ntlv->idx = ++tstate->counter;
3034 	tstate->count++;
3035 
3036 	return (ntlv->idx);
3037 }
3038 
3039 static uint16_t
3040 pack_table(struct tidx *tstate, char *name)
3041 {
3042 
3043 	if (table_check_name(name) != 0)
3044 		return (0);
3045 
3046 	return (pack_object(tstate, name, IPFW_TLV_TBL_NAME));
3047 }
3048 
3049 void
3050 fill_table(struct _ipfw_insn *cmd, char *av, uint8_t opcode,
3051     struct tidx *tstate)
3052 {
3053 	uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
3054 	uint16_t uidx;
3055 	char *p;
3056 
3057 	if ((p = strchr(av + 6, ')')) == NULL)
3058 		errx(EX_DATAERR, "forgotten parenthesis: '%s'", av);
3059 	*p = '\0';
3060 	p = strchr(av + 6, ',');
3061 	if (p)
3062 		*p++ = '\0';
3063 
3064 	if ((uidx = pack_table(tstate, av + 6)) == 0)
3065 		errx(EX_DATAERR, "Invalid table name: %s", av + 6);
3066 
3067 	cmd->opcode = opcode;
3068 	cmd->arg1 = uidx;
3069 	if (p) {
3070 		cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3071 		d[0] = strtoul(p, NULL, 0);
3072 	} else
3073 		cmd->len |= F_INSN_SIZE(ipfw_insn);
3074 }
3075 
3076 
3077 /*
3078  * fills the addr and mask fields in the instruction as appropriate from av.
3079  * Update length as appropriate.
3080  * The following formats are allowed:
3081  *	me	returns O_IP_*_ME
3082  *	1.2.3.4		single IP address
3083  *	1.2.3.4:5.6.7.8	address:mask
3084  *	1.2.3.4/24	address/mask
3085  *	1.2.3.4/26{1,6,5,4,23}	set of addresses in a subnet
3086  * We can have multiple comma-separated address/mask entries.
3087  */
3088 static void
3089 fill_ip(ipfw_insn_ip *cmd, char *av, int cblen, struct tidx *tstate)
3090 {
3091 	int len = 0;
3092 	uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
3093 
3094 	cmd->o.len &= ~F_LEN_MASK;	/* zero len */
3095 
3096 	if (_substrcmp(av, "any") == 0)
3097 		return;
3098 
3099 	if (_substrcmp(av, "me") == 0) {
3100 		cmd->o.len |= F_INSN_SIZE(ipfw_insn);
3101 		return;
3102 	}
3103 
3104 	if (strncmp(av, "table(", 6) == 0) {
3105 		fill_table(&cmd->o, av, O_IP_DST_LOOKUP, tstate);
3106 		return;
3107 	}
3108 
3109     while (av) {
3110 	/*
3111 	 * After the address we can have '/' or ':' indicating a mask,
3112 	 * ',' indicating another address follows, '{' indicating a
3113 	 * set of addresses of unspecified size.
3114 	 */
3115 	char *t = NULL, *p = strpbrk(av, "/:,{");
3116 	int masklen;
3117 	char md, nd = '\0';
3118 
3119 	CHECK_LENGTH(cblen, F_INSN_SIZE(ipfw_insn) + 2 + len);
3120 
3121 	if (p) {
3122 		md = *p;
3123 		*p++ = '\0';
3124 		if ((t = strpbrk(p, ",{")) != NULL) {
3125 			nd = *t;
3126 			*t = '\0';
3127 		}
3128 	} else
3129 		md = '\0';
3130 
3131 	if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
3132 		errx(EX_NOHOST, "hostname ``%s'' unknown", av);
3133 	switch (md) {
3134 	case ':':
3135 		if (!inet_aton(p, (struct in_addr *)&d[1]))
3136 			errx(EX_DATAERR, "bad netmask ``%s''", p);
3137 		break;
3138 	case '/':
3139 		masklen = atoi(p);
3140 		if (masklen == 0)
3141 			d[1] = htonl(0U);	/* mask */
3142 		else if (masklen > 32)
3143 			errx(EX_DATAERR, "bad width ``%s''", p);
3144 		else
3145 			d[1] = htonl(~0U << (32 - masklen));
3146 		break;
3147 	case '{':	/* no mask, assume /24 and put back the '{' */
3148 		d[1] = htonl(~0U << (32 - 24));
3149 		*(--p) = md;
3150 		break;
3151 
3152 	case ',':	/* single address plus continuation */
3153 		*(--p) = md;
3154 		/* FALLTHROUGH */
3155 	case 0:		/* initialization value */
3156 	default:
3157 		d[1] = htonl(~0U);	/* force /32 */
3158 		break;
3159 	}
3160 	d[0] &= d[1];		/* mask base address with mask */
3161 	if (t)
3162 		*t = nd;
3163 	/* find next separator */
3164 	if (p)
3165 		p = strpbrk(p, ",{");
3166 	if (p && *p == '{') {
3167 		/*
3168 		 * We have a set of addresses. They are stored as follows:
3169 		 *   arg1	is the set size (powers of 2, 2..256)
3170 		 *   addr	is the base address IN HOST FORMAT
3171 		 *   mask..	is an array of arg1 bits (rounded up to
3172 		 *		the next multiple of 32) with bits set
3173 		 *		for each host in the map.
3174 		 */
3175 		uint32_t *map = (uint32_t *)&cmd->mask;
3176 		int low, high;
3177 		int i = contigmask((uint8_t *)&(d[1]), 32);
3178 
3179 		if (len > 0)
3180 			errx(EX_DATAERR, "address set cannot be in a list");
3181 		if (i < 24 || i > 31)
3182 			errx(EX_DATAERR, "invalid set with mask %d\n", i);
3183 		cmd->o.arg1 = 1<<(32-i);	/* map length		*/
3184 		d[0] = ntohl(d[0]);		/* base addr in host format */
3185 		cmd->o.opcode = O_IP_DST_SET;	/* default */
3186 		cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
3187 		for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
3188 			map[i] = 0;	/* clear map */
3189 
3190 		av = p + 1;
3191 		low = d[0] & 0xff;
3192 		high = low + cmd->o.arg1 - 1;
3193 		/*
3194 		 * Here, i stores the previous value when we specify a range
3195 		 * of addresses within a mask, e.g. 45-63. i = -1 means we
3196 		 * have no previous value.
3197 		 */
3198 		i = -1;	/* previous value in a range */
3199 		while (isdigit(*av)) {
3200 			char *s;
3201 			int a = strtol(av, &s, 0);
3202 
3203 			if (s == av) { /* no parameter */
3204 			    if (*av != '}')
3205 				errx(EX_DATAERR, "set not closed\n");
3206 			    if (i != -1)
3207 				errx(EX_DATAERR, "incomplete range %d-", i);
3208 			    break;
3209 			}
3210 			if (a < low || a > high)
3211 			    errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
3212 				a, low, high);
3213 			a -= low;
3214 			if (i == -1)	/* no previous in range */
3215 			    i = a;
3216 			else {		/* check that range is valid */
3217 			    if (i > a)
3218 				errx(EX_DATAERR, "invalid range %d-%d",
3219 					i+low, a+low);
3220 			    if (*s == '-')
3221 				errx(EX_DATAERR, "double '-' in range");
3222 			}
3223 			for (; i <= a; i++)
3224 			    map[i/32] |= 1<<(i & 31);
3225 			i = -1;
3226 			if (*s == '-')
3227 			    i = a;
3228 			else if (*s == '}')
3229 			    break;
3230 			av = s+1;
3231 		}
3232 		return;
3233 	}
3234 	av = p;
3235 	if (av)			/* then *av must be a ',' */
3236 		av++;
3237 
3238 	/* Check this entry */
3239 	if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
3240 		/*
3241 		 * 'any' turns the entire list into a NOP.
3242 		 * 'not any' never matches, so it is removed from the
3243 		 * list unless it is the only item, in which case we
3244 		 * report an error.
3245 		 */
3246 		if (cmd->o.len & F_NOT) {	/* "not any" never matches */
3247 			if (av == NULL && len == 0) /* only this entry */
3248 				errx(EX_DATAERR, "not any never matches");
3249 		}
3250 		/* else do nothing and skip this entry */
3251 		return;
3252 	}
3253 	/* A single IP can be stored in an optimized format */
3254 	if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
3255 		cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
3256 		return;
3257 	}
3258 	len += 2;	/* two words... */
3259 	d += 2;
3260     } /* end while */
3261     if (len + 1 > F_LEN_MASK)
3262 	errx(EX_DATAERR, "address list too long");
3263     cmd->o.len |= len+1;
3264 }
3265 
3266 
3267 /* n2mask sets n bits of the mask */
3268 void
3269 n2mask(struct in6_addr *mask, int n)
3270 {
3271 	static int	minimask[9] =
3272 	    { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
3273 	u_char		*p;
3274 
3275 	memset(mask, 0, sizeof(struct in6_addr));
3276 	p = (u_char *) mask;
3277 	for (; n > 0; p++, n -= 8) {
3278 		if (n >= 8)
3279 			*p = 0xff;
3280 		else
3281 			*p = minimask[n];
3282 	}
3283 	return;
3284 }
3285 
3286 static void
3287 fill_flags_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3288 	struct _s_x *flags, char *p)
3289 {
3290 	char *e;
3291 	uint32_t set = 0, clear = 0;
3292 
3293 	if (fill_flags(flags, p, &e, &set, &clear) != 0)
3294 		errx(EX_DATAERR, "invalid flag %s", e);
3295 
3296 	cmd->opcode = opcode;
3297 	cmd->len =  (cmd->len & (F_NOT | F_OR)) | 1;
3298 	cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3299 }
3300 
3301 
3302 void
3303 ipfw_delete(char *av[])
3304 {
3305 	ipfw_range_tlv rt;
3306 	char *sep;
3307 	int i, j;
3308 	int exitval = EX_OK;
3309 	int do_set = 0;
3310 
3311 	av++;
3312 	NEED1("missing rule specification");
3313 	if ( *av && _substrcmp(*av, "set") == 0) {
3314 		/* Do not allow using the following syntax:
3315 		 *	ipfw set N delete set M
3316 		 */
3317 		if (co.use_set)
3318 			errx(EX_DATAERR, "invalid syntax");
3319 		do_set = 1;	/* delete set */
3320 		av++;
3321 	}
3322 
3323 	/* Rule number */
3324 	while (*av && isdigit(**av)) {
3325 		i = strtol(*av, &sep, 10);
3326 		j = i;
3327 		if (*sep== '-')
3328 			j = strtol(sep + 1, NULL, 10);
3329 		av++;
3330 		if (co.do_nat) {
3331 			exitval = ipfw_delete_nat(i);
3332 		} else if (co.do_pipe) {
3333 			exitval = ipfw_delete_pipe(co.do_pipe, i);
3334 		} else {
3335 			memset(&rt, 0, sizeof(rt));
3336 			if (do_set != 0) {
3337 				rt.set = i & 31;
3338 				rt.flags = IPFW_RCFLAG_SET;
3339 			} else {
3340 				rt.start_rule = i & 0xffff;
3341 				rt.end_rule = j & 0xffff;
3342 				if (rt.start_rule == 0 && rt.end_rule == 0)
3343 					rt.flags |= IPFW_RCFLAG_ALL;
3344 				else
3345 					rt.flags |= IPFW_RCFLAG_RANGE;
3346 				if (co.use_set != 0) {
3347 					rt.set = co.use_set - 1;
3348 					rt.flags |= IPFW_RCFLAG_SET;
3349 				}
3350 			}
3351 			if (co.do_dynamic == 2)
3352 				rt.flags |= IPFW_RCFLAG_DYNAMIC;
3353 			i = do_range_cmd(IP_FW_XDEL, &rt);
3354 			if (i != 0) {
3355 				exitval = EX_UNAVAILABLE;
3356 				if (co.do_quiet)
3357 					continue;
3358 				warn("rule %u: setsockopt(IP_FW_XDEL)",
3359 				    rt.start_rule);
3360 			} else if (rt.new_set == 0 && do_set == 0 &&
3361 			    co.do_dynamic != 2) {
3362 				exitval = EX_UNAVAILABLE;
3363 				if (co.do_quiet)
3364 					continue;
3365 				if (rt.start_rule != rt.end_rule)
3366 					warnx("no rules rules in %u-%u range",
3367 					    rt.start_rule, rt.end_rule);
3368 				else
3369 					warnx("rule %u not found",
3370 					    rt.start_rule);
3371 			}
3372 		}
3373 	}
3374 	if (exitval != EX_OK && co.do_force == 0)
3375 		exit(exitval);
3376 }
3377 
3378 
3379 /*
3380  * fill the interface structure. We do not check the name as we can
3381  * create interfaces dynamically, so checking them at insert time
3382  * makes relatively little sense.
3383  * Interface names containing '*', '?', or '[' are assumed to be shell
3384  * patterns which match interfaces.
3385  */
3386 static void
3387 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen, struct tidx *tstate)
3388 {
3389 	char *p;
3390 	uint16_t uidx;
3391 
3392 	cmd->name[0] = '\0';
3393 	cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3394 
3395 	CHECK_CMDLEN;
3396 
3397 	/* Parse the interface or address */
3398 	if (strcmp(arg, "any") == 0)
3399 		cmd->o.len = 0;		/* effectively ignore this command */
3400 	else if (strncmp(arg, "table(", 6) == 0) {
3401 		if ((p = strchr(arg + 6, ')')) == NULL)
3402 			errx(EX_DATAERR, "forgotten parenthesis: '%s'", arg);
3403 		*p = '\0';
3404 		p = strchr(arg + 6, ',');
3405 		if (p)
3406 			*p++ = '\0';
3407 		if ((uidx = pack_table(tstate, arg + 6)) == 0)
3408 			errx(EX_DATAERR, "Invalid table name: %s", arg + 6);
3409 
3410 		cmd->name[0] = '\1'; /* Special value indicating table */
3411 		cmd->p.kidx = uidx;
3412 	} else if (!isdigit(*arg)) {
3413 		strlcpy(cmd->name, arg, sizeof(cmd->name));
3414 		cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3415 	} else if (!inet_aton(arg, &cmd->p.ip))
3416 		errx(EX_DATAERR, "bad ip address ``%s''", arg);
3417 }
3418 
3419 static void
3420 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
3421 {
3422 	int i;
3423 	size_t l;
3424 	char *ap, *ptr, *optr;
3425 	struct ether_addr *mac;
3426 	const char *macset = "0123456789abcdefABCDEF:";
3427 
3428 	if (strcmp(p, "any") == 0) {
3429 		for (i = 0; i < ETHER_ADDR_LEN; i++)
3430 			addr[i] = mask[i] = 0;
3431 		return;
3432 	}
3433 
3434 	optr = ptr = strdup(p);
3435 	if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
3436 		l = strlen(ap);
3437 		if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
3438 			errx(EX_DATAERR, "Incorrect MAC address");
3439 		bcopy(mac, addr, ETHER_ADDR_LEN);
3440 	} else
3441 		errx(EX_DATAERR, "Incorrect MAC address");
3442 
3443 	if (ptr != NULL) { /* we have mask? */
3444 		if (p[ptr - optr - 1] == '/') { /* mask len */
3445 			long ml = strtol(ptr, &ap, 10);
3446 			if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
3447 				errx(EX_DATAERR, "Incorrect mask length");
3448 			for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
3449 				mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
3450 		} else { /* mask */
3451 			l = strlen(ptr);
3452 			if (strspn(ptr, macset) != l ||
3453 			    (mac = ether_aton(ptr)) == NULL)
3454 				errx(EX_DATAERR, "Incorrect mask");
3455 			bcopy(mac, mask, ETHER_ADDR_LEN);
3456 		}
3457 	} else { /* default mask: ff:ff:ff:ff:ff:ff */
3458 		for (i = 0; i < ETHER_ADDR_LEN; i++)
3459 			mask[i] = 0xff;
3460 	}
3461 	for (i = 0; i < ETHER_ADDR_LEN; i++)
3462 		addr[i] &= mask[i];
3463 
3464 	free(optr);
3465 }
3466 
3467 /*
3468  * helper function, updates the pointer to cmd with the length
3469  * of the current command, and also cleans up the first word of
3470  * the new command in case it has been clobbered before.
3471  */
3472 static ipfw_insn *
3473 next_cmd(ipfw_insn *cmd, int *len)
3474 {
3475 	*len -= F_LEN(cmd);
3476 	CHECK_LENGTH(*len, 0);
3477 	cmd += F_LEN(cmd);
3478 	bzero(cmd, sizeof(*cmd));
3479 	return cmd;
3480 }
3481 
3482 /*
3483  * Takes arguments and copies them into a comment
3484  */
3485 static void
3486 fill_comment(ipfw_insn *cmd, char **av, int cblen)
3487 {
3488 	int i, l;
3489 	char *p = (char *)(cmd + 1);
3490 
3491 	cmd->opcode = O_NOP;
3492 	cmd->len =  (cmd->len & (F_NOT | F_OR));
3493 
3494 	/* Compute length of comment string. */
3495 	for (i = 0, l = 0; av[i] != NULL; i++)
3496 		l += strlen(av[i]) + 1;
3497 	if (l == 0)
3498 		return;
3499 	if (l > 84)
3500 		errx(EX_DATAERR,
3501 		    "comment too long (max 80 chars)");
3502 	l = 1 + (l+3)/4;
3503 	cmd->len =  (cmd->len & (F_NOT | F_OR)) | l;
3504 	CHECK_CMDLEN;
3505 
3506 	for (i = 0; av[i] != NULL; i++) {
3507 		strcpy(p, av[i]);
3508 		p += strlen(av[i]);
3509 		*p++ = ' ';
3510 	}
3511 	*(--p) = '\0';
3512 }
3513 
3514 /*
3515  * A function to fill simple commands of size 1.
3516  * Existing flags are preserved.
3517  */
3518 static void
3519 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3520 {
3521 	cmd->opcode = opcode;
3522 	cmd->len =  ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3523 	cmd->arg1 = arg;
3524 }
3525 
3526 /*
3527  * Fetch and add the MAC address and type, with masks. This generates one or
3528  * two microinstructions, and returns the pointer to the last one.
3529  */
3530 static ipfw_insn *
3531 add_mac(ipfw_insn *cmd, char *av[], int cblen)
3532 {
3533 	ipfw_insn_mac *mac;
3534 
3535 	if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
3536 		errx(EX_DATAERR, "MAC dst src");
3537 
3538 	cmd->opcode = O_MACADDR2;
3539 	cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3540 	CHECK_CMDLEN;
3541 
3542 	mac = (ipfw_insn_mac *)cmd;
3543 	get_mac_addr_mask(av[0], mac->addr, mac->mask);	/* dst */
3544 	get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
3545 	    &(mac->mask[ETHER_ADDR_LEN])); /* src */
3546 	return cmd;
3547 }
3548 
3549 static ipfw_insn *
3550 add_mactype(ipfw_insn *cmd, char *av, int cblen)
3551 {
3552 	if (!av)
3553 		errx(EX_DATAERR, "missing MAC type");
3554 	if (strcmp(av, "any") != 0) { /* we have a non-null type */
3555 		fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
3556 		    cblen);
3557 		cmd->opcode = O_MAC_TYPE;
3558 		return cmd;
3559 	} else
3560 		return NULL;
3561 }
3562 
3563 static ipfw_insn *
3564 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
3565 {
3566 	struct protoent *pe;
3567 	char *ep;
3568 	int proto;
3569 
3570 	proto = strtol(av, &ep, 10);
3571 	if (*ep != '\0' || proto <= 0) {
3572 		if ((pe = getprotobyname(av)) == NULL)
3573 			return NULL;
3574 		proto = pe->p_proto;
3575 	}
3576 
3577 	fill_cmd(cmd, O_PROTO, 0, proto);
3578 	*protop = proto;
3579 	return cmd;
3580 }
3581 
3582 static ipfw_insn *
3583 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
3584 {
3585 	u_char proto = IPPROTO_IP;
3586 
3587 	if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3588 		; /* do not set O_IP4 nor O_IP6 */
3589 	else if (strcmp(av, "ip4") == 0)
3590 		/* explicit "just IPv4" rule */
3591 		fill_cmd(cmd, O_IP4, 0, 0);
3592 	else if (strcmp(av, "ip6") == 0) {
3593 		/* explicit "just IPv6" rule */
3594 		proto = IPPROTO_IPV6;
3595 		fill_cmd(cmd, O_IP6, 0, 0);
3596 	} else
3597 		return add_proto0(cmd, av, protop);
3598 
3599 	*protop = proto;
3600 	return cmd;
3601 }
3602 
3603 static ipfw_insn *
3604 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
3605 {
3606 	u_char proto = IPPROTO_IP;
3607 
3608 	if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3609 		; /* do not set O_IP4 nor O_IP6 */
3610 	else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3611 		/* explicit "just IPv4" rule */
3612 		fill_cmd(cmd, O_IP4, 0, 0);
3613 	else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3614 		/* explicit "just IPv6" rule */
3615 		proto = IPPROTO_IPV6;
3616 		fill_cmd(cmd, O_IP6, 0, 0);
3617 	} else
3618 		return add_proto0(cmd, av, protop);
3619 
3620 	*protop = proto;
3621 	return cmd;
3622 }
3623 
3624 static ipfw_insn *
3625 add_srcip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3626 {
3627 	fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3628 	if (cmd->opcode == O_IP_DST_SET)			/* set */
3629 		cmd->opcode = O_IP_SRC_SET;
3630 	else if (cmd->opcode == O_IP_DST_LOOKUP)		/* table */
3631 		cmd->opcode = O_IP_SRC_LOOKUP;
3632 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))		/* me */
3633 		cmd->opcode = O_IP_SRC_ME;
3634 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))	/* one IP */
3635 		cmd->opcode = O_IP_SRC;
3636 	else							/* addr/mask */
3637 		cmd->opcode = O_IP_SRC_MASK;
3638 	return cmd;
3639 }
3640 
3641 static ipfw_insn *
3642 add_dstip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3643 {
3644 	fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3645 	if (cmd->opcode == O_IP_DST_SET)			/* set */
3646 		;
3647 	else if (cmd->opcode == O_IP_DST_LOOKUP)		/* table */
3648 		;
3649 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))		/* me */
3650 		cmd->opcode = O_IP_DST_ME;
3651 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))	/* one IP */
3652 		cmd->opcode = O_IP_DST;
3653 	else							/* addr/mask */
3654 		cmd->opcode = O_IP_DST_MASK;
3655 	return cmd;
3656 }
3657 
3658 static struct _s_x f_reserved_keywords[] = {
3659 	{ "altq",	TOK_OR },
3660 	{ "//",		TOK_OR },
3661 	{ "diverted",	TOK_OR },
3662 	{ "dst-port",	TOK_OR },
3663 	{ "src-port",	TOK_OR },
3664 	{ "established",	TOK_OR },
3665 	{ "keep-state",	TOK_OR },
3666 	{ "frag",	TOK_OR },
3667 	{ "icmptypes",	TOK_OR },
3668 	{ "in",		TOK_OR },
3669 	{ "out",	TOK_OR },
3670 	{ "ip6",	TOK_OR },
3671 	{ "any",	TOK_OR },
3672 	{ "to",		TOK_OR },
3673 	{ "via",	TOK_OR },
3674 	{ "{",		TOK_OR },
3675 	{ NULL, 0 }	/* terminator */
3676 };
3677 
3678 static ipfw_insn *
3679 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
3680 {
3681 
3682 	if (match_token(f_reserved_keywords, av) != -1)
3683 		return (NULL);
3684 
3685 	if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
3686 		/* XXX todo: check that we have a protocol with ports */
3687 		cmd->opcode = opcode;
3688 		return cmd;
3689 	}
3690 	return NULL;
3691 }
3692 
3693 static ipfw_insn *
3694 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3695 {
3696 	struct in6_addr a;
3697 	char *host, *ch, buf[INET6_ADDRSTRLEN];
3698 	ipfw_insn *ret = NULL;
3699 	int len;
3700 
3701 	/* Copy first address in set if needed */
3702 	if ((ch = strpbrk(av, "/,")) != NULL) {
3703 		len = ch - av;
3704 		strlcpy(buf, av, sizeof(buf));
3705 		if (len < sizeof(buf))
3706 			buf[len] = '\0';
3707 		host = buf;
3708 	} else
3709 		host = av;
3710 
3711 	if (proto == IPPROTO_IPV6  || strcmp(av, "me6") == 0 ||
3712 	    inet_pton(AF_INET6, host, &a) == 1)
3713 		ret = add_srcip6(cmd, av, cblen, tstate);
3714 	/* XXX: should check for IPv4, not !IPv6 */
3715 	if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3716 	    inet_pton(AF_INET6, host, &a) != 1))
3717 		ret = add_srcip(cmd, av, cblen, tstate);
3718 	if (ret == NULL && strcmp(av, "any") != 0)
3719 		ret = cmd;
3720 
3721 	return ret;
3722 }
3723 
3724 static ipfw_insn *
3725 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3726 {
3727 	struct in6_addr a;
3728 	char *host, *ch, buf[INET6_ADDRSTRLEN];
3729 	ipfw_insn *ret = NULL;
3730 	int len;
3731 
3732 	/* Copy first address in set if needed */
3733 	if ((ch = strpbrk(av, "/,")) != NULL) {
3734 		len = ch - av;
3735 		strlcpy(buf, av, sizeof(buf));
3736 		if (len < sizeof(buf))
3737 			buf[len] = '\0';
3738 		host = buf;
3739 	} else
3740 		host = av;
3741 
3742 	if (proto == IPPROTO_IPV6  || strcmp(av, "me6") == 0 ||
3743 	    inet_pton(AF_INET6, host, &a) == 1)
3744 		ret = add_dstip6(cmd, av, cblen, tstate);
3745 	/* XXX: should check for IPv4, not !IPv6 */
3746 	if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3747 	    inet_pton(AF_INET6, host, &a) != 1))
3748 		ret = add_dstip(cmd, av, cblen, tstate);
3749 	if (ret == NULL && strcmp(av, "any") != 0)
3750 		ret = cmd;
3751 
3752 	return ret;
3753 }
3754 
3755 /*
3756  * Parse arguments and assemble the microinstructions which make up a rule.
3757  * Rules are added into the 'rulebuf' and then copied in the correct order
3758  * into the actual rule.
3759  *
3760  * The syntax for a rule starts with the action, followed by
3761  * optional action parameters, and the various match patterns.
3762  * In the assembled microcode, the first opcode must be an O_PROBE_STATE
3763  * (generated if the rule includes a keep-state option), then the
3764  * various match patterns, log/altq actions, and the actual action.
3765  *
3766  */
3767 void
3768 compile_rule(char *av[], uint32_t *rbuf, int *rbufsize, struct tidx *tstate)
3769 {
3770 	/*
3771 	 * rules are added into the 'rulebuf' and then copied in
3772 	 * the correct order into the actual rule.
3773 	 * Some things that need to go out of order (prob, action etc.)
3774 	 * go into actbuf[].
3775 	 */
3776 	static uint32_t actbuf[255], cmdbuf[255];
3777 	int rblen, ablen, cblen;
3778 
3779 	ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
3780 	ipfw_insn *first_cmd;	/* first match pattern */
3781 
3782 	struct ip_fw_rule *rule;
3783 
3784 	/*
3785 	 * various flags used to record that we entered some fields.
3786 	 */
3787 	ipfw_insn *have_state = NULL;	/* any state-related option */
3788 	int have_rstate = 0;
3789 	ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
3790 	ipfw_insn *have_skipcmd = NULL;
3791 	size_t len;
3792 
3793 	int i;
3794 
3795 	int open_par = 0;	/* open parenthesis ( */
3796 
3797 	/* proto is here because it is used to fetch ports */
3798 	u_char proto = IPPROTO_IP;	/* default protocol */
3799 
3800 	double match_prob = 1; /* match probability, default is always match */
3801 
3802 	bzero(actbuf, sizeof(actbuf));		/* actions go here */
3803 	bzero(cmdbuf, sizeof(cmdbuf));
3804 	bzero(rbuf, *rbufsize);
3805 
3806 	rule = (struct ip_fw_rule *)rbuf;
3807 	cmd = (ipfw_insn *)cmdbuf;
3808 	action = (ipfw_insn *)actbuf;
3809 
3810 	rblen = *rbufsize / sizeof(uint32_t);
3811 	rblen -= sizeof(struct ip_fw_rule) / sizeof(uint32_t);
3812 	ablen = sizeof(actbuf) / sizeof(actbuf[0]);
3813 	cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
3814 	cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
3815 
3816 #define	CHECK_RBUFLEN(len)	{ CHECK_LENGTH(rblen, len); rblen -= len; }
3817 #define	CHECK_ACTLEN		CHECK_LENGTH(ablen, action->len)
3818 
3819 	av++;
3820 
3821 	/* [rule N]	-- Rule number optional */
3822 	if (av[0] && isdigit(**av)) {
3823 		rule->rulenum = atoi(*av);
3824 		av++;
3825 	}
3826 
3827 	/* [set N]	-- set number (0..RESVD_SET), optional */
3828 	if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
3829 		int set = strtoul(av[1], NULL, 10);
3830 		if (set < 0 || set > RESVD_SET)
3831 			errx(EX_DATAERR, "illegal set %s", av[1]);
3832 		rule->set = set;
3833 		tstate->set = set;
3834 		av += 2;
3835 	}
3836 
3837 	/* [prob D]	-- match probability, optional */
3838 	if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
3839 		match_prob = strtod(av[1], NULL);
3840 
3841 		if (match_prob <= 0 || match_prob > 1)
3842 			errx(EX_DATAERR, "illegal match prob. %s", av[1]);
3843 		av += 2;
3844 	}
3845 
3846 	/* action	-- mandatory */
3847 	NEED1("missing action");
3848 	i = match_token(rule_actions, *av);
3849 	av++;
3850 	action->len = 1;	/* default */
3851 	CHECK_ACTLEN;
3852 	switch(i) {
3853 	case TOK_CHECKSTATE:
3854 		have_state = action;
3855 		action->opcode = O_CHECK_STATE;
3856 		if (*av == NULL ||
3857 		    match_token(rule_options, *av) == TOK_COMMENT) {
3858 			action->arg1 = pack_object(tstate,
3859 			    default_state_name, IPFW_TLV_STATE_NAME);
3860 			break;
3861 		}
3862 		if (*av[0] == ':') {
3863 			if (strcmp(*av + 1, "any") == 0)
3864 				action->arg1 = 0;
3865 			else if (state_check_name(*av + 1) == 0)
3866 				action->arg1 = pack_object(tstate, *av + 1,
3867 				    IPFW_TLV_STATE_NAME);
3868 			else
3869 				errx(EX_DATAERR, "Invalid state name %s",
3870 				    *av);
3871 			av++;
3872 			break;
3873 		}
3874 		errx(EX_DATAERR, "Invalid state name %s", *av);
3875 		break;
3876 
3877 	case TOK_ABORT:
3878 		action->opcode = O_REJECT;
3879 		action->arg1 = ICMP_REJECT_ABORT;
3880 		break;
3881 
3882 	case TOK_ABORT6:
3883 		action->opcode = O_UNREACH6;
3884 		action->arg1 = ICMP6_UNREACH_ABORT;
3885 		break;
3886 
3887 	case TOK_ACCEPT:
3888 		action->opcode = O_ACCEPT;
3889 		break;
3890 
3891 	case TOK_DENY:
3892 		action->opcode = O_DENY;
3893 		action->arg1 = 0;
3894 		break;
3895 
3896 	case TOK_REJECT:
3897 		action->opcode = O_REJECT;
3898 		action->arg1 = ICMP_UNREACH_HOST;
3899 		break;
3900 
3901 	case TOK_RESET:
3902 		action->opcode = O_REJECT;
3903 		action->arg1 = ICMP_REJECT_RST;
3904 		break;
3905 
3906 	case TOK_RESET6:
3907 		action->opcode = O_UNREACH6;
3908 		action->arg1 = ICMP6_UNREACH_RST;
3909 		break;
3910 
3911 	case TOK_UNREACH:
3912 		action->opcode = O_REJECT;
3913 		NEED1("missing reject code");
3914 		fill_reject_code(&action->arg1, *av);
3915 		av++;
3916 		break;
3917 
3918 	case TOK_UNREACH6:
3919 		action->opcode = O_UNREACH6;
3920 		NEED1("missing unreach code");
3921 		fill_unreach6_code(&action->arg1, *av);
3922 		av++;
3923 		break;
3924 
3925 	case TOK_COUNT:
3926 		action->opcode = O_COUNT;
3927 		break;
3928 
3929 	case TOK_NAT:
3930 		action->opcode = O_NAT;
3931 		action->len = F_INSN_SIZE(ipfw_insn_nat);
3932 		CHECK_ACTLEN;
3933 		if (*av != NULL && _substrcmp(*av, "global") == 0) {
3934 			action->arg1 = IP_FW_NAT44_GLOBAL;
3935 			av++;
3936 			break;
3937 		} else
3938 			goto chkarg;
3939 	case TOK_QUEUE:
3940 		action->opcode = O_QUEUE;
3941 		goto chkarg;
3942 	case TOK_PIPE:
3943 		action->opcode = O_PIPE;
3944 		goto chkarg;
3945 	case TOK_SKIPTO:
3946 		action->opcode = O_SKIPTO;
3947 		goto chkarg;
3948 	case TOK_NETGRAPH:
3949 		action->opcode = O_NETGRAPH;
3950 		goto chkarg;
3951 	case TOK_NGTEE:
3952 		action->opcode = O_NGTEE;
3953 		goto chkarg;
3954 	case TOK_DIVERT:
3955 		action->opcode = O_DIVERT;
3956 		goto chkarg;
3957 	case TOK_TEE:
3958 		action->opcode = O_TEE;
3959 		goto chkarg;
3960 	case TOK_CALL:
3961 		action->opcode = O_CALLRETURN;
3962 chkarg:
3963 		if (!av[0])
3964 			errx(EX_USAGE, "missing argument for %s", *(av - 1));
3965 		if (isdigit(**av)) {
3966 			action->arg1 = strtoul(*av, NULL, 10);
3967 			if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
3968 				errx(EX_DATAERR, "illegal argument for %s",
3969 				    *(av - 1));
3970 		} else if (_substrcmp(*av, "tablearg") == 0) {
3971 			action->arg1 = IP_FW_TARG;
3972 		} else if (i == TOK_DIVERT || i == TOK_TEE) {
3973 			struct servent *s;
3974 			setservent(1);
3975 			s = getservbyname(av[0], "divert");
3976 			if (s != NULL)
3977 				action->arg1 = ntohs(s->s_port);
3978 			else
3979 				errx(EX_DATAERR, "illegal divert/tee port");
3980 		} else
3981 			errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
3982 		av++;
3983 		break;
3984 
3985 	case TOK_FORWARD: {
3986 		/*
3987 		 * Locate the address-port separator (':' or ',').
3988 		 * Could be one of the following:
3989 		 *	hostname:port
3990 		 *	IPv4 a.b.c.d,port
3991 		 *	IPv4 a.b.c.d:port
3992 		 *	IPv6 w:x:y::z,port
3993 		 * The ':' can only be used with hostname and IPv4 address.
3994 		 * XXX-BZ Should we also support [w:x:y::z]:port?
3995 		 */
3996 		struct sockaddr_storage result;
3997 		struct addrinfo *res;
3998 		char *s, *end;
3999 		int family;
4000 		u_short port_number;
4001 
4002 		NEED1("missing forward address[:port]");
4003 
4004 		/*
4005 		 * locate the address-port separator (':' or ',')
4006 		 */
4007 		s = strchr(*av, ',');
4008 		if (s == NULL) {
4009 			/* Distinguish between IPv4:port and IPv6 cases. */
4010 			s = strchr(*av, ':');
4011 			if (s && strchr(s+1, ':'))
4012 				s = NULL; /* no port */
4013 		}
4014 
4015 		port_number = 0;
4016 		if (s != NULL) {
4017 			/* Terminate host portion and set s to start of port. */
4018 			*(s++) = '\0';
4019 			i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
4020 			if (s == end)
4021 				errx(EX_DATAERR,
4022 				    "illegal forwarding port ``%s''", s);
4023 			port_number = (u_short)i;
4024 		}
4025 
4026 		if (_substrcmp(*av, "tablearg") == 0) {
4027 			family = PF_INET;
4028 			((struct sockaddr_in*)&result)->sin_addr.s_addr =
4029 			    INADDR_ANY;
4030 		} else {
4031 			/*
4032 			 * Resolve the host name or address to a family and a
4033 			 * network representation of the address.
4034 			 */
4035 			if (getaddrinfo(*av, NULL, NULL, &res))
4036 				errx(EX_DATAERR, NULL);
4037 			/* Just use the first host in the answer. */
4038 			family = res->ai_family;
4039 			memcpy(&result, res->ai_addr, res->ai_addrlen);
4040 			freeaddrinfo(res);
4041 		}
4042 
4043  		if (family == PF_INET) {
4044 			ipfw_insn_sa *p = (ipfw_insn_sa *)action;
4045 
4046 			action->opcode = O_FORWARD_IP;
4047 			action->len = F_INSN_SIZE(ipfw_insn_sa);
4048 			CHECK_ACTLEN;
4049 
4050 			/*
4051 			 * In the kernel we assume AF_INET and use only
4052 			 * sin_port and sin_addr. Remember to set sin_len as
4053 			 * the routing code seems to use it too.
4054 			 */
4055 			p->sa.sin_len = sizeof(struct sockaddr_in);
4056 			p->sa.sin_family = AF_INET;
4057 			p->sa.sin_port = port_number;
4058 			p->sa.sin_addr.s_addr =
4059 			     ((struct sockaddr_in *)&result)->sin_addr.s_addr;
4060 		} else if (family == PF_INET6) {
4061 			ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
4062 
4063 			action->opcode = O_FORWARD_IP6;
4064 			action->len = F_INSN_SIZE(ipfw_insn_sa6);
4065 			CHECK_ACTLEN;
4066 
4067 			p->sa.sin6_len = sizeof(struct sockaddr_in6);
4068 			p->sa.sin6_family = AF_INET6;
4069 			p->sa.sin6_port = port_number;
4070 			p->sa.sin6_flowinfo = 0;
4071 			p->sa.sin6_scope_id =
4072 			    ((struct sockaddr_in6 *)&result)->sin6_scope_id;
4073 			bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
4074 			    &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
4075 		} else {
4076 			errx(EX_DATAERR, "Invalid address family in forward action");
4077 		}
4078 		av++;
4079 		break;
4080 	    }
4081 	case TOK_COMMENT:
4082 		/* pretend it is a 'count' rule followed by the comment */
4083 		action->opcode = O_COUNT;
4084 		av--;		/* go back... */
4085 		break;
4086 
4087 	case TOK_SETFIB:
4088 	    {
4089 		int numfibs;
4090 		size_t intsize = sizeof(int);
4091 
4092 		action->opcode = O_SETFIB;
4093 		NEED1("missing fib number");
4094 		if (_substrcmp(*av, "tablearg") == 0) {
4095 			action->arg1 = IP_FW_TARG;
4096 		} else {
4097 		        action->arg1 = strtoul(*av, NULL, 10);
4098 			if (sysctlbyname("net.fibs", &numfibs, &intsize,
4099 			    NULL, 0) == -1)
4100 				errx(EX_DATAERR, "fibs not suported.\n");
4101 			if (action->arg1 >= numfibs)  /* Temporary */
4102 				errx(EX_DATAERR, "fib too large.\n");
4103 			/* Add high-order bit to fib to make room for tablearg*/
4104 			action->arg1 |= 0x8000;
4105 		}
4106 		av++;
4107 		break;
4108 	    }
4109 
4110 	case TOK_SETDSCP:
4111 	    {
4112 		int code;
4113 
4114 		action->opcode = O_SETDSCP;
4115 		NEED1("missing DSCP code");
4116 		if (_substrcmp(*av, "tablearg") == 0) {
4117 			action->arg1 = IP_FW_TARG;
4118 		} else {
4119 			if (isalpha(*av[0])) {
4120 				if ((code = match_token(f_ipdscp, *av)) == -1)
4121 					errx(EX_DATAERR, "Unknown DSCP code");
4122 				action->arg1 = code;
4123 			} else
4124 			        action->arg1 = strtoul(*av, NULL, 10);
4125 			/*
4126 			 * Add high-order bit to DSCP to make room
4127 			 * for tablearg
4128 			 */
4129 			action->arg1 |= 0x8000;
4130 		}
4131 		av++;
4132 		break;
4133 	    }
4134 
4135 	case TOK_REASS:
4136 		action->opcode = O_REASS;
4137 		break;
4138 
4139 	case TOK_RETURN:
4140 		fill_cmd(action, O_CALLRETURN, F_NOT, 0);
4141 		break;
4142 
4143 	case TOK_TCPSETMSS: {
4144 		u_long mss;
4145 		uint16_t idx;
4146 
4147 		idx = pack_object(tstate, "tcp-setmss", IPFW_TLV_EACTION);
4148 		if (idx == 0)
4149 			errx(EX_DATAERR, "pack_object failed");
4150 		fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4151 		NEED1("Missing MSS value");
4152 		action = next_cmd(action, &ablen);
4153 		action->len = 1;
4154 		CHECK_ACTLEN;
4155 		mss = strtoul(*av, NULL, 10);
4156 		if (mss == 0 || mss > UINT16_MAX)
4157 			errx(EX_USAGE, "invalid MSS value %s", *av);
4158 		fill_cmd(action, O_EXTERNAL_DATA, 0, (uint16_t)mss);
4159 		av++;
4160 		break;
4161 	}
4162 
4163 	default:
4164 		av--;
4165 		if (match_token(rule_eactions, *av) == -1)
4166 			errx(EX_DATAERR, "invalid action %s\n", *av);
4167 		/*
4168 		 * External actions support.
4169 		 * XXX: we support only syntax with instance name.
4170 		 *	For known external actions (from rule_eactions list)
4171 		 *	we can handle syntax directly. But with `eaction'
4172 		 *	keyword we can use only `eaction <name> <instance>'
4173 		 *	syntax.
4174 		 */
4175 	case TOK_EACTION: {
4176 		uint16_t idx;
4177 
4178 		NEED1("Missing eaction name");
4179 		if (eaction_check_name(*av) != 0)
4180 			errx(EX_DATAERR, "Invalid eaction name %s", *av);
4181 		idx = pack_object(tstate, *av, IPFW_TLV_EACTION);
4182 		if (idx == 0)
4183 			errx(EX_DATAERR, "pack_object failed");
4184 		fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4185 		av++;
4186 		NEED1("Missing eaction instance name");
4187 		action = next_cmd(action, &ablen);
4188 		action->len = 1;
4189 		CHECK_ACTLEN;
4190 		if (eaction_check_name(*av) != 0)
4191 			errx(EX_DATAERR, "Invalid eaction instance name %s",
4192 			    *av);
4193 		/*
4194 		 * External action instance object has TLV type depended
4195 		 * from the external action name object index. Since we
4196 		 * currently don't know this index, use zero as TLV type.
4197 		 */
4198 		idx = pack_object(tstate, *av, 0);
4199 		if (idx == 0)
4200 			errx(EX_DATAERR, "pack_object failed");
4201 		fill_cmd(action, O_EXTERNAL_INSTANCE, 0, idx);
4202 		av++;
4203 		}
4204 	}
4205 	action = next_cmd(action, &ablen);
4206 
4207 	/*
4208 	 * [altq queuename] -- altq tag, optional
4209 	 * [log [logamount N]]	-- log, optional
4210 	 *
4211 	 * If they exist, it go first in the cmdbuf, but then it is
4212 	 * skipped in the copy section to the end of the buffer.
4213 	 */
4214 	while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
4215 		av++;
4216 		switch (i) {
4217 		case TOK_LOG:
4218 		    {
4219 			ipfw_insn_log *c = (ipfw_insn_log *)cmd;
4220 			int l;
4221 
4222 			if (have_log)
4223 				errx(EX_DATAERR,
4224 				    "log cannot be specified more than once");
4225 			have_log = (ipfw_insn *)c;
4226 			cmd->len = F_INSN_SIZE(ipfw_insn_log);
4227 			CHECK_CMDLEN;
4228 			cmd->opcode = O_LOG;
4229 			if (av[0] && _substrcmp(*av, "logamount") == 0) {
4230 				av++;
4231 				NEED1("logamount requires argument");
4232 				l = atoi(*av);
4233 				if (l < 0)
4234 					errx(EX_DATAERR,
4235 					    "logamount must be positive");
4236 				c->max_log = l;
4237 				av++;
4238 			} else {
4239 				len = sizeof(c->max_log);
4240 				if (sysctlbyname("net.inet.ip.fw.verbose_limit",
4241 				    &c->max_log, &len, NULL, 0) == -1) {
4242 					if (co.test_only) {
4243 						c->max_log = 0;
4244 						break;
4245 					}
4246 					errx(1, "sysctlbyname(\"%s\")",
4247 					    "net.inet.ip.fw.verbose_limit");
4248 				}
4249 			}
4250 		    }
4251 			break;
4252 
4253 #ifndef NO_ALTQ
4254 		case TOK_ALTQ:
4255 		    {
4256 			ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
4257 
4258 			NEED1("missing altq queue name");
4259 			if (have_altq)
4260 				errx(EX_DATAERR,
4261 				    "altq cannot be specified more than once");
4262 			have_altq = (ipfw_insn *)a;
4263 			cmd->len = F_INSN_SIZE(ipfw_insn_altq);
4264 			CHECK_CMDLEN;
4265 			cmd->opcode = O_ALTQ;
4266 			a->qid = altq_name_to_qid(*av);
4267 			av++;
4268 		    }
4269 			break;
4270 #endif
4271 
4272 		case TOK_TAG:
4273 		case TOK_UNTAG: {
4274 			uint16_t tag;
4275 
4276 			if (have_tag)
4277 				errx(EX_USAGE, "tag and untag cannot be "
4278 				    "specified more than once");
4279 			GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
4280 			   rule_action_params);
4281 			have_tag = cmd;
4282 			fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
4283 			av++;
4284 			break;
4285 		}
4286 
4287 		default:
4288 			abort();
4289 		}
4290 		cmd = next_cmd(cmd, &cblen);
4291 	}
4292 
4293 	if (have_state)	{ /* must be a check-state, we are done */
4294 		if (*av != NULL &&
4295 		    match_token(rule_options, *av) == TOK_COMMENT) {
4296 			/* check-state has a comment */
4297 			av++;
4298 			fill_comment(cmd, av, cblen);
4299 			cmd = next_cmd(cmd, &cblen);
4300 			av[0] = NULL;
4301 		}
4302 		goto done;
4303 	}
4304 
4305 #define OR_START(target)					\
4306 	if (av[0] && (*av[0] == '(' || *av[0] == '{')) { 	\
4307 		if (open_par)					\
4308 			errx(EX_USAGE, "nested \"(\" not allowed\n"); \
4309 		prev = NULL;					\
4310 		open_par = 1;					\
4311 		if ( (av[0])[1] == '\0') {			\
4312 			av++;					\
4313 		} else						\
4314 			(*av)++;				\
4315 	}							\
4316 	target:							\
4317 
4318 
4319 #define	CLOSE_PAR						\
4320 	if (open_par) {						\
4321 		if (av[0] && (					\
4322 		    strcmp(*av, ")") == 0 ||			\
4323 		    strcmp(*av, "}") == 0)) {			\
4324 			prev = NULL;				\
4325 			open_par = 0;				\
4326 			av++;					\
4327 		} else						\
4328 			errx(EX_USAGE, "missing \")\"\n");	\
4329 	}
4330 
4331 #define NOT_BLOCK						\
4332 	if (av[0] && _substrcmp(*av, "not") == 0) {		\
4333 		if (cmd->len & F_NOT)				\
4334 			errx(EX_USAGE, "double \"not\" not allowed\n"); \
4335 		cmd->len |= F_NOT;				\
4336 		av++;						\
4337 	}
4338 
4339 #define OR_BLOCK(target)					\
4340 	if (av[0] && _substrcmp(*av, "or") == 0) {		\
4341 		if (prev == NULL || open_par == 0)		\
4342 			errx(EX_DATAERR, "invalid OR block");	\
4343 		prev->len |= F_OR;				\
4344 		av++;					\
4345 		goto target;					\
4346 	}							\
4347 	CLOSE_PAR;
4348 
4349 	first_cmd = cmd;
4350 
4351 #if 0
4352 	/*
4353 	 * MAC addresses, optional.
4354 	 * If we have this, we skip the part "proto from src to dst"
4355 	 * and jump straight to the option parsing.
4356 	 */
4357 	NOT_BLOCK;
4358 	NEED1("missing protocol");
4359 	if (_substrcmp(*av, "MAC") == 0 ||
4360 	    _substrcmp(*av, "mac") == 0) {
4361 		av++;			/* the "MAC" keyword */
4362 		add_mac(cmd, av);	/* exits in case of errors */
4363 		cmd = next_cmd(cmd);
4364 		av += 2;		/* dst-mac and src-mac */
4365 		NOT_BLOCK;
4366 		NEED1("missing mac type");
4367 		if (add_mactype(cmd, av[0]))
4368 			cmd = next_cmd(cmd);
4369 		av++;			/* any or mac-type */
4370 		goto read_options;
4371 	}
4372 #endif
4373 
4374 	/*
4375 	 * protocol, mandatory
4376 	 */
4377     OR_START(get_proto);
4378 	NOT_BLOCK;
4379 	NEED1("missing protocol");
4380 	if (add_proto_compat(cmd, *av, &proto)) {
4381 		av++;
4382 		if (F_LEN(cmd) != 0) {
4383 			prev = cmd;
4384 			cmd = next_cmd(cmd, &cblen);
4385 		}
4386 	} else if (first_cmd != cmd) {
4387 		errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4388 	} else {
4389 		rule->flags |= IPFW_RULE_JUSTOPTS;
4390 		goto read_options;
4391 	}
4392     OR_BLOCK(get_proto);
4393 
4394 	first_cmd = cmd; /* update pointer to use in compact form */
4395 
4396 	/*
4397 	 * "from", mandatory
4398 	 */
4399 	if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
4400 		errx(EX_USAGE, "missing ``from''");
4401 	av++;
4402 
4403 	/*
4404 	 * source IP, mandatory
4405 	 */
4406     OR_START(source_ip);
4407 	NOT_BLOCK;	/* optional "not" */
4408 	NEED1("missing source address");
4409 	if (add_src(cmd, *av, proto, cblen, tstate)) {
4410 		av++;
4411 		if (F_LEN(cmd) != 0) {	/* ! any */
4412 			prev = cmd;
4413 			cmd = next_cmd(cmd, &cblen);
4414 		}
4415 	} else
4416 		errx(EX_USAGE, "bad source address %s", *av);
4417     OR_BLOCK(source_ip);
4418 
4419 	/*
4420 	 * source ports, optional
4421 	 */
4422 	NOT_BLOCK;	/* optional "not" */
4423 	if ( av[0] != NULL ) {
4424 		if (_substrcmp(*av, "any") == 0 ||
4425 		    add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4426 			av++;
4427 			if (F_LEN(cmd) != 0)
4428 				cmd = next_cmd(cmd, &cblen);
4429 		}
4430 	}
4431 
4432 	/*
4433 	 * "to", mandatory
4434 	 */
4435 	if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
4436 		errx(EX_USAGE, "missing ``to''");
4437 	av++;
4438 
4439 	/*
4440 	 * destination, mandatory
4441 	 */
4442     OR_START(dest_ip);
4443 	NOT_BLOCK;	/* optional "not" */
4444 	NEED1("missing dst address");
4445 	if (add_dst(cmd, *av, proto, cblen, tstate)) {
4446 		av++;
4447 		if (F_LEN(cmd) != 0) {	/* ! any */
4448 			prev = cmd;
4449 			cmd = next_cmd(cmd, &cblen);
4450 		}
4451 	} else
4452 		errx( EX_USAGE, "bad destination address %s", *av);
4453     OR_BLOCK(dest_ip);
4454 
4455 	/*
4456 	 * dest. ports, optional
4457 	 */
4458 	NOT_BLOCK;	/* optional "not" */
4459 	if (av[0]) {
4460 		if (_substrcmp(*av, "any") == 0 ||
4461 		    add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4462 			av++;
4463 			if (F_LEN(cmd) != 0)
4464 				cmd = next_cmd(cmd, &cblen);
4465 		}
4466 	}
4467 	if (first_cmd == cmd)
4468 		rule->flags |= IPFW_RULE_NOOPT;
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 			char *end;
4672 			int jid;
4673 
4674 			cmd->opcode = O_JAIL;
4675 			/*
4676 			 * If av is a number, then we'll just pass it as-is.  If
4677 			 * it's a name, try to resolve that to a jid.
4678 			 *
4679 			 * We save the jail_getid(3) call for a fallback because
4680 			 * it entails an unconditional trip to the kernel to
4681 			 * either validate a jid or resolve a name to a jid.
4682 			 * This specific token doesn't currently require a
4683 			 * jid to be an active jail, so we save a transition
4684 			 * by simply using a number that we're given.
4685 			 */
4686 			jid = strtoul(*av, &end, 10);
4687 			if (*end != '\0') {
4688 				jid = jail_getid(*av);
4689 				if (jid < 0)
4690 				    errx(EX_DATAERR, "%s", jail_errmsg);
4691 			}
4692 			cmd32->d[0] = (uint32_t)jid;
4693 			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4694 			av++;
4695 		    }
4696 			break;
4697 
4698 		case TOK_ESTAB:
4699 			fill_cmd(cmd, O_ESTAB, 0, 0);
4700 			break;
4701 
4702 		case TOK_SETUP:
4703 			fill_cmd(cmd, O_TCPFLAGS, 0,
4704 				(TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
4705 			break;
4706 
4707 		case TOK_TCPDATALEN:
4708 			NEED1("tcpdatalen requires length");
4709 			if (strpbrk(*av, "-,")) {
4710 			    if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
4711 				errx(EX_DATAERR, "invalid tcpdata len %s", *av);
4712 			} else
4713 			    fill_cmd(cmd, O_TCPDATALEN, 0,
4714 				    strtoul(*av, NULL, 0));
4715 			av++;
4716 			break;
4717 
4718 		case TOK_TCPOPTS:
4719 			NEED1("missing argument for tcpoptions");
4720 			fill_flags_cmd(cmd, O_TCPOPTS, f_tcpopts, *av);
4721 			av++;
4722 			break;
4723 
4724 		case TOK_TCPSEQ:
4725 		case TOK_TCPACK:
4726 			NEED1("tcpseq/tcpack requires argument");
4727 			cmd->len = F_INSN_SIZE(ipfw_insn_u32);
4728 			cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
4729 			cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
4730 			av++;
4731 			break;
4732 
4733 		case TOK_TCPMSS:
4734 		case TOK_TCPWIN:
4735 			NEED1("tcpmss/tcpwin requires size");
4736 			if (strpbrk(*av, "-,")) {
4737 				if (add_ports(cmd, *av, 0,
4738 				    i == TOK_TCPWIN ? O_TCPWIN : O_TCPMSS,
4739 				    cblen) == NULL)
4740 					errx(EX_DATAERR, "invalid %s size %s",
4741 					    s, *av);
4742 			} else
4743 				fill_cmd(cmd, i == TOK_TCPWIN ? O_TCPWIN :
4744 				    O_TCPMSS, 0, strtoul(*av, NULL, 0));
4745 			av++;
4746 			break;
4747 
4748 		case TOK_TCPFLAGS:
4749 			NEED1("missing argument for tcpflags");
4750 			cmd->opcode = O_TCPFLAGS;
4751 			fill_flags_cmd(cmd, O_TCPFLAGS, f_tcpflags, *av);
4752 			av++;
4753 			break;
4754 
4755 		case TOK_KEEPSTATE:
4756 		case TOK_RECORDSTATE: {
4757 			uint16_t uidx;
4758 
4759 			if (open_par)
4760 				errx(EX_USAGE, "keep-state or record-state cannot be part "
4761 				    "of an or block");
4762 			if (have_state)
4763 				errx(EX_USAGE, "only one of keep-state, record-state, "
4764 					" limit and set-limit is allowed");
4765 			if (*av != NULL && *av[0] == ':') {
4766 				if (state_check_name(*av + 1) != 0)
4767 					errx(EX_DATAERR,
4768 					    "Invalid state name %s", *av);
4769 				uidx = pack_object(tstate, *av + 1,
4770 				    IPFW_TLV_STATE_NAME);
4771 				av++;
4772 			} else
4773 				uidx = pack_object(tstate, default_state_name,
4774 				    IPFW_TLV_STATE_NAME);
4775 			have_state = cmd;
4776 			have_rstate = i == TOK_RECORDSTATE;
4777 			fill_cmd(cmd, O_KEEP_STATE, 0, uidx);
4778 			break;
4779 		}
4780 
4781 		case TOK_LIMIT:
4782 		case TOK_SETLIMIT: {
4783 			ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
4784 			int val;
4785 
4786 			if (open_par)
4787 				errx(EX_USAGE,
4788 				    "limit or set-limit cannot be part of an or block");
4789 			if (have_state)
4790 				errx(EX_USAGE, "only one of keep-state, record-state, "
4791 					" limit and set-limit is allowed");
4792 			have_state = cmd;
4793 			have_rstate = i == TOK_SETLIMIT;
4794 
4795 			cmd->len = F_INSN_SIZE(ipfw_insn_limit);
4796 			CHECK_CMDLEN;
4797 			cmd->opcode = O_LIMIT;
4798 			c->limit_mask = c->conn_limit = 0;
4799 
4800 			while ( av[0] != NULL ) {
4801 				if ((val = match_token(limit_masks, *av)) <= 0)
4802 					break;
4803 				c->limit_mask |= val;
4804 				av++;
4805 			}
4806 
4807 			if (c->limit_mask == 0)
4808 				errx(EX_USAGE, "limit: missing limit mask");
4809 
4810 			GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
4811 			    TOK_LIMIT, rule_options);
4812 			av++;
4813 
4814 			if (*av != NULL && *av[0] == ':') {
4815 				if (state_check_name(*av + 1) != 0)
4816 					errx(EX_DATAERR,
4817 					    "Invalid state name %s", *av);
4818 				cmd->arg1 = pack_object(tstate, *av + 1,
4819 				    IPFW_TLV_STATE_NAME);
4820 				av++;
4821 			} else
4822 				cmd->arg1 = pack_object(tstate,
4823 				    default_state_name, IPFW_TLV_STATE_NAME);
4824 			break;
4825 		}
4826 
4827 		case TOK_PROTO:
4828 			NEED1("missing protocol");
4829 			if (add_proto(cmd, *av, &proto)) {
4830 				av++;
4831 			} else
4832 				errx(EX_DATAERR, "invalid protocol ``%s''",
4833 				    *av);
4834 			break;
4835 
4836 		case TOK_SRCIP:
4837 			NEED1("missing source IP");
4838 			if (add_srcip(cmd, *av, cblen, tstate)) {
4839 				av++;
4840 			}
4841 			break;
4842 
4843 		case TOK_DSTIP:
4844 			NEED1("missing destination IP");
4845 			if (add_dstip(cmd, *av, cblen, tstate)) {
4846 				av++;
4847 			}
4848 			break;
4849 
4850 		case TOK_SRCIP6:
4851 			NEED1("missing source IP6");
4852 			if (add_srcip6(cmd, *av, cblen, tstate)) {
4853 				av++;
4854 			}
4855 			break;
4856 
4857 		case TOK_DSTIP6:
4858 			NEED1("missing destination IP6");
4859 			if (add_dstip6(cmd, *av, cblen, tstate)) {
4860 				av++;
4861 			}
4862 			break;
4863 
4864 		case TOK_SRCPORT:
4865 			NEED1("missing source port");
4866 			if (_substrcmp(*av, "any") == 0 ||
4867 			    add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4868 				av++;
4869 			} else
4870 				errx(EX_DATAERR, "invalid source port %s", *av);
4871 			break;
4872 
4873 		case TOK_DSTPORT:
4874 			NEED1("missing destination port");
4875 			if (_substrcmp(*av, "any") == 0 ||
4876 			    add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4877 				av++;
4878 			} else
4879 				errx(EX_DATAERR, "invalid destination port %s",
4880 				    *av);
4881 			break;
4882 
4883 		case TOK_MAC:
4884 			if (add_mac(cmd, av, cblen))
4885 				av += 2;
4886 			break;
4887 
4888 		case TOK_MACTYPE:
4889 			NEED1("missing mac type");
4890 			if (!add_mactype(cmd, *av, cblen))
4891 				errx(EX_DATAERR, "invalid mac type %s", *av);
4892 			av++;
4893 			break;
4894 
4895 		case TOK_VERREVPATH:
4896 			fill_cmd(cmd, O_VERREVPATH, 0, 0);
4897 			break;
4898 
4899 		case TOK_VERSRCREACH:
4900 			fill_cmd(cmd, O_VERSRCREACH, 0, 0);
4901 			break;
4902 
4903 		case TOK_ANTISPOOF:
4904 			fill_cmd(cmd, O_ANTISPOOF, 0, 0);
4905 			break;
4906 
4907 		case TOK_IPSEC:
4908 			fill_cmd(cmd, O_IPSEC, 0, 0);
4909 			break;
4910 
4911 		case TOK_IPV6:
4912 			fill_cmd(cmd, O_IP6, 0, 0);
4913 			break;
4914 
4915 		case TOK_IPV4:
4916 			fill_cmd(cmd, O_IP4, 0, 0);
4917 			break;
4918 
4919 		case TOK_EXT6HDR:
4920 			fill_ext6hdr( cmd, *av );
4921 			av++;
4922 			break;
4923 
4924 		case TOK_FLOWID:
4925 			if (proto != IPPROTO_IPV6 )
4926 				errx( EX_USAGE, "flow-id filter is active "
4927 				    "only for ipv6 protocol\n");
4928 			fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
4929 			av++;
4930 			break;
4931 
4932 		case TOK_COMMENT:
4933 			fill_comment(cmd, av, cblen);
4934 			av[0]=NULL;
4935 			break;
4936 
4937 		case TOK_TAGGED:
4938 			if (av[0] && strpbrk(*av, "-,")) {
4939 				if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
4940 					errx(EX_DATAERR, "tagged: invalid tag"
4941 					    " list: %s", *av);
4942 			}
4943 			else {
4944 				uint16_t tag;
4945 
4946 				GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
4947 				    TOK_TAGGED, rule_options);
4948 				fill_cmd(cmd, O_TAGGED, 0, tag);
4949 			}
4950 			av++;
4951 			break;
4952 
4953 		case TOK_FIB:
4954 			NEED1("fib requires fib number");
4955 			fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
4956 			av++;
4957 			break;
4958 		case TOK_SOCKARG:
4959 			fill_cmd(cmd, O_SOCKARG, 0, 0);
4960 			break;
4961 
4962 		case TOK_LOOKUP: {
4963 			ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
4964 			int j;
4965 
4966 			if (!av[0] || !av[1])
4967 				errx(EX_USAGE, "format: lookup argument tablenum");
4968 			cmd->opcode = O_IP_DST_LOOKUP;
4969 			cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
4970 			i = match_token(rule_options, *av);
4971 			for (j = 0; lookup_key[j] >= 0 ; j++) {
4972 				if (i == lookup_key[j])
4973 					break;
4974 			}
4975 			if (lookup_key[j] <= 0)
4976 				errx(EX_USAGE, "format: cannot lookup on %s", *av);
4977 			__PAST_END(c->d, 1) = j; // i converted to option
4978 			av++;
4979 
4980 			if ((j = pack_table(tstate, *av)) == 0)
4981 				errx(EX_DATAERR, "Invalid table name: %s", *av);
4982 
4983 			cmd->arg1 = j;
4984 			av++;
4985 		    }
4986 			break;
4987 		case TOK_FLOW:
4988 			NEED1("missing table name");
4989 			if (strncmp(*av, "table(", 6) != 0)
4990 				errx(EX_DATAERR,
4991 				    "enclose table name into \"table()\"");
4992 			fill_table(cmd, *av, O_IP_FLOW_LOOKUP, tstate);
4993 			av++;
4994 			break;
4995 
4996 		case TOK_SKIPACTION:
4997 			if (have_skipcmd)
4998 				errx(EX_USAGE, "only one defer-action "
4999 					"is allowed");
5000 			have_skipcmd = cmd;
5001 			fill_cmd(cmd, O_SKIP_ACTION, 0, 0);
5002 			break;
5003 
5004 		default:
5005 			errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
5006 		}
5007 		if (F_LEN(cmd) > 0) {	/* prepare to advance */
5008 			prev = cmd;
5009 			cmd = next_cmd(cmd, &cblen);
5010 		}
5011 	}
5012 
5013 done:
5014 
5015 	if (!have_state && have_skipcmd)
5016 		warnx("Rule contains \"defer-immediate-action\" "
5017 			"and doesn't contain any state-related options.");
5018 
5019 	/*
5020 	 * Now copy stuff into the rule.
5021 	 * If we have a keep-state option, the first instruction
5022 	 * must be a PROBE_STATE (which is generated here).
5023 	 * If we have a LOG option, it was stored as the first command,
5024 	 * and now must be moved to the top of the action part.
5025 	 */
5026 	dst = (ipfw_insn *)rule->cmd;
5027 
5028 	/*
5029 	 * First thing to write into the command stream is the match probability.
5030 	 */
5031 	if (match_prob != 1) { /* 1 means always match */
5032 		dst->opcode = O_PROB;
5033 		dst->len = 2;
5034 		*((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
5035 		dst += dst->len;
5036 	}
5037 
5038 	/*
5039 	 * generate O_PROBE_STATE if necessary
5040 	 */
5041 	if (have_state && have_state->opcode != O_CHECK_STATE && !have_rstate) {
5042 		fill_cmd(dst, O_PROBE_STATE, 0, have_state->arg1);
5043 		dst = next_cmd(dst, &rblen);
5044 	}
5045 
5046 	/*
5047 	 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG,
5048 	 * O_SKIP_ACTION
5049 	 */
5050 	for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
5051 		i = F_LEN(src);
5052 		CHECK_RBUFLEN(i);
5053 
5054 		switch (src->opcode) {
5055 		case O_LOG:
5056 		case O_KEEP_STATE:
5057 		case O_LIMIT:
5058 		case O_ALTQ:
5059 		case O_TAG:
5060 		case O_SKIP_ACTION:
5061 			break;
5062 		default:
5063 			bcopy(src, dst, i * sizeof(uint32_t));
5064 			dst += i;
5065 		}
5066 	}
5067 
5068 	/*
5069 	 * put back the have_state command as last opcode
5070 	 */
5071 	if (have_state && have_state->opcode != O_CHECK_STATE) {
5072 		i = F_LEN(have_state);
5073 		CHECK_RBUFLEN(i);
5074 		bcopy(have_state, dst, i * sizeof(uint32_t));
5075 		dst += i;
5076 	}
5077 
5078 	/*
5079 	 * put back the have_skipcmd command as very last opcode
5080 	 */
5081 	if (have_skipcmd) {
5082 		i = F_LEN(have_skipcmd);
5083 		CHECK_RBUFLEN(i);
5084 		bcopy(have_skipcmd, dst, i * sizeof(uint32_t));
5085 		dst += i;
5086 	}
5087 
5088 	/*
5089 	 * start action section
5090 	 */
5091 	rule->act_ofs = dst - rule->cmd;
5092 
5093 	/* put back O_LOG, O_ALTQ, O_TAG if necessary */
5094 	if (have_log) {
5095 		i = F_LEN(have_log);
5096 		CHECK_RBUFLEN(i);
5097 		bcopy(have_log, dst, i * sizeof(uint32_t));
5098 		dst += i;
5099 	}
5100 	if (have_altq) {
5101 		i = F_LEN(have_altq);
5102 		CHECK_RBUFLEN(i);
5103 		bcopy(have_altq, dst, i * sizeof(uint32_t));
5104 		dst += i;
5105 	}
5106 	if (have_tag) {
5107 		i = F_LEN(have_tag);
5108 		CHECK_RBUFLEN(i);
5109 		bcopy(have_tag, dst, i * sizeof(uint32_t));
5110 		dst += i;
5111 	}
5112 
5113 	/*
5114 	 * copy all other actions
5115 	 */
5116 	for (src = (ipfw_insn *)actbuf; src != action; src += i) {
5117 		i = F_LEN(src);
5118 		CHECK_RBUFLEN(i);
5119 		bcopy(src, dst, i * sizeof(uint32_t));
5120 		dst += i;
5121 	}
5122 
5123 	rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
5124 	*rbufsize = (char *)dst - (char *)rule;
5125 }
5126 
5127 static int
5128 compare_ntlv(const void *_a, const void *_b)
5129 {
5130 	ipfw_obj_ntlv *a, *b;
5131 
5132 	a = (ipfw_obj_ntlv *)_a;
5133 	b = (ipfw_obj_ntlv *)_b;
5134 
5135 	if (a->set < b->set)
5136 		return (-1);
5137 	else if (a->set > b->set)
5138 		return (1);
5139 
5140 	if (a->idx < b->idx)
5141 		return (-1);
5142 	else if (a->idx > b->idx)
5143 		return (1);
5144 
5145 	if (a->head.type < b->head.type)
5146 		return (-1);
5147 	else if (a->head.type > b->head.type)
5148 		return (1);
5149 
5150 	return (0);
5151 }
5152 
5153 /*
5154  * Provide kernel with sorted list of referenced objects
5155  */
5156 static void
5157 object_sort_ctlv(ipfw_obj_ctlv *ctlv)
5158 {
5159 
5160 	qsort(ctlv + 1, ctlv->count, ctlv->objsize, compare_ntlv);
5161 }
5162 
5163 struct object_kt {
5164 	uint16_t	uidx;
5165 	uint16_t	type;
5166 };
5167 static int
5168 compare_object_kntlv(const void *k, const void *v)
5169 {
5170 	ipfw_obj_ntlv *ntlv;
5171 	struct object_kt key;
5172 
5173 	key = *((struct object_kt *)k);
5174 	ntlv = (ipfw_obj_ntlv *)v;
5175 
5176 	if (key.uidx < ntlv->idx)
5177 		return (-1);
5178 	else if (key.uidx > ntlv->idx)
5179 		return (1);
5180 
5181 	if (key.type < ntlv->head.type)
5182 		return (-1);
5183 	else if (key.type > ntlv->head.type)
5184 		return (1);
5185 
5186 	return (0);
5187 }
5188 
5189 /*
5190  * Finds object name in @ctlv by @idx and @type.
5191  * Uses the following facts:
5192  * 1) All TLVs are the same size
5193  * 2) Kernel implementation provides already sorted list.
5194  *
5195  * Returns table name or NULL.
5196  */
5197 static char *
5198 object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx, uint16_t type)
5199 {
5200 	ipfw_obj_ntlv *ntlv;
5201 	struct object_kt key;
5202 
5203 	key.uidx = idx;
5204 	key.type = type;
5205 
5206 	ntlv = bsearch(&key, (ctlv + 1), ctlv->count, ctlv->objsize,
5207 	    compare_object_kntlv);
5208 
5209 	if (ntlv != NULL)
5210 		return (ntlv->name);
5211 
5212 	return (NULL);
5213 }
5214 
5215 static char *
5216 table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx)
5217 {
5218 
5219 	return (object_search_ctlv(ctlv, idx, IPFW_TLV_TBL_NAME));
5220 }
5221 
5222 /*
5223  * Adds one or more rules to ipfw chain.
5224  * Data layout:
5225  * Request:
5226  * [
5227  *   ip_fw3_opheader
5228  *   [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
5229  *   [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ] (*2) (*3)
5230  * ]
5231  * Reply:
5232  * [
5233  *   ip_fw3_opheader
5234  *   [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
5235  *   [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ]
5236  * ]
5237  *
5238  * Rules in reply are modified to store their actual ruleset number.
5239  *
5240  * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
5241  * according to their idx field and there has to be no duplicates.
5242  * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
5243  * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
5244  */
5245 void
5246 ipfw_add(char *av[])
5247 {
5248 	uint32_t rulebuf[1024];
5249 	int rbufsize, default_off, tlen, rlen;
5250 	size_t sz;
5251 	struct tidx ts;
5252 	struct ip_fw_rule *rule;
5253 	caddr_t tbuf;
5254 	ip_fw3_opheader *op3;
5255 	ipfw_obj_ctlv *ctlv, *tstate;
5256 
5257 	rbufsize = sizeof(rulebuf);
5258 	memset(rulebuf, 0, rbufsize);
5259 	memset(&ts, 0, sizeof(ts));
5260 
5261 	/* Optimize case with no tables */
5262 	default_off = sizeof(ipfw_obj_ctlv) + sizeof(ip_fw3_opheader);
5263 	op3 = (ip_fw3_opheader *)rulebuf;
5264 	ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5265 	rule = (struct ip_fw_rule *)(ctlv + 1);
5266 	rbufsize -= default_off;
5267 
5268 	compile_rule(av, (uint32_t *)rule, &rbufsize, &ts);
5269 	/* Align rule size to u64 boundary */
5270 	rlen = roundup2(rbufsize, sizeof(uint64_t));
5271 
5272 	tbuf = NULL;
5273 	sz = 0;
5274 	tstate = NULL;
5275 	if (ts.count != 0) {
5276 		/* Some tables. We have to alloc more data */
5277 		tlen = ts.count * sizeof(ipfw_obj_ntlv);
5278 		sz = default_off + sizeof(ipfw_obj_ctlv) + tlen + rlen;
5279 
5280 		if ((tbuf = calloc(1, sz)) == NULL)
5281 			err(EX_UNAVAILABLE, "malloc() failed for IP_FW_ADD");
5282 		op3 = (ip_fw3_opheader *)tbuf;
5283 		/* Tables first */
5284 		ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5285 		ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
5286 		ctlv->head.length = sizeof(ipfw_obj_ctlv) + tlen;
5287 		ctlv->count = ts.count;
5288 		ctlv->objsize = sizeof(ipfw_obj_ntlv);
5289 		memcpy(ctlv + 1, ts.idx, tlen);
5290 		object_sort_ctlv(ctlv);
5291 		tstate = ctlv;
5292 		/* Rule next */
5293 		ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
5294 		ctlv->head.type = IPFW_TLV_RULE_LIST;
5295 		ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5296 		ctlv->count = 1;
5297 		memcpy(ctlv + 1, rule, rbufsize);
5298 	} else {
5299 		/* Simply add header */
5300 		sz = rlen + default_off;
5301 		memset(ctlv, 0, sizeof(*ctlv));
5302 		ctlv->head.type = IPFW_TLV_RULE_LIST;
5303 		ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5304 		ctlv->count = 1;
5305 	}
5306 
5307 	if (do_get3(IP_FW_XADD, op3, &sz) != 0)
5308 		err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_XADD");
5309 
5310 	if (!co.do_quiet) {
5311 		struct format_opts sfo;
5312 		struct buf_pr bp;
5313 		memset(&sfo, 0, sizeof(sfo));
5314 		sfo.tstate = tstate;
5315 		sfo.set_mask = (uint32_t)(-1);
5316 		bp_alloc(&bp, 4096);
5317 		show_static_rule(&co, &sfo, &bp, rule, NULL);
5318 		printf("%s", bp.buf);
5319 		bp_free(&bp);
5320 	}
5321 
5322 	if (tbuf != NULL)
5323 		free(tbuf);
5324 
5325 	if (ts.idx != NULL)
5326 		free(ts.idx);
5327 }
5328 
5329 /*
5330  * clear the counters or the log counters.
5331  * optname has the following values:
5332  *  0 (zero both counters and logging)
5333  *  1 (zero logging only)
5334  */
5335 void
5336 ipfw_zero(int ac, char *av[], int optname)
5337 {
5338 	ipfw_range_tlv rt;
5339 	char const *errstr;
5340 	char const *name = optname ? "RESETLOG" : "ZERO";
5341 	uint32_t arg;
5342 	int failed = EX_OK;
5343 
5344 	optname = optname ? IP_FW_XRESETLOG : IP_FW_XZERO;
5345 	av++; ac--;
5346 
5347 	if (ac == 0) {
5348 		/* clear all entries */
5349 		memset(&rt, 0, sizeof(rt));
5350 		rt.flags = IPFW_RCFLAG_ALL;
5351 		if (do_range_cmd(optname, &rt) < 0)
5352 			err(EX_UNAVAILABLE, "setsockopt(IP_FW_X%s)", name);
5353 		if (!co.do_quiet)
5354 			printf("%s.\n", optname == IP_FW_XZERO ?
5355 			    "Accounting cleared":"Logging counts reset");
5356 
5357 		return;
5358 	}
5359 
5360 	while (ac) {
5361 		/* Rule number */
5362 		if (isdigit(**av)) {
5363 			arg = strtonum(*av, 0, 0xffff, &errstr);
5364 			if (errstr)
5365 				errx(EX_DATAERR,
5366 				    "invalid rule number %s\n", *av);
5367 			memset(&rt, 0, sizeof(rt));
5368 			rt.start_rule = arg;
5369 			rt.end_rule = arg;
5370 			rt.flags |= IPFW_RCFLAG_RANGE;
5371 			if (co.use_set != 0) {
5372 				rt.set = co.use_set - 1;
5373 				rt.flags |= IPFW_RCFLAG_SET;
5374 			}
5375 			if (do_range_cmd(optname, &rt) != 0) {
5376 				warn("rule %u: setsockopt(IP_FW_X%s)",
5377 				    arg, name);
5378 				failed = EX_UNAVAILABLE;
5379 			} else if (rt.new_set == 0) {
5380 				printf("Entry %d not found\n", arg);
5381 				failed = EX_UNAVAILABLE;
5382 			} else if (!co.do_quiet)
5383 				printf("Entry %d %s.\n", arg,
5384 				    optname == IP_FW_XZERO ?
5385 					"cleared" : "logging count reset");
5386 		} else {
5387 			errx(EX_USAGE, "invalid rule number ``%s''", *av);
5388 		}
5389 		av++; ac--;
5390 	}
5391 	if (failed != EX_OK)
5392 		exit(failed);
5393 }
5394 
5395 void
5396 ipfw_flush(int force)
5397 {
5398 	ipfw_range_tlv rt;
5399 
5400 	if (!force && !co.do_quiet) { /* need to ask user */
5401 		int c;
5402 
5403 		printf("Are you sure? [yn] ");
5404 		fflush(stdout);
5405 		do {
5406 			c = toupper(getc(stdin));
5407 			while (c != '\n' && getc(stdin) != '\n')
5408 				if (feof(stdin))
5409 					return; /* and do not flush */
5410 		} while (c != 'Y' && c != 'N');
5411 		printf("\n");
5412 		if (c == 'N')	/* user said no */
5413 			return;
5414 	}
5415 	if (co.do_pipe) {
5416 		dummynet_flush();
5417 		return;
5418 	}
5419 	/* `ipfw set N flush` - is the same that `ipfw delete set N` */
5420 	memset(&rt, 0, sizeof(rt));
5421 	if (co.use_set != 0) {
5422 		rt.set = co.use_set - 1;
5423 		rt.flags = IPFW_RCFLAG_SET;
5424 	} else
5425 		rt.flags = IPFW_RCFLAG_ALL;
5426 	if (do_range_cmd(IP_FW_XDEL, &rt) != 0)
5427 			err(EX_UNAVAILABLE, "setsockopt(IP_FW_XDEL)");
5428 	if (!co.do_quiet)
5429 		printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
5430 }
5431 
5432 static struct _s_x intcmds[] = {
5433       { "talist",	TOK_TALIST },
5434       { "iflist",	TOK_IFLIST },
5435       { "olist",	TOK_OLIST },
5436       { "vlist",	TOK_VLIST },
5437       { NULL, 0 }
5438 };
5439 
5440 static struct _s_x otypes[] = {
5441 	{ "EACTION",	IPFW_TLV_EACTION },
5442 	{ "DYNSTATE",	IPFW_TLV_STATE_NAME },
5443 	{ NULL, 0 }
5444 };
5445 
5446 static const char*
5447 lookup_eaction_name(ipfw_obj_ntlv *ntlv, int cnt, uint16_t type)
5448 {
5449 	const char *name;
5450 	int i;
5451 
5452 	name = NULL;
5453 	for (i = 0; i < cnt; i++) {
5454 		if (ntlv[i].head.type != IPFW_TLV_EACTION)
5455 			continue;
5456 		if (IPFW_TLV_EACTION_NAME(ntlv[i].idx) != type)
5457 			continue;
5458 		name = ntlv[i].name;
5459 		break;
5460 	}
5461 	return (name);
5462 }
5463 
5464 static void
5465 ipfw_list_objects(int ac, char *av[])
5466 {
5467 	ipfw_obj_lheader req, *olh;
5468 	ipfw_obj_ntlv *ntlv;
5469 	const char *name;
5470 	size_t sz;
5471 	int i;
5472 
5473 	memset(&req, 0, sizeof(req));
5474 	sz = sizeof(req);
5475 	if (do_get3(IP_FW_DUMP_SRVOBJECTS, &req.opheader, &sz) != 0)
5476 		if (errno != ENOMEM)
5477 			return;
5478 
5479 	sz = req.size;
5480 	if ((olh = calloc(1, sz)) == NULL)
5481 		return;
5482 
5483 	olh->size = sz;
5484 	if (do_get3(IP_FW_DUMP_SRVOBJECTS, &olh->opheader, &sz) != 0) {
5485 		free(olh);
5486 		return;
5487 	}
5488 
5489 	if (olh->count > 0)
5490 		printf("Objects list:\n");
5491 	else
5492 		printf("There are no objects\n");
5493 	ntlv = (ipfw_obj_ntlv *)(olh + 1);
5494 	for (i = 0; i < olh->count; i++) {
5495 		name = match_value(otypes, ntlv->head.type);
5496 		if (name == NULL)
5497 			name = lookup_eaction_name(
5498 			    (ipfw_obj_ntlv *)(olh + 1), olh->count,
5499 			    ntlv->head.type);
5500 		if (name == NULL)
5501 			printf(" kidx: %4d\ttype: %10d\tname: %s\n",
5502 			    ntlv->idx, ntlv->head.type, ntlv->name);
5503 		else
5504 			printf(" kidx: %4d\ttype: %10s\tname: %s\n",
5505 			    ntlv->idx, name, ntlv->name);
5506 		ntlv++;
5507 	}
5508 	free(olh);
5509 }
5510 
5511 void
5512 ipfw_internal_handler(int ac, char *av[])
5513 {
5514 	int tcmd;
5515 
5516 	ac--; av++;
5517 	NEED1("internal cmd required");
5518 
5519 	if ((tcmd = match_token(intcmds, *av)) == -1)
5520 		errx(EX_USAGE, "invalid internal sub-cmd: %s", *av);
5521 
5522 	switch (tcmd) {
5523 	case TOK_IFLIST:
5524 		ipfw_list_tifaces();
5525 		break;
5526 	case TOK_TALIST:
5527 		ipfw_list_ta(ac, av);
5528 		break;
5529 	case TOK_OLIST:
5530 		ipfw_list_objects(ac, av);
5531 		break;
5532 	case TOK_VLIST:
5533 		ipfw_list_values(ac, av);
5534 		break;
5535 	}
5536 }
5537 
5538 static int
5539 ipfw_get_tracked_ifaces(ipfw_obj_lheader **polh)
5540 {
5541 	ipfw_obj_lheader req, *olh;
5542 	size_t sz;
5543 
5544 	memset(&req, 0, sizeof(req));
5545 	sz = sizeof(req);
5546 
5547 	if (do_get3(IP_FW_XIFLIST, &req.opheader, &sz) != 0) {
5548 		if (errno != ENOMEM)
5549 			return (errno);
5550 	}
5551 
5552 	sz = req.size;
5553 	if ((olh = calloc(1, sz)) == NULL)
5554 		return (ENOMEM);
5555 
5556 	olh->size = sz;
5557 	if (do_get3(IP_FW_XIFLIST, &olh->opheader, &sz) != 0) {
5558 		free(olh);
5559 		return (errno);
5560 	}
5561 
5562 	*polh = olh;
5563 	return (0);
5564 }
5565 
5566 static int
5567 ifinfo_cmp(const void *a, const void *b)
5568 {
5569 	ipfw_iface_info *ia, *ib;
5570 
5571 	ia = (ipfw_iface_info *)a;
5572 	ib = (ipfw_iface_info *)b;
5573 
5574 	return (stringnum_cmp(ia->ifname, ib->ifname));
5575 }
5576 
5577 /*
5578  * Retrieves table list from kernel,
5579  * optionally sorts it and calls requested function for each table.
5580  * Returns 0 on success.
5581  */
5582 static void
5583 ipfw_list_tifaces()
5584 {
5585 	ipfw_obj_lheader *olh;
5586 	ipfw_iface_info *info;
5587 	int i, error;
5588 
5589 	if ((error = ipfw_get_tracked_ifaces(&olh)) != 0)
5590 		err(EX_OSERR, "Unable to request ipfw tracked interface list");
5591 
5592 
5593 	qsort(olh + 1, olh->count, olh->objsize, ifinfo_cmp);
5594 
5595 	info = (ipfw_iface_info *)(olh + 1);
5596 	for (i = 0; i < olh->count; i++) {
5597 		if (info->flags & IPFW_IFFLAG_RESOLVED)
5598 			printf("%s ifindex: %d refcount: %u changes: %u\n",
5599 			    info->ifname, info->ifindex, info->refcnt,
5600 			    info->gencnt);
5601 		else
5602 			printf("%s ifindex: unresolved refcount: %u changes: %u\n",
5603 			    info->ifname, info->refcnt, info->gencnt);
5604 		info = (ipfw_iface_info *)((caddr_t)info + olh->objsize);
5605 	}
5606 
5607 	free(olh);
5608 }
5609 
5610 
5611 
5612 
5613