xref: /dragonfly/sys/net/pf/pf.c (revision 0de090e1)
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		toeplitz_sport;
2888 
2889 	bzero(&init_addr, sizeof(init_addr));
2890 	if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
2891 		return (1);
2892 
2893 	if (proto == IPPROTO_ICMP) {
2894 		low = 1;
2895 		high = 65535;
2896 	}
2897 
2898 	bzero(&key, sizeof(key));
2899 	key.af = af;
2900 	key.proto = proto;
2901 	key.port[0] = dport;
2902 	PF_ACPY(&key.addr[0], daddr, key.af);
2903 
2904 	do {
2905 		PF_ACPY(&key.addr[1], naddr, key.af);
2906 
2907 		/*
2908 		 * We want to select a port that calculates to a toeplitz hash
2909 		 * that masks to the same cpu, otherwise the response may
2910 		 * not see the new state.
2911 		 *
2912 		 * We can still do this even if the kernel is disregarding
2913 		 * the hash and vectoring the packets to a specific cpu,
2914 		 * but it will reduce the number of ports we can use.
2915 		 */
2916 		switch(af) {
2917 		case AF_INET:
2918 			toeplitz_sport =
2919 				toeplitz_piecemeal_port(sport) ^
2920 				toeplitz_piecemeal_addr(saddr->v4.s_addr) ^
2921 				toeplitz_piecemeal_addr(naddr->v4.s_addr);
2922 			break;
2923 		case AF_INET6:
2924 			/* XXX TODO XXX */
2925 		default:
2926 			/* XXX TODO XXX */
2927 			toeplitz_sport = 0;
2928 			break;
2929 		}
2930 
2931 		/*
2932 		 * port search; start random, step;
2933 		 * similar 2 portloop in in_pcbbind
2934 		 *
2935 		 * WARNING! We try to match such that the kernel will
2936 		 *	    dispatch the translated host/port to the same
2937 		 *	    cpu, but this might not be possible.
2938 		 *
2939 		 *	    In the case where the port is fixed, or for the
2940 		 *	    UDP case (whos toeplitz does not incorporate the
2941 		 *	    port), we set not_cpu_localized which ultimately
2942 		 *	    causes the pf_state_tree element
2943 		 *
2944 		 * XXX fixed ports present a problem for cpu localization.
2945 		 */
2946 		if (!(proto == IPPROTO_TCP ||
2947 		      proto == IPPROTO_UDP ||
2948 		      proto == IPPROTO_ICMP)) {
2949 			/*
2950 			 * non-specific protocol, leave port intact.
2951 			 */
2952 			key.port[1] = sport;
2953 			if (pf_find_state_all(&key, PF_IN, NULL) == NULL) {
2954 				*nport = sport;
2955 				pd->not_cpu_localized = 1;
2956 				return (0);
2957 			}
2958 		} else if (low == 0 && high == 0) {
2959 			/*
2960 			 * static-port same as originator.
2961 			 */
2962 			key.port[1] = sport;
2963 			if (pf_find_state_all(&key, PF_IN, NULL) == NULL) {
2964 				*nport = sport;
2965 				pd->not_cpu_localized = 1;
2966 				return (0);
2967 			}
2968 		} else if (low == high) {
2969 			/*
2970 			 * specific port as specified.
2971 			 */
2972 			key.port[1] = htons(low);
2973 			if (pf_find_state_all(&key, PF_IN, NULL) == NULL) {
2974 				*nport = htons(low);
2975 				pd->not_cpu_localized = 1;
2976 				return (0);
2977 			}
2978 		} else {
2979 			/*
2980 			 * normal dynamic port
2981 			 */
2982 			u_int16_t tmp;
2983 
2984 			if (low > high) {
2985 				tmp = low;
2986 				low = high;
2987 				high = tmp;
2988 			}
2989 			/* low < high */
2990 			cut = htonl(karc4random()) % (1 + high - low) + low;
2991 			/* low <= cut <= high */
2992 			for (tmp = cut; tmp <= high; ++(tmp)) {
2993 				key.port[1] = htons(tmp);
2994 				if ((toeplitz_piecemeal_port(key.port[1]) ^
2995 				     toeplitz_sport) & ncpus2_mask) {
2996 					continue;
2997 				}
2998 				if (pf_find_state_all(&key, PF_IN, NULL) ==
2999 				    NULL && !in_baddynamic(tmp, proto)) {
3000 					if (proto == IPPROTO_UDP)
3001 						pd->not_cpu_localized = 1;
3002 					*nport = htons(tmp);
3003 					return (0);
3004 				}
3005 			}
3006 			for (tmp = cut - 1; tmp >= low; --(tmp)) {
3007 				key.port[1] = htons(tmp);
3008 				if ((toeplitz_piecemeal_port(key.port[1]) ^
3009 				     toeplitz_sport) & ncpus2_mask) {
3010 					continue;
3011 				}
3012 				if (pf_find_state_all(&key, PF_IN, NULL) ==
3013 				    NULL && !in_baddynamic(tmp, proto)) {
3014 					if (proto == IPPROTO_UDP)
3015 						pd->not_cpu_localized = 1;
3016 					*nport = htons(tmp);
3017 					return (0);
3018 				}
3019 			}
3020 		}
3021 
3022 		/*
3023 		 * Next address
3024 		 */
3025 		switch (r->rpool.opts & PF_POOL_TYPEMASK) {
3026 		case PF_POOL_RANDOM:
3027 		case PF_POOL_ROUNDROBIN:
3028 			if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
3029 				return (1);
3030 			break;
3031 		case PF_POOL_NONE:
3032 		case PF_POOL_SRCHASH:
3033 		case PF_POOL_BITMASK:
3034 		default:
3035 			return (1);
3036 		}
3037 	} while (! PF_AEQ(&init_addr, naddr, af) );
3038 	return (1);					/* none available */
3039 }
3040 
3041 struct pf_rule *
3042 pf_match_translation(struct pf_pdesc *pd, struct mbuf *m, int off,
3043     int direction, struct pfi_kif *kif, struct pf_addr *saddr, u_int16_t sport,
3044     struct pf_addr *daddr, u_int16_t dport, int rs_num)
3045 {
3046 	struct pf_rule		*r, *rm = NULL;
3047 	struct pf_ruleset	*ruleset = NULL;
3048 	int			 tag = -1;
3049 	int			 rtableid = -1;
3050 	int			 asd = 0;
3051 
3052 	r = TAILQ_FIRST(pf_main_ruleset.rules[rs_num].active.ptr);
3053 	while (r && rm == NULL) {
3054 		struct pf_rule_addr	*src = NULL, *dst = NULL;
3055 		struct pf_addr_wrap	*xdst = NULL;
3056 		struct pf_pooladdr	*cur;
3057 
3058 		if (r->action == PF_BINAT && direction == PF_IN) {
3059 			src = &r->dst;
3060 			cur = r->rpool.cur;	/* SMP race possible */
3061 			cpu_ccfence();
3062 			if (cur)
3063 				xdst = &cur->addr;
3064 		} else {
3065 			src = &r->src;
3066 			dst = &r->dst;
3067 		}
3068 
3069 		r->evaluations++;
3070 		if (pfi_kif_match(r->kif, kif) == r->ifnot)
3071 			r = r->skip[PF_SKIP_IFP].ptr;
3072 		else if (r->direction && r->direction != direction)
3073 			r = r->skip[PF_SKIP_DIR].ptr;
3074 		else if (r->af && r->af != pd->af)
3075 			r = r->skip[PF_SKIP_AF].ptr;
3076 		else if (r->proto && r->proto != pd->proto)
3077 			r = r->skip[PF_SKIP_PROTO].ptr;
3078 		else if (PF_MISMATCHAW(&src->addr, saddr, pd->af,
3079 		    src->neg, kif))
3080 			r = r->skip[src == &r->src ? PF_SKIP_SRC_ADDR :
3081 			    PF_SKIP_DST_ADDR].ptr;
3082 		else if (src->port_op && !pf_match_port(src->port_op,
3083 		    src->port[0], src->port[1], sport))
3084 			r = r->skip[src == &r->src ? PF_SKIP_SRC_PORT :
3085 			    PF_SKIP_DST_PORT].ptr;
3086 		else if (dst != NULL &&
3087 		    PF_MISMATCHAW(&dst->addr, daddr, pd->af, dst->neg, NULL))
3088 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
3089 		else if (xdst != NULL && PF_MISMATCHAW(xdst, daddr, pd->af,
3090 		    0, NULL))
3091 			r = TAILQ_NEXT(r, entries);
3092 		else if (dst != NULL && dst->port_op &&
3093 		    !pf_match_port(dst->port_op, dst->port[0],
3094 		    dst->port[1], dport))
3095 			r = r->skip[PF_SKIP_DST_PORT].ptr;
3096 		else if (r->match_tag && !pf_match_tag(m, r, &tag))
3097 			r = TAILQ_NEXT(r, entries);
3098 		else if (r->os_fingerprint != PF_OSFP_ANY && (pd->proto !=
3099 		    IPPROTO_TCP || !pf_osfp_match(pf_osfp_fingerprint(pd, m,
3100 		    off, pd->hdr.tcp), r->os_fingerprint)))
3101 			r = TAILQ_NEXT(r, entries);
3102 		else {
3103 			if (r->tag)
3104 				tag = r->tag;
3105 			if (r->rtableid >= 0)
3106 				rtableid = r->rtableid;
3107 			if (r->anchor == NULL) {
3108 				rm = r;
3109 			} else
3110 				pf_step_into_anchor(&asd, &ruleset, rs_num,
3111 				    &r, NULL, NULL);
3112 		}
3113 		if (r == NULL)
3114 			pf_step_out_of_anchor(&asd, &ruleset, rs_num, &r,
3115 			    NULL, NULL);
3116 	}
3117 	if (pf_tag_packet(m, tag, rtableid))
3118 		return (NULL);
3119 	if (rm != NULL && (rm->action == PF_NONAT ||
3120 	    rm->action == PF_NORDR || rm->action == PF_NOBINAT))
3121 		return (NULL);
3122 	return (rm);
3123 }
3124 
3125 struct pf_rule *
3126 pf_get_translation(struct pf_pdesc *pd, struct mbuf *m, int off, int direction,
3127     struct pfi_kif *kif, struct pf_src_node **sn,
3128     struct pf_state_key **skw, struct pf_state_key **sks,
3129     struct pf_state_key **skp, struct pf_state_key **nkp,
3130     struct pf_addr *saddr, struct pf_addr *daddr,
3131     u_int16_t sport, u_int16_t dport)
3132 {
3133 	struct pf_rule	*r = NULL;
3134 
3135 	if (direction == PF_OUT) {
3136 		r = pf_match_translation(pd, m, off, direction, kif, saddr,
3137 		    sport, daddr, dport, PF_RULESET_BINAT);
3138 		if (r == NULL)
3139 			r = pf_match_translation(pd, m, off, direction, kif,
3140 			    saddr, sport, daddr, dport, PF_RULESET_NAT);
3141 	} else {
3142 		r = pf_match_translation(pd, m, off, direction, kif, saddr,
3143 		    sport, daddr, dport, PF_RULESET_RDR);
3144 		if (r == NULL)
3145 			r = pf_match_translation(pd, m, off, direction, kif,
3146 			    saddr, sport, daddr, dport, PF_RULESET_BINAT);
3147 	}
3148 
3149 	if (r != NULL) {
3150 		struct pf_addr	*naddr;
3151 		u_int16_t	*nport;
3152 
3153 		if (pf_state_key_setup(pd, r, skw, sks, skp, nkp,
3154 		    saddr, daddr, sport, dport))
3155 			return r;
3156 
3157 		/* XXX We only modify one side for now. */
3158 		naddr = &(*nkp)->addr[1];
3159 		nport = &(*nkp)->port[1];
3160 
3161 		/*
3162 		 * NOTE: Currently all translations will clear
3163 		 *	 BRIDGE_MBUF_TAGGED, telling the bridge to
3164 		 *	 ignore the original input encapsulation.
3165 		 */
3166 		switch (r->action) {
3167 		case PF_NONAT:
3168 		case PF_NOBINAT:
3169 		case PF_NORDR:
3170 			return (NULL);
3171 		case PF_NAT:
3172 			m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
3173 			if (pf_get_sport(pd, pd->af, pd->proto, r,
3174 			    saddr, daddr, sport, dport,
3175 			    naddr, nport, r->rpool.proxy_port[0],
3176 			    r->rpool.proxy_port[1], sn)) {
3177 				DPFPRINTF(PF_DEBUG_MISC,
3178 				    ("pf: NAT proxy port allocation "
3179 				    "(%u-%u) failed\n",
3180 				    r->rpool.proxy_port[0],
3181 				    r->rpool.proxy_port[1]));
3182 				return (NULL);
3183 			}
3184 			break;
3185 		case PF_BINAT:
3186 			m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
3187 			switch (direction) {
3188 			case PF_OUT:
3189 				if (r->rpool.cur->addr.type == PF_ADDR_DYNIFTL){
3190 					switch (pd->af) {
3191 #ifdef INET
3192 					case AF_INET:
3193 						if (r->rpool.cur->addr.p.dyn->
3194 						    pfid_acnt4 < 1)
3195 							return (NULL);
3196 						PF_POOLMASK(naddr,
3197 						    &r->rpool.cur->addr.p.dyn->
3198 						    pfid_addr4,
3199 						    &r->rpool.cur->addr.p.dyn->
3200 						    pfid_mask4,
3201 						    saddr, AF_INET);
3202 						break;
3203 #endif /* INET */
3204 #ifdef INET6
3205 					case AF_INET6:
3206 						if (r->rpool.cur->addr.p.dyn->
3207 						    pfid_acnt6 < 1)
3208 							return (NULL);
3209 						PF_POOLMASK(naddr,
3210 						    &r->rpool.cur->addr.p.dyn->
3211 						    pfid_addr6,
3212 						    &r->rpool.cur->addr.p.dyn->
3213 						    pfid_mask6,
3214 						    saddr, AF_INET6);
3215 						break;
3216 #endif /* INET6 */
3217 					}
3218 				} else
3219 					PF_POOLMASK(naddr,
3220 					    &r->rpool.cur->addr.v.a.addr,
3221 					    &r->rpool.cur->addr.v.a.mask,
3222 					    saddr, pd->af);
3223 				break;
3224 			case PF_IN:
3225 				if (r->src.addr.type == PF_ADDR_DYNIFTL) {
3226 					switch (pd->af) {
3227 #ifdef INET
3228 					case AF_INET:
3229 						if (r->src.addr.p.dyn->
3230 						    pfid_acnt4 < 1)
3231 							return (NULL);
3232 						PF_POOLMASK(naddr,
3233 						    &r->src.addr.p.dyn->
3234 						    pfid_addr4,
3235 						    &r->src.addr.p.dyn->
3236 						    pfid_mask4,
3237 						    daddr, AF_INET);
3238 						break;
3239 #endif /* INET */
3240 #ifdef INET6
3241 					case AF_INET6:
3242 						if (r->src.addr.p.dyn->
3243 						    pfid_acnt6 < 1)
3244 							return (NULL);
3245 						PF_POOLMASK(naddr,
3246 						    &r->src.addr.p.dyn->
3247 						    pfid_addr6,
3248 						    &r->src.addr.p.dyn->
3249 						    pfid_mask6,
3250 						    daddr, AF_INET6);
3251 						break;
3252 #endif /* INET6 */
3253 					}
3254 				} else
3255 					PF_POOLMASK(naddr,
3256 					    &r->src.addr.v.a.addr,
3257 					    &r->src.addr.v.a.mask, daddr,
3258 					    pd->af);
3259 				break;
3260 			}
3261 			break;
3262 		case PF_RDR: {
3263 			m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
3264 			if (pf_map_addr(pd->af, r, saddr, naddr, NULL, sn))
3265 				return (NULL);
3266 			if ((r->rpool.opts & PF_POOL_TYPEMASK) ==
3267 			    PF_POOL_BITMASK)
3268 				PF_POOLMASK(naddr, naddr,
3269 				    &r->rpool.cur->addr.v.a.mask, daddr,
3270 				    pd->af);
3271 
3272 			if (r->rpool.proxy_port[1]) {
3273 				u_int32_t	tmp_nport;
3274 
3275 				tmp_nport = ((ntohs(dport) -
3276 				    ntohs(r->dst.port[0])) %
3277 				    (r->rpool.proxy_port[1] -
3278 				    r->rpool.proxy_port[0] + 1)) +
3279 				    r->rpool.proxy_port[0];
3280 
3281 				/* wrap around if necessary */
3282 				if (tmp_nport > 65535)
3283 					tmp_nport -= 65535;
3284 				*nport = htons((u_int16_t)tmp_nport);
3285 			} else if (r->rpool.proxy_port[0]) {
3286 				*nport = htons(r->rpool.proxy_port[0]);
3287 			}
3288 			pd->not_cpu_localized = 1;
3289 			break;
3290 		}
3291 		default:
3292 			return (NULL);
3293 		}
3294 	}
3295 
3296 	return (r);
3297 }
3298 
3299 struct netmsg_hashlookup {
3300 	struct netmsg_base	base;
3301 	struct inpcb		**nm_pinp;
3302 	struct inpcbinfo    	*nm_pcbinfo;
3303 	struct pf_addr		*nm_saddr;
3304 	struct pf_addr		*nm_daddr;
3305 	uint16_t		nm_sport;
3306 	uint16_t		nm_dport;
3307 	sa_family_t		nm_af;
3308 };
3309 
3310 #ifdef PF_SOCKET_LOOKUP_DOMSG
3311 static void
3312 in_pcblookup_hash_handler(netmsg_t msg)
3313 {
3314 	struct netmsg_hashlookup *rmsg = (struct netmsg_hashlookup *)msg;
3315 
3316 	if (rmsg->nm_af == AF_INET)
3317 		*rmsg->nm_pinp = in_pcblookup_hash(rmsg->nm_pcbinfo,
3318 		    rmsg->nm_saddr->v4, rmsg->nm_sport, rmsg->nm_daddr->v4,
3319 		    rmsg->nm_dport, INPLOOKUP_WILDCARD, NULL);
3320 #ifdef INET6
3321 	else
3322 		*rmsg->nm_pinp = in6_pcblookup_hash(rmsg->nm_pcbinfo,
3323 		    &rmsg->nm_saddr->v6, rmsg->nm_sport, &rmsg->nm_daddr->v6,
3324 		    rmsg->nm_dport, INPLOOKUP_WILDCARD, NULL);
3325 #endif /* INET6 */
3326 	lwkt_replymsg(&rmsg->base.lmsg, 0);
3327 }
3328 #endif	/* PF_SOCKET_LOOKUP_DOMSG */
3329 
3330 int
3331 pf_socket_lookup(int direction, struct pf_pdesc *pd)
3332 {
3333 	struct pf_addr		*saddr, *daddr;
3334 	u_int16_t		 sport, dport;
3335 	struct inpcbinfo	*pi;
3336 	struct inpcb		*inp;
3337 	struct netmsg_hashlookup *msg = NULL;
3338 #ifdef PF_SOCKET_LOOKUP_DOMSG
3339 	struct netmsg_hashlookup msg0;
3340 #endif
3341 	int			 pi_cpu = 0;
3342 
3343 	if (pd == NULL)
3344 		return (-1);
3345 	pd->lookup.uid = UID_MAX;
3346 	pd->lookup.gid = GID_MAX;
3347 	pd->lookup.pid = NO_PID;
3348 	if (direction == PF_IN) {
3349 		saddr = pd->src;
3350 		daddr = pd->dst;
3351 	} else {
3352 		saddr = pd->dst;
3353 		daddr = pd->src;
3354 	}
3355 	switch (pd->proto) {
3356 	case IPPROTO_TCP:
3357 		if (pd->hdr.tcp == NULL)
3358 			return (-1);
3359 		sport = pd->hdr.tcp->th_sport;
3360 		dport = pd->hdr.tcp->th_dport;
3361 
3362 		pi_cpu = tcp_addrcpu(saddr->v4.s_addr, sport, daddr->v4.s_addr, dport);
3363 		pi = &tcbinfo[pi_cpu];
3364 		/*
3365 		 * Our netstack runs lockless on MP systems
3366 		 * (only for TCP connections at the moment).
3367 		 *
3368 		 * As we are not allowed to read another CPU's tcbinfo,
3369 		 * we have to ask that CPU via remote call to search the
3370 		 * table for us.
3371 		 *
3372 		 * Prepare a msg iff data belongs to another CPU.
3373 		 */
3374 		if (pi_cpu != mycpu->gd_cpuid) {
3375 #ifdef PF_SOCKET_LOOKUP_DOMSG
3376 			/*
3377 			 * NOTE:
3378 			 *
3379 			 * Following lwkt_domsg() is dangerous and could
3380 			 * lockup the network system, e.g.
3381 			 *
3382 			 * On 2 CPU system:
3383 			 * netisr0 domsg to netisr1 (due to lookup)
3384 			 * netisr1 domsg to netisr0 (due to lookup)
3385 			 *
3386 			 * We simply return -1 here, since we are probably
3387 			 * called before NAT, so the TCP packet should
3388 			 * already be on the correct CPU.
3389 			 */
3390 			msg = &msg0;
3391 			netmsg_init(&msg->base, NULL, &curthread->td_msgport,
3392 				    0, in_pcblookup_hash_handler);
3393 			msg->nm_pinp = &inp;
3394 			msg->nm_pcbinfo = pi;
3395 			msg->nm_saddr = saddr;
3396 			msg->nm_sport = sport;
3397 			msg->nm_daddr = daddr;
3398 			msg->nm_dport = dport;
3399 			msg->nm_af = pd->af;
3400 #else	/* !PF_SOCKET_LOOKUP_DOMSG */
3401 			kprintf("pf_socket_lookup: tcp packet not on the "
3402 				"correct cpu %d, cur cpu %d\n",
3403 				pi_cpu, mycpuid);
3404 			print_backtrace(-1);
3405 			return -1;
3406 #endif	/* PF_SOCKET_LOOKUP_DOMSG */
3407 		}
3408 		break;
3409 	case IPPROTO_UDP:
3410 		if (pd->hdr.udp == NULL)
3411 			return (-1);
3412 		sport = pd->hdr.udp->uh_sport;
3413 		dport = pd->hdr.udp->uh_dport;
3414 		pi = &udbinfo[mycpuid];
3415 		break;
3416 	default:
3417 		return (-1);
3418 	}
3419 	if (direction != PF_IN) {
3420 		u_int16_t	p;
3421 
3422 		p = sport;
3423 		sport = dport;
3424 		dport = p;
3425 	}
3426 	switch (pd->af) {
3427 #ifdef INET6
3428 	case AF_INET6:
3429 		/*
3430 		 * Query other CPU, second part
3431 		 *
3432 		 * msg only gets initialized when:
3433 		 * 1) packet is TCP
3434 		 * 2) the info belongs to another CPU
3435 		 *
3436 		 * Use some switch/case magic to avoid code duplication.
3437 		 */
3438 		if (msg == NULL) {
3439 			inp = in6_pcblookup_hash(pi, &saddr->v6, sport,
3440 			    &daddr->v6, dport, INPLOOKUP_WILDCARD, NULL);
3441 
3442 			if (inp == NULL)
3443 				return (-1);
3444 			break;
3445 		}
3446 		/* FALLTHROUGH if SMP and on other CPU */
3447 #endif /* INET6 */
3448 	case AF_INET:
3449 		if (msg != NULL) {
3450 			lwkt_domsg(netisr_cpuport(pi_cpu),
3451 				     &msg->base.lmsg, 0);
3452 		} else
3453 		{
3454 			inp = in_pcblookup_hash(pi, saddr->v4, sport, daddr->v4,
3455 			    dport, INPLOOKUP_WILDCARD, NULL);
3456 		}
3457 		if (inp == NULL)
3458 			return (-1);
3459 		break;
3460 
3461 	default:
3462 		return (-1);
3463 	}
3464 	pd->lookup.uid = inp->inp_socket->so_cred->cr_uid;
3465 	pd->lookup.gid = inp->inp_socket->so_cred->cr_groups[0];
3466 	return (1);
3467 }
3468 
3469 u_int8_t
3470 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3471 {
3472 	int		 hlen;
3473 	u_int8_t	 hdr[60];
3474 	u_int8_t	*opt, optlen;
3475 	u_int8_t	 wscale = 0;
3476 
3477 	hlen = th_off << 2;		/* hlen <= sizeof(hdr) */
3478 	if (hlen <= sizeof(struct tcphdr))
3479 		return (0);
3480 	if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3481 		return (0);
3482 	opt = hdr + sizeof(struct tcphdr);
3483 	hlen -= sizeof(struct tcphdr);
3484 	while (hlen >= 3) {
3485 		switch (*opt) {
3486 		case TCPOPT_EOL:
3487 		case TCPOPT_NOP:
3488 			++opt;
3489 			--hlen;
3490 			break;
3491 		case TCPOPT_WINDOW:
3492 			wscale = opt[2];
3493 			if (wscale > TCP_MAX_WINSHIFT)
3494 				wscale = TCP_MAX_WINSHIFT;
3495 			wscale |= PF_WSCALE_FLAG;
3496 			/* FALLTHROUGH */
3497 		default:
3498 			optlen = opt[1];
3499 			if (optlen < 2)
3500 				optlen = 2;
3501 			hlen -= optlen;
3502 			opt += optlen;
3503 			break;
3504 		}
3505 	}
3506 	return (wscale);
3507 }
3508 
3509 u_int16_t
3510 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3511 {
3512 	int		 hlen;
3513 	u_int8_t	 hdr[60];
3514 	u_int8_t	*opt, optlen;
3515 	u_int16_t	 mss = tcp_mssdflt;
3516 
3517 	hlen = th_off << 2;	/* hlen <= sizeof(hdr) */
3518 	if (hlen <= sizeof(struct tcphdr))
3519 		return (0);
3520 	if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3521 		return (0);
3522 	opt = hdr + sizeof(struct tcphdr);
3523 	hlen -= sizeof(struct tcphdr);
3524 	while (hlen >= TCPOLEN_MAXSEG) {
3525 		switch (*opt) {
3526 		case TCPOPT_EOL:
3527 		case TCPOPT_NOP:
3528 			++opt;
3529 			--hlen;
3530 			break;
3531 		case TCPOPT_MAXSEG:
3532 			bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3533 			/* FALLTHROUGH */
3534 		default:
3535 			optlen = opt[1];
3536 			if (optlen < 2)
3537 				optlen = 2;
3538 			hlen -= optlen;
3539 			opt += optlen;
3540 			break;
3541 		}
3542 	}
3543 	return (mss);
3544 }
3545 
3546 u_int16_t
3547 pf_calc_mss(struct pf_addr *addr, sa_family_t af, u_int16_t offer)
3548 {
3549 #ifdef INET
3550 	struct sockaddr_in	*dst;
3551 	struct route		 ro;
3552 #endif /* INET */
3553 #ifdef INET6
3554 	struct sockaddr_in6	*dst6;
3555 	struct route_in6	 ro6;
3556 #endif /* INET6 */
3557 	struct rtentry		*rt = NULL;
3558 	int			 hlen = 0;
3559 	u_int16_t		 mss = tcp_mssdflt;
3560 
3561 	switch (af) {
3562 #ifdef INET
3563 	case AF_INET:
3564 		hlen = sizeof(struct ip);
3565 		bzero(&ro, sizeof(ro));
3566 		dst = (struct sockaddr_in *)&ro.ro_dst;
3567 		dst->sin_family = AF_INET;
3568 		dst->sin_len = sizeof(*dst);
3569 		dst->sin_addr = addr->v4;
3570 		rtalloc_ign(&ro, (RTF_CLONING | RTF_PRCLONING));
3571 		rt = ro.ro_rt;
3572 		break;
3573 #endif /* INET */
3574 #ifdef INET6
3575 	case AF_INET6:
3576 		hlen = sizeof(struct ip6_hdr);
3577 		bzero(&ro6, sizeof(ro6));
3578 		dst6 = (struct sockaddr_in6 *)&ro6.ro_dst;
3579 		dst6->sin6_family = AF_INET6;
3580 		dst6->sin6_len = sizeof(*dst6);
3581 		dst6->sin6_addr = addr->v6;
3582 		rtalloc_ign((struct route *)&ro6, (RTF_CLONING | RTF_PRCLONING));
3583 		rt = ro6.ro_rt;
3584 		break;
3585 #endif /* INET6 */
3586 	}
3587 
3588 	if (rt && rt->rt_ifp) {
3589 		mss = rt->rt_ifp->if_mtu - hlen - sizeof(struct tcphdr);
3590 		mss = max(tcp_mssdflt, mss);
3591 		RTFREE(rt);
3592 	}
3593 	mss = min(mss, offer);
3594 	mss = max(mss, 64);		/* sanity - at least max opt space */
3595 	return (mss);
3596 }
3597 
3598 void
3599 pf_set_rt_ifp(struct pf_state *s, struct pf_addr *saddr)
3600 {
3601 	struct pf_rule *r = s->rule.ptr;
3602 
3603 	s->rt_kif = NULL;
3604 	if (!r->rt || r->rt == PF_FASTROUTE)
3605 		return;
3606 	switch (s->key[PF_SK_WIRE]->af) {
3607 #ifdef INET
3608 	case AF_INET:
3609 		pf_map_addr(AF_INET, r, saddr, &s->rt_addr, NULL,
3610 		    &s->nat_src_node);
3611 		s->rt_kif = r->rpool.cur->kif;
3612 		break;
3613 #endif /* INET */
3614 #ifdef INET6
3615 	case AF_INET6:
3616 		pf_map_addr(AF_INET6, r, saddr, &s->rt_addr, NULL,
3617 		    &s->nat_src_node);
3618 		s->rt_kif = r->rpool.cur->kif;
3619 		break;
3620 #endif /* INET6 */
3621 	}
3622 }
3623 
3624 u_int32_t
3625 pf_tcp_iss(struct pf_pdesc *pd)
3626 {
3627 	MD5_CTX ctx;
3628 	u_int32_t digest[4];
3629 
3630 	if (pf_tcp_secret_init == 0) {
3631 		lwkt_gettoken(&pf_gtoken);
3632 		if (pf_tcp_secret_init == 0) {
3633 			karc4rand(pf_tcp_secret, sizeof(pf_tcp_secret));
3634 			MD5Init(&pf_tcp_secret_ctx);
3635 			MD5Update(&pf_tcp_secret_ctx, pf_tcp_secret,
3636 			    sizeof(pf_tcp_secret));
3637 			pf_tcp_secret_init = 1;
3638 		}
3639 		lwkt_reltoken(&pf_gtoken);
3640 	}
3641 	ctx = pf_tcp_secret_ctx;
3642 
3643 	MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3644 	MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3645 	if (pd->af == AF_INET6) {
3646 		MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3647 		MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3648 	} else {
3649 		MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3650 		MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3651 	}
3652 	MD5Final((u_char *)digest, &ctx);
3653 	pf_tcp_iss_off += 4096;
3654 
3655 	return (digest[0] + pd->hdr.tcp->th_seq + pf_tcp_iss_off);
3656 }
3657 
3658 int
3659 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3660     struct pfi_kif *kif, struct mbuf *m, int off, void *h,
3661     struct pf_pdesc *pd, struct pf_rule **am, struct pf_ruleset **rsm,
3662     struct ifqueue *ifq, struct inpcb *inp)
3663 {
3664 	struct pf_rule		*nr = NULL;
3665 	struct pf_addr		*saddr = pd->src, *daddr = pd->dst;
3666 	sa_family_t		 af = pd->af;
3667 	struct pf_rule		*r, *a = NULL;
3668 	struct pf_ruleset	*ruleset = NULL;
3669 	struct pf_src_node	*nsn = NULL;
3670 	struct tcphdr		*th = pd->hdr.tcp;
3671 	struct pf_state_key	*skw = NULL, *sks = NULL;
3672 	struct pf_state_key	*sk = NULL, *nk = NULL;
3673 	u_short			 reason;
3674 	int			 rewrite = 0, hdrlen = 0;
3675 	int			 tag = -1, rtableid = -1;
3676 	int			 asd = 0;
3677 	int			 match = 0;
3678 	int			 state_icmp = 0;
3679 	u_int16_t		 sport = 0, dport = 0;
3680 	u_int16_t		 bproto_sum = 0, bip_sum = 0;
3681 	u_int8_t		 icmptype = 0, icmpcode = 0;
3682 
3683 
3684 	if (direction == PF_IN && pf_check_congestion(ifq)) {
3685 		REASON_SET(&reason, PFRES_CONGEST);
3686 		return (PF_DROP);
3687 	}
3688 
3689 	if (inp != NULL)
3690 		pd->lookup.done = pf_socket_lookup(direction, pd);
3691 	else if (debug_pfugidhack) {
3692 		DPFPRINTF(PF_DEBUG_MISC, ("pf: unlocked lookup\n"));
3693 		pd->lookup.done = pf_socket_lookup(direction, pd);
3694 	}
3695 
3696 	switch (pd->proto) {
3697 	case IPPROTO_TCP:
3698 		sport = th->th_sport;
3699 		dport = th->th_dport;
3700 		hdrlen = sizeof(*th);
3701 		break;
3702 	case IPPROTO_UDP:
3703 		sport = pd->hdr.udp->uh_sport;
3704 		dport = pd->hdr.udp->uh_dport;
3705 		hdrlen = sizeof(*pd->hdr.udp);
3706 		break;
3707 #ifdef INET
3708 	case IPPROTO_ICMP:
3709 		if (pd->af != AF_INET)
3710 			break;
3711 		sport = dport = pd->hdr.icmp->icmp_id;
3712 		hdrlen = sizeof(*pd->hdr.icmp);
3713 		icmptype = pd->hdr.icmp->icmp_type;
3714 		icmpcode = pd->hdr.icmp->icmp_code;
3715 
3716 		if (icmptype == ICMP_UNREACH ||
3717 		    icmptype == ICMP_SOURCEQUENCH ||
3718 		    icmptype == ICMP_REDIRECT ||
3719 		    icmptype == ICMP_TIMXCEED ||
3720 		    icmptype == ICMP_PARAMPROB)
3721 			state_icmp++;
3722 		break;
3723 #endif /* INET */
3724 #ifdef INET6
3725 	case IPPROTO_ICMPV6:
3726 		if (af != AF_INET6)
3727 			break;
3728 		sport = dport = pd->hdr.icmp6->icmp6_id;
3729 		hdrlen = sizeof(*pd->hdr.icmp6);
3730 		icmptype = pd->hdr.icmp6->icmp6_type;
3731 		icmpcode = pd->hdr.icmp6->icmp6_code;
3732 
3733 		if (icmptype == ICMP6_DST_UNREACH ||
3734 		    icmptype == ICMP6_PACKET_TOO_BIG ||
3735 		    icmptype == ICMP6_TIME_EXCEEDED ||
3736 		    icmptype == ICMP6_PARAM_PROB)
3737 			state_icmp++;
3738 		break;
3739 #endif /* INET6 */
3740 	default:
3741 		sport = dport = hdrlen = 0;
3742 		break;
3743 	}
3744 
3745 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3746 
3747 	/* check packet for BINAT/NAT/RDR */
3748 	if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn,
3749 	    &skw, &sks, &sk, &nk, saddr, daddr, sport, dport)) != NULL) {
3750 		if (nk == NULL || sk == NULL) {
3751 			REASON_SET(&reason, PFRES_MEMORY);
3752 			goto cleanup;
3753 		}
3754 
3755 		if (pd->ip_sum)
3756 			bip_sum = *pd->ip_sum;
3757 
3758 		m->m_flags &= ~M_HASH;
3759 		switch (pd->proto) {
3760 		case IPPROTO_TCP:
3761 			bproto_sum = th->th_sum;
3762 			pd->proto_sum = &th->th_sum;
3763 
3764 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3765 			    nk->port[pd->sidx] != sport) {
3766 				pf_change_ap(saddr, &th->th_sport, pd->ip_sum,
3767 				    &th->th_sum, &nk->addr[pd->sidx],
3768 				    nk->port[pd->sidx], 0, af);
3769 				pd->sport = &th->th_sport;
3770 				sport = th->th_sport;
3771 			}
3772 
3773 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3774 			    nk->port[pd->didx] != dport) {
3775 				pf_change_ap(daddr, &th->th_dport, pd->ip_sum,
3776 				    &th->th_sum, &nk->addr[pd->didx],
3777 				    nk->port[pd->didx], 0, af);
3778 				dport = th->th_dport;
3779 				pd->dport = &th->th_dport;
3780 			}
3781 			rewrite++;
3782 			break;
3783 		case IPPROTO_UDP:
3784 			bproto_sum = pd->hdr.udp->uh_sum;
3785 			pd->proto_sum = &pd->hdr.udp->uh_sum;
3786 
3787 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3788 			    nk->port[pd->sidx] != sport) {
3789 				pf_change_ap(saddr, &pd->hdr.udp->uh_sport,
3790 				    pd->ip_sum, &pd->hdr.udp->uh_sum,
3791 				    &nk->addr[pd->sidx],
3792 				    nk->port[pd->sidx], 1, af);
3793 				sport = pd->hdr.udp->uh_sport;
3794 				pd->sport = &pd->hdr.udp->uh_sport;
3795 			}
3796 
3797 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3798 			    nk->port[pd->didx] != dport) {
3799 				pf_change_ap(daddr, &pd->hdr.udp->uh_dport,
3800 				    pd->ip_sum, &pd->hdr.udp->uh_sum,
3801 				    &nk->addr[pd->didx],
3802 				    nk->port[pd->didx], 1, af);
3803 				dport = pd->hdr.udp->uh_dport;
3804 				pd->dport = &pd->hdr.udp->uh_dport;
3805 			}
3806 			rewrite++;
3807 			break;
3808 #ifdef INET
3809 		case IPPROTO_ICMP:
3810 			nk->port[0] = nk->port[1];
3811 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3812 				pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3813 				    nk->addr[pd->sidx].v4.s_addr, 0);
3814 
3815 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3816 				pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3817 				    nk->addr[pd->didx].v4.s_addr, 0);
3818 
3819 			if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3820 				pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3821 				    pd->hdr.icmp->icmp_cksum, sport,
3822 				    nk->port[1], 0);
3823 				pd->hdr.icmp->icmp_id = nk->port[1];
3824 				pd->sport = &pd->hdr.icmp->icmp_id;
3825 			}
3826 			m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3827 			break;
3828 #endif /* INET */
3829 #ifdef INET6
3830 		case IPPROTO_ICMPV6:
3831 			nk->port[0] = nk->port[1];
3832 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3833 				pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3834 				    &nk->addr[pd->sidx], 0);
3835 
3836 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3837 				pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3838 				    &nk->addr[pd->didx], 0);
3839 			rewrite++;
3840 			break;
3841 #endif /* INET */
3842 		default:
3843 			switch (af) {
3844 #ifdef INET
3845 			case AF_INET:
3846 				if (PF_ANEQ(saddr,
3847 				    &nk->addr[pd->sidx], AF_INET))
3848 					pf_change_a(&saddr->v4.s_addr,
3849 					    pd->ip_sum,
3850 					    nk->addr[pd->sidx].v4.s_addr, 0);
3851 
3852 				if (PF_ANEQ(daddr,
3853 				    &nk->addr[pd->didx], AF_INET))
3854 					pf_change_a(&daddr->v4.s_addr,
3855 					    pd->ip_sum,
3856 					    nk->addr[pd->didx].v4.s_addr, 0);
3857 				break;
3858 #endif /* INET */
3859 #ifdef INET6
3860 			case AF_INET6:
3861 				if (PF_ANEQ(saddr,
3862 				    &nk->addr[pd->sidx], AF_INET6))
3863 					PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3864 
3865 				if (PF_ANEQ(daddr,
3866 				    &nk->addr[pd->didx], AF_INET6))
3867 					PF_ACPY(saddr, &nk->addr[pd->didx], af);
3868 				break;
3869 #endif /* INET */
3870 			}
3871 			break;
3872 		}
3873 		if (nr->natpass)
3874 			r = NULL;
3875 		pd->nat_rule = nr;
3876 	}
3877 
3878 	while (r != NULL) {
3879 		r->evaluations++;
3880 		if (pfi_kif_match(r->kif, kif) == r->ifnot)
3881 			r = r->skip[PF_SKIP_IFP].ptr;
3882 		else if (r->direction && r->direction != direction)
3883 			r = r->skip[PF_SKIP_DIR].ptr;
3884 		else if (r->af && r->af != af)
3885 			r = r->skip[PF_SKIP_AF].ptr;
3886 		else if (r->proto && r->proto != pd->proto)
3887 			r = r->skip[PF_SKIP_PROTO].ptr;
3888 		else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3889 		    r->src.neg, kif))
3890 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3891 		/* tcp/udp only. port_op always 0 in other cases */
3892 		else if (r->src.port_op && !pf_match_port(r->src.port_op,
3893 		    r->src.port[0], r->src.port[1], sport))
3894 			r = r->skip[PF_SKIP_SRC_PORT].ptr;
3895 		else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3896 		    r->dst.neg, NULL))
3897 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
3898 		/* tcp/udp only. port_op always 0 in other cases */
3899 		else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3900 		    r->dst.port[0], r->dst.port[1], dport))
3901 			r = r->skip[PF_SKIP_DST_PORT].ptr;
3902 		/* icmp only. type always 0 in other cases */
3903 		else if (r->type && r->type != icmptype + 1)
3904 			r = TAILQ_NEXT(r, entries);
3905 		/* icmp only. type always 0 in other cases */
3906 		else if (r->code && r->code != icmpcode + 1)
3907 			r = TAILQ_NEXT(r, entries);
3908 		else if (r->tos && !(r->tos == pd->tos))
3909 			r = TAILQ_NEXT(r, entries);
3910 		else if (r->rule_flag & PFRULE_FRAGMENT)
3911 			r = TAILQ_NEXT(r, entries);
3912 		else if (pd->proto == IPPROTO_TCP &&
3913 		    (r->flagset & th->th_flags) != r->flags)
3914 			r = TAILQ_NEXT(r, entries);
3915 		/* tcp/udp only. uid.op always 0 in other cases */
3916 		else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3917 		    pf_socket_lookup(direction, pd), 1)) &&
3918 		    !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3919 		    pd->lookup.uid))
3920 			r = TAILQ_NEXT(r, entries);
3921 		/* tcp/udp only. gid.op always 0 in other cases */
3922 		else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3923 		    pf_socket_lookup(direction, pd), 1)) &&
3924 		    !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3925 		    pd->lookup.gid))
3926 			r = TAILQ_NEXT(r, entries);
3927 		else if (r->prob &&
3928 		  r->prob <= karc4random())
3929 			r = TAILQ_NEXT(r, entries);
3930 		else if (r->match_tag && !pf_match_tag(m, r, &tag))
3931 			r = TAILQ_NEXT(r, entries);
3932 		else if (r->os_fingerprint != PF_OSFP_ANY &&
3933 		    (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3934 		    pf_osfp_fingerprint(pd, m, off, th),
3935 		    r->os_fingerprint)))
3936 			r = TAILQ_NEXT(r, entries);
3937 		else {
3938 			if (r->tag)
3939 				tag = r->tag;
3940 			if (r->rtableid >= 0)
3941 				rtableid = r->rtableid;
3942 			if (r->anchor == NULL) {
3943 				match = 1;
3944 				*rm = r;
3945 				*am = a;
3946 				*rsm = ruleset;
3947 				if ((*rm)->quick)
3948 					break;
3949 				r = TAILQ_NEXT(r, entries);
3950 			} else
3951 				pf_step_into_anchor(&asd, &ruleset,
3952 				    PF_RULESET_FILTER, &r, &a, &match);
3953 		}
3954 		if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
3955 		    PF_RULESET_FILTER, &r, &a, &match))
3956 			break;
3957 	}
3958 	r = *rm;
3959 	a = *am;
3960 	ruleset = *rsm;
3961 
3962 	REASON_SET(&reason, PFRES_MATCH);
3963 
3964 	if (r->log || (nr != NULL && nr->log)) {
3965 		if (rewrite)
3966 			m_copyback(m, off, hdrlen, pd->hdr.any);
3967 		PFLOG_PACKET(kif, h, m, af, direction, reason, r->log ? r : nr,
3968 		    a, ruleset, pd);
3969 	}
3970 
3971 	if ((r->action == PF_DROP) &&
3972 	    ((r->rule_flag & PFRULE_RETURNRST) ||
3973 	    (r->rule_flag & PFRULE_RETURNICMP) ||
3974 	    (r->rule_flag & PFRULE_RETURN))) {
3975 		/* undo NAT changes, if they have taken place */
3976 		if (nr != NULL) {
3977 			PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3978 			PF_ACPY(daddr, &sk->addr[pd->didx], af);
3979 			if (pd->sport)
3980 				*pd->sport = sk->port[pd->sidx];
3981 			if (pd->dport)
3982 				*pd->dport = sk->port[pd->didx];
3983 			if (pd->proto_sum)
3984 				*pd->proto_sum = bproto_sum;
3985 			if (pd->ip_sum)
3986 				*pd->ip_sum = bip_sum;
3987 			m_copyback(m, off, hdrlen, pd->hdr.any);
3988 		}
3989 		if (pd->proto == IPPROTO_TCP &&
3990 		    ((r->rule_flag & PFRULE_RETURNRST) ||
3991 		    (r->rule_flag & PFRULE_RETURN)) &&
3992 		    !(th->th_flags & TH_RST)) {
3993 			u_int32_t	 ack = ntohl(th->th_seq) + pd->p_len;
3994 			int		 len = 0;
3995 			struct ip	*h4;
3996 #ifdef INET6
3997 			struct ip6_hdr	*h6;
3998 #endif
3999 			switch (af) {
4000 			case AF_INET:
4001 				h4 = mtod(m, struct ip *);
4002 				len = h4->ip_len - off;
4003 				break;
4004 #ifdef INET6
4005 			case AF_INET6:
4006 				h6 = mtod(m, struct ip6_hdr *);
4007 				len = h6->ip6_plen - (off - sizeof(*h6));
4008 				break;
4009 #endif
4010 			}
4011 
4012 			if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
4013 				REASON_SET(&reason, PFRES_PROTCKSUM);
4014 			else {
4015 				if (th->th_flags & TH_SYN)
4016 					ack++;
4017 				if (th->th_flags & TH_FIN)
4018 					ack++;
4019 				pf_send_tcp(r, af, pd->dst,
4020 				    pd->src, th->th_dport, th->th_sport,
4021 				    ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
4022 				    r->return_ttl, 1, 0, pd->eh, kif->pfik_ifp);
4023 			}
4024 		} else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
4025 		    r->return_icmp)
4026 			pf_send_icmp(m, r->return_icmp >> 8,
4027 			    r->return_icmp & 255, af, r);
4028 		else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
4029 		    r->return_icmp6)
4030 			pf_send_icmp(m, r->return_icmp6 >> 8,
4031 			    r->return_icmp6 & 255, af, r);
4032 	}
4033 
4034 	if (r->action == PF_DROP)
4035 		goto cleanup;
4036 
4037 	if (pf_tag_packet(m, tag, rtableid)) {
4038 		REASON_SET(&reason, PFRES_MEMORY);
4039 		goto cleanup;
4040 	}
4041 
4042 	if (!state_icmp && (r->keep_state || nr != NULL ||
4043 	    (pd->flags & PFDESC_TCP_NORM))) {
4044 		int action;
4045 		action = pf_create_state(r, nr, a, pd, nsn, skw, sks, nk, sk, m,
4046 		    off, sport, dport, &rewrite, kif, sm, tag, bproto_sum,
4047 		    bip_sum, hdrlen);
4048 		if (action != PF_PASS)
4049 			return (action);
4050 	}
4051 
4052 	/* copy back packet headers if we performed NAT operations */
4053 	if (rewrite)
4054 		m_copyback(m, off, hdrlen, pd->hdr.any);
4055 
4056 	return (PF_PASS);
4057 
4058 cleanup:
4059 	if (sk != NULL)
4060 		kfree(sk, M_PFSTATEKEYPL);
4061 	if (nk != NULL)
4062 		kfree(nk, M_PFSTATEKEYPL);
4063 	return (PF_DROP);
4064 }
4065 
4066 static __inline int
4067 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
4068     struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *skw,
4069     struct pf_state_key *sks, struct pf_state_key *nk, struct pf_state_key *sk,
4070     struct mbuf *m, int off, u_int16_t sport, u_int16_t dport, int *rewrite,
4071     struct pfi_kif *kif, struct pf_state **sm, int tag, u_int16_t bproto_sum,
4072     u_int16_t bip_sum, int hdrlen)
4073 {
4074 	struct pf_state		*s = NULL;
4075 	struct pf_src_node	*sn = NULL;
4076 	struct tcphdr		*th = pd->hdr.tcp;
4077 	u_int16_t		 mss = tcp_mssdflt;
4078 	u_short			 reason;
4079 	int cpu = mycpu->gd_cpuid;
4080 
4081 	/* check maximums */
4082 	if (r->max_states && (r->states_cur >= r->max_states)) {
4083 		pf_status.lcounters[LCNT_STATES]++;
4084 		REASON_SET(&reason, PFRES_MAXSTATES);
4085 		return (PF_DROP);
4086 	}
4087 	/* src node for filter rule */
4088 	if ((r->rule_flag & PFRULE_SRCTRACK ||
4089 	    r->rpool.opts & PF_POOL_STICKYADDR) &&
4090 	    pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
4091 		REASON_SET(&reason, PFRES_SRCLIMIT);
4092 		goto csfailed;
4093 	}
4094 	/* src node for translation rule */
4095 	if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
4096 	    pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
4097 		REASON_SET(&reason, PFRES_SRCLIMIT);
4098 		goto csfailed;
4099 	}
4100 	s = kmalloc(sizeof(struct pf_state), M_PFSTATEPL, M_NOWAIT|M_ZERO);
4101 	if (s == NULL) {
4102 		REASON_SET(&reason, PFRES_MEMORY);
4103 		goto csfailed;
4104 	}
4105 	lockinit(&s->lk, "pfstlk", 0, 0);
4106 	s->id = 0; /* XXX Do we really need that? not in OpenBSD */
4107 	s->creatorid = 0;
4108 	s->rule.ptr = r;
4109 	s->nat_rule.ptr = nr;
4110 	s->anchor.ptr = a;
4111 	s->state_flags = PFSTATE_CREATEINPROG;
4112 	STATE_INC_COUNTERS(s);
4113 	if (r->allow_opts)
4114 		s->state_flags |= PFSTATE_ALLOWOPTS;
4115 	if (r->rule_flag & PFRULE_STATESLOPPY)
4116 		s->state_flags |= PFSTATE_SLOPPY;
4117 	if (pd->not_cpu_localized)
4118 		s->state_flags |= PFSTATE_STACK_GLOBAL;
4119 
4120 	s->log = r->log & PF_LOG_ALL;
4121 	if (nr != NULL)
4122 		s->log |= nr->log & PF_LOG_ALL;
4123 	switch (pd->proto) {
4124 	case IPPROTO_TCP:
4125 		s->src.seqlo = ntohl(th->th_seq);
4126 		s->src.seqhi = s->src.seqlo + pd->p_len + 1;
4127 		if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
4128 		    r->keep_state == PF_STATE_MODULATE) {
4129 			/* Generate sequence number modulator */
4130 			if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
4131 			    0)
4132 				s->src.seqdiff = 1;
4133 			pf_change_a(&th->th_seq, &th->th_sum,
4134 			    htonl(s->src.seqlo + s->src.seqdiff), 0);
4135 			*rewrite = 1;
4136 		} else
4137 			s->src.seqdiff = 0;
4138 		if (th->th_flags & TH_SYN) {
4139 			s->src.seqhi++;
4140 			s->src.wscale = pf_get_wscale(m, off,
4141 			    th->th_off, pd->af);
4142 		}
4143 		s->src.max_win = MAX(ntohs(th->th_win), 1);
4144 		if (s->src.wscale & PF_WSCALE_MASK) {
4145 			/* Remove scale factor from initial window */
4146 			int win = s->src.max_win;
4147 			win += 1 << (s->src.wscale & PF_WSCALE_MASK);
4148 			s->src.max_win = (win - 1) >>
4149 			    (s->src.wscale & PF_WSCALE_MASK);
4150 		}
4151 		if (th->th_flags & TH_FIN)
4152 			s->src.seqhi++;
4153 		s->dst.seqhi = 1;
4154 		s->dst.max_win = 1;
4155 		s->src.state = TCPS_SYN_SENT;
4156 		s->dst.state = TCPS_CLOSED;
4157 		s->timeout = PFTM_TCP_FIRST_PACKET;
4158 		break;
4159 	case IPPROTO_UDP:
4160 		s->src.state = PFUDPS_SINGLE;
4161 		s->dst.state = PFUDPS_NO_TRAFFIC;
4162 		s->timeout = PFTM_UDP_FIRST_PACKET;
4163 		break;
4164 	case IPPROTO_ICMP:
4165 #ifdef INET6
4166 	case IPPROTO_ICMPV6:
4167 #endif
4168 		s->timeout = PFTM_ICMP_FIRST_PACKET;
4169 		break;
4170 	default:
4171 		s->src.state = PFOTHERS_SINGLE;
4172 		s->dst.state = PFOTHERS_NO_TRAFFIC;
4173 		s->timeout = PFTM_OTHER_FIRST_PACKET;
4174 	}
4175 
4176 	s->creation = time_second;
4177 	s->expire = time_second;
4178 
4179 	if (sn != NULL) {
4180 		s->src_node = sn;
4181 		s->src_node->states++;
4182 	}
4183 	if (nsn != NULL) {
4184 		/* XXX We only modify one side for now. */
4185 		PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
4186 		s->nat_src_node = nsn;
4187 		s->nat_src_node->states++;
4188 	}
4189 	if (pd->proto == IPPROTO_TCP) {
4190 		if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
4191 		    off, pd, th, &s->src, &s->dst)) {
4192 			REASON_SET(&reason, PFRES_MEMORY);
4193 			pf_src_tree_remove_state(s);
4194 			STATE_DEC_COUNTERS(s);
4195 			kfree(s, M_PFSTATEPL);
4196 			return (PF_DROP);
4197 		}
4198 		if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
4199 		    pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
4200 		    &s->src, &s->dst, rewrite)) {
4201 			/* This really shouldn't happen!!! */
4202 			DPFPRINTF(PF_DEBUG_URGENT,
4203 			    ("pf_normalize_tcp_stateful failed on first pkt"));
4204 			pf_normalize_tcp_cleanup(s);
4205 			pf_src_tree_remove_state(s);
4206 			STATE_DEC_COUNTERS(s);
4207 			kfree(s, M_PFSTATEPL);
4208 			return (PF_DROP);
4209 		}
4210 	}
4211 	s->direction = pd->dir;
4212 
4213 	if (sk == NULL && pf_state_key_setup(pd, nr, &skw, &sks, &sk, &nk,
4214 					     pd->src, pd->dst, sport, dport)) {
4215 		REASON_SET(&reason, PFRES_MEMORY);
4216 		goto csfailed;
4217 	}
4218 
4219 	if (pf_state_insert(BOUND_IFACE(r, kif), skw, sks, s)) {
4220 		if (pd->proto == IPPROTO_TCP)
4221 			pf_normalize_tcp_cleanup(s);
4222 		REASON_SET(&reason, PFRES_STATEINS);
4223 		pf_src_tree_remove_state(s);
4224 		STATE_DEC_COUNTERS(s);
4225 		kfree(s, M_PFSTATEPL);
4226 		return (PF_DROP);
4227 	} else
4228 		*sm = s;
4229 
4230 	pf_set_rt_ifp(s, pd->src);	/* needs s->state_key set */
4231 	if (tag > 0) {
4232 		pf_tag_ref(tag);
4233 		s->tag = tag;
4234 	}
4235 	if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
4236 	    TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
4237 		s->src.state = PF_TCPS_PROXY_SRC;
4238 		/* undo NAT changes, if they have taken place */
4239 		if (nr != NULL) {
4240 			struct pf_state_key *skt = s->key[PF_SK_WIRE];
4241 			if (pd->dir == PF_OUT)
4242 				skt = s->key[PF_SK_STACK];
4243 			PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
4244 			PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
4245 			if (pd->sport)
4246 				*pd->sport = skt->port[pd->sidx];
4247 			if (pd->dport)
4248 				*pd->dport = skt->port[pd->didx];
4249 			if (pd->proto_sum)
4250 				*pd->proto_sum = bproto_sum;
4251 			if (pd->ip_sum)
4252 				*pd->ip_sum = bip_sum;
4253 			m->m_flags &= ~M_HASH;
4254 			m_copyback(m, off, hdrlen, pd->hdr.any);
4255 		}
4256 		s->src.seqhi = htonl(karc4random());
4257 		/* Find mss option */
4258 		mss = pf_get_mss(m, off, th->th_off, pd->af);
4259 		mss = pf_calc_mss(pd->src, pd->af, mss);
4260 		mss = pf_calc_mss(pd->dst, pd->af, mss);
4261 		s->src.mss = mss;
4262 		s->state_flags &= ~PFSTATE_CREATEINPROG;
4263 		pf_send_tcp(r, pd->af, pd->dst, pd->src, th->th_dport,
4264 			    th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
4265 			    TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL, NULL);
4266 		REASON_SET(&reason, PFRES_SYNPROXY);
4267 		return (PF_SYNPROXY_DROP);
4268 	}
4269 
4270 	s->state_flags &= ~PFSTATE_CREATEINPROG;
4271 	return (PF_PASS);
4272 
4273 csfailed:
4274 	if (sk != NULL)
4275 		kfree(sk, M_PFSTATEKEYPL);
4276 	if (nk != NULL)
4277 		kfree(nk, M_PFSTATEKEYPL);
4278 
4279 	if (sn != NULL && sn->states == 0 && sn->expire == 0) {
4280 		RB_REMOVE(pf_src_tree, &tree_src_tracking[cpu], sn);
4281 		pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
4282 		atomic_add_int(&pf_status.src_nodes, -1);
4283 		kfree(sn, M_PFSRCTREEPL);
4284 	}
4285 	if (nsn != sn && nsn != NULL && nsn->states == 0 && nsn->expire == 0) {
4286 		RB_REMOVE(pf_src_tree, &tree_src_tracking[cpu], nsn);
4287 		pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
4288 		atomic_add_int(&pf_status.src_nodes, -1);
4289 		kfree(nsn, M_PFSRCTREEPL);
4290 	}
4291 	if (s) {
4292 		pf_src_tree_remove_state(s);
4293 		STATE_DEC_COUNTERS(s);
4294 		kfree(s, M_PFSTATEPL);
4295 	}
4296 
4297 	return (PF_DROP);
4298 }
4299 
4300 int
4301 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
4302     struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
4303     struct pf_ruleset **rsm)
4304 {
4305 	struct pf_rule		*r, *a = NULL;
4306 	struct pf_ruleset	*ruleset = NULL;
4307 	sa_family_t		 af = pd->af;
4308 	u_short			 reason;
4309 	int			 tag = -1;
4310 	int			 asd = 0;
4311 	int			 match = 0;
4312 
4313 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
4314 	while (r != NULL) {
4315 		r->evaluations++;
4316 		if (pfi_kif_match(r->kif, kif) == r->ifnot)
4317 			r = r->skip[PF_SKIP_IFP].ptr;
4318 		else if (r->direction && r->direction != direction)
4319 			r = r->skip[PF_SKIP_DIR].ptr;
4320 		else if (r->af && r->af != af)
4321 			r = r->skip[PF_SKIP_AF].ptr;
4322 		else if (r->proto && r->proto != pd->proto)
4323 			r = r->skip[PF_SKIP_PROTO].ptr;
4324 		else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
4325 		    r->src.neg, kif))
4326 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
4327 		else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
4328 		    r->dst.neg, NULL))
4329 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
4330 		else if (r->tos && !(r->tos == pd->tos))
4331 			r = TAILQ_NEXT(r, entries);
4332 		else if (r->os_fingerprint != PF_OSFP_ANY)
4333 			r = TAILQ_NEXT(r, entries);
4334 		else if (pd->proto == IPPROTO_UDP &&
4335 		    (r->src.port_op || r->dst.port_op))
4336 			r = TAILQ_NEXT(r, entries);
4337 		else if (pd->proto == IPPROTO_TCP &&
4338 		    (r->src.port_op || r->dst.port_op || r->flagset))
4339 			r = TAILQ_NEXT(r, entries);
4340 		else if ((pd->proto == IPPROTO_ICMP ||
4341 		    pd->proto == IPPROTO_ICMPV6) &&
4342 		    (r->type || r->code))
4343 			r = TAILQ_NEXT(r, entries);
4344 		else if (r->prob && r->prob <= karc4random())
4345 			r = TAILQ_NEXT(r, entries);
4346 		else if (r->match_tag && !pf_match_tag(m, r, &tag))
4347 			r = TAILQ_NEXT(r, entries);
4348 		else {
4349 			if (r->anchor == NULL) {
4350 				match = 1;
4351 				*rm = r;
4352 				*am = a;
4353 				*rsm = ruleset;
4354 				if ((*rm)->quick)
4355 					break;
4356 				r = TAILQ_NEXT(r, entries);
4357 			} else
4358 				pf_step_into_anchor(&asd, &ruleset,
4359 				    PF_RULESET_FILTER, &r, &a, &match);
4360 		}
4361 		if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
4362 		    PF_RULESET_FILTER, &r, &a, &match))
4363 			break;
4364 	}
4365 	r = *rm;
4366 	a = *am;
4367 	ruleset = *rsm;
4368 
4369 	REASON_SET(&reason, PFRES_MATCH);
4370 
4371 	if (r->log)
4372 		PFLOG_PACKET(kif, h, m, af, direction, reason, r, a, ruleset,
4373 		    pd);
4374 
4375 	if (r->action != PF_PASS)
4376 		return (PF_DROP);
4377 
4378 	if (pf_tag_packet(m, tag, -1)) {
4379 		REASON_SET(&reason, PFRES_MEMORY);
4380 		return (PF_DROP);
4381 	}
4382 
4383 	return (PF_PASS);
4384 }
4385 
4386 /*
4387  * Called with state locked
4388  */
4389 int
4390 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
4391 	struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
4392 	struct pf_pdesc *pd, u_short *reason, int *copyback)
4393 {
4394 	struct tcphdr		*th = pd->hdr.tcp;
4395 	u_int16_t		 win = ntohs(th->th_win);
4396 	u_int32_t		 ack, end, seq, orig_seq;
4397 	u_int8_t		 sws, dws;
4398 	int			 ackskew;
4399 
4400 	if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
4401 		sws = src->wscale & PF_WSCALE_MASK;
4402 		dws = dst->wscale & PF_WSCALE_MASK;
4403 	} else {
4404 		sws = dws = 0;
4405 	}
4406 
4407 	/*
4408 	 * Sequence tracking algorithm from Guido van Rooij's paper:
4409 	 *   http://www.madison-gurkha.com/publications/tcp_filtering/
4410 	 *	tcp_filtering.ps
4411 	 */
4412 
4413 	orig_seq = seq = ntohl(th->th_seq);
4414 	if (src->seqlo == 0) {
4415 		/* First packet from this end. Set its state */
4416 
4417 		if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
4418 		    src->scrub == NULL) {
4419 			if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
4420 				REASON_SET(reason, PFRES_MEMORY);
4421 				return (PF_DROP);
4422 			}
4423 		}
4424 
4425 		/* Deferred generation of sequence number modulator */
4426 		if (dst->seqdiff && !src->seqdiff) {
4427 			/* use random iss for the TCP server */
4428 			while ((src->seqdiff = karc4random() - seq) == 0)
4429 				;
4430 			ack = ntohl(th->th_ack) - dst->seqdiff;
4431 			pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
4432 			    src->seqdiff), 0);
4433 			pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
4434 			*copyback = 1;
4435 		} else {
4436 			ack = ntohl(th->th_ack);
4437 		}
4438 
4439 		end = seq + pd->p_len;
4440 		if (th->th_flags & TH_SYN) {
4441 			end++;
4442 			(*state)->sync_flags |= PFSTATE_GOT_SYN2;
4443 			if (dst->wscale & PF_WSCALE_FLAG) {
4444 				src->wscale = pf_get_wscale(m, off, th->th_off,
4445 				    pd->af);
4446 				if (src->wscale & PF_WSCALE_FLAG) {
4447 					/* Remove scale factor from initial
4448 					 * window */
4449 					sws = src->wscale & PF_WSCALE_MASK;
4450 					win = ((u_int32_t)win + (1 << sws) - 1)
4451 					    >> sws;
4452 					dws = dst->wscale & PF_WSCALE_MASK;
4453 				} else {
4454 					/* fixup other window */
4455 					dst->max_win <<= dst->wscale &
4456 					    PF_WSCALE_MASK;
4457 					/* in case of a retrans SYN|ACK */
4458 					dst->wscale = 0;
4459 				}
4460 			}
4461 		}
4462 		if (th->th_flags & TH_FIN)
4463 			end++;
4464 
4465 		src->seqlo = seq;
4466 		if (src->state < TCPS_SYN_SENT)
4467 			src->state = TCPS_SYN_SENT;
4468 
4469 		/*
4470 		 * May need to slide the window (seqhi may have been set by
4471 		 * the crappy stack check or if we picked up the connection
4472 		 * after establishment)
4473 		 */
4474 		if (src->seqhi == 1 ||
4475 		    SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
4476 			src->seqhi = end + MAX(1, dst->max_win << dws);
4477 		if (win > src->max_win)
4478 			src->max_win = win;
4479 
4480 	} else {
4481 		ack = ntohl(th->th_ack) - dst->seqdiff;
4482 		if (src->seqdiff) {
4483 			/* Modulate sequence numbers */
4484 			pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
4485 			    src->seqdiff), 0);
4486 			pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
4487 			*copyback = 1;
4488 		}
4489 		end = seq + pd->p_len;
4490 		if (th->th_flags & TH_SYN)
4491 			end++;
4492 		if (th->th_flags & TH_FIN)
4493 			end++;
4494 	}
4495 
4496 	if ((th->th_flags & TH_ACK) == 0) {
4497 		/* Let it pass through the ack skew check */
4498 		ack = dst->seqlo;
4499 	} else if ((ack == 0 &&
4500 	    (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4501 	    /* broken tcp stacks do not set ack */
4502 	    (dst->state < TCPS_SYN_SENT)) {
4503 		/*
4504 		 * Many stacks (ours included) will set the ACK number in an
4505 		 * FIN|ACK if the SYN times out -- no sequence to ACK.
4506 		 */
4507 		ack = dst->seqlo;
4508 	}
4509 
4510 	if (seq == end) {
4511 		/* Ease sequencing restrictions on no data packets */
4512 		seq = src->seqlo;
4513 		end = seq;
4514 	}
4515 
4516 	ackskew = dst->seqlo - ack;
4517 
4518 
4519 	/*
4520 	 * Need to demodulate the sequence numbers in any TCP SACK options
4521 	 * (Selective ACK). We could optionally validate the SACK values
4522 	 * against the current ACK window, either forwards or backwards, but
4523 	 * I'm not confident that SACK has been implemented properly
4524 	 * everywhere. It wouldn't surprise me if several stacks accidently
4525 	 * SACK too far backwards of previously ACKed data. There really aren't
4526 	 * any security implications of bad SACKing unless the target stack
4527 	 * doesn't validate the option length correctly. Someone trying to
4528 	 * spoof into a TCP connection won't bother blindly sending SACK
4529 	 * options anyway.
4530 	 */
4531 	if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4532 		if (pf_modulate_sack(m, off, pd, th, dst))
4533 			*copyback = 1;
4534 	}
4535 
4536 
4537 #define MAXACKWINDOW (0xffff + 1500)	/* 1500 is an arbitrary fudge factor */
4538 	if (SEQ_GEQ(src->seqhi, end) &&
4539 	    /* Last octet inside other's window space */
4540 	    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4541 	    /* Retrans: not more than one window back */
4542 	    (ackskew >= -MAXACKWINDOW) &&
4543 	    /* Acking not more than one reassembled fragment backwards */
4544 	    (ackskew <= (MAXACKWINDOW << sws)) &&
4545 	    /* Acking not more than one window forward */
4546 	    ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4547 	    (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4548 	    (pd->flags & PFDESC_IP_REAS) == 0)) {
4549 	    /* Require an exact/+1 sequence match on resets when possible */
4550 
4551 		if (dst->scrub || src->scrub) {
4552 			if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4553 			    *state, src, dst, copyback))
4554 				return (PF_DROP);
4555 		}
4556 
4557 		/* update max window */
4558 		if (src->max_win < win)
4559 			src->max_win = win;
4560 		/* synchronize sequencing */
4561 		if (SEQ_GT(end, src->seqlo))
4562 			src->seqlo = end;
4563 		/* slide the window of what the other end can send */
4564 		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4565 			dst->seqhi = ack + MAX((win << sws), 1);
4566 
4567 
4568 		/* update states */
4569 		if (th->th_flags & TH_SYN)
4570 			if (src->state < TCPS_SYN_SENT)
4571 				src->state = TCPS_SYN_SENT;
4572 		if (th->th_flags & TH_FIN)
4573 			if (src->state < TCPS_CLOSING)
4574 				src->state = TCPS_CLOSING;
4575 		if (th->th_flags & TH_ACK) {
4576 			if (dst->state == TCPS_SYN_SENT) {
4577 				dst->state = TCPS_ESTABLISHED;
4578 				if (src->state == TCPS_ESTABLISHED &&
4579 				    (*state)->src_node != NULL &&
4580 				    pf_src_connlimit(*state)) {
4581 					REASON_SET(reason, PFRES_SRCLIMIT);
4582 					return (PF_DROP);
4583 				}
4584 			} else if (dst->state == TCPS_CLOSING)
4585 				dst->state = TCPS_FIN_WAIT_2;
4586 		}
4587 		if (th->th_flags & TH_RST)
4588 			src->state = dst->state = TCPS_TIME_WAIT;
4589 
4590 		/* update expire time */
4591 		(*state)->expire = time_second;
4592 		if (src->state >= TCPS_FIN_WAIT_2 &&
4593 		    dst->state >= TCPS_FIN_WAIT_2)
4594 			(*state)->timeout = PFTM_TCP_CLOSED;
4595 		else if (src->state >= TCPS_CLOSING &&
4596 		    dst->state >= TCPS_CLOSING)
4597 			(*state)->timeout = PFTM_TCP_FIN_WAIT;
4598 		else if (src->state < TCPS_ESTABLISHED ||
4599 		    dst->state < TCPS_ESTABLISHED)
4600 			(*state)->timeout = PFTM_TCP_OPENING;
4601 		else if (src->state >= TCPS_CLOSING ||
4602 		    dst->state >= TCPS_CLOSING)
4603 			(*state)->timeout = PFTM_TCP_CLOSING;
4604 		else
4605 			(*state)->timeout = PFTM_TCP_ESTABLISHED;
4606 
4607 		/* Fall through to PASS packet */
4608 
4609 	} else if ((dst->state < TCPS_SYN_SENT ||
4610 		dst->state >= TCPS_FIN_WAIT_2 ||
4611 		src->state >= TCPS_FIN_WAIT_2) &&
4612 	    SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4613 	    /* Within a window forward of the originating packet */
4614 	    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4615 	    /* Within a window backward of the originating packet */
4616 
4617 		/*
4618 		 * This currently handles three situations:
4619 		 *  1) Stupid stacks will shotgun SYNs before their peer
4620 		 *     replies.
4621 		 *  2) When PF catches an already established stream (the
4622 		 *     firewall rebooted, the state table was flushed, routes
4623 		 *     changed...)
4624 		 *  3) Packets get funky immediately after the connection
4625 		 *     closes (this should catch Solaris spurious ACK|FINs
4626 		 *     that web servers like to spew after a close)
4627 		 *
4628 		 * This must be a little more careful than the above code
4629 		 * since packet floods will also be caught here. We don't
4630 		 * update the TTL here to mitigate the damage of a packet
4631 		 * flood and so the same code can handle awkward establishment
4632 		 * and a loosened connection close.
4633 		 * In the establishment case, a correct peer response will
4634 		 * validate the connection, go through the normal state code
4635 		 * and keep updating the state TTL.
4636 		 */
4637 
4638 		if (pf_status.debug >= PF_DEBUG_MISC) {
4639 			kprintf("pf: loose state match: ");
4640 			pf_print_state(*state);
4641 			pf_print_flags(th->th_flags);
4642 			kprintf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4643 			    "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack, pd->p_len,
4644 			    ackskew, (unsigned long long)(*state)->packets[0],
4645 			    (unsigned long long)(*state)->packets[1],
4646 			    pd->dir == PF_IN ? "in" : "out",
4647 			    pd->dir == (*state)->direction ? "fwd" : "rev");
4648 		}
4649 
4650 		if (dst->scrub || src->scrub) {
4651 			if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4652 			    *state, src, dst, copyback))
4653 				return (PF_DROP);
4654 		}
4655 
4656 		/* update max window */
4657 		if (src->max_win < win)
4658 			src->max_win = win;
4659 		/* synchronize sequencing */
4660 		if (SEQ_GT(end, src->seqlo))
4661 			src->seqlo = end;
4662 		/* slide the window of what the other end can send */
4663 		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4664 			dst->seqhi = ack + MAX((win << sws), 1);
4665 
4666 		/*
4667 		 * Cannot set dst->seqhi here since this could be a shotgunned
4668 		 * SYN and not an already established connection.
4669 		 */
4670 
4671 		if (th->th_flags & TH_FIN)
4672 			if (src->state < TCPS_CLOSING)
4673 				src->state = TCPS_CLOSING;
4674 		if (th->th_flags & TH_RST)
4675 			src->state = dst->state = TCPS_TIME_WAIT;
4676 
4677 		/* Fall through to PASS packet */
4678 
4679 	} else if ((*state)->pickup_mode == PF_PICKUPS_HASHONLY ||
4680 		    ((*state)->pickup_mode == PF_PICKUPS_ENABLED &&
4681 		     ((*state)->sync_flags & PFSTATE_GOT_SYN_MASK) !=
4682 		      PFSTATE_GOT_SYN_MASK)) {
4683 		/*
4684 		 * If pickup mode is hash only, do not fail on sequence checks.
4685 		 *
4686 		 * If pickup mode is enabled and we did not see the SYN in
4687 		 * both direction, do not fail on sequence checks because
4688 		 * we do not have complete information on window scale.
4689 		 *
4690 		 * Adjust expiration and fall through to PASS packet.
4691 		 * XXX Add a FIN check to reduce timeout?
4692 		 */
4693 		(*state)->expire = time_second;
4694 	} else  {
4695 		/*
4696 		 * Failure processing
4697 		 */
4698 		if ((*state)->dst.state == TCPS_SYN_SENT &&
4699 		    (*state)->src.state == TCPS_SYN_SENT) {
4700 			/* Send RST for state mismatches during handshake */
4701 			if (!(th->th_flags & TH_RST))
4702 				pf_send_tcp((*state)->rule.ptr, pd->af,
4703 				    pd->dst, pd->src, th->th_dport,
4704 				    th->th_sport, ntohl(th->th_ack), 0,
4705 				    TH_RST, 0, 0,
4706 				    (*state)->rule.ptr->return_ttl, 1, 0,
4707 				    pd->eh, kif->pfik_ifp);
4708 			src->seqlo = 0;
4709 			src->seqhi = 1;
4710 			src->max_win = 1;
4711 		} else if (pf_status.debug >= PF_DEBUG_MISC) {
4712 			kprintf("pf: BAD state: ");
4713 			pf_print_state(*state);
4714 			pf_print_flags(th->th_flags);
4715 			kprintf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4716 			    "pkts=%llu:%llu dir=%s,%s\n",
4717 			    seq, orig_seq, ack, pd->p_len, ackskew,
4718 			    (unsigned long long)(*state)->packets[0],
4719 				(unsigned long long)(*state)->packets[1],
4720 			    pd->dir == PF_IN ? "in" : "out",
4721 			    pd->dir == (*state)->direction ? "fwd" : "rev");
4722 			kprintf("pf: State failure on: %c %c %c %c | %c %c\n",
4723 			    SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4724 			    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4725 			    ' ': '2',
4726 			    (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4727 			    (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4728 			    SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4729 			    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4730 		}
4731 		REASON_SET(reason, PFRES_BADSTATE);
4732 		return (PF_DROP);
4733 	}
4734 
4735 	return (PF_PASS);
4736 }
4737 
4738 /*
4739  * Called with state locked
4740  */
4741 int
4742 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4743 	struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4744 {
4745 	struct tcphdr		*th = pd->hdr.tcp;
4746 
4747 	if (th->th_flags & TH_SYN)
4748 		if (src->state < TCPS_SYN_SENT)
4749 			src->state = TCPS_SYN_SENT;
4750 	if (th->th_flags & TH_FIN)
4751 		if (src->state < TCPS_CLOSING)
4752 			src->state = TCPS_CLOSING;
4753 	if (th->th_flags & TH_ACK) {
4754 		if (dst->state == TCPS_SYN_SENT) {
4755 			dst->state = TCPS_ESTABLISHED;
4756 			if (src->state == TCPS_ESTABLISHED &&
4757 			    (*state)->src_node != NULL &&
4758 			    pf_src_connlimit(*state)) {
4759 				REASON_SET(reason, PFRES_SRCLIMIT);
4760 				return (PF_DROP);
4761 			}
4762 		} else if (dst->state == TCPS_CLOSING) {
4763 			dst->state = TCPS_FIN_WAIT_2;
4764 		} else if (src->state == TCPS_SYN_SENT &&
4765 		    dst->state < TCPS_SYN_SENT) {
4766 			/*
4767 			 * Handle a special sloppy case where we only see one
4768 			 * half of the connection. If there is a ACK after
4769 			 * the initial SYN without ever seeing a packet from
4770 			 * the destination, set the connection to established.
4771 			 */
4772 			dst->state = src->state = TCPS_ESTABLISHED;
4773 			if ((*state)->src_node != NULL &&
4774 			    pf_src_connlimit(*state)) {
4775 				REASON_SET(reason, PFRES_SRCLIMIT);
4776 				return (PF_DROP);
4777 			}
4778 		} else if (src->state == TCPS_CLOSING &&
4779 		    dst->state == TCPS_ESTABLISHED &&
4780 		    dst->seqlo == 0) {
4781 			/*
4782 			 * Handle the closing of half connections where we
4783 			 * don't see the full bidirectional FIN/ACK+ACK
4784 			 * handshake.
4785 			 */
4786 			dst->state = TCPS_CLOSING;
4787 		}
4788 	}
4789 	if (th->th_flags & TH_RST)
4790 		src->state = dst->state = TCPS_TIME_WAIT;
4791 
4792 	/* update expire time */
4793 	(*state)->expire = time_second;
4794 	if (src->state >= TCPS_FIN_WAIT_2 &&
4795 	    dst->state >= TCPS_FIN_WAIT_2)
4796 		(*state)->timeout = PFTM_TCP_CLOSED;
4797 	else if (src->state >= TCPS_CLOSING &&
4798 	    dst->state >= TCPS_CLOSING)
4799 		(*state)->timeout = PFTM_TCP_FIN_WAIT;
4800 	else if (src->state < TCPS_ESTABLISHED ||
4801 	    dst->state < TCPS_ESTABLISHED)
4802 		(*state)->timeout = PFTM_TCP_OPENING;
4803 	else if (src->state >= TCPS_CLOSING ||
4804 	    dst->state >= TCPS_CLOSING)
4805 		(*state)->timeout = PFTM_TCP_CLOSING;
4806 	else
4807 		(*state)->timeout = PFTM_TCP_ESTABLISHED;
4808 
4809 	return (PF_PASS);
4810 }
4811 
4812 /*
4813  * Test TCP connection state.  Caller must hold the state locked.
4814  */
4815 int
4816 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4817 		  struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4818 		  u_short *reason)
4819 {
4820 	struct pf_state_key_cmp	 key;
4821 	struct tcphdr		*th = pd->hdr.tcp;
4822 	int			 copyback = 0;
4823 	int			 error;
4824 	struct pf_state_peer	*src, *dst;
4825 	struct pf_state_key	*sk;
4826 
4827 	bzero(&key, sizeof(key));
4828 	key.af = pd->af;
4829 	key.proto = IPPROTO_TCP;
4830 	if (direction == PF_IN)	{	/* wire side, straight */
4831 		PF_ACPY(&key.addr[0], pd->src, key.af);
4832 		PF_ACPY(&key.addr[1], pd->dst, key.af);
4833 		key.port[0] = th->th_sport;
4834 		key.port[1] = th->th_dport;
4835 		if (pf_status.debug >= PF_DEBUG_MISC) {
4836 			kprintf("test-tcp IN (%08x:%d) -> (%08x:%d)\n",
4837 				ntohl(key.addr[0].addr32[0]),
4838 				ntohs(key.port[0]),
4839 				ntohl(key.addr[1].addr32[0]),
4840 				ntohs(key.port[1]));
4841 		}
4842 	} else {			/* stack side, reverse */
4843 		PF_ACPY(&key.addr[1], pd->src, key.af);
4844 		PF_ACPY(&key.addr[0], pd->dst, key.af);
4845 		key.port[1] = th->th_sport;
4846 		key.port[0] = th->th_dport;
4847 		if (pf_status.debug >= PF_DEBUG_MISC) {
4848 			kprintf("test-tcp OUT (%08x:%d) <- (%08x:%d)\n",
4849 				ntohl(key.addr[0].addr32[0]),
4850 				ntohs(key.port[0]),
4851 				ntohl(key.addr[1].addr32[0]),
4852 				ntohs(key.port[1]));
4853 		}
4854 	}
4855 
4856 	STATE_LOOKUP(kif, &key, direction, *state, m);
4857 	lockmgr(&(*state)->lk, LK_EXCLUSIVE);
4858 
4859 	if (direction == (*state)->direction) {
4860 		src = &(*state)->src;
4861 		dst = &(*state)->dst;
4862 	} else {
4863 		src = &(*state)->dst;
4864 		dst = &(*state)->src;
4865 	}
4866 
4867 	sk = (*state)->key[pd->didx];
4868 
4869 	if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4870 		if (direction != (*state)->direction) {
4871 			REASON_SET(reason, PFRES_SYNPROXY);
4872 			FAIL (PF_SYNPROXY_DROP);
4873 		}
4874 		if (th->th_flags & TH_SYN) {
4875 			if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4876 				REASON_SET(reason, PFRES_SYNPROXY);
4877 				FAIL (PF_DROP);
4878 			}
4879 			pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
4880 			    pd->src, th->th_dport, th->th_sport,
4881 			    (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4882 			    TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1,
4883 			    0, NULL, NULL);
4884 			REASON_SET(reason, PFRES_SYNPROXY);
4885 			FAIL (PF_SYNPROXY_DROP);
4886 		} else if (!(th->th_flags & TH_ACK) ||
4887 		    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4888 		    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4889 			REASON_SET(reason, PFRES_SYNPROXY);
4890 			FAIL (PF_DROP);
4891 		} else if ((*state)->src_node != NULL &&
4892 		    pf_src_connlimit(*state)) {
4893 			REASON_SET(reason, PFRES_SRCLIMIT);
4894 			FAIL (PF_DROP);
4895 		} else
4896 			(*state)->src.state = PF_TCPS_PROXY_DST;
4897 	}
4898 	if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4899 		if (direction == (*state)->direction) {
4900 			if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4901 			    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4902 			    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4903 				REASON_SET(reason, PFRES_SYNPROXY);
4904 				FAIL (PF_DROP);
4905 			}
4906 			(*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4907 			if ((*state)->dst.seqhi == 1)
4908 				(*state)->dst.seqhi = htonl(karc4random());
4909 			pf_send_tcp((*state)->rule.ptr, pd->af,
4910 			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
4911 			    sk->port[pd->sidx], sk->port[pd->didx],
4912 			    (*state)->dst.seqhi, 0, TH_SYN, 0,
4913 			    (*state)->src.mss, 0, 0, (*state)->tag, NULL, NULL);
4914 			REASON_SET(reason, PFRES_SYNPROXY);
4915 			FAIL (PF_SYNPROXY_DROP);
4916 		} else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4917 		    (TH_SYN|TH_ACK)) ||
4918 		    (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4919 			REASON_SET(reason, PFRES_SYNPROXY);
4920 			FAIL (PF_DROP);
4921 		} else {
4922 			(*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4923 			(*state)->dst.seqlo = ntohl(th->th_seq);
4924 			pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
4925 			    pd->src, th->th_dport, th->th_sport,
4926 			    ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4927 			    TH_ACK, (*state)->src.max_win, 0, 0, 0,
4928 			    (*state)->tag, NULL, NULL);
4929 			pf_send_tcp((*state)->rule.ptr, pd->af,
4930 			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
4931 			    sk->port[pd->sidx], sk->port[pd->didx],
4932 			    (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4933 			    TH_ACK, (*state)->dst.max_win, 0, 0, 1,
4934 			    0, NULL, NULL);
4935 			(*state)->src.seqdiff = (*state)->dst.seqhi -
4936 			    (*state)->src.seqlo;
4937 			(*state)->dst.seqdiff = (*state)->src.seqhi -
4938 			    (*state)->dst.seqlo;
4939 			(*state)->src.seqhi = (*state)->src.seqlo +
4940 			    (*state)->dst.max_win;
4941 			(*state)->dst.seqhi = (*state)->dst.seqlo +
4942 			    (*state)->src.max_win;
4943 			(*state)->src.wscale = (*state)->dst.wscale = 0;
4944 			(*state)->src.state = (*state)->dst.state =
4945 			    TCPS_ESTABLISHED;
4946 			REASON_SET(reason, PFRES_SYNPROXY);
4947 			FAIL (PF_SYNPROXY_DROP);
4948 		}
4949 	}
4950 
4951 	/*
4952 	 * Check for connection (addr+port pair) reuse.  We can't actually
4953 	 * unlink the state if we don't own it.
4954 	 */
4955 	if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4956 	    dst->state >= TCPS_FIN_WAIT_2 &&
4957 	    src->state >= TCPS_FIN_WAIT_2) {
4958 		if (pf_status.debug >= PF_DEBUG_MISC) {
4959 			kprintf("pf: state reuse ");
4960 			pf_print_state(*state);
4961 			pf_print_flags(th->th_flags);
4962 			kprintf("\n");
4963 		}
4964 		/* XXX make sure it's the same direction ?? */
4965 		(*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4966 		if ((*state)->cpuid == mycpu->gd_cpuid) {
4967 			pf_unlink_state(*state);
4968 			*state = NULL;
4969 		} else {
4970 			(*state)->timeout = PFTM_PURGE;
4971 		}
4972 		FAIL (PF_DROP);
4973 	}
4974 
4975 	if ((*state)->state_flags & PFSTATE_SLOPPY) {
4976 		if (pf_tcp_track_sloppy(src, dst, state, pd,
4977 					reason) == PF_DROP) {
4978 			FAIL (PF_DROP);
4979 		}
4980 	} else {
4981 		if (pf_tcp_track_full(src, dst, state, kif, m, off, pd,
4982 				      reason, &copyback) == PF_DROP) {
4983 			FAIL (PF_DROP);
4984 		}
4985 	}
4986 
4987 	/* translate source/destination address, if necessary */
4988 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4989 		struct pf_state_key *nk = (*state)->key[pd->didx];
4990 
4991 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4992 		    nk->port[pd->sidx] != th->th_sport)  {
4993 			/*
4994 			 * The translated source address may be completely
4995 			 * unrelated to the saved link header, make sure
4996 			 * a bridge doesn't try to use it.
4997 			 */
4998 			m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
4999 			pf_change_ap(pd->src, &th->th_sport, pd->ip_sum,
5000 			    &th->th_sum, &nk->addr[pd->sidx],
5001 			    nk->port[pd->sidx], 0, pd->af);
5002 		}
5003 
5004 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
5005 		    nk->port[pd->didx] != th->th_dport) {
5006 			/*
5007 			 * If we don't redispatch the packet will go into
5008 			 * the protocol stack on the wrong cpu for the
5009 			 * post-translated address.
5010 			 */
5011 			pf_change_ap(pd->dst, &th->th_dport, pd->ip_sum,
5012 			    &th->th_sum, &nk->addr[pd->didx],
5013 			    nk->port[pd->didx], 0, pd->af);
5014 		}
5015 		copyback = 1;
5016 	}
5017 
5018 	/* Copyback sequence modulation or stateful scrub changes if needed */
5019 	if (copyback) {
5020 		m->m_flags &= ~M_HASH;
5021 		m_copyback(m, off, sizeof(*th), (caddr_t)th);
5022 	}
5023 
5024 	pfsync_update_state(*state);
5025 	error = PF_PASS;
5026 done:
5027 	if (*state)
5028 		lockmgr(&(*state)->lk, LK_RELEASE);
5029 	return (error);
5030 }
5031 
5032 /*
5033  * Test UDP connection state.  Caller must hold the state locked.
5034  */
5035 int
5036 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
5037 		  struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
5038 {
5039 	struct pf_state_peer	*src, *dst;
5040 	struct pf_state_key_cmp	 key;
5041 	struct udphdr		*uh = pd->hdr.udp;
5042 
5043 	bzero(&key, sizeof(key));
5044 	key.af = pd->af;
5045 	key.proto = IPPROTO_UDP;
5046 	if (direction == PF_IN)	{	/* wire side, straight */
5047 		PF_ACPY(&key.addr[0], pd->src, key.af);
5048 		PF_ACPY(&key.addr[1], pd->dst, key.af);
5049 		key.port[0] = uh->uh_sport;
5050 		key.port[1] = uh->uh_dport;
5051 	} else {			/* stack side, reverse */
5052 		PF_ACPY(&key.addr[1], pd->src, key.af);
5053 		PF_ACPY(&key.addr[0], pd->dst, key.af);
5054 		key.port[1] = uh->uh_sport;
5055 		key.port[0] = uh->uh_dport;
5056 	}
5057 
5058 	STATE_LOOKUP(kif, &key, direction, *state, m);
5059 	lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5060 
5061 	if (direction == (*state)->direction) {
5062 		src = &(*state)->src;
5063 		dst = &(*state)->dst;
5064 	} else {
5065 		src = &(*state)->dst;
5066 		dst = &(*state)->src;
5067 	}
5068 
5069 	/* update states */
5070 	if (src->state < PFUDPS_SINGLE)
5071 		src->state = PFUDPS_SINGLE;
5072 	if (dst->state == PFUDPS_SINGLE)
5073 		dst->state = PFUDPS_MULTIPLE;
5074 
5075 	/* update expire time */
5076 	(*state)->expire = time_second;
5077 	if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
5078 		(*state)->timeout = PFTM_UDP_MULTIPLE;
5079 	else
5080 		(*state)->timeout = PFTM_UDP_SINGLE;
5081 
5082 	/* translate source/destination address, if necessary */
5083 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5084 		struct pf_state_key *nk = (*state)->key[pd->didx];
5085 
5086 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
5087 		    nk->port[pd->sidx] != uh->uh_sport) {
5088 			/*
5089 			 * The translated source address may be completely
5090 			 * unrelated to the saved link header, make sure
5091 			 * a bridge doesn't try to use it.
5092 			 */
5093 			m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
5094 			m->m_flags &= ~M_HASH;
5095 			pf_change_ap(pd->src, &uh->uh_sport, pd->ip_sum,
5096 			    &uh->uh_sum, &nk->addr[pd->sidx],
5097 			    nk->port[pd->sidx], 1, pd->af);
5098 		}
5099 
5100 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
5101 		    nk->port[pd->didx] != uh->uh_dport) {
5102 			/*
5103 			 * If we don't redispatch the packet will go into
5104 			 * the protocol stack on the wrong cpu for the
5105 			 * post-translated address.
5106 			 */
5107 			m->m_flags &= ~M_HASH;
5108 			pf_change_ap(pd->dst, &uh->uh_dport, pd->ip_sum,
5109 			    &uh->uh_sum, &nk->addr[pd->didx],
5110 			    nk->port[pd->didx], 1, pd->af);
5111 		}
5112 		m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
5113 	}
5114 
5115 	pfsync_update_state(*state);
5116 	lockmgr(&(*state)->lk, LK_RELEASE);
5117 	return (PF_PASS);
5118 }
5119 
5120 /*
5121  * Test ICMP connection state.  Caller must hold the state locked.
5122  */
5123 int
5124 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
5125 		   struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
5126 		   u_short *reason)
5127 {
5128 	struct pf_addr	*saddr = pd->src, *daddr = pd->dst;
5129 	u_int16_t	 icmpid = 0, *icmpsum = NULL;
5130 	u_int8_t	 icmptype = 0;
5131 	int		 state_icmp = 0;
5132 	int		 error;
5133 	struct pf_state_key_cmp key;
5134 
5135 	bzero(&key, sizeof(key));
5136 
5137 	switch (pd->proto) {
5138 #ifdef INET
5139 	case IPPROTO_ICMP:
5140 		icmptype = pd->hdr.icmp->icmp_type;
5141 		icmpid = pd->hdr.icmp->icmp_id;
5142 		icmpsum = &pd->hdr.icmp->icmp_cksum;
5143 
5144 		if (icmptype == ICMP_UNREACH ||
5145 		    icmptype == ICMP_SOURCEQUENCH ||
5146 		    icmptype == ICMP_REDIRECT ||
5147 		    icmptype == ICMP_TIMXCEED ||
5148 		    icmptype == ICMP_PARAMPROB)
5149 			state_icmp++;
5150 		break;
5151 #endif /* INET */
5152 #ifdef INET6
5153 	case IPPROTO_ICMPV6:
5154 		icmptype = pd->hdr.icmp6->icmp6_type;
5155 		icmpid = pd->hdr.icmp6->icmp6_id;
5156 		icmpsum = &pd->hdr.icmp6->icmp6_cksum;
5157 
5158 		if (icmptype == ICMP6_DST_UNREACH ||
5159 		    icmptype == ICMP6_PACKET_TOO_BIG ||
5160 		    icmptype == ICMP6_TIME_EXCEEDED ||
5161 		    icmptype == ICMP6_PARAM_PROB)
5162 			state_icmp++;
5163 		break;
5164 #endif /* INET6 */
5165 	}
5166 
5167 	if (!state_icmp) {
5168 
5169 		/*
5170 		 * ICMP query/reply message not related to a TCP/UDP packet.
5171 		 * Search for an ICMP state.
5172 		 */
5173 		key.af = pd->af;
5174 		key.proto = pd->proto;
5175 		key.port[0] = key.port[1] = icmpid;
5176 		if (direction == PF_IN)	{	/* wire side, straight */
5177 			PF_ACPY(&key.addr[0], pd->src, key.af);
5178 			PF_ACPY(&key.addr[1], pd->dst, key.af);
5179 		} else {			/* stack side, reverse */
5180 			PF_ACPY(&key.addr[1], pd->src, key.af);
5181 			PF_ACPY(&key.addr[0], pd->dst, key.af);
5182 		}
5183 
5184 		STATE_LOOKUP(kif, &key, direction, *state, m);
5185 		lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5186 
5187 		(*state)->expire = time_second;
5188 		(*state)->timeout = PFTM_ICMP_ERROR_REPLY;
5189 
5190 		/* translate source/destination address, if necessary */
5191 		if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5192 			struct pf_state_key *nk = (*state)->key[pd->didx];
5193 
5194 			switch (pd->af) {
5195 #ifdef INET
5196 			case AF_INET:
5197 				if (PF_ANEQ(pd->src,
5198 				    &nk->addr[pd->sidx], AF_INET))
5199 					pf_change_a(&saddr->v4.s_addr,
5200 					    pd->ip_sum,
5201 					    nk->addr[pd->sidx].v4.s_addr, 0);
5202 
5203 				if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
5204 				    AF_INET))
5205 					pf_change_a(&daddr->v4.s_addr,
5206 					    pd->ip_sum,
5207 					    nk->addr[pd->didx].v4.s_addr, 0);
5208 
5209 				if (nk->port[0] !=
5210 				    pd->hdr.icmp->icmp_id) {
5211 					pd->hdr.icmp->icmp_cksum =
5212 					    pf_cksum_fixup(
5213 					    pd->hdr.icmp->icmp_cksum, icmpid,
5214 					    nk->port[pd->sidx], 0);
5215 					pd->hdr.icmp->icmp_id =
5216 					    nk->port[pd->sidx];
5217 				}
5218 
5219 				m->m_flags &= ~M_HASH;
5220 				m_copyback(m, off, ICMP_MINLEN,
5221 				    (caddr_t)pd->hdr.icmp);
5222 				break;
5223 #endif /* INET */
5224 #ifdef INET6
5225 			case AF_INET6:
5226 				if (PF_ANEQ(pd->src,
5227 				    &nk->addr[pd->sidx], AF_INET6))
5228 					pf_change_a6(saddr,
5229 					    &pd->hdr.icmp6->icmp6_cksum,
5230 					    &nk->addr[pd->sidx], 0);
5231 
5232 				if (PF_ANEQ(pd->dst,
5233 				    &nk->addr[pd->didx], AF_INET6))
5234 					pf_change_a6(daddr,
5235 					    &pd->hdr.icmp6->icmp6_cksum,
5236 					    &nk->addr[pd->didx], 0);
5237 
5238 				m->m_flags &= ~M_HASH;
5239 				m_copyback(m, off,
5240 					sizeof(struct icmp6_hdr),
5241 					(caddr_t)pd->hdr.icmp6);
5242 				break;
5243 #endif /* INET6 */
5244 			}
5245 		}
5246 	} else {
5247 		/*
5248 		 * ICMP error message in response to a TCP/UDP packet.
5249 		 * Extract the inner TCP/UDP header and search for that state.
5250 		 */
5251 
5252 		struct pf_pdesc	pd2;
5253 #ifdef INET
5254 		struct ip	h2;
5255 #endif /* INET */
5256 #ifdef INET6
5257 		struct ip6_hdr	h2_6;
5258 		int		terminal = 0;
5259 #endif /* INET6 */
5260 		int		ipoff2;
5261 		int		off2;
5262 
5263 		pd2.not_cpu_localized = 1;
5264 		pd2.af = pd->af;
5265 		/* Payload packet is from the opposite direction. */
5266 		pd2.sidx = (direction == PF_IN) ? 1 : 0;
5267 		pd2.didx = (direction == PF_IN) ? 0 : 1;
5268 		switch (pd->af) {
5269 #ifdef INET
5270 		case AF_INET:
5271 			/* offset of h2 in mbuf chain */
5272 			ipoff2 = off + ICMP_MINLEN;
5273 
5274 			if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
5275 			    NULL, reason, pd2.af)) {
5276 				DPFPRINTF(PF_DEBUG_MISC,
5277 				    ("pf: ICMP error message too short "
5278 				    "(ip)\n"));
5279 				FAIL (PF_DROP);
5280 			}
5281 			/*
5282 			 * ICMP error messages don't refer to non-first
5283 			 * fragments
5284 			 */
5285 			if (h2.ip_off & htons(IP_OFFMASK)) {
5286 				REASON_SET(reason, PFRES_FRAG);
5287 				FAIL (PF_DROP);
5288 			}
5289 
5290 			/* offset of protocol header that follows h2 */
5291 			off2 = ipoff2 + (h2.ip_hl << 2);
5292 
5293 			pd2.proto = h2.ip_p;
5294 			pd2.src = (struct pf_addr *)&h2.ip_src;
5295 			pd2.dst = (struct pf_addr *)&h2.ip_dst;
5296 			pd2.ip_sum = &h2.ip_sum;
5297 			break;
5298 #endif /* INET */
5299 #ifdef INET6
5300 		case AF_INET6:
5301 			ipoff2 = off + sizeof(struct icmp6_hdr);
5302 
5303 			if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
5304 			    NULL, reason, pd2.af)) {
5305 				DPFPRINTF(PF_DEBUG_MISC,
5306 				    ("pf: ICMP error message too short "
5307 				    "(ip6)\n"));
5308 				FAIL (PF_DROP);
5309 			}
5310 			pd2.proto = h2_6.ip6_nxt;
5311 			pd2.src = (struct pf_addr *)&h2_6.ip6_src;
5312 			pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
5313 			pd2.ip_sum = NULL;
5314 			off2 = ipoff2 + sizeof(h2_6);
5315 			do {
5316 				switch (pd2.proto) {
5317 				case IPPROTO_FRAGMENT:
5318 					/*
5319 					 * ICMPv6 error messages for
5320 					 * non-first fragments
5321 					 */
5322 					REASON_SET(reason, PFRES_FRAG);
5323 					FAIL (PF_DROP);
5324 				case IPPROTO_AH:
5325 				case IPPROTO_HOPOPTS:
5326 				case IPPROTO_ROUTING:
5327 				case IPPROTO_DSTOPTS: {
5328 					/* get next header and header length */
5329 					struct ip6_ext opt6;
5330 
5331 					if (!pf_pull_hdr(m, off2, &opt6,
5332 					    sizeof(opt6), NULL, reason,
5333 					    pd2.af)) {
5334 						DPFPRINTF(PF_DEBUG_MISC,
5335 						    ("pf: ICMPv6 short opt\n"));
5336 						FAIL (PF_DROP);
5337 					}
5338 					if (pd2.proto == IPPROTO_AH)
5339 						off2 += (opt6.ip6e_len + 2) * 4;
5340 					else
5341 						off2 += (opt6.ip6e_len + 1) * 8;
5342 					pd2.proto = opt6.ip6e_nxt;
5343 					/* goto the next header */
5344 					break;
5345 				}
5346 				default:
5347 					terminal++;
5348 					break;
5349 				}
5350 			} while (!terminal);
5351 			break;
5352 #endif /* INET6 */
5353 		default:
5354 			DPFPRINTF(PF_DEBUG_MISC,
5355 			    ("pf: ICMP AF %d unknown (ip6)\n", pd->af));
5356 			FAIL (PF_DROP);
5357 			break;
5358 		}
5359 
5360 		switch (pd2.proto) {
5361 		case IPPROTO_TCP: {
5362 			struct tcphdr		 th;
5363 			u_int32_t		 seq;
5364 			struct pf_state_peer	*src, *dst;
5365 			u_int8_t		 dws;
5366 			int			 copyback = 0;
5367 
5368 			/*
5369 			 * Only the first 8 bytes of the TCP header can be
5370 			 * expected. Don't access any TCP header fields after
5371 			 * th_seq, an ackskew test is not possible.
5372 			 */
5373 			if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
5374 			    pd2.af)) {
5375 				DPFPRINTF(PF_DEBUG_MISC,
5376 				    ("pf: ICMP error message too short "
5377 				    "(tcp)\n"));
5378 				FAIL (PF_DROP);
5379 			}
5380 
5381 			key.af = pd2.af;
5382 			key.proto = IPPROTO_TCP;
5383 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5384 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5385 			key.port[pd2.sidx] = th.th_sport;
5386 			key.port[pd2.didx] = th.th_dport;
5387 
5388 			STATE_LOOKUP(kif, &key, direction, *state, m);
5389 			lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5390 
5391 			if (direction == (*state)->direction) {
5392 				src = &(*state)->dst;
5393 				dst = &(*state)->src;
5394 			} else {
5395 				src = &(*state)->src;
5396 				dst = &(*state)->dst;
5397 			}
5398 
5399 			if (src->wscale && dst->wscale)
5400 				dws = dst->wscale & PF_WSCALE_MASK;
5401 			else
5402 				dws = 0;
5403 
5404 			/* Demodulate sequence number */
5405 			seq = ntohl(th.th_seq) - src->seqdiff;
5406 			if (src->seqdiff) {
5407 				pf_change_a(&th.th_seq, icmpsum,
5408 				    htonl(seq), 0);
5409 				copyback = 1;
5410 			}
5411 
5412 			if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
5413 			    (!SEQ_GEQ(src->seqhi, seq) ||
5414 			    !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
5415 				if (pf_status.debug >= PF_DEBUG_MISC) {
5416 					kprintf("pf: BAD ICMP %d:%d ",
5417 					    icmptype, pd->hdr.icmp->icmp_code);
5418 					pf_print_host(pd->src, 0, pd->af);
5419 					kprintf(" -> ");
5420 					pf_print_host(pd->dst, 0, pd->af);
5421 					kprintf(" state: ");
5422 					pf_print_state(*state);
5423 					kprintf(" seq=%u\n", seq);
5424 				}
5425 				REASON_SET(reason, PFRES_BADSTATE);
5426 				FAIL (PF_DROP);
5427 			} else {
5428 				if (pf_status.debug >= PF_DEBUG_MISC) {
5429 					kprintf("pf: OK ICMP %d:%d ",
5430 					    icmptype, pd->hdr.icmp->icmp_code);
5431 					pf_print_host(pd->src, 0, pd->af);
5432 					kprintf(" -> ");
5433 					pf_print_host(pd->dst, 0, pd->af);
5434 					kprintf(" state: ");
5435 					pf_print_state(*state);
5436 					kprintf(" seq=%u\n", seq);
5437 				}
5438 			}
5439 
5440 			/* translate source/destination address, if necessary */
5441 			if ((*state)->key[PF_SK_WIRE] !=
5442 			    (*state)->key[PF_SK_STACK]) {
5443 				struct pf_state_key *nk =
5444 				    (*state)->key[pd->didx];
5445 
5446 				if (PF_ANEQ(pd2.src,
5447 				    &nk->addr[pd2.sidx], pd2.af) ||
5448 				    nk->port[pd2.sidx] != th.th_sport)
5449 					pf_change_icmp(pd2.src, &th.th_sport,
5450 					    daddr, &nk->addr[pd2.sidx],
5451 					    nk->port[pd2.sidx], NULL,
5452 					    pd2.ip_sum, icmpsum,
5453 					    pd->ip_sum, 0, pd2.af);
5454 
5455 				if (PF_ANEQ(pd2.dst,
5456 				    &nk->addr[pd2.didx], pd2.af) ||
5457 				    nk->port[pd2.didx] != th.th_dport)
5458 					pf_change_icmp(pd2.dst, &th.th_dport,
5459 					    NULL, /* XXX Inbound NAT? */
5460 					    &nk->addr[pd2.didx],
5461 					    nk->port[pd2.didx], NULL,
5462 					    pd2.ip_sum, icmpsum,
5463 					    pd->ip_sum, 0, pd2.af);
5464 				copyback = 1;
5465 			}
5466 
5467 			if (copyback) {
5468 				switch (pd2.af) {
5469 #ifdef INET
5470 				case AF_INET:
5471 					m_copyback(m, off, ICMP_MINLEN,
5472 					    (caddr_t)pd->hdr.icmp);
5473 					m_copyback(m, ipoff2, sizeof(h2),
5474 					    (caddr_t)&h2);
5475 					break;
5476 #endif /* INET */
5477 #ifdef INET6
5478 				case AF_INET6:
5479 					m_copyback(m, off,
5480 					    sizeof(struct icmp6_hdr),
5481 					    (caddr_t)pd->hdr.icmp6);
5482 					m_copyback(m, ipoff2, sizeof(h2_6),
5483 					    (caddr_t)&h2_6);
5484 					break;
5485 #endif /* INET6 */
5486 				}
5487 				m->m_flags &= ~M_HASH;
5488 				m_copyback(m, off2, 8, (caddr_t)&th);
5489 			}
5490 			break;
5491 		}
5492 		case IPPROTO_UDP: {
5493 			struct udphdr		uh;
5494 
5495 			if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
5496 			    NULL, reason, pd2.af)) {
5497 				DPFPRINTF(PF_DEBUG_MISC,
5498 				    ("pf: ICMP error message too short "
5499 				    "(udp)\n"));
5500 				return (PF_DROP);
5501 			}
5502 
5503 			key.af = pd2.af;
5504 			key.proto = IPPROTO_UDP;
5505 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5506 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5507 			key.port[pd2.sidx] = uh.uh_sport;
5508 			key.port[pd2.didx] = uh.uh_dport;
5509 
5510 			STATE_LOOKUP(kif, &key, direction, *state, m);
5511 			lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5512 
5513 			/* translate source/destination address, if necessary */
5514 			if ((*state)->key[PF_SK_WIRE] !=
5515 			    (*state)->key[PF_SK_STACK]) {
5516 				struct pf_state_key *nk =
5517 				    (*state)->key[pd->didx];
5518 
5519 				if (PF_ANEQ(pd2.src,
5520 				    &nk->addr[pd2.sidx], pd2.af) ||
5521 				    nk->port[pd2.sidx] != uh.uh_sport)
5522 					pf_change_icmp(pd2.src, &uh.uh_sport,
5523 					    daddr, &nk->addr[pd2.sidx],
5524 					    nk->port[pd2.sidx], &uh.uh_sum,
5525 					    pd2.ip_sum, icmpsum,
5526 					    pd->ip_sum, 1, pd2.af);
5527 
5528 				if (PF_ANEQ(pd2.dst,
5529 				    &nk->addr[pd2.didx], pd2.af) ||
5530 				    nk->port[pd2.didx] != uh.uh_dport)
5531 					pf_change_icmp(pd2.dst, &uh.uh_dport,
5532 					    NULL, /* XXX Inbound NAT? */
5533 					    &nk->addr[pd2.didx],
5534 					    nk->port[pd2.didx], &uh.uh_sum,
5535 					    pd2.ip_sum, icmpsum,
5536 					    pd->ip_sum, 1, pd2.af);
5537 
5538 				switch (pd2.af) {
5539 #ifdef INET
5540 				case AF_INET:
5541 					m_copyback(m, off, ICMP_MINLEN,
5542 					    (caddr_t)pd->hdr.icmp);
5543 					m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5544 					break;
5545 #endif /* INET */
5546 #ifdef INET6
5547 				case AF_INET6:
5548 					m_copyback(m, off,
5549 					    sizeof(struct icmp6_hdr),
5550 					    (caddr_t)pd->hdr.icmp6);
5551 					m_copyback(m, ipoff2, sizeof(h2_6),
5552 					    (caddr_t)&h2_6);
5553 					break;
5554 #endif /* INET6 */
5555 				}
5556 				m->m_flags &= ~M_HASH;
5557 				m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
5558 			}
5559 			break;
5560 		}
5561 #ifdef INET
5562 		case IPPROTO_ICMP: {
5563 			struct icmp		iih;
5564 
5565 			if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
5566 			    NULL, reason, pd2.af)) {
5567 				DPFPRINTF(PF_DEBUG_MISC,
5568 				    ("pf: ICMP error message too short i"
5569 				    "(icmp)\n"));
5570 				return (PF_DROP);
5571 			}
5572 
5573 			key.af = pd2.af;
5574 			key.proto = IPPROTO_ICMP;
5575 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5576 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5577 			key.port[0] = key.port[1] = iih.icmp_id;
5578 
5579 			STATE_LOOKUP(kif, &key, direction, *state, m);
5580 			lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5581 
5582 			/* translate source/destination address, if necessary */
5583 			if ((*state)->key[PF_SK_WIRE] !=
5584 			    (*state)->key[PF_SK_STACK]) {
5585 				struct pf_state_key *nk =
5586 				    (*state)->key[pd->didx];
5587 
5588 				if (PF_ANEQ(pd2.src,
5589 				    &nk->addr[pd2.sidx], pd2.af) ||
5590 				    nk->port[pd2.sidx] != iih.icmp_id)
5591 					pf_change_icmp(pd2.src, &iih.icmp_id,
5592 					    daddr, &nk->addr[pd2.sidx],
5593 					    nk->port[pd2.sidx], NULL,
5594 					    pd2.ip_sum, icmpsum,
5595 					    pd->ip_sum, 0, AF_INET);
5596 
5597 				if (PF_ANEQ(pd2.dst,
5598 				    &nk->addr[pd2.didx], pd2.af) ||
5599 				    nk->port[pd2.didx] != iih.icmp_id)
5600 					pf_change_icmp(pd2.dst, &iih.icmp_id,
5601 					    NULL, /* XXX Inbound NAT? */
5602 					    &nk->addr[pd2.didx],
5603 					    nk->port[pd2.didx], NULL,
5604 					    pd2.ip_sum, icmpsum,
5605 					    pd->ip_sum, 0, AF_INET);
5606 
5607 				m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
5608 				m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5609 				m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5610 				m->m_flags &= ~M_HASH;
5611 			}
5612 			break;
5613 		}
5614 #endif /* INET */
5615 #ifdef INET6
5616 		case IPPROTO_ICMPV6: {
5617 			struct icmp6_hdr	iih;
5618 
5619 			if (!pf_pull_hdr(m, off2, &iih,
5620 			    sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5621 				DPFPRINTF(PF_DEBUG_MISC,
5622 				    ("pf: ICMP error message too short "
5623 				    "(icmp6)\n"));
5624 				FAIL (PF_DROP);
5625 			}
5626 
5627 			key.af = pd2.af;
5628 			key.proto = IPPROTO_ICMPV6;
5629 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5630 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5631 			key.port[0] = key.port[1] = iih.icmp6_id;
5632 
5633 			STATE_LOOKUP(kif, &key, direction, *state, m);
5634 			lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5635 
5636 			/* translate source/destination address, if necessary */
5637 			if ((*state)->key[PF_SK_WIRE] !=
5638 			    (*state)->key[PF_SK_STACK]) {
5639 				struct pf_state_key *nk =
5640 				    (*state)->key[pd->didx];
5641 
5642 				if (PF_ANEQ(pd2.src,
5643 				    &nk->addr[pd2.sidx], pd2.af) ||
5644 				    nk->port[pd2.sidx] != iih.icmp6_id)
5645 					pf_change_icmp(pd2.src, &iih.icmp6_id,
5646 					    daddr, &nk->addr[pd2.sidx],
5647 					    nk->port[pd2.sidx], NULL,
5648 					    pd2.ip_sum, icmpsum,
5649 					    pd->ip_sum, 0, AF_INET6);
5650 
5651 				if (PF_ANEQ(pd2.dst,
5652 				    &nk->addr[pd2.didx], pd2.af) ||
5653 				    nk->port[pd2.didx] != iih.icmp6_id)
5654 					pf_change_icmp(pd2.dst, &iih.icmp6_id,
5655 					    NULL, /* XXX Inbound NAT? */
5656 					    &nk->addr[pd2.didx],
5657 					    nk->port[pd2.didx], NULL,
5658 					    pd2.ip_sum, icmpsum,
5659 					    pd->ip_sum, 0, AF_INET6);
5660 
5661 				m_copyback(m, off, sizeof(struct icmp6_hdr),
5662 				    (caddr_t)pd->hdr.icmp6);
5663 				m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5664 				m_copyback(m, off2, sizeof(struct icmp6_hdr),
5665 				    (caddr_t)&iih);
5666 				m->m_flags &= ~M_HASH;
5667 			}
5668 			break;
5669 		}
5670 #endif /* INET6 */
5671 		default: {
5672 			key.af = pd2.af;
5673 			key.proto = pd2.proto;
5674 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5675 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5676 			key.port[0] = key.port[1] = 0;
5677 
5678 			STATE_LOOKUP(kif, &key, direction, *state, m);
5679 			lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5680 
5681 			/* translate source/destination address, if necessary */
5682 			if ((*state)->key[PF_SK_WIRE] !=
5683 			    (*state)->key[PF_SK_STACK]) {
5684 				struct pf_state_key *nk =
5685 				    (*state)->key[pd->didx];
5686 
5687 				if (PF_ANEQ(pd2.src,
5688 				    &nk->addr[pd2.sidx], pd2.af))
5689 					pf_change_icmp(pd2.src, NULL, daddr,
5690 					    &nk->addr[pd2.sidx], 0, NULL,
5691 					    pd2.ip_sum, icmpsum,
5692 					    pd->ip_sum, 0, pd2.af);
5693 
5694 				if (PF_ANEQ(pd2.dst,
5695 				    &nk->addr[pd2.didx], pd2.af))
5696 					pf_change_icmp(pd2.src, NULL,
5697 					    NULL, /* XXX Inbound NAT? */
5698 					    &nk->addr[pd2.didx], 0, NULL,
5699 					    pd2.ip_sum, icmpsum,
5700 					    pd->ip_sum, 0, pd2.af);
5701 
5702 				switch (pd2.af) {
5703 #ifdef INET
5704 				case AF_INET:
5705 					m_copyback(m, off, ICMP_MINLEN,
5706 					    (caddr_t)pd->hdr.icmp);
5707 					m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5708 					m->m_flags &= ~M_HASH;
5709 					break;
5710 #endif /* INET */
5711 #ifdef INET6
5712 				case AF_INET6:
5713 					m_copyback(m, off,
5714 					    sizeof(struct icmp6_hdr),
5715 					    (caddr_t)pd->hdr.icmp6);
5716 					m_copyback(m, ipoff2, sizeof(h2_6),
5717 					    (caddr_t)&h2_6);
5718 					m->m_flags &= ~M_HASH;
5719 					break;
5720 #endif /* INET6 */
5721 				}
5722 			}
5723 			break;
5724 		}
5725 		}
5726 	}
5727 
5728 	pfsync_update_state(*state);
5729 	error = PF_PASS;
5730 done:
5731 	if (*state)
5732 		lockmgr(&(*state)->lk, LK_RELEASE);
5733 	return (error);
5734 }
5735 
5736 /*
5737  * Test other connection state.  Caller must hold the state locked.
5738  */
5739 int
5740 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5741 		    struct mbuf *m, struct pf_pdesc *pd)
5742 {
5743 	struct pf_state_peer	*src, *dst;
5744 	struct pf_state_key_cmp	 key;
5745 
5746 	bzero(&key, sizeof(key));
5747 	key.af = pd->af;
5748 	key.proto = pd->proto;
5749 	if (direction == PF_IN)	{
5750 		PF_ACPY(&key.addr[0], pd->src, key.af);
5751 		PF_ACPY(&key.addr[1], pd->dst, key.af);
5752 		key.port[0] = key.port[1] = 0;
5753 	} else {
5754 		PF_ACPY(&key.addr[1], pd->src, key.af);
5755 		PF_ACPY(&key.addr[0], pd->dst, key.af);
5756 		key.port[1] = key.port[0] = 0;
5757 	}
5758 
5759 	STATE_LOOKUP(kif, &key, direction, *state, m);
5760 	lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5761 
5762 	if (direction == (*state)->direction) {
5763 		src = &(*state)->src;
5764 		dst = &(*state)->dst;
5765 	} else {
5766 		src = &(*state)->dst;
5767 		dst = &(*state)->src;
5768 	}
5769 
5770 	/* update states */
5771 	if (src->state < PFOTHERS_SINGLE)
5772 		src->state = PFOTHERS_SINGLE;
5773 	if (dst->state == PFOTHERS_SINGLE)
5774 		dst->state = PFOTHERS_MULTIPLE;
5775 
5776 	/* update expire time */
5777 	(*state)->expire = time_second;
5778 	if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5779 		(*state)->timeout = PFTM_OTHER_MULTIPLE;
5780 	else
5781 		(*state)->timeout = PFTM_OTHER_SINGLE;
5782 
5783 	/* translate source/destination address, if necessary */
5784 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5785 		struct pf_state_key *nk = (*state)->key[pd->didx];
5786 
5787 		KKASSERT(nk);
5788 		KKASSERT(pd);
5789 		KKASSERT(pd->src);
5790 		KKASSERT(pd->dst);
5791 		switch (pd->af) {
5792 #ifdef INET
5793 		case AF_INET:
5794 			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5795 				pf_change_a(&pd->src->v4.s_addr,
5796 				    pd->ip_sum,
5797 				    nk->addr[pd->sidx].v4.s_addr,
5798 				    0);
5799 
5800 
5801 			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5802 				pf_change_a(&pd->dst->v4.s_addr,
5803 				    pd->ip_sum,
5804 				    nk->addr[pd->didx].v4.s_addr,
5805 				    0);
5806 
5807 			break;
5808 #endif /* INET */
5809 #ifdef INET6
5810 		case AF_INET6:
5811 			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5812 				PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5813 
5814 			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5815 				PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5816 #endif /* INET6 */
5817 		}
5818 	}
5819 
5820 	pfsync_update_state(*state);
5821 	lockmgr(&(*state)->lk, LK_RELEASE);
5822 	return (PF_PASS);
5823 }
5824 
5825 /*
5826  * ipoff and off are measured from the start of the mbuf chain.
5827  * h must be at "ipoff" on the mbuf chain.
5828  */
5829 void *
5830 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5831     u_short *actionp, u_short *reasonp, sa_family_t af)
5832 {
5833 	switch (af) {
5834 #ifdef INET
5835 	case AF_INET: {
5836 		struct ip	*h = mtod(m, struct ip *);
5837 		u_int16_t	 fragoff = (h->ip_off & IP_OFFMASK) << 3;
5838 
5839 		if (fragoff) {
5840 			if (fragoff >= len)
5841 				ACTION_SET(actionp, PF_PASS);
5842 			else {
5843 				ACTION_SET(actionp, PF_DROP);
5844 				REASON_SET(reasonp, PFRES_FRAG);
5845 			}
5846 			return (NULL);
5847 		}
5848 		if (m->m_pkthdr.len < off + len ||
5849 		    h->ip_len < off + len) {
5850 			ACTION_SET(actionp, PF_DROP);
5851 			REASON_SET(reasonp, PFRES_SHORT);
5852 			return (NULL);
5853 		}
5854 		break;
5855 	}
5856 #endif /* INET */
5857 #ifdef INET6
5858 	case AF_INET6: {
5859 		struct ip6_hdr	*h = mtod(m, struct ip6_hdr *);
5860 
5861 		if (m->m_pkthdr.len < off + len ||
5862 		    (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5863 		    (unsigned)(off + len)) {
5864 			ACTION_SET(actionp, PF_DROP);
5865 			REASON_SET(reasonp, PFRES_SHORT);
5866 			return (NULL);
5867 		}
5868 		break;
5869 	}
5870 #endif /* INET6 */
5871 	}
5872 	m_copydata(m, off, len, p);
5873 	return (p);
5874 }
5875 
5876 int
5877 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif)
5878 {
5879 	struct sockaddr_in	*dst;
5880 	int			 ret = 1;
5881 	int			 check_mpath;
5882 #ifdef INET6
5883 	struct sockaddr_in6	*dst6;
5884 	struct route_in6	 ro;
5885 #else
5886 	struct route		 ro;
5887 #endif
5888 	struct radix_node	*rn;
5889 	struct rtentry		*rt;
5890 	struct ifnet		*ifp;
5891 
5892 	check_mpath = 0;
5893 	bzero(&ro, sizeof(ro));
5894 	switch (af) {
5895 	case AF_INET:
5896 		dst = satosin(&ro.ro_dst);
5897 		dst->sin_family = AF_INET;
5898 		dst->sin_len = sizeof(*dst);
5899 		dst->sin_addr = addr->v4;
5900 		break;
5901 #ifdef INET6
5902 	case AF_INET6:
5903 		dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5904 		dst6->sin6_family = AF_INET6;
5905 		dst6->sin6_len = sizeof(*dst6);
5906 		dst6->sin6_addr = addr->v6;
5907 		break;
5908 #endif /* INET6 */
5909 	default:
5910 		return (0);
5911 	}
5912 
5913 	/* Skip checks for ipsec interfaces */
5914 	if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5915 		goto out;
5916 
5917 	rtalloc_ign((struct route *)&ro, 0);
5918 
5919 	if (ro.ro_rt != NULL) {
5920 		/* No interface given, this is a no-route check */
5921 		if (kif == NULL)
5922 			goto out;
5923 
5924 		if (kif->pfik_ifp == NULL) {
5925 			ret = 0;
5926 			goto out;
5927 		}
5928 
5929 		/* Perform uRPF check if passed input interface */
5930 		ret = 0;
5931 		rn = (struct radix_node *)ro.ro_rt;
5932 		do {
5933 			rt = (struct rtentry *)rn;
5934 			ifp = rt->rt_ifp;
5935 
5936 			if (kif->pfik_ifp == ifp)
5937 				ret = 1;
5938 			rn = NULL;
5939 		} while (check_mpath == 1 && rn != NULL && ret == 0);
5940 	} else
5941 		ret = 0;
5942 out:
5943 	if (ro.ro_rt != NULL)
5944 		RTFREE(ro.ro_rt);
5945 	return (ret);
5946 }
5947 
5948 int
5949 pf_rtlabel_match(struct pf_addr *addr, sa_family_t af, struct pf_addr_wrap *aw)
5950 {
5951 	struct sockaddr_in	*dst;
5952 #ifdef INET6
5953 	struct sockaddr_in6	*dst6;
5954 	struct route_in6	 ro;
5955 #else
5956 	struct route		 ro;
5957 #endif
5958 	int			 ret = 0;
5959 
5960 	ASSERT_LWKT_TOKEN_HELD(&pf_token);
5961 
5962 	bzero(&ro, sizeof(ro));
5963 	switch (af) {
5964 	case AF_INET:
5965 		dst = satosin(&ro.ro_dst);
5966 		dst->sin_family = AF_INET;
5967 		dst->sin_len = sizeof(*dst);
5968 		dst->sin_addr = addr->v4;
5969 		break;
5970 #ifdef INET6
5971 	case AF_INET6:
5972 		dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5973 		dst6->sin6_family = AF_INET6;
5974 		dst6->sin6_len = sizeof(*dst6);
5975 		dst6->sin6_addr = addr->v6;
5976 		break;
5977 #endif /* INET6 */
5978 	default:
5979 		return (0);
5980 	}
5981 
5982 rtalloc_ign((struct route *)&ro, (RTF_CLONING | RTF_PRCLONING));
5983 
5984 	if (ro.ro_rt != NULL) {
5985 		RTFREE(ro.ro_rt);
5986 	}
5987 
5988 	return (ret);
5989 }
5990 
5991 #ifdef INET
5992 void
5993 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5994     struct pf_state *s, struct pf_pdesc *pd)
5995 {
5996 	struct mbuf		*m0, *m1;
5997 	struct route		 iproute;
5998 	struct route		*ro = NULL;
5999 	struct sockaddr_in	*dst;
6000 	struct ip		*ip;
6001 	struct ifnet		*ifp = NULL;
6002 	struct pf_addr		 naddr;
6003 	struct pf_src_node	*sn = NULL;
6004 	int			 error = 0;
6005 	int sw_csum;
6006 #ifdef IPSEC
6007 	struct m_tag		*mtag;
6008 #endif /* IPSEC */
6009 
6010 	ASSERT_LWKT_TOKEN_HELD(&pf_token);
6011 
6012 	if (m == NULL || *m == NULL || r == NULL ||
6013 	    (dir != PF_IN && dir != PF_OUT) || oifp == NULL)
6014 		panic("pf_route: invalid parameters");
6015 
6016 	if (((*m)->m_pkthdr.fw_flags & PF_MBUF_ROUTED) == 0) {
6017 		(*m)->m_pkthdr.fw_flags |= PF_MBUF_ROUTED;
6018 		(*m)->m_pkthdr.pf.routed = 1;
6019 	} else {
6020 		if ((*m)->m_pkthdr.pf.routed++ > 3) {
6021 			m0 = *m;
6022 			*m = NULL;
6023 			goto bad;
6024 		}
6025 	}
6026 
6027 	if (r->rt == PF_DUPTO) {
6028 		if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
6029 			return;
6030 		}
6031 	} else {
6032 		if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
6033 			return;
6034 		}
6035 		m0 = *m;
6036 	}
6037 
6038 	if (m0->m_len < sizeof(struct ip)) {
6039 		DPFPRINTF(PF_DEBUG_URGENT,
6040 		    ("pf_route: m0->m_len < sizeof(struct ip)\n"));
6041 		goto bad;
6042 	}
6043 
6044 	ip = mtod(m0, struct ip *);
6045 
6046 	ro = &iproute;
6047 	bzero((caddr_t)ro, sizeof(*ro));
6048 	dst = satosin(&ro->ro_dst);
6049 	dst->sin_family = AF_INET;
6050 	dst->sin_len = sizeof(*dst);
6051 	dst->sin_addr = ip->ip_dst;
6052 
6053 	if (r->rt == PF_FASTROUTE) {
6054 		rtalloc(ro);
6055 		if (ro->ro_rt == 0) {
6056 			ipstat.ips_noroute++;
6057 			goto bad;
6058 		}
6059 
6060 		ifp = ro->ro_rt->rt_ifp;
6061 		ro->ro_rt->rt_use++;
6062 
6063 		if (ro->ro_rt->rt_flags & RTF_GATEWAY)
6064 			dst = satosin(ro->ro_rt->rt_gateway);
6065 	} else {
6066 		if (TAILQ_EMPTY(&r->rpool.list)) {
6067 			DPFPRINTF(PF_DEBUG_URGENT,
6068 			    ("pf_route: TAILQ_EMPTY(&r->rpool.list)\n"));
6069 			goto bad;
6070 		}
6071 		if (s == NULL) {
6072 			pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
6073 			    &naddr, NULL, &sn);
6074 			if (!PF_AZERO(&naddr, AF_INET))
6075 				dst->sin_addr.s_addr = naddr.v4.s_addr;
6076 			ifp = r->rpool.cur->kif ?
6077 			    r->rpool.cur->kif->pfik_ifp : NULL;
6078 		} else {
6079 			if (!PF_AZERO(&s->rt_addr, AF_INET))
6080 				dst->sin_addr.s_addr =
6081 				    s->rt_addr.v4.s_addr;
6082 			ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
6083 		}
6084 	}
6085 	if (ifp == NULL)
6086 		goto bad;
6087 
6088 	if (oifp != ifp) {
6089 		if (pf_test(PF_OUT, ifp, &m0, NULL, NULL) != PF_PASS) {
6090 			goto bad;
6091 		} else if (m0 == NULL) {
6092 			goto done;
6093 		}
6094 		if (m0->m_len < sizeof(struct ip)) {
6095 			DPFPRINTF(PF_DEBUG_URGENT,
6096 			    ("pf_route: m0->m_len < sizeof(struct ip)\n"));
6097 			goto bad;
6098 		}
6099 		ip = mtod(m0, struct ip *);
6100 	}
6101 
6102 	/* Copied from FreeBSD 5.1-CURRENT ip_output. */
6103 	m0->m_pkthdr.csum_flags |= CSUM_IP;
6104 	sw_csum = m0->m_pkthdr.csum_flags & ~ifp->if_hwassist;
6105 	if (sw_csum & CSUM_DELAY_DATA) {
6106 		in_delayed_cksum(m0);
6107 		sw_csum &= ~CSUM_DELAY_DATA;
6108 	}
6109 	m0->m_pkthdr.csum_flags &= ifp->if_hwassist;
6110 	m0->m_pkthdr.csum_iphlen = (ip->ip_hl << 2);
6111 
6112 	/*
6113 	 * WARNING!  We cannot fragment if the packet was modified from an
6114 	 *	     original which expected to be using TSO.  In this
6115 	 *	     situation we pray that the target interface is
6116 	 *	     compatible with the originating interface.
6117 	 */
6118 	if (ip->ip_len <= ifp->if_mtu ||
6119 	    (m0->m_pkthdr.csum_flags & CSUM_TSO) ||
6120 	    ((ifp->if_hwassist & CSUM_FRAGMENT) &&
6121 		(ip->ip_off & IP_DF) == 0)) {
6122 		ip->ip_len = htons(ip->ip_len);
6123 		ip->ip_off = htons(ip->ip_off);
6124 		ip->ip_sum = 0;
6125 		if (sw_csum & CSUM_DELAY_IP) {
6126 			/* From KAME */
6127 			if (ip->ip_v == IPVERSION &&
6128 			    (ip->ip_hl << 2) == sizeof(*ip)) {
6129 				ip->ip_sum = in_cksum_hdr(ip);
6130 			} else {
6131 				ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
6132 			}
6133 		}
6134 		lwkt_reltoken(&pf_token);
6135 		error = ifp->if_output(ifp, m0, sintosa(dst), ro->ro_rt);
6136 		lwkt_gettoken(&pf_token);
6137 		goto done;
6138 	}
6139 
6140 	/*
6141 	 * Too large for interface; fragment if possible.
6142 	 * Must be able to put at least 8 bytes per fragment.
6143 	 */
6144 	if (ip->ip_off & IP_DF) {
6145 		ipstat.ips_cantfrag++;
6146 		if (r->rt != PF_DUPTO) {
6147 			icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
6148 				   ifp->if_mtu);
6149 			goto done;
6150 		} else
6151 			goto bad;
6152 	}
6153 
6154 	m1 = m0;
6155 	error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist, sw_csum);
6156 	if (error) {
6157 		goto bad;
6158 	}
6159 
6160 	for (m0 = m1; m0; m0 = m1) {
6161 		m1 = m0->m_nextpkt;
6162 		m0->m_nextpkt = 0;
6163 		if (error == 0) {
6164 			lwkt_reltoken(&pf_token);
6165 			error = (*ifp->if_output)(ifp, m0, sintosa(dst),
6166 						  NULL);
6167 			lwkt_gettoken(&pf_token);
6168 		} else
6169 			m_freem(m0);
6170 	}
6171 
6172 	if (error == 0)
6173 		ipstat.ips_fragmented++;
6174 
6175 done:
6176 	if (r->rt != PF_DUPTO)
6177 		*m = NULL;
6178 	if (ro == &iproute && ro->ro_rt)
6179 		RTFREE(ro->ro_rt);
6180 	return;
6181 
6182 bad:
6183 	m_freem(m0);
6184 	goto done;
6185 }
6186 #endif /* INET */
6187 
6188 #ifdef INET6
6189 void
6190 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
6191     struct pf_state *s, struct pf_pdesc *pd)
6192 {
6193 	struct mbuf		*m0;
6194 	struct route_in6	 ip6route;
6195 	struct route_in6	*ro;
6196 	struct sockaddr_in6	*dst;
6197 	struct ip6_hdr		*ip6;
6198 	struct ifnet		*ifp = NULL;
6199 	struct pf_addr		 naddr;
6200 	struct pf_src_node	*sn = NULL;
6201 
6202 	if (m == NULL || *m == NULL || r == NULL ||
6203 	    (dir != PF_IN && dir != PF_OUT) || oifp == NULL)
6204 		panic("pf_route6: invalid parameters");
6205 
6206 	if (((*m)->m_pkthdr.fw_flags & PF_MBUF_ROUTED) == 0) {
6207 		(*m)->m_pkthdr.fw_flags |= PF_MBUF_ROUTED;
6208 		(*m)->m_pkthdr.pf.routed = 1;
6209 	} else {
6210 		if ((*m)->m_pkthdr.pf.routed++ > 3) {
6211 			m0 = *m;
6212 			*m = NULL;
6213 			goto bad;
6214 		}
6215 	}
6216 
6217 	if (r->rt == PF_DUPTO) {
6218 		if ((m0 = m_dup(*m, M_NOWAIT)) == NULL)
6219 			return;
6220 	} else {
6221 		if ((r->rt == PF_REPLYTO) == (r->direction == dir))
6222 			return;
6223 		m0 = *m;
6224 	}
6225 
6226 	if (m0->m_len < sizeof(struct ip6_hdr)) {
6227 		DPFPRINTF(PF_DEBUG_URGENT,
6228 		    ("pf_route6: m0->m_len < sizeof(struct ip6_hdr)\n"));
6229 		goto bad;
6230 	}
6231 	ip6 = mtod(m0, struct ip6_hdr *);
6232 
6233 	ro = &ip6route;
6234 	bzero((caddr_t)ro, sizeof(*ro));
6235 	dst = (struct sockaddr_in6 *)&ro->ro_dst;
6236 	dst->sin6_family = AF_INET6;
6237 	dst->sin6_len = sizeof(*dst);
6238 	dst->sin6_addr = ip6->ip6_dst;
6239 
6240 	/*
6241 	 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
6242 	 * so make sure pf.flags is clear.
6243 	 *
6244 	 * Cheat. XXX why only in the v6 case???
6245 	 */
6246 	if (r->rt == PF_FASTROUTE) {
6247 		m0->m_pkthdr.fw_flags |= PF_MBUF_TAGGED;
6248 		m0->m_pkthdr.pf.flags = 0;
6249 		/* XXX Re-Check when Upgrading to > 4.4 */
6250 		m0->m_pkthdr.pf.statekey = NULL;
6251 		ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
6252 		return;
6253 	}
6254 
6255 	if (TAILQ_EMPTY(&r->rpool.list)) {
6256 		DPFPRINTF(PF_DEBUG_URGENT,
6257 		    ("pf_route6: TAILQ_EMPTY(&r->rpool.list)\n"));
6258 		goto bad;
6259 	}
6260 	if (s == NULL) {
6261 		pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
6262 		    &naddr, NULL, &sn);
6263 		if (!PF_AZERO(&naddr, AF_INET6))
6264 			PF_ACPY((struct pf_addr *)&dst->sin6_addr,
6265 			    &naddr, AF_INET6);
6266 		ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
6267 	} else {
6268 		if (!PF_AZERO(&s->rt_addr, AF_INET6))
6269 			PF_ACPY((struct pf_addr *)&dst->sin6_addr,
6270 			    &s->rt_addr, AF_INET6);
6271 		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
6272 	}
6273 	if (ifp == NULL)
6274 		goto bad;
6275 
6276 	if (oifp != ifp) {
6277 		if (pf_test6(PF_OUT, ifp, &m0, NULL, NULL) != PF_PASS) {
6278 			goto bad;
6279 		} else if (m0 == NULL) {
6280 			goto done;
6281 		}
6282 		if (m0->m_len < sizeof(struct ip6_hdr)) {
6283 			DPFPRINTF(PF_DEBUG_URGENT,
6284 			    ("pf_route6: m0->m_len < sizeof(struct ip6_hdr)\n"));
6285 			goto bad;
6286 		}
6287 		ip6 = mtod(m0, struct ip6_hdr *);
6288 	}
6289 
6290 	/*
6291 	 * If the packet is too large for the outgoing interface,
6292 	 * send back an icmp6 error.
6293 	 */
6294 	if (IN6_IS_ADDR_LINKLOCAL(&dst->sin6_addr))
6295 		dst->sin6_addr.s6_addr16[1] = htons(ifp->if_index);
6296 	if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu) {
6297 		nd6_output(ifp, ifp, m0, dst, NULL);
6298 	} else {
6299 		in6_ifstat_inc(ifp, ifs6_in_toobig);
6300 		if (r->rt != PF_DUPTO)
6301 			icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
6302 		else
6303 			goto bad;
6304 	}
6305 
6306 done:
6307 	if (r->rt != PF_DUPTO)
6308 		*m = NULL;
6309 	return;
6310 
6311 bad:
6312 	m_freem(m0);
6313 	goto done;
6314 }
6315 #endif /* INET6 */
6316 
6317 
6318 /*
6319  * check protocol (tcp/udp/icmp/icmp6) checksum and set mbuf flag
6320  *   off is the offset where the protocol header starts
6321  *   len is the total length of protocol header plus payload
6322  * returns 0 when the checksum is valid, otherwise returns 1.
6323  */
6324 /*
6325  * XXX
6326  * FreeBSD supports cksum offload for the following drivers.
6327  * em(4), gx(4), lge(4), nge(4), ti(4), xl(4)
6328  * If we can make full use of it we would outperform ipfw/ipfilter in
6329  * very heavy traffic.
6330  * I have not tested 'cause I don't have NICs that supports cksum offload.
6331  * (There might be problems. Typical phenomena would be
6332  *   1. No route message for UDP packet.
6333  *   2. No connection acceptance from external hosts regardless of rule set.)
6334  */
6335 int
6336 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p,
6337     sa_family_t af)
6338 {
6339 	u_int16_t sum = 0;
6340 	int hw_assist = 0;
6341 	struct ip *ip;
6342 
6343 	if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
6344 		return (1);
6345 	if (m->m_pkthdr.len < off + len)
6346 		return (1);
6347 
6348 	switch (p) {
6349 	case IPPROTO_TCP:
6350 	case IPPROTO_UDP:
6351 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
6352 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
6353 				sum = m->m_pkthdr.csum_data;
6354 			} else {
6355 				ip = mtod(m, struct ip *);
6356 				sum = in_pseudo(ip->ip_src.s_addr,
6357 					ip->ip_dst.s_addr, htonl((u_short)len +
6358 					m->m_pkthdr.csum_data + p));
6359 			}
6360 			sum ^= 0xffff;
6361 			++hw_assist;
6362 		}
6363 		break;
6364 	case IPPROTO_ICMP:
6365 #ifdef INET6
6366 	case IPPROTO_ICMPV6:
6367 #endif /* INET6 */
6368 		break;
6369 	default:
6370 		return (1);
6371 	}
6372 
6373 	if (!hw_assist) {
6374 		switch (af) {
6375 		case AF_INET:
6376 			if (p == IPPROTO_ICMP) {
6377 				if (m->m_len < off)
6378 					return (1);
6379 				m->m_data += off;
6380 				m->m_len -= off;
6381 				sum = in_cksum(m, len);
6382 				m->m_data -= off;
6383 				m->m_len += off;
6384 			} else {
6385 				if (m->m_len < sizeof(struct ip))
6386 					return (1);
6387 				sum = in_cksum_range(m, p, off, len);
6388 				if (sum == 0) {
6389 					m->m_pkthdr.csum_flags |=
6390 					    (CSUM_DATA_VALID |
6391 					     CSUM_PSEUDO_HDR);
6392 					m->m_pkthdr.csum_data = 0xffff;
6393 				}
6394 			}
6395 			break;
6396 #ifdef INET6
6397 		case AF_INET6:
6398 			if (m->m_len < sizeof(struct ip6_hdr))
6399 				return (1);
6400 			sum = in6_cksum(m, p, off, len);
6401 			/*
6402 			 * XXX
6403 			 * IPv6 H/W cksum off-load not supported yet!
6404 			 *
6405 			 * if (sum == 0) {
6406 			 *	m->m_pkthdr.csum_flags |=
6407 			 *	    (CSUM_DATA_VALID|CSUM_PSEUDO_HDR);
6408 			 *	m->m_pkthdr.csum_data = 0xffff;
6409 			 *}
6410 			 */
6411 			break;
6412 #endif /* INET6 */
6413 		default:
6414 			return (1);
6415 		}
6416 	}
6417 	if (sum) {
6418 		switch (p) {
6419 		case IPPROTO_TCP:
6420 			tcpstat.tcps_rcvbadsum++;
6421 			break;
6422 		case IPPROTO_UDP:
6423 			udp_stat.udps_badsum++;
6424 			break;
6425 		case IPPROTO_ICMP:
6426 			icmpstat.icps_checksum++;
6427 			break;
6428 #ifdef INET6
6429 		case IPPROTO_ICMPV6:
6430 			icmp6stat.icp6s_checksum++;
6431 			break;
6432 #endif /* INET6 */
6433 		}
6434 		return (1);
6435 	}
6436 	return (0);
6437 }
6438 
6439 struct pf_divert *
6440 pf_find_divert(struct mbuf *m)
6441 {
6442 	struct m_tag    *mtag;
6443 
6444 	if ((mtag = m_tag_find(m, PACKET_TAG_PF_DIVERT, NULL)) == NULL)
6445 		return (NULL);
6446 
6447 	return ((struct pf_divert *)(mtag + 1));
6448 }
6449 
6450 struct pf_divert *
6451 pf_get_divert(struct mbuf *m)
6452 {
6453 	struct m_tag    *mtag;
6454 
6455 	if ((mtag = m_tag_find(m, PACKET_TAG_PF_DIVERT, NULL)) == NULL) {
6456 		mtag = m_tag_get(PACKET_TAG_PF_DIVERT, sizeof(struct pf_divert),
6457 		    M_NOWAIT);
6458 		if (mtag == NULL)
6459 			return (NULL);
6460 		bzero(mtag + 1, sizeof(struct pf_divert));
6461 		m_tag_prepend(m, mtag);
6462 	}
6463 
6464 	return ((struct pf_divert *)(mtag + 1));
6465 }
6466 
6467 #ifdef INET
6468 
6469 /*
6470  * WARNING: pf_token held shared on entry, THIS IS CPU LOCALIZED CODE
6471  */
6472 int
6473 pf_test(int dir, struct ifnet *ifp, struct mbuf **m0,
6474     struct ether_header *eh, struct inpcb *inp)
6475 {
6476 	struct pfi_kif		*kif;
6477 	u_short			 action, reason = 0, log = 0;
6478 	struct mbuf		*m = *m0;
6479 	struct ip		*h = NULL;
6480 	struct pf_rule		*a = NULL, *r = &pf_default_rule, *tr, *nr;
6481 	struct pf_state		*s = NULL;
6482 	struct pf_ruleset	*ruleset = NULL;
6483 	struct pf_pdesc		 pd;
6484 	int			 off, dirndx;
6485 #ifdef ALTQ
6486 	int			 pqid = 0;
6487 #endif
6488 
6489 	if (!pf_status.running)
6490 		return (PF_PASS);
6491 
6492 	memset(&pd, 0, sizeof(pd));
6493 #ifdef foo
6494 	if (ifp->if_type == IFT_CARP && ifp->if_carpdev)
6495 		kif = (struct pfi_kif *)ifp->if_carpdev->if_pf_kif;
6496 	else
6497 #endif
6498 		kif = (struct pfi_kif *)ifp->if_pf_kif;
6499 
6500 	if (kif == NULL) {
6501 		DPFPRINTF(PF_DEBUG_URGENT,
6502 		    ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
6503 		return (PF_DROP);
6504 	}
6505 	if (kif->pfik_flags & PFI_IFLAG_SKIP)
6506 		return (PF_PASS);
6507 
6508 #ifdef DIAGNOSTIC
6509 	if ((m->m_flags & M_PKTHDR) == 0)
6510 		panic("non-M_PKTHDR is passed to pf_test");
6511 #endif /* DIAGNOSTIC */
6512 
6513 	if (m->m_pkthdr.len < (int)sizeof(*h)) {
6514 		action = PF_DROP;
6515 		REASON_SET(&reason, PFRES_SHORT);
6516 		log = 1;
6517 		goto done;
6518 	}
6519 
6520 	/*
6521 	 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
6522 	 * so make sure pf.flags is clear.
6523 	 */
6524 	if (m->m_pkthdr.fw_flags & PF_MBUF_TAGGED)
6525 		return (PF_PASS);
6526 	m->m_pkthdr.pf.flags = 0;
6527 	/* Re-Check when updating to > 4.4 */
6528 	m->m_pkthdr.pf.statekey = NULL;
6529 
6530 	/* We do IP header normalization and packet reassembly here */
6531 	if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
6532 		action = PF_DROP;
6533 		goto done;
6534 	}
6535 	m = *m0;	/* pf_normalize messes with m0 */
6536 	h = mtod(m, struct ip *);
6537 
6538 	off = h->ip_hl << 2;
6539 	if (off < (int)sizeof(*h)) {
6540 		action = PF_DROP;
6541 		REASON_SET(&reason, PFRES_SHORT);
6542 		log = 1;
6543 		goto done;
6544 	}
6545 
6546 	pd.src = (struct pf_addr *)&h->ip_src;
6547 	pd.dst = (struct pf_addr *)&h->ip_dst;
6548 	pd.sport = pd.dport = NULL;
6549 	pd.ip_sum = &h->ip_sum;
6550 	pd.proto_sum = NULL;
6551 	pd.proto = h->ip_p;
6552 	pd.dir = dir;
6553 	pd.sidx = (dir == PF_IN) ? 0 : 1;
6554 	pd.didx = (dir == PF_IN) ? 1 : 0;
6555 	pd.af = AF_INET;
6556 	pd.tos = h->ip_tos;
6557 	pd.tot_len = h->ip_len;
6558 	pd.eh = eh;
6559 
6560 	/* handle fragments that didn't get reassembled by normalization */
6561 	if (h->ip_off & (IP_MF | IP_OFFMASK)) {
6562 		action = pf_test_fragment(&r, dir, kif, m, h,
6563 		    &pd, &a, &ruleset);
6564 		goto done;
6565 	}
6566 
6567 	switch (h->ip_p) {
6568 
6569 	case IPPROTO_TCP: {
6570 		struct tcphdr	th;
6571 
6572 		pd.hdr.tcp = &th;
6573 		if (!pf_pull_hdr(m, off, &th, sizeof(th),
6574 		    &action, &reason, AF_INET)) {
6575 			log = action != PF_PASS;
6576 			goto done;
6577 		}
6578 		pd.p_len = pd.tot_len - off - (th.th_off << 2);
6579 #ifdef ALTQ
6580 		if ((th.th_flags & TH_ACK) && pd.p_len == 0)
6581 			pqid = 1;
6582 #endif
6583 		action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6584 		if (action == PF_DROP)
6585 			goto done;
6586 		action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6587 					   &reason);
6588 		if (action == PF_PASS) {
6589 			r = s->rule.ptr;
6590 			a = s->anchor.ptr;
6591 			log = s->log;
6592 		} else if (s == NULL) {
6593 			action = pf_test_rule(&r, &s, dir, kif,
6594 					      m, off, h, &pd, &a,
6595 					      &ruleset, NULL, inp);
6596 		}
6597 		break;
6598 	}
6599 
6600 	case IPPROTO_UDP: {
6601 		struct udphdr	uh;
6602 
6603 		pd.hdr.udp = &uh;
6604 		if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6605 		    &action, &reason, AF_INET)) {
6606 			log = action != PF_PASS;
6607 			goto done;
6608 		}
6609 		if (uh.uh_dport == 0 ||
6610 		    ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6611 		    ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6612 			action = PF_DROP;
6613 			REASON_SET(&reason, PFRES_SHORT);
6614 			goto done;
6615 		}
6616 		action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6617 		if (action == PF_PASS) {
6618 			r = s->rule.ptr;
6619 			a = s->anchor.ptr;
6620 			log = s->log;
6621 		} else if (s == NULL) {
6622 			action = pf_test_rule(&r, &s, dir, kif,
6623 					      m, off, h, &pd, &a,
6624 					      &ruleset, NULL, inp);
6625 		}
6626 		break;
6627 	}
6628 
6629 	case IPPROTO_ICMP: {
6630 		struct icmp	ih;
6631 
6632 		pd.hdr.icmp = &ih;
6633 		if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
6634 		    &action, &reason, AF_INET)) {
6635 			log = action != PF_PASS;
6636 			goto done;
6637 		}
6638 		action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
6639 					    &reason);
6640 		if (action == PF_PASS) {
6641 			r = s->rule.ptr;
6642 			a = s->anchor.ptr;
6643 			log = s->log;
6644 		} else if (s == NULL) {
6645 			action = pf_test_rule(&r, &s, dir, kif,
6646 					      m, off, h, &pd, &a,
6647 					      &ruleset, NULL, inp);
6648 		}
6649 		break;
6650 	}
6651 
6652 	default:
6653 		action = pf_test_state_other(&s, dir, kif, m, &pd);
6654 		if (action == PF_PASS) {
6655 			r = s->rule.ptr;
6656 			a = s->anchor.ptr;
6657 			log = s->log;
6658 		} else if (s == NULL) {
6659 			action = pf_test_rule(&r, &s, dir, kif, m, off, h,
6660 					      &pd, &a, &ruleset, NULL, inp);
6661 		}
6662 		break;
6663 	}
6664 
6665 done:
6666 	if (action == PF_PASS && h->ip_hl > 5 &&
6667 	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6668 		action = PF_DROP;
6669 		REASON_SET(&reason, PFRES_IPOPTIONS);
6670 		log = 1;
6671 		DPFPRINTF(PF_DEBUG_MISC,
6672 		    ("pf: dropping packet with ip options\n"));
6673 	}
6674 
6675 	if ((s && s->tag) || r->rtableid)
6676 		pf_tag_packet(m, s ? s->tag : 0, r->rtableid);
6677 
6678 #if 0
6679 	if (dir == PF_IN && s && s->key[PF_SK_STACK])
6680 		m->m_pkthdr.pf.statekey = s->key[PF_SK_STACK];
6681 #endif
6682 
6683 #ifdef ALTQ
6684 	/*
6685 	 * Generate a hash code and qid request for ALTQ.  A qid of 0
6686 	 * is allowed and will cause altq to select the default queue.
6687 	 */
6688 	if (action == PF_PASS) {
6689 		m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
6690 		if (pqid || (pd.tos & IPTOS_LOWDELAY))
6691 			m->m_pkthdr.pf.qid = r->pqid;
6692 		else
6693 			m->m_pkthdr.pf.qid = r->qid;
6694 		m->m_pkthdr.pf.ecn_af = AF_INET;
6695 		m->m_pkthdr.pf.hdr = h;
6696 		/* add connection hash for fairq */
6697 		if (s) {
6698 			/* for fairq */
6699 			m->m_pkthdr.pf.state_hash = s->hash;
6700 			m->m_pkthdr.pf.flags |= PF_TAG_STATE_HASHED;
6701 		}
6702 	}
6703 #endif /* ALTQ */
6704 
6705 	/*
6706 	 * connections redirected to loopback should not match sockets
6707 	 * bound specifically to loopback due to security implications,
6708 	 * see tcp_input() and in_pcblookup_listen().
6709 	 */
6710 	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6711 	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6712 	    (s->nat_rule.ptr->action == PF_RDR ||
6713 	    s->nat_rule.ptr->action == PF_BINAT) &&
6714 	    (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
6715 		m->m_pkthdr.pf.flags |= PF_TAG_TRANSLATE_LOCALHOST;
6716 
6717 	if (dir == PF_IN && action == PF_PASS && r->divert.port) {
6718 		struct pf_divert *divert;
6719 
6720 		if ((divert = pf_get_divert(m))) {
6721 			m->m_pkthdr.pf.flags |= PF_TAG_DIVERTED;
6722 			divert->port = r->divert.port;
6723 			divert->addr.ipv4 = r->divert.addr.v4;
6724 		}
6725 	}
6726 
6727 	if (log) {
6728 		struct pf_rule *lr;
6729 
6730 		if (s != NULL && s->nat_rule.ptr != NULL &&
6731 		    s->nat_rule.ptr->log & PF_LOG_ALL)
6732 			lr = s->nat_rule.ptr;
6733 		else
6734 			lr = r;
6735 		PFLOG_PACKET(kif, h, m, AF_INET, dir, reason, lr, a, ruleset,
6736 		    &pd);
6737 	}
6738 
6739 	kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6740 	kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6741 
6742 	if (action == PF_PASS || r->action == PF_DROP) {
6743 		dirndx = (dir == PF_OUT);
6744 		r->packets[dirndx]++;
6745 		r->bytes[dirndx] += pd.tot_len;
6746 		if (a != NULL) {
6747 			a->packets[dirndx]++;
6748 			a->bytes[dirndx] += pd.tot_len;
6749 		}
6750 		if (s != NULL) {
6751 			if (s->nat_rule.ptr != NULL) {
6752 				s->nat_rule.ptr->packets[dirndx]++;
6753 				s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6754 			}
6755 			if (s->src_node != NULL) {
6756 				s->src_node->packets[dirndx]++;
6757 				s->src_node->bytes[dirndx] += pd.tot_len;
6758 			}
6759 			if (s->nat_src_node != NULL) {
6760 				s->nat_src_node->packets[dirndx]++;
6761 				s->nat_src_node->bytes[dirndx] += pd.tot_len;
6762 			}
6763 			dirndx = (dir == s->direction) ? 0 : 1;
6764 			s->packets[dirndx]++;
6765 			s->bytes[dirndx] += pd.tot_len;
6766 		}
6767 		tr = r;
6768 		nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6769 		if (nr != NULL && r == &pf_default_rule)
6770 			tr = nr;
6771 		if (tr->src.addr.type == PF_ADDR_TABLE)
6772 			pfr_update_stats(tr->src.addr.p.tbl,
6773 			    (s == NULL) ? pd.src :
6774 			    &s->key[(s->direction == PF_IN)]->
6775 				addr[(s->direction == PF_OUT)],
6776 			    pd.af, pd.tot_len, dir == PF_OUT,
6777 			    r->action == PF_PASS, tr->src.neg);
6778 		if (tr->dst.addr.type == PF_ADDR_TABLE)
6779 			pfr_update_stats(tr->dst.addr.p.tbl,
6780 			    (s == NULL) ? pd.dst :
6781 			    &s->key[(s->direction == PF_IN)]->
6782 				addr[(s->direction == PF_IN)],
6783 			    pd.af, pd.tot_len, dir == PF_OUT,
6784 			    r->action == PF_PASS, tr->dst.neg);
6785 	}
6786 
6787 
6788 	if (action == PF_SYNPROXY_DROP) {
6789 		m_freem(*m0);
6790 		*m0 = NULL;
6791 		action = PF_PASS;
6792 	} else if (r->rt) {
6793 		/* pf_route can free the mbuf causing *m0 to become NULL */
6794 		pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
6795 	}
6796 
6797 	return (action);
6798 }
6799 #endif /* INET */
6800 
6801 #ifdef INET6
6802 
6803 /*
6804  * WARNING: pf_token held shared on entry, THIS IS CPU LOCALIZED CODE
6805  */
6806 int
6807 pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0,
6808     struct ether_header *eh, struct inpcb *inp)
6809 {
6810 	struct pfi_kif		*kif;
6811 	u_short			 action, reason = 0, log = 0;
6812 	struct mbuf		*m = *m0, *n = NULL;
6813 	struct ip6_hdr		*h = NULL;
6814 	struct pf_rule		*a = NULL, *r = &pf_default_rule, *tr, *nr;
6815 	struct pf_state		*s = NULL;
6816 	struct pf_ruleset	*ruleset = NULL;
6817 	struct pf_pdesc		 pd;
6818 	int			 off, terminal = 0, dirndx, rh_cnt = 0;
6819 
6820 	if (!pf_status.running)
6821 		return (PF_PASS);
6822 
6823 	memset(&pd, 0, sizeof(pd));
6824 #ifdef foo
6825 	if (ifp->if_type == IFT_CARP && ifp->if_carpdev)
6826 		kif = (struct pfi_kif *)ifp->if_carpdev->if_pf_kif;
6827 	else
6828 #endif
6829 		kif = (struct pfi_kif *)ifp->if_pf_kif;
6830 
6831 	if (kif == NULL) {
6832 		DPFPRINTF(PF_DEBUG_URGENT,
6833 		    ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6834 		return (PF_DROP);
6835 	}
6836 	if (kif->pfik_flags & PFI_IFLAG_SKIP)
6837 		return (PF_PASS);
6838 
6839 #ifdef DIAGNOSTIC
6840 	if ((m->m_flags & M_PKTHDR) == 0)
6841 		panic("non-M_PKTHDR is passed to pf_test6");
6842 #endif /* DIAGNOSTIC */
6843 
6844 	if (m->m_pkthdr.len < (int)sizeof(*h)) {
6845 		action = PF_DROP;
6846 		REASON_SET(&reason, PFRES_SHORT);
6847 		log = 1;
6848 		goto done;
6849 	}
6850 
6851 	/*
6852 	 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
6853 	 * so make sure pf.flags is clear.
6854 	 */
6855 	if (m->m_pkthdr.fw_flags & PF_MBUF_TAGGED)
6856 		return (PF_PASS);
6857 	m->m_pkthdr.pf.flags = 0;
6858 	/* Re-Check when updating to > 4.4 */
6859 	m->m_pkthdr.pf.statekey = NULL;
6860 
6861 	/* We do IP header normalization and packet reassembly here */
6862 	if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6863 		action = PF_DROP;
6864 		goto done;
6865 	}
6866 	m = *m0;	/* pf_normalize messes with m0 */
6867 	h = mtod(m, struct ip6_hdr *);
6868 
6869 #if 1
6870 	/*
6871 	 * we do not support jumbogram yet.  if we keep going, zero ip6_plen
6872 	 * will do something bad, so drop the packet for now.
6873 	 */
6874 	if (htons(h->ip6_plen) == 0) {
6875 		action = PF_DROP;
6876 		REASON_SET(&reason, PFRES_NORM);	/*XXX*/
6877 		goto done;
6878 	}
6879 #endif
6880 
6881 	pd.src = (struct pf_addr *)&h->ip6_src;
6882 	pd.dst = (struct pf_addr *)&h->ip6_dst;
6883 	pd.sport = pd.dport = NULL;
6884 	pd.ip_sum = NULL;
6885 	pd.proto_sum = NULL;
6886 	pd.dir = dir;
6887 	pd.sidx = (dir == PF_IN) ? 0 : 1;
6888 	pd.didx = (dir == PF_IN) ? 1 : 0;
6889 	pd.af = AF_INET6;
6890 	pd.tos = 0;
6891 	pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6892 	pd.eh = eh;
6893 
6894 	off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6895 	pd.proto = h->ip6_nxt;
6896 	do {
6897 		switch (pd.proto) {
6898 		case IPPROTO_FRAGMENT:
6899 			action = pf_test_fragment(&r, dir, kif, m, h,
6900 			    &pd, &a, &ruleset);
6901 			if (action == PF_DROP)
6902 				REASON_SET(&reason, PFRES_FRAG);
6903 			goto done;
6904 		case IPPROTO_ROUTING: {
6905 			struct ip6_rthdr rthdr;
6906 
6907 			if (rh_cnt++) {
6908 				DPFPRINTF(PF_DEBUG_MISC,
6909 				    ("pf: IPv6 more than one rthdr\n"));
6910 				action = PF_DROP;
6911 				REASON_SET(&reason, PFRES_IPOPTIONS);
6912 				log = 1;
6913 				goto done;
6914 			}
6915 			if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6916 			    &reason, pd.af)) {
6917 				DPFPRINTF(PF_DEBUG_MISC,
6918 				    ("pf: IPv6 short rthdr\n"));
6919 				action = PF_DROP;
6920 				REASON_SET(&reason, PFRES_SHORT);
6921 				log = 1;
6922 				goto done;
6923 			}
6924 			if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6925 				DPFPRINTF(PF_DEBUG_MISC,
6926 				    ("pf: IPv6 rthdr0\n"));
6927 				action = PF_DROP;
6928 				REASON_SET(&reason, PFRES_IPOPTIONS);
6929 				log = 1;
6930 				goto done;
6931 			}
6932 			/* FALLTHROUGH */
6933 		}
6934 		case IPPROTO_AH:
6935 		case IPPROTO_HOPOPTS:
6936 		case IPPROTO_DSTOPTS: {
6937 			/* get next header and header length */
6938 			struct ip6_ext	opt6;
6939 
6940 			if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6941 			    NULL, &reason, pd.af)) {
6942 				DPFPRINTF(PF_DEBUG_MISC,
6943 				    ("pf: IPv6 short opt\n"));
6944 				action = PF_DROP;
6945 				log = 1;
6946 				goto done;
6947 			}
6948 			if (pd.proto == IPPROTO_AH)
6949 				off += (opt6.ip6e_len + 2) * 4;
6950 			else
6951 				off += (opt6.ip6e_len + 1) * 8;
6952 			pd.proto = opt6.ip6e_nxt;
6953 			/* goto the next header */
6954 			break;
6955 		}
6956 		default:
6957 			terminal++;
6958 			break;
6959 		}
6960 	} while (!terminal);
6961 
6962 	/* if there's no routing header, use unmodified mbuf for checksumming */
6963 	if (!n)
6964 		n = m;
6965 
6966 	switch (pd.proto) {
6967 
6968 	case IPPROTO_TCP: {
6969 		struct tcphdr	th;
6970 
6971 		pd.hdr.tcp = &th;
6972 		if (!pf_pull_hdr(m, off, &th, sizeof(th),
6973 		    &action, &reason, AF_INET6)) {
6974 			log = action != PF_PASS;
6975 			goto done;
6976 		}
6977 		pd.p_len = pd.tot_len - off - (th.th_off << 2);
6978 		action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6979 		if (action == PF_DROP)
6980 			goto done;
6981 		action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6982 					   &reason);
6983 		if (action == PF_PASS) {
6984 			r = s->rule.ptr;
6985 			a = s->anchor.ptr;
6986 			log = s->log;
6987 		} else if (s == NULL) {
6988 			action = pf_test_rule(&r, &s, dir, kif,
6989 					      m, off, h, &pd, &a,
6990 					      &ruleset, NULL, inp);
6991 		}
6992 		break;
6993 	}
6994 
6995 	case IPPROTO_UDP: {
6996 		struct udphdr	uh;
6997 
6998 		pd.hdr.udp = &uh;
6999 		if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
7000 		    &action, &reason, AF_INET6)) {
7001 			log = action != PF_PASS;
7002 			goto done;
7003 		}
7004 		if (uh.uh_dport == 0 ||
7005 		    ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
7006 		    ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
7007 			action = PF_DROP;
7008 			REASON_SET(&reason, PFRES_SHORT);
7009 			goto done;
7010 		}
7011 		action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
7012 		if (action == PF_PASS) {
7013 			r = s->rule.ptr;
7014 			a = s->anchor.ptr;
7015 			log = s->log;
7016 		} else if (s == NULL) {
7017 			action = pf_test_rule(&r, &s, dir, kif,
7018 					      m, off, h, &pd, &a,
7019 					      &ruleset, NULL, inp);
7020 		}
7021 		break;
7022 	}
7023 
7024 	case IPPROTO_ICMPV6: {
7025 		struct icmp6_hdr	ih;
7026 
7027 		pd.hdr.icmp6 = &ih;
7028 		if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
7029 		    &action, &reason, AF_INET6)) {
7030 			log = action != PF_PASS;
7031 			goto done;
7032 		}
7033 		action = pf_test_state_icmp(&s, dir, kif,
7034 					    m, off, h, &pd, &reason);
7035 		if (action == PF_PASS) {
7036 			r = s->rule.ptr;
7037 			a = s->anchor.ptr;
7038 			log = s->log;
7039 		} else if (s == NULL) {
7040 			action = pf_test_rule(&r, &s, dir, kif,
7041 					      m, off, h, &pd, &a,
7042 					      &ruleset, NULL, inp);
7043 		}
7044 		break;
7045 	}
7046 
7047 	default:
7048 		action = pf_test_state_other(&s, dir, kif, m, &pd);
7049 		if (action == PF_PASS) {
7050 			r = s->rule.ptr;
7051 			a = s->anchor.ptr;
7052 			log = s->log;
7053 		} else if (s == NULL) {
7054 			action = pf_test_rule(&r, &s, dir, kif, m, off, h,
7055 					      &pd, &a, &ruleset, NULL, inp);
7056 		}
7057 		break;
7058 	}
7059 
7060 done:
7061 	if (n != m) {
7062 		m_freem(n);
7063 		n = NULL;
7064 	}
7065 
7066 	/* handle dangerous IPv6 extension headers. */
7067 	if (action == PF_PASS && rh_cnt &&
7068 	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
7069 		action = PF_DROP;
7070 		REASON_SET(&reason, PFRES_IPOPTIONS);
7071 		log = 1;
7072 		DPFPRINTF(PF_DEBUG_MISC,
7073 		    ("pf: dropping packet with dangerous v6 headers\n"));
7074 	}
7075 
7076 	if ((s && s->tag) || r->rtableid)
7077 		pf_tag_packet(m, s ? s->tag : 0, r->rtableid);
7078 
7079 #if 0
7080 	if (dir == PF_IN && s && s->key[PF_SK_STACK])
7081 		m->m_pkthdr.pf.statekey = s->key[PF_SK_STACK];
7082 #endif
7083 
7084 #ifdef ALTQ
7085 	/*
7086 	 * Generate a hash code and qid request for ALTQ.  A qid of 0
7087 	 * is allowed and will cause altq to select the default queue.
7088 	 */
7089 	if (action == PF_PASS) {
7090 		m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
7091 		if (pd.tos & IPTOS_LOWDELAY)
7092 			m->m_pkthdr.pf.qid = r->pqid;
7093 		else
7094 			m->m_pkthdr.pf.qid = r->qid;
7095 		m->m_pkthdr.pf.ecn_af = AF_INET6;
7096 		m->m_pkthdr.pf.hdr = h;
7097 		if (s) {
7098 			/* for fairq */
7099 			m->m_pkthdr.pf.state_hash = s->hash;
7100 			m->m_pkthdr.pf.flags |= PF_TAG_STATE_HASHED;
7101 		}
7102 	}
7103 #endif /* ALTQ */
7104 
7105 	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
7106 	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
7107 	    (s->nat_rule.ptr->action == PF_RDR ||
7108 	    s->nat_rule.ptr->action == PF_BINAT) &&
7109 	    IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
7110 		m->m_pkthdr.pf.flags |= PF_TAG_TRANSLATE_LOCALHOST;
7111 
7112 	if (dir == PF_IN && action == PF_PASS && r->divert.port) {
7113 		struct pf_divert *divert;
7114 
7115 		if ((divert = pf_get_divert(m))) {
7116 			m->m_pkthdr.pf.flags |= PF_TAG_DIVERTED;
7117 			divert->port = r->divert.port;
7118 			divert->addr.ipv6 = r->divert.addr.v6;
7119 		}
7120 	}
7121 
7122 	if (log) {
7123 		struct pf_rule *lr;
7124 
7125 		if (s != NULL && s->nat_rule.ptr != NULL &&
7126 		    s->nat_rule.ptr->log & PF_LOG_ALL)
7127 			lr = s->nat_rule.ptr;
7128 		else
7129 			lr = r;
7130 		PFLOG_PACKET(kif, h, m, AF_INET6, dir, reason, lr, a, ruleset,
7131 		    &pd);
7132 	}
7133 
7134 	kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
7135 	kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
7136 
7137 	if (action == PF_PASS || r->action == PF_DROP) {
7138 		dirndx = (dir == PF_OUT);
7139 		r->packets[dirndx]++;
7140 		r->bytes[dirndx] += pd.tot_len;
7141 		if (a != NULL) {
7142 			a->packets[dirndx]++;
7143 			a->bytes[dirndx] += pd.tot_len;
7144 		}
7145 		if (s != NULL) {
7146 			if (s->nat_rule.ptr != NULL) {
7147 				s->nat_rule.ptr->packets[dirndx]++;
7148 				s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
7149 			}
7150 			if (s->src_node != NULL) {
7151 				s->src_node->packets[dirndx]++;
7152 				s->src_node->bytes[dirndx] += pd.tot_len;
7153 			}
7154 			if (s->nat_src_node != NULL) {
7155 				s->nat_src_node->packets[dirndx]++;
7156 				s->nat_src_node->bytes[dirndx] += pd.tot_len;
7157 			}
7158 			dirndx = (dir == s->direction) ? 0 : 1;
7159 			s->packets[dirndx]++;
7160 			s->bytes[dirndx] += pd.tot_len;
7161 		}
7162 		tr = r;
7163 		nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
7164 		if (nr != NULL && r == &pf_default_rule)
7165 			tr = nr;
7166 		if (tr->src.addr.type == PF_ADDR_TABLE)
7167 			pfr_update_stats(tr->src.addr.p.tbl,
7168 			    (s == NULL) ? pd.src :
7169 			    &s->key[(s->direction == PF_IN)]->addr[0],
7170 			    pd.af, pd.tot_len, dir == PF_OUT,
7171 			    r->action == PF_PASS, tr->src.neg);
7172 		if (tr->dst.addr.type == PF_ADDR_TABLE)
7173 			pfr_update_stats(tr->dst.addr.p.tbl,
7174 			    (s == NULL) ? pd.dst :
7175 			    &s->key[(s->direction == PF_IN)]->addr[1],
7176 			    pd.af, pd.tot_len, dir == PF_OUT,
7177 			    r->action == PF_PASS, tr->dst.neg);
7178 	}
7179 
7180 
7181 	if (action == PF_SYNPROXY_DROP) {
7182 		m_freem(*m0);
7183 		*m0 = NULL;
7184 		action = PF_PASS;
7185 	} else if (r->rt)
7186 		/* pf_route6 can free the mbuf causing *m0 to become NULL */
7187 		pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);
7188 
7189 	return (action);
7190 }
7191 #endif /* INET6 */
7192 
7193 int
7194 pf_check_congestion(struct ifqueue *ifq)
7195 {
7196 		return (0);
7197 }
7198