ipfw2.c revision 116919
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 116919 2003-06-27 17:18: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	bcopy(&d->rule, &rulenum, sizeof(rulenum));
1281	printf("%05d %*llu %*llu (%ds)", rulenum, pcwidth,
1282	    align_uint64(&d->pcnt), bcwidth,
1283	    align_uint64(&d->bcnt), d->expire);
1284	switch (d->dyn_type) {
1285	case O_LIMIT_PARENT:
1286		printf(" PARENT %d", d->count);
1287		break;
1288	case O_LIMIT:
1289		printf(" LIMIT");
1290		break;
1291	case O_KEEP_STATE: /* bidir, no mask */
1292		printf(" STATE");
1293		break;
1294	}
1295
1296	if ((pe = getprotobynumber(d->id.proto)) != NULL)
1297		printf(" %s", pe->p_name);
1298	else
1299		printf(" proto %u", d->id.proto);
1300
1301	a.s_addr = htonl(d->id.src_ip);
1302	printf(" %s %d", inet_ntoa(a), d->id.src_port);
1303
1304	a.s_addr = htonl(d->id.dst_ip);
1305	printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
1306	printf("\n");
1307}
1308
1309int
1310sort_q(const void *pa, const void *pb)
1311{
1312	int rev = (do_sort < 0);
1313	int field = rev ? -do_sort : do_sort;
1314	long long res = 0;
1315	const struct dn_flow_queue *a = pa;
1316	const struct dn_flow_queue *b = pb;
1317
1318	switch (field) {
1319	case 1: /* pkts */
1320		res = a->len - b->len;
1321		break;
1322	case 2: /* bytes */
1323		res = a->len_bytes - b->len_bytes;
1324		break;
1325
1326	case 3: /* tot pkts */
1327		res = a->tot_pkts - b->tot_pkts;
1328		break;
1329
1330	case 4: /* tot bytes */
1331		res = a->tot_bytes - b->tot_bytes;
1332		break;
1333	}
1334	if (res < 0)
1335		res = -1;
1336	if (res > 0)
1337		res = 1;
1338	return (int)(rev ? res : -res);
1339}
1340
1341static void
1342list_queues(struct dn_flow_set *fs, struct dn_flow_queue *q)
1343{
1344	int l;
1345
1346	printf("    mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
1347	    fs->flow_mask.proto,
1348	    fs->flow_mask.src_ip, fs->flow_mask.src_port,
1349	    fs->flow_mask.dst_ip, fs->flow_mask.dst_port);
1350	if (fs->rq_elements == 0)
1351		return;
1352
1353	printf("BKT Prot ___Source IP/port____ "
1354	    "____Dest. IP/port____ Tot_pkt/bytes Pkt/Byte Drp\n");
1355	if (do_sort != 0)
1356		heapsort(q, fs->rq_elements, sizeof *q, sort_q);
1357	for (l = 0; l < fs->rq_elements; l++) {
1358		struct in_addr ina;
1359		struct protoent *pe;
1360
1361		ina.s_addr = htonl(q[l].id.src_ip);
1362		printf("%3d ", q[l].hash_slot);
1363		pe = getprotobynumber(q[l].id.proto);
1364		if (pe)
1365			printf("%-4s ", pe->p_name);
1366		else
1367			printf("%4u ", q[l].id.proto);
1368		printf("%15s/%-5d ",
1369		    inet_ntoa(ina), q[l].id.src_port);
1370		ina.s_addr = htonl(q[l].id.dst_ip);
1371		printf("%15s/%-5d ",
1372		    inet_ntoa(ina), q[l].id.dst_port);
1373		printf("%4qu %8qu %2u %4u %3u\n",
1374		    q[l].tot_pkts, q[l].tot_bytes,
1375		    q[l].len, q[l].len_bytes, q[l].drops);
1376		if (verbose)
1377			printf("   S %20qd  F %20qd\n",
1378			    q[l].S, q[l].F);
1379	}
1380}
1381
1382static void
1383print_flowset_parms(struct dn_flow_set *fs, char *prefix)
1384{
1385	int l;
1386	char qs[30];
1387	char plr[30];
1388	char red[90];	/* Display RED parameters */
1389
1390	l = fs->qsize;
1391	if (fs->flags_fs & DN_QSIZE_IS_BYTES) {
1392		if (l >= 8192)
1393			sprintf(qs, "%d KB", l / 1024);
1394		else
1395			sprintf(qs, "%d B", l);
1396	} else
1397		sprintf(qs, "%3d sl.", l);
1398	if (fs->plr)
1399		sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
1400	else
1401		plr[0] = '\0';
1402	if (fs->flags_fs & DN_IS_RED)	/* RED parameters */
1403		sprintf(red,
1404		    "\n\t  %cRED w_q %f min_th %d max_th %d max_p %f",
1405		    (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ',
1406		    1.0 * fs->w_q / (double)(1 << SCALE_RED),
1407		    SCALE_VAL(fs->min_th),
1408		    SCALE_VAL(fs->max_th),
1409		    1.0 * fs->max_p / (double)(1 << SCALE_RED));
1410	else
1411		sprintf(red, "droptail");
1412
1413	printf("%s %s%s %d queues (%d buckets) %s\n",
1414	    prefix, qs, plr, fs->rq_elements, fs->rq_size, red);
1415}
1416
1417static void
1418list_pipes(void *data, int nbytes, int ac, char *av[])
1419{
1420	u_long rulenum;
1421	void *next = data;
1422	struct dn_pipe *p = (struct dn_pipe *) data;
1423	struct dn_flow_set *fs;
1424	struct dn_flow_queue *q;
1425	int l;
1426
1427	if (ac > 0)
1428		rulenum = strtoul(*av++, NULL, 10);
1429	else
1430		rulenum = 0;
1431	for (; nbytes >= sizeof *p; p = (struct dn_pipe *)next) {
1432		double b = p->bandwidth;
1433		char buf[30];
1434		char prefix[80];
1435
1436		if (p->next != (struct dn_pipe *)DN_IS_PIPE)
1437			break;	/* done with pipes, now queues */
1438
1439		/*
1440		 * compute length, as pipe have variable size
1441		 */
1442		l = sizeof(*p) + p->fs.rq_elements * sizeof(*q);
1443		next = (void *)p + l;
1444		nbytes -= l;
1445
1446		if (rulenum != 0 && rulenum != p->pipe_nr)
1447			continue;
1448
1449		/*
1450		 * Print rate (or clocking interface)
1451		 */
1452		if (p->if_name[0] != '\0')
1453			sprintf(buf, "%s", p->if_name);
1454		else if (b == 0)
1455			sprintf(buf, "unlimited");
1456		else if (b >= 1000000)
1457			sprintf(buf, "%7.3f Mbit/s", b/1000000);
1458		else if (b >= 1000)
1459			sprintf(buf, "%7.3f Kbit/s", b/1000);
1460		else
1461			sprintf(buf, "%7.3f bit/s ", b);
1462
1463		sprintf(prefix, "%05d: %s %4d ms ",
1464		    p->pipe_nr, buf, p->delay);
1465		print_flowset_parms(&(p->fs), prefix);
1466		if (verbose)
1467			printf("   V %20qd\n", p->V >> MY_M);
1468
1469		q = (struct dn_flow_queue *)(p+1);
1470		list_queues(&(p->fs), q);
1471	}
1472	for (fs = next; nbytes >= sizeof *fs; fs = next) {
1473		char prefix[80];
1474
1475		if (fs->next != (struct dn_flow_set *)DN_IS_QUEUE)
1476			break;
1477		l = sizeof(*fs) + fs->rq_elements * sizeof(*q);
1478		next = (void *)fs + l;
1479		nbytes -= l;
1480		q = (struct dn_flow_queue *)(fs+1);
1481		sprintf(prefix, "q%05d: weight %d pipe %d ",
1482		    fs->fs_nr, fs->weight, fs->parent_nr);
1483		print_flowset_parms(fs, prefix);
1484		list_queues(fs, q);
1485	}
1486}
1487
1488/*
1489 * This one handles all set-related commands
1490 * 	ipfw set { show | enable | disable }
1491 * 	ipfw set swap X Y
1492 * 	ipfw set move X to Y
1493 * 	ipfw set move rule X to Y
1494 */
1495static void
1496sets_handler(int ac, char *av[])
1497{
1498	u_int32_t set_disable, masks[2];
1499	int i, nbytes;
1500	u_int16_t rulenum;
1501	u_int8_t cmd, new_set;
1502
1503	ac--;
1504	av++;
1505
1506	if (!ac)
1507		errx(EX_USAGE, "set needs command");
1508	if (!strncmp(*av, "show", strlen(*av)) ) {
1509		void *data;
1510		char *msg;
1511
1512		nbytes = sizeof(struct ip_fw);
1513		if ((data = malloc(nbytes)) == NULL)
1514			err(EX_OSERR, "malloc");
1515		if (getsockopt(s, IPPROTO_IP, IP_FW_GET, data, &nbytes) < 0)
1516			err(EX_OSERR, "getsockopt(IP_FW_GET)");
1517		bcopy(&((struct ip_fw *)data)->next_rule,
1518			&set_disable, sizeof(set_disable));
1519
1520		for (i = 0, msg = "disable" ; i < 31; i++)
1521			if (  (set_disable & (1<<i))) {
1522				printf("%s %d", msg, i);
1523				msg = "";
1524			}
1525		msg = (set_disable) ? " enable" : "enable";
1526		for (i = 0; i < 31; i++)
1527			if ( !(set_disable & (1<<i))) {
1528				printf("%s %d", msg, i);
1529				msg = "";
1530			}
1531		printf("\n");
1532	} else if (!strncmp(*av, "swap", strlen(*av))) {
1533		ac--; av++;
1534		if (ac != 2)
1535			errx(EX_USAGE, "set swap needs 2 set numbers\n");
1536		rulenum = atoi(av[0]);
1537		new_set = atoi(av[1]);
1538		if (!isdigit(*(av[0])) || rulenum > 30)
1539			errx(EX_DATAERR, "invalid set number %s\n", av[0]);
1540		if (!isdigit(*(av[1])) || new_set > 30)
1541			errx(EX_DATAERR, "invalid set number %s\n", av[1]);
1542		masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
1543		i = setsockopt(s, IPPROTO_IP, IP_FW_DEL,
1544			masks, sizeof(u_int32_t));
1545	} else if (!strncmp(*av, "move", strlen(*av))) {
1546		ac--; av++;
1547		if (ac && !strncmp(*av, "rule", strlen(*av))) {
1548			cmd = 2;
1549			ac--; av++;
1550		} else
1551			cmd = 3;
1552		if (ac != 3 || strncmp(av[1], "to", strlen(*av)))
1553			errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
1554		rulenum = atoi(av[0]);
1555		new_set = atoi(av[2]);
1556		if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > 30) ||
1557			(cmd == 2 && rulenum == 65535) )
1558			errx(EX_DATAERR, "invalid source number %s\n", av[0]);
1559		if (!isdigit(*(av[2])) || new_set > 30)
1560			errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
1561		masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
1562		i = setsockopt(s, IPPROTO_IP, IP_FW_DEL,
1563			masks, sizeof(u_int32_t));
1564	} else if (!strncmp(*av, "disable", strlen(*av)) ||
1565		   !strncmp(*av, "enable",  strlen(*av)) ) {
1566		int which = !strncmp(*av, "enable",  strlen(*av)) ? 1 : 0;
1567
1568		ac--; av++;
1569		masks[0] = masks[1] = 0;
1570
1571		while (ac) {
1572			if (isdigit(**av)) {
1573				i = atoi(*av);
1574				if (i < 0 || i > 30)
1575					errx(EX_DATAERR,
1576					    "invalid set number %d\n", i);
1577				masks[which] |= (1<<i);
1578			} else if (!strncmp(*av, "disable", strlen(*av)))
1579				which = 0;
1580			else if (!strncmp(*av, "enable", strlen(*av)))
1581				which = 1;
1582			else
1583				errx(EX_DATAERR,
1584					"invalid set command %s\n", *av);
1585			av++; ac--;
1586		}
1587		if ( (masks[0] & masks[1]) != 0 )
1588			errx(EX_DATAERR,
1589			    "cannot enable and disable the same set\n");
1590
1591		i = setsockopt(s, IPPROTO_IP, IP_FW_DEL, masks, sizeof(masks));
1592		if (i)
1593			warn("set enable/disable: setsockopt(IP_FW_DEL)");
1594	} else
1595		errx(EX_USAGE, "invalid set command %s\n", *av);
1596}
1597
1598static void
1599sysctl_handler(int ac, char *av[], int which)
1600{
1601	ac--;
1602	av++;
1603
1604	if (*av == NULL) {
1605		warnx("missing keyword to enable/disable\n");
1606	} else if (strncmp(*av, "firewall", strlen(*av)) == 0) {
1607		sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
1608		    &which, sizeof(which));
1609	} else if (strncmp(*av, "one_pass", strlen(*av)) == 0) {
1610		sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
1611		    &which, sizeof(which));
1612	} else if (strncmp(*av, "debug", strlen(*av)) == 0) {
1613		sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
1614		    &which, sizeof(which));
1615	} else if (strncmp(*av, "verbose", strlen(*av)) == 0) {
1616		sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
1617		    &which, sizeof(which));
1618	} else if (strncmp(*av, "dyn_keepalive", strlen(*av)) == 0) {
1619		sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
1620		    &which, sizeof(which));
1621	} else {
1622		warnx("unrecognize enable/disable keyword: %s\n", *av);
1623	}
1624}
1625
1626static void
1627list(int ac, char *av[])
1628{
1629	struct ip_fw *r;
1630	ipfw_dyn_rule *dynrules, *d;
1631
1632	void *lim, *data = NULL;
1633	int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
1634	int exitval = EX_OK;
1635	int lac;
1636	char **lav;
1637	u_long rnum;
1638	char *endptr;
1639	int seen = 0;
1640
1641	const int ocmd = do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
1642	int nalloc = 1024;	/* start somewhere... */
1643
1644	ac--;
1645	av++;
1646
1647	/* get rules or pipes from kernel, resizing array as necessary */
1648	nbytes = nalloc;
1649
1650	while (nbytes >= nalloc) {
1651		nalloc = nalloc * 2 + 200;
1652		nbytes = nalloc;
1653		if ((data = realloc(data, nbytes)) == NULL)
1654			err(EX_OSERR, "realloc");
1655		if (getsockopt(s, IPPROTO_IP, ocmd, data, &nbytes) < 0)
1656			err(EX_OSERR, "getsockopt(IP_%s_GET)",
1657				do_pipe ? "DUMMYNET" : "FW");
1658	}
1659
1660	if (do_pipe) {
1661		list_pipes(data, nbytes, ac, av);
1662		goto done;
1663	}
1664
1665	/*
1666	 * Count static rules. They have variable size so we
1667	 * need to scan the list to count them.
1668	 */
1669	for (nstat = 1, r = data, lim = data + nbytes;
1670		    r->rulenum < 65535 && (void *)r < lim;
1671		    ++nstat, r = (void *)r + RULESIZE(r) )
1672		; /* nothing */
1673
1674	/*
1675	 * Count dynamic rules. This is easier as they have
1676	 * fixed size.
1677	 */
1678	r = (void *)r + RULESIZE(r);
1679	dynrules = (ipfw_dyn_rule *)r ;
1680	n = (void *)r - data;
1681	ndyn = (nbytes - n) / sizeof *dynrules;
1682
1683	/* if showing stats, figure out column widths ahead of time */
1684	bcwidth = pcwidth = 0;
1685	if (do_acct) {
1686		for (n = 0, r = data; n < nstat;
1687		    n++, r = (void *)r + RULESIZE(r)) {
1688			/* packet counter */
1689			width = snprintf(NULL, 0, "%llu",
1690			    align_uint64(&r->pcnt));
1691			if (width > pcwidth)
1692				pcwidth = width;
1693
1694			/* byte counter */
1695			width = snprintf(NULL, 0, "%llu",
1696			    align_uint64(&r->bcnt));
1697			if (width > bcwidth)
1698				bcwidth = width;
1699		}
1700	}
1701	if (do_dynamic && ndyn) {
1702		for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1703			width = snprintf(NULL, 0, "%llu",
1704			    align_uint64(&d->pcnt));
1705			if (width > pcwidth)
1706				pcwidth = width;
1707
1708			width = snprintf(NULL, 0, "%llu",
1709			    align_uint64(&d->bcnt));
1710			if (width > bcwidth)
1711				bcwidth = width;
1712		}
1713	}
1714	/* if no rule numbers were specified, list all rules */
1715	if (ac == 0) {
1716		for (n = 0, r = data; n < nstat;
1717		    n++, r = (void *)r + RULESIZE(r) )
1718			show_ipfw(r, pcwidth, bcwidth);
1719
1720		if (do_dynamic && ndyn) {
1721			printf("## Dynamic rules (%d):\n", ndyn);
1722			for (n = 0, d = dynrules; n < ndyn; n++, d++)
1723				show_dyn_ipfw(d, pcwidth, bcwidth);
1724		}
1725		goto done;
1726	}
1727
1728	/* display specific rules requested on command line */
1729
1730	for (lac = ac, lav = av; lac != 0; lac--) {
1731		/* convert command line rule # */
1732		rnum = strtoul(*lav++, &endptr, 10);
1733		if (*endptr) {
1734			exitval = EX_USAGE;
1735			warnx("invalid rule number: %s", *(lav - 1));
1736			continue;
1737		}
1738		for (n = seen = 0, r = data; n < nstat;
1739		    n++, r = (void *)r + RULESIZE(r) ) {
1740			if (r->rulenum > rnum)
1741				break;
1742			if (r->rulenum == rnum) {
1743				show_ipfw(r, pcwidth, bcwidth);
1744				seen = 1;
1745			}
1746		}
1747		if (!seen) {
1748			/* give precedence to other error(s) */
1749			if (exitval == EX_OK)
1750				exitval = EX_UNAVAILABLE;
1751			warnx("rule %lu does not exist", rnum);
1752		}
1753	}
1754
1755	if (do_dynamic && ndyn) {
1756		printf("## Dynamic rules:\n");
1757		for (lac = ac, lav = av; lac != 0; lac--) {
1758			rnum = strtoul(*lav++, &endptr, 10);
1759			if (*endptr)
1760				/* already warned */
1761				continue;
1762			for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1763				uint16_t rulenum;
1764
1765				bcopy(&d->rule, &rulenum, sizeof(rulenum));
1766				if (rulenum > rnum)
1767					break;
1768				if (rulenum == rnum)
1769					show_dyn_ipfw(d, pcwidth, bcwidth);
1770			}
1771		}
1772	}
1773
1774	ac = 0;
1775
1776done:
1777	free(data);
1778
1779	if (exitval != EX_OK)
1780		exit(exitval);
1781}
1782
1783static void
1784show_usage(void)
1785{
1786	fprintf(stderr, "usage: ipfw [options]\n"
1787"    add [number] rule\n"
1788"    pipe number config [pipeconfig]\n"
1789"    queue number config [queueconfig]\n"
1790"    [pipe] flush\n"
1791"    [pipe] delete number ...\n"
1792"    [pipe] {list|show} [number ...]\n"
1793"    {zero|resetlog} [number ...]\n"
1794"do \"ipfw -h\" or see ipfw manpage for details\n"
1795);
1796
1797	exit(EX_USAGE);
1798}
1799
1800static void
1801help(void)
1802{
1803
1804	fprintf(stderr, "ipfw syntax summary:\n"
1805"ipfw add [N] [prob {0..1}] ACTION [log [logamount N]] ADDR OPTIONS\n"
1806"ipfw {pipe|queue} N config BODY\n"
1807"ipfw [pipe] {zero|delete|show} [N{,N}]\n"
1808"\n"
1809"RULE:		[1..] [PROB] BODY\n"
1810"RULENUM:	INTEGER(1..65534)\n"
1811"PROB:		prob REAL(0..1)\n"
1812"BODY:		check-state [LOG] (no body) |\n"
1813"		ACTION [LOG] MATCH_ADDR [OPTION_LIST]\n"
1814"ACTION:	check-state | allow | count | deny | reject | skipto N |\n"
1815"		{divert|tee} PORT | forward ADDR | pipe N | queue N\n"
1816"ADDR:		[ MAC dst src ether_type ] \n"
1817"		[ from IPLIST [ PORT ] to IPLIST [ PORTLIST ] ]\n"
1818"IPLIST:	IPADDR | ( IPADDR or ... or IPADDR )\n"
1819"IPADDR:	[not] { any | me | ip | ip/bits | ip:mask | ip/bits{x,y,z} }\n"
1820"OPTION_LIST:	OPTION [,OPTION_LIST]\n"
1821);
1822exit(0);
1823}
1824
1825
1826static int
1827lookup_host (char *host, struct in_addr *ipaddr)
1828{
1829	struct hostent *he;
1830
1831	if (!inet_aton(host, ipaddr)) {
1832		if ((he = gethostbyname(host)) == NULL)
1833			return(-1);
1834		*ipaddr = *(struct in_addr *)he->h_addr_list[0];
1835	}
1836	return(0);
1837}
1838
1839/*
1840 * fills the addr and mask fields in the instruction as appropriate from av.
1841 * Update length as appropriate.
1842 * The following formats are allowed:
1843 *	any	matches any IP. Actually returns an empty instruction.
1844 *	me	returns O_IP_*_ME
1845 *	1.2.3.4		single IP address
1846 *	1.2.3.4:5.6.7.8	address:mask
1847 *	1.2.3.4/24	address/mask
1848 *	1.2.3.4/26{1,6,5,4,23}	set of addresses in a subnet
1849 */
1850static void
1851fill_ip(ipfw_insn_ip *cmd, char *av)
1852{
1853	char *p = 0, md = 0;
1854	u_int32_t i;
1855
1856	cmd->o.len &= ~F_LEN_MASK;	/* zero len */
1857
1858	if (!strncmp(av, "any", strlen(av)))
1859		return;
1860
1861	if (!strncmp(av, "me", strlen(av))) {
1862		cmd->o.len |= F_INSN_SIZE(ipfw_insn);
1863		return;
1864	}
1865
1866	p = strchr(av, '/');
1867	if (!p)
1868		p = strchr(av, ':');
1869	if (p) {
1870		md = *p;
1871		*p++ = '\0';
1872	}
1873
1874	if (lookup_host(av, &cmd->addr) != 0)
1875		errx(EX_NOHOST, "hostname ``%s'' unknown", av);
1876	switch (md) {
1877	case ':':
1878		if (!inet_aton(p, &cmd->mask))
1879			errx(EX_DATAERR, "bad netmask ``%s''", p);
1880		break;
1881	case '/':
1882		i = atoi(p);
1883		if (i == 0)
1884			cmd->mask.s_addr = htonl(0);
1885		else if (i > 32)
1886			errx(EX_DATAERR, "bad width ``%s''", p);
1887		else
1888			cmd->mask.s_addr = htonl(~0 << (32 - i));
1889		break;
1890	default:
1891		cmd->mask.s_addr = htonl(~0);
1892		break;
1893	}
1894	cmd->addr.s_addr &= cmd->mask.s_addr;
1895	/*
1896	 * now look if we have a set of addresses. They are stored as follows:
1897	 *   arg1	is the set size (powers of 2, 2..256)
1898	 *   addr	is the base address IN HOST FORMAT
1899	 *   mask..	is an array of u_int32_t with bits set.
1900	 */
1901	if (p)
1902		p = strchr(p, '{');
1903	if (p) {	/* fetch addresses */
1904		u_int32_t *d;
1905		int low, high;
1906		int i = contigmask((u_char *)&(cmd->mask), 32);
1907
1908		if (i < 24 || i > 31) {
1909			fprintf(stderr, "invalid set with mask %d\n",
1910				i);
1911			exit(0);
1912		}
1913		cmd->o.arg1 = 1<<(32-i);
1914		cmd->addr.s_addr = ntohl(cmd->addr.s_addr);
1915		d = (u_int32_t *)&cmd->mask;
1916		cmd->o.opcode = O_IP_DST_SET;	/* default */
1917		cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
1918		for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
1919			d[i] = 0;	/* clear masks */
1920
1921		av = p+1;
1922		low = cmd->addr.s_addr & 0xff;
1923		high = low + cmd->o.arg1 - 1;
1924		i = -1;	/* previous value in a range */
1925		while (isdigit(*av)) {
1926			char *s;
1927			u_int16_t a = strtol(av, &s, 0);
1928
1929			if (s == av) /* no parameter */
1930				break;
1931			if (a < low || a > high) {
1932			    fprintf(stderr, "addr %d out of range [%d-%d]\n",
1933				a, low, high);
1934			    exit(0);
1935			}
1936			a -= low;
1937			if (i == -1)	/* no previous in range */
1938			    i = a;
1939			else {		/* check that range is valid */
1940			    if (i > a)
1941				errx(EX_DATAERR, "invalid range %d-%d",
1942					i+low, a+low);
1943			    if (*s == '-')
1944				errx(EX_DATAERR, "double '-' in range");
1945			}
1946			for (; i <= a; i++)
1947			    d[i/32] |= 1<<(i & 31);
1948			i = -1;
1949			if (*s == '-')
1950			    i = a;
1951			else if (*s != ',')
1952			    break;
1953			av = s+1;
1954		}
1955		return;
1956	}
1957
1958	if (cmd->mask.s_addr == 0) { /* any */
1959		if (cmd->o.len & F_NOT)
1960			errx(EX_DATAERR, "not any never matches");
1961		else	/* useless, nuke it */
1962			return;
1963	} else if (cmd->mask.s_addr ==  IP_MASK_ALL)	/* one IP */
1964		cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1965	else						/* addr/mask */
1966		cmd->o.len |= F_INSN_SIZE(ipfw_insn_ip);
1967}
1968
1969
1970/*
1971 * helper function to process a set of flags and set bits in the
1972 * appropriate masks.
1973 */
1974static void
1975fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
1976	struct _s_x *flags, char *p)
1977{
1978	u_int8_t set=0, clear=0;
1979
1980	while (p && *p) {
1981		char *q;	/* points to the separator */
1982		int val;
1983		u_int8_t *which;	/* mask we are working on */
1984
1985		if (*p == '!') {
1986			p++;
1987			which = &clear;
1988		} else
1989			which = &set;
1990		q = strchr(p, ',');
1991		if (q)
1992			*q++ = '\0';
1993		val = match_token(flags, p);
1994		if (val <= 0)
1995			errx(EX_DATAERR, "invalid flag %s", p);
1996		*which |= (u_int8_t)val;
1997		p = q;
1998	}
1999        cmd->opcode = opcode;
2000        cmd->len =  (cmd->len & (F_NOT | F_OR)) | 1;
2001        cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
2002}
2003
2004
2005static void
2006delete(int ac, char *av[])
2007{
2008	u_int32_t rulenum;
2009	struct dn_pipe pipe;
2010	int i;
2011	int exitval = EX_OK;
2012	int do_set = 0;
2013
2014	memset(&pipe, 0, sizeof pipe);
2015
2016	av++; ac--;
2017	if (ac > 0 && !strncmp(*av, "set", strlen(*av))) {
2018		do_set = 1;	/* delete set */
2019		ac--; av++;
2020	}
2021
2022	/* Rule number */
2023	while (ac && isdigit(**av)) {
2024		i = atoi(*av); av++; ac--;
2025		if (do_pipe) {
2026			if (do_pipe == 1)
2027				pipe.pipe_nr = i;
2028			else
2029				pipe.fs.fs_nr = i;
2030			i = setsockopt(s, IPPROTO_IP, IP_DUMMYNET_DEL,
2031			    &pipe, sizeof pipe);
2032			if (i) {
2033				exitval = 1;
2034				warn("rule %u: setsockopt(IP_DUMMYNET_DEL)",
2035				    do_pipe == 1 ? pipe.pipe_nr :
2036				    pipe.fs.fs_nr);
2037			}
2038		} else {
2039			rulenum =  (i & 0xffff) | (do_set << 24);
2040			i = setsockopt(s, IPPROTO_IP, IP_FW_DEL, &rulenum,
2041			    sizeof rulenum);
2042			if (i) {
2043				exitval = EX_UNAVAILABLE;
2044				warn("rule %u: setsockopt(IP_FW_DEL)",
2045				    rulenum);
2046			}
2047		}
2048	}
2049	if (exitval != EX_OK)
2050		exit(exitval);
2051}
2052
2053
2054/*
2055 * fill the interface structure. We do not check the name as we can
2056 * create interfaces dynamically, so checking them at insert time
2057 * makes relatively little sense.
2058 * A '*' following the name means any unit.
2059 */
2060static void
2061fill_iface(ipfw_insn_if *cmd, char *arg)
2062{
2063	cmd->name[0] = '\0';
2064	cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
2065
2066	/* Parse the interface or address */
2067	if (!strcmp(arg, "any"))
2068		cmd->o.len = 0;		/* effectively ignore this command */
2069	else if (!isdigit(*arg)) {
2070		char *q;
2071
2072		strncpy(cmd->name, arg, sizeof(cmd->name));
2073		cmd->name[sizeof(cmd->name) - 1] = '\0';
2074		/* find first digit or wildcard */
2075		for (q = cmd->name; *q && !isdigit(*q) && *q != '*'; q++)
2076			continue;
2077		cmd->p.unit = (*q == '*') ? -1 : atoi(q);
2078		*q = '\0';
2079	} else if (!inet_aton(arg, &cmd->p.ip))
2080		errx(EX_DATAERR, "bad ip address ``%s''", arg);
2081}
2082
2083/*
2084 * the following macro returns an error message if we run out of
2085 * arguments.
2086 */
2087#define	NEED1(msg)	{if (!ac) errx(EX_USAGE, msg);}
2088
2089static void
2090config_pipe(int ac, char **av)
2091{
2092	struct dn_pipe pipe;
2093	int i;
2094	char *end;
2095	u_int32_t a;
2096	void *par = NULL;
2097
2098	memset(&pipe, 0, sizeof pipe);
2099
2100	av++; ac--;
2101	/* Pipe number */
2102	if (ac && isdigit(**av)) {
2103		i = atoi(*av); av++; ac--;
2104		if (do_pipe == 1)
2105			pipe.pipe_nr = i;
2106		else
2107			pipe.fs.fs_nr = i;
2108	}
2109	while (ac > 0) {
2110		double d;
2111		int tok = match_token(dummynet_params, *av);
2112		ac--; av++;
2113
2114		switch(tok) {
2115		case TOK_NOERROR:
2116			pipe.fs.flags_fs |= DN_NOERROR;
2117			break;
2118
2119		case TOK_PLR:
2120			NEED1("plr needs argument 0..1\n");
2121			d = strtod(av[0], NULL);
2122			if (d > 1)
2123				d = 1;
2124			else if (d < 0)
2125				d = 0;
2126			pipe.fs.plr = (int)(d*0x7fffffff);
2127			ac--; av++;
2128			break;
2129
2130		case TOK_QUEUE:
2131			NEED1("queue needs queue size\n");
2132			end = NULL;
2133			pipe.fs.qsize = strtoul(av[0], &end, 0);
2134			if (*end == 'K' || *end == 'k') {
2135				pipe.fs.flags_fs |= DN_QSIZE_IS_BYTES;
2136				pipe.fs.qsize *= 1024;
2137			} else if (*end == 'B' || !strncmp(end, "by", 2)) {
2138				pipe.fs.flags_fs |= DN_QSIZE_IS_BYTES;
2139			}
2140			ac--; av++;
2141			break;
2142
2143		case TOK_BUCKETS:
2144			NEED1("buckets needs argument\n");
2145			pipe.fs.rq_size = strtoul(av[0], NULL, 0);
2146			ac--; av++;
2147			break;
2148
2149		case TOK_MASK:
2150			NEED1("mask needs mask specifier\n");
2151			/*
2152			 * per-flow queue, mask is dst_ip, dst_port,
2153			 * src_ip, src_port, proto measured in bits
2154			 */
2155			par = NULL;
2156
2157			pipe.fs.flow_mask.dst_ip = 0;
2158			pipe.fs.flow_mask.src_ip = 0;
2159			pipe.fs.flow_mask.dst_port = 0;
2160			pipe.fs.flow_mask.src_port = 0;
2161			pipe.fs.flow_mask.proto = 0;
2162			end = NULL;
2163
2164			while (ac >= 1) {
2165			    u_int32_t *p32 = NULL;
2166			    u_int16_t *p16 = NULL;
2167
2168			    tok = match_token(dummynet_params, *av);
2169			    ac--; av++;
2170			    switch(tok) {
2171			    case TOK_ALL:
2172				    /*
2173				     * special case, all bits significant
2174				     */
2175				    pipe.fs.flow_mask.dst_ip = ~0;
2176				    pipe.fs.flow_mask.src_ip = ~0;
2177				    pipe.fs.flow_mask.dst_port = ~0;
2178				    pipe.fs.flow_mask.src_port = ~0;
2179				    pipe.fs.flow_mask.proto = ~0;
2180				    pipe.fs.flags_fs |= DN_HAVE_FLOW_MASK;
2181				    goto end_mask;
2182
2183			    case TOK_DSTIP:
2184				    p32 = &pipe.fs.flow_mask.dst_ip;
2185				    break;
2186
2187			    case TOK_SRCIP:
2188				    p32 = &pipe.fs.flow_mask.src_ip;
2189				    break;
2190
2191			    case TOK_DSTPORT:
2192				    p16 = &pipe.fs.flow_mask.dst_port;
2193				    break;
2194
2195			    case TOK_SRCPORT:
2196				    p16 = &pipe.fs.flow_mask.src_port;
2197				    break;
2198
2199			    case TOK_PROTO:
2200				    break;
2201
2202			    default:
2203				    ac++; av--; /* backtrack */
2204				    goto end_mask;
2205			    }
2206			    if (ac < 1)
2207				    errx(EX_USAGE, "mask: value missing");
2208			    if (*av[0] == '/') {
2209				    a = strtoul(av[0]+1, &end, 0);
2210				    a = (a == 32) ? ~0 : (1 << a) - 1;
2211			    } else
2212				    a = strtoul(av[0], &end, 0);
2213			    if (p32 != NULL)
2214				    *p32 = a;
2215			    else if (p16 != NULL) {
2216				    if (a > 65535)
2217					    errx(EX_DATAERR,
2218						"mask: must be 16 bit");
2219				    *p16 = (u_int16_t)a;
2220			    } else {
2221				    if (a > 255)
2222					    errx(EX_DATAERR,
2223						"mask: must be 8 bit");
2224				    pipe.fs.flow_mask.proto = (u_int8_t)a;
2225			    }
2226			    if (a != 0)
2227				    pipe.fs.flags_fs |= DN_HAVE_FLOW_MASK;
2228			    ac--; av++;
2229			} /* end while, config masks */
2230end_mask:
2231			break;
2232
2233		case TOK_RED:
2234		case TOK_GRED:
2235			NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
2236			pipe.fs.flags_fs |= DN_IS_RED;
2237			if (tok == TOK_GRED)
2238				pipe.fs.flags_fs |= DN_IS_GENTLE_RED;
2239			/*
2240			 * the format for parameters is w_q/min_th/max_th/max_p
2241			 */
2242			if ((end = strsep(&av[0], "/"))) {
2243			    double w_q = strtod(end, NULL);
2244			    if (w_q > 1 || w_q <= 0)
2245				errx(EX_DATAERR, "0 < w_q <= 1");
2246			    pipe.fs.w_q = (int) (w_q * (1 << SCALE_RED));
2247			}
2248			if ((end = strsep(&av[0], "/"))) {
2249			    pipe.fs.min_th = strtoul(end, &end, 0);
2250			    if (*end == 'K' || *end == 'k')
2251				pipe.fs.min_th *= 1024;
2252			}
2253			if ((end = strsep(&av[0], "/"))) {
2254			    pipe.fs.max_th = strtoul(end, &end, 0);
2255			    if (*end == 'K' || *end == 'k')
2256				pipe.fs.max_th *= 1024;
2257			}
2258			if ((end = strsep(&av[0], "/"))) {
2259			    double max_p = strtod(end, NULL);
2260			    if (max_p > 1 || max_p <= 0)
2261				errx(EX_DATAERR, "0 < max_p <= 1");
2262			    pipe.fs.max_p = (int)(max_p * (1 << SCALE_RED));
2263			}
2264			ac--; av++;
2265			break;
2266
2267		case TOK_DROPTAIL:
2268			pipe.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
2269			break;
2270
2271		case TOK_BW:
2272			NEED1("bw needs bandwidth or interface\n");
2273			if (do_pipe != 1)
2274			    errx(EX_DATAERR, "bandwidth only valid for pipes");
2275			/*
2276			 * set clocking interface or bandwidth value
2277			 */
2278			if (av[0][0] >= 'a' && av[0][0] <= 'z') {
2279			    int l = sizeof(pipe.if_name)-1;
2280			    /* interface name */
2281			    strncpy(pipe.if_name, av[0], l);
2282			    pipe.if_name[l] = '\0';
2283			    pipe.bandwidth = 0;
2284			} else {
2285			    pipe.if_name[0] = '\0';
2286			    pipe.bandwidth = strtoul(av[0], &end, 0);
2287			    if (*end == 'K' || *end == 'k') {
2288				end++;
2289				pipe.bandwidth *= 1000;
2290			    } else if (*end == 'M') {
2291				end++;
2292				pipe.bandwidth *= 1000000;
2293			    }
2294			    if (*end == 'B' || !strncmp(end, "by", 2))
2295				pipe.bandwidth *= 8;
2296			    if (pipe.bandwidth < 0)
2297				errx(EX_DATAERR, "bandwidth too large");
2298			}
2299			ac--; av++;
2300			break;
2301
2302		case TOK_DELAY:
2303			if (do_pipe != 1)
2304				errx(EX_DATAERR, "delay only valid for pipes");
2305			NEED1("delay needs argument 0..10000ms\n");
2306			pipe.delay = strtoul(av[0], NULL, 0);
2307			ac--; av++;
2308			break;
2309
2310		case TOK_WEIGHT:
2311			if (do_pipe == 1)
2312				errx(EX_DATAERR,"weight only valid for queues");
2313			NEED1("weight needs argument 0..100\n");
2314			pipe.fs.weight = strtoul(av[0], &end, 0);
2315			ac--; av++;
2316			break;
2317
2318		case TOK_PIPE:
2319			if (do_pipe == 1)
2320				errx(EX_DATAERR,"pipe only valid for queues");
2321			NEED1("pipe needs pipe_number\n");
2322			pipe.fs.parent_nr = strtoul(av[0], &end, 0);
2323			ac--; av++;
2324			break;
2325
2326		default:
2327			errx(EX_DATAERR, "unrecognised option ``%s''", *av);
2328		}
2329	}
2330	if (do_pipe == 1) {
2331		if (pipe.pipe_nr == 0)
2332			errx(EX_DATAERR, "pipe_nr must be > 0");
2333		if (pipe.delay > 10000)
2334			errx(EX_DATAERR, "delay must be < 10000");
2335	} else { /* do_pipe == 2, queue */
2336		if (pipe.fs.parent_nr == 0)
2337			errx(EX_DATAERR, "pipe must be > 0");
2338		if (pipe.fs.weight >100)
2339			errx(EX_DATAERR, "weight must be <= 100");
2340	}
2341	if (pipe.fs.flags_fs & DN_QSIZE_IS_BYTES) {
2342		if (pipe.fs.qsize > 1024*1024)
2343			errx(EX_DATAERR, "queue size must be < 1MB");
2344	} else {
2345		if (pipe.fs.qsize > 100)
2346			errx(EX_DATAERR, "2 <= queue size <= 100");
2347	}
2348	if (pipe.fs.flags_fs & DN_IS_RED) {
2349		size_t len;
2350		int lookup_depth, avg_pkt_size;
2351		double s, idle, weight, w_q;
2352		struct clockinfo clock;
2353		int t;
2354
2355		if (pipe.fs.min_th >= pipe.fs.max_th)
2356		    errx(EX_DATAERR, "min_th %d must be < than max_th %d",
2357			pipe.fs.min_th, pipe.fs.max_th);
2358		if (pipe.fs.max_th == 0)
2359		    errx(EX_DATAERR, "max_th must be > 0");
2360
2361		len = sizeof(int);
2362		if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
2363			&lookup_depth, &len, NULL, 0) == -1)
2364
2365		    errx(1, "sysctlbyname(\"%s\")",
2366			"net.inet.ip.dummynet.red_lookup_depth");
2367		if (lookup_depth == 0)
2368		    errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
2369			" must be greater than zero");
2370
2371		len = sizeof(int);
2372		if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
2373			&avg_pkt_size, &len, NULL, 0) == -1)
2374
2375		    errx(1, "sysctlbyname(\"%s\")",
2376			"net.inet.ip.dummynet.red_avg_pkt_size");
2377		if (avg_pkt_size == 0)
2378			errx(EX_DATAERR,
2379			    "net.inet.ip.dummynet.red_avg_pkt_size must"
2380			    " be greater than zero");
2381
2382		len = sizeof(struct clockinfo);
2383		if (sysctlbyname("kern.clockrate", &clock, &len, NULL, 0) == -1)
2384			errx(1, "sysctlbyname(\"%s\")", "kern.clockrate");
2385
2386		/*
2387		 * Ticks needed for sending a medium-sized packet.
2388		 * Unfortunately, when we are configuring a WF2Q+ queue, we
2389		 * do not have bandwidth information, because that is stored
2390		 * in the parent pipe, and also we have multiple queues
2391		 * competing for it. So we set s=0, which is not very
2392		 * correct. But on the other hand, why do we want RED with
2393		 * WF2Q+ ?
2394		 */
2395		if (pipe.bandwidth==0) /* this is a WF2Q+ queue */
2396			s = 0;
2397		else
2398			s = clock.hz * avg_pkt_size * 8 / pipe.bandwidth;
2399
2400		/*
2401		 * max idle time (in ticks) before avg queue size becomes 0.
2402		 * NOTA:  (3/w_q) is approx the value x so that
2403		 * (1-w_q)^x < 10^-3.
2404		 */
2405		w_q = ((double)pipe.fs.w_q) / (1 << SCALE_RED);
2406		idle = s * 3. / w_q;
2407		pipe.fs.lookup_step = (int)idle / lookup_depth;
2408		if (!pipe.fs.lookup_step)
2409			pipe.fs.lookup_step = 1;
2410		weight = 1 - w_q;
2411		for (t = pipe.fs.lookup_step; t > 0; --t)
2412			weight *= weight;
2413		pipe.fs.lookup_weight = (int)(weight * (1 << SCALE_RED));
2414	}
2415	i = setsockopt(s, IPPROTO_IP, IP_DUMMYNET_CONFIGURE, &pipe,
2416			    sizeof pipe);
2417	if (i)
2418		err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
2419}
2420
2421static void
2422get_mac_addr_mask(char *p, u_char *addr, u_char *mask)
2423{
2424	int i, l;
2425
2426	for (i=0; i<6; i++)
2427		addr[i] = mask[i] = 0;
2428	if (!strcmp(p, "any"))
2429		return;
2430
2431	for (i=0; *p && i<6;i++, p++) {
2432		addr[i] = strtol(p, &p, 16);
2433		if (*p != ':') /* we start with the mask */
2434			break;
2435	}
2436	if (*p == '/') { /* mask len */
2437		l = strtol(p+1, &p, 0);
2438		for (i=0; l>0; l -=8, i++)
2439			mask[i] = (l >=8) ? 0xff : (~0) << (8-l);
2440	} else if (*p == '&') { /* mask */
2441		for (i=0, p++; *p && i<6;i++, p++) {
2442			mask[i] = strtol(p, &p, 16);
2443			if (*p != ':')
2444				break;
2445		}
2446	} else if (*p == '\0') {
2447		for (i=0; i<6; i++)
2448			mask[i] = 0xff;
2449	}
2450	for (i=0; i<6; i++)
2451		addr[i] &= mask[i];
2452}
2453
2454/*
2455 * helper function, updates the pointer to cmd with the length
2456 * of the current command, and also cleans up the first word of
2457 * the new command in case it has been clobbered before.
2458 */
2459static ipfw_insn *
2460next_cmd(ipfw_insn *cmd)
2461{
2462	cmd += F_LEN(cmd);
2463	bzero(cmd, sizeof(*cmd));
2464	return cmd;
2465}
2466
2467/*
2468 * A function to fill simple commands of size 1.
2469 * Existing flags are preserved.
2470 */
2471static void
2472fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, u_int16_t arg)
2473{
2474	cmd->opcode = opcode;
2475	cmd->len =  ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
2476	cmd->arg1 = arg;
2477}
2478
2479/*
2480 * Fetch and add the MAC address and type, with masks. This generates one or
2481 * two microinstructions, and returns the pointer to the last one.
2482 */
2483static ipfw_insn *
2484add_mac(ipfw_insn *cmd, int ac, char *av[])
2485{
2486	ipfw_insn_mac *mac;
2487
2488	if (ac < 2)
2489		errx(EX_DATAERR, "MAC dst src");
2490
2491	cmd->opcode = O_MACADDR2;
2492	cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
2493
2494	mac = (ipfw_insn_mac *)cmd;
2495	get_mac_addr_mask(av[0], mac->addr, mac->mask);	/* dst */
2496	get_mac_addr_mask(av[1], &(mac->addr[6]), &(mac->mask[6])); /* src */
2497	return cmd;
2498}
2499
2500static ipfw_insn *
2501add_mactype(ipfw_insn *cmd, int ac, char *av)
2502{
2503	if (ac < 1)
2504		errx(EX_DATAERR, "missing MAC type");
2505	if (strcmp(av, "any") != 0) { /* we have a non-null type */
2506		fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE);
2507		cmd->opcode = O_MAC_TYPE;
2508		return cmd;
2509	} else
2510		return NULL;
2511}
2512
2513static ipfw_insn *
2514add_proto(ipfw_insn *cmd, char *av)
2515{
2516	struct protoent *pe;
2517	u_char proto = 0;
2518
2519	if (!strncmp(av, "all", strlen(av)))
2520		; /* same as "ip" */
2521	else if ((proto = atoi(av)) > 0)
2522		; /* all done! */
2523	else if ((pe = getprotobyname(av)) != NULL)
2524		proto = pe->p_proto;
2525	else
2526		return NULL;
2527	if (proto != IPPROTO_IP)
2528		fill_cmd(cmd, O_PROTO, 0, proto);
2529	return cmd;
2530}
2531
2532static ipfw_insn *
2533add_srcip(ipfw_insn *cmd, char *av)
2534{
2535	fill_ip((ipfw_insn_ip *)cmd, av);
2536	if (cmd->opcode == O_IP_DST_SET)			/* set */
2537		cmd->opcode = O_IP_SRC_SET;
2538	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))		/* me */
2539		cmd->opcode = O_IP_SRC_ME;
2540	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))	/* one IP */
2541		cmd->opcode = O_IP_SRC;
2542	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_ip))	/* addr/mask */
2543		cmd->opcode = O_IP_SRC_MASK;
2544	return cmd;
2545}
2546
2547static ipfw_insn *
2548add_dstip(ipfw_insn *cmd, char *av)
2549{
2550	fill_ip((ipfw_insn_ip *)cmd, av);
2551	if (cmd->opcode == O_IP_DST_SET)			/* set */
2552		;
2553	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))		/* me */
2554		cmd->opcode = O_IP_DST_ME;
2555	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))	/* one IP */
2556		cmd->opcode = O_IP_DST;
2557	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_ip))	/* addr/mask */
2558		cmd->opcode = O_IP_DST_MASK;
2559	return cmd;
2560}
2561
2562static ipfw_insn *
2563add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode)
2564{
2565	if (!strncmp(av, "any", strlen(av))) {
2566		return NULL;
2567	} else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) {
2568		/* XXX todo: check that we have a protocol with ports */
2569		cmd->opcode = opcode;
2570		return cmd;
2571	}
2572	return NULL;
2573}
2574
2575/*
2576 * Parse arguments and assemble the microinstructions which make up a rule.
2577 * Rules are added into the 'rulebuf' and then copied in the correct order
2578 * into the actual rule.
2579 *
2580 * The syntax for a rule starts with the action, followed by an
2581 * optional log action, and the various match patterns.
2582 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
2583 * (generated if the rule includes a keep-state option), then the
2584 * various match patterns, the "log" action, and the actual action.
2585 *
2586 */
2587static void
2588add(int ac, char *av[])
2589{
2590	/*
2591	 * rules are added into the 'rulebuf' and then copied in
2592	 * the correct order into the actual rule.
2593	 * Some things that need to go out of order (prob, action etc.)
2594	 * go into actbuf[].
2595	 */
2596	static u_int32_t rulebuf[255], actbuf[255], cmdbuf[255];
2597
2598	ipfw_insn *src, *dst, *cmd, *action, *prev;
2599	ipfw_insn *first_cmd;	/* first match pattern */
2600
2601	struct ip_fw *rule;
2602
2603	/*
2604	 * various flags used to record that we entered some fields.
2605	 */
2606	ipfw_insn *have_state = NULL;	/* check-state or keep-state */
2607
2608	int i;
2609
2610	int open_par = 0;	/* open parenthesis ( */
2611
2612	/* proto is here because it is used to fetch ports */
2613	u_char proto = IPPROTO_IP;	/* default protocol */
2614
2615	double match_prob = 1; /* match probability, default is always match */
2616
2617	bzero(actbuf, sizeof(actbuf));		/* actions go here */
2618	bzero(cmdbuf, sizeof(cmdbuf));
2619	bzero(rulebuf, sizeof(rulebuf));
2620
2621	rule = (struct ip_fw *)rulebuf;
2622	cmd = (ipfw_insn *)cmdbuf;
2623	action = (ipfw_insn *)actbuf;
2624
2625	av++; ac--;
2626
2627	/* [rule N]	-- Rule number optional */
2628	if (ac && isdigit(**av)) {
2629		rule->rulenum = atoi(*av);
2630		av++;
2631		ac--;
2632	}
2633
2634	/* [set N]	-- set number (0..30), optional */
2635	if (ac > 1 && !strncmp(*av, "set", strlen(*av))) {
2636		int set = strtoul(av[1], NULL, 10);
2637		if (set < 0 || set > 30)
2638			errx(EX_DATAERR, "illegal set %s", av[1]);
2639		rule->set = set;
2640		av += 2; ac -= 2;
2641	}
2642
2643	/* [prob D]	-- match probability, optional */
2644	if (ac > 1 && !strncmp(*av, "prob", strlen(*av))) {
2645		match_prob = strtod(av[1], NULL);
2646
2647		if (match_prob <= 0 || match_prob > 1)
2648			errx(EX_DATAERR, "illegal match prob. %s", av[1]);
2649		av += 2; ac -= 2;
2650	}
2651
2652	/* action	-- mandatory */
2653	NEED1("missing action");
2654	i = match_token(rule_actions, *av);
2655	ac--; av++;
2656	action->len = 1;	/* default */
2657	switch(i) {
2658	case TOK_CHECKSTATE:
2659		have_state = action;
2660		action->opcode = O_CHECK_STATE;
2661		break;
2662
2663	case TOK_ACCEPT:
2664		action->opcode = O_ACCEPT;
2665		break;
2666
2667	case TOK_DENY:
2668		action->opcode = O_DENY;
2669		action->arg1 = 0;
2670		break;
2671
2672	case TOK_REJECT:
2673		action->opcode = O_REJECT;
2674		action->arg1 = ICMP_UNREACH_HOST;
2675		break;
2676
2677	case TOK_RESET:
2678		action->opcode = O_REJECT;
2679		action->arg1 = ICMP_REJECT_RST;
2680		break;
2681
2682	case TOK_UNREACH:
2683		action->opcode = O_REJECT;
2684		NEED1("missing reject code");
2685		fill_reject_code(&action->arg1, *av);
2686		ac--; av++;
2687		break;
2688
2689	case TOK_COUNT:
2690		action->opcode = O_COUNT;
2691		break;
2692
2693	case TOK_QUEUE:
2694	case TOK_PIPE:
2695		action->len = F_INSN_SIZE(ipfw_insn_pipe);
2696	case TOK_SKIPTO:
2697		if (i == TOK_QUEUE)
2698			action->opcode = O_QUEUE;
2699		else if (i == TOK_PIPE)
2700			action->opcode = O_PIPE;
2701		else if (i == TOK_SKIPTO)
2702			action->opcode = O_SKIPTO;
2703		NEED1("missing skipto/pipe/queue number");
2704		action->arg1 = strtoul(*av, NULL, 10);
2705		av++; ac--;
2706		break;
2707
2708	case TOK_DIVERT:
2709	case TOK_TEE:
2710		action->opcode = (i == TOK_DIVERT) ? O_DIVERT : O_TEE;
2711		NEED1("missing divert/tee port");
2712		action->arg1 = strtoul(*av, NULL, 0);
2713		if (action->arg1 == 0) {
2714			struct servent *s;
2715			setservent(1);
2716			s = getservbyname(av[0], "divert");
2717			if (s != NULL)
2718				action->arg1 = ntohs(s->s_port);
2719			else
2720				errx(EX_DATAERR, "illegal divert/tee port");
2721		}
2722		ac--; av++;
2723		break;
2724
2725	case TOK_FORWARD: {
2726		ipfw_insn_sa *p = (ipfw_insn_sa *)action;
2727		char *s, *end;
2728
2729		NEED1("missing forward address[:port]");
2730
2731		action->opcode = O_FORWARD_IP;
2732		action->len = F_INSN_SIZE(ipfw_insn_sa);
2733
2734		p->sa.sin_len = sizeof(struct sockaddr_in);
2735		p->sa.sin_family = AF_INET;
2736		p->sa.sin_port = 0;
2737		/*
2738		 * locate the address-port separator (':' or ',')
2739		 */
2740		s = strchr(*av, ':');
2741		if (s == NULL)
2742			s = strchr(*av, ',');
2743		if (s != NULL) {
2744			*(s++) = '\0';
2745			i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
2746			if (s == end)
2747				errx(EX_DATAERR,
2748				    "illegal forwarding port ``%s''", s);
2749			p->sa.sin_port = (u_short)i;
2750		}
2751		lookup_host(*av, &(p->sa.sin_addr));
2752		}
2753		ac--; av++;
2754		break;
2755
2756	default:
2757		errx(EX_DATAERR, "invalid action %s\n", av[-1]);
2758	}
2759	action = next_cmd(action);
2760
2761	/*
2762	 * [log [logamount N]]	-- log, optional
2763	 *
2764	 * If exists, it goes first in the cmdbuf, but then it is
2765	 * skipped in the copy section to the end of the buffer.
2766	 */
2767	if (ac && !strncmp(*av, "log", strlen(*av))) {
2768		ipfw_insn_log *c = (ipfw_insn_log *)cmd;
2769
2770		cmd->len = F_INSN_SIZE(ipfw_insn_log);
2771		cmd->opcode = O_LOG;
2772		av++; ac--;
2773		if (ac && !strncmp(*av, "logamount", strlen(*av))) {
2774			ac--; av++;
2775			NEED1("logamount requires argument");
2776			c->max_log = atoi(*av);
2777			if (c->max_log < 0)
2778				errx(EX_DATAERR, "logamount must be positive");
2779			ac--; av++;
2780		}
2781		cmd = next_cmd(cmd);
2782	}
2783
2784	if (have_state)	/* must be a check-state, we are done */
2785		goto done;
2786
2787#define OR_START(target)					\
2788	if (ac && (*av[0] == '(' || *av[0] == '{')) {		\
2789		if (open_par)					\
2790			errx(EX_USAGE, "nested \"(\" not allowed\n"); \
2791		prev = NULL;					\
2792		open_par = 1;					\
2793		if ( (av[0])[1] == '\0') {			\
2794			ac--; av++;				\
2795		} else						\
2796			(*av)++;				\
2797	}							\
2798	target:							\
2799
2800
2801#define	CLOSE_PAR						\
2802	if (open_par) {						\
2803		if (ac && (					\
2804		    !strncmp(*av, ")", strlen(*av)) ||		\
2805		    !strncmp(*av, "}", strlen(*av)) )) {	\
2806			prev = NULL;				\
2807			open_par = 0;				\
2808			ac--; av++;				\
2809		} else						\
2810			errx(EX_USAGE, "missing \")\"\n");	\
2811	}
2812
2813#define NOT_BLOCK						\
2814	if (ac && !strncmp(*av, "not", strlen(*av))) {		\
2815		if (cmd->len & F_NOT)				\
2816			errx(EX_USAGE, "double \"not\" not allowed\n"); \
2817		cmd->len |= F_NOT;				\
2818		ac--; av++;					\
2819	}
2820
2821#define OR_BLOCK(target)					\
2822	if (ac && !strncmp(*av, "or", strlen(*av))) {		\
2823		if (prev == NULL || open_par == 0)		\
2824			errx(EX_DATAERR, "invalid OR block");	\
2825		prev->len |= F_OR;				\
2826		ac--; av++;					\
2827		goto target;					\
2828	}							\
2829	CLOSE_PAR;
2830
2831	first_cmd = cmd;
2832
2833#if 0
2834	/*
2835	 * MAC addresses, optional.
2836	 * If we have this, we skip the part "proto from src to dst"
2837	 * and jump straight to the option parsing.
2838	 */
2839	NOT_BLOCK;
2840	NEED1("missing protocol");
2841	if (!strncmp(*av, "MAC", strlen(*av)) ||
2842	    !strncmp(*av, "mac", strlen(*av))) {
2843		ac--; av++;	/* the "MAC" keyword */
2844		add_mac(cmd, ac, av); /* exits in case of errors */
2845		cmd = next_cmd(cmd);
2846		ac -= 2; av += 2;	/* dst-mac and src-mac */
2847		NOT_BLOCK;
2848		NEED1("missing mac type");
2849		if (add_mactype(cmd, ac, av[0]))
2850			cmd = next_cmd(cmd);
2851		ac--; av++;	/* any or mac-type */
2852		goto read_options;
2853	}
2854#endif
2855
2856	/*
2857	 * protocol, mandatory
2858	 */
2859    OR_START(get_proto);
2860	NOT_BLOCK;
2861	NEED1("missing protocol");
2862	if (add_proto(cmd, *av)) {
2863		av++; ac--;
2864		if (F_LEN(cmd) == 0)	/* plain IP */
2865			proto = 0;
2866		else {
2867			proto = cmd->arg1;
2868			prev = cmd;
2869			cmd = next_cmd(cmd);
2870		}
2871	} else if (first_cmd != cmd) {
2872		errx(EX_DATAERR, "invalid protocol ``%s''", *av);
2873	} else
2874		goto read_options;
2875    OR_BLOCK(get_proto);
2876
2877	/*
2878	 * "from", mandatory
2879	 */
2880	if (!ac || strncmp(*av, "from", strlen(*av)))
2881		errx(EX_USAGE, "missing ``from''");
2882	ac--; av++;
2883
2884	/*
2885	 * source IP, mandatory
2886	 */
2887    OR_START(source_ip);
2888	NOT_BLOCK;	/* optional "not" */
2889	NEED1("missing source address");
2890	if (add_srcip(cmd, *av)) {
2891		ac--; av++;
2892		if (F_LEN(cmd) != 0) {	/* ! any */
2893			prev = cmd;
2894			cmd = next_cmd(cmd);
2895		}
2896	}
2897    OR_BLOCK(source_ip);
2898
2899	/*
2900	 * source ports, optional
2901	 */
2902	NOT_BLOCK;	/* optional "not" */
2903	if (ac) {
2904		if (!strncmp(*av, "any", strlen(*av)) ||
2905		    add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
2906			ac--; av++;
2907			if (F_LEN(cmd) != 0)
2908				cmd = next_cmd(cmd);
2909		}
2910	}
2911
2912	/*
2913	 * "to", mandatory
2914	 */
2915	if (!ac || strncmp(*av, "to", strlen(*av)))
2916		errx(EX_USAGE, "missing ``to''");
2917	av++; ac--;
2918
2919	/*
2920	 * destination, mandatory
2921	 */
2922    OR_START(dest_ip);
2923	NOT_BLOCK;	/* optional "not" */
2924	NEED1("missing dst address");
2925	if (add_dstip(cmd, *av)) {
2926		ac--; av++;
2927		if (F_LEN(cmd) != 0) {	/* ! any */
2928			prev = cmd;
2929			cmd = next_cmd(cmd);
2930		}
2931	}
2932    OR_BLOCK(dest_ip);
2933
2934	/*
2935	 * dest. ports, optional
2936	 */
2937	NOT_BLOCK;	/* optional "not" */
2938	if (ac) {
2939		if (!strncmp(*av, "any", strlen(*av)) ||
2940		    add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
2941			ac--; av++;
2942			if (F_LEN(cmd) != 0)
2943				cmd = next_cmd(cmd);
2944		}
2945	}
2946
2947read_options:
2948	if (ac && first_cmd == cmd) {
2949		/*
2950		 * nothing specified so far, store in the rule to ease
2951		 * printout later.
2952		 */
2953		 rule->_pad = 1;
2954	}
2955	prev = NULL;
2956	while (ac) {
2957		char *s;
2958		ipfw_insn_u32 *cmd32;	/* alias for cmd */
2959
2960		s = *av;
2961		cmd32 = (ipfw_insn_u32 *)cmd;
2962
2963		if (*s == '!') {	/* alternate syntax for NOT */
2964			if (cmd->len & F_NOT)
2965				errx(EX_USAGE, "double \"not\" not allowed\n");
2966			cmd->len = F_NOT;
2967			s++;
2968		}
2969		i = match_token(rule_options, s);
2970		ac--; av++;
2971		switch(i) {
2972		case TOK_NOT:
2973			if (cmd->len & F_NOT)
2974				errx(EX_USAGE, "double \"not\" not allowed\n");
2975			cmd->len = F_NOT;
2976			break;
2977
2978		case TOK_OR:
2979			if (open_par == 0 || prev == NULL)
2980				errx(EX_USAGE, "invalid \"or\" block\n");
2981			prev->len |= F_OR;
2982			break;
2983
2984		case TOK_STARTBRACE:
2985			if (open_par)
2986				errx(EX_USAGE, "+nested \"(\" not allowed\n");
2987			open_par = 1;
2988			break;
2989
2990		case TOK_ENDBRACE:
2991			if (!open_par)
2992				errx(EX_USAGE, "+missing \")\"\n");
2993			open_par = 0;
2994			prev = NULL;
2995        		break;
2996
2997		case TOK_IN:
2998			fill_cmd(cmd, O_IN, 0, 0);
2999			break;
3000
3001		case TOK_OUT:
3002			cmd->len ^= F_NOT; /* toggle F_NOT */
3003			fill_cmd(cmd, O_IN, 0, 0);
3004			break;
3005
3006		case TOK_FRAG:
3007			fill_cmd(cmd, O_FRAG, 0, 0);
3008			break;
3009
3010		case TOK_LAYER2:
3011			fill_cmd(cmd, O_LAYER2, 0, 0);
3012			break;
3013
3014		case TOK_XMIT:
3015		case TOK_RECV:
3016		case TOK_VIA:
3017			NEED1("recv, xmit, via require interface name"
3018				" or address");
3019			fill_iface((ipfw_insn_if *)cmd, av[0]);
3020			ac--; av++;
3021			if (F_LEN(cmd) == 0)	/* not a valid address */
3022				break;
3023			if (i == TOK_XMIT)
3024				cmd->opcode = O_XMIT;
3025			else if (i == TOK_RECV)
3026				cmd->opcode = O_RECV;
3027			else if (i == TOK_VIA)
3028				cmd->opcode = O_VIA;
3029			break;
3030
3031		case TOK_ICMPTYPES:
3032			NEED1("icmptypes requires list of types");
3033			fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
3034			av++; ac--;
3035			break;
3036
3037		case TOK_IPTTL:
3038			NEED1("ipttl requires TTL");
3039			if (strpbrk(*av, "-,")) {
3040			    if (!add_ports(cmd, *av, 0, O_IPTTL))
3041				errx(EX_DATAERR, "invalid ipttl %s", *av);
3042			} else
3043			    fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
3044			ac--; av++;
3045			break;
3046
3047		case TOK_IPID:
3048			NEED1("ipid requires id");
3049			if (strpbrk(*av, "-,")) {
3050			    if (!add_ports(cmd, *av, 0, O_IPID))
3051				errx(EX_DATAERR, "invalid ipid %s", *av);
3052			} else
3053			    fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
3054			ac--; av++;
3055			break;
3056
3057		case TOK_IPLEN:
3058			NEED1("iplen requires length");
3059			if (strpbrk(*av, "-,")) {
3060			    if (!add_ports(cmd, *av, 0, O_IPLEN))
3061				errx(EX_DATAERR, "invalid ip len %s", *av);
3062			} else
3063			    fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
3064			ac--; av++;
3065			break;
3066
3067		case TOK_IPVER:
3068			NEED1("ipver requires version");
3069			fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
3070			ac--; av++;
3071			break;
3072
3073		case TOK_IPPRECEDENCE:
3074			NEED1("ipprecedence requires value");
3075			fill_cmd(cmd, O_IPPRECEDENCE, 0,
3076			    (strtoul(*av, NULL, 0) & 7) << 5);
3077			ac--; av++;
3078			break;
3079
3080		case TOK_IPOPTS:
3081			NEED1("missing argument for ipoptions");
3082			fill_flags(cmd, O_IPOPT, f_ipopts, *av);
3083			ac--; av++;
3084			break;
3085
3086		case TOK_IPTOS:
3087			NEED1("missing argument for iptos");
3088			fill_flags(cmd, O_IPTOS, f_iptos, *av);
3089			ac--; av++;
3090			break;
3091
3092		case TOK_UID:
3093			NEED1("uid requires argument");
3094		    {
3095			char *end;
3096			uid_t uid;
3097			struct passwd *pwd;
3098
3099			cmd->opcode = O_UID;
3100			uid = strtoul(*av, &end, 0);
3101			pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
3102			if (pwd == NULL)
3103				errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
3104			cmd32->d[0] = pwd->pw_uid;
3105			cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3106			ac--; av++;
3107		    }
3108			break;
3109
3110		case TOK_GID:
3111			NEED1("gid requires argument");
3112		    {
3113			char *end;
3114			gid_t gid;
3115			struct group *grp;
3116
3117			cmd->opcode = O_GID;
3118			gid = strtoul(*av, &end, 0);
3119			grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
3120			if (grp == NULL)
3121				errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
3122			cmd32->d[0] = grp->gr_gid;
3123			cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3124			ac--; av++;
3125		    }
3126			break;
3127
3128		case TOK_ESTAB:
3129			fill_cmd(cmd, O_ESTAB, 0, 0);
3130			break;
3131
3132		case TOK_SETUP:
3133			fill_cmd(cmd, O_TCPFLAGS, 0,
3134				(TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
3135			break;
3136
3137		case TOK_TCPOPTS:
3138			NEED1("missing argument for tcpoptions");
3139			fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
3140			ac--; av++;
3141			break;
3142
3143		case TOK_TCPSEQ:
3144		case TOK_TCPACK:
3145			NEED1("tcpseq/tcpack requires argument");
3146			cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3147			cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
3148			cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
3149			ac--; av++;
3150			break;
3151
3152		case TOK_TCPWIN:
3153			NEED1("tcpwin requires length");
3154			fill_cmd(cmd, O_TCPWIN, 0,
3155			    htons(strtoul(*av, NULL, 0)));
3156			ac--; av++;
3157			break;
3158
3159		case TOK_TCPFLAGS:
3160			NEED1("missing argument for tcpflags");
3161			cmd->opcode = O_TCPFLAGS;
3162			fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
3163			ac--; av++;
3164			break;
3165
3166		case TOK_KEEPSTATE:
3167			if (open_par)
3168				errx(EX_USAGE, "keep-state cannot be part "
3169				    "of an or block");
3170			if (have_state)
3171				errx(EX_USAGE, "only one of keep-state "
3172					"and limit is allowed");
3173			have_state = cmd;
3174			fill_cmd(cmd, O_KEEP_STATE, 0, 0);
3175			break;
3176
3177		case TOK_LIMIT:
3178			if (open_par)
3179				errx(EX_USAGE, "limit cannot be part "
3180				    "of an or block");
3181			if (have_state)
3182				errx(EX_USAGE, "only one of keep-state "
3183					"and limit is allowed");
3184			NEED1("limit needs mask and # of connections");
3185			have_state = cmd;
3186		    {
3187			ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
3188
3189			cmd->len = F_INSN_SIZE(ipfw_insn_limit);
3190			cmd->opcode = O_LIMIT;
3191			c->limit_mask = 0;
3192			c->conn_limit = 0;
3193			for (; ac >1 ;) {
3194				int val;
3195
3196				val = match_token(limit_masks, *av);
3197				if (val <= 0)
3198					break;
3199				c->limit_mask |= val;
3200				ac--; av++;
3201			}
3202			c->conn_limit = atoi(*av);
3203			if (c->conn_limit == 0)
3204				errx(EX_USAGE, "limit: limit must be >0");
3205			if (c->limit_mask == 0)
3206				errx(EX_USAGE, "missing limit mask");
3207			ac--; av++;
3208		    }
3209			break;
3210
3211		case TOK_PROTO:
3212			NEED1("missing protocol");
3213			if (add_proto(cmd, *av)) {
3214				proto = cmd->arg1;
3215				ac--; av++;
3216			} else
3217				errx(EX_DATAERR, "invalid protocol ``%s''",
3218				    *av);
3219			break;
3220
3221		case TOK_SRCIP:
3222			NEED1("missing source IP");
3223			if (add_srcip(cmd, *av)) {
3224				ac--; av++;
3225			}
3226			break;
3227
3228		case TOK_DSTIP:
3229			NEED1("missing destination IP");
3230			if (add_dstip(cmd, *av)) {
3231				ac--; av++;
3232			}
3233			break;
3234
3235		case TOK_SRCPORT:
3236			NEED1("missing source port");
3237			if (!strncmp(*av, "any", strlen(*av)) ||
3238			    add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
3239				ac--; av++;
3240			} else
3241				errx(EX_DATAERR, "invalid source port %s", *av);
3242			break;
3243
3244		case TOK_DSTPORT:
3245			NEED1("missing destination port");
3246			if (!strncmp(*av, "any", strlen(*av)) ||
3247			    add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
3248				ac--; av++;
3249			} else
3250				errx(EX_DATAERR, "invalid destination port %s",
3251				    *av);
3252			break;
3253
3254		case TOK_MAC:
3255			if (ac < 2)
3256				errx(EX_USAGE, "MAC dst-mac src-mac");
3257			if (add_mac(cmd, ac, av)) {
3258				ac -= 2; av += 2;
3259			}
3260			break;
3261
3262		case TOK_MACTYPE:
3263			NEED1("missing mac type");
3264			if (!add_mactype(cmd, ac, *av))
3265				errx(EX_DATAERR, "invalid mac type %s", *av);
3266			ac--; av++;
3267			break;
3268
3269		case TOK_VERREVPATH:
3270			fill_cmd(cmd, O_VERREVPATH, 0, 0);
3271			break;
3272
3273		default:
3274			errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
3275		}
3276		if (F_LEN(cmd) > 0) {	/* prepare to advance */
3277			prev = cmd;
3278			cmd = next_cmd(cmd);
3279		}
3280	}
3281
3282done:
3283	/*
3284	 * Now copy stuff into the rule.
3285	 * If we have a keep-state option, the first instruction
3286	 * must be a PROBE_STATE (which is generated here).
3287	 * If we have a LOG option, it was stored as the first command,
3288	 * and now must be moved to the top of the action part.
3289	 */
3290	dst = (ipfw_insn *)rule->cmd;
3291
3292	/*
3293	 * First thing to write into the command stream is the match probability.
3294	 */
3295	if (match_prob != 1) { /* 1 means always match */
3296		dst->opcode = O_PROB;
3297		dst->len = 2;
3298		*((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
3299		dst += dst->len;
3300	}
3301
3302	/*
3303	 * generate O_PROBE_STATE if necessary
3304	 */
3305	if (have_state && have_state->opcode != O_CHECK_STATE) {
3306		fill_cmd(dst, O_PROBE_STATE, 0, 0);
3307		dst = next_cmd(dst);
3308	}
3309	/*
3310	 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT
3311	 */
3312	for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
3313		i = F_LEN(src);
3314
3315		switch (src->opcode) {
3316		case O_LOG:
3317		case O_KEEP_STATE:
3318		case O_LIMIT:
3319			break;
3320		default:
3321			bcopy(src, dst, i * sizeof(u_int32_t));
3322			dst += i;
3323		}
3324	}
3325
3326	/*
3327	 * put back the have_state command as last opcode
3328	 */
3329	if (have_state && have_state->opcode != O_CHECK_STATE) {
3330		i = F_LEN(have_state);
3331		bcopy(have_state, dst, i * sizeof(u_int32_t));
3332		dst += i;
3333	}
3334	/*
3335	 * start action section
3336	 */
3337	rule->act_ofs = dst - rule->cmd;
3338
3339	/*
3340	 * put back O_LOG if necessary
3341	 */
3342	src = (ipfw_insn *)cmdbuf;
3343	if ( src->opcode == O_LOG ) {
3344		i = F_LEN(src);
3345		bcopy(src, dst, i * sizeof(u_int32_t));
3346		dst += i;
3347	}
3348	/*
3349	 * copy all other actions
3350	 */
3351	for (src = (ipfw_insn *)actbuf; src != action; src += i) {
3352		i = F_LEN(src);
3353		bcopy(src, dst, i * sizeof(u_int32_t));
3354		dst += i;
3355	}
3356
3357	rule->cmd_len = (u_int32_t *)dst - (u_int32_t *)(rule->cmd);
3358	i = (void *)dst - (void *)rule;
3359	if (getsockopt(s, IPPROTO_IP, IP_FW_ADD, rule, &i) == -1)
3360		err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
3361	if (!do_quiet)
3362		show_ipfw(rule, 10, 10);
3363}
3364
3365static void
3366zero(int ac, char *av[])
3367{
3368	int rulenum;
3369	int failed = EX_OK;
3370
3371	av++; ac--;
3372
3373	if (!ac) {
3374		/* clear all entries */
3375		if (setsockopt(s, IPPROTO_IP, IP_FW_ZERO, NULL, 0) < 0)
3376			err(EX_UNAVAILABLE, "setsockopt(%s)", "IP_FW_ZERO");
3377		if (!do_quiet)
3378			printf("Accounting cleared.\n");
3379
3380		return;
3381	}
3382
3383	while (ac) {
3384		/* Rule number */
3385		if (isdigit(**av)) {
3386			rulenum = atoi(*av);
3387			av++;
3388			ac--;
3389			if (setsockopt(s, IPPROTO_IP,
3390			    IP_FW_ZERO, &rulenum, sizeof rulenum)) {
3391				warn("rule %u: setsockopt(IP_FW_ZERO)",
3392				    rulenum);
3393				failed = EX_UNAVAILABLE;
3394			} else if (!do_quiet)
3395				printf("Entry %d cleared\n", rulenum);
3396		} else {
3397			errx(EX_USAGE, "invalid rule number ``%s''", *av);
3398		}
3399	}
3400	if (failed != EX_OK)
3401		exit(failed);
3402}
3403
3404static void
3405resetlog(int ac, char *av[])
3406{
3407	int rulenum;
3408	int failed = EX_OK;
3409
3410	av++; ac--;
3411
3412	if (!ac) {
3413		/* clear all entries */
3414		if (setsockopt(s, IPPROTO_IP, IP_FW_RESETLOG, NULL, 0) < 0)
3415			err(EX_UNAVAILABLE, "setsockopt(IP_FW_RESETLOG)");
3416		if (!do_quiet)
3417			printf("Logging counts reset.\n");
3418
3419		return;
3420	}
3421
3422	while (ac) {
3423		/* Rule number */
3424		if (isdigit(**av)) {
3425			rulenum = atoi(*av);
3426			av++;
3427			ac--;
3428			if (setsockopt(s, IPPROTO_IP,
3429			    IP_FW_RESETLOG, &rulenum, sizeof rulenum)) {
3430				warn("rule %u: setsockopt(IP_FW_RESETLOG)",
3431				    rulenum);
3432				failed = EX_UNAVAILABLE;
3433			} else if (!do_quiet)
3434				printf("Entry %d logging count reset\n",
3435				    rulenum);
3436		} else {
3437			errx(EX_DATAERR, "invalid rule number ``%s''", *av);
3438		}
3439	}
3440	if (failed != EX_OK)
3441		exit(failed);
3442}
3443
3444static void
3445flush()
3446{
3447	int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
3448
3449	if (!do_force && !do_quiet) { /* need to ask user */
3450		int c;
3451
3452		printf("Are you sure? [yn] ");
3453		fflush(stdout);
3454		do {
3455			c = toupper(getc(stdin));
3456			while (c != '\n' && getc(stdin) != '\n')
3457				if (feof(stdin))
3458					return; /* and do not flush */
3459		} while (c != 'Y' && c != 'N');
3460		printf("\n");
3461		if (c == 'N')	/* user said no */
3462			return;
3463	}
3464	if (setsockopt(s, IPPROTO_IP, cmd, NULL, 0) < 0)
3465		err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
3466		    do_pipe ? "DUMMYNET" : "FW");
3467	if (!do_quiet)
3468		printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules");
3469}
3470
3471static int
3472ipfw_main(int ac, char **av)
3473{
3474	int ch;
3475
3476	if (ac == 1)
3477		show_usage();
3478
3479	/* Set the force flag for non-interactive processes */
3480	do_force = !isatty(STDIN_FILENO);
3481
3482	optind = optreset = 1;
3483	while ((ch = getopt(ac, av, "hs:acdefNqStv")) != -1)
3484		switch (ch) {
3485		case 'h': /* help */
3486			help();
3487			break;	/* NOTREACHED */
3488
3489		case 's': /* sort */
3490			do_sort = atoi(optarg);
3491			break;
3492		case 'a':
3493			do_acct = 1;
3494			break;
3495		case 'c':
3496			do_compact = 1;
3497			break;
3498		case 'd':
3499			do_dynamic = 1;
3500			break;
3501		case 'e':
3502			do_expired = 1;
3503			break;
3504		case 'f':
3505			do_force = 1;
3506			break;
3507		case 'N':
3508			do_resolv = 1;
3509			break;
3510		case 'q':
3511			do_quiet = 1;
3512			break;
3513		case 'S':
3514			show_sets = 1;
3515			break;
3516		case 't':
3517			do_time = 1;
3518			break;
3519		case 'v': /* verbose */
3520			verbose++;
3521			break;
3522		default:
3523			show_usage();
3524		}
3525
3526	ac -= optind;
3527	av += optind;
3528	NEED1("bad arguments, for usage summary ``ipfw''");
3529
3530	/*
3531	 * optional: pipe or queue
3532	 */
3533	if (!strncmp(*av, "pipe", strlen(*av))) {
3534		do_pipe = 1;
3535		ac--;
3536		av++;
3537	} else if (!strncmp(*av, "queue", strlen(*av))) {
3538		do_pipe = 2;
3539		ac--;
3540		av++;
3541	}
3542	NEED1("missing command");
3543
3544	/*
3545	 * for pipes and queues we normally say 'pipe NN config'
3546	 * but the code is easier to parse as 'pipe config NN'
3547	 * so we swap the two arguments.
3548	 */
3549	if (do_pipe > 0 && ac > 1 && *av[0] >= '0' && *av[0] <= '9') {
3550		char *p = av[0];
3551		av[0] = av[1];
3552		av[1] = p;
3553	}
3554	if (!strncmp(*av, "add", strlen(*av)))
3555		add(ac, av);
3556	else if (do_pipe && !strncmp(*av, "config", strlen(*av)))
3557		config_pipe(ac, av);
3558	else if (!strncmp(*av, "delete", strlen(*av)))
3559		delete(ac, av);
3560	else if (!strncmp(*av, "flush", strlen(*av)))
3561		flush();
3562	else if (!strncmp(*av, "zero", strlen(*av)))
3563		zero(ac, av);
3564	else if (!strncmp(*av, "resetlog", strlen(*av)))
3565		resetlog(ac, av);
3566	else if (!strncmp(*av, "print", strlen(*av)) ||
3567	         !strncmp(*av, "list", strlen(*av)))
3568		list(ac, av);
3569	else if (!strncmp(*av, "set", strlen(*av)))
3570		sets_handler(ac, av);
3571	else if (!strncmp(*av, "enable", strlen(*av)))
3572		sysctl_handler(ac, av, 1);
3573	else if (!strncmp(*av, "disable", strlen(*av)))
3574		sysctl_handler(ac, av, 0);
3575	else if (!strncmp(*av, "show", strlen(*av))) {
3576		do_acct++;
3577		list(ac, av);
3578	} else
3579		errx(EX_USAGE, "bad command `%s'", *av);
3580	return 0;
3581}
3582
3583
3584static void
3585ipfw_readfile(int ac, char *av[])
3586{
3587#define MAX_ARGS	32
3588#define WHITESP		" \t\f\v\n\r"
3589	char	buf[BUFSIZ];
3590	char	*a, *p, *args[MAX_ARGS], *cmd = NULL;
3591	char	linename[10];
3592	int	i=0, lineno=0, qflag=0, pflag=0, status;
3593	FILE	*f = NULL;
3594	pid_t	preproc = 0;
3595	int	c;
3596
3597	while ((c = getopt(ac, av, "p:q")) != -1) {
3598		switch(c) {
3599		case 'p':
3600			pflag = 1;
3601			cmd = optarg;
3602			args[0] = cmd;
3603			i = 1;
3604			break;
3605
3606		case 'q':
3607			qflag = 1;
3608			break;
3609
3610		default:
3611			errx(EX_USAGE, "bad arguments, for usage"
3612			     " summary ``ipfw''");
3613		}
3614
3615		if (pflag)
3616			break;
3617	}
3618
3619	if (pflag) {
3620		/* Pass all but the last argument to the preprocessor. */
3621		while (optind < ac - 1) {
3622			if (i >= MAX_ARGS)
3623				errx(EX_USAGE, "too many preprocessor options");
3624			args[i++] = av[optind++];
3625		}
3626	}
3627
3628	av += optind;
3629	ac -= optind;
3630	if (ac != 1)
3631		errx(EX_USAGE, "extraneous filename arguments");
3632
3633	if ((f = fopen(av[0], "r")) == NULL)
3634		err(EX_UNAVAILABLE, "fopen: %s", av[0]);
3635
3636	if (pflag) {
3637		/* pipe through preprocessor (cpp or m4) */
3638		int pipedes[2];
3639
3640		args[i] = 0;
3641
3642		if (pipe(pipedes) == -1)
3643			err(EX_OSERR, "cannot create pipe");
3644
3645		switch((preproc = fork())) {
3646		case -1:
3647			err(EX_OSERR, "cannot fork");
3648
3649		case 0:
3650			/* child */
3651			if (dup2(fileno(f), 0) == -1
3652			    || dup2(pipedes[1], 1) == -1)
3653				err(EX_OSERR, "dup2()");
3654			fclose(f);
3655			close(pipedes[1]);
3656			close(pipedes[0]);
3657			execvp(cmd, args);
3658			err(EX_OSERR, "execvp(%s) failed", cmd);
3659
3660		default:
3661			/* parent */
3662			fclose(f);
3663			close(pipedes[1]);
3664			if ((f = fdopen(pipedes[0], "r")) == NULL) {
3665				int savederrno = errno;
3666
3667				(void)kill(preproc, SIGTERM);
3668				errno = savederrno;
3669				err(EX_OSERR, "fdopen()");
3670			}
3671		}
3672	}
3673
3674	while (fgets(buf, BUFSIZ, f)) {
3675		lineno++;
3676		sprintf(linename, "Line %d", lineno);
3677		args[0] = linename;
3678
3679		if (*buf == '#')
3680			continue;
3681		if ((p = strchr(buf, '#')) != NULL)
3682			*p = '\0';
3683		i = 1;
3684		if (qflag)
3685			args[i++] = "-q";
3686		for (a = strtok(buf, WHITESP);
3687		    a && i < MAX_ARGS; a = strtok(NULL, WHITESP), i++)
3688			args[i] = a;
3689		if (i == (qflag? 2: 1))
3690			continue;
3691		if (i == MAX_ARGS)
3692			errx(EX_USAGE, "%s: too many arguments",
3693			    linename);
3694		args[i] = NULL;
3695
3696		ipfw_main(i, args);
3697	}
3698	fclose(f);
3699	if (pflag) {
3700		if (waitpid(preproc, &status, 0) == -1)
3701			errx(EX_OSERR, "waitpid()");
3702		if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
3703			errx(EX_UNAVAILABLE,
3704			    "preprocessor exited with status %d",
3705			    WEXITSTATUS(status));
3706		else if (WIFSIGNALED(status))
3707			errx(EX_UNAVAILABLE,
3708			    "preprocessor exited with signal %d",
3709			    WTERMSIG(status));
3710	}
3711}
3712
3713int
3714main(int ac, char *av[])
3715{
3716	s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
3717	if (s < 0)
3718		err(EX_UNAVAILABLE, "socket");
3719
3720	/*
3721	 * If the last argument is an absolute pathname, interpret it
3722	 * as a file to be preprocessed.
3723	 */
3724
3725	if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0)
3726		ipfw_readfile(ac, av);
3727	else
3728		ipfw_main(ac, av);
3729	return EX_OK;
3730}
3731