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