source: rtems-libbsd/freebsd/contrib/pf/pfctl/pfctl_optimize.c @ d112679

4.11
Last change on this file since d112679 was d112679, checked in by Christian Mauderer <Christian.Mauderer@…>, on 07/06/16 at 07:50:51

pfctl: Add const and move static variables.

Note: This should be upstreamed into BSD.

Make everything constant that can be constant and move static variables
out of their functions.

  • Property mode set to 100644
File size: 48.3 KB
Line 
1#include <machine/rtems-bsd-user-space.h>
2
3/*      $OpenBSD: pfctl_optimize.c,v 1.17 2008/05/06 03:45:21 mpf Exp $ */
4
5/*
6 * Copyright (c) 2004 Mike Frantzen <frantzen@openbsd.org>
7 *
8 * Permission to use, copy, modify, and distribute this software for any
9 * purpose with or without fee is hereby granted, provided that the above
10 * copyright notice and this permission notice appear in all copies.
11 *
12 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 */
20
21#include <sys/cdefs.h>
22__FBSDID("$FreeBSD$");
23
24#include <rtems/bsd/sys/types.h>
25#include <sys/ioctl.h>
26#include <sys/socket.h>
27
28#include <net/if.h>
29#include <net/pfvar.h>
30
31#include <netinet/in.h>
32#include <arpa/inet.h>
33
34#include <assert.h>
35#include <ctype.h>
36#include <err.h>
37#include <errno.h>
38#include <stddef.h>
39#include <stdio.h>
40#include <stdlib.h>
41#include <string.h>
42
43#include "pfctl_parser.h"
44#include "pfctl.h"
45
46/* The size at which a table becomes faster than individual rules */
47#define TABLE_THRESHOLD         6
48
49
50/* #define OPT_DEBUG    1 */
51#ifdef OPT_DEBUG
52# define DEBUG(str, v...) \
53        printf("%s: " str "\n", __FUNCTION__ , ## v)
54#else
55# define DEBUG(str, v...) ((void)0)
56#endif
57
58
59/*
60 * A container that lets us sort a superblock to optimize the skip step jumps
61 */
62struct pf_skip_step {
63        int                             ps_count;       /* number of items */
64        TAILQ_HEAD( , pf_opt_rule)      ps_rules;
65        TAILQ_ENTRY(pf_skip_step)       ps_entry;
66};
67
68
69/*
70 * A superblock is a block of adjacent rules of similar action.  If there
71 * are five PASS rules in a row, they all become members of a superblock.
72 * Once we have a superblock, we are free to re-order any rules within it
73 * in order to improve performance; if a packet is passed, it doesn't matter
74 * who passed it.
75 */
76struct superblock {
77        TAILQ_HEAD( , pf_opt_rule)               sb_rules;
78        TAILQ_ENTRY(superblock)                  sb_entry;
79        struct superblock                       *sb_profiled_block;
80        TAILQ_HEAD(skiplist, pf_skip_step)       sb_skipsteps[PF_SKIP_COUNT];
81};
82TAILQ_HEAD(superblocks, superblock);
83
84
85/*
86 * Description of the PF rule structure.
87 */
88enum {
89    BARRIER,    /* the presence of the field puts the rule in it's own block */
90    BREAK,      /* the field may not differ between rules in a superblock */
91    NOMERGE,    /* the field may not differ between rules when combined */
92    COMBINED,   /* the field may itself be combined with other rules */
93    DC,         /* we just don't care about the field */
94    NEVER};     /* we should never see this field set?!? */
95struct pf_rule_field {
96        const char      *prf_name;
97        int              prf_type;
98        size_t           prf_offset;
99        size_t           prf_size;
100} pf_rule_desc[] = {
101#define PF_RULE_FIELD(field, ty)        \
102    {#field,                            \
103    ty,                                 \
104    offsetof(struct pf_rule, field),    \
105    sizeof(((struct pf_rule *)0)->field)}
106
107
108    /*
109     * The presence of these fields in a rule put the rule in it's own
110     * superblock.  Thus it will not be optimized.  It also prevents the
111     * rule from being re-ordered at all.
112     */
113    PF_RULE_FIELD(label,                BARRIER),
114    PF_RULE_FIELD(prob,                 BARRIER),
115    PF_RULE_FIELD(max_states,           BARRIER),
116    PF_RULE_FIELD(max_src_nodes,        BARRIER),
117    PF_RULE_FIELD(max_src_states,       BARRIER),
118    PF_RULE_FIELD(max_src_conn,         BARRIER),
119    PF_RULE_FIELD(max_src_conn_rate,    BARRIER),
120    PF_RULE_FIELD(anchor,               BARRIER),       /* for now */
121
122    /*
123     * These fields must be the same between all rules in the same superblock.
124     * These rules are allowed to be re-ordered but only among like rules.
125     * For instance we can re-order all 'tag "foo"' rules because they have the
126     * same tag.  But we can not re-order between a 'tag "foo"' and a
127     * 'tag "bar"' since that would change the meaning of the ruleset.
128     */
129    PF_RULE_FIELD(tagname,              BREAK),
130    PF_RULE_FIELD(keep_state,           BREAK),
131    PF_RULE_FIELD(qname,                BREAK),
132    PF_RULE_FIELD(pqname,               BREAK),
133    PF_RULE_FIELD(rt,                   BREAK),
134    PF_RULE_FIELD(allow_opts,           BREAK),
135    PF_RULE_FIELD(rule_flag,            BREAK),
136    PF_RULE_FIELD(action,               BREAK),
137    PF_RULE_FIELD(log,                  BREAK),
138    PF_RULE_FIELD(quick,                BREAK),
139    PF_RULE_FIELD(return_ttl,           BREAK),
140    PF_RULE_FIELD(overload_tblname,     BREAK),
141    PF_RULE_FIELD(flush,                BREAK),
142    PF_RULE_FIELD(rpool,                BREAK),
143    PF_RULE_FIELD(logif,                BREAK),
144
145    /*
146     * Any fields not listed in this structure act as BREAK fields
147     */
148
149
150    /*
151     * These fields must not differ when we merge two rules together but
152     * their difference isn't enough to put the rules in different superblocks.
153     * There are no problems re-ordering any rules with these fields.
154     */
155    PF_RULE_FIELD(af,                   NOMERGE),
156    PF_RULE_FIELD(ifnot,                NOMERGE),
157    PF_RULE_FIELD(ifname,               NOMERGE),       /* hack for IF groups */
158    PF_RULE_FIELD(match_tag_not,        NOMERGE),
159    PF_RULE_FIELD(match_tagname,        NOMERGE),
160    PF_RULE_FIELD(os_fingerprint,       NOMERGE),
161    PF_RULE_FIELD(timeout,              NOMERGE),
162    PF_RULE_FIELD(return_icmp,          NOMERGE),
163    PF_RULE_FIELD(return_icmp6,         NOMERGE),
164    PF_RULE_FIELD(uid,                  NOMERGE),
165    PF_RULE_FIELD(gid,                  NOMERGE),
166    PF_RULE_FIELD(direction,            NOMERGE),
167    PF_RULE_FIELD(proto,                NOMERGE),
168    PF_RULE_FIELD(type,                 NOMERGE),
169    PF_RULE_FIELD(code,                 NOMERGE),
170    PF_RULE_FIELD(flags,                NOMERGE),
171    PF_RULE_FIELD(flagset,              NOMERGE),
172    PF_RULE_FIELD(tos,                  NOMERGE),
173    PF_RULE_FIELD(src.port,             NOMERGE),
174    PF_RULE_FIELD(dst.port,             NOMERGE),
175    PF_RULE_FIELD(src.port_op,          NOMERGE),
176    PF_RULE_FIELD(dst.port_op,          NOMERGE),
177    PF_RULE_FIELD(src.neg,              NOMERGE),
178    PF_RULE_FIELD(dst.neg,              NOMERGE),
179
180    /* These fields can be merged */
181    PF_RULE_FIELD(src.addr,             COMBINED),
182    PF_RULE_FIELD(dst.addr,             COMBINED),
183
184    /* We just don't care about these fields.  They're set by the kernel */
185    PF_RULE_FIELD(skip,                 DC),
186    PF_RULE_FIELD(evaluations,          DC),
187    PF_RULE_FIELD(packets,              DC),
188    PF_RULE_FIELD(bytes,                DC),
189    PF_RULE_FIELD(kif,                  DC),
190    PF_RULE_FIELD(states_cur,           DC),
191    PF_RULE_FIELD(states_tot,           DC),
192    PF_RULE_FIELD(src_nodes,            DC),
193    PF_RULE_FIELD(nr,                   DC),
194    PF_RULE_FIELD(entries,              DC),
195    PF_RULE_FIELD(qid,                  DC),
196    PF_RULE_FIELD(pqid,                 DC),
197    PF_RULE_FIELD(anchor_relative,      DC),
198    PF_RULE_FIELD(anchor_wildcard,      DC),
199    PF_RULE_FIELD(tag,                  DC),
200    PF_RULE_FIELD(match_tag,            DC),
201    PF_RULE_FIELD(overload_tbl,         DC),
202
203    /* These fields should never be set in a PASS/BLOCK rule */
204    PF_RULE_FIELD(natpass,              NEVER),
205    PF_RULE_FIELD(max_mss,              NEVER),
206    PF_RULE_FIELD(min_ttl,              NEVER),
207    PF_RULE_FIELD(set_tos,              NEVER),
208};
209#ifdef __rtems__
210static int pf_opt_create_table_num;
211static int add_opt_table_num = 0;
212#endif /* __rtems__ */
213
214
215
216int     add_opt_table(struct pfctl *, struct pf_opt_tbl **, sa_family_t,
217            struct pf_rule_addr *);
218int     addrs_combineable(struct pf_rule_addr *, struct pf_rule_addr *);
219int     addrs_equal(struct pf_rule_addr *, struct pf_rule_addr *);
220int     block_feedback(struct pfctl *, struct superblock *);
221int     combine_rules(struct pfctl *, struct superblock *);
222void    comparable_rule(struct pf_rule *, const struct pf_rule *, int);
223int     construct_superblocks(struct pfctl *, struct pf_opt_queue *,
224            struct superblocks *);
225void    exclude_supersets(struct pf_rule *, struct pf_rule *);
226int     interface_group(const char *);
227int     load_feedback_profile(struct pfctl *, struct superblocks *);
228int     optimize_superblock(struct pfctl *, struct superblock *);
229int     pf_opt_create_table(struct pfctl *, struct pf_opt_tbl *);
230void    remove_from_skipsteps(struct skiplist *, struct superblock *,
231            struct pf_opt_rule *, struct pf_skip_step *);
232int     remove_identical_rules(struct pfctl *, struct superblock *);
233int     reorder_rules(struct pfctl *, struct superblock *, int);
234int     rules_combineable(struct pf_rule *, struct pf_rule *);
235void    skip_append(struct superblock *, int, struct pf_skip_step *,
236            struct pf_opt_rule *);
237int     skip_compare(int, struct pf_skip_step *, struct pf_opt_rule *);
238void    skip_init(void);
239int     skip_cmp_af(struct pf_rule *, struct pf_rule *);
240int     skip_cmp_dir(struct pf_rule *, struct pf_rule *);
241int     skip_cmp_dst_addr(struct pf_rule *, struct pf_rule *);
242int     skip_cmp_dst_port(struct pf_rule *, struct pf_rule *);
243int     skip_cmp_ifp(struct pf_rule *, struct pf_rule *);
244int     skip_cmp_proto(struct pf_rule *, struct pf_rule *);
245int     skip_cmp_src_addr(struct pf_rule *, struct pf_rule *);
246int     skip_cmp_src_port(struct pf_rule *, struct pf_rule *);
247int     superblock_inclusive(struct superblock *, struct pf_opt_rule *);
248void    superblock_free(struct pfctl *, struct superblock *);
249
250
251int (*skip_comparitors[PF_SKIP_COUNT])(struct pf_rule *, struct pf_rule *);
252const char *skip_comparitors_names[PF_SKIP_COUNT];
253#define PF_SKIP_COMPARITORS {                           \
254    { "ifp", PF_SKIP_IFP, skip_cmp_ifp },               \
255    { "dir", PF_SKIP_DIR, skip_cmp_dir },               \
256    { "af", PF_SKIP_AF, skip_cmp_af },                  \
257    { "proto", PF_SKIP_PROTO, skip_cmp_proto },         \
258    { "saddr", PF_SKIP_SRC_ADDR, skip_cmp_src_addr },   \
259    { "sport", PF_SKIP_SRC_PORT, skip_cmp_src_port },   \
260    { "daddr", PF_SKIP_DST_ADDR, skip_cmp_dst_addr },   \
261    { "dport", PF_SKIP_DST_PORT, skip_cmp_dst_port }    \
262}
263
264struct pfr_buffer table_buffer;
265int table_identifier;
266
267
268int
269pfctl_optimize_ruleset(struct pfctl *pf, struct pf_ruleset *rs)
270{
271        struct superblocks superblocks;
272        struct pf_opt_queue opt_queue;
273        struct superblock *block;
274        struct pf_opt_rule *por;
275        struct pf_rule *r;
276        struct pf_rulequeue *old_rules;
277
278        DEBUG("optimizing ruleset");
279        memset(&table_buffer, 0, sizeof(table_buffer));
280        skip_init();
281        TAILQ_INIT(&opt_queue);
282
283        old_rules = rs->rules[PF_RULESET_FILTER].active.ptr;
284        rs->rules[PF_RULESET_FILTER].active.ptr =
285            rs->rules[PF_RULESET_FILTER].inactive.ptr;
286        rs->rules[PF_RULESET_FILTER].inactive.ptr = old_rules;
287
288        /*
289         * XXX expanding the pf_opt_rule format throughout pfctl might allow
290         * us to avoid all this copying.
291         */
292        while ((r = TAILQ_FIRST(rs->rules[PF_RULESET_FILTER].inactive.ptr))
293            != NULL) {
294                TAILQ_REMOVE(rs->rules[PF_RULESET_FILTER].inactive.ptr, r,
295                    entries);
296                if ((por = calloc(1, sizeof(*por))) == NULL)
297                        err(1, "calloc");
298                memcpy(&por->por_rule, r, sizeof(*r));
299                if (TAILQ_FIRST(&r->rpool.list) != NULL) {
300                        TAILQ_INIT(&por->por_rule.rpool.list);
301                        pfctl_move_pool(&r->rpool, &por->por_rule.rpool);
302                } else
303                        bzero(&por->por_rule.rpool,
304                            sizeof(por->por_rule.rpool));
305
306
307                TAILQ_INSERT_TAIL(&opt_queue, por, por_entry);
308        }
309
310        TAILQ_INIT(&superblocks);
311        if (construct_superblocks(pf, &opt_queue, &superblocks))
312                goto error;
313
314        if (pf->optimize & PF_OPTIMIZE_PROFILE) {
315                if (load_feedback_profile(pf, &superblocks))
316                        goto error;
317        }
318
319        TAILQ_FOREACH(block, &superblocks, sb_entry) {
320                if (optimize_superblock(pf, block))
321                        goto error;
322        }
323
324        rs->anchor->refcnt = 0;
325        while ((block = TAILQ_FIRST(&superblocks))) {
326                TAILQ_REMOVE(&superblocks, block, sb_entry);
327
328                while ((por = TAILQ_FIRST(&block->sb_rules))) {
329                        TAILQ_REMOVE(&block->sb_rules, por, por_entry);
330                        por->por_rule.nr = rs->anchor->refcnt++;
331                        if ((r = calloc(1, sizeof(*r))) == NULL)
332                                err(1, "calloc");
333                        memcpy(r, &por->por_rule, sizeof(*r));
334                        TAILQ_INIT(&r->rpool.list);
335                        pfctl_move_pool(&por->por_rule.rpool, &r->rpool);
336                        TAILQ_INSERT_TAIL(
337                            rs->rules[PF_RULESET_FILTER].active.ptr,
338                            r, entries);
339                        free(por);
340                }
341                free(block);
342        }
343
344        return (0);
345
346error:
347        while ((por = TAILQ_FIRST(&opt_queue))) {
348                TAILQ_REMOVE(&opt_queue, por, por_entry);
349                if (por->por_src_tbl) {
350                        pfr_buf_clear(por->por_src_tbl->pt_buf);
351                        free(por->por_src_tbl->pt_buf);
352                        free(por->por_src_tbl);
353                }
354                if (por->por_dst_tbl) {
355                        pfr_buf_clear(por->por_dst_tbl->pt_buf);
356                        free(por->por_dst_tbl->pt_buf);
357                        free(por->por_dst_tbl);
358                }
359                free(por);
360        }
361        while ((block = TAILQ_FIRST(&superblocks))) {
362                TAILQ_REMOVE(&superblocks, block, sb_entry);
363                superblock_free(pf, block);
364        }
365        return (1);
366}
367
368
369/*
370 * Go ahead and optimize a superblock
371 */
372int
373optimize_superblock(struct pfctl *pf, struct superblock *block)
374{
375#ifdef OPT_DEBUG
376        struct pf_opt_rule *por;
377#endif /* OPT_DEBUG */
378
379        /* We have a few optimization passes:
380         *   1) remove duplicate rules or rules that are a subset of other
381         *      rules
382         *   2) combine otherwise identical rules with different IP addresses
383         *      into a single rule and put the addresses in a table.
384         *   3) re-order the rules to improve kernel skip steps
385         *   4) re-order the 'quick' rules based on feedback from the
386         *      active ruleset statistics
387         *
388         * XXX combine_rules() doesn't combine v4 and v6 rules.  would just
389         *     have to keep af in the table container, make af 'COMBINE' and
390         *     twiddle the af on the merged rule
391         * XXX maybe add a weighting to the metric on skipsteps when doing
392         *     reordering.  sometimes two sequential tables will be better
393         *     that four consecutive interfaces.
394         * XXX need to adjust the skipstep count of everything after PROTO,
395         *     since they aren't actually checked on a proto mismatch in
396         *     pf_test_{tcp, udp, icmp}()
397         * XXX should i treat proto=0, af=0 or dir=0 special in skepstep
398         *     calculation since they are a DC?
399         * XXX keep last skiplist of last superblock to influence this
400         *     superblock.  '5 inet6 log' should make '3 inet6' come before '4
401         *     inet' in the next superblock.
402         * XXX would be useful to add tables for ports
403         * XXX we can also re-order some mutually exclusive superblocks to
404         *     try merging superblocks before any of these optimization passes.
405         *     for instance a single 'log in' rule in the middle of non-logging
406         *     out rules.
407         */
408
409        /* shortcut.  there will be a lot of 1-rule superblocks */
410        if (!TAILQ_NEXT(TAILQ_FIRST(&block->sb_rules), por_entry))
411                return (0);
412
413#ifdef OPT_DEBUG
414        printf("--- Superblock ---\n");
415        TAILQ_FOREACH(por, &block->sb_rules, por_entry) {
416                printf("  ");
417                print_rule(&por->por_rule, por->por_rule.anchor ?
418                    por->por_rule.anchor->name : "", 1, 0);
419        }
420#endif /* OPT_DEBUG */
421
422
423        if (remove_identical_rules(pf, block))
424                return (1);
425        if (combine_rules(pf, block))
426                return (1);
427        if ((pf->optimize & PF_OPTIMIZE_PROFILE) &&
428            TAILQ_FIRST(&block->sb_rules)->por_rule.quick &&
429            block->sb_profiled_block) {
430                if (block_feedback(pf, block))
431                        return (1);
432        } else if (reorder_rules(pf, block, 0)) {
433                return (1);
434        }
435
436        /*
437         * Don't add any optimization passes below reorder_rules().  It will
438         * have divided superblocks into smaller blocks for further refinement
439         * and doesn't put them back together again.  What once was a true
440         * superblock might have been split into multiple superblocks.
441         */
442
443#ifdef OPT_DEBUG
444        printf("--- END Superblock ---\n");
445#endif /* OPT_DEBUG */
446        return (0);
447}
448
449
450/*
451 * Optimization pass #1: remove identical rules
452 */
453int
454remove_identical_rules(struct pfctl *pf, struct superblock *block)
455{
456        struct pf_opt_rule *por1, *por2, *por_next, *por2_next;
457        struct pf_rule a, a2, b, b2;
458
459        for (por1 = TAILQ_FIRST(&block->sb_rules); por1; por1 = por_next) {
460                por_next = TAILQ_NEXT(por1, por_entry);
461                for (por2 = por_next; por2; por2 = por2_next) {
462                        por2_next = TAILQ_NEXT(por2, por_entry);
463                        comparable_rule(&a, &por1->por_rule, DC);
464                        comparable_rule(&b, &por2->por_rule, DC);
465                        memcpy(&a2, &a, sizeof(a2));
466                        memcpy(&b2, &b, sizeof(b2));
467
468                        exclude_supersets(&a, &b);
469                        exclude_supersets(&b2, &a2);
470                        if (memcmp(&a, &b, sizeof(a)) == 0) {
471                                DEBUG("removing identical rule  nr%d = *nr%d*",
472                                    por1->por_rule.nr, por2->por_rule.nr);
473                                TAILQ_REMOVE(&block->sb_rules, por2, por_entry);
474                                if (por_next == por2)
475                                        por_next = TAILQ_NEXT(por1, por_entry);
476                                free(por2);
477                        } else if (memcmp(&a2, &b2, sizeof(a2)) == 0) {
478                                DEBUG("removing identical rule  *nr%d* = nr%d",
479                                    por1->por_rule.nr, por2->por_rule.nr);
480                                TAILQ_REMOVE(&block->sb_rules, por1, por_entry);
481                                free(por1);
482                                break;
483                        }
484                }
485        }
486
487        return (0);
488}
489
490
491/*
492 * Optimization pass #2: combine similar rules with different addresses
493 * into a single rule and a table
494 */
495int
496combine_rules(struct pfctl *pf, struct superblock *block)
497{
498        struct pf_opt_rule *p1, *p2, *por_next;
499        int src_eq, dst_eq;
500
501        if ((pf->loadopt & PFCTL_FLAG_TABLE) == 0) {
502                warnx("Must enable table loading for optimizations");
503                return (1);
504        }
505
506        /* First we make a pass to combine the rules.  O(n log n) */
507        TAILQ_FOREACH(p1, &block->sb_rules, por_entry) {
508                for (p2 = TAILQ_NEXT(p1, por_entry); p2; p2 = por_next) {
509                        por_next = TAILQ_NEXT(p2, por_entry);
510
511                        src_eq = addrs_equal(&p1->por_rule.src,
512                            &p2->por_rule.src);
513                        dst_eq = addrs_equal(&p1->por_rule.dst,
514                            &p2->por_rule.dst);
515
516                        if (src_eq && !dst_eq && p1->por_src_tbl == NULL &&
517                            p2->por_dst_tbl == NULL &&
518                            p2->por_src_tbl == NULL &&
519                            rules_combineable(&p1->por_rule, &p2->por_rule) &&
520                            addrs_combineable(&p1->por_rule.dst,
521                            &p2->por_rule.dst)) {
522                                DEBUG("can combine rules  nr%d = nr%d",
523                                    p1->por_rule.nr, p2->por_rule.nr);
524                                if (p1->por_dst_tbl == NULL &&
525                                    add_opt_table(pf, &p1->por_dst_tbl,
526                                    p1->por_rule.af, &p1->por_rule.dst))
527                                        return (1);
528                                if (add_opt_table(pf, &p1->por_dst_tbl,
529                                    p1->por_rule.af, &p2->por_rule.dst))
530                                        return (1);
531                                p2->por_dst_tbl = p1->por_dst_tbl;
532                                if (p1->por_dst_tbl->pt_rulecount >=
533                                    TABLE_THRESHOLD) {
534                                        TAILQ_REMOVE(&block->sb_rules, p2,
535                                            por_entry);
536                                        free(p2);
537                                }
538                        } else if (!src_eq && dst_eq && p1->por_dst_tbl == NULL
539                            && p2->por_src_tbl == NULL &&
540                            p2->por_dst_tbl == NULL &&
541                            rules_combineable(&p1->por_rule, &p2->por_rule) &&
542                            addrs_combineable(&p1->por_rule.src,
543                            &p2->por_rule.src)) {
544                                DEBUG("can combine rules  nr%d = nr%d",
545                                    p1->por_rule.nr, p2->por_rule.nr);
546                                if (p1->por_src_tbl == NULL &&
547                                    add_opt_table(pf, &p1->por_src_tbl,
548                                    p1->por_rule.af, &p1->por_rule.src))
549                                        return (1);
550                                if (add_opt_table(pf, &p1->por_src_tbl,
551                                    p1->por_rule.af, &p2->por_rule.src))
552                                        return (1);
553                                p2->por_src_tbl = p1->por_src_tbl;
554                                if (p1->por_src_tbl->pt_rulecount >=
555                                    TABLE_THRESHOLD) {
556                                        TAILQ_REMOVE(&block->sb_rules, p2,
557                                            por_entry);
558                                        free(p2);
559                                }
560                        }
561                }
562        }
563
564
565        /*
566         * Then we make a final pass to create a valid table name and
567         * insert the name into the rules.
568         */
569        for (p1 = TAILQ_FIRST(&block->sb_rules); p1; p1 = por_next) {
570                por_next = TAILQ_NEXT(p1, por_entry);
571                assert(p1->por_src_tbl == NULL || p1->por_dst_tbl == NULL);
572
573                if (p1->por_src_tbl && p1->por_src_tbl->pt_rulecount >=
574                    TABLE_THRESHOLD) {
575                        if (p1->por_src_tbl->pt_generated) {
576                                /* This rule is included in a table */
577                                TAILQ_REMOVE(&block->sb_rules, p1, por_entry);
578                                free(p1);
579                                continue;
580                        }
581                        p1->por_src_tbl->pt_generated = 1;
582
583                        if ((pf->opts & PF_OPT_NOACTION) == 0 &&
584                            pf_opt_create_table(pf, p1->por_src_tbl))
585                                return (1);
586
587                        pf->tdirty = 1;
588
589                        if (pf->opts & PF_OPT_VERBOSE)
590                                print_tabledef(p1->por_src_tbl->pt_name,
591                                    PFR_TFLAG_CONST, 1,
592                                    &p1->por_src_tbl->pt_nodes);
593
594                        memset(&p1->por_rule.src.addr, 0,
595                            sizeof(p1->por_rule.src.addr));
596                        p1->por_rule.src.addr.type = PF_ADDR_TABLE;
597                        strlcpy(p1->por_rule.src.addr.v.tblname,
598                            p1->por_src_tbl->pt_name,
599                            sizeof(p1->por_rule.src.addr.v.tblname));
600
601                        pfr_buf_clear(p1->por_src_tbl->pt_buf);
602                        free(p1->por_src_tbl->pt_buf);
603                        p1->por_src_tbl->pt_buf = NULL;
604                }
605                if (p1->por_dst_tbl && p1->por_dst_tbl->pt_rulecount >=
606                    TABLE_THRESHOLD) {
607                        if (p1->por_dst_tbl->pt_generated) {
608                                /* This rule is included in a table */
609                                TAILQ_REMOVE(&block->sb_rules, p1, por_entry);
610                                free(p1);
611                                continue;
612                        }
613                        p1->por_dst_tbl->pt_generated = 1;
614
615                        if ((pf->opts & PF_OPT_NOACTION) == 0 &&
616                            pf_opt_create_table(pf, p1->por_dst_tbl))
617                                return (1);
618                        pf->tdirty = 1;
619
620                        if (pf->opts & PF_OPT_VERBOSE)
621                                print_tabledef(p1->por_dst_tbl->pt_name,
622                                    PFR_TFLAG_CONST, 1,
623                                    &p1->por_dst_tbl->pt_nodes);
624
625                        memset(&p1->por_rule.dst.addr, 0,
626                            sizeof(p1->por_rule.dst.addr));
627                        p1->por_rule.dst.addr.type = PF_ADDR_TABLE;
628                        strlcpy(p1->por_rule.dst.addr.v.tblname,
629                            p1->por_dst_tbl->pt_name,
630                            sizeof(p1->por_rule.dst.addr.v.tblname));
631
632                        pfr_buf_clear(p1->por_dst_tbl->pt_buf);
633                        free(p1->por_dst_tbl->pt_buf);
634                        p1->por_dst_tbl->pt_buf = NULL;
635                }
636        }
637
638        return (0);
639}
640
641
642/*
643 * Optimization pass #3: re-order rules to improve skip steps
644 */
645int
646reorder_rules(struct pfctl *pf, struct superblock *block, int depth)
647{
648        struct superblock *newblock;
649        struct pf_skip_step *skiplist;
650        struct pf_opt_rule *por;
651        int i, largest, largest_list, rule_count = 0;
652        TAILQ_HEAD( , pf_opt_rule) head;
653
654        /*
655         * Calculate the best-case skip steps.  We put each rule in a list
656         * of other rules with common fields
657         */
658        for (i = 0; i < PF_SKIP_COUNT; i++) {
659                TAILQ_FOREACH(por, &block->sb_rules, por_entry) {
660                        TAILQ_FOREACH(skiplist, &block->sb_skipsteps[i],
661                            ps_entry) {
662                                if (skip_compare(i, skiplist, por) == 0)
663                                        break;
664                        }
665                        if (skiplist == NULL) {
666                                if ((skiplist = calloc(1, sizeof(*skiplist))) ==
667                                    NULL)
668                                        err(1, "calloc");
669                                TAILQ_INIT(&skiplist->ps_rules);
670                                TAILQ_INSERT_TAIL(&block->sb_skipsteps[i],
671                                    skiplist, ps_entry);
672                        }
673                        skip_append(block, i, skiplist, por);
674                }
675        }
676
677        TAILQ_FOREACH(por, &block->sb_rules, por_entry)
678                rule_count++;
679
680        /*
681         * Now we're going to ignore any fields that are identical between
682         * all of the rules in the superblock and those fields which differ
683         * between every rule in the superblock.
684         */
685        largest = 0;
686        for (i = 0; i < PF_SKIP_COUNT; i++) {
687                skiplist = TAILQ_FIRST(&block->sb_skipsteps[i]);
688                if (skiplist->ps_count == rule_count) {
689                        DEBUG("(%d) original skipstep '%s' is all rules",
690                            depth, skip_comparitors_names[i]);
691                        skiplist->ps_count = 0;
692                } else if (skiplist->ps_count == 1) {
693                        skiplist->ps_count = 0;
694                } else {
695                        DEBUG("(%d) original skipstep '%s' largest jump is %d",
696                            depth, skip_comparitors_names[i],
697                            skiplist->ps_count);
698                        if (skiplist->ps_count > largest)
699                                largest = skiplist->ps_count;
700                }
701        }
702        if (largest == 0) {
703                /* Ugh.  There is NO commonality in the superblock on which
704                 * optimize the skipsteps optimization.
705                 */
706                goto done;
707        }
708
709        /*
710         * Now we're going to empty the superblock rule list and re-create
711         * it based on a more optimal skipstep order.
712         */
713        TAILQ_INIT(&head);
714        while ((por = TAILQ_FIRST(&block->sb_rules))) {
715                TAILQ_REMOVE(&block->sb_rules, por, por_entry);
716                TAILQ_INSERT_TAIL(&head, por, por_entry);
717        }
718
719
720        while (!TAILQ_EMPTY(&head)) {
721                largest = 1;
722
723                /*
724                 * Find the most useful skip steps remaining
725                 */
726                for (i = 0; i < PF_SKIP_COUNT; i++) {
727                        skiplist = TAILQ_FIRST(&block->sb_skipsteps[i]);
728                        if (skiplist->ps_count > largest) {
729                                largest = skiplist->ps_count;
730                                largest_list = i;
731                        }
732                }
733
734                if (largest <= 1) {
735                        /*
736                         * Nothing useful left.  Leave remaining rules in order.
737                         */
738                        DEBUG("(%d) no more commonality for skip steps", depth);
739                        while ((por = TAILQ_FIRST(&head))) {
740                                TAILQ_REMOVE(&head, por, por_entry);
741                                TAILQ_INSERT_TAIL(&block->sb_rules, por,
742                                    por_entry);
743                        }
744                } else {
745                        /*
746                         * There is commonality.  Extract those common rules
747                         * and place them in the ruleset adjacent to each
748                         * other.
749                         */
750                        skiplist = TAILQ_FIRST(&block->sb_skipsteps[
751                            largest_list]);
752                        DEBUG("(%d) skipstep '%s' largest jump is %d @ #%d",
753                            depth, skip_comparitors_names[largest_list],
754                            largest, TAILQ_FIRST(&TAILQ_FIRST(&block->
755                            sb_skipsteps [largest_list])->ps_rules)->
756                            por_rule.nr);
757                        TAILQ_REMOVE(&block->sb_skipsteps[largest_list],
758                            skiplist, ps_entry);
759
760
761                        /*
762                         * There may be further commonality inside these
763                         * rules.  So we'll split them off into they're own
764                         * superblock and pass it back into the optimizer.
765                         */
766                        if (skiplist->ps_count > 2) {
767                                if ((newblock = calloc(1, sizeof(*newblock)))
768                                    == NULL) {
769                                        warn("calloc");
770                                        return (1);
771                                }
772                                TAILQ_INIT(&newblock->sb_rules);
773                                for (i = 0; i < PF_SKIP_COUNT; i++)
774                                        TAILQ_INIT(&newblock->sb_skipsteps[i]);
775                                TAILQ_INSERT_BEFORE(block, newblock, sb_entry);
776                                DEBUG("(%d) splitting off %d rules from superblock @ #%d",
777                                    depth, skiplist->ps_count,
778                                    TAILQ_FIRST(&skiplist->ps_rules)->
779                                    por_rule.nr);
780                        } else {
781                                newblock = block;
782                        }
783
784                        while ((por = TAILQ_FIRST(&skiplist->ps_rules))) {
785                                TAILQ_REMOVE(&head, por, por_entry);
786                                TAILQ_REMOVE(&skiplist->ps_rules, por,
787                                    por_skip_entry[largest_list]);
788                                TAILQ_INSERT_TAIL(&newblock->sb_rules, por,
789                                    por_entry);
790
791                                /* Remove this rule from all other skiplists */
792                                remove_from_skipsteps(&block->sb_skipsteps[
793                                    largest_list], block, por, skiplist);
794                        }
795                        free(skiplist);
796                        if (newblock != block)
797                                if (reorder_rules(pf, newblock, depth + 1))
798                                        return (1);
799                }
800        }
801
802done:
803        for (i = 0; i < PF_SKIP_COUNT; i++) {
804                while ((skiplist = TAILQ_FIRST(&block->sb_skipsteps[i]))) {
805                        TAILQ_REMOVE(&block->sb_skipsteps[i], skiplist,
806                            ps_entry);
807                        free(skiplist);
808                }
809        }
810
811        return (0);
812}
813
814
815/*
816 * Optimization pass #4: re-order 'quick' rules based on feedback from the
817 * currently running ruleset
818 */
819int
820block_feedback(struct pfctl *pf, struct superblock *block)
821{
822        TAILQ_HEAD( , pf_opt_rule) queue;
823        struct pf_opt_rule *por1, *por2;
824        u_int64_t total_count = 0;
825        struct pf_rule a, b;
826
827
828        /*
829         * Walk through all of the profiled superblock's rules and copy
830         * the counters onto our rules.
831         */
832        TAILQ_FOREACH(por1, &block->sb_profiled_block->sb_rules, por_entry) {
833                comparable_rule(&a, &por1->por_rule, DC);
834                total_count += por1->por_rule.packets[0] +
835                    por1->por_rule.packets[1];
836                TAILQ_FOREACH(por2, &block->sb_rules, por_entry) {
837                        if (por2->por_profile_count)
838                                continue;
839                        comparable_rule(&b, &por2->por_rule, DC);
840                        if (memcmp(&a, &b, sizeof(a)) == 0) {
841                                por2->por_profile_count =
842                                    por1->por_rule.packets[0] +
843                                    por1->por_rule.packets[1];
844                                break;
845                        }
846                }
847        }
848        superblock_free(pf, block->sb_profiled_block);
849        block->sb_profiled_block = NULL;
850
851        /*
852         * Now we pull all of the rules off the superblock and re-insert them
853         * in sorted order.
854         */
855
856        TAILQ_INIT(&queue);
857        while ((por1 = TAILQ_FIRST(&block->sb_rules)) != NULL) {
858                TAILQ_REMOVE(&block->sb_rules, por1, por_entry);
859                TAILQ_INSERT_TAIL(&queue, por1, por_entry);
860        }
861
862        while ((por1 = TAILQ_FIRST(&queue)) != NULL) {
863                TAILQ_REMOVE(&queue, por1, por_entry);
864/* XXX I should sort all of the unused rules based on skip steps */
865                TAILQ_FOREACH(por2, &block->sb_rules, por_entry) {
866                        if (por1->por_profile_count > por2->por_profile_count) {
867                                TAILQ_INSERT_BEFORE(por2, por1, por_entry);
868                                break;
869                        }
870                }
871#ifdef __FreeBSD__
872                if (por2 == NULL)
873#else
874                if (por2 == TAILQ_END(&block->sb_rules))
875#endif
876                        TAILQ_INSERT_TAIL(&block->sb_rules, por1, por_entry);
877        }
878
879        return (0);
880}
881
882
883/*
884 * Load the current ruleset from the kernel and try to associate them with
885 * the ruleset we're optimizing.
886 */
887int
888load_feedback_profile(struct pfctl *pf, struct superblocks *superblocks)
889{
890        struct superblock *block, *blockcur;
891        struct superblocks prof_superblocks;
892        struct pf_opt_rule *por;
893        struct pf_opt_queue queue;
894        struct pfioc_rule pr;
895        struct pf_rule a, b;
896        int nr, mnr;
897
898        TAILQ_INIT(&queue);
899        TAILQ_INIT(&prof_superblocks);
900
901        memset(&pr, 0, sizeof(pr));
902        pr.rule.action = PF_PASS;
903        if (ioctl(pf->dev, DIOCGETRULES, &pr)) {
904                warn("DIOCGETRULES");
905                return (1);
906        }
907        mnr = pr.nr;
908
909        DEBUG("Loading %d active rules for a feedback profile", mnr);
910        for (nr = 0; nr < mnr; ++nr) {
911                struct pf_ruleset *rs;
912                if ((por = calloc(1, sizeof(*por))) == NULL) {
913                        warn("calloc");
914                        return (1);
915                }
916                pr.nr = nr;
917                if (ioctl(pf->dev, DIOCGETRULE, &pr)) {
918                        warn("DIOCGETRULES");
919                        return (1);
920                }
921                memcpy(&por->por_rule, &pr.rule, sizeof(por->por_rule));
922                rs = pf_find_or_create_ruleset(pr.anchor_call);
923                por->por_rule.anchor = rs->anchor;
924                if (TAILQ_EMPTY(&por->por_rule.rpool.list))
925                        memset(&por->por_rule.rpool, 0,
926                            sizeof(por->por_rule.rpool));
927                TAILQ_INSERT_TAIL(&queue, por, por_entry);
928
929                /* XXX pfctl_get_pool(pf->dev, &pr.rule.rpool, nr, pr.ticket,
930                 *         PF_PASS, pf->anchor) ???
931                 * ... pfctl_clear_pool(&pr.rule.rpool)
932                 */
933        }
934
935        if (construct_superblocks(pf, &queue, &prof_superblocks))
936                return (1);
937
938
939        /*
940         * Now we try to associate the active ruleset's superblocks with
941         * the superblocks we're compiling.
942         */
943        block = TAILQ_FIRST(superblocks);
944        blockcur = TAILQ_FIRST(&prof_superblocks);
945        while (block && blockcur) {
946                comparable_rule(&a, &TAILQ_FIRST(&block->sb_rules)->por_rule,
947                    BREAK);
948                comparable_rule(&b, &TAILQ_FIRST(&blockcur->sb_rules)->por_rule,
949                    BREAK);
950                if (memcmp(&a, &b, sizeof(a)) == 0) {
951                        /* The two superblocks lined up */
952                        block->sb_profiled_block = blockcur;
953                } else {
954                        DEBUG("superblocks don't line up between #%d and #%d",
955                            TAILQ_FIRST(&block->sb_rules)->por_rule.nr,
956                            TAILQ_FIRST(&blockcur->sb_rules)->por_rule.nr);
957                        break;
958                }
959                block = TAILQ_NEXT(block, sb_entry);
960                blockcur = TAILQ_NEXT(blockcur, sb_entry);
961        }
962
963
964
965        /* Free any superblocks we couldn't link */
966        while (blockcur) {
967                block = TAILQ_NEXT(blockcur, sb_entry);
968                superblock_free(pf, blockcur);
969                blockcur = block;
970        }
971        return (0);
972}
973
974
975/*
976 * Compare a rule to a skiplist to see if the rule is a member
977 */
978int
979skip_compare(int skipnum, struct pf_skip_step *skiplist,
980    struct pf_opt_rule *por)
981{
982        struct pf_rule *a, *b;
983        if (skipnum >= PF_SKIP_COUNT || skipnum < 0)
984                errx(1, "skip_compare() out of bounds");
985        a = &por->por_rule;
986        b = &TAILQ_FIRST(&skiplist->ps_rules)->por_rule;
987
988        return ((skip_comparitors[skipnum])(a, b));
989}
990
991
992/*
993 * Add a rule to a skiplist
994 */
995void
996skip_append(struct superblock *superblock, int skipnum,
997    struct pf_skip_step *skiplist, struct pf_opt_rule *por)
998{
999        struct pf_skip_step *prev;
1000
1001        skiplist->ps_count++;
1002        TAILQ_INSERT_TAIL(&skiplist->ps_rules, por, por_skip_entry[skipnum]);
1003
1004        /* Keep the list of skiplists sorted by whichever is larger */
1005        while ((prev = TAILQ_PREV(skiplist, skiplist, ps_entry)) &&
1006            prev->ps_count < skiplist->ps_count) {
1007                TAILQ_REMOVE(&superblock->sb_skipsteps[skipnum],
1008                    skiplist, ps_entry);
1009                TAILQ_INSERT_BEFORE(prev, skiplist, ps_entry);
1010        }
1011}
1012
1013
1014/*
1015 * Remove a rule from the other skiplist calculations.
1016 */
1017void
1018remove_from_skipsteps(struct skiplist *head, struct superblock *block,
1019    struct pf_opt_rule *por, struct pf_skip_step *active_list)
1020{
1021        struct pf_skip_step *sk, *next;
1022        struct pf_opt_rule *p2;
1023        int i, found;
1024
1025        for (i = 0; i < PF_SKIP_COUNT; i++) {
1026                sk = TAILQ_FIRST(&block->sb_skipsteps[i]);
1027                if (sk == NULL || sk == active_list || sk->ps_count <= 1)
1028                        continue;
1029                found = 0;
1030                do {
1031                        TAILQ_FOREACH(p2, &sk->ps_rules, por_skip_entry[i])
1032                                if (p2 == por) {
1033                                        TAILQ_REMOVE(&sk->ps_rules, p2,
1034                                            por_skip_entry[i]);
1035                                        found = 1;
1036                                        sk->ps_count--;
1037                                        break;
1038                                }
1039                } while (!found && (sk = TAILQ_NEXT(sk, ps_entry)));
1040                if (found && sk) {
1041                        /* Does this change the sorting order? */
1042                        while ((next = TAILQ_NEXT(sk, ps_entry)) &&
1043                            next->ps_count > sk->ps_count) {
1044                                TAILQ_REMOVE(head, sk, ps_entry);
1045                                TAILQ_INSERT_AFTER(head, next, sk, ps_entry);
1046                        }
1047#ifdef OPT_DEBUG
1048                        next = TAILQ_NEXT(sk, ps_entry);
1049                        assert(next == NULL || next->ps_count <= sk->ps_count);
1050#endif /* OPT_DEBUG */
1051                }
1052        }
1053}
1054
1055
1056/* Compare two rules AF field for skiplist construction */
1057int
1058skip_cmp_af(struct pf_rule *a, struct pf_rule *b)
1059{
1060        if (a->af != b->af || a->af == 0)
1061                return (1);
1062        return (0);
1063}
1064
1065/* Compare two rules DIRECTION field for skiplist construction */
1066int
1067skip_cmp_dir(struct pf_rule *a, struct pf_rule *b)
1068{
1069        if (a->direction == 0 || a->direction != b->direction)
1070                return (1);
1071        return (0);
1072}
1073
1074/* Compare two rules DST Address field for skiplist construction */
1075int
1076skip_cmp_dst_addr(struct pf_rule *a, struct pf_rule *b)
1077{
1078        if (a->dst.neg != b->dst.neg ||
1079            a->dst.addr.type != b->dst.addr.type)
1080                return (1);
1081        /* XXX if (a->proto != b->proto && a->proto != 0 && b->proto != 0
1082         *    && (a->proto == IPPROTO_TCP || a->proto == IPPROTO_UDP ||
1083         *    a->proto == IPPROTO_ICMP
1084         *      return (1);
1085         */
1086        switch (a->dst.addr.type) {
1087        case PF_ADDR_ADDRMASK:
1088                if (memcmp(&a->dst.addr.v.a.addr, &b->dst.addr.v.a.addr,
1089                    sizeof(a->dst.addr.v.a.addr)) ||
1090                    memcmp(&a->dst.addr.v.a.mask, &b->dst.addr.v.a.mask,
1091                    sizeof(a->dst.addr.v.a.mask)) ||
1092                    (a->dst.addr.v.a.addr.addr32[0] == 0 &&
1093                    a->dst.addr.v.a.addr.addr32[1] == 0 &&
1094                    a->dst.addr.v.a.addr.addr32[2] == 0 &&
1095                    a->dst.addr.v.a.addr.addr32[3] == 0))
1096                        return (1);
1097                return (0);
1098        case PF_ADDR_DYNIFTL:
1099                if (strcmp(a->dst.addr.v.ifname, b->dst.addr.v.ifname) != 0 ||
1100                    a->dst.addr.iflags != a->dst.addr.iflags ||
1101                    memcmp(&a->dst.addr.v.a.mask, &b->dst.addr.v.a.mask,
1102                    sizeof(a->dst.addr.v.a.mask)))
1103                        return (1);
1104                return (0);
1105        case PF_ADDR_NOROUTE:
1106        case PF_ADDR_URPFFAILED:
1107                return (0);
1108        case PF_ADDR_TABLE:
1109                return (strcmp(a->dst.addr.v.tblname, b->dst.addr.v.tblname));
1110        }
1111        return (1);
1112}
1113
1114/* Compare two rules DST port field for skiplist construction */
1115int
1116skip_cmp_dst_port(struct pf_rule *a, struct pf_rule *b)
1117{
1118        /* XXX if (a->proto != b->proto && a->proto != 0 && b->proto != 0
1119         *    && (a->proto == IPPROTO_TCP || a->proto == IPPROTO_UDP ||
1120         *    a->proto == IPPROTO_ICMP
1121         *      return (1);
1122         */
1123        if (a->dst.port_op == PF_OP_NONE || a->dst.port_op != b->dst.port_op ||
1124            a->dst.port[0] != b->dst.port[0] ||
1125            a->dst.port[1] != b->dst.port[1])
1126                return (1);
1127        return (0);
1128}
1129
1130/* Compare two rules IFP field for skiplist construction */
1131int
1132skip_cmp_ifp(struct pf_rule *a, struct pf_rule *b)
1133{
1134        if (strcmp(a->ifname, b->ifname) || a->ifname[0] == '\0')
1135                return (1);
1136        return (a->ifnot != b->ifnot);
1137}
1138
1139/* Compare two rules PROTO field for skiplist construction */
1140int
1141skip_cmp_proto(struct pf_rule *a, struct pf_rule *b)
1142{
1143        return (a->proto != b->proto || a->proto == 0);
1144}
1145
1146/* Compare two rules SRC addr field for skiplist construction */
1147int
1148skip_cmp_src_addr(struct pf_rule *a, struct pf_rule *b)
1149{
1150        if (a->src.neg != b->src.neg ||
1151            a->src.addr.type != b->src.addr.type)
1152                return (1);
1153        /* XXX if (a->proto != b->proto && a->proto != 0 && b->proto != 0
1154         *    && (a->proto == IPPROTO_TCP || a->proto == IPPROTO_UDP ||
1155         *    a->proto == IPPROTO_ICMP
1156         *      return (1);
1157         */
1158        switch (a->src.addr.type) {
1159        case PF_ADDR_ADDRMASK:
1160                if (memcmp(&a->src.addr.v.a.addr, &b->src.addr.v.a.addr,
1161                    sizeof(a->src.addr.v.a.addr)) ||
1162                    memcmp(&a->src.addr.v.a.mask, &b->src.addr.v.a.mask,
1163                    sizeof(a->src.addr.v.a.mask)) ||
1164                    (a->src.addr.v.a.addr.addr32[0] == 0 &&
1165                    a->src.addr.v.a.addr.addr32[1] == 0 &&
1166                    a->src.addr.v.a.addr.addr32[2] == 0 &&
1167                    a->src.addr.v.a.addr.addr32[3] == 0))
1168                        return (1);
1169                return (0);
1170        case PF_ADDR_DYNIFTL:
1171                if (strcmp(a->src.addr.v.ifname, b->src.addr.v.ifname) != 0 ||
1172                    a->src.addr.iflags != a->src.addr.iflags ||
1173                    memcmp(&a->src.addr.v.a.mask, &b->src.addr.v.a.mask,
1174                    sizeof(a->src.addr.v.a.mask)))
1175                        return (1);
1176                return (0);
1177        case PF_ADDR_NOROUTE:
1178        case PF_ADDR_URPFFAILED:
1179                return (0);
1180        case PF_ADDR_TABLE:
1181                return (strcmp(a->src.addr.v.tblname, b->src.addr.v.tblname));
1182        }
1183        return (1);
1184}
1185
1186/* Compare two rules SRC port field for skiplist construction */
1187int
1188skip_cmp_src_port(struct pf_rule *a, struct pf_rule *b)
1189{
1190        if (a->src.port_op == PF_OP_NONE || a->src.port_op != b->src.port_op ||
1191            a->src.port[0] != b->src.port[0] ||
1192            a->src.port[1] != b->src.port[1])
1193                return (1);
1194        /* XXX if (a->proto != b->proto && a->proto != 0 && b->proto != 0
1195         *    && (a->proto == IPPROTO_TCP || a->proto == IPPROTO_UDP ||
1196         *    a->proto == IPPROTO_ICMP
1197         *      return (1);
1198         */
1199        return (0);
1200}
1201
1202
1203void
1204skip_init(void)
1205{
1206        struct {
1207                char *name;
1208                int skipnum;
1209                int (*func)(struct pf_rule *, struct pf_rule *);
1210        } comps[] = PF_SKIP_COMPARITORS;
1211        int skipnum, i;
1212
1213        for (skipnum = 0; skipnum < PF_SKIP_COUNT; skipnum++) {
1214                for (i = 0; i < sizeof(comps)/sizeof(*comps); i++)
1215                        if (comps[i].skipnum == skipnum) {
1216                                skip_comparitors[skipnum] = comps[i].func;
1217                                skip_comparitors_names[skipnum] = comps[i].name;
1218                        }
1219        }
1220        for (skipnum = 0; skipnum < PF_SKIP_COUNT; skipnum++)
1221                if (skip_comparitors[skipnum] == NULL)
1222                        errx(1, "Need to add skip step comparitor to pfctl?!");
1223}
1224
1225/*
1226 * Add a host/netmask to a table
1227 */
1228int
1229add_opt_table(struct pfctl *pf, struct pf_opt_tbl **tbl, sa_family_t af,
1230    struct pf_rule_addr *addr)
1231{
1232#ifdef OPT_DEBUG
1233        char buf[128];
1234#endif /* OPT_DEBUG */
1235#ifndef __rtems__
1236        static int tablenum = 0;
1237#endif /* __rtems__ */
1238        struct node_host node_host;
1239
1240        if (*tbl == NULL) {
1241                if ((*tbl = calloc(1, sizeof(**tbl))) == NULL ||
1242                    ((*tbl)->pt_buf = calloc(1, sizeof(*(*tbl)->pt_buf))) ==
1243                    NULL)
1244                        err(1, "calloc");
1245                (*tbl)->pt_buf->pfrb_type = PFRB_ADDRS;
1246                SIMPLEQ_INIT(&(*tbl)->pt_nodes);
1247
1248                /* This is just a temporary table name */
1249                snprintf((*tbl)->pt_name, sizeof((*tbl)->pt_name), "%s%d",
1250#ifndef __rtems__
1251                    PF_OPT_TABLE_PREFIX, tablenum++);
1252#else /* __rtems__ */
1253                    PF_OPT_TABLE_PREFIX, add_opt_table_num++);
1254#endif /* __rtems__ */
1255                DEBUG("creating table <%s>", (*tbl)->pt_name);
1256        }
1257
1258        memset(&node_host, 0, sizeof(node_host));
1259        node_host.af = af;
1260        node_host.addr = addr->addr;
1261
1262#ifdef OPT_DEBUG
1263        DEBUG("<%s> adding %s/%d", (*tbl)->pt_name, inet_ntop(af,
1264            &node_host.addr.v.a.addr, buf, sizeof(buf)),
1265            unmask(&node_host.addr.v.a.mask, af));
1266#endif /* OPT_DEBUG */
1267
1268        if (append_addr_host((*tbl)->pt_buf, &node_host, 0, 0)) {
1269                warn("failed to add host");
1270                return (1);
1271        }
1272        if (pf->opts & PF_OPT_VERBOSE) {
1273                struct node_tinit *ti;
1274
1275                if ((ti = calloc(1, sizeof(*ti))) == NULL)
1276                        err(1, "malloc");
1277                if ((ti->host = malloc(sizeof(*ti->host))) == NULL)
1278                        err(1, "malloc");
1279                memcpy(ti->host, &node_host, sizeof(*ti->host));
1280                SIMPLEQ_INSERT_TAIL(&(*tbl)->pt_nodes, ti, entries);
1281        }
1282
1283        (*tbl)->pt_rulecount++;
1284        if ((*tbl)->pt_rulecount == TABLE_THRESHOLD)
1285                DEBUG("table <%s> now faster than skip steps", (*tbl)->pt_name);
1286
1287        return (0);
1288}
1289
1290/*
1291 * Do the dirty work of choosing an unused table name and creating it.
1292 * (be careful with the table name, it might already be used in another anchor)
1293 */
1294int
1295pf_opt_create_table(struct pfctl *pf, struct pf_opt_tbl *tbl)
1296{
1297#ifndef __rtems__
1298        static int tablenum;
1299#endif /* __rtems__ */
1300        struct pfr_table *t;
1301
1302        if (table_buffer.pfrb_type == 0) {
1303                /* Initialize the list of tables */
1304                table_buffer.pfrb_type = PFRB_TABLES;
1305                for (;;) {
1306                        pfr_buf_grow(&table_buffer, table_buffer.pfrb_size);
1307                        table_buffer.pfrb_size = table_buffer.pfrb_msize;
1308                        if (pfr_get_tables(NULL, table_buffer.pfrb_caddr,
1309                            &table_buffer.pfrb_size, PFR_FLAG_ALLRSETS))
1310                                err(1, "pfr_get_tables");
1311                        if (table_buffer.pfrb_size <= table_buffer.pfrb_msize)
1312                                break;
1313                }
1314                table_identifier = arc4random();
1315        }
1316
1317        /* XXX would be *really* nice to avoid duplicating identical tables */
1318
1319        /* Now we have to pick a table name that isn't used */
1320again:
1321        DEBUG("translating temporary table <%s> to <%s%x_%d>", tbl->pt_name,
1322#ifndef __rtems__
1323            PF_OPT_TABLE_PREFIX, table_identifier, tablenum);
1324#else /* __rtems__ */
1325            PF_OPT_TABLE_PREFIX, table_identifier, pf_opt_create_table_num);
1326#endif /* __rtems__ */
1327        snprintf(tbl->pt_name, sizeof(tbl->pt_name), "%s%x_%d",
1328#ifndef __rtems__
1329            PF_OPT_TABLE_PREFIX, table_identifier, tablenum);
1330#else /* __rtems__ */
1331            PF_OPT_TABLE_PREFIX, table_identifier, pf_opt_create_table_num);
1332#endif /* __rtems__ */
1333        PFRB_FOREACH(t, &table_buffer) {
1334                if (strcasecmp(t->pfrt_name, tbl->pt_name) == 0) {
1335                        /* Collision.  Try again */
1336                        DEBUG("wow, table <%s> in use.  trying again",
1337                            tbl->pt_name);
1338                        table_identifier = arc4random();
1339                        goto again;
1340                }
1341        }
1342#ifndef __rtems__
1343        tablenum++;
1344#else /* __rtems__ */
1345        pf_opt_create_table_num++;
1346#endif /* __rtems__ */
1347
1348
1349        if (pfctl_define_table(tbl->pt_name, PFR_TFLAG_CONST, 1,
1350            pf->astack[0]->name, tbl->pt_buf, pf->astack[0]->ruleset.tticket)) {
1351                warn("failed to create table %s in %s",
1352                    tbl->pt_name, pf->astack[0]->name);
1353                return (1);
1354        }
1355        return (0);
1356}
1357
1358/*
1359 * Partition the flat ruleset into a list of distinct superblocks
1360 */
1361int
1362construct_superblocks(struct pfctl *pf, struct pf_opt_queue *opt_queue,
1363    struct superblocks *superblocks)
1364{
1365        struct superblock *block = NULL;
1366        struct pf_opt_rule *por;
1367        int i;
1368
1369        while (!TAILQ_EMPTY(opt_queue)) {
1370                por = TAILQ_FIRST(opt_queue);
1371                TAILQ_REMOVE(opt_queue, por, por_entry);
1372                if (block == NULL || !superblock_inclusive(block, por)) {
1373                        if ((block = calloc(1, sizeof(*block))) == NULL) {
1374                                warn("calloc");
1375                                return (1);
1376                        }
1377                        TAILQ_INIT(&block->sb_rules);
1378                        for (i = 0; i < PF_SKIP_COUNT; i++)
1379                                TAILQ_INIT(&block->sb_skipsteps[i]);
1380                        TAILQ_INSERT_TAIL(superblocks, block, sb_entry);
1381                }
1382                TAILQ_INSERT_TAIL(&block->sb_rules, por, por_entry);
1383        }
1384
1385        return (0);
1386}
1387
1388
1389/*
1390 * Compare two rule addresses
1391 */
1392int
1393addrs_equal(struct pf_rule_addr *a, struct pf_rule_addr *b)
1394{
1395        if (a->neg != b->neg)
1396                return (0);
1397        return (memcmp(&a->addr, &b->addr, sizeof(a->addr)) == 0);
1398}
1399
1400
1401/*
1402 * The addresses are not equal, but can we combine them into one table?
1403 */
1404int
1405addrs_combineable(struct pf_rule_addr *a, struct pf_rule_addr *b)
1406{
1407        if (a->addr.type != PF_ADDR_ADDRMASK ||
1408            b->addr.type != PF_ADDR_ADDRMASK)
1409                return (0);
1410        if (a->neg != b->neg || a->port_op != b->port_op ||
1411            a->port[0] != b->port[0] || a->port[1] != b->port[1])
1412                return (0);
1413        return (1);
1414}
1415
1416
1417/*
1418 * Are we allowed to combine these two rules
1419 */
1420int
1421rules_combineable(struct pf_rule *p1, struct pf_rule *p2)
1422{
1423        struct pf_rule a, b;
1424
1425        comparable_rule(&a, p1, COMBINED);
1426        comparable_rule(&b, p2, COMBINED);
1427        return (memcmp(&a, &b, sizeof(a)) == 0);
1428}
1429
1430
1431/*
1432 * Can a rule be included inside a superblock
1433 */
1434int
1435superblock_inclusive(struct superblock *block, struct pf_opt_rule *por)
1436{
1437        struct pf_rule a, b;
1438        int i, j;
1439
1440        /* First check for hard breaks */
1441        for (i = 0; i < sizeof(pf_rule_desc)/sizeof(*pf_rule_desc); i++) {
1442                if (pf_rule_desc[i].prf_type == BARRIER) {
1443                        for (j = 0; j < pf_rule_desc[i].prf_size; j++)
1444                                if (((char *)&por->por_rule)[j +
1445                                    pf_rule_desc[i].prf_offset] != 0)
1446                                        return (0);
1447                }
1448        }
1449
1450        /* per-rule src-track is also a hard break */
1451        if (por->por_rule.rule_flag & PFRULE_RULESRCTRACK)
1452                return (0);
1453
1454        /*
1455         * Have to handle interface groups separately.  Consider the following
1456         * rules:
1457         *      block on EXTIFS to any port 22
1458         *      pass  on em0 to any port 22
1459         * (where EXTIFS is an arbitrary interface group)
1460         * The optimizer may decide to re-order the pass rule in front of the
1461         * block rule.  But what if EXTIFS includes em0???  Such a reordering
1462         * would change the meaning of the ruleset.
1463         * We can't just lookup the EXTIFS group and check if em0 is a member
1464         * because the user is allowed to add interfaces to a group during
1465         * runtime.
1466         * Ergo interface groups become a defacto superblock break :-(
1467         */
1468        if (interface_group(por->por_rule.ifname) ||
1469            interface_group(TAILQ_FIRST(&block->sb_rules)->por_rule.ifname)) {
1470                if (strcasecmp(por->por_rule.ifname,
1471                    TAILQ_FIRST(&block->sb_rules)->por_rule.ifname) != 0)
1472                        return (0);
1473        }
1474
1475        comparable_rule(&a, &TAILQ_FIRST(&block->sb_rules)->por_rule, NOMERGE);
1476        comparable_rule(&b, &por->por_rule, NOMERGE);
1477        if (memcmp(&a, &b, sizeof(a)) == 0)
1478                return (1);
1479
1480#ifdef OPT_DEBUG
1481        for (i = 0; i < sizeof(por->por_rule); i++) {
1482                int closest = -1;
1483                if (((u_int8_t *)&a)[i] != ((u_int8_t *)&b)[i]) {
1484                        for (j = 0; j < sizeof(pf_rule_desc) /
1485                            sizeof(*pf_rule_desc); j++) {
1486                                if (i >= pf_rule_desc[j].prf_offset &&
1487                                    i < pf_rule_desc[j].prf_offset +
1488                                    pf_rule_desc[j].prf_size) {
1489                                        DEBUG("superblock break @ %d due to %s",
1490                                            por->por_rule.nr,
1491                                            pf_rule_desc[j].prf_name);
1492                                        return (0);
1493                                }
1494                                if (i > pf_rule_desc[j].prf_offset) {
1495                                        if (closest == -1 ||
1496                                            i-pf_rule_desc[j].prf_offset <
1497                                            i-pf_rule_desc[closest].prf_offset)
1498                                                closest = j;
1499                                }
1500                        }
1501
1502                        if (closest >= 0)
1503                                DEBUG("superblock break @ %d on %s+%xh",
1504                                    por->por_rule.nr,
1505                                    pf_rule_desc[closest].prf_name,
1506                                    i - pf_rule_desc[closest].prf_offset -
1507                                    pf_rule_desc[closest].prf_size);
1508                        else
1509                                DEBUG("superblock break @ %d on field @ %d",
1510                                    por->por_rule.nr, i);
1511                        return (0);
1512                }
1513        }
1514#endif /* OPT_DEBUG */
1515
1516        return (0);
1517}
1518
1519
1520/*
1521 * Figure out if an interface name is an actual interface or actually a
1522 * group of interfaces.
1523 */
1524int
1525interface_group(const char *ifname)
1526{
1527        if (ifname == NULL || !ifname[0])
1528                return (0);
1529
1530        /* Real interfaces must end in a number, interface groups do not */
1531        if (isdigit(ifname[strlen(ifname) - 1]))
1532                return (0);
1533        else
1534                return (1);
1535}
1536
1537
1538/*
1539 * Make a rule that can directly compared by memcmp()
1540 */
1541void
1542comparable_rule(struct pf_rule *dst, const struct pf_rule *src, int type)
1543{
1544        int i;
1545        /*
1546         * To simplify the comparison, we just zero out the fields that are
1547         * allowed to be different and then do a simple memcmp()
1548         */
1549        memcpy(dst, src, sizeof(*dst));
1550        for (i = 0; i < sizeof(pf_rule_desc)/sizeof(*pf_rule_desc); i++)
1551                if (pf_rule_desc[i].prf_type >= type) {
1552#ifdef OPT_DEBUG
1553                        assert(pf_rule_desc[i].prf_type != NEVER ||
1554                            *(((char *)dst) + pf_rule_desc[i].prf_offset) == 0);
1555#endif /* OPT_DEBUG */
1556                        memset(((char *)dst) + pf_rule_desc[i].prf_offset, 0,
1557                            pf_rule_desc[i].prf_size);
1558                }
1559}
1560
1561
1562/*
1563 * Remove superset information from two rules so we can directly compare them
1564 * with memcmp()
1565 */
1566void
1567exclude_supersets(struct pf_rule *super, struct pf_rule *sub)
1568{
1569        if (super->ifname[0] == '\0')
1570                memset(sub->ifname, 0, sizeof(sub->ifname));
1571        if (super->direction == PF_INOUT)
1572                sub->direction = PF_INOUT;
1573        if ((super->proto == 0 || super->proto == sub->proto) &&
1574            super->flags == 0 && super->flagset == 0 && (sub->flags ||
1575            sub->flagset)) {
1576                sub->flags = super->flags;
1577                sub->flagset = super->flagset;
1578        }
1579        if (super->proto == 0)
1580                sub->proto = 0;
1581
1582        if (super->src.port_op == 0) {
1583                sub->src.port_op = 0;
1584                sub->src.port[0] = 0;
1585                sub->src.port[1] = 0;
1586        }
1587        if (super->dst.port_op == 0) {
1588                sub->dst.port_op = 0;
1589                sub->dst.port[0] = 0;
1590                sub->dst.port[1] = 0;
1591        }
1592
1593        if (super->src.addr.type == PF_ADDR_ADDRMASK && !super->src.neg &&
1594            !sub->src.neg && super->src.addr.v.a.mask.addr32[0] == 0 &&
1595            super->src.addr.v.a.mask.addr32[1] == 0 &&
1596            super->src.addr.v.a.mask.addr32[2] == 0 &&
1597            super->src.addr.v.a.mask.addr32[3] == 0)
1598                memset(&sub->src.addr, 0, sizeof(sub->src.addr));
1599        else if (super->src.addr.type == PF_ADDR_ADDRMASK &&
1600            sub->src.addr.type == PF_ADDR_ADDRMASK &&
1601            super->src.neg == sub->src.neg &&
1602            super->af == sub->af &&
1603            unmask(&super->src.addr.v.a.mask, super->af) <
1604            unmask(&sub->src.addr.v.a.mask, sub->af) &&
1605            super->src.addr.v.a.addr.addr32[0] ==
1606            (sub->src.addr.v.a.addr.addr32[0] &
1607            super->src.addr.v.a.mask.addr32[0]) &&
1608            super->src.addr.v.a.addr.addr32[1] ==
1609            (sub->src.addr.v.a.addr.addr32[1] &
1610            super->src.addr.v.a.mask.addr32[1]) &&
1611            super->src.addr.v.a.addr.addr32[2] ==
1612            (sub->src.addr.v.a.addr.addr32[2] &
1613            super->src.addr.v.a.mask.addr32[2]) &&
1614            super->src.addr.v.a.addr.addr32[3] ==
1615            (sub->src.addr.v.a.addr.addr32[3] &
1616            super->src.addr.v.a.mask.addr32[3])) {
1617                /* sub->src.addr is a subset of super->src.addr/mask */
1618                memcpy(&sub->src.addr, &super->src.addr, sizeof(sub->src.addr));
1619        }
1620
1621        if (super->dst.addr.type == PF_ADDR_ADDRMASK && !super->dst.neg &&
1622            !sub->dst.neg && super->dst.addr.v.a.mask.addr32[0] == 0 &&
1623            super->dst.addr.v.a.mask.addr32[1] == 0 &&
1624            super->dst.addr.v.a.mask.addr32[2] == 0 &&
1625            super->dst.addr.v.a.mask.addr32[3] == 0)
1626                memset(&sub->dst.addr, 0, sizeof(sub->dst.addr));
1627        else if (super->dst.addr.type == PF_ADDR_ADDRMASK &&
1628            sub->dst.addr.type == PF_ADDR_ADDRMASK &&
1629            super->dst.neg == sub->dst.neg &&
1630            super->af == sub->af &&
1631            unmask(&super->dst.addr.v.a.mask, super->af) <
1632            unmask(&sub->dst.addr.v.a.mask, sub->af) &&
1633            super->dst.addr.v.a.addr.addr32[0] ==
1634            (sub->dst.addr.v.a.addr.addr32[0] &
1635            super->dst.addr.v.a.mask.addr32[0]) &&
1636            super->dst.addr.v.a.addr.addr32[1] ==
1637            (sub->dst.addr.v.a.addr.addr32[1] &
1638            super->dst.addr.v.a.mask.addr32[1]) &&
1639            super->dst.addr.v.a.addr.addr32[2] ==
1640            (sub->dst.addr.v.a.addr.addr32[2] &
1641            super->dst.addr.v.a.mask.addr32[2]) &&
1642            super->dst.addr.v.a.addr.addr32[3] ==
1643            (sub->dst.addr.v.a.addr.addr32[3] &
1644            super->dst.addr.v.a.mask.addr32[3])) {
1645                /* sub->dst.addr is a subset of super->dst.addr/mask */
1646                memcpy(&sub->dst.addr, &super->dst.addr, sizeof(sub->dst.addr));
1647        }
1648
1649        if (super->af == 0)
1650                sub->af = 0;
1651}
1652
1653
1654void
1655superblock_free(struct pfctl *pf, struct superblock *block)
1656{
1657        struct pf_opt_rule *por;
1658        while ((por = TAILQ_FIRST(&block->sb_rules))) {
1659                TAILQ_REMOVE(&block->sb_rules, por, por_entry);
1660                if (por->por_src_tbl) {
1661                        if (por->por_src_tbl->pt_buf) {
1662                                pfr_buf_clear(por->por_src_tbl->pt_buf);
1663                                free(por->por_src_tbl->pt_buf);
1664                        }
1665                        free(por->por_src_tbl);
1666                }
1667                if (por->por_dst_tbl) {
1668                        if (por->por_dst_tbl->pt_buf) {
1669                                pfr_buf_clear(por->por_dst_tbl->pt_buf);
1670                                free(por->por_dst_tbl->pt_buf);
1671                        }
1672                        free(por->por_dst_tbl);
1673                }
1674                free(por);
1675        }
1676        if (block->sb_profiled_block)
1677                superblock_free(pf, block->sb_profiled_block);
1678        free(block);
1679}
1680
Note: See TracBrowser for help on using the repository browser.