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