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