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