xref: /freebsd/sbin/ipfw/ipfw2.c (revision 2a3e3873a1e4cd958f2b0f85d3b10cfa40575d30)
1 /*
2  * Copyright (c) 2002-2003 Luigi Rizzo
3  * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
4  * Copyright (c) 1994 Ugen J.S.Antsilevich
5  *
6  * Idea and grammar partially left from:
7  * Copyright (c) 1993 Daniel Boulet
8  *
9  * Redistribution and use in source forms, with and without modification,
10  * are permitted provided that this entire comment appears intact.
11  *
12  * Redistribution in binary form may occur without any restrictions.
13  * Obviously, it would be nice if you gave credit where credit is due
14  * but requiring it would be too onerous.
15  *
16  * This software is provided ``AS IS'' without any warranties of any kind.
17  *
18  * NEW command line interface for IP firewall facility
19  *
20  * $FreeBSD$
21  */
22 
23 #include <sys/types.h>
24 #include <sys/param.h>
25 #include <sys/socket.h>
26 #include <sys/sockio.h>
27 #include <sys/sysctl.h>
28 
29 #include "ipfw2.h"
30 
31 #include <ctype.h>
32 #include <err.h>
33 #include <errno.h>
34 #include <grp.h>
35 #include <netdb.h>
36 #include <pwd.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <sysexits.h>
41 #include <time.h>	/* ctime */
42 #include <timeconv.h>	/* _long_to_time */
43 #include <unistd.h>
44 #include <fcntl.h>
45 #include <stddef.h>	/* offsetof */
46 
47 #include <net/ethernet.h>
48 #include <net/if.h>		/* only IFNAMSIZ */
49 #include <netinet/in.h>
50 #include <netinet/in_systm.h>	/* only n_short, n_long */
51 #include <netinet/ip.h>
52 #include <netinet/ip_icmp.h>
53 #include <netinet/ip_fw.h>
54 #include <netinet/tcp.h>
55 #include <arpa/inet.h>
56 
57 struct cmdline_opts co;	/* global options */
58 
59 int resvd_set_number = RESVD_SET;
60 
61 int ipfw_socket = -1;
62 
63 #ifndef s6_addr32
64 #define s6_addr32 __u6_addr.__u6_addr32
65 #endif
66 
67 #define	CHECK_LENGTH(v, len) do {				\
68 	if ((v) < (len))					\
69 		errx(EX_DATAERR, "Rule too long");		\
70 	} while (0)
71 /*
72  * Check if we have enough space in cmd buffer. Note that since
73  * first 8? u32 words are reserved by reserved header, full cmd
74  * buffer can't be used, so we need to protect from buffer overrun
75  * only. At the beginnig, cblen is less than actual buffer size by
76  * size of ipfw_insn_u32 instruction + 1 u32 work. This eliminates need
77  * for checking small instructions fitting in given range.
78  * We also (ab)use the fact that ipfw_insn is always the first field
79  * for any custom instruction.
80  */
81 #define	CHECK_CMDLEN	CHECK_LENGTH(cblen, F_LEN((ipfw_insn *)cmd))
82 
83 #define GET_UINT_ARG(arg, min, max, tok, s_x) do {			\
84 	if (!av[0])							\
85 		errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
86 	if (_substrcmp(*av, "tablearg") == 0) {				\
87 		arg = IP_FW_TABLEARG;					\
88 		break;							\
89 	}								\
90 									\
91 	{								\
92 	long _xval;							\
93 	char *end;							\
94 									\
95 	_xval = strtol(*av, &end, 10);					\
96 									\
97 	if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
98 		errx(EX_DATAERR, "%s: invalid argument: %s",		\
99 		    match_value(s_x, tok), *av);			\
100 									\
101 	if (errno == ERANGE || _xval < min || _xval > max)		\
102 		errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
103 		    match_value(s_x, tok), min, max, *av);		\
104 									\
105 	if (_xval == IP_FW_TABLEARG)					\
106 		errx(EX_DATAERR, "%s: illegal argument value: %s",	\
107 		    match_value(s_x, tok), *av);			\
108 	arg = _xval;							\
109 	}								\
110 } while (0)
111 
112 static void
113 PRINT_UINT_ARG(const char *str, uint32_t arg)
114 {
115 	if (str != NULL)
116 		printf("%s",str);
117 	if (arg == IP_FW_TABLEARG)
118 		printf("tablearg");
119 	else
120 		printf("%u", arg);
121 }
122 
123 static struct _s_x f_tcpflags[] = {
124 	{ "syn", TH_SYN },
125 	{ "fin", TH_FIN },
126 	{ "ack", TH_ACK },
127 	{ "psh", TH_PUSH },
128 	{ "rst", TH_RST },
129 	{ "urg", TH_URG },
130 	{ "tcp flag", 0 },
131 	{ NULL,	0 }
132 };
133 
134 static struct _s_x f_tcpopts[] = {
135 	{ "mss",	IP_FW_TCPOPT_MSS },
136 	{ "maxseg",	IP_FW_TCPOPT_MSS },
137 	{ "window",	IP_FW_TCPOPT_WINDOW },
138 	{ "sack",	IP_FW_TCPOPT_SACK },
139 	{ "ts",		IP_FW_TCPOPT_TS },
140 	{ "timestamp",	IP_FW_TCPOPT_TS },
141 	{ "cc",		IP_FW_TCPOPT_CC },
142 	{ "tcp option",	0 },
143 	{ NULL,	0 }
144 };
145 
146 /*
147  * IP options span the range 0 to 255 so we need to remap them
148  * (though in fact only the low 5 bits are significant).
149  */
150 static struct _s_x f_ipopts[] = {
151 	{ "ssrr",	IP_FW_IPOPT_SSRR},
152 	{ "lsrr",	IP_FW_IPOPT_LSRR},
153 	{ "rr",		IP_FW_IPOPT_RR},
154 	{ "ts",		IP_FW_IPOPT_TS},
155 	{ "ip option",	0 },
156 	{ NULL,	0 }
157 };
158 
159 static struct _s_x f_iptos[] = {
160 	{ "lowdelay",	IPTOS_LOWDELAY},
161 	{ "throughput",	IPTOS_THROUGHPUT},
162 	{ "reliability", IPTOS_RELIABILITY},
163 	{ "mincost",	IPTOS_MINCOST},
164 	{ "congestion",	IPTOS_ECN_CE},
165 	{ "ecntransport", IPTOS_ECN_ECT0},
166 	{ "ip tos option", 0},
167 	{ NULL,	0 }
168 };
169 
170 static struct _s_x f_ipdscp[] = {
171 	{ "af11", IPTOS_DSCP_AF11 >> 2 },	/* 001010 */
172 	{ "af12", IPTOS_DSCP_AF12 >> 2 },	/* 001100 */
173 	{ "af13", IPTOS_DSCP_AF13 >> 2 },	/* 001110 */
174 	{ "af21", IPTOS_DSCP_AF21 >> 2 },	/* 010010 */
175 	{ "af22", IPTOS_DSCP_AF22 >> 2 },	/* 010100 */
176 	{ "af23", IPTOS_DSCP_AF23 >> 2 },	/* 010110 */
177 	{ "af31", IPTOS_DSCP_AF31 >> 2 },	/* 011010 */
178 	{ "af32", IPTOS_DSCP_AF32 >> 2 },	/* 011100 */
179 	{ "af33", IPTOS_DSCP_AF33 >> 2 },	/* 011110 */
180 	{ "af41", IPTOS_DSCP_AF41 >> 2 },	/* 100010 */
181 	{ "af42", IPTOS_DSCP_AF42 >> 2 },	/* 100100 */
182 	{ "af43", IPTOS_DSCP_AF43 >> 2 },	/* 100110 */
183 	{ "be", IPTOS_DSCP_CS0 >> 2 }, 	/* 000000 */
184 	{ "ef", IPTOS_DSCP_EF >> 2 },	/* 101110 */
185 	{ "cs0", IPTOS_DSCP_CS0 >> 2 },	/* 000000 */
186 	{ "cs1", IPTOS_DSCP_CS1 >> 2 },	/* 001000 */
187 	{ "cs2", IPTOS_DSCP_CS2 >> 2 },	/* 010000 */
188 	{ "cs3", IPTOS_DSCP_CS3 >> 2 },	/* 011000 */
189 	{ "cs4", IPTOS_DSCP_CS4 >> 2 },	/* 100000 */
190 	{ "cs5", IPTOS_DSCP_CS5 >> 2 },	/* 101000 */
191 	{ "cs6", IPTOS_DSCP_CS6 >> 2 },	/* 110000 */
192 	{ "cs7", IPTOS_DSCP_CS7 >> 2 },	/* 100000 */
193 	{ NULL, 0 }
194 };
195 
196 static struct _s_x limit_masks[] = {
197 	{"all",		DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
198 	{"src-addr",	DYN_SRC_ADDR},
199 	{"src-port",	DYN_SRC_PORT},
200 	{"dst-addr",	DYN_DST_ADDR},
201 	{"dst-port",	DYN_DST_PORT},
202 	{NULL,		0}
203 };
204 
205 /*
206  * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
207  * This is only used in this code.
208  */
209 #define IPPROTO_ETHERTYPE	0x1000
210 static struct _s_x ether_types[] = {
211     /*
212      * Note, we cannot use "-:&/" in the names because they are field
213      * separators in the type specifications. Also, we use s = NULL as
214      * end-delimiter, because a type of 0 can be legal.
215      */
216 	{ "ip",		0x0800 },
217 	{ "ipv4",	0x0800 },
218 	{ "ipv6",	0x86dd },
219 	{ "arp",	0x0806 },
220 	{ "rarp",	0x8035 },
221 	{ "vlan",	0x8100 },
222 	{ "loop",	0x9000 },
223 	{ "trail",	0x1000 },
224 	{ "at",		0x809b },
225 	{ "atalk",	0x809b },
226 	{ "aarp",	0x80f3 },
227 	{ "pppoe_disc",	0x8863 },
228 	{ "pppoe_sess",	0x8864 },
229 	{ "ipx_8022",	0x00E0 },
230 	{ "ipx_8023",	0x0000 },
231 	{ "ipx_ii",	0x8137 },
232 	{ "ipx_snap",	0x8137 },
233 	{ "ipx",	0x8137 },
234 	{ "ns",		0x0600 },
235 	{ NULL,		0 }
236 };
237 
238 
239 static struct _s_x rule_actions[] = {
240 	{ "accept",		TOK_ACCEPT },
241 	{ "pass",		TOK_ACCEPT },
242 	{ "allow",		TOK_ACCEPT },
243 	{ "permit",		TOK_ACCEPT },
244 	{ "count",		TOK_COUNT },
245 	{ "pipe",		TOK_PIPE },
246 	{ "queue",		TOK_QUEUE },
247 	{ "divert",		TOK_DIVERT },
248 	{ "tee",		TOK_TEE },
249 	{ "netgraph",		TOK_NETGRAPH },
250 	{ "ngtee",		TOK_NGTEE },
251 	{ "fwd",		TOK_FORWARD },
252 	{ "forward",		TOK_FORWARD },
253 	{ "skipto",		TOK_SKIPTO },
254 	{ "deny",		TOK_DENY },
255 	{ "drop",		TOK_DENY },
256 	{ "reject",		TOK_REJECT },
257 	{ "reset6",		TOK_RESET6 },
258 	{ "reset",		TOK_RESET },
259 	{ "unreach6",		TOK_UNREACH6 },
260 	{ "unreach",		TOK_UNREACH },
261 	{ "check-state",	TOK_CHECKSTATE },
262 	{ "//",			TOK_COMMENT },
263 	{ "nat",		TOK_NAT },
264 	{ "reass",		TOK_REASS },
265 	{ "setfib",		TOK_SETFIB },
266 	{ "setdscp",		TOK_SETDSCP },
267 	{ "call",		TOK_CALL },
268 	{ "return",		TOK_RETURN },
269 	{ NULL, 0 }	/* terminator */
270 };
271 
272 static struct _s_x rule_action_params[] = {
273 	{ "altq",		TOK_ALTQ },
274 	{ "log",		TOK_LOG },
275 	{ "tag",		TOK_TAG },
276 	{ "untag",		TOK_UNTAG },
277 	{ NULL, 0 }	/* terminator */
278 };
279 
280 /*
281  * The 'lookup' instruction accepts one of the following arguments.
282  * -1 is a terminator for the list.
283  * Arguments are passed as v[1] in O_DST_LOOKUP options.
284  */
285 static int lookup_key[] = {
286 	TOK_DSTIP, TOK_SRCIP, TOK_DSTPORT, TOK_SRCPORT,
287 	TOK_UID, TOK_JAIL, TOK_DSCP, -1 };
288 
289 static struct _s_x rule_options[] = {
290 	{ "tagged",		TOK_TAGGED },
291 	{ "uid",		TOK_UID },
292 	{ "gid",		TOK_GID },
293 	{ "jail",		TOK_JAIL },
294 	{ "in",			TOK_IN },
295 	{ "limit",		TOK_LIMIT },
296 	{ "keep-state",		TOK_KEEPSTATE },
297 	{ "bridged",		TOK_LAYER2 },
298 	{ "layer2",		TOK_LAYER2 },
299 	{ "out",		TOK_OUT },
300 	{ "diverted",		TOK_DIVERTED },
301 	{ "diverted-loopback",	TOK_DIVERTEDLOOPBACK },
302 	{ "diverted-output",	TOK_DIVERTEDOUTPUT },
303 	{ "xmit",		TOK_XMIT },
304 	{ "recv",		TOK_RECV },
305 	{ "via",		TOK_VIA },
306 	{ "fragment",		TOK_FRAG },
307 	{ "frag",		TOK_FRAG },
308 	{ "fib",		TOK_FIB },
309 	{ "ipoptions",		TOK_IPOPTS },
310 	{ "ipopts",		TOK_IPOPTS },
311 	{ "iplen",		TOK_IPLEN },
312 	{ "ipid",		TOK_IPID },
313 	{ "ipprecedence",	TOK_IPPRECEDENCE },
314 	{ "dscp",		TOK_DSCP },
315 	{ "iptos",		TOK_IPTOS },
316 	{ "ipttl",		TOK_IPTTL },
317 	{ "ipversion",		TOK_IPVER },
318 	{ "ipver",		TOK_IPVER },
319 	{ "estab",		TOK_ESTAB },
320 	{ "established",	TOK_ESTAB },
321 	{ "setup",		TOK_SETUP },
322 	{ "sockarg",		TOK_SOCKARG },
323 	{ "tcpdatalen",		TOK_TCPDATALEN },
324 	{ "tcpflags",		TOK_TCPFLAGS },
325 	{ "tcpflgs",		TOK_TCPFLAGS },
326 	{ "tcpoptions",		TOK_TCPOPTS },
327 	{ "tcpopts",		TOK_TCPOPTS },
328 	{ "tcpseq",		TOK_TCPSEQ },
329 	{ "tcpack",		TOK_TCPACK },
330 	{ "tcpwin",		TOK_TCPWIN },
331 	{ "icmptype",		TOK_ICMPTYPES },
332 	{ "icmptypes",		TOK_ICMPTYPES },
333 	{ "dst-ip",		TOK_DSTIP },
334 	{ "src-ip",		TOK_SRCIP },
335 	{ "dst-port",		TOK_DSTPORT },
336 	{ "src-port",		TOK_SRCPORT },
337 	{ "proto",		TOK_PROTO },
338 	{ "MAC",		TOK_MAC },
339 	{ "mac",		TOK_MAC },
340 	{ "mac-type",		TOK_MACTYPE },
341 	{ "verrevpath",		TOK_VERREVPATH },
342 	{ "versrcreach",	TOK_VERSRCREACH },
343 	{ "antispoof",		TOK_ANTISPOOF },
344 	{ "ipsec",		TOK_IPSEC },
345 	{ "icmp6type",		TOK_ICMP6TYPES },
346 	{ "icmp6types",		TOK_ICMP6TYPES },
347 	{ "ext6hdr",		TOK_EXT6HDR},
348 	{ "flow-id",		TOK_FLOWID},
349 	{ "ipv6",		TOK_IPV6},
350 	{ "ip6",		TOK_IPV6},
351 	{ "ipv4",		TOK_IPV4},
352 	{ "ip4",		TOK_IPV4},
353 	{ "dst-ipv6",		TOK_DSTIP6},
354 	{ "dst-ip6",		TOK_DSTIP6},
355 	{ "src-ipv6",		TOK_SRCIP6},
356 	{ "src-ip6",		TOK_SRCIP6},
357 	{ "lookup",		TOK_LOOKUP},
358 	{ "//",			TOK_COMMENT },
359 
360 	{ "not",		TOK_NOT },		/* pseudo option */
361 	{ "!", /* escape ? */	TOK_NOT },		/* pseudo option */
362 	{ "or",			TOK_OR },		/* pseudo option */
363 	{ "|", /* escape */	TOK_OR },		/* pseudo option */
364 	{ "{",			TOK_STARTBRACE },	/* pseudo option */
365 	{ "(",			TOK_STARTBRACE },	/* pseudo option */
366 	{ "}",			TOK_ENDBRACE },		/* pseudo option */
367 	{ ")",			TOK_ENDBRACE },		/* pseudo option */
368 	{ NULL, 0 }	/* terminator */
369 };
370 
371 /*
372  * Helper routine to print a possibly unaligned uint64_t on
373  * various platform. If width > 0, print the value with
374  * the desired width, followed by a space;
375  * otherwise, return the required width.
376  */
377 int
378 pr_u64(uint64_t *pd, int width)
379 {
380 #ifdef TCC
381 #define U64_FMT "I64"
382 #else
383 #define U64_FMT "llu"
384 #endif
385 	uint64_t u;
386 	unsigned long long d;
387 
388 	bcopy (pd, &u, sizeof(u));
389 	d = u;
390 	return (width > 0) ?
391 		printf("%*" U64_FMT " ", width, d) :
392 		snprintf(NULL, 0, "%" U64_FMT, d) ;
393 #undef U64_FMT
394 }
395 
396 void *
397 safe_calloc(size_t number, size_t size)
398 {
399 	void *ret = calloc(number, size);
400 
401 	if (ret == NULL)
402 		err(EX_OSERR, "calloc");
403 	return ret;
404 }
405 
406 void *
407 safe_realloc(void *ptr, size_t size)
408 {
409 	void *ret = realloc(ptr, size);
410 
411 	if (ret == NULL)
412 		err(EX_OSERR, "realloc");
413 	return ret;
414 }
415 
416 /*
417  * conditionally runs the command.
418  * Selected options or negative -> getsockopt
419  */
420 int
421 do_cmd(int optname, void *optval, uintptr_t optlen)
422 {
423 	int i;
424 
425 	if (co.test_only)
426 		return 0;
427 
428 	if (ipfw_socket == -1)
429 		ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
430 	if (ipfw_socket < 0)
431 		err(EX_UNAVAILABLE, "socket");
432 
433 	if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
434 	    optname == IP_FW_ADD || optname == IP_FW3 ||
435 	    optname == IP_FW_NAT_GET_CONFIG ||
436 	    optname < 0 ||
437 	    optname == IP_FW_NAT_GET_LOG) {
438 		if (optname < 0)
439 			optname = -optname;
440 		i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
441 			(socklen_t *)optlen);
442 	} else {
443 		i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
444 	}
445 	return i;
446 }
447 
448 /*
449  * do_setcmd3 - pass ipfw control cmd to kernel
450  * @optname: option name
451  * @optval: pointer to option data
452  * @optlen: option length
453  *
454  * Function encapsulates option value in IP_FW3 socket option
455  * and calls setsockopt().
456  * Function returns 0 on success or -1 otherwise.
457  */
458 static int
459 do_setcmd3(int optname, void *optval, socklen_t optlen)
460 {
461 	socklen_t len;
462 	ip_fw3_opheader *op3;
463 
464 	if (co.test_only)
465 		return (0);
466 
467 	if (ipfw_socket == -1)
468 		ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
469 	if (ipfw_socket < 0)
470 		err(EX_UNAVAILABLE, "socket");
471 
472 	len = sizeof(ip_fw3_opheader) + optlen;
473 	op3 = alloca(len);
474 	/* Zero reserved fields */
475 	memset(op3, 0, sizeof(ip_fw3_opheader));
476 	memcpy(op3 + 1, optval, optlen);
477 	op3->opcode = optname;
478 
479 	return setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, len);
480 }
481 
482 /**
483  * match_token takes a table and a string, returns the value associated
484  * with the string (-1 in case of failure).
485  */
486 int
487 match_token(struct _s_x *table, char *string)
488 {
489 	struct _s_x *pt;
490 	uint i = strlen(string);
491 
492 	for (pt = table ; i && pt->s != NULL ; pt++)
493 		if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
494 			return pt->x;
495 	return -1;
496 }
497 
498 /**
499  * match_value takes a table and a value, returns the string associated
500  * with the value (NULL in case of failure).
501  */
502 char const *
503 match_value(struct _s_x *p, int value)
504 {
505 	for (; p->s != NULL; p++)
506 		if (p->x == value)
507 			return p->s;
508 	return NULL;
509 }
510 
511 /*
512  * _substrcmp takes two strings and returns 1 if they do not match,
513  * and 0 if they match exactly or the first string is a sub-string
514  * of the second.  A warning is printed to stderr in the case that the
515  * first string is a sub-string of the second.
516  *
517  * This function will be removed in the future through the usual
518  * deprecation process.
519  */
520 int
521 _substrcmp(const char *str1, const char* str2)
522 {
523 
524 	if (strncmp(str1, str2, strlen(str1)) != 0)
525 		return 1;
526 
527 	if (strlen(str1) != strlen(str2))
528 		warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
529 		    str1, str2);
530 	return 0;
531 }
532 
533 /*
534  * _substrcmp2 takes three strings and returns 1 if the first two do not match,
535  * and 0 if they match exactly or the second string is a sub-string
536  * of the first.  A warning is printed to stderr in the case that the
537  * first string does not match the third.
538  *
539  * This function exists to warn about the bizarre construction
540  * strncmp(str, "by", 2) which is used to allow people to use a shortcut
541  * for "bytes".  The problem is that in addition to accepting "by",
542  * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
543  * other string beginning with "by".
544  *
545  * This function will be removed in the future through the usual
546  * deprecation process.
547  */
548 int
549 _substrcmp2(const char *str1, const char* str2, const char* str3)
550 {
551 
552 	if (strncmp(str1, str2, strlen(str2)) != 0)
553 		return 1;
554 
555 	if (strcmp(str1, str3) != 0)
556 		warnx("DEPRECATED: '%s' matched '%s'",
557 		    str1, str3);
558 	return 0;
559 }
560 
561 /*
562  * prints one port, symbolic or numeric
563  */
564 static void
565 print_port(int proto, uint16_t port)
566 {
567 
568 	if (proto == IPPROTO_ETHERTYPE) {
569 		char const *s;
570 
571 		if (co.do_resolv && (s = match_value(ether_types, port)) )
572 			printf("%s", s);
573 		else
574 			printf("0x%04x", port);
575 	} else {
576 		struct servent *se = NULL;
577 		if (co.do_resolv) {
578 			struct protoent *pe = getprotobynumber(proto);
579 
580 			se = getservbyport(htons(port), pe ? pe->p_name : NULL);
581 		}
582 		if (se)
583 			printf("%s", se->s_name);
584 		else
585 			printf("%d", port);
586 	}
587 }
588 
589 static struct _s_x _port_name[] = {
590 	{"dst-port",	O_IP_DSTPORT},
591 	{"src-port",	O_IP_SRCPORT},
592 	{"ipid",	O_IPID},
593 	{"iplen",	O_IPLEN},
594 	{"ipttl",	O_IPTTL},
595 	{"mac-type",	O_MAC_TYPE},
596 	{"tcpdatalen",	O_TCPDATALEN},
597 	{"tcpwin",	O_TCPWIN},
598 	{"tagged",	O_TAGGED},
599 	{NULL,		0}
600 };
601 
602 /*
603  * Print the values in a list 16-bit items of the types above.
604  * XXX todo: add support for mask.
605  */
606 static void
607 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode)
608 {
609 	uint16_t *p = cmd->ports;
610 	int i;
611 	char const *sep;
612 
613 	if (opcode != 0) {
614 		sep = match_value(_port_name, opcode);
615 		if (sep == NULL)
616 			sep = "???";
617 		printf (" %s", sep);
618 	}
619 	sep = " ";
620 	for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
621 		printf("%s", sep);
622 		print_port(proto, p[0]);
623 		if (p[0] != p[1]) {
624 			printf("-");
625 			print_port(proto, p[1]);
626 		}
627 		sep = ",";
628 	}
629 }
630 
631 /*
632  * Like strtol, but also translates service names into port numbers
633  * for some protocols.
634  * In particular:
635  *	proto == -1 disables the protocol check;
636  *	proto == IPPROTO_ETHERTYPE looks up an internal table
637  *	proto == <some value in /etc/protocols> matches the values there.
638  * Returns *end == s in case the parameter is not found.
639  */
640 static int
641 strtoport(char *s, char **end, int base, int proto)
642 {
643 	char *p, *buf;
644 	char *s1;
645 	int i;
646 
647 	*end = s;		/* default - not found */
648 	if (*s == '\0')
649 		return 0;	/* not found */
650 
651 	if (isdigit(*s))
652 		return strtol(s, end, base);
653 
654 	/*
655 	 * find separator. '\\' escapes the next char.
656 	 */
657 	for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
658 		if (*s1 == '\\' && s1[1] != '\0')
659 			s1++;
660 
661 	buf = safe_calloc(s1 - s + 1, 1);
662 
663 	/*
664 	 * copy into a buffer skipping backslashes
665 	 */
666 	for (p = s, i = 0; p != s1 ; p++)
667 		if (*p != '\\')
668 			buf[i++] = *p;
669 	buf[i++] = '\0';
670 
671 	if (proto == IPPROTO_ETHERTYPE) {
672 		i = match_token(ether_types, buf);
673 		free(buf);
674 		if (i != -1) {	/* found */
675 			*end = s1;
676 			return i;
677 		}
678 	} else {
679 		struct protoent *pe = NULL;
680 		struct servent *se;
681 
682 		if (proto != 0)
683 			pe = getprotobynumber(proto);
684 		setservent(1);
685 		se = getservbyname(buf, pe ? pe->p_name : NULL);
686 		free(buf);
687 		if (se != NULL) {
688 			*end = s1;
689 			return ntohs(se->s_port);
690 		}
691 	}
692 	return 0;	/* not found */
693 }
694 
695 /*
696  * Fill the body of the command with the list of port ranges.
697  */
698 static int
699 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
700 {
701 	uint16_t a, b, *p = cmd->ports;
702 	int i = 0;
703 	char *s = av;
704 
705 	while (*s) {
706 		a = strtoport(av, &s, 0, proto);
707 		if (s == av) 			/* empty or invalid argument */
708 			return (0);
709 
710 		CHECK_LENGTH(cblen, i + 2);
711 
712 		switch (*s) {
713 		case '-':			/* a range */
714 			av = s + 1;
715 			b = strtoport(av, &s, 0, proto);
716 			/* Reject expressions like '1-abc' or '1-2-3'. */
717 			if (s == av || (*s != ',' && *s != '\0'))
718 				return (0);
719 			p[0] = a;
720 			p[1] = b;
721 			break;
722 		case ',':			/* comma separated list */
723 		case '\0':
724 			p[0] = p[1] = a;
725 			break;
726 		default:
727 			warnx("port list: invalid separator <%c> in <%s>",
728 				*s, av);
729 			return (0);
730 		}
731 
732 		i++;
733 		p += 2;
734 		av = s + 1;
735 	}
736 	if (i > 0) {
737 		if (i + 1 > F_LEN_MASK)
738 			errx(EX_DATAERR, "too many ports/ranges\n");
739 		cmd->o.len |= i + 1;	/* leave F_NOT and F_OR untouched */
740 	}
741 	return (i);
742 }
743 
744 /*
745  * Fill the body of the command with the list of DiffServ codepoints.
746  */
747 static void
748 fill_dscp(ipfw_insn *cmd, char *av, int cblen)
749 {
750 	uint32_t *low, *high;
751 	char *s = av, *a;
752 	int code;
753 
754 	cmd->opcode = O_DSCP;
755 	cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
756 
757 	CHECK_CMDLEN;
758 
759 	low = (uint32_t *)(cmd + 1);
760 	high = low + 1;
761 
762 	*low = 0;
763 	*high = 0;
764 
765 	while (s != NULL) {
766 		a = strchr(s, ',');
767 
768 		if (a != NULL)
769 			*a++ = '\0';
770 
771 		if (isalpha(*s)) {
772 			if ((code = match_token(f_ipdscp, s)) == -1)
773 				errx(EX_DATAERR, "Unknown DSCP code");
774 		} else {
775 			code = strtoul(s, NULL, 10);
776 			if (code < 0 || code > 63)
777 				errx(EX_DATAERR, "Invalid DSCP value");
778 		}
779 
780 		if (code > 32)
781 			*high |= 1 << (code - 32);
782 		else
783 			*low |= 1 << code;
784 
785 		s = a;
786 	}
787 }
788 
789 static struct _s_x icmpcodes[] = {
790       { "net",			ICMP_UNREACH_NET },
791       { "host",			ICMP_UNREACH_HOST },
792       { "protocol",		ICMP_UNREACH_PROTOCOL },
793       { "port",			ICMP_UNREACH_PORT },
794       { "needfrag",		ICMP_UNREACH_NEEDFRAG },
795       { "srcfail",		ICMP_UNREACH_SRCFAIL },
796       { "net-unknown",		ICMP_UNREACH_NET_UNKNOWN },
797       { "host-unknown",		ICMP_UNREACH_HOST_UNKNOWN },
798       { "isolated",		ICMP_UNREACH_ISOLATED },
799       { "net-prohib",		ICMP_UNREACH_NET_PROHIB },
800       { "host-prohib",		ICMP_UNREACH_HOST_PROHIB },
801       { "tosnet",		ICMP_UNREACH_TOSNET },
802       { "toshost",		ICMP_UNREACH_TOSHOST },
803       { "filter-prohib",	ICMP_UNREACH_FILTER_PROHIB },
804       { "host-precedence",	ICMP_UNREACH_HOST_PRECEDENCE },
805       { "precedence-cutoff",	ICMP_UNREACH_PRECEDENCE_CUTOFF },
806       { NULL, 0 }
807 };
808 
809 static void
810 fill_reject_code(u_short *codep, char *str)
811 {
812 	int val;
813 	char *s;
814 
815 	val = strtoul(str, &s, 0);
816 	if (s == str || *s != '\0' || val >= 0x100)
817 		val = match_token(icmpcodes, str);
818 	if (val < 0)
819 		errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
820 	*codep = val;
821 	return;
822 }
823 
824 static void
825 print_reject_code(uint16_t code)
826 {
827 	char const *s = match_value(icmpcodes, code);
828 
829 	if (s != NULL)
830 		printf("unreach %s", s);
831 	else
832 		printf("unreach %u", code);
833 }
834 
835 /*
836  * Returns the number of bits set (from left) in a contiguous bitmask,
837  * or -1 if the mask is not contiguous.
838  * XXX this needs a proper fix.
839  * This effectively works on masks in big-endian (network) format.
840  * when compiled on little endian architectures.
841  *
842  * First bit is bit 7 of the first byte -- note, for MAC addresses,
843  * the first bit on the wire is bit 0 of the first byte.
844  * len is the max length in bits.
845  */
846 int
847 contigmask(uint8_t *p, int len)
848 {
849 	int i, n;
850 
851 	for (i=0; i<len ; i++)
852 		if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
853 			break;
854 	for (n=i+1; n < len; n++)
855 		if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
856 			return -1; /* mask not contiguous */
857 	return i;
858 }
859 
860 /*
861  * print flags set/clear in the two bitmasks passed as parameters.
862  * There is a specialized check for f_tcpflags.
863  */
864 static void
865 print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list)
866 {
867 	char const *comma = "";
868 	int i;
869 	uint8_t set = cmd->arg1 & 0xff;
870 	uint8_t clear = (cmd->arg1 >> 8) & 0xff;
871 
872 	if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
873 		printf(" setup");
874 		return;
875 	}
876 
877 	printf(" %s ", name);
878 	for (i=0; list[i].x != 0; i++) {
879 		if (set & list[i].x) {
880 			set &= ~list[i].x;
881 			printf("%s%s", comma, list[i].s);
882 			comma = ",";
883 		}
884 		if (clear & list[i].x) {
885 			clear &= ~list[i].x;
886 			printf("%s!%s", comma, list[i].s);
887 			comma = ",";
888 		}
889 	}
890 }
891 
892 /*
893  * Print the ip address contained in a command.
894  */
895 static void
896 print_ip(ipfw_insn_ip *cmd, char const *s)
897 {
898 	struct hostent *he = NULL;
899 	uint32_t len = F_LEN((ipfw_insn *)cmd);
900 	uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
901 
902 	if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
903 		uint32_t d = a[1];
904 		const char *arg = "<invalid>";
905 
906 		if (d < sizeof(lookup_key)/sizeof(lookup_key[0]))
907 			arg = match_value(rule_options, lookup_key[d]);
908 		printf("%s lookup %s %d", cmd->o.len & F_NOT ? " not": "",
909 			arg, cmd->o.arg1);
910 		return;
911 	}
912 	printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
913 
914 	if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
915 		printf("me");
916 		return;
917 	}
918 	if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
919 	    cmd->o.opcode == O_IP_DST_LOOKUP) {
920 		printf("table(%u", ((ipfw_insn *)cmd)->arg1);
921 		if (len == F_INSN_SIZE(ipfw_insn_u32))
922 			printf(",%u", *a);
923 		printf(")");
924 		return;
925 	}
926 	if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
927 		uint32_t x, *map = (uint32_t *)&(cmd->mask);
928 		int i, j;
929 		char comma = '{';
930 
931 		x = cmd->o.arg1 - 1;
932 		x = htonl( ~x );
933 		cmd->addr.s_addr = htonl(cmd->addr.s_addr);
934 		printf("%s/%d", inet_ntoa(cmd->addr),
935 			contigmask((uint8_t *)&x, 32));
936 		x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
937 		x &= 0xff; /* base */
938 		/*
939 		 * Print bits and ranges.
940 		 * Locate first bit set (i), then locate first bit unset (j).
941 		 * If we have 3+ consecutive bits set, then print them as a
942 		 * range, otherwise only print the initial bit and rescan.
943 		 */
944 		for (i=0; i < cmd->o.arg1; i++)
945 			if (map[i/32] & (1<<(i & 31))) {
946 				for (j=i+1; j < cmd->o.arg1; j++)
947 					if (!(map[ j/32] & (1<<(j & 31))))
948 						break;
949 				printf("%c%d", comma, i+x);
950 				if (j>i+2) { /* range has at least 3 elements */
951 					printf("-%d", j-1+x);
952 					i = j-1;
953 				}
954 				comma = ',';
955 			}
956 		printf("}");
957 		return;
958 	}
959 	/*
960 	 * len == 2 indicates a single IP, whereas lists of 1 or more
961 	 * addr/mask pairs have len = (2n+1). We convert len to n so we
962 	 * use that to count the number of entries.
963 	 */
964     for (len = len / 2; len > 0; len--, a += 2) {
965 	int mb =	/* mask length */
966 	    (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
967 		32 : contigmask((uint8_t *)&(a[1]), 32);
968 	if (mb == 32 && co.do_resolv)
969 		he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
970 	if (he != NULL)		/* resolved to name */
971 		printf("%s", he->h_name);
972 	else if (mb == 0)	/* any */
973 		printf("any");
974 	else {		/* numeric IP followed by some kind of mask */
975 		printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) );
976 		if (mb < 0)
977 			printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) );
978 		else if (mb < 32)
979 			printf("/%d", mb);
980 	}
981 	if (len > 1)
982 		printf(",");
983     }
984 }
985 
986 /*
987  * prints a MAC address/mask pair
988  */
989 static void
990 print_mac(uint8_t *addr, uint8_t *mask)
991 {
992 	int l = contigmask(mask, 48);
993 
994 	if (l == 0)
995 		printf(" any");
996 	else {
997 		printf(" %02x:%02x:%02x:%02x:%02x:%02x",
998 		    addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
999 		if (l == -1)
1000 			printf("&%02x:%02x:%02x:%02x:%02x:%02x",
1001 			    mask[0], mask[1], mask[2],
1002 			    mask[3], mask[4], mask[5]);
1003 		else if (l < 48)
1004 			printf("/%d", l);
1005 	}
1006 }
1007 
1008 static void
1009 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1010 {
1011 	uint8_t type;
1012 
1013 	cmd->d[0] = 0;
1014 	while (*av) {
1015 		if (*av == ',')
1016 			av++;
1017 
1018 		type = strtoul(av, &av, 0);
1019 
1020 		if (*av != ',' && *av != '\0')
1021 			errx(EX_DATAERR, "invalid ICMP type");
1022 
1023 		if (type > 31)
1024 			errx(EX_DATAERR, "ICMP type out of range");
1025 
1026 		cmd->d[0] |= 1 << type;
1027 	}
1028 	cmd->o.opcode = O_ICMPTYPE;
1029 	cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1030 }
1031 
1032 static void
1033 print_icmptypes(ipfw_insn_u32 *cmd)
1034 {
1035 	int i;
1036 	char sep= ' ';
1037 
1038 	printf(" icmptypes");
1039 	for (i = 0; i < 32; i++) {
1040 		if ( (cmd->d[0] & (1 << (i))) == 0)
1041 			continue;
1042 		printf("%c%d", sep, i);
1043 		sep = ',';
1044 	}
1045 }
1046 
1047 static void
1048 print_dscp(ipfw_insn_u32 *cmd)
1049 {
1050 	int i, c;
1051 	uint32_t *v;
1052 	char sep= ' ';
1053 	const char *code;
1054 
1055 	printf(" dscp");
1056 	i = 0;
1057 	c = 0;
1058 	v = cmd->d;
1059 	while (i < 64) {
1060 		if (*v & (1 << i)) {
1061 			if ((code = match_value(f_ipdscp, i)) != NULL)
1062 				printf("%c%s", sep, code);
1063 			else
1064 				printf("%c%d", sep, i);
1065 			sep = ',';
1066 		}
1067 
1068 		if ((++i % 32) == 0)
1069 			v++;
1070 	}
1071 }
1072 
1073 /*
1074  * show_ipfw() prints the body of an ipfw rule.
1075  * Because the standard rule has at least proto src_ip dst_ip, we use
1076  * a helper function to produce these entries if not provided explicitly.
1077  * The first argument is the list of fields we have, the second is
1078  * the list of fields we want to be printed.
1079  *
1080  * Special cases if we have provided a MAC header:
1081  *   + if the rule does not contain IP addresses/ports, do not print them;
1082  *   + if the rule does not contain an IP proto, print "all" instead of "ip";
1083  *
1084  * Once we have 'have_options', IP header fields are printed as options.
1085  */
1086 #define	HAVE_PROTO	0x0001
1087 #define	HAVE_SRCIP	0x0002
1088 #define	HAVE_DSTIP	0x0004
1089 #define	HAVE_PROTO4	0x0008
1090 #define	HAVE_PROTO6	0x0010
1091 #define	HAVE_IP		0x0100
1092 #define	HAVE_OPTIONS	0x8000
1093 
1094 static void
1095 show_prerequisites(int *flags, int want, int cmd)
1096 {
1097 	(void)cmd;	/* UNUSED */
1098 	if (co.comment_only)
1099 		return;
1100 	if ( (*flags & HAVE_IP) == HAVE_IP)
1101 		*flags |= HAVE_OPTIONS;
1102 
1103 	if ( !(*flags & HAVE_OPTIONS)) {
1104 		if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) {
1105 			if ( (*flags & HAVE_PROTO4))
1106 				printf(" ip4");
1107 			else if ( (*flags & HAVE_PROTO6))
1108 				printf(" ip6");
1109 			else
1110 				printf(" ip");
1111 		}
1112 		if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
1113 			printf(" from any");
1114 		if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
1115 			printf(" to any");
1116 	}
1117 	*flags |= want;
1118 }
1119 
1120 static void
1121 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth)
1122 {
1123 	static int twidth = 0;
1124 	int l;
1125 	ipfw_insn *cmd, *tagptr = NULL;
1126 	const char *comment = NULL;	/* ptr to comment if we have one */
1127 	int proto = 0;		/* default */
1128 	int flags = 0;	/* prerequisites */
1129 	ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
1130 	ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
1131 	int or_block = 0;	/* we are in an or block */
1132 	uint32_t set_disable;
1133 
1134 	bcopy(&rule->next_rule, &set_disable, sizeof(set_disable));
1135 
1136 	if (set_disable & (1 << rule->set)) { /* disabled */
1137 		if (!co.show_sets)
1138 			return;
1139 		else
1140 			printf("# DISABLED ");
1141 	}
1142 	printf("%05u ", rule->rulenum);
1143 
1144 	if (pcwidth > 0 || bcwidth > 0) {
1145 		pr_u64(&rule->pcnt, pcwidth);
1146 		pr_u64(&rule->bcnt, bcwidth);
1147 	}
1148 
1149 	if (co.do_time == 2)
1150 		printf("%10u ", rule->timestamp);
1151 	else if (co.do_time == 1) {
1152 		char timestr[30];
1153 		time_t t = (time_t)0;
1154 
1155 		if (twidth == 0) {
1156 			strcpy(timestr, ctime(&t));
1157 			*strchr(timestr, '\n') = '\0';
1158 			twidth = strlen(timestr);
1159 		}
1160 		if (rule->timestamp) {
1161 			t = _long_to_time(rule->timestamp);
1162 
1163 			strcpy(timestr, ctime(&t));
1164 			*strchr(timestr, '\n') = '\0';
1165 			printf("%s ", timestr);
1166 		} else {
1167 			printf("%*s", twidth, " ");
1168 		}
1169 	}
1170 
1171 	if (co.show_sets)
1172 		printf("set %d ", rule->set);
1173 
1174 	/*
1175 	 * print the optional "match probability"
1176 	 */
1177 	if (rule->cmd_len > 0) {
1178 		cmd = rule->cmd ;
1179 		if (cmd->opcode == O_PROB) {
1180 			ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1181 			double d = 1.0 * p->d[0];
1182 
1183 			d = (d / 0x7fffffff);
1184 			printf("prob %f ", d);
1185 		}
1186 	}
1187 
1188 	/*
1189 	 * first print actions
1190 	 */
1191 	for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1192 			l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1193 		switch(cmd->opcode) {
1194 		case O_CHECK_STATE:
1195 			printf("check-state");
1196 			/* avoid printing anything else */
1197 			flags = HAVE_PROTO | HAVE_SRCIP |
1198 				HAVE_DSTIP | HAVE_IP;
1199 			break;
1200 
1201 		case O_ACCEPT:
1202 			printf("allow");
1203 			break;
1204 
1205 		case O_COUNT:
1206 			printf("count");
1207 			break;
1208 
1209 		case O_DENY:
1210 			printf("deny");
1211 			break;
1212 
1213 		case O_REJECT:
1214 			if (cmd->arg1 == ICMP_REJECT_RST)
1215 				printf("reset");
1216 			else if (cmd->arg1 == ICMP_UNREACH_HOST)
1217 				printf("reject");
1218 			else
1219 				print_reject_code(cmd->arg1);
1220 			break;
1221 
1222 		case O_UNREACH6:
1223 			if (cmd->arg1 == ICMP6_UNREACH_RST)
1224 				printf("reset6");
1225 			else
1226 				print_unreach6_code(cmd->arg1);
1227 			break;
1228 
1229 		case O_SKIPTO:
1230 			PRINT_UINT_ARG("skipto ", cmd->arg1);
1231 			break;
1232 
1233 		case O_PIPE:
1234 			PRINT_UINT_ARG("pipe ", cmd->arg1);
1235 			break;
1236 
1237 		case O_QUEUE:
1238 			PRINT_UINT_ARG("queue ", cmd->arg1);
1239 			break;
1240 
1241 		case O_DIVERT:
1242 			PRINT_UINT_ARG("divert ", cmd->arg1);
1243 			break;
1244 
1245 		case O_TEE:
1246 			PRINT_UINT_ARG("tee ", cmd->arg1);
1247 			break;
1248 
1249 		case O_NETGRAPH:
1250 			PRINT_UINT_ARG("netgraph ", cmd->arg1);
1251 			break;
1252 
1253 		case O_NGTEE:
1254 			PRINT_UINT_ARG("ngtee ", cmd->arg1);
1255 			break;
1256 
1257 		case O_FORWARD_IP:
1258 		    {
1259 			ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1260 
1261 			if (s->sa.sin_addr.s_addr == INADDR_ANY) {
1262 				printf("fwd tablearg");
1263 			} else {
1264 				printf("fwd %s", inet_ntoa(s->sa.sin_addr));
1265 			}
1266 			if (s->sa.sin_port)
1267 				printf(",%d", s->sa.sin_port);
1268 		    }
1269 			break;
1270 
1271 		case O_FORWARD_IP6:
1272 		    {
1273 			char buf[4 + INET6_ADDRSTRLEN + 1];
1274 			ipfw_insn_sa6 *s = (ipfw_insn_sa6 *)cmd;
1275 
1276 			printf("fwd %s", inet_ntop(AF_INET6, &s->sa.sin6_addr,
1277 			    buf, sizeof(buf)));
1278 			if (s->sa.sin6_port)
1279 				printf(",%d", s->sa.sin6_port);
1280 		    }
1281 			break;
1282 
1283 		case O_LOG: /* O_LOG is printed last */
1284 			logptr = (ipfw_insn_log *)cmd;
1285 			break;
1286 
1287 		case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1288 			altqptr = (ipfw_insn_altq *)cmd;
1289 			break;
1290 
1291 		case O_TAG:
1292 			tagptr = cmd;
1293 			break;
1294 
1295 		case O_NAT:
1296 			if (cmd->arg1 != 0)
1297 				PRINT_UINT_ARG("nat ", cmd->arg1);
1298 			else
1299 				printf("nat global");
1300 			break;
1301 
1302 		case O_SETFIB:
1303 			PRINT_UINT_ARG("setfib ", cmd->arg1);
1304  			break;
1305 
1306 		case O_SETDSCP:
1307 		    {
1308 			const char *code;
1309 
1310 			if ((code = match_value(f_ipdscp, cmd->arg1)) != NULL)
1311 				printf("setdscp %s", code);
1312 			else
1313 				PRINT_UINT_ARG("setdscp ", cmd->arg1);
1314 		    }
1315  			break;
1316 
1317 		case O_REASS:
1318 			printf("reass");
1319 			break;
1320 
1321 		case O_CALLRETURN:
1322 			if (cmd->len & F_NOT)
1323 				printf("return");
1324 			else
1325 				PRINT_UINT_ARG("call ", cmd->arg1);
1326 			break;
1327 
1328 		default:
1329 			printf("** unrecognized action %d len %d ",
1330 				cmd->opcode, cmd->len);
1331 		}
1332 	}
1333 	if (logptr) {
1334 		if (logptr->max_log > 0)
1335 			printf(" log logamount %d", logptr->max_log);
1336 		else
1337 			printf(" log");
1338 	}
1339 #ifndef NO_ALTQ
1340 	if (altqptr) {
1341 		print_altq_cmd(altqptr);
1342 	}
1343 #endif
1344 	if (tagptr) {
1345 		if (tagptr->len & F_NOT)
1346 			PRINT_UINT_ARG(" untag ", tagptr->arg1);
1347 		else
1348 			PRINT_UINT_ARG(" tag ", tagptr->arg1);
1349 	}
1350 
1351 	/*
1352 	 * then print the body.
1353 	 */
1354 	for (l = rule->act_ofs, cmd = rule->cmd ;
1355 			l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1356 		if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1357 			continue;
1358 		if (cmd->opcode == O_IP4) {
1359 			flags |= HAVE_PROTO4;
1360 			break;
1361 		} else if (cmd->opcode == O_IP6) {
1362 			flags |= HAVE_PROTO6;
1363 			break;
1364 		}
1365 	}
1366 	if (rule->_pad & 1) {	/* empty rules before options */
1367 		if (!co.do_compact) {
1368 			show_prerequisites(&flags, HAVE_PROTO, 0);
1369 			printf(" from any to any");
1370 		}
1371 		flags |= HAVE_IP | HAVE_OPTIONS | HAVE_PROTO |
1372 			 HAVE_SRCIP | HAVE_DSTIP;
1373 	}
1374 
1375 	if (co.comment_only)
1376 		comment = "...";
1377 
1378 	for (l = rule->act_ofs, cmd = rule->cmd ;
1379 			l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1380 		/* useful alias */
1381 		ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1382 
1383 		if (co.comment_only) {
1384 			if (cmd->opcode != O_NOP)
1385 				continue;
1386 			printf(" // %s\n", (char *)(cmd + 1));
1387 			return;
1388 		}
1389 
1390 		show_prerequisites(&flags, 0, cmd->opcode);
1391 
1392 		switch(cmd->opcode) {
1393 		case O_PROB:
1394 			break;	/* done already */
1395 
1396 		case O_PROBE_STATE:
1397 			break; /* no need to print anything here */
1398 
1399 		case O_IP_SRC:
1400 		case O_IP_SRC_LOOKUP:
1401 		case O_IP_SRC_MASK:
1402 		case O_IP_SRC_ME:
1403 		case O_IP_SRC_SET:
1404 			show_prerequisites(&flags, HAVE_PROTO, 0);
1405 			if (!(flags & HAVE_SRCIP))
1406 				printf(" from");
1407 			if ((cmd->len & F_OR) && !or_block)
1408 				printf(" {");
1409 			print_ip((ipfw_insn_ip *)cmd,
1410 				(flags & HAVE_OPTIONS) ? " src-ip" : "");
1411 			flags |= HAVE_SRCIP;
1412 			break;
1413 
1414 		case O_IP_DST:
1415 		case O_IP_DST_LOOKUP:
1416 		case O_IP_DST_MASK:
1417 		case O_IP_DST_ME:
1418 		case O_IP_DST_SET:
1419 			show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1420 			if (!(flags & HAVE_DSTIP))
1421 				printf(" to");
1422 			if ((cmd->len & F_OR) && !or_block)
1423 				printf(" {");
1424 			print_ip((ipfw_insn_ip *)cmd,
1425 				(flags & HAVE_OPTIONS) ? " dst-ip" : "");
1426 			flags |= HAVE_DSTIP;
1427 			break;
1428 
1429 		case O_IP6_SRC:
1430 		case O_IP6_SRC_MASK:
1431 		case O_IP6_SRC_ME:
1432 			show_prerequisites(&flags, HAVE_PROTO, 0);
1433 			if (!(flags & HAVE_SRCIP))
1434 				printf(" from");
1435 			if ((cmd->len & F_OR) && !or_block)
1436 				printf(" {");
1437 			print_ip6((ipfw_insn_ip6 *)cmd,
1438 			    (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1439 			flags |= HAVE_SRCIP | HAVE_PROTO;
1440 			break;
1441 
1442 		case O_IP6_DST:
1443 		case O_IP6_DST_MASK:
1444 		case O_IP6_DST_ME:
1445 			show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1446 			if (!(flags & HAVE_DSTIP))
1447 				printf(" to");
1448 			if ((cmd->len & F_OR) && !or_block)
1449 				printf(" {");
1450 			print_ip6((ipfw_insn_ip6 *)cmd,
1451 			    (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1452 			flags |= HAVE_DSTIP;
1453 			break;
1454 
1455 		case O_FLOW6ID:
1456 		print_flow6id( (ipfw_insn_u32 *) cmd );
1457 		flags |= HAVE_OPTIONS;
1458 		break;
1459 
1460 		case O_IP_DSTPORT:
1461 			show_prerequisites(&flags,
1462 				HAVE_PROTO | HAVE_SRCIP |
1463 				HAVE_DSTIP | HAVE_IP, 0);
1464 		case O_IP_SRCPORT:
1465 			if (flags & HAVE_DSTIP)
1466 				flags |= HAVE_IP;
1467 			show_prerequisites(&flags,
1468 				HAVE_PROTO | HAVE_SRCIP, 0);
1469 			if ((cmd->len & F_OR) && !or_block)
1470 				printf(" {");
1471 			if (cmd->len & F_NOT)
1472 				printf(" not");
1473 			print_newports((ipfw_insn_u16 *)cmd, proto,
1474 				(flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1475 			break;
1476 
1477 		case O_PROTO: {
1478 			struct protoent *pe = NULL;
1479 
1480 			if ((cmd->len & F_OR) && !or_block)
1481 				printf(" {");
1482 			if (cmd->len & F_NOT)
1483 				printf(" not");
1484 			proto = cmd->arg1;
1485 			pe = getprotobynumber(cmd->arg1);
1486 			if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1487 			    !(flags & HAVE_PROTO))
1488 				show_prerequisites(&flags,
1489 				    HAVE_PROTO | HAVE_IP | HAVE_SRCIP |
1490 				    HAVE_DSTIP | HAVE_OPTIONS, 0);
1491 			if (flags & HAVE_OPTIONS)
1492 				printf(" proto");
1493 			if (pe)
1494 				printf(" %s", pe->p_name);
1495 			else
1496 				printf(" %u", cmd->arg1);
1497 			}
1498 			flags |= HAVE_PROTO;
1499 			break;
1500 
1501 		default: /*options ... */
1502 			if (!(cmd->len & (F_OR|F_NOT)))
1503 				if (((cmd->opcode == O_IP6) &&
1504 				    (flags & HAVE_PROTO6)) ||
1505 				    ((cmd->opcode == O_IP4) &&
1506 				    (flags & HAVE_PROTO4)))
1507 					break;
1508 			show_prerequisites(&flags, HAVE_PROTO | HAVE_SRCIP |
1509 				    HAVE_DSTIP | HAVE_IP | HAVE_OPTIONS, 0);
1510 			if ((cmd->len & F_OR) && !or_block)
1511 				printf(" {");
1512 			if (cmd->len & F_NOT && cmd->opcode != O_IN)
1513 				printf(" not");
1514 			switch(cmd->opcode) {
1515 			case O_MACADDR2: {
1516 				ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1517 
1518 				printf(" MAC");
1519 				print_mac(m->addr, m->mask);
1520 				print_mac(m->addr + 6, m->mask + 6);
1521 				}
1522 				break;
1523 
1524 			case O_MAC_TYPE:
1525 				print_newports((ipfw_insn_u16 *)cmd,
1526 						IPPROTO_ETHERTYPE, cmd->opcode);
1527 				break;
1528 
1529 
1530 			case O_FRAG:
1531 				printf(" frag");
1532 				break;
1533 
1534 			case O_FIB:
1535 				printf(" fib %u", cmd->arg1 );
1536 				break;
1537 			case O_SOCKARG:
1538 				printf(" sockarg");
1539 				break;
1540 
1541 			case O_IN:
1542 				printf(cmd->len & F_NOT ? " out" : " in");
1543 				break;
1544 
1545 			case O_DIVERTED:
1546 				switch (cmd->arg1) {
1547 				case 3:
1548 					printf(" diverted");
1549 					break;
1550 				case 1:
1551 					printf(" diverted-loopback");
1552 					break;
1553 				case 2:
1554 					printf(" diverted-output");
1555 					break;
1556 				default:
1557 					printf(" diverted-?<%u>", cmd->arg1);
1558 					break;
1559 				}
1560 				break;
1561 
1562 			case O_LAYER2:
1563 				printf(" layer2");
1564 				break;
1565 			case O_XMIT:
1566 			case O_RECV:
1567 			case O_VIA:
1568 			    {
1569 				char const *s;
1570 				ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1571 
1572 				if (cmd->opcode == O_XMIT)
1573 					s = "xmit";
1574 				else if (cmd->opcode == O_RECV)
1575 					s = "recv";
1576 				else /* if (cmd->opcode == O_VIA) */
1577 					s = "via";
1578 				if (cmdif->name[0] == '\0')
1579 					printf(" %s %s", s,
1580 					    inet_ntoa(cmdif->p.ip));
1581 				else if (cmdif->name[0] == '\1') /* interface table */
1582 					printf(" %s table(%d)", s, cmdif->p.glob);
1583 				else
1584 					printf(" %s %s", s, cmdif->name);
1585 
1586 				break;
1587 			    }
1588 			case O_IPID:
1589 				if (F_LEN(cmd) == 1)
1590 				    printf(" ipid %u", cmd->arg1 );
1591 				else
1592 				    print_newports((ipfw_insn_u16 *)cmd, 0,
1593 					O_IPID);
1594 				break;
1595 
1596 			case O_IPTTL:
1597 				if (F_LEN(cmd) == 1)
1598 				    printf(" ipttl %u", cmd->arg1 );
1599 				else
1600 				    print_newports((ipfw_insn_u16 *)cmd, 0,
1601 					O_IPTTL);
1602 				break;
1603 
1604 			case O_IPVER:
1605 				printf(" ipver %u", cmd->arg1 );
1606 				break;
1607 
1608 			case O_IPPRECEDENCE:
1609 				printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1610 				break;
1611 
1612 			case O_DSCP:
1613 				print_dscp((ipfw_insn_u32 *)cmd);
1614 	 			break;
1615 
1616 			case O_IPLEN:
1617 				if (F_LEN(cmd) == 1)
1618 				    printf(" iplen %u", cmd->arg1 );
1619 				else
1620 				    print_newports((ipfw_insn_u16 *)cmd, 0,
1621 					O_IPLEN);
1622 				break;
1623 
1624 			case O_IPOPT:
1625 				print_flags("ipoptions", cmd, f_ipopts);
1626 				break;
1627 
1628 			case O_IPTOS:
1629 				print_flags("iptos", cmd, f_iptos);
1630 				break;
1631 
1632 			case O_ICMPTYPE:
1633 				print_icmptypes((ipfw_insn_u32 *)cmd);
1634 				break;
1635 
1636 			case O_ESTAB:
1637 				printf(" established");
1638 				break;
1639 
1640 			case O_TCPDATALEN:
1641 				if (F_LEN(cmd) == 1)
1642 				    printf(" tcpdatalen %u", cmd->arg1 );
1643 				else
1644 				    print_newports((ipfw_insn_u16 *)cmd, 0,
1645 					O_TCPDATALEN);
1646 				break;
1647 
1648 			case O_TCPFLAGS:
1649 				print_flags("tcpflags", cmd, f_tcpflags);
1650 				break;
1651 
1652 			case O_TCPOPTS:
1653 				print_flags("tcpoptions", cmd, f_tcpopts);
1654 				break;
1655 
1656 			case O_TCPWIN:
1657 				if (F_LEN(cmd) == 1)
1658 				    printf(" tcpwin %u", cmd->arg1);
1659 				else
1660 				    print_newports((ipfw_insn_u16 *)cmd, 0,
1661 					O_TCPWIN);
1662 				break;
1663 
1664 			case O_TCPACK:
1665 				printf(" tcpack %d", ntohl(cmd32->d[0]));
1666 				break;
1667 
1668 			case O_TCPSEQ:
1669 				printf(" tcpseq %d", ntohl(cmd32->d[0]));
1670 				break;
1671 
1672 			case O_UID:
1673 			    {
1674 				struct passwd *pwd = getpwuid(cmd32->d[0]);
1675 
1676 				if (pwd)
1677 					printf(" uid %s", pwd->pw_name);
1678 				else
1679 					printf(" uid %u", cmd32->d[0]);
1680 			    }
1681 				break;
1682 
1683 			case O_GID:
1684 			    {
1685 				struct group *grp = getgrgid(cmd32->d[0]);
1686 
1687 				if (grp)
1688 					printf(" gid %s", grp->gr_name);
1689 				else
1690 					printf(" gid %u", cmd32->d[0]);
1691 			    }
1692 				break;
1693 
1694 			case O_JAIL:
1695 				printf(" jail %d", cmd32->d[0]);
1696 				break;
1697 
1698 			case O_VERREVPATH:
1699 				printf(" verrevpath");
1700 				break;
1701 
1702 			case O_VERSRCREACH:
1703 				printf(" versrcreach");
1704 				break;
1705 
1706 			case O_ANTISPOOF:
1707 				printf(" antispoof");
1708 				break;
1709 
1710 			case O_IPSEC:
1711 				printf(" ipsec");
1712 				break;
1713 
1714 			case O_NOP:
1715 				comment = (char *)(cmd + 1);
1716 				break;
1717 
1718 			case O_KEEP_STATE:
1719 				printf(" keep-state");
1720 				break;
1721 
1722 			case O_LIMIT: {
1723 				struct _s_x *p = limit_masks;
1724 				ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1725 				uint8_t x = c->limit_mask;
1726 				char const *comma = " ";
1727 
1728 				printf(" limit");
1729 				for (; p->x != 0 ; p++)
1730 					if ((x & p->x) == p->x) {
1731 						x &= ~p->x;
1732 						printf("%s%s", comma, p->s);
1733 						comma = ",";
1734 					}
1735 				PRINT_UINT_ARG(" ", c->conn_limit);
1736 				break;
1737 			}
1738 
1739 			case O_IP6:
1740 				printf(" ip6");
1741 				break;
1742 
1743 			case O_IP4:
1744 				printf(" ip4");
1745 				break;
1746 
1747 			case O_ICMP6TYPE:
1748 				print_icmp6types((ipfw_insn_u32 *)cmd);
1749 				break;
1750 
1751 			case O_EXT_HDR:
1752 				print_ext6hdr( (ipfw_insn *) cmd );
1753 				break;
1754 
1755 			case O_TAGGED:
1756 				if (F_LEN(cmd) == 1)
1757 					PRINT_UINT_ARG(" tagged ", cmd->arg1);
1758 				else
1759 					print_newports((ipfw_insn_u16 *)cmd, 0,
1760 					    O_TAGGED);
1761 				break;
1762 
1763 			default:
1764 				printf(" [opcode %d len %d]",
1765 				    cmd->opcode, cmd->len);
1766 			}
1767 		}
1768 		if (cmd->len & F_OR) {
1769 			printf(" or");
1770 			or_block = 1;
1771 		} else if (or_block) {
1772 			printf(" }");
1773 			or_block = 0;
1774 		}
1775 	}
1776 	show_prerequisites(&flags, HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP
1777 					      | HAVE_IP, 0);
1778 	if (comment)
1779 		printf(" // %s", comment);
1780 	printf("\n");
1781 }
1782 
1783 static void
1784 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth)
1785 {
1786 	struct protoent *pe;
1787 	struct in_addr a;
1788 	uint16_t rulenum;
1789 	char buf[INET6_ADDRSTRLEN];
1790 
1791 	if (!co.do_expired) {
1792 		if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1793 			return;
1794 	}
1795 	bcopy(&d->rule, &rulenum, sizeof(rulenum));
1796 	printf("%05d", rulenum);
1797 	if (pcwidth > 0 || bcwidth > 0) {
1798 		printf(" ");
1799 		pr_u64(&d->pcnt, pcwidth);
1800 		pr_u64(&d->bcnt, bcwidth);
1801 		printf("(%ds)", d->expire);
1802 	}
1803 	switch (d->dyn_type) {
1804 	case O_LIMIT_PARENT:
1805 		printf(" PARENT %d", d->count);
1806 		break;
1807 	case O_LIMIT:
1808 		printf(" LIMIT");
1809 		break;
1810 	case O_KEEP_STATE: /* bidir, no mask */
1811 		printf(" STATE");
1812 		break;
1813 	}
1814 
1815 	if ((pe = getprotobynumber(d->id.proto)) != NULL)
1816 		printf(" %s", pe->p_name);
1817 	else
1818 		printf(" proto %u", d->id.proto);
1819 
1820 	if (d->id.addr_type == 4) {
1821 		a.s_addr = htonl(d->id.src_ip);
1822 		printf(" %s %d", inet_ntoa(a), d->id.src_port);
1823 
1824 		a.s_addr = htonl(d->id.dst_ip);
1825 		printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
1826 	} else if (d->id.addr_type == 6) {
1827 		printf(" %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
1828 		    sizeof(buf)), d->id.src_port);
1829 		printf(" <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6, buf,
1830 		    sizeof(buf)), d->id.dst_port);
1831 	} else
1832 		printf(" UNKNOWN <-> UNKNOWN\n");
1833 
1834 	printf("\n");
1835 }
1836 
1837 /*
1838  * This one handles all set-related commands
1839  * 	ipfw set { show | enable | disable }
1840  * 	ipfw set swap X Y
1841  * 	ipfw set move X to Y
1842  * 	ipfw set move rule X to Y
1843  */
1844 void
1845 ipfw_sets_handler(char *av[])
1846 {
1847 	uint32_t set_disable, masks[2];
1848 	int i, nbytes;
1849 	uint16_t rulenum;
1850 	uint8_t cmd, new_set;
1851 
1852 	av++;
1853 
1854 	if (av[0] == NULL)
1855 		errx(EX_USAGE, "set needs command");
1856 	if (_substrcmp(*av, "show") == 0) {
1857 		void *data = NULL;
1858 		char const *msg;
1859 		int nalloc;
1860 
1861 		nalloc = nbytes = sizeof(struct ip_fw);
1862 		while (nbytes >= nalloc) {
1863 			if (data)
1864 				free(data);
1865 			nalloc = nalloc * 2 + 200;
1866 			nbytes = nalloc;
1867 			data = safe_calloc(1, nbytes);
1868 			if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0)
1869 				err(EX_OSERR, "getsockopt(IP_FW_GET)");
1870 		}
1871 
1872 		bcopy(&((struct ip_fw *)data)->next_rule,
1873 			&set_disable, sizeof(set_disable));
1874 
1875 		for (i = 0, msg = "disable" ; i < RESVD_SET; i++)
1876 			if ((set_disable & (1<<i))) {
1877 				printf("%s %d", msg, i);
1878 				msg = "";
1879 			}
1880 		msg = (set_disable) ? " enable" : "enable";
1881 		for (i = 0; i < RESVD_SET; i++)
1882 			if (!(set_disable & (1<<i))) {
1883 				printf("%s %d", msg, i);
1884 				msg = "";
1885 			}
1886 		printf("\n");
1887 	} else if (_substrcmp(*av, "swap") == 0) {
1888 		av++;
1889 		if ( av[0] == NULL || av[1] == NULL )
1890 			errx(EX_USAGE, "set swap needs 2 set numbers\n");
1891 		rulenum = atoi(av[0]);
1892 		new_set = atoi(av[1]);
1893 		if (!isdigit(*(av[0])) || rulenum > RESVD_SET)
1894 			errx(EX_DATAERR, "invalid set number %s\n", av[0]);
1895 		if (!isdigit(*(av[1])) || new_set > RESVD_SET)
1896 			errx(EX_DATAERR, "invalid set number %s\n", av[1]);
1897 		masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
1898 		i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1899 	} else if (_substrcmp(*av, "move") == 0) {
1900 		av++;
1901 		if (av[0] && _substrcmp(*av, "rule") == 0) {
1902 			cmd = 2;
1903 			av++;
1904 		} else
1905 			cmd = 3;
1906 		if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
1907 				av[3] != NULL ||  _substrcmp(av[1], "to") != 0)
1908 			errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
1909 		rulenum = atoi(av[0]);
1910 		new_set = atoi(av[2]);
1911 		if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) ||
1912 			(cmd == 2 && rulenum == IPFW_DEFAULT_RULE) )
1913 			errx(EX_DATAERR, "invalid source number %s\n", av[0]);
1914 		if (!isdigit(*(av[2])) || new_set > RESVD_SET)
1915 			errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
1916 		masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
1917 		i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1918 	} else if (_substrcmp(*av, "disable") == 0 ||
1919 		   _substrcmp(*av, "enable") == 0 ) {
1920 		int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
1921 
1922 		av++;
1923 		masks[0] = masks[1] = 0;
1924 
1925 		while (av[0]) {
1926 			if (isdigit(**av)) {
1927 				i = atoi(*av);
1928 				if (i < 0 || i > RESVD_SET)
1929 					errx(EX_DATAERR,
1930 					    "invalid set number %d\n", i);
1931 				masks[which] |= (1<<i);
1932 			} else if (_substrcmp(*av, "disable") == 0)
1933 				which = 0;
1934 			else if (_substrcmp(*av, "enable") == 0)
1935 				which = 1;
1936 			else
1937 				errx(EX_DATAERR,
1938 					"invalid set command %s\n", *av);
1939 			av++;
1940 		}
1941 		if ( (masks[0] & masks[1]) != 0 )
1942 			errx(EX_DATAERR,
1943 			    "cannot enable and disable the same set\n");
1944 
1945 		i = do_cmd(IP_FW_DEL, masks, sizeof(masks));
1946 		if (i)
1947 			warn("set enable/disable: setsockopt(IP_FW_DEL)");
1948 	} else
1949 		errx(EX_USAGE, "invalid set command %s\n", *av);
1950 }
1951 
1952 void
1953 ipfw_sysctl_handler(char *av[], int which)
1954 {
1955 	av++;
1956 
1957 	if (av[0] == NULL) {
1958 		warnx("missing keyword to enable/disable\n");
1959 	} else if (_substrcmp(*av, "firewall") == 0) {
1960 		sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
1961 		    &which, sizeof(which));
1962 		sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
1963 		    &which, sizeof(which));
1964 	} else if (_substrcmp(*av, "one_pass") == 0) {
1965 		sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
1966 		    &which, sizeof(which));
1967 	} else if (_substrcmp(*av, "debug") == 0) {
1968 		sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
1969 		    &which, sizeof(which));
1970 	} else if (_substrcmp(*av, "verbose") == 0) {
1971 		sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
1972 		    &which, sizeof(which));
1973 	} else if (_substrcmp(*av, "dyn_keepalive") == 0) {
1974 		sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
1975 		    &which, sizeof(which));
1976 #ifndef NO_ALTQ
1977 	} else if (_substrcmp(*av, "altq") == 0) {
1978 		altq_set_enabled(which);
1979 #endif
1980 	} else {
1981 		warnx("unrecognize enable/disable keyword: %s\n", *av);
1982 	}
1983 }
1984 
1985 void
1986 ipfw_list(int ac, char *av[], int show_counters)
1987 {
1988 	struct ip_fw *r;
1989 	ipfw_dyn_rule *dynrules, *d;
1990 
1991 #define NEXT(r)	((struct ip_fw *)((char *)r + RULESIZE(r)))
1992 	char *lim;
1993 	void *data = NULL;
1994 	int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
1995 	int exitval = EX_OK;
1996 	int lac;
1997 	char **lav;
1998 	u_long rnum, last;
1999 	char *endptr;
2000 	int seen = 0;
2001 	uint8_t set;
2002 
2003 	const int ocmd = co.do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
2004 	int nalloc = 1024;	/* start somewhere... */
2005 
2006 	last = 0;
2007 
2008 	if (co.test_only) {
2009 		fprintf(stderr, "Testing only, list disabled\n");
2010 		return;
2011 	}
2012 	if (co.do_pipe) {
2013 		dummynet_list(ac, av, show_counters);
2014 		return;
2015 	}
2016 
2017 	ac--;
2018 	av++;
2019 
2020 	/* get rules or pipes from kernel, resizing array as necessary */
2021 	nbytes = nalloc;
2022 
2023 	while (nbytes >= nalloc) {
2024 		nalloc = nalloc * 2 + 200;
2025 		nbytes = nalloc;
2026 		data = safe_realloc(data, nbytes);
2027 		if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0)
2028 			err(EX_OSERR, "getsockopt(IP_%s_GET)",
2029 				co.do_pipe ? "DUMMYNET" : "FW");
2030 	}
2031 
2032 	/*
2033 	 * Count static rules. They have variable size so we
2034 	 * need to scan the list to count them.
2035 	 */
2036 	for (nstat = 1, r = data, lim = (char *)data + nbytes;
2037 		    r->rulenum < IPFW_DEFAULT_RULE && (char *)r < lim;
2038 		    ++nstat, r = NEXT(r) )
2039 		; /* nothing */
2040 
2041 	/*
2042 	 * Count dynamic rules. This is easier as they have
2043 	 * fixed size.
2044 	 */
2045 	r = NEXT(r);
2046 	dynrules = (ipfw_dyn_rule *)r ;
2047 	n = (char *)r - (char *)data;
2048 	ndyn = (nbytes - n) / sizeof *dynrules;
2049 
2050 	/* if showing stats, figure out column widths ahead of time */
2051 	bcwidth = pcwidth = 0;
2052 	if (show_counters) {
2053 		for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2054 			/* skip rules from another set */
2055 			if (co.use_set && r->set != co.use_set - 1)
2056 				continue;
2057 
2058 			/* packet counter */
2059 			width = pr_u64(&r->pcnt, 0);
2060 			if (width > pcwidth)
2061 				pcwidth = width;
2062 
2063 			/* byte counter */
2064 			width = pr_u64(&r->bcnt, 0);
2065 			if (width > bcwidth)
2066 				bcwidth = width;
2067 		}
2068 	}
2069 	if (co.do_dynamic && ndyn) {
2070 		for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2071 			if (co.use_set) {
2072 				/* skip rules from another set */
2073 				bcopy((char *)&d->rule + sizeof(uint16_t),
2074 				      &set, sizeof(uint8_t));
2075 				if (set != co.use_set - 1)
2076 					continue;
2077 			}
2078 			width = pr_u64(&d->pcnt, 0);
2079 			if (width > pcwidth)
2080 				pcwidth = width;
2081 
2082 			width = pr_u64(&d->bcnt, 0);
2083 			if (width > bcwidth)
2084 				bcwidth = width;
2085 		}
2086 	}
2087 	/* if no rule numbers were specified, list all rules */
2088 	if (ac == 0) {
2089 		for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2090 			if (co.use_set && r->set != co.use_set - 1)
2091 				continue;
2092 			show_ipfw(r, pcwidth, bcwidth);
2093 		}
2094 
2095 		if (co.do_dynamic && ndyn) {
2096 			printf("## Dynamic rules (%d):\n", ndyn);
2097 			for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2098 				if (co.use_set) {
2099 					bcopy((char *)&d->rule + sizeof(uint16_t),
2100 					      &set, sizeof(uint8_t));
2101 					if (set != co.use_set - 1)
2102 						continue;
2103 				}
2104 				show_dyn_ipfw(d, pcwidth, bcwidth);
2105 		}
2106 		}
2107 		goto done;
2108 	}
2109 
2110 	/* display specific rules requested on command line */
2111 
2112 	for (lac = ac, lav = av; lac != 0; lac--) {
2113 		/* convert command line rule # */
2114 		last = rnum = strtoul(*lav++, &endptr, 10);
2115 		if (*endptr == '-')
2116 			last = strtoul(endptr+1, &endptr, 10);
2117 		if (*endptr) {
2118 			exitval = EX_USAGE;
2119 			warnx("invalid rule number: %s", *(lav - 1));
2120 			continue;
2121 		}
2122 		for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) {
2123 			if (r->rulenum > last)
2124 				break;
2125 			if (co.use_set && r->set != co.use_set - 1)
2126 				continue;
2127 			if (r->rulenum >= rnum && r->rulenum <= last) {
2128 				show_ipfw(r, pcwidth, bcwidth);
2129 				seen = 1;
2130 			}
2131 		}
2132 		if (!seen) {
2133 			/* give precedence to other error(s) */
2134 			if (exitval == EX_OK)
2135 				exitval = EX_UNAVAILABLE;
2136 			warnx("rule %lu does not exist", rnum);
2137 		}
2138 	}
2139 
2140 	if (co.do_dynamic && ndyn) {
2141 		printf("## Dynamic rules:\n");
2142 		for (lac = ac, lav = av; lac != 0; lac--) {
2143 			last = rnum = strtoul(*lav++, &endptr, 10);
2144 			if (*endptr == '-')
2145 				last = strtoul(endptr+1, &endptr, 10);
2146 			if (*endptr)
2147 				/* already warned */
2148 				continue;
2149 			for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2150 				uint16_t rulenum;
2151 
2152 				bcopy(&d->rule, &rulenum, sizeof(rulenum));
2153 				if (rulenum > rnum)
2154 					break;
2155 				if (co.use_set) {
2156 					bcopy((char *)&d->rule + sizeof(uint16_t),
2157 					      &set, sizeof(uint8_t));
2158 					if (set != co.use_set - 1)
2159 						continue;
2160 				}
2161 				if (r->rulenum >= rnum && r->rulenum <= last)
2162 					show_dyn_ipfw(d, pcwidth, bcwidth);
2163 			}
2164 		}
2165 	}
2166 
2167 	ac = 0;
2168 
2169 done:
2170 	free(data);
2171 
2172 	if (exitval != EX_OK)
2173 		exit(exitval);
2174 #undef NEXT
2175 }
2176 
2177 static int
2178 lookup_host (char *host, struct in_addr *ipaddr)
2179 {
2180 	struct hostent *he;
2181 
2182 	if (!inet_aton(host, ipaddr)) {
2183 		if ((he = gethostbyname(host)) == NULL)
2184 			return(-1);
2185 		*ipaddr = *(struct in_addr *)he->h_addr_list[0];
2186 	}
2187 	return(0);
2188 }
2189 
2190 /*
2191  * fills the addr and mask fields in the instruction as appropriate from av.
2192  * Update length as appropriate.
2193  * The following formats are allowed:
2194  *	me	returns O_IP_*_ME
2195  *	1.2.3.4		single IP address
2196  *	1.2.3.4:5.6.7.8	address:mask
2197  *	1.2.3.4/24	address/mask
2198  *	1.2.3.4/26{1,6,5,4,23}	set of addresses in a subnet
2199  * We can have multiple comma-separated address/mask entries.
2200  */
2201 static void
2202 fill_ip(ipfw_insn_ip *cmd, char *av, int cblen)
2203 {
2204 	int len = 0;
2205 	uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2206 
2207 	cmd->o.len &= ~F_LEN_MASK;	/* zero len */
2208 
2209 	if (_substrcmp(av, "any") == 0)
2210 		return;
2211 
2212 	if (_substrcmp(av, "me") == 0) {
2213 		cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2214 		return;
2215 	}
2216 
2217 	if (strncmp(av, "table(", 6) == 0) {
2218 		char *p = strchr(av + 6, ',');
2219 
2220 		if (p)
2221 			*p++ = '\0';
2222 		cmd->o.opcode = O_IP_DST_LOOKUP;
2223 		cmd->o.arg1 = strtoul(av + 6, NULL, 0);
2224 		if (p) {
2225 			cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2226 			d[0] = strtoul(p, NULL, 0);
2227 		} else
2228 			cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2229 		return;
2230 	}
2231 
2232     while (av) {
2233 	/*
2234 	 * After the address we can have '/' or ':' indicating a mask,
2235 	 * ',' indicating another address follows, '{' indicating a
2236 	 * set of addresses of unspecified size.
2237 	 */
2238 	char *t = NULL, *p = strpbrk(av, "/:,{");
2239 	int masklen;
2240 	char md, nd = '\0';
2241 
2242 	CHECK_LENGTH(cblen, F_INSN_SIZE(ipfw_insn) + 2 + len);
2243 
2244 	if (p) {
2245 		md = *p;
2246 		*p++ = '\0';
2247 		if ((t = strpbrk(p, ",{")) != NULL) {
2248 			nd = *t;
2249 			*t = '\0';
2250 		}
2251 	} else
2252 		md = '\0';
2253 
2254 	if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2255 		errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2256 	switch (md) {
2257 	case ':':
2258 		if (!inet_aton(p, (struct in_addr *)&d[1]))
2259 			errx(EX_DATAERR, "bad netmask ``%s''", p);
2260 		break;
2261 	case '/':
2262 		masklen = atoi(p);
2263 		if (masklen == 0)
2264 			d[1] = htonl(0);	/* mask */
2265 		else if (masklen > 32)
2266 			errx(EX_DATAERR, "bad width ``%s''", p);
2267 		else
2268 			d[1] = htonl(~0 << (32 - masklen));
2269 		break;
2270 	case '{':	/* no mask, assume /24 and put back the '{' */
2271 		d[1] = htonl(~0 << (32 - 24));
2272 		*(--p) = md;
2273 		break;
2274 
2275 	case ',':	/* single address plus continuation */
2276 		*(--p) = md;
2277 		/* FALLTHROUGH */
2278 	case 0:		/* initialization value */
2279 	default:
2280 		d[1] = htonl(~0);	/* force /32 */
2281 		break;
2282 	}
2283 	d[0] &= d[1];		/* mask base address with mask */
2284 	if (t)
2285 		*t = nd;
2286 	/* find next separator */
2287 	if (p)
2288 		p = strpbrk(p, ",{");
2289 	if (p && *p == '{') {
2290 		/*
2291 		 * We have a set of addresses. They are stored as follows:
2292 		 *   arg1	is the set size (powers of 2, 2..256)
2293 		 *   addr	is the base address IN HOST FORMAT
2294 		 *   mask..	is an array of arg1 bits (rounded up to
2295 		 *		the next multiple of 32) with bits set
2296 		 *		for each host in the map.
2297 		 */
2298 		uint32_t *map = (uint32_t *)&cmd->mask;
2299 		int low, high;
2300 		int i = contigmask((uint8_t *)&(d[1]), 32);
2301 
2302 		if (len > 0)
2303 			errx(EX_DATAERR, "address set cannot be in a list");
2304 		if (i < 24 || i > 31)
2305 			errx(EX_DATAERR, "invalid set with mask %d\n", i);
2306 		cmd->o.arg1 = 1<<(32-i);	/* map length		*/
2307 		d[0] = ntohl(d[0]);		/* base addr in host format */
2308 		cmd->o.opcode = O_IP_DST_SET;	/* default */
2309 		cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2310 		for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2311 			map[i] = 0;	/* clear map */
2312 
2313 		av = p + 1;
2314 		low = d[0] & 0xff;
2315 		high = low + cmd->o.arg1 - 1;
2316 		/*
2317 		 * Here, i stores the previous value when we specify a range
2318 		 * of addresses within a mask, e.g. 45-63. i = -1 means we
2319 		 * have no previous value.
2320 		 */
2321 		i = -1;	/* previous value in a range */
2322 		while (isdigit(*av)) {
2323 			char *s;
2324 			int a = strtol(av, &s, 0);
2325 
2326 			if (s == av) { /* no parameter */
2327 			    if (*av != '}')
2328 				errx(EX_DATAERR, "set not closed\n");
2329 			    if (i != -1)
2330 				errx(EX_DATAERR, "incomplete range %d-", i);
2331 			    break;
2332 			}
2333 			if (a < low || a > high)
2334 			    errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2335 				a, low, high);
2336 			a -= low;
2337 			if (i == -1)	/* no previous in range */
2338 			    i = a;
2339 			else {		/* check that range is valid */
2340 			    if (i > a)
2341 				errx(EX_DATAERR, "invalid range %d-%d",
2342 					i+low, a+low);
2343 			    if (*s == '-')
2344 				errx(EX_DATAERR, "double '-' in range");
2345 			}
2346 			for (; i <= a; i++)
2347 			    map[i/32] |= 1<<(i & 31);
2348 			i = -1;
2349 			if (*s == '-')
2350 			    i = a;
2351 			else if (*s == '}')
2352 			    break;
2353 			av = s+1;
2354 		}
2355 		return;
2356 	}
2357 	av = p;
2358 	if (av)			/* then *av must be a ',' */
2359 		av++;
2360 
2361 	/* Check this entry */
2362 	if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2363 		/*
2364 		 * 'any' turns the entire list into a NOP.
2365 		 * 'not any' never matches, so it is removed from the
2366 		 * list unless it is the only item, in which case we
2367 		 * report an error.
2368 		 */
2369 		if (cmd->o.len & F_NOT) {	/* "not any" never matches */
2370 			if (av == NULL && len == 0) /* only this entry */
2371 				errx(EX_DATAERR, "not any never matches");
2372 		}
2373 		/* else do nothing and skip this entry */
2374 		return;
2375 	}
2376 	/* A single IP can be stored in an optimized format */
2377 	if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
2378 		cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2379 		return;
2380 	}
2381 	len += 2;	/* two words... */
2382 	d += 2;
2383     } /* end while */
2384     if (len + 1 > F_LEN_MASK)
2385 	errx(EX_DATAERR, "address list too long");
2386     cmd->o.len |= len+1;
2387 }
2388 
2389 
2390 /* n2mask sets n bits of the mask */
2391 void
2392 n2mask(struct in6_addr *mask, int n)
2393 {
2394 	static int	minimask[9] =
2395 	    { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
2396 	u_char		*p;
2397 
2398 	memset(mask, 0, sizeof(struct in6_addr));
2399 	p = (u_char *) mask;
2400 	for (; n > 0; p++, n -= 8) {
2401 		if (n >= 8)
2402 			*p = 0xff;
2403 		else
2404 			*p = minimask[n];
2405 	}
2406 	return;
2407 }
2408 
2409 /*
2410  * helper function to process a set of flags and set bits in the
2411  * appropriate masks.
2412  */
2413 static void
2414 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
2415 	struct _s_x *flags, char *p)
2416 {
2417 	uint8_t set=0, clear=0;
2418 
2419 	while (p && *p) {
2420 		char *q;	/* points to the separator */
2421 		int val;
2422 		uint8_t *which;	/* mask we are working on */
2423 
2424 		if (*p == '!') {
2425 			p++;
2426 			which = &clear;
2427 		} else
2428 			which = &set;
2429 		q = strchr(p, ',');
2430 		if (q)
2431 			*q++ = '\0';
2432 		val = match_token(flags, p);
2433 		if (val <= 0)
2434 			errx(EX_DATAERR, "invalid flag %s", p);
2435 		*which |= (uint8_t)val;
2436 		p = q;
2437 	}
2438 	cmd->opcode = opcode;
2439 	cmd->len =  (cmd->len & (F_NOT | F_OR)) | 1;
2440 	cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
2441 }
2442 
2443 
2444 void
2445 ipfw_delete(char *av[])
2446 {
2447 	uint32_t rulenum;
2448 	int i;
2449 	int exitval = EX_OK;
2450 	int do_set = 0;
2451 
2452 	av++;
2453 	NEED1("missing rule specification");
2454 	if ( *av && _substrcmp(*av, "set") == 0) {
2455 		/* Do not allow using the following syntax:
2456 		 *	ipfw set N delete set M
2457 		 */
2458 		if (co.use_set)
2459 			errx(EX_DATAERR, "invalid syntax");
2460 		do_set = 1;	/* delete set */
2461 		av++;
2462 	}
2463 
2464 	/* Rule number */
2465 	while (*av && isdigit(**av)) {
2466 		i = atoi(*av); av++;
2467 		if (co.do_nat) {
2468 			exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
2469 			if (exitval) {
2470 				exitval = EX_UNAVAILABLE;
2471 				warn("rule %u not available", i);
2472 			}
2473  		} else if (co.do_pipe) {
2474 			exitval = ipfw_delete_pipe(co.do_pipe, i);
2475 		} else {
2476 			if (co.use_set)
2477 				rulenum = (i & 0xffff) | (5 << 24) |
2478 				    ((co.use_set - 1) << 16);
2479 			else
2480 			rulenum =  (i & 0xffff) | (do_set << 24);
2481 			i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum);
2482 			if (i) {
2483 				exitval = EX_UNAVAILABLE;
2484 				warn("rule %u: setsockopt(IP_FW_DEL)",
2485 				    rulenum);
2486 			}
2487 		}
2488 	}
2489 	if (exitval != EX_OK)
2490 		exit(exitval);
2491 }
2492 
2493 
2494 /*
2495  * fill the interface structure. We do not check the name as we can
2496  * create interfaces dynamically, so checking them at insert time
2497  * makes relatively little sense.
2498  * Interface names containing '*', '?', or '[' are assumed to be shell
2499  * patterns which match interfaces.
2500  */
2501 static void
2502 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen)
2503 {
2504 	cmd->name[0] = '\0';
2505 	cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
2506 
2507 	CHECK_CMDLEN;
2508 
2509 	/* Parse the interface or address */
2510 	if (strcmp(arg, "any") == 0)
2511 		cmd->o.len = 0;		/* effectively ignore this command */
2512 	else if (strncmp(arg, "table(", 6) == 0) {
2513 		char *p = strchr(arg + 6, ',');
2514 		if (p)
2515 			*p++ = '\0';
2516 		cmd->name[0] = '\1'; /* Special value indicating table */
2517 		cmd->p.glob = strtoul(arg + 6, NULL, 0);
2518 	} else if (!isdigit(*arg)) {
2519 		strlcpy(cmd->name, arg, sizeof(cmd->name));
2520 		cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
2521 	} else if (!inet_aton(arg, &cmd->p.ip))
2522 		errx(EX_DATAERR, "bad ip address ``%s''", arg);
2523 }
2524 
2525 static void
2526 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
2527 {
2528 	int i;
2529 	size_t l;
2530 	char *ap, *ptr, *optr;
2531 	struct ether_addr *mac;
2532 	const char *macset = "0123456789abcdefABCDEF:";
2533 
2534 	if (strcmp(p, "any") == 0) {
2535 		for (i = 0; i < ETHER_ADDR_LEN; i++)
2536 			addr[i] = mask[i] = 0;
2537 		return;
2538 	}
2539 
2540 	optr = ptr = strdup(p);
2541 	if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
2542 		l = strlen(ap);
2543 		if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
2544 			errx(EX_DATAERR, "Incorrect MAC address");
2545 		bcopy(mac, addr, ETHER_ADDR_LEN);
2546 	} else
2547 		errx(EX_DATAERR, "Incorrect MAC address");
2548 
2549 	if (ptr != NULL) { /* we have mask? */
2550 		if (p[ptr - optr - 1] == '/') { /* mask len */
2551 			long ml = strtol(ptr, &ap, 10);
2552 			if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
2553 				errx(EX_DATAERR, "Incorrect mask length");
2554 			for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
2555 				mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
2556 		} else { /* mask */
2557 			l = strlen(ptr);
2558 			if (strspn(ptr, macset) != l ||
2559 			    (mac = ether_aton(ptr)) == NULL)
2560 				errx(EX_DATAERR, "Incorrect mask");
2561 			bcopy(mac, mask, ETHER_ADDR_LEN);
2562 		}
2563 	} else { /* default mask: ff:ff:ff:ff:ff:ff */
2564 		for (i = 0; i < ETHER_ADDR_LEN; i++)
2565 			mask[i] = 0xff;
2566 	}
2567 	for (i = 0; i < ETHER_ADDR_LEN; i++)
2568 		addr[i] &= mask[i];
2569 
2570 	free(optr);
2571 }
2572 
2573 /*
2574  * helper function, updates the pointer to cmd with the length
2575  * of the current command, and also cleans up the first word of
2576  * the new command in case it has been clobbered before.
2577  */
2578 static ipfw_insn *
2579 next_cmd(ipfw_insn *cmd, int *len)
2580 {
2581 	*len -= F_LEN(cmd);
2582 	CHECK_LENGTH(*len, 0);
2583 	cmd += F_LEN(cmd);
2584 	bzero(cmd, sizeof(*cmd));
2585 	return cmd;
2586 }
2587 
2588 /*
2589  * Takes arguments and copies them into a comment
2590  */
2591 static void
2592 fill_comment(ipfw_insn *cmd, char **av, int cblen)
2593 {
2594 	int i, l;
2595 	char *p = (char *)(cmd + 1);
2596 
2597 	cmd->opcode = O_NOP;
2598 	cmd->len =  (cmd->len & (F_NOT | F_OR));
2599 
2600 	/* Compute length of comment string. */
2601 	for (i = 0, l = 0; av[i] != NULL; i++)
2602 		l += strlen(av[i]) + 1;
2603 	if (l == 0)
2604 		return;
2605 	if (l > 84)
2606 		errx(EX_DATAERR,
2607 		    "comment too long (max 80 chars)");
2608 	l = 1 + (l+3)/4;
2609 	cmd->len =  (cmd->len & (F_NOT | F_OR)) | l;
2610 	CHECK_CMDLEN;
2611 
2612 	for (i = 0; av[i] != NULL; i++) {
2613 		strcpy(p, av[i]);
2614 		p += strlen(av[i]);
2615 		*p++ = ' ';
2616 	}
2617 	*(--p) = '\0';
2618 }
2619 
2620 /*
2621  * A function to fill simple commands of size 1.
2622  * Existing flags are preserved.
2623  */
2624 static void
2625 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
2626 {
2627 	cmd->opcode = opcode;
2628 	cmd->len =  ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
2629 	cmd->arg1 = arg;
2630 }
2631 
2632 /*
2633  * Fetch and add the MAC address and type, with masks. This generates one or
2634  * two microinstructions, and returns the pointer to the last one.
2635  */
2636 static ipfw_insn *
2637 add_mac(ipfw_insn *cmd, char *av[], int cblen)
2638 {
2639 	ipfw_insn_mac *mac;
2640 
2641 	if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
2642 		errx(EX_DATAERR, "MAC dst src");
2643 
2644 	cmd->opcode = O_MACADDR2;
2645 	cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
2646 	CHECK_CMDLEN;
2647 
2648 	mac = (ipfw_insn_mac *)cmd;
2649 	get_mac_addr_mask(av[0], mac->addr, mac->mask);	/* dst */
2650 	get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
2651 	    &(mac->mask[ETHER_ADDR_LEN])); /* src */
2652 	return cmd;
2653 }
2654 
2655 static ipfw_insn *
2656 add_mactype(ipfw_insn *cmd, char *av, int cblen)
2657 {
2658 	if (!av)
2659 		errx(EX_DATAERR, "missing MAC type");
2660 	if (strcmp(av, "any") != 0) { /* we have a non-null type */
2661 		fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
2662 		    cblen);
2663 		cmd->opcode = O_MAC_TYPE;
2664 		return cmd;
2665 	} else
2666 		return NULL;
2667 }
2668 
2669 static ipfw_insn *
2670 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
2671 {
2672 	struct protoent *pe;
2673 	char *ep;
2674 	int proto;
2675 
2676 	proto = strtol(av, &ep, 10);
2677 	if (*ep != '\0' || proto <= 0) {
2678 		if ((pe = getprotobyname(av)) == NULL)
2679 			return NULL;
2680 		proto = pe->p_proto;
2681 	}
2682 
2683 	fill_cmd(cmd, O_PROTO, 0, proto);
2684 	*protop = proto;
2685 	return cmd;
2686 }
2687 
2688 static ipfw_insn *
2689 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
2690 {
2691 	u_char proto = IPPROTO_IP;
2692 
2693 	if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2694 		; /* do not set O_IP4 nor O_IP6 */
2695 	else if (strcmp(av, "ip4") == 0)
2696 		/* explicit "just IPv4" rule */
2697 		fill_cmd(cmd, O_IP4, 0, 0);
2698 	else if (strcmp(av, "ip6") == 0) {
2699 		/* explicit "just IPv6" rule */
2700 		proto = IPPROTO_IPV6;
2701 		fill_cmd(cmd, O_IP6, 0, 0);
2702 	} else
2703 		return add_proto0(cmd, av, protop);
2704 
2705 	*protop = proto;
2706 	return cmd;
2707 }
2708 
2709 static ipfw_insn *
2710 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
2711 {
2712 	u_char proto = IPPROTO_IP;
2713 
2714 	if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2715 		; /* do not set O_IP4 nor O_IP6 */
2716 	else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
2717 		/* explicit "just IPv4" rule */
2718 		fill_cmd(cmd, O_IP4, 0, 0);
2719 	else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
2720 		/* explicit "just IPv6" rule */
2721 		proto = IPPROTO_IPV6;
2722 		fill_cmd(cmd, O_IP6, 0, 0);
2723 	} else
2724 		return add_proto0(cmd, av, protop);
2725 
2726 	*protop = proto;
2727 	return cmd;
2728 }
2729 
2730 static ipfw_insn *
2731 add_srcip(ipfw_insn *cmd, char *av, int cblen)
2732 {
2733 	fill_ip((ipfw_insn_ip *)cmd, av, cblen);
2734 	if (cmd->opcode == O_IP_DST_SET)			/* set */
2735 		cmd->opcode = O_IP_SRC_SET;
2736 	else if (cmd->opcode == O_IP_DST_LOOKUP)		/* table */
2737 		cmd->opcode = O_IP_SRC_LOOKUP;
2738 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))		/* me */
2739 		cmd->opcode = O_IP_SRC_ME;
2740 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))	/* one IP */
2741 		cmd->opcode = O_IP_SRC;
2742 	else							/* addr/mask */
2743 		cmd->opcode = O_IP_SRC_MASK;
2744 	return cmd;
2745 }
2746 
2747 static ipfw_insn *
2748 add_dstip(ipfw_insn *cmd, char *av, int cblen)
2749 {
2750 	fill_ip((ipfw_insn_ip *)cmd, av, cblen);
2751 	if (cmd->opcode == O_IP_DST_SET)			/* set */
2752 		;
2753 	else if (cmd->opcode == O_IP_DST_LOOKUP)		/* table */
2754 		;
2755 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))		/* me */
2756 		cmd->opcode = O_IP_DST_ME;
2757 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))	/* one IP */
2758 		cmd->opcode = O_IP_DST;
2759 	else							/* addr/mask */
2760 		cmd->opcode = O_IP_DST_MASK;
2761 	return cmd;
2762 }
2763 
2764 static ipfw_insn *
2765 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
2766 {
2767 	/* XXX "any" is trapped before. Perhaps "to" */
2768 	if (_substrcmp(av, "any") == 0) {
2769 		return NULL;
2770 	} else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
2771 		/* XXX todo: check that we have a protocol with ports */
2772 		cmd->opcode = opcode;
2773 		return cmd;
2774 	}
2775 	return NULL;
2776 }
2777 
2778 static ipfw_insn *
2779 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen)
2780 {
2781 	struct in6_addr a;
2782 	char *host, *ch, buf[INET6_ADDRSTRLEN];
2783 	ipfw_insn *ret = NULL;
2784 	int len;
2785 
2786 	/* Copy first address in set if needed */
2787 	if ((ch = strpbrk(av, "/,")) != NULL) {
2788 		len = ch - av;
2789 		strlcpy(buf, av, sizeof(buf));
2790 		if (len < sizeof(buf))
2791 			buf[len] = '\0';
2792 		host = buf;
2793 	} else
2794 		host = av;
2795 
2796 	if (proto == IPPROTO_IPV6  || strcmp(av, "me6") == 0 ||
2797 	    inet_pton(AF_INET6, host, &a) == 1)
2798 		ret = add_srcip6(cmd, av, cblen);
2799 	/* XXX: should check for IPv4, not !IPv6 */
2800 	if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2801 	    inet_pton(AF_INET6, host, &a) != 1))
2802 		ret = add_srcip(cmd, av, cblen);
2803 	if (ret == NULL && strcmp(av, "any") != 0)
2804 		ret = cmd;
2805 
2806 	return ret;
2807 }
2808 
2809 static ipfw_insn *
2810 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen)
2811 {
2812 	struct in6_addr a;
2813 	char *host, *ch, buf[INET6_ADDRSTRLEN];
2814 	ipfw_insn *ret = NULL;
2815 	int len;
2816 
2817 	/* Copy first address in set if needed */
2818 	if ((ch = strpbrk(av, "/,")) != NULL) {
2819 		len = ch - av;
2820 		strlcpy(buf, av, sizeof(buf));
2821 		if (len < sizeof(buf))
2822 			buf[len] = '\0';
2823 		host = buf;
2824 	} else
2825 		host = av;
2826 
2827 	if (proto == IPPROTO_IPV6  || strcmp(av, "me6") == 0 ||
2828 	    inet_pton(AF_INET6, host, &a) == 1)
2829 		ret = add_dstip6(cmd, av, cblen);
2830 	/* XXX: should check for IPv4, not !IPv6 */
2831 	if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2832 	    inet_pton(AF_INET6, host, &a) != 1))
2833 		ret = add_dstip(cmd, av, cblen);
2834 	if (ret == NULL && strcmp(av, "any") != 0)
2835 		ret = cmd;
2836 
2837 	return ret;
2838 }
2839 
2840 /*
2841  * Parse arguments and assemble the microinstructions which make up a rule.
2842  * Rules are added into the 'rulebuf' and then copied in the correct order
2843  * into the actual rule.
2844  *
2845  * The syntax for a rule starts with the action, followed by
2846  * optional action parameters, and the various match patterns.
2847  * In the assembled microcode, the first opcode must be an O_PROBE_STATE
2848  * (generated if the rule includes a keep-state option), then the
2849  * various match patterns, log/altq actions, and the actual action.
2850  *
2851  */
2852 void
2853 ipfw_add(char *av[])
2854 {
2855 	/*
2856 	 * rules are added into the 'rulebuf' and then copied in
2857 	 * the correct order into the actual rule.
2858 	 * Some things that need to go out of order (prob, action etc.)
2859 	 * go into actbuf[].
2860 	 */
2861 	static uint32_t rulebuf[255], actbuf[255], cmdbuf[255];
2862 	int rblen, ablen, cblen;
2863 
2864 	ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
2865 	ipfw_insn *first_cmd;	/* first match pattern */
2866 
2867 	struct ip_fw *rule;
2868 
2869 	/*
2870 	 * various flags used to record that we entered some fields.
2871 	 */
2872 	ipfw_insn *have_state = NULL;	/* check-state or keep-state */
2873 	ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
2874 	size_t len;
2875 
2876 	int i;
2877 
2878 	int open_par = 0;	/* open parenthesis ( */
2879 
2880 	/* proto is here because it is used to fetch ports */
2881 	u_char proto = IPPROTO_IP;	/* default protocol */
2882 
2883 	double match_prob = 1; /* match probability, default is always match */
2884 
2885 	bzero(actbuf, sizeof(actbuf));		/* actions go here */
2886 	bzero(cmdbuf, sizeof(cmdbuf));
2887 	bzero(rulebuf, sizeof(rulebuf));
2888 
2889 	rule = (struct ip_fw *)rulebuf;
2890 	cmd = (ipfw_insn *)cmdbuf;
2891 	action = (ipfw_insn *)actbuf;
2892 
2893 	rblen = sizeof(rulebuf) / sizeof(rulebuf[0]);
2894 	rblen -= offsetof(struct ip_fw, cmd) / sizeof(rulebuf[0]);
2895 	ablen = sizeof(actbuf) / sizeof(actbuf[0]);
2896 	cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
2897 	cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
2898 
2899 #define	CHECK_RBUFLEN(len)	{ CHECK_LENGTH(rblen, len); rblen -= len; }
2900 #define	CHECK_ACTLEN		CHECK_LENGTH(ablen, action->len)
2901 
2902 	av++;
2903 
2904 	/* [rule N]	-- Rule number optional */
2905 	if (av[0] && isdigit(**av)) {
2906 		rule->rulenum = atoi(*av);
2907 		av++;
2908 	}
2909 
2910 	/* [set N]	-- set number (0..RESVD_SET), optional */
2911 	if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
2912 		int set = strtoul(av[1], NULL, 10);
2913 		if (set < 0 || set > RESVD_SET)
2914 			errx(EX_DATAERR, "illegal set %s", av[1]);
2915 		rule->set = set;
2916 		av += 2;
2917 	}
2918 
2919 	/* [prob D]	-- match probability, optional */
2920 	if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
2921 		match_prob = strtod(av[1], NULL);
2922 
2923 		if (match_prob <= 0 || match_prob > 1)
2924 			errx(EX_DATAERR, "illegal match prob. %s", av[1]);
2925 		av += 2;
2926 	}
2927 
2928 	/* action	-- mandatory */
2929 	NEED1("missing action");
2930 	i = match_token(rule_actions, *av);
2931 	av++;
2932 	action->len = 1;	/* default */
2933 	CHECK_ACTLEN;
2934 	switch(i) {
2935 	case TOK_CHECKSTATE:
2936 		have_state = action;
2937 		action->opcode = O_CHECK_STATE;
2938 		break;
2939 
2940 	case TOK_ACCEPT:
2941 		action->opcode = O_ACCEPT;
2942 		break;
2943 
2944 	case TOK_DENY:
2945 		action->opcode = O_DENY;
2946 		action->arg1 = 0;
2947 		break;
2948 
2949 	case TOK_REJECT:
2950 		action->opcode = O_REJECT;
2951 		action->arg1 = ICMP_UNREACH_HOST;
2952 		break;
2953 
2954 	case TOK_RESET:
2955 		action->opcode = O_REJECT;
2956 		action->arg1 = ICMP_REJECT_RST;
2957 		break;
2958 
2959 	case TOK_RESET6:
2960 		action->opcode = O_UNREACH6;
2961 		action->arg1 = ICMP6_UNREACH_RST;
2962 		break;
2963 
2964 	case TOK_UNREACH:
2965 		action->opcode = O_REJECT;
2966 		NEED1("missing reject code");
2967 		fill_reject_code(&action->arg1, *av);
2968 		av++;
2969 		break;
2970 
2971 	case TOK_UNREACH6:
2972 		action->opcode = O_UNREACH6;
2973 		NEED1("missing unreach code");
2974 		fill_unreach6_code(&action->arg1, *av);
2975 		av++;
2976 		break;
2977 
2978 	case TOK_COUNT:
2979 		action->opcode = O_COUNT;
2980 		break;
2981 
2982 	case TOK_NAT:
2983 		action->opcode = O_NAT;
2984 		action->len = F_INSN_SIZE(ipfw_insn_nat);
2985 		CHECK_ACTLEN;
2986 		if (_substrcmp(*av, "global") == 0) {
2987 			action->arg1 = 0;
2988 			av++;
2989 			break;
2990 		} else
2991 			goto chkarg;
2992 
2993 	case TOK_QUEUE:
2994 		action->opcode = O_QUEUE;
2995 		goto chkarg;
2996 	case TOK_PIPE:
2997 		action->opcode = O_PIPE;
2998 		goto chkarg;
2999 	case TOK_SKIPTO:
3000 		action->opcode = O_SKIPTO;
3001 		goto chkarg;
3002 	case TOK_NETGRAPH:
3003 		action->opcode = O_NETGRAPH;
3004 		goto chkarg;
3005 	case TOK_NGTEE:
3006 		action->opcode = O_NGTEE;
3007 		goto chkarg;
3008 	case TOK_DIVERT:
3009 		action->opcode = O_DIVERT;
3010 		goto chkarg;
3011 	case TOK_TEE:
3012 		action->opcode = O_TEE;
3013 		goto chkarg;
3014 	case TOK_CALL:
3015 		action->opcode = O_CALLRETURN;
3016 chkarg:
3017 		if (!av[0])
3018 			errx(EX_USAGE, "missing argument for %s", *(av - 1));
3019 		if (isdigit(**av)) {
3020 			action->arg1 = strtoul(*av, NULL, 10);
3021 			if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
3022 				errx(EX_DATAERR, "illegal argument for %s",
3023 				    *(av - 1));
3024 		} else if (_substrcmp(*av, "tablearg") == 0) {
3025 			action->arg1 = IP_FW_TABLEARG;
3026 		} else if (i == TOK_DIVERT || i == TOK_TEE) {
3027 			struct servent *s;
3028 			setservent(1);
3029 			s = getservbyname(av[0], "divert");
3030 			if (s != NULL)
3031 				action->arg1 = ntohs(s->s_port);
3032 			else
3033 				errx(EX_DATAERR, "illegal divert/tee port");
3034 		} else
3035 			errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
3036 		av++;
3037 		break;
3038 
3039 	case TOK_FORWARD: {
3040 		/*
3041 		 * Locate the address-port separator (':' or ',').
3042 		 * Could be one of the following:
3043 		 *	hostname:port
3044 		 *	IPv4 a.b.c.d,port
3045 		 *	IPv4 a.b.c.d:port
3046 		 *	IPv6 w:x:y::z,port
3047 		 * The ':' can only be used with hostname and IPv4 address.
3048 		 * XXX-BZ Should we also support [w:x:y::z]:port?
3049 		 */
3050 		struct sockaddr_storage result;
3051 		struct addrinfo *res;
3052 		char *s, *end;
3053 		int family;
3054 		u_short port_number;
3055 
3056 		NEED1("missing forward address[:port]");
3057 
3058 		/*
3059 		 * locate the address-port separator (':' or ',')
3060 		 */
3061 		s = strchr(*av, ',');
3062 		if (s == NULL) {
3063 			/* Distinguish between IPv4:port and IPv6 cases. */
3064 			s = strchr(*av, ':');
3065 			if (s && strchr(s+1, ':'))
3066 				s = NULL; /* no port */
3067 		}
3068 
3069 		port_number = 0;
3070 		if (s != NULL) {
3071 			/* Terminate host portion and set s to start of port. */
3072 			*(s++) = '\0';
3073 			i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
3074 			if (s == end)
3075 				errx(EX_DATAERR,
3076 				    "illegal forwarding port ``%s''", s);
3077 			port_number = (u_short)i;
3078 		}
3079 
3080 		if (_substrcmp(*av, "tablearg") == 0) {
3081 			family = PF_INET;
3082 			((struct sockaddr_in*)&result)->sin_addr.s_addr =
3083 			    INADDR_ANY;
3084 		} else {
3085 			/*
3086 			 * Resolve the host name or address to a family and a
3087 			 * network representation of the address.
3088 			 */
3089 			if (getaddrinfo(*av, NULL, NULL, &res))
3090 				errx(EX_DATAERR, NULL);
3091 			/* Just use the first host in the answer. */
3092 			family = res->ai_family;
3093 			memcpy(&result, res->ai_addr, res->ai_addrlen);
3094 			freeaddrinfo(res);
3095 		}
3096 
3097  		if (family == PF_INET) {
3098 			ipfw_insn_sa *p = (ipfw_insn_sa *)action;
3099 
3100 			action->opcode = O_FORWARD_IP;
3101 			action->len = F_INSN_SIZE(ipfw_insn_sa);
3102 			CHECK_ACTLEN;
3103 
3104 			/*
3105 			 * In the kernel we assume AF_INET and use only
3106 			 * sin_port and sin_addr. Remember to set sin_len as
3107 			 * the routing code seems to use it too.
3108 			 */
3109 			p->sa.sin_len = sizeof(struct sockaddr_in);
3110 			p->sa.sin_family = AF_INET;
3111 			p->sa.sin_port = port_number;
3112 			p->sa.sin_addr.s_addr =
3113 			     ((struct sockaddr_in *)&result)->sin_addr.s_addr;
3114 		} else if (family == PF_INET6) {
3115 			ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
3116 
3117 			action->opcode = O_FORWARD_IP6;
3118 			action->len = F_INSN_SIZE(ipfw_insn_sa6);
3119 			CHECK_ACTLEN;
3120 
3121 			p->sa.sin6_len = sizeof(struct sockaddr_in6);
3122 			p->sa.sin6_family = AF_INET6;
3123 			p->sa.sin6_port = port_number;
3124 			p->sa.sin6_flowinfo = 0;
3125 			p->sa.sin6_scope_id = 0;
3126 			/* No table support for v6 yet. */
3127 			bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
3128 			    &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
3129 		} else {
3130 			errx(EX_DATAERR, "Invalid address family in forward action");
3131 		}
3132 		av++;
3133 		break;
3134 	    }
3135 	case TOK_COMMENT:
3136 		/* pretend it is a 'count' rule followed by the comment */
3137 		action->opcode = O_COUNT;
3138 		av--;		/* go back... */
3139 		break;
3140 
3141 	case TOK_SETFIB:
3142 	    {
3143 		int numfibs;
3144 		size_t intsize = sizeof(int);
3145 
3146 		action->opcode = O_SETFIB;
3147 		NEED1("missing fib number");
3148 		if (_substrcmp(*av, "tablearg") == 0) {
3149 			action->arg1 = IP_FW_TABLEARG;
3150 		} else {
3151 		        action->arg1 = strtoul(*av, NULL, 10);
3152 			if (sysctlbyname("net.fibs", &numfibs, &intsize,
3153 			    NULL, 0) == -1)
3154 				errx(EX_DATAERR, "fibs not suported.\n");
3155 			if (action->arg1 >= numfibs)  /* Temporary */
3156 				errx(EX_DATAERR, "fib too large.\n");
3157 		}
3158 		av++;
3159 		break;
3160 	    }
3161 
3162 	case TOK_SETDSCP:
3163 	    {
3164 		int code;
3165 
3166 		action->opcode = O_SETDSCP;
3167 		NEED1("missing DSCP code");
3168 		if (_substrcmp(*av, "tablearg") == 0) {
3169 			action->arg1 = IP_FW_TABLEARG;
3170 		} else if (isalpha(*av[0])) {
3171 			if ((code = match_token(f_ipdscp, *av)) == -1)
3172 				errx(EX_DATAERR, "Unknown DSCP code");
3173 			action->arg1 = code;
3174 		} else
3175 		        action->arg1 = strtoul(*av, NULL, 10);
3176 		av++;
3177 		break;
3178 	    }
3179 
3180 	case TOK_REASS:
3181 		action->opcode = O_REASS;
3182 		break;
3183 
3184 	case TOK_RETURN:
3185 		fill_cmd(action, O_CALLRETURN, F_NOT, 0);
3186 		break;
3187 
3188 	default:
3189 		errx(EX_DATAERR, "invalid action %s\n", av[-1]);
3190 	}
3191 	action = next_cmd(action, &ablen);
3192 
3193 	/*
3194 	 * [altq queuename] -- altq tag, optional
3195 	 * [log [logamount N]]	-- log, optional
3196 	 *
3197 	 * If they exist, it go first in the cmdbuf, but then it is
3198 	 * skipped in the copy section to the end of the buffer.
3199 	 */
3200 	while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
3201 		av++;
3202 		switch (i) {
3203 		case TOK_LOG:
3204 		    {
3205 			ipfw_insn_log *c = (ipfw_insn_log *)cmd;
3206 			int l;
3207 
3208 			if (have_log)
3209 				errx(EX_DATAERR,
3210 				    "log cannot be specified more than once");
3211 			have_log = (ipfw_insn *)c;
3212 			cmd->len = F_INSN_SIZE(ipfw_insn_log);
3213 			CHECK_CMDLEN;
3214 			cmd->opcode = O_LOG;
3215 			if (av[0] && _substrcmp(*av, "logamount") == 0) {
3216 				av++;
3217 				NEED1("logamount requires argument");
3218 				l = atoi(*av);
3219 				if (l < 0)
3220 					errx(EX_DATAERR,
3221 					    "logamount must be positive");
3222 				c->max_log = l;
3223 				av++;
3224 			} else {
3225 				len = sizeof(c->max_log);
3226 				if (sysctlbyname("net.inet.ip.fw.verbose_limit",
3227 				    &c->max_log, &len, NULL, 0) == -1) {
3228 					if (co.test_only) {
3229 						c->max_log = 0;
3230 						break;
3231 					}
3232 					errx(1, "sysctlbyname(\"%s\")",
3233 					    "net.inet.ip.fw.verbose_limit");
3234 				}
3235 			}
3236 		    }
3237 			break;
3238 
3239 #ifndef NO_ALTQ
3240 		case TOK_ALTQ:
3241 		    {
3242 			ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
3243 
3244 			NEED1("missing altq queue name");
3245 			if (have_altq)
3246 				errx(EX_DATAERR,
3247 				    "altq cannot be specified more than once");
3248 			have_altq = (ipfw_insn *)a;
3249 			cmd->len = F_INSN_SIZE(ipfw_insn_altq);
3250 			CHECK_CMDLEN;
3251 			cmd->opcode = O_ALTQ;
3252 			a->qid = altq_name_to_qid(*av);
3253 			av++;
3254 		    }
3255 			break;
3256 #endif
3257 
3258 		case TOK_TAG:
3259 		case TOK_UNTAG: {
3260 			uint16_t tag;
3261 
3262 			if (have_tag)
3263 				errx(EX_USAGE, "tag and untag cannot be "
3264 				    "specified more than once");
3265 			GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
3266 			   rule_action_params);
3267 			have_tag = cmd;
3268 			fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
3269 			av++;
3270 			break;
3271 		}
3272 
3273 		default:
3274 			abort();
3275 		}
3276 		cmd = next_cmd(cmd, &cblen);
3277 	}
3278 
3279 	if (have_state)	/* must be a check-state, we are done */
3280 		goto done;
3281 
3282 #define OR_START(target)					\
3283 	if (av[0] && (*av[0] == '(' || *av[0] == '{')) { 	\
3284 		if (open_par)					\
3285 			errx(EX_USAGE, "nested \"(\" not allowed\n"); \
3286 		prev = NULL;					\
3287 		open_par = 1;					\
3288 		if ( (av[0])[1] == '\0') {			\
3289 			av++;					\
3290 		} else						\
3291 			(*av)++;				\
3292 	}							\
3293 	target:							\
3294 
3295 
3296 #define	CLOSE_PAR						\
3297 	if (open_par) {						\
3298 		if (av[0] && (					\
3299 		    strcmp(*av, ")") == 0 ||			\
3300 		    strcmp(*av, "}") == 0)) {			\
3301 			prev = NULL;				\
3302 			open_par = 0;				\
3303 			av++;					\
3304 		} else						\
3305 			errx(EX_USAGE, "missing \")\"\n");	\
3306 	}
3307 
3308 #define NOT_BLOCK						\
3309 	if (av[0] && _substrcmp(*av, "not") == 0) {		\
3310 		if (cmd->len & F_NOT)				\
3311 			errx(EX_USAGE, "double \"not\" not allowed\n"); \
3312 		cmd->len |= F_NOT;				\
3313 		av++;						\
3314 	}
3315 
3316 #define OR_BLOCK(target)					\
3317 	if (av[0] && _substrcmp(*av, "or") == 0) {		\
3318 		if (prev == NULL || open_par == 0)		\
3319 			errx(EX_DATAERR, "invalid OR block");	\
3320 		prev->len |= F_OR;				\
3321 		av++;					\
3322 		goto target;					\
3323 	}							\
3324 	CLOSE_PAR;
3325 
3326 	first_cmd = cmd;
3327 
3328 #if 0
3329 	/*
3330 	 * MAC addresses, optional.
3331 	 * If we have this, we skip the part "proto from src to dst"
3332 	 * and jump straight to the option parsing.
3333 	 */
3334 	NOT_BLOCK;
3335 	NEED1("missing protocol");
3336 	if (_substrcmp(*av, "MAC") == 0 ||
3337 	    _substrcmp(*av, "mac") == 0) {
3338 		av++;			/* the "MAC" keyword */
3339 		add_mac(cmd, av);	/* exits in case of errors */
3340 		cmd = next_cmd(cmd);
3341 		av += 2;		/* dst-mac and src-mac */
3342 		NOT_BLOCK;
3343 		NEED1("missing mac type");
3344 		if (add_mactype(cmd, av[0]))
3345 			cmd = next_cmd(cmd);
3346 		av++;			/* any or mac-type */
3347 		goto read_options;
3348 	}
3349 #endif
3350 
3351 	/*
3352 	 * protocol, mandatory
3353 	 */
3354     OR_START(get_proto);
3355 	NOT_BLOCK;
3356 	NEED1("missing protocol");
3357 	if (add_proto_compat(cmd, *av, &proto)) {
3358 		av++;
3359 		if (F_LEN(cmd) != 0) {
3360 			prev = cmd;
3361 			cmd = next_cmd(cmd, &cblen);
3362 		}
3363 	} else if (first_cmd != cmd) {
3364 		errx(EX_DATAERR, "invalid protocol ``%s''", *av);
3365 	} else
3366 		goto read_options;
3367     OR_BLOCK(get_proto);
3368 
3369 	/*
3370 	 * "from", mandatory
3371 	 */
3372 	if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
3373 		errx(EX_USAGE, "missing ``from''");
3374 	av++;
3375 
3376 	/*
3377 	 * source IP, mandatory
3378 	 */
3379     OR_START(source_ip);
3380 	NOT_BLOCK;	/* optional "not" */
3381 	NEED1("missing source address");
3382 	if (add_src(cmd, *av, proto, cblen)) {
3383 		av++;
3384 		if (F_LEN(cmd) != 0) {	/* ! any */
3385 			prev = cmd;
3386 			cmd = next_cmd(cmd, &cblen);
3387 		}
3388 	} else
3389 		errx(EX_USAGE, "bad source address %s", *av);
3390     OR_BLOCK(source_ip);
3391 
3392 	/*
3393 	 * source ports, optional
3394 	 */
3395 	NOT_BLOCK;	/* optional "not" */
3396 	if ( av[0] != NULL ) {
3397 		if (_substrcmp(*av, "any") == 0 ||
3398 		    add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
3399 			av++;
3400 			if (F_LEN(cmd) != 0)
3401 				cmd = next_cmd(cmd, &cblen);
3402 		}
3403 	}
3404 
3405 	/*
3406 	 * "to", mandatory
3407 	 */
3408 	if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
3409 		errx(EX_USAGE, "missing ``to''");
3410 	av++;
3411 
3412 	/*
3413 	 * destination, mandatory
3414 	 */
3415     OR_START(dest_ip);
3416 	NOT_BLOCK;	/* optional "not" */
3417 	NEED1("missing dst address");
3418 	if (add_dst(cmd, *av, proto, cblen)) {
3419 		av++;
3420 		if (F_LEN(cmd) != 0) {	/* ! any */
3421 			prev = cmd;
3422 			cmd = next_cmd(cmd, &cblen);
3423 		}
3424 	} else
3425 		errx( EX_USAGE, "bad destination address %s", *av);
3426     OR_BLOCK(dest_ip);
3427 
3428 	/*
3429 	 * dest. ports, optional
3430 	 */
3431 	NOT_BLOCK;	/* optional "not" */
3432 	if (av[0]) {
3433 		if (_substrcmp(*av, "any") == 0 ||
3434 		    add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
3435 			av++;
3436 			if (F_LEN(cmd) != 0)
3437 				cmd = next_cmd(cmd, &cblen);
3438 		}
3439 	}
3440 
3441 read_options:
3442 	if (av[0] && first_cmd == cmd) {
3443 		/*
3444 		 * nothing specified so far, store in the rule to ease
3445 		 * printout later.
3446 		 */
3447 		 rule->_pad = 1;
3448 	}
3449 	prev = NULL;
3450 	while ( av[0] != NULL ) {
3451 		char *s;
3452 		ipfw_insn_u32 *cmd32;	/* alias for cmd */
3453 
3454 		s = *av;
3455 		cmd32 = (ipfw_insn_u32 *)cmd;
3456 
3457 		if (*s == '!') {	/* alternate syntax for NOT */
3458 			if (cmd->len & F_NOT)
3459 				errx(EX_USAGE, "double \"not\" not allowed\n");
3460 			cmd->len = F_NOT;
3461 			s++;
3462 		}
3463 		i = match_token(rule_options, s);
3464 		av++;
3465 		switch(i) {
3466 		case TOK_NOT:
3467 			if (cmd->len & F_NOT)
3468 				errx(EX_USAGE, "double \"not\" not allowed\n");
3469 			cmd->len = F_NOT;
3470 			break;
3471 
3472 		case TOK_OR:
3473 			if (open_par == 0 || prev == NULL)
3474 				errx(EX_USAGE, "invalid \"or\" block\n");
3475 			prev->len |= F_OR;
3476 			break;
3477 
3478 		case TOK_STARTBRACE:
3479 			if (open_par)
3480 				errx(EX_USAGE, "+nested \"(\" not allowed\n");
3481 			open_par = 1;
3482 			break;
3483 
3484 		case TOK_ENDBRACE:
3485 			if (!open_par)
3486 				errx(EX_USAGE, "+missing \")\"\n");
3487 			open_par = 0;
3488 			prev = NULL;
3489 			break;
3490 
3491 		case TOK_IN:
3492 			fill_cmd(cmd, O_IN, 0, 0);
3493 			break;
3494 
3495 		case TOK_OUT:
3496 			cmd->len ^= F_NOT; /* toggle F_NOT */
3497 			fill_cmd(cmd, O_IN, 0, 0);
3498 			break;
3499 
3500 		case TOK_DIVERTED:
3501 			fill_cmd(cmd, O_DIVERTED, 0, 3);
3502 			break;
3503 
3504 		case TOK_DIVERTEDLOOPBACK:
3505 			fill_cmd(cmd, O_DIVERTED, 0, 1);
3506 			break;
3507 
3508 		case TOK_DIVERTEDOUTPUT:
3509 			fill_cmd(cmd, O_DIVERTED, 0, 2);
3510 			break;
3511 
3512 		case TOK_FRAG:
3513 			fill_cmd(cmd, O_FRAG, 0, 0);
3514 			break;
3515 
3516 		case TOK_LAYER2:
3517 			fill_cmd(cmd, O_LAYER2, 0, 0);
3518 			break;
3519 
3520 		case TOK_XMIT:
3521 		case TOK_RECV:
3522 		case TOK_VIA:
3523 			NEED1("recv, xmit, via require interface name"
3524 				" or address");
3525 			fill_iface((ipfw_insn_if *)cmd, av[0], cblen);
3526 			av++;
3527 			if (F_LEN(cmd) == 0)	/* not a valid address */
3528 				break;
3529 			if (i == TOK_XMIT)
3530 				cmd->opcode = O_XMIT;
3531 			else if (i == TOK_RECV)
3532 				cmd->opcode = O_RECV;
3533 			else if (i == TOK_VIA)
3534 				cmd->opcode = O_VIA;
3535 			break;
3536 
3537 		case TOK_ICMPTYPES:
3538 			NEED1("icmptypes requires list of types");
3539 			fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
3540 			av++;
3541 			break;
3542 
3543 		case TOK_ICMP6TYPES:
3544 			NEED1("icmptypes requires list of types");
3545 			fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
3546 			av++;
3547 			break;
3548 
3549 		case TOK_IPTTL:
3550 			NEED1("ipttl requires TTL");
3551 			if (strpbrk(*av, "-,")) {
3552 			    if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
3553 				errx(EX_DATAERR, "invalid ipttl %s", *av);
3554 			} else
3555 			    fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
3556 			av++;
3557 			break;
3558 
3559 		case TOK_IPID:
3560 			NEED1("ipid requires id");
3561 			if (strpbrk(*av, "-,")) {
3562 			    if (!add_ports(cmd, *av, 0, O_IPID, cblen))
3563 				errx(EX_DATAERR, "invalid ipid %s", *av);
3564 			} else
3565 			    fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
3566 			av++;
3567 			break;
3568 
3569 		case TOK_IPLEN:
3570 			NEED1("iplen requires length");
3571 			if (strpbrk(*av, "-,")) {
3572 			    if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
3573 				errx(EX_DATAERR, "invalid ip len %s", *av);
3574 			} else
3575 			    fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
3576 			av++;
3577 			break;
3578 
3579 		case TOK_IPVER:
3580 			NEED1("ipver requires version");
3581 			fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
3582 			av++;
3583 			break;
3584 
3585 		case TOK_IPPRECEDENCE:
3586 			NEED1("ipprecedence requires value");
3587 			fill_cmd(cmd, O_IPPRECEDENCE, 0,
3588 			    (strtoul(*av, NULL, 0) & 7) << 5);
3589 			av++;
3590 			break;
3591 
3592 		case TOK_DSCP:
3593 			NEED1("missing DSCP code");
3594 			fill_dscp(cmd, *av, cblen);
3595 			av++;
3596 			break;
3597 
3598 		case TOK_IPOPTS:
3599 			NEED1("missing argument for ipoptions");
3600 			fill_flags(cmd, O_IPOPT, f_ipopts, *av);
3601 			av++;
3602 			break;
3603 
3604 		case TOK_IPTOS:
3605 			NEED1("missing argument for iptos");
3606 			fill_flags(cmd, O_IPTOS, f_iptos, *av);
3607 			av++;
3608 			break;
3609 
3610 		case TOK_UID:
3611 			NEED1("uid requires argument");
3612 		    {
3613 			char *end;
3614 			uid_t uid;
3615 			struct passwd *pwd;
3616 
3617 			cmd->opcode = O_UID;
3618 			uid = strtoul(*av, &end, 0);
3619 			pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
3620 			if (pwd == NULL)
3621 				errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
3622 			cmd32->d[0] = pwd->pw_uid;
3623 			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3624 			av++;
3625 		    }
3626 			break;
3627 
3628 		case TOK_GID:
3629 			NEED1("gid requires argument");
3630 		    {
3631 			char *end;
3632 			gid_t gid;
3633 			struct group *grp;
3634 
3635 			cmd->opcode = O_GID;
3636 			gid = strtoul(*av, &end, 0);
3637 			grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
3638 			if (grp == NULL)
3639 				errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
3640 			cmd32->d[0] = grp->gr_gid;
3641 			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3642 			av++;
3643 		    }
3644 			break;
3645 
3646 		case TOK_JAIL:
3647 			NEED1("jail requires argument");
3648 		    {
3649 			char *end;
3650 			int jid;
3651 
3652 			cmd->opcode = O_JAIL;
3653 			jid = (int)strtol(*av, &end, 0);
3654 			if (jid < 0 || *end != '\0')
3655 				errx(EX_DATAERR, "jail requires prison ID");
3656 			cmd32->d[0] = (uint32_t)jid;
3657 			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3658 			av++;
3659 		    }
3660 			break;
3661 
3662 		case TOK_ESTAB:
3663 			fill_cmd(cmd, O_ESTAB, 0, 0);
3664 			break;
3665 
3666 		case TOK_SETUP:
3667 			fill_cmd(cmd, O_TCPFLAGS, 0,
3668 				(TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
3669 			break;
3670 
3671 		case TOK_TCPDATALEN:
3672 			NEED1("tcpdatalen requires length");
3673 			if (strpbrk(*av, "-,")) {
3674 			    if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
3675 				errx(EX_DATAERR, "invalid tcpdata len %s", *av);
3676 			} else
3677 			    fill_cmd(cmd, O_TCPDATALEN, 0,
3678 				    strtoul(*av, NULL, 0));
3679 			av++;
3680 			break;
3681 
3682 		case TOK_TCPOPTS:
3683 			NEED1("missing argument for tcpoptions");
3684 			fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
3685 			av++;
3686 			break;
3687 
3688 		case TOK_TCPSEQ:
3689 		case TOK_TCPACK:
3690 			NEED1("tcpseq/tcpack requires argument");
3691 			cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3692 			cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
3693 			cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
3694 			av++;
3695 			break;
3696 
3697 		case TOK_TCPWIN:
3698 			NEED1("tcpwin requires length");
3699 			if (strpbrk(*av, "-,")) {
3700 			    if (!add_ports(cmd, *av, 0, O_TCPWIN, cblen))
3701 				errx(EX_DATAERR, "invalid tcpwin len %s", *av);
3702 			} else
3703 			    fill_cmd(cmd, O_TCPWIN, 0,
3704 				    strtoul(*av, NULL, 0));
3705 			av++;
3706 			break;
3707 
3708 		case TOK_TCPFLAGS:
3709 			NEED1("missing argument for tcpflags");
3710 			cmd->opcode = O_TCPFLAGS;
3711 			fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
3712 			av++;
3713 			break;
3714 
3715 		case TOK_KEEPSTATE:
3716 			if (open_par)
3717 				errx(EX_USAGE, "keep-state cannot be part "
3718 				    "of an or block");
3719 			if (have_state)
3720 				errx(EX_USAGE, "only one of keep-state "
3721 					"and limit is allowed");
3722 			have_state = cmd;
3723 			fill_cmd(cmd, O_KEEP_STATE, 0, 0);
3724 			break;
3725 
3726 		case TOK_LIMIT: {
3727 			ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
3728 			int val;
3729 
3730 			if (open_par)
3731 				errx(EX_USAGE,
3732 				    "limit cannot be part of an or block");
3733 			if (have_state)
3734 				errx(EX_USAGE, "only one of keep-state and "
3735 				    "limit is allowed");
3736 			have_state = cmd;
3737 
3738 			cmd->len = F_INSN_SIZE(ipfw_insn_limit);
3739 			CHECK_CMDLEN;
3740 			cmd->opcode = O_LIMIT;
3741 			c->limit_mask = c->conn_limit = 0;
3742 
3743 			while ( av[0] != NULL ) {
3744 				if ((val = match_token(limit_masks, *av)) <= 0)
3745 					break;
3746 				c->limit_mask |= val;
3747 				av++;
3748 			}
3749 
3750 			if (c->limit_mask == 0)
3751 				errx(EX_USAGE, "limit: missing limit mask");
3752 
3753 			GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
3754 			    TOK_LIMIT, rule_options);
3755 
3756 			av++;
3757 			break;
3758 		}
3759 
3760 		case TOK_PROTO:
3761 			NEED1("missing protocol");
3762 			if (add_proto(cmd, *av, &proto)) {
3763 				av++;
3764 			} else
3765 				errx(EX_DATAERR, "invalid protocol ``%s''",
3766 				    *av);
3767 			break;
3768 
3769 		case TOK_SRCIP:
3770 			NEED1("missing source IP");
3771 			if (add_srcip(cmd, *av, cblen)) {
3772 				av++;
3773 			}
3774 			break;
3775 
3776 		case TOK_DSTIP:
3777 			NEED1("missing destination IP");
3778 			if (add_dstip(cmd, *av, cblen)) {
3779 				av++;
3780 			}
3781 			break;
3782 
3783 		case TOK_SRCIP6:
3784 			NEED1("missing source IP6");
3785 			if (add_srcip6(cmd, *av, cblen)) {
3786 				av++;
3787 			}
3788 			break;
3789 
3790 		case TOK_DSTIP6:
3791 			NEED1("missing destination IP6");
3792 			if (add_dstip6(cmd, *av, cblen)) {
3793 				av++;
3794 			}
3795 			break;
3796 
3797 		case TOK_SRCPORT:
3798 			NEED1("missing source port");
3799 			if (_substrcmp(*av, "any") == 0 ||
3800 			    add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
3801 				av++;
3802 			} else
3803 				errx(EX_DATAERR, "invalid source port %s", *av);
3804 			break;
3805 
3806 		case TOK_DSTPORT:
3807 			NEED1("missing destination port");
3808 			if (_substrcmp(*av, "any") == 0 ||
3809 			    add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
3810 				av++;
3811 			} else
3812 				errx(EX_DATAERR, "invalid destination port %s",
3813 				    *av);
3814 			break;
3815 
3816 		case TOK_MAC:
3817 			if (add_mac(cmd, av, cblen))
3818 				av += 2;
3819 			break;
3820 
3821 		case TOK_MACTYPE:
3822 			NEED1("missing mac type");
3823 			if (!add_mactype(cmd, *av, cblen))
3824 				errx(EX_DATAERR, "invalid mac type %s", *av);
3825 			av++;
3826 			break;
3827 
3828 		case TOK_VERREVPATH:
3829 			fill_cmd(cmd, O_VERREVPATH, 0, 0);
3830 			break;
3831 
3832 		case TOK_VERSRCREACH:
3833 			fill_cmd(cmd, O_VERSRCREACH, 0, 0);
3834 			break;
3835 
3836 		case TOK_ANTISPOOF:
3837 			fill_cmd(cmd, O_ANTISPOOF, 0, 0);
3838 			break;
3839 
3840 		case TOK_IPSEC:
3841 			fill_cmd(cmd, O_IPSEC, 0, 0);
3842 			break;
3843 
3844 		case TOK_IPV6:
3845 			fill_cmd(cmd, O_IP6, 0, 0);
3846 			break;
3847 
3848 		case TOK_IPV4:
3849 			fill_cmd(cmd, O_IP4, 0, 0);
3850 			break;
3851 
3852 		case TOK_EXT6HDR:
3853 			fill_ext6hdr( cmd, *av );
3854 			av++;
3855 			break;
3856 
3857 		case TOK_FLOWID:
3858 			if (proto != IPPROTO_IPV6 )
3859 				errx( EX_USAGE, "flow-id filter is active "
3860 				    "only for ipv6 protocol\n");
3861 			fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
3862 			av++;
3863 			break;
3864 
3865 		case TOK_COMMENT:
3866 			fill_comment(cmd, av, cblen);
3867 			av[0]=NULL;
3868 			break;
3869 
3870 		case TOK_TAGGED:
3871 			if (av[0] && strpbrk(*av, "-,")) {
3872 				if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
3873 					errx(EX_DATAERR, "tagged: invalid tag"
3874 					    " list: %s", *av);
3875 			}
3876 			else {
3877 				uint16_t tag;
3878 
3879 				GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
3880 				    TOK_TAGGED, rule_options);
3881 				fill_cmd(cmd, O_TAGGED, 0, tag);
3882 			}
3883 			av++;
3884 			break;
3885 
3886 		case TOK_FIB:
3887 			NEED1("fib requires fib number");
3888 			fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
3889 			av++;
3890 			break;
3891 		case TOK_SOCKARG:
3892 			fill_cmd(cmd, O_SOCKARG, 0, 0);
3893 			break;
3894 
3895 		case TOK_LOOKUP: {
3896 			ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
3897 			char *p;
3898 			int j;
3899 
3900 			if (!av[0] || !av[1])
3901 				errx(EX_USAGE, "format: lookup argument tablenum");
3902 			cmd->opcode = O_IP_DST_LOOKUP;
3903 			cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
3904 			i = match_token(rule_options, *av);
3905 			for (j = 0; lookup_key[j] >= 0 ; j++) {
3906 				if (i == lookup_key[j])
3907 					break;
3908 			}
3909 			if (lookup_key[j] <= 0)
3910 				errx(EX_USAGE, "format: cannot lookup on %s", *av);
3911 			__PAST_END(c->d, 1) = j; // i converted to option
3912 			av++;
3913 			cmd->arg1 = strtoul(*av, &p, 0);
3914 			if (p && *p)
3915 				errx(EX_USAGE, "format: lookup argument tablenum");
3916 			av++;
3917 		    }
3918 			break;
3919 
3920 		default:
3921 			errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
3922 		}
3923 		if (F_LEN(cmd) > 0) {	/* prepare to advance */
3924 			prev = cmd;
3925 			cmd = next_cmd(cmd, &cblen);
3926 		}
3927 	}
3928 
3929 done:
3930 	/*
3931 	 * Now copy stuff into the rule.
3932 	 * If we have a keep-state option, the first instruction
3933 	 * must be a PROBE_STATE (which is generated here).
3934 	 * If we have a LOG option, it was stored as the first command,
3935 	 * and now must be moved to the top of the action part.
3936 	 */
3937 	dst = (ipfw_insn *)rule->cmd;
3938 
3939 	/*
3940 	 * First thing to write into the command stream is the match probability.
3941 	 */
3942 	if (match_prob != 1) { /* 1 means always match */
3943 		dst->opcode = O_PROB;
3944 		dst->len = 2;
3945 		*((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
3946 		dst += dst->len;
3947 	}
3948 
3949 	/*
3950 	 * generate O_PROBE_STATE if necessary
3951 	 */
3952 	if (have_state && have_state->opcode != O_CHECK_STATE) {
3953 		fill_cmd(dst, O_PROBE_STATE, 0, 0);
3954 		dst = next_cmd(dst, &rblen);
3955 	}
3956 
3957 	/* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
3958 	for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
3959 		i = F_LEN(src);
3960 		CHECK_RBUFLEN(i);
3961 
3962 		switch (src->opcode) {
3963 		case O_LOG:
3964 		case O_KEEP_STATE:
3965 		case O_LIMIT:
3966 		case O_ALTQ:
3967 		case O_TAG:
3968 			break;
3969 		default:
3970 			bcopy(src, dst, i * sizeof(uint32_t));
3971 			dst += i;
3972 		}
3973 	}
3974 
3975 	/*
3976 	 * put back the have_state command as last opcode
3977 	 */
3978 	if (have_state && have_state->opcode != O_CHECK_STATE) {
3979 		i = F_LEN(have_state);
3980 		CHECK_RBUFLEN(i);
3981 		bcopy(have_state, dst, i * sizeof(uint32_t));
3982 		dst += i;
3983 	}
3984 	/*
3985 	 * start action section
3986 	 */
3987 	rule->act_ofs = dst - rule->cmd;
3988 
3989 	/* put back O_LOG, O_ALTQ, O_TAG if necessary */
3990 	if (have_log) {
3991 		i = F_LEN(have_log);
3992 		CHECK_RBUFLEN(i);
3993 		bcopy(have_log, dst, i * sizeof(uint32_t));
3994 		dst += i;
3995 	}
3996 	if (have_altq) {
3997 		i = F_LEN(have_altq);
3998 		CHECK_RBUFLEN(i);
3999 		bcopy(have_altq, dst, i * sizeof(uint32_t));
4000 		dst += i;
4001 	}
4002 	if (have_tag) {
4003 		i = F_LEN(have_tag);
4004 		CHECK_RBUFLEN(i);
4005 		bcopy(have_tag, dst, i * sizeof(uint32_t));
4006 		dst += i;
4007 	}
4008 
4009 	/*
4010 	 * copy all other actions
4011 	 */
4012 	for (src = (ipfw_insn *)actbuf; src != action; src += i) {
4013 		i = F_LEN(src);
4014 		CHECK_RBUFLEN(i);
4015 		bcopy(src, dst, i * sizeof(uint32_t));
4016 		dst += i;
4017 	}
4018 
4019 	rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
4020 	i = (char *)dst - (char *)rule;
4021 	if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1)
4022 		err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
4023 	if (!co.do_quiet)
4024 		show_ipfw(rule, 0, 0);
4025 }
4026 
4027 /*
4028  * clear the counters or the log counters.
4029  */
4030 void
4031 ipfw_zero(int ac, char *av[], int optname /* 0 = IP_FW_ZERO, 1 = IP_FW_RESETLOG */)
4032 {
4033 	uint32_t arg, saved_arg;
4034 	int failed = EX_OK;
4035 	char const *errstr;
4036 	char const *name = optname ? "RESETLOG" : "ZERO";
4037 
4038 	optname = optname ? IP_FW_RESETLOG : IP_FW_ZERO;
4039 
4040 	av++; ac--;
4041 
4042 	if (!ac) {
4043 		/* clear all entries */
4044 		if (do_cmd(optname, NULL, 0) < 0)
4045 			err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name);
4046 		if (!co.do_quiet)
4047 			printf("%s.\n", optname == IP_FW_ZERO ?
4048 			    "Accounting cleared":"Logging counts reset");
4049 
4050 		return;
4051 	}
4052 
4053 	while (ac) {
4054 		/* Rule number */
4055 		if (isdigit(**av)) {
4056 			arg = strtonum(*av, 0, 0xffff, &errstr);
4057 			if (errstr)
4058 				errx(EX_DATAERR,
4059 				    "invalid rule number %s\n", *av);
4060 			saved_arg = arg;
4061 			if (co.use_set)
4062 				arg |= (1 << 24) | ((co.use_set - 1) << 16);
4063 			av++;
4064 			ac--;
4065 			if (do_cmd(optname, &arg, sizeof(arg))) {
4066 				warn("rule %u: setsockopt(IP_FW_%s)",
4067 				    saved_arg, name);
4068 				failed = EX_UNAVAILABLE;
4069 			} else if (!co.do_quiet)
4070 				printf("Entry %d %s.\n", saved_arg,
4071 				    optname == IP_FW_ZERO ?
4072 					"cleared" : "logging count reset");
4073 		} else {
4074 			errx(EX_USAGE, "invalid rule number ``%s''", *av);
4075 		}
4076 	}
4077 	if (failed != EX_OK)
4078 		exit(failed);
4079 }
4080 
4081 void
4082 ipfw_flush(int force)
4083 {
4084 	int cmd = co.do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
4085 
4086 	if (!force && !co.do_quiet) { /* need to ask user */
4087 		int c;
4088 
4089 		printf("Are you sure? [yn] ");
4090 		fflush(stdout);
4091 		do {
4092 			c = toupper(getc(stdin));
4093 			while (c != '\n' && getc(stdin) != '\n')
4094 				if (feof(stdin))
4095 					return; /* and do not flush */
4096 		} while (c != 'Y' && c != 'N');
4097 		printf("\n");
4098 		if (c == 'N')	/* user said no */
4099 			return;
4100 	}
4101 	if (co.do_pipe) {
4102 		dummynet_flush();
4103 		return;
4104 	}
4105 	/* `ipfw set N flush` - is the same that `ipfw delete set N` */
4106 	if (co.use_set) {
4107 		uint32_t arg = ((co.use_set - 1) & 0xffff) | (1 << 24);
4108 		if (do_cmd(IP_FW_DEL, &arg, sizeof(arg)) < 0)
4109 			err(EX_UNAVAILABLE, "setsockopt(IP_FW_DEL)");
4110 	} else if (do_cmd(cmd, NULL, 0) < 0)
4111 		err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
4112 		    co.do_pipe ? "DUMMYNET" : "FW");
4113 	if (!co.do_quiet)
4114 		printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
4115 }
4116 
4117 
4118 static void table_list(uint16_t num, int need_header);
4119 static void table_fill_xentry(char *arg, ipfw_table_xentry *xent);
4120 
4121 /*
4122  * This one handles all table-related commands
4123  * 	ipfw table N add addr[/masklen] [value]
4124  * 	ipfw table N delete addr[/masklen]
4125  * 	ipfw table {N | all} flush
4126  * 	ipfw table {N | all} list
4127  */
4128 void
4129 ipfw_table_handler(int ac, char *av[])
4130 {
4131 	ipfw_table_xentry xent;
4132 	int do_add;
4133 	int is_all;
4134 	size_t len;
4135 	uint32_t a;
4136 	uint32_t tables_max;
4137 
4138 	len = sizeof(tables_max);
4139 	if (sysctlbyname("net.inet.ip.fw.tables_max", &tables_max, &len,
4140 	    NULL, 0) == -1) {
4141 		if (co.test_only)
4142 			tables_max = 128; /* Old conservative default */
4143 		else
4144 			errx(1, "Can't determine maximum number of ipfw tables."
4145 			    " Perhaps you forgot to load ipfw module?");
4146 	}
4147 
4148 	memset(&xent, 0, sizeof(xent));
4149 
4150 	ac--; av++;
4151 	if (ac && isdigit(**av)) {
4152 		xent.tbl = atoi(*av);
4153 		is_all = 0;
4154 		ac--; av++;
4155 	} else if (ac && _substrcmp(*av, "all") == 0) {
4156 		xent.tbl = 0;
4157 		is_all = 1;
4158 		ac--; av++;
4159 	} else
4160 		errx(EX_USAGE, "table number or 'all' keyword required");
4161 	if (xent.tbl >= tables_max)
4162 		errx(EX_USAGE, "The table number exceeds the maximum allowed "
4163 			"value (%d)", tables_max - 1);
4164 	NEED1("table needs command");
4165 	if (is_all && _substrcmp(*av, "list") != 0
4166 		   && _substrcmp(*av, "flush") != 0)
4167 		errx(EX_USAGE, "table number required");
4168 
4169 	if (_substrcmp(*av, "add") == 0 ||
4170 	    _substrcmp(*av, "delete") == 0) {
4171 		do_add = **av == 'a';
4172 		ac--; av++;
4173 		if (!ac)
4174 			errx(EX_USAGE, "address required");
4175 
4176 		table_fill_xentry(*av, &xent);
4177 
4178 		ac--; av++;
4179 		if (do_add && ac) {
4180 			unsigned int tval;
4181 			/* isdigit is a bit of a hack here.. */
4182 			if (strchr(*av, (int)'.') == NULL && isdigit(**av))  {
4183 				xent.value = strtoul(*av, NULL, 0);
4184 			} else {
4185 				if (lookup_host(*av, (struct in_addr *)&tval) == 0) {
4186 					/* The value must be stored in host order	 *
4187 					 * so that the values < 65k can be distinguished */
4188 		       			xent.value = ntohl(tval);
4189 				} else {
4190 					errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
4191 				}
4192 			}
4193 		} else
4194 			xent.value = 0;
4195 		if (do_setcmd3(do_add ? IP_FW_TABLE_XADD : IP_FW_TABLE_XDEL,
4196 		    &xent, xent.len) < 0) {
4197 			/* If running silent, don't bomb out on these errors. */
4198 			if (!(co.do_quiet && (errno == (do_add ? EEXIST : ESRCH))))
4199 				err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)",
4200 				    do_add ? "XADD" : "XDEL");
4201 			/* In silent mode, react to a failed add by deleting */
4202 			if (do_add) {
4203 				do_setcmd3(IP_FW_TABLE_XDEL, &xent, xent.len);
4204 				if (do_setcmd3(IP_FW_TABLE_XADD, &xent, xent.len) < 0)
4205 					err(EX_OSERR,
4206 					    "setsockopt(IP_FW_TABLE_XADD)");
4207 			}
4208 		}
4209 	} else if (_substrcmp(*av, "flush") == 0) {
4210 		a = is_all ? tables_max : (uint32_t)(xent.tbl + 1);
4211 		do {
4212 			if (do_cmd(IP_FW_TABLE_FLUSH, &xent.tbl,
4213 			    sizeof(xent.tbl)) < 0)
4214 				err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)");
4215 		} while (++xent.tbl < a);
4216 	} else if (_substrcmp(*av, "list") == 0) {
4217 		a = is_all ? tables_max : (uint32_t)(xent.tbl + 1);
4218 		do {
4219 			table_list(xent.tbl, is_all);
4220 		} while (++xent.tbl < a);
4221 	} else
4222 		errx(EX_USAGE, "invalid table command %s", *av);
4223 }
4224 
4225 static void
4226 table_fill_xentry(char *arg, ipfw_table_xentry *xent)
4227 {
4228 	int addrlen, mask, masklen, type;
4229 	struct in6_addr *paddr;
4230 	uint32_t *pkey;
4231 	char *p;
4232 	uint32_t key;
4233 
4234 	mask = 0;
4235 	type = 0;
4236 	addrlen = 0;
4237 	masklen = 0;
4238 
4239 	/*
4240 	 * Let's try to guess type by agrument.
4241 	 * Possible types:
4242 	 * 1) IPv4[/mask]
4243 	 * 2) IPv6[/mask]
4244 	 * 3) interface name
4245 	 * 4) port, uid/gid or other u32 key (base 10 format)
4246 	 * 5) hostname
4247 	 */
4248 	paddr = &xent->k.addr6;
4249 	if (ishexnumber(*arg) != 0 || *arg == ':') {
4250 		/* Remove / if exists */
4251 		if ((p = strchr(arg, '/')) != NULL) {
4252 			*p = '\0';
4253 			mask = atoi(p + 1);
4254 		}
4255 
4256 		if (inet_pton(AF_INET, arg, paddr) == 1) {
4257 			if (p != NULL && mask > 32)
4258 				errx(EX_DATAERR, "bad IPv4 mask width: %s",
4259 				    p + 1);
4260 
4261 			type = IPFW_TABLE_CIDR;
4262 			masklen = p ? mask : 32;
4263 			addrlen = sizeof(struct in_addr);
4264 		} else if (inet_pton(AF_INET6, arg, paddr) == 1) {
4265 			if (IN6_IS_ADDR_V4COMPAT(paddr))
4266 				errx(EX_DATAERR,
4267 				    "Use IPv4 instead of v4-compatible");
4268 			if (p != NULL && mask > 128)
4269 				errx(EX_DATAERR, "bad IPv6 mask width: %s",
4270 				    p + 1);
4271 
4272 			type = IPFW_TABLE_CIDR;
4273 			masklen = p ? mask : 128;
4274 			addrlen = sizeof(struct in6_addr);
4275 		} else {
4276 			/* Port or any other key */
4277 			key = strtol(arg, &p, 10);
4278 			/* Skip non-base 10 entries like 'fa1' */
4279 			if (p != arg) {
4280 				pkey = (uint32_t *)paddr;
4281 				*pkey = htonl(key);
4282 				type = IPFW_TABLE_CIDR;
4283 				addrlen = sizeof(uint32_t);
4284 			}
4285 		}
4286 	}
4287 
4288 	if (type == 0 && strchr(arg, '.') == NULL) {
4289 		/* Assume interface name. Copy significant data only */
4290 		mask = MIN(strlen(arg), IF_NAMESIZE - 1);
4291 		memcpy(xent->k.iface, arg, mask);
4292 		/* Set mask to exact match */
4293 		masklen = 8 * IF_NAMESIZE;
4294 		type = IPFW_TABLE_INTERFACE;
4295 		addrlen = IF_NAMESIZE;
4296 	}
4297 
4298 	if (type == 0) {
4299 		if (lookup_host(arg, (struct in_addr *)paddr) != 0)
4300 			errx(EX_NOHOST, "hostname ``%s'' unknown", arg);
4301 
4302 		masklen = 32;
4303 		type = IPFW_TABLE_CIDR;
4304 		addrlen = sizeof(struct in_addr);
4305 	}
4306 
4307 	xent->type = type;
4308 	xent->masklen = masklen;
4309 	xent->len = offsetof(ipfw_table_xentry, k) + addrlen;
4310 }
4311 
4312 static void
4313 table_list(uint16_t num, int need_header)
4314 {
4315 	ipfw_xtable *tbl;
4316 	ipfw_table_xentry *xent;
4317 	socklen_t l;
4318 	uint32_t *a, sz, tval;
4319 	char tbuf[128];
4320 	struct in6_addr *addr6;
4321 	ip_fw3_opheader *op3;
4322 
4323 	/* Prepend value with IP_FW3 header */
4324 	l = sizeof(ip_fw3_opheader) + sizeof(uint32_t);
4325 	op3 = alloca(l);
4326 	/* Zero reserved fields */
4327 	memset(op3, 0, sizeof(ip_fw3_opheader));
4328 	a = (uint32_t *)(op3 + 1);
4329 	*a = num;
4330 	op3->opcode = IP_FW_TABLE_XGETSIZE;
4331 	if (do_cmd(IP_FW3, op3, (uintptr_t)&l) < 0)
4332 		err(EX_OSERR, "getsockopt(IP_FW_TABLE_XGETSIZE)");
4333 
4334 	/* If a is zero we have nothing to do, the table is empty. */
4335 	if (*a == 0)
4336 		return;
4337 
4338 	l = *a;
4339 	tbl = safe_calloc(1, l);
4340 	tbl->opheader.opcode = IP_FW_TABLE_XLIST;
4341 	tbl->tbl = num;
4342 	if (do_cmd(IP_FW3, tbl, (uintptr_t)&l) < 0)
4343 		err(EX_OSERR, "getsockopt(IP_FW_TABLE_XLIST)");
4344 	if (tbl->cnt && need_header)
4345 		printf("---table(%d)---\n", tbl->tbl);
4346 	sz = tbl->size - sizeof(ipfw_xtable);
4347 	xent = &tbl->xent[0];
4348 	while (sz > 0) {
4349 		switch (tbl->type) {
4350 		case IPFW_TABLE_CIDR:
4351 			/* IPv4 or IPv6 prefixes */
4352 			tval = xent->value;
4353 			addr6 = &xent->k.addr6;
4354 
4355 
4356 			if (IN6_IS_ADDR_V4COMPAT(addr6)) {
4357 				/* IPv4 address */
4358 				inet_ntop(AF_INET, &addr6->s6_addr32[3], tbuf, sizeof(tbuf));
4359 			} else {
4360 				/* IPv6 address */
4361 				inet_ntop(AF_INET6, addr6, tbuf, sizeof(tbuf));
4362 			}
4363 
4364 			if (co.do_value_as_ip) {
4365 				tval = htonl(tval);
4366 				printf("%s/%u %s\n", tbuf, xent->masklen,
4367 				    inet_ntoa(*(struct in_addr *)&tval));
4368 			} else
4369 				printf("%s/%u %u\n", tbuf, xent->masklen, tval);
4370 			break;
4371 		case IPFW_TABLE_INTERFACE:
4372 			/* Interface names */
4373 			tval = xent->value;
4374 			if (co.do_value_as_ip) {
4375 				tval = htonl(tval);
4376 				printf("%s %s\n", xent->k.iface,
4377 				    inet_ntoa(*(struct in_addr *)&tval));
4378 			} else
4379 				printf("%s %u\n", xent->k.iface, tval);
4380 		}
4381 
4382 		if (sz < xent->len)
4383 			break;
4384 		sz -= xent->len;
4385 		xent = (ipfw_table_xentry *)((char *)xent + xent->len);
4386 	}
4387 
4388 	free(tbl);
4389 }
4390