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