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