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