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