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