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