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