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