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