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