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