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