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