ipfw2.c revision 101295
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 101295 2002-08-04 05:16:19Z 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		verbose;
69
70#define	IP_MASK_ALL	0xffffffff
71
72/*
73 * structure to hold flag names and associated values to be
74 * set in the appropriate masks.
75 * A NULL string terminates the array.
76 * Often, an element with 0 value contains an error string.
77 *
78 */
79struct _s_x {
80	char *s;
81	int x;
82};
83
84static struct _s_x f_tcpflags[] = {
85	{ "syn", TH_SYN },
86	{ "fin", TH_FIN },
87	{ "ack", TH_ACK },
88	{ "psh", TH_PUSH },
89	{ "rst", TH_RST },
90	{ "urg", TH_URG },
91	{ "tcp flag", 0 },
92	{ NULL,	0 }
93};
94
95static struct _s_x f_tcpopts[] = {
96	{ "mss",	IP_FW_TCPOPT_MSS },
97	{ "maxseg",	IP_FW_TCPOPT_MSS },
98	{ "window",	IP_FW_TCPOPT_WINDOW },
99	{ "sack",	IP_FW_TCPOPT_SACK },
100	{ "ts",		IP_FW_TCPOPT_TS },
101	{ "timestamp",	IP_FW_TCPOPT_TS },
102	{ "cc",		IP_FW_TCPOPT_CC },
103	{ "tcp option",	0 },
104	{ NULL,	0 }
105};
106
107/*
108 * IP options span the range 0 to 255 so we need to remap them
109 * (though in fact only the low 5 bits are significant).
110 */
111static struct _s_x f_ipopts[] = {
112	{ "ssrr",	IP_FW_IPOPT_SSRR},
113	{ "lsrr",	IP_FW_IPOPT_LSRR},
114	{ "rr",		IP_FW_IPOPT_RR},
115	{ "ts",		IP_FW_IPOPT_TS},
116	{ "ip option",	0 },
117	{ NULL,	0 }
118};
119
120static struct _s_x f_iptos[] = {
121	{ "lowdelay",	IPTOS_LOWDELAY},
122	{ "throughput",	IPTOS_THROUGHPUT},
123	{ "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		for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
1573			d[i] = 0;	/* clear masks */
1574
1575		av = p+1;
1576		low = cmd->addr.s_addr & 0xff;
1577		high = low + cmd->o.arg1 - 1;
1578		while (isdigit(*av)) {
1579			char *s;
1580			u_int16_t a = strtol(av, &s, 0);
1581
1582			if (s == av) /* no parameter */
1583				break;
1584			if (a < low || a > high) {
1585			    fprintf(stderr, "addr %d out of range [%d-%d]\n",
1586				a, low, high);
1587			    exit(0);
1588			}
1589			a -= low;
1590			d[ a/32] |= 1<<(a & 31);
1591			if (*s != ',')
1592				break;
1593			av = s+1;
1594		}
1595		return;
1596	}
1597
1598	if (cmd->mask.s_addr == 0) { /* any */
1599		if (cmd->o.len & F_NOT)
1600			errx(EX_DATAERR, "not any never matches");
1601		else	/* useless, nuke it */
1602			return;
1603	} else if (cmd->mask.s_addr ==  IP_MASK_ALL)	/* one IP */
1604		cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1605	else						/* addr/mask */
1606		cmd->o.len |= F_INSN_SIZE(ipfw_insn_ip);
1607}
1608
1609
1610/*
1611 * helper function to process a set of flags and set bits in the
1612 * appropriate masks.
1613 */
1614static void
1615fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
1616	struct _s_x *flags, char *p)
1617{
1618	u_int8_t set=0, clear=0;
1619
1620	while (p && *p) {
1621		char *q;	/* points to the separator */
1622		int val;
1623		u_int8_t *which;	/* mask we are working on */
1624
1625		if (*p == '!') {
1626			p++;
1627			which = &clear;
1628		} else
1629			which = &set;
1630		q = strchr(p, ',');
1631		if (q)
1632			*q++ = '\0';
1633		val = match_token(flags, p);
1634		if (val <= 0)
1635			errx(EX_DATAERR, "invalid flag %s", p);
1636		*which |= (u_int8_t)val;
1637		p = q;
1638	}
1639        cmd->opcode = opcode;
1640        cmd->len =  (cmd->len & (F_NOT | F_OR)) | 1;
1641        cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
1642}
1643
1644
1645static void
1646delete(int ac, char *av[])
1647{
1648	int rulenum;
1649	struct dn_pipe pipe;
1650	int i;
1651	int exitval = EX_OK;
1652
1653	memset(&pipe, 0, sizeof pipe);
1654
1655	av++; ac--;
1656
1657	/* Rule number */
1658	while (ac && isdigit(**av)) {
1659		i = atoi(*av); av++; ac--;
1660		if (do_pipe) {
1661			if (do_pipe == 1)
1662				pipe.pipe_nr = i;
1663			else
1664				pipe.fs.fs_nr = i;
1665			i = setsockopt(s, IPPROTO_IP, IP_DUMMYNET_DEL,
1666			    &pipe, sizeof pipe);
1667			if (i) {
1668				exitval = 1;
1669				warn("rule %u: setsockopt(IP_DUMMYNET_DEL)",
1670				    do_pipe == 1 ? pipe.pipe_nr :
1671				    pipe.fs.fs_nr);
1672			}
1673		} else {
1674			rulenum = i;
1675			i = setsockopt(s, IPPROTO_IP, IP_FW_DEL, &rulenum,
1676			    sizeof rulenum);
1677			if (i) {
1678				exitval = EX_UNAVAILABLE;
1679				warn("rule %u: setsockopt(IP_FW_DEL)",
1680				    rulenum);
1681			}
1682		}
1683	}
1684	if (exitval != EX_OK)
1685		exit(exitval);
1686}
1687
1688
1689/*
1690 * fill the interface structure. We do not check the name as we can
1691 * create interfaces dynamically, so checking them at insert time
1692 * makes relatively little sense.
1693 * A '*' following the name means any unit.
1694 */
1695static void
1696fill_iface(ipfw_insn_if *cmd, char *arg)
1697{
1698	cmd->name[0] = '\0';
1699	cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
1700
1701	/* Parse the interface or address */
1702	if (!strcmp(arg, "any"))
1703		cmd->o.len = 0;		/* effectively ignore this command */
1704	else if (!isdigit(*arg)) {
1705		char *q;
1706
1707		strncpy(cmd->name, arg, sizeof(cmd->name));
1708		cmd->name[sizeof(cmd->name) - 1] = '\0';
1709		/* find first digit or wildcard */
1710		for (q = cmd->name; *q && !isdigit(*q) && *q != '*'; q++)
1711			continue;
1712		cmd->p.unit = (*q == '*') ? -1 : atoi(q);
1713		*q = '\0';
1714	} else if (!inet_aton(arg, &cmd->p.ip))
1715		errx(EX_DATAERR, "bad ip address ``%s''", arg);
1716}
1717
1718/*
1719 * the following macro returns an error message if we run out of
1720 * arguments.
1721 */
1722#define	NEED1(msg)	{if (!ac) errx(EX_USAGE, msg);}
1723
1724static void
1725config_pipe(int ac, char **av)
1726{
1727	struct dn_pipe pipe;
1728	int i;
1729	char *end;
1730	u_int32_t a;
1731	void *par = NULL;
1732
1733	memset(&pipe, 0, sizeof pipe);
1734
1735	av++; ac--;
1736	/* Pipe number */
1737	if (ac && isdigit(**av)) {
1738		i = atoi(*av); av++; ac--;
1739		if (do_pipe == 1)
1740			pipe.pipe_nr = i;
1741		else
1742			pipe.fs.fs_nr = i;
1743	}
1744	while (ac > 0) {
1745		double d;
1746		int tok = match_token(dummynet_params, *av);
1747		ac--; av++;
1748
1749		switch(tok) {
1750		case TOK_PLR:
1751			NEED1("plr needs argument 0..1\n");
1752			d = strtod(av[0], NULL);
1753			if (d > 1)
1754				d = 1;
1755			else if (d < 0)
1756				d = 0;
1757			pipe.fs.plr = (int)(d*0x7fffffff);
1758			ac--; av++;
1759			break;
1760
1761		case TOK_QUEUE:
1762			NEED1("queue needs queue size\n");
1763			end = NULL;
1764			pipe.fs.qsize = strtoul(av[0], &end, 0);
1765			if (*end == 'K' || *end == 'k') {
1766				pipe.fs.flags_fs |= DN_QSIZE_IS_BYTES;
1767				pipe.fs.qsize *= 1024;
1768			} else if (*end == 'B' || !strncmp(end, "by", 2)) {
1769				pipe.fs.flags_fs |= DN_QSIZE_IS_BYTES;
1770			}
1771			ac--; av++;
1772			break;
1773
1774		case TOK_BUCKETS:
1775			NEED1("buckets needs argument\n");
1776			pipe.fs.rq_size = strtoul(av[0], NULL, 0);
1777			ac--; av++;
1778			break;
1779
1780		case TOK_MASK:
1781			NEED1("mask needs mask specifier\n");
1782			/*
1783			 * per-flow queue, mask is dst_ip, dst_port,
1784			 * src_ip, src_port, proto measured in bits
1785			 */
1786			par = NULL;
1787
1788			pipe.fs.flow_mask.dst_ip = 0;
1789			pipe.fs.flow_mask.src_ip = 0;
1790			pipe.fs.flow_mask.dst_port = 0;
1791			pipe.fs.flow_mask.src_port = 0;
1792			pipe.fs.flow_mask.proto = 0;
1793			end = NULL;
1794
1795			while (ac >= 1) {
1796			    u_int32_t *p32 = NULL;
1797			    u_int16_t *p16 = NULL;
1798
1799			    tok = match_token(dummynet_params, *av);
1800			    ac--; av++;
1801			    switch(tok) {
1802			    case TOK_ALL:
1803				    /*
1804				     * special case, all bits significant
1805				     */
1806				    pipe.fs.flow_mask.dst_ip = ~0;
1807				    pipe.fs.flow_mask.src_ip = ~0;
1808				    pipe.fs.flow_mask.dst_port = ~0;
1809				    pipe.fs.flow_mask.src_port = ~0;
1810				    pipe.fs.flow_mask.proto = ~0;
1811				    pipe.fs.flags_fs |= DN_HAVE_FLOW_MASK;
1812				    goto end_mask;
1813
1814			    case TOK_DSTIP:
1815				    p32 = &pipe.fs.flow_mask.dst_ip;
1816				    break;
1817
1818			    case TOK_SRCIP:
1819				    p32 = &pipe.fs.flow_mask.src_ip;
1820				    break;
1821
1822			    case TOK_DSTPORT:
1823				    p16 = &pipe.fs.flow_mask.dst_port;
1824				    break;
1825
1826			    case TOK_SRCPORT:
1827				    p16 = &pipe.fs.flow_mask.src_port;
1828				    break;
1829
1830			    case TOK_PROTO:
1831				    break;
1832
1833			    default:
1834				    ac++; av--; /* backtrack */
1835				    goto end_mask;
1836			    }
1837			    if (ac < 1)
1838				    errx(EX_USAGE, "mask: value missing");
1839			    if (*av[0] == '/') {
1840				    a = strtoul(av[0]+1, &end, 0);
1841				    a = (a == 32) ? ~0 : (1 << a) - 1;
1842			    } else
1843				    a = strtoul(av[0], &end, 0);
1844			    if (p32 != NULL)
1845				    *p32 = a;
1846			    else if (p16 != NULL) {
1847				    if (a > 65535)
1848					    errx(EX_DATAERR,
1849						"mask: must be 16 bit");
1850				    *p16 = (u_int16_t)a;
1851			    } else {
1852				    if (a > 255)
1853					    errx(EX_DATAERR,
1854						"mask: must be 8 bit");
1855				    pipe.fs.flow_mask.proto = (u_int8_t)a;
1856			    }
1857			    if (a != 0)
1858				    pipe.fs.flags_fs |= DN_HAVE_FLOW_MASK;
1859			    ac--; av++;
1860			} /* end while, config masks */
1861end_mask:
1862			break;
1863
1864		case TOK_RED:
1865		case TOK_GRED:
1866			NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
1867			pipe.fs.flags_fs |= DN_IS_RED;
1868			if (tok == TOK_GRED)
1869				pipe.fs.flags_fs |= DN_IS_GENTLE_RED;
1870			/*
1871			 * the format for parameters is w_q/min_th/max_th/max_p
1872			 */
1873			if ((end = strsep(&av[0], "/"))) {
1874			    double w_q = strtod(end, NULL);
1875			    if (w_q > 1 || w_q <= 0)
1876				errx(EX_DATAERR, "0 < w_q <= 1");
1877			    pipe.fs.w_q = (int) (w_q * (1 << SCALE_RED));
1878			}
1879			if ((end = strsep(&av[0], "/"))) {
1880			    pipe.fs.min_th = strtoul(end, &end, 0);
1881			    if (*end == 'K' || *end == 'k')
1882				pipe.fs.min_th *= 1024;
1883			}
1884			if ((end = strsep(&av[0], "/"))) {
1885			    pipe.fs.max_th = strtoul(end, &end, 0);
1886			    if (*end == 'K' || *end == 'k')
1887				pipe.fs.max_th *= 1024;
1888			}
1889			if ((end = strsep(&av[0], "/"))) {
1890			    double max_p = strtod(end, NULL);
1891			    if (max_p > 1 || max_p <= 0)
1892				errx(EX_DATAERR, "0 < max_p <= 1");
1893			    pipe.fs.max_p = (int)(max_p * (1 << SCALE_RED));
1894			}
1895			ac--; av++;
1896			break;
1897
1898		case TOK_DROPTAIL:
1899			pipe.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
1900			break;
1901
1902		case TOK_BW:
1903			NEED1("bw needs bandwidth or interface\n");
1904			if (do_pipe != 1)
1905			    errx(EX_DATAERR, "bandwidth only valid for pipes");
1906			/*
1907			 * set clocking interface or bandwidth value
1908			 */
1909			if (av[0][0] >= 'a' && av[0][0] <= 'z') {
1910			    int l = sizeof(pipe.if_name)-1;
1911			    /* interface name */
1912			    strncpy(pipe.if_name, av[0], l);
1913			    pipe.if_name[l] = '\0';
1914			    pipe.bandwidth = 0;
1915			} else {
1916			    pipe.if_name[0] = '\0';
1917			    pipe.bandwidth = strtoul(av[0], &end, 0);
1918			    if (*end == 'K' || *end == 'k') {
1919				end++;
1920				pipe.bandwidth *= 1000;
1921			    } else if (*end == 'M') {
1922				end++;
1923				pipe.bandwidth *= 1000000;
1924			    }
1925			    if (*end == 'B' || !strncmp(end, "by", 2))
1926				pipe.bandwidth *= 8;
1927			    if (pipe.bandwidth < 0)
1928				errx(EX_DATAERR, "bandwidth too large");
1929			}
1930			ac--; av++;
1931			break;
1932
1933		case TOK_DELAY:
1934			if (do_pipe != 1)
1935				errx(EX_DATAERR, "delay only valid for pipes");
1936			NEED1("delay needs argument 0..10000ms\n");
1937			pipe.delay = strtoul(av[0], NULL, 0);
1938			ac--; av++;
1939			break;
1940
1941		case TOK_WEIGHT:
1942			if (do_pipe == 1)
1943				errx(EX_DATAERR,"weight only valid for queues");
1944			NEED1("weight needs argument 0..100\n");
1945			pipe.fs.weight = strtoul(av[0], &end, 0);
1946			ac--; av++;
1947			break;
1948
1949		case TOK_PIPE:
1950			if (do_pipe == 1)
1951				errx(EX_DATAERR,"pipe only valid for queues");
1952			NEED1("pipe needs pipe_number\n");
1953			pipe.fs.parent_nr = strtoul(av[0], &end, 0);
1954			ac--; av++;
1955			break;
1956
1957		default:
1958			errx(EX_DATAERR, "unrecognised option ``%s''", *av);
1959		}
1960	}
1961	if (do_pipe == 1) {
1962		if (pipe.pipe_nr == 0)
1963			errx(EX_DATAERR, "pipe_nr must be > 0");
1964		if (pipe.delay > 10000)
1965			errx(EX_DATAERR, "delay must be < 10000");
1966	} else { /* do_pipe == 2, queue */
1967		if (pipe.fs.parent_nr == 0)
1968			errx(EX_DATAERR, "pipe must be > 0");
1969		if (pipe.fs.weight >100)
1970			errx(EX_DATAERR, "weight must be <= 100");
1971	}
1972	if (pipe.fs.flags_fs & DN_QSIZE_IS_BYTES) {
1973		if (pipe.fs.qsize > 1024*1024)
1974			errx(EX_DATAERR, "queue size must be < 1MB");
1975	} else {
1976		if (pipe.fs.qsize > 100)
1977			errx(EX_DATAERR, "2 <= queue size <= 100");
1978	}
1979	if (pipe.fs.flags_fs & DN_IS_RED) {
1980		size_t len;
1981		int lookup_depth, avg_pkt_size;
1982		double s, idle, weight, w_q;
1983		struct clockinfo clock;
1984		int t;
1985
1986		if (pipe.fs.min_th >= pipe.fs.max_th)
1987		    errx(EX_DATAERR, "min_th %d must be < than max_th %d",
1988			pipe.fs.min_th, pipe.fs.max_th);
1989		if (pipe.fs.max_th == 0)
1990		    errx(EX_DATAERR, "max_th must be > 0");
1991
1992		len = sizeof(int);
1993		if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
1994			&lookup_depth, &len, NULL, 0) == -1)
1995
1996		    errx(1, "sysctlbyname(\"%s\")",
1997			"net.inet.ip.dummynet.red_lookup_depth");
1998		if (lookup_depth == 0)
1999		    errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
2000			" must be greater than zero");
2001
2002		len = sizeof(int);
2003		if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
2004			&avg_pkt_size, &len, NULL, 0) == -1)
2005
2006		    errx(1, "sysctlbyname(\"%s\")",
2007			"net.inet.ip.dummynet.red_avg_pkt_size");
2008		if (avg_pkt_size == 0)
2009			errx(EX_DATAERR,
2010			    "net.inet.ip.dummynet.red_avg_pkt_size must"
2011			    " be greater than zero");
2012
2013		len = sizeof(struct clockinfo);
2014		if (sysctlbyname("kern.clockrate", &clock, &len, NULL, 0) == -1)
2015			errx(1, "sysctlbyname(\"%s\")", "kern.clockrate");
2016
2017		/*
2018		 * Ticks needed for sending a medium-sized packet.
2019		 * Unfortunately, when we are configuring a WF2Q+ queue, we
2020		 * do not have bandwidth information, because that is stored
2021		 * in the parent pipe, and also we have multiple queues
2022		 * competing for it. So we set s=0, which is not very
2023		 * correct. But on the other hand, why do we want RED with
2024		 * WF2Q+ ?
2025		 */
2026		if (pipe.bandwidth==0) /* this is a WF2Q+ queue */
2027			s = 0;
2028		else
2029			s = clock.hz * avg_pkt_size * 8 / pipe.bandwidth;
2030
2031		/*
2032		 * max idle time (in ticks) before avg queue size becomes 0.
2033		 * NOTA:  (3/w_q) is approx the value x so that
2034		 * (1-w_q)^x < 10^-3.
2035		 */
2036		w_q = ((double)pipe.fs.w_q) / (1 << SCALE_RED);
2037		idle = s * 3. / w_q;
2038		pipe.fs.lookup_step = (int)idle / lookup_depth;
2039		if (!pipe.fs.lookup_step)
2040			pipe.fs.lookup_step = 1;
2041		weight = 1 - w_q;
2042		for (t = pipe.fs.lookup_step; t > 0; --t)
2043			weight *= weight;
2044		pipe.fs.lookup_weight = (int)(weight * (1 << SCALE_RED));
2045	}
2046	i = setsockopt(s, IPPROTO_IP, IP_DUMMYNET_CONFIGURE, &pipe,
2047			    sizeof pipe);
2048	if (i)
2049		err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
2050}
2051
2052static void
2053get_mac_addr_mask(char *p, u_char *addr, u_char *mask)
2054{
2055	int i, l;
2056
2057	for (i=0; i<6; i++)
2058		addr[i] = mask[i] = 0;
2059	if (!strcmp(p, "any"))
2060		return;
2061
2062	for (i=0; *p && i<6;i++, p++) {
2063		addr[i] = strtol(p, &p, 16);
2064		if (*p != ':') /* we start with the mask */
2065			break;
2066	}
2067	if (*p == '/') { /* mask len */
2068		l = strtol(p+1, &p, 0);
2069		for (i=0; l>0; l -=8, i++)
2070			mask[i] = (l >=8) ? 0xff : (~0) << (8-l);
2071	} else if (*p == '&') { /* mask */
2072		for (i=0, p++; *p && i<6;i++, p++) {
2073			mask[i] = strtol(p, &p, 16);
2074			if (*p != ':')
2075				break;
2076		}
2077	} else if (*p == '\0') {
2078		for (i=0; i<6; i++)
2079			mask[i] = 0xff;
2080	}
2081	for (i=0; i<6; i++)
2082		addr[i] &= mask[i];
2083}
2084
2085/*
2086 * helper function, updates the pointer to cmd with the length
2087 * of the current command, and also cleans up the first word of
2088 * the new command in case it has been clobbered before.
2089 */
2090static ipfw_insn *
2091next_cmd(ipfw_insn *cmd)
2092{
2093	cmd += F_LEN(cmd);
2094	bzero(cmd, sizeof(*cmd));
2095	return cmd;
2096}
2097
2098/*
2099 * A function to fill simple commands of size 1.
2100 * Existing flags are preserved.
2101 */
2102static void
2103fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, u_int16_t arg)
2104{
2105	cmd->opcode = opcode;
2106	cmd->len =  ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
2107	cmd->arg1 = arg;
2108}
2109
2110/*
2111 * Fetch and add the MAC address and type, with masks. This generates one or
2112 * two microinstructions, and returns the pointer to the last one.
2113 */
2114static ipfw_insn *
2115add_mac(ipfw_insn *cmd, int ac, char *av[])
2116{
2117	ipfw_insn_mac *mac; /* also *src */
2118
2119	if (ac <3)
2120		errx(EX_DATAERR, "MAC dst src type");
2121
2122	cmd->opcode = O_MACADDR2;
2123	cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
2124
2125	mac = (ipfw_insn_mac *)cmd;
2126	get_mac_addr_mask(av[0], mac->addr, mac->mask);		/* dst */
2127	get_mac_addr_mask(av[1], &(mac->addr[6]), &(mac->mask[6])); /* src */
2128	av += 2;
2129
2130	if (strcmp(av[0], "any") != 0) {	/* we have a non-null port */
2131		cmd += F_LEN(cmd);
2132
2133		fill_newports((ipfw_insn_u16 *)cmd, av[0], IPPROTO_ETHERTYPE);
2134		cmd->opcode = O_MAC_TYPE;
2135	}
2136
2137	return cmd;
2138}
2139
2140/*
2141 * Parse arguments and assemble the microinstructions which make up a rule.
2142 * Rules are added into the 'rulebuf' and then copied in the correct order
2143 * into the actual rule.
2144 *
2145 * The syntax for a rule starts with the action, followed by an
2146 * optional log action, and the various match patterns.
2147 * In the assembled microcode, the first opcode must be a O_PROBE_STATE
2148 * (generated if the rule includes a keep-state option), then the
2149 * various match patterns, the "log" action, and the actual action.
2150 *
2151 */
2152static void
2153add(int ac, char *av[])
2154{
2155	/*
2156	 * rules are added into the 'rulebuf' and then copied in
2157	 * the correct order into the actual rule.
2158	 * Some things that need to go out of order (prob, action etc.)
2159	 * go into actbuf[].
2160	 */
2161	static u_int32_t rulebuf[255], actbuf[255], cmdbuf[255];
2162
2163	ipfw_insn *src, *dst, *cmd, *action, *prev;
2164
2165	struct ip_fw *rule;
2166
2167	/*
2168	 * various flags used to record that we entered some fields.
2169	 */
2170	int have_mac = 0;	/* set if we have a MAC address */
2171	ipfw_insn *have_state = NULL;	/* check-state or keep-state */
2172
2173	int i;
2174
2175	int open_par = 0;	/* open parenthesis ( */
2176
2177	/* proto is here because it is used to fetch ports */
2178	u_char proto = IPPROTO_IP;	/* default protocol */
2179
2180	bzero(actbuf, sizeof(actbuf));		/* actions go here */
2181	bzero(cmdbuf, sizeof(cmdbuf));
2182	bzero(rulebuf, sizeof(rulebuf));
2183
2184	rule = (struct ip_fw *)rulebuf;
2185	cmd = (ipfw_insn *)cmdbuf;
2186	action = (ipfw_insn *)actbuf;
2187
2188	av++; ac--;
2189
2190	/* [rule N]	-- Rule number optional */
2191	if (ac && isdigit(**av)) {
2192		rule->rulenum = atoi(*av);
2193		av++;
2194		ac--;
2195	}
2196
2197	/* [prob D]	-- match probability, optional */
2198	if (ac > 1 && !strncmp(*av, "prob", strlen(*av))) {
2199		double d = strtod(av[1], NULL);
2200
2201		if (d <= 0 || d > 1)
2202			errx(EX_DATAERR, "illegal match prob. %s", av[1]);
2203		if (d != 1) { /* 1 means always match */
2204			action->opcode = O_PROB;
2205			action->len = 2;
2206			*((int32_t *)(action+1)) =
2207				(int32_t)((1 - d) * 0x7fffffff);
2208			action += action->len;
2209		}
2210		av += 2; ac -= 2;
2211	}
2212
2213	/* action	-- mandatory */
2214	NEED1("missing action");
2215	i = match_token(rule_actions, *av);
2216	ac--; av++;
2217	action->len = 1;	/* default */
2218	switch(i) {
2219	case TOK_CHECKSTATE:
2220		have_state = action;
2221		action->opcode = O_CHECK_STATE;
2222		break;
2223
2224	case TOK_ACCEPT:
2225		action->opcode = O_ACCEPT;
2226		break;
2227
2228	case TOK_DENY:
2229		action->opcode = O_DENY;
2230		action->arg1 = 0;
2231		break;
2232
2233	case TOK_REJECT:
2234		action->opcode = O_REJECT;
2235		action->arg1 = ICMP_UNREACH_HOST;
2236		break;
2237
2238	case TOK_RESET:
2239		action->opcode = O_REJECT;
2240		action->arg1 = ICMP_REJECT_RST;
2241		break;
2242
2243	case TOK_UNREACH:
2244		action->opcode = O_REJECT;
2245		NEED1("missing reject code");
2246		fill_reject_code(&action->arg1, *av);
2247		ac--; av++;
2248		break;
2249
2250	case TOK_COUNT:
2251		action->opcode = O_COUNT;
2252		break;
2253
2254	case TOK_QUEUE:
2255	case TOK_PIPE:
2256		action->len = F_INSN_SIZE(ipfw_insn_pipe);
2257	case TOK_SKIPTO:
2258		if (i == TOK_QUEUE)
2259			action->opcode = O_QUEUE;
2260		else if (i == TOK_PIPE)
2261			action->opcode = O_PIPE;
2262		else if (i == TOK_SKIPTO)
2263			action->opcode = O_SKIPTO;
2264		NEED1("missing skipto/pipe/queue number");
2265		action->arg1 = strtoul(*av, NULL, 10);
2266		av++; ac--;
2267		break;
2268
2269	case TOK_DIVERT:
2270	case TOK_TEE:
2271		action->opcode = (i == TOK_DIVERT) ? O_DIVERT : O_TEE;
2272		NEED1("missing divert/tee port");
2273		action->arg1 = strtoul(*av, NULL, 0);
2274		if (action->arg1 == 0) {
2275			struct servent *s;
2276			setservent(1);
2277			s = getservbyname(av[0], "divert");
2278			if (s != NULL)
2279				action->arg1 = ntohs(s->s_port);
2280			else
2281				errx(EX_DATAERR, "illegal divert/tee port");
2282		}
2283		ac--; av++;
2284		break;
2285
2286	case TOK_FORWARD: {
2287		ipfw_insn_sa *p = (ipfw_insn_sa *)action;
2288		char *s, *end;
2289
2290		NEED1("missing forward address[:port]");
2291
2292		action->opcode = O_FORWARD_IP;
2293		action->len = F_INSN_SIZE(ipfw_insn_sa);
2294
2295		p->sa.sin_len = sizeof(struct sockaddr_in);
2296		p->sa.sin_family = AF_INET;
2297		p->sa.sin_port = 0;
2298		/*
2299		 * locate the address-port separator (':' or ',')
2300		 */
2301		s = strchr(*av, ':');
2302		if (s == NULL)
2303			s = strchr(*av, ',');
2304		if (s != NULL) {
2305			*(s++) = '\0';
2306			i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
2307			if (s == end)
2308				errx(EX_DATAERR,
2309				    "illegal forwarding port ``%s''", s);
2310			p->sa.sin_port = htons( (u_short)i );
2311		}
2312		lookup_host(*av, &(p->sa.sin_addr));
2313		}
2314		ac--; av++;
2315		break;
2316
2317	default:
2318		errx(EX_DATAERR, "invalid action %s\n", *av);
2319	}
2320	action = next_cmd(action);
2321
2322	/*
2323	 * [log [logamount N]]	-- log, optional
2324	 *
2325	 * If exists, it goes first in the cmdbuf, but then it is
2326	 * skipped in the copy section to the end of the buffer.
2327	 */
2328	if (ac && !strncmp(*av, "log", strlen(*av))) {
2329		ipfw_insn_log *c = (ipfw_insn_log *)cmd;
2330
2331		cmd->len = F_INSN_SIZE(ipfw_insn_log);
2332		cmd->opcode = O_LOG;
2333		av++; ac--;
2334		if (ac && !strncmp(*av, "logamount", strlen(*av))) {
2335			ac--; av++;
2336			NEED1("logamount requires argument");
2337			c->max_log = atoi(*av);
2338			if (c->max_log < 0)
2339				errx(EX_DATAERR, "logamount must be positive");
2340			ac--; av++;
2341		}
2342		cmd = next_cmd(cmd);
2343	}
2344
2345	if (have_state)	/* must be a check-state, we are done */
2346		goto done;
2347
2348#define OR_START(target)					\
2349	if (ac && (*av[0] == '(' || *av[0] == '{')) {		\
2350		if (open_par)					\
2351			errx(EX_USAGE, "nested \"(\" not allowed\n"); \
2352		open_par = 1;					\
2353		if ( (av[0])[1] == '\0') {			\
2354			ac--; av++;				\
2355		} else						\
2356			(*av)++;				\
2357	}							\
2358	target:							\
2359
2360
2361#define	CLOSE_PAR						\
2362	if (open_par) {						\
2363		if (ac && (					\
2364		    !strncmp(*av, ")", strlen(*av)) ||		\
2365		    !strncmp(*av, "}", strlen(*av)) )) {	\
2366			open_par = 0;				\
2367			ac--; av++;				\
2368		} else						\
2369			errx(EX_USAGE, "missing \")\"\n");	\
2370	}
2371
2372#define NOT_BLOCK						\
2373	if (ac && !strncmp(*av, "not", strlen(*av))) {		\
2374		if (cmd->len & F_NOT)				\
2375			errx(EX_USAGE, "double \"not\" not allowed\n"); \
2376		cmd->len |= F_NOT;				\
2377		ac--; av++;					\
2378	}
2379
2380#define OR_BLOCK(target)					\
2381	if (ac && !strncmp(*av, "or", strlen(*av))) {		\
2382		if (prev == NULL || open_par == 0)		\
2383			errx(EX_DATAERR, "invalid OR block");	\
2384		prev->len |= F_OR;				\
2385		ac--; av++;					\
2386		goto target;					\
2387	}							\
2388	CLOSE_PAR;
2389
2390	/*
2391	 * protocol, mandatory
2392	 */
2393    OR_START(get_proto);
2394	NOT_BLOCK;
2395	NEED1("missing protocol");
2396	{
2397	struct protoent *pe;
2398
2399	if (!strncmp(*av, "all", strlen(*av)))
2400		; /* same as "ip" */
2401	else if (!strncmp(*av, "MAC", strlen(*av))) {
2402		/* need exactly 3 fields */
2403		cmd = add_mac(cmd, ac-1, av+1);	/* exits in case of errors */
2404		ac -= 3;
2405		av += 3;
2406		have_mac = 1;
2407	} else if ((proto = atoi(*av)) > 0)
2408		; /* all done! */
2409	else if ((pe = getprotobyname(*av)) != NULL)
2410		proto = pe->p_proto;
2411	else
2412		errx(EX_DATAERR, "invalid protocol ``%s''", *av);
2413	av++; ac--;
2414	if (proto != IPPROTO_IP)
2415		fill_cmd(cmd, O_PROTO, 0, proto);
2416	}
2417	cmd = next_cmd(cmd);
2418    OR_BLOCK(get_proto);
2419
2420	/*
2421	 * "from", mandatory (unless we have a MAC address)
2422	 */
2423	if (!ac || strncmp(*av, "from", strlen(*av))) {
2424		if (have_mac)	/* we do not need a "to" address */
2425			goto read_to;
2426		errx(EX_USAGE, "missing ``from''");
2427	}
2428	ac--; av++;
2429
2430	/*
2431	 * source IP, mandatory
2432	 */
2433    OR_START(source_ip);
2434	NOT_BLOCK;	/* optional "not" */
2435	NEED1("missing source address");
2436
2437	/* source	-- mandatory */
2438	fill_ip((ipfw_insn_ip *)cmd, *av);
2439	if (cmd->opcode == O_IP_DST_SET)			/* set */
2440		cmd->opcode = O_IP_SRC_SET;
2441	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))		/* me */
2442		cmd->opcode = O_IP_SRC_ME;
2443	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))	/* one IP */
2444		cmd->opcode = O_IP_SRC;
2445	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_ip))	/* addr/mask */
2446		cmd->opcode = O_IP_SRC_MASK;
2447	/* otherwise len will be zero and the command skipped */
2448	ac--; av++;
2449	prev = cmd; /* in case we need to backtrack */
2450	cmd = next_cmd(cmd);
2451    OR_BLOCK(source_ip);
2452
2453	/*
2454	 * source ports, optional
2455	 */
2456	NOT_BLOCK;	/* optional "not" */
2457	if (ac && fill_newports((ipfw_insn_u16 *)cmd, *av, proto)) {
2458		/* XXX todo: check that we have a protocol with ports */
2459		cmd->opcode = O_IP_SRCPORT;
2460		ac--;
2461		av++;
2462		cmd = next_cmd(cmd);
2463	}
2464
2465read_to:
2466	/*
2467	 * "to", mandatory (unless we have a MAC address
2468	 */
2469	if (!ac || strncmp(*av, "to", strlen(*av))) {
2470		if (have_mac)
2471			goto read_options;
2472		errx(EX_USAGE, "missing ``to''");
2473	}
2474	av++; ac--;
2475
2476	/*
2477	 * destination, mandatory
2478	 */
2479    OR_START(dest_ip);
2480	NOT_BLOCK;	/* optional "not" */
2481	NEED1("missing dst address");
2482	fill_ip((ipfw_insn_ip *)cmd, *av);
2483	if (cmd->opcode == O_IP_DST_SET)			/* set */
2484		;
2485	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))		/* me */
2486		cmd->opcode = O_IP_DST_ME;
2487	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))	/* one IP */
2488		cmd->opcode = O_IP_DST;
2489	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_ip))	/* addr/mask */
2490		cmd->opcode = O_IP_DST_MASK;
2491	ac--;
2492	av++;
2493	prev = cmd;
2494	cmd = next_cmd(cmd);
2495    OR_BLOCK(dest_ip);
2496
2497	/*
2498	 * dest. ports, optional
2499	 */
2500	NOT_BLOCK;	/* optional "not" */
2501	if (ac && fill_newports((ipfw_insn_u16 *)cmd, *av, proto)) {
2502		/* XXX todo: check that we have a protocol with ports */
2503		cmd->opcode = O_IP_DSTPORT;
2504		ac--;
2505		av++;
2506		cmd += F_LEN(cmd);
2507	}
2508
2509read_options:
2510	prev = NULL;
2511	while (ac) {
2512		char *s = *av;
2513		ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;	/* alias */
2514
2515		if (*s == '!') {	/* alternate syntax for NOT */
2516			if (cmd->len & F_NOT)
2517				errx(EX_USAGE, "double \"not\" not allowed\n");
2518			cmd->len = F_NOT;
2519			s++;
2520		}
2521		i = match_token(rule_options, s);
2522		ac--; av++;
2523		switch(i) {
2524		case TOK_NOT:
2525			if (cmd->len & F_NOT)
2526				errx(EX_USAGE, "double \"not\" not allowed\n");
2527			cmd->len = F_NOT;
2528			break;
2529
2530		case TOK_OR:
2531			if (prev == NULL)
2532				errx(EX_USAGE, "invalid \"or\" block\n");
2533			prev->len |= F_OR;
2534			break;
2535
2536		case TOK_IN:
2537			fill_cmd(cmd, O_IN, 0, 0);
2538			break;
2539
2540		case TOK_OUT:
2541			cmd->len ^= F_NOT; /* toggle F_NOT */
2542			fill_cmd(cmd, O_IN, 0, 0);
2543			break;
2544
2545		case TOK_FRAG:
2546			fill_cmd(cmd, O_FRAG, 0, 0);
2547			break;
2548
2549		case TOK_LAYER2:
2550			fill_cmd(cmd, O_LAYER2, 0, 0);
2551			break;
2552
2553		case TOK_XMIT:
2554		case TOK_RECV:
2555		case TOK_VIA:
2556			NEED1("recv, xmit, via require interface name"
2557				" or address");
2558			fill_iface((ipfw_insn_if *)cmd, av[0]);
2559			ac--; av++;
2560			if (F_LEN(cmd) == 0)	/* not a valid address */
2561				break;
2562			if (i == TOK_XMIT)
2563				cmd->opcode = O_XMIT;
2564			else if (i == TOK_RECV)
2565				cmd->opcode = O_RECV;
2566			else if (i == TOK_VIA)
2567				cmd->opcode = O_VIA;
2568			break;
2569
2570		case TOK_ICMPTYPES:
2571			NEED1("icmptypes requires list of types");
2572			fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
2573			av++; ac--;
2574			break;
2575
2576		case TOK_IPTTL:
2577			NEED1("ipttl requires TTL");
2578			fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
2579			ac--; av++;
2580			break;
2581
2582		case TOK_IPID:
2583			NEED1("ipid requires length");
2584			fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
2585			ac--; av++;
2586			break;
2587
2588		case TOK_IPLEN:
2589			NEED1("iplen requires length");
2590			fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
2591			ac--; av++;
2592			break;
2593
2594		case TOK_IPVER:
2595			NEED1("ipver requires version");
2596			fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
2597			ac--; av++;
2598			break;
2599
2600		case TOK_IPPRECEDENCE:
2601			NEED1("ipprecedence requires value");
2602			fill_cmd(cmd, O_IPPRECEDENCE, 0,
2603			    (strtoul(*av, NULL, 0) & 7) << 5);
2604			ac--; av++;
2605			break;
2606
2607		case TOK_IPOPTS:
2608			NEED1("missing argument for ipoptions");
2609			fill_flags(cmd, O_IPOPT, f_ipopts, *av);
2610			ac--; av++;
2611			break;
2612
2613		case TOK_IPTOS:
2614			NEED1("missing argument for iptos");
2615			fill_flags(cmd, O_IPTOS, f_iptos, *av);
2616			ac--; av++;
2617			break;
2618
2619		case TOK_UID:
2620			NEED1("uid requires argument");
2621		    {
2622			char *end;
2623			uid_t uid;
2624			struct passwd *pwd;
2625
2626			cmd->opcode = O_UID;
2627			uid = strtoul(*av, &end, 0);
2628			pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
2629			if (pwd == NULL)
2630				errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
2631			cmd32->d[0] = uid;
2632			cmd->len = F_INSN_SIZE(ipfw_insn_u32);
2633			ac--; av++;
2634		    }
2635			break;
2636
2637		case TOK_GID:
2638			NEED1("gid requires argument");
2639		    {
2640			char *end;
2641			gid_t gid;
2642			struct group *grp;
2643
2644			cmd->opcode = O_GID;
2645			gid = strtoul(*av, &end, 0);
2646			grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
2647			if (grp == NULL)
2648				errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
2649
2650			cmd32->d[0] = gid;
2651			cmd->len = F_INSN_SIZE(ipfw_insn_u32);
2652			ac--; av++;
2653		    }
2654			break;
2655
2656		case TOK_ESTAB:
2657			fill_cmd(cmd, O_ESTAB, 0, 0);
2658			break;
2659
2660		case TOK_SETUP:
2661			fill_cmd(cmd, O_TCPFLAGS, 0,
2662				(TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
2663			break;
2664
2665		case TOK_TCPOPTS:
2666			NEED1("missing argument for tcpoptions");
2667			fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
2668			ac--; av++;
2669			break;
2670
2671		case TOK_TCPSEQ:
2672		case TOK_TCPACK:
2673			NEED1("tcpseq/tcpack requires argument");
2674			cmd->len = F_INSN_SIZE(ipfw_insn_u32);
2675			cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
2676			cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
2677			ac--; av++;
2678			break;
2679
2680		case TOK_TCPWIN:
2681			NEED1("tcpwin requires length");
2682			fill_cmd(cmd, O_TCPWIN, 0,
2683			    htons(strtoul(*av, NULL, 0)));
2684			ac--; av++;
2685			break;
2686
2687		case TOK_TCPFLAGS:
2688			NEED1("missing argument for tcpflags");
2689			cmd->opcode = O_TCPFLAGS;
2690			fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
2691			ac--; av++;
2692			break;
2693
2694		case TOK_KEEPSTATE:
2695			if (have_state)
2696				errx(EX_USAGE, "only one of keep-state "
2697					"and limit is allowed");
2698			have_state = cmd;
2699			fill_cmd(cmd, O_KEEP_STATE, 0, 0);
2700			break;
2701
2702		case TOK_LIMIT:
2703			NEED1("limit needs mask and # of connections");
2704			if (have_state)
2705				errx(EX_USAGE, "only one of keep-state "
2706					"and limit is allowed");
2707			have_state = cmd;
2708		    {
2709			ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
2710
2711			cmd->len = F_INSN_SIZE(ipfw_insn_limit);
2712			cmd->opcode = O_LIMIT;
2713			c->limit_mask = 0;
2714			c->conn_limit = 0;
2715			for (; ac >1 ;) {
2716				int val;
2717
2718				val = match_token(limit_masks, *av);
2719				if (val <= 0)
2720					break;
2721				c->limit_mask |= val;
2722				ac--; av++;
2723			}
2724			c->conn_limit = atoi(*av);
2725			if (c->conn_limit == 0)
2726				errx(EX_USAGE, "limit: limit must be >0");
2727			if (c->limit_mask == 0)
2728				errx(EX_USAGE, "missing limit mask");
2729			ac--; av++;
2730		    }
2731			break;
2732
2733		default:
2734			errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
2735		}
2736		if (F_LEN(cmd) > 0) {	/* prepare to advance */
2737			prev = cmd;
2738			cmd = next_cmd(cmd);
2739		}
2740	}
2741
2742done:
2743	/*
2744	 * Now copy stuff into the rule.
2745	 * If we have a keep-state option, the first instruction
2746	 * must be a PROBE_STATE (which is generated here).
2747	 * If we have a LOG option, it was stored as the first command,
2748	 * and now must be moved to the top of the action part.
2749	 */
2750	dst = (ipfw_insn *)rule->cmd;
2751
2752	/*
2753	 * generate O_PROBE_STATE if necessary
2754	 */
2755	if (have_state && have_state->opcode != O_CHECK_STATE) {
2756		fill_cmd(dst, O_PROBE_STATE, 0, 0);
2757		dst = next_cmd(dst);
2758	}
2759	/*
2760	 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT
2761	 */
2762	for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
2763		i = F_LEN(src);
2764
2765		switch (src->opcode) {
2766		case O_LOG:
2767		case O_KEEP_STATE:
2768		case O_LIMIT:
2769			break;
2770		default:
2771			bcopy(src, dst, i * sizeof(u_int32_t));
2772			dst += i;
2773		}
2774	}
2775
2776	/*
2777	 * put back the have_state command as last opcode
2778	 */
2779	if (have_state && have_state->opcode != O_CHECK_STATE) {
2780		i = F_LEN(have_state);
2781		bcopy(have_state, dst, i * sizeof(u_int32_t));
2782		dst += i;
2783	}
2784	/*
2785	 * start action section
2786	 */
2787	rule->act_ofs = dst - rule->cmd;
2788
2789	/*
2790	 * put back O_LOG if necessary
2791	 */
2792	src = (ipfw_insn *)cmdbuf;
2793	if ( src->opcode == O_LOG ) {
2794		i = F_LEN(src);
2795		bcopy(src, dst, i * sizeof(u_int32_t));
2796		dst += i;
2797	}
2798	/*
2799	 * copy all other actions
2800	 */
2801	for (src = (ipfw_insn *)actbuf; src != action; src += i) {
2802		i = F_LEN(src);
2803		bcopy(src, dst, i * sizeof(u_int32_t));
2804		dst += i;
2805	}
2806
2807	rule->cmd_len = (u_int32_t *)dst - (u_int32_t *)(rule->cmd);
2808	i = (void *)dst - (void *)rule;
2809	if (getsockopt(s, IPPROTO_IP, IP_FW_ADD, rule, &i) == -1)
2810		err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
2811	if (!do_quiet)
2812		show_ipfw(rule);
2813}
2814
2815static void
2816zero (int ac, char *av[])
2817{
2818	int rulenum;
2819	int failed = EX_OK;
2820
2821	av++; ac--;
2822
2823	if (!ac) {
2824		/* clear all entries */
2825		if (setsockopt(s, IPPROTO_IP, IP_FW_ZERO, NULL, 0) < 0)
2826			err(EX_UNAVAILABLE, "setsockopt(%s)", "IP_FW_ZERO");
2827		if (!do_quiet)
2828			printf("Accounting cleared.\n");
2829
2830		return;
2831	}
2832
2833	while (ac) {
2834		/* Rule number */
2835		if (isdigit(**av)) {
2836			rulenum = atoi(*av);
2837			av++;
2838			ac--;
2839			if (setsockopt(s, IPPROTO_IP,
2840			    IP_FW_ZERO, &rulenum, sizeof rulenum)) {
2841				warn("rule %u: setsockopt(IP_FW_ZERO)",
2842				    rulenum);
2843				failed = EX_UNAVAILABLE;
2844			} else if (!do_quiet)
2845				printf("Entry %d cleared\n", rulenum);
2846		} else {
2847			errx(EX_USAGE, "invalid rule number ``%s''", *av);
2848		}
2849	}
2850	if (failed != EX_OK)
2851		exit(failed);
2852}
2853
2854static void
2855resetlog (int ac, char *av[])
2856{
2857	int rulenum;
2858	int failed = EX_OK;
2859
2860	av++; ac--;
2861
2862	if (!ac) {
2863		/* clear all entries */
2864		if (setsockopt(s, IPPROTO_IP, IP_FW_RESETLOG, NULL, 0) < 0)
2865			err(EX_UNAVAILABLE, "setsockopt(IP_FW_RESETLOG)");
2866		if (!do_quiet)
2867			printf("Logging counts reset.\n");
2868
2869		return;
2870	}
2871
2872	while (ac) {
2873		/* Rule number */
2874		if (isdigit(**av)) {
2875			rulenum = atoi(*av);
2876			av++;
2877			ac--;
2878			if (setsockopt(s, IPPROTO_IP,
2879			    IP_FW_RESETLOG, &rulenum, sizeof rulenum)) {
2880				warn("rule %u: setsockopt(IP_FW_RESETLOG)",
2881				    rulenum);
2882				failed = EX_UNAVAILABLE;
2883			} else if (!do_quiet)
2884				printf("Entry %d logging count reset\n",
2885				    rulenum);
2886		} else {
2887			errx(EX_DATAERR, "invalid rule number ``%s''", *av);
2888		}
2889	}
2890	if (failed != EX_OK)
2891		exit(failed);
2892}
2893
2894static void
2895flush()
2896{
2897	int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
2898
2899	if (!do_force && !do_quiet) { /* need to ask user */
2900		int c;
2901
2902		printf("Are you sure? [yn] ");
2903		fflush(stdout);
2904		do {
2905			c = toupper(getc(stdin));
2906			while (c != '\n' && getc(stdin) != '\n')
2907				if (feof(stdin))
2908					return; /* and do not flush */
2909		} while (c != 'Y' && c != 'N');
2910		printf("\n");
2911		if (c == 'N')	/* user said no */
2912			return;
2913	}
2914	if (setsockopt(s, IPPROTO_IP, cmd, NULL, 0) < 0)
2915		err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
2916		    do_pipe ? "DUMMYNET" : "FW");
2917	if (!do_quiet)
2918		printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules");
2919}
2920
2921static int
2922ipfw_main(int ac, char **av)
2923{
2924	int ch;
2925
2926	if (ac == 1)
2927		show_usage();
2928
2929	/* Set the force flag for non-interactive processes */
2930	do_force = !isatty(STDIN_FILENO);
2931
2932	optind = optreset = 1;
2933	while ((ch = getopt(ac, av, "hs:adefNqtv")) != -1)
2934		switch (ch) {
2935		case 'h': /* help */
2936			help();
2937			break;	/* NOTREACHED */
2938
2939		case 's': /* sort */
2940			do_sort = atoi(optarg);
2941			break;
2942		case 'a':
2943			do_acct = 1;
2944			break;
2945		case 'd':
2946			do_dynamic = 1;
2947			break;
2948		case 'e':
2949			do_expired = 1;
2950			break;
2951		case 'f':
2952			do_force = 1;
2953			break;
2954		case 'N':
2955			do_resolv = 1;
2956			break;
2957		case 'q':
2958			do_quiet = 1;
2959			break;
2960		case 't':
2961			do_time = 1;
2962			break;
2963		case 'v': /* verbose */
2964			verbose++;
2965			break;
2966		default:
2967			show_usage();
2968		}
2969
2970	ac -= optind;
2971	av += optind;
2972	NEED1("bad arguments, for usage summary ``ipfw''");
2973
2974	/*
2975	 * optional: pipe or queue
2976	 */
2977	if (!strncmp(*av, "pipe", strlen(*av))) {
2978		do_pipe = 1;
2979		ac--;
2980		av++;
2981	} else if (!strncmp(*av, "queue", strlen(*av))) {
2982		do_pipe = 2;
2983		ac--;
2984		av++;
2985	}
2986	NEED1("missing command");
2987
2988	/*
2989	 * for pipes and queues we normally say 'pipe NN config'
2990	 * but the code is easier to parse as 'pipe config NN'
2991	 * so we swap the two arguments.
2992	 */
2993	if (do_pipe > 0 && ac > 1 && *av[0] >= '0' && *av[0] <= '9') {
2994		char *p = av[0];
2995		av[0] = av[1];
2996		av[1] = p;
2997	}
2998	if (!strncmp(*av, "add", strlen(*av)))
2999		add(ac, av);
3000	else if (do_pipe && !strncmp(*av, "config", strlen(*av)))
3001		config_pipe(ac, av);
3002	else if (!strncmp(*av, "delete", strlen(*av)))
3003		delete(ac, av);
3004	else if (!strncmp(*av, "flush", strlen(*av)))
3005		flush();
3006	else if (!strncmp(*av, "zero", strlen(*av)))
3007		zero(ac, av);
3008	else if (!strncmp(*av, "resetlog", strlen(*av)))
3009		resetlog(ac, av);
3010	else if (!strncmp(*av, "print", strlen(*av)) ||
3011	         !strncmp(*av, "list", strlen(*av)))
3012		list(ac, av);
3013	else if (!strncmp(*av, "show", strlen(*av))) {
3014		do_acct++;
3015		list(ac, av);
3016	} else
3017		errx(EX_USAGE, "bad command `%s'", *av);
3018	return 0;
3019}
3020
3021
3022static void
3023ipfw_readfile(int ac, char *av[])
3024{
3025#define MAX_ARGS	32
3026#define WHITESP		" \t\f\v\n\r"
3027	char	buf[BUFSIZ];
3028	char	*a, *p, *args[MAX_ARGS], *cmd = NULL;
3029	char	linename[10];
3030	int	i=0, lineno=0, qflag=0, pflag=0, status;
3031	FILE	*f = NULL;
3032	pid_t	preproc = 0;
3033	int	c;
3034
3035	while ((c = getopt(ac, av, "D:U:p:q")) != -1)
3036		switch(c) {
3037		case 'D':
3038			if (!pflag)
3039				errx(EX_USAGE, "-D requires -p");
3040			if (i > MAX_ARGS - 2)
3041				errx(EX_USAGE,
3042				     "too many -D or -U options");
3043			args[i++] = "-D";
3044			args[i++] = optarg;
3045			break;
3046
3047		case 'U':
3048			if (!pflag)
3049				errx(EX_USAGE, "-U requires -p");
3050			if (i > MAX_ARGS - 2)
3051				errx(EX_USAGE,
3052				     "too many -D or -U options");
3053			args[i++] = "-U";
3054			args[i++] = optarg;
3055			break;
3056
3057		case 'p':
3058			pflag = 1;
3059			cmd = optarg;
3060			args[0] = cmd;
3061			i = 1;
3062			break;
3063
3064		case 'q':
3065			qflag = 1;
3066			break;
3067
3068		default:
3069			errx(EX_USAGE, "bad arguments, for usage"
3070			     " summary ``ipfw''");
3071		}
3072
3073	av += optind;
3074	ac -= optind;
3075	if (ac != 1)
3076		errx(EX_USAGE, "extraneous filename arguments");
3077
3078	if ((f = fopen(av[0], "r")) == NULL)
3079		err(EX_UNAVAILABLE, "fopen: %s", av[0]);
3080
3081	if (pflag) {
3082		/* pipe through preprocessor (cpp or m4) */
3083		int pipedes[2];
3084
3085		args[i] = 0;
3086
3087		if (pipe(pipedes) == -1)
3088			err(EX_OSERR, "cannot create pipe");
3089
3090		switch((preproc = fork())) {
3091		case -1:
3092			err(EX_OSERR, "cannot fork");
3093
3094		case 0:
3095			/* child */
3096			if (dup2(fileno(f), 0) == -1
3097			    || dup2(pipedes[1], 1) == -1)
3098				err(EX_OSERR, "dup2()");
3099			fclose(f);
3100			close(pipedes[1]);
3101			close(pipedes[0]);
3102			execvp(cmd, args);
3103			err(EX_OSERR, "execvp(%s) failed", cmd);
3104
3105		default:
3106			/* parent */
3107			fclose(f);
3108			close(pipedes[1]);
3109			if ((f = fdopen(pipedes[0], "r")) == NULL) {
3110				int savederrno = errno;
3111
3112				(void)kill(preproc, SIGTERM);
3113				errno = savederrno;
3114				err(EX_OSERR, "fdopen()");
3115			}
3116		}
3117	}
3118
3119	while (fgets(buf, BUFSIZ, f)) {
3120		lineno++;
3121		sprintf(linename, "Line %d", lineno);
3122		args[0] = linename;
3123
3124		if (*buf == '#')
3125			continue;
3126		if ((p = strchr(buf, '#')) != NULL)
3127			*p = '\0';
3128		i = 1;
3129		if (qflag)
3130			args[i++] = "-q";
3131		for (a = strtok(buf, WHITESP);
3132		    a && i < MAX_ARGS; a = strtok(NULL, WHITESP), i++)
3133			args[i] = a;
3134		if (i == (qflag? 2: 1))
3135			continue;
3136		if (i == MAX_ARGS)
3137			errx(EX_USAGE, "%s: too many arguments",
3138			    linename);
3139		args[i] = NULL;
3140
3141		ipfw_main(i, args);
3142	}
3143	fclose(f);
3144	if (pflag) {
3145		if (waitpid(preproc, &status, 0) == -1)
3146			errx(EX_OSERR, "waitpid()");
3147		if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
3148			errx(EX_UNAVAILABLE,
3149			    "preprocessor exited with status %d",
3150			    WEXITSTATUS(status));
3151		else if (WIFSIGNALED(status))
3152			errx(EX_UNAVAILABLE,
3153			    "preprocessor exited with signal %d",
3154			    WTERMSIG(status));
3155	}
3156}
3157
3158int
3159main(int ac, char *av[])
3160{
3161	s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
3162	if (s < 0)
3163		err(EX_UNAVAILABLE, "socket");
3164
3165	/*
3166	 * If the last argument is an absolute pathname, interpret it
3167	 * as a file to be preprocessed.
3168	 */
3169
3170	if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0)
3171		ipfw_readfile(ac, av);
3172	else
3173		ipfw_main(ac, av);
3174	return EX_OK;
3175}
3176