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