xref: /freebsd/sbin/ipfw/ipfw2.c (revision 7afc53b8dfcc7d5897920ce6cc7e842fbb4ab813)
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/param.h>
24 #include <sys/mbuf.h>
25 #include <sys/socket.h>
26 #include <sys/sockio.h>
27 #include <sys/sysctl.h>
28 #include <sys/time.h>
29 #include <sys/wait.h>
30 #include <sys/queue.h>
31 
32 #include <ctype.h>
33 #include <err.h>
34 #include <errno.h>
35 #include <grp.h>
36 #include <limits.h>
37 #include <netdb.h>
38 #include <pwd.h>
39 #include <signal.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <stdarg.h>
43 #include <string.h>
44 #include <timeconv.h>	/* XXX do we need this ? */
45 #include <unistd.h>
46 #include <sysexits.h>
47 #include <unistd.h>
48 #include <fcntl.h>
49 
50 #include <net/if.h>
51 #include <net/pfvar.h>
52 #include <net/route.h> /* def. of struct route */
53 #include <netinet/in.h>
54 #include <netinet/in_systm.h>
55 #include <netinet/ip.h>
56 #include <netinet/ip_icmp.h>
57 #include <netinet/icmp6.h>
58 #include <netinet/ip_fw.h>
59 #include <netinet/ip_dummynet.h>
60 #include <netinet/tcp.h>
61 #include <arpa/inet.h>
62 
63 int
64 		do_resolv,		/* Would try to resolve all */
65 		do_time,		/* Show time stamps */
66 		do_quiet,		/* Be quiet in add and flush */
67 		do_pipe,		/* this cmd refers to a pipe */
68 		do_sort,		/* field to sort results (0 = no) */
69 		do_dynamic,		/* display dynamic rules */
70 		do_expired,		/* display expired dynamic rules */
71 		do_compact,		/* show rules in compact mode */
72 		do_force,		/* do not ask for confirmation */
73 		show_sets,		/* display rule sets */
74 		test_only,		/* only check syntax */
75 		comment_only,		/* only print action and comment */
76 		verbose;
77 
78 #define	IP_MASK_ALL	0xffffffff
79 /*
80  * the following macro returns an error message if we run out of
81  * arguments.
82  */
83 #define NEED1(msg)      {if (!ac) errx(EX_USAGE, msg);}
84 
85 /*
86  * _s_x is a structure that stores a string <-> token pairs, used in
87  * various places in the parser. Entries are stored in arrays,
88  * with an entry with s=NULL as terminator.
89  * The search routines are match_token() and match_value().
90  * Often, an element with x=0 contains an error string.
91  *
92  */
93 struct _s_x {
94 	char const *s;
95 	int x;
96 };
97 
98 static struct _s_x f_tcpflags[] = {
99 	{ "syn", TH_SYN },
100 	{ "fin", TH_FIN },
101 	{ "ack", TH_ACK },
102 	{ "psh", TH_PUSH },
103 	{ "rst", TH_RST },
104 	{ "urg", TH_URG },
105 	{ "tcp flag", 0 },
106 	{ NULL,	0 }
107 };
108 
109 static struct _s_x f_tcpopts[] = {
110 	{ "mss",	IP_FW_TCPOPT_MSS },
111 	{ "maxseg",	IP_FW_TCPOPT_MSS },
112 	{ "window",	IP_FW_TCPOPT_WINDOW },
113 	{ "sack",	IP_FW_TCPOPT_SACK },
114 	{ "ts",		IP_FW_TCPOPT_TS },
115 	{ "timestamp",	IP_FW_TCPOPT_TS },
116 	{ "cc",		IP_FW_TCPOPT_CC },
117 	{ "tcp option",	0 },
118 	{ NULL,	0 }
119 };
120 
121 /*
122  * IP options span the range 0 to 255 so we need to remap them
123  * (though in fact only the low 5 bits are significant).
124  */
125 static struct _s_x f_ipopts[] = {
126 	{ "ssrr",	IP_FW_IPOPT_SSRR},
127 	{ "lsrr",	IP_FW_IPOPT_LSRR},
128 	{ "rr",		IP_FW_IPOPT_RR},
129 	{ "ts",		IP_FW_IPOPT_TS},
130 	{ "ip option",	0 },
131 	{ NULL,	0 }
132 };
133 
134 static struct _s_x f_iptos[] = {
135 	{ "lowdelay",	IPTOS_LOWDELAY},
136 	{ "throughput",	IPTOS_THROUGHPUT},
137 	{ "reliability", IPTOS_RELIABILITY},
138 	{ "mincost",	IPTOS_MINCOST},
139 	{ "congestion",	IPTOS_CE},
140 	{ "ecntransport", IPTOS_ECT},
141 	{ "ip tos option", 0},
142 	{ NULL,	0 }
143 };
144 
145 static struct _s_x limit_masks[] = {
146 	{"all",		DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
147 	{"src-addr",	DYN_SRC_ADDR},
148 	{"src-port",	DYN_SRC_PORT},
149 	{"dst-addr",	DYN_DST_ADDR},
150 	{"dst-port",	DYN_DST_PORT},
151 	{NULL,		0}
152 };
153 
154 /*
155  * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
156  * This is only used in this code.
157  */
158 #define IPPROTO_ETHERTYPE	0x1000
159 static struct _s_x ether_types[] = {
160     /*
161      * Note, we cannot use "-:&/" in the names because they are field
162      * separators in the type specifications. Also, we use s = NULL as
163      * end-delimiter, because a type of 0 can be legal.
164      */
165 	{ "ip",		0x0800 },
166 	{ "ipv4",	0x0800 },
167 	{ "ipv6",	0x86dd },
168 	{ "arp",	0x0806 },
169 	{ "rarp",	0x8035 },
170 	{ "vlan",	0x8100 },
171 	{ "loop",	0x9000 },
172 	{ "trail",	0x1000 },
173 	{ "at",		0x809b },
174 	{ "atalk",	0x809b },
175 	{ "aarp",	0x80f3 },
176 	{ "pppoe_disc",	0x8863 },
177 	{ "pppoe_sess",	0x8864 },
178 	{ "ipx_8022",	0x00E0 },
179 	{ "ipx_8023",	0x0000 },
180 	{ "ipx_ii",	0x8137 },
181 	{ "ipx_snap",	0x8137 },
182 	{ "ipx",	0x8137 },
183 	{ "ns",		0x0600 },
184 	{ NULL,		0 }
185 };
186 
187 static void show_usage(void);
188 
189 enum tokens {
190 	TOK_NULL=0,
191 
192 	TOK_OR,
193 	TOK_NOT,
194 	TOK_STARTBRACE,
195 	TOK_ENDBRACE,
196 
197 	TOK_ACCEPT,
198 	TOK_COUNT,
199 	TOK_PIPE,
200 	TOK_QUEUE,
201 	TOK_DIVERT,
202 	TOK_TEE,
203 	TOK_NETGRAPH,
204 	TOK_NGTEE,
205 	TOK_FORWARD,
206 	TOK_SKIPTO,
207 	TOK_DENY,
208 	TOK_REJECT,
209 	TOK_RESET,
210 	TOK_UNREACH,
211 	TOK_CHECKSTATE,
212 
213 	TOK_ALTQ,
214 	TOK_LOG,
215 
216 	TOK_UID,
217 	TOK_GID,
218 	TOK_JAIL,
219 	TOK_IN,
220 	TOK_LIMIT,
221 	TOK_KEEPSTATE,
222 	TOK_LAYER2,
223 	TOK_OUT,
224 	TOK_DIVERTED,
225 	TOK_DIVERTEDLOOPBACK,
226 	TOK_DIVERTEDOUTPUT,
227 	TOK_XMIT,
228 	TOK_RECV,
229 	TOK_VIA,
230 	TOK_FRAG,
231 	TOK_IPOPTS,
232 	TOK_IPLEN,
233 	TOK_IPID,
234 	TOK_IPPRECEDENCE,
235 	TOK_IPTOS,
236 	TOK_IPTTL,
237 	TOK_IPVER,
238 	TOK_ESTAB,
239 	TOK_SETUP,
240 	TOK_TCPDATALEN,
241 	TOK_TCPFLAGS,
242 	TOK_TCPOPTS,
243 	TOK_TCPSEQ,
244 	TOK_TCPACK,
245 	TOK_TCPWIN,
246 	TOK_ICMPTYPES,
247 	TOK_MAC,
248 	TOK_MACTYPE,
249 	TOK_VERREVPATH,
250 	TOK_VERSRCREACH,
251 	TOK_ANTISPOOF,
252 	TOK_IPSEC,
253 	TOK_COMMENT,
254 
255 	TOK_PLR,
256 	TOK_NOERROR,
257 	TOK_BUCKETS,
258 	TOK_DSTIP,
259 	TOK_SRCIP,
260 	TOK_DSTPORT,
261 	TOK_SRCPORT,
262 	TOK_ALL,
263 	TOK_MASK,
264 	TOK_BW,
265 	TOK_DELAY,
266 	TOK_RED,
267 	TOK_GRED,
268 	TOK_DROPTAIL,
269 	TOK_PROTO,
270 	TOK_WEIGHT,
271 
272 	TOK_IPV6,
273 	TOK_FLOWID,
274 	TOK_ICMP6TYPES,
275 	TOK_EXT6HDR,
276 	TOK_DSTIP6,
277 	TOK_SRCIP6,
278 
279 	TOK_IPV4,
280 };
281 
282 struct _s_x dummynet_params[] = {
283 	{ "plr",		TOK_PLR },
284 	{ "noerror",		TOK_NOERROR },
285 	{ "buckets",		TOK_BUCKETS },
286 	{ "dst-ip",		TOK_DSTIP },
287 	{ "src-ip",		TOK_SRCIP },
288 	{ "dst-port",		TOK_DSTPORT },
289 	{ "src-port",		TOK_SRCPORT },
290 	{ "proto",		TOK_PROTO },
291 	{ "weight",		TOK_WEIGHT },
292 	{ "all",		TOK_ALL },
293 	{ "mask",		TOK_MASK },
294 	{ "droptail",		TOK_DROPTAIL },
295 	{ "red",		TOK_RED },
296 	{ "gred",		TOK_GRED },
297 	{ "bw",			TOK_BW },
298 	{ "bandwidth",		TOK_BW },
299 	{ "delay",		TOK_DELAY },
300 	{ "pipe",		TOK_PIPE },
301 	{ "queue",		TOK_QUEUE },
302 	{ "flow-id",		TOK_FLOWID},
303 	{ "dst-ipv6",		TOK_DSTIP6},
304 	{ "dst-ip6",		TOK_DSTIP6},
305 	{ "src-ipv6",		TOK_SRCIP6},
306 	{ "src-ip6",		TOK_SRCIP6},
307 	{ "dummynet-params",	TOK_NULL },
308 	{ NULL, 0 }	/* terminator */
309 };
310 
311 struct _s_x rule_actions[] = {
312 	{ "accept",		TOK_ACCEPT },
313 	{ "pass",		TOK_ACCEPT },
314 	{ "allow",		TOK_ACCEPT },
315 	{ "permit",		TOK_ACCEPT },
316 	{ "count",		TOK_COUNT },
317 	{ "pipe",		TOK_PIPE },
318 	{ "queue",		TOK_QUEUE },
319 	{ "divert",		TOK_DIVERT },
320 	{ "tee",		TOK_TEE },
321 	{ "netgraph",		TOK_NETGRAPH },
322 	{ "ngtee",		TOK_NGTEE },
323 	{ "fwd",		TOK_FORWARD },
324 	{ "forward",		TOK_FORWARD },
325 	{ "skipto",		TOK_SKIPTO },
326 	{ "deny",		TOK_DENY },
327 	{ "drop",		TOK_DENY },
328 	{ "reject",		TOK_REJECT },
329 	{ "reset",		TOK_RESET },
330 	{ "unreach",		TOK_UNREACH },
331 	{ "check-state",	TOK_CHECKSTATE },
332 	{ "//",			TOK_COMMENT },
333 	{ NULL, 0 }	/* terminator */
334 };
335 
336 struct _s_x rule_action_params[] = {
337 	{ "altq",		TOK_ALTQ },
338 	{ "log",		TOK_LOG },
339 	{ NULL, 0 }	/* terminator */
340 };
341 
342 struct _s_x rule_options[] = {
343 	{ "uid",		TOK_UID },
344 	{ "gid",		TOK_GID },
345 	{ "jail",		TOK_JAIL },
346 	{ "in",			TOK_IN },
347 	{ "limit",		TOK_LIMIT },
348 	{ "keep-state",		TOK_KEEPSTATE },
349 	{ "bridged",		TOK_LAYER2 },
350 	{ "layer2",		TOK_LAYER2 },
351 	{ "out",		TOK_OUT },
352 	{ "diverted",		TOK_DIVERTED },
353 	{ "diverted-loopback",	TOK_DIVERTEDLOOPBACK },
354 	{ "diverted-output",	TOK_DIVERTEDOUTPUT },
355 	{ "xmit",		TOK_XMIT },
356 	{ "recv",		TOK_RECV },
357 	{ "via",		TOK_VIA },
358 	{ "fragment",		TOK_FRAG },
359 	{ "frag",		TOK_FRAG },
360 	{ "ipoptions",		TOK_IPOPTS },
361 	{ "ipopts",		TOK_IPOPTS },
362 	{ "iplen",		TOK_IPLEN },
363 	{ "ipid",		TOK_IPID },
364 	{ "ipprecedence",	TOK_IPPRECEDENCE },
365 	{ "iptos",		TOK_IPTOS },
366 	{ "ipttl",		TOK_IPTTL },
367 	{ "ipversion",		TOK_IPVER },
368 	{ "ipver",		TOK_IPVER },
369 	{ "estab",		TOK_ESTAB },
370 	{ "established",	TOK_ESTAB },
371 	{ "setup",		TOK_SETUP },
372 	{ "tcpdatalen",		TOK_TCPDATALEN },
373 	{ "tcpflags",		TOK_TCPFLAGS },
374 	{ "tcpflgs",		TOK_TCPFLAGS },
375 	{ "tcpoptions",		TOK_TCPOPTS },
376 	{ "tcpopts",		TOK_TCPOPTS },
377 	{ "tcpseq",		TOK_TCPSEQ },
378 	{ "tcpack",		TOK_TCPACK },
379 	{ "tcpwin",		TOK_TCPWIN },
380 	{ "icmptype",		TOK_ICMPTYPES },
381 	{ "icmptypes",		TOK_ICMPTYPES },
382 	{ "dst-ip",		TOK_DSTIP },
383 	{ "src-ip",		TOK_SRCIP },
384 	{ "dst-port",		TOK_DSTPORT },
385 	{ "src-port",		TOK_SRCPORT },
386 	{ "proto",		TOK_PROTO },
387 	{ "MAC",		TOK_MAC },
388 	{ "mac",		TOK_MAC },
389 	{ "mac-type",		TOK_MACTYPE },
390 	{ "verrevpath",		TOK_VERREVPATH },
391 	{ "versrcreach",	TOK_VERSRCREACH },
392 	{ "antispoof",		TOK_ANTISPOOF },
393 	{ "ipsec",		TOK_IPSEC },
394 	{ "icmp6type",		TOK_ICMP6TYPES },
395 	{ "icmp6types",		TOK_ICMP6TYPES },
396 	{ "ext6hdr",		TOK_EXT6HDR},
397 	{ "flow-id",		TOK_FLOWID},
398 	{ "ipv6",		TOK_IPV6},
399 	{ "ip6",		TOK_IPV6},
400 	{ "ipv4",		TOK_IPV4},
401 	{ "ip4",		TOK_IPV4},
402 	{ "dst-ipv6",		TOK_DSTIP6},
403 	{ "dst-ip6",		TOK_DSTIP6},
404 	{ "src-ipv6",		TOK_SRCIP6},
405 	{ "src-ip6",		TOK_SRCIP6},
406 	{ "//",			TOK_COMMENT },
407 
408 	{ "not",		TOK_NOT },		/* pseudo option */
409 	{ "!", /* escape ? */	TOK_NOT },		/* pseudo option */
410 	{ "or",			TOK_OR },		/* pseudo option */
411 	{ "|", /* escape */	TOK_OR },		/* pseudo option */
412 	{ "{",			TOK_STARTBRACE },	/* pseudo option */
413 	{ "(",			TOK_STARTBRACE },	/* pseudo option */
414 	{ "}",			TOK_ENDBRACE },		/* pseudo option */
415 	{ ")",			TOK_ENDBRACE },		/* pseudo option */
416 	{ NULL, 0 }	/* terminator */
417 };
418 
419 static __inline uint64_t
420 align_uint64(uint64_t *pll) {
421 	uint64_t ret;
422 
423 	bcopy (pll, &ret, sizeof(ret));
424 	return ret;
425 }
426 
427 /*
428  * conditionally runs the command.
429  */
430 static int
431 do_cmd(int optname, void *optval, uintptr_t optlen)
432 {
433 	static int s = -1;	/* the socket */
434 	int i;
435 
436 	if (test_only)
437 		return 0;
438 
439 	if (s == -1)
440 		s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
441 	if (s < 0)
442 		err(EX_UNAVAILABLE, "socket");
443 
444 	if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
445 	    optname == IP_FW_ADD || optname == IP_FW_TABLE_LIST ||
446 	    optname == IP_FW_TABLE_GETSIZE)
447 		i = getsockopt(s, IPPROTO_IP, optname, optval,
448 			(socklen_t *)optlen);
449 	else
450 		i = setsockopt(s, IPPROTO_IP, optname, optval, optlen);
451 	return i;
452 }
453 
454 /**
455  * match_token takes a table and a string, returns the value associated
456  * with the string (-1 in case of failure).
457  */
458 static int
459 match_token(struct _s_x *table, char *string)
460 {
461 	struct _s_x *pt;
462 	uint i = strlen(string);
463 
464 	for (pt = table ; i && pt->s != NULL ; pt++)
465 		if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
466 			return pt->x;
467 	return -1;
468 }
469 
470 /**
471  * match_value takes a table and a value, returns the string associated
472  * with the value (NULL in case of failure).
473  */
474 static char const *
475 match_value(struct _s_x *p, int value)
476 {
477 	for (; p->s != NULL; p++)
478 		if (p->x == value)
479 			return p->s;
480 	return NULL;
481 }
482 
483 /*
484  * _substrcmp takes two strings and returns 1 if they do not match,
485  * and 0 if they match exactly or the first string is a sub-string
486  * of the second.  A warning is printed to stderr in the case that the
487  * first string is a sub-string of the second.
488  *
489  * This function will be removed in the future through the usual
490  * deprecation process.
491  */
492 static int
493 _substrcmp(const char *str1, const char* str2)
494 {
495 
496 	if (strncmp(str1, str2, strlen(str1)) != 0)
497 		return 1;
498 
499 	if (strlen(str1) != strlen(str2))
500 		warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
501 		    str1, str2);
502 	return 0;
503 }
504 
505 /*
506  * _substrcmp2 takes three strings and returns 1 if the first two do not match,
507  * and 0 if they match exactly or the second string is a sub-string
508  * of the first.  A warning is printed to stderr in the case that the
509  * first string does not match the third.
510  *
511  * This function exists to warn about the bizzare construction
512  * strncmp(str, "by", 2) which is used to allow people to use a shotcut
513  * for "bytes".  The problem is that in addition to accepting "by",
514  * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
515  * other string beginning with "by".
516  *
517  * This function will be removed in the future through the usual
518  * deprecation process.
519  */
520 static int
521 _substrcmp2(const char *str1, const char* str2, const char* str3)
522 {
523 
524 	if (strncmp(str1, str2, strlen(str2)) != 0)
525 		return 1;
526 
527 	if (strcmp(str1, str3) != 0)
528 		warnx("DEPRECATED: '%s' matched '%s'",
529 		    str1, str3);
530 	return 0;
531 }
532 
533 /*
534  * prints one port, symbolic or numeric
535  */
536 static void
537 print_port(int proto, uint16_t port)
538 {
539 
540 	if (proto == IPPROTO_ETHERTYPE) {
541 		char const *s;
542 
543 		if (do_resolv && (s = match_value(ether_types, port)) )
544 			printf("%s", s);
545 		else
546 			printf("0x%04x", port);
547 	} else {
548 		struct servent *se = NULL;
549 		if (do_resolv) {
550 			struct protoent *pe = getprotobynumber(proto);
551 
552 			se = getservbyport(htons(port), pe ? pe->p_name : NULL);
553 		}
554 		if (se)
555 			printf("%s", se->s_name);
556 		else
557 			printf("%d", port);
558 	}
559 }
560 
561 struct _s_x _port_name[] = {
562 	{"dst-port",	O_IP_DSTPORT},
563 	{"src-port",	O_IP_SRCPORT},
564 	{"ipid",	O_IPID},
565 	{"iplen",	O_IPLEN},
566 	{"ipttl",	O_IPTTL},
567 	{"mac-type",	O_MAC_TYPE},
568 	{"tcpdatalen",	O_TCPDATALEN},
569 	{NULL,		0}
570 };
571 
572 /*
573  * Print the values in a list 16-bit items of the types above.
574  * XXX todo: add support for mask.
575  */
576 static void
577 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode)
578 {
579 	uint16_t *p = cmd->ports;
580 	int i;
581 	char const *sep;
582 
583 	if (cmd->o.len & F_NOT)
584 		printf(" not");
585 	if (opcode != 0) {
586 		sep = match_value(_port_name, opcode);
587 		if (sep == NULL)
588 			sep = "???";
589 		printf (" %s", sep);
590 	}
591 	sep = " ";
592 	for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
593 		printf(sep);
594 		print_port(proto, p[0]);
595 		if (p[0] != p[1]) {
596 			printf("-");
597 			print_port(proto, p[1]);
598 		}
599 		sep = ",";
600 	}
601 }
602 
603 /*
604  * Like strtol, but also translates service names into port numbers
605  * for some protocols.
606  * In particular:
607  *	proto == -1 disables the protocol check;
608  *	proto == IPPROTO_ETHERTYPE looks up an internal table
609  *	proto == <some value in /etc/protocols> matches the values there.
610  * Returns *end == s in case the parameter is not found.
611  */
612 static int
613 strtoport(char *s, char **end, int base, int proto)
614 {
615 	char *p, *buf;
616 	char *s1;
617 	int i;
618 
619 	*end = s;		/* default - not found */
620 	if (*s == '\0')
621 		return 0;	/* not found */
622 
623 	if (isdigit(*s))
624 		return strtol(s, end, base);
625 
626 	/*
627 	 * find separator. '\\' escapes the next char.
628 	 */
629 	for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
630 		if (*s1 == '\\' && s1[1] != '\0')
631 			s1++;
632 
633 	buf = malloc(s1 - s + 1);
634 	if (buf == NULL)
635 		return 0;
636 
637 	/*
638 	 * copy into a buffer skipping backslashes
639 	 */
640 	for (p = s, i = 0; p != s1 ; p++)
641 		if (*p != '\\')
642 			buf[i++] = *p;
643 	buf[i++] = '\0';
644 
645 	if (proto == IPPROTO_ETHERTYPE) {
646 		i = match_token(ether_types, buf);
647 		free(buf);
648 		if (i != -1) {	/* found */
649 			*end = s1;
650 			return i;
651 		}
652 	} else {
653 		struct protoent *pe = NULL;
654 		struct servent *se;
655 
656 		if (proto != 0)
657 			pe = getprotobynumber(proto);
658 		setservent(1);
659 		se = getservbyname(buf, pe ? pe->p_name : NULL);
660 		free(buf);
661 		if (se != NULL) {
662 			*end = s1;
663 			return ntohs(se->s_port);
664 		}
665 	}
666 	return 0;	/* not found */
667 }
668 
669 /*
670  * Map between current altq queue id numbers and names.
671  */
672 static int altq_fetched = 0;
673 static TAILQ_HEAD(, pf_altq) altq_entries =
674 	TAILQ_HEAD_INITIALIZER(altq_entries);
675 
676 static void
677 altq_set_enabled(int enabled)
678 {
679 	int pffd;
680 
681 	pffd = open("/dev/pf", O_RDWR);
682 	if (pffd == -1)
683 		err(EX_UNAVAILABLE,
684 		    "altq support opening pf(4) control device");
685 	if (enabled) {
686 		if (ioctl(pffd, DIOCSTARTALTQ) != 0 && errno != EEXIST)
687 			err(EX_UNAVAILABLE, "enabling altq");
688 	} else {
689 		if (ioctl(pffd, DIOCSTOPALTQ) != 0 && errno != ENOENT)
690 			err(EX_UNAVAILABLE, "disabling altq");
691 	}
692 	close(pffd);
693 }
694 
695 static void
696 altq_fetch()
697 {
698 	struct pfioc_altq pfioc;
699 	struct pf_altq *altq;
700 	int pffd, mnr;
701 
702 	if (altq_fetched)
703 		return;
704 	altq_fetched = 1;
705 	pffd = open("/dev/pf", O_RDONLY);
706 	if (pffd == -1) {
707 		warn("altq support opening pf(4) control device");
708 		return;
709 	}
710 	bzero(&pfioc, sizeof(pfioc));
711 	if (ioctl(pffd, DIOCGETALTQS, &pfioc) != 0) {
712 		warn("altq support getting queue list");
713 		close(pffd);
714 		return;
715 	}
716 	mnr = pfioc.nr;
717 	for (pfioc.nr = 0; pfioc.nr < mnr; pfioc.nr++) {
718 		if (ioctl(pffd, DIOCGETALTQ, &pfioc) != 0) {
719 			if (errno == EBUSY)
720 				break;
721 			warn("altq support getting queue list");
722 			close(pffd);
723 			return;
724 		}
725 		if (pfioc.altq.qid == 0)
726 			continue;
727 		altq = malloc(sizeof(*altq));
728 		if (altq == NULL)
729 			err(EX_OSERR, "malloc");
730 		*altq = pfioc.altq;
731 		TAILQ_INSERT_TAIL(&altq_entries, altq, entries);
732 	}
733 	close(pffd);
734 }
735 
736 static u_int32_t
737 altq_name_to_qid(const char *name)
738 {
739 	struct pf_altq *altq;
740 
741 	altq_fetch();
742 	TAILQ_FOREACH(altq, &altq_entries, entries)
743 		if (strcmp(name, altq->qname) == 0)
744 			break;
745 	if (altq == NULL)
746 		errx(EX_DATAERR, "altq has no queue named `%s'", name);
747 	return altq->qid;
748 }
749 
750 static const char *
751 altq_qid_to_name(u_int32_t qid)
752 {
753 	struct pf_altq *altq;
754 
755 	altq_fetch();
756 	TAILQ_FOREACH(altq, &altq_entries, entries)
757 		if (qid == altq->qid)
758 			break;
759 	if (altq == NULL)
760 		return NULL;
761 	return altq->qname;
762 }
763 
764 static void
765 fill_altq_qid(u_int32_t *qid, const char *av)
766 {
767 	*qid = altq_name_to_qid(av);
768 }
769 
770 /*
771  * Fill the body of the command with the list of port ranges.
772  */
773 static int
774 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto)
775 {
776 	uint16_t a, b, *p = cmd->ports;
777 	int i = 0;
778 	char *s = av;
779 
780 	while (*s) {
781 		a = strtoport(av, &s, 0, proto);
782 		if (s == av) /* no parameter */
783 			break;
784 		if (*s == '-') { /* a range */
785 			av = s+1;
786 			b = strtoport(av, &s, 0, proto);
787 			if (s == av) /* no parameter */
788 				break;
789 			p[0] = a;
790 			p[1] = b;
791 		} else if (*s == ',' || *s == '\0' )
792 			p[0] = p[1] = a;
793 		else 	/* invalid separator */
794 			errx(EX_DATAERR, "invalid separator <%c> in <%s>\n",
795 				*s, av);
796 		i++;
797 		p += 2;
798 		av = s+1;
799 	}
800 	if (i > 0) {
801 		if (i+1 > F_LEN_MASK)
802 			errx(EX_DATAERR, "too many ports/ranges\n");
803 		cmd->o.len |= i+1; /* leave F_NOT and F_OR untouched */
804 	}
805 	return i;
806 }
807 
808 static struct _s_x icmpcodes[] = {
809       { "net",			ICMP_UNREACH_NET },
810       { "host",			ICMP_UNREACH_HOST },
811       { "protocol",		ICMP_UNREACH_PROTOCOL },
812       { "port",			ICMP_UNREACH_PORT },
813       { "needfrag",		ICMP_UNREACH_NEEDFRAG },
814       { "srcfail",		ICMP_UNREACH_SRCFAIL },
815       { "net-unknown",		ICMP_UNREACH_NET_UNKNOWN },
816       { "host-unknown",		ICMP_UNREACH_HOST_UNKNOWN },
817       { "isolated",		ICMP_UNREACH_ISOLATED },
818       { "net-prohib",		ICMP_UNREACH_NET_PROHIB },
819       { "host-prohib",		ICMP_UNREACH_HOST_PROHIB },
820       { "tosnet",		ICMP_UNREACH_TOSNET },
821       { "toshost",		ICMP_UNREACH_TOSHOST },
822       { "filter-prohib",	ICMP_UNREACH_FILTER_PROHIB },
823       { "host-precedence",	ICMP_UNREACH_HOST_PRECEDENCE },
824       { "precedence-cutoff",	ICMP_UNREACH_PRECEDENCE_CUTOFF },
825       { NULL, 0 }
826 };
827 
828 static void
829 fill_reject_code(u_short *codep, char *str)
830 {
831 	int val;
832 	char *s;
833 
834 	val = strtoul(str, &s, 0);
835 	if (s == str || *s != '\0' || val >= 0x100)
836 		val = match_token(icmpcodes, str);
837 	if (val < 0)
838 		errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
839 	*codep = val;
840 	return;
841 }
842 
843 static void
844 print_reject_code(uint16_t code)
845 {
846 	char const *s = match_value(icmpcodes, code);
847 
848 	if (s != NULL)
849 		printf("unreach %s", s);
850 	else
851 		printf("unreach %u", code);
852 }
853 
854 /*
855  * Returns the number of bits set (from left) in a contiguous bitmask,
856  * or -1 if the mask is not contiguous.
857  * XXX this needs a proper fix.
858  * This effectively works on masks in big-endian (network) format.
859  * when compiled on little endian architectures.
860  *
861  * First bit is bit 7 of the first byte -- note, for MAC addresses,
862  * the first bit on the wire is bit 0 of the first byte.
863  * len is the max length in bits.
864  */
865 static int
866 contigmask(uint8_t *p, int len)
867 {
868 	int i, n;
869 
870 	for (i=0; i<len ; i++)
871 		if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
872 			break;
873 	for (n=i+1; n < len; n++)
874 		if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
875 			return -1; /* mask not contiguous */
876 	return i;
877 }
878 
879 /*
880  * print flags set/clear in the two bitmasks passed as parameters.
881  * There is a specialized check for f_tcpflags.
882  */
883 static void
884 print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list)
885 {
886 	char const *comma = "";
887 	int i;
888 	uint8_t set = cmd->arg1 & 0xff;
889 	uint8_t clear = (cmd->arg1 >> 8) & 0xff;
890 
891 	if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
892 		printf(" setup");
893 		return;
894 	}
895 
896 	printf(" %s ", name);
897 	for (i=0; list[i].x != 0; i++) {
898 		if (set & list[i].x) {
899 			set &= ~list[i].x;
900 			printf("%s%s", comma, list[i].s);
901 			comma = ",";
902 		}
903 		if (clear & list[i].x) {
904 			clear &= ~list[i].x;
905 			printf("%s!%s", comma, list[i].s);
906 			comma = ",";
907 		}
908 	}
909 }
910 
911 /*
912  * Print the ip address contained in a command.
913  */
914 static void
915 print_ip(ipfw_insn_ip *cmd, char const *s)
916 {
917 	struct hostent *he = NULL;
918 	int len = F_LEN((ipfw_insn *)cmd);
919 	uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
920 
921 	printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
922 
923 	if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
924 		printf("me");
925 		return;
926 	}
927 	if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
928 	    cmd->o.opcode == O_IP_DST_LOOKUP) {
929 		printf("table(%u", ((ipfw_insn *)cmd)->arg1);
930 		if (len == F_INSN_SIZE(ipfw_insn_u32))
931 			printf(",%u", *a);
932 		printf(")");
933 		return;
934 	}
935 	if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
936 		uint32_t x, *map = (uint32_t *)&(cmd->mask);
937 		int i, j;
938 		char comma = '{';
939 
940 		x = cmd->o.arg1 - 1;
941 		x = htonl( ~x );
942 		cmd->addr.s_addr = htonl(cmd->addr.s_addr);
943 		printf("%s/%d", inet_ntoa(cmd->addr),
944 			contigmask((uint8_t *)&x, 32));
945 		x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
946 		x &= 0xff; /* base */
947 		/*
948 		 * Print bits and ranges.
949 		 * Locate first bit set (i), then locate first bit unset (j).
950 		 * If we have 3+ consecutive bits set, then print them as a
951 		 * range, otherwise only print the initial bit and rescan.
952 		 */
953 		for (i=0; i < cmd->o.arg1; i++)
954 			if (map[i/32] & (1<<(i & 31))) {
955 				for (j=i+1; j < cmd->o.arg1; j++)
956 					if (!(map[ j/32] & (1<<(j & 31))))
957 						break;
958 				printf("%c%d", comma, i+x);
959 				if (j>i+2) { /* range has at least 3 elements */
960 					printf("-%d", j-1+x);
961 					i = j-1;
962 				}
963 				comma = ',';
964 			}
965 		printf("}");
966 		return;
967 	}
968 	/*
969 	 * len == 2 indicates a single IP, whereas lists of 1 or more
970 	 * addr/mask pairs have len = (2n+1). We convert len to n so we
971 	 * use that to count the number of entries.
972 	 */
973     for (len = len / 2; len > 0; len--, a += 2) {
974 	int mb =	/* mask length */
975 	    (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
976 		32 : contigmask((uint8_t *)&(a[1]), 32);
977 	if (mb == 32 && do_resolv)
978 		he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
979 	if (he != NULL)		/* resolved to name */
980 		printf("%s", he->h_name);
981 	else if (mb == 0)	/* any */
982 		printf("any");
983 	else {		/* numeric IP followed by some kind of mask */
984 		printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) );
985 		if (mb < 0)
986 			printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) );
987 		else if (mb < 32)
988 			printf("/%d", mb);
989 	}
990 	if (len > 1)
991 		printf(",");
992     }
993 }
994 
995 /*
996  * prints a MAC address/mask pair
997  */
998 static void
999 print_mac(uint8_t *addr, uint8_t *mask)
1000 {
1001 	int l = contigmask(mask, 48);
1002 
1003 	if (l == 0)
1004 		printf(" any");
1005 	else {
1006 		printf(" %02x:%02x:%02x:%02x:%02x:%02x",
1007 		    addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1008 		if (l == -1)
1009 			printf("&%02x:%02x:%02x:%02x:%02x:%02x",
1010 			    mask[0], mask[1], mask[2],
1011 			    mask[3], mask[4], mask[5]);
1012 		else if (l < 48)
1013 			printf("/%d", l);
1014 	}
1015 }
1016 
1017 static void
1018 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1019 {
1020 	uint8_t type;
1021 
1022 	cmd->d[0] = 0;
1023 	while (*av) {
1024 		if (*av == ',')
1025 			av++;
1026 
1027 		type = strtoul(av, &av, 0);
1028 
1029 		if (*av != ',' && *av != '\0')
1030 			errx(EX_DATAERR, "invalid ICMP type");
1031 
1032 		if (type > 31)
1033 			errx(EX_DATAERR, "ICMP type out of range");
1034 
1035 		cmd->d[0] |= 1 << type;
1036 	}
1037 	cmd->o.opcode = O_ICMPTYPE;
1038 	cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1039 }
1040 
1041 static void
1042 print_icmptypes(ipfw_insn_u32 *cmd)
1043 {
1044 	int i;
1045 	char sep= ' ';
1046 
1047 	printf(" icmptypes");
1048 	for (i = 0; i < 32; i++) {
1049 		if ( (cmd->d[0] & (1 << (i))) == 0)
1050 			continue;
1051 		printf("%c%d", sep, i);
1052 		sep = ',';
1053 	}
1054 }
1055 
1056 /*
1057  * Print the ip address contained in a command.
1058  */
1059 static void
1060 print_ip6(ipfw_insn_ip6 *cmd, char const *s)
1061 {
1062        struct hostent *he = NULL;
1063        int len = F_LEN((ipfw_insn *) cmd) - 1;
1064        struct in6_addr *a = &(cmd->addr6);
1065        char trad[255];
1066 
1067        printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
1068 
1069        if (cmd->o.opcode == O_IP6_SRC_ME || cmd->o.opcode == O_IP6_DST_ME) {
1070                printf("me6");
1071                return;
1072        }
1073        if (cmd->o.opcode == O_IP6) {
1074                printf(" ipv6");
1075                return;
1076        }
1077 
1078        /*
1079         * len == 4 indicates a single IP, whereas lists of 1 or more
1080         * addr/mask pairs have len = (2n+1). We convert len to n so we
1081         * use that to count the number of entries.
1082         */
1083 
1084        for (len = len / 4; len > 0; len -= 2, a += 2) {
1085            int mb =        /* mask length */
1086                (cmd->o.opcode == O_IP6_SRC || cmd->o.opcode == O_IP6_DST) ?
1087                128 : contigmask((uint8_t *)&(a[1]), 128);
1088 
1089            if (mb == 128 && do_resolv)
1090                he = gethostbyaddr((char *)a, sizeof(*a), AF_INET6);
1091            if (he != NULL)             /* resolved to name */
1092                printf("%s", he->h_name);
1093            else if (mb == 0)           /* any */
1094                printf("any");
1095            else {          /* numeric IP followed by some kind of mask */
1096                if (inet_ntop(AF_INET6,  a, trad, sizeof( trad ) ) == NULL)
1097                    printf("Error ntop in print_ip6\n");
1098                printf("%s",  trad );
1099                if (mb < 0)     /* XXX not really legal... */
1100                    printf(":%s",
1101                        inet_ntop(AF_INET6, &a[1], trad, sizeof(trad)));
1102                else if (mb < 128)
1103                    printf("/%d", mb);
1104            }
1105            if (len > 2)
1106                printf(",");
1107        }
1108 }
1109 
1110 static void
1111 fill_icmp6types(ipfw_insn_icmp6 *cmd, char *av)
1112 {
1113        uint8_t type;
1114 
1115        cmd->d[0] = 0;
1116        while (*av) {
1117            if (*av == ',')
1118                av++;
1119            type = strtoul(av, &av, 0);
1120            if (*av != ',' && *av != '\0')
1121                errx(EX_DATAERR, "invalid ICMP6 type");
1122 	   /*
1123 	    * XXX: shouldn't this be 0xFF?  I can't see any reason why
1124 	    * we shouldn't be able to filter all possiable values
1125 	    * regardless of the ability of the rest of the kernel to do
1126 	    * anything useful with them.
1127 	    */
1128            if (type > ICMP6_MAXTYPE)
1129                errx(EX_DATAERR, "ICMP6 type out of range");
1130            cmd->d[type / 32] |= ( 1 << (type % 32));
1131        }
1132        cmd->o.opcode = O_ICMP6TYPE;
1133        cmd->o.len |= F_INSN_SIZE(ipfw_insn_icmp6);
1134 }
1135 
1136 
1137 static void
1138 print_icmp6types(ipfw_insn_u32 *cmd)
1139 {
1140        int i, j;
1141        char sep= ' ';
1142 
1143        printf(" ipv6 icmp6types");
1144        for (i = 0; i < 7; i++)
1145                for (j=0; j < 32; ++j) {
1146                        if ( (cmd->d[i] & (1 << (j))) == 0)
1147                                continue;
1148                        printf("%c%d", sep, (i*32 + j));
1149                        sep = ',';
1150                }
1151 }
1152 
1153 static void
1154 print_flow6id( ipfw_insn_u32 *cmd)
1155 {
1156        uint16_t i, limit = cmd->o.arg1;
1157        char sep = ',';
1158 
1159        printf(" flow-id ");
1160        for( i=0; i < limit; ++i) {
1161                if (i == limit - 1)
1162                        sep = ' ';
1163                printf("%d%c", cmd->d[i], sep);
1164        }
1165 }
1166 
1167 /* structure and define for the extension header in ipv6 */
1168 static struct _s_x ext6hdrcodes[] = {
1169        { "frag",       EXT_FRAGMENT },
1170        { "hopopt",     EXT_HOPOPTS },
1171        { "route",      EXT_ROUTING },
1172        { "ah",         EXT_AH },
1173        { "esp",        EXT_ESP },
1174        { NULL,         0 }
1175 };
1176 
1177 /* fills command for the extension header filtering */
1178 int
1179 fill_ext6hdr( ipfw_insn *cmd, char *av)
1180 {
1181        int tok;
1182        char *s = av;
1183 
1184        cmd->arg1 = 0;
1185 
1186        while(s) {
1187            av = strsep( &s, ",") ;
1188            tok = match_token(ext6hdrcodes, av);
1189            switch (tok) {
1190            case EXT_FRAGMENT:
1191                cmd->arg1 |= EXT_FRAGMENT;
1192                break;
1193 
1194            case EXT_HOPOPTS:
1195                cmd->arg1 |= EXT_HOPOPTS;
1196                break;
1197 
1198            case EXT_ROUTING:
1199                cmd->arg1 |= EXT_ROUTING;
1200                break;
1201 
1202            case EXT_AH:
1203                cmd->arg1 |= EXT_AH;
1204                break;
1205 
1206            case EXT_ESP:
1207                cmd->arg1 |= EXT_ESP;
1208                break;
1209 
1210            default:
1211                errx( EX_DATAERR, "invalid option for ipv6 exten header" );
1212                break;
1213            }
1214        }
1215        if (cmd->arg1 == 0 )
1216            return 0;
1217        cmd->opcode = O_EXT_HDR;
1218        cmd->len |= F_INSN_SIZE( ipfw_insn );
1219        return 1;
1220 }
1221 
1222 void
1223 print_ext6hdr( ipfw_insn *cmd )
1224 {
1225        char sep = ' ';
1226 
1227        printf(" extension header:");
1228        if (cmd->arg1 & EXT_FRAGMENT ) {
1229            printf("%cfragmentation", sep);
1230            sep = ',';
1231        }
1232        if (cmd->arg1 & EXT_HOPOPTS ) {
1233            printf("%chop options", sep);
1234            sep = ',';
1235        }
1236        if (cmd->arg1 & EXT_ROUTING ) {
1237            printf("%crouting options", sep);
1238            sep = ',';
1239        }
1240        if (cmd->arg1 & EXT_AH ) {
1241            printf("%cauthentication header", sep);
1242            sep = ',';
1243        }
1244        if (cmd->arg1 & EXT_ESP ) {
1245            printf("%cencapsulated security payload", sep);
1246        }
1247 }
1248 
1249 /*
1250  * show_ipfw() prints the body of an ipfw rule.
1251  * Because the standard rule has at least proto src_ip dst_ip, we use
1252  * a helper function to produce these entries if not provided explicitly.
1253  * The first argument is the list of fields we have, the second is
1254  * the list of fields we want to be printed.
1255  *
1256  * Special cases if we have provided a MAC header:
1257  *   + if the rule does not contain IP addresses/ports, do not print them;
1258  *   + if the rule does not contain an IP proto, print "all" instead of "ip";
1259  *
1260  * Once we have 'have_options', IP header fields are printed as options.
1261  */
1262 #define	HAVE_PROTO	0x0001
1263 #define	HAVE_SRCIP	0x0002
1264 #define	HAVE_DSTIP	0x0004
1265 #define	HAVE_MAC	0x0008
1266 #define	HAVE_MACTYPE	0x0010
1267 #define	HAVE_PROTO4	0x0040
1268 #define	HAVE_PROTO6	0x0080
1269 #define	HAVE_OPTIONS	0x8000
1270 
1271 #define	HAVE_IP		(HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP)
1272 static void
1273 show_prerequisites(int *flags, int want, int cmd)
1274 {
1275 	if (comment_only)
1276 		return;
1277 	if ( (*flags & HAVE_IP) == HAVE_IP)
1278 		*flags |= HAVE_OPTIONS;
1279 
1280 	if ( (*flags & (HAVE_MAC|HAVE_MACTYPE|HAVE_OPTIONS)) == HAVE_MAC &&
1281 	     cmd != O_MAC_TYPE) {
1282 		/*
1283 		 * mac-type was optimized out by the compiler,
1284 		 * restore it
1285 		 */
1286 		printf(" any");
1287 		*flags |= HAVE_MACTYPE | HAVE_OPTIONS;
1288 		return;
1289 	}
1290 	if ( !(*flags & HAVE_OPTIONS)) {
1291 		if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO))
1292 			if ( (*flags & HAVE_PROTO4))
1293 				printf(" ip4");
1294 			else if ( (*flags & HAVE_PROTO6))
1295 				printf(" ip6");
1296 			else
1297 				printf(" ip");
1298 
1299 		if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
1300 			printf(" from any");
1301 		if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
1302 			printf(" to any");
1303 	}
1304 	*flags |= want;
1305 }
1306 
1307 static void
1308 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth)
1309 {
1310 	static int twidth = 0;
1311 	int l;
1312 	ipfw_insn *cmd;
1313 	char *comment = NULL;	/* ptr to comment if we have one */
1314 	int proto = 0;		/* default */
1315 	int flags = 0;	/* prerequisites */
1316 	ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
1317 	ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
1318 	int or_block = 0;	/* we are in an or block */
1319 	uint32_t set_disable;
1320 
1321 	bcopy(&rule->next_rule, &set_disable, sizeof(set_disable));
1322 
1323 	if (set_disable & (1 << rule->set)) { /* disabled */
1324 		if (!show_sets)
1325 			return;
1326 		else
1327 			printf("# DISABLED ");
1328 	}
1329 	printf("%05u ", rule->rulenum);
1330 
1331 	if (pcwidth>0 || bcwidth>0)
1332 		printf("%*llu %*llu ", pcwidth, align_uint64(&rule->pcnt),
1333 		    bcwidth, align_uint64(&rule->bcnt));
1334 
1335 	if (do_time == 2)
1336 		printf("%10u ", rule->timestamp);
1337 	else if (do_time == 1) {
1338 		char timestr[30];
1339 		time_t t = (time_t)0;
1340 
1341 		if (twidth == 0) {
1342 			strcpy(timestr, ctime(&t));
1343 			*strchr(timestr, '\n') = '\0';
1344 			twidth = strlen(timestr);
1345 		}
1346 		if (rule->timestamp) {
1347 #if _FreeBSD_version < 500000 /* XXX check */
1348 #define	_long_to_time(x)	(time_t)(x)
1349 #endif
1350 			t = _long_to_time(rule->timestamp);
1351 
1352 			strcpy(timestr, ctime(&t));
1353 			*strchr(timestr, '\n') = '\0';
1354 			printf("%s ", timestr);
1355 		} else {
1356 			printf("%*s", twidth, " ");
1357 		}
1358 	}
1359 
1360 	if (show_sets)
1361 		printf("set %d ", rule->set);
1362 
1363 	/*
1364 	 * print the optional "match probability"
1365 	 */
1366 	if (rule->cmd_len > 0) {
1367 		cmd = rule->cmd ;
1368 		if (cmd->opcode == O_PROB) {
1369 			ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1370 			double d = 1.0 * p->d[0];
1371 
1372 			d = (d / 0x7fffffff);
1373 			printf("prob %f ", d);
1374 		}
1375 	}
1376 
1377 	/*
1378 	 * first print actions
1379 	 */
1380         for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1381 			l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1382 		switch(cmd->opcode) {
1383 		case O_CHECK_STATE:
1384 			printf("check-state");
1385 			flags = HAVE_IP; /* avoid printing anything else */
1386 			break;
1387 
1388 		case O_ACCEPT:
1389 			printf("allow");
1390 			break;
1391 
1392 		case O_COUNT:
1393 			printf("count");
1394 			break;
1395 
1396 		case O_DENY:
1397 			printf("deny");
1398 			break;
1399 
1400 		case O_REJECT:
1401 			if (cmd->arg1 == ICMP_REJECT_RST)
1402 				printf("reset");
1403 			else if (cmd->arg1 == ICMP_UNREACH_HOST)
1404 				printf("reject");
1405 			else
1406 				print_reject_code(cmd->arg1);
1407 			break;
1408 
1409 		case O_SKIPTO:
1410 			printf("skipto %u", cmd->arg1);
1411 			break;
1412 
1413 		case O_PIPE:
1414 			printf("pipe %u", cmd->arg1);
1415 			break;
1416 
1417 		case O_QUEUE:
1418 			printf("queue %u", cmd->arg1);
1419 			break;
1420 
1421 		case O_DIVERT:
1422 			printf("divert %u", cmd->arg1);
1423 			break;
1424 
1425 		case O_TEE:
1426 			printf("tee %u", cmd->arg1);
1427 			break;
1428 
1429 		case O_NETGRAPH:
1430 			printf("netgraph %u", cmd->arg1);
1431 			break;
1432 
1433 		case O_NGTEE:
1434 			printf("ngtee %u", cmd->arg1);
1435 			break;
1436 
1437 		case O_FORWARD_IP:
1438 		    {
1439 			ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1440 
1441 			printf("fwd %s", inet_ntoa(s->sa.sin_addr));
1442 			if (s->sa.sin_port)
1443 				printf(",%d", s->sa.sin_port);
1444 		    }
1445 			break;
1446 
1447 		case O_LOG: /* O_LOG is printed last */
1448 			logptr = (ipfw_insn_log *)cmd;
1449 			break;
1450 
1451 		case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1452 			altqptr = (ipfw_insn_altq *)cmd;
1453 			break;
1454 
1455 		default:
1456 			printf("** unrecognized action %d len %d ",
1457 				cmd->opcode, cmd->len);
1458 		}
1459 	}
1460 	if (logptr) {
1461 		if (logptr->max_log > 0)
1462 			printf(" log logamount %d", logptr->max_log);
1463 		else
1464 			printf(" log");
1465 	}
1466 	if (altqptr) {
1467 		const char *qname;
1468 
1469 		qname = altq_qid_to_name(altqptr->qid);
1470 		if (qname == NULL)
1471 			printf(" altq ?<%u>", altqptr->qid);
1472 		else
1473 			printf(" altq %s", qname);
1474 	}
1475 
1476 	/*
1477 	 * then print the body.
1478 	 */
1479         for (l = rule->act_ofs, cmd = rule->cmd ;
1480 			l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1481 		if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1482 			continue;
1483 		if (cmd->opcode == O_IP4) {
1484 			flags |= HAVE_PROTO4;
1485 			break;
1486 		} else if (cmd->opcode == O_IP6) {
1487 			flags |= HAVE_PROTO6;
1488 			break;
1489 		}
1490 	}
1491 	if (rule->_pad & 1) {	/* empty rules before options */
1492 		if (!do_compact) {
1493 			show_prerequisites(&flags, HAVE_PROTO, 0);
1494 			printf(" from any to any");
1495 		}
1496 		flags |= HAVE_IP | HAVE_OPTIONS;
1497 	}
1498 
1499 	if (comment_only)
1500 		comment = "...";
1501 
1502         for (l = rule->act_ofs, cmd = rule->cmd ;
1503 			l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1504 		/* useful alias */
1505 		ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1506 
1507 		if (comment_only) {
1508 			if (cmd->opcode != O_NOP)
1509 				continue;
1510 			printf(" // %s\n", (char *)(cmd + 1));
1511 			return;
1512 		}
1513 
1514 		show_prerequisites(&flags, 0, cmd->opcode);
1515 
1516 		switch(cmd->opcode) {
1517 		case O_PROB:
1518 			break;	/* done already */
1519 
1520 		case O_PROBE_STATE:
1521 			break; /* no need to print anything here */
1522 
1523 		case O_MACADDR2: {
1524 			ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1525 
1526 			if ((cmd->len & F_OR) && !or_block)
1527 				printf(" {");
1528 			if (cmd->len & F_NOT)
1529 				printf(" not");
1530 			printf(" MAC");
1531 			flags |= HAVE_MAC;
1532 			print_mac(m->addr, m->mask);
1533 			print_mac(m->addr + 6, m->mask + 6);
1534 			}
1535 			break;
1536 
1537 		case O_MAC_TYPE:
1538 			if ((cmd->len & F_OR) && !or_block)
1539 				printf(" {");
1540 			print_newports((ipfw_insn_u16 *)cmd, IPPROTO_ETHERTYPE,
1541 				(flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1542 			flags |= HAVE_MAC | HAVE_MACTYPE | HAVE_OPTIONS;
1543 			break;
1544 
1545 		case O_IP_SRC:
1546 		case O_IP_SRC_LOOKUP:
1547 		case O_IP_SRC_MASK:
1548 		case O_IP_SRC_ME:
1549 		case O_IP_SRC_SET:
1550 			show_prerequisites(&flags, HAVE_PROTO, 0);
1551 			if (!(flags & HAVE_SRCIP))
1552 				printf(" from");
1553 			if ((cmd->len & F_OR) && !or_block)
1554 				printf(" {");
1555 			print_ip((ipfw_insn_ip *)cmd,
1556 				(flags & HAVE_OPTIONS) ? " src-ip" : "");
1557 			flags |= HAVE_SRCIP;
1558 			break;
1559 
1560 		case O_IP_DST:
1561 		case O_IP_DST_LOOKUP:
1562 		case O_IP_DST_MASK:
1563 		case O_IP_DST_ME:
1564 		case O_IP_DST_SET:
1565 			show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1566 			if (!(flags & HAVE_DSTIP))
1567 				printf(" to");
1568 			if ((cmd->len & F_OR) && !or_block)
1569 				printf(" {");
1570 			print_ip((ipfw_insn_ip *)cmd,
1571 				(flags & HAVE_OPTIONS) ? " dst-ip" : "");
1572 			flags |= HAVE_DSTIP;
1573 			break;
1574 
1575 		case O_IP6_SRC:
1576 		case O_IP6_SRC_MASK:
1577 		case O_IP6_SRC_ME:
1578 			show_prerequisites(&flags, HAVE_PROTO6, 0);
1579 			if (!(flags & HAVE_SRCIP))
1580 				printf(" from");
1581 			if ((cmd->len & F_OR) && !or_block)
1582 				printf(" {");
1583 			print_ip6((ipfw_insn_ip6 *)cmd,
1584 			    (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1585 			flags |= HAVE_SRCIP | HAVE_PROTO;
1586 			break;
1587 
1588 		case O_IP6_DST:
1589 		case O_IP6_DST_MASK:
1590 		case O_IP6_DST_ME:
1591 			show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1592 			if (!(flags & HAVE_DSTIP))
1593 				printf(" to");
1594 			if ((cmd->len & F_OR) && !or_block)
1595 				printf(" {");
1596 			print_ip6((ipfw_insn_ip6 *)cmd,
1597 			    (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1598 			flags |= HAVE_DSTIP;
1599 			break;
1600 
1601 		case O_FLOW6ID:
1602 		print_flow6id( (ipfw_insn_u32 *) cmd );
1603 		flags |= HAVE_OPTIONS;
1604 		break;
1605 
1606 		case O_IP_DSTPORT:
1607 			show_prerequisites(&flags, HAVE_IP, 0);
1608 		case O_IP_SRCPORT:
1609 			show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1610 			if ((cmd->len & F_OR) && !or_block)
1611 				printf(" {");
1612 			print_newports((ipfw_insn_u16 *)cmd, proto,
1613 				(flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1614 			break;
1615 
1616 		case O_PROTO: {
1617 			struct protoent *pe = NULL;
1618 
1619 			if ((cmd->len & F_OR) && !or_block)
1620 				printf(" {");
1621 			if (cmd->len & F_NOT)
1622 				printf(" not");
1623 			proto = cmd->arg1;
1624 			pe = getprotobynumber(cmd->arg1);
1625 			if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1626 			    !(flags & HAVE_PROTO))
1627 				show_prerequisites(&flags,
1628 				    HAVE_IP | HAVE_OPTIONS, 0);
1629 			if (flags & HAVE_OPTIONS)
1630 				printf(" proto");
1631 			if (pe)
1632 				printf(" %s", pe->p_name);
1633 			else
1634 				printf(" %u", cmd->arg1);
1635 			}
1636 			flags |= HAVE_PROTO;
1637 			break;
1638 
1639 		default: /*options ... */
1640 			if (!(cmd->len & (F_OR|F_NOT)))
1641 				if (((cmd->opcode == O_IP6) &&
1642 				    (flags & HAVE_PROTO6)) ||
1643 				    ((cmd->opcode == O_IP4) &&
1644 				    (flags & HAVE_PROTO4)))
1645 					break;
1646 			show_prerequisites(&flags, HAVE_IP | HAVE_OPTIONS, 0);
1647 			if ((cmd->len & F_OR) && !or_block)
1648 				printf(" {");
1649 			if (cmd->len & F_NOT && cmd->opcode != O_IN)
1650 				printf(" not");
1651 			switch(cmd->opcode) {
1652 			case O_FRAG:
1653 				printf(" frag");
1654 				break;
1655 
1656 			case O_IN:
1657 				printf(cmd->len & F_NOT ? " out" : " in");
1658 				break;
1659 
1660 			case O_DIVERTED:
1661 				switch (cmd->arg1) {
1662 				case 3:
1663 					printf(" diverted");
1664 					break;
1665 				case 1:
1666 					printf(" diverted-loopback");
1667 					break;
1668 				case 2:
1669 					printf(" diverted-output");
1670 					break;
1671 				default:
1672 					printf(" diverted-?<%u>", cmd->arg1);
1673 					break;
1674 				}
1675 				break;
1676 
1677 			case O_LAYER2:
1678 				printf(" layer2");
1679 				break;
1680 			case O_XMIT:
1681 			case O_RECV:
1682 			case O_VIA:
1683 			    {
1684 				char const *s;
1685 				ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1686 
1687 				if (cmd->opcode == O_XMIT)
1688 					s = "xmit";
1689 				else if (cmd->opcode == O_RECV)
1690 					s = "recv";
1691 				else /* if (cmd->opcode == O_VIA) */
1692 					s = "via";
1693 				if (cmdif->name[0] == '\0')
1694 					printf(" %s %s", s,
1695 					    inet_ntoa(cmdif->p.ip));
1696 				else
1697 					printf(" %s %s", s, cmdif->name);
1698 
1699 				break;
1700 			    }
1701 			case O_IPID:
1702 				if (F_LEN(cmd) == 1)
1703 				    printf(" ipid %u", cmd->arg1 );
1704 				else
1705 				    print_newports((ipfw_insn_u16 *)cmd, 0,
1706 					O_IPID);
1707 				break;
1708 
1709 			case O_IPTTL:
1710 				if (F_LEN(cmd) == 1)
1711 				    printf(" ipttl %u", cmd->arg1 );
1712 				else
1713 				    print_newports((ipfw_insn_u16 *)cmd, 0,
1714 					O_IPTTL);
1715 				break;
1716 
1717 			case O_IPVER:
1718 				printf(" ipver %u", cmd->arg1 );
1719 				break;
1720 
1721 			case O_IPPRECEDENCE:
1722 				printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1723 				break;
1724 
1725 			case O_IPLEN:
1726 				if (F_LEN(cmd) == 1)
1727 				    printf(" iplen %u", cmd->arg1 );
1728 				else
1729 				    print_newports((ipfw_insn_u16 *)cmd, 0,
1730 					O_IPLEN);
1731 				break;
1732 
1733 			case O_IPOPT:
1734 				print_flags("ipoptions", cmd, f_ipopts);
1735 				break;
1736 
1737 			case O_IPTOS:
1738 				print_flags("iptos", cmd, f_iptos);
1739 				break;
1740 
1741 			case O_ICMPTYPE:
1742 				print_icmptypes((ipfw_insn_u32 *)cmd);
1743 				break;
1744 
1745 			case O_ESTAB:
1746 				printf(" established");
1747 				break;
1748 
1749 			case O_TCPDATALEN:
1750 				if (F_LEN(cmd) == 1)
1751 				    printf(" tcpdatalen %u", cmd->arg1 );
1752 				else
1753 				    print_newports((ipfw_insn_u16 *)cmd, 0,
1754 					O_TCPDATALEN);
1755 				break;
1756 
1757 			case O_TCPFLAGS:
1758 				print_flags("tcpflags", cmd, f_tcpflags);
1759 				break;
1760 
1761 			case O_TCPOPTS:
1762 				print_flags("tcpoptions", cmd, f_tcpopts);
1763 				break;
1764 
1765 			case O_TCPWIN:
1766 				printf(" tcpwin %d", ntohs(cmd->arg1));
1767 				break;
1768 
1769 			case O_TCPACK:
1770 				printf(" tcpack %d", ntohl(cmd32->d[0]));
1771 				break;
1772 
1773 			case O_TCPSEQ:
1774 				printf(" tcpseq %d", ntohl(cmd32->d[0]));
1775 				break;
1776 
1777 			case O_UID:
1778 			    {
1779 				struct passwd *pwd = getpwuid(cmd32->d[0]);
1780 
1781 				if (pwd)
1782 					printf(" uid %s", pwd->pw_name);
1783 				else
1784 					printf(" uid %u", cmd32->d[0]);
1785 			    }
1786 				break;
1787 
1788 			case O_GID:
1789 			    {
1790 				struct group *grp = getgrgid(cmd32->d[0]);
1791 
1792 				if (grp)
1793 					printf(" gid %s", grp->gr_name);
1794 				else
1795 					printf(" gid %u", cmd32->d[0]);
1796 			    }
1797 				break;
1798 
1799 			case O_JAIL:
1800 				printf(" jail %d", cmd32->d[0]);
1801 				break;
1802 
1803 			case O_VERREVPATH:
1804 				printf(" verrevpath");
1805 				break;
1806 
1807 			case O_VERSRCREACH:
1808 				printf(" versrcreach");
1809 				break;
1810 
1811 			case O_ANTISPOOF:
1812 				printf(" antispoof");
1813 				break;
1814 
1815 			case O_IPSEC:
1816 				printf(" ipsec");
1817 				break;
1818 
1819 			case O_NOP:
1820 				comment = (char *)(cmd + 1);
1821 				break;
1822 
1823 			case O_KEEP_STATE:
1824 				printf(" keep-state");
1825 				break;
1826 
1827 			case O_LIMIT:
1828 			    {
1829 				struct _s_x *p = limit_masks;
1830 				ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1831 				uint8_t x = c->limit_mask;
1832 				char const *comma = " ";
1833 
1834 				printf(" limit");
1835 				for (; p->x != 0 ; p++)
1836 					if ((x & p->x) == p->x) {
1837 						x &= ~p->x;
1838 						printf("%s%s", comma, p->s);
1839 						comma = ",";
1840 					}
1841 				printf(" %d", c->conn_limit);
1842 			    }
1843 				break;
1844 
1845 			case O_IP6:
1846 				printf(" ipv6");
1847 				break;
1848 
1849 			case O_IP4:
1850 				printf(" ipv4");
1851 				break;
1852 
1853 			case O_ICMP6TYPE:
1854 				print_icmp6types((ipfw_insn_u32 *)cmd);
1855 				break;
1856 
1857 			case O_EXT_HDR:
1858 				print_ext6hdr( (ipfw_insn *) cmd );
1859 				break;
1860 
1861 			default:
1862 				printf(" [opcode %d len %d]",
1863 				    cmd->opcode, cmd->len);
1864 			}
1865 		}
1866 		if (cmd->len & F_OR) {
1867 			printf(" or");
1868 			or_block = 1;
1869 		} else if (or_block) {
1870 			printf(" }");
1871 			or_block = 0;
1872 		}
1873 	}
1874 	show_prerequisites(&flags, HAVE_IP, 0);
1875 	if (comment)
1876 		printf(" // %s", comment);
1877 	printf("\n");
1878 }
1879 
1880 static void
1881 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth)
1882 {
1883 	struct protoent *pe;
1884 	struct in_addr a;
1885 	uint16_t rulenum;
1886 
1887 	if (!do_expired) {
1888 		if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1889 			return;
1890 	}
1891 	bcopy(&d->rule, &rulenum, sizeof(rulenum));
1892 	printf("%05d", rulenum);
1893 	if (pcwidth>0 || bcwidth>0)
1894 	    printf(" %*llu %*llu (%ds)", pcwidth,
1895 		align_uint64(&d->pcnt), bcwidth,
1896 		align_uint64(&d->bcnt), d->expire);
1897 	switch (d->dyn_type) {
1898 	case O_LIMIT_PARENT:
1899 		printf(" PARENT %d", d->count);
1900 		break;
1901 	case O_LIMIT:
1902 		printf(" LIMIT");
1903 		break;
1904 	case O_KEEP_STATE: /* bidir, no mask */
1905 		printf(" STATE");
1906 		break;
1907 	}
1908 
1909 	if ((pe = getprotobynumber(d->id.proto)) != NULL)
1910 		printf(" %s", pe->p_name);
1911 	else
1912 		printf(" proto %u", d->id.proto);
1913 
1914 	a.s_addr = htonl(d->id.src_ip);
1915 	printf(" %s %d", inet_ntoa(a), d->id.src_port);
1916 
1917 	a.s_addr = htonl(d->id.dst_ip);
1918 	printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
1919 	printf("\n");
1920 }
1921 
1922 static int
1923 sort_q(const void *pa, const void *pb)
1924 {
1925 	int rev = (do_sort < 0);
1926 	int field = rev ? -do_sort : do_sort;
1927 	long long res = 0;
1928 	const struct dn_flow_queue *a = pa;
1929 	const struct dn_flow_queue *b = pb;
1930 
1931 	switch (field) {
1932 	case 1: /* pkts */
1933 		res = a->len - b->len;
1934 		break;
1935 	case 2: /* bytes */
1936 		res = a->len_bytes - b->len_bytes;
1937 		break;
1938 
1939 	case 3: /* tot pkts */
1940 		res = a->tot_pkts - b->tot_pkts;
1941 		break;
1942 
1943 	case 4: /* tot bytes */
1944 		res = a->tot_bytes - b->tot_bytes;
1945 		break;
1946 	}
1947 	if (res < 0)
1948 		res = -1;
1949 	if (res > 0)
1950 		res = 1;
1951 	return (int)(rev ? res : -res);
1952 }
1953 
1954 static void
1955 list_queues(struct dn_flow_set *fs, struct dn_flow_queue *q)
1956 {
1957 	int l;
1958 	int index_printed, indexes = 0;
1959 	char buff[255];
1960 	struct protoent *pe;
1961 
1962 	if (fs->rq_elements == 0)
1963 		return;
1964 
1965 	if (do_sort != 0)
1966 		heapsort(q, fs->rq_elements, sizeof *q, sort_q);
1967 
1968 	/* Print IPv4 flows */
1969 	index_printed = 0;
1970 	for (l = 0; l < fs->rq_elements; l++) {
1971 		struct in_addr ina;
1972 
1973 		/* XXX: Should check for IPv4 flows */
1974 		if (IS_IP6_FLOW_ID(&(q[l].id)))
1975 			continue;
1976 
1977 		if (!index_printed) {
1978 			index_printed = 1;
1979 			if (indexes > 0)	/* currently a no-op */
1980 				printf("\n");
1981 			indexes++;
1982 			printf("    "
1983 			    "mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
1984 			    fs->flow_mask.proto,
1985 			    fs->flow_mask.src_ip, fs->flow_mask.src_port,
1986 			    fs->flow_mask.dst_ip, fs->flow_mask.dst_port);
1987 
1988 			printf("BKT Prot ___Source IP/port____ "
1989 			    "____Dest. IP/port____ "
1990 			    "Tot_pkt/bytes Pkt/Byte Drp\n");
1991 		}
1992 
1993 		printf("%3d ", q[l].hash_slot);
1994 		pe = getprotobynumber(q[l].id.proto);
1995 		if (pe)
1996 			printf("%-4s ", pe->p_name);
1997 		else
1998 			printf("%4u ", q[l].id.proto);
1999 		ina.s_addr = htonl(q[l].id.src_ip);
2000 		printf("%15s/%-5d ",
2001 		    inet_ntoa(ina), q[l].id.src_port);
2002 		ina.s_addr = htonl(q[l].id.dst_ip);
2003 		printf("%15s/%-5d ",
2004 		    inet_ntoa(ina), q[l].id.dst_port);
2005 		printf("%4qu %8qu %2u %4u %3u\n",
2006 		    q[l].tot_pkts, q[l].tot_bytes,
2007 		    q[l].len, q[l].len_bytes, q[l].drops);
2008 		if (verbose)
2009 			printf("   S %20qd  F %20qd\n",
2010 			    q[l].S, q[l].F);
2011 	}
2012 
2013 	/* Print IPv6 flows */
2014 	index_printed = 0;
2015 	for (l = 0; l < fs->rq_elements; l++) {
2016 		if (!IS_IP6_FLOW_ID(&(q[l].id)))
2017 			continue;
2018 
2019 		if (!index_printed) {
2020 			index_printed = 1;
2021 			if (indexes > 0)
2022 				printf("\n");
2023 			indexes++;
2024 			printf("\n        mask: proto: 0x%02x, flow_id: 0x%08x,  ",
2025 			    fs->flow_mask.proto, fs->flow_mask.flow_id6);
2026 			inet_ntop(AF_INET6, &(fs->flow_mask.src_ip6),
2027 			    buff, sizeof(buff));
2028 			printf("%s/0x%04x -> ", buff, fs->flow_mask.src_port);
2029 			inet_ntop( AF_INET6, &(fs->flow_mask.dst_ip6),
2030 			    buff, sizeof(buff) );
2031 			printf("%s/0x%04x\n", buff, fs->flow_mask.dst_port);
2032 
2033 			printf("BKT ___Prot___ _flow-id_ "
2034 			    "______________Source IPv6/port_______________ "
2035 			    "_______________Dest. IPv6/port_______________ "
2036 			    "Tot_pkt/bytes Pkt/Byte Drp\n");
2037 		}
2038 		printf("%3d ", q[l].hash_slot);
2039 		pe = getprotobynumber(q[l].id.proto);
2040 		if (pe != NULL)
2041 			printf("%9s ", pe->p_name);
2042 		else
2043 			printf("%9u ", q[l].id.proto);
2044 		printf("%7d  %39s/%-5d ", q[l].id.flow_id6,
2045 		    inet_ntop(AF_INET6, &(q[l].id.src_ip6), buff, sizeof(buff)),
2046 		    q[l].id.src_port);
2047 		printf(" %39s/%-5d ",
2048 		    inet_ntop(AF_INET6, &(q[l].id.dst_ip6), buff, sizeof(buff)),
2049 		    q[l].id.dst_port);
2050 		printf(" %4qu %8qu %2u %4u %3u\n",
2051 		    q[l].tot_pkts, q[l].tot_bytes,
2052 		    q[l].len, q[l].len_bytes, q[l].drops);
2053 		if (verbose)
2054 			printf("   S %20qd  F %20qd\n", q[l].S, q[l].F);
2055 	}
2056 }
2057 
2058 static void
2059 print_flowset_parms(struct dn_flow_set *fs, char *prefix)
2060 {
2061 	int l;
2062 	char qs[30];
2063 	char plr[30];
2064 	char red[90];	/* Display RED parameters */
2065 
2066 	l = fs->qsize;
2067 	if (fs->flags_fs & DN_QSIZE_IS_BYTES) {
2068 		if (l >= 8192)
2069 			sprintf(qs, "%d KB", l / 1024);
2070 		else
2071 			sprintf(qs, "%d B", l);
2072 	} else
2073 		sprintf(qs, "%3d sl.", l);
2074 	if (fs->plr)
2075 		sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
2076 	else
2077 		plr[0] = '\0';
2078 	if (fs->flags_fs & DN_IS_RED)	/* RED parameters */
2079 		sprintf(red,
2080 		    "\n\t  %cRED w_q %f min_th %d max_th %d max_p %f",
2081 		    (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ',
2082 		    1.0 * fs->w_q / (double)(1 << SCALE_RED),
2083 		    SCALE_VAL(fs->min_th),
2084 		    SCALE_VAL(fs->max_th),
2085 		    1.0 * fs->max_p / (double)(1 << SCALE_RED));
2086 	else
2087 		sprintf(red, "droptail");
2088 
2089 	printf("%s %s%s %d queues (%d buckets) %s\n",
2090 	    prefix, qs, plr, fs->rq_elements, fs->rq_size, red);
2091 }
2092 
2093 static void
2094 list_pipes(void *data, uint nbytes, int ac, char *av[])
2095 {
2096 	int rulenum;
2097 	void *next = data;
2098 	struct dn_pipe *p = (struct dn_pipe *) data;
2099 	struct dn_flow_set *fs;
2100 	struct dn_flow_queue *q;
2101 	int l;
2102 
2103 	if (ac > 0)
2104 		rulenum = strtoul(*av++, NULL, 10);
2105 	else
2106 		rulenum = 0;
2107 	for (; nbytes >= sizeof *p; p = (struct dn_pipe *)next) {
2108 		double b = p->bandwidth;
2109 		char buf[30];
2110 		char prefix[80];
2111 
2112 		if (p->next != (struct dn_pipe *)DN_IS_PIPE)
2113 			break;	/* done with pipes, now queues */
2114 
2115 		/*
2116 		 * compute length, as pipe have variable size
2117 		 */
2118 		l = sizeof(*p) + p->fs.rq_elements * sizeof(*q);
2119 		next = (char *)p + l;
2120 		nbytes -= l;
2121 
2122 		if ((rulenum != 0 && rulenum != p->pipe_nr) || do_pipe == 2)
2123 			continue;
2124 
2125 		/*
2126 		 * Print rate (or clocking interface)
2127 		 */
2128 		if (p->if_name[0] != '\0')
2129 			sprintf(buf, "%s", p->if_name);
2130 		else if (b == 0)
2131 			sprintf(buf, "unlimited");
2132 		else if (b >= 1000000)
2133 			sprintf(buf, "%7.3f Mbit/s", b/1000000);
2134 		else if (b >= 1000)
2135 			sprintf(buf, "%7.3f Kbit/s", b/1000);
2136 		else
2137 			sprintf(buf, "%7.3f bit/s ", b);
2138 
2139 		sprintf(prefix, "%05d: %s %4d ms ",
2140 		    p->pipe_nr, buf, p->delay);
2141 		print_flowset_parms(&(p->fs), prefix);
2142 		if (verbose)
2143 			printf("   V %20qd\n", p->V >> MY_M);
2144 
2145 		q = (struct dn_flow_queue *)(p+1);
2146 		list_queues(&(p->fs), q);
2147 	}
2148 	for (fs = next; nbytes >= sizeof *fs; fs = next) {
2149 		char prefix[80];
2150 
2151 		if (fs->next != (struct dn_flow_set *)DN_IS_QUEUE)
2152 			break;
2153 		l = sizeof(*fs) + fs->rq_elements * sizeof(*q);
2154 		next = (char *)fs + l;
2155 		nbytes -= l;
2156 
2157 		if (rulenum != 0 && ((rulenum != fs->fs_nr && do_pipe == 2) ||
2158 		    (rulenum != fs->parent_nr && do_pipe == 1))) {
2159 			continue;
2160 		}
2161 
2162 		q = (struct dn_flow_queue *)(fs+1);
2163 		sprintf(prefix, "q%05d: weight %d pipe %d ",
2164 		    fs->fs_nr, fs->weight, fs->parent_nr);
2165 		print_flowset_parms(fs, prefix);
2166 		list_queues(fs, q);
2167 	}
2168 }
2169 
2170 /*
2171  * This one handles all set-related commands
2172  * 	ipfw set { show | enable | disable }
2173  * 	ipfw set swap X Y
2174  * 	ipfw set move X to Y
2175  * 	ipfw set move rule X to Y
2176  */
2177 static void
2178 sets_handler(int ac, char *av[])
2179 {
2180 	uint32_t set_disable, masks[2];
2181 	int i, nbytes;
2182 	uint16_t rulenum;
2183 	uint8_t cmd, new_set;
2184 
2185 	ac--;
2186 	av++;
2187 
2188 	if (!ac)
2189 		errx(EX_USAGE, "set needs command");
2190 	if (_substrcmp(*av, "show") == 0) {
2191 		void *data;
2192 		char const *msg;
2193 
2194 		nbytes = sizeof(struct ip_fw);
2195 		if ((data = calloc(1, nbytes)) == NULL)
2196 			err(EX_OSERR, "calloc");
2197 		if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0)
2198 			err(EX_OSERR, "getsockopt(IP_FW_GET)");
2199 		bcopy(&((struct ip_fw *)data)->next_rule,
2200 			&set_disable, sizeof(set_disable));
2201 
2202 		for (i = 0, msg = "disable" ; i < RESVD_SET; i++)
2203 			if ((set_disable & (1<<i))) {
2204 				printf("%s %d", msg, i);
2205 				msg = "";
2206 			}
2207 		msg = (set_disable) ? " enable" : "enable";
2208 		for (i = 0; i < RESVD_SET; i++)
2209 			if (!(set_disable & (1<<i))) {
2210 				printf("%s %d", msg, i);
2211 				msg = "";
2212 			}
2213 		printf("\n");
2214 	} else if (_substrcmp(*av, "swap") == 0) {
2215 		ac--; av++;
2216 		if (ac != 2)
2217 			errx(EX_USAGE, "set swap needs 2 set numbers\n");
2218 		rulenum = atoi(av[0]);
2219 		new_set = atoi(av[1]);
2220 		if (!isdigit(*(av[0])) || rulenum > RESVD_SET)
2221 			errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2222 		if (!isdigit(*(av[1])) || new_set > RESVD_SET)
2223 			errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2224 		masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
2225 		i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
2226 	} else if (_substrcmp(*av, "move") == 0) {
2227 		ac--; av++;
2228 		if (ac && _substrcmp(*av, "rule") == 0) {
2229 			cmd = 2;
2230 			ac--; av++;
2231 		} else
2232 			cmd = 3;
2233 		if (ac != 3 || _substrcmp(av[1], "to") != 0)
2234 			errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2235 		rulenum = atoi(av[0]);
2236 		new_set = atoi(av[2]);
2237 		if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) ||
2238 			(cmd == 2 && rulenum == 65535) )
2239 			errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2240 		if (!isdigit(*(av[2])) || new_set > RESVD_SET)
2241 			errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2242 		masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
2243 		i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
2244 	} else if (_substrcmp(*av, "disable") == 0 ||
2245 		   _substrcmp(*av, "enable") == 0 ) {
2246 		int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2247 
2248 		ac--; av++;
2249 		masks[0] = masks[1] = 0;
2250 
2251 		while (ac) {
2252 			if (isdigit(**av)) {
2253 				i = atoi(*av);
2254 				if (i < 0 || i > RESVD_SET)
2255 					errx(EX_DATAERR,
2256 					    "invalid set number %d\n", i);
2257 				masks[which] |= (1<<i);
2258 			} else if (_substrcmp(*av, "disable") == 0)
2259 				which = 0;
2260 			else if (_substrcmp(*av, "enable") == 0)
2261 				which = 1;
2262 			else
2263 				errx(EX_DATAERR,
2264 					"invalid set command %s\n", *av);
2265 			av++; ac--;
2266 		}
2267 		if ( (masks[0] & masks[1]) != 0 )
2268 			errx(EX_DATAERR,
2269 			    "cannot enable and disable the same set\n");
2270 
2271 		i = do_cmd(IP_FW_DEL, masks, sizeof(masks));
2272 		if (i)
2273 			warn("set enable/disable: setsockopt(IP_FW_DEL)");
2274 	} else
2275 		errx(EX_USAGE, "invalid set command %s\n", *av);
2276 }
2277 
2278 static void
2279 sysctl_handler(int ac, char *av[], int which)
2280 {
2281 	ac--;
2282 	av++;
2283 
2284 	if (ac == 0) {
2285 		warnx("missing keyword to enable/disable\n");
2286 	} else if (_substrcmp(*av, "firewall") == 0) {
2287 		sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2288 		    &which, sizeof(which));
2289 	} else if (_substrcmp(*av, "one_pass") == 0) {
2290 		sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2291 		    &which, sizeof(which));
2292 	} else if (_substrcmp(*av, "debug") == 0) {
2293 		sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2294 		    &which, sizeof(which));
2295 	} else if (_substrcmp(*av, "verbose") == 0) {
2296 		sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2297 		    &which, sizeof(which));
2298 	} else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2299 		sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2300 		    &which, sizeof(which));
2301 	} else if (_substrcmp(*av, "altq") == 0) {
2302 		altq_set_enabled(which);
2303 	} else {
2304 		warnx("unrecognize enable/disable keyword: %s\n", *av);
2305 	}
2306 }
2307 
2308 static void
2309 list(int ac, char *av[], int show_counters)
2310 {
2311 	struct ip_fw *r;
2312 	ipfw_dyn_rule *dynrules, *d;
2313 
2314 #define NEXT(r)	((struct ip_fw *)((char *)r + RULESIZE(r)))
2315 	char *lim;
2316 	void *data = NULL;
2317 	int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
2318 	int exitval = EX_OK;
2319 	int lac;
2320 	char **lav;
2321 	u_long rnum, last;
2322 	char *endptr;
2323 	int seen = 0;
2324 
2325 	const int ocmd = do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
2326 	int nalloc = 1024;	/* start somewhere... */
2327 
2328 	last = 0;
2329 
2330 	if (test_only) {
2331 		fprintf(stderr, "Testing only, list disabled\n");
2332 		return;
2333 	}
2334 
2335 	ac--;
2336 	av++;
2337 
2338 	/* get rules or pipes from kernel, resizing array as necessary */
2339 	nbytes = nalloc;
2340 
2341 	while (nbytes >= nalloc) {
2342 		nalloc = nalloc * 2 + 200;
2343 		nbytes = nalloc;
2344 		if ((data = realloc(data, nbytes)) == NULL)
2345 			err(EX_OSERR, "realloc");
2346 		if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0)
2347 			err(EX_OSERR, "getsockopt(IP_%s_GET)",
2348 				do_pipe ? "DUMMYNET" : "FW");
2349 	}
2350 
2351 	if (do_pipe) {
2352 		list_pipes(data, nbytes, ac, av);
2353 		goto done;
2354 	}
2355 
2356 	/*
2357 	 * Count static rules. They have variable size so we
2358 	 * need to scan the list to count them.
2359 	 */
2360 	for (nstat = 1, r = data, lim = (char *)data + nbytes;
2361 		    r->rulenum < 65535 && (char *)r < lim;
2362 		    ++nstat, r = NEXT(r) )
2363 		; /* nothing */
2364 
2365 	/*
2366 	 * Count dynamic rules. This is easier as they have
2367 	 * fixed size.
2368 	 */
2369 	r = NEXT(r);
2370 	dynrules = (ipfw_dyn_rule *)r ;
2371 	n = (char *)r - (char *)data;
2372 	ndyn = (nbytes - n) / sizeof *dynrules;
2373 
2374 	/* if showing stats, figure out column widths ahead of time */
2375 	bcwidth = pcwidth = 0;
2376 	if (show_counters) {
2377 		for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2378 			/* packet counter */
2379 			width = snprintf(NULL, 0, "%llu",
2380 			    align_uint64(&r->pcnt));
2381 			if (width > pcwidth)
2382 				pcwidth = width;
2383 
2384 			/* byte counter */
2385 			width = snprintf(NULL, 0, "%llu",
2386 			    align_uint64(&r->bcnt));
2387 			if (width > bcwidth)
2388 				bcwidth = width;
2389 		}
2390 	}
2391 	if (do_dynamic && ndyn) {
2392 		for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2393 			width = snprintf(NULL, 0, "%llu",
2394 			    align_uint64(&d->pcnt));
2395 			if (width > pcwidth)
2396 				pcwidth = width;
2397 
2398 			width = snprintf(NULL, 0, "%llu",
2399 			    align_uint64(&d->bcnt));
2400 			if (width > bcwidth)
2401 				bcwidth = width;
2402 		}
2403 	}
2404 	/* if no rule numbers were specified, list all rules */
2405 	if (ac == 0) {
2406 		for (n = 0, r = data; n < nstat; n++, r = NEXT(r) )
2407 			show_ipfw(r, pcwidth, bcwidth);
2408 
2409 		if (do_dynamic && ndyn) {
2410 			printf("## Dynamic rules (%d):\n", ndyn);
2411 			for (n = 0, d = dynrules; n < ndyn; n++, d++)
2412 				show_dyn_ipfw(d, pcwidth, bcwidth);
2413 		}
2414 		goto done;
2415 	}
2416 
2417 	/* display specific rules requested on command line */
2418 
2419 	for (lac = ac, lav = av; lac != 0; lac--) {
2420 		/* convert command line rule # */
2421 		last = rnum = strtoul(*lav++, &endptr, 10);
2422 		if (*endptr == '-')
2423 			last = strtoul(endptr+1, &endptr, 10);
2424 		if (*endptr) {
2425 			exitval = EX_USAGE;
2426 			warnx("invalid rule number: %s", *(lav - 1));
2427 			continue;
2428 		}
2429 		for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) {
2430 			if (r->rulenum > last)
2431 				break;
2432 			if (r->rulenum >= rnum && r->rulenum <= last) {
2433 				show_ipfw(r, pcwidth, bcwidth);
2434 				seen = 1;
2435 			}
2436 		}
2437 		if (!seen) {
2438 			/* give precedence to other error(s) */
2439 			if (exitval == EX_OK)
2440 				exitval = EX_UNAVAILABLE;
2441 			warnx("rule %lu does not exist", rnum);
2442 		}
2443 	}
2444 
2445 	if (do_dynamic && ndyn) {
2446 		printf("## Dynamic rules:\n");
2447 		for (lac = ac, lav = av; lac != 0; lac--) {
2448 			last = rnum = strtoul(*lav++, &endptr, 10);
2449 			if (*endptr == '-')
2450 				last = strtoul(endptr+1, &endptr, 10);
2451 			if (*endptr)
2452 				/* already warned */
2453 				continue;
2454 			for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2455 				uint16_t rulenum;
2456 
2457 				bcopy(&d->rule, &rulenum, sizeof(rulenum));
2458 				if (rulenum > rnum)
2459 					break;
2460 				if (r->rulenum >= rnum && r->rulenum <= last)
2461 					show_dyn_ipfw(d, pcwidth, bcwidth);
2462 			}
2463 		}
2464 	}
2465 
2466 	ac = 0;
2467 
2468 done:
2469 	free(data);
2470 
2471 	if (exitval != EX_OK)
2472 		exit(exitval);
2473 #undef NEXT
2474 }
2475 
2476 static void
2477 show_usage(void)
2478 {
2479 	fprintf(stderr, "usage: ipfw [options]\n"
2480 "do \"ipfw -h\" or see ipfw manpage for details\n"
2481 );
2482 	exit(EX_USAGE);
2483 }
2484 
2485 static void
2486 help(void)
2487 {
2488 	fprintf(stderr,
2489 "ipfw syntax summary (but please do read the ipfw(8) manpage):\n"
2490 "ipfw [-abcdefhnNqStTv] <command> where <command> is one of:\n"
2491 "add [num] [set N] [prob x] RULE-BODY\n"
2492 "{pipe|queue} N config PIPE-BODY\n"
2493 "[pipe|queue] {zero|delete|show} [N{,N}]\n"
2494 "set [disable N... enable N...] | move [rule] X to Y | swap X Y | show\n"
2495 "table N {add ip[/bits] [value] | delete ip[/bits] | flush | list}\n"
2496 "\n"
2497 "RULE-BODY:	check-state [PARAMS] | ACTION [PARAMS] ADDR [OPTION_LIST]\n"
2498 "ACTION:	check-state | allow | count | deny | unreach CODE | skipto N |\n"
2499 "		{divert|tee} PORT | forward ADDR | pipe N | queue N\n"
2500 "PARAMS: 	[log [logamount LOGLIMIT]] [altq QUEUE_NAME]\n"
2501 "ADDR:		[ MAC dst src ether_type ] \n"
2502 "		[ ip from IPADDR [ PORT ] to IPADDR [ PORTLIST ] ]\n"
2503 "		[ ipv6|ip6 from IP6ADDR [ PORT ] to IP6ADDR [ PORTLIST ] ]\n"
2504 "IPADDR:	[not] { any | me | ip/bits{x,y,z} | table(t[,v]) | IPLIST }\n"
2505 "IP6ADDR:	[not] { any | me | me6 | ip6/bits | IP6LIST }\n"
2506 "IP6LIST:	{ ip6 | ip6/bits }[,IP6LIST]\n"
2507 "IPLIST:	{ ip | ip/bits | ip:mask }[,IPLIST]\n"
2508 "OPTION_LIST:	OPTION [OPTION_LIST]\n"
2509 "OPTION:	bridged | diverted | diverted-loopback | diverted-output |\n"
2510 "	{dst-ip|src-ip} IPADDR | {dst-ip6|src-ip6|dst-ipv6|src-ipv6} IP6ADDR |\n"
2511 "	{dst-port|src-port} LIST |\n"
2512 "	estab | frag | {gid|uid} N | icmptypes LIST | in | out | ipid LIST |\n"
2513 "	iplen LIST | ipoptions SPEC | ipprecedence | ipsec | iptos SPEC |\n"
2514 "	ipttl LIST | ipversion VER | keep-state | layer2 | limit ... |\n"
2515 "	icmp6types LIST | ext6hdr LIST | flow-id N[,N] |\n"
2516 "	mac ... | mac-type LIST | proto LIST | {recv|xmit|via} {IF|IPADDR} |\n"
2517 "	setup | {tcpack|tcpseq|tcpwin} NN | tcpflags SPEC | tcpoptions SPEC |\n"
2518 "	tcpdatalen LIST | verrevpath | versrcreach | antispoof\n"
2519 );
2520 exit(0);
2521 }
2522 
2523 
2524 static int
2525 lookup_host (char *host, struct in_addr *ipaddr)
2526 {
2527 	struct hostent *he;
2528 
2529 	if (!inet_aton(host, ipaddr)) {
2530 		if ((he = gethostbyname(host)) == NULL)
2531 			return(-1);
2532 		*ipaddr = *(struct in_addr *)he->h_addr_list[0];
2533 	}
2534 	return(0);
2535 }
2536 
2537 /*
2538  * fills the addr and mask fields in the instruction as appropriate from av.
2539  * Update length as appropriate.
2540  * The following formats are allowed:
2541  *	me	returns O_IP_*_ME
2542  *	1.2.3.4		single IP address
2543  *	1.2.3.4:5.6.7.8	address:mask
2544  *	1.2.3.4/24	address/mask
2545  *	1.2.3.4/26{1,6,5,4,23}	set of addresses in a subnet
2546  * We can have multiple comma-separated address/mask entries.
2547  */
2548 static void
2549 fill_ip(ipfw_insn_ip *cmd, char *av)
2550 {
2551 	int len = 0;
2552 	uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2553 
2554 	cmd->o.len &= ~F_LEN_MASK;	/* zero len */
2555 
2556 	if (_substrcmp(av, "any") == 0)
2557 		return;
2558 
2559 	if (_substrcmp(av, "me") == 0) {
2560 		cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2561 		return;
2562 	}
2563 
2564 	if (strncmp(av, "table(", 6) == 0) {
2565 		char *p = strchr(av + 6, ',');
2566 
2567 		if (p)
2568 			*p++ = '\0';
2569 		cmd->o.opcode = O_IP_DST_LOOKUP;
2570 		cmd->o.arg1 = strtoul(av + 6, NULL, 0);
2571 		if (p) {
2572 			cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2573 			d[0] = strtoul(p, NULL, 0);
2574 		} else
2575 			cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2576 		return;
2577 	}
2578 
2579     while (av) {
2580 	/*
2581 	 * After the address we can have '/' or ':' indicating a mask,
2582 	 * ',' indicating another address follows, '{' indicating a
2583 	 * set of addresses of unspecified size.
2584 	 */
2585 	char *p = strpbrk(av, "/:,{");
2586 	int masklen;
2587 	char md;
2588 
2589 	if (p) {
2590 		md = *p;
2591 		*p++ = '\0';
2592 	} else
2593 		md = '\0';
2594 
2595 	if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2596 		errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2597 	switch (md) {
2598 	case ':':
2599 		if (!inet_aton(p, (struct in_addr *)&d[1]))
2600 			errx(EX_DATAERR, "bad netmask ``%s''", p);
2601 		break;
2602 	case '/':
2603 		masklen = atoi(p);
2604 		if (masklen == 0)
2605 			d[1] = htonl(0);	/* mask */
2606 		else if (masklen > 32)
2607 			errx(EX_DATAERR, "bad width ``%s''", p);
2608 		else
2609 			d[1] = htonl(~0 << (32 - masklen));
2610 		break;
2611 	case '{':	/* no mask, assume /24 and put back the '{' */
2612 		d[1] = htonl(~0 << (32 - 24));
2613 		*(--p) = md;
2614 		break;
2615 
2616 	case ',':	/* single address plus continuation */
2617 		*(--p) = md;
2618 		/* FALLTHROUGH */
2619 	case 0:		/* initialization value */
2620 	default:
2621 		d[1] = htonl(~0);	/* force /32 */
2622 		break;
2623 	}
2624 	d[0] &= d[1];		/* mask base address with mask */
2625 	/* find next separator */
2626 	if (p)
2627 		p = strpbrk(p, ",{");
2628 	if (p && *p == '{') {
2629 		/*
2630 		 * We have a set of addresses. They are stored as follows:
2631 		 *   arg1	is the set size (powers of 2, 2..256)
2632 		 *   addr	is the base address IN HOST FORMAT
2633 		 *   mask..	is an array of arg1 bits (rounded up to
2634 		 *		the next multiple of 32) with bits set
2635 		 *		for each host in the map.
2636 		 */
2637 		uint32_t *map = (uint32_t *)&cmd->mask;
2638 		int low, high;
2639 		int i = contigmask((uint8_t *)&(d[1]), 32);
2640 
2641 		if (len > 0)
2642 			errx(EX_DATAERR, "address set cannot be in a list");
2643 		if (i < 24 || i > 31)
2644 			errx(EX_DATAERR, "invalid set with mask %d\n", i);
2645 		cmd->o.arg1 = 1<<(32-i);	/* map length		*/
2646 		d[0] = ntohl(d[0]);		/* base addr in host format */
2647 		cmd->o.opcode = O_IP_DST_SET;	/* default */
2648 		cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2649 		for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2650 			map[i] = 0;	/* clear map */
2651 
2652 		av = p + 1;
2653 		low = d[0] & 0xff;
2654 		high = low + cmd->o.arg1 - 1;
2655 		/*
2656 		 * Here, i stores the previous value when we specify a range
2657 		 * of addresses within a mask, e.g. 45-63. i = -1 means we
2658 		 * have no previous value.
2659 		 */
2660 		i = -1;	/* previous value in a range */
2661 		while (isdigit(*av)) {
2662 			char *s;
2663 			int a = strtol(av, &s, 0);
2664 
2665 			if (s == av) { /* no parameter */
2666 			    if (*av != '}')
2667 				errx(EX_DATAERR, "set not closed\n");
2668 			    if (i != -1)
2669 				errx(EX_DATAERR, "incomplete range %d-", i);
2670 			    break;
2671 			}
2672 			if (a < low || a > high)
2673 			    errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2674 				a, low, high);
2675 			a -= low;
2676 			if (i == -1)	/* no previous in range */
2677 			    i = a;
2678 			else {		/* check that range is valid */
2679 			    if (i > a)
2680 				errx(EX_DATAERR, "invalid range %d-%d",
2681 					i+low, a+low);
2682 			    if (*s == '-')
2683 				errx(EX_DATAERR, "double '-' in range");
2684 			}
2685 			for (; i <= a; i++)
2686 			    map[i/32] |= 1<<(i & 31);
2687 			i = -1;
2688 			if (*s == '-')
2689 			    i = a;
2690 			else if (*s == '}')
2691 			    break;
2692 			av = s+1;
2693 		}
2694 		return;
2695 	}
2696 	av = p;
2697 	if (av)			/* then *av must be a ',' */
2698 		av++;
2699 
2700 	/* Check this entry */
2701 	if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2702 		/*
2703 		 * 'any' turns the entire list into a NOP.
2704 		 * 'not any' never matches, so it is removed from the
2705 		 * list unless it is the only item, in which case we
2706 		 * report an error.
2707 		 */
2708 		if (cmd->o.len & F_NOT) {	/* "not any" never matches */
2709 			if (av == NULL && len == 0) /* only this entry */
2710 				errx(EX_DATAERR, "not any never matches");
2711 		}
2712 		/* else do nothing and skip this entry */
2713 		return;
2714 	}
2715 	/* A single IP can be stored in an optimized format */
2716 	if (d[1] == IP_MASK_ALL && av == NULL && len == 0) {
2717 		cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2718 		return;
2719 	}
2720 	len += 2;	/* two words... */
2721 	d += 2;
2722     } /* end while */
2723     cmd->o.len |= len+1;
2724 }
2725 
2726 
2727 /* Try to find ipv6 address by hostname */
2728 static int
2729 lookup_host6 (char *host, struct in6_addr *ip6addr)
2730 {
2731 	struct hostent *he;
2732 
2733 	if (!inet_pton(AF_INET6, host, ip6addr)) {
2734 		if ((he = gethostbyname2(host, AF_INET6)) == NULL)
2735 			return(-1);
2736 		memcpy(ip6addr, he->h_addr_list[0], sizeof( struct in6_addr));
2737 	}
2738 	return(0);
2739 }
2740 
2741 
2742 /* n2mask sets n bits of the mask */
2743 static void
2744 n2mask(struct in6_addr *mask, int n)
2745 {
2746 	static int	minimask[9] =
2747 	    { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
2748 	u_char		*p;
2749 
2750 	memset(mask, 0, sizeof(struct in6_addr));
2751 	p = (u_char *) mask;
2752 	for (; n > 0; p++, n -= 8) {
2753 		if (n >= 8)
2754 			*p = 0xff;
2755 		else
2756 			*p = minimask[n];
2757 	}
2758 	return;
2759 }
2760 
2761 
2762 /*
2763  * fill the addr and mask fields in the instruction as appropriate from av.
2764  * Update length as appropriate.
2765  * The following formats are allowed:
2766  *     any     matches any IP6. Actually returns an empty instruction.
2767  *     me      returns O_IP6_*_ME
2768  *
2769  *     03f1::234:123:0342                single IP6 addres
2770  *     03f1::234:123:0342/24            address/mask
2771  *     03f1::234:123:0342/24,03f1::234:123:0343/               List of address
2772  *
2773  * Set of address (as in ipv6) not supported because ipv6 address
2774  * are typically random past the initial prefix.
2775  * Return 1 on success, 0 on failure.
2776  */
2777 static int
2778 fill_ip6(ipfw_insn_ip6 *cmd, char *av)
2779 {
2780 	int len = 0;
2781 	struct in6_addr *d = &(cmd->addr6);
2782 	/*
2783 	 * Needed for multiple address.
2784 	 * Note d[1] points to struct in6_add r mask6 of cmd
2785 	 */
2786 
2787        cmd->o.len &= ~F_LEN_MASK;	/* zero len */
2788 
2789        if (strcmp(av, "any") == 0)
2790 	       return (1);
2791 
2792 
2793        if (strcmp(av, "me") == 0) {	/* Set the data for "me" opt*/
2794 	       cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2795 	       return (1);
2796        }
2797 
2798        if (strcmp(av, "me6") == 0) {	/* Set the data for "me" opt*/
2799 	       cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2800 	       return (1);
2801        }
2802 
2803        av = strdup(av);
2804        while (av) {
2805 		/*
2806 		 * After the address we can have '/' indicating a mask,
2807 		 * or ',' indicating another address follows.
2808 		 */
2809 
2810 		char *p;
2811 		int masklen;
2812 		char md = '\0';
2813 
2814 		if ((p = strpbrk(av, "/,")) ) {
2815 			md = *p;	/* save the separator */
2816 			*p = '\0';	/* terminate address string */
2817 			p++;		/* and skip past it */
2818 		}
2819 		/* now p points to NULL, mask or next entry */
2820 
2821 		/* lookup stores address in *d as a side effect */
2822 		if (lookup_host6(av, d) != 0) {
2823 			/* XXX: failed. Free memory and go */
2824 			errx(EX_DATAERR, "bad address \"%s\"", av);
2825 		}
2826 		/* next, look at the mask, if any */
2827 		masklen = (md == '/') ? atoi(p) : 128;
2828 		if (masklen > 128 || masklen < 0)
2829 			errx(EX_DATAERR, "bad width \"%s\''", p);
2830 		else
2831 			n2mask(&d[1], masklen);
2832 
2833 		APPLY_MASK(d, &d[1])   /* mask base address with mask */
2834 
2835 		/* find next separator */
2836 
2837 		if (md == '/') {	/* find separator past the mask */
2838 			p = strpbrk(p, ",");
2839 			if (p != NULL)
2840 				p++;
2841 		}
2842 		av = p;
2843 
2844 		/* Check this entry */
2845 		if (masklen == 0) {
2846 			/*
2847 			 * 'any' turns the entire list into a NOP.
2848 			 * 'not any' never matches, so it is removed from the
2849 			 * list unless it is the only item, in which case we
2850 			 * report an error.
2851 			 */
2852 			if (cmd->o.len & F_NOT && av == NULL && len == 0)
2853 				errx(EX_DATAERR, "not any never matches");
2854 			continue;
2855 		}
2856 
2857 		/*
2858 		 * A single IP can be stored alone
2859 		 */
2860 		if (masklen == 128 && av == NULL && len == 0) {
2861 			len = F_INSN_SIZE(struct in6_addr);
2862 			break;
2863 		}
2864 
2865 		/* Update length and pointer to arguments */
2866 		len += F_INSN_SIZE(struct in6_addr)*2;
2867 		d += 2;
2868 	} /* end while */
2869 
2870 	/*
2871 	 * Total length of the command, remember that 1 is the size of
2872 	 * the base command.
2873 	 */
2874 	cmd->o.len |= len+1;
2875 	free(av);
2876 	return (1);
2877 }
2878 
2879 /*
2880  * fills command for ipv6 flow-id filtering
2881  * note that the 20 bit flow number is stored in a array of u_int32_t
2882  * it's supported lists of flow-id, so in the o.arg1 we store how many
2883  * additional flow-id we want to filter, the basic is 1
2884  */
2885 void
2886 fill_flow6( ipfw_insn_u32 *cmd, char *av )
2887 {
2888 	u_int32_t type;	 /* Current flow number */
2889 	u_int16_t nflow = 0;    /* Current flow index */
2890 	char *s = av;
2891 	cmd->d[0] = 0;	  /* Initializing the base number*/
2892 
2893 	while (s) {
2894 		av = strsep( &s, ",") ;
2895 		type = strtoul(av, &av, 0);
2896 		if (*av != ',' && *av != '\0')
2897 			errx(EX_DATAERR, "invalid ipv6 flow number %s", av);
2898 		if (type > 0xfffff)
2899 			errx(EX_DATAERR, "flow number out of range %s", av);
2900 		cmd->d[nflow] |= type;
2901 		nflow++;
2902 	}
2903 	if( nflow > 0 ) {
2904 		cmd->o.opcode = O_FLOW6ID;
2905 		cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + nflow;
2906 		cmd->o.arg1 = nflow;
2907 	}
2908 	else {
2909 		errx(EX_DATAERR, "invalid ipv6 flow number %s", av);
2910 	}
2911 }
2912 
2913 static ipfw_insn *
2914 add_srcip6(ipfw_insn *cmd, char *av)
2915 {
2916 
2917 	fill_ip6((ipfw_insn_ip6 *)cmd, av);
2918 	if (F_LEN(cmd) == 0)				/* any */
2919 		;
2920 	if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) {	/* "me" */
2921 		cmd->opcode = O_IP6_SRC_ME;
2922 	} else if (F_LEN(cmd) ==
2923 	    (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) {
2924 		/* single IP, no mask*/
2925 		cmd->opcode = O_IP6_SRC;
2926 	} else {					/* addr/mask opt */
2927 		cmd->opcode = O_IP6_SRC_MASK;
2928 	}
2929 	return cmd;
2930 }
2931 
2932 static ipfw_insn *
2933 add_dstip6(ipfw_insn *cmd, char *av)
2934 {
2935 
2936 	fill_ip6((ipfw_insn_ip6 *)cmd, av);
2937 	if (F_LEN(cmd) == 0)				/* any */
2938 		;
2939 	if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) {	/* "me" */
2940 		cmd->opcode = O_IP6_DST_ME;
2941 	} else if (F_LEN(cmd) ==
2942 	    (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) {
2943 		/* single IP, no mask*/
2944 		cmd->opcode = O_IP6_DST;
2945 	} else {					/* addr/mask opt */
2946 		cmd->opcode = O_IP6_DST_MASK;
2947 	}
2948 	return cmd;
2949 }
2950 
2951 
2952 /*
2953  * helper function to process a set of flags and set bits in the
2954  * appropriate masks.
2955  */
2956 static void
2957 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
2958 	struct _s_x *flags, char *p)
2959 {
2960 	uint8_t set=0, clear=0;
2961 
2962 	while (p && *p) {
2963 		char *q;	/* points to the separator */
2964 		int val;
2965 		uint8_t *which;	/* mask we are working on */
2966 
2967 		if (*p == '!') {
2968 			p++;
2969 			which = &clear;
2970 		} else
2971 			which = &set;
2972 		q = strchr(p, ',');
2973 		if (q)
2974 			*q++ = '\0';
2975 		val = match_token(flags, p);
2976 		if (val <= 0)
2977 			errx(EX_DATAERR, "invalid flag %s", p);
2978 		*which |= (uint8_t)val;
2979 		p = q;
2980 	}
2981         cmd->opcode = opcode;
2982         cmd->len =  (cmd->len & (F_NOT | F_OR)) | 1;
2983         cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
2984 }
2985 
2986 
2987 static void
2988 delete(int ac, char *av[])
2989 {
2990 	uint32_t rulenum;
2991 	struct dn_pipe p;
2992 	int i;
2993 	int exitval = EX_OK;
2994 	int do_set = 0;
2995 
2996 	memset(&p, 0, sizeof p);
2997 
2998 	av++; ac--;
2999 	NEED1("missing rule specification");
3000 	if (ac > 0 && _substrcmp(*av, "set") == 0) {
3001 		do_set = 1;	/* delete set */
3002 		ac--; av++;
3003 	}
3004 
3005 	/* Rule number */
3006 	while (ac && isdigit(**av)) {
3007 		i = atoi(*av); av++; ac--;
3008 		if (do_pipe) {
3009 			if (do_pipe == 1)
3010 				p.pipe_nr = i;
3011 			else
3012 				p.fs.fs_nr = i;
3013 			i = do_cmd(IP_DUMMYNET_DEL, &p, sizeof p);
3014 			if (i) {
3015 				exitval = 1;
3016 				warn("rule %u: setsockopt(IP_DUMMYNET_DEL)",
3017 				    do_pipe == 1 ? p.pipe_nr : p.fs.fs_nr);
3018 			}
3019 		} else {
3020 			rulenum =  (i & 0xffff) | (do_set << 24);
3021 			i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum);
3022 			if (i) {
3023 				exitval = EX_UNAVAILABLE;
3024 				warn("rule %u: setsockopt(IP_FW_DEL)",
3025 				    rulenum);
3026 			}
3027 		}
3028 	}
3029 	if (exitval != EX_OK)
3030 		exit(exitval);
3031 }
3032 
3033 
3034 /*
3035  * fill the interface structure. We do not check the name as we can
3036  * create interfaces dynamically, so checking them at insert time
3037  * makes relatively little sense.
3038  * Interface names containing '*', '?', or '[' are assumed to be shell
3039  * patterns which match interfaces.
3040  */
3041 static void
3042 fill_iface(ipfw_insn_if *cmd, char *arg)
3043 {
3044 	cmd->name[0] = '\0';
3045 	cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3046 
3047 	/* Parse the interface or address */
3048 	if (strcmp(arg, "any") == 0)
3049 		cmd->o.len = 0;		/* effectively ignore this command */
3050 	else if (!isdigit(*arg)) {
3051 		strlcpy(cmd->name, arg, sizeof(cmd->name));
3052 		cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3053 	} else if (!inet_aton(arg, &cmd->p.ip))
3054 		errx(EX_DATAERR, "bad ip address ``%s''", arg);
3055 }
3056 
3057 static void
3058 config_pipe(int ac, char **av)
3059 {
3060 	struct dn_pipe p;
3061 	int i;
3062 	char *end;
3063 	void *par = NULL;
3064 
3065 	memset(&p, 0, sizeof p);
3066 
3067 	av++; ac--;
3068 	/* Pipe number */
3069 	if (ac && isdigit(**av)) {
3070 		i = atoi(*av); av++; ac--;
3071 		if (do_pipe == 1)
3072 			p.pipe_nr = i;
3073 		else
3074 			p.fs.fs_nr = i;
3075 	}
3076 	while (ac > 0) {
3077 		double d;
3078 		int tok = match_token(dummynet_params, *av);
3079 		ac--; av++;
3080 
3081 		switch(tok) {
3082 		case TOK_NOERROR:
3083 			p.fs.flags_fs |= DN_NOERROR;
3084 			break;
3085 
3086 		case TOK_PLR:
3087 			NEED1("plr needs argument 0..1\n");
3088 			d = strtod(av[0], NULL);
3089 			if (d > 1)
3090 				d = 1;
3091 			else if (d < 0)
3092 				d = 0;
3093 			p.fs.plr = (int)(d*0x7fffffff);
3094 			ac--; av++;
3095 			break;
3096 
3097 		case TOK_QUEUE:
3098 			NEED1("queue needs queue size\n");
3099 			end = NULL;
3100 			p.fs.qsize = strtoul(av[0], &end, 0);
3101 			if (*end == 'K' || *end == 'k') {
3102 				p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
3103 				p.fs.qsize *= 1024;
3104 			} else if (*end == 'B' ||
3105 			    _substrcmp2(end, "by", "bytes") == 0) {
3106 				p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
3107 			}
3108 			ac--; av++;
3109 			break;
3110 
3111 		case TOK_BUCKETS:
3112 			NEED1("buckets needs argument\n");
3113 			p.fs.rq_size = strtoul(av[0], NULL, 0);
3114 			ac--; av++;
3115 			break;
3116 
3117 		case TOK_MASK:
3118 			NEED1("mask needs mask specifier\n");
3119 			/*
3120 			 * per-flow queue, mask is dst_ip, dst_port,
3121 			 * src_ip, src_port, proto measured in bits
3122 			 */
3123 			par = NULL;
3124 
3125 			bzero(&p.fs.flow_mask, sizeof(p.fs.flow_mask));
3126 			end = NULL;
3127 
3128 			while (ac >= 1) {
3129 			    uint32_t *p32 = NULL;
3130 			    uint16_t *p16 = NULL;
3131 			    uint32_t *p20 = NULL;
3132 			    struct in6_addr *pa6 = NULL;
3133 			    uint32_t a;
3134 
3135 			    tok = match_token(dummynet_params, *av);
3136 			    ac--; av++;
3137 			    switch(tok) {
3138 			    case TOK_ALL:
3139 				    /*
3140 				     * special case, all bits significant
3141 				     */
3142 				    p.fs.flow_mask.dst_ip = ~0;
3143 				    p.fs.flow_mask.src_ip = ~0;
3144 				    p.fs.flow_mask.dst_port = ~0;
3145 				    p.fs.flow_mask.src_port = ~0;
3146 				    p.fs.flow_mask.proto = ~0;
3147 				    n2mask(&(p.fs.flow_mask.dst_ip6), 128);
3148 				    n2mask(&(p.fs.flow_mask.src_ip6), 128);
3149 				    p.fs.flow_mask.flow_id6 = ~0;
3150 				    p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
3151 				    goto end_mask;
3152 
3153 			    case TOK_DSTIP:
3154 				    p32 = &p.fs.flow_mask.dst_ip;
3155 				    break;
3156 
3157 			    case TOK_SRCIP:
3158 				    p32 = &p.fs.flow_mask.src_ip;
3159 				    break;
3160 
3161 			    case TOK_DSTIP6:
3162 				    pa6 = &(p.fs.flow_mask.dst_ip6);
3163 				    break;
3164 
3165 			    case TOK_SRCIP6:
3166 				    pa6 = &(p.fs.flow_mask.src_ip6);
3167 				    break;
3168 
3169 			    case TOK_FLOWID:
3170 				    p20 = &p.fs.flow_mask.flow_id6;
3171 				    break;
3172 
3173 			    case TOK_DSTPORT:
3174 				    p16 = &p.fs.flow_mask.dst_port;
3175 				    break;
3176 
3177 			    case TOK_SRCPORT:
3178 				    p16 = &p.fs.flow_mask.src_port;
3179 				    break;
3180 
3181 			    case TOK_PROTO:
3182 				    break;
3183 
3184 			    default:
3185 				    ac++; av--; /* backtrack */
3186 				    goto end_mask;
3187 			    }
3188 			    if (ac < 1)
3189 				    errx(EX_USAGE, "mask: value missing");
3190 			    if (*av[0] == '/') {
3191 				    a = strtoul(av[0]+1, &end, 0);
3192 				    if (pa6 == NULL)
3193 					    a = (a == 32) ? ~0 : (1 << a) - 1;
3194 			    } else
3195 				    a = strtoul(av[0], &end, 0);
3196 			    if (p32 != NULL)
3197 				    *p32 = a;
3198 			    else if (p16 != NULL) {
3199 				    if (a > 0xFFFF)
3200 					    errx(EX_DATAERR,
3201 						"port mask must be 16 bit");
3202 				    *p16 = (uint16_t)a;
3203 			    } else if (p20 != NULL) {
3204 				    if (a > 0xfffff)
3205 					errx(EX_DATAERR,
3206 					    "flow_id mask must be 20 bit");
3207 				    *p20 = (uint32_t)a;
3208 			    } else if (pa6 != NULL) {
3209 				    if (a < 0 || a > 128)
3210 					errx(EX_DATAERR,
3211 					    "in6addr invalid mask len");
3212 				    else
3213 					n2mask(pa6, a);
3214 			    } else {
3215 				    if (a > 0xFF)
3216 					    errx(EX_DATAERR,
3217 						"proto mask must be 8 bit");
3218 				    p.fs.flow_mask.proto = (uint8_t)a;
3219 			    }
3220 			    if (a != 0)
3221 				    p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
3222 			    ac--; av++;
3223 			} /* end while, config masks */
3224 end_mask:
3225 			break;
3226 
3227 		case TOK_RED:
3228 		case TOK_GRED:
3229 			NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
3230 			p.fs.flags_fs |= DN_IS_RED;
3231 			if (tok == TOK_GRED)
3232 				p.fs.flags_fs |= DN_IS_GENTLE_RED;
3233 			/*
3234 			 * the format for parameters is w_q/min_th/max_th/max_p
3235 			 */
3236 			if ((end = strsep(&av[0], "/"))) {
3237 			    double w_q = strtod(end, NULL);
3238 			    if (w_q > 1 || w_q <= 0)
3239 				errx(EX_DATAERR, "0 < w_q <= 1");
3240 			    p.fs.w_q = (int) (w_q * (1 << SCALE_RED));
3241 			}
3242 			if ((end = strsep(&av[0], "/"))) {
3243 			    p.fs.min_th = strtoul(end, &end, 0);
3244 			    if (*end == 'K' || *end == 'k')
3245 				p.fs.min_th *= 1024;
3246 			}
3247 			if ((end = strsep(&av[0], "/"))) {
3248 			    p.fs.max_th = strtoul(end, &end, 0);
3249 			    if (*end == 'K' || *end == 'k')
3250 				p.fs.max_th *= 1024;
3251 			}
3252 			if ((end = strsep(&av[0], "/"))) {
3253 			    double max_p = strtod(end, NULL);
3254 			    if (max_p > 1 || max_p <= 0)
3255 				errx(EX_DATAERR, "0 < max_p <= 1");
3256 			    p.fs.max_p = (int)(max_p * (1 << SCALE_RED));
3257 			}
3258 			ac--; av++;
3259 			break;
3260 
3261 		case TOK_DROPTAIL:
3262 			p.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
3263 			break;
3264 
3265 		case TOK_BW:
3266 			NEED1("bw needs bandwidth or interface\n");
3267 			if (do_pipe != 1)
3268 			    errx(EX_DATAERR, "bandwidth only valid for pipes");
3269 			/*
3270 			 * set clocking interface or bandwidth value
3271 			 */
3272 			if (av[0][0] >= 'a' && av[0][0] <= 'z') {
3273 			    int l = sizeof(p.if_name)-1;
3274 			    /* interface name */
3275 			    strncpy(p.if_name, av[0], l);
3276 			    p.if_name[l] = '\0';
3277 			    p.bandwidth = 0;
3278 			} else {
3279 			    p.if_name[0] = '\0';
3280 			    p.bandwidth = strtoul(av[0], &end, 0);
3281 			    if (*end == 'K' || *end == 'k') {
3282 				end++;
3283 				p.bandwidth *= 1000;
3284 			    } else if (*end == 'M') {
3285 				end++;
3286 				p.bandwidth *= 1000000;
3287 			    }
3288 			    if (*end == 'B' ||
3289 			        _substrcmp2(end, "by", "bytes") == 0)
3290 				p.bandwidth *= 8;
3291 			    if (p.bandwidth < 0)
3292 				errx(EX_DATAERR, "bandwidth too large");
3293 			}
3294 			ac--; av++;
3295 			break;
3296 
3297 		case TOK_DELAY:
3298 			if (do_pipe != 1)
3299 				errx(EX_DATAERR, "delay only valid for pipes");
3300 			NEED1("delay needs argument 0..10000ms\n");
3301 			p.delay = strtoul(av[0], NULL, 0);
3302 			ac--; av++;
3303 			break;
3304 
3305 		case TOK_WEIGHT:
3306 			if (do_pipe == 1)
3307 				errx(EX_DATAERR,"weight only valid for queues");
3308 			NEED1("weight needs argument 0..100\n");
3309 			p.fs.weight = strtoul(av[0], &end, 0);
3310 			ac--; av++;
3311 			break;
3312 
3313 		case TOK_PIPE:
3314 			if (do_pipe == 1)
3315 				errx(EX_DATAERR,"pipe only valid for queues");
3316 			NEED1("pipe needs pipe_number\n");
3317 			p.fs.parent_nr = strtoul(av[0], &end, 0);
3318 			ac--; av++;
3319 			break;
3320 
3321 		default:
3322 			errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]);
3323 		}
3324 	}
3325 	if (do_pipe == 1) {
3326 		if (p.pipe_nr == 0)
3327 			errx(EX_DATAERR, "pipe_nr must be > 0");
3328 		if (p.delay > 10000)
3329 			errx(EX_DATAERR, "delay must be < 10000");
3330 	} else { /* do_pipe == 2, queue */
3331 		if (p.fs.parent_nr == 0)
3332 			errx(EX_DATAERR, "pipe must be > 0");
3333 		if (p.fs.weight >100)
3334 			errx(EX_DATAERR, "weight must be <= 100");
3335 	}
3336 	if (p.fs.flags_fs & DN_QSIZE_IS_BYTES) {
3337 		if (p.fs.qsize > 1024*1024)
3338 			errx(EX_DATAERR, "queue size must be < 1MB");
3339 	} else {
3340 		if (p.fs.qsize > 100)
3341 			errx(EX_DATAERR, "2 <= queue size <= 100");
3342 	}
3343 	if (p.fs.flags_fs & DN_IS_RED) {
3344 		size_t len;
3345 		int lookup_depth, avg_pkt_size;
3346 		double s, idle, weight, w_q;
3347 		struct clockinfo ck;
3348 		int t;
3349 
3350 		if (p.fs.min_th >= p.fs.max_th)
3351 		    errx(EX_DATAERR, "min_th %d must be < than max_th %d",
3352 			p.fs.min_th, p.fs.max_th);
3353 		if (p.fs.max_th == 0)
3354 		    errx(EX_DATAERR, "max_th must be > 0");
3355 
3356 		len = sizeof(int);
3357 		if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
3358 			&lookup_depth, &len, NULL, 0) == -1)
3359 
3360 		    errx(1, "sysctlbyname(\"%s\")",
3361 			"net.inet.ip.dummynet.red_lookup_depth");
3362 		if (lookup_depth == 0)
3363 		    errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
3364 			" must be greater than zero");
3365 
3366 		len = sizeof(int);
3367 		if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
3368 			&avg_pkt_size, &len, NULL, 0) == -1)
3369 
3370 		    errx(1, "sysctlbyname(\"%s\")",
3371 			"net.inet.ip.dummynet.red_avg_pkt_size");
3372 		if (avg_pkt_size == 0)
3373 			errx(EX_DATAERR,
3374 			    "net.inet.ip.dummynet.red_avg_pkt_size must"
3375 			    " be greater than zero");
3376 
3377 		len = sizeof(struct clockinfo);
3378 		if (sysctlbyname("kern.clockrate", &ck, &len, NULL, 0) == -1)
3379 			errx(1, "sysctlbyname(\"%s\")", "kern.clockrate");
3380 
3381 		/*
3382 		 * Ticks needed for sending a medium-sized packet.
3383 		 * Unfortunately, when we are configuring a WF2Q+ queue, we
3384 		 * do not have bandwidth information, because that is stored
3385 		 * in the parent pipe, and also we have multiple queues
3386 		 * competing for it. So we set s=0, which is not very
3387 		 * correct. But on the other hand, why do we want RED with
3388 		 * WF2Q+ ?
3389 		 */
3390 		if (p.bandwidth==0) /* this is a WF2Q+ queue */
3391 			s = 0;
3392 		else
3393 			s = ck.hz * avg_pkt_size * 8 / p.bandwidth;
3394 
3395 		/*
3396 		 * max idle time (in ticks) before avg queue size becomes 0.
3397 		 * NOTA:  (3/w_q) is approx the value x so that
3398 		 * (1-w_q)^x < 10^-3.
3399 		 */
3400 		w_q = ((double)p.fs.w_q) / (1 << SCALE_RED);
3401 		idle = s * 3. / w_q;
3402 		p.fs.lookup_step = (int)idle / lookup_depth;
3403 		if (!p.fs.lookup_step)
3404 			p.fs.lookup_step = 1;
3405 		weight = 1 - w_q;
3406 		for (t = p.fs.lookup_step; t > 0; --t)
3407 			weight *= weight;
3408 		p.fs.lookup_weight = (int)(weight * (1 << SCALE_RED));
3409 	}
3410 	i = do_cmd(IP_DUMMYNET_CONFIGURE, &p, sizeof p);
3411 	if (i)
3412 		err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
3413 }
3414 
3415 static void
3416 get_mac_addr_mask(char *p, uint8_t *addr, uint8_t *mask)
3417 {
3418 	int i, l;
3419 
3420 	for (i=0; i<6; i++)
3421 		addr[i] = mask[i] = 0;
3422 	if (strcmp(p, "any") == 0)
3423 		return;
3424 
3425 	for (i=0; *p && i<6;i++, p++) {
3426 		addr[i] = strtol(p, &p, 16);
3427 		if (*p != ':') /* we start with the mask */
3428 			break;
3429 	}
3430 	if (*p == '/') { /* mask len */
3431 		l = strtol(p+1, &p, 0);
3432 		for (i=0; l>0; l -=8, i++)
3433 			mask[i] = (l >=8) ? 0xff : (~0) << (8-l);
3434 	} else if (*p == '&') { /* mask */
3435 		for (i=0, p++; *p && i<6;i++, p++) {
3436 			mask[i] = strtol(p, &p, 16);
3437 			if (*p != ':')
3438 				break;
3439 		}
3440 	} else if (*p == '\0') {
3441 		for (i=0; i<6; i++)
3442 			mask[i] = 0xff;
3443 	}
3444 	for (i=0; i<6; i++)
3445 		addr[i] &= mask[i];
3446 }
3447 
3448 /*
3449  * helper function, updates the pointer to cmd with the length
3450  * of the current command, and also cleans up the first word of
3451  * the new command in case it has been clobbered before.
3452  */
3453 static ipfw_insn *
3454 next_cmd(ipfw_insn *cmd)
3455 {
3456 	cmd += F_LEN(cmd);
3457 	bzero(cmd, sizeof(*cmd));
3458 	return cmd;
3459 }
3460 
3461 /*
3462  * Takes arguments and copies them into a comment
3463  */
3464 static void
3465 fill_comment(ipfw_insn *cmd, int ac, char **av)
3466 {
3467 	int i, l;
3468 	char *p = (char *)(cmd + 1);
3469 
3470 	cmd->opcode = O_NOP;
3471 	cmd->len =  (cmd->len & (F_NOT | F_OR));
3472 
3473 	/* Compute length of comment string. */
3474 	for (i = 0, l = 0; i < ac; i++)
3475 		l += strlen(av[i]) + 1;
3476 	if (l == 0)
3477 		return;
3478 	if (l > 84)
3479 		errx(EX_DATAERR,
3480 		    "comment too long (max 80 chars)");
3481 	l = 1 + (l+3)/4;
3482 	cmd->len =  (cmd->len & (F_NOT | F_OR)) | l;
3483 	for (i = 0; i < ac; i++) {
3484 		strcpy(p, av[i]);
3485 		p += strlen(av[i]);
3486 		*p++ = ' ';
3487 	}
3488 	*(--p) = '\0';
3489 }
3490 
3491 /*
3492  * A function to fill simple commands of size 1.
3493  * Existing flags are preserved.
3494  */
3495 static void
3496 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3497 {
3498 	cmd->opcode = opcode;
3499 	cmd->len =  ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3500 	cmd->arg1 = arg;
3501 }
3502 
3503 /*
3504  * Fetch and add the MAC address and type, with masks. This generates one or
3505  * two microinstructions, and returns the pointer to the last one.
3506  */
3507 static ipfw_insn *
3508 add_mac(ipfw_insn *cmd, int ac, char *av[])
3509 {
3510 	ipfw_insn_mac *mac;
3511 
3512 	if (ac < 2)
3513 		errx(EX_DATAERR, "MAC dst src");
3514 
3515 	cmd->opcode = O_MACADDR2;
3516 	cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3517 
3518 	mac = (ipfw_insn_mac *)cmd;
3519 	get_mac_addr_mask(av[0], mac->addr, mac->mask);	/* dst */
3520 	get_mac_addr_mask(av[1], &(mac->addr[6]), &(mac->mask[6])); /* src */
3521 	return cmd;
3522 }
3523 
3524 static ipfw_insn *
3525 add_mactype(ipfw_insn *cmd, int ac, char *av)
3526 {
3527 	if (ac < 1)
3528 		errx(EX_DATAERR, "missing MAC type");
3529 	if (strcmp(av, "any") != 0) { /* we have a non-null type */
3530 		fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE);
3531 		cmd->opcode = O_MAC_TYPE;
3532 		return cmd;
3533 	} else
3534 		return NULL;
3535 }
3536 
3537 static ipfw_insn *
3538 add_proto(ipfw_insn *cmd, char *av, u_char *proto)
3539 {
3540 	struct protoent *pe;
3541 
3542 	*proto = IPPROTO_IP;
3543 
3544 	if (_substrcmp(av, "all") == 0)
3545 		; /* do not set O_IP4 nor O_IP6 */
3546 	else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3547 		/* explicit "just IPv4" rule */
3548 		fill_cmd(cmd, O_IP4, 0, 0);
3549 	else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3550 		/* explicit "just IPv6" rule */
3551 		*proto = IPPROTO_IPV6;
3552 		fill_cmd(cmd, O_IP6, 0, 0);
3553 	} else if ((*proto = atoi(av)) > 0)
3554 		; /* all done! */
3555 	else if ((pe = getprotobyname(av)) != NULL)
3556 		*proto = pe->p_proto;
3557 	else
3558 		return NULL;
3559 	if (*proto != IPPROTO_IP && *proto != IPPROTO_IPV6)
3560 		fill_cmd(cmd, O_PROTO, 0, *proto);
3561 
3562 	return cmd;
3563 }
3564 
3565 static ipfw_insn *
3566 add_srcip(ipfw_insn *cmd, char *av)
3567 {
3568 	fill_ip((ipfw_insn_ip *)cmd, av);
3569 	if (cmd->opcode == O_IP_DST_SET)			/* set */
3570 		cmd->opcode = O_IP_SRC_SET;
3571 	else if (cmd->opcode == O_IP_DST_LOOKUP)		/* table */
3572 		cmd->opcode = O_IP_SRC_LOOKUP;
3573 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))		/* me */
3574 		cmd->opcode = O_IP_SRC_ME;
3575 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))	/* one IP */
3576 		cmd->opcode = O_IP_SRC;
3577 	else							/* addr/mask */
3578 		cmd->opcode = O_IP_SRC_MASK;
3579 	return cmd;
3580 }
3581 
3582 static ipfw_insn *
3583 add_dstip(ipfw_insn *cmd, char *av)
3584 {
3585 	fill_ip((ipfw_insn_ip *)cmd, av);
3586 	if (cmd->opcode == O_IP_DST_SET)			/* set */
3587 		;
3588 	else if (cmd->opcode == O_IP_DST_LOOKUP)		/* table */
3589 		;
3590 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))		/* me */
3591 		cmd->opcode = O_IP_DST_ME;
3592 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))	/* one IP */
3593 		cmd->opcode = O_IP_DST;
3594 	else							/* addr/mask */
3595 		cmd->opcode = O_IP_DST_MASK;
3596 	return cmd;
3597 }
3598 
3599 static ipfw_insn *
3600 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode)
3601 {
3602 	if (_substrcmp(av, "any") == 0) {
3603 		return NULL;
3604 	} else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) {
3605 		/* XXX todo: check that we have a protocol with ports */
3606 		cmd->opcode = opcode;
3607 		return cmd;
3608 	}
3609 	return NULL;
3610 }
3611 
3612 static ipfw_insn *
3613 add_src(ipfw_insn *cmd, char *av, u_char proto)
3614 {
3615 	struct in6_addr a;
3616 
3617 	if (proto == IPPROTO_IPV6  || strcmp(av, "me6") == 0 ||
3618 	    inet_pton(AF_INET6, av, &a))
3619 		return add_srcip6(cmd, av);
3620 	/* XXX: should check for IPv4, not !IPv6 */
3621 	if (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3622 	    !inet_pton(AF_INET6, av, &a))
3623 		return add_srcip(cmd, av);
3624 	if (strcmp(av, "any") != 0)
3625 		return cmd;
3626 
3627 	return NULL;
3628 }
3629 
3630 static ipfw_insn *
3631 add_dst(ipfw_insn *cmd, char *av, u_char proto)
3632 {
3633 	struct in6_addr a;
3634 
3635 	if (proto == IPPROTO_IPV6  || strcmp(av, "me6") == 0 ||
3636 	    inet_pton(AF_INET6, av, &a))
3637 		return add_dstip6(cmd, av);
3638 	/* XXX: should check for IPv4, not !IPv6 */
3639 	if (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3640 	    !inet_pton(AF_INET6, av, &a))
3641 		return add_dstip(cmd, av);
3642 	if (strcmp(av, "any") != 0)
3643 		return cmd;
3644 
3645 	return NULL;
3646 }
3647 
3648 /*
3649  * Parse arguments and assemble the microinstructions which make up a rule.
3650  * Rules are added into the 'rulebuf' and then copied in the correct order
3651  * into the actual rule.
3652  *
3653  * The syntax for a rule starts with the action, followed by
3654  * optional action parameters, and the various match patterns.
3655  * In the assembled microcode, the first opcode must be an O_PROBE_STATE
3656  * (generated if the rule includes a keep-state option), then the
3657  * various match patterns, log/altq actions, and the actual action.
3658  *
3659  */
3660 static void
3661 add(int ac, char *av[])
3662 {
3663 	/*
3664 	 * rules are added into the 'rulebuf' and then copied in
3665 	 * the correct order into the actual rule.
3666 	 * Some things that need to go out of order (prob, action etc.)
3667 	 * go into actbuf[].
3668 	 */
3669 	static uint32_t rulebuf[255], actbuf[255], cmdbuf[255];
3670 
3671 	ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
3672 	ipfw_insn *first_cmd;	/* first match pattern */
3673 
3674 	struct ip_fw *rule;
3675 
3676 	/*
3677 	 * various flags used to record that we entered some fields.
3678 	 */
3679 	ipfw_insn *have_state = NULL;	/* check-state or keep-state */
3680 	ipfw_insn *have_log = NULL, *have_altq = NULL;
3681 	size_t len;
3682 
3683 	int i;
3684 
3685 	int open_par = 0;	/* open parenthesis ( */
3686 
3687 	/* proto is here because it is used to fetch ports */
3688 	u_char proto = IPPROTO_IP;	/* default protocol */
3689 
3690 	double match_prob = 1; /* match probability, default is always match */
3691 
3692 	bzero(actbuf, sizeof(actbuf));		/* actions go here */
3693 	bzero(cmdbuf, sizeof(cmdbuf));
3694 	bzero(rulebuf, sizeof(rulebuf));
3695 
3696 	rule = (struct ip_fw *)rulebuf;
3697 	cmd = (ipfw_insn *)cmdbuf;
3698 	action = (ipfw_insn *)actbuf;
3699 
3700 	av++; ac--;
3701 
3702 	/* [rule N]	-- Rule number optional */
3703 	if (ac && isdigit(**av)) {
3704 		rule->rulenum = atoi(*av);
3705 		av++;
3706 		ac--;
3707 	}
3708 
3709 	/* [set N]	-- set number (0..RESVD_SET), optional */
3710 	if (ac > 1 && _substrcmp(*av, "set") == 0) {
3711 		int set = strtoul(av[1], NULL, 10);
3712 		if (set < 0 || set > RESVD_SET)
3713 			errx(EX_DATAERR, "illegal set %s", av[1]);
3714 		rule->set = set;
3715 		av += 2; ac -= 2;
3716 	}
3717 
3718 	/* [prob D]	-- match probability, optional */
3719 	if (ac > 1 && _substrcmp(*av, "prob") == 0) {
3720 		match_prob = strtod(av[1], NULL);
3721 
3722 		if (match_prob <= 0 || match_prob > 1)
3723 			errx(EX_DATAERR, "illegal match prob. %s", av[1]);
3724 		av += 2; ac -= 2;
3725 	}
3726 
3727 	/* action	-- mandatory */
3728 	NEED1("missing action");
3729 	i = match_token(rule_actions, *av);
3730 	ac--; av++;
3731 	action->len = 1;	/* default */
3732 	switch(i) {
3733 	case TOK_CHECKSTATE:
3734 		have_state = action;
3735 		action->opcode = O_CHECK_STATE;
3736 		break;
3737 
3738 	case TOK_ACCEPT:
3739 		action->opcode = O_ACCEPT;
3740 		break;
3741 
3742 	case TOK_DENY:
3743 		action->opcode = O_DENY;
3744 		action->arg1 = 0;
3745 		break;
3746 
3747 	case TOK_REJECT:
3748 		action->opcode = O_REJECT;
3749 		action->arg1 = ICMP_UNREACH_HOST;
3750 		break;
3751 
3752 	case TOK_RESET:
3753 		action->opcode = O_REJECT;
3754 		action->arg1 = ICMP_REJECT_RST;
3755 		break;
3756 
3757 	case TOK_UNREACH:
3758 		action->opcode = O_REJECT;
3759 		NEED1("missing reject code");
3760 		fill_reject_code(&action->arg1, *av);
3761 		ac--; av++;
3762 		break;
3763 
3764 	case TOK_COUNT:
3765 		action->opcode = O_COUNT;
3766 		break;
3767 
3768 	case TOK_QUEUE:
3769 	case TOK_PIPE:
3770 		action->len = F_INSN_SIZE(ipfw_insn_pipe);
3771 	case TOK_SKIPTO:
3772 		if (i == TOK_QUEUE)
3773 			action->opcode = O_QUEUE;
3774 		else if (i == TOK_PIPE)
3775 			action->opcode = O_PIPE;
3776 		else if (i == TOK_SKIPTO)
3777 			action->opcode = O_SKIPTO;
3778 		NEED1("missing skipto/pipe/queue number");
3779 		action->arg1 = strtoul(*av, NULL, 10);
3780 		av++; ac--;
3781 		break;
3782 
3783 	case TOK_DIVERT:
3784 	case TOK_TEE:
3785 		action->opcode = (i == TOK_DIVERT) ? O_DIVERT : O_TEE;
3786 		NEED1("missing divert/tee port");
3787 		action->arg1 = strtoul(*av, NULL, 0);
3788 		if (action->arg1 == 0) {
3789 			struct servent *s;
3790 			setservent(1);
3791 			s = getservbyname(av[0], "divert");
3792 			if (s != NULL)
3793 				action->arg1 = ntohs(s->s_port);
3794 			else
3795 				errx(EX_DATAERR, "illegal divert/tee port");
3796 		}
3797 		ac--; av++;
3798 		break;
3799 
3800 	case TOK_NETGRAPH:
3801 	case TOK_NGTEE:
3802 		action->opcode = (i == TOK_NETGRAPH ) ? O_NETGRAPH : O_NGTEE;
3803 		NEED1("missing netgraph cookie");
3804 		action->arg1 = strtoul(*av, NULL, 0);
3805 		if (action->arg1 == 0)
3806 			errx(EX_DATAERR, "illegal netgraph cookie");
3807 		ac--; av++;
3808 		break;
3809 
3810 	case TOK_FORWARD: {
3811 		ipfw_insn_sa *p = (ipfw_insn_sa *)action;
3812 		char *s, *end;
3813 
3814 		NEED1("missing forward address[:port]");
3815 
3816 		action->opcode = O_FORWARD_IP;
3817 		action->len = F_INSN_SIZE(ipfw_insn_sa);
3818 
3819 		p->sa.sin_len = sizeof(struct sockaddr_in);
3820 		p->sa.sin_family = AF_INET;
3821 		p->sa.sin_port = 0;
3822 		/*
3823 		 * locate the address-port separator (':' or ',')
3824 		 */
3825 		s = strchr(*av, ':');
3826 		if (s == NULL)
3827 			s = strchr(*av, ',');
3828 		if (s != NULL) {
3829 			*(s++) = '\0';
3830 			i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
3831 			if (s == end)
3832 				errx(EX_DATAERR,
3833 				    "illegal forwarding port ``%s''", s);
3834 			p->sa.sin_port = (u_short)i;
3835 		}
3836 		lookup_host(*av, &(p->sa.sin_addr));
3837 		}
3838 		ac--; av++;
3839 		break;
3840 
3841 	case TOK_COMMENT:
3842 		/* pretend it is a 'count' rule followed by the comment */
3843 		action->opcode = O_COUNT;
3844 		ac++; av--;	/* go back... */
3845 		break;
3846 
3847 	default:
3848 		errx(EX_DATAERR, "invalid action %s\n", av[-1]);
3849 	}
3850 	action = next_cmd(action);
3851 
3852 	/*
3853 	 * [altq queuename] -- altq tag, optional
3854 	 * [log [logamount N]]	-- log, optional
3855 	 *
3856 	 * If they exist, it go first in the cmdbuf, but then it is
3857 	 * skipped in the copy section to the end of the buffer.
3858 	 */
3859 	while (ac != 0 && (i = match_token(rule_action_params, *av)) != -1) {
3860 		ac--; av++;
3861 		switch (i) {
3862 		case TOK_LOG:
3863 		    {
3864 			ipfw_insn_log *c = (ipfw_insn_log *)cmd;
3865 			int l;
3866 
3867 			if (have_log)
3868 				errx(EX_DATAERR,
3869 				    "log cannot be specified more than once");
3870 			have_log = (ipfw_insn *)c;
3871 			cmd->len = F_INSN_SIZE(ipfw_insn_log);
3872 			cmd->opcode = O_LOG;
3873 			if (ac && _substrcmp(*av, "logamount") == 0) {
3874 				ac--; av++;
3875 				NEED1("logamount requires argument");
3876 				l = atoi(*av);
3877 				if (l < 0)
3878 					errx(EX_DATAERR,
3879 					    "logamount must be positive");
3880 				c->max_log = l;
3881 				ac--; av++;
3882 			} else {
3883 				len = sizeof(c->max_log);
3884 				if (sysctlbyname("net.inet.ip.fw.verbose_limit",
3885 				    &c->max_log, &len, NULL, 0) == -1)
3886 					errx(1, "sysctlbyname(\"%s\")",
3887 					    "net.inet.ip.fw.verbose_limit");
3888 			}
3889 		    }
3890 			break;
3891 
3892 		case TOK_ALTQ:
3893 		    {
3894 			ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
3895 
3896 			NEED1("missing altq queue name");
3897 			if (have_altq)
3898 				errx(EX_DATAERR,
3899 				    "altq cannot be specified more than once");
3900 			have_altq = (ipfw_insn *)a;
3901 			cmd->len = F_INSN_SIZE(ipfw_insn_altq);
3902 			cmd->opcode = O_ALTQ;
3903 			fill_altq_qid(&a->qid, *av);
3904 			ac--; av++;
3905 		    }
3906 			break;
3907 
3908 		default:
3909 			abort();
3910 		}
3911 		cmd = next_cmd(cmd);
3912 	}
3913 
3914 	if (have_state)	/* must be a check-state, we are done */
3915 		goto done;
3916 
3917 #define OR_START(target)					\
3918 	if (ac && (*av[0] == '(' || *av[0] == '{')) {		\
3919 		if (open_par)					\
3920 			errx(EX_USAGE, "nested \"(\" not allowed\n"); \
3921 		prev = NULL;					\
3922 		open_par = 1;					\
3923 		if ( (av[0])[1] == '\0') {			\
3924 			ac--; av++;				\
3925 		} else						\
3926 			(*av)++;				\
3927 	}							\
3928 	target:							\
3929 
3930 
3931 #define	CLOSE_PAR						\
3932 	if (open_par) {						\
3933 		if (ac && (					\
3934 		    strcmp(*av, ")") == 0 ||			\
3935 		    strcmp(*av, "}") == 0)) {			\
3936 			prev = NULL;				\
3937 			open_par = 0;				\
3938 			ac--; av++;				\
3939 		} else						\
3940 			errx(EX_USAGE, "missing \")\"\n");	\
3941 	}
3942 
3943 #define NOT_BLOCK						\
3944 	if (ac && _substrcmp(*av, "not") == 0) {		\
3945 		if (cmd->len & F_NOT)				\
3946 			errx(EX_USAGE, "double \"not\" not allowed\n"); \
3947 		cmd->len |= F_NOT;				\
3948 		ac--; av++;					\
3949 	}
3950 
3951 #define OR_BLOCK(target)					\
3952 	if (ac && _substrcmp(*av, "or") == 0) {		\
3953 		if (prev == NULL || open_par == 0)		\
3954 			errx(EX_DATAERR, "invalid OR block");	\
3955 		prev->len |= F_OR;				\
3956 		ac--; av++;					\
3957 		goto target;					\
3958 	}							\
3959 	CLOSE_PAR;
3960 
3961 	first_cmd = cmd;
3962 
3963 #if 0
3964 	/*
3965 	 * MAC addresses, optional.
3966 	 * If we have this, we skip the part "proto from src to dst"
3967 	 * and jump straight to the option parsing.
3968 	 */
3969 	NOT_BLOCK;
3970 	NEED1("missing protocol");
3971 	if (_substrcmp(*av, "MAC") == 0 ||
3972 	    _substrcmp(*av, "mac") == 0) {
3973 		ac--; av++;	/* the "MAC" keyword */
3974 		add_mac(cmd, ac, av); /* exits in case of errors */
3975 		cmd = next_cmd(cmd);
3976 		ac -= 2; av += 2;	/* dst-mac and src-mac */
3977 		NOT_BLOCK;
3978 		NEED1("missing mac type");
3979 		if (add_mactype(cmd, ac, av[0]))
3980 			cmd = next_cmd(cmd);
3981 		ac--; av++;	/* any or mac-type */
3982 		goto read_options;
3983 	}
3984 #endif
3985 
3986 	/*
3987 	 * protocol, mandatory
3988 	 */
3989     OR_START(get_proto);
3990 	NOT_BLOCK;
3991 	NEED1("missing protocol");
3992 	if (add_proto(cmd, *av, &proto)) {
3993 		av++; ac--;
3994 		if (F_LEN(cmd) == 0)	/* plain IP */
3995 			proto = 0;
3996 		else {
3997 			proto = cmd->arg1;
3998 			prev = cmd;
3999 			cmd = next_cmd(cmd);
4000 		}
4001 	} else if (first_cmd != cmd) {
4002 		errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4003 	} else
4004 		goto read_options;
4005     OR_BLOCK(get_proto);
4006 
4007 	/*
4008 	 * "from", mandatory
4009 	 */
4010 	if (!ac || _substrcmp(*av, "from") != 0)
4011 		errx(EX_USAGE, "missing ``from''");
4012 	ac--; av++;
4013 
4014 	/*
4015 	 * source IP, mandatory
4016 	 */
4017     OR_START(source_ip);
4018 	NOT_BLOCK;	/* optional "not" */
4019 	NEED1("missing source address");
4020 	if (add_src(cmd, *av, proto)) {
4021 		ac--; av++;
4022 		if (F_LEN(cmd) != 0) {	/* ! any */
4023 			prev = cmd;
4024 			cmd = next_cmd(cmd);
4025 		}
4026 	} else
4027 		errx(EX_USAGE, "bad source address %s", *av);
4028     OR_BLOCK(source_ip);
4029 
4030 	/*
4031 	 * source ports, optional
4032 	 */
4033 	NOT_BLOCK;	/* optional "not" */
4034 	if (ac) {
4035 		if (_substrcmp(*av, "any") == 0 ||
4036 		    add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
4037 			ac--; av++;
4038 			if (F_LEN(cmd) != 0)
4039 				cmd = next_cmd(cmd);
4040 		}
4041 	}
4042 
4043 	/*
4044 	 * "to", mandatory
4045 	 */
4046 	if (!ac || _substrcmp(*av, "to") != 0)
4047 		errx(EX_USAGE, "missing ``to''");
4048 	av++; ac--;
4049 
4050 	/*
4051 	 * destination, mandatory
4052 	 */
4053     OR_START(dest_ip);
4054 	NOT_BLOCK;	/* optional "not" */
4055 	NEED1("missing dst address");
4056 	if (add_dst(cmd, *av, proto)) {
4057 		ac--; av++;
4058 		if (F_LEN(cmd) != 0) {	/* ! any */
4059 			prev = cmd;
4060 			cmd = next_cmd(cmd);
4061 		}
4062 	} else
4063 		errx( EX_USAGE, "bad destination address %s", *av);
4064     OR_BLOCK(dest_ip);
4065 
4066 	/*
4067 	 * dest. ports, optional
4068 	 */
4069 	NOT_BLOCK;	/* optional "not" */
4070 	if (ac) {
4071 		if (_substrcmp(*av, "any") == 0 ||
4072 		    add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
4073 			ac--; av++;
4074 			if (F_LEN(cmd) != 0)
4075 				cmd = next_cmd(cmd);
4076 		}
4077 	}
4078 
4079 read_options:
4080 	if (ac && first_cmd == cmd) {
4081 		/*
4082 		 * nothing specified so far, store in the rule to ease
4083 		 * printout later.
4084 		 */
4085 		 rule->_pad = 1;
4086 	}
4087 	prev = NULL;
4088 	while (ac) {
4089 		char *s;
4090 		ipfw_insn_u32 *cmd32;	/* alias for cmd */
4091 
4092 		s = *av;
4093 		cmd32 = (ipfw_insn_u32 *)cmd;
4094 
4095 		if (*s == '!') {	/* alternate syntax for NOT */
4096 			if (cmd->len & F_NOT)
4097 				errx(EX_USAGE, "double \"not\" not allowed\n");
4098 			cmd->len = F_NOT;
4099 			s++;
4100 		}
4101 		i = match_token(rule_options, s);
4102 		ac--; av++;
4103 		switch(i) {
4104 		case TOK_NOT:
4105 			if (cmd->len & F_NOT)
4106 				errx(EX_USAGE, "double \"not\" not allowed\n");
4107 			cmd->len = F_NOT;
4108 			break;
4109 
4110 		case TOK_OR:
4111 			if (open_par == 0 || prev == NULL)
4112 				errx(EX_USAGE, "invalid \"or\" block\n");
4113 			prev->len |= F_OR;
4114 			break;
4115 
4116 		case TOK_STARTBRACE:
4117 			if (open_par)
4118 				errx(EX_USAGE, "+nested \"(\" not allowed\n");
4119 			open_par = 1;
4120 			break;
4121 
4122 		case TOK_ENDBRACE:
4123 			if (!open_par)
4124 				errx(EX_USAGE, "+missing \")\"\n");
4125 			open_par = 0;
4126 			prev = NULL;
4127         		break;
4128 
4129 		case TOK_IN:
4130 			fill_cmd(cmd, O_IN, 0, 0);
4131 			break;
4132 
4133 		case TOK_OUT:
4134 			cmd->len ^= F_NOT; /* toggle F_NOT */
4135 			fill_cmd(cmd, O_IN, 0, 0);
4136 			break;
4137 
4138 		case TOK_DIVERTED:
4139 			fill_cmd(cmd, O_DIVERTED, 0, 3);
4140 			break;
4141 
4142 		case TOK_DIVERTEDLOOPBACK:
4143 			fill_cmd(cmd, O_DIVERTED, 0, 1);
4144 			break;
4145 
4146 		case TOK_DIVERTEDOUTPUT:
4147 			fill_cmd(cmd, O_DIVERTED, 0, 2);
4148 			break;
4149 
4150 		case TOK_FRAG:
4151 			fill_cmd(cmd, O_FRAG, 0, 0);
4152 			break;
4153 
4154 		case TOK_LAYER2:
4155 			fill_cmd(cmd, O_LAYER2, 0, 0);
4156 			break;
4157 
4158 		case TOK_XMIT:
4159 		case TOK_RECV:
4160 		case TOK_VIA:
4161 			NEED1("recv, xmit, via require interface name"
4162 				" or address");
4163 			fill_iface((ipfw_insn_if *)cmd, av[0]);
4164 			ac--; av++;
4165 			if (F_LEN(cmd) == 0)	/* not a valid address */
4166 				break;
4167 			if (i == TOK_XMIT)
4168 				cmd->opcode = O_XMIT;
4169 			else if (i == TOK_RECV)
4170 				cmd->opcode = O_RECV;
4171 			else if (i == TOK_VIA)
4172 				cmd->opcode = O_VIA;
4173 			break;
4174 
4175 		case TOK_ICMPTYPES:
4176 			NEED1("icmptypes requires list of types");
4177 			fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
4178 			av++; ac--;
4179 			break;
4180 
4181 		case TOK_ICMP6TYPES:
4182 			NEED1("icmptypes requires list of types");
4183 			fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av);
4184 			av++; ac--;
4185 			break;
4186 
4187 		case TOK_IPTTL:
4188 			NEED1("ipttl requires TTL");
4189 			if (strpbrk(*av, "-,")) {
4190 			    if (!add_ports(cmd, *av, 0, O_IPTTL))
4191 				errx(EX_DATAERR, "invalid ipttl %s", *av);
4192 			} else
4193 			    fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
4194 			ac--; av++;
4195 			break;
4196 
4197 		case TOK_IPID:
4198 			NEED1("ipid requires id");
4199 			if (strpbrk(*av, "-,")) {
4200 			    if (!add_ports(cmd, *av, 0, O_IPID))
4201 				errx(EX_DATAERR, "invalid ipid %s", *av);
4202 			} else
4203 			    fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
4204 			ac--; av++;
4205 			break;
4206 
4207 		case TOK_IPLEN:
4208 			NEED1("iplen requires length");
4209 			if (strpbrk(*av, "-,")) {
4210 			    if (!add_ports(cmd, *av, 0, O_IPLEN))
4211 				errx(EX_DATAERR, "invalid ip len %s", *av);
4212 			} else
4213 			    fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
4214 			ac--; av++;
4215 			break;
4216 
4217 		case TOK_IPVER:
4218 			NEED1("ipver requires version");
4219 			fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
4220 			ac--; av++;
4221 			break;
4222 
4223 		case TOK_IPPRECEDENCE:
4224 			NEED1("ipprecedence requires value");
4225 			fill_cmd(cmd, O_IPPRECEDENCE, 0,
4226 			    (strtoul(*av, NULL, 0) & 7) << 5);
4227 			ac--; av++;
4228 			break;
4229 
4230 		case TOK_IPOPTS:
4231 			NEED1("missing argument for ipoptions");
4232 			fill_flags(cmd, O_IPOPT, f_ipopts, *av);
4233 			ac--; av++;
4234 			break;
4235 
4236 		case TOK_IPTOS:
4237 			NEED1("missing argument for iptos");
4238 			fill_flags(cmd, O_IPTOS, f_iptos, *av);
4239 			ac--; av++;
4240 			break;
4241 
4242 		case TOK_UID:
4243 			NEED1("uid requires argument");
4244 		    {
4245 			char *end;
4246 			uid_t uid;
4247 			struct passwd *pwd;
4248 
4249 			cmd->opcode = O_UID;
4250 			uid = strtoul(*av, &end, 0);
4251 			pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
4252 			if (pwd == NULL)
4253 				errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
4254 			cmd32->d[0] = pwd->pw_uid;
4255 			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4256 			ac--; av++;
4257 		    }
4258 			break;
4259 
4260 		case TOK_GID:
4261 			NEED1("gid requires argument");
4262 		    {
4263 			char *end;
4264 			gid_t gid;
4265 			struct group *grp;
4266 
4267 			cmd->opcode = O_GID;
4268 			gid = strtoul(*av, &end, 0);
4269 			grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
4270 			if (grp == NULL)
4271 				errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
4272 			cmd32->d[0] = grp->gr_gid;
4273 			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4274 			ac--; av++;
4275 		    }
4276 			break;
4277 
4278 		case TOK_JAIL:
4279 			NEED1("jail requires argument");
4280 		    {
4281 			char *end;
4282 			int jid;
4283 
4284 			cmd->opcode = O_JAIL;
4285 			jid = (int)strtol(*av, &end, 0);
4286 			if (jid < 0 || *end != '\0')
4287 				errx(EX_DATAERR, "jail requires prison ID");
4288 			cmd32->d[0] = (uint32_t)jid;
4289 			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4290 			ac--; av++;
4291 		    }
4292 			break;
4293 
4294 		case TOK_ESTAB:
4295 			fill_cmd(cmd, O_ESTAB, 0, 0);
4296 			break;
4297 
4298 		case TOK_SETUP:
4299 			fill_cmd(cmd, O_TCPFLAGS, 0,
4300 				(TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
4301 			break;
4302 
4303 		case TOK_TCPDATALEN:
4304 			NEED1("tcpdatalen requires length");
4305 			if (strpbrk(*av, "-,")) {
4306 			    if (!add_ports(cmd, *av, 0, O_TCPDATALEN))
4307 				errx(EX_DATAERR, "invalid tcpdata len %s", *av);
4308 			} else
4309 			    fill_cmd(cmd, O_TCPDATALEN, 0,
4310 				    strtoul(*av, NULL, 0));
4311 			ac--; av++;
4312 			break;
4313 
4314 		case TOK_TCPOPTS:
4315 			NEED1("missing argument for tcpoptions");
4316 			fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
4317 			ac--; av++;
4318 			break;
4319 
4320 		case TOK_TCPSEQ:
4321 		case TOK_TCPACK:
4322 			NEED1("tcpseq/tcpack requires argument");
4323 			cmd->len = F_INSN_SIZE(ipfw_insn_u32);
4324 			cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
4325 			cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
4326 			ac--; av++;
4327 			break;
4328 
4329 		case TOK_TCPWIN:
4330 			NEED1("tcpwin requires length");
4331 			fill_cmd(cmd, O_TCPWIN, 0,
4332 			    htons(strtoul(*av, NULL, 0)));
4333 			ac--; av++;
4334 			break;
4335 
4336 		case TOK_TCPFLAGS:
4337 			NEED1("missing argument for tcpflags");
4338 			cmd->opcode = O_TCPFLAGS;
4339 			fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
4340 			ac--; av++;
4341 			break;
4342 
4343 		case TOK_KEEPSTATE:
4344 			if (open_par)
4345 				errx(EX_USAGE, "keep-state cannot be part "
4346 				    "of an or block");
4347 			if (have_state)
4348 				errx(EX_USAGE, "only one of keep-state "
4349 					"and limit is allowed");
4350 			have_state = cmd;
4351 			fill_cmd(cmd, O_KEEP_STATE, 0, 0);
4352 			break;
4353 
4354 		case TOK_LIMIT:
4355 			if (open_par)
4356 				errx(EX_USAGE, "limit cannot be part "
4357 				    "of an or block");
4358 			if (have_state)
4359 				errx(EX_USAGE, "only one of keep-state "
4360 					"and limit is allowed");
4361 			NEED1("limit needs mask and # of connections");
4362 			have_state = cmd;
4363 		    {
4364 			ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
4365 
4366 			cmd->len = F_INSN_SIZE(ipfw_insn_limit);
4367 			cmd->opcode = O_LIMIT;
4368 			c->limit_mask = 0;
4369 			c->conn_limit = 0;
4370 			for (; ac >1 ;) {
4371 				int val;
4372 
4373 				val = match_token(limit_masks, *av);
4374 				if (val <= 0)
4375 					break;
4376 				c->limit_mask |= val;
4377 				ac--; av++;
4378 			}
4379 			c->conn_limit = atoi(*av);
4380 			if (c->conn_limit == 0)
4381 				errx(EX_USAGE, "limit: limit must be >0");
4382 			if (c->limit_mask == 0)
4383 				errx(EX_USAGE, "missing limit mask");
4384 			ac--; av++;
4385 		    }
4386 			break;
4387 
4388 		case TOK_PROTO:
4389 			NEED1("missing protocol");
4390 			if (add_proto(cmd, *av, &proto)) {
4391 				ac--; av++;
4392 			} else
4393 				errx(EX_DATAERR, "invalid protocol ``%s''",
4394 				    *av);
4395 			break;
4396 
4397 		case TOK_SRCIP:
4398 			NEED1("missing source IP");
4399 			if (add_srcip(cmd, *av)) {
4400 				ac--; av++;
4401 			}
4402 			break;
4403 
4404 		case TOK_DSTIP:
4405 			NEED1("missing destination IP");
4406 			if (add_dstip(cmd, *av)) {
4407 				ac--; av++;
4408 			}
4409 			break;
4410 
4411 		case TOK_SRCIP6:
4412 			NEED1("missing source IP6");
4413 			if (add_srcip6(cmd, *av)) {
4414 				ac--; av++;
4415 			}
4416 			break;
4417 
4418 		case TOK_DSTIP6:
4419 			NEED1("missing destination IP6");
4420 			if (add_dstip6(cmd, *av)) {
4421 				ac--; av++;
4422 			}
4423 			break;
4424 
4425 		case TOK_SRCPORT:
4426 			NEED1("missing source port");
4427 			if (_substrcmp(*av, "any") == 0 ||
4428 			    add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
4429 				ac--; av++;
4430 			} else
4431 				errx(EX_DATAERR, "invalid source port %s", *av);
4432 			break;
4433 
4434 		case TOK_DSTPORT:
4435 			NEED1("missing destination port");
4436 			if (_substrcmp(*av, "any") == 0 ||
4437 			    add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
4438 				ac--; av++;
4439 			} else
4440 				errx(EX_DATAERR, "invalid destination port %s",
4441 				    *av);
4442 			break;
4443 
4444 		case TOK_MAC:
4445 			if (add_mac(cmd, ac, av)) {
4446 				ac -= 2; av += 2;
4447 			}
4448 			break;
4449 
4450 		case TOK_MACTYPE:
4451 			NEED1("missing mac type");
4452 			if (!add_mactype(cmd, ac, *av))
4453 				errx(EX_DATAERR, "invalid mac type %s", *av);
4454 			ac--; av++;
4455 			break;
4456 
4457 		case TOK_VERREVPATH:
4458 			fill_cmd(cmd, O_VERREVPATH, 0, 0);
4459 			break;
4460 
4461 		case TOK_VERSRCREACH:
4462 			fill_cmd(cmd, O_VERSRCREACH, 0, 0);
4463 			break;
4464 
4465 		case TOK_ANTISPOOF:
4466 			fill_cmd(cmd, O_ANTISPOOF, 0, 0);
4467 			break;
4468 
4469 		case TOK_IPSEC:
4470 			fill_cmd(cmd, O_IPSEC, 0, 0);
4471 			break;
4472 
4473 		case TOK_IPV6:
4474 			fill_cmd(cmd, O_IP6, 0, 0);
4475 			break;
4476 
4477 		case TOK_IPV4:
4478 			fill_cmd(cmd, O_IP4, 0, 0);
4479 			break;
4480 
4481 		case TOK_EXT6HDR:
4482 			fill_ext6hdr( cmd, *av );
4483 			ac--; av++;
4484 			break;
4485 
4486 		case TOK_FLOWID:
4487 			if (proto != IPPROTO_IPV6 )
4488 				errx( EX_USAGE, "flow-id filter is active "
4489 				    "only for ipv6 protocol\n");
4490 			fill_flow6( (ipfw_insn_u32 *) cmd, *av );
4491 			ac--; av++;
4492 			break;
4493 
4494 		case TOK_COMMENT:
4495 			fill_comment(cmd, ac, av);
4496 			av += ac;
4497 			ac = 0;
4498 			break;
4499 
4500 		default:
4501 			errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
4502 		}
4503 		if (F_LEN(cmd) > 0) {	/* prepare to advance */
4504 			prev = cmd;
4505 			cmd = next_cmd(cmd);
4506 		}
4507 	}
4508 
4509 done:
4510 	/*
4511 	 * Now copy stuff into the rule.
4512 	 * If we have a keep-state option, the first instruction
4513 	 * must be a PROBE_STATE (which is generated here).
4514 	 * If we have a LOG option, it was stored as the first command,
4515 	 * and now must be moved to the top of the action part.
4516 	 */
4517 	dst = (ipfw_insn *)rule->cmd;
4518 
4519 	/*
4520 	 * First thing to write into the command stream is the match probability.
4521 	 */
4522 	if (match_prob != 1) { /* 1 means always match */
4523 		dst->opcode = O_PROB;
4524 		dst->len = 2;
4525 		*((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
4526 		dst += dst->len;
4527 	}
4528 
4529 	/*
4530 	 * generate O_PROBE_STATE if necessary
4531 	 */
4532 	if (have_state && have_state->opcode != O_CHECK_STATE) {
4533 		fill_cmd(dst, O_PROBE_STATE, 0, 0);
4534 		dst = next_cmd(dst);
4535 	}
4536 	/*
4537 	 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ
4538 	 */
4539 	for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
4540 		i = F_LEN(src);
4541 
4542 		switch (src->opcode) {
4543 		case O_LOG:
4544 		case O_KEEP_STATE:
4545 		case O_LIMIT:
4546 		case O_ALTQ:
4547 			break;
4548 		default:
4549 			bcopy(src, dst, i * sizeof(uint32_t));
4550 			dst += i;
4551 		}
4552 	}
4553 
4554 	/*
4555 	 * put back the have_state command as last opcode
4556 	 */
4557 	if (have_state && have_state->opcode != O_CHECK_STATE) {
4558 		i = F_LEN(have_state);
4559 		bcopy(have_state, dst, i * sizeof(uint32_t));
4560 		dst += i;
4561 	}
4562 	/*
4563 	 * start action section
4564 	 */
4565 	rule->act_ofs = dst - rule->cmd;
4566 
4567 	/*
4568 	 * put back O_LOG, O_ALTQ if necessary
4569 	 */
4570 	if (have_log) {
4571 		i = F_LEN(have_log);
4572 		bcopy(have_log, dst, i * sizeof(uint32_t));
4573 		dst += i;
4574 	}
4575 	if (have_altq) {
4576 		i = F_LEN(have_altq);
4577 		bcopy(have_altq, dst, i * sizeof(uint32_t));
4578 		dst += i;
4579 	}
4580 	/*
4581 	 * copy all other actions
4582 	 */
4583 	for (src = (ipfw_insn *)actbuf; src != action; src += i) {
4584 		i = F_LEN(src);
4585 		bcopy(src, dst, i * sizeof(uint32_t));
4586 		dst += i;
4587 	}
4588 
4589 	rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
4590 	i = (char *)dst - (char *)rule;
4591 	if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1)
4592 		err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
4593 	if (!do_quiet)
4594 		show_ipfw(rule, 0, 0);
4595 }
4596 
4597 static void
4598 zero(int ac, char *av[], int optname /* IP_FW_ZERO or IP_FW_RESETLOG */)
4599 {
4600 	int rulenum;
4601 	int failed = EX_OK;
4602 	char const *name = optname == IP_FW_ZERO ?  "ZERO" : "RESETLOG";
4603 
4604 	av++; ac--;
4605 
4606 	if (!ac) {
4607 		/* clear all entries */
4608 		if (do_cmd(optname, NULL, 0) < 0)
4609 			err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name);
4610 		if (!do_quiet)
4611 			printf("%s.\n", optname == IP_FW_ZERO ?
4612 			    "Accounting cleared":"Logging counts reset");
4613 
4614 		return;
4615 	}
4616 
4617 	while (ac) {
4618 		/* Rule number */
4619 		if (isdigit(**av)) {
4620 			rulenum = atoi(*av);
4621 			av++;
4622 			ac--;
4623 			if (do_cmd(optname, &rulenum, sizeof rulenum)) {
4624 				warn("rule %u: setsockopt(IP_FW_%s)",
4625 				    rulenum, name);
4626 				failed = EX_UNAVAILABLE;
4627 			} else if (!do_quiet)
4628 				printf("Entry %d %s.\n", rulenum,
4629 				    optname == IP_FW_ZERO ?
4630 					"cleared" : "logging count reset");
4631 		} else {
4632 			errx(EX_USAGE, "invalid rule number ``%s''", *av);
4633 		}
4634 	}
4635 	if (failed != EX_OK)
4636 		exit(failed);
4637 }
4638 
4639 static void
4640 flush(int force)
4641 {
4642 	int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
4643 
4644 	if (!force && !do_quiet) { /* need to ask user */
4645 		int c;
4646 
4647 		printf("Are you sure? [yn] ");
4648 		fflush(stdout);
4649 		do {
4650 			c = toupper(getc(stdin));
4651 			while (c != '\n' && getc(stdin) != '\n')
4652 				if (feof(stdin))
4653 					return; /* and do not flush */
4654 		} while (c != 'Y' && c != 'N');
4655 		printf("\n");
4656 		if (c == 'N')	/* user said no */
4657 			return;
4658 	}
4659 	if (do_cmd(cmd, NULL, 0) < 0)
4660 		err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
4661 		    do_pipe ? "DUMMYNET" : "FW");
4662 	if (!do_quiet)
4663 		printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules");
4664 }
4665 
4666 /*
4667  * Free a the (locally allocated) copy of command line arguments.
4668  */
4669 static void
4670 free_args(int ac, char **av)
4671 {
4672 	int i;
4673 
4674 	for (i=0; i < ac; i++)
4675 		free(av[i]);
4676 	free(av);
4677 }
4678 
4679 /*
4680  * This one handles all table-related commands
4681  * 	ipfw table N add addr[/masklen] [value]
4682  * 	ipfw table N delete addr[/masklen]
4683  * 	ipfw table N flush
4684  * 	ipfw table N list
4685  */
4686 static void
4687 table_handler(int ac, char *av[])
4688 {
4689 	ipfw_table_entry ent;
4690 	ipfw_table *tbl;
4691 	int do_add;
4692 	char *p;
4693 	socklen_t l;
4694 	uint32_t a;
4695 
4696 	ac--; av++;
4697 	if (ac && isdigit(**av)) {
4698 		ent.tbl = atoi(*av);
4699 		ac--; av++;
4700 	} else
4701 		errx(EX_USAGE, "table number required");
4702 	NEED1("table needs command");
4703 	if (_substrcmp(*av, "add") == 0 ||
4704 	    _substrcmp(*av, "delete") == 0) {
4705 		do_add = **av == 'a';
4706 		ac--; av++;
4707 		if (!ac)
4708 			errx(EX_USAGE, "IP address required");
4709 		p = strchr(*av, '/');
4710 		if (p) {
4711 			*p++ = '\0';
4712 			ent.masklen = atoi(p);
4713 			if (ent.masklen > 32)
4714 				errx(EX_DATAERR, "bad width ``%s''", p);
4715 		} else
4716 			ent.masklen = 32;
4717 		if (lookup_host(*av, (struct in_addr *)&ent.addr) != 0)
4718 			errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
4719 		ac--; av++;
4720 		if (do_add && ac)
4721 			ent.value = strtoul(*av, NULL, 0);
4722 		else
4723 			ent.value = 0;
4724 		if (do_cmd(do_add ? IP_FW_TABLE_ADD : IP_FW_TABLE_DEL,
4725 		    &ent, sizeof(ent)) < 0)
4726 			err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)",
4727 			    do_add ? "ADD" : "DEL");
4728 	} else if (_substrcmp(*av, "flush") == 0) {
4729 		if (do_cmd(IP_FW_TABLE_FLUSH, &ent.tbl, sizeof(ent.tbl)) < 0)
4730 			err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)");
4731 	} else if (_substrcmp(*av, "list") == 0) {
4732 		a = ent.tbl;
4733 		l = sizeof(a);
4734 		if (do_cmd(IP_FW_TABLE_GETSIZE, &a, (uintptr_t)&l) < 0)
4735 			err(EX_OSERR, "getsockopt(IP_FW_TABLE_GETSIZE)");
4736 		l = sizeof(*tbl) + a * sizeof(ipfw_table_entry);
4737 		tbl = malloc(l);
4738 		if (tbl == NULL)
4739 			err(EX_OSERR, "malloc");
4740 		tbl->tbl = ent.tbl;
4741 		if (do_cmd(IP_FW_TABLE_LIST, tbl, (uintptr_t)&l) < 0)
4742 			err(EX_OSERR, "getsockopt(IP_FW_TABLE_LIST)");
4743 		for (a = 0; a < tbl->cnt; a++) {
4744 			printf("%s/%u %u\n",
4745 			    inet_ntoa(*(struct in_addr *)&tbl->ent[a].addr),
4746 			    tbl->ent[a].masklen, tbl->ent[a].value);
4747 		}
4748 	} else
4749 		errx(EX_USAGE, "invalid table command %s", *av);
4750 }
4751 
4752 /*
4753  * Called with the arguments (excluding program name).
4754  * Returns 0 if successful, 1 if empty command, errx() in case of errors.
4755  */
4756 static int
4757 ipfw_main(int oldac, char **oldav)
4758 {
4759 	int ch, ac, save_ac;
4760 	char **av, **save_av;
4761 	int do_acct = 0;		/* Show packet/byte count */
4762 
4763 #define WHITESP		" \t\f\v\n\r"
4764 	if (oldac == 0)
4765 		return 1;
4766 	else if (oldac == 1) {
4767 		/*
4768 		 * If we are called with a single string, try to split it into
4769 		 * arguments for subsequent parsing.
4770 		 * But first, remove spaces after a ',', by copying the string
4771 		 * in-place.
4772 		 */
4773 		char *arg = oldav[0];	/* The string... */
4774 		int l = strlen(arg);
4775 		int copy = 0;		/* 1 if we need to copy, 0 otherwise */
4776 		int i, j;
4777 		for (i = j = 0; i < l; i++) {
4778 			if (arg[i] == '#')	/* comment marker */
4779 				break;
4780 			if (copy) {
4781 				arg[j++] = arg[i];
4782 				copy = !index("," WHITESP, arg[i]);
4783 			} else {
4784 				copy = !index(WHITESP, arg[i]);
4785 				if (copy)
4786 					arg[j++] = arg[i];
4787 			}
4788 		}
4789 		if (!copy && j > 0)	/* last char was a 'blank', remove it */
4790 			j--;
4791 		l = j;			/* the new argument length */
4792 		arg[j++] = '\0';
4793 		if (l == 0)		/* empty string! */
4794 			return 1;
4795 
4796 		/*
4797 		 * First, count number of arguments. Because of the previous
4798 		 * processing, this is just the number of blanks plus 1.
4799 		 */
4800 		for (i = 0, ac = 1; i < l; i++)
4801 			if (index(WHITESP, arg[i]) != NULL)
4802 				ac++;
4803 
4804 		av = calloc(ac, sizeof(char *));
4805 
4806 		/*
4807 		 * Second, copy arguments from cmd[] to av[]. For each one,
4808 		 * j is the initial character, i is the one past the end.
4809 		 */
4810 		for (ac = 0, i = j = 0; i < l; i++)
4811 			if (index(WHITESP, arg[i]) != NULL || i == l-1) {
4812 				if (i == l-1)
4813 					i++;
4814 				av[ac] = calloc(i-j+1, 1);
4815 				bcopy(arg+j, av[ac], i-j);
4816 				ac++;
4817 				j = i + 1;
4818 			}
4819 	} else {
4820 		/*
4821 		 * If an argument ends with ',' join with the next one.
4822 		 */
4823 		int first, i, l;
4824 
4825 		av = calloc(oldac, sizeof(char *));
4826 		for (first = i = ac = 0, l = 0; i < oldac; i++) {
4827 			char *arg = oldav[i];
4828 			int k = strlen(arg);
4829 
4830 			l += k;
4831 			if (arg[k-1] != ',' || i == oldac-1) {
4832 				/* Time to copy. */
4833 				av[ac] = calloc(l+1, 1);
4834 				for (l=0; first <= i; first++) {
4835 					strcat(av[ac]+l, oldav[first]);
4836 					l += strlen(oldav[first]);
4837 				}
4838 				ac++;
4839 				l = 0;
4840 				first = i+1;
4841 			}
4842 		}
4843 	}
4844 
4845 	/* Set the force flag for non-interactive processes */
4846 	if (!do_force)
4847 		do_force = !isatty(STDIN_FILENO);
4848 
4849 	/* Save arguments for final freeing of memory. */
4850 	save_ac = ac;
4851 	save_av = av;
4852 
4853 	optind = optreset = 0;
4854 	while ((ch = getopt(ac, av, "abcdefhnNqs:STtv")) != -1)
4855 		switch (ch) {
4856 		case 'a':
4857 			do_acct = 1;
4858 			break;
4859 
4860 		case 'b':
4861 			comment_only = 1;
4862 			do_compact = 1;
4863 			break;
4864 
4865 		case 'c':
4866 			do_compact = 1;
4867 			break;
4868 
4869 		case 'd':
4870 			do_dynamic = 1;
4871 			break;
4872 
4873 		case 'e':
4874 			do_expired = 1;
4875 			break;
4876 
4877 		case 'f':
4878 			do_force = 1;
4879 			break;
4880 
4881 		case 'h': /* help */
4882 			free_args(save_ac, save_av);
4883 			help();
4884 			break;	/* NOTREACHED */
4885 
4886 		case 'n':
4887 			test_only = 1;
4888 			break;
4889 
4890 		case 'N':
4891 			do_resolv = 1;
4892 			break;
4893 
4894 		case 'q':
4895 			do_quiet = 1;
4896 			break;
4897 
4898 		case 's': /* sort */
4899 			do_sort = atoi(optarg);
4900 			break;
4901 
4902 		case 'S':
4903 			show_sets = 1;
4904 			break;
4905 
4906 		case 't':
4907 			do_time = 1;
4908 			break;
4909 
4910 		case 'T':
4911 			do_time = 2;	/* numeric timestamp */
4912 			break;
4913 
4914 		case 'v': /* verbose */
4915 			verbose = 1;
4916 			break;
4917 
4918 		default:
4919 			free_args(save_ac, save_av);
4920 			return 1;
4921 		}
4922 
4923 	ac -= optind;
4924 	av += optind;
4925 	NEED1("bad arguments, for usage summary ``ipfw''");
4926 
4927 	/*
4928 	 * An undocumented behaviour of ipfw1 was to allow rule numbers first,
4929 	 * e.g. "100 add allow ..." instead of "add 100 allow ...".
4930 	 * In case, swap first and second argument to get the normal form.
4931 	 */
4932 	if (ac > 1 && isdigit(*av[0])) {
4933 		char *p = av[0];
4934 
4935 		av[0] = av[1];
4936 		av[1] = p;
4937 	}
4938 
4939 	/*
4940 	 * optional: pipe or queue
4941 	 */
4942 	do_pipe = 0;
4943 	if (_substrcmp(*av, "pipe") == 0)
4944 		do_pipe = 1;
4945 	else if (_substrcmp(*av, "queue") == 0)
4946 		do_pipe = 2;
4947 	if (do_pipe) {
4948 		ac--;
4949 		av++;
4950 	}
4951 	NEED1("missing command");
4952 
4953 	/*
4954 	 * For pipes and queues we normally say 'pipe NN config'
4955 	 * but the code is easier to parse as 'pipe config NN'
4956 	 * so we swap the two arguments.
4957 	 */
4958 	if (do_pipe > 0 && ac > 1 && isdigit(*av[0])) {
4959 		char *p = av[0];
4960 
4961 		av[0] = av[1];
4962 		av[1] = p;
4963 	}
4964 
4965 	if (_substrcmp(*av, "add") == 0)
4966 		add(ac, av);
4967 	else if (do_pipe && _substrcmp(*av, "config") == 0)
4968 		config_pipe(ac, av);
4969 	else if (_substrcmp(*av, "delete") == 0)
4970 		delete(ac, av);
4971 	else if (_substrcmp(*av, "flush") == 0)
4972 		flush(do_force);
4973 	else if (_substrcmp(*av, "zero") == 0)
4974 		zero(ac, av, IP_FW_ZERO);
4975 	else if (_substrcmp(*av, "resetlog") == 0)
4976 		zero(ac, av, IP_FW_RESETLOG);
4977 	else if (_substrcmp(*av, "print") == 0 ||
4978 	         _substrcmp(*av, "list") == 0)
4979 		list(ac, av, do_acct);
4980 	else if (_substrcmp(*av, "set") == 0)
4981 		sets_handler(ac, av);
4982 	else if (_substrcmp(*av, "table") == 0)
4983 		table_handler(ac, av);
4984 	else if (_substrcmp(*av, "enable") == 0)
4985 		sysctl_handler(ac, av, 1);
4986 	else if (_substrcmp(*av, "disable") == 0)
4987 		sysctl_handler(ac, av, 0);
4988 	else if (_substrcmp(*av, "show") == 0)
4989 		list(ac, av, 1 /* show counters */);
4990 	else
4991 		errx(EX_USAGE, "bad command `%s'", *av);
4992 
4993 	/* Free memory allocated in the argument parsing. */
4994 	free_args(save_ac, save_av);
4995 	return 0;
4996 }
4997 
4998 
4999 static void
5000 ipfw_readfile(int ac, char *av[])
5001 {
5002 #define MAX_ARGS	32
5003 	char	buf[BUFSIZ];
5004 	char	*cmd = NULL, *filename = av[ac-1];
5005 	int	c, lineno=0;
5006 	FILE	*f = NULL;
5007 	pid_t	preproc = 0;
5008 
5009 	filename = av[ac-1];
5010 
5011 	while ((c = getopt(ac, av, "cfNnp:qS")) != -1) {
5012 		switch(c) {
5013 		case 'c':
5014 			do_compact = 1;
5015 			break;
5016 
5017 		case 'f':
5018 			do_force = 1;
5019 			break;
5020 
5021 		case 'N':
5022 			do_resolv = 1;
5023 			break;
5024 
5025 		case 'n':
5026 			test_only = 1;
5027 			break;
5028 
5029 		case 'p':
5030 			cmd = optarg;
5031 			/*
5032 			 * Skip previous args and delete last one, so we
5033 			 * pass all but the last argument to the preprocessor
5034 			 * via av[optind-1]
5035 			 */
5036 			av += optind - 1;
5037 			ac -= optind - 1;
5038 			av[ac-1] = NULL;
5039 			fprintf(stderr, "command is %s\n", av[0]);
5040 			break;
5041 
5042 		case 'q':
5043 			do_quiet = 1;
5044 			break;
5045 
5046 		case 'S':
5047 			show_sets = 1;
5048 			break;
5049 
5050 		default:
5051 			errx(EX_USAGE, "bad arguments, for usage"
5052 			     " summary ``ipfw''");
5053 		}
5054 
5055 		if (cmd != NULL)
5056 			break;
5057 	}
5058 
5059 	if (cmd == NULL && ac != optind + 1) {
5060 		fprintf(stderr, "ac %d, optind %d\n", ac, optind);
5061 		errx(EX_USAGE, "extraneous filename arguments");
5062 	}
5063 
5064 	if ((f = fopen(filename, "r")) == NULL)
5065 		err(EX_UNAVAILABLE, "fopen: %s", filename);
5066 
5067 	if (cmd != NULL) {			/* pipe through preprocessor */
5068 		int pipedes[2];
5069 
5070 		if (pipe(pipedes) == -1)
5071 			err(EX_OSERR, "cannot create pipe");
5072 
5073 		preproc = fork();
5074 		if (preproc == -1)
5075 			err(EX_OSERR, "cannot fork");
5076 
5077 		if (preproc == 0) {
5078 			/*
5079 			 * Child, will run the preprocessor with the
5080 			 * file on stdin and the pipe on stdout.
5081 			 */
5082 			if (dup2(fileno(f), 0) == -1
5083 			    || dup2(pipedes[1], 1) == -1)
5084 				err(EX_OSERR, "dup2()");
5085 			fclose(f);
5086 			close(pipedes[1]);
5087 			close(pipedes[0]);
5088 			execvp(cmd, av);
5089 			err(EX_OSERR, "execvp(%s) failed", cmd);
5090 		} else { /* parent, will reopen f as the pipe */
5091 			fclose(f);
5092 			close(pipedes[1]);
5093 			if ((f = fdopen(pipedes[0], "r")) == NULL) {
5094 				int savederrno = errno;
5095 
5096 				(void)kill(preproc, SIGTERM);
5097 				errno = savederrno;
5098 				err(EX_OSERR, "fdopen()");
5099 			}
5100 		}
5101 	}
5102 
5103 	while (fgets(buf, BUFSIZ, f)) {		/* read commands */
5104 		char linename[10];
5105 		char *args[1];
5106 
5107 		lineno++;
5108 		sprintf(linename, "Line %d", lineno);
5109 		setprogname(linename); /* XXX */
5110 		args[0] = buf;
5111 		ipfw_main(1, args);
5112 	}
5113 	fclose(f);
5114 	if (cmd != NULL) {
5115 		int status;
5116 
5117 		if (waitpid(preproc, &status, 0) == -1)
5118 			errx(EX_OSERR, "waitpid()");
5119 		if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
5120 			errx(EX_UNAVAILABLE,
5121 			    "preprocessor exited with status %d",
5122 			    WEXITSTATUS(status));
5123 		else if (WIFSIGNALED(status))
5124 			errx(EX_UNAVAILABLE,
5125 			    "preprocessor exited with signal %d",
5126 			    WTERMSIG(status));
5127 	}
5128 }
5129 
5130 int
5131 main(int ac, char *av[])
5132 {
5133 	/*
5134 	 * If the last argument is an absolute pathname, interpret it
5135 	 * as a file to be preprocessed.
5136 	 */
5137 
5138 	if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0)
5139 		ipfw_readfile(ac, av);
5140 	else {
5141 		if (ipfw_main(ac-1, av+1))
5142 			show_usage();
5143 	}
5144 	return EX_OK;
5145 }
5146