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