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