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