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