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