ipfw2.c revision 99475
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 99475 2002-07-05 22:43:06Z 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 <unistd.h>
44#include <sysexits.h>
45
46#include <net/if.h>
47#include <netinet/in.h>
48#include <netinet/in_systm.h>
49#include <netinet/ip.h>
50#include <netinet/ip_icmp.h>
51#include <netinet/ip_fw.h>
52#include <net/route.h> /* def. of struct route */
53#include <netinet/ip_dummynet.h>
54#include <netinet/tcp.h>
55#include <arpa/inet.h>
56
57int		s,			/* main RAW socket */
58		do_resolv,		/* Would try to resolve all */
59		do_acct,		/* Show packet/byte count */
60		do_time,		/* Show time stamps */
61		do_quiet,		/* Be quiet in add and flush */
62		do_force,		/* Don't ask for confirmation */
63		do_pipe,		/* this cmd refers to a pipe */
64		do_sort,		/* field to sort results (0 = no) */
65		do_dynamic,		/* display dynamic rules */
66		do_expired,		/* display expired dynamic rules */
67		verbose;
68
69#define	IP_MASK_ALL	0xffffffff
70
71/*
72 * structure to hold flag names and associated values to be
73 * set in the appropriate masks.
74 * A NULL string terminates the array.
75 * Often, an element with 0 value contains an error string.
76 *
77 */
78struct _s_x {
79	char *s;
80	int x;
81};
82
83static struct _s_x f_tcpflags[] = {
84	{ "syn", TH_SYN },
85	{ "fin", TH_FIN },
86	{ "ack", TH_ACK },
87	{ "psh", TH_PUSH },
88	{ "rst", TH_RST },
89	{ "urg", TH_URG },
90	{ "tcp flag", 0 },
91	{ NULL,	0 }
92};
93
94static struct _s_x f_tcpopts[] = {
95	{ "mss",	IP_FW_TCPOPT_MSS },
96	{ "maxseg",	IP_FW_TCPOPT_MSS },
97	{ "window",	IP_FW_TCPOPT_WINDOW },
98	{ "sack",	IP_FW_TCPOPT_SACK },
99	{ "ts",		IP_FW_TCPOPT_TS },
100	{ "timestamp",	IP_FW_TCPOPT_TS },
101	{ "cc",		IP_FW_TCPOPT_CC },
102	{ "tcp option",	0 },
103	{ NULL,	0 }
104};
105
106/*
107 * IP options span the range 0 to 255 so we need to remap them
108 * (though in fact only the low 5 bits are significant).
109 */
110static struct _s_x f_ipopts[] = {
111	{ "ssrr",	IP_FW_IPOPT_SSRR},
112	{ "lsrr",	IP_FW_IPOPT_LSRR},
113	{ "rr",		IP_FW_IPOPT_RR},
114	{ "ts",		IP_FW_IPOPT_TS},
115	{ "ip option",	0 },
116	{ NULL,	0 }
117};
118
119static struct _s_x f_iptos[] = {
120	{ "lowdelay",	IPTOS_LOWDELAY},
121	{ "throughput",	IPTOS_THROUGHPUT},
122	{ "reliability", IPTOS_RELIABILITY},
123	{ "mincost",	IPTOS_MINCOST},
124	{ "congestion",	IPTOS_CE},
125	{ "ecntransport", IPTOS_ECT},
126	{ "ip tos option", 0},
127	{ NULL,	0 }
128};
129
130static struct _s_x limit_masks[] = {
131	{"all",		DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
132	{"src-addr",	DYN_SRC_ADDR},
133	{"src-port",	DYN_SRC_PORT},
134	{"dst-addr",	DYN_DST_ADDR},
135	{"dst-port",	DYN_DST_PORT},
136	{NULL,		0}
137};
138
139/*
140 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
141 * This is only used in this code.
142 */
143#define IPPROTO_ETHERTYPE	0x1000
144static struct _s_x ether_types[] = {
145    /*
146     * Note, we cannot use "-:&/" in the names because they are field
147     * separators in the type specifications. Also, we use s = NULL as
148     * end-delimiter, because a type of 0 can be legal.
149     */
150	{ "ip",		0x0800 },
151	{ "ipv4",	0x0800 },
152	{ "ipv6",	0x86dd },
153	{ "arp",	0x0806 },
154	{ "rarp",	0x8035 },
155	{ "vlan",	0x8100 },
156	{ "loop",	0x9000 },
157	{ "trail",	0x1000 },
158	{ "at",		0x809b },
159	{ "atalk",	0x809b },
160	{ "aarp",	0x80f3 },
161	{ "pppoe_disc",	0x8863 },
162	{ "pppoe_sess",	0x8864 },
163	{ "ipx_8022",	0x00E0 },
164	{ "ipx_8023",	0x0000 },
165	{ "ipx_ii",	0x8137 },
166	{ "ipx_snap",	0x8137 },
167	{ "ipx",	0x8137 },
168	{ "ns",		0x0600 },
169	{ NULL,		0 }
170};
171
172static void show_usage(void);
173
174enum tokens {
175	TOK_NULL=0,
176
177	TOK_OR,
178	TOK_NOT,
179
180	TOK_ACCEPT,
181	TOK_COUNT,
182	TOK_PIPE,
183	TOK_QUEUE,
184	TOK_DIVERT,
185	TOK_TEE,
186	TOK_FORWARD,
187	TOK_SKIPTO,
188	TOK_DENY,
189	TOK_REJECT,
190	TOK_RESET,
191	TOK_UNREACH,
192	TOK_CHECKSTATE,
193
194	TOK_UID,
195	TOK_GID,
196	TOK_IN,
197	TOK_LIMIT,
198	TOK_KEEPSTATE,
199	TOK_LAYER2,
200	TOK_OUT,
201	TOK_XMIT,
202	TOK_RECV,
203	TOK_VIA,
204	TOK_FRAG,
205	TOK_IPOPTS,
206	TOK_IPLEN,
207	TOK_IPID,
208	TOK_IPPRECEDENCE,
209	TOK_IPTOS,
210	TOK_IPTTL,
211	TOK_IPVER,
212	TOK_ESTAB,
213	TOK_SETUP,
214	TOK_TCPFLAGS,
215	TOK_TCPOPTS,
216	TOK_TCPSEQ,
217	TOK_TCPACK,
218	TOK_TCPWIN,
219	TOK_ICMPTYPES,
220
221	TOK_PLR,
222	TOK_BUCKETS,
223	TOK_DSTIP,
224	TOK_SRCIP,
225	TOK_DSTPORT,
226	TOK_SRCPORT,
227	TOK_ALL,
228	TOK_MASK,
229	TOK_BW,
230	TOK_DELAY,
231	TOK_RED,
232	TOK_GRED,
233	TOK_DROPTAIL,
234	TOK_PROTO,
235	TOK_WEIGHT,
236};
237
238struct _s_x dummynet_params[] = {
239	{ "plr",		TOK_PLR },
240	{ "buckets",		TOK_BUCKETS },
241	{ "dst-ip",		TOK_DSTIP },
242	{ "src-ip",		TOK_SRCIP },
243	{ "dst-port",		TOK_DSTPORT },
244	{ "src-port",		TOK_SRCPORT },
245	{ "proto",		TOK_PROTO },
246	{ "weight",		TOK_WEIGHT },
247	{ "all",		TOK_ALL },
248	{ "mask",		TOK_MASK },
249	{ "droptail",		TOK_DROPTAIL },
250	{ "red",		TOK_RED },
251	{ "gred",		TOK_GRED },
252	{ "bw",			TOK_BW },
253	{ "bandwidth",		TOK_BW },
254	{ "delay",		TOK_DELAY },
255	{ "pipe",		TOK_PIPE },
256	{ "queue",		TOK_QUEUE },
257	{ "dummynet-params",	TOK_NULL },
258	{ NULL, 0 }
259};
260
261struct _s_x rule_actions[] = {
262	{ "accept",		TOK_ACCEPT },
263	{ "pass",		TOK_ACCEPT },
264	{ "allow",		TOK_ACCEPT },
265	{ "permit",		TOK_ACCEPT },
266	{ "count",		TOK_COUNT },
267	{ "pipe",		TOK_PIPE },
268	{ "queue",		TOK_QUEUE },
269	{ "divert",		TOK_DIVERT },
270	{ "tee",		TOK_TEE },
271	{ "fwd",		TOK_FORWARD },
272	{ "forward",		TOK_FORWARD },
273	{ "skipto",		TOK_SKIPTO },
274	{ "deny",		TOK_DENY },
275	{ "drop",		TOK_DENY },
276	{ "reject",		TOK_REJECT },
277	{ "reset",		TOK_RESET },
278	{ "unreach",		TOK_UNREACH },
279	{ "check-state",	TOK_CHECKSTATE },
280	{ NULL,			TOK_NULL },
281	{ NULL, 0 }
282};
283
284struct _s_x rule_options[] = {
285	{ "uid",		TOK_UID },
286	{ "gid",		TOK_GID },
287	{ "in",			TOK_IN },
288	{ "limit",		TOK_LIMIT },
289	{ "keep-state",		TOK_KEEPSTATE },
290	{ "bridged",		TOK_LAYER2 },
291	{ "layer2",		TOK_LAYER2 },
292	{ "out",		TOK_OUT },
293	{ "xmit",		TOK_XMIT },
294	{ "recv",		TOK_RECV },
295	{ "via",		TOK_VIA },
296	{ "fragment",		TOK_FRAG },
297	{ "frag",		TOK_FRAG },
298	{ "ipoptions",		TOK_IPOPTS },
299	{ "ipopts",		TOK_IPOPTS },
300	{ "iplen",		TOK_IPLEN },
301	{ "ipid",		TOK_IPID },
302	{ "ipprecedence",	TOK_IPPRECEDENCE },
303	{ "iptos",		TOK_IPTOS },
304	{ "ipttl",		TOK_IPTTL },
305	{ "ipversion",		TOK_IPVER },
306	{ "ipver",		TOK_IPVER },
307	{ "estab",		TOK_ESTAB },
308	{ "established",	TOK_ESTAB },
309	{ "setup",		TOK_SETUP },
310	{ "tcpflags",		TOK_TCPFLAGS },
311	{ "tcpflgs",		TOK_TCPFLAGS },
312	{ "tcpoptions",		TOK_TCPOPTS },
313	{ "tcpopts",		TOK_TCPOPTS },
314	{ "tcpseq",		TOK_TCPSEQ },
315	{ "tcpack",		TOK_TCPACK },
316	{ "tcpwin",		TOK_TCPWIN },
317	{ "icmptypes",		TOK_ICMPTYPES },
318
319	{ "not",		TOK_NOT },		/* pseudo option */
320	{ "!", /* escape ? */	TOK_NOT },		/* pseudo option */
321	{ "or",			TOK_OR },		/* pseudo option */
322	{ "|", /* escape */	TOK_OR },		/* pseudo option */
323	{ NULL,			TOK_NULL },
324	{ NULL, 0 }
325};
326
327/**
328 * match_token takes a table and a string, returns the value associated
329 * with the string (0 meaning an error in most cases)
330 */
331static int
332match_token(struct _s_x *table, char *string)
333{
334	struct _s_x *pt;
335	int i = strlen(string);
336
337	for (pt = table ; i && pt->s != NULL ; pt++)
338		if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
339			return pt->x;
340	return -1;
341};
342
343static char *
344match_value(struct _s_x *p, u_int32_t value)
345{
346	for (; p->s != NULL; p++)
347		if (p->x == value)
348			return p->s;
349	return NULL;
350}
351
352/*
353 * prints one port, symbolic or numeric
354 */
355static void
356print_port(int proto, u_int16_t port)
357{
358
359	if (proto == IPPROTO_ETHERTYPE) {
360		char *s;
361
362		if (do_resolv && (s = match_value(ether_types, port)) )
363			printf("%s", s);
364		else
365			printf("0x%04x", port);
366	} else {
367		struct servent *se = NULL;
368		if (do_resolv) {
369			struct protoent *pe = getprotobynumber(proto);
370
371			se = getservbyport(htons(port), pe ? pe->p_name : NULL);
372		}
373		if (se)
374			printf("%s", se->s_name);
375		else
376			printf("%d", port);
377	}
378}
379
380/*
381 * print the values in a list of ports
382 * XXX todo: add support for mask.
383 */
384static void
385print_newports(ipfw_insn_u16 *cmd, int proto)
386{
387	u_int16_t *p = cmd->ports;
388	int i;
389	char *sep= " ";
390
391	if (cmd->o.len & F_NOT)
392		printf(" not");
393	for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
394		printf(sep);
395		print_port(proto, p[0]);
396		if (p[0] != p[1]) {
397			printf("-");
398			print_port(proto, p[1]);
399		}
400		sep = ",";
401	}
402}
403
404/*
405 * Like strtol, but also translates service names into port numbers
406 * for some protocols.
407 * In particular:
408 *	proto == -1 disables the protocol check;
409 *	proto == IPPROTO_ETHERTYPE looks up an internal table
410 *	proto == <some value in /etc/protocols> matches the values there.
411 */
412static int
413strtoport(char *s, char **end, int base, int proto)
414{
415	char *s1, sep;
416	int i;
417
418	if ( *s == '\0')
419		goto none;
420
421	if (isdigit(*s))
422		return strtol(s, end, base);
423
424	/*
425	 * find separator and replace with a '\0'
426	 */
427	for (s1 = s; *s1 && isalnum(*s1) ; s1++)
428		;
429	sep = *s1;
430	*s1 = '\0';
431
432	if (proto == IPPROTO_ETHERTYPE) {
433		i = match_token(ether_types, s);
434		*s1 = sep;
435		if (i == -1) {	/* not found */
436			*end = s;
437			return 0;
438		} else {
439			*end = s1;
440			return i;
441		}
442	} else {
443		struct protoent *pe = NULL;
444		struct servent *se;
445
446		if (proto != 0)
447			pe = getprotobynumber(proto);
448		setservent(1);
449		se = getservbyname(s, pe ? pe->p_name : NULL);
450		*s1 = sep;
451		if (se != NULL) {
452			*end = s1;
453			return ntohs(se->s_port);
454		}
455	}
456none:
457	*end = s;
458	return 0;
459}
460
461/*
462 * fill the body of the command with the list of port ranges.
463 * At the moment it only understands numeric ranges.
464 */
465static int
466fill_newports(ipfw_insn_u16 *cmd, char *av, int proto)
467{
468	u_int16_t *p = cmd->ports;
469	int i = 0;
470
471	for (; *av ; i++, p +=2 ) {
472		u_int16_t a, b;
473		char *s;
474
475		a = strtoport(av, &s, 0, proto);
476		if (s == av) /* no parameter */
477			break;
478		if (*s == '-') { /* a range */
479			av = s+1;
480			b = strtoport(av, &s, 0, proto);
481			if (s == av) /* no parameter */
482				break;
483			p[0] = a;
484			p[1] = b;
485		} else if (*s == ',' || *s == '\0' ) {
486			p[0] = p[1] = a;
487		} else	/* invalid separator */
488			break;
489		av = s+1;
490	}
491	if (i > 0) {
492		if (i+1 > F_LEN_MASK)
493			errx(EX_DATAERR, "too many port range\n");
494		cmd->o.len |= i+1; /* leave F_NOT and F_OR untouched */
495	}
496	return i;
497}
498
499static struct _s_x icmpcodes[] = {
500      { "net",			ICMP_UNREACH_NET },
501      { "host",			ICMP_UNREACH_HOST },
502      { "protocol",		ICMP_UNREACH_PROTOCOL },
503      { "port",			ICMP_UNREACH_PORT },
504      { "needfrag",		ICMP_UNREACH_NEEDFRAG },
505      { "srcfail",		ICMP_UNREACH_SRCFAIL },
506      { "net-unknown",		ICMP_UNREACH_NET_UNKNOWN },
507      { "host-unknown",		ICMP_UNREACH_HOST_UNKNOWN },
508      { "isolated",		ICMP_UNREACH_ISOLATED },
509      { "net-prohib",		ICMP_UNREACH_NET_PROHIB },
510      { "host-prohib",		ICMP_UNREACH_HOST_PROHIB },
511      { "tosnet",		ICMP_UNREACH_TOSNET },
512      { "toshost",		ICMP_UNREACH_TOSHOST },
513      { "filter-prohib",	ICMP_UNREACH_FILTER_PROHIB },
514      { "host-precedence",	ICMP_UNREACH_HOST_PRECEDENCE },
515      { "precedence-cutoff",	ICMP_UNREACH_PRECEDENCE_CUTOFF },
516      { NULL, 0 }
517};
518
519static void
520fill_reject_code(u_short *codep, char *str)
521{
522	int val;
523	char *s;
524
525	val = strtoul(str, &s, 0);
526	if (s == str || *s != '\0' || val >= 0x100)
527		val = match_token(icmpcodes, str);
528	if (val <= 0)
529		errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
530	*codep = val;
531	return;
532}
533
534static void
535print_reject_code(u_int16_t code)
536{
537	char *s = match_value(icmpcodes, code);
538
539	if (s != NULL)
540		printf("unreach %s", s);
541	else
542		printf("unreach %u", code);
543}
544
545/*
546 * Returns the number of bits set (from left) in a contiguous bitmask,
547 * or -1 if the mask is not contiguous.
548 * XXX this needs a proper fix.
549 * This effectively works on masks in big-endian (network) format.
550 * when compiled on little endian architectures.
551 *
552 * First bit is bit 7 of the first byte -- note, for MAC addresses,
553 * the first bit on the wire is bit 0 of the first byte.
554 * len is the max length in bits.
555 */
556static int
557contigmask(u_char *p, int len)
558{
559	int i, n;
560	for (i=0; i<len ; i++)
561		if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
562			break;
563	for (n=i+1; n < len; n++)
564		if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
565			return -1; /* mask not contiguous */
566	return i;
567}
568
569/*
570 * print flags set/clear in the two bitmasks passed as parameters.
571 * There is a specialized check for f_tcpflags.
572 */
573static void
574print_flags(char *name, ipfw_insn *cmd, struct _s_x *list)
575{
576	char *comma="";
577	int i;
578	u_char set = cmd->arg1 & 0xff;
579	u_char clear = (cmd->arg1 >> 8) & 0xff;
580
581	if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
582		printf(" setup");
583		return;
584	}
585
586	printf(" %s ", name);
587	for (i=0; list[i].x != 0; i++) {
588		if (set & list[i].x) {
589			set &= ~list[i].x;
590			printf("%s%s", comma, list[i].s);
591			comma = ",";
592		}
593		if (clear & list[i].x) {
594			clear &= ~list[i].x;
595			printf("%s!%s", comma, list[i].s);
596			comma = ",";
597		}
598	}
599}
600
601/*
602 * Print the ip address contained in a command.
603 */
604static void
605print_ip(ipfw_insn_ip *cmd)
606{
607	struct hostent *he = NULL;
608	int mb;
609
610	printf("%s ", cmd->o.len & F_NOT ? " not": "");
611
612	if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
613		printf("me");
614		return;
615	}
616	if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
617		u_int32_t x, *d;
618		int i;
619		char comma = '{';
620
621		x = cmd->o.arg1 - 1;
622		x = htonl( ~x );
623		cmd->addr.s_addr = htonl(cmd->addr.s_addr);
624		printf("%s/%d", inet_ntoa(cmd->addr),
625			contigmask((u_char *)&x, 32));
626		x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
627		x &= 0xff; /* base */
628		d = (u_int32_t *)&(cmd->mask);
629		for (i=0; i < cmd->o.arg1; i++)
630			if (d[ i/32] & (1<<(i & 31))) {
631				printf("%c%d", comma, i+x);
632				comma = ',';
633			}
634		printf("}");
635		return;
636	}
637	if (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST)
638		mb = 32;
639	else
640		mb = contigmask((u_char *)&(cmd->mask.s_addr), 32);
641	if (mb == 32 && do_resolv)
642		he = gethostbyaddr((char *)&(cmd->addr.s_addr),
643		    sizeof(u_long), AF_INET);
644	if (he != NULL)		/* resolved to name */
645		printf("%s", he->h_name);
646	else if (mb == 0)	/* any */
647		printf("any");
648	else {		/* numeric IP followed by some kind of mask */
649		printf("%s", inet_ntoa(cmd->addr));
650		if (mb < 0)
651			printf(":%s", inet_ntoa(cmd->mask));
652		else if (mb < 32)
653			printf("/%d", mb);
654	}
655}
656
657/*
658 * prints a MAC address/mask pair
659 */
660static void
661print_mac(u_char *addr, u_char *mask)
662{
663	int l = contigmask(mask, 48);
664
665	if (l == 0)
666		printf(" any");
667	else {
668		printf(" %02x:%02x:%02x:%02x:%02x:%02x",
669		    addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
670		if (l == -1)
671			printf("&%02x:%02x:%02x:%02x:%02x:%02x",
672			    mask[0], mask[1], mask[2],
673			    mask[3], mask[4], mask[5]);
674		else if (l < 48)
675			printf("/%d", l);
676	}
677}
678
679static void
680fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
681{
682	u_int8_t type;
683
684	cmd->d[0] = 0;
685	while (*av) {
686		if (*av == ',')
687			av++;
688
689		type = strtoul(av, &av, 0);
690
691		if (*av != ',' && *av != '\0')
692			errx(EX_DATAERR, "invalid ICMP type");
693
694		if (type > 31)
695			errx(EX_DATAERR, "ICMP type out of range");
696
697		cmd->d[0] |= 1 << type;
698	}
699	cmd->o.opcode = O_ICMPTYPE;
700	cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
701}
702
703static void
704print_icmptypes(ipfw_insn_u32 *cmd)
705{
706	int i;
707	char sep= ' ';
708
709	printf(" icmptypes");
710	for (i = 0; i < 32; i++) {
711		if ( (cmd->d[0] & (1 << (i))) == 0)
712			continue;
713		printf("%c%d", sep, i);
714		sep = ',';
715	}
716}
717
718/*
719 * show_ipfw() prints the body of an ipfw rule.
720 * Because the standard rule has at least proto src_ip dst_ip, we use
721 * a helper function to produce these entries if not provided explicitly.
722 */
723#define	HAVE_PROTO	1
724#define	HAVE_SRCIP	2
725#define	HAVE_DSTIP	4
726#define	HAVE_MAC	8
727
728static void
729show_prerequisites(int *flags, int want)
730{
731	if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO))
732		printf(" ip");
733	if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
734		printf(" from any");
735	if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
736		printf(" to any");
737	*flags |= want;
738}
739
740static void
741show_ipfw(struct ip_fw *rule)
742{
743	int l;
744	ipfw_insn *cmd;
745	int proto = 0;		/* default */
746	int flags = 0;	/* prerequisites */
747	ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
748	int or_block = 0;	/* we are in an or block */
749
750	printf("%05u ", rule->rulenum);
751
752	if (do_acct)
753		printf("%10qu %10qu ", rule->pcnt, rule->bcnt);
754
755	if (do_time) {
756		if (rule->timestamp) {
757			char timestr[30];
758			time_t t = _long_to_time(rule->timestamp);
759
760			strcpy(timestr, ctime(&t));
761			*strchr(timestr, '\n') = '\0';
762			printf("%s ", timestr);
763		} else {
764			printf("			 ");
765		}
766	}
767
768	/*
769	 * first print actions
770	 */
771        for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
772			l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
773		switch(cmd->opcode) {
774		case O_CHECK_STATE:
775			printf("check-state");
776			/* avoid printing anything else */
777			flags = HAVE_PROTO|HAVE_SRCIP|HAVE_DSTIP;
778			break;
779
780		case O_PROB:
781		    {
782			ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
783			double d = 1.0 * p->d[0];
784
785			d = 1 - (d / 0x7fffffff);
786			printf("prob %f ", d);
787		    }
788			break;
789
790		case O_ACCEPT:
791			printf("allow");
792			break;
793
794		case O_COUNT:
795			printf("count");
796			break;
797
798		case O_DENY:
799			printf("deny");
800			break;
801
802		case O_REJECT:
803			if (cmd->arg1 == ICMP_REJECT_RST)
804				printf("reset");
805			else if (cmd->arg1 == ICMP_UNREACH_HOST)
806				printf("reject");
807			else
808				print_reject_code(cmd->arg1);
809			break;
810
811		case O_SKIPTO:
812			printf("skipto %u", cmd->arg1);
813			break;
814
815		case O_PIPE:
816			printf("pipe %u", cmd->arg1);
817			break;
818
819		case O_QUEUE:
820			printf("queue %u", cmd->arg1);
821			break;
822
823		case O_DIVERT:
824			printf("divert %u", cmd->arg1);
825			break;
826
827		case O_TEE:
828			printf("tee %u", cmd->arg1);
829			break;
830
831		case O_FORWARD_IP:
832		    {
833			ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
834
835			printf("fwd %s", inet_ntoa(s->sa.sin_addr));
836			if (s->sa.sin_port)
837				printf(",%d", ntohs(s->sa.sin_port));
838		    }
839			break;
840
841		case O_LOG: /* O_LOG is printed last */
842			logptr = (ipfw_insn_log *)cmd;
843			break;
844
845		default:
846			printf("** unrecognized action %d len %d",
847				cmd->opcode, cmd->len);
848		}
849	}
850	if (logptr) {
851		if (logptr->max_log > 0)
852			printf(" log logamount %d ", logptr->max_log);
853		else
854			printf(" log ");
855	}
856	/*
857	 * then print the body
858	 */
859        for (l = rule->act_ofs, cmd = rule->cmd ;
860			l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
861		/* useful alias */
862		ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
863
864		switch(cmd->opcode) {
865		case O_PROBE_STATE:
866			break; /* no need to print anything here */
867
868		case O_MACADDR2: {
869			ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
870			if ( (flags & HAVE_MAC) == 0)
871				printf(" MAC");
872			flags |= HAVE_MAC;
873			if (cmd->len & F_NOT)
874				printf(" not");
875			print_mac( m->addr, m->mask);
876			print_mac( m->addr + 6, m->mask + 6);
877			}
878			break;
879
880		case O_MAC_TYPE:
881			print_newports((ipfw_insn_u16 *)cmd, IPPROTO_ETHERTYPE);
882			break;
883
884		case O_IP_SRC:
885		case O_IP_SRC_MASK:
886		case O_IP_SRC_ME:
887		case O_IP_SRC_SET:
888			show_prerequisites(&flags, HAVE_PROTO);
889			if (!(flags & HAVE_SRCIP))
890				printf(" from");
891			if ((cmd->len & F_OR) && !or_block)
892				printf(" {");
893			print_ip((ipfw_insn_ip *)cmd);
894			flags |= HAVE_SRCIP;
895			break;
896
897		case O_IP_DST:
898		case O_IP_DST_MASK:
899		case O_IP_DST_ME:
900		case O_IP_DST_SET:
901			show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP);
902			if (!(flags & HAVE_DSTIP))
903				printf(" to");
904			if ((cmd->len & F_OR) && !or_block)
905				printf(" {");
906			print_ip((ipfw_insn_ip *)cmd);
907			flags |= HAVE_DSTIP;
908			break;
909
910		case O_IP_DSTPORT:
911			show_prerequisites(&flags,
912				HAVE_PROTO|HAVE_SRCIP|HAVE_DSTIP);
913		case O_IP_SRCPORT:
914			show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP);
915			print_newports((ipfw_insn_u16 *)cmd, proto);
916			break;
917
918		case O_PROTO: {
919			struct protoent *pe;
920
921			if ((cmd->len & F_OR) && !or_block)
922				printf(" {");
923			if (cmd->len & F_NOT)
924				printf(" not");
925			proto = cmd->arg1;
926			pe = getprotobynumber(cmd->arg1);
927			if (pe)
928				printf(" %s", pe->p_name);
929			else
930				printf(" %u", cmd->arg1);
931			}
932			flags |= HAVE_PROTO;
933			break;
934
935		default: /*options ... */
936			show_prerequisites(&flags,
937			    HAVE_PROTO|HAVE_SRCIP|HAVE_DSTIP);
938			if ((cmd->len & F_OR) && !or_block)
939				printf(" {");
940			if (cmd->len & F_NOT && cmd->opcode != O_IN)
941				printf(" not");
942			switch(cmd->opcode) {
943			case O_FRAG:
944				printf(" frag");
945				break;
946
947			case O_IN:
948				printf(cmd->len & F_NOT ? " out" : " in");
949				break;
950
951			case O_LAYER2:
952				printf(" layer2");
953				break;
954			case O_XMIT:
955			case O_RECV:
956			case O_VIA: {
957				char *s;
958				ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
959
960				if (cmd->opcode == O_XMIT)
961					s = "xmit";
962				else if (cmd->opcode == O_RECV)
963					s = "recv";
964				else if (cmd->opcode == O_VIA)
965					s = "via";
966				if (cmdif->name[0] == '\0')
967					printf(" %s %s", s,
968					    inet_ntoa(cmdif->p.ip));
969				else if (cmdif->p.unit == -1)
970					printf(" %s %s*", s, cmdif->name);
971				else
972					printf(" %s %s%d", s, cmdif->name,
973					    cmdif->p.unit);
974				}
975				break;
976
977			case O_IPID:
978				printf(" ipid %u", cmd->arg1 );
979				break;
980
981			case O_IPTTL:
982				printf(" ipttl %u", cmd->arg1 );
983				break;
984
985			case O_IPVER:
986				printf(" ipver %u", cmd->arg1 );
987				break;
988
989			case O_IPPRECEDENCE:
990				printf(" ipprecedence %u", (cmd->arg1) >> 5 );
991				break;
992
993			case O_IPLEN:
994				printf(" iplen %u", cmd->arg1 );
995				break;
996
997			case O_IPOPTS:
998				print_flags("ipoptions", cmd, f_ipopts);
999				break;
1000
1001			case O_IPTOS:
1002				print_flags("iptos", cmd, f_iptos);
1003				break;
1004
1005			case O_ICMPTYPE:
1006				print_icmptypes((ipfw_insn_u32 *)cmd);
1007				break;
1008
1009			case O_ESTAB:
1010				printf(" established");
1011				break;
1012
1013			case O_TCPFLAGS:
1014				print_flags("tcpflags", cmd, f_tcpflags);
1015				break;
1016
1017			case O_TCPOPTS:
1018				print_flags("tcpoptions", cmd, f_tcpopts);
1019				break;
1020
1021			case O_TCPWIN:
1022				printf(" tcpwin %d", ntohs(cmd->arg1));
1023				break;
1024
1025			case O_TCPACK:
1026				printf(" tcpack %d", ntohl(cmd32->d[0]));
1027				break;
1028
1029			case O_TCPSEQ:
1030				printf(" tcpseq %d", ntohl(cmd32->d[0]));
1031				break;
1032
1033			case O_UID:
1034			    {
1035				struct passwd *pwd = getpwuid(cmd32->d[0]);
1036
1037				if (pwd)
1038					printf(" uid %s", pwd->pw_name);
1039				else
1040					printf(" uid %u", cmd32->d[0]);
1041			    }
1042				break;
1043
1044			case O_GID:
1045			    {
1046				struct group *grp = getgrgid(cmd32->d[0]);
1047
1048				if (grp)
1049					printf(" gid %s", grp->gr_name);
1050				else
1051					printf(" gid %u", cmd32->d[0]);
1052			    }
1053				break;
1054
1055			case O_KEEP_STATE:
1056				printf(" keep-state");
1057				break;
1058
1059			case O_LIMIT:
1060			    {
1061				struct _s_x *p = limit_masks;
1062				ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1063				u_int8_t x = c->limit_mask;
1064				char *comma = " ";
1065
1066				printf(" limit");
1067				for ( ; p->x != 0 ; p++)
1068					if (x & p->x) {
1069						x &= ~p->x;
1070						printf("%s%s", comma, p->s);
1071						comma = ",";
1072					}
1073				printf(" %d", c->conn_limit);
1074			    }
1075				break;
1076
1077			default:
1078				printf(" [opcode %d len %d]",
1079				    cmd->opcode, cmd->len);
1080			}
1081		}
1082		if (cmd->len & F_OR) {
1083			printf(" or");
1084			or_block = 1;
1085		} else if (or_block) {
1086			printf(" }");
1087			or_block = 0;
1088		}
1089	}
1090	show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP|HAVE_DSTIP);
1091
1092	printf("\n");
1093}
1094
1095static void
1096show_dyn_ipfw(ipfw_dyn_rule *d)
1097{
1098	struct protoent *pe;
1099	struct in_addr a;
1100
1101	if (!do_expired) {
1102		if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1103			return;
1104	}
1105
1106	printf("%05d %10qu %10qu (%ds)",
1107	    (int)(d->rule), d->pcnt, d->bcnt, d->expire);
1108	switch (d->dyn_type) {
1109	case O_LIMIT_PARENT:
1110		printf(" PARENT %d", d->count);
1111		break;
1112	case O_LIMIT:
1113		printf(" LIMIT");
1114		break;
1115	case O_KEEP_STATE: /* bidir, no mask */
1116		printf(" STATE");
1117		break;
1118	}
1119
1120	if ((pe = getprotobynumber(d->id.proto)) != NULL)
1121		printf(" %s", pe->p_name);
1122	else
1123		printf(" proto %u", d->id.proto);
1124
1125	a.s_addr = htonl(d->id.src_ip);
1126	printf(" %s %d", inet_ntoa(a), d->id.src_port);
1127
1128	a.s_addr = htonl(d->id.dst_ip);
1129	printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
1130	printf("\n");
1131}
1132
1133int
1134sort_q(const void *pa, const void *pb)
1135{
1136	int rev = (do_sort < 0);
1137	int field = rev ? -do_sort : do_sort;
1138	long long res = 0;
1139	const struct dn_flow_queue *a = pa;
1140	const struct dn_flow_queue *b = pb;
1141
1142	switch (field) {
1143	case 1: /* pkts */
1144		res = a->len - b->len;
1145		break;
1146	case 2: /* bytes */
1147		res = a->len_bytes - b->len_bytes;
1148		break;
1149
1150	case 3: /* tot pkts */
1151		res = a->tot_pkts - b->tot_pkts;
1152		break;
1153
1154	case 4: /* tot bytes */
1155		res = a->tot_bytes - b->tot_bytes;
1156		break;
1157	}
1158	if (res < 0)
1159		res = -1;
1160	if (res > 0)
1161		res = 1;
1162	return (int)(rev ? res : -res);
1163}
1164
1165static void
1166list_queues(struct dn_flow_set *fs, struct dn_flow_queue *q)
1167{
1168	int l;
1169
1170	printf("    mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
1171	    fs->flow_mask.proto,
1172	    fs->flow_mask.src_ip, fs->flow_mask.src_port,
1173	    fs->flow_mask.dst_ip, fs->flow_mask.dst_port);
1174	if (fs->rq_elements == 0)
1175		return;
1176
1177	printf("BKT Prot ___Source IP/port____ "
1178	    "____Dest. IP/port____ Tot_pkt/bytes Pkt/Byte Drp\n");
1179	if (do_sort != 0)
1180		heapsort(q, fs->rq_elements, sizeof *q, sort_q);
1181	for (l = 0; l < fs->rq_elements; l++) {
1182		struct in_addr ina;
1183		struct protoent *pe;
1184
1185		ina.s_addr = htonl(q[l].id.src_ip);
1186		printf("%3d ", q[l].hash_slot);
1187		pe = getprotobynumber(q[l].id.proto);
1188		if (pe)
1189			printf("%-4s ", pe->p_name);
1190		else
1191			printf("%4u ", q[l].id.proto);
1192		printf("%15s/%-5d ",
1193		    inet_ntoa(ina), q[l].id.src_port);
1194		ina.s_addr = htonl(q[l].id.dst_ip);
1195		printf("%15s/%-5d ",
1196		    inet_ntoa(ina), q[l].id.dst_port);
1197		printf("%4qu %8qu %2u %4u %3u\n",
1198		    q[l].tot_pkts, q[l].tot_bytes,
1199		    q[l].len, q[l].len_bytes, q[l].drops);
1200		if (verbose)
1201			printf("   S %20qd  F %20qd\n",
1202			    q[l].S, q[l].F);
1203	}
1204}
1205
1206static void
1207print_flowset_parms(struct dn_flow_set *fs, char *prefix)
1208{
1209	int l;
1210	char qs[30];
1211	char plr[30];
1212	char red[90];	/* Display RED parameters */
1213
1214	l = fs->qsize;
1215	if (fs->flags_fs & DN_QSIZE_IS_BYTES) {
1216		if (l >= 8192)
1217			sprintf(qs, "%d KB", l / 1024);
1218		else
1219			sprintf(qs, "%d B", l);
1220	} else
1221		sprintf(qs, "%3d sl.", l);
1222	if (fs->plr)
1223		sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
1224	else
1225		plr[0] = '\0';
1226	if (fs->flags_fs & DN_IS_RED)	/* RED parameters */
1227		sprintf(red,
1228		    "\n\t  %cRED w_q %f min_th %d max_th %d max_p %f",
1229		    (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ',
1230		    1.0 * fs->w_q / (double)(1 << SCALE_RED),
1231		    SCALE_VAL(fs->min_th),
1232		    SCALE_VAL(fs->max_th),
1233		    1.0 * fs->max_p / (double)(1 << SCALE_RED));
1234	else
1235		sprintf(red, "droptail");
1236
1237	printf("%s %s%s %d queues (%d buckets) %s\n",
1238	    prefix, qs, plr, fs->rq_elements, fs->rq_size, red);
1239}
1240
1241static void
1242list_pipes(void *data, int nbytes, int ac, char *av[])
1243{
1244	u_long rulenum;
1245	void *next = data;
1246	struct dn_pipe *p = (struct dn_pipe *) data;
1247	struct dn_flow_set *fs;
1248	struct dn_flow_queue *q;
1249	int l;
1250
1251	if (ac > 0)
1252		rulenum = strtoul(*av++, NULL, 10);
1253	else
1254		rulenum = 0;
1255	for (; nbytes >= sizeof *p; p = (struct dn_pipe *)next) {
1256		double b = p->bandwidth;
1257		char buf[30];
1258		char prefix[80];
1259
1260		if (p->next != (struct dn_pipe *)DN_IS_PIPE)
1261			break;	/* done with pipes, now queues */
1262
1263		/*
1264		 * compute length, as pipe have variable size
1265		 */
1266		l = sizeof(*p) + p->fs.rq_elements * sizeof(*q);
1267		next = (void *)p + l;
1268		nbytes -= l;
1269
1270		if (rulenum != 0 && rulenum != p->pipe_nr)
1271			continue;
1272
1273		/*
1274		 * Print rate (or clocking interface)
1275		 */
1276		if (p->if_name[0] != '\0')
1277			sprintf(buf, "%s", p->if_name);
1278		else if (b == 0)
1279			sprintf(buf, "unlimited");
1280		else if (b >= 1000000)
1281			sprintf(buf, "%7.3f Mbit/s", b/1000000);
1282		else if (b >= 1000)
1283			sprintf(buf, "%7.3f Kbit/s", b/1000);
1284		else
1285			sprintf(buf, "%7.3f bit/s ", b);
1286
1287		sprintf(prefix, "%05d: %s %4d ms ",
1288		    p->pipe_nr, buf, p->delay);
1289		print_flowset_parms(&(p->fs), prefix);
1290		if (verbose)
1291			printf("   V %20qd\n", p->V >> MY_M);
1292
1293		q = (struct dn_flow_queue *)(p+1);
1294		list_queues(&(p->fs), q);
1295	}
1296	for (fs = next; nbytes >= sizeof *fs; fs = next) {
1297		char prefix[80];
1298
1299		if (fs->next != (struct dn_flow_set *)DN_IS_QUEUE)
1300			break;
1301		l = sizeof(*fs) + fs->rq_elements * sizeof(*q);
1302		next = (void *)fs + l;
1303		nbytes -= l;
1304		q = (struct dn_flow_queue *)(fs+1);
1305		sprintf(prefix, "q%05d: weight %d pipe %d ",
1306		    fs->fs_nr, fs->weight, fs->parent_nr);
1307		print_flowset_parms(fs, prefix);
1308		list_queues(fs, q);
1309	}
1310}
1311
1312static void
1313list(int ac, char *av[])
1314{
1315	struct ip_fw *r;
1316	ipfw_dyn_rule *dynrules, *d;
1317
1318	void *lim, *data = NULL;
1319	int n, nbytes, nstat, ndyn;
1320	int exitval = EX_OK;
1321	int lac;
1322	char **lav;
1323	u_long rnum;
1324	char *endptr;
1325	int seen = 0;
1326
1327	const int ocmd = do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
1328	int nalloc = 1024;	/* start somewhere... */
1329
1330	ac--;
1331	av++;
1332
1333	/* get rules or pipes from kernel, resizing array as necessary */
1334	nbytes = nalloc;
1335
1336	while (nbytes >= nalloc) {
1337		nalloc = nalloc * 2 + 200;
1338		nbytes = nalloc;
1339		if ((data = realloc(data, nbytes)) == NULL)
1340			err(EX_OSERR, "realloc");
1341		if (getsockopt(s, IPPROTO_IP, ocmd, data, &nbytes) < 0)
1342			err(EX_OSERR, "getsockopt(IP_%s_GET)",
1343				do_pipe ? "DUMMYNET" : "FW");
1344	}
1345
1346	if (do_pipe) {
1347		list_pipes(data, nbytes, ac, av);
1348		goto done;
1349	}
1350
1351	/*
1352	 * Count static rules. They have variable size so we
1353	 * need to scan the list to count them.
1354	 */
1355	for (nstat = 1, r = data, lim = data + nbytes;
1356		    r->rulenum < 65535 && (void *)r < lim;
1357		    ++nstat, r = (void *)r + RULESIZE(r) )
1358		; /* nothing */
1359
1360	/*
1361	 * Count dynamic rules. This is easier as they have
1362	 * fixed size.
1363	 */
1364	r = (void *)r + RULESIZE(r);
1365	dynrules = (ipfw_dyn_rule *)r ;
1366	n = (void *)r - data;
1367	ndyn = (nbytes - n) / sizeof *dynrules;
1368
1369	/* if no rule numbers were specified, list all rules */
1370	if (ac == 0) {
1371		for (n = 0, r = data; n < nstat;
1372		    n++, r = (void *)r + RULESIZE(r) )
1373			show_ipfw(r);
1374
1375		if (do_dynamic && ndyn) {
1376			printf("## Dynamic rules (%d):\n", ndyn);
1377			for (n = 0, d = dynrules; n < ndyn; n++, d++)
1378				show_dyn_ipfw(d);
1379		}
1380		goto done;
1381	}
1382
1383	/* display specific rules requested on command line */
1384
1385	for (lac = ac, lav = av; lac != 0; lac--) {
1386		/* convert command line rule # */
1387		rnum = strtoul(*lav++, &endptr, 10);
1388		if (*endptr) {
1389			exitval = EX_USAGE;
1390			warnx("invalid rule number: %s", *(lav - 1));
1391			continue;
1392		}
1393		for (n = seen = 0, r = data; n < nstat;
1394		    n++, r = (void *)r + RULESIZE(r) ) {
1395			if (r->rulenum > rnum)
1396				break;
1397			if (r->rulenum == rnum) {
1398				show_ipfw(r);
1399				seen = 1;
1400			}
1401		}
1402		if (!seen) {
1403			/* give precedence to other error(s) */
1404			if (exitval == EX_OK)
1405				exitval = EX_UNAVAILABLE;
1406			warnx("rule %lu does not exist", rnum);
1407		}
1408	}
1409
1410	if (do_dynamic && ndyn) {
1411		printf("## Dynamic rules:\n");
1412		for (lac = ac, lav = av; lac != 0; lac--) {
1413			rnum = strtoul(*lav++, &endptr, 10);
1414			if (*endptr)
1415				/* already warned */
1416				continue;
1417			for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1418				if ((int)(d->rule) > rnum)
1419					break;
1420				if ((int)(d->rule) == rnum)
1421					show_dyn_ipfw(d);
1422			}
1423		}
1424	}
1425
1426	ac = 0;
1427
1428done:
1429	free(data);
1430
1431	if (exitval != EX_OK)
1432		exit(exitval);
1433}
1434
1435static void
1436show_usage(void)
1437{
1438	fprintf(stderr, "usage: ipfw [options]\n"
1439"    add [number] rule\n"
1440"    pipe number config [pipeconfig]\n"
1441"    queue number config [queueconfig]\n"
1442"    [pipe] flush\n"
1443"    [pipe] delete number ...\n"
1444"    [pipe] {list|show} [number ...]\n"
1445"    {zero|resetlog} [number ...]\n"
1446"do \"ipfw -h\" or see ipfw manpage for details\n"
1447);
1448
1449	exit(EX_USAGE);
1450}
1451
1452static void
1453help(void)
1454{
1455
1456	fprintf(stderr, "ipfw syntax summary:\n"
1457"ipfw add [N] [prob {0..1}] ACTION [log [logamount N]] ADDR OPTIONS\n"
1458"ipfw {pipe|queue} N config BODY\n"
1459"ipfw [pipe] {zero|delete|show} [N{,N}]\n"
1460"\n"
1461"RULE:		[1..] [PROB] BODY\n"
1462"RULENUM:	INTEGER(1..65534)\n"
1463"PROB:		prob REAL(0..1)\n"
1464"BODY:		check-state [LOG] (no body) |\n"
1465"		ACTION [LOG] MATCH_ADDR [OPTION_LIST]\n"
1466"ACTION:	check-state | allow | count | deny | reject | skipto N |\n"
1467"		{divert|tee} PORT | forward ADDR | pipe N | queue N\n"
1468"ADDR:		[ MAC dst src ether_type ] \n"
1469"		[ from IPLIST [ PORT ] to IPLIST [ PORTLIST ] ]\n"
1470"IPLIST:	IPADDR | ( IPADDR or ... or IPADDR )\n"
1471"IPADDR:	[not] { any | me | ip | ip/bits | ip:mask | ip/bits{x,y,z} }\n"
1472"OPTION_LIST:	OPTION [,OPTION_LIST]\n"
1473);
1474exit(0);
1475}
1476
1477
1478static int
1479lookup_host (char *host, struct in_addr *ipaddr)
1480{
1481	struct hostent *he;
1482
1483	if (!inet_aton(host, ipaddr)) {
1484		if ((he = gethostbyname(host)) == NULL)
1485			return(-1);
1486		*ipaddr = *(struct in_addr *)he->h_addr_list[0];
1487	}
1488	return(0);
1489}
1490
1491/*
1492 * fills the addr and mask fields in the instruction as appropriate from av.
1493 * Update length as appropriate.
1494 * The following formats are allowed:
1495 *	any	matches any IP. Actually returns an empty instruction.
1496 *	me	returns O_IP_*_ME
1497 *	1.2.3.4		single IP address
1498 *	1.2.3.4:5.6.7.8	address:mask
1499 *	1.2.3.4/24	address/mask
1500 *	1.2.3.4/26{1,6,5,4,23}	set of addresses in a subnet
1501 */
1502static void
1503fill_ip(ipfw_insn_ip *cmd, char *av)
1504{
1505	char *p = 0, md = 0;
1506	u_int32_t i;
1507
1508	cmd->o.len &= ~F_LEN_MASK;	/* zero len */
1509
1510	if (!strncmp(av, "any", strlen(av)))
1511		return;
1512
1513	if (!strncmp(av, "me", strlen(av))) {
1514		cmd->o.len |= F_INSN_SIZE(ipfw_insn);
1515		return;
1516	}
1517
1518	p = strchr(av, '/');
1519	if (!p)
1520		p = strchr(av, ':');
1521	if (p) {
1522		md = *p;
1523		*p++ = '\0';
1524	}
1525
1526	if (lookup_host(av, &cmd->addr) != 0)
1527		errx(EX_NOHOST, "hostname ``%s'' unknown", av);
1528	switch (md) {
1529	case ':':
1530		if (!inet_aton(p, &cmd->mask))
1531			errx(EX_DATAERR, "bad netmask ``%s''", p);
1532		break;
1533	case '/':
1534		i = atoi(p);
1535		if (i == 0)
1536			cmd->mask.s_addr = htonl(0);
1537		else if (i > 32)
1538			errx(EX_DATAERR, "bad width ``%s''", p);
1539		else
1540			cmd->mask.s_addr = htonl(~0 << (32 - i));
1541		break;
1542	default:
1543		cmd->mask.s_addr = htonl(~0);
1544		break;
1545	}
1546	cmd->addr.s_addr &= cmd->mask.s_addr;
1547	/*
1548	 * now look if we have a set of addresses. They are stored as follows:
1549	 *   arg1	is the set size (powers of 2, 2..256)
1550	 *   addr	is the base address IN HOST FORMAT
1551	 *   mask..	is an array of u_int32_t with bits set.
1552	 */
1553	if (p)
1554		p = strchr(p, '{');
1555	if (p) {	/* fetch addresses */
1556		u_int32_t *d;
1557		int low, high;
1558		int i = contigmask((u_char *)&(cmd->mask), 32);
1559
1560		if (i < 24 || i > 31) {
1561			fprintf(stderr, "invalid set with mask %d\n",
1562				i);
1563			exit(0);
1564		}
1565		cmd->o.arg1 = 1<<(32-i);
1566		cmd->addr.s_addr = ntohl(cmd->addr.s_addr);
1567		d = (u_int32_t *)&cmd->mask;
1568		cmd->o.opcode = O_IP_DST_SET;	/* default */
1569		cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
1570		fprintf(stderr,"-- set size %d cmdlen %d\n",
1571			cmd->o.arg1, cmd->o.len );
1572		for (i = 0; i < cmd->o.arg1/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[1], &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	int have_state = 0;	/* 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 = 1;
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) {
2346		have_state = 0;
2347		goto done;
2348	}
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_IPOPTS, f_ipopts, *av);
2612			ac--; av++;
2613			break;
2614
2615		case TOK_IPTOS:
2616			NEED1("missing argument for iptos");
2617			fill_flags(cmd, O_IPOPTS, 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			have_state = 1;
2698			fill_cmd(cmd, O_KEEP_STATE, 0, 0);
2699			break;
2700
2701		case TOK_LIMIT:
2702			NEED1("limit needs mask and # of connections");
2703		    {
2704			ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
2705
2706			cmd->len = F_INSN_SIZE(ipfw_insn_limit);
2707			cmd->opcode = O_LIMIT;
2708			c->limit_mask = 0;
2709			c->conn_limit = 0;
2710			for (; ac >1 ;) {
2711				int val;
2712
2713				val = match_token(limit_masks, *av);
2714				if (val <= 0)
2715					break;
2716				c->limit_mask |= val;
2717				ac--; av++;
2718			}
2719			c->conn_limit = atoi(*av);
2720			if (c->conn_limit == 0)
2721				errx(EX_USAGE, "limit: limit must be >0");
2722			if (c->limit_mask == 0)
2723				errx(EX_USAGE, "missing limit mask");
2724			ac--; av++;
2725			have_state = 1;
2726		    }
2727			break;
2728
2729		default:
2730			errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
2731		}
2732		if (F_LEN(cmd) > 0) {	/* prepare to advance */
2733			prev = cmd;
2734			cmd = next_cmd(cmd);
2735		}
2736	}
2737
2738done:
2739	/*
2740	 * Now copy stuff into the rule.
2741	 * If we have a keep-state option, the first instruction
2742	 * must be a PROBE_STATE (which is generated here).
2743	 * If we have a LOG option, it was stored as the first command,
2744	 * and now must be moved to the top of the action part.
2745	 */
2746	dst = (ipfw_insn *)rule->cmd;
2747
2748	/*
2749	 * generate O_PROBE_STATE if necessary
2750	 */
2751	if (have_state) {
2752		fill_cmd(dst, O_PROBE_STATE, 0, 0);
2753		dst = next_cmd(dst);
2754	}
2755	/*
2756	 * copy all commands but O_LOG
2757	 */
2758	for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
2759		i = F_LEN(src);
2760
2761		if (src->opcode != O_LOG) {
2762			bcopy(src, dst, i * sizeof(u_int32_t));
2763			dst += i;
2764		}
2765	}
2766
2767	/*
2768	 * start action section
2769	 */
2770	rule->act_ofs = dst - rule->cmd;
2771
2772	/*
2773	 * put back O_LOG if necessary
2774	 */
2775	src = (ipfw_insn *)cmdbuf;
2776	if ( src->opcode == O_LOG ) {
2777		i = F_LEN(src);
2778		bcopy(src, dst, i * sizeof(u_int32_t));
2779		dst += i;
2780	}
2781	/*
2782	 * copy all other actions
2783	 */
2784	for (src = (ipfw_insn *)actbuf; src != action; src += i) {
2785		i = F_LEN(src);
2786		bcopy(src, dst, i * sizeof(u_int32_t));
2787		dst += i;
2788	}
2789
2790	rule->cmd_len = (u_int32_t *)dst - (u_int32_t *)(rule->cmd);
2791	i = (void *)dst - (void *)rule;
2792	if (!do_quiet)
2793		show_ipfw(rule);
2794	if (getsockopt(s, IPPROTO_IP, IP_FW_ADD, rule, &i) == -1)
2795		err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
2796	if (!do_quiet)
2797		show_ipfw(rule);
2798}
2799
2800static void
2801zero (int ac, char *av[])
2802{
2803	int rulenum;
2804	int failed = EX_OK;
2805
2806	av++; ac--;
2807
2808	if (!ac) {
2809		/* clear all entries */
2810		if (setsockopt(s, IPPROTO_IP, IP_FW_ZERO, NULL, 0) < 0)
2811			err(EX_UNAVAILABLE, "setsockopt(%s)", "IP_FW_ZERO");
2812		if (!do_quiet)
2813			printf("Accounting cleared.\n");
2814
2815		return;
2816	}
2817
2818	while (ac) {
2819		/* Rule number */
2820		if (isdigit(**av)) {
2821			rulenum = atoi(*av);
2822			av++;
2823			ac--;
2824			if (setsockopt(s, IPPROTO_IP,
2825			    IP_FW_ZERO, &rulenum, sizeof rulenum)) {
2826				warn("rule %u: setsockopt(IP_FW_ZERO)",
2827				    rulenum);
2828				failed = EX_UNAVAILABLE;
2829			} else if (!do_quiet)
2830				printf("Entry %d cleared\n", rulenum);
2831		} else {
2832			errx(EX_USAGE, "invalid rule number ``%s''", *av);
2833		}
2834	}
2835	if (failed != EX_OK)
2836		exit(failed);
2837}
2838
2839static void
2840resetlog (int ac, char *av[])
2841{
2842	int rulenum;
2843	int failed = EX_OK;
2844
2845	av++; ac--;
2846
2847	if (!ac) {
2848		/* clear all entries */
2849		if (setsockopt(s, IPPROTO_IP, IP_FW_RESETLOG, NULL, 0) < 0)
2850			err(EX_UNAVAILABLE, "setsockopt(IP_FW_RESETLOG)");
2851		if (!do_quiet)
2852			printf("Logging counts reset.\n");
2853
2854		return;
2855	}
2856
2857	while (ac) {
2858		/* Rule number */
2859		if (isdigit(**av)) {
2860			rulenum = atoi(*av);
2861			av++;
2862			ac--;
2863			if (setsockopt(s, IPPROTO_IP,
2864			    IP_FW_RESETLOG, &rulenum, sizeof rulenum)) {
2865				warn("rule %u: setsockopt(IP_FW_RESETLOG)",
2866				    rulenum);
2867				failed = EX_UNAVAILABLE;
2868			} else if (!do_quiet)
2869				printf("Entry %d logging count reset\n",
2870				    rulenum);
2871		} else {
2872			errx(EX_DATAERR, "invalid rule number ``%s''", *av);
2873		}
2874	}
2875	if (failed != EX_OK)
2876		exit(failed);
2877}
2878
2879static void
2880flush()
2881{
2882	int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
2883
2884	if (!do_force && !do_quiet) { /* need to ask user */
2885		int c;
2886
2887		printf("Are you sure? [yn] ");
2888		fflush(stdout);
2889		do {
2890			c = toupper(getc(stdin));
2891			while (c != '\n' && getc(stdin) != '\n')
2892				if (feof(stdin))
2893					return; /* and do not flush */
2894		} while (c != 'Y' && c != 'N');
2895		printf("\n");
2896		if (c == 'N')	/* user said no */
2897			return;
2898	}
2899	if (setsockopt(s, IPPROTO_IP, cmd, NULL, 0) < 0)
2900		err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
2901		    do_pipe ? "DUMMYNET" : "FW");
2902	if (!do_quiet)
2903		printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules");
2904}
2905
2906static int
2907ipfw_main(int ac, char **av)
2908{
2909	int ch;
2910
2911	if (ac == 1)
2912		show_usage();
2913
2914	/* Set the force flag for non-interactive processes */
2915	do_force = !isatty(STDIN_FILENO);
2916
2917	optind = optreset = 1;
2918	while ((ch = getopt(ac, av, "hs:adefNqtv")) != -1)
2919		switch (ch) {
2920		case 'h': /* help */
2921			help();
2922			break;	/* NOTREACHED */
2923
2924		case 's': /* sort */
2925			do_sort = atoi(optarg);
2926			break;
2927		case 'a':
2928			do_acct = 1;
2929			break;
2930		case 'd':
2931			do_dynamic = 1;
2932			break;
2933		case 'e':
2934			do_expired = 1;
2935			break;
2936		case 'f':
2937			do_force = 1;
2938			break;
2939		case 'N':
2940			do_resolv = 1;
2941			break;
2942		case 'q':
2943			do_quiet = 1;
2944			break;
2945		case 't':
2946			do_time = 1;
2947			break;
2948		case 'v': /* verbose */
2949			verbose++;
2950			break;
2951		default:
2952			show_usage();
2953		}
2954
2955	ac -= optind;
2956	av += optind;
2957	NEED1("bad arguments, for usage summary ``ipfw''");
2958
2959	/*
2960	 * optional: pipe or queue
2961	 */
2962	if (!strncmp(*av, "pipe", strlen(*av))) {
2963		do_pipe = 1;
2964		ac--;
2965		av++;
2966	} else if (!strncmp(*av, "queue", strlen(*av))) {
2967		do_pipe = 2;
2968		ac--;
2969		av++;
2970	}
2971	NEED1("missing command");
2972
2973	/*
2974	 * for pipes and queues we normally say 'pipe NN config'
2975	 * but the code is easier to parse as 'pipe config NN'
2976	 * so we swap the two arguments.
2977	 */
2978	if (do_pipe > 0 && ac > 1 && *av[0] >= '0' && *av[0] <= '9') {
2979		char *p = av[0];
2980		av[0] = av[1];
2981		av[1] = p;
2982	}
2983	if (!strncmp(*av, "add", strlen(*av)))
2984		add(ac, av);
2985	else if (do_pipe && !strncmp(*av, "config", strlen(*av)))
2986		config_pipe(ac, av);
2987	else if (!strncmp(*av, "delete", strlen(*av)))
2988		delete(ac, av);
2989	else if (!strncmp(*av, "flush", strlen(*av)))
2990		flush();
2991	else if (!strncmp(*av, "zero", strlen(*av)))
2992		zero(ac, av);
2993	else if (!strncmp(*av, "resetlog", strlen(*av)))
2994		resetlog(ac, av);
2995	else if (!strncmp(*av, "print", strlen(*av)) ||
2996	         !strncmp(*av, "list", strlen(*av)))
2997		list(ac, av);
2998	else if (!strncmp(*av, "show", strlen(*av))) {
2999		do_acct++;
3000		list(ac, av);
3001	} else
3002		errx(EX_USAGE, "bad command `%s'", *av);
3003	return 0;
3004}
3005
3006
3007static void
3008ipfw_readfile(int ac, char *av[])
3009{
3010#define MAX_ARGS	32
3011#define WHITESP		" \t\f\v\n\r"
3012	char	buf[BUFSIZ];
3013	char	*a, *p, *args[MAX_ARGS], *cmd = NULL;
3014	char	linename[10];
3015	int	i=0, lineno=0, qflag=0, pflag=0, status;
3016	FILE	*f = NULL;
3017	pid_t	preproc = 0;
3018	int	c;
3019
3020	while ((c = getopt(ac, av, "D:U:p:q")) != -1)
3021		switch(c) {
3022		case 'D':
3023			if (!pflag)
3024				errx(EX_USAGE, "-D requires -p");
3025			if (i > MAX_ARGS - 2)
3026				errx(EX_USAGE,
3027				     "too many -D or -U options");
3028			args[i++] = "-D";
3029			args[i++] = optarg;
3030			break;
3031
3032		case 'U':
3033			if (!pflag)
3034				errx(EX_USAGE, "-U requires -p");
3035			if (i > MAX_ARGS - 2)
3036				errx(EX_USAGE,
3037				     "too many -D or -U options");
3038			args[i++] = "-U";
3039			args[i++] = optarg;
3040			break;
3041
3042		case 'p':
3043			pflag = 1;
3044			cmd = optarg;
3045			args[0] = cmd;
3046			i = 1;
3047			break;
3048
3049		case 'q':
3050			qflag = 1;
3051			break;
3052
3053		default:
3054			errx(EX_USAGE, "bad arguments, for usage"
3055			     " summary ``ipfw''");
3056		}
3057
3058	av += optind;
3059	ac -= optind;
3060	if (ac != 1)
3061		errx(EX_USAGE, "extraneous filename arguments");
3062
3063	if ((f = fopen(av[0], "r")) == NULL)
3064		err(EX_UNAVAILABLE, "fopen: %s", av[0]);
3065
3066	if (pflag) {
3067		/* pipe through preprocessor (cpp or m4) */
3068		int pipedes[2];
3069
3070		args[i] = 0;
3071
3072		if (pipe(pipedes) == -1)
3073			err(EX_OSERR, "cannot create pipe");
3074
3075		switch((preproc = fork())) {
3076		case -1:
3077			err(EX_OSERR, "cannot fork");
3078
3079		case 0:
3080			/* child */
3081			if (dup2(fileno(f), 0) == -1
3082			    || dup2(pipedes[1], 1) == -1)
3083				err(EX_OSERR, "dup2()");
3084			fclose(f);
3085			close(pipedes[1]);
3086			close(pipedes[0]);
3087			execvp(cmd, args);
3088			err(EX_OSERR, "execvp(%s) failed", cmd);
3089
3090		default:
3091			/* parent */
3092			fclose(f);
3093			close(pipedes[1]);
3094			if ((f = fdopen(pipedes[0], "r")) == NULL) {
3095				int savederrno = errno;
3096
3097				(void)kill(preproc, SIGTERM);
3098				errno = savederrno;
3099				err(EX_OSERR, "fdopen()");
3100			}
3101		}
3102	}
3103
3104	while (fgets(buf, BUFSIZ, f)) {
3105		lineno++;
3106		sprintf(linename, "Line %d", lineno);
3107		args[0] = linename;
3108
3109		if (*buf == '#')
3110			continue;
3111		if ((p = strchr(buf, '#')) != NULL)
3112			*p = '\0';
3113		i = 1;
3114		if (qflag)
3115			args[i++] = "-q";
3116		for (a = strtok(buf, WHITESP);
3117		    a && i < MAX_ARGS; a = strtok(NULL, WHITESP), i++)
3118			args[i] = a;
3119		if (i == (qflag? 2: 1))
3120			continue;
3121		if (i == MAX_ARGS)
3122			errx(EX_USAGE, "%s: too many arguments",
3123			    linename);
3124		args[i] = NULL;
3125
3126		ipfw_main(i, args);
3127	}
3128	fclose(f);
3129	if (pflag) {
3130		if (waitpid(preproc, &status, 0) == -1)
3131			errx(EX_OSERR, "waitpid()");
3132		if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
3133			errx(EX_UNAVAILABLE,
3134			    "preprocessor exited with status %d",
3135			    WEXITSTATUS(status));
3136		else if (WIFSIGNALED(status))
3137			errx(EX_UNAVAILABLE,
3138			    "preprocessor exited with signal %d",
3139			    WTERMSIG(status));
3140	}
3141}
3142
3143int
3144main(int ac, char *av[])
3145{
3146	s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
3147	if (s < 0)
3148		err(EX_UNAVAILABLE, "socket");
3149
3150	setbuf(stdout, 0);
3151
3152	/*
3153	 * If the last argument is an absolute pathname, interpret it
3154	 * as a file to be preprocessed.
3155	 */
3156
3157	if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0)
3158		ipfw_readfile(ac, av);
3159	else
3160		ipfw_main(ac, av);
3161	return EX_OK;
3162}
3163