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