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