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