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