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