xref: /openbsd-src/sbin/pfctl/pfctl.c (revision 2b0358df1d88d06ef4139321dd05bd5e05d91eaf)
1 /*	$OpenBSD: pfctl.c,v 1.281 2009/04/06 12:05:55 henning 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 }
1550 
1551 int
1552 pfctl_load_options(struct pfctl *pf)
1553 {
1554 	int i, error = 0;
1555 
1556 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1557 		return (0);
1558 
1559 	/* load limits */
1560 	for (i = 0; i < PF_LIMIT_MAX; i++) {
1561 		if ((pf->opts & PF_OPT_MERGE) && !pf->limit_set[i])
1562 			continue;
1563 		if (pfctl_load_limit(pf, i, pf->limit[i]))
1564 			error = 1;
1565 	}
1566 
1567 	/*
1568 	 * If we've set the limit, but haven't explicitly set adaptive
1569 	 * timeouts, do it now with a start of 60% and end of 120%.
1570 	 */
1571 	if (pf->limit_set[PF_LIMIT_STATES] &&
1572 	    !pf->timeout_set[PFTM_ADAPTIVE_START] &&
1573 	    !pf->timeout_set[PFTM_ADAPTIVE_END]) {
1574 		pf->timeout[PFTM_ADAPTIVE_START] =
1575 			(pf->limit[PF_LIMIT_STATES] / 10) * 6;
1576 		pf->timeout_set[PFTM_ADAPTIVE_START] = 1;
1577 		pf->timeout[PFTM_ADAPTIVE_END] =
1578 			(pf->limit[PF_LIMIT_STATES] / 10) * 12;
1579 		pf->timeout_set[PFTM_ADAPTIVE_END] = 1;
1580 	}
1581 
1582 	/* load timeouts */
1583 	for (i = 0; i < PFTM_MAX; i++) {
1584 		if ((pf->opts & PF_OPT_MERGE) && !pf->timeout_set[i])
1585 			continue;
1586 		if (pfctl_load_timeout(pf, i, pf->timeout[i]))
1587 			error = 1;
1588 	}
1589 
1590 	/* load debug */
1591 	if (!(pf->opts & PF_OPT_MERGE) || pf->debug_set)
1592 		if (pfctl_load_debug(pf, pf->debug))
1593 			error = 1;
1594 
1595 	/* load logif */
1596 	if (!(pf->opts & PF_OPT_MERGE) || pf->ifname_set)
1597 		if (pfctl_load_logif(pf, pf->ifname))
1598 			error = 1;
1599 
1600 	/* load hostid */
1601 	if (!(pf->opts & PF_OPT_MERGE) || pf->hostid_set)
1602 		if (pfctl_load_hostid(pf, pf->hostid))
1603 			error = 1;
1604 
1605 	/* load reassembly settings */
1606 	if (!(pf->opts & PF_OPT_MERGE) || pf->reass_set)
1607 		if (pfctl_load_reassembly(pf, pf->reassemble))
1608 			error = 1;
1609 
1610 	return (error);
1611 }
1612 
1613 int
1614 pfctl_set_limit(struct pfctl *pf, const char *opt, unsigned int limit)
1615 {
1616 	int i;
1617 
1618 
1619 	for (i = 0; pf_limits[i].name; i++) {
1620 		if (strcasecmp(opt, pf_limits[i].name) == 0) {
1621 			pf->limit[pf_limits[i].index] = limit;
1622 			pf->limit_set[pf_limits[i].index] = 1;
1623 			break;
1624 		}
1625 	}
1626 	if (pf_limits[i].name == NULL) {
1627 		warnx("Bad pool name.");
1628 		return (1);
1629 	}
1630 
1631 	if (pf->opts & PF_OPT_VERBOSE)
1632 		printf("set limit %s %d\n", opt, limit);
1633 
1634 	return (0);
1635 }
1636 
1637 int
1638 pfctl_load_limit(struct pfctl *pf, unsigned int index, unsigned int limit)
1639 {
1640 	struct pfioc_limit pl;
1641 
1642 	memset(&pl, 0, sizeof(pl));
1643 	pl.index = index;
1644 	pl.limit = limit;
1645 	if (ioctl(pf->dev, DIOCSETLIMIT, &pl)) {
1646 		if (errno == EBUSY)
1647 			warnx("Current pool size exceeds requested hard limit");
1648 		else
1649 			warnx("DIOCSETLIMIT");
1650 		return (1);
1651 	}
1652 	return (0);
1653 }
1654 
1655 int
1656 pfctl_set_timeout(struct pfctl *pf, const char *opt, int seconds, int quiet)
1657 {
1658 	int i;
1659 
1660 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1661 		return (0);
1662 
1663 	for (i = 0; pf_timeouts[i].name; i++) {
1664 		if (strcasecmp(opt, pf_timeouts[i].name) == 0) {
1665 			pf->timeout[pf_timeouts[i].timeout] = seconds;
1666 			pf->timeout_set[pf_timeouts[i].timeout] = 1;
1667 			break;
1668 		}
1669 	}
1670 
1671 	if (pf_timeouts[i].name == NULL) {
1672 		warnx("Bad timeout name.");
1673 		return (1);
1674 	}
1675 
1676 
1677 	if (pf->opts & PF_OPT_VERBOSE && ! quiet)
1678 		printf("set timeout %s %d\n", opt, seconds);
1679 
1680 	return (0);
1681 }
1682 
1683 int
1684 pfctl_load_timeout(struct pfctl *pf, unsigned int timeout, unsigned int seconds)
1685 {
1686 	struct pfioc_tm pt;
1687 
1688 	memset(&pt, 0, sizeof(pt));
1689 	pt.timeout = timeout;
1690 	pt.seconds = seconds;
1691 	if (ioctl(pf->dev, DIOCSETTIMEOUT, &pt)) {
1692 		warnx("DIOCSETTIMEOUT");
1693 		return (1);
1694 	}
1695 	return (0);
1696 }
1697 
1698 int
1699 pfctl_set_reassembly(struct pfctl *pf, int on, int nodf)
1700 {
1701 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1702 		return (0);
1703 
1704 	pf->reass_set = 1;
1705 	if (on) {
1706 		pf->reassemble = PF_REASS_ENABLED;
1707 		if (nodf)
1708 			pf->reassemble &= PF_REASS_NODF;
1709 	}
1710 
1711 	if (pf->opts & PF_OPT_VERBOSE)
1712 		printf("set reassemble %s %s\n", on ? "yes" : "no",
1713 		    nodf ? "no-df" : "");
1714 
1715 	return (0);
1716 }
1717 
1718 int
1719 pfctl_set_optimization(struct pfctl *pf, const char *opt)
1720 {
1721 	const struct pf_hint *hint;
1722 	int i, r;
1723 
1724 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1725 		return (0);
1726 
1727 	for (i = 0; pf_hints[i].name; i++)
1728 		if (strcasecmp(opt, pf_hints[i].name) == 0)
1729 			break;
1730 
1731 	hint = pf_hints[i].hint;
1732 	if (hint == NULL) {
1733 		warnx("invalid state timeouts optimization");
1734 		return (1);
1735 	}
1736 
1737 	for (i = 0; hint[i].name; i++)
1738 		if ((r = pfctl_set_timeout(pf, hint[i].name,
1739 		    hint[i].timeout, 1)))
1740 			return (r);
1741 
1742 	if (pf->opts & PF_OPT_VERBOSE)
1743 		printf("set optimization %s\n", opt);
1744 
1745 	return (0);
1746 }
1747 
1748 int
1749 pfctl_set_logif(struct pfctl *pf, char *ifname)
1750 {
1751 
1752 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1753 		return (0);
1754 
1755 	if (!strcmp(ifname, "none")) {
1756 		free(pf->ifname);
1757 		pf->ifname = NULL;
1758 	} else {
1759 		pf->ifname = strdup(ifname);
1760 		if (!pf->ifname)
1761 			errx(1, "pfctl_set_logif: strdup");
1762 	}
1763 	pf->ifname_set = 1;
1764 
1765 	if (pf->opts & PF_OPT_VERBOSE)
1766 		printf("set loginterface %s\n", ifname);
1767 
1768 	return (0);
1769 }
1770 
1771 int
1772 pfctl_load_logif(struct pfctl *pf, char *ifname)
1773 {
1774 	struct pfioc_if pi;
1775 
1776 	memset(&pi, 0, sizeof(pi));
1777 	if (ifname && strlcpy(pi.ifname, ifname,
1778 	    sizeof(pi.ifname)) >= sizeof(pi.ifname)) {
1779 		warnx("pfctl_load_logif: strlcpy");
1780 		return (1);
1781 	}
1782 	if (ioctl(pf->dev, DIOCSETSTATUSIF, &pi)) {
1783 		warnx("DIOCSETSTATUSIF");
1784 		return (1);
1785 	}
1786 	return (0);
1787 }
1788 
1789 int
1790 pfctl_set_hostid(struct pfctl *pf, u_int32_t hostid)
1791 {
1792 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1793 		return (0);
1794 
1795 	HTONL(hostid);
1796 
1797 	pf->hostid = hostid;
1798 	pf->hostid_set = 1;
1799 
1800 	if (pf->opts & PF_OPT_VERBOSE)
1801 		printf("set hostid 0x%08x\n", ntohl(hostid));
1802 
1803 	return (0);
1804 }
1805 
1806 int
1807 pfctl_load_hostid(struct pfctl *pf, u_int32_t hostid)
1808 {
1809 	if (ioctl(dev, DIOCSETHOSTID, &hostid)) {
1810 		warnx("DIOCSETHOSTID");
1811 		return (1);
1812 	}
1813 	return (0);
1814 }
1815 
1816 int
1817 pfctl_load_reassembly(struct pfctl *pf, u_int32_t reassembly)
1818 {
1819 	if (ioctl(dev, DIOCSETREASS, &reassembly)) {
1820 		warnx("DIOCSETREASS");
1821 		return (1);
1822 	}
1823 	return (0);
1824 }
1825 
1826 int
1827 pfctl_set_debug(struct pfctl *pf, char *d)
1828 {
1829 	u_int32_t	level;
1830 
1831 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1832 		return (0);
1833 
1834 	if (!strcmp(d, "none"))
1835 		pf->debug = PF_DEBUG_NONE;
1836 	else if (!strcmp(d, "urgent"))
1837 		pf->debug = PF_DEBUG_URGENT;
1838 	else if (!strcmp(d, "misc"))
1839 		pf->debug = PF_DEBUG_MISC;
1840 	else if (!strcmp(d, "loud"))
1841 		pf->debug = PF_DEBUG_NOISY;
1842 	else {
1843 		warnx("unknown debug level \"%s\"", d);
1844 		return (-1);
1845 	}
1846 
1847 	pf->debug_set = 1;
1848 
1849 	if ((pf->opts & PF_OPT_NOACTION) == 0)
1850 		if (ioctl(dev, DIOCSETDEBUG, &level))
1851 			err(1, "DIOCSETDEBUG");
1852 
1853 	if (pf->opts & PF_OPT_VERBOSE)
1854 		printf("set debug %s\n", d);
1855 
1856 	return (0);
1857 }
1858 
1859 int
1860 pfctl_load_debug(struct pfctl *pf, unsigned int level)
1861 {
1862 	if (ioctl(pf->dev, DIOCSETDEBUG, &level)) {
1863 		warnx("DIOCSETDEBUG");
1864 		return (1);
1865 	}
1866 	return (0);
1867 }
1868 
1869 int
1870 pfctl_set_interface_flags(struct pfctl *pf, char *ifname, int flags, int how)
1871 {
1872 	struct pfioc_iface	pi;
1873 
1874 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
1875 		return (0);
1876 
1877 	bzero(&pi, sizeof(pi));
1878 
1879 	pi.pfiio_flags = flags;
1880 
1881 	if (strlcpy(pi.pfiio_name, ifname, sizeof(pi.pfiio_name)) >=
1882 	    sizeof(pi.pfiio_name))
1883 		errx(1, "pfctl_set_interface_flags: strlcpy");
1884 
1885 	if ((pf->opts & PF_OPT_NOACTION) == 0) {
1886 		if (how == 0) {
1887 			if (ioctl(pf->dev, DIOCCLRIFFLAG, &pi))
1888 				err(1, "DIOCCLRIFFLAG");
1889 		} else {
1890 			if (ioctl(pf->dev, DIOCSETIFFLAG, &pi))
1891 				err(1, "DIOCSETIFFLAG");
1892 		}
1893 	}
1894 	return (0);
1895 }
1896 
1897 void
1898 pfctl_debug(int dev, u_int32_t level, int opts)
1899 {
1900 	if (ioctl(dev, DIOCSETDEBUG, &level))
1901 		err(1, "DIOCSETDEBUG");
1902 	if ((opts & PF_OPT_QUIET) == 0) {
1903 		fprintf(stderr, "debug level set to '");
1904 		switch (level) {
1905 		case PF_DEBUG_NONE:
1906 			fprintf(stderr, "none");
1907 			break;
1908 		case PF_DEBUG_URGENT:
1909 			fprintf(stderr, "urgent");
1910 			break;
1911 		case PF_DEBUG_MISC:
1912 			fprintf(stderr, "misc");
1913 			break;
1914 		case PF_DEBUG_NOISY:
1915 			fprintf(stderr, "loud");
1916 			break;
1917 		default:
1918 			fprintf(stderr, "<invalid>");
1919 			break;
1920 		}
1921 		fprintf(stderr, "'\n");
1922 	}
1923 }
1924 
1925 int
1926 pfctl_test_altqsupport(int dev, int opts)
1927 {
1928 	struct pfioc_altq pa;
1929 
1930 	if (ioctl(dev, DIOCGETALTQS, &pa)) {
1931 		if (errno == ENODEV) {
1932 			if (!(opts & PF_OPT_QUIET))
1933 				fprintf(stderr, "No ALTQ support in kernel\n"
1934 				    "ALTQ related functions disabled\n");
1935 			return (0);
1936 		} else
1937 			err(1, "DIOCGETALTQS");
1938 	}
1939 	return (1);
1940 }
1941 
1942 int
1943 pfctl_show_anchors(int dev, int opts, char *anchorname)
1944 {
1945 	struct pfioc_ruleset	 pr;
1946 	u_int32_t		 mnr, nr;
1947 
1948 	memset(&pr, 0, sizeof(pr));
1949 	memcpy(pr.path, anchorname, sizeof(pr.path));
1950 	if (ioctl(dev, DIOCGETRULESETS, &pr)) {
1951 		if (errno == EINVAL)
1952 			fprintf(stderr, "Anchor '%s' not found.\n",
1953 			    anchorname);
1954 		else
1955 			err(1, "DIOCGETRULESETS");
1956 		return (-1);
1957 	}
1958 	mnr = pr.nr;
1959 	for (nr = 0; nr < mnr; ++nr) {
1960 		char sub[MAXPATHLEN];
1961 
1962 		pr.nr = nr;
1963 		if (ioctl(dev, DIOCGETRULESET, &pr))
1964 			err(1, "DIOCGETRULESET");
1965 		if (!strcmp(pr.name, PF_RESERVED_ANCHOR))
1966 			continue;
1967 		sub[0] = 0;
1968 		if (pr.path[0]) {
1969 			strlcat(sub, pr.path, sizeof(sub));
1970 			strlcat(sub, "/", sizeof(sub));
1971 		}
1972 		strlcat(sub, pr.name, sizeof(sub));
1973 		if (sub[0] != '_' || (opts & PF_OPT_VERBOSE))
1974 			printf("  %s\n", sub);
1975 		if ((opts & PF_OPT_VERBOSE) && pfctl_show_anchors(dev, opts, sub))
1976 			return (-1);
1977 	}
1978 	return (0);
1979 }
1980 
1981 const char *
1982 pfctl_lookup_option(char *cmd, const char **list)
1983 {
1984 	if (cmd != NULL && *cmd)
1985 		for (; *list; list++)
1986 			if (!strncmp(cmd, *list, strlen(cmd)))
1987 				return (*list);
1988 	return (NULL);
1989 }
1990 
1991 int
1992 main(int argc, char *argv[])
1993 {
1994 	int	 error = 0;
1995 	int	 ch;
1996 	int	 mode = O_RDONLY;
1997 	int	 opts = 0;
1998 	int	 optimize = PF_OPTIMIZE_BASIC;
1999 	char	 anchorname[MAXPATHLEN];
2000 	char	*path;
2001 
2002 	if (argc < 2)
2003 		usage();
2004 
2005 	while ((ch = getopt(argc, argv,
2006 	    "a:AdD:eqf:F:ghi:k:K:mnNOo:p:rRs:t:T:vx:z")) != -1) {
2007 		switch (ch) {
2008 		case 'a':
2009 			anchoropt = optarg;
2010 			break;
2011 		case 'd':
2012 			opts |= PF_OPT_DISABLE;
2013 			mode = O_RDWR;
2014 			break;
2015 		case 'D':
2016 			if (pfctl_cmdline_symset(optarg) < 0)
2017 				warnx("could not parse macro definition %s",
2018 				    optarg);
2019 			break;
2020 		case 'e':
2021 			opts |= PF_OPT_ENABLE;
2022 			mode = O_RDWR;
2023 			break;
2024 		case 'q':
2025 			opts |= PF_OPT_QUIET;
2026 			break;
2027 		case 'F':
2028 			clearopt = pfctl_lookup_option(optarg, clearopt_list);
2029 			if (clearopt == NULL) {
2030 				warnx("Unknown flush modifier '%s'", optarg);
2031 				usage();
2032 			}
2033 			mode = O_RDWR;
2034 			break;
2035 		case 'i':
2036 			ifaceopt = optarg;
2037 			break;
2038 		case 'k':
2039 			if (state_killers >= 2) {
2040 				warnx("can only specify -k twice");
2041 				usage();
2042 				/* NOTREACHED */
2043 			}
2044 			state_kill[state_killers++] = optarg;
2045 			mode = O_RDWR;
2046 			break;
2047 		case 'K':
2048 			if (src_node_killers >= 2) {
2049 				warnx("can only specify -K twice");
2050 				usage();
2051 				/* NOTREACHED */
2052 			}
2053 			src_node_kill[src_node_killers++] = optarg;
2054 			mode = O_RDWR;
2055 			break;
2056 		case 'm':
2057 			opts |= PF_OPT_MERGE;
2058 			break;
2059 		case 'n':
2060 			opts |= PF_OPT_NOACTION;
2061 			break;
2062 		case 'N':
2063 			loadopt |= PFCTL_FLAG_NAT;
2064 			break;
2065 		case 'r':
2066 			opts |= PF_OPT_USEDNS;
2067 			break;
2068 		case 'f':
2069 			rulesopt = optarg;
2070 			mode = O_RDWR;
2071 			break;
2072 		case 'g':
2073 			opts |= PF_OPT_DEBUG;
2074 			break;
2075 		case 'A':
2076 			loadopt |= PFCTL_FLAG_ALTQ;
2077 			break;
2078 		case 'R':
2079 			loadopt |= PFCTL_FLAG_FILTER;
2080 			break;
2081 		case 'o':
2082 			optiopt = pfctl_lookup_option(optarg, optiopt_list);
2083 			if (optiopt == NULL) {
2084 				warnx("Unknown optimization '%s'", optarg);
2085 				usage();
2086 			}
2087 			opts |= PF_OPT_OPTIMIZE;
2088 			break;
2089 		case 'O':
2090 			loadopt |= PFCTL_FLAG_OPTION;
2091 			break;
2092 		case 'p':
2093 			pf_device = optarg;
2094 			break;
2095 		case 's':
2096 			showopt = pfctl_lookup_option(optarg, showopt_list);
2097 			if (showopt == NULL) {
2098 				warnx("Unknown show modifier '%s'", optarg);
2099 				usage();
2100 			}
2101 			break;
2102 		case 't':
2103 			tableopt = optarg;
2104 			break;
2105 		case 'T':
2106 			tblcmdopt = pfctl_lookup_option(optarg, tblcmdopt_list);
2107 			if (tblcmdopt == NULL) {
2108 				warnx("Unknown table command '%s'", optarg);
2109 				usage();
2110 			}
2111 			break;
2112 		case 'v':
2113 			if (opts & PF_OPT_VERBOSE)
2114 				opts |= PF_OPT_VERBOSE2;
2115 			opts |= PF_OPT_VERBOSE;
2116 			break;
2117 		case 'x':
2118 			debugopt = pfctl_lookup_option(optarg, debugopt_list);
2119 			if (debugopt == NULL) {
2120 				warnx("Unknown debug level '%s'", optarg);
2121 				usage();
2122 			}
2123 			mode = O_RDWR;
2124 			break;
2125 		case 'z':
2126 			opts |= PF_OPT_CLRRULECTRS;
2127 			mode = O_RDWR;
2128 			break;
2129 		case 'h':
2130 			/* FALLTHROUGH */
2131 		default:
2132 			usage();
2133 			/* NOTREACHED */
2134 		}
2135 	}
2136 
2137 	if (tblcmdopt != NULL) {
2138 		argc -= optind;
2139 		argv += optind;
2140 		ch = *tblcmdopt;
2141 		if (ch == 'l') {
2142 			loadopt |= PFCTL_FLAG_TABLE;
2143 			tblcmdopt = NULL;
2144 		} else
2145 			mode = strchr("acdefkrz", ch) ? O_RDWR : O_RDONLY;
2146 	} else if (argc != optind) {
2147 		warnx("unknown command line argument: %s ...", argv[optind]);
2148 		usage();
2149 		/* NOTREACHED */
2150 	}
2151 	if (loadopt == 0)
2152 		loadopt = ~0;
2153 
2154 	if ((path = calloc(1, MAXPATHLEN)) == NULL)
2155 		errx(1, "pfctl: calloc");
2156 	memset(anchorname, 0, sizeof(anchorname));
2157 	if (anchoropt != NULL) {
2158 		int len = strlen(anchoropt);
2159 
2160 		if (anchoropt[len - 1] == '*') {
2161 			if (len >= 2 && anchoropt[len - 2] == '/')
2162 				anchoropt[len - 2] = '\0';
2163 			else
2164 				anchoropt[len - 1] = '\0';
2165 			opts |= PF_OPT_RECURSE;
2166 		}
2167 		if (strlcpy(anchorname, anchoropt,
2168 		    sizeof(anchorname)) >= sizeof(anchorname))
2169 			errx(1, "anchor name '%s' too long",
2170 			    anchoropt);
2171 		loadopt &= PFCTL_FLAG_FILTER|PFCTL_FLAG_NAT|PFCTL_FLAG_TABLE;
2172 	}
2173 
2174 	if ((opts & PF_OPT_NOACTION) == 0) {
2175 		dev = open(pf_device, mode);
2176 		if (dev == -1)
2177 			err(1, "%s", pf_device);
2178 		altqsupport = pfctl_test_altqsupport(dev, opts);
2179 	} else {
2180 		dev = open(pf_device, O_RDONLY);
2181 		if (dev >= 0)
2182 			opts |= PF_OPT_DUMMYACTION;
2183 		/* turn off options */
2184 		opts &= ~ (PF_OPT_DISABLE | PF_OPT_ENABLE);
2185 		clearopt = showopt = debugopt = NULL;
2186 		altqsupport = 1;
2187 	}
2188 
2189 	if (opts & PF_OPT_DISABLE)
2190 		if (pfctl_disable(dev, opts))
2191 			error = 1;
2192 
2193 	if (showopt != NULL) {
2194 		switch (*showopt) {
2195 		case 'A':
2196 			pfctl_show_anchors(dev, opts, anchorname);
2197 			break;
2198 		case 'r':
2199 			pfctl_load_fingerprints(dev, opts);
2200 			pfctl_show_rules(dev, path, opts, PFCTL_SHOW_RULES,
2201 			    anchorname, 0);
2202 			break;
2203 		case 'l':
2204 			pfctl_load_fingerprints(dev, opts);
2205 			pfctl_show_rules(dev, path, opts, PFCTL_SHOW_LABELS,
2206 			    anchorname, 0);
2207 			break;
2208 		case 'n':
2209 			pfctl_load_fingerprints(dev, opts);
2210 			pfctl_show_nat(dev, opts, anchorname);
2211 			break;
2212 		case 'q':
2213 			pfctl_show_altq(dev, ifaceopt, opts,
2214 			    opts & PF_OPT_VERBOSE2);
2215 			break;
2216 		case 's':
2217 			pfctl_show_states(dev, ifaceopt, opts);
2218 			break;
2219 		case 'S':
2220 			pfctl_show_src_nodes(dev, opts);
2221 			break;
2222 		case 'i':
2223 			pfctl_show_status(dev, opts);
2224 			break;
2225 		case 't':
2226 			pfctl_show_timeouts(dev, opts);
2227 			break;
2228 		case 'm':
2229 			pfctl_show_limits(dev, opts);
2230 			break;
2231 		case 'a':
2232 			opts |= PF_OPT_SHOWALL;
2233 			pfctl_load_fingerprints(dev, opts);
2234 
2235 			pfctl_show_nat(dev, opts, anchorname);
2236 			pfctl_show_rules(dev, path, opts, 0, anchorname, 0);
2237 			pfctl_show_altq(dev, ifaceopt, opts, 0);
2238 			pfctl_show_states(dev, ifaceopt, opts);
2239 			pfctl_show_src_nodes(dev, opts);
2240 			pfctl_show_status(dev, opts);
2241 			pfctl_show_rules(dev, path, opts, 1, anchorname, 0);
2242 			pfctl_show_timeouts(dev, opts);
2243 			pfctl_show_limits(dev, opts);
2244 			pfctl_show_tables(anchorname, opts);
2245 			pfctl_show_fingerprints(opts);
2246 			break;
2247 		case 'T':
2248 			pfctl_show_tables(anchorname, opts);
2249 			break;
2250 		case 'o':
2251 			pfctl_load_fingerprints(dev, opts);
2252 			pfctl_show_fingerprints(opts);
2253 			break;
2254 		case 'I':
2255 			pfctl_show_ifaces(ifaceopt, opts);
2256 			break;
2257 		}
2258 	}
2259 
2260 	if ((opts & PF_OPT_CLRRULECTRS) && showopt == NULL)
2261 		pfctl_show_rules(dev, path, opts, PFCTL_SHOW_NOTHING,
2262 		    anchorname, 0);
2263 
2264 	if (clearopt != NULL) {
2265 		if (anchorname[0] == '_' || strstr(anchorname, "/_") != NULL)
2266 			errx(1, "anchor names beginning with '_' cannot "
2267 			    "be modified from the command line");
2268 
2269 		switch (*clearopt) {
2270 		case 'r':
2271 			pfctl_clear_rules(dev, opts, anchorname);
2272 			break;
2273 		case 'n':
2274 			pfctl_clear_nat(dev, opts, anchorname);
2275 			break;
2276 		case 'q':
2277 			pfctl_clear_altq(dev, opts);
2278 			break;
2279 		case 's':
2280 			pfctl_clear_states(dev, ifaceopt, opts);
2281 			break;
2282 		case 'S':
2283 			pfctl_clear_src_nodes(dev, opts);
2284 			break;
2285 		case 'i':
2286 			pfctl_clear_stats(dev, opts);
2287 			break;
2288 		case 'a':
2289 			pfctl_clear_rules(dev, opts, anchorname);
2290 			pfctl_clear_nat(dev, opts, anchorname);
2291 			pfctl_clear_tables(anchorname, opts);
2292 			if (!*anchorname) {
2293 				pfctl_clear_altq(dev, opts);
2294 				pfctl_clear_states(dev, ifaceopt, opts);
2295 				pfctl_clear_src_nodes(dev, opts);
2296 				pfctl_clear_stats(dev, opts);
2297 				pfctl_clear_fingerprints(dev, opts);
2298 				pfctl_clear_interface_flags(dev, opts);
2299 			}
2300 			break;
2301 		case 'o':
2302 			pfctl_clear_fingerprints(dev, opts);
2303 			break;
2304 		case 'T':
2305 			pfctl_clear_tables(anchorname, opts);
2306 			break;
2307 		}
2308 	}
2309 	if (state_killers) {
2310 		if (!strcmp(state_kill[0], "label"))
2311 			pfctl_label_kill_states(dev, ifaceopt, opts);
2312 		else if (!strcmp(state_kill[0], "id"))
2313 			pfctl_id_kill_states(dev, ifaceopt, opts);
2314 		else
2315 			pfctl_net_kill_states(dev, ifaceopt, opts);
2316 	}
2317 
2318 	if (src_node_killers)
2319 		pfctl_kill_src_nodes(dev, ifaceopt, opts);
2320 
2321 	if (tblcmdopt != NULL) {
2322 		error = pfctl_command_tables(argc, argv, tableopt,
2323 		    tblcmdopt, rulesopt, anchorname, opts);
2324 		rulesopt = NULL;
2325 	}
2326 	if (optiopt != NULL) {
2327 		switch (*optiopt) {
2328 		case 'n':
2329 			optimize = 0;
2330 			break;
2331 		case 'b':
2332 			optimize |= PF_OPTIMIZE_BASIC;
2333 			break;
2334 		case 'o':
2335 		case 'p':
2336 			optimize |= PF_OPTIMIZE_PROFILE;
2337 			break;
2338 		}
2339 	}
2340 
2341 	if ((rulesopt != NULL) && (loadopt & PFCTL_FLAG_OPTION) &&
2342 	    !anchorname[0])
2343 		if (pfctl_clear_interface_flags(dev, opts | PF_OPT_QUIET))
2344 			error = 1;
2345 
2346 	if (rulesopt != NULL && !(opts & (PF_OPT_MERGE|PF_OPT_NOACTION)) &&
2347 	    !anchorname[0] && (loadopt & PFCTL_FLAG_OPTION))
2348 		if (pfctl_file_fingerprints(dev, opts, PF_OSFP_FILE))
2349 			error = 1;
2350 
2351 	if (rulesopt != NULL) {
2352 		if (anchorname[0] == '_' || strstr(anchorname, "/_") != NULL)
2353 			errx(1, "anchor names beginning with '_' cannot "
2354 			    "be modified from the command line");
2355 		if (pfctl_rules(dev, rulesopt, opts, optimize,
2356 		    anchorname, NULL))
2357 			error = 1;
2358 		else if (!(opts & PF_OPT_NOACTION) &&
2359 		    (loadopt & PFCTL_FLAG_TABLE))
2360 			warn_namespace_collision(NULL);
2361 	}
2362 
2363 	if (opts & PF_OPT_ENABLE)
2364 		if (pfctl_enable(dev, opts))
2365 			error = 1;
2366 
2367 	if (debugopt != NULL) {
2368 		switch (*debugopt) {
2369 		case 'n':
2370 			pfctl_debug(dev, PF_DEBUG_NONE, opts);
2371 			break;
2372 		case 'u':
2373 			pfctl_debug(dev, PF_DEBUG_URGENT, opts);
2374 			break;
2375 		case 'm':
2376 			pfctl_debug(dev, PF_DEBUG_MISC, opts);
2377 			break;
2378 		case 'l':
2379 			pfctl_debug(dev, PF_DEBUG_NOISY, opts);
2380 			break;
2381 		}
2382 	}
2383 
2384 	exit(error);
2385 }
2386