xref: /dragonfly/sys/net/pf/pf.c (revision 82730a9c)
1 /*	$OpenBSD: pf.c,v 1.614 2008/08/02 12:34:37 henning Exp $ */
2 
3 /*
4  * Copyright (c) 2004 The DragonFly Project.  All rights reserved.
5  *
6  * Copyright (c) 2001 Daniel Hartmeier
7  * Copyright (c) 2002 - 2008 Henning Brauer
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  *
14  *    - Redistributions of source code must retain the above copyright
15  *      notice, this list of conditions and the following disclaimer.
16  *    - Redistributions in binary form must reproduce the above
17  *      copyright notice, this list of conditions and the following
18  *      disclaimer in the documentation and/or other materials provided
19  *      with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  *
34  * Effort sponsored in part by the Defense Advanced Research Projects
35  * Agency (DARPA) and Air Force Research Laboratory, Air Force
36  * Materiel Command, USAF, under agreement number F30602-01-2-0537.
37  *
38  */
39 
40 #include "opt_inet.h"
41 #include "opt_inet6.h"
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/malloc.h>
46 #include <sys/mbuf.h>
47 #include <sys/filio.h>
48 #include <sys/socket.h>
49 #include <sys/socketvar.h>
50 #include <sys/kernel.h>
51 #include <sys/time.h>
52 #include <sys/sysctl.h>
53 #include <sys/endian.h>
54 #include <sys/proc.h>
55 #include <sys/kthread.h>
56 
57 #include <machine/inttypes.h>
58 
59 #include <sys/md5.h>
60 
61 #include <net/if.h>
62 #include <net/if_types.h>
63 #include <net/bpf.h>
64 #include <net/netisr2.h>
65 #include <net/route.h>
66 
67 #include <netinet/in.h>
68 #include <netinet/in_var.h>
69 #include <netinet/in_systm.h>
70 #include <netinet/ip.h>
71 #include <netinet/ip_var.h>
72 #include <netinet/tcp.h>
73 #include <netinet/tcp_seq.h>
74 #include <netinet/udp.h>
75 #include <netinet/ip_icmp.h>
76 #include <netinet/in_pcb.h>
77 #include <netinet/tcp_timer.h>
78 #include <netinet/tcp_var.h>
79 #include <netinet/udp_var.h>
80 #include <netinet/icmp_var.h>
81 #include <netinet/if_ether.h>
82 
83 #include <net/pf/pfvar.h>
84 #include <net/pf/if_pflog.h>
85 
86 #include <net/pf/if_pfsync.h>
87 
88 #ifdef INET6
89 #include <netinet/ip6.h>
90 #include <netinet/icmp6.h>
91 #include <netinet6/nd6.h>
92 #include <netinet6/ip6_var.h>
93 #include <netinet6/in6_pcb.h>
94 #endif /* INET6 */
95 
96 #include <sys/in_cksum.h>
97 #include <sys/ucred.h>
98 #include <machine/limits.h>
99 #include <sys/msgport2.h>
100 #include <net/netmsg2.h>
101 
102 extern int ip_optcopy(struct ip *, struct ip *);
103 extern int debug_pfugidhack;
104 
105 struct lwkt_token pf_token = LWKT_TOKEN_INITIALIZER(pf_token);
106 
107 #define DPFPRINTF(n, x)	if (pf_status.debug >= (n)) kprintf x
108 
109 /*
110  * Global variables
111  */
112 
113 /* mask radix tree */
114 struct radix_node_head	*pf_maskhead;
115 
116 /* state tables */
117 struct pf_state_tree	 pf_statetbl;
118 
119 struct pf_altqqueue	 pf_altqs[2];
120 struct pf_palist	 pf_pabuf;
121 struct pf_altqqueue	*pf_altqs_active;
122 struct pf_altqqueue	*pf_altqs_inactive;
123 struct pf_status	 pf_status;
124 
125 u_int32_t		 ticket_altqs_active;
126 u_int32_t		 ticket_altqs_inactive;
127 int			 altqs_inactive_open;
128 u_int32_t		 ticket_pabuf;
129 
130 MD5_CTX			 pf_tcp_secret_ctx;
131 u_char			 pf_tcp_secret[16];
132 int			 pf_tcp_secret_init;
133 int			 pf_tcp_iss_off;
134 
135 struct pf_anchor_stackframe {
136 	struct pf_ruleset			*rs;
137 	struct pf_rule				*r;
138 	struct pf_anchor_node			*parent;
139 	struct pf_anchor			*child;
140 } pf_anchor_stack[64];
141 
142 struct malloc_type	 *pf_src_tree_pl, *pf_rule_pl, *pf_pooladdr_pl;
143 struct malloc_type	 *pf_state_pl, *pf_state_key_pl, *pf_state_item_pl;
144 struct malloc_type	 *pf_altq_pl;
145 
146 void			 pf_print_host(struct pf_addr *, u_int16_t, u_int8_t);
147 
148 void			 pf_init_threshold(struct pf_threshold *, u_int32_t,
149 			    u_int32_t);
150 void			 pf_add_threshold(struct pf_threshold *);
151 int			 pf_check_threshold(struct pf_threshold *);
152 
153 void			 pf_change_ap(struct pf_addr *, u_int16_t *,
154 			    u_int16_t *, u_int16_t *, struct pf_addr *,
155 			    u_int16_t, u_int8_t, sa_family_t);
156 int			 pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
157 			    struct tcphdr *, struct pf_state_peer *);
158 #ifdef INET6
159 void			 pf_change_a6(struct pf_addr *, u_int16_t *,
160 			    struct pf_addr *, u_int8_t);
161 #endif /* INET6 */
162 void			 pf_change_icmp(struct pf_addr *, u_int16_t *,
163 			    struct pf_addr *, struct pf_addr *, u_int16_t,
164 			    u_int16_t *, u_int16_t *, u_int16_t *,
165 			    u_int16_t *, u_int8_t, sa_family_t);
166 void			 pf_send_tcp(const struct pf_rule *, sa_family_t,
167 			    const struct pf_addr *, const struct pf_addr *,
168 			    u_int16_t, u_int16_t, u_int32_t, u_int32_t,
169 			    u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
170 			    u_int16_t, struct ether_header *, struct ifnet *);
171 void			 pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
172 			    sa_family_t, struct pf_rule *);
173 struct pf_rule		*pf_match_translation(struct pf_pdesc *, struct mbuf *,
174 			    int, int, struct pfi_kif *,
175 			    struct pf_addr *, u_int16_t, struct pf_addr *,
176 			    u_int16_t, int);
177 struct pf_rule		*pf_get_translation(struct pf_pdesc *, struct mbuf *,
178 			    int, int, struct pfi_kif *, struct pf_src_node **,
179 			    struct pf_state_key **, struct pf_state_key **,
180 			    struct pf_state_key **, struct pf_state_key **,
181 			    struct pf_addr *, struct pf_addr *,
182 			    u_int16_t, u_int16_t);
183 void			 pf_detach_state(struct pf_state *);
184 int			 pf_state_key_setup(struct pf_pdesc *, struct pf_rule *,
185 			    struct pf_state_key **, struct pf_state_key **,
186 			    struct pf_state_key **, struct pf_state_key **,
187 			    struct pf_addr *, struct pf_addr *,
188 			    u_int16_t, u_int16_t);
189 void			 pf_state_key_detach(struct pf_state *, int);
190 u_int32_t		 pf_tcp_iss(struct pf_pdesc *);
191 int			 pf_test_rule(struct pf_rule **, struct pf_state **,
192 			    int, struct pfi_kif *, struct mbuf *, int,
193 			    void *, struct pf_pdesc *, struct pf_rule **,
194 			    struct pf_ruleset **, struct ifqueue *, struct inpcb *);
195 static __inline int	 pf_create_state(struct pf_rule *, struct pf_rule *,
196 			    struct pf_rule *, struct pf_pdesc *,
197 			    struct pf_src_node *, struct pf_state_key *,
198 			    struct pf_state_key *, struct pf_state_key *,
199 			    struct pf_state_key *, struct mbuf *, int,
200 			    u_int16_t, u_int16_t, int *, struct pfi_kif *,
201 			    struct pf_state **, int, u_int16_t, u_int16_t,
202 			    int);
203 int			 pf_test_fragment(struct pf_rule **, int,
204 			    struct pfi_kif *, struct mbuf *, void *,
205 			    struct pf_pdesc *, struct pf_rule **,
206 			    struct pf_ruleset **);
207 int			 pf_tcp_track_full(struct pf_state_peer *,
208 			    struct pf_state_peer *, struct pf_state **,
209 			    struct pfi_kif *, struct mbuf *, int,
210 			    struct pf_pdesc *, u_short *, int *);
211 int			pf_tcp_track_sloppy(struct pf_state_peer *,
212 			    struct pf_state_peer *, struct pf_state **,
213 			    struct pf_pdesc *, u_short *);
214 int			 pf_test_state_tcp(struct pf_state **, int,
215 			    struct pfi_kif *, struct mbuf *, int,
216 			    void *, struct pf_pdesc *, u_short *);
217 int			 pf_test_state_udp(struct pf_state **, int,
218 			    struct pfi_kif *, struct mbuf *, int,
219 			    void *, struct pf_pdesc *);
220 int			 pf_test_state_icmp(struct pf_state **, int,
221 			    struct pfi_kif *, struct mbuf *, int,
222 			    void *, struct pf_pdesc *, u_short *);
223 int			 pf_test_state_other(struct pf_state **, int,
224 			    struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
225 void			 pf_step_into_anchor(int *, struct pf_ruleset **, int,
226 			    struct pf_rule **, struct pf_rule **, int *);
227 int			 pf_step_out_of_anchor(int *, struct pf_ruleset **,
228 			     int, struct pf_rule **, struct pf_rule **,
229 			     int *);
230 void			 pf_hash(struct pf_addr *, struct pf_addr *,
231 			    struct pf_poolhashkey *, sa_family_t);
232 int			 pf_map_addr(u_int8_t, struct pf_rule *,
233 			    struct pf_addr *, struct pf_addr *,
234 			    struct pf_addr *, struct pf_src_node **);
235 int			 pf_get_sport(sa_family_t, u_int8_t, struct pf_rule *,
236 			    struct pf_addr *, struct pf_addr *, u_int16_t,
237 			    struct pf_addr *, u_int16_t*, u_int16_t, u_int16_t,
238 			    struct pf_src_node **);
239 void			 pf_route(struct mbuf **, struct pf_rule *, int,
240 			    struct ifnet *, struct pf_state *,
241 			    struct pf_pdesc *);
242 void			 pf_route6(struct mbuf **, struct pf_rule *, int,
243 			    struct ifnet *, struct pf_state *,
244 			    struct pf_pdesc *);
245 u_int8_t		 pf_get_wscale(struct mbuf *, int, u_int16_t,
246 			    sa_family_t);
247 u_int16_t		 pf_get_mss(struct mbuf *, int, u_int16_t,
248 			    sa_family_t);
249 u_int16_t		 pf_calc_mss(struct pf_addr *, sa_family_t,
250 				u_int16_t);
251 void			 pf_set_rt_ifp(struct pf_state *,
252 			    struct pf_addr *);
253 int			 pf_check_proto_cksum(struct mbuf *, int, int,
254 			    u_int8_t, sa_family_t);
255 struct pf_divert	*pf_get_divert(struct mbuf *);
256 void			 pf_print_state_parts(struct pf_state *,
257 			    struct pf_state_key *, struct pf_state_key *);
258 int			 pf_addr_wrap_neq(struct pf_addr_wrap *,
259 			    struct pf_addr_wrap *);
260 struct pf_state		*pf_find_state(struct pfi_kif *,
261 			    struct pf_state_key_cmp *, u_int, struct mbuf *);
262 int			 pf_src_connlimit(struct pf_state **);
263 int			 pf_check_congestion(struct ifqueue *);
264 
265 extern int pf_end_threads;
266 
267 struct pf_pool_limit pf_pool_limits[PF_LIMIT_MAX] = {
268 	{ &pf_state_pl, PFSTATE_HIWAT },
269 	{ &pf_src_tree_pl, PFSNODE_HIWAT },
270 	{ &pf_frent_pl, PFFRAG_FRENT_HIWAT },
271 	{ &pfr_ktable_pl, PFR_KTABLE_HIWAT },
272 	{ &pfr_kentry_pl, PFR_KENTRY_HIWAT }
273 };
274 
275 #define STATE_LOOKUP(i, k, d, s, m)					\
276 	do {								\
277 		s = pf_find_state(i, k, d, m);			\
278 		if (s == NULL || (s)->timeout == PFTM_PURGE)		\
279 			return (PF_DROP);				\
280 		if (d == PF_OUT &&					\
281 		    (((s)->rule.ptr->rt == PF_ROUTETO &&		\
282 		    (s)->rule.ptr->direction == PF_OUT) ||		\
283 		    ((s)->rule.ptr->rt == PF_REPLYTO &&			\
284 		    (s)->rule.ptr->direction == PF_IN)) &&		\
285 		    (s)->rt_kif != NULL &&				\
286 		    (s)->rt_kif != i)					\
287 			return (PF_PASS);				\
288 	} while (0)
289 
290 #define BOUND_IFACE(r, k) \
291 	((r)->rule_flag & PFRULE_IFBOUND) ? (k) : pfi_all
292 
293 #define STATE_INC_COUNTERS(s)				\
294 	do {						\
295 		s->rule.ptr->states_cur++;		\
296 		s->rule.ptr->states_tot++;		\
297 		if (s->anchor.ptr != NULL) {		\
298 			s->anchor.ptr->states_cur++;	\
299 			s->anchor.ptr->states_tot++;	\
300 		}					\
301 		if (s->nat_rule.ptr != NULL) {		\
302 			s->nat_rule.ptr->states_cur++;	\
303 			s->nat_rule.ptr->states_tot++;	\
304 		}					\
305 	} while (0)
306 
307 #define STATE_DEC_COUNTERS(s)				\
308 	do {						\
309 		if (s->nat_rule.ptr != NULL)		\
310 			s->nat_rule.ptr->states_cur--;	\
311 		if (s->anchor.ptr != NULL)		\
312 			s->anchor.ptr->states_cur--;	\
313 		s->rule.ptr->states_cur--;		\
314 	} while (0)
315 
316 static MALLOC_DEFINE(M_PFSTATEPL, "pfstatepl", "pf state pool list");
317 static MALLOC_DEFINE(M_PFSRCTREEPL, "pfsrctpl", "pf source tree pool list");
318 static MALLOC_DEFINE(M_PFSTATEKEYPL, "pfstatekeypl", "pf state key pool list");
319 static MALLOC_DEFINE(M_PFSTATEITEMPL, "pfstateitempl", "pf state item pool list");
320 
321 static __inline int pf_src_compare(struct pf_src_node *, struct pf_src_node *);
322 static __inline int pf_state_compare_key(struct pf_state_key *,
323 	struct pf_state_key *);
324 static __inline int pf_state_compare_id(struct pf_state *,
325 	struct pf_state *);
326 
327 struct pf_src_tree tree_src_tracking;
328 
329 struct pf_state_tree_id tree_id;
330 struct pf_state_queue state_list;
331 
332 RB_GENERATE(pf_src_tree, pf_src_node, entry, pf_src_compare);
333 RB_GENERATE(pf_state_tree, pf_state_key, entry, pf_state_compare_key);
334 RB_GENERATE(pf_state_tree_id, pf_state,
335     entry_id, pf_state_compare_id);
336 
337 static __inline int
338 pf_src_compare(struct pf_src_node *a, struct pf_src_node *b)
339 {
340 	int	diff;
341 
342 	if (a->rule.ptr > b->rule.ptr)
343 		return (1);
344 	if (a->rule.ptr < b->rule.ptr)
345 		return (-1);
346 	if ((diff = a->af - b->af) != 0)
347 		return (diff);
348 	switch (a->af) {
349 #ifdef INET
350 	case AF_INET:
351 		if (a->addr.addr32[0] > b->addr.addr32[0])
352 			return (1);
353 		if (a->addr.addr32[0] < b->addr.addr32[0])
354 			return (-1);
355 		break;
356 #endif /* INET */
357 #ifdef INET6
358 	case AF_INET6:
359 		if (a->addr.addr32[3] > b->addr.addr32[3])
360 			return (1);
361 		if (a->addr.addr32[3] < b->addr.addr32[3])
362 			return (-1);
363 		if (a->addr.addr32[2] > b->addr.addr32[2])
364 			return (1);
365 		if (a->addr.addr32[2] < b->addr.addr32[2])
366 			return (-1);
367 		if (a->addr.addr32[1] > b->addr.addr32[1])
368 			return (1);
369 		if (a->addr.addr32[1] < b->addr.addr32[1])
370 			return (-1);
371 		if (a->addr.addr32[0] > b->addr.addr32[0])
372 			return (1);
373 		if (a->addr.addr32[0] < b->addr.addr32[0])
374 			return (-1);
375 		break;
376 #endif /* INET6 */
377 	}
378 	return (0);
379 }
380 
381 u_int32_t
382 pf_state_hash(struct pf_state_key *sk)
383 {
384 	u_int32_t hv = (u_int32_t)(((intptr_t)sk >> 6) ^ ((intptr_t)sk >> 15));
385 	if (hv == 0)	/* disallow 0 */
386 		hv = 1;
387 	return(hv);
388 }
389 
390 #ifdef INET6
391 void
392 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
393 {
394 	switch (af) {
395 #ifdef INET
396 	case AF_INET:
397 		dst->addr32[0] = src->addr32[0];
398 		break;
399 #endif /* INET */
400 	case AF_INET6:
401 		dst->addr32[0] = src->addr32[0];
402 		dst->addr32[1] = src->addr32[1];
403 		dst->addr32[2] = src->addr32[2];
404 		dst->addr32[3] = src->addr32[3];
405 		break;
406 	}
407 }
408 #endif /* INET6 */
409 
410 void
411 pf_init_threshold(struct pf_threshold *threshold,
412     u_int32_t limit, u_int32_t seconds)
413 {
414 	threshold->limit = limit * PF_THRESHOLD_MULT;
415 	threshold->seconds = seconds;
416 	threshold->count = 0;
417 	threshold->last = time_second;
418 }
419 
420 void
421 pf_add_threshold(struct pf_threshold *threshold)
422 {
423 	u_int32_t t = time_second, diff = t - threshold->last;
424 
425 	if (diff >= threshold->seconds)
426 		threshold->count = 0;
427 	else
428 		threshold->count -= threshold->count * diff /
429 		    threshold->seconds;
430 	threshold->count += PF_THRESHOLD_MULT;
431 	threshold->last = t;
432 }
433 
434 int
435 pf_check_threshold(struct pf_threshold *threshold)
436 {
437 	return (threshold->count > threshold->limit);
438 }
439 
440 int
441 pf_src_connlimit(struct pf_state **state)
442 {
443 	int bad = 0;
444 
445 	(*state)->src_node->conn++;
446 	(*state)->src.tcp_est = 1;
447 	pf_add_threshold(&(*state)->src_node->conn_rate);
448 
449 	if ((*state)->rule.ptr->max_src_conn &&
450 	    (*state)->rule.ptr->max_src_conn <
451 	    (*state)->src_node->conn) {
452 		pf_status.lcounters[LCNT_SRCCONN]++;
453 		bad++;
454 	}
455 
456 	if ((*state)->rule.ptr->max_src_conn_rate.limit &&
457 	    pf_check_threshold(&(*state)->src_node->conn_rate)) {
458 		pf_status.lcounters[LCNT_SRCCONNRATE]++;
459 		bad++;
460 	}
461 
462 	if (!bad)
463 		return (0);
464 
465 	if ((*state)->rule.ptr->overload_tbl) {
466 		struct pfr_addr p;
467 		u_int32_t	killed = 0;
468 
469 		pf_status.lcounters[LCNT_OVERLOAD_TABLE]++;
470 		if (pf_status.debug >= PF_DEBUG_MISC) {
471 			kprintf("pf_src_connlimit: blocking address ");
472 			pf_print_host(&(*state)->src_node->addr, 0,
473 			    (*state)->key[PF_SK_WIRE]->af);
474 		}
475 
476 		bzero(&p, sizeof(p));
477 		p.pfra_af = (*state)->key[PF_SK_WIRE]->af;
478 		switch ((*state)->key[PF_SK_WIRE]->af) {
479 #ifdef INET
480 		case AF_INET:
481 			p.pfra_net = 32;
482 			p.pfra_ip4addr = (*state)->src_node->addr.v4;
483 			break;
484 #endif /* INET */
485 #ifdef INET6
486 		case AF_INET6:
487 			p.pfra_net = 128;
488 			p.pfra_ip6addr = (*state)->src_node->addr.v6;
489 			break;
490 #endif /* INET6 */
491 		}
492 
493 		pfr_insert_kentry((*state)->rule.ptr->overload_tbl,
494 		    &p, time_second);
495 
496 		/* kill existing states if that's required. */
497 		if ((*state)->rule.ptr->flush) {
498 			struct pf_state_key *sk;
499 			struct pf_state *st;
500 
501 			pf_status.lcounters[LCNT_OVERLOAD_FLUSH]++;
502 			RB_FOREACH(st, pf_state_tree_id, &tree_id) {
503 				sk = st->key[PF_SK_WIRE];
504 				/*
505 				 * Kill states from this source.  (Only those
506 				 * from the same rule if PF_FLUSH_GLOBAL is not
507 				 * set)
508 				 */
509 				if (sk->af ==
510 				    (*state)->key[PF_SK_WIRE]->af &&
511 				    (((*state)->direction == PF_OUT &&
512 				    PF_AEQ(&(*state)->src_node->addr,
513 					&sk->addr[0], sk->af)) ||
514 				    ((*state)->direction == PF_IN &&
515 				    PF_AEQ(&(*state)->src_node->addr,
516 					&sk->addr[1], sk->af))) &&
517 				    ((*state)->rule.ptr->flush &
518 				    PF_FLUSH_GLOBAL ||
519 				    (*state)->rule.ptr == st->rule.ptr)) {
520 					st->timeout = PFTM_PURGE;
521 					st->src.state = st->dst.state =
522 					    TCPS_CLOSED;
523 					killed++;
524 				}
525 			}
526 			if (pf_status.debug >= PF_DEBUG_MISC)
527 				kprintf(", %u states killed", killed);
528 		}
529 		if (pf_status.debug >= PF_DEBUG_MISC)
530 			kprintf("\n");
531 	}
532 
533 	/* kill this state */
534 	(*state)->timeout = PFTM_PURGE;
535 	(*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
536 	return (1);
537 }
538 
539 int
540 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
541     struct pf_addr *src, sa_family_t af)
542 {
543 	struct pf_src_node	k;
544 
545 	if (*sn == NULL) {
546 		k.af = af;
547 		PF_ACPY(&k.addr, src, af);
548 		if (rule->rule_flag & PFRULE_RULESRCTRACK ||
549 		    rule->rpool.opts & PF_POOL_STICKYADDR)
550 			k.rule.ptr = rule;
551 		else
552 			k.rule.ptr = NULL;
553 		pf_status.scounters[SCNT_SRC_NODE_SEARCH]++;
554 		*sn = RB_FIND(pf_src_tree, &tree_src_tracking, &k);
555 	}
556 	if (*sn == NULL) {
557 		if (!rule->max_src_nodes ||
558 		    rule->src_nodes < rule->max_src_nodes)
559 			(*sn) = kmalloc(sizeof(struct pf_src_node), M_PFSRCTREEPL, M_NOWAIT|M_ZERO);
560 		else
561 			pf_status.lcounters[LCNT_SRCNODES]++;
562 		if ((*sn) == NULL)
563 			return (-1);
564 
565 		pf_init_threshold(&(*sn)->conn_rate,
566 		    rule->max_src_conn_rate.limit,
567 		    rule->max_src_conn_rate.seconds);
568 
569 		(*sn)->af = af;
570 		if (rule->rule_flag & PFRULE_RULESRCTRACK ||
571 		    rule->rpool.opts & PF_POOL_STICKYADDR)
572 			(*sn)->rule.ptr = rule;
573 		else
574 			(*sn)->rule.ptr = NULL;
575 		PF_ACPY(&(*sn)->addr, src, af);
576 		if (RB_INSERT(pf_src_tree,
577 		    &tree_src_tracking, *sn) != NULL) {
578 			if (pf_status.debug >= PF_DEBUG_MISC) {
579 				kprintf("pf: src_tree insert failed: ");
580 				pf_print_host(&(*sn)->addr, 0, af);
581 				kprintf("\n");
582 			}
583 			kfree(*sn, M_PFSRCTREEPL);
584 			return (-1);
585 		}
586 		(*sn)->creation = time_second;
587 		(*sn)->ruletype = rule->action;
588 		if ((*sn)->rule.ptr != NULL)
589 			(*sn)->rule.ptr->src_nodes++;
590 		pf_status.scounters[SCNT_SRC_NODE_INSERT]++;
591 		pf_status.src_nodes++;
592 	} else {
593 		if (rule->max_src_states &&
594 		    (*sn)->states >= rule->max_src_states) {
595 			pf_status.lcounters[LCNT_SRCSTATES]++;
596 			return (-1);
597 		}
598 	}
599 	return (0);
600 }
601 
602 /* state table stuff */
603 
604 static __inline int
605 pf_state_compare_key(struct pf_state_key *a, struct pf_state_key *b)
606 {
607 	int	diff;
608 
609 	if ((diff = a->proto - b->proto) != 0)
610 		return (diff);
611 	if ((diff = a->af - b->af) != 0)
612 		return (diff);
613 	switch (a->af) {
614 #ifdef INET
615 	case AF_INET:
616 		if (a->addr[0].addr32[0] > b->addr[0].addr32[0])
617 			return (1);
618 		if (a->addr[0].addr32[0] < b->addr[0].addr32[0])
619 			return (-1);
620 		if (a->addr[1].addr32[0] > b->addr[1].addr32[0])
621 			return (1);
622 		if (a->addr[1].addr32[0] < b->addr[1].addr32[0])
623 			return (-1);
624 		break;
625 #endif /* INET */
626 #ifdef INET6
627 	case AF_INET6:
628 		if (a->addr[0].addr32[3] > b->addr[0].addr32[3])
629 			return (1);
630 		if (a->addr[0].addr32[3] < b->addr[0].addr32[3])
631 			return (-1);
632 		if (a->addr[1].addr32[3] > b->addr[1].addr32[3])
633 			return (1);
634 		if (a->addr[1].addr32[3] < b->addr[1].addr32[3])
635 			return (-1);
636 		if (a->addr[0].addr32[2] > b->addr[0].addr32[2])
637 			return (1);
638 		if (a->addr[0].addr32[2] < b->addr[0].addr32[2])
639 			return (-1);
640 		if (a->addr[1].addr32[2] > b->addr[1].addr32[2])
641 			return (1);
642 		if (a->addr[1].addr32[2] < b->addr[1].addr32[2])
643 			return (-1);
644 		if (a->addr[0].addr32[1] > b->addr[0].addr32[1])
645 			return (1);
646 		if (a->addr[0].addr32[1] < b->addr[0].addr32[1])
647 			return (-1);
648 		if (a->addr[1].addr32[1] > b->addr[1].addr32[1])
649 			return (1);
650 		if (a->addr[1].addr32[1] < b->addr[1].addr32[1])
651 			return (-1);
652 		if (a->addr[0].addr32[0] > b->addr[0].addr32[0])
653 			return (1);
654 		if (a->addr[0].addr32[0] < b->addr[0].addr32[0])
655 			return (-1);
656 		if (a->addr[1].addr32[0] > b->addr[1].addr32[0])
657 			return (1);
658 		if (a->addr[1].addr32[0] < b->addr[1].addr32[0])
659 			return (-1);
660 		break;
661 #endif /* INET6 */
662 	}
663 
664 	if ((diff = a->port[0] - b->port[0]) != 0)
665 		return (diff);
666 	if ((diff = a->port[1] - b->port[1]) != 0)
667 		return (diff);
668 
669 	return (0);
670 }
671 
672 static __inline int
673 pf_state_compare_id(struct pf_state *a, struct pf_state *b)
674 {
675 	if (a->id > b->id)
676 		return (1);
677 	if (a->id < b->id)
678 		return (-1);
679 	if (a->creatorid > b->creatorid)
680 		return (1);
681 	if (a->creatorid < b->creatorid)
682 		return (-1);
683 
684 	return (0);
685 }
686 
687 int
688 pf_state_key_attach(struct pf_state_key *sk, struct pf_state *s, int idx)
689 {
690 	struct pf_state_item	*si;
691 	struct pf_state_key     *cur;
692 
693 	KKASSERT(s->key[idx] == NULL);	/* XXX handle this? */
694 
695 	if ((cur = RB_INSERT(pf_state_tree, &pf_statetbl, sk)) != NULL) {
696 		/* key exists. check for same kif, if none, add to key */
697 		TAILQ_FOREACH(si, &cur->states, entry)
698 			if (si->s->kif == s->kif &&
699 			    si->s->direction == s->direction) {
700 				if (pf_status.debug >= PF_DEBUG_MISC) {
701 					kprintf(
702 					    "pf: %s key attach failed on %s: ",
703 					    (idx == PF_SK_WIRE) ?
704 					    "wire" : "stack",
705 					    s->kif->pfik_name);
706 					pf_print_state_parts(s,
707 					    (idx == PF_SK_WIRE) ? sk : NULL,
708 					    (idx == PF_SK_STACK) ? sk : NULL);
709 					kprintf("\n");
710 				}
711 				kfree(sk, M_PFSTATEKEYPL);
712 				return (-1);	/* collision! */
713 			}
714 		kfree(sk, M_PFSTATEKEYPL);
715 
716 		s->key[idx] = cur;
717 	} else
718 		s->key[idx] = sk;
719 
720 	if ((si = kmalloc(sizeof(struct pf_state_item), M_PFSTATEITEMPL, M_NOWAIT)) == NULL) {
721 		pf_state_key_detach(s, idx);
722 		return (-1);
723 	}
724 	si->s = s;
725 
726 	/* list is sorted, if-bound states before floating */
727 	if (s->kif == pfi_all)
728 		TAILQ_INSERT_TAIL(&s->key[idx]->states, si, entry);
729 	else
730 		TAILQ_INSERT_HEAD(&s->key[idx]->states, si, entry);
731 	return (0);
732 }
733 
734 void
735 pf_detach_state(struct pf_state *s)
736 {
737 	if (s->key[PF_SK_WIRE] == s->key[PF_SK_STACK])
738 		s->key[PF_SK_WIRE] = NULL;
739 
740 	if (s->key[PF_SK_STACK] != NULL)
741 		pf_state_key_detach(s, PF_SK_STACK);
742 
743 	if (s->key[PF_SK_WIRE] != NULL)
744 		pf_state_key_detach(s, PF_SK_WIRE);
745 }
746 
747 void
748 pf_state_key_detach(struct pf_state *s, int idx)
749 {
750 	struct pf_state_item	*si;
751 	si = TAILQ_FIRST(&s->key[idx]->states);
752 	while (si && si->s != s)
753 	    si = TAILQ_NEXT(si, entry);
754 
755 	if (si) {
756 		TAILQ_REMOVE(&s->key[idx]->states, si, entry);
757 		kfree(si, M_PFSTATEITEMPL);
758 	}
759 
760 	if (TAILQ_EMPTY(&s->key[idx]->states)) {
761 		RB_REMOVE(pf_state_tree, &pf_statetbl, s->key[idx]);
762 		if (s->key[idx]->reverse)
763 			s->key[idx]->reverse->reverse = NULL;
764 		if (s->key[idx]->inp)
765 			s->key[idx]->inp->inp_pf_sk = NULL;
766 		kfree(s->key[idx], M_PFSTATEKEYPL);
767 	}
768 	s->key[idx] = NULL;
769 }
770 
771 struct pf_state_key *
772 pf_alloc_state_key(int pool_flags)
773 {
774 	struct pf_state_key	*sk;
775 
776 	if ((sk = kmalloc(sizeof(struct pf_state_key), M_PFSTATEKEYPL, pool_flags)) == NULL)
777 			return (NULL);
778 	TAILQ_INIT(&sk->states);
779 
780 	return (sk);
781 }
782 
783 int
784 pf_state_key_setup(struct pf_pdesc *pd, struct pf_rule *nr,
785 	struct pf_state_key **skw, struct pf_state_key **sks,
786 	struct pf_state_key **skp, struct pf_state_key **nkp,
787 	struct pf_addr *saddr, struct pf_addr *daddr,
788 	u_int16_t sport, u_int16_t dport)
789 {
790 	KKASSERT((*skp == NULL && *nkp == NULL));
791 
792 	if ((*skp = pf_alloc_state_key(M_NOWAIT | M_ZERO)) == NULL)
793 		return (ENOMEM);
794 
795 	PF_ACPY(&(*skp)->addr[pd->sidx], saddr, pd->af);
796 	PF_ACPY(&(*skp)->addr[pd->didx], daddr, pd->af);
797 	(*skp)->port[pd->sidx] = sport;
798 	(*skp)->port[pd->didx] = dport;
799 	(*skp)->proto = pd->proto;
800 	(*skp)->af = pd->af;
801 
802 	if (nr != NULL) {
803 		if ((*nkp = pf_alloc_state_key(M_NOWAIT | M_ZERO)) == NULL)
804 			return (ENOMEM); /* caller must handle cleanup */
805 
806 		/* XXX maybe just bcopy and TAILQ_INIT(&(*nkp)->states) */
807 		PF_ACPY(&(*nkp)->addr[0], &(*skp)->addr[0], pd->af);
808 		PF_ACPY(&(*nkp)->addr[1], &(*skp)->addr[1], pd->af);
809 		(*nkp)->port[0] = (*skp)->port[0];
810 		(*nkp)->port[1] = (*skp)->port[1];
811 		(*nkp)->proto = pd->proto;
812 		(*nkp)->af = pd->af;
813 	} else
814 		*nkp = *skp;
815 
816 	if (pd->dir == PF_IN) {
817 		*skw = *skp;
818 		*sks = *nkp;
819 	} else {
820 		*sks = *skp;
821 		*skw = *nkp;
822 	}
823 	return (0);
824 }
825 
826 
827 int
828 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
829     struct pf_state_key *sks, struct pf_state *s)
830 {
831 	s->kif = kif;
832 
833 	if (skw == sks) {
834 		if (pf_state_key_attach(skw, s, PF_SK_WIRE))
835 			return (-1);
836 		s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
837 	} else {
838 		if (pf_state_key_attach(skw, s, PF_SK_WIRE)) {
839 			kfree(sks, M_PFSTATEKEYPL);
840 			return (-1);
841 		}
842 		if (pf_state_key_attach(sks, s, PF_SK_STACK)) {
843 			pf_state_key_detach(s, PF_SK_WIRE);
844 			return (-1);
845 		}
846 	}
847 
848 	if (s->id == 0 && s->creatorid == 0) {
849 		s->id = htobe64(pf_status.stateid++);
850 		s->creatorid = pf_status.hostid;
851 	}
852 
853 	/*
854 	 * Calculate hash code for altq
855 	 */
856 	s->hash = crc32(s->key[PF_SK_WIRE], sizeof(*sks));
857 
858 	if (RB_INSERT(pf_state_tree_id, &tree_id, s) != NULL) {
859 		if (pf_status.debug >= PF_DEBUG_MISC) {
860 			kprintf("pf: state insert failed: "
861 			    "id: %016jx creatorid: %08x",
862 			      (uintmax_t)be64toh(s->id), ntohl(s->creatorid));
863 			if (s->sync_flags & PFSTATE_FROMSYNC)
864 				kprintf(" (from sync)");
865 			kprintf("\n");
866 		}
867 		pf_detach_state(s);
868 		return (-1);
869 	}
870 	TAILQ_INSERT_TAIL(&state_list, s, entry_list);
871 	pf_status.fcounters[FCNT_STATE_INSERT]++;
872 	pf_status.states++;
873 	pfi_kif_ref(kif, PFI_KIF_REF_STATE);
874 	pfsync_insert_state(s);
875 	return (0);
876 }
877 
878 struct pf_state *
879 pf_find_state_byid(struct pf_state_cmp *key)
880 {
881 	pf_status.fcounters[FCNT_STATE_SEARCH]++;
882 
883 	return (RB_FIND(pf_state_tree_id, &tree_id, (struct pf_state *)key));
884 }
885 
886 struct pf_state *
887 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir,
888     struct mbuf *m)
889 {
890 	struct pf_state_key	*sk;
891 	struct pf_state_item	*si;
892 
893 	pf_status.fcounters[FCNT_STATE_SEARCH]++;
894 
895 	if (dir == PF_OUT && m->m_pkthdr.pf.statekey &&
896 	    ((struct pf_state_key *)m->m_pkthdr.pf.statekey)->reverse)
897 		sk = ((struct pf_state_key *)m->m_pkthdr.pf.statekey)->reverse;
898 	else {
899 		if ((sk = RB_FIND(pf_state_tree, &pf_statetbl,
900 		    (struct pf_state_key *)key)) == NULL)
901 			return (NULL);
902 		if (dir == PF_OUT && m->m_pkthdr.pf.statekey) {
903 			((struct pf_state_key *)
904 			    m->m_pkthdr.pf.statekey)->reverse = sk;
905 			sk->reverse = m->m_pkthdr.pf.statekey;
906 		}
907 	}
908 
909 	if (dir == PF_OUT)
910 		m->m_pkthdr.pf.statekey = NULL;
911 
912 	/* list is sorted, if-bound states before floating ones */
913 	TAILQ_FOREACH(si, &sk->states, entry)
914 		if ((si->s->kif == pfi_all || si->s->kif == kif) &&
915 		    sk == (dir == PF_IN ? si->s->key[PF_SK_WIRE] :
916 		    si->s->key[PF_SK_STACK]))
917 			return (si->s);
918 
919 	return (NULL);
920 }
921 
922 struct pf_state *
923 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
924 {
925 	struct pf_state_key	*sk;
926 	struct pf_state_item	*si, *ret = NULL;
927 
928 	pf_status.fcounters[FCNT_STATE_SEARCH]++;
929 
930 	sk = RB_FIND(pf_state_tree, &pf_statetbl, (struct pf_state_key *)key);
931 
932 	if (sk != NULL) {
933 		TAILQ_FOREACH(si, &sk->states, entry)
934 			if (dir == PF_INOUT ||
935 			    (sk == (dir == PF_IN ? si->s->key[PF_SK_WIRE] :
936 			    si->s->key[PF_SK_STACK]))) {
937 				if (more == NULL)
938 					return (si->s);
939 
940 				if (ret)
941 					(*more)++;
942 				else
943 					ret = si;
944 			}
945 	}
946 	return (ret ? ret->s : NULL);
947 }
948 
949 /* END state table stuff */
950 
951 
952 void
953 pf_purge_thread(void *v)
954 {
955 	int nloops = 0;
956 	int locked = 0;
957 
958 	lwkt_gettoken(&pf_token);
959 	for (;;) {
960 		tsleep(pf_purge_thread, PWAIT, "pftm", 1 * hz);
961 
962 		lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
963 
964 		if (pf_end_threads) {
965 			pf_purge_expired_states(pf_status.states, 0);
966 			pf_purge_expired_fragments();
967 			pf_purge_expired_src_nodes(1);
968 			pf_end_threads++;
969 
970 			lockmgr(&pf_consistency_lock, LK_RELEASE);
971 			wakeup(pf_purge_thread);
972 			kthread_exit();
973 		}
974 		crit_enter();
975 
976 		/* process a fraction of the state table every second */
977 		if(!pf_purge_expired_states(1 + (pf_status.states
978 		    / pf_default_rule.timeout[PFTM_INTERVAL]), 0)) {
979 
980 			pf_purge_expired_states(1 + (pf_status.states
981 			    / pf_default_rule.timeout[PFTM_INTERVAL]), 1);
982 		}
983 
984 		/* purge other expired types every PFTM_INTERVAL seconds */
985 		if (++nloops >= pf_default_rule.timeout[PFTM_INTERVAL]) {
986 			pf_purge_expired_fragments();
987 			if (!pf_purge_expired_src_nodes(locked)) {
988 				pf_purge_expired_src_nodes(1);
989 			}
990 			nloops = 0;
991 		}
992 		crit_exit();
993 		lockmgr(&pf_consistency_lock, LK_RELEASE);
994 	}
995 	lwkt_reltoken(&pf_token);
996 }
997 
998 u_int32_t
999 pf_state_expires(const struct pf_state *state)
1000 {
1001 	u_int32_t	timeout;
1002 	u_int32_t	start;
1003 	u_int32_t	end;
1004 	u_int32_t	states;
1005 
1006 	/* handle all PFTM_* > PFTM_MAX here */
1007 	if (state->timeout == PFTM_PURGE)
1008 		return (time_second);
1009 	if (state->timeout == PFTM_UNTIL_PACKET)
1010 		return (0);
1011 	KKASSERT(state->timeout != PFTM_UNLINKED);
1012 	KKASSERT(state->timeout < PFTM_MAX);
1013 	timeout = state->rule.ptr->timeout[state->timeout];
1014 	if (!timeout)
1015 		timeout = pf_default_rule.timeout[state->timeout];
1016 	start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1017 	if (start) {
1018 		end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1019 		states = state->rule.ptr->states_cur;
1020 	} else {
1021 		start = pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1022 		end = pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1023 		states = pf_status.states;
1024 	}
1025 	if (end && states > start && start < end) {
1026 		if (states < end)
1027 			return (state->expire + timeout * (end - states) /
1028 			    (end - start));
1029 		else
1030 			return (time_second);
1031 	}
1032 	return (state->expire + timeout);
1033 }
1034 
1035 int
1036 pf_purge_expired_src_nodes(int waslocked)
1037 {
1038 	 struct pf_src_node		*cur, *next;
1039 	 int				 locked = waslocked;
1040 
1041 	 for (cur = RB_MIN(pf_src_tree, &tree_src_tracking); cur; cur = next) {
1042 		 next = RB_NEXT(pf_src_tree, &tree_src_tracking, cur);
1043 
1044 		 if (cur->states <= 0 && cur->expire <= time_second) {
1045 			 if (! locked) {
1046 				 lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
1047 			 	 next = RB_NEXT(pf_src_tree,
1048 				     &tree_src_tracking, cur);
1049 				 locked = 1;
1050 			 }
1051 			 if (cur->rule.ptr != NULL) {
1052 				 cur->rule.ptr->src_nodes--;
1053 				 if (cur->rule.ptr->states_cur <= 0 &&
1054 				     cur->rule.ptr->max_src_nodes <= 0)
1055 					 pf_rm_rule(NULL, cur->rule.ptr);
1056 			 }
1057 			 RB_REMOVE(pf_src_tree, &tree_src_tracking, cur);
1058 			 pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
1059 			 pf_status.src_nodes--;
1060 			 kfree(cur, M_PFSRCTREEPL);
1061 		 }
1062 	 }
1063 
1064 	 if (locked && !waslocked)
1065 		lockmgr(&pf_consistency_lock, LK_RELEASE);
1066 	return(1);
1067 }
1068 
1069 void
1070 pf_src_tree_remove_state(struct pf_state *s)
1071 {
1072 	u_int32_t timeout;
1073 
1074 	if (s->src_node != NULL) {
1075 		if (s->src.tcp_est)
1076 			--s->src_node->conn;
1077 		if (--s->src_node->states <= 0) {
1078 			timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1079 			if (!timeout)
1080 				timeout =
1081 				    pf_default_rule.timeout[PFTM_SRC_NODE];
1082 			s->src_node->expire = time_second + timeout;
1083 		}
1084 	}
1085 	if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1086 		if (--s->nat_src_node->states <= 0) {
1087 			timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1088 			if (!timeout)
1089 				timeout =
1090 				    pf_default_rule.timeout[PFTM_SRC_NODE];
1091 			s->nat_src_node->expire = time_second + timeout;
1092 		}
1093 	}
1094 	s->src_node = s->nat_src_node = NULL;
1095 }
1096 
1097 /* callers should be at crit_enter() */
1098 void
1099 pf_unlink_state(struct pf_state *cur)
1100 {
1101 	if (cur->src.state == PF_TCPS_PROXY_DST) {
1102 		/* XXX wire key the right one? */
1103 		pf_send_tcp(cur->rule.ptr, cur->key[PF_SK_WIRE]->af,
1104 		    &cur->key[PF_SK_WIRE]->addr[1],
1105 		    &cur->key[PF_SK_WIRE]->addr[0],
1106 		    cur->key[PF_SK_WIRE]->port[1],
1107 		    cur->key[PF_SK_WIRE]->port[0],
1108 		    cur->src.seqhi, cur->src.seqlo + 1,
1109 		    TH_RST|TH_ACK, 0, 0, 0, 1, cur->tag, NULL, NULL);
1110 	}
1111 	RB_REMOVE(pf_state_tree_id, &tree_id, cur);
1112 	if (cur->creatorid == pf_status.hostid)
1113 		pfsync_delete_state(cur);
1114 	cur->timeout = PFTM_UNLINKED;
1115 	pf_src_tree_remove_state(cur);
1116 	pf_detach_state(cur);
1117 }
1118 
1119 static struct pf_state	*purge_cur;
1120 
1121 /* callers should be at crit_enter() and hold the
1122  * write_lock on pf_consistency_lock */
1123 void
1124 pf_free_state(struct pf_state *cur)
1125 {
1126 	if (pfsyncif != NULL &&
1127 	    (pfsyncif->sc_bulk_send_next == cur ||
1128 	    pfsyncif->sc_bulk_terminator == cur))
1129 		return;
1130 	KKASSERT(cur->timeout == PFTM_UNLINKED);
1131 	if (--cur->rule.ptr->states_cur <= 0 &&
1132 	    cur->rule.ptr->src_nodes <= 0)
1133 		pf_rm_rule(NULL, cur->rule.ptr);
1134 	if (cur->nat_rule.ptr != NULL)
1135 		if (--cur->nat_rule.ptr->states_cur <= 0 &&
1136 			cur->nat_rule.ptr->src_nodes <= 0)
1137 			pf_rm_rule(NULL, cur->nat_rule.ptr);
1138 	if (cur->anchor.ptr != NULL)
1139 		if (--cur->anchor.ptr->states_cur <= 0)
1140 			pf_rm_rule(NULL, cur->anchor.ptr);
1141 	pf_normalize_tcp_cleanup(cur);
1142 	pfi_kif_unref(cur->kif, PFI_KIF_REF_STATE);
1143 
1144 	/*
1145 	 * We may be freeing pf_purge_expired_states()'s saved scan entry,
1146 	 * adjust it if necessary.
1147 	 */
1148 	if (purge_cur == cur) {
1149 		kprintf("PURGE CONFLICT\n");
1150 		purge_cur = TAILQ_NEXT(purge_cur, entry_list);
1151 	}
1152 	TAILQ_REMOVE(&state_list, cur, entry_list);
1153 	if (cur->tag)
1154 		pf_tag_unref(cur->tag);
1155 	kfree(cur, M_PFSTATEPL);
1156 	pf_status.fcounters[FCNT_STATE_REMOVALS]++;
1157 	pf_status.states--;
1158 }
1159 
1160 int
1161 pf_purge_expired_states(u_int32_t maxcheck, int waslocked)
1162 {
1163 	struct pf_state		*cur;
1164 	int 			 locked = waslocked;
1165 
1166 	while (maxcheck--) {
1167 		/*
1168 		 * Wrap to start of list when we hit the end
1169 		 */
1170 		cur = purge_cur;
1171 		if (cur == NULL) {
1172 			cur = TAILQ_FIRST(&state_list);
1173 			if (cur == NULL)
1174 				break;	/* list empty */
1175 		}
1176 
1177 		/*
1178 		 * Setup next (purge_cur) while we process this one.  If we block and
1179 		 * something else deletes purge_cur, pf_free_state() will adjust it further
1180 		 * ahead.
1181 		 */
1182 		purge_cur = TAILQ_NEXT(cur, entry_list);
1183 
1184 		if (cur->timeout == PFTM_UNLINKED) {
1185 			/* free unlinked state */
1186 			if (! locked) {
1187 				lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
1188 				locked = 1;
1189 			}
1190 			pf_free_state(cur);
1191 		} else if (pf_state_expires(cur) <= time_second) {
1192 			/* unlink and free expired state */
1193 			pf_unlink_state(cur);
1194 			if (! locked) {
1195 				if (!lockmgr(&pf_consistency_lock, LK_EXCLUSIVE))
1196 					return (0);
1197 				locked = 1;
1198 			}
1199 			pf_free_state(cur);
1200 		}
1201 	}
1202 
1203 	if (locked)
1204 		lockmgr(&pf_consistency_lock, LK_RELEASE);
1205 	return (1);
1206 }
1207 
1208 int
1209 pf_tbladdr_setup(struct pf_ruleset *rs, struct pf_addr_wrap *aw)
1210 {
1211 	if (aw->type != PF_ADDR_TABLE)
1212 		return (0);
1213 	if ((aw->p.tbl = pfr_attach_table(rs, aw->v.tblname)) == NULL)
1214 		return (1);
1215 	return (0);
1216 }
1217 
1218 void
1219 pf_tbladdr_remove(struct pf_addr_wrap *aw)
1220 {
1221 	if (aw->type != PF_ADDR_TABLE || aw->p.tbl == NULL)
1222 		return;
1223 	pfr_detach_table(aw->p.tbl);
1224 	aw->p.tbl = NULL;
1225 }
1226 
1227 void
1228 pf_tbladdr_copyout(struct pf_addr_wrap *aw)
1229 {
1230 	struct pfr_ktable *kt = aw->p.tbl;
1231 
1232 	if (aw->type != PF_ADDR_TABLE || kt == NULL)
1233 		return;
1234 	if (!(kt->pfrkt_flags & PFR_TFLAG_ACTIVE) && kt->pfrkt_root != NULL)
1235 		kt = kt->pfrkt_root;
1236 	aw->p.tbl = NULL;
1237 	aw->p.tblcnt = (kt->pfrkt_flags & PFR_TFLAG_ACTIVE) ?
1238 		kt->pfrkt_cnt : -1;
1239 }
1240 
1241 void
1242 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1243 {
1244 	switch (af) {
1245 #ifdef INET
1246 	case AF_INET: {
1247 		u_int32_t a = ntohl(addr->addr32[0]);
1248 		kprintf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1249 		    (a>>8)&255, a&255);
1250 		if (p) {
1251 			p = ntohs(p);
1252 			kprintf(":%u", p);
1253 		}
1254 		break;
1255 	}
1256 #endif /* INET */
1257 #ifdef INET6
1258 	case AF_INET6: {
1259 		u_int16_t b;
1260 		u_int8_t i, curstart = 255, curend = 0,
1261 		    maxstart = 0, maxend = 0;
1262 		for (i = 0; i < 8; i++) {
1263 			if (!addr->addr16[i]) {
1264 				if (curstart == 255)
1265 					curstart = i;
1266 				else
1267 					curend = i;
1268 			} else {
1269 				if (curstart) {
1270 					if ((curend - curstart) >
1271 					    (maxend - maxstart)) {
1272 						maxstart = curstart;
1273 						maxend = curend;
1274 						curstart = 255;
1275 					}
1276 				}
1277 			}
1278 		}
1279 		for (i = 0; i < 8; i++) {
1280 			if (i >= maxstart && i <= maxend) {
1281 				if (maxend != 7) {
1282 					if (i == maxstart)
1283 						kprintf(":");
1284 				} else {
1285 					if (i == maxend)
1286 						kprintf(":");
1287 				}
1288 			} else {
1289 				b = ntohs(addr->addr16[i]);
1290 				kprintf("%x", b);
1291 				if (i < 7)
1292 					kprintf(":");
1293 			}
1294 		}
1295 		if (p) {
1296 			p = ntohs(p);
1297 			kprintf("[%u]", p);
1298 		}
1299 		break;
1300 	}
1301 #endif /* INET6 */
1302 	}
1303 }
1304 
1305 void
1306 pf_print_state(struct pf_state *s)
1307 {
1308 	pf_print_state_parts(s, NULL, NULL);
1309 }
1310 
1311 void
1312 pf_print_state_parts(struct pf_state *s,
1313     struct pf_state_key *skwp, struct pf_state_key *sksp)
1314 {
1315 	struct pf_state_key *skw, *sks;
1316 	u_int8_t proto, dir;
1317 
1318 	/* Do our best to fill these, but they're skipped if NULL */
1319 	skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1320 	sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1321 	proto = skw ? skw->proto : (sks ? sks->proto : 0);
1322 	dir = s ? s->direction : 0;
1323 
1324 	switch (proto) {
1325 	case IPPROTO_TCP:
1326 		kprintf("TCP ");
1327 		break;
1328 	case IPPROTO_UDP:
1329 		kprintf("UDP ");
1330 		break;
1331 	case IPPROTO_ICMP:
1332 		kprintf("ICMP ");
1333 		break;
1334 	case IPPROTO_ICMPV6:
1335 		kprintf("ICMPV6 ");
1336 		break;
1337 	default:
1338 		kprintf("%u ", skw->proto);
1339 		break;
1340 	}
1341 	switch (dir) {
1342 	case PF_IN:
1343 		kprintf(" in");
1344 		break;
1345 	case PF_OUT:
1346 		kprintf(" out");
1347 		break;
1348 	}
1349 	if (skw) {
1350 		kprintf(" wire: ");
1351 		pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1352 		kprintf(" ");
1353 		pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1354 	}
1355 	if (sks) {
1356 		kprintf(" stack: ");
1357 		if (sks != skw) {
1358 			pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1359 			kprintf(" ");
1360 			pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1361 		} else
1362 			kprintf("-");
1363 	}
1364 	if (s) {
1365 		if (proto == IPPROTO_TCP) {
1366 			kprintf(" [lo=%u high=%u win=%u modulator=%u",
1367 			    s->src.seqlo, s->src.seqhi,
1368 			    s->src.max_win, s->src.seqdiff);
1369 			if (s->src.wscale && s->dst.wscale)
1370 				kprintf(" wscale=%u",
1371 				    s->src.wscale & PF_WSCALE_MASK);
1372 			kprintf("]");
1373 			kprintf(" [lo=%u high=%u win=%u modulator=%u",
1374 			    s->dst.seqlo, s->dst.seqhi,
1375 			    s->dst.max_win, s->dst.seqdiff);
1376 			if (s->src.wscale && s->dst.wscale)
1377 				kprintf(" wscale=%u",
1378 				s->dst.wscale & PF_WSCALE_MASK);
1379 			kprintf("]");
1380 		}
1381 		kprintf(" %u:%u", s->src.state, s->dst.state);
1382 	}
1383 }
1384 
1385 void
1386 pf_print_flags(u_int8_t f)
1387 {
1388 	if (f)
1389 		kprintf(" ");
1390 	if (f & TH_FIN)
1391 		kprintf("F");
1392 	if (f & TH_SYN)
1393 		kprintf("S");
1394 	if (f & TH_RST)
1395 		kprintf("R");
1396 	if (f & TH_PUSH)
1397 		kprintf("P");
1398 	if (f & TH_ACK)
1399 		kprintf("A");
1400 	if (f & TH_URG)
1401 		kprintf("U");
1402 	if (f & TH_ECE)
1403 		kprintf("E");
1404 	if (f & TH_CWR)
1405 		kprintf("W");
1406 }
1407 
1408 #define	PF_SET_SKIP_STEPS(i)					\
1409 	do {							\
1410 		while (head[i] != cur) {			\
1411 			head[i]->skip[i].ptr = cur;		\
1412 			head[i] = TAILQ_NEXT(head[i], entries);	\
1413 		}						\
1414 	} while (0)
1415 
1416 void
1417 pf_calc_skip_steps(struct pf_rulequeue *rules)
1418 {
1419 	struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1420 	int i;
1421 
1422 	cur = TAILQ_FIRST(rules);
1423 	prev = cur;
1424 	for (i = 0; i < PF_SKIP_COUNT; ++i)
1425 		head[i] = cur;
1426 	while (cur != NULL) {
1427 
1428 		if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1429 			PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1430 		if (cur->direction != prev->direction)
1431 			PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1432 		if (cur->af != prev->af)
1433 			PF_SET_SKIP_STEPS(PF_SKIP_AF);
1434 		if (cur->proto != prev->proto)
1435 			PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1436 		if (cur->src.neg != prev->src.neg ||
1437 		    pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1438 			PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1439 		if (cur->src.port[0] != prev->src.port[0] ||
1440 		    cur->src.port[1] != prev->src.port[1] ||
1441 		    cur->src.port_op != prev->src.port_op)
1442 			PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
1443 		if (cur->dst.neg != prev->dst.neg ||
1444 		    pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1445 			PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1446 		if (cur->dst.port[0] != prev->dst.port[0] ||
1447 		    cur->dst.port[1] != prev->dst.port[1] ||
1448 		    cur->dst.port_op != prev->dst.port_op)
1449 			PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1450 
1451 		prev = cur;
1452 		cur = TAILQ_NEXT(cur, entries);
1453 	}
1454 	for (i = 0; i < PF_SKIP_COUNT; ++i)
1455 		PF_SET_SKIP_STEPS(i);
1456 }
1457 
1458 int
1459 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1460 {
1461 	if (aw1->type != aw2->type)
1462 		return (1);
1463 	switch (aw1->type) {
1464 	case PF_ADDR_ADDRMASK:
1465 	case PF_ADDR_RANGE:
1466 		if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, 0))
1467 			return (1);
1468 		if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, 0))
1469 			return (1);
1470 		return (0);
1471 	case PF_ADDR_DYNIFTL:
1472 		return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
1473 	case PF_ADDR_NOROUTE:
1474 	case PF_ADDR_URPFFAILED:
1475 		return (0);
1476 	case PF_ADDR_TABLE:
1477 		return (aw1->p.tbl != aw2->p.tbl);
1478 	case PF_ADDR_RTLABEL:
1479 		return (aw1->v.rtlabel != aw2->v.rtlabel);
1480 	default:
1481 		kprintf("invalid address type: %d\n", aw1->type);
1482 		return (1);
1483 	}
1484 }
1485 
1486 u_int16_t
1487 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
1488 {
1489 	u_int32_t	l;
1490 
1491 	if (udp && !cksum)
1492 		return (0x0000);
1493 	l = cksum + old - new;
1494 	l = (l >> 16) + (l & 65535);
1495 	l = l & 65535;
1496 	if (udp && !l)
1497 		return (0xFFFF);
1498 	return (l);
1499 }
1500 
1501 void
1502 pf_change_ap(struct pf_addr *a, u_int16_t *p, u_int16_t *ic, u_int16_t *pc,
1503     struct pf_addr *an, u_int16_t pn, u_int8_t u, sa_family_t af)
1504 {
1505 	struct pf_addr	ao;
1506 	u_int16_t	po = *p;
1507 
1508 	PF_ACPY(&ao, a, af);
1509 	PF_ACPY(a, an, af);
1510 
1511 	*p = pn;
1512 
1513 	switch (af) {
1514 #ifdef INET
1515 	case AF_INET:
1516 		*ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
1517 		    ao.addr16[0], an->addr16[0], 0),
1518 		    ao.addr16[1], an->addr16[1], 0);
1519 		*p = pn;
1520 		*pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1521 		    ao.addr16[0], an->addr16[0], u),
1522 		    ao.addr16[1], an->addr16[1], u),
1523 		    po, pn, u);
1524 		break;
1525 #endif /* INET */
1526 #ifdef INET6
1527 	case AF_INET6:
1528 		*pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1529 		    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1530 		    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1531 		    ao.addr16[0], an->addr16[0], u),
1532 		    ao.addr16[1], an->addr16[1], u),
1533 		    ao.addr16[2], an->addr16[2], u),
1534 		    ao.addr16[3], an->addr16[3], u),
1535 		    ao.addr16[4], an->addr16[4], u),
1536 		    ao.addr16[5], an->addr16[5], u),
1537 		    ao.addr16[6], an->addr16[6], u),
1538 		    ao.addr16[7], an->addr16[7], u),
1539 		    po, pn, u);
1540 		break;
1541 #endif /* INET6 */
1542 	}
1543 }
1544 
1545 
1546 /* Changes a u_int32_t.  Uses a void * so there are no align restrictions */
1547 void
1548 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
1549 {
1550 	u_int32_t	ao;
1551 
1552 	memcpy(&ao, a, sizeof(ao));
1553 	memcpy(a, &an, sizeof(u_int32_t));
1554 	*c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
1555 	    ao % 65536, an % 65536, u);
1556 }
1557 
1558 #ifdef INET6
1559 void
1560 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
1561 {
1562 	struct pf_addr	ao;
1563 
1564 	PF_ACPY(&ao, a, AF_INET6);
1565 	PF_ACPY(a, an, AF_INET6);
1566 
1567 	*c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1568 	    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1569 	    pf_cksum_fixup(pf_cksum_fixup(*c,
1570 	    ao.addr16[0], an->addr16[0], u),
1571 	    ao.addr16[1], an->addr16[1], u),
1572 	    ao.addr16[2], an->addr16[2], u),
1573 	    ao.addr16[3], an->addr16[3], u),
1574 	    ao.addr16[4], an->addr16[4], u),
1575 	    ao.addr16[5], an->addr16[5], u),
1576 	    ao.addr16[6], an->addr16[6], u),
1577 	    ao.addr16[7], an->addr16[7], u);
1578 }
1579 #endif /* INET6 */
1580 
1581 void
1582 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
1583     struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
1584     u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
1585 {
1586 	struct pf_addr	oia, ooa;
1587 
1588 	PF_ACPY(&oia, ia, af);
1589 	if (oa)
1590 		PF_ACPY(&ooa, oa, af);
1591 
1592 	/* Change inner protocol port, fix inner protocol checksum. */
1593 	if (ip != NULL) {
1594 		u_int16_t	oip = *ip;
1595 		u_int32_t	opc = 0;
1596 
1597 		if (pc != NULL)
1598 			opc = *pc;
1599 		*ip = np;
1600 		if (pc != NULL)
1601 			*pc = pf_cksum_fixup(*pc, oip, *ip, u);
1602 		*ic = pf_cksum_fixup(*ic, oip, *ip, 0);
1603 		if (pc != NULL)
1604 			*ic = pf_cksum_fixup(*ic, opc, *pc, 0);
1605 	}
1606 	/* Change inner ip address, fix inner ip and icmp checksums. */
1607 	PF_ACPY(ia, na, af);
1608 	switch (af) {
1609 #ifdef INET
1610 	case AF_INET: {
1611 		u_int32_t	 oh2c = *h2c;
1612 
1613 		*h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
1614 		    oia.addr16[0], ia->addr16[0], 0),
1615 		    oia.addr16[1], ia->addr16[1], 0);
1616 		*ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
1617 		    oia.addr16[0], ia->addr16[0], 0),
1618 		    oia.addr16[1], ia->addr16[1], 0);
1619 		*ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
1620 		break;
1621 	}
1622 #endif /* INET */
1623 #ifdef INET6
1624 	case AF_INET6:
1625 		*ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1626 		    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1627 		    pf_cksum_fixup(pf_cksum_fixup(*ic,
1628 		    oia.addr16[0], ia->addr16[0], u),
1629 		    oia.addr16[1], ia->addr16[1], u),
1630 		    oia.addr16[2], ia->addr16[2], u),
1631 		    oia.addr16[3], ia->addr16[3], u),
1632 		    oia.addr16[4], ia->addr16[4], u),
1633 		    oia.addr16[5], ia->addr16[5], u),
1634 		    oia.addr16[6], ia->addr16[6], u),
1635 		    oia.addr16[7], ia->addr16[7], u);
1636 		break;
1637 #endif /* INET6 */
1638 	}
1639 	/* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
1640 	if (oa) {
1641 		PF_ACPY(oa, na, af);
1642 		switch (af) {
1643 #ifdef INET
1644 		case AF_INET:
1645 			*hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
1646 			    ooa.addr16[0], oa->addr16[0], 0),
1647 			    ooa.addr16[1], oa->addr16[1], 0);
1648 			break;
1649 #endif /* INET */
1650 #ifdef INET6
1651 		case AF_INET6:
1652 			*ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1653 			    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1654 			    pf_cksum_fixup(pf_cksum_fixup(*ic,
1655 			    ooa.addr16[0], oa->addr16[0], u),
1656 			    ooa.addr16[1], oa->addr16[1], u),
1657 			    ooa.addr16[2], oa->addr16[2], u),
1658 			    ooa.addr16[3], oa->addr16[3], u),
1659 			    ooa.addr16[4], oa->addr16[4], u),
1660 			    ooa.addr16[5], oa->addr16[5], u),
1661 			    ooa.addr16[6], oa->addr16[6], u),
1662 			    ooa.addr16[7], oa->addr16[7], u);
1663 			break;
1664 #endif /* INET6 */
1665 		}
1666 	}
1667 }
1668 
1669 
1670 /*
1671  * Need to modulate the sequence numbers in the TCP SACK option
1672  * (credits to Krzysztof Pfaff for report and patch)
1673  */
1674 int
1675 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
1676     struct tcphdr *th, struct pf_state_peer *dst)
1677 {
1678 	int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
1679 	u_int8_t opts[TCP_MAXOLEN], *opt = opts;
1680 	int copyback = 0, i, olen;
1681 	struct raw_sackblock sack;
1682 
1683 #define TCPOLEN_SACKLEN	(TCPOLEN_SACK + 2)
1684 	if (hlen < TCPOLEN_SACKLEN ||
1685 	    !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
1686 		return 0;
1687 
1688 	while (hlen >= TCPOLEN_SACKLEN) {
1689 		olen = opt[1];
1690 		switch (*opt) {
1691 		case TCPOPT_EOL:	/* FALLTHROUGH */
1692 		case TCPOPT_NOP:
1693 			opt++;
1694 			hlen--;
1695 			break;
1696 		case TCPOPT_SACK:
1697 			if (olen > hlen)
1698 				olen = hlen;
1699 			if (olen >= TCPOLEN_SACKLEN) {
1700 				for (i = 2; i + TCPOLEN_SACK <= olen;
1701 				    i += TCPOLEN_SACK) {
1702 					memcpy(&sack, &opt[i], sizeof(sack));
1703 					pf_change_a(&sack.rblk_start, &th->th_sum,
1704 					    htonl(ntohl(sack.rblk_start) -
1705 					    dst->seqdiff), 0);
1706 					pf_change_a(&sack.rblk_end, &th->th_sum,
1707 					    htonl(ntohl(sack.rblk_end) -
1708 					    dst->seqdiff), 0);
1709 					memcpy(&opt[i], &sack, sizeof(sack));
1710 				}
1711 				copyback = 1;
1712 			}
1713 			/* FALLTHROUGH */
1714 		default:
1715 			if (olen < 2)
1716 				olen = 2;
1717 			hlen -= olen;
1718 			opt += olen;
1719 		}
1720 	}
1721 
1722 	if (copyback)
1723 		m_copyback(m, off + sizeof(*th), thoptlen, opts);
1724 	return (copyback);
1725 }
1726 
1727 void
1728 pf_send_tcp(const struct pf_rule *r, sa_family_t af,
1729     const struct pf_addr *saddr, const struct pf_addr *daddr,
1730     u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
1731     u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
1732     u_int16_t rtag, struct ether_header *eh, struct ifnet *ifp)
1733 {
1734 	struct mbuf	*m;
1735 	int		 len = 0, tlen;
1736 #ifdef INET
1737 	struct ip	*h = NULL;
1738 #endif /* INET */
1739 #ifdef INET6
1740 	struct ip6_hdr	*h6 = NULL;
1741 #endif /* INET6 */
1742 	struct tcphdr	*th = NULL;
1743 	char		*opt;
1744 
1745 	ASSERT_LWKT_TOKEN_HELD(&pf_token);
1746 
1747 	/* maximum segment size tcp option */
1748 	tlen = sizeof(struct tcphdr);
1749 	if (mss)
1750 		tlen += 4;
1751 
1752 	switch (af) {
1753 #ifdef INET
1754 	case AF_INET:
1755 		len = sizeof(struct ip) + tlen;
1756 		break;
1757 #endif /* INET */
1758 #ifdef INET6
1759 	case AF_INET6:
1760 		len = sizeof(struct ip6_hdr) + tlen;
1761 		break;
1762 #endif /* INET6 */
1763 	}
1764 
1765 	/*
1766 	 * Create outgoing mbuf.
1767 	 *
1768 	 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
1769 	 * so make sure pf.flags is clear.
1770 	 */
1771 	m = m_gethdr(MB_DONTWAIT, MT_HEADER);
1772 	if (m == NULL) {
1773 		return;
1774 	}
1775 	if (tag)
1776 		m->m_pkthdr.fw_flags |= PF_MBUF_TAGGED;
1777 	m->m_pkthdr.pf.flags = 0;
1778 	m->m_pkthdr.pf.tag = rtag;
1779 	/* XXX Recheck when upgrading to > 4.4 */
1780 	m->m_pkthdr.pf.statekey = NULL;
1781 	if (r != NULL && r->rtableid >= 0)
1782 		m->m_pkthdr.pf.rtableid = r->rtableid;
1783 
1784 #ifdef ALTQ
1785 	if (r != NULL && r->qid) {
1786 		m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
1787 		m->m_pkthdr.pf.qid = r->qid;
1788 		m->m_pkthdr.pf.ecn_af = af;
1789 		m->m_pkthdr.pf.hdr = mtod(m, struct ip *);
1790 	}
1791 #endif /* ALTQ */
1792 	m->m_data += max_linkhdr;
1793 	m->m_pkthdr.len = m->m_len = len;
1794 	m->m_pkthdr.rcvif = NULL;
1795 	bzero(m->m_data, len);
1796 	switch (af) {
1797 #ifdef INET
1798 	case AF_INET:
1799 		h = mtod(m, struct ip *);
1800 
1801 		/* IP header fields included in the TCP checksum */
1802 		h->ip_p = IPPROTO_TCP;
1803 		h->ip_len = tlen;
1804 		h->ip_src.s_addr = saddr->v4.s_addr;
1805 		h->ip_dst.s_addr = daddr->v4.s_addr;
1806 
1807 		th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
1808 		break;
1809 #endif /* INET */
1810 #ifdef INET6
1811 	case AF_INET6:
1812 		h6 = mtod(m, struct ip6_hdr *);
1813 
1814 		/* IP header fields included in the TCP checksum */
1815 		h6->ip6_nxt = IPPROTO_TCP;
1816 		h6->ip6_plen = htons(tlen);
1817 		memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
1818 		memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
1819 
1820 		th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
1821 		break;
1822 #endif /* INET6 */
1823 	}
1824 
1825 	/* TCP header */
1826 	th->th_sport = sport;
1827 	th->th_dport = dport;
1828 	th->th_seq = htonl(seq);
1829 	th->th_ack = htonl(ack);
1830 	th->th_off = tlen >> 2;
1831 	th->th_flags = flags;
1832 	th->th_win = htons(win);
1833 
1834 	if (mss) {
1835 		opt = (char *)(th + 1);
1836 		opt[0] = TCPOPT_MAXSEG;
1837 		opt[1] = 4;
1838 		mss = htons(mss);
1839 		bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
1840 	}
1841 
1842 	switch (af) {
1843 #ifdef INET
1844 	case AF_INET:
1845 		/* TCP checksum */
1846 		th->th_sum = in_cksum(m, len);
1847 
1848 		/* Finish the IP header */
1849 		h->ip_v = 4;
1850 		h->ip_hl = sizeof(*h) >> 2;
1851 		h->ip_tos = IPTOS_LOWDELAY;
1852 		h->ip_len = len;
1853 		h->ip_off = path_mtu_discovery ? IP_DF : 0;
1854 		h->ip_ttl = ttl ? ttl : ip_defttl;
1855 		h->ip_sum = 0;
1856 		if (eh == NULL) {
1857 			lwkt_reltoken(&pf_token);
1858 			ip_output(m, NULL, NULL, 0, NULL, NULL);
1859 			lwkt_gettoken(&pf_token);
1860 		} else {
1861 			struct route		 ro;
1862 			struct rtentry		 rt;
1863 			struct ether_header	*e = (void *)ro.ro_dst.sa_data;
1864 
1865 			if (ifp == NULL) {
1866 				m_freem(m);
1867 				return;
1868 			}
1869 			rt.rt_ifp = ifp;
1870 			ro.ro_rt = &rt;
1871 			ro.ro_dst.sa_len = sizeof(ro.ro_dst);
1872 			ro.ro_dst.sa_family = pseudo_AF_HDRCMPLT;
1873 			bcopy(eh->ether_dhost, e->ether_shost, ETHER_ADDR_LEN);
1874 			bcopy(eh->ether_shost, e->ether_dhost, ETHER_ADDR_LEN);
1875 			e->ether_type = eh->ether_type;
1876 			/* XXX_IMPORT: later */
1877 			lwkt_reltoken(&pf_token);
1878 			ip_output(m, NULL, &ro, 0, NULL, NULL);
1879 			lwkt_gettoken(&pf_token);
1880 		}
1881 		break;
1882 #endif /* INET */
1883 #ifdef INET6
1884 	case AF_INET6:
1885 		/* TCP checksum */
1886 		th->th_sum = in6_cksum(m, IPPROTO_TCP,
1887 		    sizeof(struct ip6_hdr), tlen);
1888 
1889 		h6->ip6_vfc |= IPV6_VERSION;
1890 		h6->ip6_hlim = IPV6_DEFHLIM;
1891 
1892 		lwkt_reltoken(&pf_token);
1893 		ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
1894 		lwkt_gettoken(&pf_token);
1895 		break;
1896 #endif /* INET6 */
1897 	}
1898 }
1899 
1900 void
1901 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
1902     struct pf_rule *r)
1903 {
1904 	struct mbuf	*m0;
1905 
1906 	/*
1907 	 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
1908 	 * so make sure pf.flags is clear.
1909 	 */
1910 	if ((m0 = m_copy(m, 0, M_COPYALL)) == NULL)
1911 		return;
1912 
1913 	m0->m_pkthdr.fw_flags |= PF_MBUF_TAGGED;
1914 	m0->m_pkthdr.pf.flags = 0;
1915 	/* XXX Re-Check when Upgrading to > 4.4 */
1916 	m0->m_pkthdr.pf.statekey = NULL;
1917 
1918 	if (r->rtableid >= 0)
1919 		m0->m_pkthdr.pf.rtableid = r->rtableid;
1920 
1921 #ifdef ALTQ
1922 	if (r->qid) {
1923 		m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
1924 		m0->m_pkthdr.pf.qid = r->qid;
1925 		m0->m_pkthdr.pf.ecn_af = af;
1926 		m0->m_pkthdr.pf.hdr = mtod(m0, struct ip *);
1927 	}
1928 #endif /* ALTQ */
1929 
1930 	switch (af) {
1931 #ifdef INET
1932 	case AF_INET:
1933 		icmp_error(m0, type, code, 0, 0);
1934 		break;
1935 #endif /* INET */
1936 #ifdef INET6
1937 	case AF_INET6:
1938 		icmp6_error(m0, type, code, 0);
1939 		break;
1940 #endif /* INET6 */
1941 	}
1942 }
1943 
1944 /*
1945  * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
1946  * If n is 0, they match if they are equal. If n is != 0, they match if they
1947  * are different.
1948  */
1949 int
1950 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
1951     struct pf_addr *b, sa_family_t af)
1952 {
1953 	int	match = 0;
1954 
1955 	switch (af) {
1956 #ifdef INET
1957 	case AF_INET:
1958 		if ((a->addr32[0] & m->addr32[0]) ==
1959 		    (b->addr32[0] & m->addr32[0]))
1960 			match++;
1961 		break;
1962 #endif /* INET */
1963 #ifdef INET6
1964 	case AF_INET6:
1965 		if (((a->addr32[0] & m->addr32[0]) ==
1966 		     (b->addr32[0] & m->addr32[0])) &&
1967 		    ((a->addr32[1] & m->addr32[1]) ==
1968 		     (b->addr32[1] & m->addr32[1])) &&
1969 		    ((a->addr32[2] & m->addr32[2]) ==
1970 		     (b->addr32[2] & m->addr32[2])) &&
1971 		    ((a->addr32[3] & m->addr32[3]) ==
1972 		     (b->addr32[3] & m->addr32[3])))
1973 			match++;
1974 		break;
1975 #endif /* INET6 */
1976 	}
1977 	if (match) {
1978 		if (n)
1979 			return (0);
1980 		else
1981 			return (1);
1982 	} else {
1983 		if (n)
1984 			return (1);
1985 		else
1986 			return (0);
1987 	}
1988 }
1989 
1990 /*
1991  * Return 1 if b <= a <= e, otherwise return 0.
1992  */
1993 int
1994 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
1995     struct pf_addr *a, sa_family_t af)
1996 {
1997 	switch (af) {
1998 #ifdef INET
1999 	case AF_INET:
2000 		if ((a->addr32[0] < b->addr32[0]) ||
2001 		    (a->addr32[0] > e->addr32[0]))
2002 			return (0);
2003 		break;
2004 #endif /* INET */
2005 #ifdef INET6
2006 	case AF_INET6: {
2007 		int	i;
2008 
2009 		/* check a >= b */
2010 		for (i = 0; i < 4; ++i)
2011 			if (a->addr32[i] > b->addr32[i])
2012 				break;
2013 			else if (a->addr32[i] < b->addr32[i])
2014 				return (0);
2015 		/* check a <= e */
2016 		for (i = 0; i < 4; ++i)
2017 			if (a->addr32[i] < e->addr32[i])
2018 				break;
2019 			else if (a->addr32[i] > e->addr32[i])
2020 				return (0);
2021 		break;
2022 	}
2023 #endif /* INET6 */
2024 	}
2025 	return (1);
2026 }
2027 
2028 int
2029 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2030 {
2031 	switch (op) {
2032 	case PF_OP_IRG:
2033 		return ((p > a1) && (p < a2));
2034 	case PF_OP_XRG:
2035 		return ((p < a1) || (p > a2));
2036 	case PF_OP_RRG:
2037 		return ((p >= a1) && (p <= a2));
2038 	case PF_OP_EQ:
2039 		return (p == a1);
2040 	case PF_OP_NE:
2041 		return (p != a1);
2042 	case PF_OP_LT:
2043 		return (p < a1);
2044 	case PF_OP_LE:
2045 		return (p <= a1);
2046 	case PF_OP_GT:
2047 		return (p > a1);
2048 	case PF_OP_GE:
2049 		return (p >= a1);
2050 	}
2051 	return (0); /* never reached */
2052 }
2053 
2054 int
2055 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2056 {
2057 	a1 = ntohs(a1);
2058 	a2 = ntohs(a2);
2059 	p = ntohs(p);
2060 	return (pf_match(op, a1, a2, p));
2061 }
2062 
2063 int
2064 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2065 {
2066 	if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2067 		return (0);
2068 	return (pf_match(op, a1, a2, u));
2069 }
2070 
2071 int
2072 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2073 {
2074 	if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2075 		return (0);
2076 	return (pf_match(op, a1, a2, g));
2077 }
2078 
2079 int
2080 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag)
2081 {
2082 	if (*tag == -1)
2083 		*tag = m->m_pkthdr.pf.tag;
2084 
2085 	return ((!r->match_tag_not && r->match_tag == *tag) ||
2086 	    (r->match_tag_not && r->match_tag != *tag));
2087 }
2088 
2089 int
2090 pf_tag_packet(struct mbuf *m, int tag, int rtableid)
2091 {
2092 	if (tag <= 0 && rtableid < 0)
2093 		return (0);
2094 
2095 	if (tag > 0)
2096 		m->m_pkthdr.pf.tag = tag;
2097 	if (rtableid >= 0)
2098 		m->m_pkthdr.pf.rtableid = rtableid;
2099 
2100 	return (0);
2101 }
2102 
2103 void
2104 pf_step_into_anchor(int *depth, struct pf_ruleset **rs, int n,
2105     struct pf_rule **r, struct pf_rule **a, int *match)
2106 {
2107 	struct pf_anchor_stackframe	*f;
2108 
2109 	(*r)->anchor->match = 0;
2110 	if (match)
2111 		*match = 0;
2112 	if (*depth >= NELEM(pf_anchor_stack)) {
2113 		kprintf("pf_step_into_anchor: stack overflow\n");
2114 		*r = TAILQ_NEXT(*r, entries);
2115 		return;
2116 	} else if (*depth == 0 && a != NULL)
2117 		*a = *r;
2118 	f = pf_anchor_stack + (*depth)++;
2119 	f->rs = *rs;
2120 	f->r = *r;
2121 	if ((*r)->anchor_wildcard) {
2122 		f->parent = &(*r)->anchor->children;
2123 		if ((f->child = RB_MIN(pf_anchor_node, f->parent)) ==
2124 		    NULL) {
2125 			*r = NULL;
2126 			return;
2127 		}
2128 		*rs = &f->child->ruleset;
2129 	} else {
2130 		f->parent = NULL;
2131 		f->child = NULL;
2132 		*rs = &(*r)->anchor->ruleset;
2133 	}
2134 	*r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2135 }
2136 
2137 int
2138 pf_step_out_of_anchor(int *depth, struct pf_ruleset **rs, int n,
2139     struct pf_rule **r, struct pf_rule **a, int *match)
2140 {
2141 	struct pf_anchor_stackframe	*f;
2142 	int quick = 0;
2143 
2144 	do {
2145 		if (*depth <= 0)
2146 			break;
2147 		f = pf_anchor_stack + *depth - 1;
2148 		if (f->parent != NULL && f->child != NULL) {
2149 			if (f->child->match ||
2150 			    (match != NULL && *match)) {
2151 				f->r->anchor->match = 1;
2152 				*match = 0;
2153 			}
2154 			f->child = RB_NEXT(pf_anchor_node, f->parent, f->child);
2155 			if (f->child != NULL) {
2156 				*rs = &f->child->ruleset;
2157 				*r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2158 				if (*r == NULL)
2159 					continue;
2160 				else
2161 					break;
2162 			}
2163 		}
2164 		(*depth)--;
2165 		if (*depth == 0 && a != NULL)
2166 			*a = NULL;
2167 		*rs = f->rs;
2168 		if (f->r->anchor->match || (match != NULL && *match))
2169 			quick = f->r->quick;
2170 		*r = TAILQ_NEXT(f->r, entries);
2171 	} while (*r == NULL);
2172 
2173 	return (quick);
2174 }
2175 
2176 #ifdef INET6
2177 void
2178 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2179     struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2180 {
2181 	switch (af) {
2182 #ifdef INET
2183 	case AF_INET:
2184 		naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2185 		((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2186 		break;
2187 #endif /* INET */
2188 	case AF_INET6:
2189 		naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2190 		((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2191 		naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2192 		((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2193 		naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2194 		((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2195 		naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2196 		((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2197 		break;
2198 	}
2199 }
2200 
2201 void
2202 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2203 {
2204 	switch (af) {
2205 #ifdef INET
2206 	case AF_INET:
2207 		addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2208 		break;
2209 #endif /* INET */
2210 	case AF_INET6:
2211 		if (addr->addr32[3] == 0xffffffff) {
2212 			addr->addr32[3] = 0;
2213 			if (addr->addr32[2] == 0xffffffff) {
2214 				addr->addr32[2] = 0;
2215 				if (addr->addr32[1] == 0xffffffff) {
2216 					addr->addr32[1] = 0;
2217 					addr->addr32[0] =
2218 					    htonl(ntohl(addr->addr32[0]) + 1);
2219 				} else
2220 					addr->addr32[1] =
2221 					    htonl(ntohl(addr->addr32[1]) + 1);
2222 			} else
2223 				addr->addr32[2] =
2224 				    htonl(ntohl(addr->addr32[2]) + 1);
2225 		} else
2226 			addr->addr32[3] =
2227 			    htonl(ntohl(addr->addr32[3]) + 1);
2228 		break;
2229 	}
2230 }
2231 #endif /* INET6 */
2232 
2233 #define mix(a,b,c) \
2234 	do {					\
2235 		a -= b; a -= c; a ^= (c >> 13);	\
2236 		b -= c; b -= a; b ^= (a << 8);	\
2237 		c -= a; c -= b; c ^= (b >> 13);	\
2238 		a -= b; a -= c; a ^= (c >> 12);	\
2239 		b -= c; b -= a; b ^= (a << 16);	\
2240 		c -= a; c -= b; c ^= (b >> 5);	\
2241 		a -= b; a -= c; a ^= (c >> 3);	\
2242 		b -= c; b -= a; b ^= (a << 10);	\
2243 		c -= a; c -= b; c ^= (b >> 15);	\
2244 	} while (0)
2245 
2246 /*
2247  * hash function based on bridge_hash in if_bridge.c
2248  */
2249 void
2250 pf_hash(struct pf_addr *inaddr, struct pf_addr *hash,
2251     struct pf_poolhashkey *key, sa_family_t af)
2252 {
2253 	u_int32_t	a = 0x9e3779b9, b = 0x9e3779b9, c = key->key32[0];
2254 
2255 	switch (af) {
2256 #ifdef INET
2257 	case AF_INET:
2258 		a += inaddr->addr32[0];
2259 		b += key->key32[1];
2260 		mix(a, b, c);
2261 		hash->addr32[0] = c + key->key32[2];
2262 		break;
2263 #endif /* INET */
2264 #ifdef INET6
2265 	case AF_INET6:
2266 		a += inaddr->addr32[0];
2267 		b += inaddr->addr32[2];
2268 		mix(a, b, c);
2269 		hash->addr32[0] = c;
2270 		a += inaddr->addr32[1];
2271 		b += inaddr->addr32[3];
2272 		c += key->key32[1];
2273 		mix(a, b, c);
2274 		hash->addr32[1] = c;
2275 		a += inaddr->addr32[2];
2276 		b += inaddr->addr32[1];
2277 		c += key->key32[2];
2278 		mix(a, b, c);
2279 		hash->addr32[2] = c;
2280 		a += inaddr->addr32[3];
2281 		b += inaddr->addr32[0];
2282 		c += key->key32[3];
2283 		mix(a, b, c);
2284 		hash->addr32[3] = c;
2285 		break;
2286 #endif /* INET6 */
2287 	}
2288 }
2289 
2290 int
2291 pf_map_addr(sa_family_t af, struct pf_rule *r, struct pf_addr *saddr,
2292     struct pf_addr *naddr, struct pf_addr *init_addr, struct pf_src_node **sn)
2293 {
2294 	unsigned char		 hash[16];
2295 	struct pf_pool		*rpool = &r->rpool;
2296 	struct pf_addr		*raddr = &rpool->cur->addr.v.a.addr;
2297 	struct pf_addr		*rmask = &rpool->cur->addr.v.a.mask;
2298 	struct pf_pooladdr	*acur = rpool->cur;
2299 	struct pf_src_node	 k;
2300 
2301 	if (*sn == NULL && r->rpool.opts & PF_POOL_STICKYADDR &&
2302 	    (r->rpool.opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
2303 		k.af = af;
2304 		PF_ACPY(&k.addr, saddr, af);
2305 		if (r->rule_flag & PFRULE_RULESRCTRACK ||
2306 		    r->rpool.opts & PF_POOL_STICKYADDR)
2307 			k.rule.ptr = r;
2308 		else
2309 			k.rule.ptr = NULL;
2310 		pf_status.scounters[SCNT_SRC_NODE_SEARCH]++;
2311 		*sn = RB_FIND(pf_src_tree, &tree_src_tracking, &k);
2312 		if (*sn != NULL && !PF_AZERO(&(*sn)->raddr, af)) {
2313 			PF_ACPY(naddr, &(*sn)->raddr, af);
2314 			if (pf_status.debug >= PF_DEBUG_MISC) {
2315 				kprintf("pf_map_addr: src tracking maps ");
2316 				pf_print_host(&k.addr, 0, af);
2317 				kprintf(" to ");
2318 				pf_print_host(naddr, 0, af);
2319 				kprintf("\n");
2320 			}
2321 			return (0);
2322 		}
2323 	}
2324 
2325 	if (rpool->cur->addr.type == PF_ADDR_NOROUTE)
2326 		return (1);
2327 	if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
2328 		switch (af) {
2329 #ifdef INET
2330 		case AF_INET:
2331 			if (rpool->cur->addr.p.dyn->pfid_acnt4 < 1 &&
2332 			    (rpool->opts & PF_POOL_TYPEMASK) !=
2333 			    PF_POOL_ROUNDROBIN)
2334 				return (1);
2335 			raddr = &rpool->cur->addr.p.dyn->pfid_addr4;
2336 			rmask = &rpool->cur->addr.p.dyn->pfid_mask4;
2337 			break;
2338 #endif /* INET */
2339 #ifdef INET6
2340 		case AF_INET6:
2341 			if (rpool->cur->addr.p.dyn->pfid_acnt6 < 1 &&
2342 			    (rpool->opts & PF_POOL_TYPEMASK) !=
2343 			    PF_POOL_ROUNDROBIN)
2344 				return (1);
2345 			raddr = &rpool->cur->addr.p.dyn->pfid_addr6;
2346 			rmask = &rpool->cur->addr.p.dyn->pfid_mask6;
2347 			break;
2348 #endif /* INET6 */
2349 		}
2350 	} else if (rpool->cur->addr.type == PF_ADDR_TABLE) {
2351 		if ((rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_ROUNDROBIN)
2352 			return (1); /* unsupported */
2353 	} else {
2354 		raddr = &rpool->cur->addr.v.a.addr;
2355 		rmask = &rpool->cur->addr.v.a.mask;
2356 	}
2357 
2358 	switch (rpool->opts & PF_POOL_TYPEMASK) {
2359 	case PF_POOL_NONE:
2360 		PF_ACPY(naddr, raddr, af);
2361 		break;
2362 	case PF_POOL_BITMASK:
2363 		PF_POOLMASK(naddr, raddr, rmask, saddr, af);
2364 		break;
2365 	case PF_POOL_RANDOM:
2366 		if (init_addr != NULL && PF_AZERO(init_addr, af)) {
2367 			switch (af) {
2368 #ifdef INET
2369 			case AF_INET:
2370 				rpool->counter.addr32[0] = htonl(karc4random());
2371 				break;
2372 #endif /* INET */
2373 #ifdef INET6
2374 			case AF_INET6:
2375 				if (rmask->addr32[3] != 0xffffffff)
2376 					rpool->counter.addr32[3] =
2377 					    htonl(karc4random());
2378 				else
2379 					break;
2380 				if (rmask->addr32[2] != 0xffffffff)
2381 					rpool->counter.addr32[2] =
2382 					    htonl(karc4random());
2383 				else
2384 					break;
2385 				if (rmask->addr32[1] != 0xffffffff)
2386 					rpool->counter.addr32[1] =
2387 					    htonl(karc4random());
2388 				else
2389 					break;
2390 				if (rmask->addr32[0] != 0xffffffff)
2391 					rpool->counter.addr32[0] =
2392 					    htonl(karc4random());
2393 				break;
2394 #endif /* INET6 */
2395 			}
2396 			PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
2397 			PF_ACPY(init_addr, naddr, af);
2398 
2399 		} else {
2400 			PF_AINC(&rpool->counter, af);
2401 			PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
2402 		}
2403 		break;
2404 	case PF_POOL_SRCHASH:
2405 		pf_hash(saddr, (struct pf_addr *)&hash, &rpool->key, af);
2406 		PF_POOLMASK(naddr, raddr, rmask, (struct pf_addr *)&hash, af);
2407 		break;
2408 	case PF_POOL_ROUNDROBIN:
2409 		if (rpool->cur->addr.type == PF_ADDR_TABLE) {
2410 			if (!pfr_pool_get(rpool->cur->addr.p.tbl,
2411 			    &rpool->tblidx, &rpool->counter,
2412 			    &raddr, &rmask, af))
2413 				goto get_addr;
2414 		} else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
2415 			if (!pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
2416 			    &rpool->tblidx, &rpool->counter,
2417 			    &raddr, &rmask, af))
2418 				goto get_addr;
2419 		} else if (pf_match_addr(0, raddr, rmask, &rpool->counter, af))
2420 			goto get_addr;
2421 
2422 	try_next:
2423 		if ((rpool->cur = TAILQ_NEXT(rpool->cur, entries)) == NULL)
2424 			rpool->cur = TAILQ_FIRST(&rpool->list);
2425 		if (rpool->cur->addr.type == PF_ADDR_TABLE) {
2426 			rpool->tblidx = -1;
2427 			if (pfr_pool_get(rpool->cur->addr.p.tbl,
2428 			    &rpool->tblidx, &rpool->counter,
2429 			    &raddr, &rmask, af)) {
2430 				/* table contains no address of type 'af' */
2431 				if (rpool->cur != acur)
2432 					goto try_next;
2433 				return (1);
2434 			}
2435 		} else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
2436 			rpool->tblidx = -1;
2437 			if (pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
2438 			    &rpool->tblidx, &rpool->counter,
2439 			    &raddr, &rmask, af)) {
2440 				/* table contains no address of type 'af' */
2441 				if (rpool->cur != acur)
2442 					goto try_next;
2443 				return (1);
2444 			}
2445 		} else {
2446 			raddr = &rpool->cur->addr.v.a.addr;
2447 			rmask = &rpool->cur->addr.v.a.mask;
2448 			PF_ACPY(&rpool->counter, raddr, af);
2449 		}
2450 
2451 	get_addr:
2452 		PF_ACPY(naddr, &rpool->counter, af);
2453 		if (init_addr != NULL && PF_AZERO(init_addr, af))
2454 			PF_ACPY(init_addr, naddr, af);
2455 		PF_AINC(&rpool->counter, af);
2456 		break;
2457 	}
2458 	if (*sn != NULL)
2459 		PF_ACPY(&(*sn)->raddr, naddr, af);
2460 
2461 	if (pf_status.debug >= PF_DEBUG_MISC &&
2462 	    (rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
2463 		kprintf("pf_map_addr: selected address ");
2464 		pf_print_host(naddr, 0, af);
2465 		kprintf("\n");
2466 	}
2467 
2468 	return (0);
2469 }
2470 
2471 int
2472 pf_get_sport(sa_family_t af, u_int8_t proto, struct pf_rule *r,
2473     struct pf_addr *saddr, struct pf_addr *daddr, u_int16_t dport,
2474     struct pf_addr *naddr, u_int16_t *nport, u_int16_t low, u_int16_t high,
2475     struct pf_src_node **sn)
2476 {
2477 	struct pf_state_key_cmp	key;
2478 	struct pf_addr		init_addr;
2479 	u_int16_t		cut;
2480 
2481 	bzero(&init_addr, sizeof(init_addr));
2482 	if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
2483 		return (1);
2484 
2485 	if (proto == IPPROTO_ICMP) {
2486 		low = 1;
2487 		high = 65535;
2488 	}
2489 
2490 	do {
2491 		key.af = af;
2492 		key.proto = proto;
2493 		PF_ACPY(&key.addr[1], daddr, key.af);
2494 		PF_ACPY(&key.addr[0], naddr, key.af);
2495 		key.port[1] = dport;
2496 
2497 		/*
2498 		 * port search; start random, step;
2499 		 * similar 2 portloop in in_pcbbind
2500 		 */
2501 		if (!(proto == IPPROTO_TCP || proto == IPPROTO_UDP ||
2502 		    proto == IPPROTO_ICMP)) {
2503 			key.port[0] = dport;
2504 			if (pf_find_state_all(&key, PF_IN, NULL) == NULL)
2505 				return (0);
2506 		} else if (low == 0 && high == 0) {
2507 			key.port[0] = *nport;
2508 			if (pf_find_state_all(&key, PF_IN, NULL) == NULL)
2509 				return (0);
2510 		} else if (low == high) {
2511 			key.port[0] = htons(low);
2512 			if (pf_find_state_all(&key, PF_IN, NULL) == NULL) {
2513 				*nport = htons(low);
2514 				return (0);
2515 			}
2516 		} else {
2517 			u_int16_t tmp;
2518 
2519 			if (low > high) {
2520 				tmp = low;
2521 				low = high;
2522 				high = tmp;
2523 			}
2524 			/* low < high */
2525 			cut = htonl(karc4random()) % (1 + high - low) + low;
2526 			/* low <= cut <= high */
2527 			for (tmp = cut; tmp <= high; ++(tmp)) {
2528 				key.port[0] = htons(tmp);
2529 				if (pf_find_state_all(&key, PF_IN, NULL) ==
2530 				    NULL && !in_baddynamic(tmp, proto)) {
2531 					*nport = htons(tmp);
2532 					return (0);
2533 				}
2534 			}
2535 			for (tmp = cut - 1; tmp >= low; --(tmp)) {
2536 				key.port[0] = htons(tmp);
2537 				if (pf_find_state_all(&key, PF_IN, NULL) ==
2538 				    NULL && !in_baddynamic(tmp, proto)) {
2539 					*nport = htons(tmp);
2540 					return (0);
2541 				}
2542 			}
2543 		}
2544 
2545 		switch (r->rpool.opts & PF_POOL_TYPEMASK) {
2546 		case PF_POOL_RANDOM:
2547 		case PF_POOL_ROUNDROBIN:
2548 			if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
2549 				return (1);
2550 			break;
2551 		case PF_POOL_NONE:
2552 		case PF_POOL_SRCHASH:
2553 		case PF_POOL_BITMASK:
2554 		default:
2555 			return (1);
2556 		}
2557 	} while (! PF_AEQ(&init_addr, naddr, af) );
2558 	return (1);					/* none available */
2559 }
2560 
2561 struct pf_rule *
2562 pf_match_translation(struct pf_pdesc *pd, struct mbuf *m, int off,
2563     int direction, struct pfi_kif *kif, struct pf_addr *saddr, u_int16_t sport,
2564     struct pf_addr *daddr, u_int16_t dport, int rs_num)
2565 {
2566 	struct pf_rule		*r, *rm = NULL;
2567 	struct pf_ruleset	*ruleset = NULL;
2568 	int			 tag = -1;
2569 	int			 rtableid = -1;
2570 	int			 asd = 0;
2571 
2572 	r = TAILQ_FIRST(pf_main_ruleset.rules[rs_num].active.ptr);
2573 	while (r && rm == NULL) {
2574 		struct pf_rule_addr	*src = NULL, *dst = NULL;
2575 		struct pf_addr_wrap	*xdst = NULL;
2576 
2577 		if (r->action == PF_BINAT && direction == PF_IN) {
2578 			src = &r->dst;
2579 			if (r->rpool.cur != NULL)
2580 				xdst = &r->rpool.cur->addr;
2581 		} else {
2582 			src = &r->src;
2583 			dst = &r->dst;
2584 		}
2585 
2586 		r->evaluations++;
2587 		if (pfi_kif_match(r->kif, kif) == r->ifnot)
2588 			r = r->skip[PF_SKIP_IFP].ptr;
2589 		else if (r->direction && r->direction != direction)
2590 			r = r->skip[PF_SKIP_DIR].ptr;
2591 		else if (r->af && r->af != pd->af)
2592 			r = r->skip[PF_SKIP_AF].ptr;
2593 		else if (r->proto && r->proto != pd->proto)
2594 			r = r->skip[PF_SKIP_PROTO].ptr;
2595 		else if (PF_MISMATCHAW(&src->addr, saddr, pd->af,
2596 		    src->neg, kif))
2597 			r = r->skip[src == &r->src ? PF_SKIP_SRC_ADDR :
2598 			    PF_SKIP_DST_ADDR].ptr;
2599 		else if (src->port_op && !pf_match_port(src->port_op,
2600 		    src->port[0], src->port[1], sport))
2601 			r = r->skip[src == &r->src ? PF_SKIP_SRC_PORT :
2602 			    PF_SKIP_DST_PORT].ptr;
2603 		else if (dst != NULL &&
2604 		    PF_MISMATCHAW(&dst->addr, daddr, pd->af, dst->neg, NULL))
2605 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
2606 		else if (xdst != NULL && PF_MISMATCHAW(xdst, daddr, pd->af,
2607 		    0, NULL))
2608 			r = TAILQ_NEXT(r, entries);
2609 		else if (dst != NULL && dst->port_op &&
2610 		    !pf_match_port(dst->port_op, dst->port[0],
2611 		    dst->port[1], dport))
2612 			r = r->skip[PF_SKIP_DST_PORT].ptr;
2613 		else if (r->match_tag && !pf_match_tag(m, r, &tag))
2614 			r = TAILQ_NEXT(r, entries);
2615 		else if (r->os_fingerprint != PF_OSFP_ANY && (pd->proto !=
2616 		    IPPROTO_TCP || !pf_osfp_match(pf_osfp_fingerprint(pd, m,
2617 		    off, pd->hdr.tcp), r->os_fingerprint)))
2618 			r = TAILQ_NEXT(r, entries);
2619 		else {
2620 			if (r->tag)
2621 				tag = r->tag;
2622 			if (r->rtableid >= 0)
2623 				rtableid = r->rtableid;
2624 			if (r->anchor == NULL) {
2625 				rm = r;
2626 			} else
2627 				pf_step_into_anchor(&asd, &ruleset, rs_num,
2628 				    &r, NULL, NULL);
2629 		}
2630 		if (r == NULL)
2631 			pf_step_out_of_anchor(&asd, &ruleset, rs_num, &r,
2632 			    NULL, NULL);
2633 	}
2634 	if (pf_tag_packet(m, tag, rtableid))
2635 		return (NULL);
2636 	if (rm != NULL && (rm->action == PF_NONAT ||
2637 	    rm->action == PF_NORDR || rm->action == PF_NOBINAT))
2638 		return (NULL);
2639 	return (rm);
2640 }
2641 
2642 struct pf_rule *
2643 pf_get_translation(struct pf_pdesc *pd, struct mbuf *m, int off, int direction,
2644     struct pfi_kif *kif, struct pf_src_node **sn,
2645     struct pf_state_key **skw, struct pf_state_key **sks,
2646     struct pf_state_key **skp, struct pf_state_key **nkp,
2647     struct pf_addr *saddr, struct pf_addr *daddr,
2648     u_int16_t sport, u_int16_t dport)
2649 {
2650 	struct pf_rule	*r = NULL;
2651 
2652 
2653 	if (direction == PF_OUT) {
2654 		r = pf_match_translation(pd, m, off, direction, kif, saddr,
2655 		    sport, daddr, dport, PF_RULESET_BINAT);
2656 		if (r == NULL)
2657 			r = pf_match_translation(pd, m, off, direction, kif,
2658 			    saddr, sport, daddr, dport, PF_RULESET_NAT);
2659 	} else {
2660 		r = pf_match_translation(pd, m, off, direction, kif, saddr,
2661 		    sport, daddr, dport, PF_RULESET_RDR);
2662 		if (r == NULL)
2663 			r = pf_match_translation(pd, m, off, direction, kif,
2664 			    saddr, sport, daddr, dport, PF_RULESET_BINAT);
2665 	}
2666 
2667 	if (r != NULL) {
2668 		struct pf_addr	*naddr;
2669 		u_int16_t	*nport;
2670 
2671 		if (pf_state_key_setup(pd, r, skw, sks, skp, nkp,
2672 		    saddr, daddr, sport, dport))
2673 			return r;
2674 
2675 		/* XXX We only modify one side for now. */
2676 		naddr = &(*nkp)->addr[1];
2677 		nport = &(*nkp)->port[1];
2678 
2679 		/*
2680 		 * NOTE: Currently all translations will clear
2681 		 *	 BRIDGE_MBUF_TAGGED, telling the bridge to
2682 		 *	 ignore the original input encapsulation.
2683 		 */
2684 		switch (r->action) {
2685 		case PF_NONAT:
2686 		case PF_NOBINAT:
2687 		case PF_NORDR:
2688 			return (NULL);
2689 		case PF_NAT:
2690 			m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
2691 			if (pf_get_sport(pd->af, pd->proto, r, saddr,
2692 			    daddr, dport, naddr, nport, r->rpool.proxy_port[0],
2693 			    r->rpool.proxy_port[1], sn)) {
2694 				DPFPRINTF(PF_DEBUG_MISC,
2695 				    ("pf: NAT proxy port allocation "
2696 				    "(%u-%u) failed\n",
2697 				    r->rpool.proxy_port[0],
2698 				    r->rpool.proxy_port[1]));
2699 				return (NULL);
2700 			}
2701 			break;
2702 		case PF_BINAT:
2703 			m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
2704 			switch (direction) {
2705 			case PF_OUT:
2706 				if (r->rpool.cur->addr.type == PF_ADDR_DYNIFTL){
2707 					switch (pd->af) {
2708 #ifdef INET
2709 					case AF_INET:
2710 						if (r->rpool.cur->addr.p.dyn->
2711 						    pfid_acnt4 < 1)
2712 							return (NULL);
2713 						PF_POOLMASK(naddr,
2714 						    &r->rpool.cur->addr.p.dyn->
2715 						    pfid_addr4,
2716 						    &r->rpool.cur->addr.p.dyn->
2717 						    pfid_mask4,
2718 						    saddr, AF_INET);
2719 						break;
2720 #endif /* INET */
2721 #ifdef INET6
2722 					case AF_INET6:
2723 						if (r->rpool.cur->addr.p.dyn->
2724 						    pfid_acnt6 < 1)
2725 							return (NULL);
2726 						PF_POOLMASK(naddr,
2727 						    &r->rpool.cur->addr.p.dyn->
2728 						    pfid_addr6,
2729 						    &r->rpool.cur->addr.p.dyn->
2730 						    pfid_mask6,
2731 						    saddr, AF_INET6);
2732 						break;
2733 #endif /* INET6 */
2734 					}
2735 				} else
2736 					PF_POOLMASK(naddr,
2737 					    &r->rpool.cur->addr.v.a.addr,
2738 					    &r->rpool.cur->addr.v.a.mask,
2739 					    saddr, pd->af);
2740 				break;
2741 			case PF_IN:
2742 				if (r->src.addr.type == PF_ADDR_DYNIFTL) {
2743 					switch (pd->af) {
2744 #ifdef INET
2745 					case AF_INET:
2746 						if (r->src.addr.p.dyn->
2747 						    pfid_acnt4 < 1)
2748 							return (NULL);
2749 						PF_POOLMASK(naddr,
2750 						    &r->src.addr.p.dyn->
2751 						    pfid_addr4,
2752 						    &r->src.addr.p.dyn->
2753 						    pfid_mask4,
2754 						    daddr, AF_INET);
2755 						break;
2756 #endif /* INET */
2757 #ifdef INET6
2758 					case AF_INET6:
2759 						if (r->src.addr.p.dyn->
2760 						    pfid_acnt6 < 1)
2761 							return (NULL);
2762 						PF_POOLMASK(naddr,
2763 						    &r->src.addr.p.dyn->
2764 						    pfid_addr6,
2765 						    &r->src.addr.p.dyn->
2766 						    pfid_mask6,
2767 						    daddr, AF_INET6);
2768 						break;
2769 #endif /* INET6 */
2770 					}
2771 				} else
2772 					PF_POOLMASK(naddr,
2773 					    &r->src.addr.v.a.addr,
2774 					    &r->src.addr.v.a.mask, daddr,
2775 					    pd->af);
2776 				break;
2777 			}
2778 			break;
2779 		case PF_RDR: {
2780 			m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
2781 			if (pf_map_addr(pd->af, r, saddr, naddr, NULL, sn))
2782 				return (NULL);
2783 			if ((r->rpool.opts & PF_POOL_TYPEMASK) ==
2784 			    PF_POOL_BITMASK)
2785 				PF_POOLMASK(naddr, naddr,
2786 				    &r->rpool.cur->addr.v.a.mask, daddr,
2787 				    pd->af);
2788 
2789 			if (r->rpool.proxy_port[1]) {
2790 				u_int32_t	tmp_nport;
2791 
2792 				tmp_nport = ((ntohs(dport) -
2793 				    ntohs(r->dst.port[0])) %
2794 				    (r->rpool.proxy_port[1] -
2795 				    r->rpool.proxy_port[0] + 1)) +
2796 				    r->rpool.proxy_port[0];
2797 
2798 				/* wrap around if necessary */
2799 				if (tmp_nport > 65535)
2800 					tmp_nport -= 65535;
2801 				*nport = htons((u_int16_t)tmp_nport);
2802 			} else if (r->rpool.proxy_port[0])
2803 				*nport = htons(r->rpool.proxy_port[0]);
2804 			break;
2805 		}
2806 		default:
2807 			return (NULL);
2808 		}
2809 	}
2810 
2811 	return (r);
2812 }
2813 
2814 struct netmsg_hashlookup {
2815 	struct netmsg_base	base;
2816 	struct inpcb		**nm_pinp;
2817 	struct inpcbinfo    	*nm_pcbinfo;
2818 	struct pf_addr		*nm_saddr;
2819 	struct pf_addr		*nm_daddr;
2820 	uint16_t		nm_sport;
2821 	uint16_t		nm_dport;
2822 	sa_family_t		nm_af;
2823 };
2824 
2825 #ifdef PF_SOCKET_LOOKUP_DOMSG
2826 static void
2827 in_pcblookup_hash_handler(netmsg_t msg)
2828 {
2829 	struct netmsg_hashlookup *rmsg = (struct netmsg_hashlookup *)msg;
2830 
2831 	if (rmsg->nm_af == AF_INET)
2832 		*rmsg->nm_pinp = in_pcblookup_hash(rmsg->nm_pcbinfo,
2833 		    rmsg->nm_saddr->v4, rmsg->nm_sport, rmsg->nm_daddr->v4,
2834 		    rmsg->nm_dport, INPLOOKUP_WILDCARD, NULL);
2835 #ifdef INET6
2836 	else
2837 		*rmsg->nm_pinp = in6_pcblookup_hash(rmsg->nm_pcbinfo,
2838 		    &rmsg->nm_saddr->v6, rmsg->nm_sport, &rmsg->nm_daddr->v6,
2839 		    rmsg->nm_dport, INPLOOKUP_WILDCARD, NULL);
2840 #endif /* INET6 */
2841 	lwkt_replymsg(&rmsg->base.lmsg, 0);
2842 }
2843 #endif	/* PF_SOCKET_LOOKUP_DOMSG */
2844 
2845 int
2846 pf_socket_lookup(int direction, struct pf_pdesc *pd)
2847 {
2848 	struct pf_addr		*saddr, *daddr;
2849 	u_int16_t		 sport, dport;
2850 	struct inpcbinfo	*pi;
2851 	struct inpcb		*inp;
2852 	struct netmsg_hashlookup *msg = NULL;
2853 #ifdef PF_SOCKET_LOOKUP_DOMSG
2854 	struct netmsg_hashlookup msg0;
2855 #endif
2856 	int			 pi_cpu = 0;
2857 
2858 	if (pd == NULL)
2859 		return (-1);
2860 	pd->lookup.uid = UID_MAX;
2861 	pd->lookup.gid = GID_MAX;
2862 	pd->lookup.pid = NO_PID;
2863 	if (direction == PF_IN) {
2864 		saddr = pd->src;
2865 		daddr = pd->dst;
2866 	} else {
2867 		saddr = pd->dst;
2868 		daddr = pd->src;
2869 	}
2870 	switch (pd->proto) {
2871 	case IPPROTO_TCP:
2872 		if (pd->hdr.tcp == NULL)
2873 			return (-1);
2874 		sport = pd->hdr.tcp->th_sport;
2875 		dport = pd->hdr.tcp->th_dport;
2876 
2877 		pi_cpu = tcp_addrcpu(saddr->v4.s_addr, sport, daddr->v4.s_addr, dport);
2878 		pi = &tcbinfo[pi_cpu];
2879 		/*
2880 		 * Our netstack runs lockless on MP systems
2881 		 * (only for TCP connections at the moment).
2882 		 *
2883 		 * As we are not allowed to read another CPU's tcbinfo,
2884 		 * we have to ask that CPU via remote call to search the
2885 		 * table for us.
2886 		 *
2887 		 * Prepare a msg iff data belongs to another CPU.
2888 		 */
2889 		if (pi_cpu != mycpu->gd_cpuid) {
2890 #ifdef PF_SOCKET_LOOKUP_DOMSG
2891 			/*
2892 			 * NOTE:
2893 			 *
2894 			 * Following lwkt_domsg() is dangerous and could
2895 			 * lockup the network system, e.g.
2896 			 *
2897 			 * On 2 CPU system:
2898 			 * netisr0 domsg to netisr1 (due to lookup)
2899 			 * netisr1 domsg to netisr0 (due to lookup)
2900 			 *
2901 			 * We simply return -1 here, since we are probably
2902 			 * called before NAT, so the TCP packet should
2903 			 * already be on the correct CPU.
2904 			 */
2905 			msg = &msg0;
2906 			netmsg_init(&msg->base, NULL, &curthread->td_msgport,
2907 				    0, in_pcblookup_hash_handler);
2908 			msg->nm_pinp = &inp;
2909 			msg->nm_pcbinfo = pi;
2910 			msg->nm_saddr = saddr;
2911 			msg->nm_sport = sport;
2912 			msg->nm_daddr = daddr;
2913 			msg->nm_dport = dport;
2914 			msg->nm_af = pd->af;
2915 #else	/* !PF_SOCKET_LOOKUP_DOMSG */
2916 			kprintf("pf_socket_lookup: tcp packet not on the "
2917 				"correct cpu %d, cur cpu %d\n",
2918 				pi_cpu, mycpuid);
2919 			print_backtrace(-1);
2920 			return -1;
2921 #endif	/* PF_SOCKET_LOOKUP_DOMSG */
2922 		}
2923 		break;
2924 	case IPPROTO_UDP:
2925 		if (pd->hdr.udp == NULL)
2926 			return (-1);
2927 		sport = pd->hdr.udp->uh_sport;
2928 		dport = pd->hdr.udp->uh_dport;
2929 		pi = &udbinfo;
2930 		break;
2931 	default:
2932 		return (-1);
2933 	}
2934 	if (direction != PF_IN) {
2935 		u_int16_t	p;
2936 
2937 		p = sport;
2938 		sport = dport;
2939 		dport = p;
2940 	}
2941 	switch (pd->af) {
2942 #ifdef INET6
2943 	case AF_INET6:
2944 		/*
2945 		 * Query other CPU, second part
2946 		 *
2947 		 * msg only gets initialized when:
2948 		 * 1) packet is TCP
2949 		 * 2) the info belongs to another CPU
2950 		 *
2951 		 * Use some switch/case magic to avoid code duplication.
2952 		 */
2953 		if (msg == NULL) {
2954 			inp = in6_pcblookup_hash(pi, &saddr->v6, sport,
2955 			    &daddr->v6, dport, INPLOOKUP_WILDCARD, NULL);
2956 
2957 			if (inp == NULL)
2958 				return (-1);
2959 			break;
2960 		}
2961 		/* FALLTHROUGH if SMP and on other CPU */
2962 #endif /* INET6 */
2963 	case AF_INET:
2964 		if (msg != NULL) {
2965 			lwkt_domsg(netisr_cpuport(pi_cpu),
2966 				     &msg->base.lmsg, 0);
2967 		} else
2968 		{
2969 			inp = in_pcblookup_hash(pi, saddr->v4, sport, daddr->v4,
2970 			    dport, INPLOOKUP_WILDCARD, NULL);
2971 		}
2972 		if (inp == NULL)
2973 			return (-1);
2974 		break;
2975 
2976 	default:
2977 		return (-1);
2978 	}
2979 	pd->lookup.uid = inp->inp_socket->so_cred->cr_uid;
2980 	pd->lookup.gid = inp->inp_socket->so_cred->cr_groups[0];
2981 	return (1);
2982 }
2983 
2984 u_int8_t
2985 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2986 {
2987 	int		 hlen;
2988 	u_int8_t	 hdr[60];
2989 	u_int8_t	*opt, optlen;
2990 	u_int8_t	 wscale = 0;
2991 
2992 	hlen = th_off << 2;		/* hlen <= sizeof(hdr) */
2993 	if (hlen <= sizeof(struct tcphdr))
2994 		return (0);
2995 	if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2996 		return (0);
2997 	opt = hdr + sizeof(struct tcphdr);
2998 	hlen -= sizeof(struct tcphdr);
2999 	while (hlen >= 3) {
3000 		switch (*opt) {
3001 		case TCPOPT_EOL:
3002 		case TCPOPT_NOP:
3003 			++opt;
3004 			--hlen;
3005 			break;
3006 		case TCPOPT_WINDOW:
3007 			wscale = opt[2];
3008 			if (wscale > TCP_MAX_WINSHIFT)
3009 				wscale = TCP_MAX_WINSHIFT;
3010 			wscale |= PF_WSCALE_FLAG;
3011 			/* FALLTHROUGH */
3012 		default:
3013 			optlen = opt[1];
3014 			if (optlen < 2)
3015 				optlen = 2;
3016 			hlen -= optlen;
3017 			opt += optlen;
3018 			break;
3019 		}
3020 	}
3021 	return (wscale);
3022 }
3023 
3024 u_int16_t
3025 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3026 {
3027 	int		 hlen;
3028 	u_int8_t	 hdr[60];
3029 	u_int8_t	*opt, optlen;
3030 	u_int16_t	 mss = tcp_mssdflt;
3031 
3032 	hlen = th_off << 2;	/* hlen <= sizeof(hdr) */
3033 	if (hlen <= sizeof(struct tcphdr))
3034 		return (0);
3035 	if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3036 		return (0);
3037 	opt = hdr + sizeof(struct tcphdr);
3038 	hlen -= sizeof(struct tcphdr);
3039 	while (hlen >= TCPOLEN_MAXSEG) {
3040 		switch (*opt) {
3041 		case TCPOPT_EOL:
3042 		case TCPOPT_NOP:
3043 			++opt;
3044 			--hlen;
3045 			break;
3046 		case TCPOPT_MAXSEG:
3047 			bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3048 			/* FALLTHROUGH */
3049 		default:
3050 			optlen = opt[1];
3051 			if (optlen < 2)
3052 				optlen = 2;
3053 			hlen -= optlen;
3054 			opt += optlen;
3055 			break;
3056 		}
3057 	}
3058 	return (mss);
3059 }
3060 
3061 u_int16_t
3062 pf_calc_mss(struct pf_addr *addr, sa_family_t af, u_int16_t offer)
3063 {
3064 #ifdef INET
3065 	struct sockaddr_in	*dst;
3066 	struct route		 ro;
3067 #endif /* INET */
3068 #ifdef INET6
3069 	struct sockaddr_in6	*dst6;
3070 	struct route_in6	 ro6;
3071 #endif /* INET6 */
3072 	struct rtentry		*rt = NULL;
3073 	int			 hlen = 0;
3074 	u_int16_t		 mss = tcp_mssdflt;
3075 
3076 	switch (af) {
3077 #ifdef INET
3078 	case AF_INET:
3079 		hlen = sizeof(struct ip);
3080 		bzero(&ro, sizeof(ro));
3081 		dst = (struct sockaddr_in *)&ro.ro_dst;
3082 		dst->sin_family = AF_INET;
3083 		dst->sin_len = sizeof(*dst);
3084 		dst->sin_addr = addr->v4;
3085 		rtalloc_ign(&ro, (RTF_CLONING | RTF_PRCLONING));
3086 		rt = ro.ro_rt;
3087 		break;
3088 #endif /* INET */
3089 #ifdef INET6
3090 	case AF_INET6:
3091 		hlen = sizeof(struct ip6_hdr);
3092 		bzero(&ro6, sizeof(ro6));
3093 		dst6 = (struct sockaddr_in6 *)&ro6.ro_dst;
3094 		dst6->sin6_family = AF_INET6;
3095 		dst6->sin6_len = sizeof(*dst6);
3096 		dst6->sin6_addr = addr->v6;
3097 		rtalloc_ign((struct route *)&ro6, (RTF_CLONING | RTF_PRCLONING));
3098 		rt = ro6.ro_rt;
3099 		break;
3100 #endif /* INET6 */
3101 	}
3102 
3103 	if (rt && rt->rt_ifp) {
3104 		mss = rt->rt_ifp->if_mtu - hlen - sizeof(struct tcphdr);
3105 		mss = max(tcp_mssdflt, mss);
3106 		RTFREE(rt);
3107 	}
3108 	mss = min(mss, offer);
3109 	mss = max(mss, 64);		/* sanity - at least max opt space */
3110 	return (mss);
3111 }
3112 
3113 void
3114 pf_set_rt_ifp(struct pf_state *s, struct pf_addr *saddr)
3115 {
3116 	struct pf_rule *r = s->rule.ptr;
3117 
3118 	s->rt_kif = NULL;
3119 	if (!r->rt || r->rt == PF_FASTROUTE)
3120 		return;
3121 	switch (s->key[PF_SK_WIRE]->af) {
3122 #ifdef INET
3123 	case AF_INET:
3124 		pf_map_addr(AF_INET, r, saddr, &s->rt_addr, NULL,
3125 		    &s->nat_src_node);
3126 		s->rt_kif = r->rpool.cur->kif;
3127 		break;
3128 #endif /* INET */
3129 #ifdef INET6
3130 	case AF_INET6:
3131 		pf_map_addr(AF_INET6, r, saddr, &s->rt_addr, NULL,
3132 		    &s->nat_src_node);
3133 		s->rt_kif = r->rpool.cur->kif;
3134 		break;
3135 #endif /* INET6 */
3136 	}
3137 }
3138 
3139 u_int32_t
3140 pf_tcp_iss(struct pf_pdesc *pd)
3141 {
3142 	MD5_CTX ctx;
3143 	u_int32_t digest[4];
3144 
3145 	if (pf_tcp_secret_init == 0) {
3146 		karc4rand(pf_tcp_secret, sizeof(pf_tcp_secret));
3147 		MD5Init(&pf_tcp_secret_ctx);
3148 		MD5Update(&pf_tcp_secret_ctx, pf_tcp_secret,
3149 		    sizeof(pf_tcp_secret));
3150 		pf_tcp_secret_init = 1;
3151 	}
3152 	ctx = pf_tcp_secret_ctx;
3153 
3154 	MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3155 	MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3156 	if (pd->af == AF_INET6) {
3157 		MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3158 		MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3159 	} else {
3160 		MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3161 		MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3162 	}
3163 	MD5Final((u_char *)digest, &ctx);
3164 	pf_tcp_iss_off += 4096;
3165 	return (digest[0] + pd->hdr.tcp->th_seq + pf_tcp_iss_off);
3166 }
3167 
3168 int
3169 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3170     struct pfi_kif *kif, struct mbuf *m, int off, void *h,
3171     struct pf_pdesc *pd, struct pf_rule **am, struct pf_ruleset **rsm,
3172     struct ifqueue *ifq, struct inpcb *inp)
3173 {
3174 	struct pf_rule		*nr = NULL;
3175 	struct pf_addr		*saddr = pd->src, *daddr = pd->dst;
3176 	sa_family_t		 af = pd->af;
3177 	struct pf_rule		*r, *a = NULL;
3178 	struct pf_ruleset	*ruleset = NULL;
3179 	struct pf_src_node	*nsn = NULL;
3180 	struct tcphdr		*th = pd->hdr.tcp;
3181 	struct pf_state_key	*skw = NULL, *sks = NULL;
3182 	struct pf_state_key	*sk = NULL, *nk = NULL;
3183 	u_short			 reason;
3184 	int			 rewrite = 0, hdrlen = 0;
3185 	int			 tag = -1, rtableid = -1;
3186 	int			 asd = 0;
3187 	int			 match = 0;
3188 	int			 state_icmp = 0;
3189 	u_int16_t		 sport = 0, dport = 0;
3190 	u_int16_t		 bproto_sum = 0, bip_sum = 0;
3191 	u_int8_t		 icmptype = 0, icmpcode = 0;
3192 
3193 
3194 	if (direction == PF_IN && pf_check_congestion(ifq)) {
3195 		REASON_SET(&reason, PFRES_CONGEST);
3196 		return (PF_DROP);
3197 	}
3198 
3199 	if (inp != NULL)
3200 		pd->lookup.done = pf_socket_lookup(direction, pd);
3201 	else if (debug_pfugidhack) {
3202 		DPFPRINTF(PF_DEBUG_MISC, ("pf: unlocked lookup\n"));
3203 		pd->lookup.done = pf_socket_lookup(direction, pd);
3204 	}
3205 
3206 	switch (pd->proto) {
3207 	case IPPROTO_TCP:
3208 		sport = th->th_sport;
3209 		dport = th->th_dport;
3210 		hdrlen = sizeof(*th);
3211 		break;
3212 	case IPPROTO_UDP:
3213 		sport = pd->hdr.udp->uh_sport;
3214 		dport = pd->hdr.udp->uh_dport;
3215 		hdrlen = sizeof(*pd->hdr.udp);
3216 		break;
3217 #ifdef INET
3218 	case IPPROTO_ICMP:
3219 		if (pd->af != AF_INET)
3220 			break;
3221 		sport = dport = pd->hdr.icmp->icmp_id;
3222 		hdrlen = sizeof(*pd->hdr.icmp);
3223 		icmptype = pd->hdr.icmp->icmp_type;
3224 		icmpcode = pd->hdr.icmp->icmp_code;
3225 
3226 		if (icmptype == ICMP_UNREACH ||
3227 		    icmptype == ICMP_SOURCEQUENCH ||
3228 		    icmptype == ICMP_REDIRECT ||
3229 		    icmptype == ICMP_TIMXCEED ||
3230 		    icmptype == ICMP_PARAMPROB)
3231 			state_icmp++;
3232 		break;
3233 #endif /* INET */
3234 #ifdef INET6
3235 	case IPPROTO_ICMPV6:
3236 		if (af != AF_INET6)
3237 			break;
3238 		sport = dport = pd->hdr.icmp6->icmp6_id;
3239 		hdrlen = sizeof(*pd->hdr.icmp6);
3240 		icmptype = pd->hdr.icmp6->icmp6_type;
3241 		icmpcode = pd->hdr.icmp6->icmp6_code;
3242 
3243 		if (icmptype == ICMP6_DST_UNREACH ||
3244 		    icmptype == ICMP6_PACKET_TOO_BIG ||
3245 		    icmptype == ICMP6_TIME_EXCEEDED ||
3246 		    icmptype == ICMP6_PARAM_PROB)
3247 			state_icmp++;
3248 		break;
3249 #endif /* INET6 */
3250 	default:
3251 		sport = dport = hdrlen = 0;
3252 		break;
3253 	}
3254 
3255 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3256 
3257 	/* check packet for BINAT/NAT/RDR */
3258 	if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn,
3259 	    &skw, &sks, &sk, &nk, saddr, daddr, sport, dport)) != NULL) {
3260 		if (nk == NULL || sk == NULL) {
3261 			REASON_SET(&reason, PFRES_MEMORY);
3262 			goto cleanup;
3263 		}
3264 
3265 		if (pd->ip_sum)
3266 			bip_sum = *pd->ip_sum;
3267 
3268 		m->m_flags &= ~M_HASH;
3269 		switch (pd->proto) {
3270 		case IPPROTO_TCP:
3271 			bproto_sum = th->th_sum;
3272 			pd->proto_sum = &th->th_sum;
3273 
3274 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3275 			    nk->port[pd->sidx] != sport) {
3276 				pf_change_ap(saddr, &th->th_sport, pd->ip_sum,
3277 				    &th->th_sum, &nk->addr[pd->sidx],
3278 				    nk->port[pd->sidx], 0, af);
3279 				pd->sport = &th->th_sport;
3280 				sport = th->th_sport;
3281 			}
3282 
3283 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3284 			    nk->port[pd->didx] != dport) {
3285 				pf_change_ap(daddr, &th->th_dport, pd->ip_sum,
3286 				    &th->th_sum, &nk->addr[pd->didx],
3287 				    nk->port[pd->didx], 0, af);
3288 				dport = th->th_dport;
3289 				pd->dport = &th->th_dport;
3290 			}
3291 			rewrite++;
3292 			break;
3293 		case IPPROTO_UDP:
3294 			bproto_sum = pd->hdr.udp->uh_sum;
3295 			pd->proto_sum = &pd->hdr.udp->uh_sum;
3296 
3297 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3298 			    nk->port[pd->sidx] != sport) {
3299 				pf_change_ap(saddr, &pd->hdr.udp->uh_sport,
3300 				    pd->ip_sum, &pd->hdr.udp->uh_sum,
3301 				    &nk->addr[pd->sidx],
3302 				    nk->port[pd->sidx], 1, af);
3303 				sport = pd->hdr.udp->uh_sport;
3304 				pd->sport = &pd->hdr.udp->uh_sport;
3305 			}
3306 
3307 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3308 			    nk->port[pd->didx] != dport) {
3309 				pf_change_ap(daddr, &pd->hdr.udp->uh_dport,
3310 				    pd->ip_sum, &pd->hdr.udp->uh_sum,
3311 				    &nk->addr[pd->didx],
3312 				    nk->port[pd->didx], 1, af);
3313 				dport = pd->hdr.udp->uh_dport;
3314 				pd->dport = &pd->hdr.udp->uh_dport;
3315 			}
3316 			rewrite++;
3317 			break;
3318 #ifdef INET
3319 		case IPPROTO_ICMP:
3320 			nk->port[0] = nk->port[1];
3321 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3322 				pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3323 				    nk->addr[pd->sidx].v4.s_addr, 0);
3324 
3325 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3326 				pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3327 				    nk->addr[pd->didx].v4.s_addr, 0);
3328 
3329 			if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3330 				pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3331 				    pd->hdr.icmp->icmp_cksum, sport,
3332 				    nk->port[1], 0);
3333 				pd->hdr.icmp->icmp_id = nk->port[1];
3334 				pd->sport = &pd->hdr.icmp->icmp_id;
3335 			}
3336 			m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3337 			break;
3338 #endif /* INET */
3339 #ifdef INET6
3340 		case IPPROTO_ICMPV6:
3341 			nk->port[0] = nk->port[1];
3342 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3343 				pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3344 				    &nk->addr[pd->sidx], 0);
3345 
3346 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3347 				pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3348 				    &nk->addr[pd->didx], 0);
3349 			rewrite++;
3350 			break;
3351 #endif /* INET */
3352 		default:
3353 			switch (af) {
3354 #ifdef INET
3355 			case AF_INET:
3356 				if (PF_ANEQ(saddr,
3357 				    &nk->addr[pd->sidx], AF_INET))
3358 					pf_change_a(&saddr->v4.s_addr,
3359 					    pd->ip_sum,
3360 					    nk->addr[pd->sidx].v4.s_addr, 0);
3361 
3362 				if (PF_ANEQ(daddr,
3363 				    &nk->addr[pd->didx], AF_INET))
3364 					pf_change_a(&daddr->v4.s_addr,
3365 					    pd->ip_sum,
3366 					    nk->addr[pd->didx].v4.s_addr, 0);
3367 				break;
3368 #endif /* INET */
3369 #ifdef INET6
3370 			case AF_INET6:
3371 				if (PF_ANEQ(saddr,
3372 				    &nk->addr[pd->sidx], AF_INET6))
3373 					PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3374 
3375 				if (PF_ANEQ(daddr,
3376 				    &nk->addr[pd->didx], AF_INET6))
3377 					PF_ACPY(saddr, &nk->addr[pd->didx], af);
3378 				break;
3379 #endif /* INET */
3380 			}
3381 			break;
3382 		}
3383 		if (nr->natpass)
3384 			r = NULL;
3385 		pd->nat_rule = nr;
3386 	}
3387 
3388 	while (r != NULL) {
3389 		r->evaluations++;
3390 		if (pfi_kif_match(r->kif, kif) == r->ifnot)
3391 			r = r->skip[PF_SKIP_IFP].ptr;
3392 		else if (r->direction && r->direction != direction)
3393 			r = r->skip[PF_SKIP_DIR].ptr;
3394 		else if (r->af && r->af != af)
3395 			r = r->skip[PF_SKIP_AF].ptr;
3396 		else if (r->proto && r->proto != pd->proto)
3397 			r = r->skip[PF_SKIP_PROTO].ptr;
3398 		else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3399 		    r->src.neg, kif))
3400 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3401 		/* tcp/udp only. port_op always 0 in other cases */
3402 		else if (r->src.port_op && !pf_match_port(r->src.port_op,
3403 		    r->src.port[0], r->src.port[1], sport))
3404 			r = r->skip[PF_SKIP_SRC_PORT].ptr;
3405 		else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3406 		    r->dst.neg, NULL))
3407 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
3408 		/* tcp/udp only. port_op always 0 in other cases */
3409 		else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3410 		    r->dst.port[0], r->dst.port[1], dport))
3411 			r = r->skip[PF_SKIP_DST_PORT].ptr;
3412 		/* icmp only. type always 0 in other cases */
3413 		else if (r->type && r->type != icmptype + 1)
3414 			r = TAILQ_NEXT(r, entries);
3415 		/* icmp only. type always 0 in other cases */
3416 		else if (r->code && r->code != icmpcode + 1)
3417 			r = TAILQ_NEXT(r, entries);
3418 		else if (r->tos && !(r->tos == pd->tos))
3419 			r = TAILQ_NEXT(r, entries);
3420 		else if (r->rule_flag & PFRULE_FRAGMENT)
3421 			r = TAILQ_NEXT(r, entries);
3422 		else if (pd->proto == IPPROTO_TCP &&
3423 		    (r->flagset & th->th_flags) != r->flags)
3424 			r = TAILQ_NEXT(r, entries);
3425 		/* tcp/udp only. uid.op always 0 in other cases */
3426 		else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3427 		    pf_socket_lookup(direction, pd), 1)) &&
3428 		    !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3429 		    pd->lookup.uid))
3430 			r = TAILQ_NEXT(r, entries);
3431 		/* tcp/udp only. gid.op always 0 in other cases */
3432 		else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3433 		    pf_socket_lookup(direction, pd), 1)) &&
3434 		    !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3435 		    pd->lookup.gid))
3436 			r = TAILQ_NEXT(r, entries);
3437 		else if (r->prob &&
3438 		  r->prob <= karc4random())
3439 			r = TAILQ_NEXT(r, entries);
3440 		else if (r->match_tag && !pf_match_tag(m, r, &tag))
3441 			r = TAILQ_NEXT(r, entries);
3442 		else if (r->os_fingerprint != PF_OSFP_ANY &&
3443 		    (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3444 		    pf_osfp_fingerprint(pd, m, off, th),
3445 		    r->os_fingerprint)))
3446 			r = TAILQ_NEXT(r, entries);
3447 		else {
3448 			if (r->tag)
3449 				tag = r->tag;
3450 			if (r->rtableid >= 0)
3451 				rtableid = r->rtableid;
3452 			if (r->anchor == NULL) {
3453 				match = 1;
3454 				*rm = r;
3455 				*am = a;
3456 				*rsm = ruleset;
3457 				if ((*rm)->quick)
3458 					break;
3459 				r = TAILQ_NEXT(r, entries);
3460 			} else
3461 				pf_step_into_anchor(&asd, &ruleset,
3462 				    PF_RULESET_FILTER, &r, &a, &match);
3463 		}
3464 		if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
3465 		    PF_RULESET_FILTER, &r, &a, &match))
3466 			break;
3467 	}
3468 	r = *rm;
3469 	a = *am;
3470 	ruleset = *rsm;
3471 
3472 	REASON_SET(&reason, PFRES_MATCH);
3473 
3474 	if (r->log || (nr != NULL && nr->log)) {
3475 		if (rewrite)
3476 			m_copyback(m, off, hdrlen, pd->hdr.any);
3477 		PFLOG_PACKET(kif, h, m, af, direction, reason, r->log ? r : nr,
3478 		    a, ruleset, pd);
3479 	}
3480 
3481 	if ((r->action == PF_DROP) &&
3482 	    ((r->rule_flag & PFRULE_RETURNRST) ||
3483 	    (r->rule_flag & PFRULE_RETURNICMP) ||
3484 	    (r->rule_flag & PFRULE_RETURN))) {
3485 		/* undo NAT changes, if they have taken place */
3486 		if (nr != NULL) {
3487 			PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3488 			PF_ACPY(daddr, &sk->addr[pd->didx], af);
3489 			if (pd->sport)
3490 				*pd->sport = sk->port[pd->sidx];
3491 			if (pd->dport)
3492 				*pd->dport = sk->port[pd->didx];
3493 			if (pd->proto_sum)
3494 				*pd->proto_sum = bproto_sum;
3495 			if (pd->ip_sum)
3496 				*pd->ip_sum = bip_sum;
3497 			m_copyback(m, off, hdrlen, pd->hdr.any);
3498 		}
3499 		if (pd->proto == IPPROTO_TCP &&
3500 		    ((r->rule_flag & PFRULE_RETURNRST) ||
3501 		    (r->rule_flag & PFRULE_RETURN)) &&
3502 		    !(th->th_flags & TH_RST)) {
3503 			u_int32_t	 ack = ntohl(th->th_seq) + pd->p_len;
3504 			int		 len = 0;
3505 			struct ip	*h4;
3506 #ifdef INET6
3507 			struct ip6_hdr	*h6;
3508 #endif
3509 			switch (af) {
3510 			case AF_INET:
3511 				h4 = mtod(m, struct ip *);
3512 				len = h4->ip_len - off;
3513 				break;
3514 #ifdef INET6
3515 			case AF_INET6:
3516 				h6 = mtod(m, struct ip6_hdr *);
3517 				len = h6->ip6_plen - (off - sizeof(*h6));
3518 				break;
3519 #endif
3520 			}
3521 
3522 			if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
3523 				REASON_SET(&reason, PFRES_PROTCKSUM);
3524 			else {
3525 				if (th->th_flags & TH_SYN)
3526 					ack++;
3527 				if (th->th_flags & TH_FIN)
3528 					ack++;
3529 				pf_send_tcp(r, af, pd->dst,
3530 				    pd->src, th->th_dport, th->th_sport,
3531 				    ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3532 				    r->return_ttl, 1, 0, pd->eh, kif->pfik_ifp);
3533 			}
3534 		} else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3535 		    r->return_icmp)
3536 			pf_send_icmp(m, r->return_icmp >> 8,
3537 			    r->return_icmp & 255, af, r);
3538 		else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3539 		    r->return_icmp6)
3540 			pf_send_icmp(m, r->return_icmp6 >> 8,
3541 			    r->return_icmp6 & 255, af, r);
3542 	}
3543 
3544 	if (r->action == PF_DROP)
3545 		goto cleanup;
3546 
3547 	if (pf_tag_packet(m, tag, rtableid)) {
3548 		REASON_SET(&reason, PFRES_MEMORY);
3549 		goto cleanup;
3550 	}
3551 
3552 	if (!state_icmp && (r->keep_state || nr != NULL ||
3553 	    (pd->flags & PFDESC_TCP_NORM))) {
3554 		int action;
3555 		action = pf_create_state(r, nr, a, pd, nsn, skw, sks, nk, sk, m,
3556 		    off, sport, dport, &rewrite, kif, sm, tag, bproto_sum,
3557 		    bip_sum, hdrlen);
3558 		if (action != PF_PASS)
3559 			return (action);
3560 	}
3561 
3562 	/* copy back packet headers if we performed NAT operations */
3563 	if (rewrite)
3564 		m_copyback(m, off, hdrlen, pd->hdr.any);
3565 
3566 	return (PF_PASS);
3567 
3568 cleanup:
3569 	if (sk != NULL)
3570 		kfree(sk, M_PFSTATEKEYPL);
3571 	if (nk != NULL)
3572 		kfree(nk, M_PFSTATEKEYPL);
3573 	return (PF_DROP);
3574 }
3575 
3576 static __inline int
3577 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3578     struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *skw,
3579     struct pf_state_key *sks, struct pf_state_key *nk, struct pf_state_key *sk,
3580     struct mbuf *m, int off, u_int16_t sport, u_int16_t dport, int *rewrite,
3581     struct pfi_kif *kif, struct pf_state **sm, int tag, u_int16_t bproto_sum,
3582     u_int16_t bip_sum, int hdrlen)
3583 {
3584 	struct pf_state		*s = NULL;
3585 	struct pf_src_node	*sn = NULL;
3586 	struct tcphdr		*th = pd->hdr.tcp;
3587 	u_int16_t		 mss = tcp_mssdflt;
3588 	u_short			 reason;
3589 
3590 	/* check maximums */
3591 	if (r->max_states && (r->states_cur >= r->max_states)) {
3592 		pf_status.lcounters[LCNT_STATES]++;
3593 		REASON_SET(&reason, PFRES_MAXSTATES);
3594 		return (PF_DROP);
3595 	}
3596 	/* src node for filter rule */
3597 	if ((r->rule_flag & PFRULE_SRCTRACK ||
3598 	    r->rpool.opts & PF_POOL_STICKYADDR) &&
3599 	    pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3600 		REASON_SET(&reason, PFRES_SRCLIMIT);
3601 		goto csfailed;
3602 	}
3603 	/* src node for translation rule */
3604 	if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3605 	    pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3606 		REASON_SET(&reason, PFRES_SRCLIMIT);
3607 		goto csfailed;
3608 	}
3609 	s = kmalloc(sizeof(struct pf_state), M_PFSTATEPL, M_NOWAIT|M_ZERO);
3610 	if (s == NULL) {
3611 		REASON_SET(&reason, PFRES_MEMORY);
3612 		goto csfailed;
3613 	}
3614 	s->id = 0; /* XXX Do we really need that? not in OpenBSD */
3615 	s->creatorid = 0;
3616 	s->rule.ptr = r;
3617 	s->nat_rule.ptr = nr;
3618 	s->anchor.ptr = a;
3619 	STATE_INC_COUNTERS(s);
3620 	if (r->allow_opts)
3621 		s->state_flags |= PFSTATE_ALLOWOPTS;
3622 	if (r->rule_flag & PFRULE_STATESLOPPY)
3623 		s->state_flags |= PFSTATE_SLOPPY;
3624 	s->log = r->log & PF_LOG_ALL;
3625 	if (nr != NULL)
3626 		s->log |= nr->log & PF_LOG_ALL;
3627 	switch (pd->proto) {
3628 	case IPPROTO_TCP:
3629 		s->src.seqlo = ntohl(th->th_seq);
3630 		s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3631 		if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3632 		    r->keep_state == PF_STATE_MODULATE) {
3633 			/* Generate sequence number modulator */
3634 			if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3635 			    0)
3636 				s->src.seqdiff = 1;
3637 			pf_change_a(&th->th_seq, &th->th_sum,
3638 			    htonl(s->src.seqlo + s->src.seqdiff), 0);
3639 			*rewrite = 1;
3640 		} else
3641 			s->src.seqdiff = 0;
3642 		if (th->th_flags & TH_SYN) {
3643 			s->src.seqhi++;
3644 			s->src.wscale = pf_get_wscale(m, off,
3645 			    th->th_off, pd->af);
3646 		}
3647 		s->src.max_win = MAX(ntohs(th->th_win), 1);
3648 		if (s->src.wscale & PF_WSCALE_MASK) {
3649 			/* Remove scale factor from initial window */
3650 			int win = s->src.max_win;
3651 			win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3652 			s->src.max_win = (win - 1) >>
3653 			    (s->src.wscale & PF_WSCALE_MASK);
3654 		}
3655 		if (th->th_flags & TH_FIN)
3656 			s->src.seqhi++;
3657 		s->dst.seqhi = 1;
3658 		s->dst.max_win = 1;
3659 		s->src.state = TCPS_SYN_SENT;
3660 		s->dst.state = TCPS_CLOSED;
3661 		s->timeout = PFTM_TCP_FIRST_PACKET;
3662 		break;
3663 	case IPPROTO_UDP:
3664 		s->src.state = PFUDPS_SINGLE;
3665 		s->dst.state = PFUDPS_NO_TRAFFIC;
3666 		s->timeout = PFTM_UDP_FIRST_PACKET;
3667 		break;
3668 	case IPPROTO_ICMP:
3669 #ifdef INET6
3670 	case IPPROTO_ICMPV6:
3671 #endif
3672 		s->timeout = PFTM_ICMP_FIRST_PACKET;
3673 		break;
3674 	default:
3675 		s->src.state = PFOTHERS_SINGLE;
3676 		s->dst.state = PFOTHERS_NO_TRAFFIC;
3677 		s->timeout = PFTM_OTHER_FIRST_PACKET;
3678 	}
3679 
3680 	s->creation = time_second;
3681 	s->expire = time_second;
3682 
3683 	if (sn != NULL) {
3684 		s->src_node = sn;
3685 		s->src_node->states++;
3686 	}
3687 	if (nsn != NULL) {
3688 		/* XXX We only modify one side for now. */
3689 		PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3690 		s->nat_src_node = nsn;
3691 		s->nat_src_node->states++;
3692 	}
3693 	if (pd->proto == IPPROTO_TCP) {
3694 		if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3695 		    off, pd, th, &s->src, &s->dst)) {
3696 			REASON_SET(&reason, PFRES_MEMORY);
3697 			pf_src_tree_remove_state(s);
3698 			STATE_DEC_COUNTERS(s);
3699 			kfree(s, M_PFSTATEPL);
3700 			return (PF_DROP);
3701 		}
3702 		if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3703 		    pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3704 		    &s->src, &s->dst, rewrite)) {
3705 			/* This really shouldn't happen!!! */
3706 			DPFPRINTF(PF_DEBUG_URGENT,
3707 			    ("pf_normalize_tcp_stateful failed on first pkt"));
3708 			pf_normalize_tcp_cleanup(s);
3709 			pf_src_tree_remove_state(s);
3710 			STATE_DEC_COUNTERS(s);
3711 			kfree(s, M_PFSTATEPL);
3712 			return (PF_DROP);
3713 		}
3714 	}
3715 	s->direction = pd->dir;
3716 
3717 	if (sk == NULL && pf_state_key_setup(pd, nr, &skw, &sks, &sk, &nk,
3718 	    pd->src, pd->dst, sport, dport))
3719 		goto csfailed;
3720 
3721 	if (pf_state_insert(BOUND_IFACE(r, kif), skw, sks, s)) {
3722 		if (pd->proto == IPPROTO_TCP)
3723 			pf_normalize_tcp_cleanup(s);
3724 		REASON_SET(&reason, PFRES_STATEINS);
3725 		pf_src_tree_remove_state(s);
3726 		STATE_DEC_COUNTERS(s);
3727 		kfree(s, M_PFSTATEPL);
3728 		return (PF_DROP);
3729 	} else
3730 		*sm = s;
3731 
3732 	pf_set_rt_ifp(s, pd->src);	/* needs s->state_key set */
3733 	if (tag > 0) {
3734 		pf_tag_ref(tag);
3735 		s->tag = tag;
3736 	}
3737 	if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3738 	    TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3739 		s->src.state = PF_TCPS_PROXY_SRC;
3740 		/* undo NAT changes, if they have taken place */
3741 		if (nr != NULL) {
3742 			struct pf_state_key *skt = s->key[PF_SK_WIRE];
3743 			if (pd->dir == PF_OUT)
3744 				skt = s->key[PF_SK_STACK];
3745 			PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3746 			PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3747 			if (pd->sport)
3748 				*pd->sport = skt->port[pd->sidx];
3749 			if (pd->dport)
3750 				*pd->dport = skt->port[pd->didx];
3751 			if (pd->proto_sum)
3752 				*pd->proto_sum = bproto_sum;
3753 			if (pd->ip_sum)
3754 				*pd->ip_sum = bip_sum;
3755 			m_copyback(m, off, hdrlen, pd->hdr.any);
3756 		}
3757 		s->src.seqhi = htonl(karc4random());
3758 		/* Find mss option */
3759 		mss = pf_get_mss(m, off, th->th_off, pd->af);
3760 		mss = pf_calc_mss(pd->src, pd->af, mss);
3761 		mss = pf_calc_mss(pd->dst, pd->af, mss);
3762 		s->src.mss = mss;
3763 		pf_send_tcp(r, pd->af, pd->dst, pd->src, th->th_dport,
3764 		    th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3765 		    TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL, NULL);
3766 		REASON_SET(&reason, PFRES_SYNPROXY);
3767 		return (PF_SYNPROXY_DROP);
3768 	}
3769 
3770 	return (PF_PASS);
3771 
3772 csfailed:
3773 	if (sk != NULL)
3774 		kfree(sk, M_PFSTATEKEYPL);
3775 	if (nk != NULL)
3776 		kfree(nk, M_PFSTATEKEYPL);
3777 
3778 	if (sn != NULL && sn->states == 0 && sn->expire == 0) {
3779 		RB_REMOVE(pf_src_tree, &tree_src_tracking, sn);
3780 		pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
3781 		pf_status.src_nodes--;
3782 		kfree(sn, M_PFSRCTREEPL);
3783 	}
3784 	if (nsn != sn && nsn != NULL && nsn->states == 0 && nsn->expire == 0) {
3785 		RB_REMOVE(pf_src_tree, &tree_src_tracking, nsn);
3786 		pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
3787 		pf_status.src_nodes--;
3788 		kfree(nsn, M_PFSRCTREEPL);
3789 	}
3790 	return (PF_DROP);
3791 }
3792 
3793 int
3794 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3795     struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3796     struct pf_ruleset **rsm)
3797 {
3798 	struct pf_rule		*r, *a = NULL;
3799 	struct pf_ruleset	*ruleset = NULL;
3800 	sa_family_t		 af = pd->af;
3801 	u_short			 reason;
3802 	int			 tag = -1;
3803 	int			 asd = 0;
3804 	int			 match = 0;
3805 
3806 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3807 	while (r != NULL) {
3808 		r->evaluations++;
3809 		if (pfi_kif_match(r->kif, kif) == r->ifnot)
3810 			r = r->skip[PF_SKIP_IFP].ptr;
3811 		else if (r->direction && r->direction != direction)
3812 			r = r->skip[PF_SKIP_DIR].ptr;
3813 		else if (r->af && r->af != af)
3814 			r = r->skip[PF_SKIP_AF].ptr;
3815 		else if (r->proto && r->proto != pd->proto)
3816 			r = r->skip[PF_SKIP_PROTO].ptr;
3817 		else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3818 		    r->src.neg, kif))
3819 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3820 		else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3821 		    r->dst.neg, NULL))
3822 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
3823 		else if (r->tos && !(r->tos == pd->tos))
3824 			r = TAILQ_NEXT(r, entries);
3825 		else if (r->os_fingerprint != PF_OSFP_ANY)
3826 			r = TAILQ_NEXT(r, entries);
3827 		else if (pd->proto == IPPROTO_UDP &&
3828 		    (r->src.port_op || r->dst.port_op))
3829 			r = TAILQ_NEXT(r, entries);
3830 		else if (pd->proto == IPPROTO_TCP &&
3831 		    (r->src.port_op || r->dst.port_op || r->flagset))
3832 			r = TAILQ_NEXT(r, entries);
3833 		else if ((pd->proto == IPPROTO_ICMP ||
3834 		    pd->proto == IPPROTO_ICMPV6) &&
3835 		    (r->type || r->code))
3836 			r = TAILQ_NEXT(r, entries);
3837 		else if (r->prob && r->prob <= karc4random())
3838 			r = TAILQ_NEXT(r, entries);
3839 		else if (r->match_tag && !pf_match_tag(m, r, &tag))
3840 			r = TAILQ_NEXT(r, entries);
3841 		else {
3842 			if (r->anchor == NULL) {
3843 				match = 1;
3844 				*rm = r;
3845 				*am = a;
3846 				*rsm = ruleset;
3847 				if ((*rm)->quick)
3848 					break;
3849 				r = TAILQ_NEXT(r, entries);
3850 			} else
3851 				pf_step_into_anchor(&asd, &ruleset,
3852 				    PF_RULESET_FILTER, &r, &a, &match);
3853 		}
3854 		if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
3855 		    PF_RULESET_FILTER, &r, &a, &match))
3856 			break;
3857 	}
3858 	r = *rm;
3859 	a = *am;
3860 	ruleset = *rsm;
3861 
3862 	REASON_SET(&reason, PFRES_MATCH);
3863 
3864 	if (r->log)
3865 		PFLOG_PACKET(kif, h, m, af, direction, reason, r, a, ruleset,
3866 		    pd);
3867 
3868 	if (r->action != PF_PASS)
3869 		return (PF_DROP);
3870 
3871 	if (pf_tag_packet(m, tag, -1)) {
3872 		REASON_SET(&reason, PFRES_MEMORY);
3873 		return (PF_DROP);
3874 	}
3875 
3876 	return (PF_PASS);
3877 }
3878 
3879 int
3880 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3881 	struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3882 	struct pf_pdesc *pd, u_short *reason, int *copyback)
3883 {
3884 	struct tcphdr		*th = pd->hdr.tcp;
3885 	u_int16_t		 win = ntohs(th->th_win);
3886 	u_int32_t		 ack, end, seq, orig_seq;
3887 	u_int8_t		 sws, dws;
3888 	int			 ackskew;
3889 
3890 	if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3891 		sws = src->wscale & PF_WSCALE_MASK;
3892 		dws = dst->wscale & PF_WSCALE_MASK;
3893 	} else
3894 		sws = dws = 0;
3895 
3896 	/*
3897 	 * Sequence tracking algorithm from Guido van Rooij's paper:
3898 	 *   http://www.madison-gurkha.com/publications/tcp_filtering/
3899 	 *	tcp_filtering.ps
3900 	 */
3901 
3902 	orig_seq = seq = ntohl(th->th_seq);
3903 	if (src->seqlo == 0) {
3904 		/* First packet from this end. Set its state */
3905 
3906 		if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3907 		    src->scrub == NULL) {
3908 			if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3909 				REASON_SET(reason, PFRES_MEMORY);
3910 				return (PF_DROP);
3911 			}
3912 		}
3913 
3914 		/* Deferred generation of sequence number modulator */
3915 		if (dst->seqdiff && !src->seqdiff) {
3916 			/* use random iss for the TCP server */
3917 			while ((src->seqdiff = karc4random() - seq) == 0)
3918 				;
3919 			ack = ntohl(th->th_ack) - dst->seqdiff;
3920 			pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3921 			    src->seqdiff), 0);
3922 			pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3923 			*copyback = 1;
3924 		} else {
3925 			ack = ntohl(th->th_ack);
3926 		}
3927 
3928 		end = seq + pd->p_len;
3929 		if (th->th_flags & TH_SYN) {
3930 			end++;
3931 			(*state)->sync_flags |= PFSTATE_GOT_SYN2;
3932 			if (dst->wscale & PF_WSCALE_FLAG) {
3933 				src->wscale = pf_get_wscale(m, off, th->th_off,
3934 				    pd->af);
3935 				if (src->wscale & PF_WSCALE_FLAG) {
3936 					/* Remove scale factor from initial
3937 					 * window */
3938 					sws = src->wscale & PF_WSCALE_MASK;
3939 					win = ((u_int32_t)win + (1 << sws) - 1)
3940 					    >> sws;
3941 					dws = dst->wscale & PF_WSCALE_MASK;
3942 				} else {
3943 					/* fixup other window */
3944 					dst->max_win <<= dst->wscale &
3945 					    PF_WSCALE_MASK;
3946 					/* in case of a retrans SYN|ACK */
3947 					dst->wscale = 0;
3948 				}
3949 			}
3950 		}
3951 		if (th->th_flags & TH_FIN)
3952 			end++;
3953 
3954 		src->seqlo = seq;
3955 		if (src->state < TCPS_SYN_SENT)
3956 			src->state = TCPS_SYN_SENT;
3957 
3958 		/*
3959 		 * May need to slide the window (seqhi may have been set by
3960 		 * the crappy stack check or if we picked up the connection
3961 		 * after establishment)
3962 		 */
3963 		if (src->seqhi == 1 ||
3964 		    SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
3965 			src->seqhi = end + MAX(1, dst->max_win << dws);
3966 		if (win > src->max_win)
3967 			src->max_win = win;
3968 
3969 	} else {
3970 		ack = ntohl(th->th_ack) - dst->seqdiff;
3971 		if (src->seqdiff) {
3972 			/* Modulate sequence numbers */
3973 			pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3974 			    src->seqdiff), 0);
3975 			pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3976 			*copyback = 1;
3977 		}
3978 		end = seq + pd->p_len;
3979 		if (th->th_flags & TH_SYN)
3980 			end++;
3981 		if (th->th_flags & TH_FIN)
3982 			end++;
3983 	}
3984 
3985 	if ((th->th_flags & TH_ACK) == 0) {
3986 		/* Let it pass through the ack skew check */
3987 		ack = dst->seqlo;
3988 	} else if ((ack == 0 &&
3989 	    (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
3990 	    /* broken tcp stacks do not set ack */
3991 	    (dst->state < TCPS_SYN_SENT)) {
3992 		/*
3993 		 * Many stacks (ours included) will set the ACK number in an
3994 		 * FIN|ACK if the SYN times out -- no sequence to ACK.
3995 		 */
3996 		ack = dst->seqlo;
3997 	}
3998 
3999 	if (seq == end) {
4000 		/* Ease sequencing restrictions on no data packets */
4001 		seq = src->seqlo;
4002 		end = seq;
4003 	}
4004 
4005 	ackskew = dst->seqlo - ack;
4006 
4007 
4008 	/*
4009 	 * Need to demodulate the sequence numbers in any TCP SACK options
4010 	 * (Selective ACK). We could optionally validate the SACK values
4011 	 * against the current ACK window, either forwards or backwards, but
4012 	 * I'm not confident that SACK has been implemented properly
4013 	 * everywhere. It wouldn't surprise me if several stacks accidently
4014 	 * SACK too far backwards of previously ACKed data. There really aren't
4015 	 * any security implications of bad SACKing unless the target stack
4016 	 * doesn't validate the option length correctly. Someone trying to
4017 	 * spoof into a TCP connection won't bother blindly sending SACK
4018 	 * options anyway.
4019 	 */
4020 	if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4021 		if (pf_modulate_sack(m, off, pd, th, dst))
4022 			*copyback = 1;
4023 	}
4024 
4025 
4026 #define MAXACKWINDOW (0xffff + 1500)	/* 1500 is an arbitrary fudge factor */
4027 	if (SEQ_GEQ(src->seqhi, end) &&
4028 	    /* Last octet inside other's window space */
4029 	    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4030 	    /* Retrans: not more than one window back */
4031 	    (ackskew >= -MAXACKWINDOW) &&
4032 	    /* Acking not more than one reassembled fragment backwards */
4033 	    (ackskew <= (MAXACKWINDOW << sws)) &&
4034 	    /* Acking not more than one window forward */
4035 	    ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4036 	    (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4037 	    (pd->flags & PFDESC_IP_REAS) == 0)) {
4038 	    /* Require an exact/+1 sequence match on resets when possible */
4039 
4040 		if (dst->scrub || src->scrub) {
4041 			if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4042 			    *state, src, dst, copyback))
4043 				return (PF_DROP);
4044 		}
4045 
4046 		/* update max window */
4047 		if (src->max_win < win)
4048 			src->max_win = win;
4049 		/* synchronize sequencing */
4050 		if (SEQ_GT(end, src->seqlo))
4051 			src->seqlo = end;
4052 		/* slide the window of what the other end can send */
4053 		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4054 			dst->seqhi = ack + MAX((win << sws), 1);
4055 
4056 
4057 		/* update states */
4058 		if (th->th_flags & TH_SYN)
4059 			if (src->state < TCPS_SYN_SENT)
4060 				src->state = TCPS_SYN_SENT;
4061 		if (th->th_flags & TH_FIN)
4062 			if (src->state < TCPS_CLOSING)
4063 				src->state = TCPS_CLOSING;
4064 		if (th->th_flags & TH_ACK) {
4065 			if (dst->state == TCPS_SYN_SENT) {
4066 				dst->state = TCPS_ESTABLISHED;
4067 				if (src->state == TCPS_ESTABLISHED &&
4068 				    (*state)->src_node != NULL &&
4069 				    pf_src_connlimit(state)) {
4070 					REASON_SET(reason, PFRES_SRCLIMIT);
4071 					return (PF_DROP);
4072 				}
4073 			} else if (dst->state == TCPS_CLOSING)
4074 				dst->state = TCPS_FIN_WAIT_2;
4075 		}
4076 		if (th->th_flags & TH_RST)
4077 			src->state = dst->state = TCPS_TIME_WAIT;
4078 
4079 		/* update expire time */
4080 		(*state)->expire = time_second;
4081 		if (src->state >= TCPS_FIN_WAIT_2 &&
4082 		    dst->state >= TCPS_FIN_WAIT_2)
4083 			(*state)->timeout = PFTM_TCP_CLOSED;
4084 		else if (src->state >= TCPS_CLOSING &&
4085 		    dst->state >= TCPS_CLOSING)
4086 			(*state)->timeout = PFTM_TCP_FIN_WAIT;
4087 		else if (src->state < TCPS_ESTABLISHED ||
4088 		    dst->state < TCPS_ESTABLISHED)
4089 			(*state)->timeout = PFTM_TCP_OPENING;
4090 		else if (src->state >= TCPS_CLOSING ||
4091 		    dst->state >= TCPS_CLOSING)
4092 			(*state)->timeout = PFTM_TCP_CLOSING;
4093 		else
4094 			(*state)->timeout = PFTM_TCP_ESTABLISHED;
4095 
4096 		/* Fall through to PASS packet */
4097 
4098 	} else if ((dst->state < TCPS_SYN_SENT ||
4099 		dst->state >= TCPS_FIN_WAIT_2 ||
4100 		src->state >= TCPS_FIN_WAIT_2) &&
4101 	    SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4102 	    /* Within a window forward of the originating packet */
4103 	    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4104 	    /* Within a window backward of the originating packet */
4105 
4106 		/*
4107 		 * This currently handles three situations:
4108 		 *  1) Stupid stacks will shotgun SYNs before their peer
4109 		 *     replies.
4110 		 *  2) When PF catches an already established stream (the
4111 		 *     firewall rebooted, the state table was flushed, routes
4112 		 *     changed...)
4113 		 *  3) Packets get funky immediately after the connection
4114 		 *     closes (this should catch Solaris spurious ACK|FINs
4115 		 *     that web servers like to spew after a close)
4116 		 *
4117 		 * This must be a little more careful than the above code
4118 		 * since packet floods will also be caught here. We don't
4119 		 * update the TTL here to mitigate the damage of a packet
4120 		 * flood and so the same code can handle awkward establishment
4121 		 * and a loosened connection close.
4122 		 * In the establishment case, a correct peer response will
4123 		 * validate the connection, go through the normal state code
4124 		 * and keep updating the state TTL.
4125 		 */
4126 
4127 		if (pf_status.debug >= PF_DEBUG_MISC) {
4128 			kprintf("pf: loose state match: ");
4129 			pf_print_state(*state);
4130 			pf_print_flags(th->th_flags);
4131 			kprintf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4132 			    "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack, pd->p_len,
4133 			    ackskew, (unsigned long long)(*state)->packets[0],
4134 			    (unsigned long long)(*state)->packets[1],
4135 			    pd->dir == PF_IN ? "in" : "out",
4136 			    pd->dir == (*state)->direction ? "fwd" : "rev");
4137 		}
4138 
4139 		if (dst->scrub || src->scrub) {
4140 			if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4141 			    *state, src, dst, copyback))
4142 				return (PF_DROP);
4143 		}
4144 
4145 		/* update max window */
4146 		if (src->max_win < win)
4147 			src->max_win = win;
4148 		/* synchronize sequencing */
4149 		if (SEQ_GT(end, src->seqlo))
4150 			src->seqlo = end;
4151 		/* slide the window of what the other end can send */
4152 		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4153 			dst->seqhi = ack + MAX((win << sws), 1);
4154 
4155 		/*
4156 		 * Cannot set dst->seqhi here since this could be a shotgunned
4157 		 * SYN and not an already established connection.
4158 		 */
4159 
4160 		if (th->th_flags & TH_FIN)
4161 			if (src->state < TCPS_CLOSING)
4162 				src->state = TCPS_CLOSING;
4163 		if (th->th_flags & TH_RST)
4164 			src->state = dst->state = TCPS_TIME_WAIT;
4165 
4166 		/* Fall through to PASS packet */
4167 
4168 	} else if ((*state)->pickup_mode == PF_PICKUPS_HASHONLY ||
4169 		    ((*state)->pickup_mode == PF_PICKUPS_ENABLED &&
4170 		     ((*state)->sync_flags & PFSTATE_GOT_SYN_MASK) !=
4171 		      PFSTATE_GOT_SYN_MASK)) {
4172 		/*
4173 		 * If pickup mode is hash only, do not fail on sequence checks.
4174 		 *
4175 		 * If pickup mode is enabled and we did not see the SYN in
4176 		 * both direction, do not fail on sequence checks because
4177 		 * we do not have complete information on window scale.
4178 		 *
4179 		 * Adjust expiration and fall through to PASS packet.
4180 		 * XXX Add a FIN check to reduce timeout?
4181 		 */
4182 		(*state)->expire = time_second;
4183 	} else  {
4184 		/*
4185 		 * Failure processing
4186 		 */
4187 		if ((*state)->dst.state == TCPS_SYN_SENT &&
4188 		    (*state)->src.state == TCPS_SYN_SENT) {
4189 			/* Send RST for state mismatches during handshake */
4190 			if (!(th->th_flags & TH_RST))
4191 				pf_send_tcp((*state)->rule.ptr, pd->af,
4192 				    pd->dst, pd->src, th->th_dport,
4193 				    th->th_sport, ntohl(th->th_ack), 0,
4194 				    TH_RST, 0, 0,
4195 				    (*state)->rule.ptr->return_ttl, 1, 0,
4196 				    pd->eh, kif->pfik_ifp);
4197 			src->seqlo = 0;
4198 			src->seqhi = 1;
4199 			src->max_win = 1;
4200 		} else if (pf_status.debug >= PF_DEBUG_MISC) {
4201 			kprintf("pf: BAD state: ");
4202 			pf_print_state(*state);
4203 			pf_print_flags(th->th_flags);
4204 			kprintf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4205 			    "pkts=%llu:%llu dir=%s,%s\n",
4206 			    seq, orig_seq, ack, pd->p_len, ackskew,
4207 			    (unsigned long long)(*state)->packets[0],
4208 				(unsigned long long)(*state)->packets[1],
4209 			    pd->dir == PF_IN ? "in" : "out",
4210 			    pd->dir == (*state)->direction ? "fwd" : "rev");
4211 			kprintf("pf: State failure on: %c %c %c %c | %c %c\n",
4212 			    SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4213 			    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4214 			    ' ': '2',
4215 			    (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4216 			    (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4217 			    SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4218 			    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4219 		}
4220 		REASON_SET(reason, PFRES_BADSTATE);
4221 		return (PF_DROP);
4222 	}
4223 
4224 	return (PF_PASS);
4225 }
4226 
4227 int
4228 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4229 	struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4230 {
4231 	struct tcphdr		*th = pd->hdr.tcp;
4232 
4233 	if (th->th_flags & TH_SYN)
4234 		if (src->state < TCPS_SYN_SENT)
4235 			src->state = TCPS_SYN_SENT;
4236 	if (th->th_flags & TH_FIN)
4237 		if (src->state < TCPS_CLOSING)
4238 			src->state = TCPS_CLOSING;
4239 	if (th->th_flags & TH_ACK) {
4240 		if (dst->state == TCPS_SYN_SENT) {
4241 			dst->state = TCPS_ESTABLISHED;
4242 			if (src->state == TCPS_ESTABLISHED &&
4243 			    (*state)->src_node != NULL &&
4244 			    pf_src_connlimit(state)) {
4245 				REASON_SET(reason, PFRES_SRCLIMIT);
4246 				return (PF_DROP);
4247 			}
4248 		} else if (dst->state == TCPS_CLOSING) {
4249 			dst->state = TCPS_FIN_WAIT_2;
4250 		} else if (src->state == TCPS_SYN_SENT &&
4251 		    dst->state < TCPS_SYN_SENT) {
4252 			/*
4253 			 * Handle a special sloppy case where we only see one
4254 			 * half of the connection. If there is a ACK after
4255 			 * the initial SYN without ever seeing a packet from
4256 			 * the destination, set the connection to established.
4257 			 */
4258 			dst->state = src->state = TCPS_ESTABLISHED;
4259 			if ((*state)->src_node != NULL &&
4260 			    pf_src_connlimit(state)) {
4261 				REASON_SET(reason, PFRES_SRCLIMIT);
4262 				return (PF_DROP);
4263 			}
4264 		} else if (src->state == TCPS_CLOSING &&
4265 		    dst->state == TCPS_ESTABLISHED &&
4266 		    dst->seqlo == 0) {
4267 			/*
4268 			 * Handle the closing of half connections where we
4269 			 * don't see the full bidirectional FIN/ACK+ACK
4270 			 * handshake.
4271 			 */
4272 			dst->state = TCPS_CLOSING;
4273 		}
4274 	}
4275 	if (th->th_flags & TH_RST)
4276 		src->state = dst->state = TCPS_TIME_WAIT;
4277 
4278 	/* update expire time */
4279 	(*state)->expire = time_second;
4280 	if (src->state >= TCPS_FIN_WAIT_2 &&
4281 	    dst->state >= TCPS_FIN_WAIT_2)
4282 		(*state)->timeout = PFTM_TCP_CLOSED;
4283 	else if (src->state >= TCPS_CLOSING &&
4284 	    dst->state >= TCPS_CLOSING)
4285 		(*state)->timeout = PFTM_TCP_FIN_WAIT;
4286 	else if (src->state < TCPS_ESTABLISHED ||
4287 	    dst->state < TCPS_ESTABLISHED)
4288 		(*state)->timeout = PFTM_TCP_OPENING;
4289 	else if (src->state >= TCPS_CLOSING ||
4290 	    dst->state >= TCPS_CLOSING)
4291 		(*state)->timeout = PFTM_TCP_CLOSING;
4292 	else
4293 		(*state)->timeout = PFTM_TCP_ESTABLISHED;
4294 
4295 	return (PF_PASS);
4296 }
4297 
4298 int
4299 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4300     struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4301     u_short *reason)
4302 {
4303 	struct pf_state_key_cmp	 key;
4304 	struct tcphdr		*th = pd->hdr.tcp;
4305 	int			 copyback = 0;
4306 	struct pf_state_peer	*src, *dst;
4307 	struct pf_state_key	*sk;
4308 
4309 	key.af = pd->af;
4310 	key.proto = IPPROTO_TCP;
4311 	if (direction == PF_IN)	{	/* wire side, straight */
4312 		PF_ACPY(&key.addr[0], pd->src, key.af);
4313 		PF_ACPY(&key.addr[1], pd->dst, key.af);
4314 		key.port[0] = th->th_sport;
4315 		key.port[1] = th->th_dport;
4316 	} else {			/* stack side, reverse */
4317 		PF_ACPY(&key.addr[1], pd->src, key.af);
4318 		PF_ACPY(&key.addr[0], pd->dst, key.af);
4319 		key.port[1] = th->th_sport;
4320 		key.port[0] = th->th_dport;
4321 	}
4322 
4323 	STATE_LOOKUP(kif, &key, direction, *state, m);
4324 
4325 	if (direction == (*state)->direction) {
4326 		src = &(*state)->src;
4327 		dst = &(*state)->dst;
4328 	} else {
4329 		src = &(*state)->dst;
4330 		dst = &(*state)->src;
4331 	}
4332 
4333 	sk = (*state)->key[pd->didx];
4334 
4335 	if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4336 		if (direction != (*state)->direction) {
4337 			REASON_SET(reason, PFRES_SYNPROXY);
4338 			return (PF_SYNPROXY_DROP);
4339 		}
4340 		if (th->th_flags & TH_SYN) {
4341 			if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4342 				REASON_SET(reason, PFRES_SYNPROXY);
4343 				return (PF_DROP);
4344 			}
4345 			pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
4346 			    pd->src, th->th_dport, th->th_sport,
4347 			    (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4348 			    TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1,
4349 			    0, NULL, NULL);
4350 			REASON_SET(reason, PFRES_SYNPROXY);
4351 			return (PF_SYNPROXY_DROP);
4352 		} else if (!(th->th_flags & TH_ACK) ||
4353 		    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4354 		    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4355 			REASON_SET(reason, PFRES_SYNPROXY);
4356 			return (PF_DROP);
4357 		} else if ((*state)->src_node != NULL &&
4358 		    pf_src_connlimit(state)) {
4359 			REASON_SET(reason, PFRES_SRCLIMIT);
4360 			return (PF_DROP);
4361 		} else
4362 			(*state)->src.state = PF_TCPS_PROXY_DST;
4363 	}
4364 	if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4365 		if (direction == (*state)->direction) {
4366 			if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4367 			    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4368 			    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4369 				REASON_SET(reason, PFRES_SYNPROXY);
4370 				return (PF_DROP);
4371 			}
4372 			(*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4373 			if ((*state)->dst.seqhi == 1)
4374 				(*state)->dst.seqhi = htonl(karc4random());
4375 			pf_send_tcp((*state)->rule.ptr, pd->af,
4376 			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
4377 			    sk->port[pd->sidx], sk->port[pd->didx],
4378 			    (*state)->dst.seqhi, 0, TH_SYN, 0,
4379 			    (*state)->src.mss, 0, 0, (*state)->tag, NULL, NULL);
4380 			REASON_SET(reason, PFRES_SYNPROXY);
4381 			return (PF_SYNPROXY_DROP);
4382 		} else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4383 		    (TH_SYN|TH_ACK)) ||
4384 		    (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4385 			REASON_SET(reason, PFRES_SYNPROXY);
4386 			return (PF_DROP);
4387 		} else {
4388 			(*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4389 			(*state)->dst.seqlo = ntohl(th->th_seq);
4390 			pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
4391 			    pd->src, th->th_dport, th->th_sport,
4392 			    ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4393 			    TH_ACK, (*state)->src.max_win, 0, 0, 0,
4394 			    (*state)->tag, NULL, NULL);
4395 			pf_send_tcp((*state)->rule.ptr, pd->af,
4396 			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
4397 			    sk->port[pd->sidx], sk->port[pd->didx],
4398 			    (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4399 			    TH_ACK, (*state)->dst.max_win, 0, 0, 1,
4400 			    0, NULL, NULL);
4401 			(*state)->src.seqdiff = (*state)->dst.seqhi -
4402 			    (*state)->src.seqlo;
4403 			(*state)->dst.seqdiff = (*state)->src.seqhi -
4404 			    (*state)->dst.seqlo;
4405 			(*state)->src.seqhi = (*state)->src.seqlo +
4406 			    (*state)->dst.max_win;
4407 			(*state)->dst.seqhi = (*state)->dst.seqlo +
4408 			    (*state)->src.max_win;
4409 			(*state)->src.wscale = (*state)->dst.wscale = 0;
4410 			(*state)->src.state = (*state)->dst.state =
4411 			    TCPS_ESTABLISHED;
4412 			REASON_SET(reason, PFRES_SYNPROXY);
4413 			return (PF_SYNPROXY_DROP);
4414 		}
4415 	}
4416 
4417 	if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4418 	    dst->state >= TCPS_FIN_WAIT_2 &&
4419 	    src->state >= TCPS_FIN_WAIT_2) {
4420 		if (pf_status.debug >= PF_DEBUG_MISC) {
4421 			kprintf("pf: state reuse ");
4422 			pf_print_state(*state);
4423 			pf_print_flags(th->th_flags);
4424 			kprintf("\n");
4425 		}
4426 		/* XXX make sure it's the same direction ?? */
4427 		(*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4428 		pf_unlink_state(*state);
4429 		*state = NULL;
4430 		return (PF_DROP);
4431 	}
4432 
4433 	if ((*state)->state_flags & PFSTATE_SLOPPY) {
4434 		if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4435 			return (PF_DROP);
4436 	} else {
4437 		if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4438 		    &copyback) == PF_DROP)
4439 			return (PF_DROP);
4440 	}
4441 
4442 	/* translate source/destination address, if necessary */
4443 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4444 		struct pf_state_key *nk = (*state)->key[pd->didx];
4445 
4446 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4447 		    nk->port[pd->sidx] != th->th_sport)  {
4448 			/*
4449 			 * The translated source address may be completely
4450 			 * unrelated to the saved link header, make sure
4451 			 * a bridge doesn't try to use it.
4452 			 */
4453 			m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
4454 			m->m_flags &= ~M_HASH;
4455 			pf_change_ap(pd->src, &th->th_sport, pd->ip_sum,
4456 			    &th->th_sum, &nk->addr[pd->sidx],
4457 			    nk->port[pd->sidx], 0, pd->af);
4458 		}
4459 
4460 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4461 		    nk->port[pd->didx] != th->th_dport) {
4462 			/*
4463 			 * If we don't redispatch the packet will go into
4464 			 * the protocol stack on the wrong cpu for the
4465 			 * post-translated address.
4466 			 */
4467 			m->m_flags &= ~M_HASH;
4468 			pf_change_ap(pd->dst, &th->th_dport, pd->ip_sum,
4469 			    &th->th_sum, &nk->addr[pd->didx],
4470 			    nk->port[pd->didx], 0, pd->af);
4471 		}
4472 		copyback = 1;
4473 	}
4474 
4475 	/* Copyback sequence modulation or stateful scrub changes if needed */
4476 	if (copyback)
4477 		m_copyback(m, off, sizeof(*th), (caddr_t)th);
4478 
4479 	return (PF_PASS);
4480 }
4481 
4482 int
4483 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4484     struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4485 {
4486 	struct pf_state_peer	*src, *dst;
4487 	struct pf_state_key_cmp	 key;
4488 	struct udphdr		*uh = pd->hdr.udp;
4489 
4490 	key.af = pd->af;
4491 	key.proto = IPPROTO_UDP;
4492 	if (direction == PF_IN)	{	/* wire side, straight */
4493 		PF_ACPY(&key.addr[0], pd->src, key.af);
4494 		PF_ACPY(&key.addr[1], pd->dst, key.af);
4495 		key.port[0] = uh->uh_sport;
4496 		key.port[1] = uh->uh_dport;
4497 	} else {			/* stack side, reverse */
4498 		PF_ACPY(&key.addr[1], pd->src, key.af);
4499 		PF_ACPY(&key.addr[0], pd->dst, key.af);
4500 		key.port[1] = uh->uh_sport;
4501 		key.port[0] = uh->uh_dport;
4502 	}
4503 
4504 	STATE_LOOKUP(kif, &key, direction, *state, m);
4505 
4506 	if (direction == (*state)->direction) {
4507 		src = &(*state)->src;
4508 		dst = &(*state)->dst;
4509 	} else {
4510 		src = &(*state)->dst;
4511 		dst = &(*state)->src;
4512 	}
4513 
4514 	/* update states */
4515 	if (src->state < PFUDPS_SINGLE)
4516 		src->state = PFUDPS_SINGLE;
4517 	if (dst->state == PFUDPS_SINGLE)
4518 		dst->state = PFUDPS_MULTIPLE;
4519 
4520 	/* update expire time */
4521 	(*state)->expire = time_second;
4522 	if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4523 		(*state)->timeout = PFTM_UDP_MULTIPLE;
4524 	else
4525 		(*state)->timeout = PFTM_UDP_SINGLE;
4526 
4527 	/* translate source/destination address, if necessary */
4528 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4529 		struct pf_state_key *nk = (*state)->key[pd->didx];
4530 
4531 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4532 		    nk->port[pd->sidx] != uh->uh_sport) {
4533 			/*
4534 			 * The translated source address may be completely
4535 			 * unrelated to the saved link header, make sure
4536 			 * a bridge doesn't try to use it.
4537 			 */
4538 			m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
4539 			m->m_flags &= ~M_HASH;
4540 			pf_change_ap(pd->src, &uh->uh_sport, pd->ip_sum,
4541 			    &uh->uh_sum, &nk->addr[pd->sidx],
4542 			    nk->port[pd->sidx], 1, pd->af);
4543 		}
4544 
4545 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4546 		    nk->port[pd->didx] != uh->uh_dport) {
4547 			/*
4548 			 * If we don't redispatch the packet will go into
4549 			 * the protocol stack on the wrong cpu for the
4550 			 * post-translated address.
4551 			 */
4552 			m->m_flags &= ~M_HASH;
4553 			pf_change_ap(pd->dst, &uh->uh_dport, pd->ip_sum,
4554 			    &uh->uh_sum, &nk->addr[pd->didx],
4555 			    nk->port[pd->didx], 1, pd->af);
4556 		}
4557 		m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4558 	}
4559 
4560 	return (PF_PASS);
4561 }
4562 
4563 int
4564 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4565     struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4566 {
4567 	struct pf_addr	*saddr = pd->src, *daddr = pd->dst;
4568 	u_int16_t	 icmpid = 0, *icmpsum;
4569 	u_int8_t	 icmptype;
4570 	int		 state_icmp = 0;
4571 	struct pf_state_key_cmp key;
4572 
4573 	switch (pd->proto) {
4574 #ifdef INET
4575 	case IPPROTO_ICMP:
4576 		icmptype = pd->hdr.icmp->icmp_type;
4577 		icmpid = pd->hdr.icmp->icmp_id;
4578 		icmpsum = &pd->hdr.icmp->icmp_cksum;
4579 
4580 		if (icmptype == ICMP_UNREACH ||
4581 		    icmptype == ICMP_SOURCEQUENCH ||
4582 		    icmptype == ICMP_REDIRECT ||
4583 		    icmptype == ICMP_TIMXCEED ||
4584 		    icmptype == ICMP_PARAMPROB)
4585 			state_icmp++;
4586 		break;
4587 #endif /* INET */
4588 #ifdef INET6
4589 	case IPPROTO_ICMPV6:
4590 		icmptype = pd->hdr.icmp6->icmp6_type;
4591 		icmpid = pd->hdr.icmp6->icmp6_id;
4592 		icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4593 
4594 		if (icmptype == ICMP6_DST_UNREACH ||
4595 		    icmptype == ICMP6_PACKET_TOO_BIG ||
4596 		    icmptype == ICMP6_TIME_EXCEEDED ||
4597 		    icmptype == ICMP6_PARAM_PROB)
4598 			state_icmp++;
4599 		break;
4600 #endif /* INET6 */
4601 	}
4602 
4603 	if (!state_icmp) {
4604 
4605 		/*
4606 		 * ICMP query/reply message not related to a TCP/UDP packet.
4607 		 * Search for an ICMP state.
4608 		 */
4609 		key.af = pd->af;
4610 		key.proto = pd->proto;
4611 		key.port[0] = key.port[1] = icmpid;
4612 		if (direction == PF_IN)	{	/* wire side, straight */
4613 			PF_ACPY(&key.addr[0], pd->src, key.af);
4614 			PF_ACPY(&key.addr[1], pd->dst, key.af);
4615 		} else {			/* stack side, reverse */
4616 			PF_ACPY(&key.addr[1], pd->src, key.af);
4617 			PF_ACPY(&key.addr[0], pd->dst, key.af);
4618 		}
4619 
4620 		STATE_LOOKUP(kif, &key, direction, *state, m);
4621 
4622 		(*state)->expire = time_second;
4623 		(*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4624 
4625 		/* translate source/destination address, if necessary */
4626 		if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4627 			struct pf_state_key *nk = (*state)->key[pd->didx];
4628 
4629 			switch (pd->af) {
4630 #ifdef INET
4631 			case AF_INET:
4632 				if (PF_ANEQ(pd->src,
4633 				    &nk->addr[pd->sidx], AF_INET))
4634 					pf_change_a(&saddr->v4.s_addr,
4635 					    pd->ip_sum,
4636 					    nk->addr[pd->sidx].v4.s_addr, 0);
4637 
4638 				if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4639 				    AF_INET))
4640 					pf_change_a(&daddr->v4.s_addr,
4641 					    pd->ip_sum,
4642 					    nk->addr[pd->didx].v4.s_addr, 0);
4643 
4644 				if (nk->port[0] !=
4645 				    pd->hdr.icmp->icmp_id) {
4646 					pd->hdr.icmp->icmp_cksum =
4647 					    pf_cksum_fixup(
4648 					    pd->hdr.icmp->icmp_cksum, icmpid,
4649 					    nk->port[pd->sidx], 0);
4650 					pd->hdr.icmp->icmp_id =
4651 					    nk->port[pd->sidx];
4652 				}
4653 
4654 				m_copyback(m, off, ICMP_MINLEN,
4655 				    (caddr_t)pd->hdr.icmp);
4656 				break;
4657 #endif /* INET */
4658 #ifdef INET6
4659 			case AF_INET6:
4660 				if (PF_ANEQ(pd->src,
4661 				    &nk->addr[pd->sidx], AF_INET6))
4662 					pf_change_a6(saddr,
4663 					    &pd->hdr.icmp6->icmp6_cksum,
4664 					    &nk->addr[pd->sidx], 0);
4665 
4666 				if (PF_ANEQ(pd->dst,
4667 				    &nk->addr[pd->didx], AF_INET6))
4668 					pf_change_a6(daddr,
4669 					    &pd->hdr.icmp6->icmp6_cksum,
4670 					    &nk->addr[pd->didx], 0);
4671 
4672 				m_copyback(m, off,
4673 					sizeof(struct icmp6_hdr),
4674 					(caddr_t)pd->hdr.icmp6);
4675 				break;
4676 #endif /* INET6 */
4677 			}
4678 		}
4679 		return (PF_PASS);
4680 
4681 	} else {
4682 		/*
4683 		 * ICMP error message in response to a TCP/UDP packet.
4684 		 * Extract the inner TCP/UDP header and search for that state.
4685 		 */
4686 
4687 		struct pf_pdesc	pd2;
4688 #ifdef INET
4689 		struct ip	h2;
4690 #endif /* INET */
4691 #ifdef INET6
4692 		struct ip6_hdr	h2_6;
4693 		int		terminal = 0;
4694 #endif /* INET6 */
4695 		int		ipoff2;
4696 		int		off2;
4697 
4698 		pd2.af = pd->af;
4699 		/* Payload packet is from the opposite direction. */
4700 		pd2.sidx = (direction == PF_IN) ? 1 : 0;
4701 		pd2.didx = (direction == PF_IN) ? 0 : 1;
4702 		switch (pd->af) {
4703 #ifdef INET
4704 		case AF_INET:
4705 			/* offset of h2 in mbuf chain */
4706 			ipoff2 = off + ICMP_MINLEN;
4707 
4708 			if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4709 			    NULL, reason, pd2.af)) {
4710 				DPFPRINTF(PF_DEBUG_MISC,
4711 				    ("pf: ICMP error message too short "
4712 				    "(ip)\n"));
4713 				return (PF_DROP);
4714 			}
4715 			/*
4716 			 * ICMP error messages don't refer to non-first
4717 			 * fragments
4718 			 */
4719 			if (h2.ip_off & htons(IP_OFFMASK)) {
4720 				REASON_SET(reason, PFRES_FRAG);
4721 				return (PF_DROP);
4722 			}
4723 
4724 			/* offset of protocol header that follows h2 */
4725 			off2 = ipoff2 + (h2.ip_hl << 2);
4726 
4727 			pd2.proto = h2.ip_p;
4728 			pd2.src = (struct pf_addr *)&h2.ip_src;
4729 			pd2.dst = (struct pf_addr *)&h2.ip_dst;
4730 			pd2.ip_sum = &h2.ip_sum;
4731 			break;
4732 #endif /* INET */
4733 #ifdef INET6
4734 		case AF_INET6:
4735 			ipoff2 = off + sizeof(struct icmp6_hdr);
4736 
4737 			if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4738 			    NULL, reason, pd2.af)) {
4739 				DPFPRINTF(PF_DEBUG_MISC,
4740 				    ("pf: ICMP error message too short "
4741 				    "(ip6)\n"));
4742 				return (PF_DROP);
4743 			}
4744 			pd2.proto = h2_6.ip6_nxt;
4745 			pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4746 			pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4747 			pd2.ip_sum = NULL;
4748 			off2 = ipoff2 + sizeof(h2_6);
4749 			do {
4750 				switch (pd2.proto) {
4751 				case IPPROTO_FRAGMENT:
4752 					/*
4753 					 * ICMPv6 error messages for
4754 					 * non-first fragments
4755 					 */
4756 					REASON_SET(reason, PFRES_FRAG);
4757 					return (PF_DROP);
4758 				case IPPROTO_AH:
4759 				case IPPROTO_HOPOPTS:
4760 				case IPPROTO_ROUTING:
4761 				case IPPROTO_DSTOPTS: {
4762 					/* get next header and header length */
4763 					struct ip6_ext opt6;
4764 
4765 					if (!pf_pull_hdr(m, off2, &opt6,
4766 					    sizeof(opt6), NULL, reason,
4767 					    pd2.af)) {
4768 						DPFPRINTF(PF_DEBUG_MISC,
4769 						    ("pf: ICMPv6 short opt\n"));
4770 						return (PF_DROP);
4771 					}
4772 					if (pd2.proto == IPPROTO_AH)
4773 						off2 += (opt6.ip6e_len + 2) * 4;
4774 					else
4775 						off2 += (opt6.ip6e_len + 1) * 8;
4776 					pd2.proto = opt6.ip6e_nxt;
4777 					/* goto the next header */
4778 					break;
4779 				}
4780 				default:
4781 					terminal++;
4782 					break;
4783 				}
4784 			} while (!terminal);
4785 			break;
4786 #endif /* INET6 */
4787 		default:
4788 			DPFPRINTF(PF_DEBUG_MISC,
4789 			    ("pf: ICMP AF %d unknown (ip6)\n", pd->af));
4790 			return (PF_DROP);
4791 			break;
4792 		}
4793 
4794 		switch (pd2.proto) {
4795 		case IPPROTO_TCP: {
4796 			struct tcphdr		 th;
4797 			u_int32_t		 seq;
4798 			struct pf_state_peer	*src, *dst;
4799 			u_int8_t		 dws;
4800 			int			 copyback = 0;
4801 
4802 			/*
4803 			 * Only the first 8 bytes of the TCP header can be
4804 			 * expected. Don't access any TCP header fields after
4805 			 * th_seq, an ackskew test is not possible.
4806 			 */
4807 			if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4808 			    pd2.af)) {
4809 				DPFPRINTF(PF_DEBUG_MISC,
4810 				    ("pf: ICMP error message too short "
4811 				    "(tcp)\n"));
4812 				return (PF_DROP);
4813 			}
4814 
4815 			key.af = pd2.af;
4816 			key.proto = IPPROTO_TCP;
4817 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4818 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4819 			key.port[pd2.sidx] = th.th_sport;
4820 			key.port[pd2.didx] = th.th_dport;
4821 
4822 			STATE_LOOKUP(kif, &key, direction, *state, m);
4823 
4824 			if (direction == (*state)->direction) {
4825 				src = &(*state)->dst;
4826 				dst = &(*state)->src;
4827 			} else {
4828 				src = &(*state)->src;
4829 				dst = &(*state)->dst;
4830 			}
4831 
4832 			if (src->wscale && dst->wscale)
4833 				dws = dst->wscale & PF_WSCALE_MASK;
4834 			else
4835 				dws = 0;
4836 
4837 			/* Demodulate sequence number */
4838 			seq = ntohl(th.th_seq) - src->seqdiff;
4839 			if (src->seqdiff) {
4840 				pf_change_a(&th.th_seq, icmpsum,
4841 				    htonl(seq), 0);
4842 				copyback = 1;
4843 			}
4844 
4845 			if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4846 			    (!SEQ_GEQ(src->seqhi, seq) ||
4847 			    !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4848 				if (pf_status.debug >= PF_DEBUG_MISC) {
4849 					kprintf("pf: BAD ICMP %d:%d ",
4850 					    icmptype, pd->hdr.icmp->icmp_code);
4851 					pf_print_host(pd->src, 0, pd->af);
4852 					kprintf(" -> ");
4853 					pf_print_host(pd->dst, 0, pd->af);
4854 					kprintf(" state: ");
4855 					pf_print_state(*state);
4856 					kprintf(" seq=%u\n", seq);
4857 				}
4858 				REASON_SET(reason, PFRES_BADSTATE);
4859 				return (PF_DROP);
4860 			} else {
4861 				if (pf_status.debug >= PF_DEBUG_MISC) {
4862 					kprintf("pf: OK ICMP %d:%d ",
4863 					    icmptype, pd->hdr.icmp->icmp_code);
4864 					pf_print_host(pd->src, 0, pd->af);
4865 					kprintf(" -> ");
4866 					pf_print_host(pd->dst, 0, pd->af);
4867 					kprintf(" state: ");
4868 					pf_print_state(*state);
4869 					kprintf(" seq=%u\n", seq);
4870 				}
4871 			}
4872 
4873 			/* translate source/destination address, if necessary */
4874 			if ((*state)->key[PF_SK_WIRE] !=
4875 			    (*state)->key[PF_SK_STACK]) {
4876 				struct pf_state_key *nk =
4877 				    (*state)->key[pd->didx];
4878 
4879 				if (PF_ANEQ(pd2.src,
4880 				    &nk->addr[pd2.sidx], pd2.af) ||
4881 				    nk->port[pd2.sidx] != th.th_sport)
4882 					pf_change_icmp(pd2.src, &th.th_sport,
4883 					    daddr, &nk->addr[pd2.sidx],
4884 					    nk->port[pd2.sidx], NULL,
4885 					    pd2.ip_sum, icmpsum,
4886 					    pd->ip_sum, 0, pd2.af);
4887 
4888 				if (PF_ANEQ(pd2.dst,
4889 				    &nk->addr[pd2.didx], pd2.af) ||
4890 				    nk->port[pd2.didx] != th.th_dport)
4891 					pf_change_icmp(pd2.dst, &th.th_dport,
4892 					    NULL, /* XXX Inbound NAT? */
4893 					    &nk->addr[pd2.didx],
4894 					    nk->port[pd2.didx], NULL,
4895 					    pd2.ip_sum, icmpsum,
4896 					    pd->ip_sum, 0, pd2.af);
4897 				copyback = 1;
4898 			}
4899 
4900 			if (copyback) {
4901 				switch (pd2.af) {
4902 #ifdef INET
4903 				case AF_INET:
4904 					m_copyback(m, off, ICMP_MINLEN,
4905 					    (caddr_t)pd->hdr.icmp);
4906 					m_copyback(m, ipoff2, sizeof(h2),
4907 					    (caddr_t)&h2);
4908 					break;
4909 #endif /* INET */
4910 #ifdef INET6
4911 				case AF_INET6:
4912 					m_copyback(m, off,
4913 					    sizeof(struct icmp6_hdr),
4914 					    (caddr_t)pd->hdr.icmp6);
4915 					m_copyback(m, ipoff2, sizeof(h2_6),
4916 					    (caddr_t)&h2_6);
4917 					break;
4918 #endif /* INET6 */
4919 				}
4920 				m_copyback(m, off2, 8, (caddr_t)&th);
4921 			}
4922 
4923 			return (PF_PASS);
4924 			break;
4925 		}
4926 		case IPPROTO_UDP: {
4927 			struct udphdr		uh;
4928 
4929 			if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4930 			    NULL, reason, pd2.af)) {
4931 				DPFPRINTF(PF_DEBUG_MISC,
4932 				    ("pf: ICMP error message too short "
4933 				    "(udp)\n"));
4934 				return (PF_DROP);
4935 			}
4936 
4937 			key.af = pd2.af;
4938 			key.proto = IPPROTO_UDP;
4939 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4940 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4941 			key.port[pd2.sidx] = uh.uh_sport;
4942 			key.port[pd2.didx] = uh.uh_dport;
4943 
4944 			STATE_LOOKUP(kif, &key, direction, *state, m);
4945 
4946 			/* translate source/destination address, if necessary */
4947 			if ((*state)->key[PF_SK_WIRE] !=
4948 			    (*state)->key[PF_SK_STACK]) {
4949 				struct pf_state_key *nk =
4950 				    (*state)->key[pd->didx];
4951 
4952 				if (PF_ANEQ(pd2.src,
4953 				    &nk->addr[pd2.sidx], pd2.af) ||
4954 				    nk->port[pd2.sidx] != uh.uh_sport)
4955 					pf_change_icmp(pd2.src, &uh.uh_sport,
4956 					    daddr, &nk->addr[pd2.sidx],
4957 					    nk->port[pd2.sidx], &uh.uh_sum,
4958 					    pd2.ip_sum, icmpsum,
4959 					    pd->ip_sum, 1, pd2.af);
4960 
4961 				if (PF_ANEQ(pd2.dst,
4962 				    &nk->addr[pd2.didx], pd2.af) ||
4963 				    nk->port[pd2.didx] != uh.uh_dport)
4964 					pf_change_icmp(pd2.dst, &uh.uh_dport,
4965 					    NULL, /* XXX Inbound NAT? */
4966 					    &nk->addr[pd2.didx],
4967 					    nk->port[pd2.didx], &uh.uh_sum,
4968 					    pd2.ip_sum, icmpsum,
4969 					    pd->ip_sum, 1, pd2.af);
4970 
4971 				switch (pd2.af) {
4972 #ifdef INET
4973 				case AF_INET:
4974 					m_copyback(m, off, ICMP_MINLEN,
4975 					    (caddr_t)pd->hdr.icmp);
4976 					m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4977 					break;
4978 #endif /* INET */
4979 #ifdef INET6
4980 				case AF_INET6:
4981 					m_copyback(m, off,
4982 					    sizeof(struct icmp6_hdr),
4983 					    (caddr_t)pd->hdr.icmp6);
4984 					m_copyback(m, ipoff2, sizeof(h2_6),
4985 					    (caddr_t)&h2_6);
4986 					break;
4987 #endif /* INET6 */
4988 				}
4989 				m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
4990 			}
4991 
4992 			return (PF_PASS);
4993 			break;
4994 		}
4995 #ifdef INET
4996 		case IPPROTO_ICMP: {
4997 			struct icmp		iih;
4998 
4999 			if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
5000 			    NULL, reason, pd2.af)) {
5001 				DPFPRINTF(PF_DEBUG_MISC,
5002 				    ("pf: ICMP error message too short i"
5003 				    "(icmp)\n"));
5004 				return (PF_DROP);
5005 			}
5006 
5007 			key.af = pd2.af;
5008 			key.proto = IPPROTO_ICMP;
5009 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5010 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5011 			key.port[0] = key.port[1] = iih.icmp_id;
5012 
5013 			STATE_LOOKUP(kif, &key, direction, *state, m);
5014 
5015 			/* translate source/destination address, if necessary */
5016 			if ((*state)->key[PF_SK_WIRE] !=
5017 			    (*state)->key[PF_SK_STACK]) {
5018 				struct pf_state_key *nk =
5019 				    (*state)->key[pd->didx];
5020 
5021 				if (PF_ANEQ(pd2.src,
5022 				    &nk->addr[pd2.sidx], pd2.af) ||
5023 				    nk->port[pd2.sidx] != iih.icmp_id)
5024 					pf_change_icmp(pd2.src, &iih.icmp_id,
5025 					    daddr, &nk->addr[pd2.sidx],
5026 					    nk->port[pd2.sidx], NULL,
5027 					    pd2.ip_sum, icmpsum,
5028 					    pd->ip_sum, 0, AF_INET);
5029 
5030 				if (PF_ANEQ(pd2.dst,
5031 				    &nk->addr[pd2.didx], pd2.af) ||
5032 				    nk->port[pd2.didx] != iih.icmp_id)
5033 					pf_change_icmp(pd2.dst, &iih.icmp_id,
5034 					    NULL, /* XXX Inbound NAT? */
5035 					    &nk->addr[pd2.didx],
5036 					    nk->port[pd2.didx], NULL,
5037 					    pd2.ip_sum, icmpsum,
5038 					    pd->ip_sum, 0, AF_INET);
5039 
5040 				m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
5041 				m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5042 				m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5043 			}
5044 			return (PF_PASS);
5045 			break;
5046 		}
5047 #endif /* INET */
5048 #ifdef INET6
5049 		case IPPROTO_ICMPV6: {
5050 			struct icmp6_hdr	iih;
5051 
5052 			if (!pf_pull_hdr(m, off2, &iih,
5053 			    sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5054 				DPFPRINTF(PF_DEBUG_MISC,
5055 				    ("pf: ICMP error message too short "
5056 				    "(icmp6)\n"));
5057 				return (PF_DROP);
5058 			}
5059 
5060 			key.af = pd2.af;
5061 			key.proto = IPPROTO_ICMPV6;
5062 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5063 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5064 			key.port[0] = key.port[1] = iih.icmp6_id;
5065 
5066 			STATE_LOOKUP(kif, &key, direction, *state, m);
5067 
5068 			/* translate source/destination address, if necessary */
5069 			if ((*state)->key[PF_SK_WIRE] !=
5070 			    (*state)->key[PF_SK_STACK]) {
5071 				struct pf_state_key *nk =
5072 				    (*state)->key[pd->didx];
5073 
5074 				if (PF_ANEQ(pd2.src,
5075 				    &nk->addr[pd2.sidx], pd2.af) ||
5076 				    nk->port[pd2.sidx] != iih.icmp6_id)
5077 					pf_change_icmp(pd2.src, &iih.icmp6_id,
5078 					    daddr, &nk->addr[pd2.sidx],
5079 					    nk->port[pd2.sidx], NULL,
5080 					    pd2.ip_sum, icmpsum,
5081 					    pd->ip_sum, 0, AF_INET6);
5082 
5083 				if (PF_ANEQ(pd2.dst,
5084 				    &nk->addr[pd2.didx], pd2.af) ||
5085 				    nk->port[pd2.didx] != iih.icmp6_id)
5086 					pf_change_icmp(pd2.dst, &iih.icmp6_id,
5087 					    NULL, /* XXX Inbound NAT? */
5088 					    &nk->addr[pd2.didx],
5089 					    nk->port[pd2.didx], NULL,
5090 					    pd2.ip_sum, icmpsum,
5091 					    pd->ip_sum, 0, AF_INET6);
5092 
5093 				m_copyback(m, off, sizeof(struct icmp6_hdr),
5094 				    (caddr_t)pd->hdr.icmp6);
5095 				m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5096 				m_copyback(m, off2, sizeof(struct icmp6_hdr),
5097 				    (caddr_t)&iih);
5098 			}
5099 
5100 			return (PF_PASS);
5101 			break;
5102 		}
5103 #endif /* INET6 */
5104 		default: {
5105 			key.af = pd2.af;
5106 			key.proto = pd2.proto;
5107 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5108 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5109 			key.port[0] = key.port[1] = 0;
5110 
5111 			STATE_LOOKUP(kif, &key, direction, *state, m);
5112 
5113 			/* translate source/destination address, if necessary */
5114 			if ((*state)->key[PF_SK_WIRE] !=
5115 			    (*state)->key[PF_SK_STACK]) {
5116 				struct pf_state_key *nk =
5117 				    (*state)->key[pd->didx];
5118 
5119 				if (PF_ANEQ(pd2.src,
5120 				    &nk->addr[pd2.sidx], pd2.af))
5121 					pf_change_icmp(pd2.src, NULL, daddr,
5122 					    &nk->addr[pd2.sidx], 0, NULL,
5123 					    pd2.ip_sum, icmpsum,
5124 					    pd->ip_sum, 0, pd2.af);
5125 
5126 				if (PF_ANEQ(pd2.dst,
5127 				    &nk->addr[pd2.didx], pd2.af))
5128 					pf_change_icmp(pd2.src, NULL,
5129 					    NULL, /* XXX Inbound NAT? */
5130 					    &nk->addr[pd2.didx], 0, NULL,
5131 					    pd2.ip_sum, icmpsum,
5132 					    pd->ip_sum, 0, pd2.af);
5133 
5134 				switch (pd2.af) {
5135 #ifdef INET
5136 				case AF_INET:
5137 					m_copyback(m, off, ICMP_MINLEN,
5138 					    (caddr_t)pd->hdr.icmp);
5139 					m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5140 					break;
5141 #endif /* INET */
5142 #ifdef INET6
5143 				case AF_INET6:
5144 					m_copyback(m, off,
5145 					    sizeof(struct icmp6_hdr),
5146 					    (caddr_t)pd->hdr.icmp6);
5147 					m_copyback(m, ipoff2, sizeof(h2_6),
5148 					    (caddr_t)&h2_6);
5149 					break;
5150 #endif /* INET6 */
5151 				}
5152 			}
5153 			return (PF_PASS);
5154 			break;
5155 		}
5156 		}
5157 	}
5158 }
5159 
5160 int
5161 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5162     struct mbuf *m, struct pf_pdesc *pd)
5163 {
5164 	struct pf_state_peer	*src, *dst;
5165 	struct pf_state_key_cmp	 key;
5166 
5167 	key.af = pd->af;
5168 	key.proto = pd->proto;
5169 	if (direction == PF_IN)	{
5170 		PF_ACPY(&key.addr[0], pd->src, key.af);
5171 		PF_ACPY(&key.addr[1], pd->dst, key.af);
5172 		key.port[0] = key.port[1] = 0;
5173 	} else {
5174 		PF_ACPY(&key.addr[1], pd->src, key.af);
5175 		PF_ACPY(&key.addr[0], pd->dst, key.af);
5176 		key.port[1] = key.port[0] = 0;
5177 	}
5178 
5179 	STATE_LOOKUP(kif, &key, direction, *state, m);
5180 
5181 	if (direction == (*state)->direction) {
5182 		src = &(*state)->src;
5183 		dst = &(*state)->dst;
5184 	} else {
5185 		src = &(*state)->dst;
5186 		dst = &(*state)->src;
5187 	}
5188 
5189 	/* update states */
5190 	if (src->state < PFOTHERS_SINGLE)
5191 		src->state = PFOTHERS_SINGLE;
5192 	if (dst->state == PFOTHERS_SINGLE)
5193 		dst->state = PFOTHERS_MULTIPLE;
5194 
5195 	/* update expire time */
5196 	(*state)->expire = time_second;
5197 	if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5198 		(*state)->timeout = PFTM_OTHER_MULTIPLE;
5199 	else
5200 		(*state)->timeout = PFTM_OTHER_SINGLE;
5201 
5202 	/* translate source/destination address, if necessary */
5203 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5204 		struct pf_state_key *nk = (*state)->key[pd->didx];
5205 
5206 		KKASSERT(nk);
5207 		KKASSERT(pd);
5208 		KKASSERT(pd->src);
5209 		KKASSERT(pd->dst);
5210 		switch (pd->af) {
5211 #ifdef INET
5212 		case AF_INET:
5213 			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5214 				pf_change_a(&pd->src->v4.s_addr,
5215 				    pd->ip_sum,
5216 				    nk->addr[pd->sidx].v4.s_addr,
5217 				    0);
5218 
5219 
5220 			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5221 				pf_change_a(&pd->dst->v4.s_addr,
5222 				    pd->ip_sum,
5223 				    nk->addr[pd->didx].v4.s_addr,
5224 				    0);
5225 
5226 			break;
5227 #endif /* INET */
5228 #ifdef INET6
5229 		case AF_INET6:
5230 			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5231 				PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5232 
5233 			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5234 				PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5235 #endif /* INET6 */
5236 		}
5237 	}
5238 	return (PF_PASS);
5239 }
5240 
5241 /*
5242  * ipoff and off are measured from the start of the mbuf chain.
5243  * h must be at "ipoff" on the mbuf chain.
5244  */
5245 void *
5246 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5247     u_short *actionp, u_short *reasonp, sa_family_t af)
5248 {
5249 	switch (af) {
5250 #ifdef INET
5251 	case AF_INET: {
5252 		struct ip	*h = mtod(m, struct ip *);
5253 		u_int16_t	 fragoff = (h->ip_off & IP_OFFMASK) << 3;
5254 
5255 		if (fragoff) {
5256 			if (fragoff >= len)
5257 				ACTION_SET(actionp, PF_PASS);
5258 			else {
5259 				ACTION_SET(actionp, PF_DROP);
5260 				REASON_SET(reasonp, PFRES_FRAG);
5261 			}
5262 			return (NULL);
5263 		}
5264 		if (m->m_pkthdr.len < off + len ||
5265 		    h->ip_len < off + len) {
5266 			ACTION_SET(actionp, PF_DROP);
5267 			REASON_SET(reasonp, PFRES_SHORT);
5268 			return (NULL);
5269 		}
5270 		break;
5271 	}
5272 #endif /* INET */
5273 #ifdef INET6
5274 	case AF_INET6: {
5275 		struct ip6_hdr	*h = mtod(m, struct ip6_hdr *);
5276 
5277 		if (m->m_pkthdr.len < off + len ||
5278 		    (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5279 		    (unsigned)(off + len)) {
5280 			ACTION_SET(actionp, PF_DROP);
5281 			REASON_SET(reasonp, PFRES_SHORT);
5282 			return (NULL);
5283 		}
5284 		break;
5285 	}
5286 #endif /* INET6 */
5287 	}
5288 	m_copydata(m, off, len, p);
5289 	return (p);
5290 }
5291 
5292 int
5293 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif)
5294 {
5295 	struct sockaddr_in	*dst;
5296 	int			 ret = 1;
5297 	int			 check_mpath;
5298 #ifdef INET6
5299 	struct sockaddr_in6	*dst6;
5300 	struct route_in6	 ro;
5301 #else
5302 	struct route		 ro;
5303 #endif
5304 	struct radix_node	*rn;
5305 	struct rtentry		*rt;
5306 	struct ifnet		*ifp;
5307 
5308 	check_mpath = 0;
5309 	bzero(&ro, sizeof(ro));
5310 	switch (af) {
5311 	case AF_INET:
5312 		dst = satosin(&ro.ro_dst);
5313 		dst->sin_family = AF_INET;
5314 		dst->sin_len = sizeof(*dst);
5315 		dst->sin_addr = addr->v4;
5316 		break;
5317 #ifdef INET6
5318 	case AF_INET6:
5319 		dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5320 		dst6->sin6_family = AF_INET6;
5321 		dst6->sin6_len = sizeof(*dst6);
5322 		dst6->sin6_addr = addr->v6;
5323 		break;
5324 #endif /* INET6 */
5325 	default:
5326 		return (0);
5327 	}
5328 
5329 	/* Skip checks for ipsec interfaces */
5330 	if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5331 		goto out;
5332 
5333 	rtalloc_ign((struct route *)&ro, 0);
5334 
5335 	if (ro.ro_rt != NULL) {
5336 		/* No interface given, this is a no-route check */
5337 		if (kif == NULL)
5338 			goto out;
5339 
5340 		if (kif->pfik_ifp == NULL) {
5341 			ret = 0;
5342 			goto out;
5343 		}
5344 
5345 		/* Perform uRPF check if passed input interface */
5346 		ret = 0;
5347 		rn = (struct radix_node *)ro.ro_rt;
5348 		do {
5349 			rt = (struct rtentry *)rn;
5350 			ifp = rt->rt_ifp;
5351 
5352 			if (kif->pfik_ifp == ifp)
5353 				ret = 1;
5354 			rn = NULL;
5355 		} while (check_mpath == 1 && rn != NULL && ret == 0);
5356 	} else
5357 		ret = 0;
5358 out:
5359 	if (ro.ro_rt != NULL)
5360 		RTFREE(ro.ro_rt);
5361 	return (ret);
5362 }
5363 
5364 int
5365 pf_rtlabel_match(struct pf_addr *addr, sa_family_t af, struct pf_addr_wrap *aw)
5366 {
5367 	struct sockaddr_in	*dst;
5368 #ifdef INET6
5369 	struct sockaddr_in6	*dst6;
5370 	struct route_in6	 ro;
5371 #else
5372 	struct route		 ro;
5373 #endif
5374 	int			 ret = 0;
5375 
5376 	ASSERT_LWKT_TOKEN_HELD(&pf_token);
5377 
5378 	bzero(&ro, sizeof(ro));
5379 	switch (af) {
5380 	case AF_INET:
5381 		dst = satosin(&ro.ro_dst);
5382 		dst->sin_family = AF_INET;
5383 		dst->sin_len = sizeof(*dst);
5384 		dst->sin_addr = addr->v4;
5385 		break;
5386 #ifdef INET6
5387 	case AF_INET6:
5388 		dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5389 		dst6->sin6_family = AF_INET6;
5390 		dst6->sin6_len = sizeof(*dst6);
5391 		dst6->sin6_addr = addr->v6;
5392 		break;
5393 #endif /* INET6 */
5394 	default:
5395 		return (0);
5396 	}
5397 
5398 rtalloc_ign((struct route *)&ro, (RTF_CLONING | RTF_PRCLONING));
5399 
5400 	if (ro.ro_rt != NULL) {
5401 		RTFREE(ro.ro_rt);
5402 	}
5403 
5404 	return (ret);
5405 }
5406 
5407 #ifdef INET
5408 void
5409 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5410     struct pf_state *s, struct pf_pdesc *pd)
5411 {
5412 	struct mbuf		*m0, *m1;
5413 	struct route		 iproute;
5414 	struct route		*ro = NULL;
5415 	struct sockaddr_in	*dst;
5416 	struct ip		*ip;
5417 	struct ifnet		*ifp = NULL;
5418 	struct pf_addr		 naddr;
5419 	struct pf_src_node	*sn = NULL;
5420 	int			 error = 0;
5421 	int sw_csum;
5422 #ifdef IPSEC
5423 	struct m_tag		*mtag;
5424 #endif /* IPSEC */
5425 
5426 	ASSERT_LWKT_TOKEN_HELD(&pf_token);
5427 
5428 	if (m == NULL || *m == NULL || r == NULL ||
5429 	    (dir != PF_IN && dir != PF_OUT) || oifp == NULL)
5430 		panic("pf_route: invalid parameters");
5431 
5432 	if (((*m)->m_pkthdr.fw_flags & PF_MBUF_ROUTED) == 0) {
5433 		(*m)->m_pkthdr.fw_flags |= PF_MBUF_ROUTED;
5434 		(*m)->m_pkthdr.pf.routed = 1;
5435 	} else {
5436 		if ((*m)->m_pkthdr.pf.routed++ > 3) {
5437 			m0 = *m;
5438 			*m = NULL;
5439 			goto bad;
5440 		}
5441 	}
5442 
5443 	if (r->rt == PF_DUPTO) {
5444 		if ((m0 = m_dup(*m, MB_DONTWAIT)) == NULL) {
5445 			return;
5446 		}
5447 	} else {
5448 		if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5449 			return;
5450 		}
5451 		m0 = *m;
5452 	}
5453 
5454 	if (m0->m_len < sizeof(struct ip)) {
5455 		DPFPRINTF(PF_DEBUG_URGENT,
5456 		    ("pf_route: m0->m_len < sizeof(struct ip)\n"));
5457 		goto bad;
5458 	}
5459 
5460 	ip = mtod(m0, struct ip *);
5461 
5462 	ro = &iproute;
5463 	bzero((caddr_t)ro, sizeof(*ro));
5464 	dst = satosin(&ro->ro_dst);
5465 	dst->sin_family = AF_INET;
5466 	dst->sin_len = sizeof(*dst);
5467 	dst->sin_addr = ip->ip_dst;
5468 
5469 	if (r->rt == PF_FASTROUTE) {
5470 		rtalloc(ro);
5471 		if (ro->ro_rt == 0) {
5472 			ipstat.ips_noroute++;
5473 			goto bad;
5474 		}
5475 
5476 		ifp = ro->ro_rt->rt_ifp;
5477 		ro->ro_rt->rt_use++;
5478 
5479 		if (ro->ro_rt->rt_flags & RTF_GATEWAY)
5480 			dst = satosin(ro->ro_rt->rt_gateway);
5481 	} else {
5482 		if (TAILQ_EMPTY(&r->rpool.list)) {
5483 			DPFPRINTF(PF_DEBUG_URGENT,
5484 			    ("pf_route: TAILQ_EMPTY(&r->rpool.list)\n"));
5485 			goto bad;
5486 		}
5487 		if (s == NULL) {
5488 			pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5489 			    &naddr, NULL, &sn);
5490 			if (!PF_AZERO(&naddr, AF_INET))
5491 				dst->sin_addr.s_addr = naddr.v4.s_addr;
5492 			ifp = r->rpool.cur->kif ?
5493 			    r->rpool.cur->kif->pfik_ifp : NULL;
5494 		} else {
5495 			if (!PF_AZERO(&s->rt_addr, AF_INET))
5496 				dst->sin_addr.s_addr =
5497 				    s->rt_addr.v4.s_addr;
5498 			ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5499 		}
5500 	}
5501 	if (ifp == NULL)
5502 		goto bad;
5503 
5504 	if (oifp != ifp) {
5505 		if (pf_test(PF_OUT, ifp, &m0, NULL, NULL) != PF_PASS) {
5506 			goto bad;
5507 		} else if (m0 == NULL) {
5508 			goto done;
5509 		}
5510 		if (m0->m_len < sizeof(struct ip)) {
5511 			DPFPRINTF(PF_DEBUG_URGENT,
5512 			    ("pf_route: m0->m_len < sizeof(struct ip)\n"));
5513 			goto bad;
5514 		}
5515 		ip = mtod(m0, struct ip *);
5516 	}
5517 
5518 	/* Copied from FreeBSD 5.1-CURRENT ip_output. */
5519 	m0->m_pkthdr.csum_flags |= CSUM_IP;
5520 	sw_csum = m0->m_pkthdr.csum_flags & ~ifp->if_hwassist;
5521 	if (sw_csum & CSUM_DELAY_DATA) {
5522 		in_delayed_cksum(m0);
5523 		sw_csum &= ~CSUM_DELAY_DATA;
5524 	}
5525 	m0->m_pkthdr.csum_flags &= ifp->if_hwassist;
5526 	m0->m_pkthdr.csum_iphlen = (ip->ip_hl << 2);
5527 
5528 	if (ip->ip_len <= ifp->if_mtu ||
5529 	    (ifp->if_hwassist & CSUM_FRAGMENT &&
5530 		(ip->ip_off & IP_DF) == 0)) {
5531 		ip->ip_len = htons(ip->ip_len);
5532 		ip->ip_off = htons(ip->ip_off);
5533 		ip->ip_sum = 0;
5534 		if (sw_csum & CSUM_DELAY_IP) {
5535 			/* From KAME */
5536 			if (ip->ip_v == IPVERSION &&
5537 			    (ip->ip_hl << 2) == sizeof(*ip)) {
5538 				ip->ip_sum = in_cksum_hdr(ip);
5539 			} else {
5540 				ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5541 			}
5542 		}
5543 		lwkt_reltoken(&pf_token);
5544 		error = ifp->if_output(ifp, m0, sintosa(dst), ro->ro_rt);
5545 		lwkt_gettoken(&pf_token);
5546 		goto done;
5547 	}
5548 
5549 	/*
5550 	 * Too large for interface; fragment if possible.
5551 	 * Must be able to put at least 8 bytes per fragment.
5552 	 */
5553 	if (ip->ip_off & IP_DF) {
5554 		ipstat.ips_cantfrag++;
5555 		if (r->rt != PF_DUPTO) {
5556 			icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5557 			    ifp->if_mtu);
5558 			goto done;
5559 		} else
5560 			goto bad;
5561 	}
5562 
5563 	m1 = m0;
5564 	error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist, sw_csum);
5565 	if (error) {
5566 		goto bad;
5567 	}
5568 
5569 	for (m0 = m1; m0; m0 = m1) {
5570 		m1 = m0->m_nextpkt;
5571 		m0->m_nextpkt = 0;
5572 		if (error == 0) {
5573 			lwkt_reltoken(&pf_token);
5574 			error = (*ifp->if_output)(ifp, m0, sintosa(dst),
5575 						  NULL);
5576 			lwkt_gettoken(&pf_token);
5577 		} else
5578 			m_freem(m0);
5579 	}
5580 
5581 	if (error == 0)
5582 		ipstat.ips_fragmented++;
5583 
5584 done:
5585 	if (r->rt != PF_DUPTO)
5586 		*m = NULL;
5587 	if (ro == &iproute && ro->ro_rt)
5588 		RTFREE(ro->ro_rt);
5589 	return;
5590 
5591 bad:
5592 	m_freem(m0);
5593 	goto done;
5594 }
5595 #endif /* INET */
5596 
5597 #ifdef INET6
5598 void
5599 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5600     struct pf_state *s, struct pf_pdesc *pd)
5601 {
5602 	struct mbuf		*m0;
5603 	struct route_in6	 ip6route;
5604 	struct route_in6	*ro;
5605 	struct sockaddr_in6	*dst;
5606 	struct ip6_hdr		*ip6;
5607 	struct ifnet		*ifp = NULL;
5608 	struct pf_addr		 naddr;
5609 	struct pf_src_node	*sn = NULL;
5610 
5611 	if (m == NULL || *m == NULL || r == NULL ||
5612 	    (dir != PF_IN && dir != PF_OUT) || oifp == NULL)
5613 		panic("pf_route6: invalid parameters");
5614 
5615 	if (((*m)->m_pkthdr.fw_flags & PF_MBUF_ROUTED) == 0) {
5616 		(*m)->m_pkthdr.fw_flags |= PF_MBUF_ROUTED;
5617 		(*m)->m_pkthdr.pf.routed = 1;
5618 	} else {
5619 		if ((*m)->m_pkthdr.pf.routed++ > 3) {
5620 			m0 = *m;
5621 			*m = NULL;
5622 			goto bad;
5623 		}
5624 	}
5625 
5626 	if (r->rt == PF_DUPTO) {
5627 		if ((m0 = m_dup(*m, MB_DONTWAIT)) == NULL)
5628 			return;
5629 	} else {
5630 		if ((r->rt == PF_REPLYTO) == (r->direction == dir))
5631 			return;
5632 		m0 = *m;
5633 	}
5634 
5635 	if (m0->m_len < sizeof(struct ip6_hdr)) {
5636 		DPFPRINTF(PF_DEBUG_URGENT,
5637 		    ("pf_route6: m0->m_len < sizeof(struct ip6_hdr)\n"));
5638 		goto bad;
5639 	}
5640 	ip6 = mtod(m0, struct ip6_hdr *);
5641 
5642 	ro = &ip6route;
5643 	bzero((caddr_t)ro, sizeof(*ro));
5644 	dst = (struct sockaddr_in6 *)&ro->ro_dst;
5645 	dst->sin6_family = AF_INET6;
5646 	dst->sin6_len = sizeof(*dst);
5647 	dst->sin6_addr = ip6->ip6_dst;
5648 
5649 	/*
5650 	 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
5651 	 * so make sure pf.flags is clear.
5652 	 *
5653 	 * Cheat. XXX why only in the v6 case???
5654 	 */
5655 	if (r->rt == PF_FASTROUTE) {
5656 		m0->m_pkthdr.fw_flags |= PF_MBUF_TAGGED;
5657 		m0->m_pkthdr.pf.flags = 0;
5658 		/* XXX Re-Check when Upgrading to > 4.4 */
5659 		m0->m_pkthdr.pf.statekey = NULL;
5660 		ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
5661 		return;
5662 	}
5663 
5664 	if (TAILQ_EMPTY(&r->rpool.list)) {
5665 		DPFPRINTF(PF_DEBUG_URGENT,
5666 		    ("pf_route6: TAILQ_EMPTY(&r->rpool.list)\n"));
5667 		goto bad;
5668 	}
5669 	if (s == NULL) {
5670 		pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5671 		    &naddr, NULL, &sn);
5672 		if (!PF_AZERO(&naddr, AF_INET6))
5673 			PF_ACPY((struct pf_addr *)&dst->sin6_addr,
5674 			    &naddr, AF_INET6);
5675 		ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5676 	} else {
5677 		if (!PF_AZERO(&s->rt_addr, AF_INET6))
5678 			PF_ACPY((struct pf_addr *)&dst->sin6_addr,
5679 			    &s->rt_addr, AF_INET6);
5680 		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5681 	}
5682 	if (ifp == NULL)
5683 		goto bad;
5684 
5685 	if (oifp != ifp) {
5686 		if (pf_test6(PF_OUT, ifp, &m0, NULL, NULL) != PF_PASS) {
5687 			goto bad;
5688 		} else if (m0 == NULL) {
5689 			goto done;
5690 		}
5691 		if (m0->m_len < sizeof(struct ip6_hdr)) {
5692 			DPFPRINTF(PF_DEBUG_URGENT,
5693 			    ("pf_route6: m0->m_len < sizeof(struct ip6_hdr)\n"));
5694 			goto bad;
5695 		}
5696 		ip6 = mtod(m0, struct ip6_hdr *);
5697 	}
5698 
5699 	/*
5700 	 * If the packet is too large for the outgoing interface,
5701 	 * send back an icmp6 error.
5702 	 */
5703 	if (IN6_IS_ADDR_LINKLOCAL(&dst->sin6_addr))
5704 		dst->sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5705 	if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu) {
5706 		nd6_output(ifp, ifp, m0, dst, NULL);
5707 	} else {
5708 		in6_ifstat_inc(ifp, ifs6_in_toobig);
5709 		if (r->rt != PF_DUPTO)
5710 			icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5711 		else
5712 			goto bad;
5713 	}
5714 
5715 done:
5716 	if (r->rt != PF_DUPTO)
5717 		*m = NULL;
5718 	return;
5719 
5720 bad:
5721 	m_freem(m0);
5722 	goto done;
5723 }
5724 #endif /* INET6 */
5725 
5726 
5727 /*
5728  * check protocol (tcp/udp/icmp/icmp6) checksum and set mbuf flag
5729  *   off is the offset where the protocol header starts
5730  *   len is the total length of protocol header plus payload
5731  * returns 0 when the checksum is valid, otherwise returns 1.
5732  */
5733 /*
5734  * XXX
5735  * FreeBSD supports cksum offload for the following drivers.
5736  * em(4), gx(4), lge(4), nge(4), ti(4), xl(4)
5737  * If we can make full use of it we would outperform ipfw/ipfilter in
5738  * very heavy traffic.
5739  * I have not tested 'cause I don't have NICs that supports cksum offload.
5740  * (There might be problems. Typical phenomena would be
5741  *   1. No route message for UDP packet.
5742  *   2. No connection acceptance from external hosts regardless of rule set.)
5743  */
5744 int
5745 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p,
5746     sa_family_t af)
5747 {
5748 	u_int16_t sum = 0;
5749 	int hw_assist = 0;
5750 	struct ip *ip;
5751 
5752 	if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5753 		return (1);
5754 	if (m->m_pkthdr.len < off + len)
5755 		return (1);
5756 
5757 	switch (p) {
5758 	case IPPROTO_TCP:
5759 	case IPPROTO_UDP:
5760 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5761 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5762 				sum = m->m_pkthdr.csum_data;
5763 			} else {
5764 				ip = mtod(m, struct ip *);
5765 				sum = in_pseudo(ip->ip_src.s_addr,
5766 					ip->ip_dst.s_addr, htonl((u_short)len +
5767 					m->m_pkthdr.csum_data + p));
5768 			}
5769 			sum ^= 0xffff;
5770 			++hw_assist;
5771 		}
5772 		break;
5773 	case IPPROTO_ICMP:
5774 #ifdef INET6
5775 	case IPPROTO_ICMPV6:
5776 #endif /* INET6 */
5777 		break;
5778 	default:
5779 		return (1);
5780 	}
5781 
5782 	if (!hw_assist) {
5783 		switch (af) {
5784 		case AF_INET:
5785 			if (p == IPPROTO_ICMP) {
5786 				if (m->m_len < off)
5787 					return (1);
5788 				m->m_data += off;
5789 				m->m_len -= off;
5790 				sum = in_cksum(m, len);
5791 				m->m_data -= off;
5792 				m->m_len += off;
5793 			} else {
5794 				if (m->m_len < sizeof(struct ip))
5795 					return (1);
5796 				sum = in_cksum_range(m, p, off, len);
5797 				if (sum == 0) {
5798 					m->m_pkthdr.csum_flags |=
5799 					    (CSUM_DATA_VALID |
5800 					     CSUM_PSEUDO_HDR);
5801 					m->m_pkthdr.csum_data = 0xffff;
5802 				}
5803 			}
5804 			break;
5805 #ifdef INET6
5806 		case AF_INET6:
5807 			if (m->m_len < sizeof(struct ip6_hdr))
5808 				return (1);
5809 			sum = in6_cksum(m, p, off, len);
5810 			/*
5811 			 * XXX
5812 			 * IPv6 H/W cksum off-load not supported yet!
5813 			 *
5814 			 * if (sum == 0) {
5815 			 *	m->m_pkthdr.csum_flags |=
5816 			 *	    (CSUM_DATA_VALID|CSUM_PSEUDO_HDR);
5817 			 *	m->m_pkthdr.csum_data = 0xffff;
5818 			 *}
5819 			 */
5820 			break;
5821 #endif /* INET6 */
5822 		default:
5823 			return (1);
5824 		}
5825 	}
5826 	if (sum) {
5827 		switch (p) {
5828 		case IPPROTO_TCP:
5829 			tcpstat.tcps_rcvbadsum++;
5830 			break;
5831 		case IPPROTO_UDP:
5832 			udp_stat.udps_badsum++;
5833 			break;
5834 		case IPPROTO_ICMP:
5835 			icmpstat.icps_checksum++;
5836 			break;
5837 #ifdef INET6
5838 		case IPPROTO_ICMPV6:
5839 			icmp6stat.icp6s_checksum++;
5840 			break;
5841 #endif /* INET6 */
5842 		}
5843 		return (1);
5844 	}
5845 	return (0);
5846 }
5847 
5848 struct pf_divert *
5849 pf_find_divert(struct mbuf *m)
5850 {
5851 	struct m_tag    *mtag;
5852 
5853 	if ((mtag = m_tag_find(m, PACKET_TAG_PF_DIVERT, NULL)) == NULL)
5854 		return (NULL);
5855 
5856 	return ((struct pf_divert *)(mtag + 1));
5857 }
5858 
5859 struct pf_divert *
5860 pf_get_divert(struct mbuf *m)
5861 {
5862 	struct m_tag    *mtag;
5863 
5864 	if ((mtag = m_tag_find(m, PACKET_TAG_PF_DIVERT, NULL)) == NULL) {
5865 		mtag = m_tag_get(PACKET_TAG_PF_DIVERT, sizeof(struct pf_divert),
5866 		    M_NOWAIT);
5867 		if (mtag == NULL)
5868 			return (NULL);
5869 		bzero(mtag + 1, sizeof(struct pf_divert));
5870 		m_tag_prepend(m, mtag);
5871 	}
5872 
5873 	return ((struct pf_divert *)(mtag + 1));
5874 }
5875 
5876 #ifdef INET
5877 int
5878 pf_test(int dir, struct ifnet *ifp, struct mbuf **m0,
5879     struct ether_header *eh, struct inpcb *inp)
5880 {
5881 	struct pfi_kif		*kif;
5882 	u_short			 action, reason = 0, log = 0;
5883 	struct mbuf		*m = *m0;
5884 	struct ip		*h = NULL;
5885 	struct pf_rule		*a = NULL, *r = &pf_default_rule, *tr, *nr;
5886 	struct pf_state		*s = NULL;
5887 	struct pf_ruleset	*ruleset = NULL;
5888 	struct pf_pdesc		 pd;
5889 	int			 off, dirndx;
5890 #ifdef ALTQ
5891 	int			 pqid = 0;
5892 #endif
5893 
5894 	if (!pf_status.running)
5895 		return (PF_PASS);
5896 
5897 	memset(&pd, 0, sizeof(pd));
5898 #ifdef foo
5899 	if (ifp->if_type == IFT_CARP && ifp->if_carpdev)
5900 		kif = (struct pfi_kif *)ifp->if_carpdev->if_pf_kif;
5901 	else
5902 #endif
5903 		kif = (struct pfi_kif *)ifp->if_pf_kif;
5904 
5905 	if (kif == NULL) {
5906 		DPFPRINTF(PF_DEBUG_URGENT,
5907 		    ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5908 		return (PF_DROP);
5909 	}
5910 	if (kif->pfik_flags & PFI_IFLAG_SKIP)
5911 		return (PF_PASS);
5912 
5913 #ifdef DIAGNOSTIC
5914 	if ((m->m_flags & M_PKTHDR) == 0)
5915 		panic("non-M_PKTHDR is passed to pf_test");
5916 #endif /* DIAGNOSTIC */
5917 
5918 	if (m->m_pkthdr.len < (int)sizeof(*h)) {
5919 		action = PF_DROP;
5920 		REASON_SET(&reason, PFRES_SHORT);
5921 		log = 1;
5922 		goto done;
5923 	}
5924 
5925 	/*
5926 	 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
5927 	 * so make sure pf.flags is clear.
5928 	 */
5929 	if (m->m_pkthdr.fw_flags & PF_MBUF_TAGGED)
5930 		return (PF_PASS);
5931 	m->m_pkthdr.pf.flags = 0;
5932 	/* Re-Check when updating to > 4.4 */
5933 	m->m_pkthdr.pf.statekey = NULL;
5934 
5935 	/* We do IP header normalization and packet reassembly here */
5936 	if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5937 		action = PF_DROP;
5938 		goto done;
5939 	}
5940 	m = *m0;	/* pf_normalize messes with m0 */
5941 	h = mtod(m, struct ip *);
5942 
5943 	off = h->ip_hl << 2;
5944 	if (off < (int)sizeof(*h)) {
5945 		action = PF_DROP;
5946 		REASON_SET(&reason, PFRES_SHORT);
5947 		log = 1;
5948 		goto done;
5949 	}
5950 
5951 	pd.src = (struct pf_addr *)&h->ip_src;
5952 	pd.dst = (struct pf_addr *)&h->ip_dst;
5953 	pd.sport = pd.dport = NULL;
5954 	pd.ip_sum = &h->ip_sum;
5955 	pd.proto_sum = NULL;
5956 	pd.proto = h->ip_p;
5957 	pd.dir = dir;
5958 	pd.sidx = (dir == PF_IN) ? 0 : 1;
5959 	pd.didx = (dir == PF_IN) ? 1 : 0;
5960 	pd.af = AF_INET;
5961 	pd.tos = h->ip_tos;
5962 	pd.tot_len = h->ip_len;
5963 	pd.eh = eh;
5964 
5965 	/* handle fragments that didn't get reassembled by normalization */
5966 	if (h->ip_off & (IP_MF | IP_OFFMASK)) {
5967 		action = pf_test_fragment(&r, dir, kif, m, h,
5968 		    &pd, &a, &ruleset);
5969 		goto done;
5970 	}
5971 
5972 	switch (h->ip_p) {
5973 
5974 	case IPPROTO_TCP: {
5975 		struct tcphdr	th;
5976 
5977 		pd.hdr.tcp = &th;
5978 		if (!pf_pull_hdr(m, off, &th, sizeof(th),
5979 		    &action, &reason, AF_INET)) {
5980 			log = action != PF_PASS;
5981 			goto done;
5982 		}
5983 		pd.p_len = pd.tot_len - off - (th.th_off << 2);
5984 #ifdef ALTQ
5985 		if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5986 			pqid = 1;
5987 #endif
5988 		action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5989 		if (action == PF_DROP)
5990 			goto done;
5991 		action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5992 		    &reason);
5993 		if (action == PF_PASS) {
5994 			pfsync_update_state(s);
5995 			r = s->rule.ptr;
5996 			a = s->anchor.ptr;
5997 			log = s->log;
5998 		} else if (s == NULL)
5999 			action = pf_test_rule(&r, &s, dir, kif,
6000 			    m, off, h, &pd, &a, &ruleset, NULL, inp);
6001 		break;
6002 	}
6003 
6004 	case IPPROTO_UDP: {
6005 		struct udphdr	uh;
6006 
6007 		pd.hdr.udp = &uh;
6008 		if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6009 		    &action, &reason, AF_INET)) {
6010 			log = action != PF_PASS;
6011 			goto done;
6012 		}
6013 		if (uh.uh_dport == 0 ||
6014 		    ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6015 		    ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6016 			action = PF_DROP;
6017 			REASON_SET(&reason, PFRES_SHORT);
6018 			goto done;
6019 		}
6020 		action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6021 		if (action == PF_PASS) {
6022 			pfsync_update_state(s);
6023 			r = s->rule.ptr;
6024 			a = s->anchor.ptr;
6025 			log = s->log;
6026 		} else if (s == NULL)
6027 			action = pf_test_rule(&r, &s, dir, kif,
6028 			    m, off, h, &pd, &a, &ruleset, NULL, inp);
6029 		break;
6030 	}
6031 
6032 	case IPPROTO_ICMP: {
6033 		struct icmp	ih;
6034 
6035 		pd.hdr.icmp = &ih;
6036 		if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
6037 		    &action, &reason, AF_INET)) {
6038 			log = action != PF_PASS;
6039 			goto done;
6040 		}
6041 		action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
6042 		    &reason);
6043 		if (action == PF_PASS) {
6044 			pfsync_update_state(s);
6045 			r = s->rule.ptr;
6046 			a = s->anchor.ptr;
6047 			log = s->log;
6048 		} else if (s == NULL)
6049 			action = pf_test_rule(&r, &s, dir, kif,
6050 			    m, off, h, &pd, &a, &ruleset, NULL, inp);
6051 		break;
6052 	}
6053 
6054 	default:
6055 		action = pf_test_state_other(&s, dir, kif, m, &pd);
6056 		if (action == PF_PASS) {
6057 			pfsync_update_state(s);
6058 			r = s->rule.ptr;
6059 			a = s->anchor.ptr;
6060 			log = s->log;
6061 		} else if (s == NULL)
6062 			action = pf_test_rule(&r, &s, dir, kif, m, off, h,
6063 			    &pd, &a, &ruleset, NULL, inp);
6064 		break;
6065 	}
6066 
6067 done:
6068 	if (action == PF_PASS && h->ip_hl > 5 &&
6069 	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6070 		action = PF_DROP;
6071 		REASON_SET(&reason, PFRES_IPOPTIONS);
6072 		log = 1;
6073 		DPFPRINTF(PF_DEBUG_MISC,
6074 		    ("pf: dropping packet with ip options\n"));
6075 	}
6076 
6077 	if ((s && s->tag) || r->rtableid)
6078 		pf_tag_packet(m, s ? s->tag : 0, r->rtableid);
6079 
6080 #if 0
6081 	if (dir == PF_IN && s && s->key[PF_SK_STACK])
6082 		m->m_pkthdr.pf.statekey = s->key[PF_SK_STACK];
6083 #endif
6084 
6085 #ifdef ALTQ
6086 	if (action == PF_PASS && r->qid) {
6087 		m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
6088 		if (pqid || (pd.tos & IPTOS_LOWDELAY))
6089 			m->m_pkthdr.pf.qid = r->pqid;
6090 		else
6091 			m->m_pkthdr.pf.qid = r->qid;
6092 		m->m_pkthdr.pf.ecn_af = AF_INET;
6093 		m->m_pkthdr.pf.hdr = h;
6094 		/* add connection hash for fairq */
6095 		if (s) {
6096 			/* for fairq */
6097 			m->m_pkthdr.pf.state_hash = s->hash;
6098 			m->m_pkthdr.pf.flags |= PF_TAG_STATE_HASHED;
6099 		}
6100 	}
6101 #endif /* ALTQ */
6102 
6103 	/*
6104 	 * connections redirected to loopback should not match sockets
6105 	 * bound specifically to loopback due to security implications,
6106 	 * see tcp_input() and in_pcblookup_listen().
6107 	 */
6108 	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6109 	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6110 	    (s->nat_rule.ptr->action == PF_RDR ||
6111 	    s->nat_rule.ptr->action == PF_BINAT) &&
6112 	    (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
6113 		m->m_pkthdr.pf.flags |= PF_TAG_TRANSLATE_LOCALHOST;
6114 
6115 	if (dir == PF_IN && action == PF_PASS && r->divert.port) {
6116 		struct pf_divert *divert;
6117 
6118 		if ((divert = pf_get_divert(m))) {
6119 			m->m_pkthdr.pf.flags |= PF_TAG_DIVERTED;
6120 			divert->port = r->divert.port;
6121 			divert->addr.ipv4 = r->divert.addr.v4;
6122 		}
6123 	}
6124 
6125 	if (log) {
6126 		struct pf_rule *lr;
6127 
6128 		if (s != NULL && s->nat_rule.ptr != NULL &&
6129 		    s->nat_rule.ptr->log & PF_LOG_ALL)
6130 			lr = s->nat_rule.ptr;
6131 		else
6132 			lr = r;
6133 		PFLOG_PACKET(kif, h, m, AF_INET, dir, reason, lr, a, ruleset,
6134 		    &pd);
6135 	}
6136 
6137 	kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6138 	kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6139 
6140 	if (action == PF_PASS || r->action == PF_DROP) {
6141 		dirndx = (dir == PF_OUT);
6142 		r->packets[dirndx]++;
6143 		r->bytes[dirndx] += pd.tot_len;
6144 		if (a != NULL) {
6145 			a->packets[dirndx]++;
6146 			a->bytes[dirndx] += pd.tot_len;
6147 		}
6148 		if (s != NULL) {
6149 			if (s->nat_rule.ptr != NULL) {
6150 				s->nat_rule.ptr->packets[dirndx]++;
6151 				s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6152 			}
6153 			if (s->src_node != NULL) {
6154 				s->src_node->packets[dirndx]++;
6155 				s->src_node->bytes[dirndx] += pd.tot_len;
6156 			}
6157 			if (s->nat_src_node != NULL) {
6158 				s->nat_src_node->packets[dirndx]++;
6159 				s->nat_src_node->bytes[dirndx] += pd.tot_len;
6160 			}
6161 			dirndx = (dir == s->direction) ? 0 : 1;
6162 			s->packets[dirndx]++;
6163 			s->bytes[dirndx] += pd.tot_len;
6164 		}
6165 		tr = r;
6166 		nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6167 		if (nr != NULL && r == &pf_default_rule)
6168 			tr = nr;
6169 		if (tr->src.addr.type == PF_ADDR_TABLE)
6170 			pfr_update_stats(tr->src.addr.p.tbl,
6171 			    (s == NULL) ? pd.src :
6172 			    &s->key[(s->direction == PF_IN)]->
6173 				addr[(s->direction == PF_OUT)],
6174 			    pd.af, pd.tot_len, dir == PF_OUT,
6175 			    r->action == PF_PASS, tr->src.neg);
6176 		if (tr->dst.addr.type == PF_ADDR_TABLE)
6177 			pfr_update_stats(tr->dst.addr.p.tbl,
6178 			    (s == NULL) ? pd.dst :
6179 			    &s->key[(s->direction == PF_IN)]->
6180 				addr[(s->direction == PF_IN)],
6181 			    pd.af, pd.tot_len, dir == PF_OUT,
6182 			    r->action == PF_PASS, tr->dst.neg);
6183 	}
6184 
6185 
6186 	if (action == PF_SYNPROXY_DROP) {
6187 		m_freem(*m0);
6188 		*m0 = NULL;
6189 		action = PF_PASS;
6190 	} else if (r->rt)
6191 		/* pf_route can free the mbuf causing *m0 to become NULL */
6192 		pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
6193 
6194 	return (action);
6195 }
6196 #endif /* INET */
6197 
6198 #ifdef INET6
6199 int
6200 pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0,
6201     struct ether_header *eh, struct inpcb *inp)
6202 {
6203 	struct pfi_kif		*kif;
6204 	u_short			 action, reason = 0, log = 0;
6205 	struct mbuf		*m = *m0, *n = NULL;
6206 	struct ip6_hdr		*h = NULL;
6207 	struct pf_rule		*a = NULL, *r = &pf_default_rule, *tr, *nr;
6208 	struct pf_state		*s = NULL;
6209 	struct pf_ruleset	*ruleset = NULL;
6210 	struct pf_pdesc		 pd;
6211 	int			 off, terminal = 0, dirndx, rh_cnt = 0;
6212 
6213 	if (!pf_status.running)
6214 		return (PF_PASS);
6215 
6216 	memset(&pd, 0, sizeof(pd));
6217 #ifdef foo
6218 	if (ifp->if_type == IFT_CARP && ifp->if_carpdev)
6219 		kif = (struct pfi_kif *)ifp->if_carpdev->if_pf_kif;
6220 	else
6221 #endif
6222 		kif = (struct pfi_kif *)ifp->if_pf_kif;
6223 
6224 	if (kif == NULL) {
6225 		DPFPRINTF(PF_DEBUG_URGENT,
6226 		    ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6227 		return (PF_DROP);
6228 	}
6229 	if (kif->pfik_flags & PFI_IFLAG_SKIP)
6230 		return (PF_PASS);
6231 
6232 #ifdef DIAGNOSTIC
6233 	if ((m->m_flags & M_PKTHDR) == 0)
6234 		panic("non-M_PKTHDR is passed to pf_test6");
6235 #endif /* DIAGNOSTIC */
6236 
6237 	if (m->m_pkthdr.len < (int)sizeof(*h)) {
6238 		action = PF_DROP;
6239 		REASON_SET(&reason, PFRES_SHORT);
6240 		log = 1;
6241 		goto done;
6242 	}
6243 
6244 	/*
6245 	 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
6246 	 * so make sure pf.flags is clear.
6247 	 */
6248 	if (m->m_pkthdr.fw_flags & PF_MBUF_TAGGED)
6249 		return (PF_PASS);
6250 	m->m_pkthdr.pf.flags = 0;
6251 	/* Re-Check when updating to > 4.4 */
6252 	m->m_pkthdr.pf.statekey = NULL;
6253 
6254 	/* We do IP header normalization and packet reassembly here */
6255 	if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6256 		action = PF_DROP;
6257 		goto done;
6258 	}
6259 	m = *m0;	/* pf_normalize messes with m0 */
6260 	h = mtod(m, struct ip6_hdr *);
6261 
6262 #if 1
6263 	/*
6264 	 * we do not support jumbogram yet.  if we keep going, zero ip6_plen
6265 	 * will do something bad, so drop the packet for now.
6266 	 */
6267 	if (htons(h->ip6_plen) == 0) {
6268 		action = PF_DROP;
6269 		REASON_SET(&reason, PFRES_NORM);	/*XXX*/
6270 		goto done;
6271 	}
6272 #endif
6273 
6274 	pd.src = (struct pf_addr *)&h->ip6_src;
6275 	pd.dst = (struct pf_addr *)&h->ip6_dst;
6276 	pd.sport = pd.dport = NULL;
6277 	pd.ip_sum = NULL;
6278 	pd.proto_sum = NULL;
6279 	pd.dir = dir;
6280 	pd.sidx = (dir == PF_IN) ? 0 : 1;
6281 	pd.didx = (dir == PF_IN) ? 1 : 0;
6282 	pd.af = AF_INET6;
6283 	pd.tos = 0;
6284 	pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6285 	pd.eh = eh;
6286 
6287 	off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6288 	pd.proto = h->ip6_nxt;
6289 	do {
6290 		switch (pd.proto) {
6291 		case IPPROTO_FRAGMENT:
6292 			action = pf_test_fragment(&r, dir, kif, m, h,
6293 			    &pd, &a, &ruleset);
6294 			if (action == PF_DROP)
6295 				REASON_SET(&reason, PFRES_FRAG);
6296 			goto done;
6297 		case IPPROTO_ROUTING: {
6298 			struct ip6_rthdr rthdr;
6299 
6300 			if (rh_cnt++) {
6301 				DPFPRINTF(PF_DEBUG_MISC,
6302 				    ("pf: IPv6 more than one rthdr\n"));
6303 				action = PF_DROP;
6304 				REASON_SET(&reason, PFRES_IPOPTIONS);
6305 				log = 1;
6306 				goto done;
6307 			}
6308 			if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6309 			    &reason, pd.af)) {
6310 				DPFPRINTF(PF_DEBUG_MISC,
6311 				    ("pf: IPv6 short rthdr\n"));
6312 				action = PF_DROP;
6313 				REASON_SET(&reason, PFRES_SHORT);
6314 				log = 1;
6315 				goto done;
6316 			}
6317 			if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6318 				DPFPRINTF(PF_DEBUG_MISC,
6319 				    ("pf: IPv6 rthdr0\n"));
6320 				action = PF_DROP;
6321 				REASON_SET(&reason, PFRES_IPOPTIONS);
6322 				log = 1;
6323 				goto done;
6324 			}
6325 			/* FALLTHROUGH */
6326 		}
6327 		case IPPROTO_AH:
6328 		case IPPROTO_HOPOPTS:
6329 		case IPPROTO_DSTOPTS: {
6330 			/* get next header and header length */
6331 			struct ip6_ext	opt6;
6332 
6333 			if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6334 			    NULL, &reason, pd.af)) {
6335 				DPFPRINTF(PF_DEBUG_MISC,
6336 				    ("pf: IPv6 short opt\n"));
6337 				action = PF_DROP;
6338 				log = 1;
6339 				goto done;
6340 			}
6341 			if (pd.proto == IPPROTO_AH)
6342 				off += (opt6.ip6e_len + 2) * 4;
6343 			else
6344 				off += (opt6.ip6e_len + 1) * 8;
6345 			pd.proto = opt6.ip6e_nxt;
6346 			/* goto the next header */
6347 			break;
6348 		}
6349 		default:
6350 			terminal++;
6351 			break;
6352 		}
6353 	} while (!terminal);
6354 
6355 	/* if there's no routing header, use unmodified mbuf for checksumming */
6356 	if (!n)
6357 		n = m;
6358 
6359 	switch (pd.proto) {
6360 
6361 	case IPPROTO_TCP: {
6362 		struct tcphdr	th;
6363 
6364 		pd.hdr.tcp = &th;
6365 		if (!pf_pull_hdr(m, off, &th, sizeof(th),
6366 		    &action, &reason, AF_INET6)) {
6367 			log = action != PF_PASS;
6368 			goto done;
6369 		}
6370 		pd.p_len = pd.tot_len - off - (th.th_off << 2);
6371 		action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6372 		if (action == PF_DROP)
6373 			goto done;
6374 		action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6375 		    &reason);
6376 		if (action == PF_PASS) {
6377 			pfsync_update_state(s);
6378 			r = s->rule.ptr;
6379 			a = s->anchor.ptr;
6380 			log = s->log;
6381 		} else if (s == NULL)
6382 			action = pf_test_rule(&r, &s, dir, kif,
6383 			    m, off, h, &pd, &a, &ruleset, NULL, inp);
6384 		break;
6385 	}
6386 
6387 	case IPPROTO_UDP: {
6388 		struct udphdr	uh;
6389 
6390 		pd.hdr.udp = &uh;
6391 		if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6392 		    &action, &reason, AF_INET6)) {
6393 			log = action != PF_PASS;
6394 			goto done;
6395 		}
6396 		if (uh.uh_dport == 0 ||
6397 		    ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6398 		    ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6399 			action = PF_DROP;
6400 			REASON_SET(&reason, PFRES_SHORT);
6401 			goto done;
6402 		}
6403 		action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6404 		if (action == PF_PASS) {
6405 			pfsync_update_state(s);
6406 			r = s->rule.ptr;
6407 			a = s->anchor.ptr;
6408 			log = s->log;
6409 		} else if (s == NULL)
6410 			action = pf_test_rule(&r, &s, dir, kif,
6411 			    m, off, h, &pd, &a, &ruleset, NULL, inp);
6412 		break;
6413 	}
6414 
6415 	case IPPROTO_ICMPV6: {
6416 		struct icmp6_hdr	ih;
6417 
6418 		pd.hdr.icmp6 = &ih;
6419 		if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6420 		    &action, &reason, AF_INET6)) {
6421 			log = action != PF_PASS;
6422 			goto done;
6423 		}
6424 		action = pf_test_state_icmp(&s, dir, kif,
6425 		    m, off, h, &pd, &reason);
6426 		if (action == PF_PASS) {
6427 			pfsync_update_state(s);
6428 			r = s->rule.ptr;
6429 			a = s->anchor.ptr;
6430 			log = s->log;
6431 		} else if (s == NULL)
6432 			action = pf_test_rule(&r, &s, dir, kif,
6433 			    m, off, h, &pd, &a, &ruleset, NULL, inp);
6434 		break;
6435 	}
6436 
6437 	default:
6438 		action = pf_test_state_other(&s, dir, kif, m, &pd);
6439 		if (action == PF_PASS) {
6440 			pfsync_update_state(s);
6441 			r = s->rule.ptr;
6442 			a = s->anchor.ptr;
6443 			log = s->log;
6444 		} else if (s == NULL)
6445 			action = pf_test_rule(&r, &s, dir, kif, m, off, h,
6446 			    &pd, &a, &ruleset, NULL, inp);
6447 		break;
6448 	}
6449 
6450 done:
6451 	if (n != m) {
6452 		m_freem(n);
6453 		n = NULL;
6454 	}
6455 
6456 	/* handle dangerous IPv6 extension headers. */
6457 	if (action == PF_PASS && rh_cnt &&
6458 	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6459 		action = PF_DROP;
6460 		REASON_SET(&reason, PFRES_IPOPTIONS);
6461 		log = 1;
6462 		DPFPRINTF(PF_DEBUG_MISC,
6463 		    ("pf: dropping packet with dangerous v6 headers\n"));
6464 	}
6465 
6466 	if ((s && s->tag) || r->rtableid)
6467 		pf_tag_packet(m, s ? s->tag : 0, r->rtableid);
6468 
6469 #if 0
6470 	if (dir == PF_IN && s && s->key[PF_SK_STACK])
6471 		m->m_pkthdr.pf.statekey = s->key[PF_SK_STACK];
6472 #endif
6473 
6474 #ifdef ALTQ
6475 	if (action == PF_PASS && r->qid) {
6476 		m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
6477 		if (pd.tos & IPTOS_LOWDELAY)
6478 			m->m_pkthdr.pf.qid = r->pqid;
6479 		else
6480 			m->m_pkthdr.pf.qid = r->qid;
6481 		m->m_pkthdr.pf.ecn_af = AF_INET6;
6482 		m->m_pkthdr.pf.hdr = h;
6483 		if (s) {
6484 			/* for fairq */
6485 			m->m_pkthdr.pf.state_hash = s->hash;
6486 			m->m_pkthdr.pf.flags |= PF_TAG_STATE_HASHED;
6487 		}
6488 	}
6489 #endif /* ALTQ */
6490 
6491 	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6492 	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6493 	    (s->nat_rule.ptr->action == PF_RDR ||
6494 	    s->nat_rule.ptr->action == PF_BINAT) &&
6495 	    IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6496 		m->m_pkthdr.pf.flags |= PF_TAG_TRANSLATE_LOCALHOST;
6497 
6498 	if (dir == PF_IN && action == PF_PASS && r->divert.port) {
6499 		struct pf_divert *divert;
6500 
6501 		if ((divert = pf_get_divert(m))) {
6502 			m->m_pkthdr.pf.flags |= PF_TAG_DIVERTED;
6503 			divert->port = r->divert.port;
6504 			divert->addr.ipv6 = r->divert.addr.v6;
6505 		}
6506 	}
6507 
6508 	if (log) {
6509 		struct pf_rule *lr;
6510 
6511 		if (s != NULL && s->nat_rule.ptr != NULL &&
6512 		    s->nat_rule.ptr->log & PF_LOG_ALL)
6513 			lr = s->nat_rule.ptr;
6514 		else
6515 			lr = r;
6516 		PFLOG_PACKET(kif, h, m, AF_INET6, dir, reason, lr, a, ruleset,
6517 		    &pd);
6518 	}
6519 
6520 	kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6521 	kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6522 
6523 	if (action == PF_PASS || r->action == PF_DROP) {
6524 		dirndx = (dir == PF_OUT);
6525 		r->packets[dirndx]++;
6526 		r->bytes[dirndx] += pd.tot_len;
6527 		if (a != NULL) {
6528 			a->packets[dirndx]++;
6529 			a->bytes[dirndx] += pd.tot_len;
6530 		}
6531 		if (s != NULL) {
6532 			if (s->nat_rule.ptr != NULL) {
6533 				s->nat_rule.ptr->packets[dirndx]++;
6534 				s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6535 			}
6536 			if (s->src_node != NULL) {
6537 				s->src_node->packets[dirndx]++;
6538 				s->src_node->bytes[dirndx] += pd.tot_len;
6539 			}
6540 			if (s->nat_src_node != NULL) {
6541 				s->nat_src_node->packets[dirndx]++;
6542 				s->nat_src_node->bytes[dirndx] += pd.tot_len;
6543 			}
6544 			dirndx = (dir == s->direction) ? 0 : 1;
6545 			s->packets[dirndx]++;
6546 			s->bytes[dirndx] += pd.tot_len;
6547 		}
6548 		tr = r;
6549 		nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6550 		if (nr != NULL && r == &pf_default_rule)
6551 			tr = nr;
6552 		if (tr->src.addr.type == PF_ADDR_TABLE)
6553 			pfr_update_stats(tr->src.addr.p.tbl,
6554 			    (s == NULL) ? pd.src :
6555 			    &s->key[(s->direction == PF_IN)]->addr[0],
6556 			    pd.af, pd.tot_len, dir == PF_OUT,
6557 			    r->action == PF_PASS, tr->src.neg);
6558 		if (tr->dst.addr.type == PF_ADDR_TABLE)
6559 			pfr_update_stats(tr->dst.addr.p.tbl,
6560 			    (s == NULL) ? pd.dst :
6561 			    &s->key[(s->direction == PF_IN)]->addr[1],
6562 			    pd.af, pd.tot_len, dir == PF_OUT,
6563 			    r->action == PF_PASS, tr->dst.neg);
6564 	}
6565 
6566 
6567 	if (action == PF_SYNPROXY_DROP) {
6568 		m_freem(*m0);
6569 		*m0 = NULL;
6570 		action = PF_PASS;
6571 	} else if (r->rt)
6572 		/* pf_route6 can free the mbuf causing *m0 to become NULL */
6573 		pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);
6574 
6575 	return (action);
6576 }
6577 #endif /* INET6 */
6578 
6579 int
6580 pf_check_congestion(struct ifqueue *ifq)
6581 {
6582 		return (0);
6583 }
6584