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