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