xref: /freebsd/sbin/pfctl/pfctl.c (revision d7d962ead0b6e5e8a39202d0590022082bf5bfb6)
1 /*	$OpenBSD: pfctl.c,v 1.278 2008/08/31 20:18:17 jmc Exp $ */
2 
3 /*-
4  * SPDX-License-Identifier: BSD-2-Clause
5  *
6  * Copyright (c) 2001 Daniel Hartmeier
7  * Copyright (c) 2002,2003 Henning Brauer
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  *
14  *    - Redistributions of source code must retain the above copyright
15  *      notice, this list of conditions and the following disclaimer.
16  *    - Redistributions in binary form must reproduce the above
17  *      copyright notice, this list of conditions and the following
18  *      disclaimer in the documentation and/or other materials provided
19  *      with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  *
34  */
35 
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38 
39 #define PFIOC_USE_LATEST
40 
41 #include <sys/types.h>
42 #include <sys/ioctl.h>
43 #include <sys/nv.h>
44 #include <sys/socket.h>
45 #include <sys/stat.h>
46 #include <sys/endian.h>
47 
48 #include <net/if.h>
49 #include <netinet/in.h>
50 #include <net/pfvar.h>
51 #include <arpa/inet.h>
52 #include <net/altq/altq.h>
53 #include <sys/sysctl.h>
54 
55 #include <err.h>
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <libpfctl.h>
59 #include <limits.h>
60 #include <netdb.h>
61 #include <stdint.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <unistd.h>
66 
67 #include "pfctl_parser.h"
68 #include "pfctl.h"
69 
70 void	 usage(void);
71 int	 pfctl_enable(int, int);
72 int	 pfctl_disable(int, int);
73 int	 pfctl_clear_stats(int, int);
74 int	 pfctl_get_skip_ifaces(void);
75 int	 pfctl_check_skip_ifaces(char *);
76 int	 pfctl_adjust_skip_ifaces(struct pfctl *);
77 int	 pfctl_clear_interface_flags(int, int);
78 int	 pfctl_clear_rules(int, int, char *);
79 int	 pfctl_clear_nat(int, int, char *);
80 int	 pfctl_clear_altq(int, int);
81 int	 pfctl_clear_src_nodes(int, int);
82 int	 pfctl_clear_iface_states(int, const char *, int);
83 void	 pfctl_addrprefix(char *, struct pf_addr *);
84 int	 pfctl_kill_src_nodes(int, const char *, int);
85 int	 pfctl_net_kill_states(int, const char *, int);
86 int	 pfctl_gateway_kill_states(int, const char *, int);
87 int	 pfctl_label_kill_states(int, const char *, int);
88 int	 pfctl_id_kill_states(int, const char *, int);
89 void	 pfctl_init_options(struct pfctl *);
90 int	 pfctl_load_options(struct pfctl *);
91 int	 pfctl_load_limit(struct pfctl *, unsigned int, unsigned int);
92 int	 pfctl_load_timeout(struct pfctl *, unsigned int, unsigned int);
93 int	 pfctl_load_debug(struct pfctl *, unsigned int);
94 int	 pfctl_load_logif(struct pfctl *, char *);
95 int	 pfctl_load_hostid(struct pfctl *, u_int32_t);
96 int	 pfctl_load_syncookies(struct pfctl *, u_int8_t);
97 int	 pfctl_get_pool(int, struct pfctl_pool *, u_int32_t, u_int32_t, int,
98 	    char *);
99 void	 pfctl_print_rule_counters(struct pfctl_rule *, int);
100 int	 pfctl_show_rules(int, char *, int, enum pfctl_show, char *, int);
101 int	 pfctl_show_nat(int, int, char *);
102 int	 pfctl_show_src_nodes(int, int);
103 int	 pfctl_show_states(int, const char *, int);
104 int	 pfctl_show_status(int, int);
105 int	 pfctl_show_running(int);
106 int	 pfctl_show_timeouts(int, int);
107 int	 pfctl_show_limits(int, int);
108 void	 pfctl_debug(int, u_int32_t, int);
109 int	 pfctl_test_altqsupport(int, int);
110 int	 pfctl_show_anchors(int, int, char *);
111 int	 pfctl_ruleset_trans(struct pfctl *, char *, struct pfctl_anchor *);
112 int	 pfctl_load_ruleset(struct pfctl *, char *,
113 		struct pfctl_ruleset *, int, int);
114 int	 pfctl_load_rule(struct pfctl *, char *, struct pfctl_rule *, int);
115 const char	*pfctl_lookup_option(char *, const char * const *);
116 
117 static struct pfctl_anchor_global	 pf_anchors;
118 static struct pfctl_anchor	 pf_main_anchor;
119 static struct pfr_buffer skip_b;
120 
121 static const char	*clearopt;
122 static char		*rulesopt;
123 static const char	*showopt;
124 static const char	*debugopt;
125 static char		*anchoropt;
126 static const char	*optiopt = NULL;
127 static const char	*pf_device = "/dev/pf";
128 static char		*ifaceopt;
129 static char		*tableopt;
130 static const char	*tblcmdopt;
131 static int		 src_node_killers;
132 static char		*src_node_kill[2];
133 static int		 state_killers;
134 static char		*state_kill[2];
135 int			 loadopt;
136 int			 altqsupport;
137 
138 int			 dev = -1;
139 static int		 first_title = 1;
140 static int		 labels = 0;
141 
142 #define INDENT(d, o)	do {						\
143 				if (o) {				\
144 					int i;				\
145 					for (i=0; i < d; i++)		\
146 						printf("  ");		\
147 				}					\
148 			} while (0);					\
149 
150 
151 static const struct {
152 	const char	*name;
153 	int		index;
154 } pf_limits[] = {
155 	{ "states",		PF_LIMIT_STATES },
156 	{ "src-nodes",		PF_LIMIT_SRC_NODES },
157 	{ "frags",		PF_LIMIT_FRAGS },
158 	{ "table-entries",	PF_LIMIT_TABLE_ENTRIES },
159 	{ NULL,			0 }
160 };
161 
162 struct pf_hint {
163 	const char	*name;
164 	int		timeout;
165 };
166 static const struct pf_hint pf_hint_normal[] = {
167 	{ "tcp.first",		2 * 60 },
168 	{ "tcp.opening",	30 },
169 	{ "tcp.established",	24 * 60 * 60 },
170 	{ "tcp.closing",	15 * 60 },
171 	{ "tcp.finwait",	45 },
172 	{ "tcp.closed",		90 },
173 	{ "tcp.tsdiff",		30 },
174 	{ NULL,			0 }
175 };
176 static const struct pf_hint pf_hint_satellite[] = {
177 	{ "tcp.first",		3 * 60 },
178 	{ "tcp.opening",	30 + 5 },
179 	{ "tcp.established",	24 * 60 * 60 },
180 	{ "tcp.closing",	15 * 60 + 5 },
181 	{ "tcp.finwait",	45 + 5 },
182 	{ "tcp.closed",		90 + 5 },
183 	{ "tcp.tsdiff",		60 },
184 	{ NULL,			0 }
185 };
186 static const struct pf_hint pf_hint_conservative[] = {
187 	{ "tcp.first",		60 * 60 },
188 	{ "tcp.opening",	15 * 60 },
189 	{ "tcp.established",	5 * 24 * 60 * 60 },
190 	{ "tcp.closing",	60 * 60 },
191 	{ "tcp.finwait",	10 * 60 },
192 	{ "tcp.closed",		3 * 60 },
193 	{ "tcp.tsdiff",		60 },
194 	{ NULL,			0 }
195 };
196 static const struct pf_hint pf_hint_aggressive[] = {
197 	{ "tcp.first",		30 },
198 	{ "tcp.opening",	5 },
199 	{ "tcp.established",	5 * 60 * 60 },
200 	{ "tcp.closing",	60 },
201 	{ "tcp.finwait",	30 },
202 	{ "tcp.closed",		30 },
203 	{ "tcp.tsdiff",		10 },
204 	{ NULL,			0 }
205 };
206 
207 static const struct {
208 	const char *name;
209 	const struct pf_hint *hint;
210 } pf_hints[] = {
211 	{ "normal",		pf_hint_normal },
212 	{ "satellite",		pf_hint_satellite },
213 	{ "high-latency",	pf_hint_satellite },
214 	{ "conservative",	pf_hint_conservative },
215 	{ "aggressive",		pf_hint_aggressive },
216 	{ NULL,			NULL }
217 };
218 
219 static const char * const clearopt_list[] = {
220 	"nat", "queue", "rules", "Sources",
221 	"states", "info", "Tables", "osfp", "all", NULL
222 };
223 
224 static const char * const showopt_list[] = {
225 	"nat", "queue", "rules", "Anchors", "Sources", "states", "info",
226 	"Interfaces", "labels", "timeouts", "memory", "Tables", "osfp",
227 	"Running", "all", NULL
228 };
229 
230 static const char * const tblcmdopt_list[] = {
231 	"kill", "flush", "add", "delete", "load", "replace", "show",
232 	"test", "zero", "expire", NULL
233 };
234 
235 static const char * const debugopt_list[] = {
236 	"none", "urgent", "misc", "loud", NULL
237 };
238 
239 static const char * const optiopt_list[] = {
240 	"none", "basic", "profile", NULL
241 };
242 
243 void
244 usage(void)
245 {
246 	extern char *__progname;
247 
248 	fprintf(stderr,
249 "usage: %s [-AdeghMmNnOPqRrvz] [-a anchor] [-D macro=value] [-F modifier]\n"
250 	"\t[-f file] [-i interface] [-K host | network]\n"
251 	"\t[-k host | network | gateway | label | id] [-o level] [-p device]\n"
252 	"\t[-s modifier] [-t table -T command [address ...]] [-x level]\n",
253 	    __progname);
254 
255 	exit(1);
256 }
257 
258 /*
259  * Cache protocol number to name translations.
260  *
261  * Translation is performed a lot e.g., when dumping states and
262  * getprotobynumber is incredibly expensive.
263  *
264  * Note from the getprotobynumber(3) manpage:
265  * <quote>
266  * These functions use a thread-specific data space; if the data is needed
267  * for future use, it should be copied before any subsequent calls overwrite
268  * it.  Only the Internet protocols are currently understood.
269  * </quote>
270  *
271  * Consequently we only cache the name and strdup it for safety.
272  *
273  * At the time of writing this comment the last entry in /etc/protocols is:
274  * divert  258     DIVERT          # Divert pseudo-protocol [non IANA]
275  */
276 const char *
277 pfctl_proto2name(int proto)
278 {
279 	static const char *pfctl_proto_cache[259];
280 	struct protoent *p;
281 
282 	if (proto >= nitems(pfctl_proto_cache)) {
283 		p = getprotobynumber(proto);
284 		if (p == NULL) {
285 			return (NULL);
286 		}
287 		return (p->p_name);
288 	}
289 
290 	if (pfctl_proto_cache[proto] == NULL) {
291 		p = getprotobynumber(proto);
292 		if (p == NULL) {
293 			return (NULL);
294 		}
295 		pfctl_proto_cache[proto] = strdup(p->p_name);
296 	}
297 
298 	return (pfctl_proto_cache[proto]);
299 }
300 
301 int
302 pfctl_enable(int dev, int opts)
303 {
304 	if (ioctl(dev, DIOCSTART)) {
305 		if (errno == EEXIST)
306 			errx(1, "pf already enabled");
307 		else if (errno == ESRCH)
308 			errx(1, "pfil registeration failed");
309 		else
310 			err(1, "DIOCSTART");
311 	}
312 	if ((opts & PF_OPT_QUIET) == 0)
313 		fprintf(stderr, "pf enabled\n");
314 
315 	if (altqsupport && ioctl(dev, DIOCSTARTALTQ))
316 		if (errno != EEXIST)
317 			err(1, "DIOCSTARTALTQ");
318 
319 	return (0);
320 }
321 
322 int
323 pfctl_disable(int dev, int opts)
324 {
325 	if (ioctl(dev, DIOCSTOP)) {
326 		if (errno == ENOENT)
327 			errx(1, "pf not enabled");
328 		else
329 			err(1, "DIOCSTOP");
330 	}
331 	if ((opts & PF_OPT_QUIET) == 0)
332 		fprintf(stderr, "pf disabled\n");
333 
334 	if (altqsupport && ioctl(dev, DIOCSTOPALTQ))
335 			if (errno != ENOENT)
336 				err(1, "DIOCSTOPALTQ");
337 
338 	return (0);
339 }
340 
341 int
342 pfctl_clear_stats(int dev, int opts)
343 {
344 	if (ioctl(dev, DIOCCLRSTATUS))
345 		err(1, "DIOCCLRSTATUS");
346 	if ((opts & PF_OPT_QUIET) == 0)
347 		fprintf(stderr, "pf: statistics cleared\n");
348 	return (0);
349 }
350 
351 int
352 pfctl_get_skip_ifaces(void)
353 {
354 	bzero(&skip_b, sizeof(skip_b));
355 	skip_b.pfrb_type = PFRB_IFACES;
356 	for (;;) {
357 		pfr_buf_grow(&skip_b, skip_b.pfrb_size);
358 		skip_b.pfrb_size = skip_b.pfrb_msize;
359 		if (pfi_get_ifaces(NULL, skip_b.pfrb_caddr, &skip_b.pfrb_size))
360 			err(1, "pfi_get_ifaces");
361 		if (skip_b.pfrb_size <= skip_b.pfrb_msize)
362 			break;
363 	}
364 	return (0);
365 }
366 
367 int
368 pfctl_check_skip_ifaces(char *ifname)
369 {
370 	struct pfi_kif		*p;
371 	struct node_host	*h = NULL, *n = NULL;
372 
373 	PFRB_FOREACH(p, &skip_b) {
374 		if (!strcmp(ifname, p->pfik_name) &&
375 		    (p->pfik_flags & PFI_IFLAG_SKIP))
376 			p->pfik_flags &= ~PFI_IFLAG_SKIP;
377 		if (!strcmp(ifname, p->pfik_name) && p->pfik_group != NULL) {
378 			if ((h = ifa_grouplookup(p->pfik_name, 0)) == NULL)
379 				continue;
380 
381 			for (n = h; n != NULL; n = n->next) {
382 				if (p->pfik_ifp == NULL)
383 					continue;
384 				if (strncmp(p->pfik_name, ifname, IFNAMSIZ))
385 					continue;
386 
387 				p->pfik_flags &= ~PFI_IFLAG_SKIP;
388 			}
389 		}
390 	}
391 	return (0);
392 }
393 
394 int
395 pfctl_adjust_skip_ifaces(struct pfctl *pf)
396 {
397 	struct pfi_kif		*p, *pp;
398 	struct node_host	*h = NULL, *n = NULL;
399 
400 	PFRB_FOREACH(p, &skip_b) {
401 		if (p->pfik_group == NULL || !(p->pfik_flags & PFI_IFLAG_SKIP))
402 			continue;
403 
404 		pfctl_set_interface_flags(pf, p->pfik_name, PFI_IFLAG_SKIP, 0);
405 		if ((h = ifa_grouplookup(p->pfik_name, 0)) == NULL)
406 			continue;
407 
408 		for (n = h; n != NULL; n = n->next)
409 			PFRB_FOREACH(pp, &skip_b) {
410 				if (pp->pfik_ifp == NULL)
411 					continue;
412 
413 				if (strncmp(pp->pfik_name, n->ifname, IFNAMSIZ))
414 					continue;
415 
416 				if (!(pp->pfik_flags & PFI_IFLAG_SKIP))
417 					pfctl_set_interface_flags(pf,
418 					    pp->pfik_name, PFI_IFLAG_SKIP, 1);
419 				if (pp->pfik_flags & PFI_IFLAG_SKIP)
420 					pp->pfik_flags &= ~PFI_IFLAG_SKIP;
421 			}
422 	}
423 
424 	PFRB_FOREACH(p, &skip_b) {
425 		if (p->pfik_ifp == NULL || ! (p->pfik_flags & PFI_IFLAG_SKIP))
426 			continue;
427 
428 		pfctl_set_interface_flags(pf, p->pfik_name, PFI_IFLAG_SKIP, 0);
429 	}
430 
431 	return (0);
432 }
433 
434 int
435 pfctl_clear_interface_flags(int dev, int opts)
436 {
437 	struct pfioc_iface	pi;
438 
439 	if ((opts & PF_OPT_NOACTION) == 0) {
440 		bzero(&pi, sizeof(pi));
441 		pi.pfiio_flags = PFI_IFLAG_SKIP;
442 
443 		if (ioctl(dev, DIOCCLRIFFLAG, &pi))
444 			err(1, "DIOCCLRIFFLAG");
445 		if ((opts & PF_OPT_QUIET) == 0)
446 			fprintf(stderr, "pf: interface flags reset\n");
447 	}
448 	return (0);
449 }
450 
451 int
452 pfctl_clear_rules(int dev, int opts, char *anchorname)
453 {
454 	struct pfr_buffer t;
455 
456 	memset(&t, 0, sizeof(t));
457 	t.pfrb_type = PFRB_TRANS;
458 	if (pfctl_add_trans(&t, PF_RULESET_SCRUB, anchorname) ||
459 	    pfctl_add_trans(&t, PF_RULESET_FILTER, anchorname) ||
460 	    pfctl_trans(dev, &t, DIOCXBEGIN, 0) ||
461 	    pfctl_trans(dev, &t, DIOCXCOMMIT, 0))
462 		err(1, "pfctl_clear_rules");
463 	if ((opts & PF_OPT_QUIET) == 0)
464 		fprintf(stderr, "rules cleared\n");
465 	return (0);
466 }
467 
468 int
469 pfctl_clear_nat(int dev, int opts, char *anchorname)
470 {
471 	struct pfr_buffer t;
472 
473 	memset(&t, 0, sizeof(t));
474 	t.pfrb_type = PFRB_TRANS;
475 	if (pfctl_add_trans(&t, PF_RULESET_NAT, anchorname) ||
476 	    pfctl_add_trans(&t, PF_RULESET_BINAT, anchorname) ||
477 	    pfctl_add_trans(&t, PF_RULESET_RDR, anchorname) ||
478 	    pfctl_trans(dev, &t, DIOCXBEGIN, 0) ||
479 	    pfctl_trans(dev, &t, DIOCXCOMMIT, 0))
480 		err(1, "pfctl_clear_nat");
481 	if ((opts & PF_OPT_QUIET) == 0)
482 		fprintf(stderr, "nat cleared\n");
483 	return (0);
484 }
485 
486 int
487 pfctl_clear_altq(int dev, int opts)
488 {
489 	struct pfr_buffer t;
490 
491 	if (!altqsupport)
492 		return (-1);
493 	memset(&t, 0, sizeof(t));
494 	t.pfrb_type = PFRB_TRANS;
495 	if (pfctl_add_trans(&t, PF_RULESET_ALTQ, "") ||
496 	    pfctl_trans(dev, &t, DIOCXBEGIN, 0) ||
497 	    pfctl_trans(dev, &t, DIOCXCOMMIT, 0))
498 		err(1, "pfctl_clear_altq");
499 	if ((opts & PF_OPT_QUIET) == 0)
500 		fprintf(stderr, "altq cleared\n");
501 	return (0);
502 }
503 
504 int
505 pfctl_clear_src_nodes(int dev, int opts)
506 {
507 	if (ioctl(dev, DIOCCLRSRCNODES))
508 		err(1, "DIOCCLRSRCNODES");
509 	if ((opts & PF_OPT_QUIET) == 0)
510 		fprintf(stderr, "source tracking entries cleared\n");
511 	return (0);
512 }
513 
514 int
515 pfctl_clear_iface_states(int dev, const char *iface, int opts)
516 {
517 	struct pfctl_kill kill;
518 	unsigned int killed;
519 
520 	memset(&kill, 0, sizeof(kill));
521 	if (iface != NULL && strlcpy(kill.ifname, iface,
522 	    sizeof(kill.ifname)) >= sizeof(kill.ifname))
523 		errx(1, "invalid interface: %s", iface);
524 
525 	if (opts & PF_OPT_KILLMATCH)
526 		kill.kill_match = true;
527 
528 	if (pfctl_clear_states(dev, &kill, &killed))
529 		err(1, "DIOCCLRSTATES");
530 	if ((opts & PF_OPT_QUIET) == 0)
531 		fprintf(stderr, "%d states cleared\n", killed);
532 	return (0);
533 }
534 
535 void
536 pfctl_addrprefix(char *addr, struct pf_addr *mask)
537 {
538 	char *p;
539 	const char *errstr;
540 	int prefix, ret_ga, q, r;
541 	struct addrinfo hints, *res;
542 
543 	if ((p = strchr(addr, '/')) == NULL)
544 		return;
545 
546 	*p++ = '\0';
547 	prefix = strtonum(p, 0, 128, &errstr);
548 	if (errstr)
549 		errx(1, "prefix is %s: %s", errstr, p);
550 
551 	bzero(&hints, sizeof(hints));
552 	/* prefix only with numeric addresses */
553 	hints.ai_flags |= AI_NUMERICHOST;
554 
555 	if ((ret_ga = getaddrinfo(addr, NULL, &hints, &res))) {
556 		errx(1, "getaddrinfo: %s", gai_strerror(ret_ga));
557 		/* NOTREACHED */
558 	}
559 
560 	if (res->ai_family == AF_INET && prefix > 32)
561 		errx(1, "prefix too long for AF_INET");
562 	else if (res->ai_family == AF_INET6 && prefix > 128)
563 		errx(1, "prefix too long for AF_INET6");
564 
565 	q = prefix >> 3;
566 	r = prefix & 7;
567 	switch (res->ai_family) {
568 	case AF_INET:
569 		bzero(&mask->v4, sizeof(mask->v4));
570 		mask->v4.s_addr = htonl((u_int32_t)
571 		    (0xffffffffffULL << (32 - prefix)));
572 		break;
573 	case AF_INET6:
574 		bzero(&mask->v6, sizeof(mask->v6));
575 		if (q > 0)
576 			memset((void *)&mask->v6, 0xff, q);
577 		if (r > 0)
578 			*((u_char *)&mask->v6 + q) =
579 			    (0xff00 >> r) & 0xff;
580 		break;
581 	}
582 	freeaddrinfo(res);
583 }
584 
585 int
586 pfctl_kill_src_nodes(int dev, const char *iface, int opts)
587 {
588 	struct pfioc_src_node_kill psnk;
589 	struct addrinfo *res[2], *resp[2];
590 	struct sockaddr last_src, last_dst;
591 	int killed, sources, dests;
592 	int ret_ga;
593 
594 	killed = sources = dests = 0;
595 
596 	memset(&psnk, 0, sizeof(psnk));
597 	memset(&psnk.psnk_src.addr.v.a.mask, 0xff,
598 	    sizeof(psnk.psnk_src.addr.v.a.mask));
599 	memset(&last_src, 0xff, sizeof(last_src));
600 	memset(&last_dst, 0xff, sizeof(last_dst));
601 
602 	pfctl_addrprefix(src_node_kill[0], &psnk.psnk_src.addr.v.a.mask);
603 
604 	if ((ret_ga = getaddrinfo(src_node_kill[0], NULL, NULL, &res[0]))) {
605 		errx(1, "getaddrinfo: %s", gai_strerror(ret_ga));
606 		/* NOTREACHED */
607 	}
608 	for (resp[0] = res[0]; resp[0]; resp[0] = resp[0]->ai_next) {
609 		if (resp[0]->ai_addr == NULL)
610 			continue;
611 		/* We get lots of duplicates.  Catch the easy ones */
612 		if (memcmp(&last_src, resp[0]->ai_addr, sizeof(last_src)) == 0)
613 			continue;
614 		last_src = *(struct sockaddr *)resp[0]->ai_addr;
615 
616 		psnk.psnk_af = resp[0]->ai_family;
617 		sources++;
618 
619 		if (psnk.psnk_af == AF_INET)
620 			psnk.psnk_src.addr.v.a.addr.v4 =
621 			    ((struct sockaddr_in *)resp[0]->ai_addr)->sin_addr;
622 		else if (psnk.psnk_af == AF_INET6)
623 			psnk.psnk_src.addr.v.a.addr.v6 =
624 			    ((struct sockaddr_in6 *)resp[0]->ai_addr)->
625 			    sin6_addr;
626 		else
627 			errx(1, "Unknown address family %d", psnk.psnk_af);
628 
629 		if (src_node_killers > 1) {
630 			dests = 0;
631 			memset(&psnk.psnk_dst.addr.v.a.mask, 0xff,
632 			    sizeof(psnk.psnk_dst.addr.v.a.mask));
633 			memset(&last_dst, 0xff, sizeof(last_dst));
634 			pfctl_addrprefix(src_node_kill[1],
635 			    &psnk.psnk_dst.addr.v.a.mask);
636 			if ((ret_ga = getaddrinfo(src_node_kill[1], NULL, NULL,
637 			    &res[1]))) {
638 				errx(1, "getaddrinfo: %s",
639 				    gai_strerror(ret_ga));
640 				/* NOTREACHED */
641 			}
642 			for (resp[1] = res[1]; resp[1];
643 			    resp[1] = resp[1]->ai_next) {
644 				if (resp[1]->ai_addr == NULL)
645 					continue;
646 				if (psnk.psnk_af != resp[1]->ai_family)
647 					continue;
648 
649 				if (memcmp(&last_dst, resp[1]->ai_addr,
650 				    sizeof(last_dst)) == 0)
651 					continue;
652 				last_dst = *(struct sockaddr *)resp[1]->ai_addr;
653 
654 				dests++;
655 
656 				if (psnk.psnk_af == AF_INET)
657 					psnk.psnk_dst.addr.v.a.addr.v4 =
658 					    ((struct sockaddr_in *)resp[1]->
659 					    ai_addr)->sin_addr;
660 				else if (psnk.psnk_af == AF_INET6)
661 					psnk.psnk_dst.addr.v.a.addr.v6 =
662 					    ((struct sockaddr_in6 *)resp[1]->
663 					    ai_addr)->sin6_addr;
664 				else
665 					errx(1, "Unknown address family %d",
666 					    psnk.psnk_af);
667 
668 				if (ioctl(dev, DIOCKILLSRCNODES, &psnk))
669 					err(1, "DIOCKILLSRCNODES");
670 				killed += psnk.psnk_killed;
671 			}
672 			freeaddrinfo(res[1]);
673 		} else {
674 			if (ioctl(dev, DIOCKILLSRCNODES, &psnk))
675 				err(1, "DIOCKILLSRCNODES");
676 			killed += psnk.psnk_killed;
677 		}
678 	}
679 
680 	freeaddrinfo(res[0]);
681 
682 	if ((opts & PF_OPT_QUIET) == 0)
683 		fprintf(stderr, "killed %d src nodes from %d sources and %d "
684 		    "destinations\n", killed, sources, dests);
685 	return (0);
686 }
687 
688 int
689 pfctl_net_kill_states(int dev, const char *iface, int opts)
690 {
691 	struct pfctl_kill kill;
692 	struct addrinfo *res[2], *resp[2];
693 	struct sockaddr last_src, last_dst;
694 	unsigned int newkilled;
695 	int killed, sources, dests;
696 	int ret_ga;
697 
698 	killed = sources = dests = 0;
699 
700 	memset(&kill, 0, sizeof(kill));
701 	memset(&kill.src.addr.v.a.mask, 0xff,
702 	    sizeof(kill.src.addr.v.a.mask));
703 	memset(&last_src, 0xff, sizeof(last_src));
704 	memset(&last_dst, 0xff, sizeof(last_dst));
705 	if (iface != NULL && strlcpy(kill.ifname, iface,
706 	    sizeof(kill.ifname)) >= sizeof(kill.ifname))
707 		errx(1, "invalid interface: %s", iface);
708 
709 	pfctl_addrprefix(state_kill[0], &kill.src.addr.v.a.mask);
710 
711 	if (opts & PF_OPT_KILLMATCH)
712 		kill.kill_match = true;
713 
714 	if ((ret_ga = getaddrinfo(state_kill[0], NULL, NULL, &res[0]))) {
715 		errx(1, "getaddrinfo: %s", gai_strerror(ret_ga));
716 		/* NOTREACHED */
717 	}
718 	for (resp[0] = res[0]; resp[0]; resp[0] = resp[0]->ai_next) {
719 		if (resp[0]->ai_addr == NULL)
720 			continue;
721 		/* We get lots of duplicates.  Catch the easy ones */
722 		if (memcmp(&last_src, resp[0]->ai_addr, sizeof(last_src)) == 0)
723 			continue;
724 		last_src = *(struct sockaddr *)resp[0]->ai_addr;
725 
726 		kill.af = resp[0]->ai_family;
727 		sources++;
728 
729 		if (kill.af == AF_INET)
730 			kill.src.addr.v.a.addr.v4 =
731 			    ((struct sockaddr_in *)resp[0]->ai_addr)->sin_addr;
732 		else if (kill.af == AF_INET6)
733 			kill.src.addr.v.a.addr.v6 =
734 			    ((struct sockaddr_in6 *)resp[0]->ai_addr)->
735 			    sin6_addr;
736 		else
737 			errx(1, "Unknown address family %d", kill.af);
738 
739 		if (state_killers > 1) {
740 			dests = 0;
741 			memset(&kill.dst.addr.v.a.mask, 0xff,
742 			    sizeof(kill.dst.addr.v.a.mask));
743 			memset(&last_dst, 0xff, sizeof(last_dst));
744 			pfctl_addrprefix(state_kill[1],
745 			    &kill.dst.addr.v.a.mask);
746 			if ((ret_ga = getaddrinfo(state_kill[1], NULL, NULL,
747 			    &res[1]))) {
748 				errx(1, "getaddrinfo: %s",
749 				    gai_strerror(ret_ga));
750 				/* NOTREACHED */
751 			}
752 			for (resp[1] = res[1]; resp[1];
753 			    resp[1] = resp[1]->ai_next) {
754 				if (resp[1]->ai_addr == NULL)
755 					continue;
756 				if (kill.af != resp[1]->ai_family)
757 					continue;
758 
759 				if (memcmp(&last_dst, resp[1]->ai_addr,
760 				    sizeof(last_dst)) == 0)
761 					continue;
762 				last_dst = *(struct sockaddr *)resp[1]->ai_addr;
763 
764 				dests++;
765 
766 				if (kill.af == AF_INET)
767 					kill.dst.addr.v.a.addr.v4 =
768 					    ((struct sockaddr_in *)resp[1]->
769 					    ai_addr)->sin_addr;
770 				else if (kill.af == AF_INET6)
771 					kill.dst.addr.v.a.addr.v6 =
772 					    ((struct sockaddr_in6 *)resp[1]->
773 					    ai_addr)->sin6_addr;
774 				else
775 					errx(1, "Unknown address family %d",
776 					    kill.af);
777 
778 				if (pfctl_kill_states(dev, &kill, &newkilled))
779 					err(1, "DIOCKILLSTATES");
780 				killed += newkilled;
781 			}
782 			freeaddrinfo(res[1]);
783 		} else {
784 			if (pfctl_kill_states(dev, &kill, &newkilled))
785 				err(1, "DIOCKILLSTATES");
786 			killed += newkilled;
787 		}
788 	}
789 
790 	freeaddrinfo(res[0]);
791 
792 	if ((opts & PF_OPT_QUIET) == 0)
793 		fprintf(stderr, "killed %d states from %d sources and %d "
794 		    "destinations\n", killed, sources, dests);
795 	return (0);
796 }
797 
798 int
799 pfctl_gateway_kill_states(int dev, const char *iface, int opts)
800 {
801 	struct pfctl_kill kill;
802 	struct addrinfo *res, *resp;
803 	struct sockaddr last_src;
804 	unsigned int newkilled;
805 	int killed = 0;
806 	int ret_ga;
807 
808 	if (state_killers != 2 || (strlen(state_kill[1]) == 0)) {
809 		warnx("no gateway specified");
810 		usage();
811 	}
812 
813 	memset(&kill, 0, sizeof(kill));
814 	memset(&kill.rt_addr.addr.v.a.mask, 0xff,
815 	    sizeof(kill.rt_addr.addr.v.a.mask));
816 	memset(&last_src, 0xff, sizeof(last_src));
817 	if (iface != NULL && strlcpy(kill.ifname, iface,
818 	    sizeof(kill.ifname)) >= sizeof(kill.ifname))
819 		errx(1, "invalid interface: %s", iface);
820 
821 	if (opts & PF_OPT_KILLMATCH)
822 		kill.kill_match = true;
823 
824 	pfctl_addrprefix(state_kill[1], &kill.rt_addr.addr.v.a.mask);
825 
826 	if ((ret_ga = getaddrinfo(state_kill[1], NULL, NULL, &res))) {
827 		errx(1, "getaddrinfo: %s", gai_strerror(ret_ga));
828 		/* NOTREACHED */
829 	}
830 	for (resp = res; resp; resp = resp->ai_next) {
831 		if (resp->ai_addr == NULL)
832 			continue;
833 		/* We get lots of duplicates.  Catch the easy ones */
834 		if (memcmp(&last_src, resp->ai_addr, sizeof(last_src)) == 0)
835 			continue;
836 		last_src = *(struct sockaddr *)resp->ai_addr;
837 
838 		kill.af = resp->ai_family;
839 
840 		if (kill.af == AF_INET)
841 			kill.rt_addr.addr.v.a.addr.v4 =
842 			    ((struct sockaddr_in *)resp->ai_addr)->sin_addr;
843 		else if (kill.af == AF_INET6)
844 			kill.rt_addr.addr.v.a.addr.v6 =
845 			    ((struct sockaddr_in6 *)resp->ai_addr)->
846 			    sin6_addr;
847 		else
848 			errx(1, "Unknown address family %d", kill.af);
849 
850 		if (pfctl_kill_states(dev, &kill, &newkilled))
851 			err(1, "DIOCKILLSTATES");
852 		killed += newkilled;
853 	}
854 
855 	freeaddrinfo(res);
856 
857 	if ((opts & PF_OPT_QUIET) == 0)
858 		fprintf(stderr, "killed %d states\n", killed);
859 	return (0);
860 }
861 
862 int
863 pfctl_label_kill_states(int dev, const char *iface, int opts)
864 {
865 	struct pfctl_kill kill;
866 	unsigned int killed;
867 
868 	if (state_killers != 2 || (strlen(state_kill[1]) == 0)) {
869 		warnx("no label specified");
870 		usage();
871 	}
872 	memset(&kill, 0, sizeof(kill));
873 	if (iface != NULL && strlcpy(kill.ifname, iface,
874 	    sizeof(kill.ifname)) >= sizeof(kill.ifname))
875 		errx(1, "invalid interface: %s", iface);
876 
877 	if (opts & PF_OPT_KILLMATCH)
878 		kill.kill_match = true;
879 
880 	if (strlcpy(kill.label, state_kill[1], sizeof(kill.label)) >=
881 	    sizeof(kill.label))
882 		errx(1, "label too long: %s", state_kill[1]);
883 
884 	if (pfctl_kill_states(dev, &kill, &killed))
885 		err(1, "DIOCKILLSTATES");
886 
887 	if ((opts & PF_OPT_QUIET) == 0)
888 		fprintf(stderr, "killed %d states\n", killed);
889 
890 	return (0);
891 }
892 
893 int
894 pfctl_id_kill_states(int dev, const char *iface, int opts)
895 {
896 	struct pfctl_kill kill;
897 	unsigned int killed;
898 
899 	if (state_killers != 2 || (strlen(state_kill[1]) == 0)) {
900 		warnx("no id specified");
901 		usage();
902 	}
903 
904 	memset(&kill, 0, sizeof(kill));
905 
906 	if (opts & PF_OPT_KILLMATCH)
907 		kill.kill_match = true;
908 
909 	if ((sscanf(state_kill[1], "%jx/%x",
910 	    &kill.cmp.id, &kill.cmp.creatorid)) == 2) {
911 	}
912 	else if ((sscanf(state_kill[1], "%jx", &kill.cmp.id)) == 1) {
913 		kill.cmp.creatorid = 0;
914 	} else {
915 		warnx("wrong id format specified");
916 		usage();
917 	}
918 	if (kill.cmp.id == 0) {
919 		warnx("cannot kill id 0");
920 		usage();
921 	}
922 
923 	if (pfctl_kill_states(dev, &kill, &killed))
924 		err(1, "DIOCKILLSTATES");
925 
926 	if ((opts & PF_OPT_QUIET) == 0)
927 		fprintf(stderr, "killed %d states\n", killed);
928 
929 	return (0);
930 }
931 
932 int
933 pfctl_get_pool(int dev, struct pfctl_pool *pool, u_int32_t nr,
934     u_int32_t ticket, int r_action, char *anchorname)
935 {
936 	struct pfioc_pooladdr pp;
937 	struct pf_pooladdr *pa;
938 	u_int32_t pnr, mpnr;
939 
940 	memset(&pp, 0, sizeof(pp));
941 	memcpy(pp.anchor, anchorname, sizeof(pp.anchor));
942 	pp.r_action = r_action;
943 	pp.r_num = nr;
944 	pp.ticket = ticket;
945 	if (ioctl(dev, DIOCGETADDRS, &pp)) {
946 		warn("DIOCGETADDRS");
947 		return (-1);
948 	}
949 	mpnr = pp.nr;
950 	TAILQ_INIT(&pool->list);
951 	for (pnr = 0; pnr < mpnr; ++pnr) {
952 		pp.nr = pnr;
953 		if (ioctl(dev, DIOCGETADDR, &pp)) {
954 			warn("DIOCGETADDR");
955 			return (-1);
956 		}
957 		pa = calloc(1, sizeof(struct pf_pooladdr));
958 		if (pa == NULL)
959 			err(1, "calloc");
960 		bcopy(&pp.addr, pa, sizeof(struct pf_pooladdr));
961 		TAILQ_INSERT_TAIL(&pool->list, pa, entries);
962 	}
963 
964 	return (0);
965 }
966 
967 void
968 pfctl_move_pool(struct pfctl_pool *src, struct pfctl_pool *dst)
969 {
970 	struct pf_pooladdr *pa;
971 
972 	while ((pa = TAILQ_FIRST(&src->list)) != NULL) {
973 		TAILQ_REMOVE(&src->list, pa, entries);
974 		TAILQ_INSERT_TAIL(&dst->list, pa, entries);
975 	}
976 }
977 
978 void
979 pfctl_clear_pool(struct pfctl_pool *pool)
980 {
981 	struct pf_pooladdr *pa;
982 
983 	while ((pa = TAILQ_FIRST(&pool->list)) != NULL) {
984 		TAILQ_REMOVE(&pool->list, pa, entries);
985 		free(pa);
986 	}
987 }
988 
989 void
990 pfctl_print_rule_counters(struct pfctl_rule *rule, int opts)
991 {
992 	if (opts & PF_OPT_DEBUG) {
993 		const char *t[PF_SKIP_COUNT] = { "i", "d", "f",
994 		    "p", "sa", "sp", "da", "dp" };
995 		int i;
996 
997 		printf("  [ Skip steps: ");
998 		for (i = 0; i < PF_SKIP_COUNT; ++i) {
999 			if (rule->skip[i].nr == rule->nr + 1)
1000 				continue;
1001 			printf("%s=", t[i]);
1002 			if (rule->skip[i].nr == -1)
1003 				printf("end ");
1004 			else
1005 				printf("%u ", rule->skip[i].nr);
1006 		}
1007 		printf("]\n");
1008 
1009 		printf("  [ queue: qname=%s qid=%u pqname=%s pqid=%u ]\n",
1010 		    rule->qname, rule->qid, rule->pqname, rule->pqid);
1011 	}
1012 	if (opts & PF_OPT_VERBOSE) {
1013 		printf("  [ Evaluations: %-8llu  Packets: %-8llu  "
1014 			    "Bytes: %-10llu  States: %-6ju]\n",
1015 			    (unsigned long long)rule->evaluations,
1016 			    (unsigned long long)(rule->packets[0] +
1017 			    rule->packets[1]),
1018 			    (unsigned long long)(rule->bytes[0] +
1019 			    rule->bytes[1]), (uintmax_t)rule->states_cur);
1020 		if (!(opts & PF_OPT_DEBUG))
1021 			printf("  [ Inserted: uid %u pid %u "
1022 			    "State Creations: %-6ju]\n",
1023 			    (unsigned)rule->cuid, (unsigned)rule->cpid,
1024 			    (uintmax_t)rule->states_tot);
1025 	}
1026 }
1027 
1028 void
1029 pfctl_print_title(char *title)
1030 {
1031 	if (!first_title)
1032 		printf("\n");
1033 	first_title = 0;
1034 	printf("%s\n", title);
1035 }
1036 
1037 int
1038 pfctl_show_rules(int dev, char *path, int opts, enum pfctl_show format,
1039     char *anchorname, int depth)
1040 {
1041 	struct pfioc_rule pr;
1042 	struct pfctl_rule rule;
1043 	u_int32_t nr, mnr, header = 0;
1044 	int rule_numbers = opts & (PF_OPT_VERBOSE2 | PF_OPT_DEBUG);
1045 	int numeric = opts & PF_OPT_NUMERIC;
1046 	int len = strlen(path);
1047 	int brace;
1048 	char *p;
1049 
1050 	if (path[0])
1051 		snprintf(&path[len], MAXPATHLEN - len, "/%s", anchorname);
1052 	else
1053 		snprintf(&path[len], MAXPATHLEN - len, "%s", anchorname);
1054 
1055 	memset(&pr, 0, sizeof(pr));
1056 	memcpy(pr.anchor, path, sizeof(pr.anchor));
1057 	if (opts & PF_OPT_SHOWALL) {
1058 		pr.rule.action = PF_PASS;
1059 		if (ioctl(dev, DIOCGETRULES, &pr)) {
1060 			warn("DIOCGETRULES");
1061 			goto error;
1062 		}
1063 		header++;
1064 	}
1065 	pr.rule.action = PF_SCRUB;
1066 	if (ioctl(dev, DIOCGETRULES, &pr)) {
1067 		warn("DIOCGETRULES");
1068 		goto error;
1069 	}
1070 	if (opts & PF_OPT_SHOWALL) {
1071 		if (format == PFCTL_SHOW_RULES && (pr.nr > 0 || header))
1072 			pfctl_print_title("FILTER RULES:");
1073 		else if (format == PFCTL_SHOW_LABELS && labels)
1074 			pfctl_print_title("LABEL COUNTERS:");
1075 	}
1076 	mnr = pr.nr;
1077 
1078 	for (nr = 0; nr < mnr; ++nr) {
1079 		pr.nr = nr;
1080 		if (pfctl_get_clear_rule(dev, nr, pr.ticket, path, PF_SCRUB,
1081 		    &rule, pr.anchor_call, opts & PF_OPT_CLRRULECTRS)) {
1082 			warn("DIOCGETRULENV");
1083 			goto error;
1084 		}
1085 
1086 		if (pfctl_get_pool(dev, &rule.rpool,
1087 		    nr, pr.ticket, PF_SCRUB, path) != 0)
1088 			goto error;
1089 
1090 		switch (format) {
1091 		case PFCTL_SHOW_LABELS:
1092 			break;
1093 		case PFCTL_SHOW_RULES:
1094 			if (rule.label[0] && (opts & PF_OPT_SHOWALL))
1095 				labels = 1;
1096 			print_rule(&rule, pr.anchor_call, rule_numbers, numeric);
1097 			printf("\n");
1098 			pfctl_print_rule_counters(&rule, opts);
1099 			break;
1100 		case PFCTL_SHOW_NOTHING:
1101 			break;
1102 		}
1103 		pfctl_clear_pool(&rule.rpool);
1104 	}
1105 	pr.rule.action = PF_PASS;
1106 	if (ioctl(dev, DIOCGETRULES, &pr)) {
1107 		warn("DIOCGETRULES");
1108 		goto error;
1109 	}
1110 	mnr = pr.nr;
1111 	for (nr = 0; nr < mnr; ++nr) {
1112 		pr.nr = nr;
1113 		if (pfctl_get_clear_rule(dev, nr, pr.ticket, path, PF_PASS,
1114 		    &rule, pr.anchor_call, opts & PF_OPT_CLRRULECTRS)) {
1115 			warn("DIOCGETRULE");
1116 			goto error;
1117 		}
1118 
1119 		if (pfctl_get_pool(dev, &rule.rpool,
1120 		    nr, pr.ticket, PF_PASS, path) != 0)
1121 			goto error;
1122 
1123 		switch (format) {
1124 		case PFCTL_SHOW_LABELS: {
1125 			bool show = false;
1126 			int i = 0;
1127 
1128 			while (rule.label[i][0]) {
1129 				printf("%s ", rule.label[i++]);
1130 				show = true;
1131 			}
1132 
1133 			if (show) {
1134 				printf("%llu %llu %llu %llu"
1135 				    " %llu %llu %llu %ju\n",
1136 				    (unsigned long long)rule.evaluations,
1137 				    (unsigned long long)(rule.packets[0] +
1138 				    rule.packets[1]),
1139 				    (unsigned long long)(rule.bytes[0] +
1140 				    rule.bytes[1]),
1141 				    (unsigned long long)rule.packets[0],
1142 				    (unsigned long long)rule.bytes[0],
1143 				    (unsigned long long)rule.packets[1],
1144 				    (unsigned long long)rule.bytes[1],
1145 				    (uintmax_t)rule.states_tot);
1146 			}
1147 			break;
1148 		}
1149 		case PFCTL_SHOW_RULES:
1150 			brace = 0;
1151 			if (rule.label[0] && (opts & PF_OPT_SHOWALL))
1152 				labels = 1;
1153 			INDENT(depth, !(opts & PF_OPT_VERBOSE));
1154 			if (pr.anchor_call[0] &&
1155 			   ((((p = strrchr(pr.anchor_call, '_')) != NULL) &&
1156 			   ((void *)p == (void *)pr.anchor_call ||
1157 			   *(--p) == '/')) || (opts & PF_OPT_RECURSE))) {
1158 				brace++;
1159 				if ((p = strrchr(pr.anchor_call, '/')) !=
1160 				    NULL)
1161 					p++;
1162 				else
1163 					p = &pr.anchor_call[0];
1164 			} else
1165 				p = &pr.anchor_call[0];
1166 
1167 			print_rule(&rule, p, rule_numbers, numeric);
1168 			if (brace)
1169 				printf(" {\n");
1170 			else
1171 				printf("\n");
1172 			pfctl_print_rule_counters(&rule, opts);
1173 			if (brace) {
1174 				pfctl_show_rules(dev, path, opts, format,
1175 				    p, depth + 1);
1176 				INDENT(depth, !(opts & PF_OPT_VERBOSE));
1177 				printf("}\n");
1178 			}
1179 			break;
1180 		case PFCTL_SHOW_NOTHING:
1181 			break;
1182 		}
1183 		pfctl_clear_pool(&rule.rpool);
1184 	}
1185 	path[len] = '\0';
1186 	return (0);
1187 
1188  error:
1189 	path[len] = '\0';
1190 	return (-1);
1191 }
1192 
1193 int
1194 pfctl_show_nat(int dev, int opts, char *anchorname)
1195 {
1196 	struct pfioc_rule pr;
1197 	struct pfctl_rule rule;
1198 	u_int32_t mnr, nr;
1199 	static int nattype[3] = { PF_NAT, PF_RDR, PF_BINAT };
1200 	int i, dotitle = opts & PF_OPT_SHOWALL;
1201 
1202 	memset(&pr, 0, sizeof(pr));
1203 	memcpy(pr.anchor, anchorname, sizeof(pr.anchor));
1204 	for (i = 0; i < 3; i++) {
1205 		pr.rule.action = nattype[i];
1206 		if (ioctl(dev, DIOCGETRULES, &pr)) {
1207 			warn("DIOCGETRULES");
1208 			return (-1);
1209 		}
1210 		mnr = pr.nr;
1211 		for (nr = 0; nr < mnr; ++nr) {
1212 			pr.nr = nr;
1213 			if (pfctl_get_rule(dev, nr, pr.ticket, anchorname,
1214 			    nattype[i], &rule, pr.anchor_call)) {
1215 				warn("DIOCGETRULE");
1216 				return (-1);
1217 			}
1218 			if (pfctl_get_pool(dev, &rule.rpool, nr,
1219 			    pr.ticket, nattype[i], anchorname) != 0)
1220 				return (-1);
1221 			if (dotitle) {
1222 				pfctl_print_title("TRANSLATION RULES:");
1223 				dotitle = 0;
1224 			}
1225 			print_rule(&rule, pr.anchor_call,
1226 			    opts & PF_OPT_VERBOSE2, opts & PF_OPT_NUMERIC);
1227 			printf("\n");
1228 			pfctl_print_rule_counters(&rule, opts);
1229 			pfctl_clear_pool(&rule.rpool);
1230 		}
1231 	}
1232 	return (0);
1233 }
1234 
1235 int
1236 pfctl_show_src_nodes(int dev, int opts)
1237 {
1238 	struct pfioc_src_nodes psn;
1239 	struct pf_src_node *p;
1240 	char *inbuf = NULL, *newinbuf = NULL;
1241 	unsigned int len = 0;
1242 	int i;
1243 
1244 	memset(&psn, 0, sizeof(psn));
1245 	for (;;) {
1246 		psn.psn_len = len;
1247 		if (len) {
1248 			newinbuf = realloc(inbuf, len);
1249 			if (newinbuf == NULL)
1250 				err(1, "realloc");
1251 			psn.psn_buf = inbuf = newinbuf;
1252 		}
1253 		if (ioctl(dev, DIOCGETSRCNODES, &psn) < 0) {
1254 			warn("DIOCGETSRCNODES");
1255 			free(inbuf);
1256 			return (-1);
1257 		}
1258 		if (psn.psn_len + sizeof(struct pfioc_src_nodes) < len)
1259 			break;
1260 		if (len == 0 && psn.psn_len == 0)
1261 			goto done;
1262 		if (len == 0 && psn.psn_len != 0)
1263 			len = psn.psn_len;
1264 		if (psn.psn_len == 0)
1265 			goto done;	/* no src_nodes */
1266 		len *= 2;
1267 	}
1268 	p = psn.psn_src_nodes;
1269 	if (psn.psn_len > 0 && (opts & PF_OPT_SHOWALL))
1270 		pfctl_print_title("SOURCE TRACKING NODES:");
1271 	for (i = 0; i < psn.psn_len; i += sizeof(*p)) {
1272 		print_src_node(p, opts);
1273 		p++;
1274 	}
1275 done:
1276 	free(inbuf);
1277 	return (0);
1278 }
1279 
1280 int
1281 pfctl_show_states(int dev, const char *iface, int opts)
1282 {
1283 	struct pfctl_states states;
1284 	struct pfctl_state *s;
1285 	int dotitle = (opts & PF_OPT_SHOWALL);
1286 
1287 	memset(&states, 0, sizeof(states));
1288 
1289 	if (pfctl_get_states(dev, &states))
1290 		return (-1);
1291 
1292 	TAILQ_FOREACH(s, &states.states, entry) {
1293 		if (iface != NULL && strcmp(s->ifname, iface))
1294 			continue;
1295 		if (dotitle) {
1296 			pfctl_print_title("STATES:");
1297 			dotitle = 0;
1298 		}
1299 		print_state(s, opts);
1300 	}
1301 
1302 	pfctl_free_states(&states);
1303 
1304 	return (0);
1305 }
1306 
1307 int
1308 pfctl_show_status(int dev, int opts)
1309 {
1310 	struct pfctl_status	*status;
1311 	struct pfctl_syncookies	cookies;
1312 
1313 	if ((status = pfctl_get_status(dev)) == NULL) {
1314 		warn("DIOCGETSTATUS");
1315 		return (-1);
1316 	}
1317 	if (pfctl_get_syncookies(dev, &cookies)) {
1318 		pfctl_free_status(status);
1319 		warn("DIOCGETSYNCOOKIES");
1320 		return (-1);
1321 	}
1322 	if (opts & PF_OPT_SHOWALL)
1323 		pfctl_print_title("INFO:");
1324 	print_status(status, &cookies, opts);
1325 	pfctl_free_status(status);
1326 	return (0);
1327 }
1328 
1329 int
1330 pfctl_show_running(int dev)
1331 {
1332 	struct pfctl_status *status;
1333 	int running;
1334 
1335 	if ((status = pfctl_get_status(dev)) == NULL) {
1336 		warn("DIOCGETSTATUS");
1337 		return (-1);
1338 	}
1339 
1340 	running = status->running;
1341 
1342 	print_running(status);
1343 	pfctl_free_status(status);
1344 	return (!running);
1345 }
1346 
1347 int
1348 pfctl_show_timeouts(int dev, int opts)
1349 {
1350 	struct pfioc_tm pt;
1351 	int i;
1352 
1353 	if (opts & PF_OPT_SHOWALL)
1354 		pfctl_print_title("TIMEOUTS:");
1355 	memset(&pt, 0, sizeof(pt));
1356 	for (i = 0; pf_timeouts[i].name; i++) {
1357 		pt.timeout = pf_timeouts[i].timeout;
1358 		if (ioctl(dev, DIOCGETTIMEOUT, &pt))
1359 			err(1, "DIOCGETTIMEOUT");
1360 		printf("%-20s %10d", pf_timeouts[i].name, pt.seconds);
1361 		if (pf_timeouts[i].timeout >= PFTM_ADAPTIVE_START &&
1362 		    pf_timeouts[i].timeout <= PFTM_ADAPTIVE_END)
1363 			printf(" states");
1364 		else
1365 			printf("s");
1366 		printf("\n");
1367 	}
1368 	return (0);
1369 
1370 }
1371 
1372 int
1373 pfctl_show_limits(int dev, int opts)
1374 {
1375 	struct pfioc_limit pl;
1376 	int i;
1377 
1378 	if (opts & PF_OPT_SHOWALL)
1379 		pfctl_print_title("LIMITS:");
1380 	memset(&pl, 0, sizeof(pl));
1381 	for (i = 0; pf_limits[i].name; i++) {
1382 		pl.index = pf_limits[i].index;
1383 		if (ioctl(dev, DIOCGETLIMIT, &pl))
1384 			err(1, "DIOCGETLIMIT");
1385 		printf("%-13s ", pf_limits[i].name);
1386 		if (pl.limit == UINT_MAX)
1387 			printf("unlimited\n");
1388 		else
1389 			printf("hard limit %8u\n", pl.limit);
1390 	}
1391 	return (0);
1392 }
1393 
1394 /* callbacks for rule/nat/rdr/addr */
1395 int
1396 pfctl_add_pool(struct pfctl *pf, struct pfctl_pool *p, sa_family_t af)
1397 {
1398 	struct pf_pooladdr *pa;
1399 
1400 	if ((pf->opts & PF_OPT_NOACTION) == 0) {
1401 		if (ioctl(pf->dev, DIOCBEGINADDRS, &pf->paddr))
1402 			err(1, "DIOCBEGINADDRS");
1403 	}
1404 
1405 	pf->paddr.af = af;
1406 	TAILQ_FOREACH(pa, &p->list, entries) {
1407 		memcpy(&pf->paddr.addr, pa, sizeof(struct pf_pooladdr));
1408 		if ((pf->opts & PF_OPT_NOACTION) == 0) {
1409 			if (ioctl(pf->dev, DIOCADDADDR, &pf->paddr))
1410 				err(1, "DIOCADDADDR");
1411 		}
1412 	}
1413 	return (0);
1414 }
1415 
1416 int
1417 pfctl_append_rule(struct pfctl *pf, struct pfctl_rule *r,
1418     const char *anchor_call)
1419 {
1420 	u_int8_t		rs_num;
1421 	struct pfctl_rule	*rule;
1422 	struct pfctl_ruleset	*rs;
1423 	char 			*p;
1424 
1425 	rs_num = pf_get_ruleset_number(r->action);
1426 	if (rs_num == PF_RULESET_MAX)
1427 		errx(1, "Invalid rule type %d", r->action);
1428 
1429 	rs = &pf->anchor->ruleset;
1430 
1431 	if (anchor_call[0] && r->anchor == NULL) {
1432 		/*
1433 		 * Don't make non-brace anchors part of the main anchor pool.
1434 		 */
1435 		if ((r->anchor = calloc(1, sizeof(*r->anchor))) == NULL)
1436 			err(1, "pfctl_append_rule: calloc");
1437 
1438 		pf_init_ruleset(&r->anchor->ruleset);
1439 		r->anchor->ruleset.anchor = r->anchor;
1440 		if (strlcpy(r->anchor->path, anchor_call,
1441 		    sizeof(rule->anchor->path)) >= sizeof(rule->anchor->path))
1442 			errx(1, "pfctl_append_rule: strlcpy");
1443 		if ((p = strrchr(anchor_call, '/')) != NULL) {
1444 			if (!strlen(p))
1445 				err(1, "pfctl_append_rule: bad anchor name %s",
1446 				    anchor_call);
1447 		} else
1448 			p = (char *)anchor_call;
1449 		if (strlcpy(r->anchor->name, p,
1450 		    sizeof(rule->anchor->name)) >= sizeof(rule->anchor->name))
1451 			errx(1, "pfctl_append_rule: strlcpy");
1452 	}
1453 
1454 	if ((rule = calloc(1, sizeof(*rule))) == NULL)
1455 		err(1, "calloc");
1456 	bcopy(r, rule, sizeof(*rule));
1457 	TAILQ_INIT(&rule->rpool.list);
1458 	pfctl_move_pool(&r->rpool, &rule->rpool);
1459 
1460 	TAILQ_INSERT_TAIL(rs->rules[rs_num].active.ptr, rule, entries);
1461 	return (0);
1462 }
1463 
1464 int
1465 pfctl_ruleset_trans(struct pfctl *pf, char *path, struct pfctl_anchor *a)
1466 {
1467 	int osize = pf->trans->pfrb_size;
1468 
1469 	if ((pf->loadopt & PFCTL_FLAG_NAT) != 0) {
1470 		if (pfctl_add_trans(pf->trans, PF_RULESET_NAT, path) ||
1471 		    pfctl_add_trans(pf->trans, PF_RULESET_BINAT, path) ||
1472 		    pfctl_add_trans(pf->trans, PF_RULESET_RDR, path))
1473 			return (1);
1474 	}
1475 	if (a == pf->astack[0] && ((altqsupport &&
1476 	    (pf->loadopt & PFCTL_FLAG_ALTQ) != 0))) {
1477 		if (pfctl_add_trans(pf->trans, PF_RULESET_ALTQ, path))
1478 			return (2);
1479 	}
1480 	if ((pf->loadopt & PFCTL_FLAG_FILTER) != 0) {
1481 		if (pfctl_add_trans(pf->trans, PF_RULESET_SCRUB, path) ||
1482 		    pfctl_add_trans(pf->trans, PF_RULESET_FILTER, path))
1483 			return (3);
1484 	}
1485 	if (pf->loadopt & PFCTL_FLAG_TABLE)
1486 		if (pfctl_add_trans(pf->trans, PF_RULESET_TABLE, path))
1487 			return (4);
1488 	if (pfctl_trans(pf->dev, pf->trans, DIOCXBEGIN, osize))
1489 		return (5);
1490 
1491 	return (0);
1492 }
1493 
1494 int
1495 pfctl_load_ruleset(struct pfctl *pf, char *path, struct pfctl_ruleset *rs,
1496     int rs_num, int depth)
1497 {
1498 	struct pfctl_rule *r;
1499 	int		error, len = strlen(path);
1500 	int		brace = 0;
1501 
1502 	pf->anchor = rs->anchor;
1503 
1504 	if (path[0])
1505 		snprintf(&path[len], MAXPATHLEN - len, "/%s", pf->anchor->name);
1506 	else
1507 		snprintf(&path[len], MAXPATHLEN - len, "%s", pf->anchor->name);
1508 
1509 	if (depth) {
1510 		if (TAILQ_FIRST(rs->rules[rs_num].active.ptr) != NULL) {
1511 			brace++;
1512 			if (pf->opts & PF_OPT_VERBOSE)
1513 				printf(" {\n");
1514 			if ((pf->opts & PF_OPT_NOACTION) == 0 &&
1515 			    (error = pfctl_ruleset_trans(pf,
1516 			    path, rs->anchor))) {
1517 				printf("pfctl_load_rulesets: "
1518 				    "pfctl_ruleset_trans %d\n", error);
1519 				goto error;
1520 			}
1521 		} else if (pf->opts & PF_OPT_VERBOSE)
1522 			printf("\n");
1523 
1524 	}
1525 
1526 	if (pf->optimize && rs_num == PF_RULESET_FILTER)
1527 		pfctl_optimize_ruleset(pf, rs);
1528 
1529 	while ((r = TAILQ_FIRST(rs->rules[rs_num].active.ptr)) != NULL) {
1530 		TAILQ_REMOVE(rs->rules[rs_num].active.ptr, r, entries);
1531 		if ((error = pfctl_load_rule(pf, path, r, depth)))
1532 			goto error;
1533 		if (r->anchor) {
1534 			if ((error = pfctl_load_ruleset(pf, path,
1535 			    &r->anchor->ruleset, rs_num, depth + 1)))
1536 				goto error;
1537 		} else if (pf->opts & PF_OPT_VERBOSE)
1538 			printf("\n");
1539 		free(r);
1540 	}
1541 	if (brace && pf->opts & PF_OPT_VERBOSE) {
1542 		INDENT(depth - 1, (pf->opts & PF_OPT_VERBOSE));
1543 		printf("}\n");
1544 	}
1545 	path[len] = '\0';
1546 	return (0);
1547 
1548  error:
1549 	path[len] = '\0';
1550 	return (error);
1551 
1552 }
1553 
1554 int
1555 pfctl_load_rule(struct pfctl *pf, char *path, struct pfctl_rule *r, int depth)
1556 {
1557 	u_int8_t		rs_num = pf_get_ruleset_number(r->action);
1558 	char			*name;
1559 	u_int32_t		ticket;
1560 	char			anchor[PF_ANCHOR_NAME_SIZE];
1561 	int			len = strlen(path);
1562 
1563 	/* set up anchor before adding to path for anchor_call */
1564 	if ((pf->opts & PF_OPT_NOACTION) == 0)
1565 		ticket = pfctl_get_ticket(pf->trans, rs_num, path);
1566 	if (strlcpy(anchor, path, sizeof(anchor)) >= sizeof(anchor))
1567 		errx(1, "pfctl_load_rule: strlcpy");
1568 
1569 	if (r->anchor) {
1570 		if (r->anchor->match) {
1571 			if (path[0])
1572 				snprintf(&path[len], MAXPATHLEN - len,
1573 				    "/%s", r->anchor->name);
1574 			else
1575 				snprintf(&path[len], MAXPATHLEN - len,
1576 				    "%s", r->anchor->name);
1577 			name = r->anchor->name;
1578 		} else
1579 			name = r->anchor->path;
1580 	} else
1581 		name = "";
1582 
1583 	if ((pf->opts & PF_OPT_NOACTION) == 0) {
1584 		if (pfctl_add_pool(pf, &r->rpool, r->af))
1585 			return (1);
1586 		if (pfctl_add_rule(pf->dev, r, anchor, name, ticket,
1587 		    pf->paddr.ticket))
1588 			err(1, "DIOCADDRULENV");
1589 	}
1590 
1591 	if (pf->opts & PF_OPT_VERBOSE) {
1592 		INDENT(depth, !(pf->opts & PF_OPT_VERBOSE2));
1593 		print_rule(r, r->anchor ? r->anchor->name : "",
1594 		    pf->opts & PF_OPT_VERBOSE2,
1595 		    pf->opts & PF_OPT_NUMERIC);
1596 	}
1597 	path[len] = '\0';
1598 	pfctl_clear_pool(&r->rpool);
1599 	return (0);
1600 }
1601 
1602 int
1603 pfctl_add_altq(struct pfctl *pf, struct pf_altq *a)
1604 {
1605 	if (altqsupport &&
1606 	    (loadopt & PFCTL_FLAG_ALTQ) != 0) {
1607 		memcpy(&pf->paltq->altq, a, sizeof(struct pf_altq));
1608 		if ((pf->opts & PF_OPT_NOACTION) == 0) {
1609 			if (ioctl(pf->dev, DIOCADDALTQ, pf->paltq)) {
1610 				if (errno == ENXIO)
1611 					errx(1, "qtype not configured");
1612 				else if (errno == ENODEV)
1613 					errx(1, "%s: driver does not support "
1614 					    "altq", a->ifname);
1615 				else
1616 					err(1, "DIOCADDALTQ");
1617 			}
1618 		}
1619 		pfaltq_store(&pf->paltq->altq);
1620 	}
1621 	return (0);
1622 }
1623 
1624 int
1625 pfctl_rules(int dev, char *filename, int opts, int optimize,
1626     char *anchorname, struct pfr_buffer *trans)
1627 {
1628 #define ERR(x) do { warn(x); goto _error; } while(0)
1629 #define ERRX(x) do { warnx(x); goto _error; } while(0)
1630 
1631 	struct pfr_buffer	*t, buf;
1632 	struct pfioc_altq	 pa;
1633 	struct pfctl		 pf;
1634 	struct pfctl_ruleset	*rs;
1635 	struct pfr_table	 trs;
1636 	char			*path;
1637 	int			 osize;
1638 
1639 	RB_INIT(&pf_anchors);
1640 	memset(&pf_main_anchor, 0, sizeof(pf_main_anchor));
1641 	pf_init_ruleset(&pf_main_anchor.ruleset);
1642 	pf_main_anchor.ruleset.anchor = &pf_main_anchor;
1643 	if (trans == NULL) {
1644 		bzero(&buf, sizeof(buf));
1645 		buf.pfrb_type = PFRB_TRANS;
1646 		t = &buf;
1647 		osize = 0;
1648 	} else {
1649 		t = trans;
1650 		osize = t->pfrb_size;
1651 	}
1652 
1653 	memset(&pa, 0, sizeof(pa));
1654 	pa.version = PFIOC_ALTQ_VERSION;
1655 	memset(&pf, 0, sizeof(pf));
1656 	memset(&trs, 0, sizeof(trs));
1657 	if ((path = calloc(1, MAXPATHLEN)) == NULL)
1658 		ERRX("pfctl_rules: calloc");
1659 	if (strlcpy(trs.pfrt_anchor, anchorname,
1660 	    sizeof(trs.pfrt_anchor)) >= sizeof(trs.pfrt_anchor))
1661 		ERRX("pfctl_rules: strlcpy");
1662 	pf.dev = dev;
1663 	pf.opts = opts;
1664 	pf.optimize = optimize;
1665 	pf.loadopt = loadopt;
1666 
1667 	/* non-brace anchor, create without resolving the path */
1668 	if ((pf.anchor = calloc(1, sizeof(*pf.anchor))) == NULL)
1669 		ERRX("pfctl_rules: calloc");
1670 	rs = &pf.anchor->ruleset;
1671 	pf_init_ruleset(rs);
1672 	rs->anchor = pf.anchor;
1673 	if (strlcpy(pf.anchor->path, anchorname,
1674 	    sizeof(pf.anchor->path)) >= sizeof(pf.anchor->path))
1675 		errx(1, "pfctl_add_rule: strlcpy");
1676 	if (strlcpy(pf.anchor->name, anchorname,
1677 	    sizeof(pf.anchor->name)) >= sizeof(pf.anchor->name))
1678 		errx(1, "pfctl_add_rule: strlcpy");
1679 
1680 
1681 	pf.astack[0] = pf.anchor;
1682 	pf.asd = 0;
1683 	if (anchorname[0])
1684 		pf.loadopt &= ~PFCTL_FLAG_ALTQ;
1685 	pf.paltq = &pa;
1686 	pf.trans = t;
1687 	pfctl_init_options(&pf);
1688 
1689 	if ((opts & PF_OPT_NOACTION) == 0) {
1690 		/*
1691 		 * XXX For the time being we need to open transactions for
1692 		 * the main ruleset before parsing, because tables are still
1693 		 * loaded at parse time.
1694 		 */
1695 		if (pfctl_ruleset_trans(&pf, anchorname, pf.anchor))
1696 			ERRX("pfctl_rules");
1697 		if (altqsupport && (pf.loadopt & PFCTL_FLAG_ALTQ))
1698 			pa.ticket =
1699 			    pfctl_get_ticket(t, PF_RULESET_ALTQ, anchorname);
1700 		if (pf.loadopt & PFCTL_FLAG_TABLE)
1701 			pf.astack[0]->ruleset.tticket =
1702 			    pfctl_get_ticket(t, PF_RULESET_TABLE, anchorname);
1703 	}
1704 
1705 	if (parse_config(filename, &pf) < 0) {
1706 		if ((opts & PF_OPT_NOACTION) == 0)
1707 			ERRX("Syntax error in config file: "
1708 			    "pf rules not loaded");
1709 		else
1710 			goto _error;
1711 	}
1712 	if (loadopt & PFCTL_FLAG_OPTION)
1713 		pfctl_adjust_skip_ifaces(&pf);
1714 
1715 	if ((pf.loadopt & PFCTL_FLAG_FILTER &&
1716 	    (pfctl_load_ruleset(&pf, path, rs, PF_RULESET_SCRUB, 0))) ||
1717 	    (pf.loadopt & PFCTL_FLAG_NAT &&
1718 	    (pfctl_load_ruleset(&pf, path, rs, PF_RULESET_NAT, 0) ||
1719 	    pfctl_load_ruleset(&pf, path, rs, PF_RULESET_RDR, 0) ||
1720 	    pfctl_load_ruleset(&pf, path, rs, PF_RULESET_BINAT, 0))) ||
1721 	    (pf.loadopt & PFCTL_FLAG_FILTER &&
1722 	    pfctl_load_ruleset(&pf, path, rs, PF_RULESET_FILTER, 0))) {
1723 		if ((opts & PF_OPT_NOACTION) == 0)
1724 			ERRX("Unable to load rules into kernel");
1725 		else
1726 			goto _error;
1727 	}
1728 
1729 	if ((altqsupport && (pf.loadopt & PFCTL_FLAG_ALTQ) != 0))
1730 		if (check_commit_altq(dev, opts) != 0)
1731 			ERRX("errors in altq config");
1732 
1733 	/* process "load anchor" directives */
1734 	if (!anchorname[0])
1735 		if (pfctl_load_anchors(dev, &pf, t) == -1)
1736 			ERRX("load anchors");
1737 
1738 	if (trans == NULL && (opts & PF_OPT_NOACTION) == 0) {
1739 		if (!anchorname[0])
1740 			if (pfctl_load_options(&pf))
1741 				goto _error;
1742 		if (pfctl_trans(dev, t, DIOCXCOMMIT, osize))
1743 			ERR("DIOCXCOMMIT");
1744 	}
1745 	free(path);
1746 	return (0);
1747 
1748 _error:
1749 	if (trans == NULL) {	/* main ruleset */
1750 		if ((opts & PF_OPT_NOACTION) == 0)
1751 			if (pfctl_trans(dev, t, DIOCXROLLBACK, osize))
1752 				err(1, "DIOCXROLLBACK");
1753 		exit(1);
1754 	} else {		/* sub ruleset */
1755 		free(path);
1756 		return (-1);
1757 	}
1758 
1759 #undef ERR
1760 #undef ERRX
1761 }
1762 
1763 FILE *
1764 pfctl_fopen(const char *name, const char *mode)
1765 {
1766 	struct stat	 st;
1767 	FILE		*fp;
1768 
1769 	fp = fopen(name, mode);
1770 	if (fp == NULL)
1771 		return (NULL);
1772 	if (fstat(fileno(fp), &st)) {
1773 		fclose(fp);
1774 		return (NULL);
1775 	}
1776 	if (S_ISDIR(st.st_mode)) {
1777 		fclose(fp);
1778 		errno = EISDIR;
1779 		return (NULL);
1780 	}
1781 	return (fp);
1782 }
1783 
1784 void
1785 pfctl_init_options(struct pfctl *pf)
1786 {
1787 
1788 	pf->timeout[PFTM_TCP_FIRST_PACKET] = PFTM_TCP_FIRST_PACKET_VAL;
1789 	pf->timeout[PFTM_TCP_OPENING] = PFTM_TCP_OPENING_VAL;
1790 	pf->timeout[PFTM_TCP_ESTABLISHED] = PFTM_TCP_ESTABLISHED_VAL;
1791 	pf->timeout[PFTM_TCP_CLOSING] = PFTM_TCP_CLOSING_VAL;
1792 	pf->timeout[PFTM_TCP_FIN_WAIT] = PFTM_TCP_FIN_WAIT_VAL;
1793 	pf->timeout[PFTM_TCP_CLOSED] = PFTM_TCP_CLOSED_VAL;
1794 	pf->timeout[PFTM_UDP_FIRST_PACKET] = PFTM_UDP_FIRST_PACKET_VAL;
1795 	pf->timeout[PFTM_UDP_SINGLE] = PFTM_UDP_SINGLE_VAL;
1796 	pf->timeout[PFTM_UDP_MULTIPLE] = PFTM_UDP_MULTIPLE_VAL;
1797 	pf->timeout[PFTM_ICMP_FIRST_PACKET] = PFTM_ICMP_FIRST_PACKET_VAL;
1798 	pf->timeout[PFTM_ICMP_ERROR_REPLY] = PFTM_ICMP_ERROR_REPLY_VAL;
1799 	pf->timeout[PFTM_OTHER_FIRST_PACKET] = PFTM_OTHER_FIRST_PACKET_VAL;
1800 	pf->timeout[PFTM_OTHER_SINGLE] = PFTM_OTHER_SINGLE_VAL;
1801 	pf->timeout[PFTM_OTHER_MULTIPLE] = PFTM_OTHER_MULTIPLE_VAL;
1802 	pf->timeout[PFTM_FRAG] = PFTM_FRAG_VAL;
1803 	pf->timeout[PFTM_INTERVAL] = PFTM_INTERVAL_VAL;
1804 	pf->timeout[PFTM_SRC_NODE] = PFTM_SRC_NODE_VAL;
1805 	pf->timeout[PFTM_TS_DIFF] = PFTM_TS_DIFF_VAL;
1806 	pf->timeout[PFTM_ADAPTIVE_START] = PFSTATE_ADAPT_START;
1807 	pf->timeout[PFTM_ADAPTIVE_END] = PFSTATE_ADAPT_END;
1808 
1809 	pf->limit[PF_LIMIT_STATES] = PFSTATE_HIWAT;
1810 	pf->limit[PF_LIMIT_FRAGS] = PFFRAG_FRENT_HIWAT;
1811 	pf->limit[PF_LIMIT_SRC_NODES] = PFSNODE_HIWAT;
1812 	pf->limit[PF_LIMIT_TABLE_ENTRIES] = PFR_KENTRY_HIWAT;
1813 
1814 	pf->debug = PF_DEBUG_URGENT;
1815 }
1816 
1817 int
1818 pfctl_load_options(struct pfctl *pf)
1819 {
1820 	int i, error = 0;
1821 
1822 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1823 		return (0);
1824 
1825 	/* load limits */
1826 	for (i = 0; i < PF_LIMIT_MAX; i++) {
1827 		if ((pf->opts & PF_OPT_MERGE) && !pf->limit_set[i])
1828 			continue;
1829 		if (pfctl_load_limit(pf, i, pf->limit[i]))
1830 			error = 1;
1831 	}
1832 
1833 	/*
1834 	 * If we've set the limit, but haven't explicitly set adaptive
1835 	 * timeouts, do it now with a start of 60% and end of 120%.
1836 	 */
1837 	if (pf->limit_set[PF_LIMIT_STATES] &&
1838 	    !pf->timeout_set[PFTM_ADAPTIVE_START] &&
1839 	    !pf->timeout_set[PFTM_ADAPTIVE_END]) {
1840 		pf->timeout[PFTM_ADAPTIVE_START] =
1841 			(pf->limit[PF_LIMIT_STATES] / 10) * 6;
1842 		pf->timeout_set[PFTM_ADAPTIVE_START] = 1;
1843 		pf->timeout[PFTM_ADAPTIVE_END] =
1844 			(pf->limit[PF_LIMIT_STATES] / 10) * 12;
1845 		pf->timeout_set[PFTM_ADAPTIVE_END] = 1;
1846 	}
1847 
1848 	/* load timeouts */
1849 	for (i = 0; i < PFTM_MAX; i++) {
1850 		if ((pf->opts & PF_OPT_MERGE) && !pf->timeout_set[i])
1851 			continue;
1852 		if (pfctl_load_timeout(pf, i, pf->timeout[i]))
1853 			error = 1;
1854 	}
1855 
1856 	/* load debug */
1857 	if (!(pf->opts & PF_OPT_MERGE) || pf->debug_set)
1858 		if (pfctl_load_debug(pf, pf->debug))
1859 			error = 1;
1860 
1861 	/* load logif */
1862 	if (!(pf->opts & PF_OPT_MERGE) || pf->ifname_set)
1863 		if (pfctl_load_logif(pf, pf->ifname))
1864 			error = 1;
1865 
1866 	/* load hostid */
1867 	if (!(pf->opts & PF_OPT_MERGE) || pf->hostid_set)
1868 		if (pfctl_load_hostid(pf, pf->hostid))
1869 			error = 1;
1870 
1871 	/* load keepcounters */
1872 	if (pfctl_set_keepcounters(pf->dev, pf->keep_counters))
1873 		error = 1;
1874 
1875 	/* load syncookies settings */
1876 	if (pfctl_load_syncookies(pf, pf->syncookies))
1877 		error = 1;
1878 
1879 	return (error);
1880 }
1881 
1882 int
1883 pfctl_set_limit(struct pfctl *pf, const char *opt, unsigned int limit)
1884 {
1885 	int i;
1886 
1887 
1888 	for (i = 0; pf_limits[i].name; i++) {
1889 		if (strcasecmp(opt, pf_limits[i].name) == 0) {
1890 			pf->limit[pf_limits[i].index] = limit;
1891 			pf->limit_set[pf_limits[i].index] = 1;
1892 			break;
1893 		}
1894 	}
1895 	if (pf_limits[i].name == NULL) {
1896 		warnx("Bad pool name.");
1897 		return (1);
1898 	}
1899 
1900 	if (pf->opts & PF_OPT_VERBOSE)
1901 		printf("set limit %s %d\n", opt, limit);
1902 
1903 	return (0);
1904 }
1905 
1906 int
1907 pfctl_load_limit(struct pfctl *pf, unsigned int index, unsigned int limit)
1908 {
1909 	struct pfioc_limit pl;
1910 
1911 	memset(&pl, 0, sizeof(pl));
1912 	pl.index = index;
1913 	pl.limit = limit;
1914 	if (ioctl(pf->dev, DIOCSETLIMIT, &pl)) {
1915 		if (errno == EBUSY)
1916 			warnx("Current pool size exceeds requested hard limit");
1917 		else
1918 			warnx("DIOCSETLIMIT");
1919 		return (1);
1920 	}
1921 	return (0);
1922 }
1923 
1924 int
1925 pfctl_set_timeout(struct pfctl *pf, const char *opt, int seconds, int quiet)
1926 {
1927 	int i;
1928 
1929 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1930 		return (0);
1931 
1932 	for (i = 0; pf_timeouts[i].name; i++) {
1933 		if (strcasecmp(opt, pf_timeouts[i].name) == 0) {
1934 			pf->timeout[pf_timeouts[i].timeout] = seconds;
1935 			pf->timeout_set[pf_timeouts[i].timeout] = 1;
1936 			break;
1937 		}
1938 	}
1939 
1940 	if (pf_timeouts[i].name == NULL) {
1941 		warnx("Bad timeout name.");
1942 		return (1);
1943 	}
1944 
1945 
1946 	if (pf->opts & PF_OPT_VERBOSE && ! quiet)
1947 		printf("set timeout %s %d\n", opt, seconds);
1948 
1949 	return (0);
1950 }
1951 
1952 int
1953 pfctl_load_timeout(struct pfctl *pf, unsigned int timeout, unsigned int seconds)
1954 {
1955 	struct pfioc_tm pt;
1956 
1957 	memset(&pt, 0, sizeof(pt));
1958 	pt.timeout = timeout;
1959 	pt.seconds = seconds;
1960 	if (ioctl(pf->dev, DIOCSETTIMEOUT, &pt)) {
1961 		warnx("DIOCSETTIMEOUT");
1962 		return (1);
1963 	}
1964 	return (0);
1965 }
1966 
1967 int
1968 pfctl_set_optimization(struct pfctl *pf, const char *opt)
1969 {
1970 	const struct pf_hint *hint;
1971 	int i, r;
1972 
1973 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1974 		return (0);
1975 
1976 	for (i = 0; pf_hints[i].name; i++)
1977 		if (strcasecmp(opt, pf_hints[i].name) == 0)
1978 			break;
1979 
1980 	hint = pf_hints[i].hint;
1981 	if (hint == NULL) {
1982 		warnx("invalid state timeouts optimization");
1983 		return (1);
1984 	}
1985 
1986 	for (i = 0; hint[i].name; i++)
1987 		if ((r = pfctl_set_timeout(pf, hint[i].name,
1988 		    hint[i].timeout, 1)))
1989 			return (r);
1990 
1991 	if (pf->opts & PF_OPT_VERBOSE)
1992 		printf("set optimization %s\n", opt);
1993 
1994 	return (0);
1995 }
1996 
1997 int
1998 pfctl_set_logif(struct pfctl *pf, char *ifname)
1999 {
2000 
2001 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
2002 		return (0);
2003 
2004 	if (!strcmp(ifname, "none")) {
2005 		free(pf->ifname);
2006 		pf->ifname = NULL;
2007 	} else {
2008 		pf->ifname = strdup(ifname);
2009 		if (!pf->ifname)
2010 			errx(1, "pfctl_set_logif: strdup");
2011 	}
2012 	pf->ifname_set = 1;
2013 
2014 	if (pf->opts & PF_OPT_VERBOSE)
2015 		printf("set loginterface %s\n", ifname);
2016 
2017 	return (0);
2018 }
2019 
2020 int
2021 pfctl_load_logif(struct pfctl *pf, char *ifname)
2022 {
2023 	struct pfioc_if pi;
2024 
2025 	memset(&pi, 0, sizeof(pi));
2026 	if (ifname && strlcpy(pi.ifname, ifname,
2027 	    sizeof(pi.ifname)) >= sizeof(pi.ifname)) {
2028 		warnx("pfctl_load_logif: strlcpy");
2029 		return (1);
2030 	}
2031 	if (ioctl(pf->dev, DIOCSETSTATUSIF, &pi)) {
2032 		warnx("DIOCSETSTATUSIF");
2033 		return (1);
2034 	}
2035 	return (0);
2036 }
2037 
2038 int
2039 pfctl_set_hostid(struct pfctl *pf, u_int32_t hostid)
2040 {
2041 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
2042 		return (0);
2043 
2044 	HTONL(hostid);
2045 
2046 	pf->hostid = hostid;
2047 	pf->hostid_set = 1;
2048 
2049 	if (pf->opts & PF_OPT_VERBOSE)
2050 		printf("set hostid 0x%08x\n", ntohl(hostid));
2051 
2052 	return (0);
2053 }
2054 
2055 int
2056 pfctl_load_hostid(struct pfctl *pf, u_int32_t hostid)
2057 {
2058 	if (ioctl(dev, DIOCSETHOSTID, &hostid)) {
2059 		warnx("DIOCSETHOSTID");
2060 		return (1);
2061 	}
2062 	return (0);
2063 }
2064 
2065 int
2066 pfctl_load_syncookies(struct pfctl *pf, u_int8_t val)
2067 {
2068 	struct pfctl_syncookies	cookies;
2069 
2070 	bzero(&cookies, sizeof(cookies));
2071 
2072 	cookies.mode = val ? PFCTL_SYNCOOKIES_ALWAYS : PFCTL_SYNCOOKIES_NEVER;
2073 
2074 	if (pfctl_set_syncookies(dev, &cookies)) {
2075 		warnx("DIOCSETSYNCOOKIES");
2076 		return (1);
2077 	}
2078 	return (0);
2079 }
2080 
2081 int
2082 pfctl_set_debug(struct pfctl *pf, char *d)
2083 {
2084 	u_int32_t	level;
2085 
2086 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
2087 		return (0);
2088 
2089 	if (!strcmp(d, "none"))
2090 		pf->debug = PF_DEBUG_NONE;
2091 	else if (!strcmp(d, "urgent"))
2092 		pf->debug = PF_DEBUG_URGENT;
2093 	else if (!strcmp(d, "misc"))
2094 		pf->debug = PF_DEBUG_MISC;
2095 	else if (!strcmp(d, "loud"))
2096 		pf->debug = PF_DEBUG_NOISY;
2097 	else {
2098 		warnx("unknown debug level \"%s\"", d);
2099 		return (-1);
2100 	}
2101 
2102 	pf->debug_set = 1;
2103 	level = pf->debug;
2104 
2105 	if ((pf->opts & PF_OPT_NOACTION) == 0)
2106 		if (ioctl(dev, DIOCSETDEBUG, &level))
2107 			err(1, "DIOCSETDEBUG");
2108 
2109 	if (pf->opts & PF_OPT_VERBOSE)
2110 		printf("set debug %s\n", d);
2111 
2112 	return (0);
2113 }
2114 
2115 int
2116 pfctl_load_debug(struct pfctl *pf, unsigned int level)
2117 {
2118 	if (ioctl(pf->dev, DIOCSETDEBUG, &level)) {
2119 		warnx("DIOCSETDEBUG");
2120 		return (1);
2121 	}
2122 	return (0);
2123 }
2124 
2125 int
2126 pfctl_set_interface_flags(struct pfctl *pf, char *ifname, int flags, int how)
2127 {
2128 	struct pfioc_iface	pi;
2129 	struct node_host	*h = NULL, *n = NULL;
2130 
2131 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
2132 		return (0);
2133 
2134 	bzero(&pi, sizeof(pi));
2135 
2136 	pi.pfiio_flags = flags;
2137 
2138 	/* Make sure our cache matches the kernel. If we set or clear the flag
2139 	 * for a group this applies to all members. */
2140 	h = ifa_grouplookup(ifname, 0);
2141 	for (n = h; n != NULL; n = n->next)
2142 		pfctl_set_interface_flags(pf, n->ifname, flags, how);
2143 
2144 	if (strlcpy(pi.pfiio_name, ifname, sizeof(pi.pfiio_name)) >=
2145 	    sizeof(pi.pfiio_name))
2146 		errx(1, "pfctl_set_interface_flags: strlcpy");
2147 
2148 	if ((pf->opts & PF_OPT_NOACTION) == 0) {
2149 		if (how == 0) {
2150 			if (ioctl(pf->dev, DIOCCLRIFFLAG, &pi))
2151 				err(1, "DIOCCLRIFFLAG");
2152 		} else {
2153 			if (ioctl(pf->dev, DIOCSETIFFLAG, &pi))
2154 				err(1, "DIOCSETIFFLAG");
2155 			pfctl_check_skip_ifaces(ifname);
2156 		}
2157 	}
2158 	return (0);
2159 }
2160 
2161 void
2162 pfctl_debug(int dev, u_int32_t level, int opts)
2163 {
2164 	if (ioctl(dev, DIOCSETDEBUG, &level))
2165 		err(1, "DIOCSETDEBUG");
2166 	if ((opts & PF_OPT_QUIET) == 0) {
2167 		fprintf(stderr, "debug level set to '");
2168 		switch (level) {
2169 		case PF_DEBUG_NONE:
2170 			fprintf(stderr, "none");
2171 			break;
2172 		case PF_DEBUG_URGENT:
2173 			fprintf(stderr, "urgent");
2174 			break;
2175 		case PF_DEBUG_MISC:
2176 			fprintf(stderr, "misc");
2177 			break;
2178 		case PF_DEBUG_NOISY:
2179 			fprintf(stderr, "loud");
2180 			break;
2181 		default:
2182 			fprintf(stderr, "<invalid>");
2183 			break;
2184 		}
2185 		fprintf(stderr, "'\n");
2186 	}
2187 }
2188 
2189 int
2190 pfctl_test_altqsupport(int dev, int opts)
2191 {
2192 	struct pfioc_altq pa;
2193 
2194 	pa.version = PFIOC_ALTQ_VERSION;
2195 	if (ioctl(dev, DIOCGETALTQS, &pa)) {
2196 		if (errno == ENODEV) {
2197 			if (opts & PF_OPT_VERBOSE)
2198 				fprintf(stderr, "No ALTQ support in kernel\n"
2199 				    "ALTQ related functions disabled\n");
2200 			return (0);
2201 		} else
2202 			err(1, "DIOCGETALTQS");
2203 	}
2204 	return (1);
2205 }
2206 
2207 int
2208 pfctl_show_anchors(int dev, int opts, char *anchorname)
2209 {
2210 	struct pfioc_ruleset	 pr;
2211 	u_int32_t		 mnr, nr;
2212 
2213 	memset(&pr, 0, sizeof(pr));
2214 	memcpy(pr.path, anchorname, sizeof(pr.path));
2215 	if (ioctl(dev, DIOCGETRULESETS, &pr)) {
2216 		if (errno == EINVAL)
2217 			fprintf(stderr, "Anchor '%s' not found.\n",
2218 			    anchorname);
2219 		else
2220 			err(1, "DIOCGETRULESETS");
2221 		return (-1);
2222 	}
2223 	mnr = pr.nr;
2224 	for (nr = 0; nr < mnr; ++nr) {
2225 		char sub[MAXPATHLEN];
2226 
2227 		pr.nr = nr;
2228 		if (ioctl(dev, DIOCGETRULESET, &pr))
2229 			err(1, "DIOCGETRULESET");
2230 		if (!strcmp(pr.name, PF_RESERVED_ANCHOR))
2231 			continue;
2232 		sub[0] = 0;
2233 		if (pr.path[0]) {
2234 			strlcat(sub, pr.path, sizeof(sub));
2235 			strlcat(sub, "/", sizeof(sub));
2236 		}
2237 		strlcat(sub, pr.name, sizeof(sub));
2238 		if (sub[0] != '_' || (opts & PF_OPT_VERBOSE))
2239 			printf("  %s\n", sub);
2240 		if ((opts & PF_OPT_VERBOSE) && pfctl_show_anchors(dev, opts, sub))
2241 			return (-1);
2242 	}
2243 	return (0);
2244 }
2245 
2246 const char *
2247 pfctl_lookup_option(char *cmd, const char * const *list)
2248 {
2249 	if (cmd != NULL && *cmd)
2250 		for (; *list; list++)
2251 			if (!strncmp(cmd, *list, strlen(cmd)))
2252 				return (*list);
2253 	return (NULL);
2254 }
2255 
2256 int
2257 main(int argc, char *argv[])
2258 {
2259 	int	 error = 0;
2260 	int	 ch;
2261 	int	 mode = O_RDONLY;
2262 	int	 opts = 0;
2263 	int	 optimize = PF_OPTIMIZE_BASIC;
2264 	char	 anchorname[MAXPATHLEN];
2265 	char	*path;
2266 
2267 	if (argc < 2)
2268 		usage();
2269 
2270 	while ((ch = getopt(argc, argv,
2271 	    "a:AdD:eqf:F:ghi:k:K:mMnNOo:Pp:rRs:t:T:vx:z")) != -1) {
2272 		switch (ch) {
2273 		case 'a':
2274 			anchoropt = optarg;
2275 			break;
2276 		case 'd':
2277 			opts |= PF_OPT_DISABLE;
2278 			mode = O_RDWR;
2279 			break;
2280 		case 'D':
2281 			if (pfctl_cmdline_symset(optarg) < 0)
2282 				warnx("could not parse macro definition %s",
2283 				    optarg);
2284 			break;
2285 		case 'e':
2286 			opts |= PF_OPT_ENABLE;
2287 			mode = O_RDWR;
2288 			break;
2289 		case 'q':
2290 			opts |= PF_OPT_QUIET;
2291 			break;
2292 		case 'F':
2293 			clearopt = pfctl_lookup_option(optarg, clearopt_list);
2294 			if (clearopt == NULL) {
2295 				warnx("Unknown flush modifier '%s'", optarg);
2296 				usage();
2297 			}
2298 			mode = O_RDWR;
2299 			break;
2300 		case 'i':
2301 			ifaceopt = optarg;
2302 			break;
2303 		case 'k':
2304 			if (state_killers >= 2) {
2305 				warnx("can only specify -k twice");
2306 				usage();
2307 				/* NOTREACHED */
2308 			}
2309 			state_kill[state_killers++] = optarg;
2310 			mode = O_RDWR;
2311 			break;
2312 		case 'K':
2313 			if (src_node_killers >= 2) {
2314 				warnx("can only specify -K twice");
2315 				usage();
2316 				/* NOTREACHED */
2317 			}
2318 			src_node_kill[src_node_killers++] = optarg;
2319 			mode = O_RDWR;
2320 			break;
2321 		case 'm':
2322 			opts |= PF_OPT_MERGE;
2323 			break;
2324 		case 'M':
2325 			opts |= PF_OPT_KILLMATCH;
2326 			break;
2327 		case 'n':
2328 			opts |= PF_OPT_NOACTION;
2329 			break;
2330 		case 'N':
2331 			loadopt |= PFCTL_FLAG_NAT;
2332 			break;
2333 		case 'r':
2334 			opts |= PF_OPT_USEDNS;
2335 			break;
2336 		case 'f':
2337 			rulesopt = optarg;
2338 			mode = O_RDWR;
2339 			break;
2340 		case 'g':
2341 			opts |= PF_OPT_DEBUG;
2342 			break;
2343 		case 'A':
2344 			loadopt |= PFCTL_FLAG_ALTQ;
2345 			break;
2346 		case 'R':
2347 			loadopt |= PFCTL_FLAG_FILTER;
2348 			break;
2349 		case 'o':
2350 			optiopt = pfctl_lookup_option(optarg, optiopt_list);
2351 			if (optiopt == NULL) {
2352 				warnx("Unknown optimization '%s'", optarg);
2353 				usage();
2354 			}
2355 			opts |= PF_OPT_OPTIMIZE;
2356 			break;
2357 		case 'O':
2358 			loadopt |= PFCTL_FLAG_OPTION;
2359 			break;
2360 		case 'p':
2361 			pf_device = optarg;
2362 			break;
2363 		case 'P':
2364 			opts |= PF_OPT_NUMERIC;
2365 			break;
2366 		case 's':
2367 			showopt = pfctl_lookup_option(optarg, showopt_list);
2368 			if (showopt == NULL) {
2369 				warnx("Unknown show modifier '%s'", optarg);
2370 				usage();
2371 			}
2372 			break;
2373 		case 't':
2374 			tableopt = optarg;
2375 			break;
2376 		case 'T':
2377 			tblcmdopt = pfctl_lookup_option(optarg, tblcmdopt_list);
2378 			if (tblcmdopt == NULL) {
2379 				warnx("Unknown table command '%s'", optarg);
2380 				usage();
2381 			}
2382 			break;
2383 		case 'v':
2384 			if (opts & PF_OPT_VERBOSE)
2385 				opts |= PF_OPT_VERBOSE2;
2386 			opts |= PF_OPT_VERBOSE;
2387 			break;
2388 		case 'x':
2389 			debugopt = pfctl_lookup_option(optarg, debugopt_list);
2390 			if (debugopt == NULL) {
2391 				warnx("Unknown debug level '%s'", optarg);
2392 				usage();
2393 			}
2394 			mode = O_RDWR;
2395 			break;
2396 		case 'z':
2397 			opts |= PF_OPT_CLRRULECTRS;
2398 			mode = O_RDWR;
2399 			break;
2400 		case 'h':
2401 			/* FALLTHROUGH */
2402 		default:
2403 			usage();
2404 			/* NOTREACHED */
2405 		}
2406 	}
2407 
2408 	if (tblcmdopt != NULL) {
2409 		argc -= optind;
2410 		argv += optind;
2411 		ch = *tblcmdopt;
2412 		if (ch == 'l') {
2413 			loadopt |= PFCTL_FLAG_TABLE;
2414 			tblcmdopt = NULL;
2415 		} else
2416 			mode = strchr("acdefkrz", ch) ? O_RDWR : O_RDONLY;
2417 	} else if (argc != optind) {
2418 		warnx("unknown command line argument: %s ...", argv[optind]);
2419 		usage();
2420 		/* NOTREACHED */
2421 	}
2422 	if (loadopt == 0)
2423 		loadopt = ~0;
2424 
2425 	if ((path = calloc(1, MAXPATHLEN)) == NULL)
2426 		errx(1, "pfctl: calloc");
2427 	memset(anchorname, 0, sizeof(anchorname));
2428 	if (anchoropt != NULL) {
2429 		int len = strlen(anchoropt);
2430 
2431 		if (anchoropt[len - 1] == '*') {
2432 			if (len >= 2 && anchoropt[len - 2] == '/')
2433 				anchoropt[len - 2] = '\0';
2434 			else
2435 				anchoropt[len - 1] = '\0';
2436 			opts |= PF_OPT_RECURSE;
2437 		}
2438 		if (strlcpy(anchorname, anchoropt,
2439 		    sizeof(anchorname)) >= sizeof(anchorname))
2440 			errx(1, "anchor name '%s' too long",
2441 			    anchoropt);
2442 		loadopt &= PFCTL_FLAG_FILTER|PFCTL_FLAG_NAT|PFCTL_FLAG_TABLE;
2443 	}
2444 
2445 	if ((opts & PF_OPT_NOACTION) == 0) {
2446 		dev = open(pf_device, mode);
2447 		if (dev == -1)
2448 			err(1, "%s", pf_device);
2449 		altqsupport = pfctl_test_altqsupport(dev, opts);
2450 	} else {
2451 		dev = open(pf_device, O_RDONLY);
2452 		if (dev >= 0)
2453 			opts |= PF_OPT_DUMMYACTION;
2454 		/* turn off options */
2455 		opts &= ~ (PF_OPT_DISABLE | PF_OPT_ENABLE);
2456 		clearopt = showopt = debugopt = NULL;
2457 #if !defined(ENABLE_ALTQ)
2458 		altqsupport = 0;
2459 #else
2460 		altqsupport = 1;
2461 #endif
2462 	}
2463 
2464 	if (opts & PF_OPT_DISABLE)
2465 		if (pfctl_disable(dev, opts))
2466 			error = 1;
2467 
2468 	if (showopt != NULL) {
2469 		switch (*showopt) {
2470 		case 'A':
2471 			pfctl_show_anchors(dev, opts, anchorname);
2472 			break;
2473 		case 'r':
2474 			pfctl_load_fingerprints(dev, opts);
2475 			pfctl_show_rules(dev, path, opts, PFCTL_SHOW_RULES,
2476 			    anchorname, 0);
2477 			break;
2478 		case 'l':
2479 			pfctl_load_fingerprints(dev, opts);
2480 			pfctl_show_rules(dev, path, opts, PFCTL_SHOW_LABELS,
2481 			    anchorname, 0);
2482 			break;
2483 		case 'n':
2484 			pfctl_load_fingerprints(dev, opts);
2485 			pfctl_show_nat(dev, opts, anchorname);
2486 			break;
2487 		case 'q':
2488 			pfctl_show_altq(dev, ifaceopt, opts,
2489 			    opts & PF_OPT_VERBOSE2);
2490 			break;
2491 		case 's':
2492 			pfctl_show_states(dev, ifaceopt, opts);
2493 			break;
2494 		case 'S':
2495 			pfctl_show_src_nodes(dev, opts);
2496 			break;
2497 		case 'i':
2498 			pfctl_show_status(dev, opts);
2499 			break;
2500 		case 'R':
2501 			error = pfctl_show_running(dev);
2502 			break;
2503 		case 't':
2504 			pfctl_show_timeouts(dev, opts);
2505 			break;
2506 		case 'm':
2507 			pfctl_show_limits(dev, opts);
2508 			break;
2509 		case 'a':
2510 			opts |= PF_OPT_SHOWALL;
2511 			pfctl_load_fingerprints(dev, opts);
2512 
2513 			pfctl_show_nat(dev, opts, anchorname);
2514 			pfctl_show_rules(dev, path, opts, 0, anchorname, 0);
2515 			pfctl_show_altq(dev, ifaceopt, opts, 0);
2516 			pfctl_show_states(dev, ifaceopt, opts);
2517 			pfctl_show_src_nodes(dev, opts);
2518 			pfctl_show_status(dev, opts);
2519 			pfctl_show_rules(dev, path, opts, 1, anchorname, 0);
2520 			pfctl_show_timeouts(dev, opts);
2521 			pfctl_show_limits(dev, opts);
2522 			pfctl_show_tables(anchorname, opts);
2523 			pfctl_show_fingerprints(opts);
2524 			break;
2525 		case 'T':
2526 			pfctl_show_tables(anchorname, opts);
2527 			break;
2528 		case 'o':
2529 			pfctl_load_fingerprints(dev, opts);
2530 			pfctl_show_fingerprints(opts);
2531 			break;
2532 		case 'I':
2533 			pfctl_show_ifaces(ifaceopt, opts);
2534 			break;
2535 		}
2536 	}
2537 
2538 	if ((opts & PF_OPT_CLRRULECTRS) && showopt == NULL)
2539 		pfctl_show_rules(dev, path, opts, PFCTL_SHOW_NOTHING,
2540 		    anchorname, 0);
2541 
2542 	if (clearopt != NULL) {
2543 		if (anchorname[0] == '_' || strstr(anchorname, "/_") != NULL)
2544 			errx(1, "anchor names beginning with '_' cannot "
2545 			    "be modified from the command line");
2546 
2547 		switch (*clearopt) {
2548 		case 'r':
2549 			pfctl_clear_rules(dev, opts, anchorname);
2550 			break;
2551 		case 'n':
2552 			pfctl_clear_nat(dev, opts, anchorname);
2553 			break;
2554 		case 'q':
2555 			pfctl_clear_altq(dev, opts);
2556 			break;
2557 		case 's':
2558 			pfctl_clear_iface_states(dev, ifaceopt, opts);
2559 			break;
2560 		case 'S':
2561 			pfctl_clear_src_nodes(dev, opts);
2562 			break;
2563 		case 'i':
2564 			pfctl_clear_stats(dev, opts);
2565 			break;
2566 		case 'a':
2567 			pfctl_clear_rules(dev, opts, anchorname);
2568 			pfctl_clear_nat(dev, opts, anchorname);
2569 			pfctl_clear_tables(anchorname, opts);
2570 			if (!*anchorname) {
2571 				pfctl_clear_altq(dev, opts);
2572 				pfctl_clear_iface_states(dev, ifaceopt, opts);
2573 				pfctl_clear_src_nodes(dev, opts);
2574 				pfctl_clear_stats(dev, opts);
2575 				pfctl_clear_fingerprints(dev, opts);
2576 				pfctl_clear_interface_flags(dev, opts);
2577 			}
2578 			break;
2579 		case 'o':
2580 			pfctl_clear_fingerprints(dev, opts);
2581 			break;
2582 		case 'T':
2583 			pfctl_clear_tables(anchorname, opts);
2584 			break;
2585 		}
2586 	}
2587 	if (state_killers) {
2588 		if (!strcmp(state_kill[0], "label"))
2589 			pfctl_label_kill_states(dev, ifaceopt, opts);
2590 		else if (!strcmp(state_kill[0], "id"))
2591 			pfctl_id_kill_states(dev, ifaceopt, opts);
2592 		else if (!strcmp(state_kill[0], "gateway"))
2593 			pfctl_gateway_kill_states(dev, ifaceopt, opts);
2594 		else
2595 			pfctl_net_kill_states(dev, ifaceopt, opts);
2596 	}
2597 
2598 	if (src_node_killers)
2599 		pfctl_kill_src_nodes(dev, ifaceopt, opts);
2600 
2601 	if (tblcmdopt != NULL) {
2602 		error = pfctl_command_tables(argc, argv, tableopt,
2603 		    tblcmdopt, rulesopt, anchorname, opts);
2604 		rulesopt = NULL;
2605 	}
2606 	if (optiopt != NULL) {
2607 		switch (*optiopt) {
2608 		case 'n':
2609 			optimize = 0;
2610 			break;
2611 		case 'b':
2612 			optimize |= PF_OPTIMIZE_BASIC;
2613 			break;
2614 		case 'o':
2615 		case 'p':
2616 			optimize |= PF_OPTIMIZE_PROFILE;
2617 			break;
2618 		}
2619 	}
2620 
2621 	if ((rulesopt != NULL) && (loadopt & PFCTL_FLAG_OPTION) &&
2622 	    !anchorname[0] && !(opts & PF_OPT_NOACTION))
2623 		if (pfctl_get_skip_ifaces())
2624 			error = 1;
2625 
2626 	if (rulesopt != NULL && !(opts & (PF_OPT_MERGE|PF_OPT_NOACTION)) &&
2627 	    !anchorname[0] && (loadopt & PFCTL_FLAG_OPTION))
2628 		if (pfctl_file_fingerprints(dev, opts, PF_OSFP_FILE))
2629 			error = 1;
2630 
2631 	if (rulesopt != NULL) {
2632 		if (anchorname[0] == '_' || strstr(anchorname, "/_") != NULL)
2633 			errx(1, "anchor names beginning with '_' cannot "
2634 			    "be modified from the command line");
2635 		if (pfctl_rules(dev, rulesopt, opts, optimize,
2636 		    anchorname, NULL))
2637 			error = 1;
2638 		else if (!(opts & PF_OPT_NOACTION) &&
2639 		    (loadopt & PFCTL_FLAG_TABLE))
2640 			warn_namespace_collision(NULL);
2641 	}
2642 
2643 	if (opts & PF_OPT_ENABLE)
2644 		if (pfctl_enable(dev, opts))
2645 			error = 1;
2646 
2647 	if (debugopt != NULL) {
2648 		switch (*debugopt) {
2649 		case 'n':
2650 			pfctl_debug(dev, PF_DEBUG_NONE, opts);
2651 			break;
2652 		case 'u':
2653 			pfctl_debug(dev, PF_DEBUG_URGENT, opts);
2654 			break;
2655 		case 'm':
2656 			pfctl_debug(dev, PF_DEBUG_MISC, opts);
2657 			break;
2658 		case 'l':
2659 			pfctl_debug(dev, PF_DEBUG_NOISY, opts);
2660 			break;
2661 		}
2662 	}
2663 
2664 	exit(error);
2665 }
2666