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