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