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