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