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