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