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