xref: /freebsd/sbin/pfctl/pfctl.c (revision 31ba4ce8898f9dfa5e7f054fdbc26e50a599a6e3)
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 		HTONL(kill.cmp.creatorid);
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 	kill.cmp.id = htobe64(kill.cmp.id);
924 	if (pfctl_kill_states(dev, &kill, &killed))
925 		err(1, "DIOCKILLSTATES");
926 
927 	if ((opts & PF_OPT_QUIET) == 0)
928 		fprintf(stderr, "killed %d states\n", killed);
929 
930 	return (0);
931 }
932 
933 int
934 pfctl_get_pool(int dev, struct pfctl_pool *pool, u_int32_t nr,
935     u_int32_t ticket, int r_action, char *anchorname)
936 {
937 	struct pfioc_pooladdr pp;
938 	struct pf_pooladdr *pa;
939 	u_int32_t pnr, mpnr;
940 
941 	memset(&pp, 0, sizeof(pp));
942 	memcpy(pp.anchor, anchorname, sizeof(pp.anchor));
943 	pp.r_action = r_action;
944 	pp.r_num = nr;
945 	pp.ticket = ticket;
946 	if (ioctl(dev, DIOCGETADDRS, &pp)) {
947 		warn("DIOCGETADDRS");
948 		return (-1);
949 	}
950 	mpnr = pp.nr;
951 	TAILQ_INIT(&pool->list);
952 	for (pnr = 0; pnr < mpnr; ++pnr) {
953 		pp.nr = pnr;
954 		if (ioctl(dev, DIOCGETADDR, &pp)) {
955 			warn("DIOCGETADDR");
956 			return (-1);
957 		}
958 		pa = calloc(1, sizeof(struct pf_pooladdr));
959 		if (pa == NULL)
960 			err(1, "calloc");
961 		bcopy(&pp.addr, pa, sizeof(struct pf_pooladdr));
962 		TAILQ_INSERT_TAIL(&pool->list, pa, entries);
963 	}
964 
965 	return (0);
966 }
967 
968 void
969 pfctl_move_pool(struct pfctl_pool *src, struct pfctl_pool *dst)
970 {
971 	struct pf_pooladdr *pa;
972 
973 	while ((pa = TAILQ_FIRST(&src->list)) != NULL) {
974 		TAILQ_REMOVE(&src->list, pa, entries);
975 		TAILQ_INSERT_TAIL(&dst->list, pa, entries);
976 	}
977 }
978 
979 void
980 pfctl_clear_pool(struct pfctl_pool *pool)
981 {
982 	struct pf_pooladdr *pa;
983 
984 	while ((pa = TAILQ_FIRST(&pool->list)) != NULL) {
985 		TAILQ_REMOVE(&pool->list, pa, entries);
986 		free(pa);
987 	}
988 }
989 
990 void
991 pfctl_print_rule_counters(struct pfctl_rule *rule, int opts)
992 {
993 	if (opts & PF_OPT_DEBUG) {
994 		const char *t[PF_SKIP_COUNT] = { "i", "d", "f",
995 		    "p", "sa", "sp", "da", "dp" };
996 		int i;
997 
998 		printf("  [ Skip steps: ");
999 		for (i = 0; i < PF_SKIP_COUNT; ++i) {
1000 			if (rule->skip[i].nr == rule->nr + 1)
1001 				continue;
1002 			printf("%s=", t[i]);
1003 			if (rule->skip[i].nr == -1)
1004 				printf("end ");
1005 			else
1006 				printf("%u ", rule->skip[i].nr);
1007 		}
1008 		printf("]\n");
1009 
1010 		printf("  [ queue: qname=%s qid=%u pqname=%s pqid=%u ]\n",
1011 		    rule->qname, rule->qid, rule->pqname, rule->pqid);
1012 	}
1013 	if (opts & PF_OPT_VERBOSE) {
1014 		printf("  [ Evaluations: %-8llu  Packets: %-8llu  "
1015 			    "Bytes: %-10llu  States: %-6ju]\n",
1016 			    (unsigned long long)rule->evaluations,
1017 			    (unsigned long long)(rule->packets[0] +
1018 			    rule->packets[1]),
1019 			    (unsigned long long)(rule->bytes[0] +
1020 			    rule->bytes[1]), (uintmax_t)rule->states_cur);
1021 		if (!(opts & PF_OPT_DEBUG))
1022 			printf("  [ Inserted: uid %u pid %u "
1023 			    "State Creations: %-6ju]\n",
1024 			    (unsigned)rule->cuid, (unsigned)rule->cpid,
1025 			    (uintmax_t)rule->states_tot);
1026 	}
1027 }
1028 
1029 void
1030 pfctl_print_title(char *title)
1031 {
1032 	if (!first_title)
1033 		printf("\n");
1034 	first_title = 0;
1035 	printf("%s\n", title);
1036 }
1037 
1038 int
1039 pfctl_show_rules(int dev, char *path, int opts, enum pfctl_show format,
1040     char *anchorname, int depth)
1041 {
1042 	struct pfioc_rule pr;
1043 	struct pfctl_rule rule;
1044 	u_int32_t nr, mnr, header = 0;
1045 	int rule_numbers = opts & (PF_OPT_VERBOSE2 | PF_OPT_DEBUG);
1046 	int numeric = opts & PF_OPT_NUMERIC;
1047 	int len = strlen(path);
1048 	int brace;
1049 	char *p;
1050 
1051 	if (path[0])
1052 		snprintf(&path[len], MAXPATHLEN - len, "/%s", anchorname);
1053 	else
1054 		snprintf(&path[len], MAXPATHLEN - len, "%s", anchorname);
1055 
1056 	memset(&pr, 0, sizeof(pr));
1057 	memcpy(pr.anchor, path, sizeof(pr.anchor));
1058 	if (opts & PF_OPT_SHOWALL) {
1059 		pr.rule.action = PF_PASS;
1060 		if (ioctl(dev, DIOCGETRULES, &pr)) {
1061 			warn("DIOCGETRULES");
1062 			goto error;
1063 		}
1064 		header++;
1065 	}
1066 	pr.rule.action = PF_SCRUB;
1067 	if (ioctl(dev, DIOCGETRULES, &pr)) {
1068 		warn("DIOCGETRULES");
1069 		goto error;
1070 	}
1071 	if (opts & PF_OPT_SHOWALL) {
1072 		if (format == PFCTL_SHOW_RULES && (pr.nr > 0 || header))
1073 			pfctl_print_title("FILTER RULES:");
1074 		else if (format == PFCTL_SHOW_LABELS && labels)
1075 			pfctl_print_title("LABEL COUNTERS:");
1076 	}
1077 	mnr = pr.nr;
1078 
1079 	for (nr = 0; nr < mnr; ++nr) {
1080 		pr.nr = nr;
1081 		if (pfctl_get_clear_rule(dev, nr, pr.ticket, path, PF_SCRUB,
1082 		    &rule, pr.anchor_call, opts & PF_OPT_CLRRULECTRS)) {
1083 			warn("DIOCGETRULENV");
1084 			goto error;
1085 		}
1086 
1087 		if (pfctl_get_pool(dev, &rule.rpool,
1088 		    nr, pr.ticket, PF_SCRUB, path) != 0)
1089 			goto error;
1090 
1091 		switch (format) {
1092 		case PFCTL_SHOW_LABELS:
1093 			break;
1094 		case PFCTL_SHOW_RULES:
1095 			if (rule.label[0] && (opts & PF_OPT_SHOWALL))
1096 				labels = 1;
1097 			print_rule(&rule, pr.anchor_call, rule_numbers, numeric);
1098 			printf("\n");
1099 			pfctl_print_rule_counters(&rule, opts);
1100 			break;
1101 		case PFCTL_SHOW_NOTHING:
1102 			break;
1103 		}
1104 		pfctl_clear_pool(&rule.rpool);
1105 	}
1106 	pr.rule.action = PF_PASS;
1107 	if (ioctl(dev, DIOCGETRULES, &pr)) {
1108 		warn("DIOCGETRULES");
1109 		goto error;
1110 	}
1111 	mnr = pr.nr;
1112 	for (nr = 0; nr < mnr; ++nr) {
1113 		pr.nr = nr;
1114 		if (pfctl_get_clear_rule(dev, nr, pr.ticket, path, PF_PASS,
1115 		    &rule, pr.anchor_call, opts & PF_OPT_CLRRULECTRS)) {
1116 			warn("DIOCGETRULE");
1117 			goto error;
1118 		}
1119 
1120 		if (pfctl_get_pool(dev, &rule.rpool,
1121 		    nr, pr.ticket, PF_PASS, path) != 0)
1122 			goto error;
1123 
1124 		switch (format) {
1125 		case PFCTL_SHOW_LABELS: {
1126 			bool show = false;
1127 			int i = 0;
1128 
1129 			while (rule.label[i][0]) {
1130 				printf("%s ", rule.label[i++]);
1131 				show = true;
1132 			}
1133 
1134 			if (show) {
1135 				printf("%llu %llu %llu %llu"
1136 				    " %llu %llu %llu %ju\n",
1137 				    (unsigned long long)rule.evaluations,
1138 				    (unsigned long long)(rule.packets[0] +
1139 				    rule.packets[1]),
1140 				    (unsigned long long)(rule.bytes[0] +
1141 				    rule.bytes[1]),
1142 				    (unsigned long long)rule.packets[0],
1143 				    (unsigned long long)rule.bytes[0],
1144 				    (unsigned long long)rule.packets[1],
1145 				    (unsigned long long)rule.bytes[1],
1146 				    (uintmax_t)rule.states_tot);
1147 			}
1148 			break;
1149 		}
1150 		case PFCTL_SHOW_RULES:
1151 			brace = 0;
1152 			if (rule.label[0] && (opts & PF_OPT_SHOWALL))
1153 				labels = 1;
1154 			INDENT(depth, !(opts & PF_OPT_VERBOSE));
1155 			if (pr.anchor_call[0] &&
1156 			   ((((p = strrchr(pr.anchor_call, '_')) != NULL) &&
1157 			   ((void *)p == (void *)pr.anchor_call ||
1158 			   *(--p) == '/')) || (opts & PF_OPT_RECURSE))) {
1159 				brace++;
1160 				if ((p = strrchr(pr.anchor_call, '/')) !=
1161 				    NULL)
1162 					p++;
1163 				else
1164 					p = &pr.anchor_call[0];
1165 			} else
1166 				p = &pr.anchor_call[0];
1167 
1168 			print_rule(&rule, p, rule_numbers, numeric);
1169 			if (brace)
1170 				printf(" {\n");
1171 			else
1172 				printf("\n");
1173 			pfctl_print_rule_counters(&rule, opts);
1174 			if (brace) {
1175 				pfctl_show_rules(dev, path, opts, format,
1176 				    p, depth + 1);
1177 				INDENT(depth, !(opts & PF_OPT_VERBOSE));
1178 				printf("}\n");
1179 			}
1180 			break;
1181 		case PFCTL_SHOW_NOTHING:
1182 			break;
1183 		}
1184 		pfctl_clear_pool(&rule.rpool);
1185 	}
1186 	path[len] = '\0';
1187 	return (0);
1188 
1189  error:
1190 	path[len] = '\0';
1191 	return (-1);
1192 }
1193 
1194 int
1195 pfctl_show_nat(int dev, int opts, char *anchorname)
1196 {
1197 	struct pfioc_rule pr;
1198 	struct pfctl_rule rule;
1199 	u_int32_t mnr, nr;
1200 	static int nattype[3] = { PF_NAT, PF_RDR, PF_BINAT };
1201 	int i, dotitle = opts & PF_OPT_SHOWALL;
1202 
1203 	memset(&pr, 0, sizeof(pr));
1204 	memcpy(pr.anchor, anchorname, sizeof(pr.anchor));
1205 	for (i = 0; i < 3; i++) {
1206 		pr.rule.action = nattype[i];
1207 		if (ioctl(dev, DIOCGETRULES, &pr)) {
1208 			warn("DIOCGETRULES");
1209 			return (-1);
1210 		}
1211 		mnr = pr.nr;
1212 		for (nr = 0; nr < mnr; ++nr) {
1213 			pr.nr = nr;
1214 			if (pfctl_get_rule(dev, nr, pr.ticket, anchorname,
1215 			    nattype[i], &rule, pr.anchor_call)) {
1216 				warn("DIOCGETRULE");
1217 				return (-1);
1218 			}
1219 			if (pfctl_get_pool(dev, &rule.rpool, nr,
1220 			    pr.ticket, nattype[i], anchorname) != 0)
1221 				return (-1);
1222 			if (dotitle) {
1223 				pfctl_print_title("TRANSLATION RULES:");
1224 				dotitle = 0;
1225 			}
1226 			print_rule(&rule, pr.anchor_call,
1227 			    opts & PF_OPT_VERBOSE2, opts & PF_OPT_NUMERIC);
1228 			printf("\n");
1229 			pfctl_print_rule_counters(&rule, opts);
1230 			pfctl_clear_pool(&rule.rpool);
1231 		}
1232 	}
1233 	return (0);
1234 }
1235 
1236 int
1237 pfctl_show_src_nodes(int dev, int opts)
1238 {
1239 	struct pfioc_src_nodes psn;
1240 	struct pf_src_node *p;
1241 	char *inbuf = NULL, *newinbuf = NULL;
1242 	unsigned int len = 0;
1243 	int i;
1244 
1245 	memset(&psn, 0, sizeof(psn));
1246 	for (;;) {
1247 		psn.psn_len = len;
1248 		if (len) {
1249 			newinbuf = realloc(inbuf, len);
1250 			if (newinbuf == NULL)
1251 				err(1, "realloc");
1252 			psn.psn_buf = inbuf = newinbuf;
1253 		}
1254 		if (ioctl(dev, DIOCGETSRCNODES, &psn) < 0) {
1255 			warn("DIOCGETSRCNODES");
1256 			free(inbuf);
1257 			return (-1);
1258 		}
1259 		if (psn.psn_len + sizeof(struct pfioc_src_nodes) < len)
1260 			break;
1261 		if (len == 0 && psn.psn_len == 0)
1262 			goto done;
1263 		if (len == 0 && psn.psn_len != 0)
1264 			len = psn.psn_len;
1265 		if (psn.psn_len == 0)
1266 			goto done;	/* no src_nodes */
1267 		len *= 2;
1268 	}
1269 	p = psn.psn_src_nodes;
1270 	if (psn.psn_len > 0 && (opts & PF_OPT_SHOWALL))
1271 		pfctl_print_title("SOURCE TRACKING NODES:");
1272 	for (i = 0; i < psn.psn_len; i += sizeof(*p)) {
1273 		print_src_node(p, opts);
1274 		p++;
1275 	}
1276 done:
1277 	free(inbuf);
1278 	return (0);
1279 }
1280 
1281 int
1282 pfctl_show_states(int dev, const char *iface, int opts)
1283 {
1284 	struct pfctl_states states;
1285 	struct pfctl_state *s;
1286 	int dotitle = (opts & PF_OPT_SHOWALL);
1287 
1288 	memset(&states, 0, sizeof(states));
1289 
1290 	if (pfctl_get_states(dev, &states))
1291 		return (-1);
1292 
1293 	TAILQ_FOREACH(s, &states.states, entry) {
1294 		if (iface != NULL && strcmp(s->ifname, iface))
1295 			continue;
1296 		if (dotitle) {
1297 			pfctl_print_title("STATES:");
1298 			dotitle = 0;
1299 		}
1300 		print_state(s, opts);
1301 	}
1302 
1303 	pfctl_free_states(&states);
1304 
1305 	return (0);
1306 }
1307 
1308 int
1309 pfctl_show_status(int dev, int opts)
1310 {
1311 	struct pf_status	status;
1312 	struct pfctl_syncookies	cookies;
1313 
1314 	if (ioctl(dev, DIOCGETSTATUS, &status)) {
1315 		warn("DIOCGETSTATUS");
1316 		return (-1);
1317 	}
1318 	if (pfctl_get_syncookies(dev, &cookies)) {
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 	return (0);
1326 }
1327 
1328 int
1329 pfctl_show_running(int dev)
1330 {
1331 	struct pf_status status;
1332 
1333 	if (ioctl(dev, DIOCGETSTATUS, &status)) {
1334 		warn("DIOCGETSTATUS");
1335 		return (-1);
1336 	}
1337 
1338 	print_running(&status);
1339 	return (!status.running);
1340 }
1341 
1342 int
1343 pfctl_show_timeouts(int dev, int opts)
1344 {
1345 	struct pfioc_tm pt;
1346 	int i;
1347 
1348 	if (opts & PF_OPT_SHOWALL)
1349 		pfctl_print_title("TIMEOUTS:");
1350 	memset(&pt, 0, sizeof(pt));
1351 	for (i = 0; pf_timeouts[i].name; i++) {
1352 		pt.timeout = pf_timeouts[i].timeout;
1353 		if (ioctl(dev, DIOCGETTIMEOUT, &pt))
1354 			err(1, "DIOCGETTIMEOUT");
1355 		printf("%-20s %10d", pf_timeouts[i].name, pt.seconds);
1356 		if (pf_timeouts[i].timeout >= PFTM_ADAPTIVE_START &&
1357 		    pf_timeouts[i].timeout <= PFTM_ADAPTIVE_END)
1358 			printf(" states");
1359 		else
1360 			printf("s");
1361 		printf("\n");
1362 	}
1363 	return (0);
1364 
1365 }
1366 
1367 int
1368 pfctl_show_limits(int dev, int opts)
1369 {
1370 	struct pfioc_limit pl;
1371 	int i;
1372 
1373 	if (opts & PF_OPT_SHOWALL)
1374 		pfctl_print_title("LIMITS:");
1375 	memset(&pl, 0, sizeof(pl));
1376 	for (i = 0; pf_limits[i].name; i++) {
1377 		pl.index = pf_limits[i].index;
1378 		if (ioctl(dev, DIOCGETLIMIT, &pl))
1379 			err(1, "DIOCGETLIMIT");
1380 		printf("%-13s ", pf_limits[i].name);
1381 		if (pl.limit == UINT_MAX)
1382 			printf("unlimited\n");
1383 		else
1384 			printf("hard limit %8u\n", pl.limit);
1385 	}
1386 	return (0);
1387 }
1388 
1389 /* callbacks for rule/nat/rdr/addr */
1390 int
1391 pfctl_add_pool(struct pfctl *pf, struct pfctl_pool *p, sa_family_t af)
1392 {
1393 	struct pf_pooladdr *pa;
1394 
1395 	if ((pf->opts & PF_OPT_NOACTION) == 0) {
1396 		if (ioctl(pf->dev, DIOCBEGINADDRS, &pf->paddr))
1397 			err(1, "DIOCBEGINADDRS");
1398 	}
1399 
1400 	pf->paddr.af = af;
1401 	TAILQ_FOREACH(pa, &p->list, entries) {
1402 		memcpy(&pf->paddr.addr, pa, sizeof(struct pf_pooladdr));
1403 		if ((pf->opts & PF_OPT_NOACTION) == 0) {
1404 			if (ioctl(pf->dev, DIOCADDADDR, &pf->paddr))
1405 				err(1, "DIOCADDADDR");
1406 		}
1407 	}
1408 	return (0);
1409 }
1410 
1411 int
1412 pfctl_append_rule(struct pfctl *pf, struct pfctl_rule *r,
1413     const char *anchor_call)
1414 {
1415 	u_int8_t		rs_num;
1416 	struct pfctl_rule	*rule;
1417 	struct pfctl_ruleset	*rs;
1418 	char 			*p;
1419 
1420 	rs_num = pf_get_ruleset_number(r->action);
1421 	if (rs_num == PF_RULESET_MAX)
1422 		errx(1, "Invalid rule type %d", r->action);
1423 
1424 	rs = &pf->anchor->ruleset;
1425 
1426 	if (anchor_call[0] && r->anchor == NULL) {
1427 		/*
1428 		 * Don't make non-brace anchors part of the main anchor pool.
1429 		 */
1430 		if ((r->anchor = calloc(1, sizeof(*r->anchor))) == NULL)
1431 			err(1, "pfctl_append_rule: calloc");
1432 
1433 		pf_init_ruleset(&r->anchor->ruleset);
1434 		r->anchor->ruleset.anchor = r->anchor;
1435 		if (strlcpy(r->anchor->path, anchor_call,
1436 		    sizeof(rule->anchor->path)) >= sizeof(rule->anchor->path))
1437 			errx(1, "pfctl_append_rule: strlcpy");
1438 		if ((p = strrchr(anchor_call, '/')) != NULL) {
1439 			if (!strlen(p))
1440 				err(1, "pfctl_append_rule: bad anchor name %s",
1441 				    anchor_call);
1442 		} else
1443 			p = (char *)anchor_call;
1444 		if (strlcpy(r->anchor->name, p,
1445 		    sizeof(rule->anchor->name)) >= sizeof(rule->anchor->name))
1446 			errx(1, "pfctl_append_rule: strlcpy");
1447 	}
1448 
1449 	if ((rule = calloc(1, sizeof(*rule))) == NULL)
1450 		err(1, "calloc");
1451 	bcopy(r, rule, sizeof(*rule));
1452 	TAILQ_INIT(&rule->rpool.list);
1453 	pfctl_move_pool(&r->rpool, &rule->rpool);
1454 
1455 	TAILQ_INSERT_TAIL(rs->rules[rs_num].active.ptr, rule, entries);
1456 	return (0);
1457 }
1458 
1459 int
1460 pfctl_ruleset_trans(struct pfctl *pf, char *path, struct pfctl_anchor *a)
1461 {
1462 	int osize = pf->trans->pfrb_size;
1463 
1464 	if ((pf->loadopt & PFCTL_FLAG_NAT) != 0) {
1465 		if (pfctl_add_trans(pf->trans, PF_RULESET_NAT, path) ||
1466 		    pfctl_add_trans(pf->trans, PF_RULESET_BINAT, path) ||
1467 		    pfctl_add_trans(pf->trans, PF_RULESET_RDR, path))
1468 			return (1);
1469 	}
1470 	if (a == pf->astack[0] && ((altqsupport &&
1471 	    (pf->loadopt & PFCTL_FLAG_ALTQ) != 0))) {
1472 		if (pfctl_add_trans(pf->trans, PF_RULESET_ALTQ, path))
1473 			return (2);
1474 	}
1475 	if ((pf->loadopt & PFCTL_FLAG_FILTER) != 0) {
1476 		if (pfctl_add_trans(pf->trans, PF_RULESET_SCRUB, path) ||
1477 		    pfctl_add_trans(pf->trans, PF_RULESET_FILTER, path))
1478 			return (3);
1479 	}
1480 	if (pf->loadopt & PFCTL_FLAG_TABLE)
1481 		if (pfctl_add_trans(pf->trans, PF_RULESET_TABLE, path))
1482 			return (4);
1483 	if (pfctl_trans(pf->dev, pf->trans, DIOCXBEGIN, osize))
1484 		return (5);
1485 
1486 	return (0);
1487 }
1488 
1489 int
1490 pfctl_load_ruleset(struct pfctl *pf, char *path, struct pfctl_ruleset *rs,
1491     int rs_num, int depth)
1492 {
1493 	struct pfctl_rule *r;
1494 	int		error, len = strlen(path);
1495 	int		brace = 0;
1496 
1497 	pf->anchor = rs->anchor;
1498 
1499 	if (path[0])
1500 		snprintf(&path[len], MAXPATHLEN - len, "/%s", pf->anchor->name);
1501 	else
1502 		snprintf(&path[len], MAXPATHLEN - len, "%s", pf->anchor->name);
1503 
1504 	if (depth) {
1505 		if (TAILQ_FIRST(rs->rules[rs_num].active.ptr) != NULL) {
1506 			brace++;
1507 			if (pf->opts & PF_OPT_VERBOSE)
1508 				printf(" {\n");
1509 			if ((pf->opts & PF_OPT_NOACTION) == 0 &&
1510 			    (error = pfctl_ruleset_trans(pf,
1511 			    path, rs->anchor))) {
1512 				printf("pfctl_load_rulesets: "
1513 				    "pfctl_ruleset_trans %d\n", error);
1514 				goto error;
1515 			}
1516 		} else if (pf->opts & PF_OPT_VERBOSE)
1517 			printf("\n");
1518 
1519 	}
1520 
1521 	if (pf->optimize && rs_num == PF_RULESET_FILTER)
1522 		pfctl_optimize_ruleset(pf, rs);
1523 
1524 	while ((r = TAILQ_FIRST(rs->rules[rs_num].active.ptr)) != NULL) {
1525 		TAILQ_REMOVE(rs->rules[rs_num].active.ptr, r, entries);
1526 		if ((error = pfctl_load_rule(pf, path, r, depth)))
1527 			goto error;
1528 		if (r->anchor) {
1529 			if ((error = pfctl_load_ruleset(pf, path,
1530 			    &r->anchor->ruleset, rs_num, depth + 1)))
1531 				goto error;
1532 		} else if (pf->opts & PF_OPT_VERBOSE)
1533 			printf("\n");
1534 		free(r);
1535 	}
1536 	if (brace && pf->opts & PF_OPT_VERBOSE) {
1537 		INDENT(depth - 1, (pf->opts & PF_OPT_VERBOSE));
1538 		printf("}\n");
1539 	}
1540 	path[len] = '\0';
1541 	return (0);
1542 
1543  error:
1544 	path[len] = '\0';
1545 	return (error);
1546 
1547 }
1548 
1549 int
1550 pfctl_load_rule(struct pfctl *pf, char *path, struct pfctl_rule *r, int depth)
1551 {
1552 	u_int8_t		rs_num = pf_get_ruleset_number(r->action);
1553 	char			*name;
1554 	u_int32_t		ticket;
1555 	char			anchor[PF_ANCHOR_NAME_SIZE];
1556 	int			len = strlen(path);
1557 
1558 	/* set up anchor before adding to path for anchor_call */
1559 	if ((pf->opts & PF_OPT_NOACTION) == 0)
1560 		ticket = pfctl_get_ticket(pf->trans, rs_num, path);
1561 	if (strlcpy(anchor, path, sizeof(anchor)) >= sizeof(anchor))
1562 		errx(1, "pfctl_load_rule: strlcpy");
1563 
1564 	if (r->anchor) {
1565 		if (r->anchor->match) {
1566 			if (path[0])
1567 				snprintf(&path[len], MAXPATHLEN - len,
1568 				    "/%s", r->anchor->name);
1569 			else
1570 				snprintf(&path[len], MAXPATHLEN - len,
1571 				    "%s", r->anchor->name);
1572 			name = r->anchor->name;
1573 		} else
1574 			name = r->anchor->path;
1575 	} else
1576 		name = "";
1577 
1578 	if ((pf->opts & PF_OPT_NOACTION) == 0) {
1579 		if (pfctl_add_pool(pf, &r->rpool, r->af))
1580 			return (1);
1581 		if (pfctl_add_rule(pf->dev, r, anchor, name, ticket,
1582 		    pf->paddr.ticket))
1583 			err(1, "DIOCADDRULENV");
1584 	}
1585 
1586 	if (pf->opts & PF_OPT_VERBOSE) {
1587 		INDENT(depth, !(pf->opts & PF_OPT_VERBOSE2));
1588 		print_rule(r, r->anchor ? r->anchor->name : "",
1589 		    pf->opts & PF_OPT_VERBOSE2,
1590 		    pf->opts & PF_OPT_NUMERIC);
1591 	}
1592 	path[len] = '\0';
1593 	pfctl_clear_pool(&r->rpool);
1594 	return (0);
1595 }
1596 
1597 int
1598 pfctl_add_altq(struct pfctl *pf, struct pf_altq *a)
1599 {
1600 	if (altqsupport &&
1601 	    (loadopt & PFCTL_FLAG_ALTQ) != 0) {
1602 		memcpy(&pf->paltq->altq, a, sizeof(struct pf_altq));
1603 		if ((pf->opts & PF_OPT_NOACTION) == 0) {
1604 			if (ioctl(pf->dev, DIOCADDALTQ, pf->paltq)) {
1605 				if (errno == ENXIO)
1606 					errx(1, "qtype not configured");
1607 				else if (errno == ENODEV)
1608 					errx(1, "%s: driver does not support "
1609 					    "altq", a->ifname);
1610 				else
1611 					err(1, "DIOCADDALTQ");
1612 			}
1613 		}
1614 		pfaltq_store(&pf->paltq->altq);
1615 	}
1616 	return (0);
1617 }
1618 
1619 int
1620 pfctl_rules(int dev, char *filename, int opts, int optimize,
1621     char *anchorname, struct pfr_buffer *trans)
1622 {
1623 #define ERR(x) do { warn(x); goto _error; } while(0)
1624 #define ERRX(x) do { warnx(x); goto _error; } while(0)
1625 
1626 	struct pfr_buffer	*t, buf;
1627 	struct pfioc_altq	 pa;
1628 	struct pfctl		 pf;
1629 	struct pfctl_ruleset	*rs;
1630 	struct pfr_table	 trs;
1631 	char			*path;
1632 	int			 osize;
1633 
1634 	RB_INIT(&pf_anchors);
1635 	memset(&pf_main_anchor, 0, sizeof(pf_main_anchor));
1636 	pf_init_ruleset(&pf_main_anchor.ruleset);
1637 	pf_main_anchor.ruleset.anchor = &pf_main_anchor;
1638 	if (trans == NULL) {
1639 		bzero(&buf, sizeof(buf));
1640 		buf.pfrb_type = PFRB_TRANS;
1641 		t = &buf;
1642 		osize = 0;
1643 	} else {
1644 		t = trans;
1645 		osize = t->pfrb_size;
1646 	}
1647 
1648 	memset(&pa, 0, sizeof(pa));
1649 	pa.version = PFIOC_ALTQ_VERSION;
1650 	memset(&pf, 0, sizeof(pf));
1651 	memset(&trs, 0, sizeof(trs));
1652 	if ((path = calloc(1, MAXPATHLEN)) == NULL)
1653 		ERRX("pfctl_rules: calloc");
1654 	if (strlcpy(trs.pfrt_anchor, anchorname,
1655 	    sizeof(trs.pfrt_anchor)) >= sizeof(trs.pfrt_anchor))
1656 		ERRX("pfctl_rules: strlcpy");
1657 	pf.dev = dev;
1658 	pf.opts = opts;
1659 	pf.optimize = optimize;
1660 	pf.loadopt = loadopt;
1661 
1662 	/* non-brace anchor, create without resolving the path */
1663 	if ((pf.anchor = calloc(1, sizeof(*pf.anchor))) == NULL)
1664 		ERRX("pfctl_rules: calloc");
1665 	rs = &pf.anchor->ruleset;
1666 	pf_init_ruleset(rs);
1667 	rs->anchor = pf.anchor;
1668 	if (strlcpy(pf.anchor->path, anchorname,
1669 	    sizeof(pf.anchor->path)) >= sizeof(pf.anchor->path))
1670 		errx(1, "pfctl_add_rule: strlcpy");
1671 	if (strlcpy(pf.anchor->name, anchorname,
1672 	    sizeof(pf.anchor->name)) >= sizeof(pf.anchor->name))
1673 		errx(1, "pfctl_add_rule: strlcpy");
1674 
1675 
1676 	pf.astack[0] = pf.anchor;
1677 	pf.asd = 0;
1678 	if (anchorname[0])
1679 		pf.loadopt &= ~PFCTL_FLAG_ALTQ;
1680 	pf.paltq = &pa;
1681 	pf.trans = t;
1682 	pfctl_init_options(&pf);
1683 
1684 	if ((opts & PF_OPT_NOACTION) == 0) {
1685 		/*
1686 		 * XXX For the time being we need to open transactions for
1687 		 * the main ruleset before parsing, because tables are still
1688 		 * loaded at parse time.
1689 		 */
1690 		if (pfctl_ruleset_trans(&pf, anchorname, pf.anchor))
1691 			ERRX("pfctl_rules");
1692 		if (altqsupport && (pf.loadopt & PFCTL_FLAG_ALTQ))
1693 			pa.ticket =
1694 			    pfctl_get_ticket(t, PF_RULESET_ALTQ, anchorname);
1695 		if (pf.loadopt & PFCTL_FLAG_TABLE)
1696 			pf.astack[0]->ruleset.tticket =
1697 			    pfctl_get_ticket(t, PF_RULESET_TABLE, anchorname);
1698 	}
1699 
1700 	if (parse_config(filename, &pf) < 0) {
1701 		if ((opts & PF_OPT_NOACTION) == 0)
1702 			ERRX("Syntax error in config file: "
1703 			    "pf rules not loaded");
1704 		else
1705 			goto _error;
1706 	}
1707 	if (loadopt & PFCTL_FLAG_OPTION)
1708 		pfctl_adjust_skip_ifaces(&pf);
1709 
1710 	if ((pf.loadopt & PFCTL_FLAG_FILTER &&
1711 	    (pfctl_load_ruleset(&pf, path, rs, PF_RULESET_SCRUB, 0))) ||
1712 	    (pf.loadopt & PFCTL_FLAG_NAT &&
1713 	    (pfctl_load_ruleset(&pf, path, rs, PF_RULESET_NAT, 0) ||
1714 	    pfctl_load_ruleset(&pf, path, rs, PF_RULESET_RDR, 0) ||
1715 	    pfctl_load_ruleset(&pf, path, rs, PF_RULESET_BINAT, 0))) ||
1716 	    (pf.loadopt & PFCTL_FLAG_FILTER &&
1717 	    pfctl_load_ruleset(&pf, path, rs, PF_RULESET_FILTER, 0))) {
1718 		if ((opts & PF_OPT_NOACTION) == 0)
1719 			ERRX("Unable to load rules into kernel");
1720 		else
1721 			goto _error;
1722 	}
1723 
1724 	if ((altqsupport && (pf.loadopt & PFCTL_FLAG_ALTQ) != 0))
1725 		if (check_commit_altq(dev, opts) != 0)
1726 			ERRX("errors in altq config");
1727 
1728 	/* process "load anchor" directives */
1729 	if (!anchorname[0])
1730 		if (pfctl_load_anchors(dev, &pf, t) == -1)
1731 			ERRX("load anchors");
1732 
1733 	if (trans == NULL && (opts & PF_OPT_NOACTION) == 0) {
1734 		if (!anchorname[0])
1735 			if (pfctl_load_options(&pf))
1736 				goto _error;
1737 		if (pfctl_trans(dev, t, DIOCXCOMMIT, osize))
1738 			ERR("DIOCXCOMMIT");
1739 	}
1740 	free(path);
1741 	return (0);
1742 
1743 _error:
1744 	if (trans == NULL) {	/* main ruleset */
1745 		if ((opts & PF_OPT_NOACTION) == 0)
1746 			if (pfctl_trans(dev, t, DIOCXROLLBACK, osize))
1747 				err(1, "DIOCXROLLBACK");
1748 		exit(1);
1749 	} else {		/* sub ruleset */
1750 		free(path);
1751 		return (-1);
1752 	}
1753 
1754 #undef ERR
1755 #undef ERRX
1756 }
1757 
1758 FILE *
1759 pfctl_fopen(const char *name, const char *mode)
1760 {
1761 	struct stat	 st;
1762 	FILE		*fp;
1763 
1764 	fp = fopen(name, mode);
1765 	if (fp == NULL)
1766 		return (NULL);
1767 	if (fstat(fileno(fp), &st)) {
1768 		fclose(fp);
1769 		return (NULL);
1770 	}
1771 	if (S_ISDIR(st.st_mode)) {
1772 		fclose(fp);
1773 		errno = EISDIR;
1774 		return (NULL);
1775 	}
1776 	return (fp);
1777 }
1778 
1779 void
1780 pfctl_init_options(struct pfctl *pf)
1781 {
1782 
1783 	pf->timeout[PFTM_TCP_FIRST_PACKET] = PFTM_TCP_FIRST_PACKET_VAL;
1784 	pf->timeout[PFTM_TCP_OPENING] = PFTM_TCP_OPENING_VAL;
1785 	pf->timeout[PFTM_TCP_ESTABLISHED] = PFTM_TCP_ESTABLISHED_VAL;
1786 	pf->timeout[PFTM_TCP_CLOSING] = PFTM_TCP_CLOSING_VAL;
1787 	pf->timeout[PFTM_TCP_FIN_WAIT] = PFTM_TCP_FIN_WAIT_VAL;
1788 	pf->timeout[PFTM_TCP_CLOSED] = PFTM_TCP_CLOSED_VAL;
1789 	pf->timeout[PFTM_UDP_FIRST_PACKET] = PFTM_UDP_FIRST_PACKET_VAL;
1790 	pf->timeout[PFTM_UDP_SINGLE] = PFTM_UDP_SINGLE_VAL;
1791 	pf->timeout[PFTM_UDP_MULTIPLE] = PFTM_UDP_MULTIPLE_VAL;
1792 	pf->timeout[PFTM_ICMP_FIRST_PACKET] = PFTM_ICMP_FIRST_PACKET_VAL;
1793 	pf->timeout[PFTM_ICMP_ERROR_REPLY] = PFTM_ICMP_ERROR_REPLY_VAL;
1794 	pf->timeout[PFTM_OTHER_FIRST_PACKET] = PFTM_OTHER_FIRST_PACKET_VAL;
1795 	pf->timeout[PFTM_OTHER_SINGLE] = PFTM_OTHER_SINGLE_VAL;
1796 	pf->timeout[PFTM_OTHER_MULTIPLE] = PFTM_OTHER_MULTIPLE_VAL;
1797 	pf->timeout[PFTM_FRAG] = PFTM_FRAG_VAL;
1798 	pf->timeout[PFTM_INTERVAL] = PFTM_INTERVAL_VAL;
1799 	pf->timeout[PFTM_SRC_NODE] = PFTM_SRC_NODE_VAL;
1800 	pf->timeout[PFTM_TS_DIFF] = PFTM_TS_DIFF_VAL;
1801 	pf->timeout[PFTM_ADAPTIVE_START] = PFSTATE_ADAPT_START;
1802 	pf->timeout[PFTM_ADAPTIVE_END] = PFSTATE_ADAPT_END;
1803 
1804 	pf->limit[PF_LIMIT_STATES] = PFSTATE_HIWAT;
1805 	pf->limit[PF_LIMIT_FRAGS] = PFFRAG_FRENT_HIWAT;
1806 	pf->limit[PF_LIMIT_SRC_NODES] = PFSNODE_HIWAT;
1807 	pf->limit[PF_LIMIT_TABLE_ENTRIES] = PFR_KENTRY_HIWAT;
1808 
1809 	pf->debug = PF_DEBUG_URGENT;
1810 }
1811 
1812 int
1813 pfctl_load_options(struct pfctl *pf)
1814 {
1815 	int i, error = 0;
1816 
1817 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1818 		return (0);
1819 
1820 	/* load limits */
1821 	for (i = 0; i < PF_LIMIT_MAX; i++) {
1822 		if ((pf->opts & PF_OPT_MERGE) && !pf->limit_set[i])
1823 			continue;
1824 		if (pfctl_load_limit(pf, i, pf->limit[i]))
1825 			error = 1;
1826 	}
1827 
1828 	/*
1829 	 * If we've set the limit, but haven't explicitly set adaptive
1830 	 * timeouts, do it now with a start of 60% and end of 120%.
1831 	 */
1832 	if (pf->limit_set[PF_LIMIT_STATES] &&
1833 	    !pf->timeout_set[PFTM_ADAPTIVE_START] &&
1834 	    !pf->timeout_set[PFTM_ADAPTIVE_END]) {
1835 		pf->timeout[PFTM_ADAPTIVE_START] =
1836 			(pf->limit[PF_LIMIT_STATES] / 10) * 6;
1837 		pf->timeout_set[PFTM_ADAPTIVE_START] = 1;
1838 		pf->timeout[PFTM_ADAPTIVE_END] =
1839 			(pf->limit[PF_LIMIT_STATES] / 10) * 12;
1840 		pf->timeout_set[PFTM_ADAPTIVE_END] = 1;
1841 	}
1842 
1843 	/* load timeouts */
1844 	for (i = 0; i < PFTM_MAX; i++) {
1845 		if ((pf->opts & PF_OPT_MERGE) && !pf->timeout_set[i])
1846 			continue;
1847 		if (pfctl_load_timeout(pf, i, pf->timeout[i]))
1848 			error = 1;
1849 	}
1850 
1851 	/* load debug */
1852 	if (!(pf->opts & PF_OPT_MERGE) || pf->debug_set)
1853 		if (pfctl_load_debug(pf, pf->debug))
1854 			error = 1;
1855 
1856 	/* load logif */
1857 	if (!(pf->opts & PF_OPT_MERGE) || pf->ifname_set)
1858 		if (pfctl_load_logif(pf, pf->ifname))
1859 			error = 1;
1860 
1861 	/* load hostid */
1862 	if (!(pf->opts & PF_OPT_MERGE) || pf->hostid_set)
1863 		if (pfctl_load_hostid(pf, pf->hostid))
1864 			error = 1;
1865 
1866 	/* load keepcounters */
1867 	if (pfctl_set_keepcounters(pf->dev, pf->keep_counters))
1868 		error = 1;
1869 
1870 	/* load syncookies settings */
1871 	if (pfctl_load_syncookies(pf, pf->syncookies))
1872 		error = 1;
1873 
1874 	return (error);
1875 }
1876 
1877 int
1878 pfctl_set_limit(struct pfctl *pf, const char *opt, unsigned int limit)
1879 {
1880 	int i;
1881 
1882 
1883 	for (i = 0; pf_limits[i].name; i++) {
1884 		if (strcasecmp(opt, pf_limits[i].name) == 0) {
1885 			pf->limit[pf_limits[i].index] = limit;
1886 			pf->limit_set[pf_limits[i].index] = 1;
1887 			break;
1888 		}
1889 	}
1890 	if (pf_limits[i].name == NULL) {
1891 		warnx("Bad pool name.");
1892 		return (1);
1893 	}
1894 
1895 	if (pf->opts & PF_OPT_VERBOSE)
1896 		printf("set limit %s %d\n", opt, limit);
1897 
1898 	return (0);
1899 }
1900 
1901 int
1902 pfctl_load_limit(struct pfctl *pf, unsigned int index, unsigned int limit)
1903 {
1904 	struct pfioc_limit pl;
1905 
1906 	memset(&pl, 0, sizeof(pl));
1907 	pl.index = index;
1908 	pl.limit = limit;
1909 	if (ioctl(pf->dev, DIOCSETLIMIT, &pl)) {
1910 		if (errno == EBUSY)
1911 			warnx("Current pool size exceeds requested hard limit");
1912 		else
1913 			warnx("DIOCSETLIMIT");
1914 		return (1);
1915 	}
1916 	return (0);
1917 }
1918 
1919 int
1920 pfctl_set_timeout(struct pfctl *pf, const char *opt, int seconds, int quiet)
1921 {
1922 	int i;
1923 
1924 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1925 		return (0);
1926 
1927 	for (i = 0; pf_timeouts[i].name; i++) {
1928 		if (strcasecmp(opt, pf_timeouts[i].name) == 0) {
1929 			pf->timeout[pf_timeouts[i].timeout] = seconds;
1930 			pf->timeout_set[pf_timeouts[i].timeout] = 1;
1931 			break;
1932 		}
1933 	}
1934 
1935 	if (pf_timeouts[i].name == NULL) {
1936 		warnx("Bad timeout name.");
1937 		return (1);
1938 	}
1939 
1940 
1941 	if (pf->opts & PF_OPT_VERBOSE && ! quiet)
1942 		printf("set timeout %s %d\n", opt, seconds);
1943 
1944 	return (0);
1945 }
1946 
1947 int
1948 pfctl_load_timeout(struct pfctl *pf, unsigned int timeout, unsigned int seconds)
1949 {
1950 	struct pfioc_tm pt;
1951 
1952 	memset(&pt, 0, sizeof(pt));
1953 	pt.timeout = timeout;
1954 	pt.seconds = seconds;
1955 	if (ioctl(pf->dev, DIOCSETTIMEOUT, &pt)) {
1956 		warnx("DIOCSETTIMEOUT");
1957 		return (1);
1958 	}
1959 	return (0);
1960 }
1961 
1962 int
1963 pfctl_set_optimization(struct pfctl *pf, const char *opt)
1964 {
1965 	const struct pf_hint *hint;
1966 	int i, r;
1967 
1968 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1969 		return (0);
1970 
1971 	for (i = 0; pf_hints[i].name; i++)
1972 		if (strcasecmp(opt, pf_hints[i].name) == 0)
1973 			break;
1974 
1975 	hint = pf_hints[i].hint;
1976 	if (hint == NULL) {
1977 		warnx("invalid state timeouts optimization");
1978 		return (1);
1979 	}
1980 
1981 	for (i = 0; hint[i].name; i++)
1982 		if ((r = pfctl_set_timeout(pf, hint[i].name,
1983 		    hint[i].timeout, 1)))
1984 			return (r);
1985 
1986 	if (pf->opts & PF_OPT_VERBOSE)
1987 		printf("set optimization %s\n", opt);
1988 
1989 	return (0);
1990 }
1991 
1992 int
1993 pfctl_set_logif(struct pfctl *pf, char *ifname)
1994 {
1995 
1996 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1997 		return (0);
1998 
1999 	if (!strcmp(ifname, "none")) {
2000 		free(pf->ifname);
2001 		pf->ifname = NULL;
2002 	} else {
2003 		pf->ifname = strdup(ifname);
2004 		if (!pf->ifname)
2005 			errx(1, "pfctl_set_logif: strdup");
2006 	}
2007 	pf->ifname_set = 1;
2008 
2009 	if (pf->opts & PF_OPT_VERBOSE)
2010 		printf("set loginterface %s\n", ifname);
2011 
2012 	return (0);
2013 }
2014 
2015 int
2016 pfctl_load_logif(struct pfctl *pf, char *ifname)
2017 {
2018 	struct pfioc_if pi;
2019 
2020 	memset(&pi, 0, sizeof(pi));
2021 	if (ifname && strlcpy(pi.ifname, ifname,
2022 	    sizeof(pi.ifname)) >= sizeof(pi.ifname)) {
2023 		warnx("pfctl_load_logif: strlcpy");
2024 		return (1);
2025 	}
2026 	if (ioctl(pf->dev, DIOCSETSTATUSIF, &pi)) {
2027 		warnx("DIOCSETSTATUSIF");
2028 		return (1);
2029 	}
2030 	return (0);
2031 }
2032 
2033 int
2034 pfctl_set_hostid(struct pfctl *pf, u_int32_t hostid)
2035 {
2036 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
2037 		return (0);
2038 
2039 	HTONL(hostid);
2040 
2041 	pf->hostid = hostid;
2042 	pf->hostid_set = 1;
2043 
2044 	if (pf->opts & PF_OPT_VERBOSE)
2045 		printf("set hostid 0x%08x\n", ntohl(hostid));
2046 
2047 	return (0);
2048 }
2049 
2050 int
2051 pfctl_load_hostid(struct pfctl *pf, u_int32_t hostid)
2052 {
2053 	if (ioctl(dev, DIOCSETHOSTID, &hostid)) {
2054 		warnx("DIOCSETHOSTID");
2055 		return (1);
2056 	}
2057 	return (0);
2058 }
2059 
2060 int
2061 pfctl_load_syncookies(struct pfctl *pf, u_int8_t val)
2062 {
2063 	struct pfctl_syncookies	cookies;
2064 
2065 	bzero(&cookies, sizeof(cookies));
2066 
2067 	cookies.mode = val ? PFCTL_SYNCOOKIES_ALWAYS : PFCTL_SYNCOOKIES_NEVER;
2068 
2069 	if (pfctl_set_syncookies(dev, &cookies)) {
2070 		warnx("DIOCSETSYNCOOKIES");
2071 		return (1);
2072 	}
2073 	return (0);
2074 }
2075 
2076 int
2077 pfctl_set_debug(struct pfctl *pf, char *d)
2078 {
2079 	u_int32_t	level;
2080 
2081 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
2082 		return (0);
2083 
2084 	if (!strcmp(d, "none"))
2085 		pf->debug = PF_DEBUG_NONE;
2086 	else if (!strcmp(d, "urgent"))
2087 		pf->debug = PF_DEBUG_URGENT;
2088 	else if (!strcmp(d, "misc"))
2089 		pf->debug = PF_DEBUG_MISC;
2090 	else if (!strcmp(d, "loud"))
2091 		pf->debug = PF_DEBUG_NOISY;
2092 	else {
2093 		warnx("unknown debug level \"%s\"", d);
2094 		return (-1);
2095 	}
2096 
2097 	pf->debug_set = 1;
2098 	level = pf->debug;
2099 
2100 	if ((pf->opts & PF_OPT_NOACTION) == 0)
2101 		if (ioctl(dev, DIOCSETDEBUG, &level))
2102 			err(1, "DIOCSETDEBUG");
2103 
2104 	if (pf->opts & PF_OPT_VERBOSE)
2105 		printf("set debug %s\n", d);
2106 
2107 	return (0);
2108 }
2109 
2110 int
2111 pfctl_load_debug(struct pfctl *pf, unsigned int level)
2112 {
2113 	if (ioctl(pf->dev, DIOCSETDEBUG, &level)) {
2114 		warnx("DIOCSETDEBUG");
2115 		return (1);
2116 	}
2117 	return (0);
2118 }
2119 
2120 int
2121 pfctl_set_interface_flags(struct pfctl *pf, char *ifname, int flags, int how)
2122 {
2123 	struct pfioc_iface	pi;
2124 	struct node_host	*h = NULL, *n = NULL;
2125 
2126 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
2127 		return (0);
2128 
2129 	bzero(&pi, sizeof(pi));
2130 
2131 	pi.pfiio_flags = flags;
2132 
2133 	/* Make sure our cache matches the kernel. If we set or clear the flag
2134 	 * for a group this applies to all members. */
2135 	h = ifa_grouplookup(ifname, 0);
2136 	for (n = h; n != NULL; n = n->next)
2137 		pfctl_set_interface_flags(pf, n->ifname, flags, how);
2138 
2139 	if (strlcpy(pi.pfiio_name, ifname, sizeof(pi.pfiio_name)) >=
2140 	    sizeof(pi.pfiio_name))
2141 		errx(1, "pfctl_set_interface_flags: strlcpy");
2142 
2143 	if ((pf->opts & PF_OPT_NOACTION) == 0) {
2144 		if (how == 0) {
2145 			if (ioctl(pf->dev, DIOCCLRIFFLAG, &pi))
2146 				err(1, "DIOCCLRIFFLAG");
2147 		} else {
2148 			if (ioctl(pf->dev, DIOCSETIFFLAG, &pi))
2149 				err(1, "DIOCSETIFFLAG");
2150 			pfctl_check_skip_ifaces(ifname);
2151 		}
2152 	}
2153 	return (0);
2154 }
2155 
2156 void
2157 pfctl_debug(int dev, u_int32_t level, int opts)
2158 {
2159 	if (ioctl(dev, DIOCSETDEBUG, &level))
2160 		err(1, "DIOCSETDEBUG");
2161 	if ((opts & PF_OPT_QUIET) == 0) {
2162 		fprintf(stderr, "debug level set to '");
2163 		switch (level) {
2164 		case PF_DEBUG_NONE:
2165 			fprintf(stderr, "none");
2166 			break;
2167 		case PF_DEBUG_URGENT:
2168 			fprintf(stderr, "urgent");
2169 			break;
2170 		case PF_DEBUG_MISC:
2171 			fprintf(stderr, "misc");
2172 			break;
2173 		case PF_DEBUG_NOISY:
2174 			fprintf(stderr, "loud");
2175 			break;
2176 		default:
2177 			fprintf(stderr, "<invalid>");
2178 			break;
2179 		}
2180 		fprintf(stderr, "'\n");
2181 	}
2182 }
2183 
2184 int
2185 pfctl_test_altqsupport(int dev, int opts)
2186 {
2187 	struct pfioc_altq pa;
2188 
2189 	pa.version = PFIOC_ALTQ_VERSION;
2190 	if (ioctl(dev, DIOCGETALTQS, &pa)) {
2191 		if (errno == ENODEV) {
2192 			if (opts & PF_OPT_VERBOSE)
2193 				fprintf(stderr, "No ALTQ support in kernel\n"
2194 				    "ALTQ related functions disabled\n");
2195 			return (0);
2196 		} else
2197 			err(1, "DIOCGETALTQS");
2198 	}
2199 	return (1);
2200 }
2201 
2202 int
2203 pfctl_show_anchors(int dev, int opts, char *anchorname)
2204 {
2205 	struct pfioc_ruleset	 pr;
2206 	u_int32_t		 mnr, nr;
2207 
2208 	memset(&pr, 0, sizeof(pr));
2209 	memcpy(pr.path, anchorname, sizeof(pr.path));
2210 	if (ioctl(dev, DIOCGETRULESETS, &pr)) {
2211 		if (errno == EINVAL)
2212 			fprintf(stderr, "Anchor '%s' not found.\n",
2213 			    anchorname);
2214 		else
2215 			err(1, "DIOCGETRULESETS");
2216 		return (-1);
2217 	}
2218 	mnr = pr.nr;
2219 	for (nr = 0; nr < mnr; ++nr) {
2220 		char sub[MAXPATHLEN];
2221 
2222 		pr.nr = nr;
2223 		if (ioctl(dev, DIOCGETRULESET, &pr))
2224 			err(1, "DIOCGETRULESET");
2225 		if (!strcmp(pr.name, PF_RESERVED_ANCHOR))
2226 			continue;
2227 		sub[0] = 0;
2228 		if (pr.path[0]) {
2229 			strlcat(sub, pr.path, sizeof(sub));
2230 			strlcat(sub, "/", sizeof(sub));
2231 		}
2232 		strlcat(sub, pr.name, sizeof(sub));
2233 		if (sub[0] != '_' || (opts & PF_OPT_VERBOSE))
2234 			printf("  %s\n", sub);
2235 		if ((opts & PF_OPT_VERBOSE) && pfctl_show_anchors(dev, opts, sub))
2236 			return (-1);
2237 	}
2238 	return (0);
2239 }
2240 
2241 const char *
2242 pfctl_lookup_option(char *cmd, const char * const *list)
2243 {
2244 	if (cmd != NULL && *cmd)
2245 		for (; *list; list++)
2246 			if (!strncmp(cmd, *list, strlen(cmd)))
2247 				return (*list);
2248 	return (NULL);
2249 }
2250 
2251 int
2252 main(int argc, char *argv[])
2253 {
2254 	int	 error = 0;
2255 	int	 ch;
2256 	int	 mode = O_RDONLY;
2257 	int	 opts = 0;
2258 	int	 optimize = PF_OPTIMIZE_BASIC;
2259 	char	 anchorname[MAXPATHLEN];
2260 	char	*path;
2261 
2262 	if (argc < 2)
2263 		usage();
2264 
2265 	while ((ch = getopt(argc, argv,
2266 	    "a:AdD:eqf:F:ghi:k:K:mMnNOo:Pp:rRs:t:T:vx:z")) != -1) {
2267 		switch (ch) {
2268 		case 'a':
2269 			anchoropt = optarg;
2270 			break;
2271 		case 'd':
2272 			opts |= PF_OPT_DISABLE;
2273 			mode = O_RDWR;
2274 			break;
2275 		case 'D':
2276 			if (pfctl_cmdline_symset(optarg) < 0)
2277 				warnx("could not parse macro definition %s",
2278 				    optarg);
2279 			break;
2280 		case 'e':
2281 			opts |= PF_OPT_ENABLE;
2282 			mode = O_RDWR;
2283 			break;
2284 		case 'q':
2285 			opts |= PF_OPT_QUIET;
2286 			break;
2287 		case 'F':
2288 			clearopt = pfctl_lookup_option(optarg, clearopt_list);
2289 			if (clearopt == NULL) {
2290 				warnx("Unknown flush modifier '%s'", optarg);
2291 				usage();
2292 			}
2293 			mode = O_RDWR;
2294 			break;
2295 		case 'i':
2296 			ifaceopt = optarg;
2297 			break;
2298 		case 'k':
2299 			if (state_killers >= 2) {
2300 				warnx("can only specify -k twice");
2301 				usage();
2302 				/* NOTREACHED */
2303 			}
2304 			state_kill[state_killers++] = optarg;
2305 			mode = O_RDWR;
2306 			break;
2307 		case 'K':
2308 			if (src_node_killers >= 2) {
2309 				warnx("can only specify -K twice");
2310 				usage();
2311 				/* NOTREACHED */
2312 			}
2313 			src_node_kill[src_node_killers++] = optarg;
2314 			mode = O_RDWR;
2315 			break;
2316 		case 'm':
2317 			opts |= PF_OPT_MERGE;
2318 			break;
2319 		case 'M':
2320 			opts |= PF_OPT_KILLMATCH;
2321 			break;
2322 		case 'n':
2323 			opts |= PF_OPT_NOACTION;
2324 			break;
2325 		case 'N':
2326 			loadopt |= PFCTL_FLAG_NAT;
2327 			break;
2328 		case 'r':
2329 			opts |= PF_OPT_USEDNS;
2330 			break;
2331 		case 'f':
2332 			rulesopt = optarg;
2333 			mode = O_RDWR;
2334 			break;
2335 		case 'g':
2336 			opts |= PF_OPT_DEBUG;
2337 			break;
2338 		case 'A':
2339 			loadopt |= PFCTL_FLAG_ALTQ;
2340 			break;
2341 		case 'R':
2342 			loadopt |= PFCTL_FLAG_FILTER;
2343 			break;
2344 		case 'o':
2345 			optiopt = pfctl_lookup_option(optarg, optiopt_list);
2346 			if (optiopt == NULL) {
2347 				warnx("Unknown optimization '%s'", optarg);
2348 				usage();
2349 			}
2350 			opts |= PF_OPT_OPTIMIZE;
2351 			break;
2352 		case 'O':
2353 			loadopt |= PFCTL_FLAG_OPTION;
2354 			break;
2355 		case 'p':
2356 			pf_device = optarg;
2357 			break;
2358 		case 'P':
2359 			opts |= PF_OPT_NUMERIC;
2360 			break;
2361 		case 's':
2362 			showopt = pfctl_lookup_option(optarg, showopt_list);
2363 			if (showopt == NULL) {
2364 				warnx("Unknown show modifier '%s'", optarg);
2365 				usage();
2366 			}
2367 			break;
2368 		case 't':
2369 			tableopt = optarg;
2370 			break;
2371 		case 'T':
2372 			tblcmdopt = pfctl_lookup_option(optarg, tblcmdopt_list);
2373 			if (tblcmdopt == NULL) {
2374 				warnx("Unknown table command '%s'", optarg);
2375 				usage();
2376 			}
2377 			break;
2378 		case 'v':
2379 			if (opts & PF_OPT_VERBOSE)
2380 				opts |= PF_OPT_VERBOSE2;
2381 			opts |= PF_OPT_VERBOSE;
2382 			break;
2383 		case 'x':
2384 			debugopt = pfctl_lookup_option(optarg, debugopt_list);
2385 			if (debugopt == NULL) {
2386 				warnx("Unknown debug level '%s'", optarg);
2387 				usage();
2388 			}
2389 			mode = O_RDWR;
2390 			break;
2391 		case 'z':
2392 			opts |= PF_OPT_CLRRULECTRS;
2393 			mode = O_RDWR;
2394 			break;
2395 		case 'h':
2396 			/* FALLTHROUGH */
2397 		default:
2398 			usage();
2399 			/* NOTREACHED */
2400 		}
2401 	}
2402 
2403 	if (tblcmdopt != NULL) {
2404 		argc -= optind;
2405 		argv += optind;
2406 		ch = *tblcmdopt;
2407 		if (ch == 'l') {
2408 			loadopt |= PFCTL_FLAG_TABLE;
2409 			tblcmdopt = NULL;
2410 		} else
2411 			mode = strchr("acdefkrz", ch) ? O_RDWR : O_RDONLY;
2412 	} else if (argc != optind) {
2413 		warnx("unknown command line argument: %s ...", argv[optind]);
2414 		usage();
2415 		/* NOTREACHED */
2416 	}
2417 	if (loadopt == 0)
2418 		loadopt = ~0;
2419 
2420 	if ((path = calloc(1, MAXPATHLEN)) == NULL)
2421 		errx(1, "pfctl: calloc");
2422 	memset(anchorname, 0, sizeof(anchorname));
2423 	if (anchoropt != NULL) {
2424 		int len = strlen(anchoropt);
2425 
2426 		if (anchoropt[len - 1] == '*') {
2427 			if (len >= 2 && anchoropt[len - 2] == '/')
2428 				anchoropt[len - 2] = '\0';
2429 			else
2430 				anchoropt[len - 1] = '\0';
2431 			opts |= PF_OPT_RECURSE;
2432 		}
2433 		if (strlcpy(anchorname, anchoropt,
2434 		    sizeof(anchorname)) >= sizeof(anchorname))
2435 			errx(1, "anchor name '%s' too long",
2436 			    anchoropt);
2437 		loadopt &= PFCTL_FLAG_FILTER|PFCTL_FLAG_NAT|PFCTL_FLAG_TABLE;
2438 	}
2439 
2440 	if ((opts & PF_OPT_NOACTION) == 0) {
2441 		dev = open(pf_device, mode);
2442 		if (dev == -1)
2443 			err(1, "%s", pf_device);
2444 		altqsupport = pfctl_test_altqsupport(dev, opts);
2445 	} else {
2446 		dev = open(pf_device, O_RDONLY);
2447 		if (dev >= 0)
2448 			opts |= PF_OPT_DUMMYACTION;
2449 		/* turn off options */
2450 		opts &= ~ (PF_OPT_DISABLE | PF_OPT_ENABLE);
2451 		clearopt = showopt = debugopt = NULL;
2452 #if !defined(ENABLE_ALTQ)
2453 		altqsupport = 0;
2454 #else
2455 		altqsupport = 1;
2456 #endif
2457 	}
2458 
2459 	if (opts & PF_OPT_DISABLE)
2460 		if (pfctl_disable(dev, opts))
2461 			error = 1;
2462 
2463 	if (showopt != NULL) {
2464 		switch (*showopt) {
2465 		case 'A':
2466 			pfctl_show_anchors(dev, opts, anchorname);
2467 			break;
2468 		case 'r':
2469 			pfctl_load_fingerprints(dev, opts);
2470 			pfctl_show_rules(dev, path, opts, PFCTL_SHOW_RULES,
2471 			    anchorname, 0);
2472 			break;
2473 		case 'l':
2474 			pfctl_load_fingerprints(dev, opts);
2475 			pfctl_show_rules(dev, path, opts, PFCTL_SHOW_LABELS,
2476 			    anchorname, 0);
2477 			break;
2478 		case 'n':
2479 			pfctl_load_fingerprints(dev, opts);
2480 			pfctl_show_nat(dev, opts, anchorname);
2481 			break;
2482 		case 'q':
2483 			pfctl_show_altq(dev, ifaceopt, opts,
2484 			    opts & PF_OPT_VERBOSE2);
2485 			break;
2486 		case 's':
2487 			pfctl_show_states(dev, ifaceopt, opts);
2488 			break;
2489 		case 'S':
2490 			pfctl_show_src_nodes(dev, opts);
2491 			break;
2492 		case 'i':
2493 			pfctl_show_status(dev, opts);
2494 			break;
2495 		case 'R':
2496 			error = pfctl_show_running(dev);
2497 			break;
2498 		case 't':
2499 			pfctl_show_timeouts(dev, opts);
2500 			break;
2501 		case 'm':
2502 			pfctl_show_limits(dev, opts);
2503 			break;
2504 		case 'a':
2505 			opts |= PF_OPT_SHOWALL;
2506 			pfctl_load_fingerprints(dev, opts);
2507 
2508 			pfctl_show_nat(dev, opts, anchorname);
2509 			pfctl_show_rules(dev, path, opts, 0, anchorname, 0);
2510 			pfctl_show_altq(dev, ifaceopt, opts, 0);
2511 			pfctl_show_states(dev, ifaceopt, opts);
2512 			pfctl_show_src_nodes(dev, opts);
2513 			pfctl_show_status(dev, opts);
2514 			pfctl_show_rules(dev, path, opts, 1, anchorname, 0);
2515 			pfctl_show_timeouts(dev, opts);
2516 			pfctl_show_limits(dev, opts);
2517 			pfctl_show_tables(anchorname, opts);
2518 			pfctl_show_fingerprints(opts);
2519 			break;
2520 		case 'T':
2521 			pfctl_show_tables(anchorname, opts);
2522 			break;
2523 		case 'o':
2524 			pfctl_load_fingerprints(dev, opts);
2525 			pfctl_show_fingerprints(opts);
2526 			break;
2527 		case 'I':
2528 			pfctl_show_ifaces(ifaceopt, opts);
2529 			break;
2530 		}
2531 	}
2532 
2533 	if ((opts & PF_OPT_CLRRULECTRS) && showopt == NULL)
2534 		pfctl_show_rules(dev, path, opts, PFCTL_SHOW_NOTHING,
2535 		    anchorname, 0);
2536 
2537 	if (clearopt != NULL) {
2538 		if (anchorname[0] == '_' || strstr(anchorname, "/_") != NULL)
2539 			errx(1, "anchor names beginning with '_' cannot "
2540 			    "be modified from the command line");
2541 
2542 		switch (*clearopt) {
2543 		case 'r':
2544 			pfctl_clear_rules(dev, opts, anchorname);
2545 			break;
2546 		case 'n':
2547 			pfctl_clear_nat(dev, opts, anchorname);
2548 			break;
2549 		case 'q':
2550 			pfctl_clear_altq(dev, opts);
2551 			break;
2552 		case 's':
2553 			pfctl_clear_iface_states(dev, ifaceopt, opts);
2554 			break;
2555 		case 'S':
2556 			pfctl_clear_src_nodes(dev, opts);
2557 			break;
2558 		case 'i':
2559 			pfctl_clear_stats(dev, opts);
2560 			break;
2561 		case 'a':
2562 			pfctl_clear_rules(dev, opts, anchorname);
2563 			pfctl_clear_nat(dev, opts, anchorname);
2564 			pfctl_clear_tables(anchorname, opts);
2565 			if (!*anchorname) {
2566 				pfctl_clear_altq(dev, opts);
2567 				pfctl_clear_iface_states(dev, ifaceopt, opts);
2568 				pfctl_clear_src_nodes(dev, opts);
2569 				pfctl_clear_stats(dev, opts);
2570 				pfctl_clear_fingerprints(dev, opts);
2571 				pfctl_clear_interface_flags(dev, opts);
2572 			}
2573 			break;
2574 		case 'o':
2575 			pfctl_clear_fingerprints(dev, opts);
2576 			break;
2577 		case 'T':
2578 			pfctl_clear_tables(anchorname, opts);
2579 			break;
2580 		}
2581 	}
2582 	if (state_killers) {
2583 		if (!strcmp(state_kill[0], "label"))
2584 			pfctl_label_kill_states(dev, ifaceopt, opts);
2585 		else if (!strcmp(state_kill[0], "id"))
2586 			pfctl_id_kill_states(dev, ifaceopt, opts);
2587 		else if (!strcmp(state_kill[0], "gateway"))
2588 			pfctl_gateway_kill_states(dev, ifaceopt, opts);
2589 		else
2590 			pfctl_net_kill_states(dev, ifaceopt, opts);
2591 	}
2592 
2593 	if (src_node_killers)
2594 		pfctl_kill_src_nodes(dev, ifaceopt, opts);
2595 
2596 	if (tblcmdopt != NULL) {
2597 		error = pfctl_command_tables(argc, argv, tableopt,
2598 		    tblcmdopt, rulesopt, anchorname, opts);
2599 		rulesopt = NULL;
2600 	}
2601 	if (optiopt != NULL) {
2602 		switch (*optiopt) {
2603 		case 'n':
2604 			optimize = 0;
2605 			break;
2606 		case 'b':
2607 			optimize |= PF_OPTIMIZE_BASIC;
2608 			break;
2609 		case 'o':
2610 		case 'p':
2611 			optimize |= PF_OPTIMIZE_PROFILE;
2612 			break;
2613 		}
2614 	}
2615 
2616 	if ((rulesopt != NULL) && (loadopt & PFCTL_FLAG_OPTION) &&
2617 	    !anchorname[0] && !(opts & PF_OPT_NOACTION))
2618 		if (pfctl_get_skip_ifaces())
2619 			error = 1;
2620 
2621 	if (rulesopt != NULL && !(opts & (PF_OPT_MERGE|PF_OPT_NOACTION)) &&
2622 	    !anchorname[0] && (loadopt & PFCTL_FLAG_OPTION))
2623 		if (pfctl_file_fingerprints(dev, opts, PF_OSFP_FILE))
2624 			error = 1;
2625 
2626 	if (rulesopt != NULL) {
2627 		if (anchorname[0] == '_' || strstr(anchorname, "/_") != NULL)
2628 			errx(1, "anchor names beginning with '_' cannot "
2629 			    "be modified from the command line");
2630 		if (pfctl_rules(dev, rulesopt, opts, optimize,
2631 		    anchorname, NULL))
2632 			error = 1;
2633 		else if (!(opts & PF_OPT_NOACTION) &&
2634 		    (loadopt & PFCTL_FLAG_TABLE))
2635 			warn_namespace_collision(NULL);
2636 	}
2637 
2638 	if (opts & PF_OPT_ENABLE)
2639 		if (pfctl_enable(dev, opts))
2640 			error = 1;
2641 
2642 	if (debugopt != NULL) {
2643 		switch (*debugopt) {
2644 		case 'n':
2645 			pfctl_debug(dev, PF_DEBUG_NONE, opts);
2646 			break;
2647 		case 'u':
2648 			pfctl_debug(dev, PF_DEBUG_URGENT, opts);
2649 			break;
2650 		case 'm':
2651 			pfctl_debug(dev, PF_DEBUG_MISC, opts);
2652 			break;
2653 		case 'l':
2654 			pfctl_debug(dev, PF_DEBUG_NOISY, opts);
2655 			break;
2656 		}
2657 	}
2658 
2659 	exit(error);
2660 }
2661