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