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