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