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