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