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