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