xref: /freebsd/sbin/ipfw/ipfw2.c (revision ea906c4152774dff300bb26fbfc1e4188351c89a)
1 /*
2  * Copyright (c) 2002-2003 Luigi Rizzo
3  * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
4  * Copyright (c) 1994 Ugen J.S.Antsilevich
5  *
6  * Idea and grammar partially left from:
7  * Copyright (c) 1993 Daniel Boulet
8  *
9  * Redistribution and use in source forms, with and without modification,
10  * are permitted provided that this entire comment appears intact.
11  *
12  * Redistribution in binary form may occur without any restrictions.
13  * Obviously, it would be nice if you gave credit where credit is due
14  * but requiring it would be too onerous.
15  *
16  * This software is provided ``AS IS'' without any warranties of any kind.
17  *
18  * NEW command line interface for IP firewall facility
19  *
20  * $FreeBSD$
21  */
22 
23 #include <sys/param.h>
24 #include <sys/mbuf.h>
25 #include <sys/socket.h>
26 #include <sys/sockio.h>
27 #include <sys/sysctl.h>
28 #include <sys/time.h>
29 #include <sys/wait.h>
30 #include <sys/queue.h>
31 
32 #include <ctype.h>
33 #include <err.h>
34 #include <errno.h>
35 #include <grp.h>
36 #include <limits.h>
37 #include <netdb.h>
38 #include <pwd.h>
39 #include <signal.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <stdarg.h>
43 #include <string.h>
44 #include <timeconv.h>	/* XXX do we need this ? */
45 #include <unistd.h>
46 #include <sysexits.h>
47 #include <unistd.h>
48 #include <fcntl.h>
49 
50 #define IPFW_INTERNAL	/* Access to protected structures in ip_fw.h. */
51 
52 #include <net/ethernet.h>
53 #include <net/if.h>
54 #include <net/if_dl.h>
55 #include <net/pfvar.h>
56 #include <net/route.h> /* def. of struct route */
57 #include <netinet/in.h>
58 #include <netinet/in_systm.h>
59 #include <netinet/ip.h>
60 #include <netinet/ip_icmp.h>
61 #include <netinet/icmp6.h>
62 #include <netinet/ip_fw.h>
63 #include <netinet/ip_dummynet.h>
64 #include <netinet/tcp.h>
65 #include <arpa/inet.h>
66 #include <alias.h>
67 
68 int
69 		do_value_as_ip,		/* show table value as IP */
70 		do_resolv,		/* Would try to resolve all */
71 		do_time,		/* Show time stamps */
72 		do_quiet,		/* Be quiet in add and flush */
73 		do_pipe,		/* this cmd refers to a pipe */
74 	        do_nat, 		/* Nat configuration. */
75 		do_sort,		/* field to sort results (0 = no) */
76 		do_dynamic,		/* display dynamic rules */
77 		do_expired,		/* display expired dynamic rules */
78 		do_compact,		/* show rules in compact mode */
79 		do_force,		/* do not ask for confirmation */
80 		use_set,		/* work with specified set number */
81 		show_sets,		/* display rule sets */
82 		test_only,		/* only check syntax */
83 		comment_only,		/* only print action and comment */
84 		verbose;
85 
86 #define	IP_MASK_ALL	0xffffffff
87 /*
88  * the following macro returns an error message if we run out of
89  * arguments.
90  */
91 #define NEED1(msg)      {if (!ac) errx(EX_USAGE, msg);}
92 
93 #define GET_UINT_ARG(arg, min, max, tok, s_x) do {			\
94 	if (!ac)							\
95 		errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
96 	if (_substrcmp(*av, "tablearg") == 0) {				\
97 		arg = IP_FW_TABLEARG;					\
98 		break;							\
99 	}								\
100 									\
101 	{								\
102 	long val;							\
103 	char *end;							\
104 									\
105 	val = strtol(*av, &end, 10);					\
106 									\
107 	if (!isdigit(**av) || *end != '\0' || (val == 0 && errno == EINVAL)) \
108 		errx(EX_DATAERR, "%s: invalid argument: %s",		\
109 		    match_value(s_x, tok), *av);			\
110 									\
111 	if (errno == ERANGE || val < min || val > max)			\
112 		errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
113 		    match_value(s_x, tok), min, max, *av);		\
114 									\
115 	if (val == IP_FW_TABLEARG)					\
116 		errx(EX_DATAERR, "%s: illegal argument value: %s",	\
117 		    match_value(s_x, tok), *av);			\
118 	arg = val;							\
119 	}								\
120 } while (0)
121 
122 #define PRINT_UINT_ARG(str, arg) do {					\
123 	if (str != NULL)						\
124 		printf("%s",str);					\
125 	if (arg == IP_FW_TABLEARG)					\
126 		printf("tablearg");					\
127 	else								\
128 		printf("%u", (uint32_t)arg);				\
129 } while (0)
130 
131 /*
132  * _s_x is a structure that stores a string <-> token pairs, used in
133  * various places in the parser. Entries are stored in arrays,
134  * with an entry with s=NULL as terminator.
135  * The search routines are match_token() and match_value().
136  * Often, an element with x=0 contains an error string.
137  *
138  */
139 struct _s_x {
140 	char const *s;
141 	int x;
142 };
143 
144 static struct _s_x f_tcpflags[] = {
145 	{ "syn", TH_SYN },
146 	{ "fin", TH_FIN },
147 	{ "ack", TH_ACK },
148 	{ "psh", TH_PUSH },
149 	{ "rst", TH_RST },
150 	{ "urg", TH_URG },
151 	{ "tcp flag", 0 },
152 	{ NULL,	0 }
153 };
154 
155 static struct _s_x f_tcpopts[] = {
156 	{ "mss",	IP_FW_TCPOPT_MSS },
157 	{ "maxseg",	IP_FW_TCPOPT_MSS },
158 	{ "window",	IP_FW_TCPOPT_WINDOW },
159 	{ "sack",	IP_FW_TCPOPT_SACK },
160 	{ "ts",		IP_FW_TCPOPT_TS },
161 	{ "timestamp",	IP_FW_TCPOPT_TS },
162 	{ "cc",		IP_FW_TCPOPT_CC },
163 	{ "tcp option",	0 },
164 	{ NULL,	0 }
165 };
166 
167 /*
168  * IP options span the range 0 to 255 so we need to remap them
169  * (though in fact only the low 5 bits are significant).
170  */
171 static struct _s_x f_ipopts[] = {
172 	{ "ssrr",	IP_FW_IPOPT_SSRR},
173 	{ "lsrr",	IP_FW_IPOPT_LSRR},
174 	{ "rr",		IP_FW_IPOPT_RR},
175 	{ "ts",		IP_FW_IPOPT_TS},
176 	{ "ip option",	0 },
177 	{ NULL,	0 }
178 };
179 
180 static struct _s_x f_iptos[] = {
181 	{ "lowdelay",	IPTOS_LOWDELAY},
182 	{ "throughput",	IPTOS_THROUGHPUT},
183 	{ "reliability", IPTOS_RELIABILITY},
184 	{ "mincost",	IPTOS_MINCOST},
185 	{ "congestion",	IPTOS_ECN_CE},
186 	{ "ecntransport", IPTOS_ECN_ECT0},
187 	{ "ip tos option", 0},
188 	{ NULL,	0 }
189 };
190 
191 static struct _s_x limit_masks[] = {
192 	{"all",		DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
193 	{"src-addr",	DYN_SRC_ADDR},
194 	{"src-port",	DYN_SRC_PORT},
195 	{"dst-addr",	DYN_DST_ADDR},
196 	{"dst-port",	DYN_DST_PORT},
197 	{NULL,		0}
198 };
199 
200 /*
201  * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
202  * This is only used in this code.
203  */
204 #define IPPROTO_ETHERTYPE	0x1000
205 static struct _s_x ether_types[] = {
206     /*
207      * Note, we cannot use "-:&/" in the names because they are field
208      * separators in the type specifications. Also, we use s = NULL as
209      * end-delimiter, because a type of 0 can be legal.
210      */
211 	{ "ip",		0x0800 },
212 	{ "ipv4",	0x0800 },
213 	{ "ipv6",	0x86dd },
214 	{ "arp",	0x0806 },
215 	{ "rarp",	0x8035 },
216 	{ "vlan",	0x8100 },
217 	{ "loop",	0x9000 },
218 	{ "trail",	0x1000 },
219 	{ "at",		0x809b },
220 	{ "atalk",	0x809b },
221 	{ "aarp",	0x80f3 },
222 	{ "pppoe_disc",	0x8863 },
223 	{ "pppoe_sess",	0x8864 },
224 	{ "ipx_8022",	0x00E0 },
225 	{ "ipx_8023",	0x0000 },
226 	{ "ipx_ii",	0x8137 },
227 	{ "ipx_snap",	0x8137 },
228 	{ "ipx",	0x8137 },
229 	{ "ns",		0x0600 },
230 	{ NULL,		0 }
231 };
232 
233 static void show_usage(void);
234 
235 enum tokens {
236 	TOK_NULL=0,
237 
238 	TOK_OR,
239 	TOK_NOT,
240 	TOK_STARTBRACE,
241 	TOK_ENDBRACE,
242 
243 	TOK_ACCEPT,
244 	TOK_COUNT,
245 	TOK_PIPE,
246 	TOK_QUEUE,
247 	TOK_DIVERT,
248 	TOK_TEE,
249 	TOK_NETGRAPH,
250 	TOK_NGTEE,
251 	TOK_FORWARD,
252 	TOK_SKIPTO,
253 	TOK_DENY,
254 	TOK_REJECT,
255 	TOK_RESET,
256 	TOK_UNREACH,
257 	TOK_CHECKSTATE,
258 	TOK_NAT,
259 
260 	TOK_ALTQ,
261 	TOK_LOG,
262 	TOK_TAG,
263 	TOK_UNTAG,
264 
265 	TOK_TAGGED,
266 	TOK_UID,
267 	TOK_GID,
268 	TOK_JAIL,
269 	TOK_IN,
270 	TOK_LIMIT,
271 	TOK_KEEPSTATE,
272 	TOK_LAYER2,
273 	TOK_OUT,
274 	TOK_DIVERTED,
275 	TOK_DIVERTEDLOOPBACK,
276 	TOK_DIVERTEDOUTPUT,
277 	TOK_XMIT,
278 	TOK_RECV,
279 	TOK_VIA,
280 	TOK_FRAG,
281 	TOK_IPOPTS,
282 	TOK_IPLEN,
283 	TOK_IPID,
284 	TOK_IPPRECEDENCE,
285 	TOK_IPTOS,
286 	TOK_IPTTL,
287 	TOK_IPVER,
288 	TOK_ESTAB,
289 	TOK_SETUP,
290 	TOK_TCPDATALEN,
291 	TOK_TCPFLAGS,
292 	TOK_TCPOPTS,
293 	TOK_TCPSEQ,
294 	TOK_TCPACK,
295 	TOK_TCPWIN,
296 	TOK_ICMPTYPES,
297 	TOK_MAC,
298 	TOK_MACTYPE,
299 	TOK_VERREVPATH,
300 	TOK_VERSRCREACH,
301 	TOK_ANTISPOOF,
302 	TOK_IPSEC,
303 	TOK_COMMENT,
304 
305 	TOK_PLR,
306 	TOK_NOERROR,
307 	TOK_BUCKETS,
308 	TOK_DSTIP,
309 	TOK_SRCIP,
310 	TOK_DSTPORT,
311 	TOK_SRCPORT,
312 	TOK_ALL,
313 	TOK_MASK,
314 	TOK_BW,
315 	TOK_DELAY,
316 	TOK_RED,
317 	TOK_GRED,
318 	TOK_DROPTAIL,
319 	TOK_PROTO,
320 	TOK_WEIGHT,
321 	TOK_IP,
322 	TOK_IF,
323  	TOK_ALOG,
324  	TOK_DENY_INC,
325  	TOK_SAME_PORTS,
326  	TOK_UNREG_ONLY,
327  	TOK_RESET_ADDR,
328  	TOK_ALIAS_REV,
329  	TOK_PROXY_ONLY,
330 	TOK_REDIR_ADDR,
331 	TOK_REDIR_PORT,
332 	TOK_REDIR_PROTO,
333 
334 	TOK_IPV6,
335 	TOK_FLOWID,
336 	TOK_ICMP6TYPES,
337 	TOK_EXT6HDR,
338 	TOK_DSTIP6,
339 	TOK_SRCIP6,
340 
341 	TOK_IPV4,
342 	TOK_UNREACH6,
343 	TOK_RESET6,
344 
345 	TOK_FIB,
346 	TOK_SETFIB,
347 };
348 
349 struct _s_x dummynet_params[] = {
350 	{ "plr",		TOK_PLR },
351 	{ "noerror",		TOK_NOERROR },
352 	{ "buckets",		TOK_BUCKETS },
353 	{ "dst-ip",		TOK_DSTIP },
354 	{ "src-ip",		TOK_SRCIP },
355 	{ "dst-port",		TOK_DSTPORT },
356 	{ "src-port",		TOK_SRCPORT },
357 	{ "proto",		TOK_PROTO },
358 	{ "weight",		TOK_WEIGHT },
359 	{ "all",		TOK_ALL },
360 	{ "mask",		TOK_MASK },
361 	{ "droptail",		TOK_DROPTAIL },
362 	{ "red",		TOK_RED },
363 	{ "gred",		TOK_GRED },
364 	{ "bw",			TOK_BW },
365 	{ "bandwidth",		TOK_BW },
366 	{ "delay",		TOK_DELAY },
367 	{ "pipe",		TOK_PIPE },
368 	{ "queue",		TOK_QUEUE },
369 	{ "flow-id",		TOK_FLOWID},
370 	{ "dst-ipv6",		TOK_DSTIP6},
371 	{ "dst-ip6",		TOK_DSTIP6},
372 	{ "src-ipv6",		TOK_SRCIP6},
373 	{ "src-ip6",		TOK_SRCIP6},
374 	{ "dummynet-params",	TOK_NULL },
375 	{ NULL, 0 }	/* terminator */
376 };
377 
378 struct _s_x nat_params[] = {
379 	{ "ip",	                TOK_IP },
380 	{ "if",	                TOK_IF },
381  	{ "log",                TOK_ALOG },
382  	{ "deny_in",	        TOK_DENY_INC },
383  	{ "same_ports",	        TOK_SAME_PORTS },
384  	{ "unreg_only",	        TOK_UNREG_ONLY },
385  	{ "reset",	        TOK_RESET_ADDR },
386  	{ "reverse",	        TOK_ALIAS_REV },
387  	{ "proxy_only",	        TOK_PROXY_ONLY },
388 	{ "redirect_addr",	TOK_REDIR_ADDR },
389 	{ "redirect_port",	TOK_REDIR_PORT },
390 	{ "redirect_proto",	TOK_REDIR_PROTO },
391  	{ NULL, 0 }	/* terminator */
392 };
393 
394 struct _s_x rule_actions[] = {
395 	{ "accept",		TOK_ACCEPT },
396 	{ "pass",		TOK_ACCEPT },
397 	{ "allow",		TOK_ACCEPT },
398 	{ "permit",		TOK_ACCEPT },
399 	{ "count",		TOK_COUNT },
400 	{ "pipe",		TOK_PIPE },
401 	{ "queue",		TOK_QUEUE },
402 	{ "divert",		TOK_DIVERT },
403 	{ "tee",		TOK_TEE },
404 	{ "netgraph",		TOK_NETGRAPH },
405 	{ "ngtee",		TOK_NGTEE },
406 	{ "fwd",		TOK_FORWARD },
407 	{ "forward",		TOK_FORWARD },
408 	{ "skipto",		TOK_SKIPTO },
409 	{ "deny",		TOK_DENY },
410 	{ "drop",		TOK_DENY },
411 	{ "reject",		TOK_REJECT },
412 	{ "reset6",		TOK_RESET6 },
413 	{ "reset",		TOK_RESET },
414 	{ "unreach6",		TOK_UNREACH6 },
415 	{ "unreach",		TOK_UNREACH },
416 	{ "check-state",	TOK_CHECKSTATE },
417 	{ "//",			TOK_COMMENT },
418 	{ "nat",                TOK_NAT },
419 	{ "setfib",		TOK_SETFIB },
420 	{ NULL, 0 }	/* terminator */
421 };
422 
423 struct _s_x rule_action_params[] = {
424 	{ "altq",		TOK_ALTQ },
425 	{ "log",		TOK_LOG },
426 	{ "tag",		TOK_TAG },
427 	{ "untag",		TOK_UNTAG },
428 	{ NULL, 0 }	/* terminator */
429 };
430 
431 struct _s_x rule_options[] = {
432 	{ "tagged",		TOK_TAGGED },
433 	{ "uid",		TOK_UID },
434 	{ "gid",		TOK_GID },
435 	{ "jail",		TOK_JAIL },
436 	{ "in",			TOK_IN },
437 	{ "limit",		TOK_LIMIT },
438 	{ "keep-state",		TOK_KEEPSTATE },
439 	{ "bridged",		TOK_LAYER2 },
440 	{ "layer2",		TOK_LAYER2 },
441 	{ "out",		TOK_OUT },
442 	{ "diverted",		TOK_DIVERTED },
443 	{ "diverted-loopback",	TOK_DIVERTEDLOOPBACK },
444 	{ "diverted-output",	TOK_DIVERTEDOUTPUT },
445 	{ "xmit",		TOK_XMIT },
446 	{ "recv",		TOK_RECV },
447 	{ "via",		TOK_VIA },
448 	{ "fragment",		TOK_FRAG },
449 	{ "frag",		TOK_FRAG },
450 	{ "fib",		TOK_FIB },
451 	{ "ipoptions",		TOK_IPOPTS },
452 	{ "ipopts",		TOK_IPOPTS },
453 	{ "iplen",		TOK_IPLEN },
454 	{ "ipid",		TOK_IPID },
455 	{ "ipprecedence",	TOK_IPPRECEDENCE },
456 	{ "iptos",		TOK_IPTOS },
457 	{ "ipttl",		TOK_IPTTL },
458 	{ "ipversion",		TOK_IPVER },
459 	{ "ipver",		TOK_IPVER },
460 	{ "estab",		TOK_ESTAB },
461 	{ "established",	TOK_ESTAB },
462 	{ "setup",		TOK_SETUP },
463 	{ "tcpdatalen",		TOK_TCPDATALEN },
464 	{ "tcpflags",		TOK_TCPFLAGS },
465 	{ "tcpflgs",		TOK_TCPFLAGS },
466 	{ "tcpoptions",		TOK_TCPOPTS },
467 	{ "tcpopts",		TOK_TCPOPTS },
468 	{ "tcpseq",		TOK_TCPSEQ },
469 	{ "tcpack",		TOK_TCPACK },
470 	{ "tcpwin",		TOK_TCPWIN },
471 	{ "icmptype",		TOK_ICMPTYPES },
472 	{ "icmptypes",		TOK_ICMPTYPES },
473 	{ "dst-ip",		TOK_DSTIP },
474 	{ "src-ip",		TOK_SRCIP },
475 	{ "dst-port",		TOK_DSTPORT },
476 	{ "src-port",		TOK_SRCPORT },
477 	{ "proto",		TOK_PROTO },
478 	{ "MAC",		TOK_MAC },
479 	{ "mac",		TOK_MAC },
480 	{ "mac-type",		TOK_MACTYPE },
481 	{ "verrevpath",		TOK_VERREVPATH },
482 	{ "versrcreach",	TOK_VERSRCREACH },
483 	{ "antispoof",		TOK_ANTISPOOF },
484 	{ "ipsec",		TOK_IPSEC },
485 	{ "icmp6type",		TOK_ICMP6TYPES },
486 	{ "icmp6types",		TOK_ICMP6TYPES },
487 	{ "ext6hdr",		TOK_EXT6HDR},
488 	{ "flow-id",		TOK_FLOWID},
489 	{ "ipv6",		TOK_IPV6},
490 	{ "ip6",		TOK_IPV6},
491 	{ "ipv4",		TOK_IPV4},
492 	{ "ip4",		TOK_IPV4},
493 	{ "dst-ipv6",		TOK_DSTIP6},
494 	{ "dst-ip6",		TOK_DSTIP6},
495 	{ "src-ipv6",		TOK_SRCIP6},
496 	{ "src-ip6",		TOK_SRCIP6},
497 	{ "//",			TOK_COMMENT },
498 
499 	{ "not",		TOK_NOT },		/* pseudo option */
500 	{ "!", /* escape ? */	TOK_NOT },		/* pseudo option */
501 	{ "or",			TOK_OR },		/* pseudo option */
502 	{ "|", /* escape */	TOK_OR },		/* pseudo option */
503 	{ "{",			TOK_STARTBRACE },	/* pseudo option */
504 	{ "(",			TOK_STARTBRACE },	/* pseudo option */
505 	{ "}",			TOK_ENDBRACE },		/* pseudo option */
506 	{ ")",			TOK_ENDBRACE },		/* pseudo option */
507 	{ NULL, 0 }	/* terminator */
508 };
509 
510 #define	TABLEARG	"tablearg"
511 
512 static __inline uint64_t
513 align_uint64(uint64_t *pll) {
514 	uint64_t ret;
515 
516 	bcopy (pll, &ret, sizeof(ret));
517 	return ret;
518 }
519 
520 /*
521  * conditionally runs the command.
522  */
523 static int
524 do_cmd(int optname, void *optval, uintptr_t optlen)
525 {
526 	static int s = -1;	/* the socket */
527 	int i;
528 
529 	if (test_only)
530 		return 0;
531 
532 	if (s == -1)
533 		s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
534 	if (s < 0)
535 		err(EX_UNAVAILABLE, "socket");
536 
537 	if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
538 	    optname == IP_FW_ADD || optname == IP_FW_TABLE_LIST ||
539 	    optname == IP_FW_TABLE_GETSIZE ||
540 	    optname == IP_FW_NAT_GET_CONFIG ||
541 	    optname == IP_FW_NAT_GET_LOG)
542 		i = getsockopt(s, IPPROTO_IP, optname, optval,
543 			(socklen_t *)optlen);
544 	else
545 		i = setsockopt(s, IPPROTO_IP, optname, optval, optlen);
546 	return i;
547 }
548 
549 /**
550  * match_token takes a table and a string, returns the value associated
551  * with the string (-1 in case of failure).
552  */
553 static int
554 match_token(struct _s_x *table, char *string)
555 {
556 	struct _s_x *pt;
557 	uint i = strlen(string);
558 
559 	for (pt = table ; i && pt->s != NULL ; pt++)
560 		if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
561 			return pt->x;
562 	return -1;
563 }
564 
565 /**
566  * match_value takes a table and a value, returns the string associated
567  * with the value (NULL in case of failure).
568  */
569 static char const *
570 match_value(struct _s_x *p, int value)
571 {
572 	for (; p->s != NULL; p++)
573 		if (p->x == value)
574 			return p->s;
575 	return NULL;
576 }
577 
578 /*
579  * _substrcmp takes two strings and returns 1 if they do not match,
580  * and 0 if they match exactly or the first string is a sub-string
581  * of the second.  A warning is printed to stderr in the case that the
582  * first string is a sub-string of the second.
583  *
584  * This function will be removed in the future through the usual
585  * deprecation process.
586  */
587 static int
588 _substrcmp(const char *str1, const char* str2)
589 {
590 
591 	if (strncmp(str1, str2, strlen(str1)) != 0)
592 		return 1;
593 
594 	if (strlen(str1) != strlen(str2))
595 		warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
596 		    str1, str2);
597 	return 0;
598 }
599 
600 /*
601  * _substrcmp2 takes three strings and returns 1 if the first two do not match,
602  * and 0 if they match exactly or the second string is a sub-string
603  * of the first.  A warning is printed to stderr in the case that the
604  * first string does not match the third.
605  *
606  * This function exists to warn about the bizzare construction
607  * strncmp(str, "by", 2) which is used to allow people to use a shotcut
608  * for "bytes".  The problem is that in addition to accepting "by",
609  * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
610  * other string beginning with "by".
611  *
612  * This function will be removed in the future through the usual
613  * deprecation process.
614  */
615 static int
616 _substrcmp2(const char *str1, const char* str2, const char* str3)
617 {
618 
619 	if (strncmp(str1, str2, strlen(str2)) != 0)
620 		return 1;
621 
622 	if (strcmp(str1, str3) != 0)
623 		warnx("DEPRECATED: '%s' matched '%s'",
624 		    str1, str3);
625 	return 0;
626 }
627 
628 /*
629  * prints one port, symbolic or numeric
630  */
631 static void
632 print_port(int proto, uint16_t port)
633 {
634 
635 	if (proto == IPPROTO_ETHERTYPE) {
636 		char const *s;
637 
638 		if (do_resolv && (s = match_value(ether_types, port)) )
639 			printf("%s", s);
640 		else
641 			printf("0x%04x", port);
642 	} else {
643 		struct servent *se = NULL;
644 		if (do_resolv) {
645 			struct protoent *pe = getprotobynumber(proto);
646 
647 			se = getservbyport(htons(port), pe ? pe->p_name : NULL);
648 		}
649 		if (se)
650 			printf("%s", se->s_name);
651 		else
652 			printf("%d", port);
653 	}
654 }
655 
656 struct _s_x _port_name[] = {
657 	{"dst-port",	O_IP_DSTPORT},
658 	{"src-port",	O_IP_SRCPORT},
659 	{"ipid",	O_IPID},
660 	{"iplen",	O_IPLEN},
661 	{"ipttl",	O_IPTTL},
662 	{"mac-type",	O_MAC_TYPE},
663 	{"tcpdatalen",	O_TCPDATALEN},
664 	{"tagged",	O_TAGGED},
665 	{NULL,		0}
666 };
667 
668 /*
669  * Print the values in a list 16-bit items of the types above.
670  * XXX todo: add support for mask.
671  */
672 static void
673 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode)
674 {
675 	uint16_t *p = cmd->ports;
676 	int i;
677 	char const *sep;
678 
679 	if (opcode != 0) {
680 		sep = match_value(_port_name, opcode);
681 		if (sep == NULL)
682 			sep = "???";
683 		printf (" %s", sep);
684 	}
685 	sep = " ";
686 	for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
687 		printf(sep);
688 		print_port(proto, p[0]);
689 		if (p[0] != p[1]) {
690 			printf("-");
691 			print_port(proto, p[1]);
692 		}
693 		sep = ",";
694 	}
695 }
696 
697 /*
698  * Like strtol, but also translates service names into port numbers
699  * for some protocols.
700  * In particular:
701  *	proto == -1 disables the protocol check;
702  *	proto == IPPROTO_ETHERTYPE looks up an internal table
703  *	proto == <some value in /etc/protocols> matches the values there.
704  * Returns *end == s in case the parameter is not found.
705  */
706 static int
707 strtoport(char *s, char **end, int base, int proto)
708 {
709 	char *p, *buf;
710 	char *s1;
711 	int i;
712 
713 	*end = s;		/* default - not found */
714 	if (*s == '\0')
715 		return 0;	/* not found */
716 
717 	if (isdigit(*s))
718 		return strtol(s, end, base);
719 
720 	/*
721 	 * find separator. '\\' escapes the next char.
722 	 */
723 	for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
724 		if (*s1 == '\\' && s1[1] != '\0')
725 			s1++;
726 
727 	buf = malloc(s1 - s + 1);
728 	if (buf == NULL)
729 		return 0;
730 
731 	/*
732 	 * copy into a buffer skipping backslashes
733 	 */
734 	for (p = s, i = 0; p != s1 ; p++)
735 		if (*p != '\\')
736 			buf[i++] = *p;
737 	buf[i++] = '\0';
738 
739 	if (proto == IPPROTO_ETHERTYPE) {
740 		i = match_token(ether_types, buf);
741 		free(buf);
742 		if (i != -1) {	/* found */
743 			*end = s1;
744 			return i;
745 		}
746 	} else {
747 		struct protoent *pe = NULL;
748 		struct servent *se;
749 
750 		if (proto != 0)
751 			pe = getprotobynumber(proto);
752 		setservent(1);
753 		se = getservbyname(buf, pe ? pe->p_name : NULL);
754 		free(buf);
755 		if (se != NULL) {
756 			*end = s1;
757 			return ntohs(se->s_port);
758 		}
759 	}
760 	return 0;	/* not found */
761 }
762 
763 /*
764  * Map between current altq queue id numbers and names.
765  */
766 static int altq_fetched = 0;
767 static TAILQ_HEAD(, pf_altq) altq_entries =
768 	TAILQ_HEAD_INITIALIZER(altq_entries);
769 
770 static void
771 altq_set_enabled(int enabled)
772 {
773 	int pffd;
774 
775 	pffd = open("/dev/pf", O_RDWR);
776 	if (pffd == -1)
777 		err(EX_UNAVAILABLE,
778 		    "altq support opening pf(4) control device");
779 	if (enabled) {
780 		if (ioctl(pffd, DIOCSTARTALTQ) != 0 && errno != EEXIST)
781 			err(EX_UNAVAILABLE, "enabling altq");
782 	} else {
783 		if (ioctl(pffd, DIOCSTOPALTQ) != 0 && errno != ENOENT)
784 			err(EX_UNAVAILABLE, "disabling altq");
785 	}
786 	close(pffd);
787 }
788 
789 static void
790 altq_fetch()
791 {
792 	struct pfioc_altq pfioc;
793 	struct pf_altq *altq;
794 	int pffd, mnr;
795 
796 	if (altq_fetched)
797 		return;
798 	altq_fetched = 1;
799 	pffd = open("/dev/pf", O_RDONLY);
800 	if (pffd == -1) {
801 		warn("altq support opening pf(4) control device");
802 		return;
803 	}
804 	bzero(&pfioc, sizeof(pfioc));
805 	if (ioctl(pffd, DIOCGETALTQS, &pfioc) != 0) {
806 		warn("altq support getting queue list");
807 		close(pffd);
808 		return;
809 	}
810 	mnr = pfioc.nr;
811 	for (pfioc.nr = 0; pfioc.nr < mnr; pfioc.nr++) {
812 		if (ioctl(pffd, DIOCGETALTQ, &pfioc) != 0) {
813 			if (errno == EBUSY)
814 				break;
815 			warn("altq support getting queue list");
816 			close(pffd);
817 			return;
818 		}
819 		if (pfioc.altq.qid == 0)
820 			continue;
821 		altq = malloc(sizeof(*altq));
822 		if (altq == NULL)
823 			err(EX_OSERR, "malloc");
824 		*altq = pfioc.altq;
825 		TAILQ_INSERT_TAIL(&altq_entries, altq, entries);
826 	}
827 	close(pffd);
828 }
829 
830 static u_int32_t
831 altq_name_to_qid(const char *name)
832 {
833 	struct pf_altq *altq;
834 
835 	altq_fetch();
836 	TAILQ_FOREACH(altq, &altq_entries, entries)
837 		if (strcmp(name, altq->qname) == 0)
838 			break;
839 	if (altq == NULL)
840 		errx(EX_DATAERR, "altq has no queue named `%s'", name);
841 	return altq->qid;
842 }
843 
844 static const char *
845 altq_qid_to_name(u_int32_t qid)
846 {
847 	struct pf_altq *altq;
848 
849 	altq_fetch();
850 	TAILQ_FOREACH(altq, &altq_entries, entries)
851 		if (qid == altq->qid)
852 			break;
853 	if (altq == NULL)
854 		return NULL;
855 	return altq->qname;
856 }
857 
858 static void
859 fill_altq_qid(u_int32_t *qid, const char *av)
860 {
861 	*qid = altq_name_to_qid(av);
862 }
863 
864 /*
865  * Fill the body of the command with the list of port ranges.
866  */
867 static int
868 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto)
869 {
870 	uint16_t a, b, *p = cmd->ports;
871 	int i = 0;
872 	char *s = av;
873 
874 	while (*s) {
875 		a = strtoport(av, &s, 0, proto);
876 		if (s == av) 			/* empty or invalid argument */
877 			return (0);
878 
879 		switch (*s) {
880 		case '-':			/* a range */
881 			av = s + 1;
882 			b = strtoport(av, &s, 0, proto);
883 			/* Reject expressions like '1-abc' or '1-2-3'. */
884 			if (s == av || (*s != ',' && *s != '\0'))
885 				return (0);
886 			p[0] = a;
887 			p[1] = b;
888 			break;
889 		case ',':			/* comma separated list */
890 		case '\0':
891 			p[0] = p[1] = a;
892 			break;
893 		default:
894 			warnx("port list: invalid separator <%c> in <%s>",
895 				*s, av);
896 			return (0);
897 		}
898 
899 		i++;
900 		p += 2;
901 		av = s + 1;
902 	}
903 	if (i > 0) {
904 		if (i + 1 > F_LEN_MASK)
905 			errx(EX_DATAERR, "too many ports/ranges\n");
906 		cmd->o.len |= i + 1;	/* leave F_NOT and F_OR untouched */
907 	}
908 	return (i);
909 }
910 
911 static struct _s_x icmpcodes[] = {
912       { "net",			ICMP_UNREACH_NET },
913       { "host",			ICMP_UNREACH_HOST },
914       { "protocol",		ICMP_UNREACH_PROTOCOL },
915       { "port",			ICMP_UNREACH_PORT },
916       { "needfrag",		ICMP_UNREACH_NEEDFRAG },
917       { "srcfail",		ICMP_UNREACH_SRCFAIL },
918       { "net-unknown",		ICMP_UNREACH_NET_UNKNOWN },
919       { "host-unknown",		ICMP_UNREACH_HOST_UNKNOWN },
920       { "isolated",		ICMP_UNREACH_ISOLATED },
921       { "net-prohib",		ICMP_UNREACH_NET_PROHIB },
922       { "host-prohib",		ICMP_UNREACH_HOST_PROHIB },
923       { "tosnet",		ICMP_UNREACH_TOSNET },
924       { "toshost",		ICMP_UNREACH_TOSHOST },
925       { "filter-prohib",	ICMP_UNREACH_FILTER_PROHIB },
926       { "host-precedence",	ICMP_UNREACH_HOST_PRECEDENCE },
927       { "precedence-cutoff",	ICMP_UNREACH_PRECEDENCE_CUTOFF },
928       { NULL, 0 }
929 };
930 
931 static void
932 fill_reject_code(u_short *codep, char *str)
933 {
934 	int val;
935 	char *s;
936 
937 	val = strtoul(str, &s, 0);
938 	if (s == str || *s != '\0' || val >= 0x100)
939 		val = match_token(icmpcodes, str);
940 	if (val < 0)
941 		errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
942 	*codep = val;
943 	return;
944 }
945 
946 static void
947 print_reject_code(uint16_t code)
948 {
949 	char const *s = match_value(icmpcodes, code);
950 
951 	if (s != NULL)
952 		printf("unreach %s", s);
953 	else
954 		printf("unreach %u", code);
955 }
956 
957 static struct _s_x icmp6codes[] = {
958       { "no-route",		ICMP6_DST_UNREACH_NOROUTE },
959       { "admin-prohib",		ICMP6_DST_UNREACH_ADMIN },
960       { "address",		ICMP6_DST_UNREACH_ADDR },
961       { "port",			ICMP6_DST_UNREACH_NOPORT },
962       { NULL, 0 }
963 };
964 
965 static void
966 fill_unreach6_code(u_short *codep, char *str)
967 {
968 	int val;
969 	char *s;
970 
971 	val = strtoul(str, &s, 0);
972 	if (s == str || *s != '\0' || val >= 0x100)
973 		val = match_token(icmp6codes, str);
974 	if (val < 0)
975 		errx(EX_DATAERR, "unknown ICMPv6 unreachable code ``%s''", str);
976 	*codep = val;
977 	return;
978 }
979 
980 static void
981 print_unreach6_code(uint16_t code)
982 {
983 	char const *s = match_value(icmp6codes, code);
984 
985 	if (s != NULL)
986 		printf("unreach6 %s", s);
987 	else
988 		printf("unreach6 %u", code);
989 }
990 
991 /*
992  * Returns the number of bits set (from left) in a contiguous bitmask,
993  * or -1 if the mask is not contiguous.
994  * XXX this needs a proper fix.
995  * This effectively works on masks in big-endian (network) format.
996  * when compiled on little endian architectures.
997  *
998  * First bit is bit 7 of the first byte -- note, for MAC addresses,
999  * the first bit on the wire is bit 0 of the first byte.
1000  * len is the max length in bits.
1001  */
1002 static int
1003 contigmask(uint8_t *p, int len)
1004 {
1005 	int i, n;
1006 
1007 	for (i=0; i<len ; i++)
1008 		if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
1009 			break;
1010 	for (n=i+1; n < len; n++)
1011 		if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
1012 			return -1; /* mask not contiguous */
1013 	return i;
1014 }
1015 
1016 /*
1017  * print flags set/clear in the two bitmasks passed as parameters.
1018  * There is a specialized check for f_tcpflags.
1019  */
1020 static void
1021 print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list)
1022 {
1023 	char const *comma = "";
1024 	int i;
1025 	uint8_t set = cmd->arg1 & 0xff;
1026 	uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1027 
1028 	if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1029 		printf(" setup");
1030 		return;
1031 	}
1032 
1033 	printf(" %s ", name);
1034 	for (i=0; list[i].x != 0; i++) {
1035 		if (set & list[i].x) {
1036 			set &= ~list[i].x;
1037 			printf("%s%s", comma, list[i].s);
1038 			comma = ",";
1039 		}
1040 		if (clear & list[i].x) {
1041 			clear &= ~list[i].x;
1042 			printf("%s!%s", comma, list[i].s);
1043 			comma = ",";
1044 		}
1045 	}
1046 }
1047 
1048 /*
1049  * Print the ip address contained in a command.
1050  */
1051 static void
1052 print_ip(ipfw_insn_ip *cmd, char const *s)
1053 {
1054 	struct hostent *he = NULL;
1055 	int len = F_LEN((ipfw_insn *)cmd);
1056 	uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
1057 
1058 	printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
1059 
1060 	if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
1061 		printf("me");
1062 		return;
1063 	}
1064 	if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
1065 	    cmd->o.opcode == O_IP_DST_LOOKUP) {
1066 		printf("table(%u", ((ipfw_insn *)cmd)->arg1);
1067 		if (len == F_INSN_SIZE(ipfw_insn_u32))
1068 			printf(",%u", *a);
1069 		printf(")");
1070 		return;
1071 	}
1072 	if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1073 		uint32_t x, *map = (uint32_t *)&(cmd->mask);
1074 		int i, j;
1075 		char comma = '{';
1076 
1077 		x = cmd->o.arg1 - 1;
1078 		x = htonl( ~x );
1079 		cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1080 		printf("%s/%d", inet_ntoa(cmd->addr),
1081 			contigmask((uint8_t *)&x, 32));
1082 		x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1083 		x &= 0xff; /* base */
1084 		/*
1085 		 * Print bits and ranges.
1086 		 * Locate first bit set (i), then locate first bit unset (j).
1087 		 * If we have 3+ consecutive bits set, then print them as a
1088 		 * range, otherwise only print the initial bit and rescan.
1089 		 */
1090 		for (i=0; i < cmd->o.arg1; i++)
1091 			if (map[i/32] & (1<<(i & 31))) {
1092 				for (j=i+1; j < cmd->o.arg1; j++)
1093 					if (!(map[ j/32] & (1<<(j & 31))))
1094 						break;
1095 				printf("%c%d", comma, i+x);
1096 				if (j>i+2) { /* range has at least 3 elements */
1097 					printf("-%d", j-1+x);
1098 					i = j-1;
1099 				}
1100 				comma = ',';
1101 			}
1102 		printf("}");
1103 		return;
1104 	}
1105 	/*
1106 	 * len == 2 indicates a single IP, whereas lists of 1 or more
1107 	 * addr/mask pairs have len = (2n+1). We convert len to n so we
1108 	 * use that to count the number of entries.
1109 	 */
1110     for (len = len / 2; len > 0; len--, a += 2) {
1111 	int mb =	/* mask length */
1112 	    (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1113 		32 : contigmask((uint8_t *)&(a[1]), 32);
1114 	if (mb == 32 && do_resolv)
1115 		he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
1116 	if (he != NULL)		/* resolved to name */
1117 		printf("%s", he->h_name);
1118 	else if (mb == 0)	/* any */
1119 		printf("any");
1120 	else {		/* numeric IP followed by some kind of mask */
1121 		printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) );
1122 		if (mb < 0)
1123 			printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) );
1124 		else if (mb < 32)
1125 			printf("/%d", mb);
1126 	}
1127 	if (len > 1)
1128 		printf(",");
1129     }
1130 }
1131 
1132 /*
1133  * prints a MAC address/mask pair
1134  */
1135 static void
1136 print_mac(uint8_t *addr, uint8_t *mask)
1137 {
1138 	int l = contigmask(mask, 48);
1139 
1140 	if (l == 0)
1141 		printf(" any");
1142 	else {
1143 		printf(" %02x:%02x:%02x:%02x:%02x:%02x",
1144 		    addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1145 		if (l == -1)
1146 			printf("&%02x:%02x:%02x:%02x:%02x:%02x",
1147 			    mask[0], mask[1], mask[2],
1148 			    mask[3], mask[4], mask[5]);
1149 		else if (l < 48)
1150 			printf("/%d", l);
1151 	}
1152 }
1153 
1154 static void
1155 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1156 {
1157 	uint8_t type;
1158 
1159 	cmd->d[0] = 0;
1160 	while (*av) {
1161 		if (*av == ',')
1162 			av++;
1163 
1164 		type = strtoul(av, &av, 0);
1165 
1166 		if (*av != ',' && *av != '\0')
1167 			errx(EX_DATAERR, "invalid ICMP type");
1168 
1169 		if (type > 31)
1170 			errx(EX_DATAERR, "ICMP type out of range");
1171 
1172 		cmd->d[0] |= 1 << type;
1173 	}
1174 	cmd->o.opcode = O_ICMPTYPE;
1175 	cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1176 }
1177 
1178 static void
1179 print_icmptypes(ipfw_insn_u32 *cmd)
1180 {
1181 	int i;
1182 	char sep= ' ';
1183 
1184 	printf(" icmptypes");
1185 	for (i = 0; i < 32; i++) {
1186 		if ( (cmd->d[0] & (1 << (i))) == 0)
1187 			continue;
1188 		printf("%c%d", sep, i);
1189 		sep = ',';
1190 	}
1191 }
1192 
1193 /*
1194  * Print the ip address contained in a command.
1195  */
1196 static void
1197 print_ip6(ipfw_insn_ip6 *cmd, char const *s)
1198 {
1199        struct hostent *he = NULL;
1200        int len = F_LEN((ipfw_insn *) cmd) - 1;
1201        struct in6_addr *a = &(cmd->addr6);
1202        char trad[255];
1203 
1204        printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
1205 
1206        if (cmd->o.opcode == O_IP6_SRC_ME || cmd->o.opcode == O_IP6_DST_ME) {
1207                printf("me6");
1208                return;
1209        }
1210        if (cmd->o.opcode == O_IP6) {
1211                printf(" ip6");
1212                return;
1213        }
1214 
1215        /*
1216         * len == 4 indicates a single IP, whereas lists of 1 or more
1217         * addr/mask pairs have len = (2n+1). We convert len to n so we
1218         * use that to count the number of entries.
1219         */
1220 
1221        for (len = len / 4; len > 0; len -= 2, a += 2) {
1222            int mb =        /* mask length */
1223                (cmd->o.opcode == O_IP6_SRC || cmd->o.opcode == O_IP6_DST) ?
1224                128 : contigmask((uint8_t *)&(a[1]), 128);
1225 
1226            if (mb == 128 && do_resolv)
1227                he = gethostbyaddr((char *)a, sizeof(*a), AF_INET6);
1228            if (he != NULL)             /* resolved to name */
1229                printf("%s", he->h_name);
1230            else if (mb == 0)           /* any */
1231                printf("any");
1232            else {          /* numeric IP followed by some kind of mask */
1233                if (inet_ntop(AF_INET6,  a, trad, sizeof( trad ) ) == NULL)
1234                    printf("Error ntop in print_ip6\n");
1235                printf("%s",  trad );
1236                if (mb < 0)     /* XXX not really legal... */
1237                    printf(":%s",
1238                        inet_ntop(AF_INET6, &a[1], trad, sizeof(trad)));
1239                else if (mb < 128)
1240                    printf("/%d", mb);
1241            }
1242            if (len > 2)
1243                printf(",");
1244        }
1245 }
1246 
1247 static void
1248 fill_icmp6types(ipfw_insn_icmp6 *cmd, char *av)
1249 {
1250        uint8_t type;
1251 
1252        bzero(cmd, sizeof(*cmd));
1253        while (*av) {
1254            if (*av == ',')
1255                av++;
1256            type = strtoul(av, &av, 0);
1257            if (*av != ',' && *av != '\0')
1258                errx(EX_DATAERR, "invalid ICMP6 type");
1259 	   /*
1260 	    * XXX: shouldn't this be 0xFF?  I can't see any reason why
1261 	    * we shouldn't be able to filter all possiable values
1262 	    * regardless of the ability of the rest of the kernel to do
1263 	    * anything useful with them.
1264 	    */
1265            if (type > ICMP6_MAXTYPE)
1266                errx(EX_DATAERR, "ICMP6 type out of range");
1267            cmd->d[type / 32] |= ( 1 << (type % 32));
1268        }
1269        cmd->o.opcode = O_ICMP6TYPE;
1270        cmd->o.len |= F_INSN_SIZE(ipfw_insn_icmp6);
1271 }
1272 
1273 
1274 static void
1275 print_icmp6types(ipfw_insn_u32 *cmd)
1276 {
1277        int i, j;
1278        char sep= ' ';
1279 
1280        printf(" ip6 icmp6types");
1281        for (i = 0; i < 7; i++)
1282                for (j=0; j < 32; ++j) {
1283                        if ( (cmd->d[i] & (1 << (j))) == 0)
1284                                continue;
1285                        printf("%c%d", sep, (i*32 + j));
1286                        sep = ',';
1287                }
1288 }
1289 
1290 static void
1291 print_flow6id( ipfw_insn_u32 *cmd)
1292 {
1293        uint16_t i, limit = cmd->o.arg1;
1294        char sep = ',';
1295 
1296        printf(" flow-id ");
1297        for( i=0; i < limit; ++i) {
1298                if (i == limit - 1)
1299                        sep = ' ';
1300                printf("%d%c", cmd->d[i], sep);
1301        }
1302 }
1303 
1304 /* structure and define for the extension header in ipv6 */
1305 static struct _s_x ext6hdrcodes[] = {
1306        { "frag",       EXT_FRAGMENT },
1307        { "hopopt",     EXT_HOPOPTS },
1308        { "route",      EXT_ROUTING },
1309        { "dstopt",     EXT_DSTOPTS },
1310        { "ah",         EXT_AH },
1311        { "esp",        EXT_ESP },
1312        { "rthdr0",     EXT_RTHDR0 },
1313        { "rthdr2",     EXT_RTHDR2 },
1314        { NULL,         0 }
1315 };
1316 
1317 /* fills command for the extension header filtering */
1318 int
1319 fill_ext6hdr( ipfw_insn *cmd, char *av)
1320 {
1321        int tok;
1322        char *s = av;
1323 
1324        cmd->arg1 = 0;
1325 
1326        while(s) {
1327            av = strsep( &s, ",") ;
1328            tok = match_token(ext6hdrcodes, av);
1329            switch (tok) {
1330            case EXT_FRAGMENT:
1331                cmd->arg1 |= EXT_FRAGMENT;
1332                break;
1333 
1334            case EXT_HOPOPTS:
1335                cmd->arg1 |= EXT_HOPOPTS;
1336                break;
1337 
1338            case EXT_ROUTING:
1339                cmd->arg1 |= EXT_ROUTING;
1340                break;
1341 
1342            case EXT_DSTOPTS:
1343                cmd->arg1 |= EXT_DSTOPTS;
1344                break;
1345 
1346            case EXT_AH:
1347                cmd->arg1 |= EXT_AH;
1348                break;
1349 
1350            case EXT_ESP:
1351                cmd->arg1 |= EXT_ESP;
1352                break;
1353 
1354            case EXT_RTHDR0:
1355                cmd->arg1 |= EXT_RTHDR0;
1356                break;
1357 
1358            case EXT_RTHDR2:
1359                cmd->arg1 |= EXT_RTHDR2;
1360                break;
1361 
1362            default:
1363                errx( EX_DATAERR, "invalid option for ipv6 exten header" );
1364                break;
1365            }
1366        }
1367        if (cmd->arg1 == 0 )
1368            return 0;
1369        cmd->opcode = O_EXT_HDR;
1370        cmd->len |= F_INSN_SIZE( ipfw_insn );
1371        return 1;
1372 }
1373 
1374 void
1375 print_ext6hdr( ipfw_insn *cmd )
1376 {
1377        char sep = ' ';
1378 
1379        printf(" extension header:");
1380        if (cmd->arg1 & EXT_FRAGMENT ) {
1381            printf("%cfragmentation", sep);
1382            sep = ',';
1383        }
1384        if (cmd->arg1 & EXT_HOPOPTS ) {
1385            printf("%chop options", sep);
1386            sep = ',';
1387        }
1388        if (cmd->arg1 & EXT_ROUTING ) {
1389            printf("%crouting options", sep);
1390            sep = ',';
1391        }
1392        if (cmd->arg1 & EXT_RTHDR0 ) {
1393            printf("%crthdr0", sep);
1394            sep = ',';
1395        }
1396        if (cmd->arg1 & EXT_RTHDR2 ) {
1397            printf("%crthdr2", sep);
1398            sep = ',';
1399        }
1400        if (cmd->arg1 & EXT_DSTOPTS ) {
1401            printf("%cdestination options", sep);
1402            sep = ',';
1403        }
1404        if (cmd->arg1 & EXT_AH ) {
1405            printf("%cauthentication header", sep);
1406            sep = ',';
1407        }
1408        if (cmd->arg1 & EXT_ESP ) {
1409            printf("%cencapsulated security payload", sep);
1410        }
1411 }
1412 
1413 /*
1414  * show_ipfw() prints the body of an ipfw rule.
1415  * Because the standard rule has at least proto src_ip dst_ip, we use
1416  * a helper function to produce these entries if not provided explicitly.
1417  * The first argument is the list of fields we have, the second is
1418  * the list of fields we want to be printed.
1419  *
1420  * Special cases if we have provided a MAC header:
1421  *   + if the rule does not contain IP addresses/ports, do not print them;
1422  *   + if the rule does not contain an IP proto, print "all" instead of "ip";
1423  *
1424  * Once we have 'have_options', IP header fields are printed as options.
1425  */
1426 #define	HAVE_PROTO	0x0001
1427 #define	HAVE_SRCIP	0x0002
1428 #define	HAVE_DSTIP	0x0004
1429 #define	HAVE_PROTO4	0x0008
1430 #define	HAVE_PROTO6	0x0010
1431 #define	HAVE_OPTIONS	0x8000
1432 
1433 #define	HAVE_IP		(HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP)
1434 static void
1435 show_prerequisites(int *flags, int want, int cmd)
1436 {
1437 	if (comment_only)
1438 		return;
1439 	if ( (*flags & HAVE_IP) == HAVE_IP)
1440 		*flags |= HAVE_OPTIONS;
1441 
1442 	if ( !(*flags & HAVE_OPTIONS)) {
1443 		if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO))
1444 			if ( (*flags & HAVE_PROTO4))
1445 				printf(" ip4");
1446 			else if ( (*flags & HAVE_PROTO6))
1447 				printf(" ip6");
1448 			else
1449 				printf(" ip");
1450 
1451 		if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
1452 			printf(" from any");
1453 		if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
1454 			printf(" to any");
1455 	}
1456 	*flags |= want;
1457 }
1458 
1459 static void
1460 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth)
1461 {
1462 	static int twidth = 0;
1463 	int l;
1464 	ipfw_insn *cmd, *tagptr = NULL;
1465 	char *comment = NULL;	/* ptr to comment if we have one */
1466 	int proto = 0;		/* default */
1467 	int flags = 0;	/* prerequisites */
1468 	ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
1469 	ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
1470 	int or_block = 0;	/* we are in an or block */
1471 	uint32_t set_disable;
1472 
1473 	bcopy(&rule->next_rule, &set_disable, sizeof(set_disable));
1474 
1475 	if (set_disable & (1 << rule->set)) { /* disabled */
1476 		if (!show_sets)
1477 			return;
1478 		else
1479 			printf("# DISABLED ");
1480 	}
1481 	printf("%05u ", rule->rulenum);
1482 
1483 	if (pcwidth>0 || bcwidth>0)
1484 		printf("%*llu %*llu ", pcwidth, align_uint64(&rule->pcnt),
1485 		    bcwidth, align_uint64(&rule->bcnt));
1486 
1487 	if (do_time == 2)
1488 		printf("%10u ", rule->timestamp);
1489 	else if (do_time == 1) {
1490 		char timestr[30];
1491 		time_t t = (time_t)0;
1492 
1493 		if (twidth == 0) {
1494 			strcpy(timestr, ctime(&t));
1495 			*strchr(timestr, '\n') = '\0';
1496 			twidth = strlen(timestr);
1497 		}
1498 		if (rule->timestamp) {
1499 			t = _long_to_time(rule->timestamp);
1500 
1501 			strcpy(timestr, ctime(&t));
1502 			*strchr(timestr, '\n') = '\0';
1503 			printf("%s ", timestr);
1504 		} else {
1505 			printf("%*s", twidth, " ");
1506 		}
1507 	}
1508 
1509 	if (show_sets)
1510 		printf("set %d ", rule->set);
1511 
1512 	/*
1513 	 * print the optional "match probability"
1514 	 */
1515 	if (rule->cmd_len > 0) {
1516 		cmd = rule->cmd ;
1517 		if (cmd->opcode == O_PROB) {
1518 			ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1519 			double d = 1.0 * p->d[0];
1520 
1521 			d = (d / 0x7fffffff);
1522 			printf("prob %f ", d);
1523 		}
1524 	}
1525 
1526 	/*
1527 	 * first print actions
1528 	 */
1529         for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1530 			l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1531 		switch(cmd->opcode) {
1532 		case O_CHECK_STATE:
1533 			printf("check-state");
1534 			flags = HAVE_IP; /* avoid printing anything else */
1535 			break;
1536 
1537 		case O_ACCEPT:
1538 			printf("allow");
1539 			break;
1540 
1541 		case O_COUNT:
1542 			printf("count");
1543 			break;
1544 
1545 		case O_DENY:
1546 			printf("deny");
1547 			break;
1548 
1549 		case O_REJECT:
1550 			if (cmd->arg1 == ICMP_REJECT_RST)
1551 				printf("reset");
1552 			else if (cmd->arg1 == ICMP_UNREACH_HOST)
1553 				printf("reject");
1554 			else
1555 				print_reject_code(cmd->arg1);
1556 			break;
1557 
1558 		case O_UNREACH6:
1559 			if (cmd->arg1 == ICMP6_UNREACH_RST)
1560 				printf("reset6");
1561 			else
1562 				print_unreach6_code(cmd->arg1);
1563 			break;
1564 
1565 		case O_SKIPTO:
1566 			PRINT_UINT_ARG("skipto ", cmd->arg1);
1567 			break;
1568 
1569 		case O_PIPE:
1570 			PRINT_UINT_ARG("pipe ", cmd->arg1);
1571 			break;
1572 
1573 		case O_QUEUE:
1574 			PRINT_UINT_ARG("queue ", cmd->arg1);
1575 			break;
1576 
1577 		case O_DIVERT:
1578 			PRINT_UINT_ARG("divert ", cmd->arg1);
1579 			break;
1580 
1581 		case O_TEE:
1582 			PRINT_UINT_ARG("tee ", cmd->arg1);
1583 			break;
1584 
1585 		case O_NETGRAPH:
1586 			PRINT_UINT_ARG("netgraph ", cmd->arg1);
1587 			break;
1588 
1589 		case O_NGTEE:
1590 			PRINT_UINT_ARG("ngtee ", cmd->arg1);
1591 			break;
1592 
1593 		case O_FORWARD_IP:
1594 		    {
1595 			ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1596 
1597 			if (s->sa.sin_addr.s_addr == INADDR_ANY) {
1598 				printf("fwd tablearg");
1599 			} else {
1600 				printf("fwd %s", inet_ntoa(s->sa.sin_addr));
1601 			}
1602 			if (s->sa.sin_port)
1603 				printf(",%d", s->sa.sin_port);
1604 		    }
1605 			break;
1606 
1607 		case O_LOG: /* O_LOG is printed last */
1608 			logptr = (ipfw_insn_log *)cmd;
1609 			break;
1610 
1611 		case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1612 			altqptr = (ipfw_insn_altq *)cmd;
1613 			break;
1614 
1615 		case O_TAG:
1616 			tagptr = cmd;
1617 			break;
1618 
1619 		case O_NAT:
1620 			PRINT_UINT_ARG("nat ", cmd->arg1);
1621  			break;
1622 
1623 		case O_SETFIB:
1624 			PRINT_UINT_ARG("setfib ", cmd->arg1);
1625  			break;
1626 
1627 		default:
1628 			printf("** unrecognized action %d len %d ",
1629 				cmd->opcode, cmd->len);
1630 		}
1631 	}
1632 	if (logptr) {
1633 		if (logptr->max_log > 0)
1634 			printf(" log logamount %d", logptr->max_log);
1635 		else
1636 			printf(" log");
1637 	}
1638 	if (altqptr) {
1639 		const char *qname;
1640 
1641 		qname = altq_qid_to_name(altqptr->qid);
1642 		if (qname == NULL)
1643 			printf(" altq ?<%u>", altqptr->qid);
1644 		else
1645 			printf(" altq %s", qname);
1646 	}
1647 	if (tagptr) {
1648 		if (tagptr->len & F_NOT)
1649 			PRINT_UINT_ARG(" untag ", tagptr->arg1);
1650 		else
1651 			PRINT_UINT_ARG(" tag ", tagptr->arg1);
1652 	}
1653 
1654 	/*
1655 	 * then print the body.
1656 	 */
1657         for (l = rule->act_ofs, cmd = rule->cmd ;
1658 			l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1659 		if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1660 			continue;
1661 		if (cmd->opcode == O_IP4) {
1662 			flags |= HAVE_PROTO4;
1663 			break;
1664 		} else if (cmd->opcode == O_IP6) {
1665 			flags |= HAVE_PROTO6;
1666 			break;
1667 		}
1668 	}
1669 	if (rule->_pad & 1) {	/* empty rules before options */
1670 		if (!do_compact) {
1671 			show_prerequisites(&flags, HAVE_PROTO, 0);
1672 			printf(" from any to any");
1673 		}
1674 		flags |= HAVE_IP | HAVE_OPTIONS;
1675 	}
1676 
1677 	if (comment_only)
1678 		comment = "...";
1679 
1680         for (l = rule->act_ofs, cmd = rule->cmd ;
1681 			l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1682 		/* useful alias */
1683 		ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1684 
1685 		if (comment_only) {
1686 			if (cmd->opcode != O_NOP)
1687 				continue;
1688 			printf(" // %s\n", (char *)(cmd + 1));
1689 			return;
1690 		}
1691 
1692 		show_prerequisites(&flags, 0, cmd->opcode);
1693 
1694 		switch(cmd->opcode) {
1695 		case O_PROB:
1696 			break;	/* done already */
1697 
1698 		case O_PROBE_STATE:
1699 			break; /* no need to print anything here */
1700 
1701 		case O_IP_SRC:
1702 		case O_IP_SRC_LOOKUP:
1703 		case O_IP_SRC_MASK:
1704 		case O_IP_SRC_ME:
1705 		case O_IP_SRC_SET:
1706 			show_prerequisites(&flags, HAVE_PROTO, 0);
1707 			if (!(flags & HAVE_SRCIP))
1708 				printf(" from");
1709 			if ((cmd->len & F_OR) && !or_block)
1710 				printf(" {");
1711 			print_ip((ipfw_insn_ip *)cmd,
1712 				(flags & HAVE_OPTIONS) ? " src-ip" : "");
1713 			flags |= HAVE_SRCIP;
1714 			break;
1715 
1716 		case O_IP_DST:
1717 		case O_IP_DST_LOOKUP:
1718 		case O_IP_DST_MASK:
1719 		case O_IP_DST_ME:
1720 		case O_IP_DST_SET:
1721 			show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1722 			if (!(flags & HAVE_DSTIP))
1723 				printf(" to");
1724 			if ((cmd->len & F_OR) && !or_block)
1725 				printf(" {");
1726 			print_ip((ipfw_insn_ip *)cmd,
1727 				(flags & HAVE_OPTIONS) ? " dst-ip" : "");
1728 			flags |= HAVE_DSTIP;
1729 			break;
1730 
1731 		case O_IP6_SRC:
1732 		case O_IP6_SRC_MASK:
1733 		case O_IP6_SRC_ME:
1734 			show_prerequisites(&flags, HAVE_PROTO, 0);
1735 			if (!(flags & HAVE_SRCIP))
1736 				printf(" from");
1737 			if ((cmd->len & F_OR) && !or_block)
1738 				printf(" {");
1739 			print_ip6((ipfw_insn_ip6 *)cmd,
1740 			    (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1741 			flags |= HAVE_SRCIP | HAVE_PROTO;
1742 			break;
1743 
1744 		case O_IP6_DST:
1745 		case O_IP6_DST_MASK:
1746 		case O_IP6_DST_ME:
1747 			show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1748 			if (!(flags & HAVE_DSTIP))
1749 				printf(" to");
1750 			if ((cmd->len & F_OR) && !or_block)
1751 				printf(" {");
1752 			print_ip6((ipfw_insn_ip6 *)cmd,
1753 			    (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1754 			flags |= HAVE_DSTIP;
1755 			break;
1756 
1757 		case O_FLOW6ID:
1758 		print_flow6id( (ipfw_insn_u32 *) cmd );
1759 		flags |= HAVE_OPTIONS;
1760 		break;
1761 
1762 		case O_IP_DSTPORT:
1763 			show_prerequisites(&flags, HAVE_IP, 0);
1764 		case O_IP_SRCPORT:
1765 			show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1766 			if ((cmd->len & F_OR) && !or_block)
1767 				printf(" {");
1768 			if (cmd->len & F_NOT)
1769 				printf(" not");
1770 			print_newports((ipfw_insn_u16 *)cmd, proto,
1771 				(flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1772 			break;
1773 
1774 		case O_PROTO: {
1775 			struct protoent *pe = NULL;
1776 
1777 			if ((cmd->len & F_OR) && !or_block)
1778 				printf(" {");
1779 			if (cmd->len & F_NOT)
1780 				printf(" not");
1781 			proto = cmd->arg1;
1782 			pe = getprotobynumber(cmd->arg1);
1783 			if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1784 			    !(flags & HAVE_PROTO))
1785 				show_prerequisites(&flags,
1786 				    HAVE_IP | HAVE_OPTIONS, 0);
1787 			if (flags & HAVE_OPTIONS)
1788 				printf(" proto");
1789 			if (pe)
1790 				printf(" %s", pe->p_name);
1791 			else
1792 				printf(" %u", cmd->arg1);
1793 			}
1794 			flags |= HAVE_PROTO;
1795 			break;
1796 
1797 		default: /*options ... */
1798 			if (!(cmd->len & (F_OR|F_NOT)))
1799 				if (((cmd->opcode == O_IP6) &&
1800 				    (flags & HAVE_PROTO6)) ||
1801 				    ((cmd->opcode == O_IP4) &&
1802 				    (flags & HAVE_PROTO4)))
1803 					break;
1804 			show_prerequisites(&flags, HAVE_IP | HAVE_OPTIONS, 0);
1805 			if ((cmd->len & F_OR) && !or_block)
1806 				printf(" {");
1807 			if (cmd->len & F_NOT && cmd->opcode != O_IN)
1808 				printf(" not");
1809 			switch(cmd->opcode) {
1810 			case O_MACADDR2: {
1811 				ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1812 
1813 				printf(" MAC");
1814 				print_mac(m->addr, m->mask);
1815 				print_mac(m->addr + 6, m->mask + 6);
1816 				}
1817 				break;
1818 
1819 			case O_MAC_TYPE:
1820 				print_newports((ipfw_insn_u16 *)cmd,
1821 						IPPROTO_ETHERTYPE, cmd->opcode);
1822 				break;
1823 
1824 
1825 			case O_FRAG:
1826 				printf(" frag");
1827 				break;
1828 
1829 			case O_FIB:
1830 				printf(" fib %u", cmd->arg1 );
1831 				break;
1832 
1833 			case O_IN:
1834 				printf(cmd->len & F_NOT ? " out" : " in");
1835 				break;
1836 
1837 			case O_DIVERTED:
1838 				switch (cmd->arg1) {
1839 				case 3:
1840 					printf(" diverted");
1841 					break;
1842 				case 1:
1843 					printf(" diverted-loopback");
1844 					break;
1845 				case 2:
1846 					printf(" diverted-output");
1847 					break;
1848 				default:
1849 					printf(" diverted-?<%u>", cmd->arg1);
1850 					break;
1851 				}
1852 				break;
1853 
1854 			case O_LAYER2:
1855 				printf(" layer2");
1856 				break;
1857 			case O_XMIT:
1858 			case O_RECV:
1859 			case O_VIA:
1860 			    {
1861 				char const *s;
1862 				ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1863 
1864 				if (cmd->opcode == O_XMIT)
1865 					s = "xmit";
1866 				else if (cmd->opcode == O_RECV)
1867 					s = "recv";
1868 				else /* if (cmd->opcode == O_VIA) */
1869 					s = "via";
1870 				if (cmdif->name[0] == '\0')
1871 					printf(" %s %s", s,
1872 					    inet_ntoa(cmdif->p.ip));
1873 				else
1874 					printf(" %s %s", s, cmdif->name);
1875 
1876 				break;
1877 			    }
1878 			case O_IPID:
1879 				if (F_LEN(cmd) == 1)
1880 				    printf(" ipid %u", cmd->arg1 );
1881 				else
1882 				    print_newports((ipfw_insn_u16 *)cmd, 0,
1883 					O_IPID);
1884 				break;
1885 
1886 			case O_IPTTL:
1887 				if (F_LEN(cmd) == 1)
1888 				    printf(" ipttl %u", cmd->arg1 );
1889 				else
1890 				    print_newports((ipfw_insn_u16 *)cmd, 0,
1891 					O_IPTTL);
1892 				break;
1893 
1894 			case O_IPVER:
1895 				printf(" ipver %u", cmd->arg1 );
1896 				break;
1897 
1898 			case O_IPPRECEDENCE:
1899 				printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1900 				break;
1901 
1902 			case O_IPLEN:
1903 				if (F_LEN(cmd) == 1)
1904 				    printf(" iplen %u", cmd->arg1 );
1905 				else
1906 				    print_newports((ipfw_insn_u16 *)cmd, 0,
1907 					O_IPLEN);
1908 				break;
1909 
1910 			case O_IPOPT:
1911 				print_flags("ipoptions", cmd, f_ipopts);
1912 				break;
1913 
1914 			case O_IPTOS:
1915 				print_flags("iptos", cmd, f_iptos);
1916 				break;
1917 
1918 			case O_ICMPTYPE:
1919 				print_icmptypes((ipfw_insn_u32 *)cmd);
1920 				break;
1921 
1922 			case O_ESTAB:
1923 				printf(" established");
1924 				break;
1925 
1926 			case O_TCPDATALEN:
1927 				if (F_LEN(cmd) == 1)
1928 				    printf(" tcpdatalen %u", cmd->arg1 );
1929 				else
1930 				    print_newports((ipfw_insn_u16 *)cmd, 0,
1931 					O_TCPDATALEN);
1932 				break;
1933 
1934 			case O_TCPFLAGS:
1935 				print_flags("tcpflags", cmd, f_tcpflags);
1936 				break;
1937 
1938 			case O_TCPOPTS:
1939 				print_flags("tcpoptions", cmd, f_tcpopts);
1940 				break;
1941 
1942 			case O_TCPWIN:
1943 				printf(" tcpwin %d", ntohs(cmd->arg1));
1944 				break;
1945 
1946 			case O_TCPACK:
1947 				printf(" tcpack %d", ntohl(cmd32->d[0]));
1948 				break;
1949 
1950 			case O_TCPSEQ:
1951 				printf(" tcpseq %d", ntohl(cmd32->d[0]));
1952 				break;
1953 
1954 			case O_UID:
1955 			    {
1956 				struct passwd *pwd = getpwuid(cmd32->d[0]);
1957 
1958 				if (pwd)
1959 					printf(" uid %s", pwd->pw_name);
1960 				else
1961 					printf(" uid %u", cmd32->d[0]);
1962 			    }
1963 				break;
1964 
1965 			case O_GID:
1966 			    {
1967 				struct group *grp = getgrgid(cmd32->d[0]);
1968 
1969 				if (grp)
1970 					printf(" gid %s", grp->gr_name);
1971 				else
1972 					printf(" gid %u", cmd32->d[0]);
1973 			    }
1974 				break;
1975 
1976 			case O_JAIL:
1977 				printf(" jail %d", cmd32->d[0]);
1978 				break;
1979 
1980 			case O_VERREVPATH:
1981 				printf(" verrevpath");
1982 				break;
1983 
1984 			case O_VERSRCREACH:
1985 				printf(" versrcreach");
1986 				break;
1987 
1988 			case O_ANTISPOOF:
1989 				printf(" antispoof");
1990 				break;
1991 
1992 			case O_IPSEC:
1993 				printf(" ipsec");
1994 				break;
1995 
1996 			case O_NOP:
1997 				comment = (char *)(cmd + 1);
1998 				break;
1999 
2000 			case O_KEEP_STATE:
2001 				printf(" keep-state");
2002 				break;
2003 
2004 			case O_LIMIT: {
2005 				struct _s_x *p = limit_masks;
2006 				ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
2007 				uint8_t x = c->limit_mask;
2008 				char const *comma = " ";
2009 
2010 				printf(" limit");
2011 				for (; p->x != 0 ; p++)
2012 					if ((x & p->x) == p->x) {
2013 						x &= ~p->x;
2014 						printf("%s%s", comma, p->s);
2015 						comma = ",";
2016 					}
2017 				PRINT_UINT_ARG(" ", c->conn_limit);
2018 				break;
2019 			}
2020 
2021 			case O_IP6:
2022 				printf(" ip6");
2023 				break;
2024 
2025 			case O_IP4:
2026 				printf(" ip4");
2027 				break;
2028 
2029 			case O_ICMP6TYPE:
2030 				print_icmp6types((ipfw_insn_u32 *)cmd);
2031 				break;
2032 
2033 			case O_EXT_HDR:
2034 				print_ext6hdr( (ipfw_insn *) cmd );
2035 				break;
2036 
2037 			case O_TAGGED:
2038 				if (F_LEN(cmd) == 1)
2039 					PRINT_UINT_ARG(" tagged ", cmd->arg1);
2040 				else
2041 					print_newports((ipfw_insn_u16 *)cmd, 0,
2042 					    O_TAGGED);
2043 				break;
2044 
2045 			default:
2046 				printf(" [opcode %d len %d]",
2047 				    cmd->opcode, cmd->len);
2048 			}
2049 		}
2050 		if (cmd->len & F_OR) {
2051 			printf(" or");
2052 			or_block = 1;
2053 		} else if (or_block) {
2054 			printf(" }");
2055 			or_block = 0;
2056 		}
2057 	}
2058 	show_prerequisites(&flags, HAVE_IP, 0);
2059 	if (comment)
2060 		printf(" // %s", comment);
2061 	printf("\n");
2062 }
2063 
2064 static void
2065 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth)
2066 {
2067 	struct protoent *pe;
2068 	struct in_addr a;
2069 	uint16_t rulenum;
2070 	char buf[INET6_ADDRSTRLEN];
2071 
2072 	if (!do_expired) {
2073 		if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
2074 			return;
2075 	}
2076 	bcopy(&d->rule, &rulenum, sizeof(rulenum));
2077 	printf("%05d", rulenum);
2078 	if (pcwidth>0 || bcwidth>0)
2079 	    printf(" %*llu %*llu (%ds)", pcwidth,
2080 		align_uint64(&d->pcnt), bcwidth,
2081 		align_uint64(&d->bcnt), d->expire);
2082 	switch (d->dyn_type) {
2083 	case O_LIMIT_PARENT:
2084 		printf(" PARENT %d", d->count);
2085 		break;
2086 	case O_LIMIT:
2087 		printf(" LIMIT");
2088 		break;
2089 	case O_KEEP_STATE: /* bidir, no mask */
2090 		printf(" STATE");
2091 		break;
2092 	}
2093 
2094 	if ((pe = getprotobynumber(d->id.proto)) != NULL)
2095 		printf(" %s", pe->p_name);
2096 	else
2097 		printf(" proto %u", d->id.proto);
2098 
2099 	if (d->id.addr_type == 4) {
2100 		a.s_addr = htonl(d->id.src_ip);
2101 		printf(" %s %d", inet_ntoa(a), d->id.src_port);
2102 
2103 		a.s_addr = htonl(d->id.dst_ip);
2104 		printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
2105 	} else if (d->id.addr_type == 6) {
2106 		printf(" %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2107 		    sizeof(buf)), d->id.src_port);
2108 		printf(" <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6, buf,
2109 		    sizeof(buf)), d->id.dst_port);
2110 	} else
2111 		printf(" UNKNOWN <-> UNKNOWN\n");
2112 
2113 	printf("\n");
2114 }
2115 
2116 static int
2117 sort_q(const void *pa, const void *pb)
2118 {
2119 	int rev = (do_sort < 0);
2120 	int field = rev ? -do_sort : do_sort;
2121 	long long res = 0;
2122 	const struct dn_flow_queue *a = pa;
2123 	const struct dn_flow_queue *b = pb;
2124 
2125 	switch (field) {
2126 	case 1: /* pkts */
2127 		res = a->len - b->len;
2128 		break;
2129 	case 2: /* bytes */
2130 		res = a->len_bytes - b->len_bytes;
2131 		break;
2132 
2133 	case 3: /* tot pkts */
2134 		res = a->tot_pkts - b->tot_pkts;
2135 		break;
2136 
2137 	case 4: /* tot bytes */
2138 		res = a->tot_bytes - b->tot_bytes;
2139 		break;
2140 	}
2141 	if (res < 0)
2142 		res = -1;
2143 	if (res > 0)
2144 		res = 1;
2145 	return (int)(rev ? res : -res);
2146 }
2147 
2148 static void
2149 list_queues(struct dn_flow_set *fs, struct dn_flow_queue *q)
2150 {
2151 	int l;
2152 	int index_printed, indexes = 0;
2153 	char buff[255];
2154 	struct protoent *pe;
2155 
2156 	if (fs->rq_elements == 0)
2157 		return;
2158 
2159 	if (do_sort != 0)
2160 		heapsort(q, fs->rq_elements, sizeof *q, sort_q);
2161 
2162 	/* Print IPv4 flows */
2163 	index_printed = 0;
2164 	for (l = 0; l < fs->rq_elements; l++) {
2165 		struct in_addr ina;
2166 
2167 		/* XXX: Should check for IPv4 flows */
2168 		if (IS_IP6_FLOW_ID(&(q[l].id)))
2169 			continue;
2170 
2171 		if (!index_printed) {
2172 			index_printed = 1;
2173 			if (indexes > 0)	/* currently a no-op */
2174 				printf("\n");
2175 			indexes++;
2176 			printf("    "
2177 			    "mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
2178 			    fs->flow_mask.proto,
2179 			    fs->flow_mask.src_ip, fs->flow_mask.src_port,
2180 			    fs->flow_mask.dst_ip, fs->flow_mask.dst_port);
2181 
2182 			printf("BKT Prot ___Source IP/port____ "
2183 			    "____Dest. IP/port____ "
2184 			    "Tot_pkt/bytes Pkt/Byte Drp\n");
2185 		}
2186 
2187 		printf("%3d ", q[l].hash_slot);
2188 		pe = getprotobynumber(q[l].id.proto);
2189 		if (pe)
2190 			printf("%-4s ", pe->p_name);
2191 		else
2192 			printf("%4u ", q[l].id.proto);
2193 		ina.s_addr = htonl(q[l].id.src_ip);
2194 		printf("%15s/%-5d ",
2195 		    inet_ntoa(ina), q[l].id.src_port);
2196 		ina.s_addr = htonl(q[l].id.dst_ip);
2197 		printf("%15s/%-5d ",
2198 		    inet_ntoa(ina), q[l].id.dst_port);
2199 		printf("%4qu %8qu %2u %4u %3u\n",
2200 		    q[l].tot_pkts, q[l].tot_bytes,
2201 		    q[l].len, q[l].len_bytes, q[l].drops);
2202 		if (verbose)
2203 			printf("   S %20qd  F %20qd\n",
2204 			    q[l].S, q[l].F);
2205 	}
2206 
2207 	/* Print IPv6 flows */
2208 	index_printed = 0;
2209 	for (l = 0; l < fs->rq_elements; l++) {
2210 		if (!IS_IP6_FLOW_ID(&(q[l].id)))
2211 			continue;
2212 
2213 		if (!index_printed) {
2214 			index_printed = 1;
2215 			if (indexes > 0)
2216 				printf("\n");
2217 			indexes++;
2218 			printf("\n        mask: proto: 0x%02x, flow_id: 0x%08x,  ",
2219 			    fs->flow_mask.proto, fs->flow_mask.flow_id6);
2220 			inet_ntop(AF_INET6, &(fs->flow_mask.src_ip6),
2221 			    buff, sizeof(buff));
2222 			printf("%s/0x%04x -> ", buff, fs->flow_mask.src_port);
2223 			inet_ntop( AF_INET6, &(fs->flow_mask.dst_ip6),
2224 			    buff, sizeof(buff) );
2225 			printf("%s/0x%04x\n", buff, fs->flow_mask.dst_port);
2226 
2227 			printf("BKT ___Prot___ _flow-id_ "
2228 			    "______________Source IPv6/port_______________ "
2229 			    "_______________Dest. IPv6/port_______________ "
2230 			    "Tot_pkt/bytes Pkt/Byte Drp\n");
2231 		}
2232 		printf("%3d ", q[l].hash_slot);
2233 		pe = getprotobynumber(q[l].id.proto);
2234 		if (pe != NULL)
2235 			printf("%9s ", pe->p_name);
2236 		else
2237 			printf("%9u ", q[l].id.proto);
2238 		printf("%7d  %39s/%-5d ", q[l].id.flow_id6,
2239 		    inet_ntop(AF_INET6, &(q[l].id.src_ip6), buff, sizeof(buff)),
2240 		    q[l].id.src_port);
2241 		printf(" %39s/%-5d ",
2242 		    inet_ntop(AF_INET6, &(q[l].id.dst_ip6), buff, sizeof(buff)),
2243 		    q[l].id.dst_port);
2244 		printf(" %4qu %8qu %2u %4u %3u\n",
2245 		    q[l].tot_pkts, q[l].tot_bytes,
2246 		    q[l].len, q[l].len_bytes, q[l].drops);
2247 		if (verbose)
2248 			printf("   S %20qd  F %20qd\n", q[l].S, q[l].F);
2249 	}
2250 }
2251 
2252 static void
2253 print_flowset_parms(struct dn_flow_set *fs, char *prefix)
2254 {
2255 	int l;
2256 	char qs[30];
2257 	char plr[30];
2258 	char red[90];	/* Display RED parameters */
2259 
2260 	l = fs->qsize;
2261 	if (fs->flags_fs & DN_QSIZE_IS_BYTES) {
2262 		if (l >= 8192)
2263 			sprintf(qs, "%d KB", l / 1024);
2264 		else
2265 			sprintf(qs, "%d B", l);
2266 	} else
2267 		sprintf(qs, "%3d sl.", l);
2268 	if (fs->plr)
2269 		sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
2270 	else
2271 		plr[0] = '\0';
2272 	if (fs->flags_fs & DN_IS_RED)	/* RED parameters */
2273 		sprintf(red,
2274 		    "\n\t  %cRED w_q %f min_th %d max_th %d max_p %f",
2275 		    (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ',
2276 		    1.0 * fs->w_q / (double)(1 << SCALE_RED),
2277 		    SCALE_VAL(fs->min_th),
2278 		    SCALE_VAL(fs->max_th),
2279 		    1.0 * fs->max_p / (double)(1 << SCALE_RED));
2280 	else
2281 		sprintf(red, "droptail");
2282 
2283 	printf("%s %s%s %d queues (%d buckets) %s\n",
2284 	    prefix, qs, plr, fs->rq_elements, fs->rq_size, red);
2285 }
2286 
2287 static void
2288 list_pipes(void *data, uint nbytes, int ac, char *av[])
2289 {
2290 	int rulenum;
2291 	void *next = data;
2292 	struct dn_pipe *p = (struct dn_pipe *) data;
2293 	struct dn_flow_set *fs;
2294 	struct dn_flow_queue *q;
2295 	int l;
2296 
2297 	if (ac > 0)
2298 		rulenum = strtoul(*av++, NULL, 10);
2299 	else
2300 		rulenum = 0;
2301 	for (; nbytes >= sizeof *p; p = (struct dn_pipe *)next) {
2302 		double b = p->bandwidth;
2303 		char buf[30];
2304 		char prefix[80];
2305 
2306 		if (SLIST_NEXT(p, next) != (struct dn_pipe *)DN_IS_PIPE)
2307 			break;	/* done with pipes, now queues */
2308 
2309 		/*
2310 		 * compute length, as pipe have variable size
2311 		 */
2312 		l = sizeof(*p) + p->fs.rq_elements * sizeof(*q);
2313 		next = (char *)p + l;
2314 		nbytes -= l;
2315 
2316 		if ((rulenum != 0 && rulenum != p->pipe_nr) || do_pipe == 2)
2317 			continue;
2318 
2319 		/*
2320 		 * Print rate (or clocking interface)
2321 		 */
2322 		if (p->if_name[0] != '\0')
2323 			sprintf(buf, "%s", p->if_name);
2324 		else if (b == 0)
2325 			sprintf(buf, "unlimited");
2326 		else if (b >= 1000000)
2327 			sprintf(buf, "%7.3f Mbit/s", b/1000000);
2328 		else if (b >= 1000)
2329 			sprintf(buf, "%7.3f Kbit/s", b/1000);
2330 		else
2331 			sprintf(buf, "%7.3f bit/s ", b);
2332 
2333 		sprintf(prefix, "%05d: %s %4d ms ",
2334 		    p->pipe_nr, buf, p->delay);
2335 		print_flowset_parms(&(p->fs), prefix);
2336 		if (verbose)
2337 			printf("   V %20qd\n", p->V >> MY_M);
2338 
2339 		q = (struct dn_flow_queue *)(p+1);
2340 		list_queues(&(p->fs), q);
2341 	}
2342 	for (fs = next; nbytes >= sizeof *fs; fs = next) {
2343 		char prefix[80];
2344 
2345 		if (SLIST_NEXT(fs, next) != (struct dn_flow_set *)DN_IS_QUEUE)
2346 			break;
2347 		l = sizeof(*fs) + fs->rq_elements * sizeof(*q);
2348 		next = (char *)fs + l;
2349 		nbytes -= l;
2350 
2351 		if (rulenum != 0 && ((rulenum != fs->fs_nr && do_pipe == 2) ||
2352 		    (rulenum != fs->parent_nr && do_pipe == 1))) {
2353 			continue;
2354 		}
2355 
2356 		q = (struct dn_flow_queue *)(fs+1);
2357 		sprintf(prefix, "q%05d: weight %d pipe %d ",
2358 		    fs->fs_nr, fs->weight, fs->parent_nr);
2359 		print_flowset_parms(fs, prefix);
2360 		list_queues(fs, q);
2361 	}
2362 }
2363 
2364 /*
2365  * This one handles all set-related commands
2366  * 	ipfw set { show | enable | disable }
2367  * 	ipfw set swap X Y
2368  * 	ipfw set move X to Y
2369  * 	ipfw set move rule X to Y
2370  */
2371 static void
2372 sets_handler(int ac, char *av[])
2373 {
2374 	uint32_t set_disable, masks[2];
2375 	int i, nbytes;
2376 	uint16_t rulenum;
2377 	uint8_t cmd, new_set;
2378 
2379 	ac--;
2380 	av++;
2381 
2382 	if (!ac)
2383 		errx(EX_USAGE, "set needs command");
2384 	if (_substrcmp(*av, "show") == 0) {
2385 		void *data;
2386 		char const *msg;
2387 
2388 		nbytes = sizeof(struct ip_fw);
2389 		if ((data = calloc(1, nbytes)) == NULL)
2390 			err(EX_OSERR, "calloc");
2391 		if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0)
2392 			err(EX_OSERR, "getsockopt(IP_FW_GET)");
2393 		bcopy(&((struct ip_fw *)data)->next_rule,
2394 			&set_disable, sizeof(set_disable));
2395 
2396 		for (i = 0, msg = "disable" ; i < RESVD_SET; i++)
2397 			if ((set_disable & (1<<i))) {
2398 				printf("%s %d", msg, i);
2399 				msg = "";
2400 			}
2401 		msg = (set_disable) ? " enable" : "enable";
2402 		for (i = 0; i < RESVD_SET; i++)
2403 			if (!(set_disable & (1<<i))) {
2404 				printf("%s %d", msg, i);
2405 				msg = "";
2406 			}
2407 		printf("\n");
2408 	} else if (_substrcmp(*av, "swap") == 0) {
2409 		ac--; av++;
2410 		if (ac != 2)
2411 			errx(EX_USAGE, "set swap needs 2 set numbers\n");
2412 		rulenum = atoi(av[0]);
2413 		new_set = atoi(av[1]);
2414 		if (!isdigit(*(av[0])) || rulenum > RESVD_SET)
2415 			errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2416 		if (!isdigit(*(av[1])) || new_set > RESVD_SET)
2417 			errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2418 		masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
2419 		i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
2420 	} else if (_substrcmp(*av, "move") == 0) {
2421 		ac--; av++;
2422 		if (ac && _substrcmp(*av, "rule") == 0) {
2423 			cmd = 2;
2424 			ac--; av++;
2425 		} else
2426 			cmd = 3;
2427 		if (ac != 3 || _substrcmp(av[1], "to") != 0)
2428 			errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2429 		rulenum = atoi(av[0]);
2430 		new_set = atoi(av[2]);
2431 		if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) ||
2432 			(cmd == 2 && rulenum == 65535) )
2433 			errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2434 		if (!isdigit(*(av[2])) || new_set > RESVD_SET)
2435 			errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2436 		masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
2437 		i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
2438 	} else if (_substrcmp(*av, "disable") == 0 ||
2439 		   _substrcmp(*av, "enable") == 0 ) {
2440 		int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2441 
2442 		ac--; av++;
2443 		masks[0] = masks[1] = 0;
2444 
2445 		while (ac) {
2446 			if (isdigit(**av)) {
2447 				i = atoi(*av);
2448 				if (i < 0 || i > RESVD_SET)
2449 					errx(EX_DATAERR,
2450 					    "invalid set number %d\n", i);
2451 				masks[which] |= (1<<i);
2452 			} else if (_substrcmp(*av, "disable") == 0)
2453 				which = 0;
2454 			else if (_substrcmp(*av, "enable") == 0)
2455 				which = 1;
2456 			else
2457 				errx(EX_DATAERR,
2458 					"invalid set command %s\n", *av);
2459 			av++; ac--;
2460 		}
2461 		if ( (masks[0] & masks[1]) != 0 )
2462 			errx(EX_DATAERR,
2463 			    "cannot enable and disable the same set\n");
2464 
2465 		i = do_cmd(IP_FW_DEL, masks, sizeof(masks));
2466 		if (i)
2467 			warn("set enable/disable: setsockopt(IP_FW_DEL)");
2468 	} else
2469 		errx(EX_USAGE, "invalid set command %s\n", *av);
2470 }
2471 
2472 static void
2473 sysctl_handler(int ac, char *av[], int which)
2474 {
2475 	ac--;
2476 	av++;
2477 
2478 	if (ac == 0) {
2479 		warnx("missing keyword to enable/disable\n");
2480 	} else if (_substrcmp(*av, "firewall") == 0) {
2481 		sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2482 		    &which, sizeof(which));
2483 	} else if (_substrcmp(*av, "one_pass") == 0) {
2484 		sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2485 		    &which, sizeof(which));
2486 	} else if (_substrcmp(*av, "debug") == 0) {
2487 		sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2488 		    &which, sizeof(which));
2489 	} else if (_substrcmp(*av, "verbose") == 0) {
2490 		sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2491 		    &which, sizeof(which));
2492 	} else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2493 		sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2494 		    &which, sizeof(which));
2495 	} else if (_substrcmp(*av, "altq") == 0) {
2496 		altq_set_enabled(which);
2497 	} else {
2498 		warnx("unrecognize enable/disable keyword: %s\n", *av);
2499 	}
2500 }
2501 
2502 static void
2503 list(int ac, char *av[], int show_counters)
2504 {
2505 	struct ip_fw *r;
2506 	ipfw_dyn_rule *dynrules, *d;
2507 
2508 #define NEXT(r)	((struct ip_fw *)((char *)r + RULESIZE(r)))
2509 	char *lim;
2510 	void *data = NULL;
2511 	int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
2512 	int exitval = EX_OK;
2513 	int lac;
2514 	char **lav;
2515 	u_long rnum, last;
2516 	char *endptr;
2517 	int seen = 0;
2518 	uint8_t set;
2519 
2520 	const int ocmd = do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
2521 	int nalloc = 1024;	/* start somewhere... */
2522 
2523 	last = 0;
2524 
2525 	if (test_only) {
2526 		fprintf(stderr, "Testing only, list disabled\n");
2527 		return;
2528 	}
2529 
2530 	ac--;
2531 	av++;
2532 
2533 	/* get rules or pipes from kernel, resizing array as necessary */
2534 	nbytes = nalloc;
2535 
2536 	while (nbytes >= nalloc) {
2537 		nalloc = nalloc * 2 + 200;
2538 		nbytes = nalloc;
2539 		if ((data = realloc(data, nbytes)) == NULL)
2540 			err(EX_OSERR, "realloc");
2541 		if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0)
2542 			err(EX_OSERR, "getsockopt(IP_%s_GET)",
2543 				do_pipe ? "DUMMYNET" : "FW");
2544 	}
2545 
2546 	if (do_pipe) {
2547 		list_pipes(data, nbytes, ac, av);
2548 		goto done;
2549 	}
2550 
2551 	/*
2552 	 * Count static rules. They have variable size so we
2553 	 * need to scan the list to count them.
2554 	 */
2555 	for (nstat = 1, r = data, lim = (char *)data + nbytes;
2556 		    r->rulenum < 65535 && (char *)r < lim;
2557 		    ++nstat, r = NEXT(r) )
2558 		; /* nothing */
2559 
2560 	/*
2561 	 * Count dynamic rules. This is easier as they have
2562 	 * fixed size.
2563 	 */
2564 	r = NEXT(r);
2565 	dynrules = (ipfw_dyn_rule *)r ;
2566 	n = (char *)r - (char *)data;
2567 	ndyn = (nbytes - n) / sizeof *dynrules;
2568 
2569 	/* if showing stats, figure out column widths ahead of time */
2570 	bcwidth = pcwidth = 0;
2571 	if (show_counters) {
2572 		for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2573 			/* skip rules from another set */
2574 			if (use_set && r->set != use_set - 1)
2575 				continue;
2576 
2577 			/* packet counter */
2578 			width = snprintf(NULL, 0, "%llu",
2579 			    align_uint64(&r->pcnt));
2580 			if (width > pcwidth)
2581 				pcwidth = width;
2582 
2583 			/* byte counter */
2584 			width = snprintf(NULL, 0, "%llu",
2585 			    align_uint64(&r->bcnt));
2586 			if (width > bcwidth)
2587 				bcwidth = width;
2588 		}
2589 	}
2590 	if (do_dynamic && ndyn) {
2591 		for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2592 			if (use_set) {
2593 				/* skip rules from another set */
2594 				bcopy((char *)&d->rule + sizeof(uint16_t),
2595 				      &set, sizeof(uint8_t));
2596 				if (set != use_set - 1)
2597 					continue;
2598 			}
2599 			width = snprintf(NULL, 0, "%llu",
2600 			    align_uint64(&d->pcnt));
2601 			if (width > pcwidth)
2602 				pcwidth = width;
2603 
2604 			width = snprintf(NULL, 0, "%llu",
2605 			    align_uint64(&d->bcnt));
2606 			if (width > bcwidth)
2607 				bcwidth = width;
2608 		}
2609 	}
2610 	/* if no rule numbers were specified, list all rules */
2611 	if (ac == 0) {
2612 		for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2613 			if (use_set && r->set != use_set - 1)
2614 				continue;
2615 			show_ipfw(r, pcwidth, bcwidth);
2616 		}
2617 
2618 		if (do_dynamic && ndyn) {
2619 			printf("## Dynamic rules (%d):\n", ndyn);
2620 			for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2621 				if (use_set) {
2622 					bcopy((char *)&d->rule + sizeof(uint16_t),
2623 					      &set, sizeof(uint8_t));
2624 					if (set != use_set - 1)
2625 						continue;
2626 				}
2627 				show_dyn_ipfw(d, pcwidth, bcwidth);
2628 		}
2629 		}
2630 		goto done;
2631 	}
2632 
2633 	/* display specific rules requested on command line */
2634 
2635 	for (lac = ac, lav = av; lac != 0; lac--) {
2636 		/* convert command line rule # */
2637 		last = rnum = strtoul(*lav++, &endptr, 10);
2638 		if (*endptr == '-')
2639 			last = strtoul(endptr+1, &endptr, 10);
2640 		if (*endptr) {
2641 			exitval = EX_USAGE;
2642 			warnx("invalid rule number: %s", *(lav - 1));
2643 			continue;
2644 		}
2645 		for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) {
2646 			if (r->rulenum > last)
2647 				break;
2648 			if (use_set && r->set != use_set - 1)
2649 				continue;
2650 			if (r->rulenum >= rnum && r->rulenum <= last) {
2651 				show_ipfw(r, pcwidth, bcwidth);
2652 				seen = 1;
2653 			}
2654 		}
2655 		if (!seen) {
2656 			/* give precedence to other error(s) */
2657 			if (exitval == EX_OK)
2658 				exitval = EX_UNAVAILABLE;
2659 			warnx("rule %lu does not exist", rnum);
2660 		}
2661 	}
2662 
2663 	if (do_dynamic && ndyn) {
2664 		printf("## Dynamic rules:\n");
2665 		for (lac = ac, lav = av; lac != 0; lac--) {
2666 			last = rnum = strtoul(*lav++, &endptr, 10);
2667 			if (*endptr == '-')
2668 				last = strtoul(endptr+1, &endptr, 10);
2669 			if (*endptr)
2670 				/* already warned */
2671 				continue;
2672 			for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2673 				uint16_t rulenum;
2674 
2675 				bcopy(&d->rule, &rulenum, sizeof(rulenum));
2676 				if (rulenum > rnum)
2677 					break;
2678 				if (use_set) {
2679 					bcopy((char *)&d->rule + sizeof(uint16_t),
2680 					      &set, sizeof(uint8_t));
2681 					if (set != use_set - 1)
2682 						continue;
2683 				}
2684 				if (r->rulenum >= rnum && r->rulenum <= last)
2685 					show_dyn_ipfw(d, pcwidth, bcwidth);
2686 			}
2687 		}
2688 	}
2689 
2690 	ac = 0;
2691 
2692 done:
2693 	free(data);
2694 
2695 	if (exitval != EX_OK)
2696 		exit(exitval);
2697 #undef NEXT
2698 }
2699 
2700 static void
2701 show_usage(void)
2702 {
2703 	fprintf(stderr, "usage: ipfw [options]\n"
2704 "do \"ipfw -h\" or see ipfw manpage for details\n"
2705 );
2706 	exit(EX_USAGE);
2707 }
2708 
2709 static void
2710 help(void)
2711 {
2712 	fprintf(stderr,
2713 "ipfw syntax summary (but please do read the ipfw(8) manpage):\n"
2714 "ipfw [-abcdefhnNqStTv] <command> where <command> is one of:\n"
2715 "add [num] [set N] [prob x] RULE-BODY\n"
2716 "{pipe|queue} N config PIPE-BODY\n"
2717 "[pipe|queue] {zero|delete|show} [N{,N}]\n"
2718 "nat N config {ip IPADDR|if IFNAME|log|deny_in|same_ports|unreg_only|reset|\n"
2719 "		reverse|proxy_only|redirect_addr linkspec|\n"
2720 "		redirect_port linkspec|redirect_proto linkspec}\n"
2721 "set [disable N... enable N...] | move [rule] X to Y | swap X Y | show\n"
2722 "set N {show|list|zero|resetlog|delete} [N{,N}] | flush\n"
2723 "table N {add ip[/bits] [value] | delete ip[/bits] | flush | list}\n"
2724 "\n"
2725 "RULE-BODY:	check-state [PARAMS] | ACTION [PARAMS] ADDR [OPTION_LIST]\n"
2726 "ACTION:	check-state | allow | count | deny | unreach{,6} CODE |\n"
2727 "               skipto N | {divert|tee} PORT | forward ADDR |\n"
2728 "               pipe N | queue N | nat N | setfib FIB\n"
2729 "PARAMS: 	[log [logamount LOGLIMIT]] [altq QUEUE_NAME]\n"
2730 "ADDR:		[ MAC dst src ether_type ] \n"
2731 "		[ ip from IPADDR [ PORT ] to IPADDR [ PORTLIST ] ]\n"
2732 "		[ ipv6|ip6 from IP6ADDR [ PORT ] to IP6ADDR [ PORTLIST ] ]\n"
2733 "IPADDR:	[not] { any | me | ip/bits{x,y,z} | table(t[,v]) | IPLIST }\n"
2734 "IP6ADDR:	[not] { any | me | me6 | ip6/bits | IP6LIST }\n"
2735 "IP6LIST:	{ ip6 | ip6/bits }[,IP6LIST]\n"
2736 "IPLIST:	{ ip | ip/bits | ip:mask }[,IPLIST]\n"
2737 "OPTION_LIST:	OPTION [OPTION_LIST]\n"
2738 "OPTION:	bridged | diverted | diverted-loopback | diverted-output |\n"
2739 "	{dst-ip|src-ip} IPADDR | {dst-ip6|src-ip6|dst-ipv6|src-ipv6} IP6ADDR |\n"
2740 "	{dst-port|src-port} LIST |\n"
2741 "	estab | frag | {gid|uid} N | icmptypes LIST | in | out | ipid LIST |\n"
2742 "	iplen LIST | ipoptions SPEC | ipprecedence | ipsec | iptos SPEC |\n"
2743 "	ipttl LIST | ipversion VER | keep-state | layer2 | limit ... |\n"
2744 "	icmp6types LIST | ext6hdr LIST | flow-id N[,N] | fib FIB |\n"
2745 "	mac ... | mac-type LIST | proto LIST | {recv|xmit|via} {IF|IPADDR} |\n"
2746 "	setup | {tcpack|tcpseq|tcpwin} NN | tcpflags SPEC | tcpoptions SPEC |\n"
2747 "	tcpdatalen LIST | verrevpath | versrcreach | antispoof\n"
2748 );
2749 exit(0);
2750 }
2751 
2752 
2753 static int
2754 lookup_host (char *host, struct in_addr *ipaddr)
2755 {
2756 	struct hostent *he;
2757 
2758 	if (!inet_aton(host, ipaddr)) {
2759 		if ((he = gethostbyname(host)) == NULL)
2760 			return(-1);
2761 		*ipaddr = *(struct in_addr *)he->h_addr_list[0];
2762 	}
2763 	return(0);
2764 }
2765 
2766 /*
2767  * fills the addr and mask fields in the instruction as appropriate from av.
2768  * Update length as appropriate.
2769  * The following formats are allowed:
2770  *	me	returns O_IP_*_ME
2771  *	1.2.3.4		single IP address
2772  *	1.2.3.4:5.6.7.8	address:mask
2773  *	1.2.3.4/24	address/mask
2774  *	1.2.3.4/26{1,6,5,4,23}	set of addresses in a subnet
2775  * We can have multiple comma-separated address/mask entries.
2776  */
2777 static void
2778 fill_ip(ipfw_insn_ip *cmd, char *av)
2779 {
2780 	int len = 0;
2781 	uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2782 
2783 	cmd->o.len &= ~F_LEN_MASK;	/* zero len */
2784 
2785 	if (_substrcmp(av, "any") == 0)
2786 		return;
2787 
2788 	if (_substrcmp(av, "me") == 0) {
2789 		cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2790 		return;
2791 	}
2792 
2793 	if (strncmp(av, "table(", 6) == 0) {
2794 		char *p = strchr(av + 6, ',');
2795 
2796 		if (p)
2797 			*p++ = '\0';
2798 		cmd->o.opcode = O_IP_DST_LOOKUP;
2799 		cmd->o.arg1 = strtoul(av + 6, NULL, 0);
2800 		if (p) {
2801 			cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2802 			d[0] = strtoul(p, NULL, 0);
2803 		} else
2804 			cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2805 		return;
2806 	}
2807 
2808     while (av) {
2809 	/*
2810 	 * After the address we can have '/' or ':' indicating a mask,
2811 	 * ',' indicating another address follows, '{' indicating a
2812 	 * set of addresses of unspecified size.
2813 	 */
2814 	char *t = NULL, *p = strpbrk(av, "/:,{");
2815 	int masklen;
2816 	char md, nd;
2817 
2818 	if (p) {
2819 		md = *p;
2820 		*p++ = '\0';
2821 		if ((t = strpbrk(p, ",{")) != NULL) {
2822 			nd = *t;
2823 			*t = '\0';
2824 		}
2825 	} else
2826 		md = '\0';
2827 
2828 	if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2829 		errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2830 	switch (md) {
2831 	case ':':
2832 		if (!inet_aton(p, (struct in_addr *)&d[1]))
2833 			errx(EX_DATAERR, "bad netmask ``%s''", p);
2834 		break;
2835 	case '/':
2836 		masklen = atoi(p);
2837 		if (masklen == 0)
2838 			d[1] = htonl(0);	/* mask */
2839 		else if (masklen > 32)
2840 			errx(EX_DATAERR, "bad width ``%s''", p);
2841 		else
2842 			d[1] = htonl(~0 << (32 - masklen));
2843 		break;
2844 	case '{':	/* no mask, assume /24 and put back the '{' */
2845 		d[1] = htonl(~0 << (32 - 24));
2846 		*(--p) = md;
2847 		break;
2848 
2849 	case ',':	/* single address plus continuation */
2850 		*(--p) = md;
2851 		/* FALLTHROUGH */
2852 	case 0:		/* initialization value */
2853 	default:
2854 		d[1] = htonl(~0);	/* force /32 */
2855 		break;
2856 	}
2857 	d[0] &= d[1];		/* mask base address with mask */
2858 	if (t)
2859 		*t = nd;
2860 	/* find next separator */
2861 	if (p)
2862 		p = strpbrk(p, ",{");
2863 	if (p && *p == '{') {
2864 		/*
2865 		 * We have a set of addresses. They are stored as follows:
2866 		 *   arg1	is the set size (powers of 2, 2..256)
2867 		 *   addr	is the base address IN HOST FORMAT
2868 		 *   mask..	is an array of arg1 bits (rounded up to
2869 		 *		the next multiple of 32) with bits set
2870 		 *		for each host in the map.
2871 		 */
2872 		uint32_t *map = (uint32_t *)&cmd->mask;
2873 		int low, high;
2874 		int i = contigmask((uint8_t *)&(d[1]), 32);
2875 
2876 		if (len > 0)
2877 			errx(EX_DATAERR, "address set cannot be in a list");
2878 		if (i < 24 || i > 31)
2879 			errx(EX_DATAERR, "invalid set with mask %d\n", i);
2880 		cmd->o.arg1 = 1<<(32-i);	/* map length		*/
2881 		d[0] = ntohl(d[0]);		/* base addr in host format */
2882 		cmd->o.opcode = O_IP_DST_SET;	/* default */
2883 		cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2884 		for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2885 			map[i] = 0;	/* clear map */
2886 
2887 		av = p + 1;
2888 		low = d[0] & 0xff;
2889 		high = low + cmd->o.arg1 - 1;
2890 		/*
2891 		 * Here, i stores the previous value when we specify a range
2892 		 * of addresses within a mask, e.g. 45-63. i = -1 means we
2893 		 * have no previous value.
2894 		 */
2895 		i = -1;	/* previous value in a range */
2896 		while (isdigit(*av)) {
2897 			char *s;
2898 			int a = strtol(av, &s, 0);
2899 
2900 			if (s == av) { /* no parameter */
2901 			    if (*av != '}')
2902 				errx(EX_DATAERR, "set not closed\n");
2903 			    if (i != -1)
2904 				errx(EX_DATAERR, "incomplete range %d-", i);
2905 			    break;
2906 			}
2907 			if (a < low || a > high)
2908 			    errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2909 				a, low, high);
2910 			a -= low;
2911 			if (i == -1)	/* no previous in range */
2912 			    i = a;
2913 			else {		/* check that range is valid */
2914 			    if (i > a)
2915 				errx(EX_DATAERR, "invalid range %d-%d",
2916 					i+low, a+low);
2917 			    if (*s == '-')
2918 				errx(EX_DATAERR, "double '-' in range");
2919 			}
2920 			for (; i <= a; i++)
2921 			    map[i/32] |= 1<<(i & 31);
2922 			i = -1;
2923 			if (*s == '-')
2924 			    i = a;
2925 			else if (*s == '}')
2926 			    break;
2927 			av = s+1;
2928 		}
2929 		return;
2930 	}
2931 	av = p;
2932 	if (av)			/* then *av must be a ',' */
2933 		av++;
2934 
2935 	/* Check this entry */
2936 	if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2937 		/*
2938 		 * 'any' turns the entire list into a NOP.
2939 		 * 'not any' never matches, so it is removed from the
2940 		 * list unless it is the only item, in which case we
2941 		 * report an error.
2942 		 */
2943 		if (cmd->o.len & F_NOT) {	/* "not any" never matches */
2944 			if (av == NULL && len == 0) /* only this entry */
2945 				errx(EX_DATAERR, "not any never matches");
2946 		}
2947 		/* else do nothing and skip this entry */
2948 		return;
2949 	}
2950 	/* A single IP can be stored in an optimized format */
2951 	if (d[1] == IP_MASK_ALL && av == NULL && len == 0) {
2952 		cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2953 		return;
2954 	}
2955 	len += 2;	/* two words... */
2956 	d += 2;
2957     } /* end while */
2958     if (len + 1 > F_LEN_MASK)
2959 	errx(EX_DATAERR, "address list too long");
2960     cmd->o.len |= len+1;
2961 }
2962 
2963 
2964 /* Try to find ipv6 address by hostname */
2965 static int
2966 lookup_host6 (char *host, struct in6_addr *ip6addr)
2967 {
2968 	struct hostent *he;
2969 
2970 	if (!inet_pton(AF_INET6, host, ip6addr)) {
2971 		if ((he = gethostbyname2(host, AF_INET6)) == NULL)
2972 			return(-1);
2973 		memcpy(ip6addr, he->h_addr_list[0], sizeof( struct in6_addr));
2974 	}
2975 	return(0);
2976 }
2977 
2978 
2979 /* n2mask sets n bits of the mask */
2980 static void
2981 n2mask(struct in6_addr *mask, int n)
2982 {
2983 	static int	minimask[9] =
2984 	    { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
2985 	u_char		*p;
2986 
2987 	memset(mask, 0, sizeof(struct in6_addr));
2988 	p = (u_char *) mask;
2989 	for (; n > 0; p++, n -= 8) {
2990 		if (n >= 8)
2991 			*p = 0xff;
2992 		else
2993 			*p = minimask[n];
2994 	}
2995 	return;
2996 }
2997 
2998 
2999 /*
3000  * fill the addr and mask fields in the instruction as appropriate from av.
3001  * Update length as appropriate.
3002  * The following formats are allowed:
3003  *     any     matches any IP6. Actually returns an empty instruction.
3004  *     me      returns O_IP6_*_ME
3005  *
3006  *     03f1::234:123:0342                single IP6 addres
3007  *     03f1::234:123:0342/24            address/mask
3008  *     03f1::234:123:0342/24,03f1::234:123:0343/               List of address
3009  *
3010  * Set of address (as in ipv6) not supported because ipv6 address
3011  * are typically random past the initial prefix.
3012  * Return 1 on success, 0 on failure.
3013  */
3014 static int
3015 fill_ip6(ipfw_insn_ip6 *cmd, char *av)
3016 {
3017 	int len = 0;
3018 	struct in6_addr *d = &(cmd->addr6);
3019 	/*
3020 	 * Needed for multiple address.
3021 	 * Note d[1] points to struct in6_add r mask6 of cmd
3022 	 */
3023 
3024        cmd->o.len &= ~F_LEN_MASK;	/* zero len */
3025 
3026        if (strcmp(av, "any") == 0)
3027 	       return (1);
3028 
3029 
3030        if (strcmp(av, "me") == 0) {	/* Set the data for "me" opt*/
3031 	       cmd->o.len |= F_INSN_SIZE(ipfw_insn);
3032 	       return (1);
3033        }
3034 
3035        if (strcmp(av, "me6") == 0) {	/* Set the data for "me" opt*/
3036 	       cmd->o.len |= F_INSN_SIZE(ipfw_insn);
3037 	       return (1);
3038        }
3039 
3040        av = strdup(av);
3041        while (av) {
3042 		/*
3043 		 * After the address we can have '/' indicating a mask,
3044 		 * or ',' indicating another address follows.
3045 		 */
3046 
3047 		char *p;
3048 		int masklen;
3049 		char md = '\0';
3050 
3051 		if ((p = strpbrk(av, "/,")) ) {
3052 			md = *p;	/* save the separator */
3053 			*p = '\0';	/* terminate address string */
3054 			p++;		/* and skip past it */
3055 		}
3056 		/* now p points to NULL, mask or next entry */
3057 
3058 		/* lookup stores address in *d as a side effect */
3059 		if (lookup_host6(av, d) != 0) {
3060 			/* XXX: failed. Free memory and go */
3061 			errx(EX_DATAERR, "bad address \"%s\"", av);
3062 		}
3063 		/* next, look at the mask, if any */
3064 		masklen = (md == '/') ? atoi(p) : 128;
3065 		if (masklen > 128 || masklen < 0)
3066 			errx(EX_DATAERR, "bad width \"%s\''", p);
3067 		else
3068 			n2mask(&d[1], masklen);
3069 
3070 		APPLY_MASK(d, &d[1])   /* mask base address with mask */
3071 
3072 		/* find next separator */
3073 
3074 		if (md == '/') {	/* find separator past the mask */
3075 			p = strpbrk(p, ",");
3076 			if (p != NULL)
3077 				p++;
3078 		}
3079 		av = p;
3080 
3081 		/* Check this entry */
3082 		if (masklen == 0) {
3083 			/*
3084 			 * 'any' turns the entire list into a NOP.
3085 			 * 'not any' never matches, so it is removed from the
3086 			 * list unless it is the only item, in which case we
3087 			 * report an error.
3088 			 */
3089 			if (cmd->o.len & F_NOT && av == NULL && len == 0)
3090 				errx(EX_DATAERR, "not any never matches");
3091 			continue;
3092 		}
3093 
3094 		/*
3095 		 * A single IP can be stored alone
3096 		 */
3097 		if (masklen == 128 && av == NULL && len == 0) {
3098 			len = F_INSN_SIZE(struct in6_addr);
3099 			break;
3100 		}
3101 
3102 		/* Update length and pointer to arguments */
3103 		len += F_INSN_SIZE(struct in6_addr)*2;
3104 		d += 2;
3105 	} /* end while */
3106 
3107 	/*
3108 	 * Total length of the command, remember that 1 is the size of
3109 	 * the base command.
3110 	 */
3111 	if (len + 1 > F_LEN_MASK)
3112 		errx(EX_DATAERR, "address list too long");
3113 	cmd->o.len |= len+1;
3114 	free(av);
3115 	return (1);
3116 }
3117 
3118 /*
3119  * fills command for ipv6 flow-id filtering
3120  * note that the 20 bit flow number is stored in a array of u_int32_t
3121  * it's supported lists of flow-id, so in the o.arg1 we store how many
3122  * additional flow-id we want to filter, the basic is 1
3123  */
3124 void
3125 fill_flow6( ipfw_insn_u32 *cmd, char *av )
3126 {
3127 	u_int32_t type;	 /* Current flow number */
3128 	u_int16_t nflow = 0;    /* Current flow index */
3129 	char *s = av;
3130 	cmd->d[0] = 0;	  /* Initializing the base number*/
3131 
3132 	while (s) {
3133 		av = strsep( &s, ",") ;
3134 		type = strtoul(av, &av, 0);
3135 		if (*av != ',' && *av != '\0')
3136 			errx(EX_DATAERR, "invalid ipv6 flow number %s", av);
3137 		if (type > 0xfffff)
3138 			errx(EX_DATAERR, "flow number out of range %s", av);
3139 		cmd->d[nflow] |= type;
3140 		nflow++;
3141 	}
3142 	if( nflow > 0 ) {
3143 		cmd->o.opcode = O_FLOW6ID;
3144 		cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + nflow;
3145 		cmd->o.arg1 = nflow;
3146 	}
3147 	else {
3148 		errx(EX_DATAERR, "invalid ipv6 flow number %s", av);
3149 	}
3150 }
3151 
3152 static ipfw_insn *
3153 add_srcip6(ipfw_insn *cmd, char *av)
3154 {
3155 
3156 	fill_ip6((ipfw_insn_ip6 *)cmd, av);
3157 	if (F_LEN(cmd) == 0)				/* any */
3158 		;
3159 	if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) {	/* "me" */
3160 		cmd->opcode = O_IP6_SRC_ME;
3161 	} else if (F_LEN(cmd) ==
3162 	    (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) {
3163 		/* single IP, no mask*/
3164 		cmd->opcode = O_IP6_SRC;
3165 	} else {					/* addr/mask opt */
3166 		cmd->opcode = O_IP6_SRC_MASK;
3167 	}
3168 	return cmd;
3169 }
3170 
3171 static ipfw_insn *
3172 add_dstip6(ipfw_insn *cmd, char *av)
3173 {
3174 
3175 	fill_ip6((ipfw_insn_ip6 *)cmd, av);
3176 	if (F_LEN(cmd) == 0)				/* any */
3177 		;
3178 	if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) {	/* "me" */
3179 		cmd->opcode = O_IP6_DST_ME;
3180 	} else if (F_LEN(cmd) ==
3181 	    (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) {
3182 		/* single IP, no mask*/
3183 		cmd->opcode = O_IP6_DST;
3184 	} else {					/* addr/mask opt */
3185 		cmd->opcode = O_IP6_DST_MASK;
3186 	}
3187 	return cmd;
3188 }
3189 
3190 
3191 /*
3192  * helper function to process a set of flags and set bits in the
3193  * appropriate masks.
3194  */
3195 static void
3196 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3197 	struct _s_x *flags, char *p)
3198 {
3199 	uint8_t set=0, clear=0;
3200 
3201 	while (p && *p) {
3202 		char *q;	/* points to the separator */
3203 		int val;
3204 		uint8_t *which;	/* mask we are working on */
3205 
3206 		if (*p == '!') {
3207 			p++;
3208 			which = &clear;
3209 		} else
3210 			which = &set;
3211 		q = strchr(p, ',');
3212 		if (q)
3213 			*q++ = '\0';
3214 		val = match_token(flags, p);
3215 		if (val <= 0)
3216 			errx(EX_DATAERR, "invalid flag %s", p);
3217 		*which |= (uint8_t)val;
3218 		p = q;
3219 	}
3220         cmd->opcode = opcode;
3221         cmd->len =  (cmd->len & (F_NOT | F_OR)) | 1;
3222         cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3223 }
3224 
3225 
3226 static void
3227 delete(int ac, char *av[])
3228 {
3229 	uint32_t rulenum;
3230 	struct dn_pipe p;
3231 	int i;
3232 	int exitval = EX_OK;
3233 	int do_set = 0;
3234 
3235 	memset(&p, 0, sizeof p);
3236 
3237 	av++; ac--;
3238 	NEED1("missing rule specification");
3239 	if (ac > 0 && _substrcmp(*av, "set") == 0) {
3240 		/* Do not allow using the following syntax:
3241 		 *	ipfw set N delete set M
3242 		 */
3243 		if (use_set)
3244 			errx(EX_DATAERR, "invalid syntax");
3245 		do_set = 1;	/* delete set */
3246 		ac--; av++;
3247 	}
3248 
3249 	/* Rule number */
3250 	while (ac && isdigit(**av)) {
3251 		i = atoi(*av); av++; ac--;
3252 		if (do_nat) {
3253 			exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
3254 			if (exitval) {
3255 				exitval = EX_UNAVAILABLE;
3256 				warn("rule %u not available", i);
3257 			}
3258  		} else if (do_pipe) {
3259 			if (do_pipe == 1)
3260 				p.pipe_nr = i;
3261 			else
3262 				p.fs.fs_nr = i;
3263 			i = do_cmd(IP_DUMMYNET_DEL, &p, sizeof p);
3264 			if (i) {
3265 				exitval = 1;
3266 				warn("rule %u: setsockopt(IP_DUMMYNET_DEL)",
3267 				    do_pipe == 1 ? p.pipe_nr : p.fs.fs_nr);
3268 			}
3269 		} else {
3270 			if (use_set)
3271 				rulenum = (i & 0xffff) | (5 << 24) |
3272 				    ((use_set - 1) << 16);
3273 			else
3274 			rulenum =  (i & 0xffff) | (do_set << 24);
3275 			i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum);
3276 			if (i) {
3277 				exitval = EX_UNAVAILABLE;
3278 				warn("rule %u: setsockopt(IP_FW_DEL)",
3279 				    rulenum);
3280 			}
3281 		}
3282 	}
3283 	if (exitval != EX_OK)
3284 		exit(exitval);
3285 }
3286 
3287 
3288 /*
3289  * fill the interface structure. We do not check the name as we can
3290  * create interfaces dynamically, so checking them at insert time
3291  * makes relatively little sense.
3292  * Interface names containing '*', '?', or '[' are assumed to be shell
3293  * patterns which match interfaces.
3294  */
3295 static void
3296 fill_iface(ipfw_insn_if *cmd, char *arg)
3297 {
3298 	cmd->name[0] = '\0';
3299 	cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3300 
3301 	/* Parse the interface or address */
3302 	if (strcmp(arg, "any") == 0)
3303 		cmd->o.len = 0;		/* effectively ignore this command */
3304 	else if (!isdigit(*arg)) {
3305 		strlcpy(cmd->name, arg, sizeof(cmd->name));
3306 		cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3307 	} else if (!inet_aton(arg, &cmd->p.ip))
3308 		errx(EX_DATAERR, "bad ip address ``%s''", arg);
3309 }
3310 
3311 /*
3312  * Search for interface with name "ifn", and fill n accordingly:
3313  *
3314  * n->ip        ip address of interface "ifn"
3315  * n->if_name   copy of interface name "ifn"
3316  */
3317 static void
3318 set_addr_dynamic(const char *ifn, struct cfg_nat *n)
3319 {
3320 	size_t needed;
3321 	int mib[6];
3322 	char *buf, *lim, *next;
3323 	struct if_msghdr *ifm;
3324 	struct ifa_msghdr *ifam;
3325 	struct sockaddr_dl *sdl;
3326 	struct sockaddr_in *sin;
3327 	int ifIndex, ifMTU;
3328 
3329 	mib[0] = CTL_NET;
3330 	mib[1] = PF_ROUTE;
3331 	mib[2] = 0;
3332 	mib[3] = AF_INET;
3333 	mib[4] = NET_RT_IFLIST;
3334 	mib[5] = 0;
3335 /*
3336  * Get interface data.
3337  */
3338 	if (sysctl(mib, 6, NULL, &needed, NULL, 0) == -1)
3339 		err(1, "iflist-sysctl-estimate");
3340 	if ((buf = malloc(needed)) == NULL)
3341 		errx(1, "malloc failed");
3342 	if (sysctl(mib, 6, buf, &needed, NULL, 0) == -1)
3343 		err(1, "iflist-sysctl-get");
3344 	lim = buf + needed;
3345 /*
3346  * Loop through interfaces until one with
3347  * given name is found. This is done to
3348  * find correct interface index for routing
3349  * message processing.
3350  */
3351 	ifIndex	= 0;
3352 	next = buf;
3353 	while (next < lim) {
3354 		ifm = (struct if_msghdr *)next;
3355 		next += ifm->ifm_msglen;
3356 		if (ifm->ifm_version != RTM_VERSION) {
3357 			if (verbose)
3358 				warnx("routing message version %d "
3359 				    "not understood", ifm->ifm_version);
3360 			continue;
3361 		}
3362 		if (ifm->ifm_type == RTM_IFINFO) {
3363 			sdl = (struct sockaddr_dl *)(ifm + 1);
3364 			if (strlen(ifn) == sdl->sdl_nlen &&
3365 			    strncmp(ifn, sdl->sdl_data, sdl->sdl_nlen) == 0) {
3366 				ifIndex = ifm->ifm_index;
3367 				ifMTU = ifm->ifm_data.ifi_mtu;
3368 				break;
3369 			}
3370 		}
3371 	}
3372 	if (!ifIndex)
3373 		errx(1, "unknown interface name %s", ifn);
3374 /*
3375  * Get interface address.
3376  */
3377 	sin = NULL;
3378 	while (next < lim) {
3379 		ifam = (struct ifa_msghdr *)next;
3380 		next += ifam->ifam_msglen;
3381 		if (ifam->ifam_version != RTM_VERSION) {
3382 			if (verbose)
3383 				warnx("routing message version %d "
3384 				    "not understood", ifam->ifam_version);
3385 			continue;
3386 		}
3387 		if (ifam->ifam_type != RTM_NEWADDR)
3388 			break;
3389 		if (ifam->ifam_addrs & RTA_IFA) {
3390 			int i;
3391 			char *cp = (char *)(ifam + 1);
3392 
3393 			for (i = 1; i < RTA_IFA; i <<= 1) {
3394 				if (ifam->ifam_addrs & i)
3395 					cp += SA_SIZE((struct sockaddr *)cp);
3396 			}
3397 			if (((struct sockaddr *)cp)->sa_family == AF_INET) {
3398 				sin = (struct sockaddr_in *)cp;
3399 				break;
3400 			}
3401 		}
3402 	}
3403 	if (sin == NULL)
3404 		errx(1, "%s: cannot get interface address", ifn);
3405 
3406 	n->ip = sin->sin_addr;
3407 	strncpy(n->if_name, ifn, IF_NAMESIZE);
3408 
3409 	free(buf);
3410 }
3411 
3412 /*
3413  * XXX - The following functions, macros and definitions come from natd.c:
3414  * it would be better to move them outside natd.c, in a file
3415  * (redirect_support.[ch]?) shared by ipfw and natd, but for now i can live
3416  * with it.
3417  */
3418 
3419 /*
3420  * Definition of a port range, and macros to deal with values.
3421  * FORMAT:  HI 16-bits == first port in range, 0 == all ports.
3422  *          LO 16-bits == number of ports in range
3423  * NOTES:   - Port values are not stored in network byte order.
3424  */
3425 
3426 #define port_range u_long
3427 
3428 #define GETLOPORT(x)     ((x) >> 0x10)
3429 #define GETNUMPORTS(x)   ((x) & 0x0000ffff)
3430 #define GETHIPORT(x)     (GETLOPORT((x)) + GETNUMPORTS((x)))
3431 
3432 /* Set y to be the low-port value in port_range variable x. */
3433 #define SETLOPORT(x,y)   ((x) = ((x) & 0x0000ffff) | ((y) << 0x10))
3434 
3435 /* Set y to be the number of ports in port_range variable x. */
3436 #define SETNUMPORTS(x,y) ((x) = ((x) & 0xffff0000) | (y))
3437 
3438 static void
3439 StrToAddr (const char* str, struct in_addr* addr)
3440 {
3441 	struct hostent* hp;
3442 
3443 	if (inet_aton (str, addr))
3444 		return;
3445 
3446 	hp = gethostbyname (str);
3447 	if (!hp)
3448 		errx (1, "unknown host %s", str);
3449 
3450 	memcpy (addr, hp->h_addr, sizeof (struct in_addr));
3451 }
3452 
3453 static int
3454 StrToPortRange (const char* str, const char* proto, port_range *portRange)
3455 {
3456 	char*           sep;
3457 	struct servent*	sp;
3458 	char*		end;
3459 	u_short         loPort;
3460 	u_short         hiPort;
3461 
3462 	/* First see if this is a service, return corresponding port if so. */
3463 	sp = getservbyname (str,proto);
3464 	if (sp) {
3465 	        SETLOPORT(*portRange, ntohs(sp->s_port));
3466 		SETNUMPORTS(*portRange, 1);
3467 		return 0;
3468 	}
3469 
3470 	/* Not a service, see if it's a single port or port range. */
3471 	sep = strchr (str, '-');
3472 	if (sep == NULL) {
3473 	        SETLOPORT(*portRange, strtol(str, &end, 10));
3474 		if (end != str) {
3475 		        /* Single port. */
3476 		        SETNUMPORTS(*portRange, 1);
3477 			return 0;
3478 		}
3479 
3480 		/* Error in port range field. */
3481 		errx (EX_DATAERR, "%s/%s: unknown service", str, proto);
3482 	}
3483 
3484 	/* Port range, get the values and sanity check. */
3485 	sscanf (str, "%hu-%hu", &loPort, &hiPort);
3486 	SETLOPORT(*portRange, loPort);
3487 	SETNUMPORTS(*portRange, 0);	/* Error by default */
3488 	if (loPort <= hiPort)
3489 	        SETNUMPORTS(*portRange, hiPort - loPort + 1);
3490 
3491 	if (GETNUMPORTS(*portRange) == 0)
3492 	        errx (EX_DATAERR, "invalid port range %s", str);
3493 
3494 	return 0;
3495 }
3496 
3497 static int
3498 StrToProto (const char* str)
3499 {
3500 	if (!strcmp (str, "tcp"))
3501 		return IPPROTO_TCP;
3502 
3503 	if (!strcmp (str, "udp"))
3504 		return IPPROTO_UDP;
3505 
3506 	errx (EX_DATAERR, "unknown protocol %s. Expected tcp or udp", str);
3507 }
3508 
3509 static int
3510 StrToAddrAndPortRange (const char* str, struct in_addr* addr, char* proto,
3511 		       port_range *portRange)
3512 {
3513 	char*	ptr;
3514 
3515 	ptr = strchr (str, ':');
3516 	if (!ptr)
3517 		errx (EX_DATAERR, "%s is missing port number", str);
3518 
3519 	*ptr = '\0';
3520 	++ptr;
3521 
3522 	StrToAddr (str, addr);
3523 	return StrToPortRange (ptr, proto, portRange);
3524 }
3525 
3526 /* End of stuff taken from natd.c. */
3527 
3528 #define INC_ARGCV() do {        \
3529 	(*_av)++;               \
3530 	(*_ac)--;               \
3531 	av = *_av;              \
3532 	ac = *_ac;              \
3533 } while(0)
3534 
3535 /*
3536  * The next 3 functions add support for the addr, port and proto redirect and
3537  * their logic is loosely based on SetupAddressRedirect(), SetupPortRedirect()
3538  * and SetupProtoRedirect() from natd.c.
3539  *
3540  * Every setup_* function fills at least one redirect entry
3541  * (struct cfg_redir) and zero or more server pool entry (struct cfg_spool)
3542  * in buf.
3543  *
3544  * The format of data in buf is:
3545  *
3546  *
3547  *     cfg_nat    cfg_redir    cfg_spool    ......  cfg_spool
3548  *
3549  *    -------------------------------------        ------------
3550  *   |          | .....X ... |          |         |           |  .....
3551  *    ------------------------------------- ...... ------------
3552  *                     ^
3553  *                spool_cnt       n=0       ......   n=(X-1)
3554  *
3555  * len points to the amount of available space in buf
3556  * space counts the memory consumed by every function
3557  *
3558  * XXX - Every function get all the argv params so it
3559  * has to check, in optional parameters, that the next
3560  * args is a valid option for the redir entry and not
3561  * another token. Only redir_port and redir_proto are
3562  * affected by this.
3563  */
3564 
3565 static int
3566 setup_redir_addr(char *spool_buf, int len,
3567 		 int *_ac, char ***_av)
3568 {
3569 	char **av, *sep; /* Token separator. */
3570 	/* Temporary buffer used to hold server pool ip's. */
3571 	char tmp_spool_buf[NAT_BUF_LEN];
3572 	int ac, i, space, lsnat;
3573 	struct cfg_redir *r;
3574 	struct cfg_spool *tmp;
3575 
3576 	av = *_av;
3577 	ac = *_ac;
3578 	space = 0;
3579 	lsnat = 0;
3580 	if (len >= SOF_REDIR) {
3581 		r = (struct cfg_redir *)spool_buf;
3582 		/* Skip cfg_redir at beginning of buf. */
3583 		spool_buf = &spool_buf[SOF_REDIR];
3584 		space = SOF_REDIR;
3585 		len -= SOF_REDIR;
3586 	} else
3587 		goto nospace;
3588 	r->mode = REDIR_ADDR;
3589 	/* Extract local address. */
3590 	if (ac == 0)
3591 		errx(EX_DATAERR, "redirect_addr: missing local address");
3592 	sep = strchr(*av, ',');
3593 	if (sep) {		/* LSNAT redirection syntax. */
3594 		r->laddr.s_addr = INADDR_NONE;
3595 		/* Preserve av, copy spool servers to tmp_spool_buf. */
3596 		strncpy(tmp_spool_buf, *av, strlen(*av)+1);
3597 		lsnat = 1;
3598 	} else
3599 		StrToAddr(*av, &r->laddr);
3600 	INC_ARGCV();
3601 
3602 	/* Extract public address. */
3603 	if (ac == 0)
3604 		errx(EX_DATAERR, "redirect_addr: missing public address");
3605 	StrToAddr(*av, &r->paddr);
3606 	INC_ARGCV();
3607 
3608 	/* Setup LSNAT server pool. */
3609 	if (sep) {
3610 		sep = strtok(tmp_spool_buf, ",");
3611 		while (sep != NULL) {
3612 			tmp = (struct cfg_spool *)spool_buf;
3613 			if (len < SOF_SPOOL)
3614 				goto nospace;
3615 			len -= SOF_SPOOL;
3616 			space += SOF_SPOOL;
3617 			StrToAddr(sep, &tmp->addr);
3618 			tmp->port = ~0;
3619 			r->spool_cnt++;
3620 			/* Point to the next possible cfg_spool. */
3621 			spool_buf = &spool_buf[SOF_SPOOL];
3622 			sep = strtok(NULL, ",");
3623 		}
3624 	}
3625 	return(space);
3626 nospace:
3627 	errx(EX_DATAERR, "redirect_addr: buf is too small\n");
3628 }
3629 
3630 static int
3631 setup_redir_port(char *spool_buf, int len,
3632 		 int *_ac, char ***_av)
3633 {
3634 	char **av, *sep, *protoName;
3635 	char tmp_spool_buf[NAT_BUF_LEN];
3636 	int ac, space, lsnat;
3637 	struct cfg_redir *r;
3638 	struct cfg_spool *tmp;
3639 	u_short numLocalPorts;
3640 	port_range portRange;
3641 
3642 	av = *_av;
3643 	ac = *_ac;
3644 	space = 0;
3645 	lsnat = 0;
3646 	numLocalPorts = 0;
3647 
3648 	if (len >= SOF_REDIR) {
3649 		r = (struct cfg_redir *)spool_buf;
3650 		/* Skip cfg_redir at beginning of buf. */
3651 		spool_buf = &spool_buf[SOF_REDIR];
3652 		space = SOF_REDIR;
3653 		len -= SOF_REDIR;
3654 	} else
3655 		goto nospace;
3656 	r->mode = REDIR_PORT;
3657 	/*
3658 	 * Extract protocol.
3659 	 */
3660 	if (ac == 0)
3661 		errx (EX_DATAERR, "redirect_port: missing protocol");
3662 	r->proto = StrToProto(*av);
3663 	protoName = *av;
3664 	INC_ARGCV();
3665 
3666 	/*
3667 	 * Extract local address.
3668 	 */
3669 	if (ac == 0)
3670 		errx (EX_DATAERR, "redirect_port: missing local address");
3671 
3672 	sep = strchr(*av, ',');
3673 	/* LSNAT redirection syntax. */
3674 	if (sep) {
3675 		r->laddr.s_addr = INADDR_NONE;
3676 		r->lport = ~0;
3677 		numLocalPorts = 1;
3678 		/* Preserve av, copy spool servers to tmp_spool_buf. */
3679 		strncpy(tmp_spool_buf, *av, strlen(*av)+1);
3680 		lsnat = 1;
3681 	} else {
3682 		if (StrToAddrAndPortRange (*av, &r->laddr, protoName,
3683 		    &portRange) != 0)
3684 			errx(EX_DATAERR, "redirect_port:"
3685 			    "invalid local port range");
3686 
3687 		r->lport = GETLOPORT(portRange);
3688 		numLocalPorts = GETNUMPORTS(portRange);
3689 	}
3690 	INC_ARGCV();
3691 
3692 	/*
3693 	 * Extract public port and optionally address.
3694 	 */
3695 	if (ac == 0)
3696 		errx (EX_DATAERR, "redirect_port: missing public port");
3697 
3698 	sep = strchr (*av, ':');
3699 	if (sep) {
3700 	        if (StrToAddrAndPortRange (*av, &r->paddr, protoName,
3701 		    &portRange) != 0)
3702 		        errx(EX_DATAERR, "redirect_port:"
3703 			    "invalid public port range");
3704 	} else {
3705 		r->paddr.s_addr = INADDR_ANY;
3706 		if (StrToPortRange (*av, protoName, &portRange) != 0)
3707 		        errx(EX_DATAERR, "redirect_port:"
3708 			    "invalid public port range");
3709 	}
3710 
3711 	r->pport = GETLOPORT(portRange);
3712 	r->pport_cnt = GETNUMPORTS(portRange);
3713 	INC_ARGCV();
3714 
3715 	/*
3716 	 * Extract remote address and optionally port.
3717 	 */
3718 	/*
3719 	 * NB: isalpha(**av) => we've to check that next parameter is really an
3720 	 * option for this redirect entry, else stop here processing arg[cv].
3721 	 */
3722 	if (ac != 0 && !isalpha(**av)) {
3723 		sep = strchr (*av, ':');
3724 		if (sep) {
3725 		        if (StrToAddrAndPortRange (*av, &r->raddr, protoName,
3726 			    &portRange) != 0)
3727 				errx(EX_DATAERR, "redirect_port:"
3728 				    "invalid remote port range");
3729 		} else {
3730 		        SETLOPORT(portRange, 0);
3731 			SETNUMPORTS(portRange, 1);
3732 			StrToAddr (*av, &r->raddr);
3733 		}
3734 		INC_ARGCV();
3735 	} else {
3736 		SETLOPORT(portRange, 0);
3737 		SETNUMPORTS(portRange, 1);
3738 		r->raddr.s_addr = INADDR_ANY;
3739 	}
3740 	r->rport = GETLOPORT(portRange);
3741 	r->rport_cnt = GETNUMPORTS(portRange);
3742 
3743 	/*
3744 	 * Make sure port ranges match up, then add the redirect ports.
3745 	 */
3746 	if (numLocalPorts != r->pport_cnt)
3747 	        errx(EX_DATAERR, "redirect_port:"
3748 		    "port ranges must be equal in size");
3749 
3750 	/* Remote port range is allowed to be '0' which means all ports. */
3751 	if (r->rport_cnt != numLocalPorts &&
3752 	    (r->rport_cnt != 1 || r->rport != 0))
3753 	        errx(EX_DATAERR, "redirect_port: remote port must"
3754 		    "be 0 or equal to local port range in size");
3755 
3756 	/*
3757 	 * Setup LSNAT server pool.
3758 	 */
3759 	if (lsnat) {
3760 		sep = strtok(tmp_spool_buf, ",");
3761 		while (sep != NULL) {
3762 			tmp = (struct cfg_spool *)spool_buf;
3763 			if (len < SOF_SPOOL)
3764 				goto nospace;
3765 			len -= SOF_SPOOL;
3766 			space += SOF_SPOOL;
3767 			if (StrToAddrAndPortRange(sep, &tmp->addr, protoName,
3768 			    &portRange) != 0)
3769 				errx(EX_DATAERR, "redirect_port:"
3770 				    "invalid local port range");
3771 			if (GETNUMPORTS(portRange) != 1)
3772 				errx(EX_DATAERR, "redirect_port: local port"
3773 				    "must be single in this context");
3774 			tmp->port = GETLOPORT(portRange);
3775 			r->spool_cnt++;
3776 			/* Point to the next possible cfg_spool. */
3777 			spool_buf = &spool_buf[SOF_SPOOL];
3778 			sep = strtok(NULL, ",");
3779 		}
3780 	}
3781 	return (space);
3782 nospace:
3783 	errx(EX_DATAERR, "redirect_port: buf is too small\n");
3784 }
3785 
3786 static int
3787 setup_redir_proto(char *spool_buf, int len,
3788 		 int *_ac, char ***_av)
3789 {
3790 	char **av;
3791 	int ac, i, space;
3792 	struct protoent *protoent;
3793 	struct cfg_redir *r;
3794 
3795 	av = *_av;
3796 	ac = *_ac;
3797 	if (len >= SOF_REDIR) {
3798 		r = (struct cfg_redir *)spool_buf;
3799 		/* Skip cfg_redir at beginning of buf. */
3800 		spool_buf = &spool_buf[SOF_REDIR];
3801 		space = SOF_REDIR;
3802 		len -= SOF_REDIR;
3803 	} else
3804 		goto nospace;
3805 	r->mode = REDIR_PROTO;
3806 	/*
3807 	 * Extract protocol.
3808 	 */
3809 	if (ac == 0)
3810 		errx(EX_DATAERR, "redirect_proto: missing protocol");
3811 
3812 	protoent = getprotobyname(*av);
3813 	if (protoent == NULL)
3814 		errx(EX_DATAERR, "redirect_proto: unknown protocol %s", *av);
3815 	else
3816 		r->proto = protoent->p_proto;
3817 
3818 	INC_ARGCV();
3819 
3820 	/*
3821 	 * Extract local address.
3822 	 */
3823 	if (ac == 0)
3824 		errx(EX_DATAERR, "redirect_proto: missing local address");
3825 	else
3826 		StrToAddr(*av, &r->laddr);
3827 
3828 	INC_ARGCV();
3829 
3830 	/*
3831 	 * Extract optional public address.
3832 	 */
3833 	if (ac == 0) {
3834 		r->paddr.s_addr = INADDR_ANY;
3835 		r->raddr.s_addr = INADDR_ANY;
3836 	} else {
3837 		/* see above in setup_redir_port() */
3838 		if (!isalpha(**av)) {
3839 			StrToAddr(*av, &r->paddr);
3840 			INC_ARGCV();
3841 
3842 			/*
3843 			 * Extract optional remote address.
3844 			 */
3845 			/* see above in setup_redir_port() */
3846 			if (ac!=0 && !isalpha(**av)) {
3847 				StrToAddr(*av, &r->raddr);
3848 				INC_ARGCV();
3849 			}
3850 		}
3851 	}
3852 	return (space);
3853 nospace:
3854 	errx(EX_DATAERR, "redirect_proto: buf is too small\n");
3855 }
3856 
3857 static void
3858 show_nat(int ac, char **av);
3859 
3860 static void
3861 print_nat_config(char *buf) {
3862 	struct cfg_nat *n;
3863 	int i, cnt, flag, off;
3864 	struct cfg_redir *t;
3865 	struct cfg_spool *s;
3866 	struct protoent *p;
3867 
3868 	n = (struct cfg_nat *)buf;
3869 	flag = 1;
3870 	off  = sizeof(*n);
3871 	printf("ipfw nat %u config", n->id);
3872 	if (strlen(n->if_name) != 0)
3873 		printf(" if %s", n->if_name);
3874 	else if (n->ip.s_addr != 0)
3875 		printf(" ip %s", inet_ntoa(n->ip));
3876 	while (n->mode != 0) {
3877 		if (n->mode & PKT_ALIAS_LOG) {
3878 			printf(" log");
3879 			n->mode &= ~PKT_ALIAS_LOG;
3880 		} else if (n->mode & PKT_ALIAS_DENY_INCOMING) {
3881 			printf(" deny_in");
3882 			n->mode &= ~PKT_ALIAS_DENY_INCOMING;
3883 		} else if (n->mode & PKT_ALIAS_SAME_PORTS) {
3884 			printf(" same_ports");
3885 			n->mode &= ~PKT_ALIAS_SAME_PORTS;
3886 		} else if (n->mode & PKT_ALIAS_UNREGISTERED_ONLY) {
3887 			printf(" unreg_only");
3888 			n->mode &= ~PKT_ALIAS_UNREGISTERED_ONLY;
3889 		} else if (n->mode & PKT_ALIAS_RESET_ON_ADDR_CHANGE) {
3890 			printf(" reset");
3891 			n->mode &= ~PKT_ALIAS_RESET_ON_ADDR_CHANGE;
3892 		} else if (n->mode & PKT_ALIAS_REVERSE) {
3893 			printf(" reverse");
3894 			n->mode &= ~PKT_ALIAS_REVERSE;
3895 		} else if (n->mode & PKT_ALIAS_PROXY_ONLY) {
3896 			printf(" proxy_only");
3897 			n->mode &= ~PKT_ALIAS_PROXY_ONLY;
3898 		}
3899 	}
3900 	/* Print all the redirect's data configuration. */
3901 	for (cnt = 0; cnt < n->redir_cnt; cnt++) {
3902 		t = (struct cfg_redir *)&buf[off];
3903 		off += SOF_REDIR;
3904 		switch (t->mode) {
3905 		case REDIR_ADDR:
3906 			printf(" redirect_addr");
3907 			if (t->spool_cnt == 0)
3908 				printf(" %s", inet_ntoa(t->laddr));
3909 			else
3910 				for (i = 0; i < t->spool_cnt; i++) {
3911 					s = (struct cfg_spool *)&buf[off];
3912 					if (i)
3913 						printf(",");
3914 					else
3915 						printf(" ");
3916 					printf("%s", inet_ntoa(s->addr));
3917 					off += SOF_SPOOL;
3918 				}
3919 			printf(" %s", inet_ntoa(t->paddr));
3920 			break;
3921 		case REDIR_PORT:
3922 			p = getprotobynumber(t->proto);
3923 			printf(" redirect_port %s ", p->p_name);
3924 			if (!t->spool_cnt) {
3925 				printf("%s:%u", inet_ntoa(t->laddr), t->lport);
3926 				if (t->pport_cnt > 1)
3927 					printf("-%u", t->lport +
3928 					    t->pport_cnt - 1);
3929 			} else
3930 				for (i=0; i < t->spool_cnt; i++) {
3931 					s = (struct cfg_spool *)&buf[off];
3932 					if (i)
3933 						printf(",");
3934 					printf("%s:%u", inet_ntoa(s->addr),
3935 					    s->port);
3936 					off += SOF_SPOOL;
3937 				}
3938 
3939 			printf(" ");
3940 			if (t->paddr.s_addr)
3941 				printf("%s:", inet_ntoa(t->paddr));
3942 			printf("%u", t->pport);
3943 			if (!t->spool_cnt && t->pport_cnt > 1)
3944 				printf("-%u", t->pport + t->pport_cnt - 1);
3945 
3946 			if (t->raddr.s_addr) {
3947 				printf(" %s", inet_ntoa(t->raddr));
3948 				if (t->rport) {
3949 					printf(":%u", t->rport);
3950 					if (!t->spool_cnt && t->rport_cnt > 1)
3951 						printf("-%u", t->rport +
3952 						    t->rport_cnt - 1);
3953 				}
3954 			}
3955 			break;
3956 		case REDIR_PROTO:
3957 			p = getprotobynumber(t->proto);
3958 			printf(" redirect_proto %s %s", p->p_name,
3959 			    inet_ntoa(t->laddr));
3960 			if (t->paddr.s_addr != 0) {
3961 				printf(" %s", inet_ntoa(t->paddr));
3962 				if (t->raddr.s_addr)
3963 					printf(" %s", inet_ntoa(t->raddr));
3964 			}
3965 			break;
3966 		default:
3967 			errx(EX_DATAERR, "unknown redir mode");
3968 			break;
3969 		}
3970 	}
3971 	printf("\n");
3972 }
3973 
3974 static void
3975 config_nat(int ac, char **av)
3976 {
3977 	struct cfg_nat *n;              /* Nat instance configuration. */
3978 	struct in_addr ip;
3979 	int i, len, off, tok;
3980 	char *id, buf[NAT_BUF_LEN]; 	/* Buffer for serialized data. */
3981 
3982 	len = NAT_BUF_LEN;
3983 	/* Offset in buf: save space for n at the beginning. */
3984 	off = sizeof(*n);
3985 	memset(buf, 0, sizeof(buf));
3986 	n = (struct cfg_nat *)buf;
3987 
3988 	av++; ac--;
3989 	/* Nat id. */
3990 	if (ac && isdigit(**av)) {
3991 		id = *av;
3992 		i = atoi(*av);
3993 		ac--; av++;
3994 		n->id = i;
3995 	} else
3996 		errx(EX_DATAERR, "missing nat id");
3997 	if (ac == 0)
3998 		errx(EX_DATAERR, "missing option");
3999 
4000 	while (ac > 0) {
4001 		tok = match_token(nat_params, *av);
4002 		ac--; av++;
4003 		switch (tok) {
4004 		case TOK_IP:
4005 			if (ac == 0)
4006 				errx(EX_DATAERR, "missing option");
4007 			if (!inet_aton(av[0], &(n->ip)))
4008 				errx(EX_DATAERR, "bad ip address ``%s''",
4009 				    av[0]);
4010 			ac--; av++;
4011 			break;
4012 		case TOK_IF:
4013 			if (ac == 0)
4014 				errx(EX_DATAERR, "missing option");
4015 			set_addr_dynamic(av[0], n);
4016 			ac--; av++;
4017 			break;
4018 		case TOK_ALOG:
4019 			n->mode |= PKT_ALIAS_LOG;
4020 			break;
4021 		case TOK_DENY_INC:
4022 			n->mode |= PKT_ALIAS_DENY_INCOMING;
4023 			break;
4024 		case TOK_SAME_PORTS:
4025 			n->mode |= PKT_ALIAS_SAME_PORTS;
4026 			break;
4027 		case TOK_UNREG_ONLY:
4028 			n->mode |= PKT_ALIAS_UNREGISTERED_ONLY;
4029 			break;
4030 		case TOK_RESET_ADDR:
4031 			n->mode |= PKT_ALIAS_RESET_ON_ADDR_CHANGE;
4032 			break;
4033 		case TOK_ALIAS_REV:
4034 			n->mode |= PKT_ALIAS_REVERSE;
4035 			break;
4036 		case TOK_PROXY_ONLY:
4037 			n->mode |= PKT_ALIAS_PROXY_ONLY;
4038 			break;
4039 			/*
4040 			 * All the setup_redir_* functions work directly in the final
4041 			 * buffer, see above for details.
4042 			 */
4043 		case TOK_REDIR_ADDR:
4044 		case TOK_REDIR_PORT:
4045 		case TOK_REDIR_PROTO:
4046 			switch (tok) {
4047 			case TOK_REDIR_ADDR:
4048 				i = setup_redir_addr(&buf[off], len, &ac, &av);
4049 				break;
4050 			case TOK_REDIR_PORT:
4051 				i = setup_redir_port(&buf[off], len, &ac, &av);
4052 				break;
4053 			case TOK_REDIR_PROTO:
4054 				i = setup_redir_proto(&buf[off], len, &ac, &av);
4055 				break;
4056 			}
4057 			n->redir_cnt++;
4058 			off += i;
4059 			len -= i;
4060 			break;
4061 		default:
4062 			errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]);
4063 		}
4064 	}
4065 
4066 	i = do_cmd(IP_FW_NAT_CFG, buf, off);
4067 	if (i)
4068 		err(1, "setsockopt(%s)", "IP_FW_NAT_CFG");
4069 
4070 	/* After every modification, we show the resultant rule. */
4071 	int _ac = 3;
4072 	char *_av[] = {"show", "config", id};
4073 	show_nat(_ac, _av);
4074 }
4075 
4076 static void
4077 config_pipe(int ac, char **av)
4078 {
4079 	struct dn_pipe p;
4080 	int i;
4081 	char *end;
4082 	void *par = NULL;
4083 
4084 	memset(&p, 0, sizeof p);
4085 
4086 	av++; ac--;
4087 	/* Pipe number */
4088 	if (ac && isdigit(**av)) {
4089 		i = atoi(*av); av++; ac--;
4090 		if (do_pipe == 1)
4091 			p.pipe_nr = i;
4092 		else
4093 			p.fs.fs_nr = i;
4094 	}
4095 	while (ac > 0) {
4096 		double d;
4097 		int tok = match_token(dummynet_params, *av);
4098 		ac--; av++;
4099 
4100 		switch(tok) {
4101 		case TOK_NOERROR:
4102 			p.fs.flags_fs |= DN_NOERROR;
4103 			break;
4104 
4105 		case TOK_PLR:
4106 			NEED1("plr needs argument 0..1\n");
4107 			d = strtod(av[0], NULL);
4108 			if (d > 1)
4109 				d = 1;
4110 			else if (d < 0)
4111 				d = 0;
4112 			p.fs.plr = (int)(d*0x7fffffff);
4113 			ac--; av++;
4114 			break;
4115 
4116 		case TOK_QUEUE:
4117 			NEED1("queue needs queue size\n");
4118 			end = NULL;
4119 			p.fs.qsize = strtoul(av[0], &end, 0);
4120 			if (*end == 'K' || *end == 'k') {
4121 				p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
4122 				p.fs.qsize *= 1024;
4123 			} else if (*end == 'B' ||
4124 			    _substrcmp2(end, "by", "bytes") == 0) {
4125 				p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
4126 			}
4127 			ac--; av++;
4128 			break;
4129 
4130 		case TOK_BUCKETS:
4131 			NEED1("buckets needs argument\n");
4132 			p.fs.rq_size = strtoul(av[0], NULL, 0);
4133 			ac--; av++;
4134 			break;
4135 
4136 		case TOK_MASK:
4137 			NEED1("mask needs mask specifier\n");
4138 			/*
4139 			 * per-flow queue, mask is dst_ip, dst_port,
4140 			 * src_ip, src_port, proto measured in bits
4141 			 */
4142 			par = NULL;
4143 
4144 			bzero(&p.fs.flow_mask, sizeof(p.fs.flow_mask));
4145 			end = NULL;
4146 
4147 			while (ac >= 1) {
4148 			    uint32_t *p32 = NULL;
4149 			    uint16_t *p16 = NULL;
4150 			    uint32_t *p20 = NULL;
4151 			    struct in6_addr *pa6 = NULL;
4152 			    uint32_t a;
4153 
4154 			    tok = match_token(dummynet_params, *av);
4155 			    ac--; av++;
4156 			    switch(tok) {
4157 			    case TOK_ALL:
4158 				    /*
4159 				     * special case, all bits significant
4160 				     */
4161 				    p.fs.flow_mask.dst_ip = ~0;
4162 				    p.fs.flow_mask.src_ip = ~0;
4163 				    p.fs.flow_mask.dst_port = ~0;
4164 				    p.fs.flow_mask.src_port = ~0;
4165 				    p.fs.flow_mask.proto = ~0;
4166 				    n2mask(&(p.fs.flow_mask.dst_ip6), 128);
4167 				    n2mask(&(p.fs.flow_mask.src_ip6), 128);
4168 				    p.fs.flow_mask.flow_id6 = ~0;
4169 				    p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
4170 				    goto end_mask;
4171 
4172 			    case TOK_DSTIP:
4173 				    p32 = &p.fs.flow_mask.dst_ip;
4174 				    break;
4175 
4176 			    case TOK_SRCIP:
4177 				    p32 = &p.fs.flow_mask.src_ip;
4178 				    break;
4179 
4180 			    case TOK_DSTIP6:
4181 				    pa6 = &(p.fs.flow_mask.dst_ip6);
4182 				    break;
4183 
4184 			    case TOK_SRCIP6:
4185 				    pa6 = &(p.fs.flow_mask.src_ip6);
4186 				    break;
4187 
4188 			    case TOK_FLOWID:
4189 				    p20 = &p.fs.flow_mask.flow_id6;
4190 				    break;
4191 
4192 			    case TOK_DSTPORT:
4193 				    p16 = &p.fs.flow_mask.dst_port;
4194 				    break;
4195 
4196 			    case TOK_SRCPORT:
4197 				    p16 = &p.fs.flow_mask.src_port;
4198 				    break;
4199 
4200 			    case TOK_PROTO:
4201 				    break;
4202 
4203 			    default:
4204 				    ac++; av--; /* backtrack */
4205 				    goto end_mask;
4206 			    }
4207 			    if (ac < 1)
4208 				    errx(EX_USAGE, "mask: value missing");
4209 			    if (*av[0] == '/') {
4210 				    a = strtoul(av[0]+1, &end, 0);
4211 				    if (pa6 == NULL)
4212 					    a = (a == 32) ? ~0 : (1 << a) - 1;
4213 			    } else
4214 				    a = strtoul(av[0], &end, 0);
4215 			    if (p32 != NULL)
4216 				    *p32 = a;
4217 			    else if (p16 != NULL) {
4218 				    if (a > 0xFFFF)
4219 					    errx(EX_DATAERR,
4220 						"port mask must be 16 bit");
4221 				    *p16 = (uint16_t)a;
4222 			    } else if (p20 != NULL) {
4223 				    if (a > 0xfffff)
4224 					errx(EX_DATAERR,
4225 					    "flow_id mask must be 20 bit");
4226 				    *p20 = (uint32_t)a;
4227 			    } else if (pa6 != NULL) {
4228 				    if (a < 0 || a > 128)
4229 					errx(EX_DATAERR,
4230 					    "in6addr invalid mask len");
4231 				    else
4232 					n2mask(pa6, a);
4233 			    } else {
4234 				    if (a > 0xFF)
4235 					    errx(EX_DATAERR,
4236 						"proto mask must be 8 bit");
4237 				    p.fs.flow_mask.proto = (uint8_t)a;
4238 			    }
4239 			    if (a != 0)
4240 				    p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
4241 			    ac--; av++;
4242 			} /* end while, config masks */
4243 end_mask:
4244 			break;
4245 
4246 		case TOK_RED:
4247 		case TOK_GRED:
4248 			NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
4249 			p.fs.flags_fs |= DN_IS_RED;
4250 			if (tok == TOK_GRED)
4251 				p.fs.flags_fs |= DN_IS_GENTLE_RED;
4252 			/*
4253 			 * the format for parameters is w_q/min_th/max_th/max_p
4254 			 */
4255 			if ((end = strsep(&av[0], "/"))) {
4256 			    double w_q = strtod(end, NULL);
4257 			    if (w_q > 1 || w_q <= 0)
4258 				errx(EX_DATAERR, "0 < w_q <= 1");
4259 			    p.fs.w_q = (int) (w_q * (1 << SCALE_RED));
4260 			}
4261 			if ((end = strsep(&av[0], "/"))) {
4262 			    p.fs.min_th = strtoul(end, &end, 0);
4263 			    if (*end == 'K' || *end == 'k')
4264 				p.fs.min_th *= 1024;
4265 			}
4266 			if ((end = strsep(&av[0], "/"))) {
4267 			    p.fs.max_th = strtoul(end, &end, 0);
4268 			    if (*end == 'K' || *end == 'k')
4269 				p.fs.max_th *= 1024;
4270 			}
4271 			if ((end = strsep(&av[0], "/"))) {
4272 			    double max_p = strtod(end, NULL);
4273 			    if (max_p > 1 || max_p <= 0)
4274 				errx(EX_DATAERR, "0 < max_p <= 1");
4275 			    p.fs.max_p = (int)(max_p * (1 << SCALE_RED));
4276 			}
4277 			ac--; av++;
4278 			break;
4279 
4280 		case TOK_DROPTAIL:
4281 			p.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
4282 			break;
4283 
4284 		case TOK_BW:
4285 			NEED1("bw needs bandwidth or interface\n");
4286 			if (do_pipe != 1)
4287 			    errx(EX_DATAERR, "bandwidth only valid for pipes");
4288 			/*
4289 			 * set clocking interface or bandwidth value
4290 			 */
4291 			if (av[0][0] >= 'a' && av[0][0] <= 'z') {
4292 			    int l = sizeof(p.if_name)-1;
4293 			    /* interface name */
4294 			    strncpy(p.if_name, av[0], l);
4295 			    p.if_name[l] = '\0';
4296 			    p.bandwidth = 0;
4297 			} else {
4298 			    p.if_name[0] = '\0';
4299 			    p.bandwidth = strtoul(av[0], &end, 0);
4300 			    if (*end == 'K' || *end == 'k') {
4301 				end++;
4302 				p.bandwidth *= 1000;
4303 			    } else if (*end == 'M') {
4304 				end++;
4305 				p.bandwidth *= 1000000;
4306 			    }
4307 			    if ((*end == 'B' &&
4308 				  _substrcmp2(end, "Bi", "Bit/s") != 0) ||
4309 			        _substrcmp2(end, "by", "bytes") == 0)
4310 				p.bandwidth *= 8;
4311 			    if (p.bandwidth < 0)
4312 				errx(EX_DATAERR, "bandwidth too large");
4313 			}
4314 			ac--; av++;
4315 			break;
4316 
4317 		case TOK_DELAY:
4318 			if (do_pipe != 1)
4319 				errx(EX_DATAERR, "delay only valid for pipes");
4320 			NEED1("delay needs argument 0..10000ms\n");
4321 			p.delay = strtoul(av[0], NULL, 0);
4322 			ac--; av++;
4323 			break;
4324 
4325 		case TOK_WEIGHT:
4326 			if (do_pipe == 1)
4327 				errx(EX_DATAERR,"weight only valid for queues");
4328 			NEED1("weight needs argument 0..100\n");
4329 			p.fs.weight = strtoul(av[0], &end, 0);
4330 			ac--; av++;
4331 			break;
4332 
4333 		case TOK_PIPE:
4334 			if (do_pipe == 1)
4335 				errx(EX_DATAERR,"pipe only valid for queues");
4336 			NEED1("pipe needs pipe_number\n");
4337 			p.fs.parent_nr = strtoul(av[0], &end, 0);
4338 			ac--; av++;
4339 			break;
4340 
4341 		default:
4342 			errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]);
4343 		}
4344 	}
4345 	if (do_pipe == 1) {
4346 		if (p.pipe_nr == 0)
4347 			errx(EX_DATAERR, "pipe_nr must be > 0");
4348 		if (p.delay > 10000)
4349 			errx(EX_DATAERR, "delay must be < 10000");
4350 	} else { /* do_pipe == 2, queue */
4351 		if (p.fs.parent_nr == 0)
4352 			errx(EX_DATAERR, "pipe must be > 0");
4353 		if (p.fs.weight >100)
4354 			errx(EX_DATAERR, "weight must be <= 100");
4355 	}
4356 	if (p.fs.flags_fs & DN_QSIZE_IS_BYTES) {
4357 		size_t len;
4358 		long limit;
4359 
4360 		len = sizeof(limit);
4361 		if (sysctlbyname("net.inet.ip.dummynet.pipe_byte_limit",
4362 			&limit, &len, NULL, 0) == -1)
4363 			limit = 1024*1024;
4364 		if (p.fs.qsize > limit)
4365 			errx(EX_DATAERR, "queue size must be < %ldB", limit);
4366 	} else {
4367 		size_t len;
4368 		long limit;
4369 
4370 		len = sizeof(limit);
4371 		if (sysctlbyname("net.inet.ip.dummynet.pipe_slot_limit",
4372 			&limit, &len, NULL, 0) == -1)
4373 			limit = 100;
4374 		if (p.fs.qsize > limit)
4375 			errx(EX_DATAERR, "2 <= queue size <= %ld", limit);
4376 	}
4377 	if (p.fs.flags_fs & DN_IS_RED) {
4378 		size_t len;
4379 		int lookup_depth, avg_pkt_size;
4380 		double s, idle, weight, w_q;
4381 		struct clockinfo ck;
4382 		int t;
4383 
4384 		if (p.fs.min_th >= p.fs.max_th)
4385 		    errx(EX_DATAERR, "min_th %d must be < than max_th %d",
4386 			p.fs.min_th, p.fs.max_th);
4387 		if (p.fs.max_th == 0)
4388 		    errx(EX_DATAERR, "max_th must be > 0");
4389 
4390 		len = sizeof(int);
4391 		if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
4392 			&lookup_depth, &len, NULL, 0) == -1)
4393 		    errx(1, "sysctlbyname(\"%s\")",
4394 			"net.inet.ip.dummynet.red_lookup_depth");
4395 		if (lookup_depth == 0)
4396 		    errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
4397 			" must be greater than zero");
4398 
4399 		len = sizeof(int);
4400 		if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
4401 			&avg_pkt_size, &len, NULL, 0) == -1)
4402 
4403 		    errx(1, "sysctlbyname(\"%s\")",
4404 			"net.inet.ip.dummynet.red_avg_pkt_size");
4405 		if (avg_pkt_size == 0)
4406 			errx(EX_DATAERR,
4407 			    "net.inet.ip.dummynet.red_avg_pkt_size must"
4408 			    " be greater than zero");
4409 
4410 		len = sizeof(struct clockinfo);
4411 		if (sysctlbyname("kern.clockrate", &ck, &len, NULL, 0) == -1)
4412 			errx(1, "sysctlbyname(\"%s\")", "kern.clockrate");
4413 
4414 		/*
4415 		 * Ticks needed for sending a medium-sized packet.
4416 		 * Unfortunately, when we are configuring a WF2Q+ queue, we
4417 		 * do not have bandwidth information, because that is stored
4418 		 * in the parent pipe, and also we have multiple queues
4419 		 * competing for it. So we set s=0, which is not very
4420 		 * correct. But on the other hand, why do we want RED with
4421 		 * WF2Q+ ?
4422 		 */
4423 		if (p.bandwidth==0) /* this is a WF2Q+ queue */
4424 			s = 0;
4425 		else
4426 			s = (double)ck.hz * avg_pkt_size * 8 / p.bandwidth;
4427 
4428 		/*
4429 		 * max idle time (in ticks) before avg queue size becomes 0.
4430 		 * NOTA:  (3/w_q) is approx the value x so that
4431 		 * (1-w_q)^x < 10^-3.
4432 		 */
4433 		w_q = ((double)p.fs.w_q) / (1 << SCALE_RED);
4434 		idle = s * 3. / w_q;
4435 		p.fs.lookup_step = (int)idle / lookup_depth;
4436 		if (!p.fs.lookup_step)
4437 			p.fs.lookup_step = 1;
4438 		weight = 1 - w_q;
4439 		for (t = p.fs.lookup_step; t > 1; --t)
4440 			weight *= 1 - w_q;
4441 		p.fs.lookup_weight = (int)(weight * (1 << SCALE_RED));
4442 	}
4443 	i = do_cmd(IP_DUMMYNET_CONFIGURE, &p, sizeof p);
4444 	if (i)
4445 		err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
4446 }
4447 
4448 static void
4449 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
4450 {
4451 	int i, l;
4452 	char *ap, *ptr, *optr;
4453 	struct ether_addr *mac;
4454 	const char *macset = "0123456789abcdefABCDEF:";
4455 
4456 	if (strcmp(p, "any") == 0) {
4457 		for (i = 0; i < ETHER_ADDR_LEN; i++)
4458 			addr[i] = mask[i] = 0;
4459 		return;
4460 	}
4461 
4462 	optr = ptr = strdup(p);
4463 	if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
4464 		l = strlen(ap);
4465 		if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
4466 			errx(EX_DATAERR, "Incorrect MAC address");
4467 		bcopy(mac, addr, ETHER_ADDR_LEN);
4468 	} else
4469 		errx(EX_DATAERR, "Incorrect MAC address");
4470 
4471 	if (ptr != NULL) { /* we have mask? */
4472 		if (p[ptr - optr - 1] == '/') { /* mask len */
4473 			l = strtol(ptr, &ap, 10);
4474 			if (*ap != 0 || l > ETHER_ADDR_LEN * 8 || l < 0)
4475 				errx(EX_DATAERR, "Incorrect mask length");
4476 			for (i = 0; l > 0 && i < ETHER_ADDR_LEN; l -= 8, i++)
4477 				mask[i] = (l >= 8) ? 0xff: (~0) << (8 - l);
4478 		} else { /* mask */
4479 			l = strlen(ptr);
4480 			if (strspn(ptr, macset) != l ||
4481 			    (mac = ether_aton(ptr)) == NULL)
4482 				errx(EX_DATAERR, "Incorrect mask");
4483 			bcopy(mac, mask, ETHER_ADDR_LEN);
4484 		}
4485 	} else { /* default mask: ff:ff:ff:ff:ff:ff */
4486 		for (i = 0; i < ETHER_ADDR_LEN; i++)
4487 			mask[i] = 0xff;
4488 	}
4489 	for (i = 0; i < ETHER_ADDR_LEN; i++)
4490 		addr[i] &= mask[i];
4491 
4492 	free(optr);
4493 }
4494 
4495 /*
4496  * helper function, updates the pointer to cmd with the length
4497  * of the current command, and also cleans up the first word of
4498  * the new command in case it has been clobbered before.
4499  */
4500 static ipfw_insn *
4501 next_cmd(ipfw_insn *cmd)
4502 {
4503 	cmd += F_LEN(cmd);
4504 	bzero(cmd, sizeof(*cmd));
4505 	return cmd;
4506 }
4507 
4508 /*
4509  * Takes arguments and copies them into a comment
4510  */
4511 static void
4512 fill_comment(ipfw_insn *cmd, int ac, char **av)
4513 {
4514 	int i, l;
4515 	char *p = (char *)(cmd + 1);
4516 
4517 	cmd->opcode = O_NOP;
4518 	cmd->len =  (cmd->len & (F_NOT | F_OR));
4519 
4520 	/* Compute length of comment string. */
4521 	for (i = 0, l = 0; i < ac; i++)
4522 		l += strlen(av[i]) + 1;
4523 	if (l == 0)
4524 		return;
4525 	if (l > 84)
4526 		errx(EX_DATAERR,
4527 		    "comment too long (max 80 chars)");
4528 	l = 1 + (l+3)/4;
4529 	cmd->len =  (cmd->len & (F_NOT | F_OR)) | l;
4530 	for (i = 0; i < ac; i++) {
4531 		strcpy(p, av[i]);
4532 		p += strlen(av[i]);
4533 		*p++ = ' ';
4534 	}
4535 	*(--p) = '\0';
4536 }
4537 
4538 /*
4539  * A function to fill simple commands of size 1.
4540  * Existing flags are preserved.
4541  */
4542 static void
4543 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
4544 {
4545 	cmd->opcode = opcode;
4546 	cmd->len =  ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
4547 	cmd->arg1 = arg;
4548 }
4549 
4550 /*
4551  * Fetch and add the MAC address and type, with masks. This generates one or
4552  * two microinstructions, and returns the pointer to the last one.
4553  */
4554 static ipfw_insn *
4555 add_mac(ipfw_insn *cmd, int ac, char *av[])
4556 {
4557 	ipfw_insn_mac *mac;
4558 
4559 	if (ac < 2)
4560 		errx(EX_DATAERR, "MAC dst src");
4561 
4562 	cmd->opcode = O_MACADDR2;
4563 	cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
4564 
4565 	mac = (ipfw_insn_mac *)cmd;
4566 	get_mac_addr_mask(av[0], mac->addr, mac->mask);	/* dst */
4567 	get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
4568 	    &(mac->mask[ETHER_ADDR_LEN])); /* src */
4569 	return cmd;
4570 }
4571 
4572 static ipfw_insn *
4573 add_mactype(ipfw_insn *cmd, int ac, char *av)
4574 {
4575 	if (ac < 1)
4576 		errx(EX_DATAERR, "missing MAC type");
4577 	if (strcmp(av, "any") != 0) { /* we have a non-null type */
4578 		fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE);
4579 		cmd->opcode = O_MAC_TYPE;
4580 		return cmd;
4581 	} else
4582 		return NULL;
4583 }
4584 
4585 static ipfw_insn *
4586 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
4587 {
4588 	struct protoent *pe;
4589 	char *ep;
4590 	int proto;
4591 
4592 	proto = strtol(av, &ep, 10);
4593 	if (*ep != '\0' || proto <= 0) {
4594 		if ((pe = getprotobyname(av)) == NULL)
4595 			return NULL;
4596 		proto = pe->p_proto;
4597 	}
4598 
4599 	fill_cmd(cmd, O_PROTO, 0, proto);
4600 	*protop = proto;
4601 	return cmd;
4602 }
4603 
4604 static ipfw_insn *
4605 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
4606 {
4607 	u_char proto = IPPROTO_IP;
4608 
4609 	if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
4610 		; /* do not set O_IP4 nor O_IP6 */
4611 	else if (strcmp(av, "ip4") == 0)
4612 		/* explicit "just IPv4" rule */
4613 		fill_cmd(cmd, O_IP4, 0, 0);
4614 	else if (strcmp(av, "ip6") == 0) {
4615 		/* explicit "just IPv6" rule */
4616 		proto = IPPROTO_IPV6;
4617 		fill_cmd(cmd, O_IP6, 0, 0);
4618 	} else
4619 		return add_proto0(cmd, av, protop);
4620 
4621 	*protop = proto;
4622 	return cmd;
4623 }
4624 
4625 static ipfw_insn *
4626 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
4627 {
4628 	u_char proto = IPPROTO_IP;
4629 
4630 	if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
4631 		; /* do not set O_IP4 nor O_IP6 */
4632 	else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
4633 		/* explicit "just IPv4" rule */
4634 		fill_cmd(cmd, O_IP4, 0, 0);
4635 	else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
4636 		/* explicit "just IPv6" rule */
4637 		proto = IPPROTO_IPV6;
4638 		fill_cmd(cmd, O_IP6, 0, 0);
4639 	} else
4640 		return add_proto0(cmd, av, protop);
4641 
4642 	*protop = proto;
4643 	return cmd;
4644 }
4645 
4646 static ipfw_insn *
4647 add_srcip(ipfw_insn *cmd, char *av)
4648 {
4649 	fill_ip((ipfw_insn_ip *)cmd, av);
4650 	if (cmd->opcode == O_IP_DST_SET)			/* set */
4651 		cmd->opcode = O_IP_SRC_SET;
4652 	else if (cmd->opcode == O_IP_DST_LOOKUP)		/* table */
4653 		cmd->opcode = O_IP_SRC_LOOKUP;
4654 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))		/* me */
4655 		cmd->opcode = O_IP_SRC_ME;
4656 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))	/* one IP */
4657 		cmd->opcode = O_IP_SRC;
4658 	else							/* addr/mask */
4659 		cmd->opcode = O_IP_SRC_MASK;
4660 	return cmd;
4661 }
4662 
4663 static ipfw_insn *
4664 add_dstip(ipfw_insn *cmd, char *av)
4665 {
4666 	fill_ip((ipfw_insn_ip *)cmd, av);
4667 	if (cmd->opcode == O_IP_DST_SET)			/* set */
4668 		;
4669 	else if (cmd->opcode == O_IP_DST_LOOKUP)		/* table */
4670 		;
4671 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))		/* me */
4672 		cmd->opcode = O_IP_DST_ME;
4673 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))	/* one IP */
4674 		cmd->opcode = O_IP_DST;
4675 	else							/* addr/mask */
4676 		cmd->opcode = O_IP_DST_MASK;
4677 	return cmd;
4678 }
4679 
4680 static ipfw_insn *
4681 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode)
4682 {
4683 	if (_substrcmp(av, "any") == 0) {
4684 		return NULL;
4685 	} else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) {
4686 		/* XXX todo: check that we have a protocol with ports */
4687 		cmd->opcode = opcode;
4688 		return cmd;
4689 	}
4690 	return NULL;
4691 }
4692 
4693 static ipfw_insn *
4694 add_src(ipfw_insn *cmd, char *av, u_char proto)
4695 {
4696 	struct in6_addr a;
4697 	char *host, *ch;
4698 	ipfw_insn *ret = NULL;
4699 
4700 	if ((host = strdup(av)) == NULL)
4701 		return NULL;
4702 	if ((ch = strrchr(host, '/')) != NULL)
4703 		*ch = '\0';
4704 
4705 	if (proto == IPPROTO_IPV6  || strcmp(av, "me6") == 0 ||
4706 	    inet_pton(AF_INET6, host, &a))
4707 		ret = add_srcip6(cmd, av);
4708 	/* XXX: should check for IPv4, not !IPv6 */
4709 	if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
4710 	    !inet_pton(AF_INET6, host, &a)))
4711 		ret = add_srcip(cmd, av);
4712 	if (ret == NULL && strcmp(av, "any") != 0)
4713 		ret = cmd;
4714 
4715 	free(host);
4716 	return ret;
4717 }
4718 
4719 static ipfw_insn *
4720 add_dst(ipfw_insn *cmd, char *av, u_char proto)
4721 {
4722 	struct in6_addr a;
4723 	char *host, *ch;
4724 	ipfw_insn *ret = NULL;
4725 
4726 	if ((host = strdup(av)) == NULL)
4727 		return NULL;
4728 	if ((ch = strrchr(host, '/')) != NULL)
4729 		*ch = '\0';
4730 
4731 	if (proto == IPPROTO_IPV6  || strcmp(av, "me6") == 0 ||
4732 	    inet_pton(AF_INET6, host, &a))
4733 		ret = add_dstip6(cmd, av);
4734 	/* XXX: should check for IPv4, not !IPv6 */
4735 	if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
4736 	    !inet_pton(AF_INET6, host, &a)))
4737 		ret = add_dstip(cmd, av);
4738 	if (ret == NULL && strcmp(av, "any") != 0)
4739 		ret = cmd;
4740 
4741 	free(host);
4742 	return ret;
4743 }
4744 
4745 /*
4746  * Parse arguments and assemble the microinstructions which make up a rule.
4747  * Rules are added into the 'rulebuf' and then copied in the correct order
4748  * into the actual rule.
4749  *
4750  * The syntax for a rule starts with the action, followed by
4751  * optional action parameters, and the various match patterns.
4752  * In the assembled microcode, the first opcode must be an O_PROBE_STATE
4753  * (generated if the rule includes a keep-state option), then the
4754  * various match patterns, log/altq actions, and the actual action.
4755  *
4756  */
4757 static void
4758 add(int ac, char *av[])
4759 {
4760 	/*
4761 	 * rules are added into the 'rulebuf' and then copied in
4762 	 * the correct order into the actual rule.
4763 	 * Some things that need to go out of order (prob, action etc.)
4764 	 * go into actbuf[].
4765 	 */
4766 	static uint32_t rulebuf[255], actbuf[255], cmdbuf[255];
4767 
4768 	ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
4769 	ipfw_insn *first_cmd;	/* first match pattern */
4770 
4771 	struct ip_fw *rule;
4772 
4773 	/*
4774 	 * various flags used to record that we entered some fields.
4775 	 */
4776 	ipfw_insn *have_state = NULL;	/* check-state or keep-state */
4777 	ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
4778 	size_t len;
4779 
4780 	int i;
4781 
4782 	int open_par = 0;	/* open parenthesis ( */
4783 
4784 	/* proto is here because it is used to fetch ports */
4785 	u_char proto = IPPROTO_IP;	/* default protocol */
4786 
4787 	double match_prob = 1; /* match probability, default is always match */
4788 
4789 	bzero(actbuf, sizeof(actbuf));		/* actions go here */
4790 	bzero(cmdbuf, sizeof(cmdbuf));
4791 	bzero(rulebuf, sizeof(rulebuf));
4792 
4793 	rule = (struct ip_fw *)rulebuf;
4794 	cmd = (ipfw_insn *)cmdbuf;
4795 	action = (ipfw_insn *)actbuf;
4796 
4797 	av++; ac--;
4798 
4799 	/* [rule N]	-- Rule number optional */
4800 	if (ac && isdigit(**av)) {
4801 		rule->rulenum = atoi(*av);
4802 		av++;
4803 		ac--;
4804 	}
4805 
4806 	/* [set N]	-- set number (0..RESVD_SET), optional */
4807 	if (ac > 1 && _substrcmp(*av, "set") == 0) {
4808 		int set = strtoul(av[1], NULL, 10);
4809 		if (set < 0 || set > RESVD_SET)
4810 			errx(EX_DATAERR, "illegal set %s", av[1]);
4811 		rule->set = set;
4812 		av += 2; ac -= 2;
4813 	}
4814 
4815 	/* [prob D]	-- match probability, optional */
4816 	if (ac > 1 && _substrcmp(*av, "prob") == 0) {
4817 		match_prob = strtod(av[1], NULL);
4818 
4819 		if (match_prob <= 0 || match_prob > 1)
4820 			errx(EX_DATAERR, "illegal match prob. %s", av[1]);
4821 		av += 2; ac -= 2;
4822 	}
4823 
4824 	/* action	-- mandatory */
4825 	NEED1("missing action");
4826 	i = match_token(rule_actions, *av);
4827 	ac--; av++;
4828 	action->len = 1;	/* default */
4829 	switch(i) {
4830 	case TOK_CHECKSTATE:
4831 		have_state = action;
4832 		action->opcode = O_CHECK_STATE;
4833 		break;
4834 
4835 	case TOK_ACCEPT:
4836 		action->opcode = O_ACCEPT;
4837 		break;
4838 
4839 	case TOK_DENY:
4840 		action->opcode = O_DENY;
4841 		action->arg1 = 0;
4842 		break;
4843 
4844 	case TOK_REJECT:
4845 		action->opcode = O_REJECT;
4846 		action->arg1 = ICMP_UNREACH_HOST;
4847 		break;
4848 
4849 	case TOK_RESET:
4850 		action->opcode = O_REJECT;
4851 		action->arg1 = ICMP_REJECT_RST;
4852 		break;
4853 
4854 	case TOK_RESET6:
4855 		action->opcode = O_UNREACH6;
4856 		action->arg1 = ICMP6_UNREACH_RST;
4857 		break;
4858 
4859 	case TOK_UNREACH:
4860 		action->opcode = O_REJECT;
4861 		NEED1("missing reject code");
4862 		fill_reject_code(&action->arg1, *av);
4863 		ac--; av++;
4864 		break;
4865 
4866 	case TOK_UNREACH6:
4867 		action->opcode = O_UNREACH6;
4868 		NEED1("missing unreach code");
4869 		fill_unreach6_code(&action->arg1, *av);
4870 		ac--; av++;
4871 		break;
4872 
4873 	case TOK_COUNT:
4874 		action->opcode = O_COUNT;
4875 		break;
4876 
4877 	case TOK_NAT:
4878  		action->opcode = O_NAT;
4879  		action->len = F_INSN_SIZE(ipfw_insn_nat);
4880 		goto chkarg;
4881 
4882 	case TOK_QUEUE:
4883 		action->opcode = O_QUEUE;
4884 		goto chkarg;
4885 	case TOK_PIPE:
4886 		action->opcode = O_PIPE;
4887 		goto chkarg;
4888 	case TOK_SKIPTO:
4889 		action->opcode = O_SKIPTO;
4890 		goto chkarg;
4891 	case TOK_NETGRAPH:
4892 		action->opcode = O_NETGRAPH;
4893 		goto chkarg;
4894 	case TOK_NGTEE:
4895 		action->opcode = O_NGTEE;
4896 		goto chkarg;
4897 	case TOK_DIVERT:
4898 		action->opcode = O_DIVERT;
4899 		goto chkarg;
4900 	case TOK_TEE:
4901 		action->opcode = O_TEE;
4902 chkarg:
4903 		if (!ac)
4904 			errx(EX_USAGE, "missing argument for %s", *(av - 1));
4905 		if (isdigit(**av)) {
4906 			action->arg1 = strtoul(*av, NULL, 10);
4907 			if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
4908 				errx(EX_DATAERR, "illegal argument for %s",
4909 				    *(av - 1));
4910 		} else if (_substrcmp(*av, TABLEARG) == 0) {
4911 			action->arg1 = IP_FW_TABLEARG;
4912 		} else if (i == TOK_DIVERT || i == TOK_TEE) {
4913 			struct servent *s;
4914 			setservent(1);
4915 			s = getservbyname(av[0], "divert");
4916 			if (s != NULL)
4917 				action->arg1 = ntohs(s->s_port);
4918 			else
4919 				errx(EX_DATAERR, "illegal divert/tee port");
4920 		} else
4921 			errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
4922 		ac--; av++;
4923 		break;
4924 
4925 	case TOK_FORWARD: {
4926 		ipfw_insn_sa *p = (ipfw_insn_sa *)action;
4927 		char *s, *end;
4928 
4929 		NEED1("missing forward address[:port]");
4930 
4931 		action->opcode = O_FORWARD_IP;
4932 		action->len = F_INSN_SIZE(ipfw_insn_sa);
4933 
4934 		p->sa.sin_len = sizeof(struct sockaddr_in);
4935 		p->sa.sin_family = AF_INET;
4936 		p->sa.sin_port = 0;
4937 		/*
4938 		 * locate the address-port separator (':' or ',')
4939 		 */
4940 		s = strchr(*av, ':');
4941 		if (s == NULL)
4942 			s = strchr(*av, ',');
4943 		if (s != NULL) {
4944 			*(s++) = '\0';
4945 			i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
4946 			if (s == end)
4947 				errx(EX_DATAERR,
4948 				    "illegal forwarding port ``%s''", s);
4949 			p->sa.sin_port = (u_short)i;
4950 		}
4951 		if (_substrcmp(*av, "tablearg") == 0)
4952 			p->sa.sin_addr.s_addr = INADDR_ANY;
4953 		else
4954 			lookup_host(*av, &(p->sa.sin_addr));
4955 		ac--; av++;
4956 		break;
4957 	    }
4958 	case TOK_COMMENT:
4959 		/* pretend it is a 'count' rule followed by the comment */
4960 		action->opcode = O_COUNT;
4961 		ac++; av--;	/* go back... */
4962 		break;
4963 
4964 	case TOK_SETFIB:
4965 	    {
4966 		int numfibs;
4967 		size_t intsize = sizeof(int);
4968 
4969 		action->opcode = O_SETFIB;
4970  		NEED1("missing fib number");
4971  	        action->arg1 = strtoul(*av, NULL, 10);
4972 		if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
4973 			errx(EX_DATAERR, "fibs not suported.\n");
4974 		if (action->arg1 >= numfibs)  /* Temporary */
4975 			errx(EX_DATAERR, "fib too large.\n");
4976  		ac--; av++;
4977  		break;
4978 	    }
4979 
4980 	default:
4981 		errx(EX_DATAERR, "invalid action %s\n", av[-1]);
4982 	}
4983 	action = next_cmd(action);
4984 
4985 	/*
4986 	 * [altq queuename] -- altq tag, optional
4987 	 * [log [logamount N]]	-- log, optional
4988 	 *
4989 	 * If they exist, it go first in the cmdbuf, but then it is
4990 	 * skipped in the copy section to the end of the buffer.
4991 	 */
4992 	while (ac != 0 && (i = match_token(rule_action_params, *av)) != -1) {
4993 		ac--; av++;
4994 		switch (i) {
4995 		case TOK_LOG:
4996 		    {
4997 			ipfw_insn_log *c = (ipfw_insn_log *)cmd;
4998 			int l;
4999 
5000 			if (have_log)
5001 				errx(EX_DATAERR,
5002 				    "log cannot be specified more than once");
5003 			have_log = (ipfw_insn *)c;
5004 			cmd->len = F_INSN_SIZE(ipfw_insn_log);
5005 			cmd->opcode = O_LOG;
5006 			if (ac && _substrcmp(*av, "logamount") == 0) {
5007 				ac--; av++;
5008 				NEED1("logamount requires argument");
5009 				l = atoi(*av);
5010 				if (l < 0)
5011 					errx(EX_DATAERR,
5012 					    "logamount must be positive");
5013 				c->max_log = l;
5014 				ac--; av++;
5015 			} else {
5016 				len = sizeof(c->max_log);
5017 				if (sysctlbyname("net.inet.ip.fw.verbose_limit",
5018 				    &c->max_log, &len, NULL, 0) == -1)
5019 					errx(1, "sysctlbyname(\"%s\")",
5020 					    "net.inet.ip.fw.verbose_limit");
5021 			}
5022 		    }
5023 			break;
5024 
5025 		case TOK_ALTQ:
5026 		    {
5027 			ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
5028 
5029 			NEED1("missing altq queue name");
5030 			if (have_altq)
5031 				errx(EX_DATAERR,
5032 				    "altq cannot be specified more than once");
5033 			have_altq = (ipfw_insn *)a;
5034 			cmd->len = F_INSN_SIZE(ipfw_insn_altq);
5035 			cmd->opcode = O_ALTQ;
5036 			fill_altq_qid(&a->qid, *av);
5037 			ac--; av++;
5038 		    }
5039 			break;
5040 
5041 		case TOK_TAG:
5042 		case TOK_UNTAG: {
5043 			uint16_t tag;
5044 
5045 			if (have_tag)
5046 				errx(EX_USAGE, "tag and untag cannot be "
5047 				    "specified more than once");
5048 			GET_UINT_ARG(tag, 1, 65534, i, rule_action_params);
5049 			have_tag = cmd;
5050 			fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
5051 			ac--; av++;
5052 			break;
5053 		}
5054 
5055 		default:
5056 			abort();
5057 		}
5058 		cmd = next_cmd(cmd);
5059 	}
5060 
5061 	if (have_state)	/* must be a check-state, we are done */
5062 		goto done;
5063 
5064 #define OR_START(target)					\
5065 	if (ac && (*av[0] == '(' || *av[0] == '{')) {		\
5066 		if (open_par)					\
5067 			errx(EX_USAGE, "nested \"(\" not allowed\n"); \
5068 		prev = NULL;					\
5069 		open_par = 1;					\
5070 		if ( (av[0])[1] == '\0') {			\
5071 			ac--; av++;				\
5072 		} else						\
5073 			(*av)++;				\
5074 	}							\
5075 	target:							\
5076 
5077 
5078 #define	CLOSE_PAR						\
5079 	if (open_par) {						\
5080 		if (ac && (					\
5081 		    strcmp(*av, ")") == 0 ||			\
5082 		    strcmp(*av, "}") == 0)) {			\
5083 			prev = NULL;				\
5084 			open_par = 0;				\
5085 			ac--; av++;				\
5086 		} else						\
5087 			errx(EX_USAGE, "missing \")\"\n");	\
5088 	}
5089 
5090 #define NOT_BLOCK						\
5091 	if (ac && _substrcmp(*av, "not") == 0) {		\
5092 		if (cmd->len & F_NOT)				\
5093 			errx(EX_USAGE, "double \"not\" not allowed\n"); \
5094 		cmd->len |= F_NOT;				\
5095 		ac--; av++;					\
5096 	}
5097 
5098 #define OR_BLOCK(target)					\
5099 	if (ac && _substrcmp(*av, "or") == 0) {		\
5100 		if (prev == NULL || open_par == 0)		\
5101 			errx(EX_DATAERR, "invalid OR block");	\
5102 		prev->len |= F_OR;				\
5103 		ac--; av++;					\
5104 		goto target;					\
5105 	}							\
5106 	CLOSE_PAR;
5107 
5108 	first_cmd = cmd;
5109 
5110 #if 0
5111 	/*
5112 	 * MAC addresses, optional.
5113 	 * If we have this, we skip the part "proto from src to dst"
5114 	 * and jump straight to the option parsing.
5115 	 */
5116 	NOT_BLOCK;
5117 	NEED1("missing protocol");
5118 	if (_substrcmp(*av, "MAC") == 0 ||
5119 	    _substrcmp(*av, "mac") == 0) {
5120 		ac--; av++;	/* the "MAC" keyword */
5121 		add_mac(cmd, ac, av); /* exits in case of errors */
5122 		cmd = next_cmd(cmd);
5123 		ac -= 2; av += 2;	/* dst-mac and src-mac */
5124 		NOT_BLOCK;
5125 		NEED1("missing mac type");
5126 		if (add_mactype(cmd, ac, av[0]))
5127 			cmd = next_cmd(cmd);
5128 		ac--; av++;	/* any or mac-type */
5129 		goto read_options;
5130 	}
5131 #endif
5132 
5133 	/*
5134 	 * protocol, mandatory
5135 	 */
5136     OR_START(get_proto);
5137 	NOT_BLOCK;
5138 	NEED1("missing protocol");
5139 	if (add_proto_compat(cmd, *av, &proto)) {
5140 		av++; ac--;
5141 		if (F_LEN(cmd) != 0) {
5142 			prev = cmd;
5143 			cmd = next_cmd(cmd);
5144 		}
5145 	} else if (first_cmd != cmd) {
5146 		errx(EX_DATAERR, "invalid protocol ``%s''", *av);
5147 	} else
5148 		goto read_options;
5149     OR_BLOCK(get_proto);
5150 
5151 	/*
5152 	 * "from", mandatory
5153 	 */
5154 	if (!ac || _substrcmp(*av, "from") != 0)
5155 		errx(EX_USAGE, "missing ``from''");
5156 	ac--; av++;
5157 
5158 	/*
5159 	 * source IP, mandatory
5160 	 */
5161     OR_START(source_ip);
5162 	NOT_BLOCK;	/* optional "not" */
5163 	NEED1("missing source address");
5164 	if (add_src(cmd, *av, proto)) {
5165 		ac--; av++;
5166 		if (F_LEN(cmd) != 0) {	/* ! any */
5167 			prev = cmd;
5168 			cmd = next_cmd(cmd);
5169 		}
5170 	} else
5171 		errx(EX_USAGE, "bad source address %s", *av);
5172     OR_BLOCK(source_ip);
5173 
5174 	/*
5175 	 * source ports, optional
5176 	 */
5177 	NOT_BLOCK;	/* optional "not" */
5178 	if (ac) {
5179 		if (_substrcmp(*av, "any") == 0 ||
5180 		    add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
5181 			ac--; av++;
5182 			if (F_LEN(cmd) != 0)
5183 				cmd = next_cmd(cmd);
5184 		}
5185 	}
5186 
5187 	/*
5188 	 * "to", mandatory
5189 	 */
5190 	if (!ac || _substrcmp(*av, "to") != 0)
5191 		errx(EX_USAGE, "missing ``to''");
5192 	av++; ac--;
5193 
5194 	/*
5195 	 * destination, mandatory
5196 	 */
5197     OR_START(dest_ip);
5198 	NOT_BLOCK;	/* optional "not" */
5199 	NEED1("missing dst address");
5200 	if (add_dst(cmd, *av, proto)) {
5201 		ac--; av++;
5202 		if (F_LEN(cmd) != 0) {	/* ! any */
5203 			prev = cmd;
5204 			cmd = next_cmd(cmd);
5205 		}
5206 	} else
5207 		errx( EX_USAGE, "bad destination address %s", *av);
5208     OR_BLOCK(dest_ip);
5209 
5210 	/*
5211 	 * dest. ports, optional
5212 	 */
5213 	NOT_BLOCK;	/* optional "not" */
5214 	if (ac) {
5215 		if (_substrcmp(*av, "any") == 0 ||
5216 		    add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
5217 			ac--; av++;
5218 			if (F_LEN(cmd) != 0)
5219 				cmd = next_cmd(cmd);
5220 		}
5221 	}
5222 
5223 read_options:
5224 	if (ac && first_cmd == cmd) {
5225 		/*
5226 		 * nothing specified so far, store in the rule to ease
5227 		 * printout later.
5228 		 */
5229 		 rule->_pad = 1;
5230 	}
5231 	prev = NULL;
5232 	while (ac) {
5233 		char *s;
5234 		ipfw_insn_u32 *cmd32;	/* alias for cmd */
5235 
5236 		s = *av;
5237 		cmd32 = (ipfw_insn_u32 *)cmd;
5238 
5239 		if (*s == '!') {	/* alternate syntax for NOT */
5240 			if (cmd->len & F_NOT)
5241 				errx(EX_USAGE, "double \"not\" not allowed\n");
5242 			cmd->len = F_NOT;
5243 			s++;
5244 		}
5245 		i = match_token(rule_options, s);
5246 		ac--; av++;
5247 		switch(i) {
5248 		case TOK_NOT:
5249 			if (cmd->len & F_NOT)
5250 				errx(EX_USAGE, "double \"not\" not allowed\n");
5251 			cmd->len = F_NOT;
5252 			break;
5253 
5254 		case TOK_OR:
5255 			if (open_par == 0 || prev == NULL)
5256 				errx(EX_USAGE, "invalid \"or\" block\n");
5257 			prev->len |= F_OR;
5258 			break;
5259 
5260 		case TOK_STARTBRACE:
5261 			if (open_par)
5262 				errx(EX_USAGE, "+nested \"(\" not allowed\n");
5263 			open_par = 1;
5264 			break;
5265 
5266 		case TOK_ENDBRACE:
5267 			if (!open_par)
5268 				errx(EX_USAGE, "+missing \")\"\n");
5269 			open_par = 0;
5270 			prev = NULL;
5271         		break;
5272 
5273 		case TOK_IN:
5274 			fill_cmd(cmd, O_IN, 0, 0);
5275 			break;
5276 
5277 		case TOK_OUT:
5278 			cmd->len ^= F_NOT; /* toggle F_NOT */
5279 			fill_cmd(cmd, O_IN, 0, 0);
5280 			break;
5281 
5282 		case TOK_DIVERTED:
5283 			fill_cmd(cmd, O_DIVERTED, 0, 3);
5284 			break;
5285 
5286 		case TOK_DIVERTEDLOOPBACK:
5287 			fill_cmd(cmd, O_DIVERTED, 0, 1);
5288 			break;
5289 
5290 		case TOK_DIVERTEDOUTPUT:
5291 			fill_cmd(cmd, O_DIVERTED, 0, 2);
5292 			break;
5293 
5294 		case TOK_FRAG:
5295 			fill_cmd(cmd, O_FRAG, 0, 0);
5296 			break;
5297 
5298 		case TOK_LAYER2:
5299 			fill_cmd(cmd, O_LAYER2, 0, 0);
5300 			break;
5301 
5302 		case TOK_XMIT:
5303 		case TOK_RECV:
5304 		case TOK_VIA:
5305 			NEED1("recv, xmit, via require interface name"
5306 				" or address");
5307 			fill_iface((ipfw_insn_if *)cmd, av[0]);
5308 			ac--; av++;
5309 			if (F_LEN(cmd) == 0)	/* not a valid address */
5310 				break;
5311 			if (i == TOK_XMIT)
5312 				cmd->opcode = O_XMIT;
5313 			else if (i == TOK_RECV)
5314 				cmd->opcode = O_RECV;
5315 			else if (i == TOK_VIA)
5316 				cmd->opcode = O_VIA;
5317 			break;
5318 
5319 		case TOK_ICMPTYPES:
5320 			NEED1("icmptypes requires list of types");
5321 			fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
5322 			av++; ac--;
5323 			break;
5324 
5325 		case TOK_ICMP6TYPES:
5326 			NEED1("icmptypes requires list of types");
5327 			fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av);
5328 			av++; ac--;
5329 			break;
5330 
5331 		case TOK_IPTTL:
5332 			NEED1("ipttl requires TTL");
5333 			if (strpbrk(*av, "-,")) {
5334 			    if (!add_ports(cmd, *av, 0, O_IPTTL))
5335 				errx(EX_DATAERR, "invalid ipttl %s", *av);
5336 			} else
5337 			    fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
5338 			ac--; av++;
5339 			break;
5340 
5341 		case TOK_IPID:
5342 			NEED1("ipid requires id");
5343 			if (strpbrk(*av, "-,")) {
5344 			    if (!add_ports(cmd, *av, 0, O_IPID))
5345 				errx(EX_DATAERR, "invalid ipid %s", *av);
5346 			} else
5347 			    fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
5348 			ac--; av++;
5349 			break;
5350 
5351 		case TOK_IPLEN:
5352 			NEED1("iplen requires length");
5353 			if (strpbrk(*av, "-,")) {
5354 			    if (!add_ports(cmd, *av, 0, O_IPLEN))
5355 				errx(EX_DATAERR, "invalid ip len %s", *av);
5356 			} else
5357 			    fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
5358 			ac--; av++;
5359 			break;
5360 
5361 		case TOK_IPVER:
5362 			NEED1("ipver requires version");
5363 			fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
5364 			ac--; av++;
5365 			break;
5366 
5367 		case TOK_IPPRECEDENCE:
5368 			NEED1("ipprecedence requires value");
5369 			fill_cmd(cmd, O_IPPRECEDENCE, 0,
5370 			    (strtoul(*av, NULL, 0) & 7) << 5);
5371 			ac--; av++;
5372 			break;
5373 
5374 		case TOK_IPOPTS:
5375 			NEED1("missing argument for ipoptions");
5376 			fill_flags(cmd, O_IPOPT, f_ipopts, *av);
5377 			ac--; av++;
5378 			break;
5379 
5380 		case TOK_IPTOS:
5381 			NEED1("missing argument for iptos");
5382 			fill_flags(cmd, O_IPTOS, f_iptos, *av);
5383 			ac--; av++;
5384 			break;
5385 
5386 		case TOK_UID:
5387 			NEED1("uid requires argument");
5388 		    {
5389 			char *end;
5390 			uid_t uid;
5391 			struct passwd *pwd;
5392 
5393 			cmd->opcode = O_UID;
5394 			uid = strtoul(*av, &end, 0);
5395 			pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
5396 			if (pwd == NULL)
5397 				errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
5398 			cmd32->d[0] = pwd->pw_uid;
5399 			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
5400 			ac--; av++;
5401 		    }
5402 			break;
5403 
5404 		case TOK_GID:
5405 			NEED1("gid requires argument");
5406 		    {
5407 			char *end;
5408 			gid_t gid;
5409 			struct group *grp;
5410 
5411 			cmd->opcode = O_GID;
5412 			gid = strtoul(*av, &end, 0);
5413 			grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
5414 			if (grp == NULL)
5415 				errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
5416 			cmd32->d[0] = grp->gr_gid;
5417 			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
5418 			ac--; av++;
5419 		    }
5420 			break;
5421 
5422 		case TOK_JAIL:
5423 			NEED1("jail requires argument");
5424 		    {
5425 			char *end;
5426 			int jid;
5427 
5428 			cmd->opcode = O_JAIL;
5429 			jid = (int)strtol(*av, &end, 0);
5430 			if (jid < 0 || *end != '\0')
5431 				errx(EX_DATAERR, "jail requires prison ID");
5432 			cmd32->d[0] = (uint32_t)jid;
5433 			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
5434 			ac--; av++;
5435 		    }
5436 			break;
5437 
5438 		case TOK_ESTAB:
5439 			fill_cmd(cmd, O_ESTAB, 0, 0);
5440 			break;
5441 
5442 		case TOK_SETUP:
5443 			fill_cmd(cmd, O_TCPFLAGS, 0,
5444 				(TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
5445 			break;
5446 
5447 		case TOK_TCPDATALEN:
5448 			NEED1("tcpdatalen requires length");
5449 			if (strpbrk(*av, "-,")) {
5450 			    if (!add_ports(cmd, *av, 0, O_TCPDATALEN))
5451 				errx(EX_DATAERR, "invalid tcpdata len %s", *av);
5452 			} else
5453 			    fill_cmd(cmd, O_TCPDATALEN, 0,
5454 				    strtoul(*av, NULL, 0));
5455 			ac--; av++;
5456 			break;
5457 
5458 		case TOK_TCPOPTS:
5459 			NEED1("missing argument for tcpoptions");
5460 			fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
5461 			ac--; av++;
5462 			break;
5463 
5464 		case TOK_TCPSEQ:
5465 		case TOK_TCPACK:
5466 			NEED1("tcpseq/tcpack requires argument");
5467 			cmd->len = F_INSN_SIZE(ipfw_insn_u32);
5468 			cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
5469 			cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
5470 			ac--; av++;
5471 			break;
5472 
5473 		case TOK_TCPWIN:
5474 			NEED1("tcpwin requires length");
5475 			fill_cmd(cmd, O_TCPWIN, 0,
5476 			    htons(strtoul(*av, NULL, 0)));
5477 			ac--; av++;
5478 			break;
5479 
5480 		case TOK_TCPFLAGS:
5481 			NEED1("missing argument for tcpflags");
5482 			cmd->opcode = O_TCPFLAGS;
5483 			fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
5484 			ac--; av++;
5485 			break;
5486 
5487 		case TOK_KEEPSTATE:
5488 			if (open_par)
5489 				errx(EX_USAGE, "keep-state cannot be part "
5490 				    "of an or block");
5491 			if (have_state)
5492 				errx(EX_USAGE, "only one of keep-state "
5493 					"and limit is allowed");
5494 			have_state = cmd;
5495 			fill_cmd(cmd, O_KEEP_STATE, 0, 0);
5496 			break;
5497 
5498 		case TOK_LIMIT: {
5499 			ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
5500 			int val;
5501 
5502 			if (open_par)
5503 				errx(EX_USAGE,
5504 				    "limit cannot be part of an or block");
5505 			if (have_state)
5506 				errx(EX_USAGE, "only one of keep-state and "
5507 				    "limit is allowed");
5508 			have_state = cmd;
5509 
5510 			cmd->len = F_INSN_SIZE(ipfw_insn_limit);
5511 			cmd->opcode = O_LIMIT;
5512 			c->limit_mask = c->conn_limit = 0;
5513 
5514 			while (ac > 0) {
5515 				if ((val = match_token(limit_masks, *av)) <= 0)
5516 					break;
5517 				c->limit_mask |= val;
5518 				ac--; av++;
5519 			}
5520 
5521 			if (c->limit_mask == 0)
5522 				errx(EX_USAGE, "limit: missing limit mask");
5523 
5524 			GET_UINT_ARG(c->conn_limit, 1, 65534, TOK_LIMIT,
5525 			    rule_options);
5526 
5527 			ac--; av++;
5528 			break;
5529 		}
5530 
5531 		case TOK_PROTO:
5532 			NEED1("missing protocol");
5533 			if (add_proto(cmd, *av, &proto)) {
5534 				ac--; av++;
5535 			} else
5536 				errx(EX_DATAERR, "invalid protocol ``%s''",
5537 				    *av);
5538 			break;
5539 
5540 		case TOK_SRCIP:
5541 			NEED1("missing source IP");
5542 			if (add_srcip(cmd, *av)) {
5543 				ac--; av++;
5544 			}
5545 			break;
5546 
5547 		case TOK_DSTIP:
5548 			NEED1("missing destination IP");
5549 			if (add_dstip(cmd, *av)) {
5550 				ac--; av++;
5551 			}
5552 			break;
5553 
5554 		case TOK_SRCIP6:
5555 			NEED1("missing source IP6");
5556 			if (add_srcip6(cmd, *av)) {
5557 				ac--; av++;
5558 			}
5559 			break;
5560 
5561 		case TOK_DSTIP6:
5562 			NEED1("missing destination IP6");
5563 			if (add_dstip6(cmd, *av)) {
5564 				ac--; av++;
5565 			}
5566 			break;
5567 
5568 		case TOK_SRCPORT:
5569 			NEED1("missing source port");
5570 			if (_substrcmp(*av, "any") == 0 ||
5571 			    add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
5572 				ac--; av++;
5573 			} else
5574 				errx(EX_DATAERR, "invalid source port %s", *av);
5575 			break;
5576 
5577 		case TOK_DSTPORT:
5578 			NEED1("missing destination port");
5579 			if (_substrcmp(*av, "any") == 0 ||
5580 			    add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
5581 				ac--; av++;
5582 			} else
5583 				errx(EX_DATAERR, "invalid destination port %s",
5584 				    *av);
5585 			break;
5586 
5587 		case TOK_MAC:
5588 			if (add_mac(cmd, ac, av)) {
5589 				ac -= 2; av += 2;
5590 			}
5591 			break;
5592 
5593 		case TOK_MACTYPE:
5594 			NEED1("missing mac type");
5595 			if (!add_mactype(cmd, ac, *av))
5596 				errx(EX_DATAERR, "invalid mac type %s", *av);
5597 			ac--; av++;
5598 			break;
5599 
5600 		case TOK_VERREVPATH:
5601 			fill_cmd(cmd, O_VERREVPATH, 0, 0);
5602 			break;
5603 
5604 		case TOK_VERSRCREACH:
5605 			fill_cmd(cmd, O_VERSRCREACH, 0, 0);
5606 			break;
5607 
5608 		case TOK_ANTISPOOF:
5609 			fill_cmd(cmd, O_ANTISPOOF, 0, 0);
5610 			break;
5611 
5612 		case TOK_IPSEC:
5613 			fill_cmd(cmd, O_IPSEC, 0, 0);
5614 			break;
5615 
5616 		case TOK_IPV6:
5617 			fill_cmd(cmd, O_IP6, 0, 0);
5618 			break;
5619 
5620 		case TOK_IPV4:
5621 			fill_cmd(cmd, O_IP4, 0, 0);
5622 			break;
5623 
5624 		case TOK_EXT6HDR:
5625 			fill_ext6hdr( cmd, *av );
5626 			ac--; av++;
5627 			break;
5628 
5629 		case TOK_FLOWID:
5630 			if (proto != IPPROTO_IPV6 )
5631 				errx( EX_USAGE, "flow-id filter is active "
5632 				    "only for ipv6 protocol\n");
5633 			fill_flow6( (ipfw_insn_u32 *) cmd, *av );
5634 			ac--; av++;
5635 			break;
5636 
5637 		case TOK_COMMENT:
5638 			fill_comment(cmd, ac, av);
5639 			av += ac;
5640 			ac = 0;
5641 			break;
5642 
5643 		case TOK_TAGGED:
5644 			if (ac > 0 && strpbrk(*av, "-,")) {
5645 				if (!add_ports(cmd, *av, 0, O_TAGGED))
5646 					errx(EX_DATAERR, "tagged: invalid tag"
5647 					    " list: %s", *av);
5648 			}
5649 			else {
5650 				uint16_t tag;
5651 
5652 				GET_UINT_ARG(tag, 1, 65534, TOK_TAGGED,
5653 				    rule_options);
5654 				fill_cmd(cmd, O_TAGGED, 0, tag);
5655 			}
5656 			ac--; av++;
5657 			break;
5658 
5659 		case TOK_FIB:
5660 			NEED1("fib requires fib number");
5661 			fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
5662 			ac--; av++;
5663 			break;
5664 
5665 		default:
5666 			errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
5667 		}
5668 		if (F_LEN(cmd) > 0) {	/* prepare to advance */
5669 			prev = cmd;
5670 			cmd = next_cmd(cmd);
5671 		}
5672 	}
5673 
5674 done:
5675 	/*
5676 	 * Now copy stuff into the rule.
5677 	 * If we have a keep-state option, the first instruction
5678 	 * must be a PROBE_STATE (which is generated here).
5679 	 * If we have a LOG option, it was stored as the first command,
5680 	 * and now must be moved to the top of the action part.
5681 	 */
5682 	dst = (ipfw_insn *)rule->cmd;
5683 
5684 	/*
5685 	 * First thing to write into the command stream is the match probability.
5686 	 */
5687 	if (match_prob != 1) { /* 1 means always match */
5688 		dst->opcode = O_PROB;
5689 		dst->len = 2;
5690 		*((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
5691 		dst += dst->len;
5692 	}
5693 
5694 	/*
5695 	 * generate O_PROBE_STATE if necessary
5696 	 */
5697 	if (have_state && have_state->opcode != O_CHECK_STATE) {
5698 		fill_cmd(dst, O_PROBE_STATE, 0, 0);
5699 		dst = next_cmd(dst);
5700 	}
5701 
5702 	/* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
5703 	for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
5704 		i = F_LEN(src);
5705 
5706 		switch (src->opcode) {
5707 		case O_LOG:
5708 		case O_KEEP_STATE:
5709 		case O_LIMIT:
5710 		case O_ALTQ:
5711 		case O_TAG:
5712 			break;
5713 		default:
5714 			bcopy(src, dst, i * sizeof(uint32_t));
5715 			dst += i;
5716 		}
5717 	}
5718 
5719 	/*
5720 	 * put back the have_state command as last opcode
5721 	 */
5722 	if (have_state && have_state->opcode != O_CHECK_STATE) {
5723 		i = F_LEN(have_state);
5724 		bcopy(have_state, dst, i * sizeof(uint32_t));
5725 		dst += i;
5726 	}
5727 	/*
5728 	 * start action section
5729 	 */
5730 	rule->act_ofs = dst - rule->cmd;
5731 
5732 	/* put back O_LOG, O_ALTQ, O_TAG if necessary */
5733 	if (have_log) {
5734 		i = F_LEN(have_log);
5735 		bcopy(have_log, dst, i * sizeof(uint32_t));
5736 		dst += i;
5737 	}
5738 	if (have_altq) {
5739 		i = F_LEN(have_altq);
5740 		bcopy(have_altq, dst, i * sizeof(uint32_t));
5741 		dst += i;
5742 	}
5743 	if (have_tag) {
5744 		i = F_LEN(have_tag);
5745 		bcopy(have_tag, dst, i * sizeof(uint32_t));
5746 		dst += i;
5747 	}
5748 	/*
5749 	 * copy all other actions
5750 	 */
5751 	for (src = (ipfw_insn *)actbuf; src != action; src += i) {
5752 		i = F_LEN(src);
5753 		bcopy(src, dst, i * sizeof(uint32_t));
5754 		dst += i;
5755 	}
5756 
5757 	rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
5758 	i = (char *)dst - (char *)rule;
5759 	if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1)
5760 		err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
5761 	if (!do_quiet)
5762 		show_ipfw(rule, 0, 0);
5763 }
5764 
5765 static void
5766 zero(int ac, char *av[], int optname /* IP_FW_ZERO or IP_FW_RESETLOG */)
5767 {
5768 	uint32_t arg, saved_arg;
5769 	int failed = EX_OK;
5770 	char const *name = optname == IP_FW_ZERO ?  "ZERO" : "RESETLOG";
5771 	char const *errstr;
5772 
5773 	av++; ac--;
5774 
5775 	if (!ac) {
5776 		/* clear all entries */
5777 		if (do_cmd(optname, NULL, 0) < 0)
5778 			err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name);
5779 		if (!do_quiet)
5780 			printf("%s.\n", optname == IP_FW_ZERO ?
5781 			    "Accounting cleared":"Logging counts reset");
5782 
5783 		return;
5784 	}
5785 
5786 	while (ac) {
5787 		/* Rule number */
5788 		if (isdigit(**av)) {
5789 			arg = strtonum(*av, 0, 0xffff, &errstr);
5790 			if (errstr)
5791 				errx(EX_DATAERR,
5792 				    "invalid rule number %s\n", *av);
5793 			saved_arg = arg;
5794 			if (use_set)
5795 				arg |= (1 << 24) | ((use_set - 1) << 16);
5796 			av++;
5797 			ac--;
5798 			if (do_cmd(optname, &arg, sizeof(arg))) {
5799 				warn("rule %u: setsockopt(IP_FW_%s)",
5800 				    saved_arg, name);
5801 				failed = EX_UNAVAILABLE;
5802 			} else if (!do_quiet)
5803 				printf("Entry %d %s.\n", saved_arg,
5804 				    optname == IP_FW_ZERO ?
5805 					"cleared" : "logging count reset");
5806 		} else {
5807 			errx(EX_USAGE, "invalid rule number ``%s''", *av);
5808 		}
5809 	}
5810 	if (failed != EX_OK)
5811 		exit(failed);
5812 }
5813 
5814 static void
5815 flush(int force)
5816 {
5817 	int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
5818 
5819 	if (!force && !do_quiet) { /* need to ask user */
5820 		int c;
5821 
5822 		printf("Are you sure? [yn] ");
5823 		fflush(stdout);
5824 		do {
5825 			c = toupper(getc(stdin));
5826 			while (c != '\n' && getc(stdin) != '\n')
5827 				if (feof(stdin))
5828 					return; /* and do not flush */
5829 		} while (c != 'Y' && c != 'N');
5830 		printf("\n");
5831 		if (c == 'N')	/* user said no */
5832 			return;
5833 	}
5834 	/* `ipfw set N flush` - is the same that `ipfw delete set N` */
5835 	if (use_set) {
5836 		uint32_t arg = ((use_set - 1) & 0xffff) | (1 << 24);
5837 		if (do_cmd(IP_FW_DEL, &arg, sizeof(arg)) < 0)
5838 			err(EX_UNAVAILABLE, "setsockopt(IP_FW_DEL)");
5839 	} else if (do_cmd(cmd, NULL, 0) < 0)
5840 		err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
5841 		    do_pipe ? "DUMMYNET" : "FW");
5842 	if (!do_quiet)
5843 		printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules");
5844 }
5845 
5846 /*
5847  * Free a the (locally allocated) copy of command line arguments.
5848  */
5849 static void
5850 free_args(int ac, char **av)
5851 {
5852 	int i;
5853 
5854 	for (i=0; i < ac; i++)
5855 		free(av[i]);
5856 	free(av);
5857 }
5858 
5859 /*
5860  * This one handles all table-related commands
5861  * 	ipfw table N add addr[/masklen] [value]
5862  * 	ipfw table N delete addr[/masklen]
5863  * 	ipfw table N flush
5864  * 	ipfw table N list
5865  */
5866 static void
5867 table_handler(int ac, char *av[])
5868 {
5869 	ipfw_table_entry ent;
5870 	ipfw_table *tbl;
5871 	int do_add;
5872 	char *p;
5873 	socklen_t l;
5874 	uint32_t a;
5875 
5876 	ac--; av++;
5877 	if (ac && isdigit(**av)) {
5878 		ent.tbl = atoi(*av);
5879 		ac--; av++;
5880 	} else
5881 		errx(EX_USAGE, "table number required");
5882 	NEED1("table needs command");
5883 	if (_substrcmp(*av, "add") == 0 ||
5884 	    _substrcmp(*av, "delete") == 0) {
5885 		do_add = **av == 'a';
5886 		ac--; av++;
5887 		if (!ac)
5888 			errx(EX_USAGE, "IP address required");
5889 		p = strchr(*av, '/');
5890 		if (p) {
5891 			*p++ = '\0';
5892 			ent.masklen = atoi(p);
5893 			if (ent.masklen > 32)
5894 				errx(EX_DATAERR, "bad width ``%s''", p);
5895 		} else
5896 			ent.masklen = 32;
5897 		if (lookup_host(*av, (struct in_addr *)&ent.addr) != 0)
5898 			errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
5899 		ac--; av++;
5900 		if (do_add && ac) {
5901 			unsigned int tval;
5902 			/* isdigit is a bit of a hack here.. */
5903 			if (strchr(*av, (int)'.') == NULL && isdigit(**av))  {
5904 				ent.value = strtoul(*av, NULL, 0);
5905 			} else {
5906 		        	if (lookup_host(*av, (struct in_addr *)&tval) == 0) {
5907 					/* The value must be stored in host order	 *
5908 					 * so that the values < 65k can be distinguished */
5909 		       			ent.value = ntohl(tval);
5910 				} else {
5911 					errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
5912 				}
5913 			}
5914 		} else
5915 			ent.value = 0;
5916 		if (do_cmd(do_add ? IP_FW_TABLE_ADD : IP_FW_TABLE_DEL,
5917 		    &ent, sizeof(ent)) < 0) {
5918 			/* If running silent, don't bomb out on these errors. */
5919 			if (!(do_quiet && (errno == (do_add ? EEXIST : ESRCH))))
5920 				err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)",
5921 				    do_add ? "ADD" : "DEL");
5922 			/* In silent mode, react to a failed add by deleting */
5923 			if (do_add) {
5924 				do_cmd(IP_FW_TABLE_DEL, &ent, sizeof(ent));
5925 				if (do_cmd(IP_FW_TABLE_ADD,
5926 				    &ent, sizeof(ent)) < 0)
5927 					err(EX_OSERR,
5928 				            "setsockopt(IP_FW_TABLE_ADD)");
5929 			}
5930 		}
5931 	} else if (_substrcmp(*av, "flush") == 0) {
5932 		if (do_cmd(IP_FW_TABLE_FLUSH, &ent.tbl, sizeof(ent.tbl)) < 0)
5933 			err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)");
5934 	} else if (_substrcmp(*av, "list") == 0) {
5935 		a = ent.tbl;
5936 		l = sizeof(a);
5937 		if (do_cmd(IP_FW_TABLE_GETSIZE, &a, (uintptr_t)&l) < 0)
5938 			err(EX_OSERR, "getsockopt(IP_FW_TABLE_GETSIZE)");
5939 		l = sizeof(*tbl) + a * sizeof(ipfw_table_entry);
5940 		tbl = malloc(l);
5941 		if (tbl == NULL)
5942 			err(EX_OSERR, "malloc");
5943 		tbl->tbl = ent.tbl;
5944 		if (do_cmd(IP_FW_TABLE_LIST, tbl, (uintptr_t)&l) < 0)
5945 			err(EX_OSERR, "getsockopt(IP_FW_TABLE_LIST)");
5946 		for (a = 0; a < tbl->cnt; a++) {
5947 			unsigned int tval;
5948 			tval = tbl->ent[a].value;
5949 			if (do_value_as_ip) {
5950 			    char tbuf[128];
5951 			    strncpy(tbuf, inet_ntoa(*(struct in_addr *)
5952 				&tbl->ent[a].addr), 127);
5953 			    /* inet_ntoa expects network order */
5954 			    tval = htonl(tval);
5955 			    printf("%s/%u %s\n", tbuf, tbl->ent[a].masklen,
5956 			        inet_ntoa(*(struct in_addr *)&tval));
5957 			} else {
5958 			    printf("%s/%u %u\n",
5959 			        inet_ntoa(*(struct in_addr *)&tbl->ent[a].addr),
5960 			        tbl->ent[a].masklen, tval);
5961 			}
5962 		}
5963 	} else
5964 		errx(EX_USAGE, "invalid table command %s", *av);
5965 }
5966 
5967 static void
5968 show_nat(int ac, char **av) {
5969 	struct cfg_nat *n;
5970 	struct cfg_redir *e;
5971 	int cmd, i, nbytes, do_cfg, do_rule, frule, lrule, nalloc, size;
5972 	int nat_cnt, redir_cnt, r;
5973 	uint8_t *data, *p;
5974 	char **lav, *endptr;
5975 
5976 	do_rule = 0;
5977 	nalloc = 1024;
5978 	size = 0;
5979 	data = NULL;
5980 	frule = 0;
5981 	lrule = 65535; /* max ipfw rule number */
5982 	ac--; av++;
5983 
5984 	/* Parse parameters. */
5985 	for (cmd = IP_FW_NAT_GET_LOG, do_cfg = 0; ac != 0; ac--, av++) {
5986 		if (!strncmp(av[0], "config", strlen(av[0]))) {
5987 			cmd = IP_FW_NAT_GET_CONFIG, do_cfg = 1;
5988 			continue;
5989 		}
5990 		/* Convert command line rule #. */
5991 		frule = lrule = strtoul(av[0], &endptr, 10);
5992 		if (*endptr == '-')
5993 			lrule = strtoul(endptr+1, &endptr, 10);
5994 		if (lrule == 0)
5995 			err(EX_USAGE, "invalid rule number: %s", av[0]);
5996 		do_rule = 1;
5997 	}
5998 
5999 	nbytes = nalloc;
6000 	while (nbytes >= nalloc) {
6001 		nalloc = nalloc * 2;
6002 		nbytes = nalloc;
6003 		if ((data = realloc(data, nbytes)) == NULL)
6004 			err(EX_OSERR, "realloc");
6005 		if (do_cmd(cmd, data, (uintptr_t)&nbytes) < 0)
6006 			err(EX_OSERR, "getsockopt(IP_FW_GET_%s)",
6007 			    (cmd == IP_FW_NAT_GET_LOG) ? "LOG" : "CONFIG");
6008 	}
6009 	if (nbytes == 0)
6010 		exit(0);
6011 	if (do_cfg) {
6012 		nat_cnt = *((int *)data);
6013 		for (i = sizeof(nat_cnt); nat_cnt; nat_cnt--) {
6014 			n = (struct cfg_nat *)&data[i];
6015 			if (frule <= n->id && lrule >= n->id)
6016 				print_nat_config(&data[i]);
6017 			i += sizeof(struct cfg_nat);
6018 			for (redir_cnt = 0; redir_cnt < n->redir_cnt; redir_cnt++) {
6019 				e = (struct cfg_redir *)&data[i];
6020 				i += sizeof(struct cfg_redir) + e->spool_cnt *
6021 				    sizeof(struct cfg_spool);
6022 			}
6023 		}
6024 	} else {
6025 		for (i = 0; 1; i += LIBALIAS_BUF_SIZE + sizeof(int)) {
6026 			p = &data[i];
6027 			if (p == data + nbytes)
6028 				break;
6029 			bcopy(p, &r, sizeof(int));
6030 			if (do_rule) {
6031 				if (!(frule <= r && lrule >= r))
6032 					continue;
6033 			}
6034 			printf("nat %u: %s\n", r, p+sizeof(int));
6035 		}
6036 	}
6037 }
6038 
6039 /*
6040  * Called with the arguments (excluding program name).
6041  * Returns 0 if successful, 1 if empty command, errx() in case of errors.
6042  */
6043 static int
6044 ipfw_main(int oldac, char **oldav)
6045 {
6046 	int ch, ac, save_ac;
6047 	const char *errstr;
6048 	char **av, **save_av;
6049 	int do_acct = 0;		/* Show packet/byte count */
6050 
6051 #define WHITESP		" \t\f\v\n\r"
6052 	if (oldac == 0)
6053 		return 1;
6054 	else if (oldac == 1) {
6055 		/*
6056 		 * If we are called with a single string, try to split it into
6057 		 * arguments for subsequent parsing.
6058 		 * But first, remove spaces after a ',', by copying the string
6059 		 * in-place.
6060 		 */
6061 		char *arg = oldav[0];	/* The string... */
6062 		int l = strlen(arg);
6063 		int copy = 0;		/* 1 if we need to copy, 0 otherwise */
6064 		int i, j;
6065 		for (i = j = 0; i < l; i++) {
6066 			if (arg[i] == '#')	/* comment marker */
6067 				break;
6068 			if (copy) {
6069 				arg[j++] = arg[i];
6070 				copy = !index("," WHITESP, arg[i]);
6071 			} else {
6072 				copy = !index(WHITESP, arg[i]);
6073 				if (copy)
6074 					arg[j++] = arg[i];
6075 			}
6076 		}
6077 		if (!copy && j > 0)	/* last char was a 'blank', remove it */
6078 			j--;
6079 		l = j;			/* the new argument length */
6080 		arg[j++] = '\0';
6081 		if (l == 0)		/* empty string! */
6082 			return 1;
6083 
6084 		/*
6085 		 * First, count number of arguments. Because of the previous
6086 		 * processing, this is just the number of blanks plus 1.
6087 		 */
6088 		for (i = 0, ac = 1; i < l; i++)
6089 			if (index(WHITESP, arg[i]) != NULL)
6090 				ac++;
6091 
6092 		av = calloc(ac, sizeof(char *));
6093 
6094 		/*
6095 		 * Second, copy arguments from cmd[] to av[]. For each one,
6096 		 * j is the initial character, i is the one past the end.
6097 		 */
6098 		for (ac = 0, i = j = 0; i < l; i++)
6099 			if (index(WHITESP, arg[i]) != NULL || i == l-1) {
6100 				if (i == l-1)
6101 					i++;
6102 				av[ac] = calloc(i-j+1, 1);
6103 				bcopy(arg+j, av[ac], i-j);
6104 				ac++;
6105 				j = i + 1;
6106 			}
6107 	} else {
6108 		/*
6109 		 * If an argument ends with ',' join with the next one.
6110 		 */
6111 		int first, i, l;
6112 
6113 		av = calloc(oldac, sizeof(char *));
6114 		for (first = i = ac = 0, l = 0; i < oldac; i++) {
6115 			char *arg = oldav[i];
6116 			int k = strlen(arg);
6117 
6118 			l += k;
6119 			if (arg[k-1] != ',' || i == oldac-1) {
6120 				/* Time to copy. */
6121 				av[ac] = calloc(l+1, 1);
6122 				for (l=0; first <= i; first++) {
6123 					strcat(av[ac]+l, oldav[first]);
6124 					l += strlen(oldav[first]);
6125 				}
6126 				ac++;
6127 				l = 0;
6128 				first = i+1;
6129 			}
6130 		}
6131 	}
6132 
6133 	/* Set the force flag for non-interactive processes */
6134 	if (!do_force)
6135 		do_force = !isatty(STDIN_FILENO);
6136 
6137 	/* Save arguments for final freeing of memory. */
6138 	save_ac = ac;
6139 	save_av = av;
6140 
6141 	optind = optreset = 0;
6142 	while ((ch = getopt(ac, av, "abcdefhinNqs:STtv")) != -1)
6143 		switch (ch) {
6144 		case 'a':
6145 			do_acct = 1;
6146 			break;
6147 
6148 		case 'b':
6149 			comment_only = 1;
6150 			do_compact = 1;
6151 			break;
6152 
6153 		case 'c':
6154 			do_compact = 1;
6155 			break;
6156 
6157 		case 'd':
6158 			do_dynamic = 1;
6159 			break;
6160 
6161 		case 'e':
6162 			do_expired = 1;
6163 			break;
6164 
6165 		case 'f':
6166 			do_force = 1;
6167 			break;
6168 
6169 		case 'h': /* help */
6170 			free_args(save_ac, save_av);
6171 			help();
6172 			break;	/* NOTREACHED */
6173 
6174 		case 'i':
6175 			do_value_as_ip = 1;
6176 			break;
6177 
6178 		case 'n':
6179 			test_only = 1;
6180 			break;
6181 
6182 		case 'N':
6183 			do_resolv = 1;
6184 			break;
6185 
6186 		case 'q':
6187 			do_quiet = 1;
6188 			break;
6189 
6190 		case 's': /* sort */
6191 			do_sort = atoi(optarg);
6192 			break;
6193 
6194 		case 'S':
6195 			show_sets = 1;
6196 			break;
6197 
6198 		case 't':
6199 			do_time = 1;
6200 			break;
6201 
6202 		case 'T':
6203 			do_time = 2;	/* numeric timestamp */
6204 			break;
6205 
6206 		case 'v': /* verbose */
6207 			verbose = 1;
6208 			break;
6209 
6210 		default:
6211 			free_args(save_ac, save_av);
6212 			return 1;
6213 		}
6214 
6215 	ac -= optind;
6216 	av += optind;
6217 	NEED1("bad arguments, for usage summary ``ipfw''");
6218 
6219 	/*
6220 	 * An undocumented behaviour of ipfw1 was to allow rule numbers first,
6221 	 * e.g. "100 add allow ..." instead of "add 100 allow ...".
6222 	 * In case, swap first and second argument to get the normal form.
6223 	 */
6224 	if (ac > 1 && isdigit(*av[0])) {
6225 		char *p = av[0];
6226 
6227 		av[0] = av[1];
6228 		av[1] = p;
6229 	}
6230 
6231 	/*
6232 	 * Optional: pipe, queue or nat.
6233 	 */
6234 	do_nat = 0;
6235 	do_pipe = 0;
6236 	if (!strncmp(*av, "nat", strlen(*av)))
6237  	        do_nat = 1;
6238  	else if (!strncmp(*av, "pipe", strlen(*av)))
6239 		do_pipe = 1;
6240 	else if (_substrcmp(*av, "queue") == 0)
6241 		do_pipe = 2;
6242 	else if (!strncmp(*av, "set", strlen(*av))) {
6243 		if (ac > 1 && isdigit(av[1][0])) {
6244 			use_set = strtonum(av[1], 0, RESVD_SET, &errstr);
6245 			if (errstr)
6246 				errx(EX_DATAERR,
6247 				    "invalid set number %s\n", av[1]);
6248 			ac -= 2; av += 2; use_set++;
6249 		}
6250 	}
6251 
6252 	if (do_pipe || do_nat) {
6253 		ac--;
6254 		av++;
6255 	}
6256 	NEED1("missing command");
6257 
6258 	/*
6259 	 * For pipes, queues and nats we normally say 'nat|pipe NN config'
6260 	 * but the code is easier to parse as 'nat|pipe config NN'
6261 	 * so we swap the two arguments.
6262 	 */
6263 	if ((do_pipe || do_nat) && ac > 1 && isdigit(*av[0])) {
6264 		char *p = av[0];
6265 
6266 		av[0] = av[1];
6267 		av[1] = p;
6268 	}
6269 
6270 	int try_next = 0;
6271 	if (use_set == 0) {
6272 		if (_substrcmp(*av, "add") == 0)
6273 			add(ac, av);
6274 		else if (do_nat && _substrcmp(*av, "show") == 0)
6275  			show_nat(ac, av);
6276 		else if (do_pipe && _substrcmp(*av, "config") == 0)
6277 			config_pipe(ac, av);
6278 		else if (do_nat && _substrcmp(*av, "config") == 0)
6279  			config_nat(ac, av);
6280 		else if (_substrcmp(*av, "set") == 0)
6281 			sets_handler(ac, av);
6282 		else if (_substrcmp(*av, "table") == 0)
6283 			table_handler(ac, av);
6284 		else if (_substrcmp(*av, "enable") == 0)
6285 			sysctl_handler(ac, av, 1);
6286 		else if (_substrcmp(*av, "disable") == 0)
6287 			sysctl_handler(ac, av, 0);
6288 		else
6289 			try_next = 1;
6290 	}
6291 
6292 	if (use_set || try_next) {
6293 		if (_substrcmp(*av, "delete") == 0)
6294 			delete(ac, av);
6295 		else if (_substrcmp(*av, "flush") == 0)
6296 			flush(do_force);
6297 		else if (_substrcmp(*av, "zero") == 0)
6298 			zero(ac, av, IP_FW_ZERO);
6299 		else if (_substrcmp(*av, "resetlog") == 0)
6300 			zero(ac, av, IP_FW_RESETLOG);
6301 		else if (_substrcmp(*av, "print") == 0 ||
6302 		         _substrcmp(*av, "list") == 0)
6303 			list(ac, av, do_acct);
6304 		else if (_substrcmp(*av, "show") == 0)
6305 			list(ac, av, 1 /* show counters */);
6306 		else
6307 			errx(EX_USAGE, "bad command `%s'", *av);
6308 	}
6309 
6310 	/* Free memory allocated in the argument parsing. */
6311 	free_args(save_ac, save_av);
6312 	return 0;
6313 }
6314 
6315 
6316 static void
6317 ipfw_readfile(int ac, char *av[])
6318 {
6319 #define MAX_ARGS	32
6320 	char	buf[BUFSIZ];
6321 	char	*cmd = NULL, *filename = av[ac-1];
6322 	int	c, lineno=0;
6323 	FILE	*f = NULL;
6324 	pid_t	preproc = 0;
6325 
6326 	filename = av[ac-1];
6327 
6328 	while ((c = getopt(ac, av, "cfNnp:qS")) != -1) {
6329 		switch(c) {
6330 		case 'c':
6331 			do_compact = 1;
6332 			break;
6333 
6334 		case 'f':
6335 			do_force = 1;
6336 			break;
6337 
6338 		case 'N':
6339 			do_resolv = 1;
6340 			break;
6341 
6342 		case 'n':
6343 			test_only = 1;
6344 			break;
6345 
6346 		case 'p':
6347 			cmd = optarg;
6348 			/*
6349 			 * Skip previous args and delete last one, so we
6350 			 * pass all but the last argument to the preprocessor
6351 			 * via av[optind-1]
6352 			 */
6353 			av += optind - 1;
6354 			ac -= optind - 1;
6355 			if (ac < 2)
6356 				errx(EX_USAGE, "no filename argument");
6357 			av[ac-1] = NULL;
6358 			fprintf(stderr, "command is %s\n", av[0]);
6359 			break;
6360 
6361 		case 'q':
6362 			do_quiet = 1;
6363 			break;
6364 
6365 		case 'S':
6366 			show_sets = 1;
6367 			break;
6368 
6369 		default:
6370 			errx(EX_USAGE, "bad arguments, for usage"
6371 			     " summary ``ipfw''");
6372 		}
6373 
6374 		if (cmd != NULL)
6375 			break;
6376 	}
6377 
6378 	if (cmd == NULL && ac != optind + 1) {
6379 		fprintf(stderr, "ac %d, optind %d\n", ac, optind);
6380 		errx(EX_USAGE, "extraneous filename arguments");
6381 	}
6382 
6383 	if ((f = fopen(filename, "r")) == NULL)
6384 		err(EX_UNAVAILABLE, "fopen: %s", filename);
6385 
6386 	if (cmd != NULL) {			/* pipe through preprocessor */
6387 		int pipedes[2];
6388 
6389 		if (pipe(pipedes) == -1)
6390 			err(EX_OSERR, "cannot create pipe");
6391 
6392 		preproc = fork();
6393 		if (preproc == -1)
6394 			err(EX_OSERR, "cannot fork");
6395 
6396 		if (preproc == 0) {
6397 			/*
6398 			 * Child, will run the preprocessor with the
6399 			 * file on stdin and the pipe on stdout.
6400 			 */
6401 			if (dup2(fileno(f), 0) == -1
6402 			    || dup2(pipedes[1], 1) == -1)
6403 				err(EX_OSERR, "dup2()");
6404 			fclose(f);
6405 			close(pipedes[1]);
6406 			close(pipedes[0]);
6407 			execvp(cmd, av);
6408 			err(EX_OSERR, "execvp(%s) failed", cmd);
6409 		} else { /* parent, will reopen f as the pipe */
6410 			fclose(f);
6411 			close(pipedes[1]);
6412 			if ((f = fdopen(pipedes[0], "r")) == NULL) {
6413 				int savederrno = errno;
6414 
6415 				(void)kill(preproc, SIGTERM);
6416 				errno = savederrno;
6417 				err(EX_OSERR, "fdopen()");
6418 			}
6419 		}
6420 	}
6421 
6422 	while (fgets(buf, BUFSIZ, f)) {		/* read commands */
6423 		char linename[10];
6424 		char *args[1];
6425 
6426 		lineno++;
6427 		sprintf(linename, "Line %d", lineno);
6428 		setprogname(linename); /* XXX */
6429 		args[0] = buf;
6430 		ipfw_main(1, args);
6431 	}
6432 	fclose(f);
6433 	if (cmd != NULL) {
6434 		int status;
6435 
6436 		if (waitpid(preproc, &status, 0) == -1)
6437 			errx(EX_OSERR, "waitpid()");
6438 		if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
6439 			errx(EX_UNAVAILABLE,
6440 			    "preprocessor exited with status %d",
6441 			    WEXITSTATUS(status));
6442 		else if (WIFSIGNALED(status))
6443 			errx(EX_UNAVAILABLE,
6444 			    "preprocessor exited with signal %d",
6445 			    WTERMSIG(status));
6446 	}
6447 }
6448 
6449 int
6450 main(int ac, char *av[])
6451 {
6452 	/*
6453 	 * If the last argument is an absolute pathname, interpret it
6454 	 * as a file to be preprocessed.
6455 	 */
6456 
6457 	if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0)
6458 		ipfw_readfile(ac, av);
6459 	else {
6460 		if (ipfw_main(ac-1, av+1))
6461 			show_usage();
6462 	}
6463 	return EX_OK;
6464 }
6465