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