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