xref: /openbsd-src/sbin/pfctl/pfctl.c (revision a28daedfc357b214be5c701aa8ba8adb29a7f1c2)
1 /*	$OpenBSD: pfctl.c,v 1.282 2009/04/16 04:40:19 david Exp $ */
2 
3 /*
4  * Copyright (c) 2001 Daniel Hartmeier
5  * Copyright (c) 2002,2003 Henning Brauer
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  *    - Redistributions of source code must retain the above copyright
13  *      notice, this list of conditions and the following disclaimer.
14  *    - Redistributions in binary form must reproduce the above
15  *      copyright notice, this list of conditions and the following
16  *      disclaimer in the documentation and/or other materials provided
17  *      with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
22  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
23  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
25  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
29  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  *
32  */
33 
34 #include <sys/types.h>
35 #include <sys/ioctl.h>
36 #include <sys/socket.h>
37 #include <sys/stat.h>
38 
39 #include <net/if.h>
40 #include <netinet/in.h>
41 #include <net/pfvar.h>
42 #include <arpa/inet.h>
43 #include <altq/altq.h>
44 #include <sys/sysctl.h>
45 
46 #include <err.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <limits.h>
50 #include <netdb.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <unistd.h>
55 
56 #include "pfctl_parser.h"
57 #include "pfctl.h"
58 
59 void	 usage(void);
60 int	 pfctl_enable(int, int);
61 int	 pfctl_disable(int, int);
62 int	 pfctl_clear_stats(int, int);
63 int	 pfctl_clear_interface_flags(int, int);
64 int	 pfctl_clear_rules(int, int, char *);
65 int	 pfctl_clear_nat(int, int, char *);
66 int	 pfctl_clear_altq(int, int);
67 int	 pfctl_clear_src_nodes(int, int);
68 int	 pfctl_clear_states(int, const char *, int);
69 void	 pfctl_addrprefix(char *, struct pf_addr *);
70 int	 pfctl_kill_src_nodes(int, const char *, int);
71 int	 pfctl_net_kill_states(int, const char *, int);
72 int	 pfctl_label_kill_states(int, const char *, int);
73 int	 pfctl_id_kill_states(int, const char *, int);
74 void	 pfctl_init_options(struct pfctl *);
75 int	 pfctl_load_options(struct pfctl *);
76 int	 pfctl_load_limit(struct pfctl *, unsigned int, unsigned int);
77 int	 pfctl_load_timeout(struct pfctl *, unsigned int, unsigned int);
78 int	 pfctl_load_debug(struct pfctl *, unsigned int);
79 int	 pfctl_load_logif(struct pfctl *, char *);
80 int	 pfctl_load_hostid(struct pfctl *, unsigned int);
81 int	 pfctl_load_reassembly(struct pfctl *, u_int32_t);
82 int	 pfctl_get_pool(int, struct pf_pool *, u_int32_t, u_int32_t, int,
83 	    char *);
84 void	 pfctl_print_rule_counters(struct pf_rule *, int);
85 int	 pfctl_show_rules(int, char *, int, enum pfctl_show, char *, int);
86 int	 pfctl_show_nat(int, int, char *);
87 int	 pfctl_show_src_nodes(int, int);
88 int	 pfctl_show_states(int, const char *, int);
89 int	 pfctl_show_status(int, int);
90 int	 pfctl_show_timeouts(int, int);
91 int	 pfctl_show_limits(int, int);
92 void	 pfctl_debug(int, u_int32_t, int);
93 int	 pfctl_test_altqsupport(int, int);
94 int	 pfctl_show_anchors(int, int, char *);
95 int	 pfctl_ruleset_trans(struct pfctl *, char *, struct pf_anchor *);
96 int	 pfctl_load_ruleset(struct pfctl *, char *,
97 		struct pf_ruleset *, int, int);
98 int	 pfctl_load_rule(struct pfctl *, char *, struct pf_rule *, int);
99 const char	*pfctl_lookup_option(char *, const char **);
100 
101 struct pf_anchor_global	 pf_anchors;
102 struct pf_anchor	 pf_main_anchor;
103 
104 const char	*clearopt;
105 char		*rulesopt;
106 const char	*showopt;
107 const char	*debugopt;
108 char		*anchoropt;
109 const char	*optiopt = NULL;
110 char		*pf_device = "/dev/pf";
111 char		*ifaceopt;
112 char		*tableopt;
113 const char	*tblcmdopt;
114 int		 src_node_killers;
115 char		*src_node_kill[2];
116 int		 state_killers;
117 char		*state_kill[2];
118 int		 loadopt;
119 int		 altqsupport;
120 
121 int		 dev = -1;
122 int		 first_title = 1;
123 int		 labels = 0;
124 
125 #define INDENT(d, o)	do {						\
126 				if (o) {				\
127 					int i;				\
128 					for (i=0; i < d; i++)		\
129 						printf("  ");		\
130 				}					\
131 			} while (0);					\
132 
133 
134 static const struct {
135 	const char	*name;
136 	int		index;
137 } pf_limits[] = {
138 	{ "states",		PF_LIMIT_STATES },
139 	{ "src-nodes",		PF_LIMIT_SRC_NODES },
140 	{ "frags",		PF_LIMIT_FRAGS },
141 	{ "tables",		PF_LIMIT_TABLES },
142 	{ "table-entries",	PF_LIMIT_TABLE_ENTRIES },
143 	{ NULL,			0 }
144 };
145 
146 struct pf_hint {
147 	const char	*name;
148 	int		timeout;
149 };
150 static const struct pf_hint pf_hint_normal[] = {
151 	{ "tcp.first",		2 * 60 },
152 	{ "tcp.opening",	30 },
153 	{ "tcp.established",	24 * 60 * 60 },
154 	{ "tcp.closing",	15 * 60 },
155 	{ "tcp.finwait",	45 },
156 	{ "tcp.closed",		90 },
157 	{ "tcp.tsdiff",		30 },
158 	{ NULL,			0 }
159 };
160 static const struct pf_hint pf_hint_satellite[] = {
161 	{ "tcp.first",		3 * 60 },
162 	{ "tcp.opening",	30 + 5 },
163 	{ "tcp.established",	24 * 60 * 60 },
164 	{ "tcp.closing",	15 * 60 + 5 },
165 	{ "tcp.finwait",	45 + 5 },
166 	{ "tcp.closed",		90 + 5 },
167 	{ "tcp.tsdiff",		60 },
168 	{ NULL,			0 }
169 };
170 static const struct pf_hint pf_hint_conservative[] = {
171 	{ "tcp.first",		60 * 60 },
172 	{ "tcp.opening",	15 * 60 },
173 	{ "tcp.established",	5 * 24 * 60 * 60 },
174 	{ "tcp.closing",	60 * 60 },
175 	{ "tcp.finwait",	10 * 60 },
176 	{ "tcp.closed",		3 * 60 },
177 	{ "tcp.tsdiff",		60 },
178 	{ NULL,			0 }
179 };
180 static const struct pf_hint pf_hint_aggressive[] = {
181 	{ "tcp.first",		30 },
182 	{ "tcp.opening",	5 },
183 	{ "tcp.established",	5 * 60 * 60 },
184 	{ "tcp.closing",	60 },
185 	{ "tcp.finwait",	30 },
186 	{ "tcp.closed",		30 },
187 	{ "tcp.tsdiff",		10 },
188 	{ NULL,			0 }
189 };
190 
191 static const struct {
192 	const char *name;
193 	const struct pf_hint *hint;
194 } pf_hints[] = {
195 	{ "normal",		pf_hint_normal },
196 	{ "satellite",		pf_hint_satellite },
197 	{ "high-latency",	pf_hint_satellite },
198 	{ "conservative",	pf_hint_conservative },
199 	{ "aggressive",		pf_hint_aggressive },
200 	{ NULL,			NULL }
201 };
202 
203 static const char *clearopt_list[] = {
204 	"nat", "queue", "rules", "Sources",
205 	"states", "info", "Tables", "osfp", "all", NULL
206 };
207 
208 static const char *showopt_list[] = {
209 	"nat", "queue", "rules", "Anchors", "Sources", "states", "info",
210 	"Interfaces", "labels", "timeouts", "memory", "Tables", "osfp",
211 	"all", NULL
212 };
213 
214 static const char *tblcmdopt_list[] = {
215 	"kill", "flush", "add", "delete", "load", "replace", "show",
216 	"test", "zero", "expire", NULL
217 };
218 
219 static const char *debugopt_list[] = {
220 	"none", "urgent", "misc", "loud", NULL
221 };
222 
223 static const char *optiopt_list[] = {
224 	"none", "basic", "profile", NULL
225 };
226 
227 void
228 usage(void)
229 {
230 	extern char *__progname;
231 
232 	fprintf(stderr, "usage: %s [-AdeghmNnOqRrvz] ", __progname);
233 	fprintf(stderr, "[-a anchor] [-D macro=value] [-F modifier]\n");
234 	fprintf(stderr, "\t[-f file] [-i interface] [-K host | network]\n");
235 	fprintf(stderr, "\t[-k host | network | label | id] ");
236 	fprintf(stderr, "[-o level] [-p device]\n");
237 	fprintf(stderr, "\t[-s modifier] ");
238 	fprintf(stderr, "[-t table -T command [address ...]] [-x level]\n");
239 	exit(1);
240 }
241 
242 int
243 pfctl_enable(int dev, int opts)
244 {
245 	if (ioctl(dev, DIOCSTART)) {
246 		if (errno == EEXIST)
247 			errx(1, "pf already enabled");
248 		else
249 			err(1, "DIOCSTART");
250 	}
251 	if ((opts & PF_OPT_QUIET) == 0)
252 		fprintf(stderr, "pf enabled\n");
253 
254 	if (altqsupport && ioctl(dev, DIOCSTARTALTQ))
255 		if (errno != EEXIST)
256 			err(1, "DIOCSTARTALTQ");
257 
258 	return (0);
259 }
260 
261 int
262 pfctl_disable(int dev, int opts)
263 {
264 	if (ioctl(dev, DIOCSTOP)) {
265 		if (errno == ENOENT)
266 			errx(1, "pf not enabled");
267 		else
268 			err(1, "DIOCSTOP");
269 	}
270 	if ((opts & PF_OPT_QUIET) == 0)
271 		fprintf(stderr, "pf disabled\n");
272 
273 	if (altqsupport && ioctl(dev, DIOCSTOPALTQ))
274 			if (errno != ENOENT)
275 				err(1, "DIOCSTOPALTQ");
276 
277 	return (0);
278 }
279 
280 int
281 pfctl_clear_stats(int dev, int opts)
282 {
283 	if (ioctl(dev, DIOCCLRSTATUS))
284 		err(1, "DIOCCLRSTATUS");
285 	if ((opts & PF_OPT_QUIET) == 0)
286 		fprintf(stderr, "pf: statistics cleared\n");
287 	return (0);
288 }
289 
290 int
291 pfctl_clear_interface_flags(int dev, int opts)
292 {
293 	struct pfioc_iface	pi;
294 
295 	if ((opts & PF_OPT_NOACTION) == 0) {
296 		bzero(&pi, sizeof(pi));
297 		pi.pfiio_flags = PFI_IFLAG_SKIP;
298 
299 		if (ioctl(dev, DIOCCLRIFFLAG, &pi))
300 			err(1, "DIOCCLRIFFLAG");
301 		if ((opts & PF_OPT_QUIET) == 0)
302 			fprintf(stderr, "pf: interface flags reset\n");
303 	}
304 	return (0);
305 }
306 
307 int
308 pfctl_clear_rules(int dev, int opts, char *anchorname)
309 {
310 	struct pfr_buffer t;
311 
312 	memset(&t, 0, sizeof(t));
313 	t.pfrb_type = PFRB_TRANS;
314 	if (pfctl_add_trans(&t, PF_RULESET_FILTER, anchorname) ||
315 	    pfctl_trans(dev, &t, DIOCXBEGIN, 0) ||
316 	    pfctl_trans(dev, &t, DIOCXCOMMIT, 0))
317 		err(1, "pfctl_clear_rules");
318 	if ((opts & PF_OPT_QUIET) == 0)
319 		fprintf(stderr, "rules cleared\n");
320 	return (0);
321 }
322 
323 int
324 pfctl_clear_nat(int dev, int opts, char *anchorname)
325 {
326 	struct pfr_buffer t;
327 
328 	memset(&t, 0, sizeof(t));
329 	t.pfrb_type = PFRB_TRANS;
330 	if (pfctl_add_trans(&t, PF_RULESET_NAT, anchorname) ||
331 	    pfctl_add_trans(&t, PF_RULESET_BINAT, anchorname) ||
332 	    pfctl_add_trans(&t, PF_RULESET_RDR, anchorname) ||
333 	    pfctl_trans(dev, &t, DIOCXBEGIN, 0) ||
334 	    pfctl_trans(dev, &t, DIOCXCOMMIT, 0))
335 		err(1, "pfctl_clear_nat");
336 	if ((opts & PF_OPT_QUIET) == 0)
337 		fprintf(stderr, "nat cleared\n");
338 	return (0);
339 }
340 
341 int
342 pfctl_clear_altq(int dev, int opts)
343 {
344 	struct pfr_buffer t;
345 
346 	if (!altqsupport)
347 		return (-1);
348 	memset(&t, 0, sizeof(t));
349 	t.pfrb_type = PFRB_TRANS;
350 	if (pfctl_add_trans(&t, PF_RULESET_ALTQ, "") ||
351 	    pfctl_trans(dev, &t, DIOCXBEGIN, 0) ||
352 	    pfctl_trans(dev, &t, DIOCXCOMMIT, 0))
353 		err(1, "pfctl_clear_altq");
354 	if ((opts & PF_OPT_QUIET) == 0)
355 		fprintf(stderr, "altq cleared\n");
356 	return (0);
357 }
358 
359 int
360 pfctl_clear_src_nodes(int dev, int opts)
361 {
362 	if (ioctl(dev, DIOCCLRSRCNODES))
363 		err(1, "DIOCCLRSRCNODES");
364 	if ((opts & PF_OPT_QUIET) == 0)
365 		fprintf(stderr, "source tracking entries cleared\n");
366 	return (0);
367 }
368 
369 int
370 pfctl_clear_states(int dev, const char *iface, int opts)
371 {
372 	struct pfioc_state_kill psk;
373 
374 	memset(&psk, 0, sizeof(psk));
375 	if (iface != NULL && strlcpy(psk.psk_ifname, iface,
376 	    sizeof(psk.psk_ifname)) >= sizeof(psk.psk_ifname))
377 		errx(1, "invalid interface: %s", iface);
378 
379 	if (ioctl(dev, DIOCCLRSTATES, &psk))
380 		err(1, "DIOCCLRSTATES");
381 	if ((opts & PF_OPT_QUIET) == 0)
382 		fprintf(stderr, "%d states cleared\n", psk.psk_killed);
383 	return (0);
384 }
385 
386 void
387 pfctl_addrprefix(char *addr, struct pf_addr *mask)
388 {
389 	char *p;
390 	const char *errstr;
391 	int prefix, ret_ga, q, r;
392 	struct addrinfo hints, *res;
393 
394 	if ((p = strchr(addr, '/')) == NULL)
395 		return;
396 
397 	*p++ = '\0';
398 	prefix = strtonum(p, 0, 128, &errstr);
399 	if (errstr)
400 		errx(1, "prefix is %s: %s", errstr, p);
401 
402 	bzero(&hints, sizeof(hints));
403 	/* prefix only with numeric addresses */
404 	hints.ai_flags |= AI_NUMERICHOST;
405 
406 	if ((ret_ga = getaddrinfo(addr, NULL, &hints, &res))) {
407 		errx(1, "getaddrinfo: %s", gai_strerror(ret_ga));
408 		/* NOTREACHED */
409 	}
410 
411 	if (res->ai_family == AF_INET && prefix > 32)
412 		errx(1, "prefix too long for AF_INET");
413 	else if (res->ai_family == AF_INET6 && prefix > 128)
414 		errx(1, "prefix too long for AF_INET6");
415 
416 	q = prefix >> 3;
417 	r = prefix & 7;
418 	switch (res->ai_family) {
419 	case AF_INET:
420 		bzero(&mask->v4, sizeof(mask->v4));
421 		mask->v4.s_addr = htonl((u_int32_t)
422 		    (0xffffffffffULL << (32 - prefix)));
423 		break;
424 	case AF_INET6:
425 		bzero(&mask->v6, sizeof(mask->v6));
426 		if (q > 0)
427 			memset((void *)&mask->v6, 0xff, q);
428 		if (r > 0)
429 			*((u_char *)&mask->v6 + q) =
430 			    (0xff00 >> r) & 0xff;
431 		break;
432 	}
433 	freeaddrinfo(res);
434 }
435 
436 int
437 pfctl_kill_src_nodes(int dev, const char *iface, int opts)
438 {
439 	struct pfioc_src_node_kill psnk;
440 	struct addrinfo *res[2], *resp[2];
441 	struct sockaddr last_src, last_dst;
442 	int killed, sources, dests;
443 	int ret_ga;
444 
445 	killed = sources = dests = 0;
446 
447 	memset(&psnk, 0, sizeof(psnk));
448 	memset(&psnk.psnk_src.addr.v.a.mask, 0xff,
449 	    sizeof(psnk.psnk_src.addr.v.a.mask));
450 	memset(&last_src, 0xff, sizeof(last_src));
451 	memset(&last_dst, 0xff, sizeof(last_dst));
452 
453 	pfctl_addrprefix(src_node_kill[0], &psnk.psnk_src.addr.v.a.mask);
454 
455 	if ((ret_ga = getaddrinfo(src_node_kill[0], NULL, NULL, &res[0]))) {
456 		errx(1, "getaddrinfo: %s", gai_strerror(ret_ga));
457 		/* NOTREACHED */
458 	}
459 	for (resp[0] = res[0]; resp[0]; resp[0] = resp[0]->ai_next) {
460 		if (resp[0]->ai_addr == NULL)
461 			continue;
462 		/* We get lots of duplicates.  Catch the easy ones */
463 		if (memcmp(&last_src, resp[0]->ai_addr, sizeof(last_src)) == 0)
464 			continue;
465 		last_src = *(struct sockaddr *)resp[0]->ai_addr;
466 
467 		psnk.psnk_af = resp[0]->ai_family;
468 		sources++;
469 
470 		if (psnk.psnk_af == AF_INET)
471 			psnk.psnk_src.addr.v.a.addr.v4 =
472 			    ((struct sockaddr_in *)resp[0]->ai_addr)->sin_addr;
473 		else if (psnk.psnk_af == AF_INET6)
474 			psnk.psnk_src.addr.v.a.addr.v6 =
475 			    ((struct sockaddr_in6 *)resp[0]->ai_addr)->
476 			    sin6_addr;
477 		else
478 			errx(1, "Unknown address family %d", psnk.psnk_af);
479 
480 		if (src_node_killers > 1) {
481 			dests = 0;
482 			memset(&psnk.psnk_dst.addr.v.a.mask, 0xff,
483 			    sizeof(psnk.psnk_dst.addr.v.a.mask));
484 			memset(&last_dst, 0xff, sizeof(last_dst));
485 			pfctl_addrprefix(src_node_kill[1],
486 			    &psnk.psnk_dst.addr.v.a.mask);
487 			if ((ret_ga = getaddrinfo(src_node_kill[1], NULL, NULL,
488 			    &res[1]))) {
489 				errx(1, "getaddrinfo: %s",
490 				    gai_strerror(ret_ga));
491 				/* NOTREACHED */
492 			}
493 			for (resp[1] = res[1]; resp[1];
494 			    resp[1] = resp[1]->ai_next) {
495 				if (resp[1]->ai_addr == NULL)
496 					continue;
497 				if (psnk.psnk_af != resp[1]->ai_family)
498 					continue;
499 
500 				if (memcmp(&last_dst, resp[1]->ai_addr,
501 				    sizeof(last_dst)) == 0)
502 					continue;
503 				last_dst = *(struct sockaddr *)resp[1]->ai_addr;
504 
505 				dests++;
506 
507 				if (psnk.psnk_af == AF_INET)
508 					psnk.psnk_dst.addr.v.a.addr.v4 =
509 					    ((struct sockaddr_in *)resp[1]->
510 					    ai_addr)->sin_addr;
511 				else if (psnk.psnk_af == AF_INET6)
512 					psnk.psnk_dst.addr.v.a.addr.v6 =
513 					    ((struct sockaddr_in6 *)resp[1]->
514 					    ai_addr)->sin6_addr;
515 				else
516 					errx(1, "Unknown address family %d",
517 					    psnk.psnk_af);
518 
519 				if (ioctl(dev, DIOCKILLSRCNODES, &psnk))
520 					err(1, "DIOCKILLSRCNODES");
521 				killed += psnk.psnk_killed;
522 			}
523 			freeaddrinfo(res[1]);
524 		} else {
525 			if (ioctl(dev, DIOCKILLSRCNODES, &psnk))
526 				err(1, "DIOCKILLSRCNODES");
527 			killed += psnk.psnk_killed;
528 		}
529 	}
530 
531 	freeaddrinfo(res[0]);
532 
533 	if ((opts & PF_OPT_QUIET) == 0)
534 		fprintf(stderr, "killed %d src nodes from %d sources and %d "
535 		    "destinations\n", killed, sources, dests);
536 	return (0);
537 }
538 
539 int
540 pfctl_net_kill_states(int dev, const char *iface, int opts)
541 {
542 	struct pfioc_state_kill psk;
543 	struct addrinfo *res[2], *resp[2];
544 	struct sockaddr last_src, last_dst;
545 	int killed, sources, dests;
546 	int ret_ga;
547 
548 	killed = sources = dests = 0;
549 
550 	memset(&psk, 0, sizeof(psk));
551 	memset(&psk.psk_src.addr.v.a.mask, 0xff,
552 	    sizeof(psk.psk_src.addr.v.a.mask));
553 	memset(&last_src, 0xff, sizeof(last_src));
554 	memset(&last_dst, 0xff, sizeof(last_dst));
555 	if (iface != NULL && strlcpy(psk.psk_ifname, iface,
556 	    sizeof(psk.psk_ifname)) >= sizeof(psk.psk_ifname))
557 		errx(1, "invalid interface: %s", iface);
558 
559 	pfctl_addrprefix(state_kill[0], &psk.psk_src.addr.v.a.mask);
560 
561 	if ((ret_ga = getaddrinfo(state_kill[0], NULL, NULL, &res[0]))) {
562 		errx(1, "getaddrinfo: %s", gai_strerror(ret_ga));
563 		/* NOTREACHED */
564 	}
565 	for (resp[0] = res[0]; resp[0]; resp[0] = resp[0]->ai_next) {
566 		if (resp[0]->ai_addr == NULL)
567 			continue;
568 		/* We get lots of duplicates.  Catch the easy ones */
569 		if (memcmp(&last_src, resp[0]->ai_addr, sizeof(last_src)) == 0)
570 			continue;
571 		last_src = *(struct sockaddr *)resp[0]->ai_addr;
572 
573 		psk.psk_af = resp[0]->ai_family;
574 		sources++;
575 
576 		if (psk.psk_af == AF_INET)
577 			psk.psk_src.addr.v.a.addr.v4 =
578 			    ((struct sockaddr_in *)resp[0]->ai_addr)->sin_addr;
579 		else if (psk.psk_af == AF_INET6)
580 			psk.psk_src.addr.v.a.addr.v6 =
581 			    ((struct sockaddr_in6 *)resp[0]->ai_addr)->
582 			    sin6_addr;
583 		else
584 			errx(1, "Unknown address family %d", psk.psk_af);
585 
586 		if (state_killers > 1) {
587 			dests = 0;
588 			memset(&psk.psk_dst.addr.v.a.mask, 0xff,
589 			    sizeof(psk.psk_dst.addr.v.a.mask));
590 			memset(&last_dst, 0xff, sizeof(last_dst));
591 			pfctl_addrprefix(state_kill[1],
592 			    &psk.psk_dst.addr.v.a.mask);
593 			if ((ret_ga = getaddrinfo(state_kill[1], NULL, NULL,
594 			    &res[1]))) {
595 				errx(1, "getaddrinfo: %s",
596 				    gai_strerror(ret_ga));
597 				/* NOTREACHED */
598 			}
599 			for (resp[1] = res[1]; resp[1];
600 			    resp[1] = resp[1]->ai_next) {
601 				if (resp[1]->ai_addr == NULL)
602 					continue;
603 				if (psk.psk_af != resp[1]->ai_family)
604 					continue;
605 
606 				if (memcmp(&last_dst, resp[1]->ai_addr,
607 				    sizeof(last_dst)) == 0)
608 					continue;
609 				last_dst = *(struct sockaddr *)resp[1]->ai_addr;
610 
611 				dests++;
612 
613 				if (psk.psk_af == AF_INET)
614 					psk.psk_dst.addr.v.a.addr.v4 =
615 					    ((struct sockaddr_in *)resp[1]->
616 					    ai_addr)->sin_addr;
617 				else if (psk.psk_af == AF_INET6)
618 					psk.psk_dst.addr.v.a.addr.v6 =
619 					    ((struct sockaddr_in6 *)resp[1]->
620 					    ai_addr)->sin6_addr;
621 				else
622 					errx(1, "Unknown address family %d",
623 					    psk.psk_af);
624 
625 				if (ioctl(dev, DIOCKILLSTATES, &psk))
626 					err(1, "DIOCKILLSTATES");
627 				killed += psk.psk_killed;
628 			}
629 			freeaddrinfo(res[1]);
630 		} else {
631 			if (ioctl(dev, DIOCKILLSTATES, &psk))
632 				err(1, "DIOCKILLSTATES");
633 			killed += psk.psk_killed;
634 		}
635 	}
636 
637 	freeaddrinfo(res[0]);
638 
639 	if ((opts & PF_OPT_QUIET) == 0)
640 		fprintf(stderr, "killed %d states from %d sources and %d "
641 		    "destinations\n", killed, sources, dests);
642 	return (0);
643 }
644 
645 int
646 pfctl_label_kill_states(int dev, const char *iface, int opts)
647 {
648 	struct pfioc_state_kill psk;
649 
650 	if (state_killers != 2 || (strlen(state_kill[1]) == 0)) {
651 		warnx("no label specified");
652 		usage();
653 	}
654 	memset(&psk, 0, sizeof(psk));
655 	if (iface != NULL && strlcpy(psk.psk_ifname, iface,
656 	    sizeof(psk.psk_ifname)) >= sizeof(psk.psk_ifname))
657 		errx(1, "invalid interface: %s", iface);
658 
659 	if (strlcpy(psk.psk_label, state_kill[1], sizeof(psk.psk_label)) >=
660 	    sizeof(psk.psk_label))
661 		errx(1, "label too long: %s", state_kill[1]);
662 
663 	if (ioctl(dev, DIOCKILLSTATES, &psk))
664 		err(1, "DIOCKILLSTATES");
665 
666 	if ((opts & PF_OPT_QUIET) == 0)
667 		fprintf(stderr, "killed %d states\n", psk.psk_killed);
668 
669 	return (0);
670 }
671 
672 int
673 pfctl_id_kill_states(int dev, const char *iface, int opts)
674 {
675 	struct pfioc_state_kill psk;
676 
677 	if (state_killers != 2 || (strlen(state_kill[1]) == 0)) {
678 		warnx("no id specified");
679 		usage();
680 	}
681 
682 	memset(&psk, 0, sizeof(psk));
683 	if ((sscanf(state_kill[1], "%llx/%x",
684 	    &psk.psk_pfcmp.id, &psk.psk_pfcmp.creatorid)) == 2)
685 		HTONL(psk.psk_pfcmp.creatorid);
686 	else if ((sscanf(state_kill[1], "%llx", &psk.psk_pfcmp.id)) == 1) {
687 		psk.psk_pfcmp.creatorid = 0;
688 	} else {
689 		warnx("wrong id format specified");
690 		usage();
691 	}
692 	if (psk.psk_pfcmp.id == 0) {
693 		warnx("cannot kill id 0");
694 		usage();
695 	}
696 
697 	psk.psk_pfcmp.id = htobe64(psk.psk_pfcmp.id);
698 	if (ioctl(dev, DIOCKILLSTATES, &psk))
699 		err(1, "DIOCKILLSTATES");
700 
701 	if ((opts & PF_OPT_QUIET) == 0)
702 		fprintf(stderr, "killed %d states\n", psk.psk_killed);
703 
704 	return (0);
705 }
706 
707 int
708 pfctl_get_pool(int dev, struct pf_pool *pool, u_int32_t nr,
709     u_int32_t ticket, int r_action, char *anchorname)
710 {
711 	struct pfioc_pooladdr pp;
712 	struct pf_pooladdr *pa;
713 	u_int32_t pnr, mpnr;
714 
715 	memset(&pp, 0, sizeof(pp));
716 	memcpy(pp.anchor, anchorname, sizeof(pp.anchor));
717 	pp.r_action = r_action;
718 	pp.r_num = nr;
719 	pp.ticket = ticket;
720 	if (ioctl(dev, DIOCGETADDRS, &pp)) {
721 		warn("DIOCGETADDRS");
722 		return (-1);
723 	}
724 	mpnr = pp.nr;
725 	TAILQ_INIT(&pool->list);
726 	for (pnr = 0; pnr < mpnr; ++pnr) {
727 		pp.nr = pnr;
728 		if (ioctl(dev, DIOCGETADDR, &pp)) {
729 			warn("DIOCGETADDR");
730 			return (-1);
731 		}
732 		pa = calloc(1, sizeof(struct pf_pooladdr));
733 		if (pa == NULL)
734 			err(1, "calloc");
735 		bcopy(&pp.addr, pa, sizeof(struct pf_pooladdr));
736 		TAILQ_INSERT_TAIL(&pool->list, pa, entries);
737 	}
738 
739 	return (0);
740 }
741 
742 void
743 pfctl_move_pool(struct pf_pool *src, struct pf_pool *dst)
744 {
745 	struct pf_pooladdr *pa;
746 
747 	while ((pa = TAILQ_FIRST(&src->list)) != NULL) {
748 		TAILQ_REMOVE(&src->list, pa, entries);
749 		TAILQ_INSERT_TAIL(&dst->list, pa, entries);
750 	}
751 }
752 
753 void
754 pfctl_clear_pool(struct pf_pool *pool)
755 {
756 	struct pf_pooladdr *pa;
757 
758 	while ((pa = TAILQ_FIRST(&pool->list)) != NULL) {
759 		TAILQ_REMOVE(&pool->list, pa, entries);
760 		free(pa);
761 	}
762 }
763 
764 void
765 pfctl_print_rule_counters(struct pf_rule *rule, int opts)
766 {
767 	if (opts & PF_OPT_DEBUG) {
768 		const char *t[PF_SKIP_COUNT] = { "i", "d", "f",
769 		    "p", "sa", "sp", "da", "dp" };
770 		int i;
771 
772 		printf("  [ Skip steps: ");
773 		for (i = 0; i < PF_SKIP_COUNT; ++i) {
774 			if (rule->skip[i].nr == rule->nr + 1)
775 				continue;
776 			printf("%s=", t[i]);
777 			if (rule->skip[i].nr == -1)
778 				printf("end ");
779 			else
780 				printf("%u ", rule->skip[i].nr);
781 		}
782 		printf("]\n");
783 
784 		printf("  [ queue: qname=%s qid=%u pqname=%s pqid=%u ]\n",
785 		    rule->qname, rule->qid, rule->pqname, rule->pqid);
786 	}
787 	if (opts & PF_OPT_VERBOSE) {
788 		printf("  [ Evaluations: %-8llu  Packets: %-8llu  "
789 			    "Bytes: %-10llu  States: %-6u]\n",
790 			    (unsigned long long)rule->evaluations,
791 			    (unsigned long long)(rule->packets[0] +
792 			    rule->packets[1]),
793 			    (unsigned long long)(rule->bytes[0] +
794 			    rule->bytes[1]), rule->states_cur);
795 		if (!(opts & PF_OPT_DEBUG))
796 			printf("  [ Inserted: uid %u pid %u "
797 			    "State Creations: %-6u]\n",
798 			    (unsigned)rule->cuid, (unsigned)rule->cpid,
799 			    rule->states_tot);
800 	}
801 }
802 
803 void
804 pfctl_print_title(char *title)
805 {
806 	if (!first_title)
807 		printf("\n");
808 	first_title = 0;
809 	printf("%s\n", title);
810 }
811 
812 int
813 pfctl_show_rules(int dev, char *path, int opts, enum pfctl_show format,
814     char *anchorname, int depth)
815 {
816 	struct pfioc_rule pr;
817 	u_int32_t nr, mnr, header = 0;
818 	int rule_numbers = opts & (PF_OPT_VERBOSE2 | PF_OPT_DEBUG);
819 	int len = strlen(path);
820 	int brace;
821 	char *p;
822 
823 	if (path[0])
824 		snprintf(&path[len], MAXPATHLEN - len, "/%s", anchorname);
825 	else
826 		snprintf(&path[len], MAXPATHLEN - len, "%s", anchorname);
827 
828 	memset(&pr, 0, sizeof(pr));
829 	memcpy(pr.anchor, path, sizeof(pr.anchor));
830 	if (opts & PF_OPT_SHOWALL) {
831 		pr.rule.action = PF_PASS;
832 		if (ioctl(dev, DIOCGETRULES, &pr)) {
833 			warn("DIOCGETRULES");
834 			goto error;
835 		}
836 		header++;
837 	}
838 	if (opts & PF_OPT_SHOWALL) {
839 		if (format == PFCTL_SHOW_RULES && (pr.nr > 0 || header))
840 			pfctl_print_title("FILTER RULES:");
841 		else if (format == PFCTL_SHOW_LABELS && labels)
842 			pfctl_print_title("LABEL COUNTERS:");
843 	}
844 	if (opts & PF_OPT_CLRRULECTRS)
845 		pr.action = PF_GET_CLR_CNTR;
846 
847 	pr.rule.action = PF_PASS;
848 	if (ioctl(dev, DIOCGETRULES, &pr)) {
849 		warn("DIOCGETRULES");
850 		goto error;
851 	}
852 	mnr = pr.nr;
853 	for (nr = 0; nr < mnr; ++nr) {
854 		pr.nr = nr;
855 		if (ioctl(dev, DIOCGETRULE, &pr)) {
856 			warn("DIOCGETRULE");
857 			goto error;
858 		}
859 
860 		if (pfctl_get_pool(dev, &pr.rule.rpool,
861 		    nr, pr.ticket, PF_PASS, path) != 0)
862 			goto error;
863 
864 		switch (format) {
865 		case PFCTL_SHOW_LABELS:
866 			if (pr.rule.label[0]) {
867 				printf("%s %llu %llu %llu %llu"
868 				    " %llu %llu %llu %llu\n",
869 				    pr.rule.label,
870 				    (unsigned long long)pr.rule.evaluations,
871 				    (unsigned long long)(pr.rule.packets[0] +
872 				    pr.rule.packets[1]),
873 				    (unsigned long long)(pr.rule.bytes[0] +
874 				    pr.rule.bytes[1]),
875 				    (unsigned long long)pr.rule.packets[0],
876 				    (unsigned long long)pr.rule.bytes[0],
877 				    (unsigned long long)pr.rule.packets[1],
878 				    (unsigned long long)pr.rule.bytes[1],
879 				    (unsigned long long)pr.rule.states_tot);
880 			}
881 			break;
882 		case PFCTL_SHOW_RULES:
883 			brace = 0;
884 			if (pr.rule.label[0] && (opts & PF_OPT_SHOWALL))
885 				labels = 1;
886 			INDENT(depth, !(opts & PF_OPT_VERBOSE));
887 			if (pr.anchor_call[0] &&
888 			   ((((p = strrchr(pr.anchor_call, '_')) != NULL) &&
889 			   ((void *)p == (void *)pr.anchor_call ||
890 			   *(--p) == '/')) || (opts & PF_OPT_RECURSE))) {
891 				brace++;
892 				if ((p = strrchr(pr.anchor_call, '/')) !=
893 				    NULL)
894 					p++;
895 				else
896 					p = &pr.anchor_call[0];
897 			} else
898 				p = &pr.anchor_call[0];
899 
900 			print_rule(&pr.rule, p, rule_numbers);
901 			if (brace)
902 				printf(" {\n");
903 			else
904 				printf("\n");
905 			pfctl_print_rule_counters(&pr.rule, opts);
906 			if (brace) {
907 				pfctl_show_rules(dev, path, opts, format,
908 				    p, depth + 1);
909 				INDENT(depth, !(opts & PF_OPT_VERBOSE));
910 				printf("}\n");
911 			}
912 			break;
913 		case PFCTL_SHOW_NOTHING:
914 			break;
915 		}
916 		pfctl_clear_pool(&pr.rule.rpool);
917 	}
918 	path[len] = '\0';
919 	return (0);
920 
921  error:
922 	path[len] = '\0';
923 	return (-1);
924 }
925 
926 int
927 pfctl_show_nat(int dev, int opts, char *anchorname)
928 {
929 	struct pfioc_rule pr;
930 	u_int32_t mnr, nr;
931 	static int nattype[3] = { PF_NAT, PF_RDR, PF_BINAT };
932 	int i, dotitle = opts & PF_OPT_SHOWALL;
933 
934 	memset(&pr, 0, sizeof(pr));
935 	memcpy(pr.anchor, anchorname, sizeof(pr.anchor));
936 	for (i = 0; i < 3; i++) {
937 		pr.rule.action = nattype[i];
938 		if (ioctl(dev, DIOCGETRULES, &pr)) {
939 			warn("DIOCGETRULES");
940 			return (-1);
941 		}
942 		mnr = pr.nr;
943 		for (nr = 0; nr < mnr; ++nr) {
944 			pr.nr = nr;
945 			if (ioctl(dev, DIOCGETRULE, &pr)) {
946 				warn("DIOCGETRULE");
947 				return (-1);
948 			}
949 			if (pfctl_get_pool(dev, &pr.rule.rpool, nr,
950 			    pr.ticket, nattype[i], anchorname) != 0)
951 				return (-1);
952 			if (dotitle) {
953 				pfctl_print_title("TRANSLATION RULES:");
954 				dotitle = 0;
955 			}
956 			print_rule(&pr.rule, pr.anchor_call,
957 			    opts & PF_OPT_VERBOSE2);
958 			printf("\n");
959 			pfctl_print_rule_counters(&pr.rule, opts);
960 			pfctl_clear_pool(&pr.rule.rpool);
961 		}
962 	}
963 	return (0);
964 }
965 
966 int
967 pfctl_show_src_nodes(int dev, int opts)
968 {
969 	struct pfioc_src_nodes psn;
970 	struct pf_src_node *p;
971 	char *inbuf = NULL, *newinbuf = NULL;
972 	unsigned int len = 0;
973 	int i;
974 
975 	memset(&psn, 0, sizeof(psn));
976 	for (;;) {
977 		psn.psn_len = len;
978 		if (len) {
979 			newinbuf = realloc(inbuf, len);
980 			if (newinbuf == NULL)
981 				err(1, "realloc");
982 			psn.psn_buf = inbuf = newinbuf;
983 		}
984 		if (ioctl(dev, DIOCGETSRCNODES, &psn) < 0) {
985 			warn("DIOCGETSRCNODES");
986 			free(inbuf);
987 			return (-1);
988 		}
989 		if (psn.psn_len + sizeof(struct pfioc_src_nodes) < len)
990 			break;
991 		if (len == 0 && psn.psn_len == 0)
992 			goto done;
993 		if (len == 0 && psn.psn_len != 0)
994 			len = psn.psn_len;
995 		if (psn.psn_len == 0)
996 			goto done;	/* no src_nodes */
997 		len *= 2;
998 	}
999 	p = psn.psn_src_nodes;
1000 	if (psn.psn_len > 0 && (opts & PF_OPT_SHOWALL))
1001 		pfctl_print_title("SOURCE TRACKING NODES:");
1002 	for (i = 0; i < psn.psn_len; i += sizeof(*p)) {
1003 		print_src_node(p, opts);
1004 		p++;
1005 	}
1006 done:
1007 	free(inbuf);
1008 	return (0);
1009 }
1010 
1011 int
1012 pfctl_show_states(int dev, const char *iface, int opts)
1013 {
1014 	struct pfioc_states ps;
1015 	struct pfsync_state *p;
1016 	char *inbuf = NULL, *newinbuf = NULL;
1017 	unsigned int len = 0;
1018 	int i, dotitle = (opts & PF_OPT_SHOWALL);
1019 
1020 	memset(&ps, 0, sizeof(ps));
1021 	for (;;) {
1022 		ps.ps_len = len;
1023 		if (len) {
1024 			newinbuf = realloc(inbuf, len);
1025 			if (newinbuf == NULL)
1026 				err(1, "realloc");
1027 			ps.ps_buf = inbuf = newinbuf;
1028 		}
1029 		if (ioctl(dev, DIOCGETSTATES, &ps) < 0) {
1030 			warn("DIOCGETSTATES");
1031 			free(inbuf);
1032 			return (-1);
1033 		}
1034 		if (ps.ps_len + sizeof(struct pfioc_states) < len)
1035 			break;
1036 		if (len == 0 && ps.ps_len == 0)
1037 			goto done;
1038 		if (len == 0 && ps.ps_len != 0)
1039 			len = ps.ps_len;
1040 		if (ps.ps_len == 0)
1041 			goto done;	/* no states */
1042 		len *= 2;
1043 	}
1044 	p = ps.ps_states;
1045 	for (i = 0; i < ps.ps_len; i += sizeof(*p), p++) {
1046 		if (iface != NULL && strcmp(p->ifname, iface))
1047 			continue;
1048 		if (dotitle) {
1049 			pfctl_print_title("STATES:");
1050 			dotitle = 0;
1051 		}
1052 		print_state(p, opts);
1053 	}
1054 done:
1055 	free(inbuf);
1056 	return (0);
1057 }
1058 
1059 int
1060 pfctl_show_status(int dev, int opts)
1061 {
1062 	struct pf_status status;
1063 
1064 	if (ioctl(dev, DIOCGETSTATUS, &status)) {
1065 		warn("DIOCGETSTATUS");
1066 		return (-1);
1067 	}
1068 	if (opts & PF_OPT_SHOWALL)
1069 		pfctl_print_title("INFO:");
1070 	print_status(&status, opts);
1071 	return (0);
1072 }
1073 
1074 int
1075 pfctl_show_timeouts(int dev, int opts)
1076 {
1077 	struct pfioc_tm pt;
1078 	int i;
1079 
1080 	if (opts & PF_OPT_SHOWALL)
1081 		pfctl_print_title("TIMEOUTS:");
1082 	memset(&pt, 0, sizeof(pt));
1083 	for (i = 0; pf_timeouts[i].name; i++) {
1084 		pt.timeout = pf_timeouts[i].timeout;
1085 		if (ioctl(dev, DIOCGETTIMEOUT, &pt))
1086 			err(1, "DIOCGETTIMEOUT");
1087 		printf("%-20s %10d", pf_timeouts[i].name, pt.seconds);
1088 		if (pf_timeouts[i].timeout >= PFTM_ADAPTIVE_START &&
1089 		    pf_timeouts[i].timeout <= PFTM_ADAPTIVE_END)
1090 			printf(" states");
1091 		else
1092 			printf("s");
1093 		printf("\n");
1094 	}
1095 	return (0);
1096 
1097 }
1098 
1099 int
1100 pfctl_show_limits(int dev, int opts)
1101 {
1102 	struct pfioc_limit pl;
1103 	int i;
1104 
1105 	if (opts & PF_OPT_SHOWALL)
1106 		pfctl_print_title("LIMITS:");
1107 	memset(&pl, 0, sizeof(pl));
1108 	for (i = 0; pf_limits[i].name; i++) {
1109 		pl.index = pf_limits[i].index;
1110 		if (ioctl(dev, DIOCGETLIMIT, &pl))
1111 			err(1, "DIOCGETLIMIT");
1112 		printf("%-13s ", pf_limits[i].name);
1113 		if (pl.limit == UINT_MAX)
1114 			printf("unlimited\n");
1115 		else
1116 			printf("hard limit %8u\n", pl.limit);
1117 	}
1118 	return (0);
1119 }
1120 
1121 /* callbacks for rule/nat/rdr/addr */
1122 int
1123 pfctl_add_pool(struct pfctl *pf, struct pf_pool *p, sa_family_t af)
1124 {
1125 	struct pf_pooladdr *pa;
1126 
1127 	if ((pf->opts & PF_OPT_NOACTION) == 0) {
1128 		if (ioctl(pf->dev, DIOCBEGINADDRS, &pf->paddr))
1129 			err(1, "DIOCBEGINADDRS");
1130 	}
1131 
1132 	pf->paddr.af = af;
1133 	TAILQ_FOREACH(pa, &p->list, entries) {
1134 		memcpy(&pf->paddr.addr, pa, sizeof(struct pf_pooladdr));
1135 		if ((pf->opts & PF_OPT_NOACTION) == 0) {
1136 			if (ioctl(pf->dev, DIOCADDADDR, &pf->paddr))
1137 				err(1, "DIOCADDADDR");
1138 		}
1139 	}
1140 	return (0);
1141 }
1142 
1143 int
1144 pfctl_add_rule(struct pfctl *pf, struct pf_rule *r, const char *anchor_call)
1145 {
1146 	u_int8_t		rs_num;
1147 	struct pf_rule		*rule;
1148 	struct pf_ruleset	*rs;
1149 	char 			*p;
1150 
1151 	rs_num = pf_get_ruleset_number(r->action == PF_MATCH ? PF_PASS :
1152 	    r->action);
1153 	if (rs_num == PF_RULESET_MAX)
1154 		errx(1, "Invalid rule type %d", r->action);
1155 
1156 	rs = &pf->anchor->ruleset;
1157 
1158 	if (anchor_call[0] && r->anchor == NULL) {
1159 		/*
1160 		 * Don't make non-brace anchors part of the main anchor pool.
1161 		 */
1162 		if ((r->anchor = calloc(1, sizeof(*r->anchor))) == NULL)
1163 			err(1, "pfctl_add_rule: calloc");
1164 
1165 		pf_init_ruleset(&r->anchor->ruleset);
1166 		r->anchor->ruleset.anchor = r->anchor;
1167 		if (strlcpy(r->anchor->path, anchor_call,
1168 		    sizeof(rule->anchor->path)) >= sizeof(rule->anchor->path))
1169                         errx(1, "pfctl_add_rule: strlcpy");
1170 		if ((p = strrchr(anchor_call, '/')) != NULL) {
1171 			if (!strlen(p))
1172 				err(1, "pfctl_add_rule: bad anchor name %s",
1173 				    anchor_call);
1174 		} else
1175 			p = (char *)anchor_call;
1176 		if (strlcpy(r->anchor->name, p,
1177 		    sizeof(rule->anchor->name)) >= sizeof(rule->anchor->name))
1178                         errx(1, "pfctl_add_rule: strlcpy");
1179 	}
1180 
1181 	if ((rule = calloc(1, sizeof(*rule))) == NULL)
1182 		err(1, "calloc");
1183 	bcopy(r, rule, sizeof(*rule));
1184 	TAILQ_INIT(&rule->rpool.list);
1185 	pfctl_move_pool(&r->rpool, &rule->rpool);
1186 
1187 	TAILQ_INSERT_TAIL(rs->rules[rs_num].active.ptr, rule, entries);
1188 	return (0);
1189 }
1190 
1191 int
1192 pfctl_ruleset_trans(struct pfctl *pf, char *path, struct pf_anchor *a)
1193 {
1194 	int osize = pf->trans->pfrb_size;
1195 
1196 	if ((pf->loadopt & PFCTL_FLAG_NAT) != 0) {
1197 		if (pfctl_add_trans(pf->trans, PF_RULESET_NAT, path) ||
1198 		    pfctl_add_trans(pf->trans, PF_RULESET_BINAT, path) ||
1199 		    pfctl_add_trans(pf->trans, PF_RULESET_RDR, path))
1200 			return (1);
1201 	}
1202 	if (a == pf->astack[0] && ((altqsupport &&
1203 	     (pf->loadopt & PFCTL_FLAG_ALTQ) != 0))) {
1204 		if (pfctl_add_trans(pf->trans, PF_RULESET_ALTQ, path))
1205 			return (2);
1206 	}
1207 	if ((pf->loadopt & PFCTL_FLAG_FILTER) != 0) {
1208 		if (pfctl_add_trans(pf->trans, PF_RULESET_FILTER, path))
1209 			return (3);
1210 	}
1211 	if (pf->loadopt & PFCTL_FLAG_TABLE)
1212 		if (pfctl_add_trans(pf->trans, PF_RULESET_TABLE, path))
1213 			return (4);
1214 	if (pfctl_trans(pf->dev, pf->trans, DIOCXBEGIN, osize))
1215 		return (5);
1216 
1217 	return (0);
1218 }
1219 
1220 int
1221 pfctl_load_ruleset(struct pfctl *pf, char *path, struct pf_ruleset *rs,
1222     int rs_num, int depth)
1223 {
1224 	struct pf_rule *r;
1225 	int		error, len = strlen(path);
1226 	int		brace = 0;
1227 
1228 	pf->anchor = rs->anchor;
1229 
1230 	if (path[0])
1231 		snprintf(&path[len], MAXPATHLEN - len, "/%s", pf->anchor->name);
1232 	else
1233 		snprintf(&path[len], MAXPATHLEN - len, "%s", pf->anchor->name);
1234 
1235 	if (depth) {
1236 		if (TAILQ_FIRST(rs->rules[rs_num].active.ptr) != NULL) {
1237 			brace++;
1238 			if (pf->opts & PF_OPT_VERBOSE)
1239 				printf(" {\n");
1240 			if ((pf->opts & PF_OPT_NOACTION) == 0 &&
1241 			    (error = pfctl_ruleset_trans(pf,
1242 			    path, rs->anchor))) {
1243 				printf("pfctl_load_rulesets: "
1244 				    "pfctl_ruleset_trans %d\n", error);
1245 				goto error;
1246 			}
1247 		} else if (pf->opts & PF_OPT_VERBOSE)
1248 			printf("\n");
1249 
1250 	}
1251 
1252 	if (pf->optimize && rs_num == PF_RULESET_FILTER)
1253 		pfctl_optimize_ruleset(pf, rs);
1254 
1255 	while ((r = TAILQ_FIRST(rs->rules[rs_num].active.ptr)) != NULL) {
1256 		TAILQ_REMOVE(rs->rules[rs_num].active.ptr, r, entries);
1257 		if ((error = pfctl_load_rule(pf, path, r, depth)))
1258 			goto error;
1259 		if (r->anchor) {
1260 			if ((error = pfctl_load_ruleset(pf, path,
1261 			    &r->anchor->ruleset, rs_num, depth + 1)))
1262 				goto error;
1263 		} else if (pf->opts & PF_OPT_VERBOSE)
1264 			printf("\n");
1265 		free(r);
1266 	}
1267 	if (brace && pf->opts & PF_OPT_VERBOSE) {
1268 		INDENT(depth - 1, (pf->opts & PF_OPT_VERBOSE));
1269 		printf("}\n");
1270 	}
1271 	path[len] = '\0';
1272 	return (0);
1273 
1274  error:
1275 	path[len] = '\0';
1276 	return (error);
1277 
1278 }
1279 
1280 int
1281 pfctl_load_rule(struct pfctl *pf, char *path, struct pf_rule *r, int depth)
1282 {
1283 	u_int8_t		rs_num = pf_get_ruleset_number(r->action);
1284 	char			*name;
1285 	struct pfioc_rule	pr;
1286 	int			len = strlen(path);
1287 
1288 	bzero(&pr, sizeof(pr));
1289 	/* set up anchor before adding to path for anchor_call */
1290 	if ((pf->opts & PF_OPT_NOACTION) == 0)
1291 		pr.ticket = pfctl_get_ticket(pf->trans, rs_num, path);
1292 	if (strlcpy(pr.anchor, path, sizeof(pr.anchor)) >= sizeof(pr.anchor))
1293 		errx(1, "pfctl_load_rule: strlcpy");
1294 
1295 	if (r->anchor) {
1296 		if (r->anchor->match) {
1297 			if (path[0])
1298 				snprintf(&path[len], MAXPATHLEN - len,
1299 				    "/%s", r->anchor->name);
1300 			else
1301 				snprintf(&path[len], MAXPATHLEN - len,
1302 				    "%s", r->anchor->name);
1303 			name = path;
1304 		} else
1305 			name = r->anchor->path;
1306 	} else
1307 		name = "";
1308 
1309 	if ((pf->opts & PF_OPT_NOACTION) == 0) {
1310 		if (pfctl_add_pool(pf, &r->rpool, r->af))
1311 			return (1);
1312 		pr.pool_ticket = pf->paddr.ticket;
1313 		memcpy(&pr.rule, r, sizeof(pr.rule));
1314 		if (r->anchor && strlcpy(pr.anchor_call, name,
1315 		    sizeof(pr.anchor_call)) >= sizeof(pr.anchor_call))
1316 			errx(1, "pfctl_load_rule: strlcpy");
1317 		if (ioctl(pf->dev, DIOCADDRULE, &pr))
1318 			err(1, "DIOCADDRULE");
1319 	}
1320 
1321 	if (pf->opts & PF_OPT_VERBOSE) {
1322 		INDENT(depth, !(pf->opts & PF_OPT_VERBOSE2));
1323 		print_rule(r, r->anchor ? r->anchor->name : "",
1324 		    pf->opts & PF_OPT_VERBOSE2);
1325 	}
1326 	path[len] = '\0';
1327 	pfctl_clear_pool(&r->rpool);
1328 	return (0);
1329 }
1330 
1331 int
1332 pfctl_add_altq(struct pfctl *pf, struct pf_altq *a)
1333 {
1334 	if (altqsupport &&
1335 	    (loadopt & PFCTL_FLAG_ALTQ) != 0) {
1336 		memcpy(&pf->paltq->altq, a, sizeof(struct pf_altq));
1337 		if ((pf->opts & PF_OPT_NOACTION) == 0) {
1338 			if (ioctl(pf->dev, DIOCADDALTQ, pf->paltq)) {
1339 				if (errno == ENXIO)
1340 					errx(1, "qtype not configured");
1341 				else if (errno == ENODEV)
1342 					errx(1, "%s: driver does not support "
1343 					    "altq", a->ifname);
1344 				else
1345 					err(1, "DIOCADDALTQ");
1346 			}
1347 		}
1348 		pfaltq_store(&pf->paltq->altq);
1349 	}
1350 	return (0);
1351 }
1352 
1353 int
1354 pfctl_rules(int dev, char *filename, int opts, int optimize,
1355     char *anchorname, struct pfr_buffer *trans)
1356 {
1357 #define ERR(x) do { warn(x); goto _error; } while(0)
1358 #define ERRX(x) do { warnx(x); goto _error; } while(0)
1359 
1360 	struct pfr_buffer	*t, buf;
1361 	struct pfioc_altq	 pa;
1362 	struct pfctl		 pf;
1363 	struct pf_ruleset	*rs;
1364 	struct pfr_table	 trs;
1365 	char			*path;
1366 	int			 osize;
1367 
1368 	RB_INIT(&pf_anchors);
1369 	memset(&pf_main_anchor, 0, sizeof(pf_main_anchor));
1370 	pf_init_ruleset(&pf_main_anchor.ruleset);
1371 	pf_main_anchor.ruleset.anchor = &pf_main_anchor;
1372 	if (trans == NULL) {
1373 		bzero(&buf, sizeof(buf));
1374 		buf.pfrb_type = PFRB_TRANS;
1375 		t = &buf;
1376 		osize = 0;
1377 	} else {
1378 		t = trans;
1379 		osize = t->pfrb_size;
1380 	}
1381 
1382 	memset(&pa, 0, sizeof(pa));
1383 	memset(&pf, 0, sizeof(pf));
1384 	memset(&trs, 0, sizeof(trs));
1385 	if ((path = calloc(1, MAXPATHLEN)) == NULL)
1386 		ERRX("pfctl_rules: calloc");
1387 	if (strlcpy(trs.pfrt_anchor, anchorname,
1388 	    sizeof(trs.pfrt_anchor)) >= sizeof(trs.pfrt_anchor))
1389 		ERRX("pfctl_rules: strlcpy");
1390 	pf.dev = dev;
1391 	pf.opts = opts;
1392 	pf.optimize = optimize;
1393 	pf.loadopt = loadopt;
1394 
1395 	/* non-brace anchor, create without resolving the path */
1396 	if ((pf.anchor = calloc(1, sizeof(*pf.anchor))) == NULL)
1397 		ERRX("pfctl_rules: calloc");
1398 	rs = &pf.anchor->ruleset;
1399 	pf_init_ruleset(rs);
1400 	rs->anchor = pf.anchor;
1401 	if (strlcpy(pf.anchor->path, anchorname,
1402 	    sizeof(pf.anchor->path)) >= sizeof(pf.anchor->path))
1403 		errx(1, "pfctl_add_rule: strlcpy");
1404 	if (strlcpy(pf.anchor->name, anchorname,
1405 	    sizeof(pf.anchor->name)) >= sizeof(pf.anchor->name))
1406 		errx(1, "pfctl_add_rule: strlcpy");
1407 
1408 
1409 	pf.astack[0] = pf.anchor;
1410 	pf.asd = 0;
1411 	if (anchorname[0])
1412 		pf.loadopt &= ~PFCTL_FLAG_ALTQ;
1413 	pf.paltq = &pa;
1414 	pf.trans = t;
1415 	pfctl_init_options(&pf);
1416 
1417 	if ((opts & PF_OPT_NOACTION) == 0) {
1418 		/*
1419 		 * XXX For the time being we need to open transactions for
1420 		 * the main ruleset before parsing, because tables are still
1421 		 * loaded at parse time.
1422 		 */
1423 		if (pfctl_ruleset_trans(&pf, anchorname, pf.anchor))
1424 			ERRX("pfctl_rules");
1425 		if (altqsupport && (pf.loadopt & PFCTL_FLAG_ALTQ))
1426 			pa.ticket =
1427 			    pfctl_get_ticket(t, PF_RULESET_ALTQ, anchorname);
1428 		if (pf.loadopt & PFCTL_FLAG_TABLE)
1429 			pf.astack[0]->ruleset.tticket =
1430 			    pfctl_get_ticket(t, PF_RULESET_TABLE, anchorname);
1431 	}
1432 
1433 	if (parse_config(filename, &pf) < 0) {
1434 		if ((opts & PF_OPT_NOACTION) == 0)
1435 			ERRX("Syntax error in config file: "
1436 			    "pf rules not loaded");
1437 		else
1438 			goto _error;
1439 	}
1440 
1441 	if ((pf.loadopt & PFCTL_FLAG_NAT &&
1442 	    (pfctl_load_ruleset(&pf, path, rs, PF_RULESET_NAT, 0) ||
1443 	    pfctl_load_ruleset(&pf, path, rs, PF_RULESET_RDR, 0) ||
1444 	    pfctl_load_ruleset(&pf, path, rs, PF_RULESET_BINAT, 0))) ||
1445 	    (pf.loadopt & PFCTL_FLAG_FILTER &&
1446 	    pfctl_load_ruleset(&pf, path, rs, PF_RULESET_FILTER, 0))) {
1447 		if ((opts & PF_OPT_NOACTION) == 0)
1448 			ERRX("Unable to load rules into kernel");
1449 		else
1450 			goto _error;
1451 	}
1452 
1453 	if ((altqsupport && (pf.loadopt & PFCTL_FLAG_ALTQ) != 0))
1454 		if (check_commit_altq(dev, opts) != 0)
1455 			ERRX("errors in altq config");
1456 
1457 	/* process "load anchor" directives */
1458 	if (!anchorname[0])
1459 		if (pfctl_load_anchors(dev, &pf, t) == -1)
1460 			ERRX("load anchors");
1461 
1462 	if (trans == NULL && (opts & PF_OPT_NOACTION) == 0) {
1463 		if (!anchorname[0])
1464 			if (pfctl_load_options(&pf))
1465 				goto _error;
1466 		if (pfctl_trans(dev, t, DIOCXCOMMIT, osize))
1467 			ERR("DIOCXCOMMIT");
1468 	}
1469 	return (0);
1470 
1471 _error:
1472 	if (trans == NULL) {	/* main ruleset */
1473 		if ((opts & PF_OPT_NOACTION) == 0)
1474 			if (pfctl_trans(dev, t, DIOCXROLLBACK, osize))
1475 				err(1, "DIOCXROLLBACK");
1476 		exit(1);
1477 	} else {		/* sub ruleset */
1478 		return (-1);
1479 	}
1480 
1481 #undef ERR
1482 #undef ERRX
1483 }
1484 
1485 FILE *
1486 pfctl_fopen(const char *name, const char *mode)
1487 {
1488 	struct stat	 st;
1489 	FILE		*fp;
1490 
1491 	fp = fopen(name, mode);
1492 	if (fp == NULL)
1493 		return (NULL);
1494 	if (fstat(fileno(fp), &st)) {
1495 		fclose(fp);
1496 		return (NULL);
1497 	}
1498 	if (S_ISDIR(st.st_mode)) {
1499 		fclose(fp);
1500 		errno = EISDIR;
1501 		return (NULL);
1502 	}
1503 	return (fp);
1504 }
1505 
1506 void
1507 pfctl_init_options(struct pfctl *pf)
1508 {
1509 	int64_t mem;
1510 	int mib[2];
1511 	size_t size;
1512 
1513 	pf->timeout[PFTM_TCP_FIRST_PACKET] = PFTM_TCP_FIRST_PACKET_VAL;
1514 	pf->timeout[PFTM_TCP_OPENING] = PFTM_TCP_OPENING_VAL;
1515 	pf->timeout[PFTM_TCP_ESTABLISHED] = PFTM_TCP_ESTABLISHED_VAL;
1516 	pf->timeout[PFTM_TCP_CLOSING] = PFTM_TCP_CLOSING_VAL;
1517 	pf->timeout[PFTM_TCP_FIN_WAIT] = PFTM_TCP_FIN_WAIT_VAL;
1518 	pf->timeout[PFTM_TCP_CLOSED] = PFTM_TCP_CLOSED_VAL;
1519 	pf->timeout[PFTM_UDP_FIRST_PACKET] = PFTM_UDP_FIRST_PACKET_VAL;
1520 	pf->timeout[PFTM_UDP_SINGLE] = PFTM_UDP_SINGLE_VAL;
1521 	pf->timeout[PFTM_UDP_MULTIPLE] = PFTM_UDP_MULTIPLE_VAL;
1522 	pf->timeout[PFTM_ICMP_FIRST_PACKET] = PFTM_ICMP_FIRST_PACKET_VAL;
1523 	pf->timeout[PFTM_ICMP_ERROR_REPLY] = PFTM_ICMP_ERROR_REPLY_VAL;
1524 	pf->timeout[PFTM_OTHER_FIRST_PACKET] = PFTM_OTHER_FIRST_PACKET_VAL;
1525 	pf->timeout[PFTM_OTHER_SINGLE] = PFTM_OTHER_SINGLE_VAL;
1526 	pf->timeout[PFTM_OTHER_MULTIPLE] = PFTM_OTHER_MULTIPLE_VAL;
1527 	pf->timeout[PFTM_FRAG] = PFTM_FRAG_VAL;
1528 	pf->timeout[PFTM_INTERVAL] = PFTM_INTERVAL_VAL;
1529 	pf->timeout[PFTM_SRC_NODE] = PFTM_SRC_NODE_VAL;
1530 	pf->timeout[PFTM_TS_DIFF] = PFTM_TS_DIFF_VAL;
1531 	pf->timeout[PFTM_ADAPTIVE_START] = PFSTATE_ADAPT_START;
1532 	pf->timeout[PFTM_ADAPTIVE_END] = PFSTATE_ADAPT_END;
1533 
1534 	pf->limit[PF_LIMIT_STATES] = PFSTATE_HIWAT;
1535 	pf->limit[PF_LIMIT_FRAGS] = PFFRAG_FRENT_HIWAT;
1536 	pf->limit[PF_LIMIT_SRC_NODES] = PFSNODE_HIWAT;
1537 	pf->limit[PF_LIMIT_TABLES] = PFR_KTABLE_HIWAT;
1538 	pf->limit[PF_LIMIT_TABLE_ENTRIES] = PFR_KENTRY_HIWAT;
1539 
1540 	mib[0] = CTL_HW;
1541 	mib[1] = HW_PHYSMEM64;
1542 	size = sizeof(mem);
1543 	if (sysctl(mib, 2, &mem, &size, NULL, 0) == -1)
1544 		err(1, "sysctl");
1545 	if (mem <= 100*1024*1024)
1546 		pf->limit[PF_LIMIT_TABLE_ENTRIES] = PFR_KENTRY_HIWAT_SMALL;
1547 
1548 	pf->debug = PF_DEBUG_URGENT;
1549 	pf->reassemble = PF_REASS_ENABLED;
1550 }
1551 
1552 int
1553 pfctl_load_options(struct pfctl *pf)
1554 {
1555 	int i, error = 0;
1556 
1557 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1558 		return (0);
1559 
1560 	/* load limits */
1561 	for (i = 0; i < PF_LIMIT_MAX; i++) {
1562 		if ((pf->opts & PF_OPT_MERGE) && !pf->limit_set[i])
1563 			continue;
1564 		if (pfctl_load_limit(pf, i, pf->limit[i]))
1565 			error = 1;
1566 	}
1567 
1568 	/*
1569 	 * If we've set the limit, but haven't explicitly set adaptive
1570 	 * timeouts, do it now with a start of 60% and end of 120%.
1571 	 */
1572 	if (pf->limit_set[PF_LIMIT_STATES] &&
1573 	    !pf->timeout_set[PFTM_ADAPTIVE_START] &&
1574 	    !pf->timeout_set[PFTM_ADAPTIVE_END]) {
1575 		pf->timeout[PFTM_ADAPTIVE_START] =
1576 			(pf->limit[PF_LIMIT_STATES] / 10) * 6;
1577 		pf->timeout_set[PFTM_ADAPTIVE_START] = 1;
1578 		pf->timeout[PFTM_ADAPTIVE_END] =
1579 			(pf->limit[PF_LIMIT_STATES] / 10) * 12;
1580 		pf->timeout_set[PFTM_ADAPTIVE_END] = 1;
1581 	}
1582 
1583 	/* load timeouts */
1584 	for (i = 0; i < PFTM_MAX; i++) {
1585 		if ((pf->opts & PF_OPT_MERGE) && !pf->timeout_set[i])
1586 			continue;
1587 		if (pfctl_load_timeout(pf, i, pf->timeout[i]))
1588 			error = 1;
1589 	}
1590 
1591 	/* load debug */
1592 	if (!(pf->opts & PF_OPT_MERGE) || pf->debug_set)
1593 		if (pfctl_load_debug(pf, pf->debug))
1594 			error = 1;
1595 
1596 	/* load logif */
1597 	if (!(pf->opts & PF_OPT_MERGE) || pf->ifname_set)
1598 		if (pfctl_load_logif(pf, pf->ifname))
1599 			error = 1;
1600 
1601 	/* load hostid */
1602 	if (!(pf->opts & PF_OPT_MERGE) || pf->hostid_set)
1603 		if (pfctl_load_hostid(pf, pf->hostid))
1604 			error = 1;
1605 
1606 	/* load reassembly settings */
1607 	if (!(pf->opts & PF_OPT_MERGE) || pf->reass_set)
1608 		if (pfctl_load_reassembly(pf, pf->reassemble))
1609 			error = 1;
1610 
1611 	return (error);
1612 }
1613 
1614 int
1615 pfctl_set_limit(struct pfctl *pf, const char *opt, unsigned int limit)
1616 {
1617 	int i;
1618 
1619 
1620 	for (i = 0; pf_limits[i].name; i++) {
1621 		if (strcasecmp(opt, pf_limits[i].name) == 0) {
1622 			pf->limit[pf_limits[i].index] = limit;
1623 			pf->limit_set[pf_limits[i].index] = 1;
1624 			break;
1625 		}
1626 	}
1627 	if (pf_limits[i].name == NULL) {
1628 		warnx("Bad pool name.");
1629 		return (1);
1630 	}
1631 
1632 	if (pf->opts & PF_OPT_VERBOSE)
1633 		printf("set limit %s %d\n", opt, limit);
1634 
1635 	return (0);
1636 }
1637 
1638 int
1639 pfctl_load_limit(struct pfctl *pf, unsigned int index, unsigned int limit)
1640 {
1641 	struct pfioc_limit pl;
1642 
1643 	memset(&pl, 0, sizeof(pl));
1644 	pl.index = index;
1645 	pl.limit = limit;
1646 	if (ioctl(pf->dev, DIOCSETLIMIT, &pl)) {
1647 		if (errno == EBUSY)
1648 			warnx("Current pool size exceeds requested hard limit");
1649 		else
1650 			warnx("DIOCSETLIMIT");
1651 		return (1);
1652 	}
1653 	return (0);
1654 }
1655 
1656 int
1657 pfctl_set_timeout(struct pfctl *pf, const char *opt, int seconds, int quiet)
1658 {
1659 	int i;
1660 
1661 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1662 		return (0);
1663 
1664 	for (i = 0; pf_timeouts[i].name; i++) {
1665 		if (strcasecmp(opt, pf_timeouts[i].name) == 0) {
1666 			pf->timeout[pf_timeouts[i].timeout] = seconds;
1667 			pf->timeout_set[pf_timeouts[i].timeout] = 1;
1668 			break;
1669 		}
1670 	}
1671 
1672 	if (pf_timeouts[i].name == NULL) {
1673 		warnx("Bad timeout name.");
1674 		return (1);
1675 	}
1676 
1677 
1678 	if (pf->opts & PF_OPT_VERBOSE && ! quiet)
1679 		printf("set timeout %s %d\n", opt, seconds);
1680 
1681 	return (0);
1682 }
1683 
1684 int
1685 pfctl_load_timeout(struct pfctl *pf, unsigned int timeout, unsigned int seconds)
1686 {
1687 	struct pfioc_tm pt;
1688 
1689 	memset(&pt, 0, sizeof(pt));
1690 	pt.timeout = timeout;
1691 	pt.seconds = seconds;
1692 	if (ioctl(pf->dev, DIOCSETTIMEOUT, &pt)) {
1693 		warnx("DIOCSETTIMEOUT");
1694 		return (1);
1695 	}
1696 	return (0);
1697 }
1698 
1699 int
1700 pfctl_set_reassembly(struct pfctl *pf, int on, int nodf)
1701 {
1702 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1703 		return (0);
1704 
1705 	pf->reass_set = 1;
1706 	if (on) {
1707 		pf->reassemble = PF_REASS_ENABLED;
1708 		if (nodf)
1709 			pf->reassemble |= PF_REASS_NODF;
1710 	} else {
1711 		pf->reassemble = 0;
1712 	}
1713 
1714 	if (pf->opts & PF_OPT_VERBOSE)
1715 		printf("set reassemble %s %s\n", on ? "yes" : "no",
1716 		    nodf ? "no-df" : "");
1717 
1718 	return (0);
1719 }
1720 
1721 int
1722 pfctl_set_optimization(struct pfctl *pf, const char *opt)
1723 {
1724 	const struct pf_hint *hint;
1725 	int i, r;
1726 
1727 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1728 		return (0);
1729 
1730 	for (i = 0; pf_hints[i].name; i++)
1731 		if (strcasecmp(opt, pf_hints[i].name) == 0)
1732 			break;
1733 
1734 	hint = pf_hints[i].hint;
1735 	if (hint == NULL) {
1736 		warnx("invalid state timeouts optimization");
1737 		return (1);
1738 	}
1739 
1740 	for (i = 0; hint[i].name; i++)
1741 		if ((r = pfctl_set_timeout(pf, hint[i].name,
1742 		    hint[i].timeout, 1)))
1743 			return (r);
1744 
1745 	if (pf->opts & PF_OPT_VERBOSE)
1746 		printf("set optimization %s\n", opt);
1747 
1748 	return (0);
1749 }
1750 
1751 int
1752 pfctl_set_logif(struct pfctl *pf, char *ifname)
1753 {
1754 
1755 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1756 		return (0);
1757 
1758 	if (!strcmp(ifname, "none")) {
1759 		free(pf->ifname);
1760 		pf->ifname = NULL;
1761 	} else {
1762 		pf->ifname = strdup(ifname);
1763 		if (!pf->ifname)
1764 			errx(1, "pfctl_set_logif: strdup");
1765 	}
1766 	pf->ifname_set = 1;
1767 
1768 	if (pf->opts & PF_OPT_VERBOSE)
1769 		printf("set loginterface %s\n", ifname);
1770 
1771 	return (0);
1772 }
1773 
1774 int
1775 pfctl_load_logif(struct pfctl *pf, char *ifname)
1776 {
1777 	struct pfioc_if pi;
1778 
1779 	memset(&pi, 0, sizeof(pi));
1780 	if (ifname && strlcpy(pi.ifname, ifname,
1781 	    sizeof(pi.ifname)) >= sizeof(pi.ifname)) {
1782 		warnx("pfctl_load_logif: strlcpy");
1783 		return (1);
1784 	}
1785 	if (ioctl(pf->dev, DIOCSETSTATUSIF, &pi)) {
1786 		warnx("DIOCSETSTATUSIF");
1787 		return (1);
1788 	}
1789 	return (0);
1790 }
1791 
1792 int
1793 pfctl_set_hostid(struct pfctl *pf, u_int32_t hostid)
1794 {
1795 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1796 		return (0);
1797 
1798 	HTONL(hostid);
1799 
1800 	pf->hostid = hostid;
1801 	pf->hostid_set = 1;
1802 
1803 	if (pf->opts & PF_OPT_VERBOSE)
1804 		printf("set hostid 0x%08x\n", ntohl(hostid));
1805 
1806 	return (0);
1807 }
1808 
1809 int
1810 pfctl_load_hostid(struct pfctl *pf, u_int32_t hostid)
1811 {
1812 	if (ioctl(dev, DIOCSETHOSTID, &hostid)) {
1813 		warnx("DIOCSETHOSTID");
1814 		return (1);
1815 	}
1816 	return (0);
1817 }
1818 
1819 int
1820 pfctl_load_reassembly(struct pfctl *pf, u_int32_t reassembly)
1821 {
1822 	if (ioctl(dev, DIOCSETREASS, &reassembly)) {
1823 		warnx("DIOCSETREASS");
1824 		return (1);
1825 	}
1826 	return (0);
1827 }
1828 
1829 int
1830 pfctl_set_debug(struct pfctl *pf, char *d)
1831 {
1832 	u_int32_t	level;
1833 
1834 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1835 		return (0);
1836 
1837 	if (!strcmp(d, "none"))
1838 		pf->debug = PF_DEBUG_NONE;
1839 	else if (!strcmp(d, "urgent"))
1840 		pf->debug = PF_DEBUG_URGENT;
1841 	else if (!strcmp(d, "misc"))
1842 		pf->debug = PF_DEBUG_MISC;
1843 	else if (!strcmp(d, "loud"))
1844 		pf->debug = PF_DEBUG_NOISY;
1845 	else {
1846 		warnx("unknown debug level \"%s\"", d);
1847 		return (-1);
1848 	}
1849 
1850 	pf->debug_set = 1;
1851 
1852 	if ((pf->opts & PF_OPT_NOACTION) == 0)
1853 		if (ioctl(dev, DIOCSETDEBUG, &level))
1854 			err(1, "DIOCSETDEBUG");
1855 
1856 	if (pf->opts & PF_OPT_VERBOSE)
1857 		printf("set debug %s\n", d);
1858 
1859 	return (0);
1860 }
1861 
1862 int
1863 pfctl_load_debug(struct pfctl *pf, unsigned int level)
1864 {
1865 	if (ioctl(pf->dev, DIOCSETDEBUG, &level)) {
1866 		warnx("DIOCSETDEBUG");
1867 		return (1);
1868 	}
1869 	return (0);
1870 }
1871 
1872 int
1873 pfctl_set_interface_flags(struct pfctl *pf, char *ifname, int flags, int how)
1874 {
1875 	struct pfioc_iface	pi;
1876 
1877 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1878 		return (0);
1879 
1880 	bzero(&pi, sizeof(pi));
1881 
1882 	pi.pfiio_flags = flags;
1883 
1884 	if (strlcpy(pi.pfiio_name, ifname, sizeof(pi.pfiio_name)) >=
1885 	    sizeof(pi.pfiio_name))
1886 		errx(1, "pfctl_set_interface_flags: strlcpy");
1887 
1888 	if ((pf->opts & PF_OPT_NOACTION) == 0) {
1889 		if (how == 0) {
1890 			if (ioctl(pf->dev, DIOCCLRIFFLAG, &pi))
1891 				err(1, "DIOCCLRIFFLAG");
1892 		} else {
1893 			if (ioctl(pf->dev, DIOCSETIFFLAG, &pi))
1894 				err(1, "DIOCSETIFFLAG");
1895 		}
1896 	}
1897 	return (0);
1898 }
1899 
1900 void
1901 pfctl_debug(int dev, u_int32_t level, int opts)
1902 {
1903 	if (ioctl(dev, DIOCSETDEBUG, &level))
1904 		err(1, "DIOCSETDEBUG");
1905 	if ((opts & PF_OPT_QUIET) == 0) {
1906 		fprintf(stderr, "debug level set to '");
1907 		switch (level) {
1908 		case PF_DEBUG_NONE:
1909 			fprintf(stderr, "none");
1910 			break;
1911 		case PF_DEBUG_URGENT:
1912 			fprintf(stderr, "urgent");
1913 			break;
1914 		case PF_DEBUG_MISC:
1915 			fprintf(stderr, "misc");
1916 			break;
1917 		case PF_DEBUG_NOISY:
1918 			fprintf(stderr, "loud");
1919 			break;
1920 		default:
1921 			fprintf(stderr, "<invalid>");
1922 			break;
1923 		}
1924 		fprintf(stderr, "'\n");
1925 	}
1926 }
1927 
1928 int
1929 pfctl_test_altqsupport(int dev, int opts)
1930 {
1931 	struct pfioc_altq pa;
1932 
1933 	if (ioctl(dev, DIOCGETALTQS, &pa)) {
1934 		if (errno == ENODEV) {
1935 			if (!(opts & PF_OPT_QUIET))
1936 				fprintf(stderr, "No ALTQ support in kernel\n"
1937 				    "ALTQ related functions disabled\n");
1938 			return (0);
1939 		} else
1940 			err(1, "DIOCGETALTQS");
1941 	}
1942 	return (1);
1943 }
1944 
1945 int
1946 pfctl_show_anchors(int dev, int opts, char *anchorname)
1947 {
1948 	struct pfioc_ruleset	 pr;
1949 	u_int32_t		 mnr, nr;
1950 
1951 	memset(&pr, 0, sizeof(pr));
1952 	memcpy(pr.path, anchorname, sizeof(pr.path));
1953 	if (ioctl(dev, DIOCGETRULESETS, &pr)) {
1954 		if (errno == EINVAL)
1955 			fprintf(stderr, "Anchor '%s' not found.\n",
1956 			    anchorname);
1957 		else
1958 			err(1, "DIOCGETRULESETS");
1959 		return (-1);
1960 	}
1961 	mnr = pr.nr;
1962 	for (nr = 0; nr < mnr; ++nr) {
1963 		char sub[MAXPATHLEN];
1964 
1965 		pr.nr = nr;
1966 		if (ioctl(dev, DIOCGETRULESET, &pr))
1967 			err(1, "DIOCGETRULESET");
1968 		if (!strcmp(pr.name, PF_RESERVED_ANCHOR))
1969 			continue;
1970 		sub[0] = 0;
1971 		if (pr.path[0]) {
1972 			strlcat(sub, pr.path, sizeof(sub));
1973 			strlcat(sub, "/", sizeof(sub));
1974 		}
1975 		strlcat(sub, pr.name, sizeof(sub));
1976 		if (sub[0] != '_' || (opts & PF_OPT_VERBOSE))
1977 			printf("  %s\n", sub);
1978 		if ((opts & PF_OPT_VERBOSE) && pfctl_show_anchors(dev, opts, sub))
1979 			return (-1);
1980 	}
1981 	return (0);
1982 }
1983 
1984 const char *
1985 pfctl_lookup_option(char *cmd, const char **list)
1986 {
1987 	if (cmd != NULL && *cmd)
1988 		for (; *list; list++)
1989 			if (!strncmp(cmd, *list, strlen(cmd)))
1990 				return (*list);
1991 	return (NULL);
1992 }
1993 
1994 int
1995 main(int argc, char *argv[])
1996 {
1997 	int	 error = 0;
1998 	int	 ch;
1999 	int	 mode = O_RDONLY;
2000 	int	 opts = 0;
2001 	int	 optimize = PF_OPTIMIZE_BASIC;
2002 	char	 anchorname[MAXPATHLEN];
2003 	char	*path;
2004 
2005 	if (argc < 2)
2006 		usage();
2007 
2008 	while ((ch = getopt(argc, argv,
2009 	    "a:AdD:eqf:F:ghi:k:K:mnNOo:p:rRs:t:T:vx:z")) != -1) {
2010 		switch (ch) {
2011 		case 'a':
2012 			anchoropt = optarg;
2013 			break;
2014 		case 'd':
2015 			opts |= PF_OPT_DISABLE;
2016 			mode = O_RDWR;
2017 			break;
2018 		case 'D':
2019 			if (pfctl_cmdline_symset(optarg) < 0)
2020 				warnx("could not parse macro definition %s",
2021 				    optarg);
2022 			break;
2023 		case 'e':
2024 			opts |= PF_OPT_ENABLE;
2025 			mode = O_RDWR;
2026 			break;
2027 		case 'q':
2028 			opts |= PF_OPT_QUIET;
2029 			break;
2030 		case 'F':
2031 			clearopt = pfctl_lookup_option(optarg, clearopt_list);
2032 			if (clearopt == NULL) {
2033 				warnx("Unknown flush modifier '%s'", optarg);
2034 				usage();
2035 			}
2036 			mode = O_RDWR;
2037 			break;
2038 		case 'i':
2039 			ifaceopt = optarg;
2040 			break;
2041 		case 'k':
2042 			if (state_killers >= 2) {
2043 				warnx("can only specify -k twice");
2044 				usage();
2045 				/* NOTREACHED */
2046 			}
2047 			state_kill[state_killers++] = optarg;
2048 			mode = O_RDWR;
2049 			break;
2050 		case 'K':
2051 			if (src_node_killers >= 2) {
2052 				warnx("can only specify -K twice");
2053 				usage();
2054 				/* NOTREACHED */
2055 			}
2056 			src_node_kill[src_node_killers++] = optarg;
2057 			mode = O_RDWR;
2058 			break;
2059 		case 'm':
2060 			opts |= PF_OPT_MERGE;
2061 			break;
2062 		case 'n':
2063 			opts |= PF_OPT_NOACTION;
2064 			break;
2065 		case 'N':
2066 			loadopt |= PFCTL_FLAG_NAT;
2067 			break;
2068 		case 'r':
2069 			opts |= PF_OPT_USEDNS;
2070 			break;
2071 		case 'f':
2072 			rulesopt = optarg;
2073 			mode = O_RDWR;
2074 			break;
2075 		case 'g':
2076 			opts |= PF_OPT_DEBUG;
2077 			break;
2078 		case 'A':
2079 			loadopt |= PFCTL_FLAG_ALTQ;
2080 			break;
2081 		case 'R':
2082 			loadopt |= PFCTL_FLAG_FILTER;
2083 			break;
2084 		case 'o':
2085 			optiopt = pfctl_lookup_option(optarg, optiopt_list);
2086 			if (optiopt == NULL) {
2087 				warnx("Unknown optimization '%s'", optarg);
2088 				usage();
2089 			}
2090 			opts |= PF_OPT_OPTIMIZE;
2091 			break;
2092 		case 'O':
2093 			loadopt |= PFCTL_FLAG_OPTION;
2094 			break;
2095 		case 'p':
2096 			pf_device = optarg;
2097 			break;
2098 		case 's':
2099 			showopt = pfctl_lookup_option(optarg, showopt_list);
2100 			if (showopt == NULL) {
2101 				warnx("Unknown show modifier '%s'", optarg);
2102 				usage();
2103 			}
2104 			break;
2105 		case 't':
2106 			tableopt = optarg;
2107 			break;
2108 		case 'T':
2109 			tblcmdopt = pfctl_lookup_option(optarg, tblcmdopt_list);
2110 			if (tblcmdopt == NULL) {
2111 				warnx("Unknown table command '%s'", optarg);
2112 				usage();
2113 			}
2114 			break;
2115 		case 'v':
2116 			if (opts & PF_OPT_VERBOSE)
2117 				opts |= PF_OPT_VERBOSE2;
2118 			opts |= PF_OPT_VERBOSE;
2119 			break;
2120 		case 'x':
2121 			debugopt = pfctl_lookup_option(optarg, debugopt_list);
2122 			if (debugopt == NULL) {
2123 				warnx("Unknown debug level '%s'", optarg);
2124 				usage();
2125 			}
2126 			mode = O_RDWR;
2127 			break;
2128 		case 'z':
2129 			opts |= PF_OPT_CLRRULECTRS;
2130 			mode = O_RDWR;
2131 			break;
2132 		case 'h':
2133 			/* FALLTHROUGH */
2134 		default:
2135 			usage();
2136 			/* NOTREACHED */
2137 		}
2138 	}
2139 
2140 	if (tblcmdopt != NULL) {
2141 		argc -= optind;
2142 		argv += optind;
2143 		ch = *tblcmdopt;
2144 		if (ch == 'l') {
2145 			loadopt |= PFCTL_FLAG_TABLE;
2146 			tblcmdopt = NULL;
2147 		} else
2148 			mode = strchr("acdefkrz", ch) ? O_RDWR : O_RDONLY;
2149 	} else if (argc != optind) {
2150 		warnx("unknown command line argument: %s ...", argv[optind]);
2151 		usage();
2152 		/* NOTREACHED */
2153 	}
2154 	if (loadopt == 0)
2155 		loadopt = ~0;
2156 
2157 	if ((path = calloc(1, MAXPATHLEN)) == NULL)
2158 		errx(1, "pfctl: calloc");
2159 	memset(anchorname, 0, sizeof(anchorname));
2160 	if (anchoropt != NULL) {
2161 		int len = strlen(anchoropt);
2162 
2163 		if (anchoropt[len - 1] == '*') {
2164 			if (len >= 2 && anchoropt[len - 2] == '/')
2165 				anchoropt[len - 2] = '\0';
2166 			else
2167 				anchoropt[len - 1] = '\0';
2168 			opts |= PF_OPT_RECURSE;
2169 		}
2170 		if (strlcpy(anchorname, anchoropt,
2171 		    sizeof(anchorname)) >= sizeof(anchorname))
2172 			errx(1, "anchor name '%s' too long",
2173 			    anchoropt);
2174 		loadopt &= PFCTL_FLAG_FILTER|PFCTL_FLAG_NAT|PFCTL_FLAG_TABLE;
2175 	}
2176 
2177 	if ((opts & PF_OPT_NOACTION) == 0) {
2178 		dev = open(pf_device, mode);
2179 		if (dev == -1)
2180 			err(1, "%s", pf_device);
2181 		altqsupport = pfctl_test_altqsupport(dev, opts);
2182 	} else {
2183 		dev = open(pf_device, O_RDONLY);
2184 		if (dev >= 0)
2185 			opts |= PF_OPT_DUMMYACTION;
2186 		/* turn off options */
2187 		opts &= ~ (PF_OPT_DISABLE | PF_OPT_ENABLE);
2188 		clearopt = showopt = debugopt = NULL;
2189 		altqsupport = 1;
2190 	}
2191 
2192 	if (opts & PF_OPT_DISABLE)
2193 		if (pfctl_disable(dev, opts))
2194 			error = 1;
2195 
2196 	if (showopt != NULL) {
2197 		switch (*showopt) {
2198 		case 'A':
2199 			pfctl_show_anchors(dev, opts, anchorname);
2200 			break;
2201 		case 'r':
2202 			pfctl_load_fingerprints(dev, opts);
2203 			pfctl_show_rules(dev, path, opts, PFCTL_SHOW_RULES,
2204 			    anchorname, 0);
2205 			break;
2206 		case 'l':
2207 			pfctl_load_fingerprints(dev, opts);
2208 			pfctl_show_rules(dev, path, opts, PFCTL_SHOW_LABELS,
2209 			    anchorname, 0);
2210 			break;
2211 		case 'n':
2212 			pfctl_load_fingerprints(dev, opts);
2213 			pfctl_show_nat(dev, opts, anchorname);
2214 			break;
2215 		case 'q':
2216 			pfctl_show_altq(dev, ifaceopt, opts,
2217 			    opts & PF_OPT_VERBOSE2);
2218 			break;
2219 		case 's':
2220 			pfctl_show_states(dev, ifaceopt, opts);
2221 			break;
2222 		case 'S':
2223 			pfctl_show_src_nodes(dev, opts);
2224 			break;
2225 		case 'i':
2226 			pfctl_show_status(dev, opts);
2227 			break;
2228 		case 't':
2229 			pfctl_show_timeouts(dev, opts);
2230 			break;
2231 		case 'm':
2232 			pfctl_show_limits(dev, opts);
2233 			break;
2234 		case 'a':
2235 			opts |= PF_OPT_SHOWALL;
2236 			pfctl_load_fingerprints(dev, opts);
2237 
2238 			pfctl_show_nat(dev, opts, anchorname);
2239 			pfctl_show_rules(dev, path, opts, 0, anchorname, 0);
2240 			pfctl_show_altq(dev, ifaceopt, opts, 0);
2241 			pfctl_show_states(dev, ifaceopt, opts);
2242 			pfctl_show_src_nodes(dev, opts);
2243 			pfctl_show_status(dev, opts);
2244 			pfctl_show_rules(dev, path, opts, 1, anchorname, 0);
2245 			pfctl_show_timeouts(dev, opts);
2246 			pfctl_show_limits(dev, opts);
2247 			pfctl_show_tables(anchorname, opts);
2248 			pfctl_show_fingerprints(opts);
2249 			break;
2250 		case 'T':
2251 			pfctl_show_tables(anchorname, opts);
2252 			break;
2253 		case 'o':
2254 			pfctl_load_fingerprints(dev, opts);
2255 			pfctl_show_fingerprints(opts);
2256 			break;
2257 		case 'I':
2258 			pfctl_show_ifaces(ifaceopt, opts);
2259 			break;
2260 		}
2261 	}
2262 
2263 	if ((opts & PF_OPT_CLRRULECTRS) && showopt == NULL)
2264 		pfctl_show_rules(dev, path, opts, PFCTL_SHOW_NOTHING,
2265 		    anchorname, 0);
2266 
2267 	if (clearopt != NULL) {
2268 		if (anchorname[0] == '_' || strstr(anchorname, "/_") != NULL)
2269 			errx(1, "anchor names beginning with '_' cannot "
2270 			    "be modified from the command line");
2271 
2272 		switch (*clearopt) {
2273 		case 'r':
2274 			pfctl_clear_rules(dev, opts, anchorname);
2275 			break;
2276 		case 'n':
2277 			pfctl_clear_nat(dev, opts, anchorname);
2278 			break;
2279 		case 'q':
2280 			pfctl_clear_altq(dev, opts);
2281 			break;
2282 		case 's':
2283 			pfctl_clear_states(dev, ifaceopt, opts);
2284 			break;
2285 		case 'S':
2286 			pfctl_clear_src_nodes(dev, opts);
2287 			break;
2288 		case 'i':
2289 			pfctl_clear_stats(dev, opts);
2290 			break;
2291 		case 'a':
2292 			pfctl_clear_rules(dev, opts, anchorname);
2293 			pfctl_clear_nat(dev, opts, anchorname);
2294 			pfctl_clear_tables(anchorname, opts);
2295 			if (!*anchorname) {
2296 				pfctl_clear_altq(dev, opts);
2297 				pfctl_clear_states(dev, ifaceopt, opts);
2298 				pfctl_clear_src_nodes(dev, opts);
2299 				pfctl_clear_stats(dev, opts);
2300 				pfctl_clear_fingerprints(dev, opts);
2301 				pfctl_clear_interface_flags(dev, opts);
2302 			}
2303 			break;
2304 		case 'o':
2305 			pfctl_clear_fingerprints(dev, opts);
2306 			break;
2307 		case 'T':
2308 			pfctl_clear_tables(anchorname, opts);
2309 			break;
2310 		}
2311 	}
2312 	if (state_killers) {
2313 		if (!strcmp(state_kill[0], "label"))
2314 			pfctl_label_kill_states(dev, ifaceopt, opts);
2315 		else if (!strcmp(state_kill[0], "id"))
2316 			pfctl_id_kill_states(dev, ifaceopt, opts);
2317 		else
2318 			pfctl_net_kill_states(dev, ifaceopt, opts);
2319 	}
2320 
2321 	if (src_node_killers)
2322 		pfctl_kill_src_nodes(dev, ifaceopt, opts);
2323 
2324 	if (tblcmdopt != NULL) {
2325 		error = pfctl_command_tables(argc, argv, tableopt,
2326 		    tblcmdopt, rulesopt, anchorname, opts);
2327 		rulesopt = NULL;
2328 	}
2329 	if (optiopt != NULL) {
2330 		switch (*optiopt) {
2331 		case 'n':
2332 			optimize = 0;
2333 			break;
2334 		case 'b':
2335 			optimize |= PF_OPTIMIZE_BASIC;
2336 			break;
2337 		case 'o':
2338 		case 'p':
2339 			optimize |= PF_OPTIMIZE_PROFILE;
2340 			break;
2341 		}
2342 	}
2343 
2344 	if ((rulesopt != NULL) && (loadopt & PFCTL_FLAG_OPTION) &&
2345 	    !anchorname[0])
2346 		if (pfctl_clear_interface_flags(dev, opts | PF_OPT_QUIET))
2347 			error = 1;
2348 
2349 	if (rulesopt != NULL && !(opts & (PF_OPT_MERGE|PF_OPT_NOACTION)) &&
2350 	    !anchorname[0] && (loadopt & PFCTL_FLAG_OPTION))
2351 		if (pfctl_file_fingerprints(dev, opts, PF_OSFP_FILE))
2352 			error = 1;
2353 
2354 	if (rulesopt != NULL) {
2355 		if (anchorname[0] == '_' || strstr(anchorname, "/_") != NULL)
2356 			errx(1, "anchor names beginning with '_' cannot "
2357 			    "be modified from the command line");
2358 		if (pfctl_rules(dev, rulesopt, opts, optimize,
2359 		    anchorname, NULL))
2360 			error = 1;
2361 		else if (!(opts & PF_OPT_NOACTION) &&
2362 		    (loadopt & PFCTL_FLAG_TABLE))
2363 			warn_namespace_collision(NULL);
2364 	}
2365 
2366 	if (opts & PF_OPT_ENABLE)
2367 		if (pfctl_enable(dev, opts))
2368 			error = 1;
2369 
2370 	if (debugopt != NULL) {
2371 		switch (*debugopt) {
2372 		case 'n':
2373 			pfctl_debug(dev, PF_DEBUG_NONE, opts);
2374 			break;
2375 		case 'u':
2376 			pfctl_debug(dev, PF_DEBUG_URGENT, opts);
2377 			break;
2378 		case 'm':
2379 			pfctl_debug(dev, PF_DEBUG_MISC, opts);
2380 			break;
2381 		case 'l':
2382 			pfctl_debug(dev, PF_DEBUG_NOISY, opts);
2383 			break;
2384 		}
2385 	}
2386 
2387 	exit(error);
2388 }
2389