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