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