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