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