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