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