ipfw2.c revision 327518
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: stable/11/sbin/ipfw/ipfw2.c 327518 2018-01-03 12:18:55Z ae $
21 */
22
23#include <sys/types.h>
24#include <sys/param.h>
25#include <sys/socket.h>
26#include <sys/sockio.h>
27#include <sys/sysctl.h>
28
29#include "ipfw2.h"
30
31#include <ctype.h>
32#include <err.h>
33#include <errno.h>
34#include <grp.h>
35#include <netdb.h>
36#include <pwd.h>
37#include <stdio.h>
38#include <stdarg.h>
39#include <stdint.h>
40#include <stdlib.h>
41#include <string.h>
42#include <sysexits.h>
43#include <time.h>	/* ctime */
44#include <timeconv.h>	/* _long_to_time */
45#include <unistd.h>
46#include <fcntl.h>
47#include <stddef.h>	/* offsetof */
48
49#include <net/ethernet.h>
50#include <net/if.h>		/* only IFNAMSIZ */
51#include <netinet/in.h>
52#include <netinet/in_systm.h>	/* only n_short, n_long */
53#include <netinet/ip.h>
54#include <netinet/ip_icmp.h>
55#include <netinet/ip_fw.h>
56#include <netinet/tcp.h>
57#include <arpa/inet.h>
58
59struct cmdline_opts co;	/* global options */
60
61struct format_opts {
62	int bcwidth;
63	int pcwidth;
64	int show_counters;
65	int show_time;		/* show timestamp */
66	uint32_t set_mask;	/* enabled sets mask */
67	uint32_t flags;		/* request flags */
68	uint32_t first;		/* first rule to request */
69	uint32_t last;		/* last rule to request */
70	uint32_t dcnt;		/* number of dynamic states */
71	ipfw_obj_ctlv *tstate;	/* table state data */
72};
73
74int resvd_set_number = RESVD_SET;
75
76int ipfw_socket = -1;
77
78#define	CHECK_LENGTH(v, len) do {				\
79	if ((v) < (len))					\
80		errx(EX_DATAERR, "Rule too long");		\
81	} while (0)
82/*
83 * Check if we have enough space in cmd buffer. Note that since
84 * first 8? u32 words are reserved by reserved header, full cmd
85 * buffer can't be used, so we need to protect from buffer overrun
86 * only. At the beginning, cblen is less than actual buffer size by
87 * size of ipfw_insn_u32 instruction + 1 u32 work. This eliminates need
88 * for checking small instructions fitting in given range.
89 * We also (ab)use the fact that ipfw_insn is always the first field
90 * for any custom instruction.
91 */
92#define	CHECK_CMDLEN	CHECK_LENGTH(cblen, F_LEN((ipfw_insn *)cmd))
93
94#define GET_UINT_ARG(arg, min, max, tok, s_x) do {			\
95	if (!av[0])							\
96		errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
97	if (_substrcmp(*av, "tablearg") == 0) {				\
98		arg = IP_FW_TARG;					\
99		break;							\
100	}								\
101									\
102	{								\
103	long _xval;							\
104	char *end;							\
105									\
106	_xval = strtol(*av, &end, 10);					\
107									\
108	if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
109		errx(EX_DATAERR, "%s: invalid argument: %s",		\
110		    match_value(s_x, tok), *av);			\
111									\
112	if (errno == ERANGE || _xval < min || _xval > max)		\
113		errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
114		    match_value(s_x, tok), min, max, *av);		\
115									\
116	if (_xval == IP_FW_TARG)					\
117		errx(EX_DATAERR, "%s: illegal argument value: %s",	\
118		    match_value(s_x, tok), *av);			\
119	arg = _xval;							\
120	}								\
121} while (0)
122
123static struct _s_x f_tcpflags[] = {
124	{ "syn", TH_SYN },
125	{ "fin", TH_FIN },
126	{ "ack", TH_ACK },
127	{ "psh", TH_PUSH },
128	{ "rst", TH_RST },
129	{ "urg", TH_URG },
130	{ "tcp flag", 0 },
131	{ NULL,	0 }
132};
133
134static struct _s_x f_tcpopts[] = {
135	{ "mss",	IP_FW_TCPOPT_MSS },
136	{ "maxseg",	IP_FW_TCPOPT_MSS },
137	{ "window",	IP_FW_TCPOPT_WINDOW },
138	{ "sack",	IP_FW_TCPOPT_SACK },
139	{ "ts",		IP_FW_TCPOPT_TS },
140	{ "timestamp",	IP_FW_TCPOPT_TS },
141	{ "cc",		IP_FW_TCPOPT_CC },
142	{ "tcp option",	0 },
143	{ NULL,	0 }
144};
145
146/*
147 * IP options span the range 0 to 255 so we need to remap them
148 * (though in fact only the low 5 bits are significant).
149 */
150static struct _s_x f_ipopts[] = {
151	{ "ssrr",	IP_FW_IPOPT_SSRR},
152	{ "lsrr",	IP_FW_IPOPT_LSRR},
153	{ "rr",		IP_FW_IPOPT_RR},
154	{ "ts",		IP_FW_IPOPT_TS},
155	{ "ip option",	0 },
156	{ NULL,	0 }
157};
158
159static struct _s_x f_iptos[] = {
160	{ "lowdelay",	IPTOS_LOWDELAY},
161	{ "throughput",	IPTOS_THROUGHPUT},
162	{ "reliability", IPTOS_RELIABILITY},
163	{ "mincost",	IPTOS_MINCOST},
164	{ "congestion",	IPTOS_ECN_CE},
165	{ "ecntransport", IPTOS_ECN_ECT0},
166	{ "ip tos option", 0},
167	{ NULL,	0 }
168};
169
170struct _s_x f_ipdscp[] = {
171	{ "af11", IPTOS_DSCP_AF11 >> 2 },	/* 001010 */
172	{ "af12", IPTOS_DSCP_AF12 >> 2 },	/* 001100 */
173	{ "af13", IPTOS_DSCP_AF13 >> 2 },	/* 001110 */
174	{ "af21", IPTOS_DSCP_AF21 >> 2 },	/* 010010 */
175	{ "af22", IPTOS_DSCP_AF22 >> 2 },	/* 010100 */
176	{ "af23", IPTOS_DSCP_AF23 >> 2 },	/* 010110 */
177	{ "af31", IPTOS_DSCP_AF31 >> 2 },	/* 011010 */
178	{ "af32", IPTOS_DSCP_AF32 >> 2 },	/* 011100 */
179	{ "af33", IPTOS_DSCP_AF33 >> 2 },	/* 011110 */
180	{ "af41", IPTOS_DSCP_AF41 >> 2 },	/* 100010 */
181	{ "af42", IPTOS_DSCP_AF42 >> 2 },	/* 100100 */
182	{ "af43", IPTOS_DSCP_AF43 >> 2 },	/* 100110 */
183	{ "be", IPTOS_DSCP_CS0 >> 2 }, 	/* 000000 */
184	{ "ef", IPTOS_DSCP_EF >> 2 },	/* 101110 */
185	{ "cs0", IPTOS_DSCP_CS0 >> 2 },	/* 000000 */
186	{ "cs1", IPTOS_DSCP_CS1 >> 2 },	/* 001000 */
187	{ "cs2", IPTOS_DSCP_CS2 >> 2 },	/* 010000 */
188	{ "cs3", IPTOS_DSCP_CS3 >> 2 },	/* 011000 */
189	{ "cs4", IPTOS_DSCP_CS4 >> 2 },	/* 100000 */
190	{ "cs5", IPTOS_DSCP_CS5 >> 2 },	/* 101000 */
191	{ "cs6", IPTOS_DSCP_CS6 >> 2 },	/* 110000 */
192	{ "cs7", IPTOS_DSCP_CS7 >> 2 },	/* 100000 */
193	{ NULL, 0 }
194};
195
196static struct _s_x limit_masks[] = {
197	{"all",		DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
198	{"src-addr",	DYN_SRC_ADDR},
199	{"src-port",	DYN_SRC_PORT},
200	{"dst-addr",	DYN_DST_ADDR},
201	{"dst-port",	DYN_DST_PORT},
202	{NULL,		0}
203};
204
205/*
206 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
207 * This is only used in this code.
208 */
209#define IPPROTO_ETHERTYPE	0x1000
210static struct _s_x ether_types[] = {
211    /*
212     * Note, we cannot use "-:&/" in the names because they are field
213     * separators in the type specifications. Also, we use s = NULL as
214     * end-delimiter, because a type of 0 can be legal.
215     */
216	{ "ip",		0x0800 },
217	{ "ipv4",	0x0800 },
218	{ "ipv6",	0x86dd },
219	{ "arp",	0x0806 },
220	{ "rarp",	0x8035 },
221	{ "vlan",	0x8100 },
222	{ "loop",	0x9000 },
223	{ "trail",	0x1000 },
224	{ "at",		0x809b },
225	{ "atalk",	0x809b },
226	{ "aarp",	0x80f3 },
227	{ "pppoe_disc",	0x8863 },
228	{ "pppoe_sess",	0x8864 },
229	{ "ipx_8022",	0x00E0 },
230	{ "ipx_8023",	0x0000 },
231	{ "ipx_ii",	0x8137 },
232	{ "ipx_snap",	0x8137 },
233	{ "ipx",	0x8137 },
234	{ "ns",		0x0600 },
235	{ NULL,		0 }
236};
237
238static struct _s_x rule_eactions[] = {
239	{ "nat64lsn",		TOK_NAT64LSN },
240	{ "nat64stl",		TOK_NAT64STL },
241	{ "nptv6",		TOK_NPTV6 },
242	{ "tcp-setmss",		TOK_TCPSETMSS },
243	{ NULL, 0 }	/* terminator */
244};
245
246static struct _s_x rule_actions[] = {
247	{ "accept",		TOK_ACCEPT },
248	{ "pass",		TOK_ACCEPT },
249	{ "allow",		TOK_ACCEPT },
250	{ "permit",		TOK_ACCEPT },
251	{ "count",		TOK_COUNT },
252	{ "pipe",		TOK_PIPE },
253	{ "queue",		TOK_QUEUE },
254	{ "divert",		TOK_DIVERT },
255	{ "tee",		TOK_TEE },
256	{ "netgraph",		TOK_NETGRAPH },
257	{ "ngtee",		TOK_NGTEE },
258	{ "fwd",		TOK_FORWARD },
259	{ "forward",		TOK_FORWARD },
260	{ "skipto",		TOK_SKIPTO },
261	{ "deny",		TOK_DENY },
262	{ "drop",		TOK_DENY },
263	{ "reject",		TOK_REJECT },
264	{ "reset6",		TOK_RESET6 },
265	{ "reset",		TOK_RESET },
266	{ "unreach6",		TOK_UNREACH6 },
267	{ "unreach",		TOK_UNREACH },
268	{ "check-state",	TOK_CHECKSTATE },
269	{ "//",			TOK_COMMENT },
270	{ "nat",		TOK_NAT },
271	{ "reass",		TOK_REASS },
272	{ "setfib",		TOK_SETFIB },
273	{ "setdscp",		TOK_SETDSCP },
274	{ "call",		TOK_CALL },
275	{ "return",		TOK_RETURN },
276	{ "eaction",		TOK_EACTION },
277	{ "tcp-setmss",		TOK_TCPSETMSS },
278	{ NULL, 0 }	/* terminator */
279};
280
281static struct _s_x rule_action_params[] = {
282	{ "altq",		TOK_ALTQ },
283	{ "log",		TOK_LOG },
284	{ "tag",		TOK_TAG },
285	{ "untag",		TOK_UNTAG },
286	{ NULL, 0 }	/* terminator */
287};
288
289/*
290 * The 'lookup' instruction accepts one of the following arguments.
291 * -1 is a terminator for the list.
292 * Arguments are passed as v[1] in O_DST_LOOKUP options.
293 */
294static int lookup_key[] = {
295	TOK_DSTIP, TOK_SRCIP, TOK_DSTPORT, TOK_SRCPORT,
296	TOK_UID, TOK_JAIL, TOK_DSCP, -1 };
297
298static struct _s_x rule_options[] = {
299	{ "tagged",		TOK_TAGGED },
300	{ "uid",		TOK_UID },
301	{ "gid",		TOK_GID },
302	{ "jail",		TOK_JAIL },
303	{ "in",			TOK_IN },
304	{ "limit",		TOK_LIMIT },
305	{ "keep-state",		TOK_KEEPSTATE },
306	{ "bridged",		TOK_LAYER2 },
307	{ "layer2",		TOK_LAYER2 },
308	{ "out",		TOK_OUT },
309	{ "diverted",		TOK_DIVERTED },
310	{ "diverted-loopback",	TOK_DIVERTEDLOOPBACK },
311	{ "diverted-output",	TOK_DIVERTEDOUTPUT },
312	{ "xmit",		TOK_XMIT },
313	{ "recv",		TOK_RECV },
314	{ "via",		TOK_VIA },
315	{ "fragment",		TOK_FRAG },
316	{ "frag",		TOK_FRAG },
317	{ "fib",		TOK_FIB },
318	{ "ipoptions",		TOK_IPOPTS },
319	{ "ipopts",		TOK_IPOPTS },
320	{ "iplen",		TOK_IPLEN },
321	{ "ipid",		TOK_IPID },
322	{ "ipprecedence",	TOK_IPPRECEDENCE },
323	{ "dscp",		TOK_DSCP },
324	{ "iptos",		TOK_IPTOS },
325	{ "ipttl",		TOK_IPTTL },
326	{ "ipversion",		TOK_IPVER },
327	{ "ipver",		TOK_IPVER },
328	{ "estab",		TOK_ESTAB },
329	{ "established",	TOK_ESTAB },
330	{ "setup",		TOK_SETUP },
331	{ "sockarg",		TOK_SOCKARG },
332	{ "tcpdatalen",		TOK_TCPDATALEN },
333	{ "tcpflags",		TOK_TCPFLAGS },
334	{ "tcpflgs",		TOK_TCPFLAGS },
335	{ "tcpoptions",		TOK_TCPOPTS },
336	{ "tcpopts",		TOK_TCPOPTS },
337	{ "tcpseq",		TOK_TCPSEQ },
338	{ "tcpack",		TOK_TCPACK },
339	{ "tcpwin",		TOK_TCPWIN },
340	{ "icmptype",		TOK_ICMPTYPES },
341	{ "icmptypes",		TOK_ICMPTYPES },
342	{ "dst-ip",		TOK_DSTIP },
343	{ "src-ip",		TOK_SRCIP },
344	{ "dst-port",		TOK_DSTPORT },
345	{ "src-port",		TOK_SRCPORT },
346	{ "proto",		TOK_PROTO },
347	{ "MAC",		TOK_MAC },
348	{ "mac",		TOK_MAC },
349	{ "mac-type",		TOK_MACTYPE },
350	{ "verrevpath",		TOK_VERREVPATH },
351	{ "versrcreach",	TOK_VERSRCREACH },
352	{ "antispoof",		TOK_ANTISPOOF },
353	{ "ipsec",		TOK_IPSEC },
354	{ "icmp6type",		TOK_ICMP6TYPES },
355	{ "icmp6types",		TOK_ICMP6TYPES },
356	{ "ext6hdr",		TOK_EXT6HDR},
357	{ "flow-id",		TOK_FLOWID},
358	{ "ipv6",		TOK_IPV6},
359	{ "ip6",		TOK_IPV6},
360	{ "ipv4",		TOK_IPV4},
361	{ "ip4",		TOK_IPV4},
362	{ "dst-ipv6",		TOK_DSTIP6},
363	{ "dst-ip6",		TOK_DSTIP6},
364	{ "src-ipv6",		TOK_SRCIP6},
365	{ "src-ip6",		TOK_SRCIP6},
366	{ "lookup",		TOK_LOOKUP},
367	{ "flow",		TOK_FLOW},
368	{ "//",			TOK_COMMENT },
369
370	{ "not",		TOK_NOT },		/* pseudo option */
371	{ "!", /* escape ? */	TOK_NOT },		/* pseudo option */
372	{ "or",			TOK_OR },		/* pseudo option */
373	{ "|", /* escape */	TOK_OR },		/* pseudo option */
374	{ "{",			TOK_STARTBRACE },	/* pseudo option */
375	{ "(",			TOK_STARTBRACE },	/* pseudo option */
376	{ "}",			TOK_ENDBRACE },		/* pseudo option */
377	{ ")",			TOK_ENDBRACE },		/* pseudo option */
378	{ NULL, 0 }	/* terminator */
379};
380
381void bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg);
382static int ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
383    ipfw_cfg_lheader **pcfg, size_t *psize);
384static int ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
385    ipfw_cfg_lheader *cfg, size_t sz, int ac, char **av);
386static void ipfw_list_tifaces(void);
387
388struct tidx;
389static uint16_t pack_object(struct tidx *tstate, char *name, int otype);
390static uint16_t pack_table(struct tidx *tstate, char *name);
391
392static char *table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx);
393static void object_sort_ctlv(ipfw_obj_ctlv *ctlv);
394static char *object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx,
395    uint16_t type);
396
397/*
398 * Simple string buffer API.
399 * Used to simplify buffer passing between function and for
400 * transparent overrun handling.
401 */
402
403/*
404 * Allocates new buffer of given size @sz.
405 *
406 * Returns 0 on success.
407 */
408int
409bp_alloc(struct buf_pr *b, size_t size)
410{
411	memset(b, 0, sizeof(struct buf_pr));
412
413	if ((b->buf = calloc(1, size)) == NULL)
414		return (ENOMEM);
415
416	b->ptr = b->buf;
417	b->size = size;
418	b->avail = b->size;
419
420	return (0);
421}
422
423void
424bp_free(struct buf_pr *b)
425{
426
427	free(b->buf);
428}
429
430/*
431 * Flushes buffer so new writer start from beginning.
432 */
433void
434bp_flush(struct buf_pr *b)
435{
436
437	b->ptr = b->buf;
438	b->avail = b->size;
439	b->buf[0] = '\0';
440}
441
442/*
443 * Print message specified by @format and args.
444 * Automatically manage buffer space and transparently handle
445 * buffer overruns.
446 *
447 * Returns number of bytes that should have been printed.
448 */
449int
450bprintf(struct buf_pr *b, char *format, ...)
451{
452	va_list args;
453	int i;
454
455	va_start(args, format);
456
457	i = vsnprintf(b->ptr, b->avail, format, args);
458	va_end(args);
459
460	if (i > b->avail || i < 0) {
461		/* Overflow or print error */
462		b->avail = 0;
463	} else {
464		b->ptr += i;
465		b->avail -= i;
466	}
467
468	b->needed += i;
469
470	return (i);
471}
472
473/*
474 * Special values printer for tablearg-aware opcodes.
475 */
476void
477bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg)
478{
479
480	if (str != NULL)
481		bprintf(bp, "%s", str);
482	if (arg == IP_FW_TARG)
483		bprintf(bp, "tablearg");
484	else
485		bprintf(bp, "%u", arg);
486}
487
488/*
489 * Helper routine to print a possibly unaligned uint64_t on
490 * various platform. If width > 0, print the value with
491 * the desired width, followed by a space;
492 * otherwise, return the required width.
493 */
494int
495pr_u64(struct buf_pr *b, uint64_t *pd, int width)
496{
497#ifdef TCC
498#define U64_FMT "I64"
499#else
500#define U64_FMT "llu"
501#endif
502	uint64_t u;
503	unsigned long long d;
504
505	bcopy (pd, &u, sizeof(u));
506	d = u;
507	return (width > 0) ?
508		bprintf(b, "%*" U64_FMT " ", width, d) :
509		snprintf(NULL, 0, "%" U64_FMT, d) ;
510#undef U64_FMT
511}
512
513
514void *
515safe_calloc(size_t number, size_t size)
516{
517	void *ret = calloc(number, size);
518
519	if (ret == NULL)
520		err(EX_OSERR, "calloc");
521	return ret;
522}
523
524void *
525safe_realloc(void *ptr, size_t size)
526{
527	void *ret = realloc(ptr, size);
528
529	if (ret == NULL)
530		err(EX_OSERR, "realloc");
531	return ret;
532}
533
534/*
535 * Compare things like interface or table names.
536 */
537int
538stringnum_cmp(const char *a, const char *b)
539{
540	int la, lb;
541
542	la = strlen(a);
543	lb = strlen(b);
544
545	if (la > lb)
546		return (1);
547	else if (la < lb)
548		return (-01);
549
550	return (strcmp(a, b));
551}
552
553
554/*
555 * conditionally runs the command.
556 * Selected options or negative -> getsockopt
557 */
558int
559do_cmd(int optname, void *optval, uintptr_t optlen)
560{
561	int i;
562
563	if (co.test_only)
564		return 0;
565
566	if (ipfw_socket == -1)
567		ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
568	if (ipfw_socket < 0)
569		err(EX_UNAVAILABLE, "socket");
570
571	if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
572	    optname == IP_FW_ADD || optname == IP_FW3 ||
573	    optname == IP_FW_NAT_GET_CONFIG ||
574	    optname < 0 ||
575	    optname == IP_FW_NAT_GET_LOG) {
576		if (optname < 0)
577			optname = -optname;
578		i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
579			(socklen_t *)optlen);
580	} else {
581		i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
582	}
583	return i;
584}
585
586/*
587 * do_set3 - pass ipfw control cmd to kernel
588 * @optname: option name
589 * @optval: pointer to option data
590 * @optlen: option length
591 *
592 * Assumes op3 header is already embedded.
593 * Calls setsockopt() with IP_FW3 as kernel-visible opcode.
594 * Returns 0 on success or errno otherwise.
595 */
596int
597do_set3(int optname, ip_fw3_opheader *op3, size_t optlen)
598{
599
600	if (co.test_only)
601		return (0);
602
603	if (ipfw_socket == -1)
604		ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
605	if (ipfw_socket < 0)
606		err(EX_UNAVAILABLE, "socket");
607
608	op3->opcode = optname;
609
610	return (setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, optlen));
611}
612
613/*
614 * do_get3 - pass ipfw control cmd to kernel
615 * @optname: option name
616 * @optval: pointer to option data
617 * @optlen: pointer to option length
618 *
619 * Assumes op3 header is already embedded.
620 * Calls getsockopt() with IP_FW3 as kernel-visible opcode.
621 * Returns 0 on success or errno otherwise.
622 */
623int
624do_get3(int optname, ip_fw3_opheader *op3, size_t *optlen)
625{
626	int error;
627	socklen_t len;
628
629	if (co.test_only)
630		return (0);
631
632	if (ipfw_socket == -1)
633		ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
634	if (ipfw_socket < 0)
635		err(EX_UNAVAILABLE, "socket");
636
637	op3->opcode = optname;
638
639	len = *optlen;
640	error = getsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, &len);
641	*optlen = len;
642
643	return (error);
644}
645
646/**
647 * match_token takes a table and a string, returns the value associated
648 * with the string (-1 in case of failure).
649 */
650int
651match_token(struct _s_x *table, const char *string)
652{
653	struct _s_x *pt;
654	uint i = strlen(string);
655
656	for (pt = table ; i && pt->s != NULL ; pt++)
657		if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
658			return pt->x;
659	return (-1);
660}
661
662/**
663 * match_token_relaxed takes a table and a string, returns the value associated
664 * with the string for the best match.
665 *
666 * Returns:
667 * value from @table for matched records
668 * -1 for non-matched records
669 * -2 if more than one records match @string.
670 */
671int
672match_token_relaxed(struct _s_x *table, const char *string)
673{
674	struct _s_x *pt, *m;
675	int i, c;
676
677	i = strlen(string);
678	c = 0;
679
680	for (pt = table ; i != 0 && pt->s != NULL ; pt++) {
681		if (strncmp(pt->s, string, i) != 0)
682			continue;
683		m = pt;
684		c++;
685	}
686
687	if (c == 1)
688		return (m->x);
689
690	return (c > 0 ? -2: -1);
691}
692
693int
694get_token(struct _s_x *table, const char *string, const char *errbase)
695{
696	int tcmd;
697
698	if ((tcmd = match_token_relaxed(table, string)) < 0)
699		errx(EX_USAGE, "%s %s %s",
700		    (tcmd == 0) ? "invalid" : "ambiguous", errbase, string);
701
702	return (tcmd);
703}
704
705/**
706 * match_value takes a table and a value, returns the string associated
707 * with the value (NULL in case of failure).
708 */
709char const *
710match_value(struct _s_x *p, int value)
711{
712	for (; p->s != NULL; p++)
713		if (p->x == value)
714			return p->s;
715	return NULL;
716}
717
718size_t
719concat_tokens(char *buf, size_t bufsize, struct _s_x *table, char *delimiter)
720{
721	struct _s_x *pt;
722	int l;
723	size_t sz;
724
725	for (sz = 0, pt = table ; pt->s != NULL; pt++) {
726		l = snprintf(buf + sz, bufsize - sz, "%s%s",
727		    (sz == 0) ? "" : delimiter, pt->s);
728		sz += l;
729		bufsize += l;
730		if (sz > bufsize)
731			return (bufsize);
732	}
733
734	return (sz);
735}
736
737/*
738 * helper function to process a set of flags and set bits in the
739 * appropriate masks.
740 */
741int
742fill_flags(struct _s_x *flags, char *p, char **e, uint32_t *set,
743    uint32_t *clear)
744{
745	char *q;	/* points to the separator */
746	int val;
747	uint32_t *which;	/* mask we are working on */
748
749	while (p && *p) {
750		if (*p == '!') {
751			p++;
752			which = clear;
753		} else
754			which = set;
755		q = strchr(p, ',');
756		if (q)
757			*q++ = '\0';
758		val = match_token(flags, p);
759		if (val <= 0) {
760			if (e != NULL)
761				*e = p;
762			return (-1);
763		}
764		*which |= (uint32_t)val;
765		p = q;
766	}
767	return (0);
768}
769
770void
771print_flags_buffer(char *buf, size_t sz, struct _s_x *list, uint32_t set)
772{
773	char const *comma = "";
774	int i, l;
775
776	for (i = 0; list[i].x != 0; i++) {
777		if ((set & list[i].x) == 0)
778			continue;
779
780		set &= ~list[i].x;
781		l = snprintf(buf, sz, "%s%s", comma, list[i].s);
782		if (l >= sz)
783			return;
784		comma = ",";
785		buf += l;
786		sz -=l;
787	}
788}
789
790/*
791 * _substrcmp takes two strings and returns 1 if they do not match,
792 * and 0 if they match exactly or the first string is a sub-string
793 * of the second.  A warning is printed to stderr in the case that the
794 * first string is a sub-string of the second.
795 *
796 * This function will be removed in the future through the usual
797 * deprecation process.
798 */
799int
800_substrcmp(const char *str1, const char* str2)
801{
802
803	if (strncmp(str1, str2, strlen(str1)) != 0)
804		return 1;
805
806	if (strlen(str1) != strlen(str2))
807		warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
808		    str1, str2);
809	return 0;
810}
811
812/*
813 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
814 * and 0 if they match exactly or the second string is a sub-string
815 * of the first.  A warning is printed to stderr in the case that the
816 * first string does not match the third.
817 *
818 * This function exists to warn about the bizarre construction
819 * strncmp(str, "by", 2) which is used to allow people to use a shortcut
820 * for "bytes".  The problem is that in addition to accepting "by",
821 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
822 * other string beginning with "by".
823 *
824 * This function will be removed in the future through the usual
825 * deprecation process.
826 */
827int
828_substrcmp2(const char *str1, const char* str2, const char* str3)
829{
830
831	if (strncmp(str1, str2, strlen(str2)) != 0)
832		return 1;
833
834	if (strcmp(str1, str3) != 0)
835		warnx("DEPRECATED: '%s' matched '%s'",
836		    str1, str3);
837	return 0;
838}
839
840/*
841 * prints one port, symbolic or numeric
842 */
843static void
844print_port(struct buf_pr *bp, int proto, uint16_t port)
845{
846
847	if (proto == IPPROTO_ETHERTYPE) {
848		char const *s;
849
850		if (co.do_resolv && (s = match_value(ether_types, port)) )
851			bprintf(bp, "%s", s);
852		else
853			bprintf(bp, "0x%04x", port);
854	} else {
855		struct servent *se = NULL;
856		if (co.do_resolv) {
857			struct protoent *pe = getprotobynumber(proto);
858
859			se = getservbyport(htons(port), pe ? pe->p_name : NULL);
860		}
861		if (se)
862			bprintf(bp, "%s", se->s_name);
863		else
864			bprintf(bp, "%d", port);
865	}
866}
867
868static struct _s_x _port_name[] = {
869	{"dst-port",	O_IP_DSTPORT},
870	{"src-port",	O_IP_SRCPORT},
871	{"ipid",	O_IPID},
872	{"iplen",	O_IPLEN},
873	{"ipttl",	O_IPTTL},
874	{"mac-type",	O_MAC_TYPE},
875	{"tcpdatalen",	O_TCPDATALEN},
876	{"tcpwin",	O_TCPWIN},
877	{"tagged",	O_TAGGED},
878	{NULL,		0}
879};
880
881/*
882 * Print the values in a list 16-bit items of the types above.
883 * XXX todo: add support for mask.
884 */
885static void
886print_newports(struct buf_pr *bp, ipfw_insn_u16 *cmd, int proto, int opcode)
887{
888	uint16_t *p = cmd->ports;
889	int i;
890	char const *sep;
891
892	if (opcode != 0) {
893		sep = match_value(_port_name, opcode);
894		if (sep == NULL)
895			sep = "???";
896		bprintf(bp, " %s", sep);
897	}
898	sep = " ";
899	for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
900		bprintf(bp, "%s", sep);
901		print_port(bp, proto, p[0]);
902		if (p[0] != p[1]) {
903			bprintf(bp, "-");
904			print_port(bp, proto, p[1]);
905		}
906		sep = ",";
907	}
908}
909
910/*
911 * Like strtol, but also translates service names into port numbers
912 * for some protocols.
913 * In particular:
914 *	proto == -1 disables the protocol check;
915 *	proto == IPPROTO_ETHERTYPE looks up an internal table
916 *	proto == <some value in /etc/protocols> matches the values there.
917 * Returns *end == s in case the parameter is not found.
918 */
919static int
920strtoport(char *s, char **end, int base, int proto)
921{
922	char *p, *buf;
923	char *s1;
924	int i;
925
926	*end = s;		/* default - not found */
927	if (*s == '\0')
928		return 0;	/* not found */
929
930	if (isdigit(*s))
931		return strtol(s, end, base);
932
933	/*
934	 * find separator. '\\' escapes the next char.
935	 */
936	for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
937		if (*s1 == '\\' && s1[1] != '\0')
938			s1++;
939
940	buf = safe_calloc(s1 - s + 1, 1);
941
942	/*
943	 * copy into a buffer skipping backslashes
944	 */
945	for (p = s, i = 0; p != s1 ; p++)
946		if (*p != '\\')
947			buf[i++] = *p;
948	buf[i++] = '\0';
949
950	if (proto == IPPROTO_ETHERTYPE) {
951		i = match_token(ether_types, buf);
952		free(buf);
953		if (i != -1) {	/* found */
954			*end = s1;
955			return i;
956		}
957	} else {
958		struct protoent *pe = NULL;
959		struct servent *se;
960
961		if (proto != 0)
962			pe = getprotobynumber(proto);
963		setservent(1);
964		se = getservbyname(buf, pe ? pe->p_name : NULL);
965		free(buf);
966		if (se != NULL) {
967			*end = s1;
968			return ntohs(se->s_port);
969		}
970	}
971	return 0;	/* not found */
972}
973
974/*
975 * Fill the body of the command with the list of port ranges.
976 */
977static int
978fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
979{
980	uint16_t a, b, *p = cmd->ports;
981	int i = 0;
982	char *s = av;
983
984	while (*s) {
985		a = strtoport(av, &s, 0, proto);
986		if (s == av) 			/* empty or invalid argument */
987			return (0);
988
989		CHECK_LENGTH(cblen, i + 2);
990
991		switch (*s) {
992		case '-':			/* a range */
993			av = s + 1;
994			b = strtoport(av, &s, 0, proto);
995			/* Reject expressions like '1-abc' or '1-2-3'. */
996			if (s == av || (*s != ',' && *s != '\0'))
997				return (0);
998			p[0] = a;
999			p[1] = b;
1000			break;
1001		case ',':			/* comma separated list */
1002		case '\0':
1003			p[0] = p[1] = a;
1004			break;
1005		default:
1006			warnx("port list: invalid separator <%c> in <%s>",
1007				*s, av);
1008			return (0);
1009		}
1010
1011		i++;
1012		p += 2;
1013		av = s + 1;
1014	}
1015	if (i > 0) {
1016		if (i + 1 > F_LEN_MASK)
1017			errx(EX_DATAERR, "too many ports/ranges\n");
1018		cmd->o.len |= i + 1;	/* leave F_NOT and F_OR untouched */
1019	}
1020	return (i);
1021}
1022
1023/*
1024 * Fill the body of the command with the list of DiffServ codepoints.
1025 */
1026static void
1027fill_dscp(ipfw_insn *cmd, char *av, int cblen)
1028{
1029	uint32_t *low, *high;
1030	char *s = av, *a;
1031	int code;
1032
1033	cmd->opcode = O_DSCP;
1034	cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
1035
1036	CHECK_CMDLEN;
1037
1038	low = (uint32_t *)(cmd + 1);
1039	high = low + 1;
1040
1041	*low = 0;
1042	*high = 0;
1043
1044	while (s != NULL) {
1045		a = strchr(s, ',');
1046
1047		if (a != NULL)
1048			*a++ = '\0';
1049
1050		if (isalpha(*s)) {
1051			if ((code = match_token(f_ipdscp, s)) == -1)
1052				errx(EX_DATAERR, "Unknown DSCP code");
1053		} else {
1054			code = strtoul(s, NULL, 10);
1055			if (code < 0 || code > 63)
1056				errx(EX_DATAERR, "Invalid DSCP value");
1057		}
1058
1059		if (code >= 32)
1060			*high |= 1 << (code - 32);
1061		else
1062			*low |= 1 << code;
1063
1064		s = a;
1065	}
1066}
1067
1068static struct _s_x icmpcodes[] = {
1069      { "net",			ICMP_UNREACH_NET },
1070      { "host",			ICMP_UNREACH_HOST },
1071      { "protocol",		ICMP_UNREACH_PROTOCOL },
1072      { "port",			ICMP_UNREACH_PORT },
1073      { "needfrag",		ICMP_UNREACH_NEEDFRAG },
1074      { "srcfail",		ICMP_UNREACH_SRCFAIL },
1075      { "net-unknown",		ICMP_UNREACH_NET_UNKNOWN },
1076      { "host-unknown",		ICMP_UNREACH_HOST_UNKNOWN },
1077      { "isolated",		ICMP_UNREACH_ISOLATED },
1078      { "net-prohib",		ICMP_UNREACH_NET_PROHIB },
1079      { "host-prohib",		ICMP_UNREACH_HOST_PROHIB },
1080      { "tosnet",		ICMP_UNREACH_TOSNET },
1081      { "toshost",		ICMP_UNREACH_TOSHOST },
1082      { "filter-prohib",	ICMP_UNREACH_FILTER_PROHIB },
1083      { "host-precedence",	ICMP_UNREACH_HOST_PRECEDENCE },
1084      { "precedence-cutoff",	ICMP_UNREACH_PRECEDENCE_CUTOFF },
1085      { NULL, 0 }
1086};
1087
1088static void
1089fill_reject_code(u_short *codep, char *str)
1090{
1091	int val;
1092	char *s;
1093
1094	val = strtoul(str, &s, 0);
1095	if (s == str || *s != '\0' || val >= 0x100)
1096		val = match_token(icmpcodes, str);
1097	if (val < 0)
1098		errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
1099	*codep = val;
1100	return;
1101}
1102
1103static void
1104print_reject_code(struct buf_pr *bp, uint16_t code)
1105{
1106	char const *s;
1107
1108	if ((s = match_value(icmpcodes, code)) != NULL)
1109		bprintf(bp, "unreach %s", s);
1110	else
1111		bprintf(bp, "unreach %u", code);
1112}
1113
1114/*
1115 * Returns the number of bits set (from left) in a contiguous bitmask,
1116 * or -1 if the mask is not contiguous.
1117 * XXX this needs a proper fix.
1118 * This effectively works on masks in big-endian (network) format.
1119 * when compiled on little endian architectures.
1120 *
1121 * First bit is bit 7 of the first byte -- note, for MAC addresses,
1122 * the first bit on the wire is bit 0 of the first byte.
1123 * len is the max length in bits.
1124 */
1125int
1126contigmask(uint8_t *p, int len)
1127{
1128	int i, n;
1129
1130	for (i=0; i<len ; i++)
1131		if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
1132			break;
1133	for (n=i+1; n < len; n++)
1134		if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
1135			return -1; /* mask not contiguous */
1136	return i;
1137}
1138
1139/*
1140 * print flags set/clear in the two bitmasks passed as parameters.
1141 * There is a specialized check for f_tcpflags.
1142 */
1143static void
1144print_flags(struct buf_pr *bp, char const *name, ipfw_insn *cmd,
1145    struct _s_x *list)
1146{
1147	char const *comma = "";
1148	int i;
1149	uint8_t set = cmd->arg1 & 0xff;
1150	uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1151
1152	if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1153		bprintf(bp, " setup");
1154		return;
1155	}
1156
1157	bprintf(bp, " %s ", name);
1158	for (i=0; list[i].x != 0; i++) {
1159		if (set & list[i].x) {
1160			set &= ~list[i].x;
1161			bprintf(bp, "%s%s", comma, list[i].s);
1162			comma = ",";
1163		}
1164		if (clear & list[i].x) {
1165			clear &= ~list[i].x;
1166			bprintf(bp, "%s!%s", comma, list[i].s);
1167			comma = ",";
1168		}
1169	}
1170}
1171
1172
1173/*
1174 * Print the ip address contained in a command.
1175 */
1176static void
1177print_ip(struct buf_pr *bp, struct format_opts *fo, ipfw_insn_ip *cmd,
1178    char const *s)
1179{
1180	struct hostent *he = NULL;
1181	struct in_addr *ia;
1182	uint32_t len = F_LEN((ipfw_insn *)cmd);
1183	uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
1184	char *t;
1185
1186	if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
1187		uint32_t d = a[1];
1188		const char *arg = "<invalid>";
1189
1190		if (d < sizeof(lookup_key)/sizeof(lookup_key[0]))
1191			arg = match_value(rule_options, lookup_key[d]);
1192		t = table_search_ctlv(fo->tstate, ((ipfw_insn *)cmd)->arg1);
1193		bprintf(bp, "%s lookup %s %s", cmd->o.len & F_NOT ? " not": "",
1194			arg, t);
1195		return;
1196	}
1197	bprintf(bp, "%s%s ", cmd->o.len & F_NOT ? " not": "", s);
1198
1199	if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
1200		bprintf(bp, "me");
1201		return;
1202	}
1203	if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
1204	    cmd->o.opcode == O_IP_DST_LOOKUP) {
1205		t = table_search_ctlv(fo->tstate, ((ipfw_insn *)cmd)->arg1);
1206		bprintf(bp, "table(%s", t);
1207		if (len == F_INSN_SIZE(ipfw_insn_u32))
1208			bprintf(bp, ",%u", *a);
1209		bprintf(bp, ")");
1210		return;
1211	}
1212	if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1213		uint32_t x, *map = (uint32_t *)&(cmd->mask);
1214		int i, j;
1215		char comma = '{';
1216
1217		x = cmd->o.arg1 - 1;
1218		x = htonl( ~x );
1219		cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1220		bprintf(bp, "%s/%d", inet_ntoa(cmd->addr),
1221			contigmask((uint8_t *)&x, 32));
1222		x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1223		x &= 0xff; /* base */
1224		/*
1225		 * Print bits and ranges.
1226		 * Locate first bit set (i), then locate first bit unset (j).
1227		 * If we have 3+ consecutive bits set, then print them as a
1228		 * range, otherwise only print the initial bit and rescan.
1229		 */
1230		for (i=0; i < cmd->o.arg1; i++)
1231			if (map[i/32] & (1<<(i & 31))) {
1232				for (j=i+1; j < cmd->o.arg1; j++)
1233					if (!(map[ j/32] & (1<<(j & 31))))
1234						break;
1235				bprintf(bp, "%c%d", comma, i+x);
1236				if (j>i+2) { /* range has at least 3 elements */
1237					bprintf(bp, "-%d", j-1+x);
1238					i = j-1;
1239				}
1240				comma = ',';
1241			}
1242		bprintf(bp, "}");
1243		return;
1244	}
1245	/*
1246	 * len == 2 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    for (len = len / 2; len > 0; len--, a += 2) {
1251	int mb =	/* mask length */
1252	    (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1253		32 : contigmask((uint8_t *)&(a[1]), 32);
1254	if (mb == 32 && co.do_resolv)
1255		he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
1256	if (he != NULL)		/* resolved to name */
1257		bprintf(bp, "%s", he->h_name);
1258	else if (mb == 0)	/* any */
1259		bprintf(bp, "any");
1260	else {		/* numeric IP followed by some kind of mask */
1261		ia = (struct in_addr *)&a[0];
1262		bprintf(bp, "%s", inet_ntoa(*ia));
1263		if (mb < 0) {
1264			ia = (struct in_addr *)&a[1];
1265			bprintf(bp, ":%s", inet_ntoa(*ia));
1266		} else if (mb < 32)
1267			bprintf(bp, "/%d", mb);
1268	}
1269	if (len > 1)
1270		bprintf(bp, ",");
1271    }
1272}
1273
1274/*
1275 * prints a MAC address/mask pair
1276 */
1277static void
1278print_mac(struct buf_pr *bp, uint8_t *addr, uint8_t *mask)
1279{
1280	int l = contigmask(mask, 48);
1281
1282	if (l == 0)
1283		bprintf(bp, " any");
1284	else {
1285		bprintf(bp, " %02x:%02x:%02x:%02x:%02x:%02x",
1286		    addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1287		if (l == -1)
1288			bprintf(bp, "&%02x:%02x:%02x:%02x:%02x:%02x",
1289			    mask[0], mask[1], mask[2],
1290			    mask[3], mask[4], mask[5]);
1291		else if (l < 48)
1292			bprintf(bp, "/%d", l);
1293	}
1294}
1295
1296static void
1297fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1298{
1299	uint8_t type;
1300
1301	cmd->d[0] = 0;
1302	while (*av) {
1303		if (*av == ',')
1304			av++;
1305
1306		type = strtoul(av, &av, 0);
1307
1308		if (*av != ',' && *av != '\0')
1309			errx(EX_DATAERR, "invalid ICMP type");
1310
1311		if (type > 31)
1312			errx(EX_DATAERR, "ICMP type out of range");
1313
1314		cmd->d[0] |= 1 << type;
1315	}
1316	cmd->o.opcode = O_ICMPTYPE;
1317	cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1318}
1319
1320static void
1321print_icmptypes(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1322{
1323	int i;
1324	char sep= ' ';
1325
1326	bprintf(bp, " icmptypes");
1327	for (i = 0; i < 32; i++) {
1328		if ( (cmd->d[0] & (1 << (i))) == 0)
1329			continue;
1330		bprintf(bp, "%c%d", sep, i);
1331		sep = ',';
1332	}
1333}
1334
1335static void
1336print_dscp(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1337{
1338	int i = 0;
1339	uint32_t *v;
1340	char sep= ' ';
1341	const char *code;
1342
1343	bprintf(bp, " dscp");
1344	v = cmd->d;
1345	while (i < 64) {
1346		if (*v & (1 << i)) {
1347			if ((code = match_value(f_ipdscp, i)) != NULL)
1348				bprintf(bp, "%c%s", sep, code);
1349			else
1350				bprintf(bp, "%c%d", sep, i);
1351			sep = ',';
1352		}
1353
1354		if ((++i % 32) == 0)
1355			v++;
1356	}
1357}
1358
1359/*
1360 * show_ipfw() prints the body of an ipfw rule.
1361 * Because the standard rule has at least proto src_ip dst_ip, we use
1362 * a helper function to produce these entries if not provided explicitly.
1363 * The first argument is the list of fields we have, the second is
1364 * the list of fields we want to be printed.
1365 *
1366 * Special cases if we have provided a MAC header:
1367 *   + if the rule does not contain IP addresses/ports, do not print them;
1368 *   + if the rule does not contain an IP proto, print "all" instead of "ip";
1369 *
1370 * Once we have 'have_options', IP header fields are printed as options.
1371 */
1372#define	HAVE_PROTO	0x0001
1373#define	HAVE_SRCIP	0x0002
1374#define	HAVE_DSTIP	0x0004
1375#define	HAVE_PROTO4	0x0008
1376#define	HAVE_PROTO6	0x0010
1377#define	HAVE_IP		0x0100
1378#define	HAVE_OPTIONS	0x8000
1379
1380static void
1381show_prerequisites(struct buf_pr *bp, int *flags, int want, int cmd)
1382{
1383	(void)cmd;	/* UNUSED */
1384	if (co.comment_only)
1385		return;
1386	if ( (*flags & HAVE_IP) == HAVE_IP)
1387		*flags |= HAVE_OPTIONS;
1388
1389	if ( !(*flags & HAVE_OPTIONS)) {
1390		if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) {
1391			if ( (*flags & HAVE_PROTO4))
1392				bprintf(bp, " ip4");
1393			else if ( (*flags & HAVE_PROTO6))
1394				bprintf(bp, " ip6");
1395			else
1396				bprintf(bp, " ip");
1397		}
1398		if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
1399			bprintf(bp, " from any");
1400		if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
1401			bprintf(bp, " to any");
1402	}
1403	*flags |= want;
1404}
1405
1406static void
1407show_static_rule(struct cmdline_opts *co, struct format_opts *fo,
1408    struct buf_pr *bp, struct ip_fw_rule *rule, struct ip_fw_bcounter *cntr)
1409{
1410	static int twidth = 0;
1411	int l;
1412	ipfw_insn *cmd, *has_eaction = NULL, *tagptr = NULL;
1413	const char *comment = NULL;	/* ptr to comment if we have one */
1414	const char *ename;
1415	int proto = 0;		/* default */
1416	int flags = 0;	/* prerequisites */
1417	ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
1418	ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
1419	int or_block = 0;	/* we are in an or block */
1420	uint32_t uval;
1421
1422	if ((fo->set_mask & (1 << rule->set)) == 0) {
1423		/* disabled mask */
1424		if (!co->show_sets)
1425			return;
1426		else
1427			bprintf(bp, "# DISABLED ");
1428	}
1429	bprintf(bp, "%05u ", rule->rulenum);
1430
1431	/* Print counters if enabled */
1432	if (fo->pcwidth > 0 || fo->bcwidth > 0) {
1433		pr_u64(bp, &cntr->pcnt, fo->pcwidth);
1434		pr_u64(bp, &cntr->bcnt, fo->bcwidth);
1435	}
1436
1437	if (co->do_time == 2)
1438		bprintf(bp, "%10u ", cntr->timestamp);
1439	else if (co->do_time == 1) {
1440		char timestr[30];
1441		time_t t = (time_t)0;
1442
1443		if (twidth == 0) {
1444			strcpy(timestr, ctime(&t));
1445			*strchr(timestr, '\n') = '\0';
1446			twidth = strlen(timestr);
1447		}
1448		if (cntr->timestamp > 0) {
1449			t = _long_to_time(cntr->timestamp);
1450
1451			strcpy(timestr, ctime(&t));
1452			*strchr(timestr, '\n') = '\0';
1453			bprintf(bp, "%s ", timestr);
1454		} else {
1455			bprintf(bp, "%*s", twidth, " ");
1456		}
1457	}
1458
1459	if (co->show_sets)
1460		bprintf(bp, "set %d ", rule->set);
1461
1462	/*
1463	 * print the optional "match probability"
1464	 */
1465	if (rule->cmd_len > 0) {
1466		cmd = rule->cmd ;
1467		if (cmd->opcode == O_PROB) {
1468			ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1469			double d = 1.0 * p->d[0];
1470
1471			d = (d / 0x7fffffff);
1472			bprintf(bp, "prob %f ", d);
1473		}
1474	}
1475
1476	/*
1477	 * first print actions
1478	 */
1479	for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1480			l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1481		switch(cmd->opcode) {
1482		case O_CHECK_STATE:
1483			bprintf(bp, "check-state");
1484			if (cmd->arg1 != 0)
1485				ename = object_search_ctlv(fo->tstate,
1486				    cmd->arg1, IPFW_TLV_STATE_NAME);
1487			else
1488				ename = NULL;
1489			bprintf(bp, " :%s", ename ? ename: "any");
1490			/* avoid printing anything else */
1491			flags = HAVE_PROTO | HAVE_SRCIP |
1492				HAVE_DSTIP | HAVE_IP;
1493			break;
1494
1495		case O_ACCEPT:
1496			bprintf(bp, "allow");
1497			break;
1498
1499		case O_COUNT:
1500			bprintf(bp, "count");
1501			break;
1502
1503		case O_DENY:
1504			bprintf(bp, "deny");
1505			break;
1506
1507		case O_REJECT:
1508			if (cmd->arg1 == ICMP_REJECT_RST)
1509				bprintf(bp, "reset");
1510			else if (cmd->arg1 == ICMP_UNREACH_HOST)
1511				bprintf(bp, "reject");
1512			else
1513				print_reject_code(bp, cmd->arg1);
1514			break;
1515
1516		case O_UNREACH6:
1517			if (cmd->arg1 == ICMP6_UNREACH_RST)
1518				bprintf(bp, "reset6");
1519			else
1520				print_unreach6_code(bp, cmd->arg1);
1521			break;
1522
1523		case O_SKIPTO:
1524			bprint_uint_arg(bp, "skipto ", cmd->arg1);
1525			break;
1526
1527		case O_PIPE:
1528			bprint_uint_arg(bp, "pipe ", cmd->arg1);
1529			break;
1530
1531		case O_QUEUE:
1532			bprint_uint_arg(bp, "queue ", cmd->arg1);
1533			break;
1534
1535		case O_DIVERT:
1536			bprint_uint_arg(bp, "divert ", cmd->arg1);
1537			break;
1538
1539		case O_TEE:
1540			bprint_uint_arg(bp, "tee ", cmd->arg1);
1541			break;
1542
1543		case O_NETGRAPH:
1544			bprint_uint_arg(bp, "netgraph ", cmd->arg1);
1545			break;
1546
1547		case O_NGTEE:
1548			bprint_uint_arg(bp, "ngtee ", cmd->arg1);
1549			break;
1550
1551		case O_FORWARD_IP:
1552		    {
1553			ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1554
1555			if (s->sa.sin_addr.s_addr == INADDR_ANY) {
1556				bprintf(bp, "fwd tablearg");
1557			} else {
1558				bprintf(bp, "fwd %s",inet_ntoa(s->sa.sin_addr));
1559			}
1560			if (s->sa.sin_port)
1561				bprintf(bp, ",%d", s->sa.sin_port);
1562		    }
1563			break;
1564
1565		case O_FORWARD_IP6:
1566		    {
1567			char buf[INET6_ADDRSTRLEN + IF_NAMESIZE + 2];
1568			ipfw_insn_sa6 *s = (ipfw_insn_sa6 *)cmd;
1569
1570			bprintf(bp, "fwd ");
1571			if (getnameinfo((const struct sockaddr *)&s->sa,
1572			    sizeof(struct sockaddr_in6), buf, sizeof(buf),
1573			    NULL, 0, NI_NUMERICHOST) == 0)
1574				bprintf(bp, "%s", buf);
1575			if (s->sa.sin6_port)
1576				bprintf(bp, ",%d", s->sa.sin6_port);
1577		    }
1578			break;
1579
1580		case O_LOG: /* O_LOG is printed last */
1581			logptr = (ipfw_insn_log *)cmd;
1582			break;
1583
1584		case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1585			altqptr = (ipfw_insn_altq *)cmd;
1586			break;
1587
1588		case O_TAG:
1589			tagptr = cmd;
1590			break;
1591
1592		case O_NAT:
1593			if (cmd->arg1 != IP_FW_NAT44_GLOBAL)
1594				bprint_uint_arg(bp, "nat ", cmd->arg1);
1595			else
1596				bprintf(bp, "nat global");
1597			break;
1598
1599		case O_SETFIB:
1600			if (cmd->arg1 == IP_FW_TARG)
1601				bprint_uint_arg(bp, "setfib ", cmd->arg1);
1602			else
1603				bprintf(bp, "setfib %u", cmd->arg1 & 0x7FFF);
1604			break;
1605
1606		case O_EXTERNAL_ACTION: {
1607			/*
1608			 * The external action can consists of two following
1609			 * each other opcodes - O_EXTERNAL_ACTION and
1610			 * O_EXTERNAL_INSTANCE. The first contains the ID of
1611			 * name of external action. The second contains the ID
1612			 * of name of external action instance.
1613			 * NOTE: in case when external action has no named
1614			 * instances support, the second opcode isn't needed.
1615			 */
1616			has_eaction = cmd;
1617			ename = object_search_ctlv(fo->tstate, cmd->arg1,
1618			    IPFW_TLV_EACTION);
1619			if (match_token(rule_eactions, ename) != -1)
1620				bprintf(bp, "%s", ename);
1621			else
1622				bprintf(bp, "eaction %s", ename);
1623			break;
1624		}
1625
1626		case O_EXTERNAL_INSTANCE: {
1627			if (has_eaction == NULL)
1628				break;
1629			/*
1630			 * XXX: we need to teach ipfw(9) to rewrite opcodes
1631			 * in the user buffer on rule addition. When we add
1632			 * the rule, we specify zero TLV type for
1633			 * O_EXTERNAL_INSTANCE object. To show correct
1634			 * rule after `ipfw add` we need to search instance
1635			 * name with zero type. But when we do `ipfw show`
1636			 * we calculate TLV type using IPFW_TLV_EACTION_NAME()
1637			 * macro.
1638			 */
1639			ename = object_search_ctlv(fo->tstate, cmd->arg1, 0);
1640			if (ename == NULL)
1641				ename = object_search_ctlv(fo->tstate,
1642				    cmd->arg1,
1643				    IPFW_TLV_EACTION_NAME(has_eaction->arg1));
1644			bprintf(bp, " %s", ename);
1645			break;
1646		}
1647
1648		case O_EXTERNAL_DATA: {
1649			if (has_eaction == NULL)
1650				break;
1651			/*
1652			 * Currently we support data formatting only for
1653			 * external data with datalen u16. For unknown data
1654			 * print its size in bytes.
1655			 */
1656			if (cmd->len == F_INSN_SIZE(ipfw_insn))
1657				bprintf(bp, " %u", cmd->arg1);
1658			else
1659				bprintf(bp, " %ubytes",
1660				    cmd->len * sizeof(uint32_t));
1661			break;
1662		}
1663
1664		case O_SETDSCP:
1665		    {
1666			const char *code;
1667
1668			if (cmd->arg1 == IP_FW_TARG) {
1669				bprint_uint_arg(bp, "setdscp ", cmd->arg1);
1670				break;
1671			}
1672			uval = cmd->arg1 & 0x3F;
1673			if ((code = match_value(f_ipdscp, uval)) != NULL)
1674				bprintf(bp, "setdscp %s", code);
1675			else
1676				bprint_uint_arg(bp, "setdscp ", uval);
1677		    }
1678 			break;
1679
1680		case O_REASS:
1681			bprintf(bp, "reass");
1682			break;
1683
1684		case O_CALLRETURN:
1685			if (cmd->len & F_NOT)
1686				bprintf(bp, "return");
1687			else
1688				bprint_uint_arg(bp, "call ", cmd->arg1);
1689			break;
1690
1691		default:
1692			bprintf(bp, "** unrecognized action %d len %d ",
1693				cmd->opcode, cmd->len);
1694		}
1695	}
1696	if (logptr) {
1697		if (logptr->max_log > 0)
1698			bprintf(bp, " log logamount %d", logptr->max_log);
1699		else
1700			bprintf(bp, " log");
1701	}
1702#ifndef NO_ALTQ
1703	if (altqptr) {
1704		print_altq_cmd(bp, altqptr);
1705	}
1706#endif
1707	if (tagptr) {
1708		if (tagptr->len & F_NOT)
1709			bprint_uint_arg(bp, " untag ", tagptr->arg1);
1710		else
1711			bprint_uint_arg(bp, " tag ", tagptr->arg1);
1712	}
1713
1714	/*
1715	 * then print the body.
1716	 */
1717	for (l = rule->act_ofs, cmd = rule->cmd;
1718			l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1719		if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1720			continue;
1721		if (cmd->opcode == O_IP4) {
1722			flags |= HAVE_PROTO4;
1723			break;
1724		} else if (cmd->opcode == O_IP6) {
1725			flags |= HAVE_PROTO6;
1726			break;
1727		}
1728	}
1729	if (rule->flags & IPFW_RULE_NOOPT) {	/* empty rules before options */
1730		if (!co->do_compact) {
1731			show_prerequisites(bp, &flags, HAVE_PROTO, 0);
1732			bprintf(bp, " from any to any");
1733		}
1734		flags |= HAVE_IP | HAVE_OPTIONS | HAVE_PROTO |
1735			 HAVE_SRCIP | HAVE_DSTIP;
1736	}
1737
1738	if (co->comment_only)
1739		comment = "...";
1740
1741	for (l = rule->act_ofs, cmd = rule->cmd;
1742			l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1743		/* useful alias */
1744		ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1745
1746		if (co->comment_only) {
1747			if (cmd->opcode != O_NOP)
1748				continue;
1749			bprintf(bp, " // %s\n", (char *)(cmd + 1));
1750			return;
1751		}
1752
1753		show_prerequisites(bp, &flags, 0, cmd->opcode);
1754
1755		switch(cmd->opcode) {
1756		case O_PROB:
1757			break;	/* done already */
1758
1759		case O_PROBE_STATE:
1760			break; /* no need to print anything here */
1761
1762		case O_IP_SRC:
1763		case O_IP_SRC_LOOKUP:
1764		case O_IP_SRC_MASK:
1765		case O_IP_SRC_ME:
1766		case O_IP_SRC_SET:
1767			show_prerequisites(bp, &flags, HAVE_PROTO, 0);
1768			if (!(flags & HAVE_SRCIP))
1769				bprintf(bp, " from");
1770			if ((cmd->len & F_OR) && !or_block)
1771				bprintf(bp, " {");
1772			print_ip(bp, fo, (ipfw_insn_ip *)cmd,
1773				(flags & HAVE_OPTIONS) ? " src-ip" : "");
1774			flags |= HAVE_SRCIP;
1775			break;
1776
1777		case O_IP_DST:
1778		case O_IP_DST_LOOKUP:
1779		case O_IP_DST_MASK:
1780		case O_IP_DST_ME:
1781		case O_IP_DST_SET:
1782			show_prerequisites(bp, &flags, HAVE_PROTO|HAVE_SRCIP, 0);
1783			if (!(flags & HAVE_DSTIP))
1784				bprintf(bp, " to");
1785			if ((cmd->len & F_OR) && !or_block)
1786				bprintf(bp, " {");
1787			print_ip(bp, fo, (ipfw_insn_ip *)cmd,
1788				(flags & HAVE_OPTIONS) ? " dst-ip" : "");
1789			flags |= HAVE_DSTIP;
1790			break;
1791
1792		case O_IP6_SRC:
1793		case O_IP6_SRC_MASK:
1794		case O_IP6_SRC_ME:
1795			show_prerequisites(bp, &flags, HAVE_PROTO, 0);
1796			if (!(flags & HAVE_SRCIP))
1797				bprintf(bp, " from");
1798			if ((cmd->len & F_OR) && !or_block)
1799				bprintf(bp, " {");
1800			print_ip6(bp, (ipfw_insn_ip6 *)cmd,
1801			    (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1802			flags |= HAVE_SRCIP | HAVE_PROTO;
1803			break;
1804
1805		case O_IP6_DST:
1806		case O_IP6_DST_MASK:
1807		case O_IP6_DST_ME:
1808			show_prerequisites(bp, &flags, HAVE_PROTO|HAVE_SRCIP, 0);
1809			if (!(flags & HAVE_DSTIP))
1810				bprintf(bp, " to");
1811			if ((cmd->len & F_OR) && !or_block)
1812				bprintf(bp, " {");
1813			print_ip6(bp, (ipfw_insn_ip6 *)cmd,
1814			    (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1815			flags |= HAVE_DSTIP;
1816			break;
1817
1818		case O_FLOW6ID:
1819			print_flow6id(bp, (ipfw_insn_u32 *) cmd );
1820			flags |= HAVE_OPTIONS;
1821			break;
1822
1823		case O_IP_DSTPORT:
1824			show_prerequisites(bp, &flags,
1825				HAVE_PROTO | HAVE_SRCIP |
1826				HAVE_DSTIP | HAVE_IP, 0);
1827		case O_IP_SRCPORT:
1828			if (flags & HAVE_DSTIP)
1829				flags |= HAVE_IP;
1830			show_prerequisites(bp, &flags,
1831				HAVE_PROTO | HAVE_SRCIP, 0);
1832			if ((cmd->len & F_OR) && !or_block)
1833				bprintf(bp, " {");
1834			if (cmd->len & F_NOT)
1835				bprintf(bp, " not");
1836			print_newports(bp, (ipfw_insn_u16 *)cmd, proto,
1837				(flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1838			break;
1839
1840		case O_PROTO: {
1841			struct protoent *pe = NULL;
1842
1843			if ((cmd->len & F_OR) && !or_block)
1844				bprintf(bp, " {");
1845			if (cmd->len & F_NOT)
1846				bprintf(bp, " not");
1847			proto = cmd->arg1;
1848			pe = getprotobynumber(cmd->arg1);
1849			if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1850			    !(flags & HAVE_PROTO))
1851				show_prerequisites(bp, &flags,
1852				    HAVE_PROTO | HAVE_IP | HAVE_SRCIP |
1853				    HAVE_DSTIP | HAVE_OPTIONS, 0);
1854			if (flags & HAVE_OPTIONS)
1855				bprintf(bp, " proto");
1856			if (pe)
1857				bprintf(bp, " %s", pe->p_name);
1858			else
1859				bprintf(bp, " %u", cmd->arg1);
1860			}
1861			flags |= HAVE_PROTO;
1862			break;
1863
1864		default: /*options ... */
1865			if (!(cmd->len & (F_OR|F_NOT)))
1866				if (((cmd->opcode == O_IP6) &&
1867				    (flags & HAVE_PROTO6)) ||
1868				    ((cmd->opcode == O_IP4) &&
1869				    (flags & HAVE_PROTO4)))
1870					break;
1871			show_prerequisites(bp, &flags, HAVE_PROTO | HAVE_SRCIP |
1872				    HAVE_DSTIP | HAVE_IP | HAVE_OPTIONS, 0);
1873			if ((cmd->len & F_OR) && !or_block)
1874				bprintf(bp, " {");
1875			if (cmd->len & F_NOT && cmd->opcode != O_IN)
1876				bprintf(bp, " not");
1877			switch(cmd->opcode) {
1878			case O_MACADDR2: {
1879				ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1880
1881				bprintf(bp, " MAC");
1882				print_mac(bp, m->addr, m->mask);
1883				print_mac(bp, m->addr + 6, m->mask + 6);
1884				}
1885				break;
1886
1887			case O_MAC_TYPE:
1888				print_newports(bp, (ipfw_insn_u16 *)cmd,
1889						IPPROTO_ETHERTYPE, cmd->opcode);
1890				break;
1891
1892
1893			case O_FRAG:
1894				bprintf(bp, " frag");
1895				break;
1896
1897			case O_FIB:
1898				bprintf(bp, " fib %u", cmd->arg1 );
1899				break;
1900			case O_SOCKARG:
1901				bprintf(bp, " sockarg");
1902				break;
1903
1904			case O_IN:
1905				bprintf(bp, cmd->len & F_NOT ? " out" : " in");
1906				break;
1907
1908			case O_DIVERTED:
1909				switch (cmd->arg1) {
1910				case 3:
1911					bprintf(bp, " diverted");
1912					break;
1913				case 1:
1914					bprintf(bp, " diverted-loopback");
1915					break;
1916				case 2:
1917					bprintf(bp, " diverted-output");
1918					break;
1919				default:
1920					bprintf(bp, " diverted-?<%u>", cmd->arg1);
1921					break;
1922				}
1923				break;
1924
1925			case O_LAYER2:
1926				bprintf(bp, " layer2");
1927				break;
1928			case O_XMIT:
1929			case O_RECV:
1930			case O_VIA:
1931			    {
1932				char const *s, *t;
1933				ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1934
1935				if (cmd->opcode == O_XMIT)
1936					s = "xmit";
1937				else if (cmd->opcode == O_RECV)
1938					s = "recv";
1939				else /* if (cmd->opcode == O_VIA) */
1940					s = "via";
1941				if (cmdif->name[0] == '\0')
1942					bprintf(bp, " %s %s", s,
1943					    inet_ntoa(cmdif->p.ip));
1944				else if (cmdif->name[0] == '\1') {
1945					/* interface table */
1946					t = table_search_ctlv(fo->tstate,
1947					    cmdif->p.kidx);
1948					bprintf(bp, " %s table(%s)", s, t);
1949				} else
1950					bprintf(bp, " %s %s", s, cmdif->name);
1951
1952				break;
1953			    }
1954			case O_IP_FLOW_LOOKUP:
1955			    {
1956				char *t;
1957
1958				t = table_search_ctlv(fo->tstate, cmd->arg1);
1959				bprintf(bp, " flow table(%s", t);
1960				if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))
1961					bprintf(bp, ",%u",
1962					    ((ipfw_insn_u32 *)cmd)->d[0]);
1963				bprintf(bp, ")");
1964				break;
1965			    }
1966			case O_IPID:
1967				if (F_LEN(cmd) == 1)
1968				    bprintf(bp, " ipid %u", cmd->arg1 );
1969				else
1970				    print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1971					O_IPID);
1972				break;
1973
1974			case O_IPTTL:
1975				if (F_LEN(cmd) == 1)
1976				    bprintf(bp, " ipttl %u", cmd->arg1 );
1977				else
1978				    print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1979					O_IPTTL);
1980				break;
1981
1982			case O_IPVER:
1983				bprintf(bp, " ipver %u", cmd->arg1 );
1984				break;
1985
1986			case O_IPPRECEDENCE:
1987				bprintf(bp, " ipprecedence %u", cmd->arg1 >> 5);
1988				break;
1989
1990			case O_DSCP:
1991				print_dscp(bp, (ipfw_insn_u32 *)cmd);
1992	 			break;
1993
1994			case O_IPLEN:
1995				if (F_LEN(cmd) == 1)
1996				    bprintf(bp, " iplen %u", cmd->arg1 );
1997				else
1998				    print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1999					O_IPLEN);
2000				break;
2001
2002			case O_IPOPT:
2003				print_flags(bp, "ipoptions", cmd, f_ipopts);
2004				break;
2005
2006			case O_IPTOS:
2007				print_flags(bp, "iptos", cmd, f_iptos);
2008				break;
2009
2010			case O_ICMPTYPE:
2011				print_icmptypes(bp, (ipfw_insn_u32 *)cmd);
2012				break;
2013
2014			case O_ESTAB:
2015				bprintf(bp, " established");
2016				break;
2017
2018			case O_TCPDATALEN:
2019				if (F_LEN(cmd) == 1)
2020				    bprintf(bp, " tcpdatalen %u", cmd->arg1 );
2021				else
2022				    print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
2023					O_TCPDATALEN);
2024				break;
2025
2026			case O_TCPFLAGS:
2027				print_flags(bp, "tcpflags", cmd, f_tcpflags);
2028				break;
2029
2030			case O_TCPOPTS:
2031				print_flags(bp, "tcpoptions", cmd, f_tcpopts);
2032				break;
2033
2034			case O_TCPWIN:
2035				if (F_LEN(cmd) == 1)
2036				    bprintf(bp, " tcpwin %u", cmd->arg1);
2037				else
2038				    print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
2039					O_TCPWIN);
2040				break;
2041
2042			case O_TCPACK:
2043				bprintf(bp, " tcpack %d", ntohl(cmd32->d[0]));
2044				break;
2045
2046			case O_TCPSEQ:
2047				bprintf(bp, " tcpseq %d", ntohl(cmd32->d[0]));
2048				break;
2049
2050			case O_UID:
2051			    {
2052				struct passwd *pwd = getpwuid(cmd32->d[0]);
2053
2054				if (pwd)
2055					bprintf(bp, " uid %s", pwd->pw_name);
2056				else
2057					bprintf(bp, " uid %u", cmd32->d[0]);
2058			    }
2059				break;
2060
2061			case O_GID:
2062			    {
2063				struct group *grp = getgrgid(cmd32->d[0]);
2064
2065				if (grp)
2066					bprintf(bp, " gid %s", grp->gr_name);
2067				else
2068					bprintf(bp, " gid %u", cmd32->d[0]);
2069			    }
2070				break;
2071
2072			case O_JAIL:
2073				bprintf(bp, " jail %d", cmd32->d[0]);
2074				break;
2075
2076			case O_VERREVPATH:
2077				bprintf(bp, " verrevpath");
2078				break;
2079
2080			case O_VERSRCREACH:
2081				bprintf(bp, " versrcreach");
2082				break;
2083
2084			case O_ANTISPOOF:
2085				bprintf(bp, " antispoof");
2086				break;
2087
2088			case O_IPSEC:
2089				bprintf(bp, " ipsec");
2090				break;
2091
2092			case O_NOP:
2093				comment = (char *)(cmd + 1);
2094				break;
2095
2096			case O_KEEP_STATE:
2097				bprintf(bp, " keep-state");
2098				bprintf(bp, " :%s",
2099				    object_search_ctlv(fo->tstate, cmd->arg1,
2100				    IPFW_TLV_STATE_NAME));
2101				break;
2102
2103			case O_LIMIT: {
2104				struct _s_x *p = limit_masks;
2105				ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
2106				uint8_t x = c->limit_mask;
2107				char const *comma = " ";
2108
2109				bprintf(bp, " limit");
2110				for (; p->x != 0 ; p++)
2111					if ((x & p->x) == p->x) {
2112						x &= ~p->x;
2113						bprintf(bp, "%s%s", comma,p->s);
2114						comma = ",";
2115					}
2116				bprint_uint_arg(bp, " ", c->conn_limit);
2117				bprintf(bp, " :%s",
2118				    object_search_ctlv(fo->tstate, cmd->arg1,
2119				    IPFW_TLV_STATE_NAME));
2120				break;
2121			}
2122
2123			case O_IP6:
2124				bprintf(bp, " ip6");
2125				break;
2126
2127			case O_IP4:
2128				bprintf(bp, " ip4");
2129				break;
2130
2131			case O_ICMP6TYPE:
2132				print_icmp6types(bp, (ipfw_insn_u32 *)cmd);
2133				break;
2134
2135			case O_EXT_HDR:
2136				print_ext6hdr(bp, (ipfw_insn *)cmd);
2137				break;
2138
2139			case O_TAGGED:
2140				if (F_LEN(cmd) == 1)
2141					bprint_uint_arg(bp, " tagged ",
2142					    cmd->arg1);
2143				else
2144					print_newports(bp, (ipfw_insn_u16 *)cmd,
2145					    0, O_TAGGED);
2146				break;
2147
2148			default:
2149				bprintf(bp, " [opcode %d len %d]",
2150				    cmd->opcode, cmd->len);
2151			}
2152		}
2153		if (cmd->len & F_OR) {
2154			bprintf(bp, " or");
2155			or_block = 1;
2156		} else if (or_block) {
2157			bprintf(bp, " }");
2158			or_block = 0;
2159		}
2160	}
2161	show_prerequisites(bp, &flags, HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP
2162					      | HAVE_IP, 0);
2163	if (comment)
2164		bprintf(bp, " // %s", comment);
2165	bprintf(bp, "\n");
2166}
2167
2168static void
2169show_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2170    struct buf_pr *bp, ipfw_dyn_rule *d)
2171{
2172	struct protoent *pe;
2173	struct in_addr a;
2174	uint16_t rulenum;
2175	char buf[INET6_ADDRSTRLEN];
2176
2177	if (!co->do_expired) {
2178		if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
2179			return;
2180	}
2181	bcopy(&d->rule, &rulenum, sizeof(rulenum));
2182	bprintf(bp, "%05d", rulenum);
2183	if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2184		bprintf(bp, " ");
2185		pr_u64(bp, &d->pcnt, fo->pcwidth);
2186		pr_u64(bp, &d->bcnt, fo->bcwidth);
2187		bprintf(bp, "(%ds)", d->expire);
2188	}
2189	switch (d->dyn_type) {
2190	case O_LIMIT_PARENT:
2191		bprintf(bp, " PARENT %d", d->count);
2192		break;
2193	case O_LIMIT:
2194		bprintf(bp, " LIMIT");
2195		break;
2196	case O_KEEP_STATE: /* bidir, no mask */
2197		bprintf(bp, " STATE");
2198		break;
2199	}
2200
2201	if ((pe = getprotobynumber(d->id.proto)) != NULL)
2202		bprintf(bp, " %s", pe->p_name);
2203	else
2204		bprintf(bp, " proto %u", d->id.proto);
2205
2206	if (d->id.addr_type == 4) {
2207		a.s_addr = htonl(d->id.src_ip);
2208		bprintf(bp, " %s %d", inet_ntoa(a), d->id.src_port);
2209
2210		a.s_addr = htonl(d->id.dst_ip);
2211		bprintf(bp, " <-> %s %d", inet_ntoa(a), d->id.dst_port);
2212	} else if (d->id.addr_type == 6) {
2213		bprintf(bp, " %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2214		    sizeof(buf)), d->id.src_port);
2215		bprintf(bp, " <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6,
2216		    buf, sizeof(buf)), d->id.dst_port);
2217	} else
2218		bprintf(bp, " UNKNOWN <-> UNKNOWN");
2219	if (d->kidx != 0)
2220		bprintf(bp, " :%s", object_search_ctlv(fo->tstate,
2221		    d->kidx, IPFW_TLV_STATE_NAME));
2222}
2223
2224static int
2225do_range_cmd(int cmd, ipfw_range_tlv *rt)
2226{
2227	ipfw_range_header rh;
2228	size_t sz;
2229
2230	memset(&rh, 0, sizeof(rh));
2231	memcpy(&rh.range, rt, sizeof(*rt));
2232	rh.range.head.length = sizeof(*rt);
2233	rh.range.head.type = IPFW_TLV_RANGE;
2234	sz = sizeof(rh);
2235
2236	if (do_get3(cmd, &rh.opheader, &sz) != 0)
2237		return (-1);
2238	/* Save number of matched objects */
2239	rt->new_set = rh.range.new_set;
2240	return (0);
2241}
2242
2243/*
2244 * This one handles all set-related commands
2245 * 	ipfw set { show | enable | disable }
2246 * 	ipfw set swap X Y
2247 * 	ipfw set move X to Y
2248 * 	ipfw set move rule X to Y
2249 */
2250void
2251ipfw_sets_handler(char *av[])
2252{
2253	ipfw_range_tlv rt;
2254	char *msg;
2255	size_t size;
2256	uint32_t masks[2];
2257	int i;
2258	uint16_t rulenum;
2259	uint8_t cmd;
2260
2261	av++;
2262	memset(&rt, 0, sizeof(rt));
2263
2264	if (av[0] == NULL)
2265		errx(EX_USAGE, "set needs command");
2266	if (_substrcmp(*av, "show") == 0) {
2267		struct format_opts fo;
2268		ipfw_cfg_lheader *cfg;
2269
2270		memset(&fo, 0, sizeof(fo));
2271		if (ipfw_get_config(&co, &fo, &cfg, &size) != 0)
2272			err(EX_OSERR, "requesting config failed");
2273
2274		for (i = 0, msg = "disable"; i < RESVD_SET; i++)
2275			if ((cfg->set_mask & (1<<i)) == 0) {
2276				printf("%s %d", msg, i);
2277				msg = "";
2278			}
2279		msg = (cfg->set_mask != (uint32_t)-1) ? " enable" : "enable";
2280		for (i = 0; i < RESVD_SET; i++)
2281			if ((cfg->set_mask & (1<<i)) != 0) {
2282				printf("%s %d", msg, i);
2283				msg = "";
2284			}
2285		printf("\n");
2286		free(cfg);
2287	} else if (_substrcmp(*av, "swap") == 0) {
2288		av++;
2289		if ( av[0] == NULL || av[1] == NULL )
2290			errx(EX_USAGE, "set swap needs 2 set numbers\n");
2291		rt.set = atoi(av[0]);
2292		rt.new_set = atoi(av[1]);
2293		if (!isdigit(*(av[0])) || rt.set > RESVD_SET)
2294			errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2295		if (!isdigit(*(av[1])) || rt.new_set > RESVD_SET)
2296			errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2297		i = do_range_cmd(IP_FW_SET_SWAP, &rt);
2298	} else if (_substrcmp(*av, "move") == 0) {
2299		av++;
2300		if (av[0] && _substrcmp(*av, "rule") == 0) {
2301			rt.flags = IPFW_RCFLAG_RANGE; /* move rules to new set */
2302			cmd = IP_FW_XMOVE;
2303			av++;
2304		} else
2305			cmd = IP_FW_SET_MOVE; /* Move set to new one */
2306		if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
2307				av[3] != NULL ||  _substrcmp(av[1], "to") != 0)
2308			errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2309		rulenum = atoi(av[0]);
2310		rt.new_set = atoi(av[2]);
2311		if (cmd == IP_FW_XMOVE) {
2312			rt.start_rule = rulenum;
2313			rt.end_rule = rulenum;
2314		} else
2315			rt.set = rulenum;
2316		rt.new_set = atoi(av[2]);
2317		if (!isdigit(*(av[0])) || (cmd == 3 && rt.set > RESVD_SET) ||
2318			(cmd == 2 && rt.start_rule == IPFW_DEFAULT_RULE) )
2319			errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2320		if (!isdigit(*(av[2])) || rt.new_set > RESVD_SET)
2321			errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2322		i = do_range_cmd(cmd, &rt);
2323		if (i < 0)
2324			err(EX_OSERR, "failed to move %s",
2325			    cmd == IP_FW_SET_MOVE ? "set": "rule");
2326	} else if (_substrcmp(*av, "disable") == 0 ||
2327		   _substrcmp(*av, "enable") == 0 ) {
2328		int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2329
2330		av++;
2331		masks[0] = masks[1] = 0;
2332
2333		while (av[0]) {
2334			if (isdigit(**av)) {
2335				i = atoi(*av);
2336				if (i < 0 || i > RESVD_SET)
2337					errx(EX_DATAERR,
2338					    "invalid set number %d\n", i);
2339				masks[which] |= (1<<i);
2340			} else if (_substrcmp(*av, "disable") == 0)
2341				which = 0;
2342			else if (_substrcmp(*av, "enable") == 0)
2343				which = 1;
2344			else
2345				errx(EX_DATAERR,
2346					"invalid set command %s\n", *av);
2347			av++;
2348		}
2349		if ( (masks[0] & masks[1]) != 0 )
2350			errx(EX_DATAERR,
2351			    "cannot enable and disable the same set\n");
2352
2353		rt.set = masks[0];
2354		rt.new_set = masks[1];
2355		i = do_range_cmd(IP_FW_SET_ENABLE, &rt);
2356		if (i)
2357			warn("set enable/disable: setsockopt(IP_FW_SET_ENABLE)");
2358	} else
2359		errx(EX_USAGE, "invalid set command %s\n", *av);
2360}
2361
2362void
2363ipfw_sysctl_handler(char *av[], int which)
2364{
2365	av++;
2366
2367	if (av[0] == NULL) {
2368		warnx("missing keyword to enable/disable\n");
2369	} else if (_substrcmp(*av, "firewall") == 0) {
2370		sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2371		    &which, sizeof(which));
2372		sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
2373		    &which, sizeof(which));
2374	} else if (_substrcmp(*av, "one_pass") == 0) {
2375		sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2376		    &which, sizeof(which));
2377	} else if (_substrcmp(*av, "debug") == 0) {
2378		sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2379		    &which, sizeof(which));
2380	} else if (_substrcmp(*av, "verbose") == 0) {
2381		sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2382		    &which, sizeof(which));
2383	} else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2384		sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2385		    &which, sizeof(which));
2386#ifndef NO_ALTQ
2387	} else if (_substrcmp(*av, "altq") == 0) {
2388		altq_set_enabled(which);
2389#endif
2390	} else {
2391		warnx("unrecognize enable/disable keyword: %s\n", *av);
2392	}
2393}
2394
2395typedef void state_cb(struct cmdline_opts *co, struct format_opts *fo,
2396    void *arg, void *state);
2397
2398static void
2399prepare_format_dyn(struct cmdline_opts *co, struct format_opts *fo,
2400    void *arg, void *_state)
2401{
2402	ipfw_dyn_rule *d;
2403	int width;
2404	uint8_t set;
2405
2406	d = (ipfw_dyn_rule *)_state;
2407	/* Count _ALL_ states */
2408	fo->dcnt++;
2409
2410	if (fo->show_counters == 0)
2411		return;
2412
2413	if (co->use_set) {
2414		/* skip states from another set */
2415		bcopy((char *)&d->rule + sizeof(uint16_t), &set,
2416		    sizeof(uint8_t));
2417		if (set != co->use_set - 1)
2418			return;
2419	}
2420
2421	width = pr_u64(NULL, &d->pcnt, 0);
2422	if (width > fo->pcwidth)
2423		fo->pcwidth = width;
2424
2425	width = pr_u64(NULL, &d->bcnt, 0);
2426	if (width > fo->bcwidth)
2427		fo->bcwidth = width;
2428}
2429
2430static int
2431foreach_state(struct cmdline_opts *co, struct format_opts *fo,
2432    caddr_t base, size_t sz, state_cb dyn_bc, void *dyn_arg)
2433{
2434	int ttype;
2435	state_cb *fptr;
2436	void *farg;
2437	ipfw_obj_tlv *tlv;
2438	ipfw_obj_ctlv *ctlv;
2439
2440	fptr = NULL;
2441	ttype = 0;
2442
2443	while (sz > 0) {
2444		ctlv = (ipfw_obj_ctlv *)base;
2445		switch (ctlv->head.type) {
2446		case IPFW_TLV_DYNSTATE_LIST:
2447			base += sizeof(*ctlv);
2448			sz -= sizeof(*ctlv);
2449			ttype = IPFW_TLV_DYN_ENT;
2450			fptr = dyn_bc;
2451			farg = dyn_arg;
2452			break;
2453		default:
2454			return (sz);
2455		}
2456
2457		while (sz > 0) {
2458			tlv = (ipfw_obj_tlv *)base;
2459			if (tlv->type != ttype)
2460				break;
2461
2462			fptr(co, fo, farg, tlv + 1);
2463			sz -= tlv->length;
2464			base += tlv->length;
2465		}
2466	}
2467
2468	return (sz);
2469}
2470
2471static void
2472prepare_format_opts(struct cmdline_opts *co, struct format_opts *fo,
2473    ipfw_obj_tlv *rtlv, int rcnt, caddr_t dynbase, size_t dynsz)
2474{
2475	int bcwidth, pcwidth, width;
2476	int n;
2477	struct ip_fw_bcounter *cntr;
2478	struct ip_fw_rule *r;
2479
2480	bcwidth = 0;
2481	pcwidth = 0;
2482	if (fo->show_counters != 0) {
2483		for (n = 0; n < rcnt; n++,
2484		    rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2485			cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2486			r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2487			/* skip rules from another set */
2488			if (co->use_set && r->set != co->use_set - 1)
2489				continue;
2490
2491			/* packet counter */
2492			width = pr_u64(NULL, &cntr->pcnt, 0);
2493			if (width > pcwidth)
2494				pcwidth = width;
2495
2496			/* byte counter */
2497			width = pr_u64(NULL, &cntr->bcnt, 0);
2498			if (width > bcwidth)
2499				bcwidth = width;
2500		}
2501	}
2502	fo->bcwidth = bcwidth;
2503	fo->pcwidth = pcwidth;
2504
2505	fo->dcnt = 0;
2506	if (co->do_dynamic && dynsz > 0)
2507		foreach_state(co, fo, dynbase, dynsz, prepare_format_dyn, NULL);
2508}
2509
2510static int
2511list_static_range(struct cmdline_opts *co, struct format_opts *fo,
2512    struct buf_pr *bp, ipfw_obj_tlv *rtlv, int rcnt)
2513{
2514	int n, seen;
2515	struct ip_fw_rule *r;
2516	struct ip_fw_bcounter *cntr;
2517	int c = 0;
2518
2519	for (n = seen = 0; n < rcnt; n++,
2520	    rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2521
2522		if ((fo->show_counters | fo->show_time) != 0) {
2523			cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2524			r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2525		} else {
2526			cntr = NULL;
2527			r = (struct ip_fw_rule *)(rtlv + 1);
2528		}
2529		if (r->rulenum > fo->last)
2530			break;
2531		if (co->use_set && r->set != co->use_set - 1)
2532			continue;
2533		if (r->rulenum >= fo->first && r->rulenum <= fo->last) {
2534			show_static_rule(co, fo, bp, r, cntr);
2535			printf("%s", bp->buf);
2536			c += rtlv->length;
2537			bp_flush(bp);
2538			seen++;
2539		}
2540	}
2541
2542	return (seen);
2543}
2544
2545static void
2546list_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2547    void *_arg, void *_state)
2548{
2549	uint16_t rulenum;
2550	uint8_t set;
2551	ipfw_dyn_rule *d;
2552	struct buf_pr *bp;
2553
2554	d = (ipfw_dyn_rule *)_state;
2555	bp = (struct buf_pr *)_arg;
2556
2557	bcopy(&d->rule, &rulenum, sizeof(rulenum));
2558	if (rulenum > fo->last)
2559		return;
2560	if (co->use_set) {
2561		bcopy((char *)&d->rule + sizeof(uint16_t),
2562		      &set, sizeof(uint8_t));
2563		if (set != co->use_set - 1)
2564			return;
2565	}
2566	if (rulenum >= fo->first) {
2567		show_dyn_state(co, fo, bp, d);
2568		printf("%s\n", bp->buf);
2569		bp_flush(bp);
2570	}
2571}
2572
2573static int
2574list_dyn_range(struct cmdline_opts *co, struct format_opts *fo,
2575    struct buf_pr *bp, caddr_t base, size_t sz)
2576{
2577
2578	sz = foreach_state(co, fo, base, sz, list_dyn_state, bp);
2579	return (sz);
2580}
2581
2582void
2583ipfw_list(int ac, char *av[], int show_counters)
2584{
2585	ipfw_cfg_lheader *cfg;
2586	struct format_opts sfo;
2587	size_t sz;
2588	int error;
2589	int lac;
2590	char **lav;
2591	uint32_t rnum;
2592	char *endptr;
2593
2594	if (co.test_only) {
2595		fprintf(stderr, "Testing only, list disabled\n");
2596		return;
2597	}
2598	if (co.do_pipe) {
2599		dummynet_list(ac, av, show_counters);
2600		return;
2601	}
2602
2603	ac--;
2604	av++;
2605	memset(&sfo, 0, sizeof(sfo));
2606
2607	/* Determine rule range to request */
2608	if (ac > 0) {
2609		for (lac = ac, lav = av; lac != 0; lac--) {
2610			rnum = strtoul(*lav++, &endptr, 10);
2611			if (sfo.first == 0 || rnum < sfo.first)
2612				sfo.first = rnum;
2613
2614			if (*endptr == '-')
2615				rnum = strtoul(endptr + 1, &endptr, 10);
2616			if (sfo.last == 0 || rnum > sfo.last)
2617				sfo.last = rnum;
2618		}
2619	}
2620
2621	/* get configuraion from kernel */
2622	cfg = NULL;
2623	sfo.show_counters = show_counters;
2624	sfo.show_time = co.do_time;
2625	sfo.flags = IPFW_CFG_GET_STATIC;
2626	if (co.do_dynamic != 0)
2627		sfo.flags |= IPFW_CFG_GET_STATES;
2628	if ((sfo.show_counters | sfo.show_time) != 0)
2629		sfo.flags |= IPFW_CFG_GET_COUNTERS;
2630	if (ipfw_get_config(&co, &sfo, &cfg, &sz) != 0)
2631		err(EX_OSERR, "retrieving config failed");
2632
2633	error = ipfw_show_config(&co, &sfo, cfg, sz, ac, av);
2634
2635	free(cfg);
2636
2637	if (error != EX_OK)
2638		exit(error);
2639}
2640
2641static int
2642ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
2643    ipfw_cfg_lheader *cfg, size_t sz, int ac, char *av[])
2644{
2645	caddr_t dynbase;
2646	size_t dynsz;
2647	int rcnt;
2648	int exitval = EX_OK;
2649	int lac;
2650	char **lav;
2651	char *endptr;
2652	size_t readsz;
2653	struct buf_pr bp;
2654	ipfw_obj_ctlv *ctlv, *tstate;
2655	ipfw_obj_tlv *rbase;
2656
2657	/*
2658	 * Handle tablenames TLV first, if any
2659	 */
2660	tstate = NULL;
2661	rbase = NULL;
2662	dynbase = NULL;
2663	dynsz = 0;
2664	readsz = sizeof(*cfg);
2665	rcnt = 0;
2666
2667	fo->set_mask = cfg->set_mask;
2668
2669	ctlv = (ipfw_obj_ctlv *)(cfg + 1);
2670
2671	if (cfg->flags & IPFW_CFG_GET_STATIC) {
2672		/* We've requested static rules */
2673		if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2674			object_sort_ctlv(ctlv);
2675			fo->tstate = ctlv;
2676			readsz += ctlv->head.length;
2677			ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2678			    ctlv->head.length);
2679		}
2680
2681		if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2682			rbase = (ipfw_obj_tlv *)(ctlv + 1);
2683			rcnt = ctlv->count;
2684			readsz += ctlv->head.length;
2685			ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2686			    ctlv->head.length);
2687		}
2688	}
2689
2690	if ((cfg->flags & IPFW_CFG_GET_STATES) && (readsz != sz))  {
2691		/* We may have some dynamic states */
2692		dynsz = sz - readsz;
2693		/* Skip empty header */
2694		if (dynsz != sizeof(ipfw_obj_ctlv))
2695			dynbase = (caddr_t)ctlv;
2696		else
2697			dynsz = 0;
2698	}
2699
2700	prepare_format_opts(co, fo, rbase, rcnt, dynbase, dynsz);
2701	bp_alloc(&bp, 4096);
2702
2703	/* if no rule numbers were specified, list all rules */
2704	if (ac == 0) {
2705		fo->first = 0;
2706		fo->last = IPFW_DEFAULT_RULE;
2707		list_static_range(co, fo, &bp, rbase, rcnt);
2708
2709		if (co->do_dynamic && dynsz > 0) {
2710			printf("## Dynamic rules (%d %zu):\n", fo->dcnt, dynsz);
2711			list_dyn_range(co, fo, &bp, dynbase, dynsz);
2712		}
2713
2714		bp_free(&bp);
2715		return (EX_OK);
2716	}
2717
2718	/* display specific rules requested on command line */
2719	for (lac = ac, lav = av; lac != 0; lac--) {
2720		/* convert command line rule # */
2721		fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2722		if (*endptr == '-')
2723			fo->last = strtoul(endptr + 1, &endptr, 10);
2724		if (*endptr) {
2725			exitval = EX_USAGE;
2726			warnx("invalid rule number: %s", *(lav - 1));
2727			continue;
2728		}
2729
2730		if (list_static_range(co, fo, &bp, rbase, rcnt) == 0) {
2731			/* give precedence to other error(s) */
2732			if (exitval == EX_OK)
2733				exitval = EX_UNAVAILABLE;
2734			if (fo->first == fo->last)
2735				warnx("rule %u does not exist", fo->first);
2736			else
2737				warnx("no rules in range %u-%u",
2738				    fo->first, fo->last);
2739		}
2740	}
2741
2742	if (co->do_dynamic && dynsz > 0) {
2743		printf("## Dynamic rules:\n");
2744		for (lac = ac, lav = av; lac != 0; lac--) {
2745			fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2746			if (*endptr == '-')
2747				fo->last = strtoul(endptr+1, &endptr, 10);
2748			if (*endptr)
2749				/* already warned */
2750				continue;
2751			list_dyn_range(co, fo, &bp, dynbase, dynsz);
2752		}
2753	}
2754
2755	bp_free(&bp);
2756	return (exitval);
2757}
2758
2759
2760/*
2761 * Retrieves current ipfw configuration of given type
2762 * and stores its pointer to @pcfg.
2763 *
2764 * Caller is responsible for freeing @pcfg.
2765 *
2766 * Returns 0 on success.
2767 */
2768
2769static int
2770ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
2771    ipfw_cfg_lheader **pcfg, size_t *psize)
2772{
2773	ipfw_cfg_lheader *cfg;
2774	size_t sz;
2775	int i;
2776
2777
2778	if (co->test_only != 0) {
2779		fprintf(stderr, "Testing only, list disabled\n");
2780		return (0);
2781	}
2782
2783	/* Start with some data size */
2784	sz = 4096;
2785	cfg = NULL;
2786
2787	for (i = 0; i < 16; i++) {
2788		if (cfg != NULL)
2789			free(cfg);
2790		if ((cfg = calloc(1, sz)) == NULL)
2791			return (ENOMEM);
2792
2793		cfg->flags = fo->flags;
2794		cfg->start_rule = fo->first;
2795		cfg->end_rule = fo->last;
2796
2797		if (do_get3(IP_FW_XGET, &cfg->opheader, &sz) != 0) {
2798			if (errno != ENOMEM) {
2799				free(cfg);
2800				return (errno);
2801			}
2802
2803			/* Buffer size is not enough. Try to increase */
2804			sz = sz * 2;
2805			if (sz < cfg->size)
2806				sz = cfg->size;
2807			continue;
2808		}
2809
2810		*pcfg = cfg;
2811		*psize = sz;
2812		return (0);
2813	}
2814
2815	free(cfg);
2816	return (ENOMEM);
2817}
2818
2819static int
2820lookup_host (char *host, struct in_addr *ipaddr)
2821{
2822	struct hostent *he;
2823
2824	if (!inet_aton(host, ipaddr)) {
2825		if ((he = gethostbyname(host)) == NULL)
2826			return(-1);
2827		*ipaddr = *(struct in_addr *)he->h_addr_list[0];
2828	}
2829	return(0);
2830}
2831
2832struct tidx {
2833	ipfw_obj_ntlv *idx;
2834	uint32_t count;
2835	uint32_t size;
2836	uint16_t counter;
2837	uint8_t set;
2838};
2839
2840int
2841ipfw_check_object_name(const char *name)
2842{
2843	int c, i, l;
2844
2845	/*
2846	 * Check that name is null-terminated and contains
2847	 * valid symbols only. Valid mask is:
2848	 * [a-zA-Z0-9\-_\.]{1,63}
2849	 */
2850	l = strlen(name);
2851	if (l == 0 || l >= 64)
2852		return (EINVAL);
2853	for (i = 0; i < l; i++) {
2854		c = name[i];
2855		if (isalpha(c) || isdigit(c) || c == '_' ||
2856		    c == '-' || c == '.')
2857			continue;
2858		return (EINVAL);
2859	}
2860	return (0);
2861}
2862
2863static char *default_state_name = "default";
2864static int
2865state_check_name(const char *name)
2866{
2867
2868	if (ipfw_check_object_name(name) != 0)
2869		return (EINVAL);
2870	if (strcmp(name, "any") == 0)
2871		return (EINVAL);
2872	return (0);
2873}
2874
2875static int
2876eaction_check_name(const char *name)
2877{
2878
2879	if (ipfw_check_object_name(name) != 0)
2880		return (EINVAL);
2881	/* Restrict some 'special' names */
2882	if (match_token(rule_actions, name) != -1 &&
2883	    match_token(rule_action_params, name) != -1)
2884		return (EINVAL);
2885	return (0);
2886}
2887
2888static uint16_t
2889pack_object(struct tidx *tstate, char *name, int otype)
2890{
2891	int i;
2892	ipfw_obj_ntlv *ntlv;
2893
2894	for (i = 0; i < tstate->count; i++) {
2895		if (strcmp(tstate->idx[i].name, name) != 0)
2896			continue;
2897		if (tstate->idx[i].set != tstate->set)
2898			continue;
2899		if (tstate->idx[i].head.type != otype)
2900			continue;
2901
2902		return (tstate->idx[i].idx);
2903	}
2904
2905	if (tstate->count + 1 > tstate->size) {
2906		tstate->size += 4;
2907		tstate->idx = realloc(tstate->idx, tstate->size *
2908		    sizeof(ipfw_obj_ntlv));
2909		if (tstate->idx == NULL)
2910			return (0);
2911	}
2912
2913	ntlv = &tstate->idx[i];
2914	memset(ntlv, 0, sizeof(ipfw_obj_ntlv));
2915	strlcpy(ntlv->name, name, sizeof(ntlv->name));
2916	ntlv->head.type = otype;
2917	ntlv->head.length = sizeof(ipfw_obj_ntlv);
2918	ntlv->set = tstate->set;
2919	ntlv->idx = ++tstate->counter;
2920	tstate->count++;
2921
2922	return (ntlv->idx);
2923}
2924
2925static uint16_t
2926pack_table(struct tidx *tstate, char *name)
2927{
2928
2929	if (table_check_name(name) != 0)
2930		return (0);
2931
2932	return (pack_object(tstate, name, IPFW_TLV_TBL_NAME));
2933}
2934
2935void
2936fill_table(struct _ipfw_insn *cmd, char *av, uint8_t opcode,
2937    struct tidx *tstate)
2938{
2939	uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2940	uint16_t uidx;
2941	char *p;
2942
2943	if ((p = strchr(av + 6, ')')) == NULL)
2944		errx(EX_DATAERR, "forgotten parenthesis: '%s'", av);
2945	*p = '\0';
2946	p = strchr(av + 6, ',');
2947	if (p)
2948		*p++ = '\0';
2949
2950	if ((uidx = pack_table(tstate, av + 6)) == 0)
2951		errx(EX_DATAERR, "Invalid table name: %s", av + 6);
2952
2953	cmd->opcode = opcode;
2954	cmd->arg1 = uidx;
2955	if (p) {
2956		cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
2957		d[0] = strtoul(p, NULL, 0);
2958	} else
2959		cmd->len |= F_INSN_SIZE(ipfw_insn);
2960}
2961
2962
2963/*
2964 * fills the addr and mask fields in the instruction as appropriate from av.
2965 * Update length as appropriate.
2966 * The following formats are allowed:
2967 *	me	returns O_IP_*_ME
2968 *	1.2.3.4		single IP address
2969 *	1.2.3.4:5.6.7.8	address:mask
2970 *	1.2.3.4/24	address/mask
2971 *	1.2.3.4/26{1,6,5,4,23}	set of addresses in a subnet
2972 * We can have multiple comma-separated address/mask entries.
2973 */
2974static void
2975fill_ip(ipfw_insn_ip *cmd, char *av, int cblen, struct tidx *tstate)
2976{
2977	int len = 0;
2978	uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2979
2980	cmd->o.len &= ~F_LEN_MASK;	/* zero len */
2981
2982	if (_substrcmp(av, "any") == 0)
2983		return;
2984
2985	if (_substrcmp(av, "me") == 0) {
2986		cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2987		return;
2988	}
2989
2990	if (strncmp(av, "table(", 6) == 0) {
2991		fill_table(&cmd->o, av, O_IP_DST_LOOKUP, tstate);
2992		return;
2993	}
2994
2995    while (av) {
2996	/*
2997	 * After the address we can have '/' or ':' indicating a mask,
2998	 * ',' indicating another address follows, '{' indicating a
2999	 * set of addresses of unspecified size.
3000	 */
3001	char *t = NULL, *p = strpbrk(av, "/:,{");
3002	int masklen;
3003	char md, nd = '\0';
3004
3005	CHECK_LENGTH(cblen, F_INSN_SIZE(ipfw_insn) + 2 + len);
3006
3007	if (p) {
3008		md = *p;
3009		*p++ = '\0';
3010		if ((t = strpbrk(p, ",{")) != NULL) {
3011			nd = *t;
3012			*t = '\0';
3013		}
3014	} else
3015		md = '\0';
3016
3017	if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
3018		errx(EX_NOHOST, "hostname ``%s'' unknown", av);
3019	switch (md) {
3020	case ':':
3021		if (!inet_aton(p, (struct in_addr *)&d[1]))
3022			errx(EX_DATAERR, "bad netmask ``%s''", p);
3023		break;
3024	case '/':
3025		masklen = atoi(p);
3026		if (masklen == 0)
3027			d[1] = htonl(0U);	/* mask */
3028		else if (masklen > 32)
3029			errx(EX_DATAERR, "bad width ``%s''", p);
3030		else
3031			d[1] = htonl(~0U << (32 - masklen));
3032		break;
3033	case '{':	/* no mask, assume /24 and put back the '{' */
3034		d[1] = htonl(~0U << (32 - 24));
3035		*(--p) = md;
3036		break;
3037
3038	case ',':	/* single address plus continuation */
3039		*(--p) = md;
3040		/* FALLTHROUGH */
3041	case 0:		/* initialization value */
3042	default:
3043		d[1] = htonl(~0U);	/* force /32 */
3044		break;
3045	}
3046	d[0] &= d[1];		/* mask base address with mask */
3047	if (t)
3048		*t = nd;
3049	/* find next separator */
3050	if (p)
3051		p = strpbrk(p, ",{");
3052	if (p && *p == '{') {
3053		/*
3054		 * We have a set of addresses. They are stored as follows:
3055		 *   arg1	is the set size (powers of 2, 2..256)
3056		 *   addr	is the base address IN HOST FORMAT
3057		 *   mask..	is an array of arg1 bits (rounded up to
3058		 *		the next multiple of 32) with bits set
3059		 *		for each host in the map.
3060		 */
3061		uint32_t *map = (uint32_t *)&cmd->mask;
3062		int low, high;
3063		int i = contigmask((uint8_t *)&(d[1]), 32);
3064
3065		if (len > 0)
3066			errx(EX_DATAERR, "address set cannot be in a list");
3067		if (i < 24 || i > 31)
3068			errx(EX_DATAERR, "invalid set with mask %d\n", i);
3069		cmd->o.arg1 = 1<<(32-i);	/* map length		*/
3070		d[0] = ntohl(d[0]);		/* base addr in host format */
3071		cmd->o.opcode = O_IP_DST_SET;	/* default */
3072		cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
3073		for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
3074			map[i] = 0;	/* clear map */
3075
3076		av = p + 1;
3077		low = d[0] & 0xff;
3078		high = low + cmd->o.arg1 - 1;
3079		/*
3080		 * Here, i stores the previous value when we specify a range
3081		 * of addresses within a mask, e.g. 45-63. i = -1 means we
3082		 * have no previous value.
3083		 */
3084		i = -1;	/* previous value in a range */
3085		while (isdigit(*av)) {
3086			char *s;
3087			int a = strtol(av, &s, 0);
3088
3089			if (s == av) { /* no parameter */
3090			    if (*av != '}')
3091				errx(EX_DATAERR, "set not closed\n");
3092			    if (i != -1)
3093				errx(EX_DATAERR, "incomplete range %d-", i);
3094			    break;
3095			}
3096			if (a < low || a > high)
3097			    errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
3098				a, low, high);
3099			a -= low;
3100			if (i == -1)	/* no previous in range */
3101			    i = a;
3102			else {		/* check that range is valid */
3103			    if (i > a)
3104				errx(EX_DATAERR, "invalid range %d-%d",
3105					i+low, a+low);
3106			    if (*s == '-')
3107				errx(EX_DATAERR, "double '-' in range");
3108			}
3109			for (; i <= a; i++)
3110			    map[i/32] |= 1<<(i & 31);
3111			i = -1;
3112			if (*s == '-')
3113			    i = a;
3114			else if (*s == '}')
3115			    break;
3116			av = s+1;
3117		}
3118		return;
3119	}
3120	av = p;
3121	if (av)			/* then *av must be a ',' */
3122		av++;
3123
3124	/* Check this entry */
3125	if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
3126		/*
3127		 * 'any' turns the entire list into a NOP.
3128		 * 'not any' never matches, so it is removed from the
3129		 * list unless it is the only item, in which case we
3130		 * report an error.
3131		 */
3132		if (cmd->o.len & F_NOT) {	/* "not any" never matches */
3133			if (av == NULL && len == 0) /* only this entry */
3134				errx(EX_DATAERR, "not any never matches");
3135		}
3136		/* else do nothing and skip this entry */
3137		return;
3138	}
3139	/* A single IP can be stored in an optimized format */
3140	if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
3141		cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
3142		return;
3143	}
3144	len += 2;	/* two words... */
3145	d += 2;
3146    } /* end while */
3147    if (len + 1 > F_LEN_MASK)
3148	errx(EX_DATAERR, "address list too long");
3149    cmd->o.len |= len+1;
3150}
3151
3152
3153/* n2mask sets n bits of the mask */
3154void
3155n2mask(struct in6_addr *mask, int n)
3156{
3157	static int	minimask[9] =
3158	    { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
3159	u_char		*p;
3160
3161	memset(mask, 0, sizeof(struct in6_addr));
3162	p = (u_char *) mask;
3163	for (; n > 0; p++, n -= 8) {
3164		if (n >= 8)
3165			*p = 0xff;
3166		else
3167			*p = minimask[n];
3168	}
3169	return;
3170}
3171
3172static void
3173fill_flags_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3174	struct _s_x *flags, char *p)
3175{
3176	char *e;
3177	uint32_t set = 0, clear = 0;
3178
3179	if (fill_flags(flags, p, &e, &set, &clear) != 0)
3180		errx(EX_DATAERR, "invalid flag %s", e);
3181
3182	cmd->opcode = opcode;
3183	cmd->len =  (cmd->len & (F_NOT | F_OR)) | 1;
3184	cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3185}
3186
3187
3188void
3189ipfw_delete(char *av[])
3190{
3191	ipfw_range_tlv rt;
3192	char *sep;
3193	int i, j;
3194	int exitval = EX_OK;
3195	int do_set = 0;
3196
3197	av++;
3198	NEED1("missing rule specification");
3199	if ( *av && _substrcmp(*av, "set") == 0) {
3200		/* Do not allow using the following syntax:
3201		 *	ipfw set N delete set M
3202		 */
3203		if (co.use_set)
3204			errx(EX_DATAERR, "invalid syntax");
3205		do_set = 1;	/* delete set */
3206		av++;
3207	}
3208
3209	/* Rule number */
3210	while (*av && isdigit(**av)) {
3211		i = strtol(*av, &sep, 10);
3212		j = i;
3213		if (*sep== '-')
3214			j = strtol(sep + 1, NULL, 10);
3215		av++;
3216		if (co.do_nat) {
3217			exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
3218			if (exitval) {
3219				exitval = EX_UNAVAILABLE;
3220				warn("rule %u not available", i);
3221			}
3222 		} else if (co.do_pipe) {
3223			exitval = ipfw_delete_pipe(co.do_pipe, i);
3224		} else {
3225			memset(&rt, 0, sizeof(rt));
3226			if (do_set != 0) {
3227				rt.set = i & 31;
3228				rt.flags = IPFW_RCFLAG_SET;
3229			} else {
3230				rt.start_rule = i & 0xffff;
3231				rt.end_rule = j & 0xffff;
3232				if (rt.start_rule == 0 && rt.end_rule == 0)
3233					rt.flags |= IPFW_RCFLAG_ALL;
3234				else
3235					rt.flags |= IPFW_RCFLAG_RANGE;
3236				if (co.use_set != 0) {
3237					rt.set = co.use_set - 1;
3238					rt.flags |= IPFW_RCFLAG_SET;
3239				}
3240			}
3241			i = do_range_cmd(IP_FW_XDEL, &rt);
3242			if (i != 0) {
3243				exitval = EX_UNAVAILABLE;
3244				warn("rule %u: setsockopt(IP_FW_XDEL)",
3245				    rt.start_rule);
3246			} else if (rt.new_set == 0 && do_set == 0) {
3247				exitval = EX_UNAVAILABLE;
3248				if (rt.start_rule != rt.end_rule)
3249					warnx("no rules rules in %u-%u range",
3250					    rt.start_rule, rt.end_rule);
3251				else
3252					warnx("rule %u not found",
3253					    rt.start_rule);
3254			}
3255		}
3256	}
3257	if (exitval != EX_OK)
3258		exit(exitval);
3259}
3260
3261
3262/*
3263 * fill the interface structure. We do not check the name as we can
3264 * create interfaces dynamically, so checking them at insert time
3265 * makes relatively little sense.
3266 * Interface names containing '*', '?', or '[' are assumed to be shell
3267 * patterns which match interfaces.
3268 */
3269static void
3270fill_iface(ipfw_insn_if *cmd, char *arg, int cblen, struct tidx *tstate)
3271{
3272	char *p;
3273	uint16_t uidx;
3274
3275	cmd->name[0] = '\0';
3276	cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3277
3278	CHECK_CMDLEN;
3279
3280	/* Parse the interface or address */
3281	if (strcmp(arg, "any") == 0)
3282		cmd->o.len = 0;		/* effectively ignore this command */
3283	else if (strncmp(arg, "table(", 6) == 0) {
3284		if ((p = strchr(arg + 6, ')')) == NULL)
3285			errx(EX_DATAERR, "forgotten parenthesis: '%s'", arg);
3286		*p = '\0';
3287		p = strchr(arg + 6, ',');
3288		if (p)
3289			*p++ = '\0';
3290		if ((uidx = pack_table(tstate, arg + 6)) == 0)
3291			errx(EX_DATAERR, "Invalid table name: %s", arg + 6);
3292
3293		cmd->name[0] = '\1'; /* Special value indicating table */
3294		cmd->p.kidx = uidx;
3295	} else if (!isdigit(*arg)) {
3296		strlcpy(cmd->name, arg, sizeof(cmd->name));
3297		cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3298	} else if (!inet_aton(arg, &cmd->p.ip))
3299		errx(EX_DATAERR, "bad ip address ``%s''", arg);
3300}
3301
3302static void
3303get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
3304{
3305	int i;
3306	size_t l;
3307	char *ap, *ptr, *optr;
3308	struct ether_addr *mac;
3309	const char *macset = "0123456789abcdefABCDEF:";
3310
3311	if (strcmp(p, "any") == 0) {
3312		for (i = 0; i < ETHER_ADDR_LEN; i++)
3313			addr[i] = mask[i] = 0;
3314		return;
3315	}
3316
3317	optr = ptr = strdup(p);
3318	if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
3319		l = strlen(ap);
3320		if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
3321			errx(EX_DATAERR, "Incorrect MAC address");
3322		bcopy(mac, addr, ETHER_ADDR_LEN);
3323	} else
3324		errx(EX_DATAERR, "Incorrect MAC address");
3325
3326	if (ptr != NULL) { /* we have mask? */
3327		if (p[ptr - optr - 1] == '/') { /* mask len */
3328			long ml = strtol(ptr, &ap, 10);
3329			if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
3330				errx(EX_DATAERR, "Incorrect mask length");
3331			for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
3332				mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
3333		} else { /* mask */
3334			l = strlen(ptr);
3335			if (strspn(ptr, macset) != l ||
3336			    (mac = ether_aton(ptr)) == NULL)
3337				errx(EX_DATAERR, "Incorrect mask");
3338			bcopy(mac, mask, ETHER_ADDR_LEN);
3339		}
3340	} else { /* default mask: ff:ff:ff:ff:ff:ff */
3341		for (i = 0; i < ETHER_ADDR_LEN; i++)
3342			mask[i] = 0xff;
3343	}
3344	for (i = 0; i < ETHER_ADDR_LEN; i++)
3345		addr[i] &= mask[i];
3346
3347	free(optr);
3348}
3349
3350/*
3351 * helper function, updates the pointer to cmd with the length
3352 * of the current command, and also cleans up the first word of
3353 * the new command in case it has been clobbered before.
3354 */
3355static ipfw_insn *
3356next_cmd(ipfw_insn *cmd, int *len)
3357{
3358	*len -= F_LEN(cmd);
3359	CHECK_LENGTH(*len, 0);
3360	cmd += F_LEN(cmd);
3361	bzero(cmd, sizeof(*cmd));
3362	return cmd;
3363}
3364
3365/*
3366 * Takes arguments and copies them into a comment
3367 */
3368static void
3369fill_comment(ipfw_insn *cmd, char **av, int cblen)
3370{
3371	int i, l;
3372	char *p = (char *)(cmd + 1);
3373
3374	cmd->opcode = O_NOP;
3375	cmd->len =  (cmd->len & (F_NOT | F_OR));
3376
3377	/* Compute length of comment string. */
3378	for (i = 0, l = 0; av[i] != NULL; i++)
3379		l += strlen(av[i]) + 1;
3380	if (l == 0)
3381		return;
3382	if (l > 84)
3383		errx(EX_DATAERR,
3384		    "comment too long (max 80 chars)");
3385	l = 1 + (l+3)/4;
3386	cmd->len =  (cmd->len & (F_NOT | F_OR)) | l;
3387	CHECK_CMDLEN;
3388
3389	for (i = 0; av[i] != NULL; i++) {
3390		strcpy(p, av[i]);
3391		p += strlen(av[i]);
3392		*p++ = ' ';
3393	}
3394	*(--p) = '\0';
3395}
3396
3397/*
3398 * A function to fill simple commands of size 1.
3399 * Existing flags are preserved.
3400 */
3401static void
3402fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3403{
3404	cmd->opcode = opcode;
3405	cmd->len =  ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3406	cmd->arg1 = arg;
3407}
3408
3409/*
3410 * Fetch and add the MAC address and type, with masks. This generates one or
3411 * two microinstructions, and returns the pointer to the last one.
3412 */
3413static ipfw_insn *
3414add_mac(ipfw_insn *cmd, char *av[], int cblen)
3415{
3416	ipfw_insn_mac *mac;
3417
3418	if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
3419		errx(EX_DATAERR, "MAC dst src");
3420
3421	cmd->opcode = O_MACADDR2;
3422	cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3423	CHECK_CMDLEN;
3424
3425	mac = (ipfw_insn_mac *)cmd;
3426	get_mac_addr_mask(av[0], mac->addr, mac->mask);	/* dst */
3427	get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
3428	    &(mac->mask[ETHER_ADDR_LEN])); /* src */
3429	return cmd;
3430}
3431
3432static ipfw_insn *
3433add_mactype(ipfw_insn *cmd, char *av, int cblen)
3434{
3435	if (!av)
3436		errx(EX_DATAERR, "missing MAC type");
3437	if (strcmp(av, "any") != 0) { /* we have a non-null type */
3438		fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
3439		    cblen);
3440		cmd->opcode = O_MAC_TYPE;
3441		return cmd;
3442	} else
3443		return NULL;
3444}
3445
3446static ipfw_insn *
3447add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
3448{
3449	struct protoent *pe;
3450	char *ep;
3451	int proto;
3452
3453	proto = strtol(av, &ep, 10);
3454	if (*ep != '\0' || proto <= 0) {
3455		if ((pe = getprotobyname(av)) == NULL)
3456			return NULL;
3457		proto = pe->p_proto;
3458	}
3459
3460	fill_cmd(cmd, O_PROTO, 0, proto);
3461	*protop = proto;
3462	return cmd;
3463}
3464
3465static ipfw_insn *
3466add_proto(ipfw_insn *cmd, char *av, u_char *protop)
3467{
3468	u_char proto = IPPROTO_IP;
3469
3470	if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3471		; /* do not set O_IP4 nor O_IP6 */
3472	else if (strcmp(av, "ip4") == 0)
3473		/* explicit "just IPv4" rule */
3474		fill_cmd(cmd, O_IP4, 0, 0);
3475	else if (strcmp(av, "ip6") == 0) {
3476		/* explicit "just IPv6" rule */
3477		proto = IPPROTO_IPV6;
3478		fill_cmd(cmd, O_IP6, 0, 0);
3479	} else
3480		return add_proto0(cmd, av, protop);
3481
3482	*protop = proto;
3483	return cmd;
3484}
3485
3486static ipfw_insn *
3487add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
3488{
3489	u_char proto = IPPROTO_IP;
3490
3491	if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3492		; /* do not set O_IP4 nor O_IP6 */
3493	else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3494		/* explicit "just IPv4" rule */
3495		fill_cmd(cmd, O_IP4, 0, 0);
3496	else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3497		/* explicit "just IPv6" rule */
3498		proto = IPPROTO_IPV6;
3499		fill_cmd(cmd, O_IP6, 0, 0);
3500	} else
3501		return add_proto0(cmd, av, protop);
3502
3503	*protop = proto;
3504	return cmd;
3505}
3506
3507static ipfw_insn *
3508add_srcip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3509{
3510	fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3511	if (cmd->opcode == O_IP_DST_SET)			/* set */
3512		cmd->opcode = O_IP_SRC_SET;
3513	else if (cmd->opcode == O_IP_DST_LOOKUP)		/* table */
3514		cmd->opcode = O_IP_SRC_LOOKUP;
3515	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))		/* me */
3516		cmd->opcode = O_IP_SRC_ME;
3517	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))	/* one IP */
3518		cmd->opcode = O_IP_SRC;
3519	else							/* addr/mask */
3520		cmd->opcode = O_IP_SRC_MASK;
3521	return cmd;
3522}
3523
3524static ipfw_insn *
3525add_dstip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3526{
3527	fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3528	if (cmd->opcode == O_IP_DST_SET)			/* set */
3529		;
3530	else if (cmd->opcode == O_IP_DST_LOOKUP)		/* table */
3531		;
3532	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))		/* me */
3533		cmd->opcode = O_IP_DST_ME;
3534	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))	/* one IP */
3535		cmd->opcode = O_IP_DST;
3536	else							/* addr/mask */
3537		cmd->opcode = O_IP_DST_MASK;
3538	return cmd;
3539}
3540
3541static struct _s_x f_reserved_keywords[] = {
3542	{ "altq",	TOK_OR },
3543	{ "//",		TOK_OR },
3544	{ "diverted",	TOK_OR },
3545	{ "dst-port",	TOK_OR },
3546	{ "src-port",	TOK_OR },
3547	{ "established",	TOK_OR },
3548	{ "keep-state",	TOK_OR },
3549	{ "frag",	TOK_OR },
3550	{ "icmptypes",	TOK_OR },
3551	{ "in",		TOK_OR },
3552	{ "out",	TOK_OR },
3553	{ "ip6",	TOK_OR },
3554	{ "any",	TOK_OR },
3555	{ "to",		TOK_OR },
3556	{ "via",	TOK_OR },
3557	{ "{",		TOK_OR },
3558	{ NULL, 0 }	/* terminator */
3559};
3560
3561static ipfw_insn *
3562add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
3563{
3564
3565	if (match_token(f_reserved_keywords, av) != -1)
3566		return (NULL);
3567
3568	if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
3569		/* XXX todo: check that we have a protocol with ports */
3570		cmd->opcode = opcode;
3571		return cmd;
3572	}
3573	return NULL;
3574}
3575
3576static ipfw_insn *
3577add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3578{
3579	struct in6_addr a;
3580	char *host, *ch, buf[INET6_ADDRSTRLEN];
3581	ipfw_insn *ret = NULL;
3582	int len;
3583
3584	/* Copy first address in set if needed */
3585	if ((ch = strpbrk(av, "/,")) != NULL) {
3586		len = ch - av;
3587		strlcpy(buf, av, sizeof(buf));
3588		if (len < sizeof(buf))
3589			buf[len] = '\0';
3590		host = buf;
3591	} else
3592		host = av;
3593
3594	if (proto == IPPROTO_IPV6  || strcmp(av, "me6") == 0 ||
3595	    inet_pton(AF_INET6, host, &a) == 1)
3596		ret = add_srcip6(cmd, av, cblen, tstate);
3597	/* XXX: should check for IPv4, not !IPv6 */
3598	if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3599	    inet_pton(AF_INET6, host, &a) != 1))
3600		ret = add_srcip(cmd, av, cblen, tstate);
3601	if (ret == NULL && strcmp(av, "any") != 0)
3602		ret = cmd;
3603
3604	return ret;
3605}
3606
3607static ipfw_insn *
3608add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3609{
3610	struct in6_addr a;
3611	char *host, *ch, buf[INET6_ADDRSTRLEN];
3612	ipfw_insn *ret = NULL;
3613	int len;
3614
3615	/* Copy first address in set if needed */
3616	if ((ch = strpbrk(av, "/,")) != NULL) {
3617		len = ch - av;
3618		strlcpy(buf, av, sizeof(buf));
3619		if (len < sizeof(buf))
3620			buf[len] = '\0';
3621		host = buf;
3622	} else
3623		host = av;
3624
3625	if (proto == IPPROTO_IPV6  || strcmp(av, "me6") == 0 ||
3626	    inet_pton(AF_INET6, host, &a) == 1)
3627		ret = add_dstip6(cmd, av, cblen, tstate);
3628	/* XXX: should check for IPv4, not !IPv6 */
3629	if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3630	    inet_pton(AF_INET6, host, &a) != 1))
3631		ret = add_dstip(cmd, av, cblen, tstate);
3632	if (ret == NULL && strcmp(av, "any") != 0)
3633		ret = cmd;
3634
3635	return ret;
3636}
3637
3638/*
3639 * Parse arguments and assemble the microinstructions which make up a rule.
3640 * Rules are added into the 'rulebuf' and then copied in the correct order
3641 * into the actual rule.
3642 *
3643 * The syntax for a rule starts with the action, followed by
3644 * optional action parameters, and the various match patterns.
3645 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
3646 * (generated if the rule includes a keep-state option), then the
3647 * various match patterns, log/altq actions, and the actual action.
3648 *
3649 */
3650void
3651compile_rule(char *av[], uint32_t *rbuf, int *rbufsize, struct tidx *tstate)
3652{
3653	/*
3654	 * rules are added into the 'rulebuf' and then copied in
3655	 * the correct order into the actual rule.
3656	 * Some things that need to go out of order (prob, action etc.)
3657	 * go into actbuf[].
3658	 */
3659	static uint32_t actbuf[255], cmdbuf[255];
3660	int rblen, ablen, cblen;
3661
3662	ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
3663	ipfw_insn *first_cmd;	/* first match pattern */
3664
3665	struct ip_fw_rule *rule;
3666
3667	/*
3668	 * various flags used to record that we entered some fields.
3669	 */
3670	ipfw_insn *have_state = NULL;	/* check-state or keep-state */
3671	ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
3672	size_t len;
3673
3674	int i;
3675
3676	int open_par = 0;	/* open parenthesis ( */
3677
3678	/* proto is here because it is used to fetch ports */
3679	u_char proto = IPPROTO_IP;	/* default protocol */
3680
3681	double match_prob = 1; /* match probability, default is always match */
3682
3683	bzero(actbuf, sizeof(actbuf));		/* actions go here */
3684	bzero(cmdbuf, sizeof(cmdbuf));
3685	bzero(rbuf, *rbufsize);
3686
3687	rule = (struct ip_fw_rule *)rbuf;
3688	cmd = (ipfw_insn *)cmdbuf;
3689	action = (ipfw_insn *)actbuf;
3690
3691	rblen = *rbufsize / sizeof(uint32_t);
3692	rblen -= sizeof(struct ip_fw_rule) / sizeof(uint32_t);
3693	ablen = sizeof(actbuf) / sizeof(actbuf[0]);
3694	cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
3695	cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
3696
3697#define	CHECK_RBUFLEN(len)	{ CHECK_LENGTH(rblen, len); rblen -= len; }
3698#define	CHECK_ACTLEN		CHECK_LENGTH(ablen, action->len)
3699
3700	av++;
3701
3702	/* [rule N]	-- Rule number optional */
3703	if (av[0] && isdigit(**av)) {
3704		rule->rulenum = atoi(*av);
3705		av++;
3706	}
3707
3708	/* [set N]	-- set number (0..RESVD_SET), optional */
3709	if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
3710		int set = strtoul(av[1], NULL, 10);
3711		if (set < 0 || set > RESVD_SET)
3712			errx(EX_DATAERR, "illegal set %s", av[1]);
3713		rule->set = set;
3714		tstate->set = set;
3715		av += 2;
3716	}
3717
3718	/* [prob D]	-- match probability, optional */
3719	if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
3720		match_prob = strtod(av[1], NULL);
3721
3722		if (match_prob <= 0 || match_prob > 1)
3723			errx(EX_DATAERR, "illegal match prob. %s", av[1]);
3724		av += 2;
3725	}
3726
3727	/* action	-- mandatory */
3728	NEED1("missing action");
3729	i = match_token(rule_actions, *av);
3730	av++;
3731	action->len = 1;	/* default */
3732	CHECK_ACTLEN;
3733	switch(i) {
3734	case TOK_CHECKSTATE:
3735		have_state = action;
3736		action->opcode = O_CHECK_STATE;
3737		if (*av == NULL ||
3738		    match_token(rule_options, *av) == TOK_COMMENT) {
3739			action->arg1 = pack_object(tstate,
3740			    default_state_name, IPFW_TLV_STATE_NAME);
3741			break;
3742		}
3743		if (*av[0] == ':') {
3744			if (strcmp(*av + 1, "any") == 0)
3745				action->arg1 = 0;
3746			else if (state_check_name(*av + 1) == 0)
3747				action->arg1 = pack_object(tstate, *av + 1,
3748				    IPFW_TLV_STATE_NAME);
3749			else
3750				errx(EX_DATAERR, "Invalid state name %s",
3751				    *av);
3752			av++;
3753			break;
3754		}
3755		errx(EX_DATAERR, "Invalid state name %s", *av);
3756		break;
3757
3758	case TOK_ACCEPT:
3759		action->opcode = O_ACCEPT;
3760		break;
3761
3762	case TOK_DENY:
3763		action->opcode = O_DENY;
3764		action->arg1 = 0;
3765		break;
3766
3767	case TOK_REJECT:
3768		action->opcode = O_REJECT;
3769		action->arg1 = ICMP_UNREACH_HOST;
3770		break;
3771
3772	case TOK_RESET:
3773		action->opcode = O_REJECT;
3774		action->arg1 = ICMP_REJECT_RST;
3775		break;
3776
3777	case TOK_RESET6:
3778		action->opcode = O_UNREACH6;
3779		action->arg1 = ICMP6_UNREACH_RST;
3780		break;
3781
3782	case TOK_UNREACH:
3783		action->opcode = O_REJECT;
3784		NEED1("missing reject code");
3785		fill_reject_code(&action->arg1, *av);
3786		av++;
3787		break;
3788
3789	case TOK_UNREACH6:
3790		action->opcode = O_UNREACH6;
3791		NEED1("missing unreach code");
3792		fill_unreach6_code(&action->arg1, *av);
3793		av++;
3794		break;
3795
3796	case TOK_COUNT:
3797		action->opcode = O_COUNT;
3798		break;
3799
3800	case TOK_NAT:
3801		action->opcode = O_NAT;
3802		action->len = F_INSN_SIZE(ipfw_insn_nat);
3803		CHECK_ACTLEN;
3804		if (*av != NULL && _substrcmp(*av, "global") == 0) {
3805			action->arg1 = IP_FW_NAT44_GLOBAL;
3806			av++;
3807			break;
3808		} else
3809			goto chkarg;
3810	case TOK_QUEUE:
3811		action->opcode = O_QUEUE;
3812		goto chkarg;
3813	case TOK_PIPE:
3814		action->opcode = O_PIPE;
3815		goto chkarg;
3816	case TOK_SKIPTO:
3817		action->opcode = O_SKIPTO;
3818		goto chkarg;
3819	case TOK_NETGRAPH:
3820		action->opcode = O_NETGRAPH;
3821		goto chkarg;
3822	case TOK_NGTEE:
3823		action->opcode = O_NGTEE;
3824		goto chkarg;
3825	case TOK_DIVERT:
3826		action->opcode = O_DIVERT;
3827		goto chkarg;
3828	case TOK_TEE:
3829		action->opcode = O_TEE;
3830		goto chkarg;
3831	case TOK_CALL:
3832		action->opcode = O_CALLRETURN;
3833chkarg:
3834		if (!av[0])
3835			errx(EX_USAGE, "missing argument for %s", *(av - 1));
3836		if (isdigit(**av)) {
3837			action->arg1 = strtoul(*av, NULL, 10);
3838			if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
3839				errx(EX_DATAERR, "illegal argument for %s",
3840				    *(av - 1));
3841		} else if (_substrcmp(*av, "tablearg") == 0) {
3842			action->arg1 = IP_FW_TARG;
3843		} else if (i == TOK_DIVERT || i == TOK_TEE) {
3844			struct servent *s;
3845			setservent(1);
3846			s = getservbyname(av[0], "divert");
3847			if (s != NULL)
3848				action->arg1 = ntohs(s->s_port);
3849			else
3850				errx(EX_DATAERR, "illegal divert/tee port");
3851		} else
3852			errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
3853		av++;
3854		break;
3855
3856	case TOK_FORWARD: {
3857		/*
3858		 * Locate the address-port separator (':' or ',').
3859		 * Could be one of the following:
3860		 *	hostname:port
3861		 *	IPv4 a.b.c.d,port
3862		 *	IPv4 a.b.c.d:port
3863		 *	IPv6 w:x:y::z,port
3864		 * The ':' can only be used with hostname and IPv4 address.
3865		 * XXX-BZ Should we also support [w:x:y::z]:port?
3866		 */
3867		struct sockaddr_storage result;
3868		struct addrinfo *res;
3869		char *s, *end;
3870		int family;
3871		u_short port_number;
3872
3873		NEED1("missing forward address[:port]");
3874
3875		/*
3876		 * locate the address-port separator (':' or ',')
3877		 */
3878		s = strchr(*av, ',');
3879		if (s == NULL) {
3880			/* Distinguish between IPv4:port and IPv6 cases. */
3881			s = strchr(*av, ':');
3882			if (s && strchr(s+1, ':'))
3883				s = NULL; /* no port */
3884		}
3885
3886		port_number = 0;
3887		if (s != NULL) {
3888			/* Terminate host portion and set s to start of port. */
3889			*(s++) = '\0';
3890			i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
3891			if (s == end)
3892				errx(EX_DATAERR,
3893				    "illegal forwarding port ``%s''", s);
3894			port_number = (u_short)i;
3895		}
3896
3897		if (_substrcmp(*av, "tablearg") == 0) {
3898			family = PF_INET;
3899			((struct sockaddr_in*)&result)->sin_addr.s_addr =
3900			    INADDR_ANY;
3901		} else {
3902			/*
3903			 * Resolve the host name or address to a family and a
3904			 * network representation of the address.
3905			 */
3906			if (getaddrinfo(*av, NULL, NULL, &res))
3907				errx(EX_DATAERR, NULL);
3908			/* Just use the first host in the answer. */
3909			family = res->ai_family;
3910			memcpy(&result, res->ai_addr, res->ai_addrlen);
3911			freeaddrinfo(res);
3912		}
3913
3914 		if (family == PF_INET) {
3915			ipfw_insn_sa *p = (ipfw_insn_sa *)action;
3916
3917			action->opcode = O_FORWARD_IP;
3918			action->len = F_INSN_SIZE(ipfw_insn_sa);
3919			CHECK_ACTLEN;
3920
3921			/*
3922			 * In the kernel we assume AF_INET and use only
3923			 * sin_port and sin_addr. Remember to set sin_len as
3924			 * the routing code seems to use it too.
3925			 */
3926			p->sa.sin_len = sizeof(struct sockaddr_in);
3927			p->sa.sin_family = AF_INET;
3928			p->sa.sin_port = port_number;
3929			p->sa.sin_addr.s_addr =
3930			     ((struct sockaddr_in *)&result)->sin_addr.s_addr;
3931		} else if (family == PF_INET6) {
3932			ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
3933
3934			action->opcode = O_FORWARD_IP6;
3935			action->len = F_INSN_SIZE(ipfw_insn_sa6);
3936			CHECK_ACTLEN;
3937
3938			p->sa.sin6_len = sizeof(struct sockaddr_in6);
3939			p->sa.sin6_family = AF_INET6;
3940			p->sa.sin6_port = port_number;
3941			p->sa.sin6_flowinfo = 0;
3942			p->sa.sin6_scope_id =
3943			    ((struct sockaddr_in6 *)&result)->sin6_scope_id;
3944			bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
3945			    &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
3946		} else {
3947			errx(EX_DATAERR, "Invalid address family in forward action");
3948		}
3949		av++;
3950		break;
3951	    }
3952	case TOK_COMMENT:
3953		/* pretend it is a 'count' rule followed by the comment */
3954		action->opcode = O_COUNT;
3955		av--;		/* go back... */
3956		break;
3957
3958	case TOK_SETFIB:
3959	    {
3960		int numfibs;
3961		size_t intsize = sizeof(int);
3962
3963		action->opcode = O_SETFIB;
3964		NEED1("missing fib number");
3965		if (_substrcmp(*av, "tablearg") == 0) {
3966			action->arg1 = IP_FW_TARG;
3967		} else {
3968		        action->arg1 = strtoul(*av, NULL, 10);
3969			if (sysctlbyname("net.fibs", &numfibs, &intsize,
3970			    NULL, 0) == -1)
3971				errx(EX_DATAERR, "fibs not suported.\n");
3972			if (action->arg1 >= numfibs)  /* Temporary */
3973				errx(EX_DATAERR, "fib too large.\n");
3974			/* Add high-order bit to fib to make room for tablearg*/
3975			action->arg1 |= 0x8000;
3976		}
3977		av++;
3978		break;
3979	    }
3980
3981	case TOK_SETDSCP:
3982	    {
3983		int code;
3984
3985		action->opcode = O_SETDSCP;
3986		NEED1("missing DSCP code");
3987		if (_substrcmp(*av, "tablearg") == 0) {
3988			action->arg1 = IP_FW_TARG;
3989		} else {
3990			if (isalpha(*av[0])) {
3991				if ((code = match_token(f_ipdscp, *av)) == -1)
3992					errx(EX_DATAERR, "Unknown DSCP code");
3993				action->arg1 = code;
3994			} else
3995			        action->arg1 = strtoul(*av, NULL, 10);
3996			/*
3997			 * Add high-order bit to DSCP to make room
3998			 * for tablearg
3999			 */
4000			action->arg1 |= 0x8000;
4001		}
4002		av++;
4003		break;
4004	    }
4005
4006	case TOK_REASS:
4007		action->opcode = O_REASS;
4008		break;
4009
4010	case TOK_RETURN:
4011		fill_cmd(action, O_CALLRETURN, F_NOT, 0);
4012		break;
4013
4014	case TOK_TCPSETMSS: {
4015		u_long mss;
4016		uint16_t idx;
4017
4018		idx = pack_object(tstate, "tcp-setmss", IPFW_TLV_EACTION);
4019		if (idx == 0)
4020			errx(EX_DATAERR, "pack_object failed");
4021		fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4022		NEED1("Missing MSS value");
4023		action = next_cmd(action, &ablen);
4024		action->len = 1;
4025		CHECK_ACTLEN;
4026		mss = strtoul(*av, NULL, 10);
4027		if (mss == 0 || mss > UINT16_MAX)
4028			errx(EX_USAGE, "invalid MSS value %s", *av);
4029		fill_cmd(action, O_EXTERNAL_DATA, 0, (uint16_t)mss);
4030		av++;
4031		break;
4032	}
4033
4034	default:
4035		av--;
4036		if (match_token(rule_eactions, *av) == -1)
4037			errx(EX_DATAERR, "invalid action %s\n", *av);
4038		/*
4039		 * External actions support.
4040		 * XXX: we support only syntax with instance name.
4041		 *	For known external actions (from rule_eactions list)
4042		 *	we can handle syntax directly. But with `eaction'
4043		 *	keyword we can use only `eaction <name> <instance>'
4044		 *	syntax.
4045		 */
4046	case TOK_EACTION: {
4047		uint16_t idx;
4048
4049		NEED1("Missing eaction name");
4050		if (eaction_check_name(*av) != 0)
4051			errx(EX_DATAERR, "Invalid eaction name %s", *av);
4052		idx = pack_object(tstate, *av, IPFW_TLV_EACTION);
4053		if (idx == 0)
4054			errx(EX_DATAERR, "pack_object failed");
4055		fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4056		av++;
4057		NEED1("Missing eaction instance name");
4058		action = next_cmd(action, &ablen);
4059		action->len = 1;
4060		CHECK_ACTLEN;
4061		if (eaction_check_name(*av) != 0)
4062			errx(EX_DATAERR, "Invalid eaction instance name %s",
4063			    *av);
4064		/*
4065		 * External action instance object has TLV type depended
4066		 * from the external action name object index. Since we
4067		 * currently don't know this index, use zero as TLV type.
4068		 */
4069		idx = pack_object(tstate, *av, 0);
4070		if (idx == 0)
4071			errx(EX_DATAERR, "pack_object failed");
4072		fill_cmd(action, O_EXTERNAL_INSTANCE, 0, idx);
4073		av++;
4074		}
4075	}
4076	action = next_cmd(action, &ablen);
4077
4078	/*
4079	 * [altq queuename] -- altq tag, optional
4080	 * [log [logamount N]]	-- log, optional
4081	 *
4082	 * If they exist, it go first in the cmdbuf, but then it is
4083	 * skipped in the copy section to the end of the buffer.
4084	 */
4085	while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
4086		av++;
4087		switch (i) {
4088		case TOK_LOG:
4089		    {
4090			ipfw_insn_log *c = (ipfw_insn_log *)cmd;
4091			int l;
4092
4093			if (have_log)
4094				errx(EX_DATAERR,
4095				    "log cannot be specified more than once");
4096			have_log = (ipfw_insn *)c;
4097			cmd->len = F_INSN_SIZE(ipfw_insn_log);
4098			CHECK_CMDLEN;
4099			cmd->opcode = O_LOG;
4100			if (av[0] && _substrcmp(*av, "logamount") == 0) {
4101				av++;
4102				NEED1("logamount requires argument");
4103				l = atoi(*av);
4104				if (l < 0)
4105					errx(EX_DATAERR,
4106					    "logamount must be positive");
4107				c->max_log = l;
4108				av++;
4109			} else {
4110				len = sizeof(c->max_log);
4111				if (sysctlbyname("net.inet.ip.fw.verbose_limit",
4112				    &c->max_log, &len, NULL, 0) == -1) {
4113					if (co.test_only) {
4114						c->max_log = 0;
4115						break;
4116					}
4117					errx(1, "sysctlbyname(\"%s\")",
4118					    "net.inet.ip.fw.verbose_limit");
4119				}
4120			}
4121		    }
4122			break;
4123
4124#ifndef NO_ALTQ
4125		case TOK_ALTQ:
4126		    {
4127			ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
4128
4129			NEED1("missing altq queue name");
4130			if (have_altq)
4131				errx(EX_DATAERR,
4132				    "altq cannot be specified more than once");
4133			have_altq = (ipfw_insn *)a;
4134			cmd->len = F_INSN_SIZE(ipfw_insn_altq);
4135			CHECK_CMDLEN;
4136			cmd->opcode = O_ALTQ;
4137			a->qid = altq_name_to_qid(*av);
4138			av++;
4139		    }
4140			break;
4141#endif
4142
4143		case TOK_TAG:
4144		case TOK_UNTAG: {
4145			uint16_t tag;
4146
4147			if (have_tag)
4148				errx(EX_USAGE, "tag and untag cannot be "
4149				    "specified more than once");
4150			GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
4151			   rule_action_params);
4152			have_tag = cmd;
4153			fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
4154			av++;
4155			break;
4156		}
4157
4158		default:
4159			abort();
4160		}
4161		cmd = next_cmd(cmd, &cblen);
4162	}
4163
4164	if (have_state)	{ /* must be a check-state, we are done */
4165		if (*av != NULL &&
4166		    match_token(rule_options, *av) == TOK_COMMENT) {
4167			/* check-state has a comment */
4168			av++;
4169			fill_comment(cmd, av, cblen);
4170			cmd = next_cmd(cmd, &cblen);
4171			av[0] = NULL;
4172		}
4173		goto done;
4174	}
4175
4176#define OR_START(target)					\
4177	if (av[0] && (*av[0] == '(' || *av[0] == '{')) { 	\
4178		if (open_par)					\
4179			errx(EX_USAGE, "nested \"(\" not allowed\n"); \
4180		prev = NULL;					\
4181		open_par = 1;					\
4182		if ( (av[0])[1] == '\0') {			\
4183			av++;					\
4184		} else						\
4185			(*av)++;				\
4186	}							\
4187	target:							\
4188
4189
4190#define	CLOSE_PAR						\
4191	if (open_par) {						\
4192		if (av[0] && (					\
4193		    strcmp(*av, ")") == 0 ||			\
4194		    strcmp(*av, "}") == 0)) {			\
4195			prev = NULL;				\
4196			open_par = 0;				\
4197			av++;					\
4198		} else						\
4199			errx(EX_USAGE, "missing \")\"\n");	\
4200	}
4201
4202#define NOT_BLOCK						\
4203	if (av[0] && _substrcmp(*av, "not") == 0) {		\
4204		if (cmd->len & F_NOT)				\
4205			errx(EX_USAGE, "double \"not\" not allowed\n"); \
4206		cmd->len |= F_NOT;				\
4207		av++;						\
4208	}
4209
4210#define OR_BLOCK(target)					\
4211	if (av[0] && _substrcmp(*av, "or") == 0) {		\
4212		if (prev == NULL || open_par == 0)		\
4213			errx(EX_DATAERR, "invalid OR block");	\
4214		prev->len |= F_OR;				\
4215		av++;					\
4216		goto target;					\
4217	}							\
4218	CLOSE_PAR;
4219
4220	first_cmd = cmd;
4221
4222#if 0
4223	/*
4224	 * MAC addresses, optional.
4225	 * If we have this, we skip the part "proto from src to dst"
4226	 * and jump straight to the option parsing.
4227	 */
4228	NOT_BLOCK;
4229	NEED1("missing protocol");
4230	if (_substrcmp(*av, "MAC") == 0 ||
4231	    _substrcmp(*av, "mac") == 0) {
4232		av++;			/* the "MAC" keyword */
4233		add_mac(cmd, av);	/* exits in case of errors */
4234		cmd = next_cmd(cmd);
4235		av += 2;		/* dst-mac and src-mac */
4236		NOT_BLOCK;
4237		NEED1("missing mac type");
4238		if (add_mactype(cmd, av[0]))
4239			cmd = next_cmd(cmd);
4240		av++;			/* any or mac-type */
4241		goto read_options;
4242	}
4243#endif
4244
4245	/*
4246	 * protocol, mandatory
4247	 */
4248    OR_START(get_proto);
4249	NOT_BLOCK;
4250	NEED1("missing protocol");
4251	if (add_proto_compat(cmd, *av, &proto)) {
4252		av++;
4253		if (F_LEN(cmd) != 0) {
4254			prev = cmd;
4255			cmd = next_cmd(cmd, &cblen);
4256		}
4257	} else if (first_cmd != cmd) {
4258		errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4259	} else
4260		goto read_options;
4261    OR_BLOCK(get_proto);
4262
4263	/*
4264	 * "from", mandatory
4265	 */
4266	if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
4267		errx(EX_USAGE, "missing ``from''");
4268	av++;
4269
4270	/*
4271	 * source IP, mandatory
4272	 */
4273    OR_START(source_ip);
4274	NOT_BLOCK;	/* optional "not" */
4275	NEED1("missing source address");
4276	if (add_src(cmd, *av, proto, cblen, tstate)) {
4277		av++;
4278		if (F_LEN(cmd) != 0) {	/* ! any */
4279			prev = cmd;
4280			cmd = next_cmd(cmd, &cblen);
4281		}
4282	} else
4283		errx(EX_USAGE, "bad source address %s", *av);
4284    OR_BLOCK(source_ip);
4285
4286	/*
4287	 * source ports, optional
4288	 */
4289	NOT_BLOCK;	/* optional "not" */
4290	if ( av[0] != NULL ) {
4291		if (_substrcmp(*av, "any") == 0 ||
4292		    add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4293			av++;
4294			if (F_LEN(cmd) != 0)
4295				cmd = next_cmd(cmd, &cblen);
4296		}
4297	}
4298
4299	/*
4300	 * "to", mandatory
4301	 */
4302	if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
4303		errx(EX_USAGE, "missing ``to''");
4304	av++;
4305
4306	/*
4307	 * destination, mandatory
4308	 */
4309    OR_START(dest_ip);
4310	NOT_BLOCK;	/* optional "not" */
4311	NEED1("missing dst address");
4312	if (add_dst(cmd, *av, proto, cblen, tstate)) {
4313		av++;
4314		if (F_LEN(cmd) != 0) {	/* ! any */
4315			prev = cmd;
4316			cmd = next_cmd(cmd, &cblen);
4317		}
4318	} else
4319		errx( EX_USAGE, "bad destination address %s", *av);
4320    OR_BLOCK(dest_ip);
4321
4322	/*
4323	 * dest. ports, optional
4324	 */
4325	NOT_BLOCK;	/* optional "not" */
4326	if (av[0]) {
4327		if (_substrcmp(*av, "any") == 0 ||
4328		    add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4329			av++;
4330			if (F_LEN(cmd) != 0)
4331				cmd = next_cmd(cmd, &cblen);
4332		}
4333	}
4334
4335read_options:
4336	if (av[0] && first_cmd == cmd) {
4337		/*
4338		 * nothing specified so far, store in the rule to ease
4339		 * printout later.
4340		 */
4341		 rule->flags |= IPFW_RULE_NOOPT;
4342	}
4343	prev = NULL;
4344	while ( av[0] != NULL ) {
4345		char *s;
4346		ipfw_insn_u32 *cmd32;	/* alias for cmd */
4347
4348		s = *av;
4349		cmd32 = (ipfw_insn_u32 *)cmd;
4350
4351		if (*s == '!') {	/* alternate syntax for NOT */
4352			if (cmd->len & F_NOT)
4353				errx(EX_USAGE, "double \"not\" not allowed\n");
4354			cmd->len = F_NOT;
4355			s++;
4356		}
4357		i = match_token(rule_options, s);
4358		av++;
4359		switch(i) {
4360		case TOK_NOT:
4361			if (cmd->len & F_NOT)
4362				errx(EX_USAGE, "double \"not\" not allowed\n");
4363			cmd->len = F_NOT;
4364			break;
4365
4366		case TOK_OR:
4367			if (open_par == 0 || prev == NULL)
4368				errx(EX_USAGE, "invalid \"or\" block\n");
4369			prev->len |= F_OR;
4370			break;
4371
4372		case TOK_STARTBRACE:
4373			if (open_par)
4374				errx(EX_USAGE, "+nested \"(\" not allowed\n");
4375			open_par = 1;
4376			break;
4377
4378		case TOK_ENDBRACE:
4379			if (!open_par)
4380				errx(EX_USAGE, "+missing \")\"\n");
4381			open_par = 0;
4382			prev = NULL;
4383			break;
4384
4385		case TOK_IN:
4386			fill_cmd(cmd, O_IN, 0, 0);
4387			break;
4388
4389		case TOK_OUT:
4390			cmd->len ^= F_NOT; /* toggle F_NOT */
4391			fill_cmd(cmd, O_IN, 0, 0);
4392			break;
4393
4394		case TOK_DIVERTED:
4395			fill_cmd(cmd, O_DIVERTED, 0, 3);
4396			break;
4397
4398		case TOK_DIVERTEDLOOPBACK:
4399			fill_cmd(cmd, O_DIVERTED, 0, 1);
4400			break;
4401
4402		case TOK_DIVERTEDOUTPUT:
4403			fill_cmd(cmd, O_DIVERTED, 0, 2);
4404			break;
4405
4406		case TOK_FRAG:
4407			fill_cmd(cmd, O_FRAG, 0, 0);
4408			break;
4409
4410		case TOK_LAYER2:
4411			fill_cmd(cmd, O_LAYER2, 0, 0);
4412			break;
4413
4414		case TOK_XMIT:
4415		case TOK_RECV:
4416		case TOK_VIA:
4417			NEED1("recv, xmit, via require interface name"
4418				" or address");
4419			fill_iface((ipfw_insn_if *)cmd, av[0], cblen, tstate);
4420			av++;
4421			if (F_LEN(cmd) == 0)	/* not a valid address */
4422				break;
4423			if (i == TOK_XMIT)
4424				cmd->opcode = O_XMIT;
4425			else if (i == TOK_RECV)
4426				cmd->opcode = O_RECV;
4427			else if (i == TOK_VIA)
4428				cmd->opcode = O_VIA;
4429			break;
4430
4431		case TOK_ICMPTYPES:
4432			NEED1("icmptypes requires list of types");
4433			fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
4434			av++;
4435			break;
4436
4437		case TOK_ICMP6TYPES:
4438			NEED1("icmptypes requires list of types");
4439			fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
4440			av++;
4441			break;
4442
4443		case TOK_IPTTL:
4444			NEED1("ipttl requires TTL");
4445			if (strpbrk(*av, "-,")) {
4446			    if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
4447				errx(EX_DATAERR, "invalid ipttl %s", *av);
4448			} else
4449			    fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
4450			av++;
4451			break;
4452
4453		case TOK_IPID:
4454			NEED1("ipid requires id");
4455			if (strpbrk(*av, "-,")) {
4456			    if (!add_ports(cmd, *av, 0, O_IPID, cblen))
4457				errx(EX_DATAERR, "invalid ipid %s", *av);
4458			} else
4459			    fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
4460			av++;
4461			break;
4462
4463		case TOK_IPLEN:
4464			NEED1("iplen requires length");
4465			if (strpbrk(*av, "-,")) {
4466			    if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
4467				errx(EX_DATAERR, "invalid ip len %s", *av);
4468			} else
4469			    fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
4470			av++;
4471			break;
4472
4473		case TOK_IPVER:
4474			NEED1("ipver requires version");
4475			fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
4476			av++;
4477			break;
4478
4479		case TOK_IPPRECEDENCE:
4480			NEED1("ipprecedence requires value");
4481			fill_cmd(cmd, O_IPPRECEDENCE, 0,
4482			    (strtoul(*av, NULL, 0) & 7) << 5);
4483			av++;
4484			break;
4485
4486		case TOK_DSCP:
4487			NEED1("missing DSCP code");
4488			fill_dscp(cmd, *av, cblen);
4489			av++;
4490			break;
4491
4492		case TOK_IPOPTS:
4493			NEED1("missing argument for ipoptions");
4494			fill_flags_cmd(cmd, O_IPOPT, f_ipopts, *av);
4495			av++;
4496			break;
4497
4498		case TOK_IPTOS:
4499			NEED1("missing argument for iptos");
4500			fill_flags_cmd(cmd, O_IPTOS, f_iptos, *av);
4501			av++;
4502			break;
4503
4504		case TOK_UID:
4505			NEED1("uid requires argument");
4506		    {
4507			char *end;
4508			uid_t uid;
4509			struct passwd *pwd;
4510
4511			cmd->opcode = O_UID;
4512			uid = strtoul(*av, &end, 0);
4513			pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
4514			if (pwd == NULL)
4515				errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
4516			cmd32->d[0] = pwd->pw_uid;
4517			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4518			av++;
4519		    }
4520			break;
4521
4522		case TOK_GID:
4523			NEED1("gid requires argument");
4524		    {
4525			char *end;
4526			gid_t gid;
4527			struct group *grp;
4528
4529			cmd->opcode = O_GID;
4530			gid = strtoul(*av, &end, 0);
4531			grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
4532			if (grp == NULL)
4533				errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
4534			cmd32->d[0] = grp->gr_gid;
4535			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4536			av++;
4537		    }
4538			break;
4539
4540		case TOK_JAIL:
4541			NEED1("jail requires argument");
4542		    {
4543			char *end;
4544			int jid;
4545
4546			cmd->opcode = O_JAIL;
4547			jid = (int)strtol(*av, &end, 0);
4548			if (jid < 0 || *end != '\0')
4549				errx(EX_DATAERR, "jail requires prison ID");
4550			cmd32->d[0] = (uint32_t)jid;
4551			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4552			av++;
4553		    }
4554			break;
4555
4556		case TOK_ESTAB:
4557			fill_cmd(cmd, O_ESTAB, 0, 0);
4558			break;
4559
4560		case TOK_SETUP:
4561			fill_cmd(cmd, O_TCPFLAGS, 0,
4562				(TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
4563			break;
4564
4565		case TOK_TCPDATALEN:
4566			NEED1("tcpdatalen requires length");
4567			if (strpbrk(*av, "-,")) {
4568			    if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
4569				errx(EX_DATAERR, "invalid tcpdata len %s", *av);
4570			} else
4571			    fill_cmd(cmd, O_TCPDATALEN, 0,
4572				    strtoul(*av, NULL, 0));
4573			av++;
4574			break;
4575
4576		case TOK_TCPOPTS:
4577			NEED1("missing argument for tcpoptions");
4578			fill_flags_cmd(cmd, O_TCPOPTS, f_tcpopts, *av);
4579			av++;
4580			break;
4581
4582		case TOK_TCPSEQ:
4583		case TOK_TCPACK:
4584			NEED1("tcpseq/tcpack requires argument");
4585			cmd->len = F_INSN_SIZE(ipfw_insn_u32);
4586			cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
4587			cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
4588			av++;
4589			break;
4590
4591		case TOK_TCPWIN:
4592			NEED1("tcpwin requires length");
4593			if (strpbrk(*av, "-,")) {
4594			    if (!add_ports(cmd, *av, 0, O_TCPWIN, cblen))
4595				errx(EX_DATAERR, "invalid tcpwin len %s", *av);
4596			} else
4597			    fill_cmd(cmd, O_TCPWIN, 0,
4598				    strtoul(*av, NULL, 0));
4599			av++;
4600			break;
4601
4602		case TOK_TCPFLAGS:
4603			NEED1("missing argument for tcpflags");
4604			cmd->opcode = O_TCPFLAGS;
4605			fill_flags_cmd(cmd, O_TCPFLAGS, f_tcpflags, *av);
4606			av++;
4607			break;
4608
4609		case TOK_KEEPSTATE: {
4610			uint16_t uidx;
4611
4612			if (open_par)
4613				errx(EX_USAGE, "keep-state cannot be part "
4614				    "of an or block");
4615			if (have_state)
4616				errx(EX_USAGE, "only one of keep-state "
4617					"and limit is allowed");
4618			if (*av != NULL && *av[0] == ':') {
4619				if (state_check_name(*av + 1) != 0)
4620					errx(EX_DATAERR,
4621					    "Invalid state name %s", *av);
4622				uidx = pack_object(tstate, *av + 1,
4623				    IPFW_TLV_STATE_NAME);
4624				av++;
4625			} else
4626				uidx = pack_object(tstate, default_state_name,
4627				    IPFW_TLV_STATE_NAME);
4628			have_state = cmd;
4629			fill_cmd(cmd, O_KEEP_STATE, 0, uidx);
4630			break;
4631		}
4632
4633		case TOK_LIMIT: {
4634			ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
4635			int val;
4636
4637			if (open_par)
4638				errx(EX_USAGE,
4639				    "limit cannot be part of an or block");
4640			if (have_state)
4641				errx(EX_USAGE, "only one of keep-state and "
4642				    "limit is allowed");
4643			have_state = cmd;
4644
4645			cmd->len = F_INSN_SIZE(ipfw_insn_limit);
4646			CHECK_CMDLEN;
4647			cmd->opcode = O_LIMIT;
4648			c->limit_mask = c->conn_limit = 0;
4649
4650			while ( av[0] != NULL ) {
4651				if ((val = match_token(limit_masks, *av)) <= 0)
4652					break;
4653				c->limit_mask |= val;
4654				av++;
4655			}
4656
4657			if (c->limit_mask == 0)
4658				errx(EX_USAGE, "limit: missing limit mask");
4659
4660			GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
4661			    TOK_LIMIT, rule_options);
4662			av++;
4663
4664			if (*av != NULL && *av[0] == ':') {
4665				if (state_check_name(*av + 1) != 0)
4666					errx(EX_DATAERR,
4667					    "Invalid state name %s", *av);
4668				cmd->arg1 = pack_object(tstate, *av + 1,
4669				    IPFW_TLV_STATE_NAME);
4670				av++;
4671			} else
4672				cmd->arg1 = pack_object(tstate,
4673				    default_state_name, IPFW_TLV_STATE_NAME);
4674			break;
4675		}
4676
4677		case TOK_PROTO:
4678			NEED1("missing protocol");
4679			if (add_proto(cmd, *av, &proto)) {
4680				av++;
4681			} else
4682				errx(EX_DATAERR, "invalid protocol ``%s''",
4683				    *av);
4684			break;
4685
4686		case TOK_SRCIP:
4687			NEED1("missing source IP");
4688			if (add_srcip(cmd, *av, cblen, tstate)) {
4689				av++;
4690			}
4691			break;
4692
4693		case TOK_DSTIP:
4694			NEED1("missing destination IP");
4695			if (add_dstip(cmd, *av, cblen, tstate)) {
4696				av++;
4697			}
4698			break;
4699
4700		case TOK_SRCIP6:
4701			NEED1("missing source IP6");
4702			if (add_srcip6(cmd, *av, cblen, tstate)) {
4703				av++;
4704			}
4705			break;
4706
4707		case TOK_DSTIP6:
4708			NEED1("missing destination IP6");
4709			if (add_dstip6(cmd, *av, cblen, tstate)) {
4710				av++;
4711			}
4712			break;
4713
4714		case TOK_SRCPORT:
4715			NEED1("missing source port");
4716			if (_substrcmp(*av, "any") == 0 ||
4717			    add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4718				av++;
4719			} else
4720				errx(EX_DATAERR, "invalid source port %s", *av);
4721			break;
4722
4723		case TOK_DSTPORT:
4724			NEED1("missing destination port");
4725			if (_substrcmp(*av, "any") == 0 ||
4726			    add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4727				av++;
4728			} else
4729				errx(EX_DATAERR, "invalid destination port %s",
4730				    *av);
4731			break;
4732
4733		case TOK_MAC:
4734			if (add_mac(cmd, av, cblen))
4735				av += 2;
4736			break;
4737
4738		case TOK_MACTYPE:
4739			NEED1("missing mac type");
4740			if (!add_mactype(cmd, *av, cblen))
4741				errx(EX_DATAERR, "invalid mac type %s", *av);
4742			av++;
4743			break;
4744
4745		case TOK_VERREVPATH:
4746			fill_cmd(cmd, O_VERREVPATH, 0, 0);
4747			break;
4748
4749		case TOK_VERSRCREACH:
4750			fill_cmd(cmd, O_VERSRCREACH, 0, 0);
4751			break;
4752
4753		case TOK_ANTISPOOF:
4754			fill_cmd(cmd, O_ANTISPOOF, 0, 0);
4755			break;
4756
4757		case TOK_IPSEC:
4758			fill_cmd(cmd, O_IPSEC, 0, 0);
4759			break;
4760
4761		case TOK_IPV6:
4762			fill_cmd(cmd, O_IP6, 0, 0);
4763			break;
4764
4765		case TOK_IPV4:
4766			fill_cmd(cmd, O_IP4, 0, 0);
4767			break;
4768
4769		case TOK_EXT6HDR:
4770			fill_ext6hdr( cmd, *av );
4771			av++;
4772			break;
4773
4774		case TOK_FLOWID:
4775			if (proto != IPPROTO_IPV6 )
4776				errx( EX_USAGE, "flow-id filter is active "
4777				    "only for ipv6 protocol\n");
4778			fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
4779			av++;
4780			break;
4781
4782		case TOK_COMMENT:
4783			fill_comment(cmd, av, cblen);
4784			av[0]=NULL;
4785			break;
4786
4787		case TOK_TAGGED:
4788			if (av[0] && strpbrk(*av, "-,")) {
4789				if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
4790					errx(EX_DATAERR, "tagged: invalid tag"
4791					    " list: %s", *av);
4792			}
4793			else {
4794				uint16_t tag;
4795
4796				GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
4797				    TOK_TAGGED, rule_options);
4798				fill_cmd(cmd, O_TAGGED, 0, tag);
4799			}
4800			av++;
4801			break;
4802
4803		case TOK_FIB:
4804			NEED1("fib requires fib number");
4805			fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
4806			av++;
4807			break;
4808		case TOK_SOCKARG:
4809			fill_cmd(cmd, O_SOCKARG, 0, 0);
4810			break;
4811
4812		case TOK_LOOKUP: {
4813			ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
4814			int j;
4815
4816			if (!av[0] || !av[1])
4817				errx(EX_USAGE, "format: lookup argument tablenum");
4818			cmd->opcode = O_IP_DST_LOOKUP;
4819			cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
4820			i = match_token(rule_options, *av);
4821			for (j = 0; lookup_key[j] >= 0 ; j++) {
4822				if (i == lookup_key[j])
4823					break;
4824			}
4825			if (lookup_key[j] <= 0)
4826				errx(EX_USAGE, "format: cannot lookup on %s", *av);
4827			__PAST_END(c->d, 1) = j; // i converted to option
4828			av++;
4829
4830			if ((j = pack_table(tstate, *av)) == 0)
4831				errx(EX_DATAERR, "Invalid table name: %s", *av);
4832
4833			cmd->arg1 = j;
4834			av++;
4835		    }
4836			break;
4837		case TOK_FLOW:
4838			NEED1("missing table name");
4839			if (strncmp(*av, "table(", 6) != 0)
4840				errx(EX_DATAERR,
4841				    "enclose table name into \"table()\"");
4842			fill_table(cmd, *av, O_IP_FLOW_LOOKUP, tstate);
4843			av++;
4844			break;
4845
4846		default:
4847			errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
4848		}
4849		if (F_LEN(cmd) > 0) {	/* prepare to advance */
4850			prev = cmd;
4851			cmd = next_cmd(cmd, &cblen);
4852		}
4853	}
4854
4855done:
4856	/*
4857	 * Now copy stuff into the rule.
4858	 * If we have a keep-state option, the first instruction
4859	 * must be a PROBE_STATE (which is generated here).
4860	 * If we have a LOG option, it was stored as the first command,
4861	 * and now must be moved to the top of the action part.
4862	 */
4863	dst = (ipfw_insn *)rule->cmd;
4864
4865	/*
4866	 * First thing to write into the command stream is the match probability.
4867	 */
4868	if (match_prob != 1) { /* 1 means always match */
4869		dst->opcode = O_PROB;
4870		dst->len = 2;
4871		*((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
4872		dst += dst->len;
4873	}
4874
4875	/*
4876	 * generate O_PROBE_STATE if necessary
4877	 */
4878	if (have_state && have_state->opcode != O_CHECK_STATE) {
4879		fill_cmd(dst, O_PROBE_STATE, 0, have_state->arg1);
4880		dst = next_cmd(dst, &rblen);
4881	}
4882
4883	/* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
4884	for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
4885		i = F_LEN(src);
4886		CHECK_RBUFLEN(i);
4887
4888		switch (src->opcode) {
4889		case O_LOG:
4890		case O_KEEP_STATE:
4891		case O_LIMIT:
4892		case O_ALTQ:
4893		case O_TAG:
4894			break;
4895		default:
4896			bcopy(src, dst, i * sizeof(uint32_t));
4897			dst += i;
4898		}
4899	}
4900
4901	/*
4902	 * put back the have_state command as last opcode
4903	 */
4904	if (have_state && have_state->opcode != O_CHECK_STATE) {
4905		i = F_LEN(have_state);
4906		CHECK_RBUFLEN(i);
4907		bcopy(have_state, dst, i * sizeof(uint32_t));
4908		dst += i;
4909	}
4910	/*
4911	 * start action section
4912	 */
4913	rule->act_ofs = dst - rule->cmd;
4914
4915	/* put back O_LOG, O_ALTQ, O_TAG if necessary */
4916	if (have_log) {
4917		i = F_LEN(have_log);
4918		CHECK_RBUFLEN(i);
4919		bcopy(have_log, dst, i * sizeof(uint32_t));
4920		dst += i;
4921	}
4922	if (have_altq) {
4923		i = F_LEN(have_altq);
4924		CHECK_RBUFLEN(i);
4925		bcopy(have_altq, dst, i * sizeof(uint32_t));
4926		dst += i;
4927	}
4928	if (have_tag) {
4929		i = F_LEN(have_tag);
4930		CHECK_RBUFLEN(i);
4931		bcopy(have_tag, dst, i * sizeof(uint32_t));
4932		dst += i;
4933	}
4934
4935	/*
4936	 * copy all other actions
4937	 */
4938	for (src = (ipfw_insn *)actbuf; src != action; src += i) {
4939		i = F_LEN(src);
4940		CHECK_RBUFLEN(i);
4941		bcopy(src, dst, i * sizeof(uint32_t));
4942		dst += i;
4943	}
4944
4945	rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
4946	*rbufsize = (char *)dst - (char *)rule;
4947}
4948
4949static int
4950compare_ntlv(const void *_a, const void *_b)
4951{
4952	ipfw_obj_ntlv *a, *b;
4953
4954	a = (ipfw_obj_ntlv *)_a;
4955	b = (ipfw_obj_ntlv *)_b;
4956
4957	if (a->set < b->set)
4958		return (-1);
4959	else if (a->set > b->set)
4960		return (1);
4961
4962	if (a->idx < b->idx)
4963		return (-1);
4964	else if (a->idx > b->idx)
4965		return (1);
4966
4967	if (a->head.type < b->head.type)
4968		return (-1);
4969	else if (a->head.type > b->head.type)
4970		return (1);
4971
4972	return (0);
4973}
4974
4975/*
4976 * Provide kernel with sorted list of referenced objects
4977 */
4978static void
4979object_sort_ctlv(ipfw_obj_ctlv *ctlv)
4980{
4981
4982	qsort(ctlv + 1, ctlv->count, ctlv->objsize, compare_ntlv);
4983}
4984
4985struct object_kt {
4986	uint16_t	uidx;
4987	uint16_t	type;
4988};
4989static int
4990compare_object_kntlv(const void *k, const void *v)
4991{
4992	ipfw_obj_ntlv *ntlv;
4993	struct object_kt key;
4994
4995	key = *((struct object_kt *)k);
4996	ntlv = (ipfw_obj_ntlv *)v;
4997
4998	if (key.uidx < ntlv->idx)
4999		return (-1);
5000	else if (key.uidx > ntlv->idx)
5001		return (1);
5002
5003	if (key.type < ntlv->head.type)
5004		return (-1);
5005	else if (key.type > ntlv->head.type)
5006		return (1);
5007
5008	return (0);
5009}
5010
5011/*
5012 * Finds object name in @ctlv by @idx and @type.
5013 * Uses the following facts:
5014 * 1) All TLVs are the same size
5015 * 2) Kernel implementation provides already sorted list.
5016 *
5017 * Returns table name or NULL.
5018 */
5019static char *
5020object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx, uint16_t type)
5021{
5022	ipfw_obj_ntlv *ntlv;
5023	struct object_kt key;
5024
5025	key.uidx = idx;
5026	key.type = type;
5027
5028	ntlv = bsearch(&key, (ctlv + 1), ctlv->count, ctlv->objsize,
5029	    compare_object_kntlv);
5030
5031	if (ntlv != NULL)
5032		return (ntlv->name);
5033
5034	return (NULL);
5035}
5036
5037static char *
5038table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx)
5039{
5040
5041	return (object_search_ctlv(ctlv, idx, IPFW_TLV_TBL_NAME));
5042}
5043
5044/*
5045 * Adds one or more rules to ipfw chain.
5046 * Data layout:
5047 * Request:
5048 * [
5049 *   ip_fw3_opheader
5050 *   [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
5051 *   [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ] (*2) (*3)
5052 * ]
5053 * Reply:
5054 * [
5055 *   ip_fw3_opheader
5056 *   [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
5057 *   [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ]
5058 * ]
5059 *
5060 * Rules in reply are modified to store their actual ruleset number.
5061 *
5062 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
5063 * according to their idx field and there has to be no duplicates.
5064 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
5065 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
5066 */
5067void
5068ipfw_add(char *av[])
5069{
5070	uint32_t rulebuf[1024];
5071	int rbufsize, default_off, tlen, rlen;
5072	size_t sz;
5073	struct tidx ts;
5074	struct ip_fw_rule *rule;
5075	caddr_t tbuf;
5076	ip_fw3_opheader *op3;
5077	ipfw_obj_ctlv *ctlv, *tstate;
5078
5079	rbufsize = sizeof(rulebuf);
5080	memset(rulebuf, 0, rbufsize);
5081	memset(&ts, 0, sizeof(ts));
5082
5083	/* Optimize case with no tables */
5084	default_off = sizeof(ipfw_obj_ctlv) + sizeof(ip_fw3_opheader);
5085	op3 = (ip_fw3_opheader *)rulebuf;
5086	ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5087	rule = (struct ip_fw_rule *)(ctlv + 1);
5088	rbufsize -= default_off;
5089
5090	compile_rule(av, (uint32_t *)rule, &rbufsize, &ts);
5091	/* Align rule size to u64 boundary */
5092	rlen = roundup2(rbufsize, sizeof(uint64_t));
5093
5094	tbuf = NULL;
5095	sz = 0;
5096	tstate = NULL;
5097	if (ts.count != 0) {
5098		/* Some tables. We have to alloc more data */
5099		tlen = ts.count * sizeof(ipfw_obj_ntlv);
5100		sz = default_off + sizeof(ipfw_obj_ctlv) + tlen + rlen;
5101
5102		if ((tbuf = calloc(1, sz)) == NULL)
5103			err(EX_UNAVAILABLE, "malloc() failed for IP_FW_ADD");
5104		op3 = (ip_fw3_opheader *)tbuf;
5105		/* Tables first */
5106		ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5107		ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
5108		ctlv->head.length = sizeof(ipfw_obj_ctlv) + tlen;
5109		ctlv->count = ts.count;
5110		ctlv->objsize = sizeof(ipfw_obj_ntlv);
5111		memcpy(ctlv + 1, ts.idx, tlen);
5112		object_sort_ctlv(ctlv);
5113		tstate = ctlv;
5114		/* Rule next */
5115		ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
5116		ctlv->head.type = IPFW_TLV_RULE_LIST;
5117		ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5118		ctlv->count = 1;
5119		memcpy(ctlv + 1, rule, rbufsize);
5120	} else {
5121		/* Simply add header */
5122		sz = rlen + default_off;
5123		memset(ctlv, 0, sizeof(*ctlv));
5124		ctlv->head.type = IPFW_TLV_RULE_LIST;
5125		ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5126		ctlv->count = 1;
5127	}
5128
5129	if (do_get3(IP_FW_XADD, op3, &sz) != 0)
5130		err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_XADD");
5131
5132	if (!co.do_quiet) {
5133		struct format_opts sfo;
5134		struct buf_pr bp;
5135		memset(&sfo, 0, sizeof(sfo));
5136		sfo.tstate = tstate;
5137		sfo.set_mask = (uint32_t)(-1);
5138		bp_alloc(&bp, 4096);
5139		show_static_rule(&co, &sfo, &bp, rule, NULL);
5140		printf("%s", bp.buf);
5141		bp_free(&bp);
5142	}
5143
5144	if (tbuf != NULL)
5145		free(tbuf);
5146
5147	if (ts.idx != NULL)
5148		free(ts.idx);
5149}
5150
5151/*
5152 * clear the counters or the log counters.
5153 * optname has the following values:
5154 *  0 (zero both counters and logging)
5155 *  1 (zero logging only)
5156 */
5157void
5158ipfw_zero(int ac, char *av[], int optname)
5159{
5160	ipfw_range_tlv rt;
5161	char const *errstr;
5162	char const *name = optname ? "RESETLOG" : "ZERO";
5163	uint32_t arg;
5164	int failed = EX_OK;
5165
5166	optname = optname ? IP_FW_XRESETLOG : IP_FW_XZERO;
5167	av++; ac--;
5168
5169	if (ac == 0) {
5170		/* clear all entries */
5171		memset(&rt, 0, sizeof(rt));
5172		rt.flags = IPFW_RCFLAG_ALL;
5173		if (do_range_cmd(optname, &rt) < 0)
5174			err(EX_UNAVAILABLE, "setsockopt(IP_FW_X%s)", name);
5175		if (!co.do_quiet)
5176			printf("%s.\n", optname == IP_FW_XZERO ?
5177			    "Accounting cleared":"Logging counts reset");
5178
5179		return;
5180	}
5181
5182	while (ac) {
5183		/* Rule number */
5184		if (isdigit(**av)) {
5185			arg = strtonum(*av, 0, 0xffff, &errstr);
5186			if (errstr)
5187				errx(EX_DATAERR,
5188				    "invalid rule number %s\n", *av);
5189			memset(&rt, 0, sizeof(rt));
5190			rt.start_rule = arg;
5191			rt.end_rule = arg;
5192			rt.flags |= IPFW_RCFLAG_RANGE;
5193			if (co.use_set != 0) {
5194				rt.set = co.use_set - 1;
5195				rt.flags |= IPFW_RCFLAG_SET;
5196			}
5197			if (do_range_cmd(optname, &rt) != 0) {
5198				warn("rule %u: setsockopt(IP_FW_X%s)",
5199				    arg, name);
5200				failed = EX_UNAVAILABLE;
5201			} else if (rt.new_set == 0) {
5202				printf("Entry %d not found\n", arg);
5203				failed = EX_UNAVAILABLE;
5204			} else if (!co.do_quiet)
5205				printf("Entry %d %s.\n", arg,
5206				    optname == IP_FW_XZERO ?
5207					"cleared" : "logging count reset");
5208		} else {
5209			errx(EX_USAGE, "invalid rule number ``%s''", *av);
5210		}
5211		av++; ac--;
5212	}
5213	if (failed != EX_OK)
5214		exit(failed);
5215}
5216
5217void
5218ipfw_flush(int force)
5219{
5220	ipfw_range_tlv rt;
5221
5222	if (!force && !co.do_quiet) { /* need to ask user */
5223		int c;
5224
5225		printf("Are you sure? [yn] ");
5226		fflush(stdout);
5227		do {
5228			c = toupper(getc(stdin));
5229			while (c != '\n' && getc(stdin) != '\n')
5230				if (feof(stdin))
5231					return; /* and do not flush */
5232		} while (c != 'Y' && c != 'N');
5233		printf("\n");
5234		if (c == 'N')	/* user said no */
5235			return;
5236	}
5237	if (co.do_pipe) {
5238		dummynet_flush();
5239		return;
5240	}
5241	/* `ipfw set N flush` - is the same that `ipfw delete set N` */
5242	memset(&rt, 0, sizeof(rt));
5243	if (co.use_set != 0) {
5244		rt.set = co.use_set - 1;
5245		rt.flags = IPFW_RCFLAG_SET;
5246	} else
5247		rt.flags = IPFW_RCFLAG_ALL;
5248	if (do_range_cmd(IP_FW_XDEL, &rt) != 0)
5249			err(EX_UNAVAILABLE, "setsockopt(IP_FW_XDEL)");
5250	if (!co.do_quiet)
5251		printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
5252}
5253
5254static struct _s_x intcmds[] = {
5255      { "talist",	TOK_TALIST },
5256      { "iflist",	TOK_IFLIST },
5257      { "olist",	TOK_OLIST },
5258      { "vlist",	TOK_VLIST },
5259      { NULL, 0 }
5260};
5261
5262static struct _s_x otypes[] = {
5263	{ "EACTION",	IPFW_TLV_EACTION },
5264	{ "DYNSTATE",	IPFW_TLV_STATE_NAME },
5265	{ NULL, 0 }
5266};
5267
5268static const char*
5269lookup_eaction_name(ipfw_obj_ntlv *ntlv, int cnt, uint16_t type)
5270{
5271	const char *name;
5272	int i;
5273
5274	name = NULL;
5275	for (i = 0; i < cnt; i++) {
5276		if (ntlv[i].head.type != IPFW_TLV_EACTION)
5277			continue;
5278		if (IPFW_TLV_EACTION_NAME(ntlv[i].idx) != type)
5279			continue;
5280		name = ntlv[i].name;
5281		break;
5282	}
5283	return (name);
5284}
5285
5286static void
5287ipfw_list_objects(int ac, char *av[])
5288{
5289	ipfw_obj_lheader req, *olh;
5290	ipfw_obj_ntlv *ntlv;
5291	const char *name;
5292	size_t sz;
5293	int i;
5294
5295	memset(&req, 0, sizeof(req));
5296	sz = sizeof(req);
5297	if (do_get3(IP_FW_DUMP_SRVOBJECTS, &req.opheader, &sz) != 0)
5298		if (errno != ENOMEM)
5299			return;
5300
5301	sz = req.size;
5302	if ((olh = calloc(1, sz)) == NULL)
5303		return;
5304
5305	olh->size = sz;
5306	if (do_get3(IP_FW_DUMP_SRVOBJECTS, &olh->opheader, &sz) != 0) {
5307		free(olh);
5308		return;
5309	}
5310
5311	if (olh->count > 0)
5312		printf("Objects list:\n");
5313	else
5314		printf("There are no objects\n");
5315	ntlv = (ipfw_obj_ntlv *)(olh + 1);
5316	for (i = 0; i < olh->count; i++) {
5317		name = match_value(otypes, ntlv->head.type);
5318		if (name == NULL)
5319			name = lookup_eaction_name(
5320			    (ipfw_obj_ntlv *)(olh + 1), olh->count,
5321			    ntlv->head.type);
5322		if (name == NULL)
5323			printf(" kidx: %4d\ttype: %10d\tname: %s\n",
5324			    ntlv->idx, ntlv->head.type, ntlv->name);
5325		else
5326			printf(" kidx: %4d\ttype: %10s\tname: %s\n",
5327			    ntlv->idx, name, ntlv->name);
5328		ntlv++;
5329	}
5330	free(olh);
5331}
5332
5333void
5334ipfw_internal_handler(int ac, char *av[])
5335{
5336	int tcmd;
5337
5338	ac--; av++;
5339	NEED1("internal cmd required");
5340
5341	if ((tcmd = match_token(intcmds, *av)) == -1)
5342		errx(EX_USAGE, "invalid internal sub-cmd: %s", *av);
5343
5344	switch (tcmd) {
5345	case TOK_IFLIST:
5346		ipfw_list_tifaces();
5347		break;
5348	case TOK_TALIST:
5349		ipfw_list_ta(ac, av);
5350		break;
5351	case TOK_OLIST:
5352		ipfw_list_objects(ac, av);
5353		break;
5354	case TOK_VLIST:
5355		ipfw_list_values(ac, av);
5356		break;
5357	}
5358}
5359
5360static int
5361ipfw_get_tracked_ifaces(ipfw_obj_lheader **polh)
5362{
5363	ipfw_obj_lheader req, *olh;
5364	size_t sz;
5365
5366	memset(&req, 0, sizeof(req));
5367	sz = sizeof(req);
5368
5369	if (do_get3(IP_FW_XIFLIST, &req.opheader, &sz) != 0) {
5370		if (errno != ENOMEM)
5371			return (errno);
5372	}
5373
5374	sz = req.size;
5375	if ((olh = calloc(1, sz)) == NULL)
5376		return (ENOMEM);
5377
5378	olh->size = sz;
5379	if (do_get3(IP_FW_XIFLIST, &olh->opheader, &sz) != 0) {
5380		free(olh);
5381		return (errno);
5382	}
5383
5384	*polh = olh;
5385	return (0);
5386}
5387
5388static int
5389ifinfo_cmp(const void *a, const void *b)
5390{
5391	ipfw_iface_info *ia, *ib;
5392
5393	ia = (ipfw_iface_info *)a;
5394	ib = (ipfw_iface_info *)b;
5395
5396	return (stringnum_cmp(ia->ifname, ib->ifname));
5397}
5398
5399/*
5400 * Retrieves table list from kernel,
5401 * optionally sorts it and calls requested function for each table.
5402 * Returns 0 on success.
5403 */
5404static void
5405ipfw_list_tifaces()
5406{
5407	ipfw_obj_lheader *olh;
5408	ipfw_iface_info *info;
5409	int i, error;
5410
5411	if ((error = ipfw_get_tracked_ifaces(&olh)) != 0)
5412		err(EX_OSERR, "Unable to request ipfw tracked interface list");
5413
5414
5415	qsort(olh + 1, olh->count, olh->objsize, ifinfo_cmp);
5416
5417	info = (ipfw_iface_info *)(olh + 1);
5418	for (i = 0; i < olh->count; i++) {
5419		if (info->flags & IPFW_IFFLAG_RESOLVED)
5420			printf("%s ifindex: %d refcount: %u changes: %u\n",
5421			    info->ifname, info->ifindex, info->refcnt,
5422			    info->gencnt);
5423		else
5424			printf("%s ifindex: unresolved refcount: %u changes: %u\n",
5425			    info->ifname, info->refcnt, info->gencnt);
5426		info = (ipfw_iface_info *)((caddr_t)info + olh->objsize);
5427	}
5428
5429	free(olh);
5430}
5431
5432
5433
5434
5435