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