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