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