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