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