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