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