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