xref: /freebsd/sys/netpfil/pf/pf.c (revision f5463265955b829775bbb32e1fd0bc11dafc36ce)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2001 Daniel Hartmeier
5  * Copyright (c) 2002 - 2008 Henning Brauer
6  * Copyright (c) 2012 Gleb Smirnoff <glebius@FreeBSD.org>
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  *    - Redistributions of source code must retain the above copyright
14  *      notice, this list of conditions and the following disclaimer.
15  *    - Redistributions in binary form must reproduce the above
16  *      copyright notice, this list of conditions and the following
17  *      disclaimer in the documentation and/or other materials provided
18  *      with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  *
33  * Effort sponsored in part by the Defense Advanced Research Projects
34  * Agency (DARPA) and Air Force Research Laboratory, Air Force
35  * Materiel Command, USAF, under agreement number F30602-01-2-0537.
36  *
37  *	$OpenBSD: pf.c,v 1.634 2009/02/27 12:37:45 henning Exp $
38  */
39 
40 #include <sys/cdefs.h>
41 #include "opt_bpf.h"
42 #include "opt_inet.h"
43 #include "opt_inet6.h"
44 #include "opt_pf.h"
45 #include "opt_sctp.h"
46 
47 #include <sys/param.h>
48 #include <sys/bus.h>
49 #include <sys/endian.h>
50 #include <sys/gsb_crc32.h>
51 #include <sys/hash.h>
52 #include <sys/interrupt.h>
53 #include <sys/kernel.h>
54 #include <sys/kthread.h>
55 #include <sys/limits.h>
56 #include <sys/mbuf.h>
57 #include <sys/md5.h>
58 #include <sys/random.h>
59 #include <sys/refcount.h>
60 #include <sys/sdt.h>
61 #include <sys/socket.h>
62 #include <sys/sysctl.h>
63 #include <sys/taskqueue.h>
64 #include <sys/ucred.h>
65 
66 #include <net/if.h>
67 #include <net/if_var.h>
68 #include <net/if_private.h>
69 #include <net/if_types.h>
70 #include <net/if_vlan_var.h>
71 #include <net/route.h>
72 #include <net/route/nhop.h>
73 #include <net/vnet.h>
74 
75 #include <net/pfil.h>
76 #include <net/pfvar.h>
77 #include <net/if_pflog.h>
78 #include <net/if_pfsync.h>
79 
80 #include <netinet/in_pcb.h>
81 #include <netinet/in_var.h>
82 #include <netinet/in_fib.h>
83 #include <netinet/ip.h>
84 #include <netinet/ip_fw.h>
85 #include <netinet/ip_icmp.h>
86 #include <netinet/icmp_var.h>
87 #include <netinet/ip_var.h>
88 #include <netinet/tcp.h>
89 #include <netinet/tcp_fsm.h>
90 #include <netinet/tcp_seq.h>
91 #include <netinet/tcp_timer.h>
92 #include <netinet/tcp_var.h>
93 #include <netinet/udp.h>
94 #include <netinet/udp_var.h>
95 
96 /* dummynet */
97 #include <netinet/ip_dummynet.h>
98 #include <netinet/ip_fw.h>
99 #include <netpfil/ipfw/dn_heap.h>
100 #include <netpfil/ipfw/ip_fw_private.h>
101 #include <netpfil/ipfw/ip_dn_private.h>
102 
103 #ifdef INET6
104 #include <netinet/ip6.h>
105 #include <netinet/icmp6.h>
106 #include <netinet6/nd6.h>
107 #include <netinet6/ip6_var.h>
108 #include <netinet6/in6_pcb.h>
109 #include <netinet6/in6_fib.h>
110 #include <netinet6/scope6_var.h>
111 #endif /* INET6 */
112 
113 #include <netinet/sctp_header.h>
114 #include <netinet/sctp_crc32.h>
115 
116 #include <machine/in_cksum.h>
117 #include <security/mac/mac_framework.h>
118 
119 #define	DPFPRINTF(n, x)	if (V_pf_status.debug >= (n)) printf x
120 
121 SDT_PROVIDER_DEFINE(pf);
122 SDT_PROBE_DEFINE4(pf, ip, test, done, "int", "int", "struct pf_krule *",
123     "struct pf_kstate *");
124 SDT_PROBE_DEFINE4(pf, ip, test6, done, "int", "int", "struct pf_krule *",
125     "struct pf_kstate *");
126 SDT_PROBE_DEFINE5(pf, ip, state, lookup, "struct pfi_kkif *",
127     "struct pf_state_key_cmp *", "int", "struct pf_pdesc *",
128     "struct pf_kstate *");
129 SDT_PROBE_DEFINE4(pf, sctp, multihome, test, "struct pfi_kkif *",
130     "struct pf_krule *", "struct mbuf *", "int");
131 
132 SDT_PROBE_DEFINE3(pf, eth, test_rule, entry, "int", "struct ifnet *",
133     "struct mbuf *");
134 SDT_PROBE_DEFINE2(pf, eth, test_rule, test, "int", "struct pf_keth_rule *");
135 SDT_PROBE_DEFINE3(pf, eth, test_rule, mismatch,
136     "int", "struct pf_keth_rule *", "char *");
137 SDT_PROBE_DEFINE2(pf, eth, test_rule, match, "int", "struct pf_keth_rule *");
138 SDT_PROBE_DEFINE2(pf, eth, test_rule, final_match,
139     "int", "struct pf_keth_rule *");
140 SDT_PROBE_DEFINE2(pf, purge, state, rowcount, "int", "size_t");
141 
142 /*
143  * Global variables
144  */
145 
146 /* state tables */
147 VNET_DEFINE(struct pf_altqqueue,	 pf_altqs[4]);
148 VNET_DEFINE(struct pf_kpalist,		 pf_pabuf);
149 VNET_DEFINE(struct pf_altqqueue *,	 pf_altqs_active);
150 VNET_DEFINE(struct pf_altqqueue *,	 pf_altq_ifs_active);
151 VNET_DEFINE(struct pf_altqqueue *,	 pf_altqs_inactive);
152 VNET_DEFINE(struct pf_altqqueue *,	 pf_altq_ifs_inactive);
153 VNET_DEFINE(struct pf_kstatus,		 pf_status);
154 
155 VNET_DEFINE(u_int32_t,			 ticket_altqs_active);
156 VNET_DEFINE(u_int32_t,			 ticket_altqs_inactive);
157 VNET_DEFINE(int,			 altqs_inactive_open);
158 VNET_DEFINE(u_int32_t,			 ticket_pabuf);
159 
160 VNET_DEFINE(MD5_CTX,			 pf_tcp_secret_ctx);
161 #define	V_pf_tcp_secret_ctx		 VNET(pf_tcp_secret_ctx)
162 VNET_DEFINE(u_char,			 pf_tcp_secret[16]);
163 #define	V_pf_tcp_secret			 VNET(pf_tcp_secret)
164 VNET_DEFINE(int,			 pf_tcp_secret_init);
165 #define	V_pf_tcp_secret_init		 VNET(pf_tcp_secret_init)
166 VNET_DEFINE(int,			 pf_tcp_iss_off);
167 #define	V_pf_tcp_iss_off		 VNET(pf_tcp_iss_off)
168 VNET_DECLARE(int,			 pf_vnet_active);
169 #define	V_pf_vnet_active		 VNET(pf_vnet_active)
170 
171 VNET_DEFINE_STATIC(uint32_t, pf_purge_idx);
172 #define V_pf_purge_idx	VNET(pf_purge_idx)
173 
174 #ifdef PF_WANT_32_TO_64_COUNTER
175 VNET_DEFINE_STATIC(uint32_t, pf_counter_periodic_iter);
176 #define	V_pf_counter_periodic_iter	VNET(pf_counter_periodic_iter)
177 
178 VNET_DEFINE(struct allrulelist_head, pf_allrulelist);
179 VNET_DEFINE(size_t, pf_allrulecount);
180 VNET_DEFINE(struct pf_krule *, pf_rulemarker);
181 #endif
182 
183 struct pf_sctp_endpoint;
184 RB_HEAD(pf_sctp_endpoints, pf_sctp_endpoint);
185 struct pf_sctp_source {
186 	sa_family_t			af;
187 	struct pf_addr			addr;
188 	TAILQ_ENTRY(pf_sctp_source)	entry;
189 };
190 TAILQ_HEAD(pf_sctp_sources, pf_sctp_source);
191 struct pf_sctp_endpoint
192 {
193 	uint32_t		 v_tag;
194 	struct pf_sctp_sources	 sources;
195 	RB_ENTRY(pf_sctp_endpoint)	entry;
196 };
197 static int
198 pf_sctp_endpoint_compare(struct pf_sctp_endpoint *a, struct pf_sctp_endpoint *b)
199 {
200 	return (a->v_tag - b->v_tag);
201 }
202 RB_PROTOTYPE(pf_sctp_endpoints, pf_sctp_endpoint, entry, pf_sctp_endpoint_compare);
203 RB_GENERATE(pf_sctp_endpoints, pf_sctp_endpoint, entry, pf_sctp_endpoint_compare);
204 VNET_DEFINE_STATIC(struct pf_sctp_endpoints, pf_sctp_endpoints);
205 #define V_pf_sctp_endpoints	VNET(pf_sctp_endpoints)
206 static struct mtx_padalign pf_sctp_endpoints_mtx;
207 MTX_SYSINIT(pf_sctp_endpoints_mtx, &pf_sctp_endpoints_mtx, "SCTP endpoints", MTX_DEF);
208 #define	PF_SCTP_ENDPOINTS_LOCK()	mtx_lock(&pf_sctp_endpoints_mtx)
209 #define	PF_SCTP_ENDPOINTS_UNLOCK()	mtx_unlock(&pf_sctp_endpoints_mtx)
210 
211 /*
212  * Queue for pf_intr() sends.
213  */
214 static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
215 struct pf_send_entry {
216 	STAILQ_ENTRY(pf_send_entry)	pfse_next;
217 	struct mbuf			*pfse_m;
218 	enum {
219 		PFSE_IP,
220 		PFSE_IP6,
221 		PFSE_ICMP,
222 		PFSE_ICMP6,
223 	}				pfse_type;
224 	struct {
225 		int		type;
226 		int		code;
227 		int		mtu;
228 	} icmpopts;
229 };
230 
231 STAILQ_HEAD(pf_send_head, pf_send_entry);
232 VNET_DEFINE_STATIC(struct pf_send_head, pf_sendqueue);
233 #define	V_pf_sendqueue	VNET(pf_sendqueue)
234 
235 static struct mtx_padalign pf_sendqueue_mtx;
236 MTX_SYSINIT(pf_sendqueue_mtx, &pf_sendqueue_mtx, "pf send queue", MTX_DEF);
237 #define	PF_SENDQ_LOCK()		mtx_lock(&pf_sendqueue_mtx)
238 #define	PF_SENDQ_UNLOCK()	mtx_unlock(&pf_sendqueue_mtx)
239 
240 /*
241  * Queue for pf_overload_task() tasks.
242  */
243 struct pf_overload_entry {
244 	SLIST_ENTRY(pf_overload_entry)	next;
245 	struct pf_addr  		addr;
246 	sa_family_t			af;
247 	uint8_t				dir;
248 	struct pf_krule  		*rule;
249 };
250 
251 SLIST_HEAD(pf_overload_head, pf_overload_entry);
252 VNET_DEFINE_STATIC(struct pf_overload_head, pf_overloadqueue);
253 #define V_pf_overloadqueue	VNET(pf_overloadqueue)
254 VNET_DEFINE_STATIC(struct task, pf_overloadtask);
255 #define	V_pf_overloadtask	VNET(pf_overloadtask)
256 
257 static struct mtx_padalign pf_overloadqueue_mtx;
258 MTX_SYSINIT(pf_overloadqueue_mtx, &pf_overloadqueue_mtx,
259     "pf overload/flush queue", MTX_DEF);
260 #define	PF_OVERLOADQ_LOCK()	mtx_lock(&pf_overloadqueue_mtx)
261 #define	PF_OVERLOADQ_UNLOCK()	mtx_unlock(&pf_overloadqueue_mtx)
262 
263 VNET_DEFINE(struct pf_krulequeue, pf_unlinked_rules);
264 struct mtx_padalign pf_unlnkdrules_mtx;
265 MTX_SYSINIT(pf_unlnkdrules_mtx, &pf_unlnkdrules_mtx, "pf unlinked rules",
266     MTX_DEF);
267 
268 struct sx pf_config_lock;
269 SX_SYSINIT(pf_config_lock, &pf_config_lock, "pf config");
270 
271 struct mtx_padalign pf_table_stats_lock;
272 MTX_SYSINIT(pf_table_stats_lock, &pf_table_stats_lock, "pf table stats",
273     MTX_DEF);
274 
275 VNET_DEFINE_STATIC(uma_zone_t,	pf_sources_z);
276 #define	V_pf_sources_z	VNET(pf_sources_z)
277 uma_zone_t		pf_mtag_z;
278 VNET_DEFINE(uma_zone_t,	 pf_state_z);
279 VNET_DEFINE(uma_zone_t,	 pf_state_key_z);
280 
281 VNET_DEFINE(struct unrhdr64, pf_stateid);
282 
283 static void		 pf_src_tree_remove_state(struct pf_kstate *);
284 static void		 pf_init_threshold(struct pf_threshold *, u_int32_t,
285 			    u_int32_t);
286 static void		 pf_add_threshold(struct pf_threshold *);
287 static int		 pf_check_threshold(struct pf_threshold *);
288 
289 static void		 pf_change_ap(struct mbuf *, struct pf_addr *, u_int16_t *,
290 			    u_int16_t *, u_int16_t *, struct pf_addr *,
291 			    u_int16_t, u_int8_t, sa_family_t);
292 static int		 pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
293 			    struct tcphdr *, struct pf_state_peer *);
294 static void		 pf_change_icmp(struct pf_addr *, u_int16_t *,
295 			    struct pf_addr *, struct pf_addr *, u_int16_t,
296 			    u_int16_t *, u_int16_t *, u_int16_t *,
297 			    u_int16_t *, u_int8_t, sa_family_t);
298 static void		 pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
299 			    sa_family_t, struct pf_krule *, int);
300 static void		 pf_detach_state(struct pf_kstate *);
301 static int		 pf_state_key_attach(struct pf_state_key *,
302 			    struct pf_state_key *, struct pf_kstate *);
303 static void		 pf_state_key_detach(struct pf_kstate *, int);
304 static int		 pf_state_key_ctor(void *, int, void *, int);
305 static u_int32_t	 pf_tcp_iss(struct pf_pdesc *);
306 static __inline void	 pf_dummynet_flag_remove(struct mbuf *m,
307 			    struct pf_mtag *pf_mtag);
308 static int		 pf_dummynet(struct pf_pdesc *, struct pf_kstate *,
309 			    struct pf_krule *, struct mbuf **);
310 static int		 pf_dummynet_route(struct pf_pdesc *,
311 			    struct pf_kstate *, struct pf_krule *,
312 			    struct ifnet *, struct sockaddr *, struct mbuf **);
313 static int		 pf_test_eth_rule(int, struct pfi_kkif *,
314 			    struct mbuf **);
315 static int		 pf_test_rule(struct pf_krule **, struct pf_kstate **,
316 			    struct pfi_kkif *, struct mbuf *, int,
317 			    struct pf_pdesc *, struct pf_krule **,
318 			    struct pf_kruleset **, struct inpcb *);
319 static int		 pf_create_state(struct pf_krule *, struct pf_krule *,
320 			    struct pf_krule *, struct pf_pdesc *,
321 			    struct pf_ksrc_node *, struct pf_state_key *,
322 			    struct pf_state_key *, struct mbuf *, int,
323 			    u_int16_t, u_int16_t, int *, struct pfi_kkif *,
324 			    struct pf_kstate **, int, u_int16_t, u_int16_t,
325 			    int, struct pf_krule_slist *);
326 static int		 pf_test_fragment(struct pf_krule **, struct pfi_kkif *,
327 			    struct mbuf *, void *, struct pf_pdesc *,
328 			    struct pf_krule **, struct pf_kruleset **);
329 static int		 pf_tcp_track_full(struct pf_kstate **,
330 			    struct pfi_kkif *, struct mbuf *, int,
331 			    struct pf_pdesc *, u_short *, int *);
332 static int		 pf_tcp_track_sloppy(struct pf_kstate **,
333 			    struct pf_pdesc *, u_short *);
334 static int		 pf_test_state_tcp(struct pf_kstate **,
335 			    struct pfi_kkif *, struct mbuf *, int,
336 			    void *, struct pf_pdesc *, u_short *);
337 static int		 pf_test_state_udp(struct pf_kstate **,
338 			    struct pfi_kkif *, struct mbuf *, int,
339 			    void *, struct pf_pdesc *);
340 static int		 pf_test_state_icmp(struct pf_kstate **,
341 			    struct pfi_kkif *, struct mbuf *, int,
342 			    void *, struct pf_pdesc *, u_short *);
343 static void		 pf_sctp_multihome_detach_addr(const struct pf_kstate *);
344 static void		 pf_sctp_multihome_delayed(struct pf_pdesc *, int,
345 			    struct pfi_kkif *, struct pf_kstate *, int);
346 static int		 pf_test_state_sctp(struct pf_kstate **,
347 			    struct pfi_kkif *, struct mbuf *, int,
348 			    void *, struct pf_pdesc *, u_short *);
349 static int		 pf_test_state_other(struct pf_kstate **,
350 			    struct pfi_kkif *, struct mbuf *, struct pf_pdesc *);
351 static u_int16_t	 pf_calc_mss(struct pf_addr *, sa_family_t,
352 				int, u_int16_t);
353 static int		 pf_check_proto_cksum(struct mbuf *, int, int,
354 			    u_int8_t, sa_family_t);
355 static void		 pf_print_state_parts(struct pf_kstate *,
356 			    struct pf_state_key *, struct pf_state_key *);
357 static void		 pf_patch_8(struct mbuf *, u_int16_t *, u_int8_t *, u_int8_t,
358 			    bool, u_int8_t);
359 static struct pf_kstate	*pf_find_state(struct pfi_kkif *,
360 			    struct pf_state_key_cmp *, u_int);
361 static int		 pf_src_connlimit(struct pf_kstate **);
362 static void		 pf_overload_task(void *v, int pending);
363 static u_short		 pf_insert_src_node(struct pf_ksrc_node **,
364 			    struct pf_krule *, struct pf_addr *, sa_family_t);
365 static u_int		 pf_purge_expired_states(u_int, int);
366 static void		 pf_purge_unlinked_rules(void);
367 static int		 pf_mtag_uminit(void *, int, int);
368 static void		 pf_mtag_free(struct m_tag *);
369 static void		 pf_packet_rework_nat(struct mbuf *, struct pf_pdesc *,
370 			    int, struct pf_state_key *);
371 #ifdef INET
372 static void		 pf_route(struct mbuf **, struct pf_krule *,
373 			    struct ifnet *, struct pf_kstate *,
374 			    struct pf_pdesc *, struct inpcb *);
375 #endif /* INET */
376 #ifdef INET6
377 static void		 pf_change_a6(struct pf_addr *, u_int16_t *,
378 			    struct pf_addr *, u_int8_t);
379 static void		 pf_route6(struct mbuf **, struct pf_krule *,
380 			    struct ifnet *, struct pf_kstate *,
381 			    struct pf_pdesc *, struct inpcb *);
382 #endif /* INET6 */
383 static __inline void pf_set_protostate(struct pf_kstate *, int, u_int8_t);
384 
385 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
386 
387 extern int pf_end_threads;
388 extern struct proc *pf_purge_proc;
389 
390 VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
391 
392 #define	PACKET_UNDO_NAT(_m, _pd, _off, _s)		\
393 	do {								\
394 		struct pf_state_key *nk;				\
395 		if ((pd->dir) == PF_OUT)					\
396 			nk = (_s)->key[PF_SK_STACK];			\
397 		else							\
398 			nk = (_s)->key[PF_SK_WIRE];			\
399 		pf_packet_rework_nat(_m, _pd, _off, nk);		\
400 	} while (0)
401 
402 #define	PACKET_LOOPED(pd)	((pd)->pf_mtag &&			\
403 				 (pd)->pf_mtag->flags & PF_MTAG_FLAG_PACKET_LOOPED)
404 
405 #define	STATE_LOOKUP(i, k, s, pd)					\
406 	do {								\
407 		(s) = pf_find_state((i), (k), (pd->dir));			\
408 		SDT_PROBE5(pf, ip, state, lookup, i, k, (pd->dir), pd, (s));	\
409 		if ((s) == NULL)					\
410 			return (PF_DROP);				\
411 		if (PACKET_LOOPED(pd))					\
412 			return (PF_PASS);				\
413 	} while (0)
414 
415 #define	BOUND_IFACE(r, k) \
416 	((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
417 
418 #define	STATE_INC_COUNTERS(s)						\
419 	do {								\
420 		struct pf_krule_item *mrm;				\
421 		counter_u64_add(s->rule.ptr->states_cur, 1);		\
422 		counter_u64_add(s->rule.ptr->states_tot, 1);		\
423 		if (s->anchor.ptr != NULL) {				\
424 			counter_u64_add(s->anchor.ptr->states_cur, 1);	\
425 			counter_u64_add(s->anchor.ptr->states_tot, 1);	\
426 		}							\
427 		if (s->nat_rule.ptr != NULL) {				\
428 			counter_u64_add(s->nat_rule.ptr->states_cur, 1);\
429 			counter_u64_add(s->nat_rule.ptr->states_tot, 1);\
430 		}							\
431 		SLIST_FOREACH(mrm, &s->match_rules, entry) {		\
432 			counter_u64_add(mrm->r->states_cur, 1);		\
433 			counter_u64_add(mrm->r->states_tot, 1);		\
434 		}							\
435 	} while (0)
436 
437 #define	STATE_DEC_COUNTERS(s)						\
438 	do {								\
439 		struct pf_krule_item *mrm;				\
440 		if (s->nat_rule.ptr != NULL)				\
441 			counter_u64_add(s->nat_rule.ptr->states_cur, -1);\
442 		if (s->anchor.ptr != NULL)				\
443 			counter_u64_add(s->anchor.ptr->states_cur, -1);	\
444 		counter_u64_add(s->rule.ptr->states_cur, -1);		\
445 		SLIST_FOREACH(mrm, &s->match_rules, entry)		\
446 			counter_u64_add(mrm->r->states_cur, -1);	\
447 	} while (0)
448 
449 MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
450 MALLOC_DEFINE(M_PF_RULE_ITEM, "pf_krule_item", "pf(4) rule items");
451 VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
452 VNET_DEFINE(struct pf_idhash *, pf_idhash);
453 VNET_DEFINE(struct pf_srchash *, pf_srchash);
454 
455 SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
456     "pf(4)");
457 
458 u_long	pf_hashmask;
459 u_long	pf_srchashmask;
460 static u_long	pf_hashsize;
461 static u_long	pf_srchashsize;
462 u_long	pf_ioctl_maxcount = 65535;
463 
464 SYSCTL_ULONG(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
465     &pf_hashsize, 0, "Size of pf(4) states hashtable");
466 SYSCTL_ULONG(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
467     &pf_srchashsize, 0, "Size of pf(4) source nodes hashtable");
468 SYSCTL_ULONG(_net_pf, OID_AUTO, request_maxcount, CTLFLAG_RWTUN,
469     &pf_ioctl_maxcount, 0, "Maximum number of tables, addresses, ... in a single ioctl() call");
470 
471 VNET_DEFINE(void *, pf_swi_cookie);
472 VNET_DEFINE(struct intr_event *, pf_swi_ie);
473 
474 VNET_DEFINE(uint32_t, pf_hashseed);
475 #define	V_pf_hashseed	VNET(pf_hashseed)
476 
477 static void
478 pf_sctp_checksum(struct mbuf *m, int off)
479 {
480 	uint32_t sum = 0;
481 
482 	/* Zero out the checksum, to enable recalculation. */
483 	m_copyback(m, off + offsetof(struct sctphdr, checksum),
484 	    sizeof(sum), (caddr_t)&sum);
485 
486 	sum = sctp_calculate_cksum(m, off);
487 
488 	m_copyback(m, off + offsetof(struct sctphdr, checksum),
489 	    sizeof(sum), (caddr_t)&sum);
490 }
491 
492 int
493 pf_addr_cmp(struct pf_addr *a, struct pf_addr *b, sa_family_t af)
494 {
495 
496 	switch (af) {
497 #ifdef INET
498 	case AF_INET:
499 		if (a->addr32[0] > b->addr32[0])
500 			return (1);
501 		if (a->addr32[0] < b->addr32[0])
502 			return (-1);
503 		break;
504 #endif /* INET */
505 #ifdef INET6
506 	case AF_INET6:
507 		if (a->addr32[3] > b->addr32[3])
508 			return (1);
509 		if (a->addr32[3] < b->addr32[3])
510 			return (-1);
511 		if (a->addr32[2] > b->addr32[2])
512 			return (1);
513 		if (a->addr32[2] < b->addr32[2])
514 			return (-1);
515 		if (a->addr32[1] > b->addr32[1])
516 			return (1);
517 		if (a->addr32[1] < b->addr32[1])
518 			return (-1);
519 		if (a->addr32[0] > b->addr32[0])
520 			return (1);
521 		if (a->addr32[0] < b->addr32[0])
522 			return (-1);
523 		break;
524 #endif /* INET6 */
525 	default:
526 		panic("%s: unknown address family %u", __func__, af);
527 	}
528 	return (0);
529 }
530 
531 static void
532 pf_packet_rework_nat(struct mbuf *m, struct pf_pdesc *pd, int off,
533 	struct pf_state_key *nk)
534 {
535 
536 	switch (pd->proto) {
537 	case IPPROTO_TCP: {
538 		struct tcphdr *th = &pd->hdr.tcp;
539 
540 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af))
541 			pf_change_ap(m, pd->src, &th->th_sport, pd->ip_sum,
542 			    &th->th_sum, &nk->addr[pd->sidx],
543 			    nk->port[pd->sidx], 0, pd->af);
544 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af))
545 			pf_change_ap(m, pd->dst, &th->th_dport, pd->ip_sum,
546 			    &th->th_sum, &nk->addr[pd->didx],
547 			    nk->port[pd->didx], 0, pd->af);
548 		m_copyback(m, off, sizeof(*th), (caddr_t)th);
549 		break;
550 	}
551 	case IPPROTO_UDP: {
552 		struct udphdr *uh = &pd->hdr.udp;
553 
554 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af))
555 			pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
556 			    &uh->uh_sum, &nk->addr[pd->sidx],
557 			    nk->port[pd->sidx], 1, pd->af);
558 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af))
559 			pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
560 			    &uh->uh_sum, &nk->addr[pd->didx],
561 			    nk->port[pd->didx], 1, pd->af);
562 		m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
563 		break;
564 	}
565 	case IPPROTO_SCTP: {
566 		struct sctphdr *sh = &pd->hdr.sctp;
567 		uint16_t checksum = 0;
568 
569 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af)) {
570 			pf_change_ap(m, pd->src, &sh->src_port, pd->ip_sum,
571 			    &checksum, &nk->addr[pd->sidx],
572 			    nk->port[pd->sidx], 1, pd->af);
573 		}
574 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af)) {
575 			pf_change_ap(m, pd->dst, &sh->dest_port, pd->ip_sum,
576 			    &checksum, &nk->addr[pd->didx],
577 			    nk->port[pd->didx], 1, pd->af);
578 		}
579 
580 		break;
581 	}
582 	case IPPROTO_ICMP: {
583 		struct icmp *ih = &pd->hdr.icmp;
584 
585 		if (nk->port[pd->sidx] != ih->icmp_id) {
586 			pd->hdr.icmp.icmp_cksum = pf_cksum_fixup(
587 			    ih->icmp_cksum, ih->icmp_id,
588 			    nk->port[pd->sidx], 0);
589 			ih->icmp_id = nk->port[pd->sidx];
590 			pd->sport = &ih->icmp_id;
591 
592 			m_copyback(m, off, ICMP_MINLEN, (caddr_t)ih);
593 		}
594 		/* FALLTHROUGH */
595 	}
596 	default:
597 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af)) {
598 			switch (pd->af) {
599 			case AF_INET:
600 				pf_change_a(&pd->src->v4.s_addr,
601 				    pd->ip_sum, nk->addr[pd->sidx].v4.s_addr,
602 				    0);
603 				break;
604 			case AF_INET6:
605 				PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
606 				break;
607 			}
608 		}
609 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af)) {
610 			switch (pd->af) {
611 			case AF_INET:
612 				pf_change_a(&pd->dst->v4.s_addr,
613 				    pd->ip_sum, nk->addr[pd->didx].v4.s_addr,
614 				    0);
615 				break;
616 			case AF_INET6:
617 				PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
618 				break;
619 			}
620 		}
621 		break;
622 	}
623 }
624 
625 static __inline uint32_t
626 pf_hashkey(struct pf_state_key *sk)
627 {
628 	uint32_t h;
629 
630 	h = murmur3_32_hash32((uint32_t *)sk,
631 	    sizeof(struct pf_state_key_cmp)/sizeof(uint32_t),
632 	    V_pf_hashseed);
633 
634 	return (h & pf_hashmask);
635 }
636 
637 static __inline uint32_t
638 pf_hashsrc(struct pf_addr *addr, sa_family_t af)
639 {
640 	uint32_t h;
641 
642 	switch (af) {
643 	case AF_INET:
644 		h = murmur3_32_hash32((uint32_t *)&addr->v4,
645 		    sizeof(addr->v4)/sizeof(uint32_t), V_pf_hashseed);
646 		break;
647 	case AF_INET6:
648 		h = murmur3_32_hash32((uint32_t *)&addr->v6,
649 		    sizeof(addr->v6)/sizeof(uint32_t), V_pf_hashseed);
650 		break;
651 	default:
652 		panic("%s: unknown address family %u", __func__, af);
653 	}
654 
655 	return (h & pf_srchashmask);
656 }
657 
658 #ifdef ALTQ
659 static int
660 pf_state_hash(struct pf_kstate *s)
661 {
662 	u_int32_t hv = (intptr_t)s / sizeof(*s);
663 
664 	hv ^= crc32(&s->src, sizeof(s->src));
665 	hv ^= crc32(&s->dst, sizeof(s->dst));
666 	if (hv == 0)
667 		hv = 1;
668 	return (hv);
669 }
670 #endif
671 
672 static __inline void
673 pf_set_protostate(struct pf_kstate *s, int which, u_int8_t newstate)
674 {
675 	if (which == PF_PEER_DST || which == PF_PEER_BOTH)
676 		s->dst.state = newstate;
677 	if (which == PF_PEER_DST)
678 		return;
679 	if (s->src.state == newstate)
680 		return;
681 	if (s->creatorid == V_pf_status.hostid &&
682 	    s->key[PF_SK_STACK] != NULL &&
683 	    s->key[PF_SK_STACK]->proto == IPPROTO_TCP &&
684 	    !(TCPS_HAVEESTABLISHED(s->src.state) ||
685 	    s->src.state == TCPS_CLOSED) &&
686 	    (TCPS_HAVEESTABLISHED(newstate) || newstate == TCPS_CLOSED))
687 		atomic_add_32(&V_pf_status.states_halfopen, -1);
688 
689 	s->src.state = newstate;
690 }
691 
692 #ifdef INET6
693 void
694 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
695 {
696 	switch (af) {
697 #ifdef INET
698 	case AF_INET:
699 		dst->addr32[0] = src->addr32[0];
700 		break;
701 #endif /* INET */
702 	case AF_INET6:
703 		dst->addr32[0] = src->addr32[0];
704 		dst->addr32[1] = src->addr32[1];
705 		dst->addr32[2] = src->addr32[2];
706 		dst->addr32[3] = src->addr32[3];
707 		break;
708 	}
709 }
710 #endif /* INET6 */
711 
712 static void
713 pf_init_threshold(struct pf_threshold *threshold,
714     u_int32_t limit, u_int32_t seconds)
715 {
716 	threshold->limit = limit * PF_THRESHOLD_MULT;
717 	threshold->seconds = seconds;
718 	threshold->count = 0;
719 	threshold->last = time_uptime;
720 }
721 
722 static void
723 pf_add_threshold(struct pf_threshold *threshold)
724 {
725 	u_int32_t t = time_uptime, diff = t - threshold->last;
726 
727 	if (diff >= threshold->seconds)
728 		threshold->count = 0;
729 	else
730 		threshold->count -= threshold->count * diff /
731 		    threshold->seconds;
732 	threshold->count += PF_THRESHOLD_MULT;
733 	threshold->last = t;
734 }
735 
736 static int
737 pf_check_threshold(struct pf_threshold *threshold)
738 {
739 	return (threshold->count > threshold->limit);
740 }
741 
742 static int
743 pf_src_connlimit(struct pf_kstate **state)
744 {
745 	struct pf_overload_entry *pfoe;
746 	int bad = 0;
747 
748 	PF_STATE_LOCK_ASSERT(*state);
749 	/*
750 	 * XXXKS: The src node is accessed unlocked!
751 	 * PF_SRC_NODE_LOCK_ASSERT((*state)->src_node);
752 	 */
753 
754 	(*state)->src_node->conn++;
755 	(*state)->src.tcp_est = 1;
756 	pf_add_threshold(&(*state)->src_node->conn_rate);
757 
758 	if ((*state)->rule.ptr->max_src_conn &&
759 	    (*state)->rule.ptr->max_src_conn <
760 	    (*state)->src_node->conn) {
761 		counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONN], 1);
762 		bad++;
763 	}
764 
765 	if ((*state)->rule.ptr->max_src_conn_rate.limit &&
766 	    pf_check_threshold(&(*state)->src_node->conn_rate)) {
767 		counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONNRATE], 1);
768 		bad++;
769 	}
770 
771 	if (!bad)
772 		return (0);
773 
774 	/* Kill this state. */
775 	(*state)->timeout = PFTM_PURGE;
776 	pf_set_protostate(*state, PF_PEER_BOTH, TCPS_CLOSED);
777 
778 	if ((*state)->rule.ptr->overload_tbl == NULL)
779 		return (1);
780 
781 	/* Schedule overloading and flushing task. */
782 	pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
783 	if (pfoe == NULL)
784 		return (1);	/* too bad :( */
785 
786 	bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
787 	pfoe->af = (*state)->key[PF_SK_WIRE]->af;
788 	pfoe->rule = (*state)->rule.ptr;
789 	pfoe->dir = (*state)->direction;
790 	PF_OVERLOADQ_LOCK();
791 	SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
792 	PF_OVERLOADQ_UNLOCK();
793 	taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
794 
795 	return (1);
796 }
797 
798 static void
799 pf_overload_task(void *v, int pending)
800 {
801 	struct pf_overload_head queue;
802 	struct pfr_addr p;
803 	struct pf_overload_entry *pfoe, *pfoe1;
804 	uint32_t killed = 0;
805 
806 	CURVNET_SET((struct vnet *)v);
807 
808 	PF_OVERLOADQ_LOCK();
809 	queue = V_pf_overloadqueue;
810 	SLIST_INIT(&V_pf_overloadqueue);
811 	PF_OVERLOADQ_UNLOCK();
812 
813 	bzero(&p, sizeof(p));
814 	SLIST_FOREACH(pfoe, &queue, next) {
815 		counter_u64_add(V_pf_status.lcounters[LCNT_OVERLOAD_TABLE], 1);
816 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
817 			printf("%s: blocking address ", __func__);
818 			pf_print_host(&pfoe->addr, 0, pfoe->af);
819 			printf("\n");
820 		}
821 
822 		p.pfra_af = pfoe->af;
823 		switch (pfoe->af) {
824 #ifdef INET
825 		case AF_INET:
826 			p.pfra_net = 32;
827 			p.pfra_ip4addr = pfoe->addr.v4;
828 			break;
829 #endif
830 #ifdef INET6
831 		case AF_INET6:
832 			p.pfra_net = 128;
833 			p.pfra_ip6addr = pfoe->addr.v6;
834 			break;
835 #endif
836 		}
837 
838 		PF_RULES_WLOCK();
839 		pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
840 		PF_RULES_WUNLOCK();
841 	}
842 
843 	/*
844 	 * Remove those entries, that don't need flushing.
845 	 */
846 	SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
847 		if (pfoe->rule->flush == 0) {
848 			SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
849 			free(pfoe, M_PFTEMP);
850 		} else
851 			counter_u64_add(
852 			    V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH], 1);
853 
854 	/* If nothing to flush, return. */
855 	if (SLIST_EMPTY(&queue)) {
856 		CURVNET_RESTORE();
857 		return;
858 	}
859 
860 	for (int i = 0; i <= pf_hashmask; i++) {
861 		struct pf_idhash *ih = &V_pf_idhash[i];
862 		struct pf_state_key *sk;
863 		struct pf_kstate *s;
864 
865 		PF_HASHROW_LOCK(ih);
866 		LIST_FOREACH(s, &ih->states, entry) {
867 		    sk = s->key[PF_SK_WIRE];
868 		    SLIST_FOREACH(pfoe, &queue, next)
869 			if (sk->af == pfoe->af &&
870 			    ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
871 			    pfoe->rule == s->rule.ptr) &&
872 			    ((pfoe->dir == PF_OUT &&
873 			    PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
874 			    (pfoe->dir == PF_IN &&
875 			    PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
876 				s->timeout = PFTM_PURGE;
877 				pf_set_protostate(s, PF_PEER_BOTH, TCPS_CLOSED);
878 				killed++;
879 			}
880 		}
881 		PF_HASHROW_UNLOCK(ih);
882 	}
883 	SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
884 		free(pfoe, M_PFTEMP);
885 	if (V_pf_status.debug >= PF_DEBUG_MISC)
886 		printf("%s: %u states killed", __func__, killed);
887 
888 	CURVNET_RESTORE();
889 }
890 
891 /*
892  * Can return locked on failure, so that we can consistently
893  * allocate and insert a new one.
894  */
895 struct pf_ksrc_node *
896 pf_find_src_node(struct pf_addr *src, struct pf_krule *rule, sa_family_t af,
897 	struct pf_srchash **sh, bool returnlocked)
898 {
899 	struct pf_ksrc_node *n;
900 
901 	counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_SEARCH], 1);
902 
903 	*sh = &V_pf_srchash[pf_hashsrc(src, af)];
904 	PF_HASHROW_LOCK(*sh);
905 	LIST_FOREACH(n, &(*sh)->nodes, entry)
906 		if (n->rule.ptr == rule && n->af == af &&
907 		    ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
908 		    (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
909 			break;
910 
911 	if (n != NULL) {
912 		n->states++;
913 		PF_HASHROW_UNLOCK(*sh);
914 	} else if (returnlocked == false)
915 		PF_HASHROW_UNLOCK(*sh);
916 
917 	return (n);
918 }
919 
920 static void
921 pf_free_src_node(struct pf_ksrc_node *sn)
922 {
923 
924 	for (int i = 0; i < 2; i++) {
925 		counter_u64_free(sn->bytes[i]);
926 		counter_u64_free(sn->packets[i]);
927 	}
928 	uma_zfree(V_pf_sources_z, sn);
929 }
930 
931 static u_short
932 pf_insert_src_node(struct pf_ksrc_node **sn, struct pf_krule *rule,
933     struct pf_addr *src, sa_family_t af)
934 {
935 	u_short			 reason = 0;
936 	struct pf_srchash	*sh = NULL;
937 
938 	KASSERT((rule->rule_flag & PFRULE_SRCTRACK ||
939 	    rule->rpool.opts & PF_POOL_STICKYADDR),
940 	    ("%s for non-tracking rule %p", __func__, rule));
941 
942 	if (*sn == NULL)
943 		*sn = pf_find_src_node(src, rule, af, &sh, true);
944 
945 	if (*sn == NULL) {
946 		PF_HASHROW_ASSERT(sh);
947 
948 		if (rule->max_src_nodes &&
949 		    counter_u64_fetch(rule->src_nodes) >= rule->max_src_nodes) {
950 			counter_u64_add(V_pf_status.lcounters[LCNT_SRCNODES], 1);
951 			PF_HASHROW_UNLOCK(sh);
952 			reason = PFRES_SRCLIMIT;
953 			goto done;
954 		}
955 
956 		(*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
957 		if ((*sn) == NULL) {
958 			PF_HASHROW_UNLOCK(sh);
959 			reason = PFRES_MEMORY;
960 			goto done;
961 		}
962 
963 		for (int i = 0; i < 2; i++) {
964 			(*sn)->bytes[i] = counter_u64_alloc(M_NOWAIT);
965 			(*sn)->packets[i] = counter_u64_alloc(M_NOWAIT);
966 
967 			if ((*sn)->bytes[i] == NULL || (*sn)->packets[i] == NULL) {
968 				pf_free_src_node(*sn);
969 				PF_HASHROW_UNLOCK(sh);
970 				reason = PFRES_MEMORY;
971 				goto done;
972 			}
973 		}
974 
975 		pf_init_threshold(&(*sn)->conn_rate,
976 		    rule->max_src_conn_rate.limit,
977 		    rule->max_src_conn_rate.seconds);
978 
979 		MPASS((*sn)->lock == NULL);
980 		(*sn)->lock = &sh->lock;
981 
982 		(*sn)->af = af;
983 		(*sn)->rule.ptr = rule;
984 		PF_ACPY(&(*sn)->addr, src, af);
985 		LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
986 		(*sn)->creation = time_uptime;
987 		(*sn)->ruletype = rule->action;
988 		(*sn)->states = 1;
989 		if ((*sn)->rule.ptr != NULL)
990 			counter_u64_add((*sn)->rule.ptr->src_nodes, 1);
991 		PF_HASHROW_UNLOCK(sh);
992 		counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_INSERT], 1);
993 	} else {
994 		if (rule->max_src_states &&
995 		    (*sn)->states >= rule->max_src_states) {
996 			counter_u64_add(V_pf_status.lcounters[LCNT_SRCSTATES],
997 			    1);
998 			reason = PFRES_SRCLIMIT;
999 			goto done;
1000 		}
1001 	}
1002 done:
1003 	return (reason);
1004 }
1005 
1006 void
1007 pf_unlink_src_node(struct pf_ksrc_node *src)
1008 {
1009 	PF_SRC_NODE_LOCK_ASSERT(src);
1010 
1011 	LIST_REMOVE(src, entry);
1012 	if (src->rule.ptr)
1013 		counter_u64_add(src->rule.ptr->src_nodes, -1);
1014 }
1015 
1016 u_int
1017 pf_free_src_nodes(struct pf_ksrc_node_list *head)
1018 {
1019 	struct pf_ksrc_node *sn, *tmp;
1020 	u_int count = 0;
1021 
1022 	LIST_FOREACH_SAFE(sn, head, entry, tmp) {
1023 		pf_free_src_node(sn);
1024 		count++;
1025 	}
1026 
1027 	counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], count);
1028 
1029 	return (count);
1030 }
1031 
1032 void
1033 pf_mtag_initialize(void)
1034 {
1035 
1036 	pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
1037 	    sizeof(struct pf_mtag), NULL, NULL, pf_mtag_uminit, NULL,
1038 	    UMA_ALIGN_PTR, 0);
1039 }
1040 
1041 /* Per-vnet data storage structures initialization. */
1042 void
1043 pf_initialize(void)
1044 {
1045 	struct pf_keyhash	*kh;
1046 	struct pf_idhash	*ih;
1047 	struct pf_srchash	*sh;
1048 	u_int i;
1049 
1050 	if (pf_hashsize == 0 || !powerof2(pf_hashsize))
1051 		pf_hashsize = PF_HASHSIZ;
1052 	if (pf_srchashsize == 0 || !powerof2(pf_srchashsize))
1053 		pf_srchashsize = PF_SRCHASHSIZ;
1054 
1055 	V_pf_hashseed = arc4random();
1056 
1057 	/* States and state keys storage. */
1058 	V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_kstate),
1059 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1060 	V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
1061 	uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
1062 	uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
1063 
1064 	V_pf_state_key_z = uma_zcreate("pf state keys",
1065 	    sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
1066 	    UMA_ALIGN_PTR, 0);
1067 
1068 	V_pf_keyhash = mallocarray(pf_hashsize, sizeof(struct pf_keyhash),
1069 	    M_PFHASH, M_NOWAIT | M_ZERO);
1070 	V_pf_idhash = mallocarray(pf_hashsize, sizeof(struct pf_idhash),
1071 	    M_PFHASH, M_NOWAIT | M_ZERO);
1072 	if (V_pf_keyhash == NULL || V_pf_idhash == NULL) {
1073 		printf("pf: Unable to allocate memory for "
1074 		    "state_hashsize %lu.\n", pf_hashsize);
1075 
1076 		free(V_pf_keyhash, M_PFHASH);
1077 		free(V_pf_idhash, M_PFHASH);
1078 
1079 		pf_hashsize = PF_HASHSIZ;
1080 		V_pf_keyhash = mallocarray(pf_hashsize,
1081 		    sizeof(struct pf_keyhash), M_PFHASH, M_WAITOK | M_ZERO);
1082 		V_pf_idhash = mallocarray(pf_hashsize,
1083 		    sizeof(struct pf_idhash), M_PFHASH, M_WAITOK | M_ZERO);
1084 	}
1085 
1086 	pf_hashmask = pf_hashsize - 1;
1087 	for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
1088 	    i++, kh++, ih++) {
1089 		mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
1090 		mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
1091 	}
1092 
1093 	/* Source nodes. */
1094 	V_pf_sources_z = uma_zcreate("pf source nodes",
1095 	    sizeof(struct pf_ksrc_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
1096 	    0);
1097 	V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
1098 	uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
1099 	uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
1100 
1101 	V_pf_srchash = mallocarray(pf_srchashsize,
1102 	    sizeof(struct pf_srchash), M_PFHASH, M_NOWAIT | M_ZERO);
1103 	if (V_pf_srchash == NULL) {
1104 		printf("pf: Unable to allocate memory for "
1105 		    "source_hashsize %lu.\n", pf_srchashsize);
1106 
1107 		pf_srchashsize = PF_SRCHASHSIZ;
1108 		V_pf_srchash = mallocarray(pf_srchashsize,
1109 		    sizeof(struct pf_srchash), M_PFHASH, M_WAITOK | M_ZERO);
1110 	}
1111 
1112 	pf_srchashmask = pf_srchashsize - 1;
1113 	for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++)
1114 		mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
1115 
1116 	/* ALTQ */
1117 	TAILQ_INIT(&V_pf_altqs[0]);
1118 	TAILQ_INIT(&V_pf_altqs[1]);
1119 	TAILQ_INIT(&V_pf_altqs[2]);
1120 	TAILQ_INIT(&V_pf_altqs[3]);
1121 	TAILQ_INIT(&V_pf_pabuf);
1122 	V_pf_altqs_active = &V_pf_altqs[0];
1123 	V_pf_altq_ifs_active = &V_pf_altqs[1];
1124 	V_pf_altqs_inactive = &V_pf_altqs[2];
1125 	V_pf_altq_ifs_inactive = &V_pf_altqs[3];
1126 
1127 	/* Send & overload+flush queues. */
1128 	STAILQ_INIT(&V_pf_sendqueue);
1129 	SLIST_INIT(&V_pf_overloadqueue);
1130 	TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, curvnet);
1131 
1132 	/* Unlinked, but may be referenced rules. */
1133 	TAILQ_INIT(&V_pf_unlinked_rules);
1134 }
1135 
1136 void
1137 pf_mtag_cleanup(void)
1138 {
1139 
1140 	uma_zdestroy(pf_mtag_z);
1141 }
1142 
1143 void
1144 pf_cleanup(void)
1145 {
1146 	struct pf_keyhash	*kh;
1147 	struct pf_idhash	*ih;
1148 	struct pf_srchash	*sh;
1149 	struct pf_send_entry	*pfse, *next;
1150 	u_int i;
1151 
1152 	for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
1153 	    i++, kh++, ih++) {
1154 		KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
1155 		    __func__));
1156 		KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
1157 		    __func__));
1158 		mtx_destroy(&kh->lock);
1159 		mtx_destroy(&ih->lock);
1160 	}
1161 	free(V_pf_keyhash, M_PFHASH);
1162 	free(V_pf_idhash, M_PFHASH);
1163 
1164 	for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1165 		KASSERT(LIST_EMPTY(&sh->nodes),
1166 		    ("%s: source node hash not empty", __func__));
1167 		mtx_destroy(&sh->lock);
1168 	}
1169 	free(V_pf_srchash, M_PFHASH);
1170 
1171 	STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
1172 		m_freem(pfse->pfse_m);
1173 		free(pfse, M_PFTEMP);
1174 	}
1175 	MPASS(RB_EMPTY(&V_pf_sctp_endpoints));
1176 
1177 	uma_zdestroy(V_pf_sources_z);
1178 	uma_zdestroy(V_pf_state_z);
1179 	uma_zdestroy(V_pf_state_key_z);
1180 }
1181 
1182 static int
1183 pf_mtag_uminit(void *mem, int size, int how)
1184 {
1185 	struct m_tag *t;
1186 
1187 	t = (struct m_tag *)mem;
1188 	t->m_tag_cookie = MTAG_ABI_COMPAT;
1189 	t->m_tag_id = PACKET_TAG_PF;
1190 	t->m_tag_len = sizeof(struct pf_mtag);
1191 	t->m_tag_free = pf_mtag_free;
1192 
1193 	return (0);
1194 }
1195 
1196 static void
1197 pf_mtag_free(struct m_tag *t)
1198 {
1199 
1200 	uma_zfree(pf_mtag_z, t);
1201 }
1202 
1203 struct pf_mtag *
1204 pf_get_mtag(struct mbuf *m)
1205 {
1206 	struct m_tag *mtag;
1207 
1208 	if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
1209 		return ((struct pf_mtag *)(mtag + 1));
1210 
1211 	mtag = uma_zalloc(pf_mtag_z, M_NOWAIT);
1212 	if (mtag == NULL)
1213 		return (NULL);
1214 	bzero(mtag + 1, sizeof(struct pf_mtag));
1215 	m_tag_prepend(m, mtag);
1216 
1217 	return ((struct pf_mtag *)(mtag + 1));
1218 }
1219 
1220 static int
1221 pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
1222     struct pf_kstate *s)
1223 {
1224 	struct pf_keyhash	*khs, *khw, *kh;
1225 	struct pf_state_key	*sk, *cur;
1226 	struct pf_kstate	*si, *olds = NULL;
1227 	int idx;
1228 
1229 	NET_EPOCH_ASSERT();
1230 	KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1231 	KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
1232 	KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
1233 
1234 	/*
1235 	 * We need to lock hash slots of both keys. To avoid deadlock
1236 	 * we always lock the slot with lower address first. Unlock order
1237 	 * isn't important.
1238 	 *
1239 	 * We also need to lock ID hash slot before dropping key
1240 	 * locks. On success we return with ID hash slot locked.
1241 	 */
1242 
1243 	if (skw == sks) {
1244 		khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
1245 		PF_HASHROW_LOCK(khs);
1246 	} else {
1247 		khs = &V_pf_keyhash[pf_hashkey(sks)];
1248 		khw = &V_pf_keyhash[pf_hashkey(skw)];
1249 		if (khs == khw) {
1250 			PF_HASHROW_LOCK(khs);
1251 		} else if (khs < khw) {
1252 			PF_HASHROW_LOCK(khs);
1253 			PF_HASHROW_LOCK(khw);
1254 		} else {
1255 			PF_HASHROW_LOCK(khw);
1256 			PF_HASHROW_LOCK(khs);
1257 		}
1258 	}
1259 
1260 #define	KEYS_UNLOCK()	do {			\
1261 	if (khs != khw) {			\
1262 		PF_HASHROW_UNLOCK(khs);		\
1263 		PF_HASHROW_UNLOCK(khw);		\
1264 	} else					\
1265 		PF_HASHROW_UNLOCK(khs);		\
1266 } while (0)
1267 
1268 	/*
1269 	 * First run: start with wire key.
1270 	 */
1271 	sk = skw;
1272 	kh = khw;
1273 	idx = PF_SK_WIRE;
1274 
1275 	MPASS(s->lock == NULL);
1276 	s->lock = &V_pf_idhash[PF_IDHASH(s)].lock;
1277 
1278 keyattach:
1279 	LIST_FOREACH(cur, &kh->keys, entry)
1280 		if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
1281 			break;
1282 
1283 	if (cur != NULL) {
1284 		/* Key exists. Check for same kif, if none, add to key. */
1285 		TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
1286 			struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
1287 
1288 			PF_HASHROW_LOCK(ih);
1289 			if (si->kif == s->kif &&
1290 			    si->direction == s->direction) {
1291 				if (sk->proto == IPPROTO_TCP &&
1292 				    si->src.state >= TCPS_FIN_WAIT_2 &&
1293 				    si->dst.state >= TCPS_FIN_WAIT_2) {
1294 					/*
1295 					 * New state matches an old >FIN_WAIT_2
1296 					 * state. We can't drop key hash locks,
1297 					 * thus we can't unlink it properly.
1298 					 *
1299 					 * As a workaround we drop it into
1300 					 * TCPS_CLOSED state, schedule purge
1301 					 * ASAP and push it into the very end
1302 					 * of the slot TAILQ, so that it won't
1303 					 * conflict with our new state.
1304 					 */
1305 					pf_set_protostate(si, PF_PEER_BOTH,
1306 					    TCPS_CLOSED);
1307 					si->timeout = PFTM_PURGE;
1308 					olds = si;
1309 				} else {
1310 					if (V_pf_status.debug >= PF_DEBUG_MISC) {
1311 						printf("pf: %s key attach "
1312 						    "failed on %s: ",
1313 						    (idx == PF_SK_WIRE) ?
1314 						    "wire" : "stack",
1315 						    s->kif->pfik_name);
1316 						pf_print_state_parts(s,
1317 						    (idx == PF_SK_WIRE) ?
1318 						    sk : NULL,
1319 						    (idx == PF_SK_STACK) ?
1320 						    sk : NULL);
1321 						printf(", existing: ");
1322 						pf_print_state_parts(si,
1323 						    (idx == PF_SK_WIRE) ?
1324 						    sk : NULL,
1325 						    (idx == PF_SK_STACK) ?
1326 						    sk : NULL);
1327 						printf("\n");
1328 					}
1329 					PF_HASHROW_UNLOCK(ih);
1330 					KEYS_UNLOCK();
1331 					uma_zfree(V_pf_state_key_z, sk);
1332 					if (idx == PF_SK_STACK)
1333 						pf_detach_state(s);
1334 					return (EEXIST); /* collision! */
1335 				}
1336 			}
1337 			PF_HASHROW_UNLOCK(ih);
1338 		}
1339 		uma_zfree(V_pf_state_key_z, sk);
1340 		s->key[idx] = cur;
1341 	} else {
1342 		LIST_INSERT_HEAD(&kh->keys, sk, entry);
1343 		s->key[idx] = sk;
1344 	}
1345 
1346 stateattach:
1347 	/* List is sorted, if-bound states before floating. */
1348 	if (s->kif == V_pfi_all)
1349 		TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1350 	else
1351 		TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1352 
1353 	if (olds) {
1354 		TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1355 		TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1356 		    key_list[idx]);
1357 		olds = NULL;
1358 	}
1359 
1360 	/*
1361 	 * Attach done. See how should we (or should not?)
1362 	 * attach a second key.
1363 	 */
1364 	if (sks == skw) {
1365 		s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1366 		idx = PF_SK_STACK;
1367 		sks = NULL;
1368 		goto stateattach;
1369 	} else if (sks != NULL) {
1370 		/*
1371 		 * Continue attaching with stack key.
1372 		 */
1373 		sk = sks;
1374 		kh = khs;
1375 		idx = PF_SK_STACK;
1376 		sks = NULL;
1377 		goto keyattach;
1378 	}
1379 
1380 	PF_STATE_LOCK(s);
1381 	KEYS_UNLOCK();
1382 
1383 	KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1384 	    ("%s failure", __func__));
1385 
1386 	return (0);
1387 #undef	KEYS_UNLOCK
1388 }
1389 
1390 static void
1391 pf_detach_state(struct pf_kstate *s)
1392 {
1393 	struct pf_state_key *sks = s->key[PF_SK_STACK];
1394 	struct pf_keyhash *kh;
1395 
1396 	NET_EPOCH_ASSERT();
1397 
1398 	pf_sctp_multihome_detach_addr(s);
1399 
1400 	if ((s->state_flags & PFSTATE_PFLOW) && V_pflow_export_state_ptr)
1401 		V_pflow_export_state_ptr(s);
1402 
1403 	if (sks != NULL) {
1404 		kh = &V_pf_keyhash[pf_hashkey(sks)];
1405 		PF_HASHROW_LOCK(kh);
1406 		if (s->key[PF_SK_STACK] != NULL)
1407 			pf_state_key_detach(s, PF_SK_STACK);
1408 		/*
1409 		 * If both point to same key, then we are done.
1410 		 */
1411 		if (sks == s->key[PF_SK_WIRE]) {
1412 			pf_state_key_detach(s, PF_SK_WIRE);
1413 			PF_HASHROW_UNLOCK(kh);
1414 			return;
1415 		}
1416 		PF_HASHROW_UNLOCK(kh);
1417 	}
1418 
1419 	if (s->key[PF_SK_WIRE] != NULL) {
1420 		kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1421 		PF_HASHROW_LOCK(kh);
1422 		if (s->key[PF_SK_WIRE] != NULL)
1423 			pf_state_key_detach(s, PF_SK_WIRE);
1424 		PF_HASHROW_UNLOCK(kh);
1425 	}
1426 }
1427 
1428 static void
1429 pf_state_key_detach(struct pf_kstate *s, int idx)
1430 {
1431 	struct pf_state_key *sk = s->key[idx];
1432 #ifdef INVARIANTS
1433 	struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1434 
1435 	PF_HASHROW_ASSERT(kh);
1436 #endif
1437 	TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1438 	s->key[idx] = NULL;
1439 
1440 	if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1441 		LIST_REMOVE(sk, entry);
1442 		uma_zfree(V_pf_state_key_z, sk);
1443 	}
1444 }
1445 
1446 static int
1447 pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1448 {
1449 	struct pf_state_key *sk = mem;
1450 
1451 	bzero(sk, sizeof(struct pf_state_key_cmp));
1452 	TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1453 	TAILQ_INIT(&sk->states[PF_SK_STACK]);
1454 
1455 	return (0);
1456 }
1457 
1458 struct pf_state_key *
1459 pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1460 	struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1461 {
1462 	struct pf_state_key *sk;
1463 
1464 	sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1465 	if (sk == NULL)
1466 		return (NULL);
1467 
1468 	PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1469 	PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1470 	sk->port[pd->sidx] = sport;
1471 	sk->port[pd->didx] = dport;
1472 	sk->proto = pd->proto;
1473 	sk->af = pd->af;
1474 
1475 	return (sk);
1476 }
1477 
1478 struct pf_state_key *
1479 pf_state_key_clone(struct pf_state_key *orig)
1480 {
1481 	struct pf_state_key *sk;
1482 
1483 	sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1484 	if (sk == NULL)
1485 		return (NULL);
1486 
1487 	bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1488 
1489 	return (sk);
1490 }
1491 
1492 int
1493 pf_state_insert(struct pfi_kkif *kif, struct pfi_kkif *orig_kif,
1494     struct pf_state_key *skw, struct pf_state_key *sks, struct pf_kstate *s)
1495 {
1496 	struct pf_idhash *ih;
1497 	struct pf_kstate *cur;
1498 	int error;
1499 
1500 	NET_EPOCH_ASSERT();
1501 
1502 	KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1503 	    ("%s: sks not pristine", __func__));
1504 	KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1505 	    ("%s: skw not pristine", __func__));
1506 	KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1507 
1508 	s->kif = kif;
1509 	s->orig_kif = orig_kif;
1510 
1511 	if (s->id == 0 && s->creatorid == 0) {
1512 		s->id = alloc_unr64(&V_pf_stateid);
1513 		s->id = htobe64(s->id);
1514 		s->creatorid = V_pf_status.hostid;
1515 	}
1516 
1517 	/* Returns with ID locked on success. */
1518 	if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1519 		return (error);
1520 
1521 	ih = &V_pf_idhash[PF_IDHASH(s)];
1522 	PF_HASHROW_ASSERT(ih);
1523 	LIST_FOREACH(cur, &ih->states, entry)
1524 		if (cur->id == s->id && cur->creatorid == s->creatorid)
1525 			break;
1526 
1527 	if (cur != NULL) {
1528 		PF_HASHROW_UNLOCK(ih);
1529 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
1530 			printf("pf: state ID collision: "
1531 			    "id: %016llx creatorid: %08x\n",
1532 			    (unsigned long long)be64toh(s->id),
1533 			    ntohl(s->creatorid));
1534 		}
1535 		pf_detach_state(s);
1536 		return (EEXIST);
1537 	}
1538 	LIST_INSERT_HEAD(&ih->states, s, entry);
1539 	/* One for keys, one for ID hash. */
1540 	refcount_init(&s->refs, 2);
1541 
1542 	pf_counter_u64_add(&V_pf_status.fcounters[FCNT_STATE_INSERT], 1);
1543 	if (V_pfsync_insert_state_ptr != NULL)
1544 		V_pfsync_insert_state_ptr(s);
1545 
1546 	/* Returns locked. */
1547 	return (0);
1548 }
1549 
1550 /*
1551  * Find state by ID: returns with locked row on success.
1552  */
1553 struct pf_kstate *
1554 pf_find_state_byid(uint64_t id, uint32_t creatorid)
1555 {
1556 	struct pf_idhash *ih;
1557 	struct pf_kstate *s;
1558 
1559 	pf_counter_u64_add(&V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1560 
1561 	ih = &V_pf_idhash[(be64toh(id) % (pf_hashmask + 1))];
1562 
1563 	PF_HASHROW_LOCK(ih);
1564 	LIST_FOREACH(s, &ih->states, entry)
1565 		if (s->id == id && s->creatorid == creatorid)
1566 			break;
1567 
1568 	if (s == NULL)
1569 		PF_HASHROW_UNLOCK(ih);
1570 
1571 	return (s);
1572 }
1573 
1574 /*
1575  * Find state by key.
1576  * Returns with ID hash slot locked on success.
1577  */
1578 static struct pf_kstate *
1579 pf_find_state(struct pfi_kkif *kif, struct pf_state_key_cmp *key, u_int dir)
1580 {
1581 	struct pf_keyhash	*kh;
1582 	struct pf_state_key	*sk;
1583 	struct pf_kstate	*s;
1584 	int idx;
1585 
1586 	pf_counter_u64_add(&V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1587 
1588 	kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1589 
1590 	PF_HASHROW_LOCK(kh);
1591 	LIST_FOREACH(sk, &kh->keys, entry)
1592 		if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1593 			break;
1594 	if (sk == NULL) {
1595 		PF_HASHROW_UNLOCK(kh);
1596 		return (NULL);
1597 	}
1598 
1599 	idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1600 
1601 	/* List is sorted, if-bound states before floating ones. */
1602 	TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1603 		if (s->kif == V_pfi_all || s->kif == kif) {
1604 			PF_STATE_LOCK(s);
1605 			PF_HASHROW_UNLOCK(kh);
1606 			if (__predict_false(s->timeout >= PFTM_MAX)) {
1607 				/*
1608 				 * State is either being processed by
1609 				 * pf_unlink_state() in an other thread, or
1610 				 * is scheduled for immediate expiry.
1611 				 */
1612 				PF_STATE_UNLOCK(s);
1613 				return (NULL);
1614 			}
1615 			return (s);
1616 		}
1617 	PF_HASHROW_UNLOCK(kh);
1618 
1619 	return (NULL);
1620 }
1621 
1622 /*
1623  * Returns with ID hash slot locked on success.
1624  */
1625 struct pf_kstate *
1626 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1627 {
1628 	struct pf_keyhash	*kh;
1629 	struct pf_state_key	*sk;
1630 	struct pf_kstate	*s, *ret = NULL;
1631 	int			 idx, inout = 0;
1632 
1633 	pf_counter_u64_add(&V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1634 
1635 	kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1636 
1637 	PF_HASHROW_LOCK(kh);
1638 	LIST_FOREACH(sk, &kh->keys, entry)
1639 		if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1640 			break;
1641 	if (sk == NULL) {
1642 		PF_HASHROW_UNLOCK(kh);
1643 		return (NULL);
1644 	}
1645 	switch (dir) {
1646 	case PF_IN:
1647 		idx = PF_SK_WIRE;
1648 		break;
1649 	case PF_OUT:
1650 		idx = PF_SK_STACK;
1651 		break;
1652 	case PF_INOUT:
1653 		idx = PF_SK_WIRE;
1654 		inout = 1;
1655 		break;
1656 	default:
1657 		panic("%s: dir %u", __func__, dir);
1658 	}
1659 second_run:
1660 	TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1661 		if (more == NULL) {
1662 			PF_STATE_LOCK(s);
1663 			PF_HASHROW_UNLOCK(kh);
1664 			return (s);
1665 		}
1666 
1667 		if (ret)
1668 			(*more)++;
1669 		else {
1670 			ret = s;
1671 			PF_STATE_LOCK(s);
1672 		}
1673 	}
1674 	if (inout == 1) {
1675 		inout = 0;
1676 		idx = PF_SK_STACK;
1677 		goto second_run;
1678 	}
1679 	PF_HASHROW_UNLOCK(kh);
1680 
1681 	return (ret);
1682 }
1683 
1684 /*
1685  * FIXME
1686  * This routine is inefficient -- locks the state only to unlock immediately on
1687  * return.
1688  * It is racy -- after the state is unlocked nothing stops other threads from
1689  * removing it.
1690  */
1691 bool
1692 pf_find_state_all_exists(struct pf_state_key_cmp *key, u_int dir)
1693 {
1694 	struct pf_kstate *s;
1695 
1696 	s = pf_find_state_all(key, dir, NULL);
1697 	if (s != NULL) {
1698 		PF_STATE_UNLOCK(s);
1699 		return (true);
1700 	}
1701 	return (false);
1702 }
1703 
1704 /* END state table stuff */
1705 
1706 static void
1707 pf_send(struct pf_send_entry *pfse)
1708 {
1709 
1710 	PF_SENDQ_LOCK();
1711 	STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1712 	PF_SENDQ_UNLOCK();
1713 	swi_sched(V_pf_swi_cookie, 0);
1714 }
1715 
1716 static bool
1717 pf_isforlocal(struct mbuf *m, int af)
1718 {
1719 	switch (af) {
1720 #ifdef INET
1721 	case AF_INET: {
1722 		struct ip *ip = mtod(m, struct ip *);
1723 
1724 		return (in_localip(ip->ip_dst));
1725 	}
1726 #endif
1727 #ifdef INET6
1728 	case AF_INET6: {
1729 		struct ip6_hdr *ip6;
1730 		struct in6_ifaddr *ia;
1731 		ip6 = mtod(m, struct ip6_hdr *);
1732 		ia = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */, false);
1733 		if (ia == NULL)
1734 			return (false);
1735 		return (! (ia->ia6_flags & IN6_IFF_NOTREADY));
1736 	}
1737 #endif
1738 	default:
1739 		panic("Unsupported af %d", af);
1740 	}
1741 
1742 	return (false);
1743 }
1744 
1745 void
1746 pf_intr(void *v)
1747 {
1748 	struct epoch_tracker et;
1749 	struct pf_send_head queue;
1750 	struct pf_send_entry *pfse, *next;
1751 
1752 	CURVNET_SET((struct vnet *)v);
1753 
1754 	PF_SENDQ_LOCK();
1755 	queue = V_pf_sendqueue;
1756 	STAILQ_INIT(&V_pf_sendqueue);
1757 	PF_SENDQ_UNLOCK();
1758 
1759 	NET_EPOCH_ENTER(et);
1760 
1761 	STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1762 		switch (pfse->pfse_type) {
1763 #ifdef INET
1764 		case PFSE_IP: {
1765 			if (pf_isforlocal(pfse->pfse_m, AF_INET)) {
1766 				pfse->pfse_m->m_flags |= M_SKIP_FIREWALL;
1767 				pfse->pfse_m->m_pkthdr.csum_flags |=
1768 				    CSUM_IP_VALID | CSUM_IP_CHECKED;
1769 				ip_input(pfse->pfse_m);
1770 			} else {
1771 				ip_output(pfse->pfse_m, NULL, NULL, 0, NULL,
1772 				    NULL);
1773 			}
1774 			break;
1775 		}
1776 		case PFSE_ICMP:
1777 			icmp_error(pfse->pfse_m, pfse->icmpopts.type,
1778 			    pfse->icmpopts.code, 0, pfse->icmpopts.mtu);
1779 			break;
1780 #endif /* INET */
1781 #ifdef INET6
1782 		case PFSE_IP6:
1783 			if (pf_isforlocal(pfse->pfse_m, AF_INET6)) {
1784 				pfse->pfse_m->m_flags |= M_SKIP_FIREWALL;
1785 				ip6_input(pfse->pfse_m);
1786 			} else {
1787 				ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL,
1788 				    NULL, NULL);
1789 			}
1790 			break;
1791 		case PFSE_ICMP6:
1792 			icmp6_error(pfse->pfse_m, pfse->icmpopts.type,
1793 			    pfse->icmpopts.code, pfse->icmpopts.mtu);
1794 			break;
1795 #endif /* INET6 */
1796 		default:
1797 			panic("%s: unknown type", __func__);
1798 		}
1799 		free(pfse, M_PFTEMP);
1800 	}
1801 	NET_EPOCH_EXIT(et);
1802 	CURVNET_RESTORE();
1803 }
1804 
1805 #define	pf_purge_thread_period	(hz / 10)
1806 
1807 #ifdef PF_WANT_32_TO_64_COUNTER
1808 static void
1809 pf_status_counter_u64_periodic(void)
1810 {
1811 
1812 	PF_RULES_RASSERT();
1813 
1814 	if ((V_pf_counter_periodic_iter % (pf_purge_thread_period * 10 * 60)) != 0) {
1815 		return;
1816 	}
1817 
1818 	for (int i = 0; i < FCNT_MAX; i++) {
1819 		pf_counter_u64_periodic(&V_pf_status.fcounters[i]);
1820 	}
1821 }
1822 
1823 static void
1824 pf_kif_counter_u64_periodic(void)
1825 {
1826 	struct pfi_kkif *kif;
1827 	size_t r, run;
1828 
1829 	PF_RULES_RASSERT();
1830 
1831 	if (__predict_false(V_pf_allkifcount == 0)) {
1832 		return;
1833 	}
1834 
1835 	if ((V_pf_counter_periodic_iter % (pf_purge_thread_period * 10 * 300)) != 0) {
1836 		return;
1837 	}
1838 
1839 	run = V_pf_allkifcount / 10;
1840 	if (run < 5)
1841 		run = 5;
1842 
1843 	for (r = 0; r < run; r++) {
1844 		kif = LIST_NEXT(V_pf_kifmarker, pfik_allkiflist);
1845 		if (kif == NULL) {
1846 			LIST_REMOVE(V_pf_kifmarker, pfik_allkiflist);
1847 			LIST_INSERT_HEAD(&V_pf_allkiflist, V_pf_kifmarker, pfik_allkiflist);
1848 			break;
1849 		}
1850 
1851 		LIST_REMOVE(V_pf_kifmarker, pfik_allkiflist);
1852 		LIST_INSERT_AFTER(kif, V_pf_kifmarker, pfik_allkiflist);
1853 
1854 		for (int i = 0; i < 2; i++) {
1855 			for (int j = 0; j < 2; j++) {
1856 				for (int k = 0; k < 2; k++) {
1857 					pf_counter_u64_periodic(&kif->pfik_packets[i][j][k]);
1858 					pf_counter_u64_periodic(&kif->pfik_bytes[i][j][k]);
1859 				}
1860 			}
1861 		}
1862 	}
1863 }
1864 
1865 static void
1866 pf_rule_counter_u64_periodic(void)
1867 {
1868 	struct pf_krule *rule;
1869 	size_t r, run;
1870 
1871 	PF_RULES_RASSERT();
1872 
1873 	if (__predict_false(V_pf_allrulecount == 0)) {
1874 		return;
1875 	}
1876 
1877 	if ((V_pf_counter_periodic_iter % (pf_purge_thread_period * 10 * 300)) != 0) {
1878 		return;
1879 	}
1880 
1881 	run = V_pf_allrulecount / 10;
1882 	if (run < 5)
1883 		run = 5;
1884 
1885 	for (r = 0; r < run; r++) {
1886 		rule = LIST_NEXT(V_pf_rulemarker, allrulelist);
1887 		if (rule == NULL) {
1888 			LIST_REMOVE(V_pf_rulemarker, allrulelist);
1889 			LIST_INSERT_HEAD(&V_pf_allrulelist, V_pf_rulemarker, allrulelist);
1890 			break;
1891 		}
1892 
1893 		LIST_REMOVE(V_pf_rulemarker, allrulelist);
1894 		LIST_INSERT_AFTER(rule, V_pf_rulemarker, allrulelist);
1895 
1896 		pf_counter_u64_periodic(&rule->evaluations);
1897 		for (int i = 0; i < 2; i++) {
1898 			pf_counter_u64_periodic(&rule->packets[i]);
1899 			pf_counter_u64_periodic(&rule->bytes[i]);
1900 		}
1901 	}
1902 }
1903 
1904 static void
1905 pf_counter_u64_periodic_main(void)
1906 {
1907 	PF_RULES_RLOCK_TRACKER;
1908 
1909 	V_pf_counter_periodic_iter++;
1910 
1911 	PF_RULES_RLOCK();
1912 	pf_counter_u64_critical_enter();
1913 	pf_status_counter_u64_periodic();
1914 	pf_kif_counter_u64_periodic();
1915 	pf_rule_counter_u64_periodic();
1916 	pf_counter_u64_critical_exit();
1917 	PF_RULES_RUNLOCK();
1918 }
1919 #else
1920 #define	pf_counter_u64_periodic_main()	do { } while (0)
1921 #endif
1922 
1923 void
1924 pf_purge_thread(void *unused __unused)
1925 {
1926 	struct epoch_tracker	 et;
1927 
1928 	VNET_ITERATOR_DECL(vnet_iter);
1929 
1930 	sx_xlock(&pf_end_lock);
1931 	while (pf_end_threads == 0) {
1932 		sx_sleep(pf_purge_thread, &pf_end_lock, 0, "pftm", pf_purge_thread_period);
1933 
1934 		VNET_LIST_RLOCK();
1935 		NET_EPOCH_ENTER(et);
1936 		VNET_FOREACH(vnet_iter) {
1937 			CURVNET_SET(vnet_iter);
1938 
1939 			/* Wait until V_pf_default_rule is initialized. */
1940 			if (V_pf_vnet_active == 0) {
1941 				CURVNET_RESTORE();
1942 				continue;
1943 			}
1944 
1945 			pf_counter_u64_periodic_main();
1946 
1947 			/*
1948 			 *  Process 1/interval fraction of the state
1949 			 * table every run.
1950 			 */
1951 			V_pf_purge_idx =
1952 			    pf_purge_expired_states(V_pf_purge_idx, pf_hashmask /
1953 			    (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1954 
1955 			/*
1956 			 * Purge other expired types every
1957 			 * PFTM_INTERVAL seconds.
1958 			 */
1959 			if (V_pf_purge_idx == 0) {
1960 				/*
1961 				 * Order is important:
1962 				 * - states and src nodes reference rules
1963 				 * - states and rules reference kifs
1964 				 */
1965 				pf_purge_expired_fragments();
1966 				pf_purge_expired_src_nodes();
1967 				pf_purge_unlinked_rules();
1968 				pfi_kkif_purge();
1969 			}
1970 			CURVNET_RESTORE();
1971 		}
1972 		NET_EPOCH_EXIT(et);
1973 		VNET_LIST_RUNLOCK();
1974 	}
1975 
1976 	pf_end_threads++;
1977 	sx_xunlock(&pf_end_lock);
1978 	kproc_exit(0);
1979 }
1980 
1981 void
1982 pf_unload_vnet_purge(void)
1983 {
1984 
1985 	/*
1986 	 * To cleanse up all kifs and rules we need
1987 	 * two runs: first one clears reference flags,
1988 	 * then pf_purge_expired_states() doesn't
1989 	 * raise them, and then second run frees.
1990 	 */
1991 	pf_purge_unlinked_rules();
1992 	pfi_kkif_purge();
1993 
1994 	/*
1995 	 * Now purge everything.
1996 	 */
1997 	pf_purge_expired_states(0, pf_hashmask);
1998 	pf_purge_fragments(UINT_MAX);
1999 	pf_purge_expired_src_nodes();
2000 
2001 	/*
2002 	 * Now all kifs & rules should be unreferenced,
2003 	 * thus should be successfully freed.
2004 	 */
2005 	pf_purge_unlinked_rules();
2006 	pfi_kkif_purge();
2007 }
2008 
2009 u_int32_t
2010 pf_state_expires(const struct pf_kstate *state)
2011 {
2012 	u_int32_t	timeout;
2013 	u_int32_t	start;
2014 	u_int32_t	end;
2015 	u_int32_t	states;
2016 
2017 	/* handle all PFTM_* > PFTM_MAX here */
2018 	if (state->timeout == PFTM_PURGE)
2019 		return (time_uptime);
2020 	KASSERT(state->timeout != PFTM_UNLINKED,
2021 	    ("pf_state_expires: timeout == PFTM_UNLINKED"));
2022 	KASSERT((state->timeout < PFTM_MAX),
2023 	    ("pf_state_expires: timeout > PFTM_MAX"));
2024 	timeout = state->rule.ptr->timeout[state->timeout];
2025 	if (!timeout)
2026 		timeout = V_pf_default_rule.timeout[state->timeout];
2027 	start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
2028 	if (start && state->rule.ptr != &V_pf_default_rule) {
2029 		end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
2030 		states = counter_u64_fetch(state->rule.ptr->states_cur);
2031 	} else {
2032 		start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
2033 		end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
2034 		states = V_pf_status.states;
2035 	}
2036 	if (end && states > start && start < end) {
2037 		if (states < end) {
2038 			timeout = (u_int64_t)timeout * (end - states) /
2039 			    (end - start);
2040 			return ((state->expire / 1000) + timeout);
2041 		}
2042 		else
2043 			return (time_uptime);
2044 	}
2045 	return ((state->expire / 1000) + timeout);
2046 }
2047 
2048 void
2049 pf_purge_expired_src_nodes(void)
2050 {
2051 	struct pf_ksrc_node_list	 freelist;
2052 	struct pf_srchash	*sh;
2053 	struct pf_ksrc_node	*cur, *next;
2054 	int i;
2055 
2056 	LIST_INIT(&freelist);
2057 	for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
2058 	    PF_HASHROW_LOCK(sh);
2059 	    LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
2060 		if (cur->states == 0 && cur->expire <= time_uptime) {
2061 			pf_unlink_src_node(cur);
2062 			LIST_INSERT_HEAD(&freelist, cur, entry);
2063 		} else if (cur->rule.ptr != NULL)
2064 			cur->rule.ptr->rule_ref |= PFRULE_REFS;
2065 	    PF_HASHROW_UNLOCK(sh);
2066 	}
2067 
2068 	pf_free_src_nodes(&freelist);
2069 
2070 	V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
2071 }
2072 
2073 static void
2074 pf_src_tree_remove_state(struct pf_kstate *s)
2075 {
2076 	struct pf_ksrc_node *sn;
2077 	uint32_t timeout;
2078 
2079 	timeout = s->rule.ptr->timeout[PFTM_SRC_NODE] ?
2080 	    s->rule.ptr->timeout[PFTM_SRC_NODE] :
2081 	    V_pf_default_rule.timeout[PFTM_SRC_NODE];
2082 
2083 	if (s->src_node != NULL) {
2084 		sn = s->src_node;
2085 		PF_SRC_NODE_LOCK(sn);
2086 		if (s->src.tcp_est)
2087 			--sn->conn;
2088 		if (--sn->states == 0)
2089 			sn->expire = time_uptime + timeout;
2090 		PF_SRC_NODE_UNLOCK(sn);
2091 	}
2092 	if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
2093 		sn = s->nat_src_node;
2094 		PF_SRC_NODE_LOCK(sn);
2095 		if (--sn->states == 0)
2096 			sn->expire = time_uptime + timeout;
2097 		PF_SRC_NODE_UNLOCK(sn);
2098 	}
2099 	s->src_node = s->nat_src_node = NULL;
2100 }
2101 
2102 /*
2103  * Unlink and potentilly free a state. Function may be
2104  * called with ID hash row locked, but always returns
2105  * unlocked, since it needs to go through key hash locking.
2106  */
2107 int
2108 pf_unlink_state(struct pf_kstate *s)
2109 {
2110 	struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
2111 
2112 	NET_EPOCH_ASSERT();
2113 	PF_HASHROW_ASSERT(ih);
2114 
2115 	if (s->timeout == PFTM_UNLINKED) {
2116 		/*
2117 		 * State is being processed
2118 		 * by pf_unlink_state() in
2119 		 * an other thread.
2120 		 */
2121 		PF_HASHROW_UNLOCK(ih);
2122 		return (0);	/* XXXGL: undefined actually */
2123 	}
2124 
2125 	if (s->src.state == PF_TCPS_PROXY_DST) {
2126 		/* XXX wire key the right one? */
2127 		pf_send_tcp(s->rule.ptr, s->key[PF_SK_WIRE]->af,
2128 		    &s->key[PF_SK_WIRE]->addr[1],
2129 		    &s->key[PF_SK_WIRE]->addr[0],
2130 		    s->key[PF_SK_WIRE]->port[1],
2131 		    s->key[PF_SK_WIRE]->port[0],
2132 		    s->src.seqhi, s->src.seqlo + 1,
2133 		    TH_RST|TH_ACK, 0, 0, 0, true, s->tag, 0, s->act.rtableid);
2134 	}
2135 
2136 	LIST_REMOVE(s, entry);
2137 	pf_src_tree_remove_state(s);
2138 
2139 	if (V_pfsync_delete_state_ptr != NULL)
2140 		V_pfsync_delete_state_ptr(s);
2141 
2142 	STATE_DEC_COUNTERS(s);
2143 
2144 	s->timeout = PFTM_UNLINKED;
2145 
2146 	/* Ensure we remove it from the list of halfopen states, if needed. */
2147 	if (s->key[PF_SK_STACK] != NULL &&
2148 	    s->key[PF_SK_STACK]->proto == IPPROTO_TCP)
2149 		pf_set_protostate(s, PF_PEER_BOTH, TCPS_CLOSED);
2150 
2151 	PF_HASHROW_UNLOCK(ih);
2152 
2153 	pf_detach_state(s);
2154 	/* pf_state_insert() initialises refs to 2 */
2155 	return (pf_release_staten(s, 2));
2156 }
2157 
2158 struct pf_kstate *
2159 pf_alloc_state(int flags)
2160 {
2161 
2162 	return (uma_zalloc(V_pf_state_z, flags | M_ZERO));
2163 }
2164 
2165 void
2166 pf_free_state(struct pf_kstate *cur)
2167 {
2168 	struct pf_krule_item *ri;
2169 
2170 	KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
2171 	KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
2172 	    cur->timeout));
2173 
2174 	while ((ri = SLIST_FIRST(&cur->match_rules))) {
2175 		SLIST_REMOVE_HEAD(&cur->match_rules, entry);
2176 		free(ri, M_PF_RULE_ITEM);
2177 	}
2178 
2179 	pf_normalize_tcp_cleanup(cur);
2180 	uma_zfree(V_pf_state_z, cur);
2181 	pf_counter_u64_add(&V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
2182 }
2183 
2184 /*
2185  * Called only from pf_purge_thread(), thus serialized.
2186  */
2187 static u_int
2188 pf_purge_expired_states(u_int i, int maxcheck)
2189 {
2190 	struct pf_idhash *ih;
2191 	struct pf_kstate *s;
2192 	struct pf_krule_item *mrm;
2193 	size_t count __unused;
2194 
2195 	V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
2196 
2197 	/*
2198 	 * Go through hash and unlink states that expire now.
2199 	 */
2200 	while (maxcheck > 0) {
2201 		count = 0;
2202 		ih = &V_pf_idhash[i];
2203 
2204 		/* only take the lock if we expect to do work */
2205 		if (!LIST_EMPTY(&ih->states)) {
2206 relock:
2207 			PF_HASHROW_LOCK(ih);
2208 			LIST_FOREACH(s, &ih->states, entry) {
2209 				if (pf_state_expires(s) <= time_uptime) {
2210 					V_pf_status.states -=
2211 					    pf_unlink_state(s);
2212 					goto relock;
2213 				}
2214 				s->rule.ptr->rule_ref |= PFRULE_REFS;
2215 				if (s->nat_rule.ptr != NULL)
2216 					s->nat_rule.ptr->rule_ref |= PFRULE_REFS;
2217 				if (s->anchor.ptr != NULL)
2218 					s->anchor.ptr->rule_ref |= PFRULE_REFS;
2219 				s->kif->pfik_flags |= PFI_IFLAG_REFS;
2220 				SLIST_FOREACH(mrm, &s->match_rules, entry)
2221 					mrm->r->rule_ref |= PFRULE_REFS;
2222 				if (s->rt_kif)
2223 					s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
2224 				count++;
2225 			}
2226 			PF_HASHROW_UNLOCK(ih);
2227 		}
2228 
2229 		SDT_PROBE2(pf, purge, state, rowcount, i, count);
2230 
2231 		/* Return when we hit end of hash. */
2232 		if (++i > pf_hashmask) {
2233 			V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
2234 			return (0);
2235 		}
2236 
2237 		maxcheck--;
2238 	}
2239 
2240 	V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
2241 
2242 	return (i);
2243 }
2244 
2245 static void
2246 pf_purge_unlinked_rules(void)
2247 {
2248 	struct pf_krulequeue tmpq;
2249 	struct pf_krule *r, *r1;
2250 
2251 	/*
2252 	 * If we have overloading task pending, then we'd
2253 	 * better skip purging this time. There is a tiny
2254 	 * probability that overloading task references
2255 	 * an already unlinked rule.
2256 	 */
2257 	PF_OVERLOADQ_LOCK();
2258 	if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
2259 		PF_OVERLOADQ_UNLOCK();
2260 		return;
2261 	}
2262 	PF_OVERLOADQ_UNLOCK();
2263 
2264 	/*
2265 	 * Do naive mark-and-sweep garbage collecting of old rules.
2266 	 * Reference flag is raised by pf_purge_expired_states()
2267 	 * and pf_purge_expired_src_nodes().
2268 	 *
2269 	 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
2270 	 * use a temporary queue.
2271 	 */
2272 	TAILQ_INIT(&tmpq);
2273 	PF_UNLNKDRULES_LOCK();
2274 	TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
2275 		if (!(r->rule_ref & PFRULE_REFS)) {
2276 			TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
2277 			TAILQ_INSERT_TAIL(&tmpq, r, entries);
2278 		} else
2279 			r->rule_ref &= ~PFRULE_REFS;
2280 	}
2281 	PF_UNLNKDRULES_UNLOCK();
2282 
2283 	if (!TAILQ_EMPTY(&tmpq)) {
2284 		PF_CONFIG_LOCK();
2285 		PF_RULES_WLOCK();
2286 		TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
2287 			TAILQ_REMOVE(&tmpq, r, entries);
2288 			pf_free_rule(r);
2289 		}
2290 		PF_RULES_WUNLOCK();
2291 		PF_CONFIG_UNLOCK();
2292 	}
2293 }
2294 
2295 void
2296 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
2297 {
2298 	switch (af) {
2299 #ifdef INET
2300 	case AF_INET: {
2301 		u_int32_t a = ntohl(addr->addr32[0]);
2302 		printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
2303 		    (a>>8)&255, a&255);
2304 		if (p) {
2305 			p = ntohs(p);
2306 			printf(":%u", p);
2307 		}
2308 		break;
2309 	}
2310 #endif /* INET */
2311 #ifdef INET6
2312 	case AF_INET6: {
2313 		u_int16_t b;
2314 		u_int8_t i, curstart, curend, maxstart, maxend;
2315 		curstart = curend = maxstart = maxend = 255;
2316 		for (i = 0; i < 8; i++) {
2317 			if (!addr->addr16[i]) {
2318 				if (curstart == 255)
2319 					curstart = i;
2320 				curend = i;
2321 			} else {
2322 				if ((curend - curstart) >
2323 				    (maxend - maxstart)) {
2324 					maxstart = curstart;
2325 					maxend = curend;
2326 				}
2327 				curstart = curend = 255;
2328 			}
2329 		}
2330 		if ((curend - curstart) >
2331 		    (maxend - maxstart)) {
2332 			maxstart = curstart;
2333 			maxend = curend;
2334 		}
2335 		for (i = 0; i < 8; i++) {
2336 			if (i >= maxstart && i <= maxend) {
2337 				if (i == 0)
2338 					printf(":");
2339 				if (i == maxend)
2340 					printf(":");
2341 			} else {
2342 				b = ntohs(addr->addr16[i]);
2343 				printf("%x", b);
2344 				if (i < 7)
2345 					printf(":");
2346 			}
2347 		}
2348 		if (p) {
2349 			p = ntohs(p);
2350 			printf("[%u]", p);
2351 		}
2352 		break;
2353 	}
2354 #endif /* INET6 */
2355 	}
2356 }
2357 
2358 void
2359 pf_print_state(struct pf_kstate *s)
2360 {
2361 	pf_print_state_parts(s, NULL, NULL);
2362 }
2363 
2364 static void
2365 pf_print_state_parts(struct pf_kstate *s,
2366     struct pf_state_key *skwp, struct pf_state_key *sksp)
2367 {
2368 	struct pf_state_key *skw, *sks;
2369 	u_int8_t proto, dir;
2370 
2371 	/* Do our best to fill these, but they're skipped if NULL */
2372 	skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
2373 	sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
2374 	proto = skw ? skw->proto : (sks ? sks->proto : 0);
2375 	dir = s ? s->direction : 0;
2376 
2377 	switch (proto) {
2378 	case IPPROTO_IPV4:
2379 		printf("IPv4");
2380 		break;
2381 	case IPPROTO_IPV6:
2382 		printf("IPv6");
2383 		break;
2384 	case IPPROTO_TCP:
2385 		printf("TCP");
2386 		break;
2387 	case IPPROTO_UDP:
2388 		printf("UDP");
2389 		break;
2390 	case IPPROTO_ICMP:
2391 		printf("ICMP");
2392 		break;
2393 	case IPPROTO_ICMPV6:
2394 		printf("ICMPv6");
2395 		break;
2396 	default:
2397 		printf("%u", proto);
2398 		break;
2399 	}
2400 	switch (dir) {
2401 	case PF_IN:
2402 		printf(" in");
2403 		break;
2404 	case PF_OUT:
2405 		printf(" out");
2406 		break;
2407 	}
2408 	if (skw) {
2409 		printf(" wire: ");
2410 		pf_print_host(&skw->addr[0], skw->port[0], skw->af);
2411 		printf(" ");
2412 		pf_print_host(&skw->addr[1], skw->port[1], skw->af);
2413 	}
2414 	if (sks) {
2415 		printf(" stack: ");
2416 		if (sks != skw) {
2417 			pf_print_host(&sks->addr[0], sks->port[0], sks->af);
2418 			printf(" ");
2419 			pf_print_host(&sks->addr[1], sks->port[1], sks->af);
2420 		} else
2421 			printf("-");
2422 	}
2423 	if (s) {
2424 		if (proto == IPPROTO_TCP) {
2425 			printf(" [lo=%u high=%u win=%u modulator=%u",
2426 			    s->src.seqlo, s->src.seqhi,
2427 			    s->src.max_win, s->src.seqdiff);
2428 			if (s->src.wscale && s->dst.wscale)
2429 				printf(" wscale=%u",
2430 				    s->src.wscale & PF_WSCALE_MASK);
2431 			printf("]");
2432 			printf(" [lo=%u high=%u win=%u modulator=%u",
2433 			    s->dst.seqlo, s->dst.seqhi,
2434 			    s->dst.max_win, s->dst.seqdiff);
2435 			if (s->src.wscale && s->dst.wscale)
2436 				printf(" wscale=%u",
2437 				s->dst.wscale & PF_WSCALE_MASK);
2438 			printf("]");
2439 		}
2440 		printf(" %u:%u", s->src.state, s->dst.state);
2441 	}
2442 }
2443 
2444 void
2445 pf_print_flags(u_int8_t f)
2446 {
2447 	if (f)
2448 		printf(" ");
2449 	if (f & TH_FIN)
2450 		printf("F");
2451 	if (f & TH_SYN)
2452 		printf("S");
2453 	if (f & TH_RST)
2454 		printf("R");
2455 	if (f & TH_PUSH)
2456 		printf("P");
2457 	if (f & TH_ACK)
2458 		printf("A");
2459 	if (f & TH_URG)
2460 		printf("U");
2461 	if (f & TH_ECE)
2462 		printf("E");
2463 	if (f & TH_CWR)
2464 		printf("W");
2465 }
2466 
2467 #define	PF_SET_SKIP_STEPS(i)					\
2468 	do {							\
2469 		while (head[i] != cur) {			\
2470 			head[i]->skip[i].ptr = cur;		\
2471 			head[i] = TAILQ_NEXT(head[i], entries);	\
2472 		}						\
2473 	} while (0)
2474 
2475 void
2476 pf_calc_skip_steps(struct pf_krulequeue *rules)
2477 {
2478 	struct pf_krule *cur, *prev, *head[PF_SKIP_COUNT];
2479 	int i;
2480 
2481 	cur = TAILQ_FIRST(rules);
2482 	prev = cur;
2483 	for (i = 0; i < PF_SKIP_COUNT; ++i)
2484 		head[i] = cur;
2485 	while (cur != NULL) {
2486 		if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
2487 			PF_SET_SKIP_STEPS(PF_SKIP_IFP);
2488 		if (cur->direction != prev->direction)
2489 			PF_SET_SKIP_STEPS(PF_SKIP_DIR);
2490 		if (cur->af != prev->af)
2491 			PF_SET_SKIP_STEPS(PF_SKIP_AF);
2492 		if (cur->proto != prev->proto)
2493 			PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
2494 		if (cur->src.neg != prev->src.neg ||
2495 		    pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
2496 			PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
2497 		if (cur->src.port[0] != prev->src.port[0] ||
2498 		    cur->src.port[1] != prev->src.port[1] ||
2499 		    cur->src.port_op != prev->src.port_op)
2500 			PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
2501 		if (cur->dst.neg != prev->dst.neg ||
2502 		    pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
2503 			PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
2504 		if (cur->dst.port[0] != prev->dst.port[0] ||
2505 		    cur->dst.port[1] != prev->dst.port[1] ||
2506 		    cur->dst.port_op != prev->dst.port_op)
2507 			PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
2508 
2509 		prev = cur;
2510 		cur = TAILQ_NEXT(cur, entries);
2511 	}
2512 	for (i = 0; i < PF_SKIP_COUNT; ++i)
2513 		PF_SET_SKIP_STEPS(i);
2514 }
2515 
2516 int
2517 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
2518 {
2519 	if (aw1->type != aw2->type)
2520 		return (1);
2521 	switch (aw1->type) {
2522 	case PF_ADDR_ADDRMASK:
2523 	case PF_ADDR_RANGE:
2524 		if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, AF_INET6))
2525 			return (1);
2526 		if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, AF_INET6))
2527 			return (1);
2528 		return (0);
2529 	case PF_ADDR_DYNIFTL:
2530 		return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
2531 	case PF_ADDR_NOROUTE:
2532 	case PF_ADDR_URPFFAILED:
2533 		return (0);
2534 	case PF_ADDR_TABLE:
2535 		return (aw1->p.tbl != aw2->p.tbl);
2536 	default:
2537 		printf("invalid address type: %d\n", aw1->type);
2538 		return (1);
2539 	}
2540 }
2541 
2542 /**
2543  * Checksum updates are a little complicated because the checksum in the TCP/UDP
2544  * header isn't always a full checksum. In some cases (i.e. output) it's a
2545  * pseudo-header checksum, which is a partial checksum over src/dst IP
2546  * addresses, protocol number and length.
2547  *
2548  * That means we have the following cases:
2549  *  * Input or forwarding: we don't have TSO, the checksum fields are full
2550  *  	checksums, we need to update the checksum whenever we change anything.
2551  *  * Output (i.e. the checksum is a pseudo-header checksum):
2552  *  	x The field being updated is src/dst address or affects the length of
2553  *  	the packet. We need to update the pseudo-header checksum (note that this
2554  *  	checksum is not ones' complement).
2555  *  	x Some other field is being modified (e.g. src/dst port numbers): We
2556  *  	don't have to update anything.
2557  **/
2558 u_int16_t
2559 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
2560 {
2561 	u_int32_t x;
2562 
2563 	x = cksum + old - new;
2564 	x = (x + (x >> 16)) & 0xffff;
2565 
2566 	/* optimise: eliminate a branch when not udp */
2567 	if (udp && cksum == 0x0000)
2568 		return cksum;
2569 	if (udp && x == 0x0000)
2570 		x = 0xffff;
2571 
2572 	return (u_int16_t)(x);
2573 }
2574 
2575 static void
2576 pf_patch_8(struct mbuf *m, u_int16_t *cksum, u_int8_t *f, u_int8_t v, bool hi,
2577     u_int8_t udp)
2578 {
2579 	u_int16_t old = htons(hi ? (*f << 8) : *f);
2580 	u_int16_t new = htons(hi ? ( v << 8) :  v);
2581 
2582 	if (*f == v)
2583 		return;
2584 
2585 	*f = v;
2586 
2587 	if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2588 		return;
2589 
2590 	*cksum = pf_cksum_fixup(*cksum, old, new, udp);
2591 }
2592 
2593 void
2594 pf_patch_16_unaligned(struct mbuf *m, u_int16_t *cksum, void *f, u_int16_t v,
2595     bool hi, u_int8_t udp)
2596 {
2597 	u_int8_t *fb = (u_int8_t *)f;
2598 	u_int8_t *vb = (u_int8_t *)&v;
2599 
2600 	pf_patch_8(m, cksum, fb++, *vb++, hi, udp);
2601 	pf_patch_8(m, cksum, fb++, *vb++, !hi, udp);
2602 }
2603 
2604 void
2605 pf_patch_32_unaligned(struct mbuf *m, u_int16_t *cksum, void *f, u_int32_t v,
2606     bool hi, u_int8_t udp)
2607 {
2608 	u_int8_t *fb = (u_int8_t *)f;
2609 	u_int8_t *vb = (u_int8_t *)&v;
2610 
2611 	pf_patch_8(m, cksum, fb++, *vb++, hi, udp);
2612 	pf_patch_8(m, cksum, fb++, *vb++, !hi, udp);
2613 	pf_patch_8(m, cksum, fb++, *vb++, hi, udp);
2614 	pf_patch_8(m, cksum, fb++, *vb++, !hi, udp);
2615 }
2616 
2617 u_int16_t
2618 pf_proto_cksum_fixup(struct mbuf *m, u_int16_t cksum, u_int16_t old,
2619         u_int16_t new, u_int8_t udp)
2620 {
2621 	if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2622 		return (cksum);
2623 
2624 	return (pf_cksum_fixup(cksum, old, new, udp));
2625 }
2626 
2627 static void
2628 pf_change_ap(struct mbuf *m, struct pf_addr *a, u_int16_t *p, u_int16_t *ic,
2629         u_int16_t *pc, struct pf_addr *an, u_int16_t pn, u_int8_t u,
2630         sa_family_t af)
2631 {
2632 	struct pf_addr	ao;
2633 	u_int16_t	po = *p;
2634 
2635 	PF_ACPY(&ao, a, af);
2636 	PF_ACPY(a, an, af);
2637 
2638 	if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2639 		*pc = ~*pc;
2640 
2641 	*p = pn;
2642 
2643 	switch (af) {
2644 #ifdef INET
2645 	case AF_INET:
2646 		*ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2647 		    ao.addr16[0], an->addr16[0], 0),
2648 		    ao.addr16[1], an->addr16[1], 0);
2649 		*p = pn;
2650 
2651 		*pc = pf_cksum_fixup(pf_cksum_fixup(*pc,
2652 		    ao.addr16[0], an->addr16[0], u),
2653 		    ao.addr16[1], an->addr16[1], u);
2654 
2655 		*pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2656 		break;
2657 #endif /* INET */
2658 #ifdef INET6
2659 	case AF_INET6:
2660 		*pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2661 		    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2662 		    pf_cksum_fixup(pf_cksum_fixup(*pc,
2663 		    ao.addr16[0], an->addr16[0], u),
2664 		    ao.addr16[1], an->addr16[1], u),
2665 		    ao.addr16[2], an->addr16[2], u),
2666 		    ao.addr16[3], an->addr16[3], u),
2667 		    ao.addr16[4], an->addr16[4], u),
2668 		    ao.addr16[5], an->addr16[5], u),
2669 		    ao.addr16[6], an->addr16[6], u),
2670 		    ao.addr16[7], an->addr16[7], u);
2671 
2672 		*pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2673 		break;
2674 #endif /* INET6 */
2675 	}
2676 
2677 	if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA |
2678 	    CSUM_DELAY_DATA_IPV6)) {
2679 		*pc = ~*pc;
2680 		if (! *pc)
2681 			*pc = 0xffff;
2682 	}
2683 }
2684 
2685 /* Changes a u_int32_t.  Uses a void * so there are no align restrictions */
2686 void
2687 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2688 {
2689 	u_int32_t	ao;
2690 
2691 	memcpy(&ao, a, sizeof(ao));
2692 	memcpy(a, &an, sizeof(u_int32_t));
2693 	*c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2694 	    ao % 65536, an % 65536, u);
2695 }
2696 
2697 void
2698 pf_change_proto_a(struct mbuf *m, void *a, u_int16_t *c, u_int32_t an, u_int8_t udp)
2699 {
2700 	u_int32_t	ao;
2701 
2702 	memcpy(&ao, a, sizeof(ao));
2703 	memcpy(a, &an, sizeof(u_int32_t));
2704 
2705 	*c = pf_proto_cksum_fixup(m,
2706 	    pf_proto_cksum_fixup(m, *c, ao / 65536, an / 65536, udp),
2707 	    ao % 65536, an % 65536, udp);
2708 }
2709 
2710 #ifdef INET6
2711 static void
2712 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2713 {
2714 	struct pf_addr	ao;
2715 
2716 	PF_ACPY(&ao, a, AF_INET6);
2717 	PF_ACPY(a, an, AF_INET6);
2718 
2719 	*c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2720 	    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2721 	    pf_cksum_fixup(pf_cksum_fixup(*c,
2722 	    ao.addr16[0], an->addr16[0], u),
2723 	    ao.addr16[1], an->addr16[1], u),
2724 	    ao.addr16[2], an->addr16[2], u),
2725 	    ao.addr16[3], an->addr16[3], u),
2726 	    ao.addr16[4], an->addr16[4], u),
2727 	    ao.addr16[5], an->addr16[5], u),
2728 	    ao.addr16[6], an->addr16[6], u),
2729 	    ao.addr16[7], an->addr16[7], u);
2730 }
2731 #endif /* INET6 */
2732 
2733 static void
2734 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2735     struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2736     u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2737 {
2738 	struct pf_addr	oia, ooa;
2739 
2740 	PF_ACPY(&oia, ia, af);
2741 	if (oa)
2742 		PF_ACPY(&ooa, oa, af);
2743 
2744 	/* Change inner protocol port, fix inner protocol checksum. */
2745 	if (ip != NULL) {
2746 		u_int16_t	oip = *ip;
2747 		u_int32_t	opc;
2748 
2749 		if (pc != NULL)
2750 			opc = *pc;
2751 		*ip = np;
2752 		if (pc != NULL)
2753 			*pc = pf_cksum_fixup(*pc, oip, *ip, u);
2754 		*ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2755 		if (pc != NULL)
2756 			*ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2757 	}
2758 	/* Change inner ip address, fix inner ip and icmp checksums. */
2759 	PF_ACPY(ia, na, af);
2760 	switch (af) {
2761 #ifdef INET
2762 	case AF_INET: {
2763 		u_int32_t	 oh2c = *h2c;
2764 
2765 		*h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2766 		    oia.addr16[0], ia->addr16[0], 0),
2767 		    oia.addr16[1], ia->addr16[1], 0);
2768 		*ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2769 		    oia.addr16[0], ia->addr16[0], 0),
2770 		    oia.addr16[1], ia->addr16[1], 0);
2771 		*ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2772 		break;
2773 	}
2774 #endif /* INET */
2775 #ifdef INET6
2776 	case AF_INET6:
2777 		*ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2778 		    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2779 		    pf_cksum_fixup(pf_cksum_fixup(*ic,
2780 		    oia.addr16[0], ia->addr16[0], u),
2781 		    oia.addr16[1], ia->addr16[1], u),
2782 		    oia.addr16[2], ia->addr16[2], u),
2783 		    oia.addr16[3], ia->addr16[3], u),
2784 		    oia.addr16[4], ia->addr16[4], u),
2785 		    oia.addr16[5], ia->addr16[5], u),
2786 		    oia.addr16[6], ia->addr16[6], u),
2787 		    oia.addr16[7], ia->addr16[7], u);
2788 		break;
2789 #endif /* INET6 */
2790 	}
2791 	/* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2792 	if (oa) {
2793 		PF_ACPY(oa, na, af);
2794 		switch (af) {
2795 #ifdef INET
2796 		case AF_INET:
2797 			*hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2798 			    ooa.addr16[0], oa->addr16[0], 0),
2799 			    ooa.addr16[1], oa->addr16[1], 0);
2800 			break;
2801 #endif /* INET */
2802 #ifdef INET6
2803 		case AF_INET6:
2804 			*ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2805 			    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2806 			    pf_cksum_fixup(pf_cksum_fixup(*ic,
2807 			    ooa.addr16[0], oa->addr16[0], u),
2808 			    ooa.addr16[1], oa->addr16[1], u),
2809 			    ooa.addr16[2], oa->addr16[2], u),
2810 			    ooa.addr16[3], oa->addr16[3], u),
2811 			    ooa.addr16[4], oa->addr16[4], u),
2812 			    ooa.addr16[5], oa->addr16[5], u),
2813 			    ooa.addr16[6], oa->addr16[6], u),
2814 			    ooa.addr16[7], oa->addr16[7], u);
2815 			break;
2816 #endif /* INET6 */
2817 		}
2818 	}
2819 }
2820 
2821 /*
2822  * Need to modulate the sequence numbers in the TCP SACK option
2823  * (credits to Krzysztof Pfaff for report and patch)
2824  */
2825 static int
2826 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2827     struct tcphdr *th, struct pf_state_peer *dst)
2828 {
2829 	int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2830 	u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2831 	int copyback = 0, i, olen;
2832 	struct sackblk sack;
2833 
2834 #define	TCPOLEN_SACKLEN	(TCPOLEN_SACK + 2)
2835 	if (hlen < TCPOLEN_SACKLEN ||
2836 	    !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2837 		return 0;
2838 
2839 	while (hlen >= TCPOLEN_SACKLEN) {
2840 		size_t startoff = opt - opts;
2841 		olen = opt[1];
2842 		switch (*opt) {
2843 		case TCPOPT_EOL:	/* FALLTHROUGH */
2844 		case TCPOPT_NOP:
2845 			opt++;
2846 			hlen--;
2847 			break;
2848 		case TCPOPT_SACK:
2849 			if (olen > hlen)
2850 				olen = hlen;
2851 			if (olen >= TCPOLEN_SACKLEN) {
2852 				for (i = 2; i + TCPOLEN_SACK <= olen;
2853 				    i += TCPOLEN_SACK) {
2854 					memcpy(&sack, &opt[i], sizeof(sack));
2855 					pf_patch_32_unaligned(m,
2856 					    &th->th_sum, &sack.start,
2857 					    htonl(ntohl(sack.start) - dst->seqdiff),
2858 					    PF_ALGNMNT(startoff),
2859 					    0);
2860 					pf_patch_32_unaligned(m, &th->th_sum,
2861 					    &sack.end,
2862 					    htonl(ntohl(sack.end) - dst->seqdiff),
2863 					    PF_ALGNMNT(startoff),
2864 					    0);
2865 					memcpy(&opt[i], &sack, sizeof(sack));
2866 				}
2867 				copyback = 1;
2868 			}
2869 			/* FALLTHROUGH */
2870 		default:
2871 			if (olen < 2)
2872 				olen = 2;
2873 			hlen -= olen;
2874 			opt += olen;
2875 		}
2876 	}
2877 
2878 	if (copyback)
2879 		m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2880 	return (copyback);
2881 }
2882 
2883 struct mbuf *
2884 pf_build_tcp(const struct pf_krule *r, sa_family_t af,
2885     const struct pf_addr *saddr, const struct pf_addr *daddr,
2886     u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2887     u_int8_t tcp_flags, u_int16_t win, u_int16_t mss, u_int8_t ttl,
2888     bool skip_firewall, u_int16_t mtag_tag, u_int16_t mtag_flags, int rtableid)
2889 {
2890 	struct mbuf	*m;
2891 	int		 len, tlen;
2892 #ifdef INET
2893 	struct ip	*h = NULL;
2894 #endif /* INET */
2895 #ifdef INET6
2896 	struct ip6_hdr	*h6 = NULL;
2897 #endif /* INET6 */
2898 	struct tcphdr	*th;
2899 	char		*opt;
2900 	struct pf_mtag  *pf_mtag;
2901 
2902 	len = 0;
2903 	th = NULL;
2904 
2905 	/* maximum segment size tcp option */
2906 	tlen = sizeof(struct tcphdr);
2907 	if (mss)
2908 		tlen += 4;
2909 
2910 	switch (af) {
2911 #ifdef INET
2912 	case AF_INET:
2913 		len = sizeof(struct ip) + tlen;
2914 		break;
2915 #endif /* INET */
2916 #ifdef INET6
2917 	case AF_INET6:
2918 		len = sizeof(struct ip6_hdr) + tlen;
2919 		break;
2920 #endif /* INET6 */
2921 	default:
2922 		panic("%s: unsupported af %d", __func__, af);
2923 	}
2924 
2925 	m = m_gethdr(M_NOWAIT, MT_DATA);
2926 	if (m == NULL)
2927 		return (NULL);
2928 
2929 #ifdef MAC
2930 	mac_netinet_firewall_send(m);
2931 #endif
2932 	if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2933 		m_freem(m);
2934 		return (NULL);
2935 	}
2936 	if (skip_firewall)
2937 		m->m_flags |= M_SKIP_FIREWALL;
2938 	pf_mtag->tag = mtag_tag;
2939 	pf_mtag->flags = mtag_flags;
2940 
2941 	if (rtableid >= 0)
2942 		M_SETFIB(m, rtableid);
2943 
2944 #ifdef ALTQ
2945 	if (r != NULL && r->qid) {
2946 		pf_mtag->qid = r->qid;
2947 
2948 		/* add hints for ecn */
2949 		pf_mtag->hdr = mtod(m, struct ip *);
2950 	}
2951 #endif /* ALTQ */
2952 	m->m_data += max_linkhdr;
2953 	m->m_pkthdr.len = m->m_len = len;
2954 	/* The rest of the stack assumes a rcvif, so provide one.
2955 	 * This is a locally generated packet, so .. close enough. */
2956 	m->m_pkthdr.rcvif = V_loif;
2957 	bzero(m->m_data, len);
2958 	switch (af) {
2959 #ifdef INET
2960 	case AF_INET:
2961 		h = mtod(m, struct ip *);
2962 
2963 		/* IP header fields included in the TCP checksum */
2964 		h->ip_p = IPPROTO_TCP;
2965 		h->ip_len = htons(tlen);
2966 		h->ip_src.s_addr = saddr->v4.s_addr;
2967 		h->ip_dst.s_addr = daddr->v4.s_addr;
2968 
2969 		th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2970 		break;
2971 #endif /* INET */
2972 #ifdef INET6
2973 	case AF_INET6:
2974 		h6 = mtod(m, struct ip6_hdr *);
2975 
2976 		/* IP header fields included in the TCP checksum */
2977 		h6->ip6_nxt = IPPROTO_TCP;
2978 		h6->ip6_plen = htons(tlen);
2979 		memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2980 		memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2981 
2982 		th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2983 		break;
2984 #endif /* INET6 */
2985 	}
2986 
2987 	/* TCP header */
2988 	th->th_sport = sport;
2989 	th->th_dport = dport;
2990 	th->th_seq = htonl(seq);
2991 	th->th_ack = htonl(ack);
2992 	th->th_off = tlen >> 2;
2993 	th->th_flags = tcp_flags;
2994 	th->th_win = htons(win);
2995 
2996 	if (mss) {
2997 		opt = (char *)(th + 1);
2998 		opt[0] = TCPOPT_MAXSEG;
2999 		opt[1] = 4;
3000 		HTONS(mss);
3001 		bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
3002 	}
3003 
3004 	switch (af) {
3005 #ifdef INET
3006 	case AF_INET:
3007 		/* TCP checksum */
3008 		th->th_sum = in_cksum(m, len);
3009 
3010 		/* Finish the IP header */
3011 		h->ip_v = 4;
3012 		h->ip_hl = sizeof(*h) >> 2;
3013 		h->ip_tos = IPTOS_LOWDELAY;
3014 		h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
3015 		h->ip_len = htons(len);
3016 		h->ip_ttl = ttl ? ttl : V_ip_defttl;
3017 		h->ip_sum = 0;
3018 		break;
3019 #endif /* INET */
3020 #ifdef INET6
3021 	case AF_INET6:
3022 		/* TCP checksum */
3023 		th->th_sum = in6_cksum(m, IPPROTO_TCP,
3024 		    sizeof(struct ip6_hdr), tlen);
3025 
3026 		h6->ip6_vfc |= IPV6_VERSION;
3027 		h6->ip6_hlim = IPV6_DEFHLIM;
3028 		break;
3029 #endif /* INET6 */
3030 	}
3031 
3032 	return (m);
3033 }
3034 
3035 static void
3036 pf_send_sctp_abort(sa_family_t af, struct pf_pdesc *pd,
3037     uint8_t ttl, int rtableid)
3038 {
3039 	struct mbuf		*m;
3040 #ifdef INET
3041 	struct ip		*h = NULL;
3042 #endif /* INET */
3043 #ifdef INET6
3044 	struct ip6_hdr		*h6 = NULL;
3045 #endif /* INET6 */
3046 	struct sctphdr		*hdr;
3047 	struct sctp_chunkhdr	*chunk;
3048 	struct pf_send_entry	*pfse;
3049 	int			 off = 0;
3050 
3051 	MPASS(af == pd->af);
3052 
3053 	m = m_gethdr(M_NOWAIT, MT_DATA);
3054 	if (m == NULL)
3055 		return;
3056 
3057 	m->m_data += max_linkhdr;
3058 	m->m_flags |= M_SKIP_FIREWALL;
3059 	/* The rest of the stack assumes a rcvif, so provide one.
3060 	 * This is a locally generated packet, so .. close enough. */
3061 	m->m_pkthdr.rcvif = V_loif;
3062 
3063 	/* IPv4|6 header */
3064 	switch (af) {
3065 #ifdef INET
3066 	case AF_INET:
3067 		bzero(m->m_data, sizeof(struct ip) + sizeof(*hdr) + sizeof(*chunk));
3068 
3069 		h = mtod(m, struct ip *);
3070 
3071 		/* IP header fields included in the TCP checksum */
3072 
3073 		h->ip_p = IPPROTO_SCTP;
3074 		h->ip_len = htons(sizeof(*h) + sizeof(*hdr) + sizeof(*chunk));
3075 		h->ip_ttl = ttl ? ttl : V_ip_defttl;
3076 		h->ip_src = pd->dst->v4;
3077 		h->ip_dst = pd->src->v4;
3078 
3079 		off += sizeof(struct ip);
3080 		break;
3081 #endif /* INET */
3082 #ifdef INET6
3083 	case AF_INET6:
3084 		bzero(m->m_data, sizeof(struct ip6_hdr) + sizeof(*hdr) + sizeof(*chunk));
3085 
3086 		h6 = mtod(m, struct ip6_hdr *);
3087 
3088 		/* IP header fields included in the TCP checksum */
3089 		h6->ip6_vfc |= IPV6_VERSION;
3090 		h6->ip6_nxt = IPPROTO_SCTP;
3091 		h6->ip6_plen = htons(sizeof(*h6) + sizeof(*hdr) + sizeof(*chunk));
3092 		h6->ip6_hlim = ttl ? ttl : V_ip6_defhlim;
3093 		memcpy(&h6->ip6_src, &pd->dst->v6, sizeof(struct in6_addr));
3094 		memcpy(&h6->ip6_dst, &pd->src->v6, sizeof(struct in6_addr));
3095 
3096 		off += sizeof(struct ip6_hdr);
3097 		break;
3098 #endif /* INET6 */
3099 	}
3100 
3101 	/* SCTP header */
3102 	hdr = mtodo(m, off);
3103 
3104 	hdr->src_port = pd->hdr.sctp.dest_port;
3105 	hdr->dest_port = pd->hdr.sctp.src_port;
3106 	hdr->v_tag = pd->sctp_initiate_tag;
3107 	hdr->checksum = 0;
3108 
3109 	/* Abort chunk. */
3110 	off += sizeof(struct sctphdr);
3111 	chunk = mtodo(m, off);
3112 
3113 	chunk->chunk_type = SCTP_ABORT_ASSOCIATION;
3114 	chunk->chunk_length = htons(sizeof(*chunk));
3115 
3116 	/* SCTP checksum */
3117 	off += sizeof(*chunk);
3118 	m->m_pkthdr.len = m->m_len = off;
3119 
3120 	pf_sctp_checksum(m, off - sizeof(*hdr) - sizeof(*chunk));;
3121 
3122 	if (rtableid >= 0)
3123 		M_SETFIB(m, rtableid);
3124 
3125 	/* Allocate outgoing queue entry, mbuf and mbuf tag. */
3126 	pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
3127 	if (pfse == NULL) {
3128 		m_freem(m);
3129 		return;
3130 	}
3131 
3132 	switch (af) {
3133 #ifdef INET
3134 	case AF_INET:
3135 		pfse->pfse_type = PFSE_IP;
3136 		break;
3137 #endif /* INET */
3138 #ifdef INET6
3139 	case AF_INET6:
3140 		pfse->pfse_type = PFSE_IP6;
3141 		break;
3142 #endif /* INET6 */
3143 	}
3144 
3145 	pfse->pfse_m = m;
3146 	pf_send(pfse);
3147 }
3148 
3149 void
3150 pf_send_tcp(const struct pf_krule *r, sa_family_t af,
3151     const struct pf_addr *saddr, const struct pf_addr *daddr,
3152     u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
3153     u_int8_t tcp_flags, u_int16_t win, u_int16_t mss, u_int8_t ttl,
3154     bool skip_firewall, u_int16_t mtag_tag, u_int16_t mtag_flags, int rtableid)
3155 {
3156 	struct pf_send_entry *pfse;
3157 	struct mbuf	*m;
3158 
3159 	m = pf_build_tcp(r, af, saddr, daddr, sport, dport, seq, ack, tcp_flags,
3160 	    win, mss, ttl, skip_firewall, mtag_tag, mtag_flags, rtableid);
3161 	if (m == NULL)
3162 		return;
3163 
3164 	/* Allocate outgoing queue entry, mbuf and mbuf tag. */
3165 	pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
3166 	if (pfse == NULL) {
3167 		m_freem(m);
3168 		return;
3169 	}
3170 
3171 	switch (af) {
3172 #ifdef INET
3173 	case AF_INET:
3174 		pfse->pfse_type = PFSE_IP;
3175 		break;
3176 #endif /* INET */
3177 #ifdef INET6
3178 	case AF_INET6:
3179 		pfse->pfse_type = PFSE_IP6;
3180 		break;
3181 #endif /* INET6 */
3182 	}
3183 
3184 	pfse->pfse_m = m;
3185 	pf_send(pfse);
3186 }
3187 
3188 static void
3189 pf_return(struct pf_krule *r, struct pf_krule *nr, struct pf_pdesc *pd,
3190     struct pf_state_key *sk, int off, struct mbuf *m, struct tcphdr *th,
3191     struct pfi_kkif *kif, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen,
3192     u_short *reason, int rtableid)
3193 {
3194 	struct pf_addr	* const saddr = pd->src;
3195 	struct pf_addr	* const daddr = pd->dst;
3196 	sa_family_t	 af = pd->af;
3197 
3198 	/* undo NAT changes, if they have taken place */
3199 	if (nr != NULL) {
3200 		PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3201 		PF_ACPY(daddr, &sk->addr[pd->didx], af);
3202 		if (pd->sport)
3203 			*pd->sport = sk->port[pd->sidx];
3204 		if (pd->dport)
3205 			*pd->dport = sk->port[pd->didx];
3206 		if (pd->proto_sum)
3207 			*pd->proto_sum = bproto_sum;
3208 		if (pd->ip_sum)
3209 			*pd->ip_sum = bip_sum;
3210 		m_copyback(m, off, hdrlen, pd->hdr.any);
3211 	}
3212 	if (pd->proto == IPPROTO_TCP &&
3213 	    ((r->rule_flag & PFRULE_RETURNRST) ||
3214 	    (r->rule_flag & PFRULE_RETURN)) &&
3215 	    !(th->th_flags & TH_RST)) {
3216 		u_int32_t	 ack = ntohl(th->th_seq) + pd->p_len;
3217 		int		 len = 0;
3218 #ifdef INET
3219 		struct ip	*h4;
3220 #endif
3221 #ifdef INET6
3222 		struct ip6_hdr	*h6;
3223 #endif
3224 
3225 		switch (af) {
3226 #ifdef INET
3227 		case AF_INET:
3228 			h4 = mtod(m, struct ip *);
3229 			len = ntohs(h4->ip_len) - off;
3230 			break;
3231 #endif
3232 #ifdef INET6
3233 		case AF_INET6:
3234 			h6 = mtod(m, struct ip6_hdr *);
3235 			len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
3236 			break;
3237 #endif
3238 		}
3239 
3240 		if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
3241 			REASON_SET(reason, PFRES_PROTCKSUM);
3242 		else {
3243 			if (th->th_flags & TH_SYN)
3244 				ack++;
3245 			if (th->th_flags & TH_FIN)
3246 				ack++;
3247 			pf_send_tcp(r, af, pd->dst,
3248 				pd->src, th->th_dport, th->th_sport,
3249 				ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3250 				r->return_ttl, true, 0, 0, rtableid);
3251 		}
3252 	} else if (pd->proto == IPPROTO_SCTP &&
3253 	    (r->rule_flag & PFRULE_RETURN)) {
3254 		pf_send_sctp_abort(af, pd, r->return_ttl, rtableid);
3255 	} else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3256 		r->return_icmp)
3257 		pf_send_icmp(m, r->return_icmp >> 8,
3258 			r->return_icmp & 255, af, r, rtableid);
3259 	else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3260 		r->return_icmp6)
3261 		pf_send_icmp(m, r->return_icmp6 >> 8,
3262 			r->return_icmp6 & 255, af, r, rtableid);
3263 }
3264 
3265 static int
3266 pf_match_ieee8021q_pcp(u_int8_t prio, struct mbuf *m)
3267 {
3268 	struct m_tag *mtag;
3269 	u_int8_t mpcp;
3270 
3271 	mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_IN, NULL);
3272 	if (mtag == NULL)
3273 		return (0);
3274 
3275 	if (prio == PF_PRIO_ZERO)
3276 		prio = 0;
3277 
3278 	mpcp = *(uint8_t *)(mtag + 1);
3279 
3280 	return (mpcp == prio);
3281 }
3282 
3283 static int
3284 pf_icmp_to_bandlim(uint8_t type)
3285 {
3286 	switch (type) {
3287 		case ICMP_ECHO:
3288 		case ICMP_ECHOREPLY:
3289 			return (BANDLIM_ICMP_ECHO);
3290 		case ICMP_TSTAMP:
3291 		case ICMP_TSTAMPREPLY:
3292 			return (BANDLIM_ICMP_TSTAMP);
3293 		case ICMP_UNREACH:
3294 		default:
3295 			return (BANDLIM_ICMP_UNREACH);
3296 	}
3297 }
3298 
3299 static void
3300 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
3301     struct pf_krule *r, int rtableid)
3302 {
3303 	struct pf_send_entry *pfse;
3304 	struct mbuf *m0;
3305 	struct pf_mtag *pf_mtag;
3306 
3307 	/* ICMP packet rate limitation. */
3308 #ifdef INET6
3309 	if (af == AF_INET6) {
3310 		if (icmp6_ratelimit(NULL, type, code))
3311 			return;
3312 	}
3313 #endif
3314 #ifdef INET
3315 	if (af == AF_INET) {
3316 		if (badport_bandlim(pf_icmp_to_bandlim(type)) != 0)
3317 			return;
3318 	}
3319 #endif
3320 
3321 	/* Allocate outgoing queue entry, mbuf and mbuf tag. */
3322 	pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
3323 	if (pfse == NULL)
3324 		return;
3325 
3326 	if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
3327 		free(pfse, M_PFTEMP);
3328 		return;
3329 	}
3330 
3331 	if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
3332 		free(pfse, M_PFTEMP);
3333 		return;
3334 	}
3335 	/* XXX: revisit */
3336 	m0->m_flags |= M_SKIP_FIREWALL;
3337 
3338 	if (rtableid >= 0)
3339 		M_SETFIB(m0, rtableid);
3340 
3341 #ifdef ALTQ
3342 	if (r->qid) {
3343 		pf_mtag->qid = r->qid;
3344 		/* add hints for ecn */
3345 		pf_mtag->hdr = mtod(m0, struct ip *);
3346 	}
3347 #endif /* ALTQ */
3348 
3349 	switch (af) {
3350 #ifdef INET
3351 	case AF_INET:
3352 		pfse->pfse_type = PFSE_ICMP;
3353 		break;
3354 #endif /* INET */
3355 #ifdef INET6
3356 	case AF_INET6:
3357 		pfse->pfse_type = PFSE_ICMP6;
3358 		break;
3359 #endif /* INET6 */
3360 	}
3361 	pfse->pfse_m = m0;
3362 	pfse->icmpopts.type = type;
3363 	pfse->icmpopts.code = code;
3364 	pf_send(pfse);
3365 }
3366 
3367 /*
3368  * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
3369  * If n is 0, they match if they are equal. If n is != 0, they match if they
3370  * are different.
3371  */
3372 int
3373 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
3374     struct pf_addr *b, sa_family_t af)
3375 {
3376 	int	match = 0;
3377 
3378 	switch (af) {
3379 #ifdef INET
3380 	case AF_INET:
3381 		if ((a->addr32[0] & m->addr32[0]) ==
3382 		    (b->addr32[0] & m->addr32[0]))
3383 			match++;
3384 		break;
3385 #endif /* INET */
3386 #ifdef INET6
3387 	case AF_INET6:
3388 		if (((a->addr32[0] & m->addr32[0]) ==
3389 		     (b->addr32[0] & m->addr32[0])) &&
3390 		    ((a->addr32[1] & m->addr32[1]) ==
3391 		     (b->addr32[1] & m->addr32[1])) &&
3392 		    ((a->addr32[2] & m->addr32[2]) ==
3393 		     (b->addr32[2] & m->addr32[2])) &&
3394 		    ((a->addr32[3] & m->addr32[3]) ==
3395 		     (b->addr32[3] & m->addr32[3])))
3396 			match++;
3397 		break;
3398 #endif /* INET6 */
3399 	}
3400 	if (match) {
3401 		if (n)
3402 			return (0);
3403 		else
3404 			return (1);
3405 	} else {
3406 		if (n)
3407 			return (1);
3408 		else
3409 			return (0);
3410 	}
3411 }
3412 
3413 /*
3414  * Return 1 if b <= a <= e, otherwise return 0.
3415  */
3416 int
3417 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
3418     struct pf_addr *a, sa_family_t af)
3419 {
3420 	switch (af) {
3421 #ifdef INET
3422 	case AF_INET:
3423 		if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
3424 		    (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
3425 			return (0);
3426 		break;
3427 #endif /* INET */
3428 #ifdef INET6
3429 	case AF_INET6: {
3430 		int	i;
3431 
3432 		/* check a >= b */
3433 		for (i = 0; i < 4; ++i)
3434 			if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
3435 				break;
3436 			else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
3437 				return (0);
3438 		/* check a <= e */
3439 		for (i = 0; i < 4; ++i)
3440 			if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
3441 				break;
3442 			else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
3443 				return (0);
3444 		break;
3445 	}
3446 #endif /* INET6 */
3447 	}
3448 	return (1);
3449 }
3450 
3451 static int
3452 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
3453 {
3454 	switch (op) {
3455 	case PF_OP_IRG:
3456 		return ((p > a1) && (p < a2));
3457 	case PF_OP_XRG:
3458 		return ((p < a1) || (p > a2));
3459 	case PF_OP_RRG:
3460 		return ((p >= a1) && (p <= a2));
3461 	case PF_OP_EQ:
3462 		return (p == a1);
3463 	case PF_OP_NE:
3464 		return (p != a1);
3465 	case PF_OP_LT:
3466 		return (p < a1);
3467 	case PF_OP_LE:
3468 		return (p <= a1);
3469 	case PF_OP_GT:
3470 		return (p > a1);
3471 	case PF_OP_GE:
3472 		return (p >= a1);
3473 	}
3474 	return (0); /* never reached */
3475 }
3476 
3477 int
3478 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
3479 {
3480 	NTOHS(a1);
3481 	NTOHS(a2);
3482 	NTOHS(p);
3483 	return (pf_match(op, a1, a2, p));
3484 }
3485 
3486 static int
3487 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
3488 {
3489 	if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
3490 		return (0);
3491 	return (pf_match(op, a1, a2, u));
3492 }
3493 
3494 static int
3495 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
3496 {
3497 	if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
3498 		return (0);
3499 	return (pf_match(op, a1, a2, g));
3500 }
3501 
3502 int
3503 pf_match_tag(struct mbuf *m, struct pf_krule *r, int *tag, int mtag)
3504 {
3505 	if (*tag == -1)
3506 		*tag = mtag;
3507 
3508 	return ((!r->match_tag_not && r->match_tag == *tag) ||
3509 	    (r->match_tag_not && r->match_tag != *tag));
3510 }
3511 
3512 int
3513 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
3514 {
3515 
3516 	KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
3517 
3518 	if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
3519 		return (ENOMEM);
3520 
3521 	pd->pf_mtag->tag = tag;
3522 
3523 	return (0);
3524 }
3525 
3526 #define	PF_ANCHOR_STACKSIZE	32
3527 struct pf_kanchor_stackframe {
3528 	struct pf_kruleset	*rs;
3529 	struct pf_krule		*r;	/* XXX: + match bit */
3530 	struct pf_kanchor	*child;
3531 };
3532 
3533 /*
3534  * XXX: We rely on malloc(9) returning pointer aligned addresses.
3535  */
3536 #define	PF_ANCHORSTACK_MATCH	0x00000001
3537 #define	PF_ANCHORSTACK_MASK	(PF_ANCHORSTACK_MATCH)
3538 
3539 #define	PF_ANCHOR_MATCH(f)	((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
3540 #define	PF_ANCHOR_RULE(f)	(struct pf_krule *)			\
3541 				((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
3542 #define	PF_ANCHOR_SET_MATCH(f)	do { (f)->r = (void *) 			\
3543 				((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH);  \
3544 } while (0)
3545 
3546 void
3547 pf_step_into_anchor(struct pf_kanchor_stackframe *stack, int *depth,
3548     struct pf_kruleset **rs, int n, struct pf_krule **r, struct pf_krule **a,
3549     int *match)
3550 {
3551 	struct pf_kanchor_stackframe	*f;
3552 
3553 	PF_RULES_RASSERT();
3554 
3555 	if (match)
3556 		*match = 0;
3557 	if (*depth >= PF_ANCHOR_STACKSIZE) {
3558 		printf("%s: anchor stack overflow on %s\n",
3559 		    __func__, (*r)->anchor->name);
3560 		*r = TAILQ_NEXT(*r, entries);
3561 		return;
3562 	} else if (*depth == 0 && a != NULL)
3563 		*a = *r;
3564 	f = stack + (*depth)++;
3565 	f->rs = *rs;
3566 	f->r = *r;
3567 	if ((*r)->anchor_wildcard) {
3568 		struct pf_kanchor_node *parent = &(*r)->anchor->children;
3569 
3570 		if ((f->child = RB_MIN(pf_kanchor_node, parent)) == NULL) {
3571 			*r = NULL;
3572 			return;
3573 		}
3574 		*rs = &f->child->ruleset;
3575 	} else {
3576 		f->child = NULL;
3577 		*rs = &(*r)->anchor->ruleset;
3578 	}
3579 	*r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
3580 }
3581 
3582 int
3583 pf_step_out_of_anchor(struct pf_kanchor_stackframe *stack, int *depth,
3584     struct pf_kruleset **rs, int n, struct pf_krule **r, struct pf_krule **a,
3585     int *match)
3586 {
3587 	struct pf_kanchor_stackframe	*f;
3588 	struct pf_krule *fr;
3589 	int quick = 0;
3590 
3591 	PF_RULES_RASSERT();
3592 
3593 	do {
3594 		if (*depth <= 0)
3595 			break;
3596 		f = stack + *depth - 1;
3597 		fr = PF_ANCHOR_RULE(f);
3598 		if (f->child != NULL) {
3599 			/*
3600 			 * This block traverses through
3601 			 * a wildcard anchor.
3602 			 */
3603 			if (match != NULL && *match) {
3604 				/*
3605 				 * If any of "*" matched, then
3606 				 * "foo/ *" matched, mark frame
3607 				 * appropriately.
3608 				 */
3609 				PF_ANCHOR_SET_MATCH(f);
3610 				*match = 0;
3611 			}
3612 			f->child = RB_NEXT(pf_kanchor_node,
3613 			    &fr->anchor->children, f->child);
3614 			if (f->child != NULL) {
3615 				*rs = &f->child->ruleset;
3616 				*r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
3617 				if (*r == NULL)
3618 					continue;
3619 				else
3620 					break;
3621 			}
3622 		}
3623 		(*depth)--;
3624 		if (*depth == 0 && a != NULL)
3625 			*a = NULL;
3626 		*rs = f->rs;
3627 		if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
3628 			quick = fr->quick;
3629 		*r = TAILQ_NEXT(fr, entries);
3630 	} while (*r == NULL);
3631 
3632 	return (quick);
3633 }
3634 
3635 struct pf_keth_anchor_stackframe {
3636 	struct pf_keth_ruleset	*rs;
3637 	struct pf_keth_rule	*r;	/* XXX: + match bit */
3638 	struct pf_keth_anchor	*child;
3639 };
3640 
3641 #define	PF_ETH_ANCHOR_MATCH(f)	((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
3642 #define	PF_ETH_ANCHOR_RULE(f)	(struct pf_keth_rule *)			\
3643 				((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
3644 #define	PF_ETH_ANCHOR_SET_MATCH(f)	do { (f)->r = (void *) 		\
3645 				((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH);  \
3646 } while (0)
3647 
3648 void
3649 pf_step_into_keth_anchor(struct pf_keth_anchor_stackframe *stack, int *depth,
3650     struct pf_keth_ruleset **rs, struct pf_keth_rule **r,
3651     struct pf_keth_rule **a, int *match)
3652 {
3653 	struct pf_keth_anchor_stackframe	*f;
3654 
3655 	NET_EPOCH_ASSERT();
3656 
3657 	if (match)
3658 		*match = 0;
3659 	if (*depth >= PF_ANCHOR_STACKSIZE) {
3660 		printf("%s: anchor stack overflow on %s\n",
3661 		    __func__, (*r)->anchor->name);
3662 		*r = TAILQ_NEXT(*r, entries);
3663 		return;
3664 	} else if (*depth == 0 && a != NULL)
3665 		*a = *r;
3666 	f = stack + (*depth)++;
3667 	f->rs = *rs;
3668 	f->r = *r;
3669 	if ((*r)->anchor_wildcard) {
3670 		struct pf_keth_anchor_node *parent = &(*r)->anchor->children;
3671 
3672 		if ((f->child = RB_MIN(pf_keth_anchor_node, parent)) == NULL) {
3673 			*r = NULL;
3674 			return;
3675 		}
3676 		*rs = &f->child->ruleset;
3677 	} else {
3678 		f->child = NULL;
3679 		*rs = &(*r)->anchor->ruleset;
3680 	}
3681 	*r = TAILQ_FIRST((*rs)->active.rules);
3682 }
3683 
3684 int
3685 pf_step_out_of_keth_anchor(struct pf_keth_anchor_stackframe *stack, int *depth,
3686     struct pf_keth_ruleset **rs, struct pf_keth_rule **r,
3687     struct pf_keth_rule **a, int *match)
3688 {
3689 	struct pf_keth_anchor_stackframe	*f;
3690 	struct pf_keth_rule *fr;
3691 	int quick = 0;
3692 
3693 	NET_EPOCH_ASSERT();
3694 
3695 	do {
3696 		if (*depth <= 0)
3697 			break;
3698 		f = stack + *depth - 1;
3699 		fr = PF_ETH_ANCHOR_RULE(f);
3700 		if (f->child != NULL) {
3701 			/*
3702 			 * This block traverses through
3703 			 * a wildcard anchor.
3704 			 */
3705 			if (match != NULL && *match) {
3706 				/*
3707 				 * If any of "*" matched, then
3708 				 * "foo/ *" matched, mark frame
3709 				 * appropriately.
3710 				 */
3711 				PF_ETH_ANCHOR_SET_MATCH(f);
3712 				*match = 0;
3713 			}
3714 			f->child = RB_NEXT(pf_keth_anchor_node,
3715 			    &fr->anchor->children, f->child);
3716 			if (f->child != NULL) {
3717 				*rs = &f->child->ruleset;
3718 				*r = TAILQ_FIRST((*rs)->active.rules);
3719 				if (*r == NULL)
3720 					continue;
3721 				else
3722 					break;
3723 			}
3724 		}
3725 		(*depth)--;
3726 		if (*depth == 0 && a != NULL)
3727 			*a = NULL;
3728 		*rs = f->rs;
3729 		if (PF_ETH_ANCHOR_MATCH(f) || (match != NULL && *match))
3730 			quick = fr->quick;
3731 		*r = TAILQ_NEXT(fr, entries);
3732 	} while (*r == NULL);
3733 
3734 	return (quick);
3735 }
3736 
3737 #ifdef INET6
3738 void
3739 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
3740     struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
3741 {
3742 	switch (af) {
3743 #ifdef INET
3744 	case AF_INET:
3745 		naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
3746 		((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
3747 		break;
3748 #endif /* INET */
3749 	case AF_INET6:
3750 		naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
3751 		((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
3752 		naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
3753 		((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
3754 		naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
3755 		((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
3756 		naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
3757 		((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
3758 		break;
3759 	}
3760 }
3761 
3762 void
3763 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
3764 {
3765 	switch (af) {
3766 #ifdef INET
3767 	case AF_INET:
3768 		addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
3769 		break;
3770 #endif /* INET */
3771 	case AF_INET6:
3772 		if (addr->addr32[3] == 0xffffffff) {
3773 			addr->addr32[3] = 0;
3774 			if (addr->addr32[2] == 0xffffffff) {
3775 				addr->addr32[2] = 0;
3776 				if (addr->addr32[1] == 0xffffffff) {
3777 					addr->addr32[1] = 0;
3778 					addr->addr32[0] =
3779 					    htonl(ntohl(addr->addr32[0]) + 1);
3780 				} else
3781 					addr->addr32[1] =
3782 					    htonl(ntohl(addr->addr32[1]) + 1);
3783 			} else
3784 				addr->addr32[2] =
3785 				    htonl(ntohl(addr->addr32[2]) + 1);
3786 		} else
3787 			addr->addr32[3] =
3788 			    htonl(ntohl(addr->addr32[3]) + 1);
3789 		break;
3790 	}
3791 }
3792 #endif /* INET6 */
3793 
3794 void
3795 pf_rule_to_actions(struct pf_krule *r, struct pf_rule_actions *a)
3796 {
3797 	/*
3798 	 * Modern rules use the same flags in rules as they do in states.
3799 	 */
3800 	a->flags |= (r->scrub_flags & (PFSTATE_NODF|PFSTATE_RANDOMID|
3801 	    PFSTATE_SCRUB_TCP|PFSTATE_SETPRIO));
3802 
3803 	/*
3804 	 * Old-style scrub rules have different flags which need to be translated.
3805 	 */
3806 	if (r->rule_flag & PFRULE_RANDOMID)
3807 		a->flags |= PFSTATE_RANDOMID;
3808 	if (r->scrub_flags & PFSTATE_SETTOS || r->rule_flag & PFRULE_SET_TOS ) {
3809 		a->flags |= PFSTATE_SETTOS;
3810 		a->set_tos = r->set_tos;
3811 	}
3812 
3813 	if (r->qid)
3814 		a->qid = r->qid;
3815 	if (r->pqid)
3816 		a->pqid = r->pqid;
3817 	if (r->rtableid >= 0)
3818 		a->rtableid = r->rtableid;
3819 	a->log |= r->log;
3820 	if (r->min_ttl)
3821 		a->min_ttl = r->min_ttl;
3822 	if (r->max_mss)
3823 		a->max_mss = r->max_mss;
3824 	if (r->dnpipe)
3825 		a->dnpipe = r->dnpipe;
3826 	if (r->dnrpipe)
3827 		a->dnrpipe = r->dnrpipe;
3828 	if (r->dnpipe || r->dnrpipe) {
3829 		if (r->free_flags & PFRULE_DN_IS_PIPE)
3830 			a->flags |= PFSTATE_DN_IS_PIPE;
3831 		else
3832 			a->flags &= ~PFSTATE_DN_IS_PIPE;
3833 	}
3834 	if (r->scrub_flags & PFSTATE_SETPRIO) {
3835 		a->set_prio[0] = r->set_prio[0];
3836 		a->set_prio[1] = r->set_prio[1];
3837 	}
3838 }
3839 
3840 int
3841 pf_socket_lookup(struct pf_pdesc *pd, struct mbuf *m)
3842 {
3843 	struct pf_addr		*saddr, *daddr;
3844 	u_int16_t		 sport, dport;
3845 	struct inpcbinfo	*pi;
3846 	struct inpcb		*inp;
3847 
3848 	pd->lookup.uid = UID_MAX;
3849 	pd->lookup.gid = GID_MAX;
3850 
3851 	switch (pd->proto) {
3852 	case IPPROTO_TCP:
3853 		sport = pd->hdr.tcp.th_sport;
3854 		dport = pd->hdr.tcp.th_dport;
3855 		pi = &V_tcbinfo;
3856 		break;
3857 	case IPPROTO_UDP:
3858 		sport = pd->hdr.udp.uh_sport;
3859 		dport = pd->hdr.udp.uh_dport;
3860 		pi = &V_udbinfo;
3861 		break;
3862 	default:
3863 		return (-1);
3864 	}
3865 	if (pd->dir == PF_IN) {
3866 		saddr = pd->src;
3867 		daddr = pd->dst;
3868 	} else {
3869 		u_int16_t	p;
3870 
3871 		p = sport;
3872 		sport = dport;
3873 		dport = p;
3874 		saddr = pd->dst;
3875 		daddr = pd->src;
3876 	}
3877 	switch (pd->af) {
3878 #ifdef INET
3879 	case AF_INET:
3880 		inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
3881 		    dport, INPLOOKUP_RLOCKPCB, NULL, m);
3882 		if (inp == NULL) {
3883 			inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
3884 			   daddr->v4, dport, INPLOOKUP_WILDCARD |
3885 			   INPLOOKUP_RLOCKPCB, NULL, m);
3886 			if (inp == NULL)
3887 				return (-1);
3888 		}
3889 		break;
3890 #endif /* INET */
3891 #ifdef INET6
3892 	case AF_INET6:
3893 		inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
3894 		    dport, INPLOOKUP_RLOCKPCB, NULL, m);
3895 		if (inp == NULL) {
3896 			inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
3897 			    &daddr->v6, dport, INPLOOKUP_WILDCARD |
3898 			    INPLOOKUP_RLOCKPCB, NULL, m);
3899 			if (inp == NULL)
3900 				return (-1);
3901 		}
3902 		break;
3903 #endif /* INET6 */
3904 
3905 	default:
3906 		return (-1);
3907 	}
3908 	INP_RLOCK_ASSERT(inp);
3909 	pd->lookup.uid = inp->inp_cred->cr_uid;
3910 	pd->lookup.gid = inp->inp_cred->cr_groups[0];
3911 	INP_RUNLOCK(inp);
3912 
3913 	return (1);
3914 }
3915 
3916 u_int8_t
3917 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3918 {
3919 	int		 hlen;
3920 	u_int8_t	 hdr[60];
3921 	u_int8_t	*opt, optlen;
3922 	u_int8_t	 wscale = 0;
3923 
3924 	hlen = th_off << 2;		/* hlen <= sizeof(hdr) */
3925 	if (hlen <= sizeof(struct tcphdr))
3926 		return (0);
3927 	if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3928 		return (0);
3929 	opt = hdr + sizeof(struct tcphdr);
3930 	hlen -= sizeof(struct tcphdr);
3931 	while (hlen >= 3) {
3932 		switch (*opt) {
3933 		case TCPOPT_EOL:
3934 		case TCPOPT_NOP:
3935 			++opt;
3936 			--hlen;
3937 			break;
3938 		case TCPOPT_WINDOW:
3939 			wscale = opt[2];
3940 			if (wscale > TCP_MAX_WINSHIFT)
3941 				wscale = TCP_MAX_WINSHIFT;
3942 			wscale |= PF_WSCALE_FLAG;
3943 			/* FALLTHROUGH */
3944 		default:
3945 			optlen = opt[1];
3946 			if (optlen < 2)
3947 				optlen = 2;
3948 			hlen -= optlen;
3949 			opt += optlen;
3950 			break;
3951 		}
3952 	}
3953 	return (wscale);
3954 }
3955 
3956 u_int16_t
3957 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3958 {
3959 	int		 hlen;
3960 	u_int8_t	 hdr[60];
3961 	u_int8_t	*opt, optlen;
3962 	u_int16_t	 mss = V_tcp_mssdflt;
3963 
3964 	hlen = th_off << 2;	/* hlen <= sizeof(hdr) */
3965 	if (hlen <= sizeof(struct tcphdr))
3966 		return (0);
3967 	if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3968 		return (0);
3969 	opt = hdr + sizeof(struct tcphdr);
3970 	hlen -= sizeof(struct tcphdr);
3971 	while (hlen >= TCPOLEN_MAXSEG) {
3972 		switch (*opt) {
3973 		case TCPOPT_EOL:
3974 		case TCPOPT_NOP:
3975 			++opt;
3976 			--hlen;
3977 			break;
3978 		case TCPOPT_MAXSEG:
3979 			bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3980 			NTOHS(mss);
3981 			/* FALLTHROUGH */
3982 		default:
3983 			optlen = opt[1];
3984 			if (optlen < 2)
3985 				optlen = 2;
3986 			hlen -= optlen;
3987 			opt += optlen;
3988 			break;
3989 		}
3990 	}
3991 	return (mss);
3992 }
3993 
3994 static u_int16_t
3995 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3996 {
3997 	struct nhop_object *nh;
3998 #ifdef INET6
3999 	struct in6_addr		dst6;
4000 	uint32_t		scopeid;
4001 #endif /* INET6 */
4002 	int			 hlen = 0;
4003 	uint16_t		 mss = 0;
4004 
4005 	NET_EPOCH_ASSERT();
4006 
4007 	switch (af) {
4008 #ifdef INET
4009 	case AF_INET:
4010 		hlen = sizeof(struct ip);
4011 		nh = fib4_lookup(rtableid, addr->v4, 0, 0, 0);
4012 		if (nh != NULL)
4013 			mss = nh->nh_mtu - hlen - sizeof(struct tcphdr);
4014 		break;
4015 #endif /* INET */
4016 #ifdef INET6
4017 	case AF_INET6:
4018 		hlen = sizeof(struct ip6_hdr);
4019 		in6_splitscope(&addr->v6, &dst6, &scopeid);
4020 		nh = fib6_lookup(rtableid, &dst6, scopeid, 0, 0);
4021 		if (nh != NULL)
4022 			mss = nh->nh_mtu - hlen - sizeof(struct tcphdr);
4023 		break;
4024 #endif /* INET6 */
4025 	}
4026 
4027 	mss = max(V_tcp_mssdflt, mss);
4028 	mss = min(mss, offer);
4029 	mss = max(mss, 64);		/* sanity - at least max opt space */
4030 	return (mss);
4031 }
4032 
4033 static u_int32_t
4034 pf_tcp_iss(struct pf_pdesc *pd)
4035 {
4036 	MD5_CTX ctx;
4037 	u_int32_t digest[4];
4038 
4039 	if (V_pf_tcp_secret_init == 0) {
4040 		arc4random_buf(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
4041 		MD5Init(&V_pf_tcp_secret_ctx);
4042 		MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
4043 		    sizeof(V_pf_tcp_secret));
4044 		V_pf_tcp_secret_init = 1;
4045 	}
4046 
4047 	ctx = V_pf_tcp_secret_ctx;
4048 
4049 	MD5Update(&ctx, (char *)&pd->hdr.tcp.th_sport, sizeof(u_short));
4050 	MD5Update(&ctx, (char *)&pd->hdr.tcp.th_dport, sizeof(u_short));
4051 	if (pd->af == AF_INET6) {
4052 		MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
4053 		MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
4054 	} else {
4055 		MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
4056 		MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
4057 	}
4058 	MD5Final((u_char *)digest, &ctx);
4059 	V_pf_tcp_iss_off += 4096;
4060 #define	ISN_RANDOM_INCREMENT (4096 - 1)
4061 	return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
4062 	    V_pf_tcp_iss_off);
4063 #undef	ISN_RANDOM_INCREMENT
4064 }
4065 
4066 static bool
4067 pf_match_eth_addr(const uint8_t *a, const struct pf_keth_rule_addr *r)
4068 {
4069 	bool match = true;
4070 
4071 	/* Always matches if not set */
4072 	if (! r->isset)
4073 		return (!r->neg);
4074 
4075 	for (int i = 0; i < ETHER_ADDR_LEN; i++) {
4076 		if ((a[i] & r->mask[i]) != (r->addr[i] & r->mask[i])) {
4077 			match = false;
4078 			break;
4079 		}
4080 	}
4081 
4082 	return (match ^ r->neg);
4083 }
4084 
4085 static int
4086 pf_match_eth_tag(struct mbuf *m, struct pf_keth_rule *r, int *tag, int mtag)
4087 {
4088 	if (*tag == -1)
4089 		*tag = mtag;
4090 
4091 	return ((!r->match_tag_not && r->match_tag == *tag) ||
4092 	    (r->match_tag_not && r->match_tag != *tag));
4093 }
4094 
4095 static void
4096 pf_bridge_to(struct ifnet *ifp, struct mbuf *m)
4097 {
4098 	/* If we don't have the interface drop the packet. */
4099 	if (ifp == NULL) {
4100 		m_freem(m);
4101 		return;
4102 	}
4103 
4104 	switch (ifp->if_type) {
4105 	case IFT_ETHER:
4106 	case IFT_XETHER:
4107 	case IFT_L2VLAN:
4108 	case IFT_BRIDGE:
4109 	case IFT_IEEE8023ADLAG:
4110 		break;
4111 	default:
4112 		m_freem(m);
4113 		return;
4114 	}
4115 
4116 	ifp->if_transmit(ifp, m);
4117 }
4118 
4119 static int
4120 pf_test_eth_rule(int dir, struct pfi_kkif *kif, struct mbuf **m0)
4121 {
4122 #ifdef INET
4123 	struct ip ip;
4124 #endif
4125 #ifdef INET6
4126 	struct ip6_hdr ip6;
4127 #endif
4128 	struct mbuf *m = *m0;
4129 	struct ether_header *e;
4130 	struct pf_keth_rule *r, *rm, *a = NULL;
4131 	struct pf_keth_ruleset *ruleset = NULL;
4132 	struct pf_mtag *mtag;
4133 	struct pf_keth_ruleq *rules;
4134 	struct pf_addr *src = NULL, *dst = NULL;
4135 	struct pfi_kkif *bridge_to;
4136 	sa_family_t af = 0;
4137 	uint16_t proto;
4138 	int asd = 0, match = 0;
4139 	int tag = -1;
4140 	uint8_t action;
4141 	struct pf_keth_anchor_stackframe	anchor_stack[PF_ANCHOR_STACKSIZE];
4142 
4143 	MPASS(kif->pfik_ifp->if_vnet == curvnet);
4144 	NET_EPOCH_ASSERT();
4145 
4146 	PF_RULES_RLOCK_TRACKER;
4147 
4148 	SDT_PROBE3(pf, eth, test_rule, entry, dir, kif->pfik_ifp, m);
4149 
4150 	mtag = pf_find_mtag(m);
4151 	if (mtag != NULL && mtag->flags & PF_MTAG_FLAG_DUMMYNET) {
4152 		/* Dummynet re-injects packets after they've
4153 		 * completed their delay. We've already
4154 		 * processed them, so pass unconditionally. */
4155 
4156 		/* But only once. We may see the packet multiple times (e.g.
4157 		 * PFIL_IN/PFIL_OUT). */
4158 		pf_dummynet_flag_remove(m, mtag);
4159 
4160 		return (PF_PASS);
4161 	}
4162 
4163 	ruleset = V_pf_keth;
4164 	rules = ck_pr_load_ptr(&ruleset->active.rules);
4165 	r = TAILQ_FIRST(rules);
4166 	rm = NULL;
4167 
4168 	e = mtod(m, struct ether_header *);
4169 	proto = ntohs(e->ether_type);
4170 
4171 	switch (proto) {
4172 #ifdef INET
4173 	case ETHERTYPE_IP: {
4174 		if (m_length(m, NULL) < (sizeof(struct ether_header) +
4175 		    sizeof(ip)))
4176 			return (PF_DROP);
4177 
4178 		af = AF_INET;
4179 		m_copydata(m, sizeof(struct ether_header), sizeof(ip),
4180 		    (caddr_t)&ip);
4181 		src = (struct pf_addr *)&ip.ip_src;
4182 		dst = (struct pf_addr *)&ip.ip_dst;
4183 		break;
4184 	}
4185 #endif /* INET */
4186 #ifdef INET6
4187 	case ETHERTYPE_IPV6: {
4188 		if (m_length(m, NULL) < (sizeof(struct ether_header) +
4189 		    sizeof(ip6)))
4190 			return (PF_DROP);
4191 
4192 		af = AF_INET6;
4193 		m_copydata(m, sizeof(struct ether_header), sizeof(ip6),
4194 		    (caddr_t)&ip6);
4195 		src = (struct pf_addr *)&ip6.ip6_src;
4196 		dst = (struct pf_addr *)&ip6.ip6_dst;
4197 		break;
4198 	}
4199 #endif /* INET6 */
4200 	}
4201 
4202 	PF_RULES_RLOCK();
4203 
4204 	while (r != NULL) {
4205 		counter_u64_add(r->evaluations, 1);
4206 		SDT_PROBE2(pf, eth, test_rule, test, r->nr, r);
4207 
4208 		if (pfi_kkif_match(r->kif, kif) == r->ifnot) {
4209 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4210 			    "kif");
4211 			r = r->skip[PFE_SKIP_IFP].ptr;
4212 		}
4213 		else if (r->direction && r->direction != dir) {
4214 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4215 			    "dir");
4216 			r = r->skip[PFE_SKIP_DIR].ptr;
4217 		}
4218 		else if (r->proto && r->proto != proto) {
4219 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4220 			    "proto");
4221 			r = r->skip[PFE_SKIP_PROTO].ptr;
4222 		}
4223 		else if (! pf_match_eth_addr(e->ether_shost, &r->src)) {
4224 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4225 			    "src");
4226 			r = r->skip[PFE_SKIP_SRC_ADDR].ptr;
4227 		}
4228 		else if (! pf_match_eth_addr(e->ether_dhost, &r->dst)) {
4229 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4230 			    "dst");
4231 			r = r->skip[PFE_SKIP_DST_ADDR].ptr;
4232 		}
4233 		else if (src != NULL && PF_MISMATCHAW(&r->ipsrc.addr, src, af,
4234 		    r->ipsrc.neg, kif, M_GETFIB(m))) {
4235 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4236 			    "ip_src");
4237 			r = r->skip[PFE_SKIP_SRC_IP_ADDR].ptr;
4238 		}
4239 		else if (dst != NULL && PF_MISMATCHAW(&r->ipdst.addr, dst, af,
4240 		    r->ipdst.neg, kif, M_GETFIB(m))) {
4241 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4242 			    "ip_dst");
4243 			r = r->skip[PFE_SKIP_DST_IP_ADDR].ptr;
4244 		}
4245 		else if (r->match_tag && !pf_match_eth_tag(m, r, &tag,
4246 		    mtag ? mtag->tag : 0)) {
4247 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4248 			    "match_tag");
4249 			r = TAILQ_NEXT(r, entries);
4250 		}
4251 		else {
4252 			if (r->tag)
4253 				tag = r->tag;
4254 			if (r->anchor == NULL) {
4255 				/* Rule matches */
4256 				rm = r;
4257 
4258 				SDT_PROBE2(pf, eth, test_rule, match, r->nr, r);
4259 
4260 				if (r->quick)
4261 					break;
4262 
4263 				r = TAILQ_NEXT(r, entries);
4264 			} else {
4265 				pf_step_into_keth_anchor(anchor_stack, &asd,
4266 				    &ruleset, &r, &a, &match);
4267 			}
4268 		}
4269 		if (r == NULL && pf_step_out_of_keth_anchor(anchor_stack, &asd,
4270 		    &ruleset, &r, &a, &match))
4271 			break;
4272 	}
4273 
4274 	r = rm;
4275 
4276 	SDT_PROBE2(pf, eth, test_rule, final_match, (r != NULL ? r->nr : -1), r);
4277 
4278 	/* Default to pass. */
4279 	if (r == NULL) {
4280 		PF_RULES_RUNLOCK();
4281 		return (PF_PASS);
4282 	}
4283 
4284 	/* Execute action. */
4285 	counter_u64_add(r->packets[dir == PF_OUT], 1);
4286 	counter_u64_add(r->bytes[dir == PF_OUT], m_length(m, NULL));
4287 	pf_update_timestamp(r);
4288 
4289 	/* Shortcut. Don't tag if we're just going to drop anyway. */
4290 	if (r->action == PF_DROP) {
4291 		PF_RULES_RUNLOCK();
4292 		return (PF_DROP);
4293 	}
4294 
4295 	if (tag > 0) {
4296 		if (mtag == NULL)
4297 			mtag = pf_get_mtag(m);
4298 		if (mtag == NULL) {
4299 			PF_RULES_RUNLOCK();
4300 			counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
4301 			return (PF_DROP);
4302 		}
4303 		mtag->tag = tag;
4304 	}
4305 
4306 	if (r->qid != 0) {
4307 		if (mtag == NULL)
4308 			mtag = pf_get_mtag(m);
4309 		if (mtag == NULL) {
4310 			PF_RULES_RUNLOCK();
4311 			counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
4312 			return (PF_DROP);
4313 		}
4314 		mtag->qid = r->qid;
4315 	}
4316 
4317 	action = r->action;
4318 	bridge_to = r->bridge_to;
4319 
4320 	/* Dummynet */
4321 	if (r->dnpipe) {
4322 		struct ip_fw_args dnflow;
4323 
4324 		/* Drop packet if dummynet is not loaded. */
4325 		if (ip_dn_io_ptr == NULL) {
4326 			PF_RULES_RUNLOCK();
4327 			m_freem(m);
4328 			counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
4329 			return (PF_DROP);
4330 		}
4331 		if (mtag == NULL)
4332 			mtag = pf_get_mtag(m);
4333 		if (mtag == NULL) {
4334 			PF_RULES_RUNLOCK();
4335 			counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
4336 			return (PF_DROP);
4337 		}
4338 
4339 		bzero(&dnflow, sizeof(dnflow));
4340 
4341 		/* We don't have port numbers here, so we set 0.  That means
4342 		 * that we'll be somewhat limited in distinguishing flows (i.e.
4343 		 * only based on IP addresses, not based on port numbers), but
4344 		 * it's better than nothing. */
4345 		dnflow.f_id.dst_port = 0;
4346 		dnflow.f_id.src_port = 0;
4347 		dnflow.f_id.proto = 0;
4348 
4349 		dnflow.rule.info = r->dnpipe;
4350 		dnflow.rule.info |= IPFW_IS_DUMMYNET;
4351 		if (r->dnflags & PFRULE_DN_IS_PIPE)
4352 			dnflow.rule.info |= IPFW_IS_PIPE;
4353 
4354 		dnflow.f_id.extra = dnflow.rule.info;
4355 
4356 		dnflow.flags = dir == PF_IN ? IPFW_ARGS_IN : IPFW_ARGS_OUT;
4357 		dnflow.flags |= IPFW_ARGS_ETHER;
4358 		dnflow.ifp = kif->pfik_ifp;
4359 
4360 		switch (af) {
4361 		case AF_INET:
4362 			dnflow.f_id.addr_type = 4;
4363 			dnflow.f_id.src_ip = src->v4.s_addr;
4364 			dnflow.f_id.dst_ip = dst->v4.s_addr;
4365 			break;
4366 		case AF_INET6:
4367 			dnflow.flags |= IPFW_ARGS_IP6;
4368 			dnflow.f_id.addr_type = 6;
4369 			dnflow.f_id.src_ip6 = src->v6;
4370 			dnflow.f_id.dst_ip6 = dst->v6;
4371 			break;
4372 		}
4373 
4374 		PF_RULES_RUNLOCK();
4375 
4376 		mtag->flags |= PF_MTAG_FLAG_DUMMYNET;
4377 		ip_dn_io_ptr(m0, &dnflow);
4378 		if (*m0 != NULL)
4379 			pf_dummynet_flag_remove(m, mtag);
4380 	} else {
4381 		PF_RULES_RUNLOCK();
4382 	}
4383 
4384 	if (action == PF_PASS && bridge_to) {
4385 		pf_bridge_to(bridge_to->pfik_ifp, *m0);
4386 		*m0 = NULL; /* We've eaten the packet. */
4387 	}
4388 
4389 	return (action);
4390 }
4391 
4392 static int
4393 pf_test_rule(struct pf_krule **rm, struct pf_kstate **sm, struct pfi_kkif *kif,
4394     struct mbuf *m, int off, struct pf_pdesc *pd, struct pf_krule **am,
4395     struct pf_kruleset **rsm, struct inpcb *inp)
4396 {
4397 	struct pf_krule		*nr = NULL;
4398 	struct pf_addr		* const saddr = pd->src;
4399 	struct pf_addr		* const daddr = pd->dst;
4400 	sa_family_t		 af = pd->af;
4401 	struct pf_krule		*r, *a = NULL;
4402 	struct pf_kruleset	*ruleset = NULL;
4403 	struct pf_krule_slist	 match_rules;
4404 	struct pf_krule_item	*ri;
4405 	struct pf_ksrc_node	*nsn = NULL;
4406 	struct tcphdr		*th = &pd->hdr.tcp;
4407 	struct pf_state_key	*sk = NULL, *nk = NULL;
4408 	u_short			 reason;
4409 	int			 rewrite = 0, hdrlen = 0;
4410 	int			 tag = -1;
4411 	int			 asd = 0;
4412 	int			 match = 0;
4413 	int			 state_icmp = 0;
4414 	u_int16_t		 sport = 0, dport = 0;
4415 	u_int16_t		 bproto_sum = 0, bip_sum = 0;
4416 	u_int8_t		 icmptype = 0, icmpcode = 0;
4417 	struct pf_kanchor_stackframe	anchor_stack[PF_ANCHOR_STACKSIZE];
4418 
4419 	PF_RULES_RASSERT();
4420 
4421 	if (inp != NULL) {
4422 		INP_LOCK_ASSERT(inp);
4423 		pd->lookup.uid = inp->inp_cred->cr_uid;
4424 		pd->lookup.gid = inp->inp_cred->cr_groups[0];
4425 		pd->lookup.done = 1;
4426 	}
4427 
4428 	switch (pd->proto) {
4429 	case IPPROTO_TCP:
4430 		sport = th->th_sport;
4431 		dport = th->th_dport;
4432 		hdrlen = sizeof(*th);
4433 		break;
4434 	case IPPROTO_UDP:
4435 		sport = pd->hdr.udp.uh_sport;
4436 		dport = pd->hdr.udp.uh_dport;
4437 		hdrlen = sizeof(pd->hdr.udp);
4438 		break;
4439 	case IPPROTO_SCTP:
4440 		sport = pd->hdr.sctp.src_port;
4441 		dport = pd->hdr.sctp.dest_port;
4442 		hdrlen = sizeof(pd->hdr.sctp);
4443 		break;
4444 #ifdef INET
4445 	case IPPROTO_ICMP:
4446 		if (pd->af != AF_INET)
4447 			break;
4448 		sport = dport = pd->hdr.icmp.icmp_id;
4449 		hdrlen = sizeof(pd->hdr.icmp);
4450 		icmptype = pd->hdr.icmp.icmp_type;
4451 		icmpcode = pd->hdr.icmp.icmp_code;
4452 
4453 		if (icmptype == ICMP_UNREACH ||
4454 		    icmptype == ICMP_SOURCEQUENCH ||
4455 		    icmptype == ICMP_REDIRECT ||
4456 		    icmptype == ICMP_TIMXCEED ||
4457 		    icmptype == ICMP_PARAMPROB)
4458 			state_icmp++;
4459 		break;
4460 #endif /* INET */
4461 #ifdef INET6
4462 	case IPPROTO_ICMPV6:
4463 		if (af != AF_INET6)
4464 			break;
4465 		sport = dport = pd->hdr.icmp6.icmp6_id;
4466 		hdrlen = sizeof(pd->hdr.icmp6);
4467 		icmptype = pd->hdr.icmp6.icmp6_type;
4468 		icmpcode = pd->hdr.icmp6.icmp6_code;
4469 
4470 		if (icmptype == ICMP6_DST_UNREACH ||
4471 		    icmptype == ICMP6_PACKET_TOO_BIG ||
4472 		    icmptype == ICMP6_TIME_EXCEEDED ||
4473 		    icmptype == ICMP6_PARAM_PROB)
4474 			state_icmp++;
4475 		break;
4476 #endif /* INET6 */
4477 	default:
4478 		sport = dport = hdrlen = 0;
4479 		break;
4480 	}
4481 
4482 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
4483 
4484 	/* check packet for BINAT/NAT/RDR */
4485 	if ((nr = pf_get_translation(pd, m, off, kif, &nsn, &sk,
4486 	    &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
4487 		KASSERT(sk != NULL, ("%s: null sk", __func__));
4488 		KASSERT(nk != NULL, ("%s: null nk", __func__));
4489 
4490 		if (nr->log) {
4491 			PFLOG_PACKET(kif, m, af, PF_PASS, PFRES_MATCH, nr, a,
4492 			    ruleset, pd, 1);
4493 		}
4494 
4495 		if (pd->ip_sum)
4496 			bip_sum = *pd->ip_sum;
4497 
4498 		switch (pd->proto) {
4499 		case IPPROTO_TCP:
4500 			bproto_sum = th->th_sum;
4501 			pd->proto_sum = &th->th_sum;
4502 
4503 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
4504 			    nk->port[pd->sidx] != sport) {
4505 				pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
4506 				    &th->th_sum, &nk->addr[pd->sidx],
4507 				    nk->port[pd->sidx], 0, af);
4508 				pd->sport = &th->th_sport;
4509 				sport = th->th_sport;
4510 			}
4511 
4512 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
4513 			    nk->port[pd->didx] != dport) {
4514 				pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
4515 				    &th->th_sum, &nk->addr[pd->didx],
4516 				    nk->port[pd->didx], 0, af);
4517 				dport = th->th_dport;
4518 				pd->dport = &th->th_dport;
4519 			}
4520 			rewrite++;
4521 			break;
4522 		case IPPROTO_UDP:
4523 			bproto_sum = pd->hdr.udp.uh_sum;
4524 			pd->proto_sum = &pd->hdr.udp.uh_sum;
4525 
4526 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
4527 			    nk->port[pd->sidx] != sport) {
4528 				pf_change_ap(m, saddr, &pd->hdr.udp.uh_sport,
4529 				    pd->ip_sum, &pd->hdr.udp.uh_sum,
4530 				    &nk->addr[pd->sidx],
4531 				    nk->port[pd->sidx], 1, af);
4532 				sport = pd->hdr.udp.uh_sport;
4533 				pd->sport = &pd->hdr.udp.uh_sport;
4534 			}
4535 
4536 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
4537 			    nk->port[pd->didx] != dport) {
4538 				pf_change_ap(m, daddr, &pd->hdr.udp.uh_dport,
4539 				    pd->ip_sum, &pd->hdr.udp.uh_sum,
4540 				    &nk->addr[pd->didx],
4541 				    nk->port[pd->didx], 1, af);
4542 				dport = pd->hdr.udp.uh_dport;
4543 				pd->dport = &pd->hdr.udp.uh_dport;
4544 			}
4545 			rewrite++;
4546 			break;
4547 		case IPPROTO_SCTP: {
4548 			uint16_t checksum = 0;
4549 
4550 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
4551 			    nk->port[pd->sidx] != sport) {
4552 				pf_change_ap(m, saddr, &pd->hdr.sctp.src_port,
4553 				    pd->ip_sum, &checksum,
4554 				    &nk->addr[pd->sidx],
4555 				    nk->port[pd->sidx], 1, af);
4556 			}
4557 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
4558 			    nk->port[pd->didx] != dport) {
4559 				pf_change_ap(m, daddr, &pd->hdr.sctp.dest_port,
4560 				    pd->ip_sum, &checksum,
4561 				    &nk->addr[pd->didx],
4562 				    nk->port[pd->didx], 1, af);
4563 			}
4564 			break;
4565 		}
4566 #ifdef INET
4567 		case IPPROTO_ICMP:
4568 			nk->port[0] = nk->port[1];
4569 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
4570 				pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
4571 				    nk->addr[pd->sidx].v4.s_addr, 0);
4572 
4573 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
4574 				pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
4575 				    nk->addr[pd->didx].v4.s_addr, 0);
4576 
4577 			if (nk->port[1] != pd->hdr.icmp.icmp_id) {
4578 				pd->hdr.icmp.icmp_cksum = pf_cksum_fixup(
4579 				    pd->hdr.icmp.icmp_cksum, sport,
4580 				    nk->port[1], 0);
4581 				pd->hdr.icmp.icmp_id = nk->port[1];
4582 				pd->sport = &pd->hdr.icmp.icmp_id;
4583 			}
4584 			m_copyback(m, off, ICMP_MINLEN, (caddr_t)&pd->hdr.icmp);
4585 			break;
4586 #endif /* INET */
4587 #ifdef INET6
4588 		case IPPROTO_ICMPV6:
4589 			nk->port[0] = nk->port[1];
4590 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
4591 				pf_change_a6(saddr, &pd->hdr.icmp6.icmp6_cksum,
4592 				    &nk->addr[pd->sidx], 0);
4593 
4594 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
4595 				pf_change_a6(daddr, &pd->hdr.icmp6.icmp6_cksum,
4596 				    &nk->addr[pd->didx], 0);
4597 			rewrite++;
4598 			break;
4599 #endif /* INET */
4600 		default:
4601 			switch (af) {
4602 #ifdef INET
4603 			case AF_INET:
4604 				if (PF_ANEQ(saddr,
4605 				    &nk->addr[pd->sidx], AF_INET))
4606 					pf_change_a(&saddr->v4.s_addr,
4607 					    pd->ip_sum,
4608 					    nk->addr[pd->sidx].v4.s_addr, 0);
4609 
4610 				if (PF_ANEQ(daddr,
4611 				    &nk->addr[pd->didx], AF_INET))
4612 					pf_change_a(&daddr->v4.s_addr,
4613 					    pd->ip_sum,
4614 					    nk->addr[pd->didx].v4.s_addr, 0);
4615 				break;
4616 #endif /* INET */
4617 #ifdef INET6
4618 			case AF_INET6:
4619 				if (PF_ANEQ(saddr,
4620 				    &nk->addr[pd->sidx], AF_INET6))
4621 					PF_ACPY(saddr, &nk->addr[pd->sidx], af);
4622 
4623 				if (PF_ANEQ(daddr,
4624 				    &nk->addr[pd->didx], AF_INET6))
4625 					PF_ACPY(daddr, &nk->addr[pd->didx], af);
4626 				break;
4627 #endif /* INET */
4628 			}
4629 			break;
4630 		}
4631 		if (nr->natpass)
4632 			r = NULL;
4633 		pd->nat_rule = nr;
4634 	}
4635 
4636 	SLIST_INIT(&match_rules);
4637 	while (r != NULL) {
4638 		pf_counter_u64_add(&r->evaluations, 1);
4639 		if (pfi_kkif_match(r->kif, kif) == r->ifnot)
4640 			r = r->skip[PF_SKIP_IFP].ptr;
4641 		else if (r->direction && r->direction != pd->dir)
4642 			r = r->skip[PF_SKIP_DIR].ptr;
4643 		else if (r->af && r->af != af)
4644 			r = r->skip[PF_SKIP_AF].ptr;
4645 		else if (r->proto && r->proto != pd->proto)
4646 			r = r->skip[PF_SKIP_PROTO].ptr;
4647 		else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
4648 		    r->src.neg, kif, M_GETFIB(m)))
4649 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
4650 		/* tcp/udp only. port_op always 0 in other cases */
4651 		else if (r->src.port_op && !pf_match_port(r->src.port_op,
4652 		    r->src.port[0], r->src.port[1], sport))
4653 			r = r->skip[PF_SKIP_SRC_PORT].ptr;
4654 		else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
4655 		    r->dst.neg, NULL, M_GETFIB(m)))
4656 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
4657 		/* tcp/udp only. port_op always 0 in other cases */
4658 		else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
4659 		    r->dst.port[0], r->dst.port[1], dport))
4660 			r = r->skip[PF_SKIP_DST_PORT].ptr;
4661 		/* icmp only. type always 0 in other cases */
4662 		else if (r->type && r->type != icmptype + 1)
4663 			r = TAILQ_NEXT(r, entries);
4664 		/* icmp only. type always 0 in other cases */
4665 		else if (r->code && r->code != icmpcode + 1)
4666 			r = TAILQ_NEXT(r, entries);
4667 		else if (r->tos && !(r->tos == pd->tos))
4668 			r = TAILQ_NEXT(r, entries);
4669 		else if (r->rule_flag & PFRULE_FRAGMENT)
4670 			r = TAILQ_NEXT(r, entries);
4671 		else if (pd->proto == IPPROTO_TCP &&
4672 		    (r->flagset & th->th_flags) != r->flags)
4673 			r = TAILQ_NEXT(r, entries);
4674 		/* tcp/udp only. uid.op always 0 in other cases */
4675 		else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
4676 		    pf_socket_lookup(pd, m), 1)) &&
4677 		    !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
4678 		    pd->lookup.uid))
4679 			r = TAILQ_NEXT(r, entries);
4680 		/* tcp/udp only. gid.op always 0 in other cases */
4681 		else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
4682 		    pf_socket_lookup(pd, m), 1)) &&
4683 		    !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
4684 		    pd->lookup.gid))
4685 			r = TAILQ_NEXT(r, entries);
4686 		else if (r->prio &&
4687 		    !pf_match_ieee8021q_pcp(r->prio, m))
4688 			r = TAILQ_NEXT(r, entries);
4689 		else if (r->prob &&
4690 		    r->prob <= arc4random())
4691 			r = TAILQ_NEXT(r, entries);
4692 		else if (r->match_tag && !pf_match_tag(m, r, &tag,
4693 		    pd->pf_mtag ? pd->pf_mtag->tag : 0))
4694 			r = TAILQ_NEXT(r, entries);
4695 		else if (r->os_fingerprint != PF_OSFP_ANY &&
4696 		    (pd->proto != IPPROTO_TCP || !pf_osfp_match(
4697 		    pf_osfp_fingerprint(pd, m, off, th),
4698 		    r->os_fingerprint)))
4699 			r = TAILQ_NEXT(r, entries);
4700 		else {
4701 			if (r->tag)
4702 				tag = r->tag;
4703 			if (r->anchor == NULL) {
4704 				if (r->action == PF_MATCH) {
4705 					ri = malloc(sizeof(struct pf_krule_item), M_PF_RULE_ITEM, M_NOWAIT | M_ZERO);
4706 					if (ri == NULL) {
4707 						REASON_SET(&reason, PFRES_MEMORY);
4708 						goto cleanup;
4709 					}
4710 					ri->r = r;
4711 					SLIST_INSERT_HEAD(&match_rules, ri, entry);
4712 					pf_counter_u64_critical_enter();
4713 					pf_counter_u64_add_protected(&r->packets[pd->dir == PF_OUT], 1);
4714 					pf_counter_u64_add_protected(&r->bytes[pd->dir == PF_OUT], pd->tot_len);
4715 					pf_counter_u64_critical_exit();
4716 					pf_rule_to_actions(r, &pd->act);
4717 					if (r->log)
4718 						PFLOG_PACKET(kif, m, af,
4719 						    r->action, PFRES_MATCH, r,
4720 						    a, ruleset, pd, 1);
4721 				} else {
4722 					match = 1;
4723 					*rm = r;
4724 					*am = a;
4725 					*rsm = ruleset;
4726 				}
4727 				if ((*rm)->quick)
4728 					break;
4729 				r = TAILQ_NEXT(r, entries);
4730 			} else
4731 				pf_step_into_anchor(anchor_stack, &asd,
4732 				    &ruleset, PF_RULESET_FILTER, &r, &a,
4733 				    &match);
4734 		}
4735 		if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
4736 		    &ruleset, PF_RULESET_FILTER, &r, &a, &match))
4737 			break;
4738 	}
4739 	r = *rm;
4740 	a = *am;
4741 	ruleset = *rsm;
4742 
4743 	REASON_SET(&reason, PFRES_MATCH);
4744 
4745 	/* apply actions for last matching pass/block rule */
4746 	pf_rule_to_actions(r, &pd->act);
4747 
4748 	if (r->log) {
4749 		if (rewrite)
4750 			m_copyback(m, off, hdrlen, pd->hdr.any);
4751 		PFLOG_PACKET(kif, m, af, r->action, reason, r, a, ruleset, pd, 1);
4752 	}
4753 
4754 	if ((r->action == PF_DROP) &&
4755 	    ((r->rule_flag & PFRULE_RETURNRST) ||
4756 	    (r->rule_flag & PFRULE_RETURNICMP) ||
4757 	    (r->rule_flag & PFRULE_RETURN))) {
4758 		pf_return(r, nr, pd, sk, off, m, th, kif, bproto_sum,
4759 		    bip_sum, hdrlen, &reason, r->rtableid);
4760 	}
4761 
4762 	if (r->action == PF_DROP)
4763 		goto cleanup;
4764 
4765 	if (tag > 0 && pf_tag_packet(m, pd, tag)) {
4766 		REASON_SET(&reason, PFRES_MEMORY);
4767 		goto cleanup;
4768 	}
4769 	if (pd->act.rtableid >= 0)
4770 		M_SETFIB(m, pd->act.rtableid);
4771 
4772 	if (!state_icmp && (r->keep_state || nr != NULL ||
4773 	    (pd->flags & PFDESC_TCP_NORM))) {
4774 		int action;
4775 		action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
4776 		    sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
4777 		    hdrlen, &match_rules);
4778 		if (action != PF_PASS) {
4779 			if (action == PF_DROP &&
4780 			    (r->rule_flag & PFRULE_RETURN))
4781 				pf_return(r, nr, pd, sk, off, m, th, kif,
4782 				    bproto_sum, bip_sum, hdrlen, &reason,
4783 				    pd->act.rtableid);
4784 			return (action);
4785 		}
4786 	} else {
4787 		while ((ri = SLIST_FIRST(&match_rules))) {
4788 			SLIST_REMOVE_HEAD(&match_rules, entry);
4789 			free(ri, M_PF_RULE_ITEM);
4790 		}
4791 
4792 		uma_zfree(V_pf_state_key_z, sk);
4793 		uma_zfree(V_pf_state_key_z, nk);
4794 	}
4795 
4796 	/* copy back packet headers if we performed NAT operations */
4797 	if (rewrite)
4798 		m_copyback(m, off, hdrlen, pd->hdr.any);
4799 
4800 	if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
4801 	    pd->dir == PF_OUT &&
4802 	    V_pfsync_defer_ptr != NULL && V_pfsync_defer_ptr(*sm, m))
4803 		/*
4804 		 * We want the state created, but we dont
4805 		 * want to send this in case a partner
4806 		 * firewall has to know about it to allow
4807 		 * replies through it.
4808 		 */
4809 		return (PF_DEFER);
4810 
4811 	return (PF_PASS);
4812 
4813 cleanup:
4814 	while ((ri = SLIST_FIRST(&match_rules))) {
4815 		SLIST_REMOVE_HEAD(&match_rules, entry);
4816 		free(ri, M_PF_RULE_ITEM);
4817 	}
4818 
4819 	uma_zfree(V_pf_state_key_z, sk);
4820 	uma_zfree(V_pf_state_key_z, nk);
4821 	return (PF_DROP);
4822 }
4823 
4824 static int
4825 pf_create_state(struct pf_krule *r, struct pf_krule *nr, struct pf_krule *a,
4826     struct pf_pdesc *pd, struct pf_ksrc_node *nsn, struct pf_state_key *nk,
4827     struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
4828     u_int16_t dport, int *rewrite, struct pfi_kkif *kif, struct pf_kstate **sm,
4829     int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen,
4830     struct pf_krule_slist *match_rules)
4831 {
4832 	struct pf_kstate	*s = NULL;
4833 	struct pf_ksrc_node	*sn = NULL;
4834 	struct tcphdr		*th = &pd->hdr.tcp;
4835 	u_int16_t		 mss = V_tcp_mssdflt;
4836 	u_short			 reason, sn_reason;
4837 	struct pf_krule_item	*ri;
4838 
4839 	/* check maximums */
4840 	if (r->max_states &&
4841 	    (counter_u64_fetch(r->states_cur) >= r->max_states)) {
4842 		counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
4843 		REASON_SET(&reason, PFRES_MAXSTATES);
4844 		goto csfailed;
4845 	}
4846 	/* src node for filter rule */
4847 	if ((r->rule_flag & PFRULE_SRCTRACK ||
4848 	    r->rpool.opts & PF_POOL_STICKYADDR) &&
4849 	    (sn_reason = pf_insert_src_node(&sn, r, pd->src, pd->af)) != 0) {
4850 		REASON_SET(&reason, sn_reason);
4851 		goto csfailed;
4852 	}
4853 	/* src node for translation rule */
4854 	if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
4855 	    (sn_reason = pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx],
4856 	    pd->af)) != 0 ) {
4857 		REASON_SET(&reason, sn_reason);
4858 		goto csfailed;
4859 	}
4860 	s = pf_alloc_state(M_NOWAIT);
4861 	if (s == NULL) {
4862 		REASON_SET(&reason, PFRES_MEMORY);
4863 		goto csfailed;
4864 	}
4865 	s->rule.ptr = r;
4866 	s->nat_rule.ptr = nr;
4867 	s->anchor.ptr = a;
4868 	bcopy(match_rules, &s->match_rules, sizeof(s->match_rules));
4869 	memcpy(&s->act, &pd->act, sizeof(struct pf_rule_actions));
4870 
4871 	STATE_INC_COUNTERS(s);
4872 	if (r->allow_opts)
4873 		s->state_flags |= PFSTATE_ALLOWOPTS;
4874 	if (r->rule_flag & PFRULE_STATESLOPPY)
4875 		s->state_flags |= PFSTATE_SLOPPY;
4876 	if (pd->flags & PFDESC_TCP_NORM) /* Set by old-style scrub rules */
4877 		s->state_flags |= PFSTATE_SCRUB_TCP;
4878 	if ((r->rule_flag & PFRULE_PFLOW) ||
4879 	    (nr != NULL && nr->rule_flag & PFRULE_PFLOW))
4880 		s->state_flags |= PFSTATE_PFLOW;
4881 
4882 	s->act.log = pd->act.log & PF_LOG_ALL;
4883 	s->sync_state = PFSYNC_S_NONE;
4884 	s->state_flags |= pd->act.flags; /* Only needed for pfsync and state export */
4885 
4886 	if (nr != NULL)
4887 		s->act.log |= nr->log & PF_LOG_ALL;
4888 	switch (pd->proto) {
4889 	case IPPROTO_TCP:
4890 		s->src.seqlo = ntohl(th->th_seq);
4891 		s->src.seqhi = s->src.seqlo + pd->p_len + 1;
4892 		if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
4893 		    r->keep_state == PF_STATE_MODULATE) {
4894 			/* Generate sequence number modulator */
4895 			if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
4896 			    0)
4897 				s->src.seqdiff = 1;
4898 			pf_change_proto_a(m, &th->th_seq, &th->th_sum,
4899 			    htonl(s->src.seqlo + s->src.seqdiff), 0);
4900 			*rewrite = 1;
4901 		} else
4902 			s->src.seqdiff = 0;
4903 		if (th->th_flags & TH_SYN) {
4904 			s->src.seqhi++;
4905 			s->src.wscale = pf_get_wscale(m, off,
4906 			    th->th_off, pd->af);
4907 		}
4908 		s->src.max_win = MAX(ntohs(th->th_win), 1);
4909 		if (s->src.wscale & PF_WSCALE_MASK) {
4910 			/* Remove scale factor from initial window */
4911 			int win = s->src.max_win;
4912 			win += 1 << (s->src.wscale & PF_WSCALE_MASK);
4913 			s->src.max_win = (win - 1) >>
4914 			    (s->src.wscale & PF_WSCALE_MASK);
4915 		}
4916 		if (th->th_flags & TH_FIN)
4917 			s->src.seqhi++;
4918 		s->dst.seqhi = 1;
4919 		s->dst.max_win = 1;
4920 		pf_set_protostate(s, PF_PEER_SRC, TCPS_SYN_SENT);
4921 		pf_set_protostate(s, PF_PEER_DST, TCPS_CLOSED);
4922 		s->timeout = PFTM_TCP_FIRST_PACKET;
4923 		atomic_add_32(&V_pf_status.states_halfopen, 1);
4924 		break;
4925 	case IPPROTO_UDP:
4926 		pf_set_protostate(s, PF_PEER_SRC, PFUDPS_SINGLE);
4927 		pf_set_protostate(s, PF_PEER_DST, PFUDPS_NO_TRAFFIC);
4928 		s->timeout = PFTM_UDP_FIRST_PACKET;
4929 		break;
4930 	case IPPROTO_SCTP:
4931 		pf_set_protostate(s, PF_PEER_SRC, SCTP_COOKIE_WAIT);
4932 		pf_set_protostate(s, PF_PEER_DST, SCTP_CLOSED);
4933 		s->timeout = PFTM_SCTP_FIRST_PACKET;
4934 		break;
4935 	case IPPROTO_ICMP:
4936 #ifdef INET6
4937 	case IPPROTO_ICMPV6:
4938 #endif
4939 		s->timeout = PFTM_ICMP_FIRST_PACKET;
4940 		break;
4941 	default:
4942 		pf_set_protostate(s, PF_PEER_SRC, PFOTHERS_SINGLE);
4943 		pf_set_protostate(s, PF_PEER_DST, PFOTHERS_NO_TRAFFIC);
4944 		s->timeout = PFTM_OTHER_FIRST_PACKET;
4945 	}
4946 
4947 	if (r->rt) {
4948 		/* pf_map_addr increases the reason counters */
4949 		if ((reason = pf_map_addr(pd->af, r, pd->src, &s->rt_addr,
4950 		    &s->rt_kif, NULL, &sn)) != 0)
4951 			goto csfailed;
4952 		s->rt = r->rt;
4953 	}
4954 
4955 	s->creation = s->expire = pf_get_uptime();
4956 
4957 	if (sn != NULL)
4958 		s->src_node = sn;
4959 	if (nsn != NULL) {
4960 		/* XXX We only modify one side for now. */
4961 		PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
4962 		s->nat_src_node = nsn;
4963 	}
4964 	if (pd->proto == IPPROTO_TCP) {
4965 		if (s->state_flags & PFSTATE_SCRUB_TCP &&
4966 		    pf_normalize_tcp_init(m, off, pd, th, &s->src, &s->dst)) {
4967 			REASON_SET(&reason, PFRES_MEMORY);
4968 			goto drop;
4969 		}
4970 		if (s->state_flags & PFSTATE_SCRUB_TCP && s->src.scrub &&
4971 		    pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
4972 		    &s->src, &s->dst, rewrite)) {
4973 			/* This really shouldn't happen!!! */
4974 			DPFPRINTF(PF_DEBUG_URGENT,
4975 			    ("pf_normalize_tcp_stateful failed on first "
4976 			     "pkt\n"));
4977 			goto drop;
4978 		}
4979 	} else if (pd->proto == IPPROTO_SCTP) {
4980 		if (pf_normalize_sctp_init(m, off, pd, &s->src, &s->dst))
4981 			goto drop;
4982 		if (! (pd->sctp_flags & (PFDESC_SCTP_INIT | PFDESC_SCTP_ADD_IP)))
4983 			goto drop;
4984 	}
4985 	s->direction = pd->dir;
4986 
4987 	/*
4988 	 * sk/nk could already been setup by pf_get_translation().
4989 	 */
4990 	if (nr == NULL) {
4991 		KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
4992 		    __func__, nr, sk, nk));
4993 		sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
4994 		if (sk == NULL)
4995 			goto csfailed;
4996 		nk = sk;
4997 	} else
4998 		KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
4999 		    __func__, nr, sk, nk));
5000 
5001 	/* Swap sk/nk for PF_OUT. */
5002 	if (pf_state_insert(BOUND_IFACE(r, kif), kif,
5003 	    (pd->dir == PF_IN) ? sk : nk,
5004 	    (pd->dir == PF_IN) ? nk : sk, s)) {
5005 		REASON_SET(&reason, PFRES_STATEINS);
5006 		goto drop;
5007 	} else
5008 		*sm = s;
5009 
5010 	if (tag > 0)
5011 		s->tag = tag;
5012 	if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
5013 	    TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
5014 		pf_set_protostate(s, PF_PEER_SRC, PF_TCPS_PROXY_SRC);
5015 		/* undo NAT changes, if they have taken place */
5016 		if (nr != NULL) {
5017 			struct pf_state_key *skt = s->key[PF_SK_WIRE];
5018 			if (pd->dir == PF_OUT)
5019 				skt = s->key[PF_SK_STACK];
5020 			PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
5021 			PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
5022 			if (pd->sport)
5023 				*pd->sport = skt->port[pd->sidx];
5024 			if (pd->dport)
5025 				*pd->dport = skt->port[pd->didx];
5026 			if (pd->proto_sum)
5027 				*pd->proto_sum = bproto_sum;
5028 			if (pd->ip_sum)
5029 				*pd->ip_sum = bip_sum;
5030 			m_copyback(m, off, hdrlen, pd->hdr.any);
5031 		}
5032 		s->src.seqhi = htonl(arc4random());
5033 		/* Find mss option */
5034 		int rtid = M_GETFIB(m);
5035 		mss = pf_get_mss(m, off, th->th_off, pd->af);
5036 		mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
5037 		mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
5038 		s->src.mss = mss;
5039 		pf_send_tcp(r, pd->af, pd->dst, pd->src, th->th_dport,
5040 		    th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
5041 		    TH_SYN|TH_ACK, 0, s->src.mss, 0, true, 0, 0,
5042 		    pd->act.rtableid);
5043 		REASON_SET(&reason, PFRES_SYNPROXY);
5044 		return (PF_SYNPROXY_DROP);
5045 	}
5046 
5047 	return (PF_PASS);
5048 
5049 csfailed:
5050 	while ((ri = SLIST_FIRST(match_rules))) {
5051 		SLIST_REMOVE_HEAD(match_rules, entry);
5052 		free(ri, M_PF_RULE_ITEM);
5053 	}
5054 
5055 	uma_zfree(V_pf_state_key_z, sk);
5056 	uma_zfree(V_pf_state_key_z, nk);
5057 
5058 	if (sn != NULL) {
5059 		PF_SRC_NODE_LOCK(sn);
5060 		if (--sn->states == 0 && sn->expire == 0) {
5061 			pf_unlink_src_node(sn);
5062 			uma_zfree(V_pf_sources_z, sn);
5063 			counter_u64_add(
5064 			    V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
5065 		}
5066 		PF_SRC_NODE_UNLOCK(sn);
5067 	}
5068 
5069 	if (nsn != sn && nsn != NULL) {
5070 		PF_SRC_NODE_LOCK(nsn);
5071 		if (--nsn->states == 0 && nsn->expire == 0) {
5072 			pf_unlink_src_node(nsn);
5073 			uma_zfree(V_pf_sources_z, nsn);
5074 			counter_u64_add(
5075 			    V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
5076 		}
5077 		PF_SRC_NODE_UNLOCK(nsn);
5078 	}
5079 
5080 drop:
5081 	if (s != NULL) {
5082 		pf_src_tree_remove_state(s);
5083 		s->timeout = PFTM_UNLINKED;
5084 		STATE_DEC_COUNTERS(s);
5085 		pf_free_state(s);
5086 	}
5087 
5088 	return (PF_DROP);
5089 }
5090 
5091 static int
5092 pf_test_fragment(struct pf_krule **rm, struct pfi_kkif *kif,
5093     struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_krule **am,
5094     struct pf_kruleset **rsm)
5095 {
5096 	struct pf_krule		*r, *a = NULL;
5097 	struct pf_kruleset	*ruleset = NULL;
5098 	struct pf_krule_slist	 match_rules;
5099 	struct pf_krule_item	*ri;
5100 	sa_family_t		 af = pd->af;
5101 	u_short			 reason;
5102 	int			 tag = -1;
5103 	int			 asd = 0;
5104 	int			 match = 0;
5105 	struct pf_kanchor_stackframe	anchor_stack[PF_ANCHOR_STACKSIZE];
5106 
5107 	PF_RULES_RASSERT();
5108 
5109 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
5110 	SLIST_INIT(&match_rules);
5111 	while (r != NULL) {
5112 		pf_counter_u64_add(&r->evaluations, 1);
5113 		if (pfi_kkif_match(r->kif, kif) == r->ifnot)
5114 			r = r->skip[PF_SKIP_IFP].ptr;
5115 		else if (r->direction && r->direction != pd->dir)
5116 			r = r->skip[PF_SKIP_DIR].ptr;
5117 		else if (r->af && r->af != af)
5118 			r = r->skip[PF_SKIP_AF].ptr;
5119 		else if (r->proto && r->proto != pd->proto)
5120 			r = r->skip[PF_SKIP_PROTO].ptr;
5121 		else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
5122 		    r->src.neg, kif, M_GETFIB(m)))
5123 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
5124 		else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
5125 		    r->dst.neg, NULL, M_GETFIB(m)))
5126 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
5127 		else if (r->tos && !(r->tos == pd->tos))
5128 			r = TAILQ_NEXT(r, entries);
5129 		else if (r->os_fingerprint != PF_OSFP_ANY)
5130 			r = TAILQ_NEXT(r, entries);
5131 		else if (pd->proto == IPPROTO_UDP &&
5132 		    (r->src.port_op || r->dst.port_op))
5133 			r = TAILQ_NEXT(r, entries);
5134 		else if (pd->proto == IPPROTO_TCP &&
5135 		    (r->src.port_op || r->dst.port_op || r->flagset))
5136 			r = TAILQ_NEXT(r, entries);
5137 		else if ((pd->proto == IPPROTO_ICMP ||
5138 		    pd->proto == IPPROTO_ICMPV6) &&
5139 		    (r->type || r->code))
5140 			r = TAILQ_NEXT(r, entries);
5141 		else if (r->prio &&
5142 		    !pf_match_ieee8021q_pcp(r->prio, m))
5143 			r = TAILQ_NEXT(r, entries);
5144 		else if (r->prob && r->prob <=
5145 		    (arc4random() % (UINT_MAX - 1) + 1))
5146 			r = TAILQ_NEXT(r, entries);
5147 		else if (r->match_tag && !pf_match_tag(m, r, &tag,
5148 		    pd->pf_mtag ? pd->pf_mtag->tag : 0))
5149 			r = TAILQ_NEXT(r, entries);
5150 		else {
5151 			if (r->anchor == NULL) {
5152 				if (r->action == PF_MATCH) {
5153 					ri = malloc(sizeof(struct pf_krule_item), M_PF_RULE_ITEM, M_NOWAIT | M_ZERO);
5154 					if (ri == NULL) {
5155 						REASON_SET(&reason, PFRES_MEMORY);
5156 						goto cleanup;
5157 					}
5158 					ri->r = r;
5159 					SLIST_INSERT_HEAD(&match_rules, ri, entry);
5160 					pf_counter_u64_critical_enter();
5161 					pf_counter_u64_add_protected(&r->packets[pd->dir == PF_OUT], 1);
5162 					pf_counter_u64_add_protected(&r->bytes[pd->dir == PF_OUT], pd->tot_len);
5163 					pf_counter_u64_critical_exit();
5164 					pf_rule_to_actions(r, &pd->act);
5165 					if (r->log)
5166 						PFLOG_PACKET(kif, m, af,
5167 						    r->action, PFRES_MATCH, r,
5168 						    a, ruleset, pd, 1);
5169 				} else {
5170 					match = 1;
5171 					*rm = r;
5172 					*am = a;
5173 					*rsm = ruleset;
5174 				}
5175 				if ((*rm)->quick)
5176 					break;
5177 				r = TAILQ_NEXT(r, entries);
5178 			} else
5179 				pf_step_into_anchor(anchor_stack, &asd,
5180 				    &ruleset, PF_RULESET_FILTER, &r, &a,
5181 				    &match);
5182 		}
5183 		if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
5184 		    &ruleset, PF_RULESET_FILTER, &r, &a, &match))
5185 			break;
5186 	}
5187 	r = *rm;
5188 	a = *am;
5189 	ruleset = *rsm;
5190 
5191 	REASON_SET(&reason, PFRES_MATCH);
5192 
5193 	/* apply actions for last matching pass/block rule */
5194 	pf_rule_to_actions(r, &pd->act);
5195 
5196 	if (r->log)
5197 		PFLOG_PACKET(kif, m, af, r->action, reason, r, a, ruleset, pd, 1);
5198 
5199 	if (r->action != PF_PASS)
5200 		return (PF_DROP);
5201 
5202 	if (tag > 0 && pf_tag_packet(m, pd, tag)) {
5203 		REASON_SET(&reason, PFRES_MEMORY);
5204 		goto cleanup;
5205 	}
5206 
5207 	return (PF_PASS);
5208 
5209 cleanup:
5210 	while ((ri = SLIST_FIRST(&match_rules))) {
5211 		SLIST_REMOVE_HEAD(&match_rules, entry);
5212 		free(ri, M_PF_RULE_ITEM);
5213 	}
5214 
5215 	return (PF_DROP);
5216 }
5217 
5218 static int
5219 pf_tcp_track_full(struct pf_kstate **state, struct pfi_kkif *kif,
5220     struct mbuf *m, int off, struct pf_pdesc *pd, u_short *reason,
5221     int *copyback)
5222 {
5223 	struct tcphdr		*th = &pd->hdr.tcp;
5224 	struct pf_state_peer	*src, *dst;
5225 	u_int16_t		 win = ntohs(th->th_win);
5226 	u_int32_t		 ack, end, seq, orig_seq;
5227 	u_int8_t		 sws, dws, psrc, pdst;
5228 	int			 ackskew;
5229 
5230 	if (pd->dir == (*state)->direction) {
5231 		src = &(*state)->src;
5232 		dst = &(*state)->dst;
5233 		psrc = PF_PEER_SRC;
5234 		pdst = PF_PEER_DST;
5235 	} else {
5236 		src = &(*state)->dst;
5237 		dst = &(*state)->src;
5238 		psrc = PF_PEER_DST;
5239 		pdst = PF_PEER_SRC;
5240 	}
5241 
5242 	if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
5243 		sws = src->wscale & PF_WSCALE_MASK;
5244 		dws = dst->wscale & PF_WSCALE_MASK;
5245 	} else
5246 		sws = dws = 0;
5247 
5248 	/*
5249 	 * Sequence tracking algorithm from Guido van Rooij's paper:
5250 	 *   http://www.madison-gurkha.com/publications/tcp_filtering/
5251 	 *	tcp_filtering.ps
5252 	 */
5253 
5254 	orig_seq = seq = ntohl(th->th_seq);
5255 	if (src->seqlo == 0) {
5256 		/* First packet from this end. Set its state */
5257 
5258 		if (((*state)->state_flags & PFSTATE_SCRUB_TCP || dst->scrub) &&
5259 		    src->scrub == NULL) {
5260 			if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
5261 				REASON_SET(reason, PFRES_MEMORY);
5262 				return (PF_DROP);
5263 			}
5264 		}
5265 
5266 		/* Deferred generation of sequence number modulator */
5267 		if (dst->seqdiff && !src->seqdiff) {
5268 			/* use random iss for the TCP server */
5269 			while ((src->seqdiff = arc4random() - seq) == 0)
5270 				;
5271 			ack = ntohl(th->th_ack) - dst->seqdiff;
5272 			pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
5273 			    src->seqdiff), 0);
5274 			pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
5275 			*copyback = 1;
5276 		} else {
5277 			ack = ntohl(th->th_ack);
5278 		}
5279 
5280 		end = seq + pd->p_len;
5281 		if (th->th_flags & TH_SYN) {
5282 			end++;
5283 			if (dst->wscale & PF_WSCALE_FLAG) {
5284 				src->wscale = pf_get_wscale(m, off, th->th_off,
5285 				    pd->af);
5286 				if (src->wscale & PF_WSCALE_FLAG) {
5287 					/* Remove scale factor from initial
5288 					 * window */
5289 					sws = src->wscale & PF_WSCALE_MASK;
5290 					win = ((u_int32_t)win + (1 << sws) - 1)
5291 					    >> sws;
5292 					dws = dst->wscale & PF_WSCALE_MASK;
5293 				} else {
5294 					/* fixup other window */
5295 					dst->max_win <<= dst->wscale &
5296 					    PF_WSCALE_MASK;
5297 					/* in case of a retrans SYN|ACK */
5298 					dst->wscale = 0;
5299 				}
5300 			}
5301 		}
5302 		if (th->th_flags & TH_FIN)
5303 			end++;
5304 
5305 		src->seqlo = seq;
5306 		if (src->state < TCPS_SYN_SENT)
5307 			pf_set_protostate(*state, psrc, TCPS_SYN_SENT);
5308 
5309 		/*
5310 		 * May need to slide the window (seqhi may have been set by
5311 		 * the crappy stack check or if we picked up the connection
5312 		 * after establishment)
5313 		 */
5314 		if (src->seqhi == 1 ||
5315 		    SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
5316 			src->seqhi = end + MAX(1, dst->max_win << dws);
5317 		if (win > src->max_win)
5318 			src->max_win = win;
5319 
5320 	} else {
5321 		ack = ntohl(th->th_ack) - dst->seqdiff;
5322 		if (src->seqdiff) {
5323 			/* Modulate sequence numbers */
5324 			pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
5325 			    src->seqdiff), 0);
5326 			pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
5327 			*copyback = 1;
5328 		}
5329 		end = seq + pd->p_len;
5330 		if (th->th_flags & TH_SYN)
5331 			end++;
5332 		if (th->th_flags & TH_FIN)
5333 			end++;
5334 	}
5335 
5336 	if ((th->th_flags & TH_ACK) == 0) {
5337 		/* Let it pass through the ack skew check */
5338 		ack = dst->seqlo;
5339 	} else if ((ack == 0 &&
5340 	    (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
5341 	    /* broken tcp stacks do not set ack */
5342 	    (dst->state < TCPS_SYN_SENT)) {
5343 		/*
5344 		 * Many stacks (ours included) will set the ACK number in an
5345 		 * FIN|ACK if the SYN times out -- no sequence to ACK.
5346 		 */
5347 		ack = dst->seqlo;
5348 	}
5349 
5350 	if (seq == end) {
5351 		/* Ease sequencing restrictions on no data packets */
5352 		seq = src->seqlo;
5353 		end = seq;
5354 	}
5355 
5356 	ackskew = dst->seqlo - ack;
5357 
5358 	/*
5359 	 * Need to demodulate the sequence numbers in any TCP SACK options
5360 	 * (Selective ACK). We could optionally validate the SACK values
5361 	 * against the current ACK window, either forwards or backwards, but
5362 	 * I'm not confident that SACK has been implemented properly
5363 	 * everywhere. It wouldn't surprise me if several stacks accidentally
5364 	 * SACK too far backwards of previously ACKed data. There really aren't
5365 	 * any security implications of bad SACKing unless the target stack
5366 	 * doesn't validate the option length correctly. Someone trying to
5367 	 * spoof into a TCP connection won't bother blindly sending SACK
5368 	 * options anyway.
5369 	 */
5370 	if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
5371 		if (pf_modulate_sack(m, off, pd, th, dst))
5372 			*copyback = 1;
5373 	}
5374 
5375 #define	MAXACKWINDOW (0xffff + 1500)	/* 1500 is an arbitrary fudge factor */
5376 	if (SEQ_GEQ(src->seqhi, end) &&
5377 	    /* Last octet inside other's window space */
5378 	    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
5379 	    /* Retrans: not more than one window back */
5380 	    (ackskew >= -MAXACKWINDOW) &&
5381 	    /* Acking not more than one reassembled fragment backwards */
5382 	    (ackskew <= (MAXACKWINDOW << sws)) &&
5383 	    /* Acking not more than one window forward */
5384 	    ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
5385 	    (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo))) {
5386 	    /* Require an exact/+1 sequence match on resets when possible */
5387 
5388 		if (dst->scrub || src->scrub) {
5389 			if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
5390 			    *state, src, dst, copyback))
5391 				return (PF_DROP);
5392 		}
5393 
5394 		/* update max window */
5395 		if (src->max_win < win)
5396 			src->max_win = win;
5397 		/* synchronize sequencing */
5398 		if (SEQ_GT(end, src->seqlo))
5399 			src->seqlo = end;
5400 		/* slide the window of what the other end can send */
5401 		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
5402 			dst->seqhi = ack + MAX((win << sws), 1);
5403 
5404 		/* update states */
5405 		if (th->th_flags & TH_SYN)
5406 			if (src->state < TCPS_SYN_SENT)
5407 				pf_set_protostate(*state, psrc, TCPS_SYN_SENT);
5408 		if (th->th_flags & TH_FIN)
5409 			if (src->state < TCPS_CLOSING)
5410 				pf_set_protostate(*state, psrc, TCPS_CLOSING);
5411 		if (th->th_flags & TH_ACK) {
5412 			if (dst->state == TCPS_SYN_SENT) {
5413 				pf_set_protostate(*state, pdst,
5414 				    TCPS_ESTABLISHED);
5415 				if (src->state == TCPS_ESTABLISHED &&
5416 				    (*state)->src_node != NULL &&
5417 				    pf_src_connlimit(state)) {
5418 					REASON_SET(reason, PFRES_SRCLIMIT);
5419 					return (PF_DROP);
5420 				}
5421 			} else if (dst->state == TCPS_CLOSING)
5422 				pf_set_protostate(*state, pdst,
5423 				    TCPS_FIN_WAIT_2);
5424 		}
5425 		if (th->th_flags & TH_RST)
5426 			pf_set_protostate(*state, PF_PEER_BOTH, TCPS_TIME_WAIT);
5427 
5428 		/* update expire time */
5429 		(*state)->expire = pf_get_uptime();
5430 		if (src->state >= TCPS_FIN_WAIT_2 &&
5431 		    dst->state >= TCPS_FIN_WAIT_2)
5432 			(*state)->timeout = PFTM_TCP_CLOSED;
5433 		else if (src->state >= TCPS_CLOSING &&
5434 		    dst->state >= TCPS_CLOSING)
5435 			(*state)->timeout = PFTM_TCP_FIN_WAIT;
5436 		else if (src->state < TCPS_ESTABLISHED ||
5437 		    dst->state < TCPS_ESTABLISHED)
5438 			(*state)->timeout = PFTM_TCP_OPENING;
5439 		else if (src->state >= TCPS_CLOSING ||
5440 		    dst->state >= TCPS_CLOSING)
5441 			(*state)->timeout = PFTM_TCP_CLOSING;
5442 		else
5443 			(*state)->timeout = PFTM_TCP_ESTABLISHED;
5444 
5445 		/* Fall through to PASS packet */
5446 
5447 	} else if ((dst->state < TCPS_SYN_SENT ||
5448 		dst->state >= TCPS_FIN_WAIT_2 ||
5449 		src->state >= TCPS_FIN_WAIT_2) &&
5450 	    SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
5451 	    /* Within a window forward of the originating packet */
5452 	    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
5453 	    /* Within a window backward of the originating packet */
5454 
5455 		/*
5456 		 * This currently handles three situations:
5457 		 *  1) Stupid stacks will shotgun SYNs before their peer
5458 		 *     replies.
5459 		 *  2) When PF catches an already established stream (the
5460 		 *     firewall rebooted, the state table was flushed, routes
5461 		 *     changed...)
5462 		 *  3) Packets get funky immediately after the connection
5463 		 *     closes (this should catch Solaris spurious ACK|FINs
5464 		 *     that web servers like to spew after a close)
5465 		 *
5466 		 * This must be a little more careful than the above code
5467 		 * since packet floods will also be caught here. We don't
5468 		 * update the TTL here to mitigate the damage of a packet
5469 		 * flood and so the same code can handle awkward establishment
5470 		 * and a loosened connection close.
5471 		 * In the establishment case, a correct peer response will
5472 		 * validate the connection, go through the normal state code
5473 		 * and keep updating the state TTL.
5474 		 */
5475 
5476 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
5477 			printf("pf: loose state match: ");
5478 			pf_print_state(*state);
5479 			pf_print_flags(th->th_flags);
5480 			printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
5481 			    "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
5482 			    pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
5483 			    (unsigned long long)(*state)->packets[1],
5484 			    pd->dir == PF_IN ? "in" : "out",
5485 			    pd->dir == (*state)->direction ? "fwd" : "rev");
5486 		}
5487 
5488 		if (dst->scrub || src->scrub) {
5489 			if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
5490 			    *state, src, dst, copyback))
5491 				return (PF_DROP);
5492 		}
5493 
5494 		/* update max window */
5495 		if (src->max_win < win)
5496 			src->max_win = win;
5497 		/* synchronize sequencing */
5498 		if (SEQ_GT(end, src->seqlo))
5499 			src->seqlo = end;
5500 		/* slide the window of what the other end can send */
5501 		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
5502 			dst->seqhi = ack + MAX((win << sws), 1);
5503 
5504 		/*
5505 		 * Cannot set dst->seqhi here since this could be a shotgunned
5506 		 * SYN and not an already established connection.
5507 		 */
5508 
5509 		if (th->th_flags & TH_FIN)
5510 			if (src->state < TCPS_CLOSING)
5511 				pf_set_protostate(*state, psrc, TCPS_CLOSING);
5512 		if (th->th_flags & TH_RST)
5513 			pf_set_protostate(*state, PF_PEER_BOTH, TCPS_TIME_WAIT);
5514 
5515 		/* Fall through to PASS packet */
5516 
5517 	} else {
5518 		if ((*state)->dst.state == TCPS_SYN_SENT &&
5519 		    (*state)->src.state == TCPS_SYN_SENT) {
5520 			/* Send RST for state mismatches during handshake */
5521 			if (!(th->th_flags & TH_RST))
5522 				pf_send_tcp((*state)->rule.ptr, pd->af,
5523 				    pd->dst, pd->src, th->th_dport,
5524 				    th->th_sport, ntohl(th->th_ack), 0,
5525 				    TH_RST, 0, 0,
5526 				    (*state)->rule.ptr->return_ttl, true, 0, 0,
5527 				    (*state)->act.rtableid);
5528 			src->seqlo = 0;
5529 			src->seqhi = 1;
5530 			src->max_win = 1;
5531 		} else if (V_pf_status.debug >= PF_DEBUG_MISC) {
5532 			printf("pf: BAD state: ");
5533 			pf_print_state(*state);
5534 			pf_print_flags(th->th_flags);
5535 			printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
5536 			    "pkts=%llu:%llu dir=%s,%s\n",
5537 			    seq, orig_seq, ack, pd->p_len, ackskew,
5538 			    (unsigned long long)(*state)->packets[0],
5539 			    (unsigned long long)(*state)->packets[1],
5540 			    pd->dir == PF_IN ? "in" : "out",
5541 			    pd->dir == (*state)->direction ? "fwd" : "rev");
5542 			printf("pf: State failure on: %c %c %c %c | %c %c\n",
5543 			    SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
5544 			    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
5545 			    ' ': '2',
5546 			    (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
5547 			    (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
5548 			    SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
5549 			    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
5550 		}
5551 		REASON_SET(reason, PFRES_BADSTATE);
5552 		return (PF_DROP);
5553 	}
5554 
5555 	return (PF_PASS);
5556 }
5557 
5558 static int
5559 pf_tcp_track_sloppy(struct pf_kstate **state, struct pf_pdesc *pd, u_short *reason)
5560 {
5561 	struct tcphdr		*th = &pd->hdr.tcp;
5562 	struct pf_state_peer	*src, *dst;
5563 	u_int8_t		 psrc, pdst;
5564 
5565 	if (pd->dir == (*state)->direction) {
5566 		src = &(*state)->src;
5567 		dst = &(*state)->dst;
5568 		psrc = PF_PEER_SRC;
5569 		pdst = PF_PEER_DST;
5570 	} else {
5571 		src = &(*state)->dst;
5572 		dst = &(*state)->src;
5573 		psrc = PF_PEER_DST;
5574 		pdst = PF_PEER_SRC;
5575 	}
5576 
5577 	if (th->th_flags & TH_SYN)
5578 		if (src->state < TCPS_SYN_SENT)
5579 			pf_set_protostate(*state, psrc, TCPS_SYN_SENT);
5580 	if (th->th_flags & TH_FIN)
5581 		if (src->state < TCPS_CLOSING)
5582 			pf_set_protostate(*state, psrc, TCPS_CLOSING);
5583 	if (th->th_flags & TH_ACK) {
5584 		if (dst->state == TCPS_SYN_SENT) {
5585 			pf_set_protostate(*state, pdst, TCPS_ESTABLISHED);
5586 			if (src->state == TCPS_ESTABLISHED &&
5587 			    (*state)->src_node != NULL &&
5588 			    pf_src_connlimit(state)) {
5589 				REASON_SET(reason, PFRES_SRCLIMIT);
5590 				return (PF_DROP);
5591 			}
5592 		} else if (dst->state == TCPS_CLOSING) {
5593 			pf_set_protostate(*state, pdst, TCPS_FIN_WAIT_2);
5594 		} else if (src->state == TCPS_SYN_SENT &&
5595 		    dst->state < TCPS_SYN_SENT) {
5596 			/*
5597 			 * Handle a special sloppy case where we only see one
5598 			 * half of the connection. If there is a ACK after
5599 			 * the initial SYN without ever seeing a packet from
5600 			 * the destination, set the connection to established.
5601 			 */
5602 			pf_set_protostate(*state, PF_PEER_BOTH,
5603 			    TCPS_ESTABLISHED);
5604 			dst->state = src->state = TCPS_ESTABLISHED;
5605 			if ((*state)->src_node != NULL &&
5606 			    pf_src_connlimit(state)) {
5607 				REASON_SET(reason, PFRES_SRCLIMIT);
5608 				return (PF_DROP);
5609 			}
5610 		} else if (src->state == TCPS_CLOSING &&
5611 		    dst->state == TCPS_ESTABLISHED &&
5612 		    dst->seqlo == 0) {
5613 			/*
5614 			 * Handle the closing of half connections where we
5615 			 * don't see the full bidirectional FIN/ACK+ACK
5616 			 * handshake.
5617 			 */
5618 			pf_set_protostate(*state, pdst, TCPS_CLOSING);
5619 		}
5620 	}
5621 	if (th->th_flags & TH_RST)
5622 		pf_set_protostate(*state, PF_PEER_BOTH, TCPS_TIME_WAIT);
5623 
5624 	/* update expire time */
5625 	(*state)->expire = pf_get_uptime();
5626 	if (src->state >= TCPS_FIN_WAIT_2 &&
5627 	    dst->state >= TCPS_FIN_WAIT_2)
5628 		(*state)->timeout = PFTM_TCP_CLOSED;
5629 	else if (src->state >= TCPS_CLOSING &&
5630 	    dst->state >= TCPS_CLOSING)
5631 		(*state)->timeout = PFTM_TCP_FIN_WAIT;
5632 	else if (src->state < TCPS_ESTABLISHED ||
5633 	    dst->state < TCPS_ESTABLISHED)
5634 		(*state)->timeout = PFTM_TCP_OPENING;
5635 	else if (src->state >= TCPS_CLOSING ||
5636 	    dst->state >= TCPS_CLOSING)
5637 		(*state)->timeout = PFTM_TCP_CLOSING;
5638 	else
5639 		(*state)->timeout = PFTM_TCP_ESTABLISHED;
5640 
5641 	return (PF_PASS);
5642 }
5643 
5644 static int
5645 pf_synproxy(struct pf_pdesc *pd, struct pf_kstate **state, u_short *reason)
5646 {
5647 	struct pf_state_key	*sk = (*state)->key[pd->didx];
5648 	struct tcphdr		*th = &pd->hdr.tcp;
5649 
5650 	if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
5651 		if (pd->dir != (*state)->direction) {
5652 			REASON_SET(reason, PFRES_SYNPROXY);
5653 			return (PF_SYNPROXY_DROP);
5654 		}
5655 		if (th->th_flags & TH_SYN) {
5656 			if (ntohl(th->th_seq) != (*state)->src.seqlo) {
5657 				REASON_SET(reason, PFRES_SYNPROXY);
5658 				return (PF_DROP);
5659 			}
5660 			pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
5661 			    pd->src, th->th_dport, th->th_sport,
5662 			    (*state)->src.seqhi, ntohl(th->th_seq) + 1,
5663 			    TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, true, 0, 0,
5664 			    (*state)->act.rtableid);
5665 			REASON_SET(reason, PFRES_SYNPROXY);
5666 			return (PF_SYNPROXY_DROP);
5667 		} else if ((th->th_flags & (TH_ACK|TH_RST|TH_FIN)) != TH_ACK ||
5668 		    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
5669 		    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
5670 			REASON_SET(reason, PFRES_SYNPROXY);
5671 			return (PF_DROP);
5672 		} else if ((*state)->src_node != NULL &&
5673 		    pf_src_connlimit(state)) {
5674 			REASON_SET(reason, PFRES_SRCLIMIT);
5675 			return (PF_DROP);
5676 		} else
5677 			pf_set_protostate(*state, PF_PEER_SRC,
5678 			    PF_TCPS_PROXY_DST);
5679 	}
5680 	if ((*state)->src.state == PF_TCPS_PROXY_DST) {
5681 		if (pd->dir == (*state)->direction) {
5682 			if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
5683 			    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
5684 			    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
5685 				REASON_SET(reason, PFRES_SYNPROXY);
5686 				return (PF_DROP);
5687 			}
5688 			(*state)->src.max_win = MAX(ntohs(th->th_win), 1);
5689 			if ((*state)->dst.seqhi == 1)
5690 				(*state)->dst.seqhi = htonl(arc4random());
5691 			pf_send_tcp((*state)->rule.ptr, pd->af,
5692 			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
5693 			    sk->port[pd->sidx], sk->port[pd->didx],
5694 			    (*state)->dst.seqhi, 0, TH_SYN, 0,
5695 			    (*state)->src.mss, 0, false, (*state)->tag, 0,
5696 			    (*state)->act.rtableid);
5697 			REASON_SET(reason, PFRES_SYNPROXY);
5698 			return (PF_SYNPROXY_DROP);
5699 		} else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
5700 		    (TH_SYN|TH_ACK)) ||
5701 		    (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
5702 			REASON_SET(reason, PFRES_SYNPROXY);
5703 			return (PF_DROP);
5704 		} else {
5705 			(*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
5706 			(*state)->dst.seqlo = ntohl(th->th_seq);
5707 			pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
5708 			    pd->src, th->th_dport, th->th_sport,
5709 			    ntohl(th->th_ack), ntohl(th->th_seq) + 1,
5710 			    TH_ACK, (*state)->src.max_win, 0, 0, false,
5711 			    (*state)->tag, 0, (*state)->act.rtableid);
5712 			pf_send_tcp((*state)->rule.ptr, pd->af,
5713 			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
5714 			    sk->port[pd->sidx], sk->port[pd->didx],
5715 			    (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
5716 			    TH_ACK, (*state)->dst.max_win, 0, 0, true, 0, 0,
5717 			    (*state)->act.rtableid);
5718 			(*state)->src.seqdiff = (*state)->dst.seqhi -
5719 			    (*state)->src.seqlo;
5720 			(*state)->dst.seqdiff = (*state)->src.seqhi -
5721 			    (*state)->dst.seqlo;
5722 			(*state)->src.seqhi = (*state)->src.seqlo +
5723 			    (*state)->dst.max_win;
5724 			(*state)->dst.seqhi = (*state)->dst.seqlo +
5725 			    (*state)->src.max_win;
5726 			(*state)->src.wscale = (*state)->dst.wscale = 0;
5727 			pf_set_protostate(*state, PF_PEER_BOTH,
5728 			    TCPS_ESTABLISHED);
5729 			REASON_SET(reason, PFRES_SYNPROXY);
5730 			return (PF_SYNPROXY_DROP);
5731 		}
5732 	}
5733 
5734 	return (PF_PASS);
5735 }
5736 
5737 static int
5738 pf_test_state_tcp(struct pf_kstate **state, struct pfi_kkif *kif,
5739     struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
5740     u_short *reason)
5741 {
5742 	struct pf_state_key_cmp	 key;
5743 	struct tcphdr		*th = &pd->hdr.tcp;
5744 	int			 copyback = 0;
5745 	int			 action;
5746 	struct pf_state_peer	*src, *dst;
5747 
5748 	bzero(&key, sizeof(key));
5749 	key.af = pd->af;
5750 	key.proto = IPPROTO_TCP;
5751 	if (pd->dir == PF_IN)	{	/* wire side, straight */
5752 		PF_ACPY(&key.addr[0], pd->src, key.af);
5753 		PF_ACPY(&key.addr[1], pd->dst, key.af);
5754 		key.port[0] = th->th_sport;
5755 		key.port[1] = th->th_dport;
5756 	} else {			/* stack side, reverse */
5757 		PF_ACPY(&key.addr[1], pd->src, key.af);
5758 		PF_ACPY(&key.addr[0], pd->dst, key.af);
5759 		key.port[1] = th->th_sport;
5760 		key.port[0] = th->th_dport;
5761 	}
5762 
5763 	STATE_LOOKUP(kif, &key, *state, pd);
5764 
5765 	if (pd->dir == (*state)->direction) {
5766 		src = &(*state)->src;
5767 		dst = &(*state)->dst;
5768 	} else {
5769 		src = &(*state)->dst;
5770 		dst = &(*state)->src;
5771 	}
5772 
5773 	if ((action = pf_synproxy(pd, state, reason)) != PF_PASS)
5774 		return (action);
5775 
5776 	if (dst->state >= TCPS_FIN_WAIT_2 &&
5777 	    src->state >= TCPS_FIN_WAIT_2 &&
5778 	    (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) ||
5779 	    ((th->th_flags & (TH_SYN|TH_ACK|TH_RST)) == TH_ACK &&
5780 	    pf_syncookie_check(pd) && pd->dir == PF_IN))) {
5781 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
5782 			printf("pf: state reuse ");
5783 			pf_print_state(*state);
5784 			pf_print_flags(th->th_flags);
5785 			printf("\n");
5786 		}
5787 		/* XXX make sure it's the same direction ?? */
5788 		pf_set_protostate(*state, PF_PEER_BOTH, TCPS_CLOSED);
5789 		pf_unlink_state(*state);
5790 		*state = NULL;
5791 		return (PF_DROP);
5792 	}
5793 
5794 	if ((*state)->state_flags & PFSTATE_SLOPPY) {
5795 		if (pf_tcp_track_sloppy(state, pd, reason) == PF_DROP)
5796 			return (PF_DROP);
5797 	} else {
5798 		if (pf_tcp_track_full(state, kif, m, off, pd, reason,
5799 		    &copyback) == PF_DROP)
5800 			return (PF_DROP);
5801 	}
5802 
5803 	/* translate source/destination address, if necessary */
5804 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5805 		struct pf_state_key *nk = (*state)->key[pd->didx];
5806 
5807 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
5808 		    nk->port[pd->sidx] != th->th_sport)
5809 			pf_change_ap(m, pd->src, &th->th_sport,
5810 			    pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
5811 			    nk->port[pd->sidx], 0, pd->af);
5812 
5813 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
5814 		    nk->port[pd->didx] != th->th_dport)
5815 			pf_change_ap(m, pd->dst, &th->th_dport,
5816 			    pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
5817 			    nk->port[pd->didx], 0, pd->af);
5818 		copyback = 1;
5819 	}
5820 
5821 	/* Copyback sequence modulation or stateful scrub changes if needed */
5822 	if (copyback)
5823 		m_copyback(m, off, sizeof(*th), (caddr_t)th);
5824 
5825 	return (PF_PASS);
5826 }
5827 
5828 static int
5829 pf_test_state_udp(struct pf_kstate **state, struct pfi_kkif *kif,
5830     struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
5831 {
5832 	struct pf_state_peer	*src, *dst;
5833 	struct pf_state_key_cmp	 key;
5834 	struct udphdr		*uh = &pd->hdr.udp;
5835 	uint8_t			 psrc, pdst;
5836 
5837 	bzero(&key, sizeof(key));
5838 	key.af = pd->af;
5839 	key.proto = IPPROTO_UDP;
5840 	if (pd->dir == PF_IN)	{	/* wire side, straight */
5841 		PF_ACPY(&key.addr[0], pd->src, key.af);
5842 		PF_ACPY(&key.addr[1], pd->dst, key.af);
5843 		key.port[0] = uh->uh_sport;
5844 		key.port[1] = uh->uh_dport;
5845 	} else {			/* stack side, reverse */
5846 		PF_ACPY(&key.addr[1], pd->src, key.af);
5847 		PF_ACPY(&key.addr[0], pd->dst, key.af);
5848 		key.port[1] = uh->uh_sport;
5849 		key.port[0] = uh->uh_dport;
5850 	}
5851 
5852 	STATE_LOOKUP(kif, &key, *state, pd);
5853 
5854 	if (pd->dir == (*state)->direction) {
5855 		src = &(*state)->src;
5856 		dst = &(*state)->dst;
5857 		psrc = PF_PEER_SRC;
5858 		pdst = PF_PEER_DST;
5859 	} else {
5860 		src = &(*state)->dst;
5861 		dst = &(*state)->src;
5862 		psrc = PF_PEER_DST;
5863 		pdst = PF_PEER_SRC;
5864 	}
5865 
5866 	/* update states */
5867 	if (src->state < PFUDPS_SINGLE)
5868 		pf_set_protostate(*state, psrc, PFUDPS_SINGLE);
5869 	if (dst->state == PFUDPS_SINGLE)
5870 		pf_set_protostate(*state, pdst, PFUDPS_MULTIPLE);
5871 
5872 	/* update expire time */
5873 	(*state)->expire = pf_get_uptime();
5874 	if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
5875 		(*state)->timeout = PFTM_UDP_MULTIPLE;
5876 	else
5877 		(*state)->timeout = PFTM_UDP_SINGLE;
5878 
5879 	/* translate source/destination address, if necessary */
5880 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5881 		struct pf_state_key *nk = (*state)->key[pd->didx];
5882 
5883 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
5884 		    nk->port[pd->sidx] != uh->uh_sport)
5885 			pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
5886 			    &uh->uh_sum, &nk->addr[pd->sidx],
5887 			    nk->port[pd->sidx], 1, pd->af);
5888 
5889 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
5890 		    nk->port[pd->didx] != uh->uh_dport)
5891 			pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
5892 			    &uh->uh_sum, &nk->addr[pd->didx],
5893 			    nk->port[pd->didx], 1, pd->af);
5894 		m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
5895 	}
5896 
5897 	return (PF_PASS);
5898 }
5899 
5900 static int
5901 pf_test_state_sctp(struct pf_kstate **state, struct pfi_kkif *kif,
5902     struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
5903 {
5904 	struct pf_state_key_cmp	 key;
5905 	struct pf_state_peer	*src, *dst;
5906 	struct sctphdr		*sh = &pd->hdr.sctp;
5907 	u_int8_t		 psrc; //, pdst;
5908 
5909 	bzero(&key, sizeof(key));
5910 	key.af = pd->af;
5911 	key.proto = IPPROTO_SCTP;
5912 	if (pd->dir == PF_IN)	{	/* wire side, straight */
5913 		PF_ACPY(&key.addr[0], pd->src, key.af);
5914 		PF_ACPY(&key.addr[1], pd->dst, key.af);
5915 		key.port[0] = sh->src_port;
5916 		key.port[1] = sh->dest_port;
5917 	} else {			/* stack side, reverse */
5918 		PF_ACPY(&key.addr[1], pd->src, key.af);
5919 		PF_ACPY(&key.addr[0], pd->dst, key.af);
5920 		key.port[1] = sh->src_port;
5921 		key.port[0] = sh->dest_port;
5922 	}
5923 
5924 	STATE_LOOKUP(kif, &key, *state, pd);
5925 
5926 	if (pd->dir == (*state)->direction) {
5927 		src = &(*state)->src;
5928 		dst = &(*state)->dst;
5929 		psrc = PF_PEER_SRC;
5930 	} else {
5931 		src = &(*state)->dst;
5932 		dst = &(*state)->src;
5933 		psrc = PF_PEER_DST;
5934 	}
5935 
5936 	/* Track state. */
5937 	if (pd->sctp_flags & PFDESC_SCTP_INIT) {
5938 		if (src->state < SCTP_COOKIE_WAIT) {
5939 			pf_set_protostate(*state, psrc, SCTP_COOKIE_WAIT);
5940 			(*state)->timeout = PFTM_SCTP_OPENING;
5941 		}
5942 	}
5943 	if (pd->sctp_flags & PFDESC_SCTP_INIT_ACK) {
5944 		MPASS(dst->scrub != NULL);
5945 		if (dst->scrub->pfss_v_tag == 0)
5946 			dst->scrub->pfss_v_tag = pd->sctp_initiate_tag;
5947 	}
5948 
5949 	if (pd->sctp_flags & (PFDESC_SCTP_COOKIE | PFDESC_SCTP_HEARTBEAT_ACK)) {
5950 		if (src->state < SCTP_ESTABLISHED) {
5951 			pf_set_protostate(*state, psrc, SCTP_ESTABLISHED);
5952 			(*state)->timeout = PFTM_SCTP_ESTABLISHED;
5953 		}
5954 	}
5955 	if (pd->sctp_flags & (PFDESC_SCTP_SHUTDOWN | PFDESC_SCTP_ABORT |
5956 	    PFDESC_SCTP_SHUTDOWN_COMPLETE)) {
5957 		if (src->state < SCTP_SHUTDOWN_PENDING) {
5958 			pf_set_protostate(*state, psrc, SCTP_SHUTDOWN_PENDING);
5959 			(*state)->timeout = PFTM_SCTP_CLOSING;
5960 		}
5961 	}
5962 	if (pd->sctp_flags & (PFDESC_SCTP_SHUTDOWN_COMPLETE)) {
5963 		pf_set_protostate(*state, psrc, SCTP_CLOSED);
5964 		(*state)->timeout = PFTM_SCTP_CLOSED;
5965 	}
5966 
5967 	if (src->scrub != NULL) {
5968 		if (src->scrub->pfss_v_tag == 0) {
5969 			src->scrub->pfss_v_tag = pd->hdr.sctp.v_tag;
5970 		} else  if (src->scrub->pfss_v_tag != pd->hdr.sctp.v_tag)
5971 			return (PF_DROP);
5972 	}
5973 
5974 	(*state)->expire = pf_get_uptime();
5975 
5976 	/* translate source/destination address, if necessary */
5977 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5978 		uint16_t checksum = 0;
5979 		struct pf_state_key *nk = (*state)->key[pd->didx];
5980 
5981 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
5982 		    nk->port[pd->sidx] != pd->hdr.sctp.src_port) {
5983 			pf_change_ap(m, pd->src, &pd->hdr.sctp.src_port,
5984 			    pd->ip_sum, &checksum, &nk->addr[pd->sidx],
5985 			    nk->port[pd->sidx], 1, pd->af);
5986 		}
5987 
5988 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
5989 		    nk->port[pd->didx] != pd->hdr.sctp.dest_port) {
5990 			pf_change_ap(m, pd->dst, &pd->hdr.sctp.dest_port,
5991 			    pd->ip_sum, &checksum, &nk->addr[pd->didx],
5992 			    nk->port[pd->didx], 1, pd->af);
5993 		}
5994 	}
5995 
5996 	return (PF_PASS);
5997 }
5998 
5999 static void
6000 pf_sctp_multihome_detach_addr(const struct pf_kstate *s)
6001 {
6002 	struct pf_sctp_endpoint key;
6003 	struct pf_sctp_endpoint *ep;
6004 	struct pf_state_key *sks = s->key[PF_SK_STACK];
6005 	struct pf_sctp_source *i, *tmp;
6006 
6007 	if (sks == NULL || sks->proto != IPPROTO_SCTP || s->dst.scrub == NULL)
6008 		return;
6009 
6010 	PF_SCTP_ENDPOINTS_LOCK();
6011 
6012 	key.v_tag = s->dst.scrub->pfss_v_tag;
6013 	ep  = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
6014 	if (ep != NULL) {
6015 		/* XXX Actually remove! */
6016 		TAILQ_FOREACH_SAFE(i, &ep->sources, entry, tmp) {
6017 			if (pf_addr_cmp(&i->addr,
6018 			    &s->key[PF_SK_WIRE]->addr[s->direction == PF_OUT],
6019 			    s->key[PF_SK_WIRE]->af) == 0) {
6020 				TAILQ_REMOVE(&ep->sources, i, entry);
6021 				free(i, M_PFTEMP);
6022 				break;
6023 			}
6024 		}
6025 
6026 		if (TAILQ_EMPTY(&ep->sources)) {
6027 			RB_REMOVE(pf_sctp_endpoints, &V_pf_sctp_endpoints, ep);
6028 			free(ep, M_PFTEMP);
6029 		}
6030 	}
6031 
6032 	/* Other direction. */
6033 	key.v_tag = s->src.scrub->pfss_v_tag;
6034 	ep = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
6035 	if (ep != NULL) {
6036 		TAILQ_FOREACH_SAFE(i, &ep->sources, entry, tmp) {
6037 			if (pf_addr_cmp(&i->addr,
6038 			    &s->key[PF_SK_WIRE]->addr[s->direction == PF_IN],
6039 			    s->key[PF_SK_WIRE]->af) == 0) {
6040 				TAILQ_REMOVE(&ep->sources, i, entry);
6041 				free(i, M_PFTEMP);
6042 				break;
6043 			}
6044 		}
6045 
6046 		if (TAILQ_EMPTY(&ep->sources)) {
6047 			RB_REMOVE(pf_sctp_endpoints, &V_pf_sctp_endpoints, ep);
6048 			free(ep, M_PFTEMP);
6049 		}
6050 	}
6051 
6052 	PF_SCTP_ENDPOINTS_UNLOCK();
6053 }
6054 
6055 static void
6056 pf_sctp_multihome_add_addr(struct pf_pdesc *pd, struct pf_addr *a, uint32_t v_tag)
6057 {
6058 	struct pf_sctp_endpoint key = {
6059 		.v_tag = v_tag,
6060 	};
6061 	struct pf_sctp_source *i;
6062 	struct pf_sctp_endpoint *ep;
6063 
6064 	PF_SCTP_ENDPOINTS_LOCK();
6065 
6066 	ep = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
6067 	if (ep == NULL) {
6068 		ep = malloc(sizeof(struct pf_sctp_endpoint),
6069 		    M_PFTEMP, M_NOWAIT);
6070 		if (ep == NULL) {
6071 			PF_SCTP_ENDPOINTS_UNLOCK();
6072 			return;
6073 		}
6074 
6075 		ep->v_tag = v_tag;
6076 		TAILQ_INIT(&ep->sources);
6077 		RB_INSERT(pf_sctp_endpoints, &V_pf_sctp_endpoints, ep);
6078 	}
6079 
6080 	/* Avoid inserting duplicates. */
6081 	TAILQ_FOREACH(i, &ep->sources, entry) {
6082 		if (pf_addr_cmp(&i->addr, a, pd->af) == 0) {
6083 			PF_SCTP_ENDPOINTS_UNLOCK();
6084 			return;
6085 		}
6086 	}
6087 
6088 	i = malloc(sizeof(*i), M_PFTEMP, M_NOWAIT);
6089 	if (i == NULL) {
6090 		PF_SCTP_ENDPOINTS_UNLOCK();
6091 		return;
6092 	}
6093 
6094 	i->af = pd->af;
6095 	memcpy(&i->addr, a, sizeof(*a));
6096 	TAILQ_INSERT_TAIL(&ep->sources, i, entry);
6097 
6098 	PF_SCTP_ENDPOINTS_UNLOCK();
6099 }
6100 
6101 static void
6102 pf_sctp_multihome_delayed(struct pf_pdesc *pd, int off, struct pfi_kkif *kif,
6103     struct pf_kstate *s, int action)
6104 {
6105 	struct pf_sctp_multihome_job	*j, *tmp;
6106 	struct pf_sctp_source		*i;
6107 	int			 ret __unused;;
6108 	struct pf_kstate	*sm = NULL;
6109 	struct pf_krule		*ra = NULL;
6110 	struct pf_krule		*r = &V_pf_default_rule;
6111 	struct pf_kruleset	*rs = NULL;
6112 	bool do_extra = true;
6113 
6114 	PF_RULES_RLOCK_TRACKER;
6115 
6116 again:
6117 	TAILQ_FOREACH_SAFE(j, &pd->sctp_multihome_jobs, next, tmp) {
6118 		if (s == NULL || action != PF_PASS)
6119 			goto free;
6120 
6121 		/* Confirm we don't recurse here. */
6122 		MPASS(! (pd->sctp_flags & PFDESC_SCTP_ADD_IP));
6123 
6124 		switch (j->op) {
6125 		case  SCTP_ADD_IP_ADDRESS: {
6126 			uint32_t v_tag = pd->sctp_initiate_tag;
6127 
6128 			if (v_tag == 0) {
6129 				if (s->direction == pd->dir)
6130 					v_tag = s->src.scrub->pfss_v_tag;
6131 				else
6132 					v_tag = s->dst.scrub->pfss_v_tag;
6133 			}
6134 
6135 			/*
6136 			 * Avoid duplicating states. We'll already have
6137 			 * created a state based on the source address of
6138 			 * the packet, but SCTP endpoints may also list this
6139 			 * address again in the INIT(_ACK) parameters.
6140 			 */
6141 			if (pf_addr_cmp(&j->src, pd->src, pd->af) == 0) {
6142 				break;
6143 			}
6144 
6145 			j->pd.sctp_flags |= PFDESC_SCTP_ADD_IP;
6146 			PF_RULES_RLOCK();
6147 			sm = NULL;
6148 			/*
6149 			 * New connections need to be floating, because
6150 			 * we cannot know what interfaces it will use.
6151 			 * That's why we pass V_pfi_all rather than kif.
6152 			 */
6153 			ret = pf_test_rule(&r, &sm, V_pfi_all,
6154 			    j->m, off, &j->pd, &ra, &rs, NULL);
6155 			PF_RULES_RUNLOCK();
6156 			SDT_PROBE4(pf, sctp, multihome, test, kif, r, j->m, ret);
6157 			if (ret != PF_DROP && sm != NULL) {
6158 				/* Inherit v_tag values. */
6159 				if (sm->direction == s->direction) {
6160 					sm->src.scrub->pfss_v_tag = s->src.scrub->pfss_v_tag;
6161 					sm->dst.scrub->pfss_v_tag = s->dst.scrub->pfss_v_tag;
6162 				} else {
6163 					sm->src.scrub->pfss_v_tag = s->dst.scrub->pfss_v_tag;
6164 					sm->dst.scrub->pfss_v_tag = s->src.scrub->pfss_v_tag;
6165 				}
6166 				PF_STATE_UNLOCK(sm);
6167 			} else {
6168 				/* If we try duplicate inserts? */
6169 				break;
6170 			}
6171 
6172 			/* Only add the addres if we've actually allowed the state. */
6173 			pf_sctp_multihome_add_addr(pd, &j->src, v_tag);
6174 
6175 			if (! do_extra) {
6176 				break;
6177 			}
6178 			/*
6179 			 * We need to do this for each of our source addresses.
6180 			 * Find those based on the verification tag.
6181 			 */
6182 			struct pf_sctp_endpoint key = {
6183 				.v_tag = pd->hdr.sctp.v_tag,
6184 			};
6185 			struct pf_sctp_endpoint *ep;
6186 
6187 			PF_SCTP_ENDPOINTS_LOCK();
6188 			ep = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
6189 			if (ep == NULL) {
6190 				PF_SCTP_ENDPOINTS_UNLOCK();
6191 				break;
6192 			}
6193 			MPASS(ep != NULL);
6194 
6195 			TAILQ_FOREACH(i, &ep->sources, entry) {
6196 				struct pf_sctp_multihome_job *nj;
6197 
6198 				/* SCTP can intermingle IPv4 and IPv6. */
6199 				if (i->af != pd->af)
6200 					continue;
6201 
6202 				nj = malloc(sizeof(*nj), M_PFTEMP, M_NOWAIT | M_ZERO);
6203 				if (! nj) {
6204 					continue;
6205 				}
6206 				memcpy(&nj->pd, &j->pd, sizeof(j->pd));
6207 				memcpy(&nj->src, &j->src, sizeof(nj->src));
6208 				nj->pd.src = &nj->src;
6209 				// New destination address!
6210 				memcpy(&nj->dst, &i->addr, sizeof(nj->dst));
6211 				nj->pd.dst = &nj->dst;
6212 				nj->m = j->m;
6213 				nj->op = j->op;
6214 
6215 				TAILQ_INSERT_TAIL(&pd->sctp_multihome_jobs, nj, next);
6216 			}
6217 			PF_SCTP_ENDPOINTS_UNLOCK();
6218 
6219 			break;
6220 		}
6221 		case SCTP_DEL_IP_ADDRESS: {
6222 			struct pf_state_key_cmp key;
6223 			uint8_t psrc;
6224 
6225 			bzero(&key, sizeof(key));
6226 			key.af = j->pd.af;
6227 			key.proto = IPPROTO_SCTP;
6228 			if (j->pd.dir == PF_IN)	{	/* wire side, straight */
6229 				PF_ACPY(&key.addr[0], j->pd.src, key.af);
6230 				PF_ACPY(&key.addr[1], j->pd.dst, key.af);
6231 				key.port[0] = j->pd.hdr.sctp.src_port;
6232 				key.port[1] = j->pd.hdr.sctp.dest_port;
6233 			} else {			/* stack side, reverse */
6234 				PF_ACPY(&key.addr[1], j->pd.src, key.af);
6235 				PF_ACPY(&key.addr[0], j->pd.dst, key.af);
6236 				key.port[1] = j->pd.hdr.sctp.src_port;
6237 				key.port[0] = j->pd.hdr.sctp.dest_port;
6238 			}
6239 
6240 			sm = pf_find_state(kif, &key, j->pd.dir);
6241 			if (sm != NULL) {
6242 				PF_STATE_LOCK_ASSERT(sm);
6243 				if (j->pd.dir == sm->direction) {
6244 					psrc = PF_PEER_SRC;
6245 				} else {
6246 					psrc = PF_PEER_DST;
6247 				}
6248 				pf_set_protostate(sm, psrc, SCTP_SHUTDOWN_PENDING);
6249 				sm->timeout = PFTM_SCTP_CLOSING;
6250 				PF_STATE_UNLOCK(sm);
6251 			}
6252 			break;
6253 		default:
6254 			panic("Unknown op %#x", j->op);
6255 		}
6256 	}
6257 
6258 	free:
6259 		TAILQ_REMOVE(&pd->sctp_multihome_jobs, j, next);
6260 		free(j, M_PFTEMP);
6261 	}
6262 
6263 	/* We may have inserted extra work while processing the list. */
6264 	if (! TAILQ_EMPTY(&pd->sctp_multihome_jobs)) {
6265 		do_extra = false;
6266 		goto again;
6267 	}
6268 }
6269 
6270 static int
6271 pf_multihome_scan(struct mbuf *m, int start, int len, struct pf_pdesc *pd,
6272     struct pfi_kkif *kif, int op)
6273 {
6274 	int			 off = 0;
6275 	struct pf_sctp_multihome_job	*job;
6276 
6277 	while (off < len) {
6278 		struct sctp_paramhdr h;
6279 
6280 		if (!pf_pull_hdr(m, start + off, &h, sizeof(h), NULL, NULL,
6281 		    pd->af))
6282 			return (PF_DROP);
6283 
6284 		/* Parameters are at least 4 bytes. */
6285 		if (ntohs(h.param_length) < 4)
6286 			return (PF_DROP);
6287 
6288 		switch (ntohs(h.param_type)) {
6289 		case  SCTP_IPV4_ADDRESS: {
6290 			struct in_addr t;
6291 
6292 			if (ntohs(h.param_length) !=
6293 			    (sizeof(struct sctp_paramhdr) + sizeof(t)))
6294 				return (PF_DROP);
6295 
6296 			if (!pf_pull_hdr(m, start + off + sizeof(h), &t, sizeof(t),
6297 			    NULL, NULL, pd->af))
6298 				return (PF_DROP);
6299 
6300 			if (in_nullhost(t))
6301 				t.s_addr = pd->src->v4.s_addr;
6302 
6303 			/*
6304 			 * We hold the state lock (idhash) here, which means
6305 			 * that we can't acquire the keyhash, or we'll get a
6306 			 * LOR (and potentially double-lock things too). We also
6307 			 * can't release the state lock here, so instead we'll
6308 			 * enqueue this for async handling.
6309 			 * There's a relatively small race here, in that a
6310 			 * packet using the new addresses could arrive already,
6311 			 * but that's just though luck for it.
6312 			 */
6313 			job = malloc(sizeof(*job), M_PFTEMP, M_NOWAIT | M_ZERO);
6314 			if (! job)
6315 				return (PF_DROP);
6316 
6317 			memcpy(&job->pd, pd, sizeof(*pd));
6318 
6319 			// New source address!
6320 			memcpy(&job->src, &t, sizeof(t));
6321 			job->pd.src = &job->src;
6322 			memcpy(&job->dst, pd->dst, sizeof(job->dst));
6323 			job->pd.dst = &job->dst;
6324 			job->m = m;
6325 			job->op = op;
6326 
6327 			TAILQ_INSERT_TAIL(&pd->sctp_multihome_jobs, job, next);
6328 			break;
6329 		}
6330 #ifdef INET6
6331 		case SCTP_IPV6_ADDRESS: {
6332 			struct in6_addr t;
6333 
6334 			if (ntohs(h.param_length) !=
6335 			    (sizeof(struct sctp_paramhdr) + sizeof(t)))
6336 				return (PF_DROP);
6337 
6338 			if (!pf_pull_hdr(m, start + off + sizeof(h), &t, sizeof(t),
6339 			    NULL, NULL, pd->af))
6340 				return (PF_DROP);
6341 			if (memcmp(&t, &pd->src->v6, sizeof(t)) == 0)
6342 				break;
6343 			if (memcmp(&t, &in6addr_any, sizeof(t)) == 0)
6344 				memcpy(&t, &pd->src->v6, sizeof(t));
6345 
6346 			job = malloc(sizeof(*job), M_PFTEMP, M_NOWAIT | M_ZERO);
6347 			if (! job)
6348 				return (PF_DROP);
6349 
6350 			memcpy(&job->pd, pd, sizeof(*pd));
6351 			memcpy(&job->src, &t, sizeof(t));
6352 			job->pd.src = &job->src;
6353 			memcpy(&job->dst, pd->dst, sizeof(job->dst));
6354 			job->pd.dst = &job->dst;
6355 			job->m = m;
6356 			job->op = op;
6357 
6358 			TAILQ_INSERT_TAIL(&pd->sctp_multihome_jobs, job, next);
6359 			break;
6360 		}
6361 #endif
6362 		case SCTP_ADD_IP_ADDRESS: {
6363 			int ret;
6364 			struct sctp_asconf_paramhdr ah;
6365 
6366 			if (!pf_pull_hdr(m, start + off, &ah, sizeof(ah),
6367 			    NULL, NULL, pd->af))
6368 				return (PF_DROP);
6369 
6370 			ret = pf_multihome_scan(m, start + off + sizeof(ah),
6371 			    ntohs(ah.ph.param_length) - sizeof(ah), pd, kif,
6372 			    SCTP_ADD_IP_ADDRESS);
6373 			if (ret != PF_PASS)
6374 				return (ret);
6375 			break;
6376 		}
6377 		case SCTP_DEL_IP_ADDRESS: {
6378 			int ret;
6379 			struct sctp_asconf_paramhdr ah;
6380 
6381 			if (!pf_pull_hdr(m, start + off, &ah, sizeof(ah),
6382 			    NULL, NULL, pd->af))
6383 				return (PF_DROP);
6384 			ret = pf_multihome_scan(m, start + off + sizeof(ah),
6385 			    ntohs(ah.ph.param_length) - sizeof(ah), pd, kif,
6386 			    SCTP_DEL_IP_ADDRESS);
6387 			if (ret != PF_PASS)
6388 				return (ret);
6389 			break;
6390 		}
6391 		default:
6392 			break;
6393 		}
6394 
6395 		off += roundup(ntohs(h.param_length), 4);
6396 	}
6397 
6398 	return (PF_PASS);
6399 }
6400 int
6401 pf_multihome_scan_init(struct mbuf *m, int start, int len, struct pf_pdesc *pd,
6402     struct pfi_kkif *kif)
6403 {
6404 	start += sizeof(struct sctp_init_chunk);
6405 	len -= sizeof(struct sctp_init_chunk);
6406 
6407 	return (pf_multihome_scan(m, start, len, pd, kif, SCTP_ADD_IP_ADDRESS));
6408 }
6409 
6410 int
6411 pf_multihome_scan_asconf(struct mbuf *m, int start, int len,
6412     struct pf_pdesc *pd, struct pfi_kkif *kif)
6413 {
6414 	start += sizeof(struct sctp_asconf_chunk);
6415 	len -= sizeof(struct sctp_asconf_chunk);
6416 
6417 	return (pf_multihome_scan(m, start, len, pd, kif, SCTP_ADD_IP_ADDRESS));
6418 }
6419 
6420 static int
6421 pf_test_state_icmp(struct pf_kstate **state, struct pfi_kkif *kif,
6422     struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
6423 {
6424 	struct pf_addr  *saddr = pd->src, *daddr = pd->dst;
6425 	u_int16_t	 icmpid = 0, *icmpsum;
6426 	u_int8_t	 icmptype, icmpcode;
6427 	int		 state_icmp = 0;
6428 	struct pf_state_key_cmp key;
6429 
6430 	bzero(&key, sizeof(key));
6431 	switch (pd->proto) {
6432 #ifdef INET
6433 	case IPPROTO_ICMP:
6434 		icmptype = pd->hdr.icmp.icmp_type;
6435 		icmpcode = pd->hdr.icmp.icmp_code;
6436 		icmpid = pd->hdr.icmp.icmp_id;
6437 		icmpsum = &pd->hdr.icmp.icmp_cksum;
6438 
6439 		if (icmptype == ICMP_UNREACH ||
6440 		    icmptype == ICMP_SOURCEQUENCH ||
6441 		    icmptype == ICMP_REDIRECT ||
6442 		    icmptype == ICMP_TIMXCEED ||
6443 		    icmptype == ICMP_PARAMPROB)
6444 			state_icmp++;
6445 		break;
6446 #endif /* INET */
6447 #ifdef INET6
6448 	case IPPROTO_ICMPV6:
6449 		icmptype = pd->hdr.icmp6.icmp6_type;
6450 		icmpcode = pd->hdr.icmp6.icmp6_code;
6451 		icmpid = pd->hdr.icmp6.icmp6_id;
6452 		icmpsum = &pd->hdr.icmp6.icmp6_cksum;
6453 
6454 		if (icmptype == ICMP6_DST_UNREACH ||
6455 		    icmptype == ICMP6_PACKET_TOO_BIG ||
6456 		    icmptype == ICMP6_TIME_EXCEEDED ||
6457 		    icmptype == ICMP6_PARAM_PROB)
6458 			state_icmp++;
6459 		break;
6460 #endif /* INET6 */
6461 	}
6462 
6463 	if (!state_icmp) {
6464 		/*
6465 		 * ICMP query/reply message not related to a TCP/UDP packet.
6466 		 * Search for an ICMP state.
6467 		 */
6468 		key.af = pd->af;
6469 		key.proto = pd->proto;
6470 		key.port[0] = key.port[1] = icmpid;
6471 		if (pd->dir == PF_IN)	{	/* wire side, straight */
6472 			PF_ACPY(&key.addr[0], pd->src, key.af);
6473 			PF_ACPY(&key.addr[1], pd->dst, key.af);
6474 		} else {			/* stack side, reverse */
6475 			PF_ACPY(&key.addr[1], pd->src, key.af);
6476 			PF_ACPY(&key.addr[0], pd->dst, key.af);
6477 		}
6478 
6479 		STATE_LOOKUP(kif, &key, *state, pd);
6480 
6481 		(*state)->expire = pf_get_uptime();
6482 		(*state)->timeout = PFTM_ICMP_ERROR_REPLY;
6483 
6484 		/* translate source/destination address, if necessary */
6485 		if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
6486 			struct pf_state_key *nk = (*state)->key[pd->didx];
6487 
6488 			switch (pd->af) {
6489 #ifdef INET
6490 			case AF_INET:
6491 				if (PF_ANEQ(pd->src,
6492 				    &nk->addr[pd->sidx], AF_INET))
6493 					pf_change_a(&saddr->v4.s_addr,
6494 					    pd->ip_sum,
6495 					    nk->addr[pd->sidx].v4.s_addr, 0);
6496 
6497 				if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
6498 				    AF_INET))
6499 					pf_change_a(&daddr->v4.s_addr,
6500 					    pd->ip_sum,
6501 					    nk->addr[pd->didx].v4.s_addr, 0);
6502 
6503 				if (nk->port[0] !=
6504 				    pd->hdr.icmp.icmp_id) {
6505 					pd->hdr.icmp.icmp_cksum =
6506 					    pf_cksum_fixup(
6507 					    pd->hdr.icmp.icmp_cksum, icmpid,
6508 					    nk->port[pd->sidx], 0);
6509 					pd->hdr.icmp.icmp_id =
6510 					    nk->port[pd->sidx];
6511 				}
6512 
6513 				m_copyback(m, off, ICMP_MINLEN,
6514 				    (caddr_t )&pd->hdr.icmp);
6515 				break;
6516 #endif /* INET */
6517 #ifdef INET6
6518 			case AF_INET6:
6519 				if (PF_ANEQ(pd->src,
6520 				    &nk->addr[pd->sidx], AF_INET6))
6521 					pf_change_a6(saddr,
6522 					    &pd->hdr.icmp6.icmp6_cksum,
6523 					    &nk->addr[pd->sidx], 0);
6524 
6525 				if (PF_ANEQ(pd->dst,
6526 				    &nk->addr[pd->didx], AF_INET6))
6527 					pf_change_a6(daddr,
6528 					    &pd->hdr.icmp6.icmp6_cksum,
6529 					    &nk->addr[pd->didx], 0);
6530 
6531 				m_copyback(m, off, sizeof(struct icmp6_hdr),
6532 				    (caddr_t )&pd->hdr.icmp6);
6533 				break;
6534 #endif /* INET6 */
6535 			}
6536 		}
6537 		return (PF_PASS);
6538 
6539 	} else {
6540 		/*
6541 		 * ICMP error message in response to a TCP/UDP packet.
6542 		 * Extract the inner TCP/UDP header and search for that state.
6543 		 */
6544 
6545 		struct pf_pdesc	pd2;
6546 		bzero(&pd2, sizeof pd2);
6547 #ifdef INET
6548 		struct ip	h2;
6549 #endif /* INET */
6550 #ifdef INET6
6551 		struct ip6_hdr	h2_6;
6552 		int		terminal = 0;
6553 #endif /* INET6 */
6554 		int		ipoff2 = 0;
6555 		int		off2 = 0;
6556 
6557 		pd2.af = pd->af;
6558 		/* Payload packet is from the opposite direction. */
6559 		pd2.sidx = (pd->dir == PF_IN) ? 1 : 0;
6560 		pd2.didx = (pd->dir == PF_IN) ? 0 : 1;
6561 		switch (pd->af) {
6562 #ifdef INET
6563 		case AF_INET:
6564 			/* offset of h2 in mbuf chain */
6565 			ipoff2 = off + ICMP_MINLEN;
6566 
6567 			if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
6568 			    NULL, reason, pd2.af)) {
6569 				DPFPRINTF(PF_DEBUG_MISC,
6570 				    ("pf: ICMP error message too short "
6571 				    "(ip)\n"));
6572 				return (PF_DROP);
6573 			}
6574 			/*
6575 			 * ICMP error messages don't refer to non-first
6576 			 * fragments
6577 			 */
6578 			if (h2.ip_off & htons(IP_OFFMASK)) {
6579 				REASON_SET(reason, PFRES_FRAG);
6580 				return (PF_DROP);
6581 			}
6582 
6583 			/* offset of protocol header that follows h2 */
6584 			off2 = ipoff2 + (h2.ip_hl << 2);
6585 
6586 			pd2.proto = h2.ip_p;
6587 			pd2.src = (struct pf_addr *)&h2.ip_src;
6588 			pd2.dst = (struct pf_addr *)&h2.ip_dst;
6589 			pd2.ip_sum = &h2.ip_sum;
6590 			break;
6591 #endif /* INET */
6592 #ifdef INET6
6593 		case AF_INET6:
6594 			ipoff2 = off + sizeof(struct icmp6_hdr);
6595 
6596 			if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
6597 			    NULL, reason, pd2.af)) {
6598 				DPFPRINTF(PF_DEBUG_MISC,
6599 				    ("pf: ICMP error message too short "
6600 				    "(ip6)\n"));
6601 				return (PF_DROP);
6602 			}
6603 			pd2.proto = h2_6.ip6_nxt;
6604 			pd2.src = (struct pf_addr *)&h2_6.ip6_src;
6605 			pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
6606 			pd2.ip_sum = NULL;
6607 			off2 = ipoff2 + sizeof(h2_6);
6608 			do {
6609 				switch (pd2.proto) {
6610 				case IPPROTO_FRAGMENT:
6611 					/*
6612 					 * ICMPv6 error messages for
6613 					 * non-first fragments
6614 					 */
6615 					REASON_SET(reason, PFRES_FRAG);
6616 					return (PF_DROP);
6617 				case IPPROTO_AH:
6618 				case IPPROTO_HOPOPTS:
6619 				case IPPROTO_ROUTING:
6620 				case IPPROTO_DSTOPTS: {
6621 					/* get next header and header length */
6622 					struct ip6_ext opt6;
6623 
6624 					if (!pf_pull_hdr(m, off2, &opt6,
6625 					    sizeof(opt6), NULL, reason,
6626 					    pd2.af)) {
6627 						DPFPRINTF(PF_DEBUG_MISC,
6628 						    ("pf: ICMPv6 short opt\n"));
6629 						return (PF_DROP);
6630 					}
6631 					if (pd2.proto == IPPROTO_AH)
6632 						off2 += (opt6.ip6e_len + 2) * 4;
6633 					else
6634 						off2 += (opt6.ip6e_len + 1) * 8;
6635 					pd2.proto = opt6.ip6e_nxt;
6636 					/* goto the next header */
6637 					break;
6638 				}
6639 				default:
6640 					terminal++;
6641 					break;
6642 				}
6643 			} while (!terminal);
6644 			break;
6645 #endif /* INET6 */
6646 		}
6647 
6648 		if (PF_ANEQ(pd->dst, pd2.src, pd->af)) {
6649 			if (V_pf_status.debug >= PF_DEBUG_MISC) {
6650 				printf("pf: BAD ICMP %d:%d outer dst: ",
6651 				    icmptype, icmpcode);
6652 				pf_print_host(pd->src, 0, pd->af);
6653 				printf(" -> ");
6654 				pf_print_host(pd->dst, 0, pd->af);
6655 				printf(" inner src: ");
6656 				pf_print_host(pd2.src, 0, pd2.af);
6657 				printf(" -> ");
6658 				pf_print_host(pd2.dst, 0, pd2.af);
6659 				printf("\n");
6660 			}
6661 			REASON_SET(reason, PFRES_BADSTATE);
6662 			return (PF_DROP);
6663 		}
6664 
6665 		switch (pd2.proto) {
6666 		case IPPROTO_TCP: {
6667 			struct tcphdr		 th;
6668 			u_int32_t		 seq;
6669 			struct pf_state_peer	*src, *dst;
6670 			u_int8_t		 dws;
6671 			int			 copyback = 0;
6672 
6673 			/*
6674 			 * Only the first 8 bytes of the TCP header can be
6675 			 * expected. Don't access any TCP header fields after
6676 			 * th_seq, an ackskew test is not possible.
6677 			 */
6678 			if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
6679 			    pd2.af)) {
6680 				DPFPRINTF(PF_DEBUG_MISC,
6681 				    ("pf: ICMP error message too short "
6682 				    "(tcp)\n"));
6683 				return (PF_DROP);
6684 			}
6685 
6686 			key.af = pd2.af;
6687 			key.proto = IPPROTO_TCP;
6688 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
6689 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
6690 			key.port[pd2.sidx] = th.th_sport;
6691 			key.port[pd2.didx] = th.th_dport;
6692 
6693 			STATE_LOOKUP(kif, &key, *state, pd);
6694 
6695 			if (pd->dir == (*state)->direction) {
6696 				src = &(*state)->dst;
6697 				dst = &(*state)->src;
6698 			} else {
6699 				src = &(*state)->src;
6700 				dst = &(*state)->dst;
6701 			}
6702 
6703 			if (src->wscale && dst->wscale)
6704 				dws = dst->wscale & PF_WSCALE_MASK;
6705 			else
6706 				dws = 0;
6707 
6708 			/* Demodulate sequence number */
6709 			seq = ntohl(th.th_seq) - src->seqdiff;
6710 			if (src->seqdiff) {
6711 				pf_change_a(&th.th_seq, icmpsum,
6712 				    htonl(seq), 0);
6713 				copyback = 1;
6714 			}
6715 
6716 			if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
6717 			    (!SEQ_GEQ(src->seqhi, seq) ||
6718 			    !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
6719 				if (V_pf_status.debug >= PF_DEBUG_MISC) {
6720 					printf("pf: BAD ICMP %d:%d ",
6721 					    icmptype, icmpcode);
6722 					pf_print_host(pd->src, 0, pd->af);
6723 					printf(" -> ");
6724 					pf_print_host(pd->dst, 0, pd->af);
6725 					printf(" state: ");
6726 					pf_print_state(*state);
6727 					printf(" seq=%u\n", seq);
6728 				}
6729 				REASON_SET(reason, PFRES_BADSTATE);
6730 				return (PF_DROP);
6731 			} else {
6732 				if (V_pf_status.debug >= PF_DEBUG_MISC) {
6733 					printf("pf: OK ICMP %d:%d ",
6734 					    icmptype, icmpcode);
6735 					pf_print_host(pd->src, 0, pd->af);
6736 					printf(" -> ");
6737 					pf_print_host(pd->dst, 0, pd->af);
6738 					printf(" state: ");
6739 					pf_print_state(*state);
6740 					printf(" seq=%u\n", seq);
6741 				}
6742 			}
6743 
6744 			/* translate source/destination address, if necessary */
6745 			if ((*state)->key[PF_SK_WIRE] !=
6746 			    (*state)->key[PF_SK_STACK]) {
6747 				struct pf_state_key *nk =
6748 				    (*state)->key[pd->didx];
6749 
6750 				if (PF_ANEQ(pd2.src,
6751 				    &nk->addr[pd2.sidx], pd2.af) ||
6752 				    nk->port[pd2.sidx] != th.th_sport)
6753 					pf_change_icmp(pd2.src, &th.th_sport,
6754 					    daddr, &nk->addr[pd2.sidx],
6755 					    nk->port[pd2.sidx], NULL,
6756 					    pd2.ip_sum, icmpsum,
6757 					    pd->ip_sum, 0, pd2.af);
6758 
6759 				if (PF_ANEQ(pd2.dst,
6760 				    &nk->addr[pd2.didx], pd2.af) ||
6761 				    nk->port[pd2.didx] != th.th_dport)
6762 					pf_change_icmp(pd2.dst, &th.th_dport,
6763 					    saddr, &nk->addr[pd2.didx],
6764 					    nk->port[pd2.didx], NULL,
6765 					    pd2.ip_sum, icmpsum,
6766 					    pd->ip_sum, 0, pd2.af);
6767 				copyback = 1;
6768 			}
6769 
6770 			if (copyback) {
6771 				switch (pd2.af) {
6772 #ifdef INET
6773 				case AF_INET:
6774 					m_copyback(m, off, ICMP_MINLEN,
6775 					    (caddr_t )&pd->hdr.icmp);
6776 					m_copyback(m, ipoff2, sizeof(h2),
6777 					    (caddr_t )&h2);
6778 					break;
6779 #endif /* INET */
6780 #ifdef INET6
6781 				case AF_INET6:
6782 					m_copyback(m, off,
6783 					    sizeof(struct icmp6_hdr),
6784 					    (caddr_t )&pd->hdr.icmp6);
6785 					m_copyback(m, ipoff2, sizeof(h2_6),
6786 					    (caddr_t )&h2_6);
6787 					break;
6788 #endif /* INET6 */
6789 				}
6790 				m_copyback(m, off2, 8, (caddr_t)&th);
6791 			}
6792 
6793 			return (PF_PASS);
6794 			break;
6795 		}
6796 		case IPPROTO_UDP: {
6797 			struct udphdr		uh;
6798 
6799 			if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
6800 			    NULL, reason, pd2.af)) {
6801 				DPFPRINTF(PF_DEBUG_MISC,
6802 				    ("pf: ICMP error message too short "
6803 				    "(udp)\n"));
6804 				return (PF_DROP);
6805 			}
6806 
6807 			key.af = pd2.af;
6808 			key.proto = IPPROTO_UDP;
6809 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
6810 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
6811 			key.port[pd2.sidx] = uh.uh_sport;
6812 			key.port[pd2.didx] = uh.uh_dport;
6813 
6814 			STATE_LOOKUP(kif, &key, *state, pd);
6815 
6816 			/* translate source/destination address, if necessary */
6817 			if ((*state)->key[PF_SK_WIRE] !=
6818 			    (*state)->key[PF_SK_STACK]) {
6819 				struct pf_state_key *nk =
6820 				    (*state)->key[pd->didx];
6821 
6822 				if (PF_ANEQ(pd2.src,
6823 				    &nk->addr[pd2.sidx], pd2.af) ||
6824 				    nk->port[pd2.sidx] != uh.uh_sport)
6825 					pf_change_icmp(pd2.src, &uh.uh_sport,
6826 					    daddr, &nk->addr[pd2.sidx],
6827 					    nk->port[pd2.sidx], &uh.uh_sum,
6828 					    pd2.ip_sum, icmpsum,
6829 					    pd->ip_sum, 1, pd2.af);
6830 
6831 				if (PF_ANEQ(pd2.dst,
6832 				    &nk->addr[pd2.didx], pd2.af) ||
6833 				    nk->port[pd2.didx] != uh.uh_dport)
6834 					pf_change_icmp(pd2.dst, &uh.uh_dport,
6835 					    saddr, &nk->addr[pd2.didx],
6836 					    nk->port[pd2.didx], &uh.uh_sum,
6837 					    pd2.ip_sum, icmpsum,
6838 					    pd->ip_sum, 1, pd2.af);
6839 
6840 				switch (pd2.af) {
6841 #ifdef INET
6842 				case AF_INET:
6843 					m_copyback(m, off, ICMP_MINLEN,
6844 					    (caddr_t )&pd->hdr.icmp);
6845 					m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
6846 					break;
6847 #endif /* INET */
6848 #ifdef INET6
6849 				case AF_INET6:
6850 					m_copyback(m, off,
6851 					    sizeof(struct icmp6_hdr),
6852 					    (caddr_t )&pd->hdr.icmp6);
6853 					m_copyback(m, ipoff2, sizeof(h2_6),
6854 					    (caddr_t )&h2_6);
6855 					break;
6856 #endif /* INET6 */
6857 				}
6858 				m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
6859 			}
6860 			return (PF_PASS);
6861 			break;
6862 		}
6863 #ifdef INET
6864 		case IPPROTO_ICMP: {
6865 			struct icmp		iih;
6866 
6867 			if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
6868 			    NULL, reason, pd2.af)) {
6869 				DPFPRINTF(PF_DEBUG_MISC,
6870 				    ("pf: ICMP error message too short i"
6871 				    "(icmp)\n"));
6872 				return (PF_DROP);
6873 			}
6874 
6875 			key.af = pd2.af;
6876 			key.proto = IPPROTO_ICMP;
6877 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
6878 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
6879 			key.port[0] = key.port[1] = iih.icmp_id;
6880 
6881 			STATE_LOOKUP(kif, &key, *state, pd);
6882 
6883 			/* translate source/destination address, if necessary */
6884 			if ((*state)->key[PF_SK_WIRE] !=
6885 			    (*state)->key[PF_SK_STACK]) {
6886 				struct pf_state_key *nk =
6887 				    (*state)->key[pd->didx];
6888 
6889 				if (PF_ANEQ(pd2.src,
6890 				    &nk->addr[pd2.sidx], pd2.af) ||
6891 				    nk->port[pd2.sidx] != iih.icmp_id)
6892 					pf_change_icmp(pd2.src, &iih.icmp_id,
6893 					    daddr, &nk->addr[pd2.sidx],
6894 					    nk->port[pd2.sidx], NULL,
6895 					    pd2.ip_sum, icmpsum,
6896 					    pd->ip_sum, 0, AF_INET);
6897 
6898 				if (PF_ANEQ(pd2.dst,
6899 				    &nk->addr[pd2.didx], pd2.af) ||
6900 				    nk->port[pd2.didx] != iih.icmp_id)
6901 					pf_change_icmp(pd2.dst, &iih.icmp_id,
6902 					    saddr, &nk->addr[pd2.didx],
6903 					    nk->port[pd2.didx], NULL,
6904 					    pd2.ip_sum, icmpsum,
6905 					    pd->ip_sum, 0, AF_INET);
6906 
6907 				m_copyback(m, off, ICMP_MINLEN, (caddr_t)&pd->hdr.icmp);
6908 				m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
6909 				m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
6910 			}
6911 			return (PF_PASS);
6912 			break;
6913 		}
6914 #endif /* INET */
6915 #ifdef INET6
6916 		case IPPROTO_ICMPV6: {
6917 			struct icmp6_hdr	iih;
6918 
6919 			if (!pf_pull_hdr(m, off2, &iih,
6920 			    sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
6921 				DPFPRINTF(PF_DEBUG_MISC,
6922 				    ("pf: ICMP error message too short "
6923 				    "(icmp6)\n"));
6924 				return (PF_DROP);
6925 			}
6926 
6927 			key.af = pd2.af;
6928 			key.proto = IPPROTO_ICMPV6;
6929 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
6930 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
6931 			key.port[0] = key.port[1] = iih.icmp6_id;
6932 
6933 			STATE_LOOKUP(kif, &key, *state, pd);
6934 
6935 			/* translate source/destination address, if necessary */
6936 			if ((*state)->key[PF_SK_WIRE] !=
6937 			    (*state)->key[PF_SK_STACK]) {
6938 				struct pf_state_key *nk =
6939 				    (*state)->key[pd->didx];
6940 
6941 				if (PF_ANEQ(pd2.src,
6942 				    &nk->addr[pd2.sidx], pd2.af) ||
6943 				    nk->port[pd2.sidx] != iih.icmp6_id)
6944 					pf_change_icmp(pd2.src, &iih.icmp6_id,
6945 					    daddr, &nk->addr[pd2.sidx],
6946 					    nk->port[pd2.sidx], NULL,
6947 					    pd2.ip_sum, icmpsum,
6948 					    pd->ip_sum, 0, AF_INET6);
6949 
6950 				if (PF_ANEQ(pd2.dst,
6951 				    &nk->addr[pd2.didx], pd2.af) ||
6952 				    nk->port[pd2.didx] != iih.icmp6_id)
6953 					pf_change_icmp(pd2.dst, &iih.icmp6_id,
6954 					    saddr, &nk->addr[pd2.didx],
6955 					    nk->port[pd2.didx], NULL,
6956 					    pd2.ip_sum, icmpsum,
6957 					    pd->ip_sum, 0, AF_INET6);
6958 
6959 				m_copyback(m, off, sizeof(struct icmp6_hdr),
6960 				    (caddr_t)&pd->hdr.icmp6);
6961 				m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
6962 				m_copyback(m, off2, sizeof(struct icmp6_hdr),
6963 				    (caddr_t)&iih);
6964 			}
6965 			return (PF_PASS);
6966 			break;
6967 		}
6968 #endif /* INET6 */
6969 		default: {
6970 			key.af = pd2.af;
6971 			key.proto = pd2.proto;
6972 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
6973 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
6974 			key.port[0] = key.port[1] = 0;
6975 
6976 			STATE_LOOKUP(kif, &key, *state, pd);
6977 
6978 			/* translate source/destination address, if necessary */
6979 			if ((*state)->key[PF_SK_WIRE] !=
6980 			    (*state)->key[PF_SK_STACK]) {
6981 				struct pf_state_key *nk =
6982 				    (*state)->key[pd->didx];
6983 
6984 				if (PF_ANEQ(pd2.src,
6985 				    &nk->addr[pd2.sidx], pd2.af))
6986 					pf_change_icmp(pd2.src, NULL, daddr,
6987 					    &nk->addr[pd2.sidx], 0, NULL,
6988 					    pd2.ip_sum, icmpsum,
6989 					    pd->ip_sum, 0, pd2.af);
6990 
6991 				if (PF_ANEQ(pd2.dst,
6992 				    &nk->addr[pd2.didx], pd2.af))
6993 					pf_change_icmp(pd2.dst, NULL, saddr,
6994 					    &nk->addr[pd2.didx], 0, NULL,
6995 					    pd2.ip_sum, icmpsum,
6996 					    pd->ip_sum, 0, pd2.af);
6997 
6998 				switch (pd2.af) {
6999 #ifdef INET
7000 				case AF_INET:
7001 					m_copyback(m, off, ICMP_MINLEN,
7002 					    (caddr_t)&pd->hdr.icmp);
7003 					m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
7004 					break;
7005 #endif /* INET */
7006 #ifdef INET6
7007 				case AF_INET6:
7008 					m_copyback(m, off,
7009 					    sizeof(struct icmp6_hdr),
7010 					    (caddr_t )&pd->hdr.icmp6);
7011 					m_copyback(m, ipoff2, sizeof(h2_6),
7012 					    (caddr_t )&h2_6);
7013 					break;
7014 #endif /* INET6 */
7015 				}
7016 			}
7017 			return (PF_PASS);
7018 			break;
7019 		}
7020 		}
7021 	}
7022 }
7023 
7024 static int
7025 pf_test_state_other(struct pf_kstate **state, struct pfi_kkif *kif,
7026     struct mbuf *m, struct pf_pdesc *pd)
7027 {
7028 	struct pf_state_peer	*src, *dst;
7029 	struct pf_state_key_cmp	 key;
7030 	uint8_t			 psrc, pdst;
7031 
7032 	bzero(&key, sizeof(key));
7033 	key.af = pd->af;
7034 	key.proto = pd->proto;
7035 	if (pd->dir == PF_IN)	{
7036 		PF_ACPY(&key.addr[0], pd->src, key.af);
7037 		PF_ACPY(&key.addr[1], pd->dst, key.af);
7038 		key.port[0] = key.port[1] = 0;
7039 	} else {
7040 		PF_ACPY(&key.addr[1], pd->src, key.af);
7041 		PF_ACPY(&key.addr[0], pd->dst, key.af);
7042 		key.port[1] = key.port[0] = 0;
7043 	}
7044 
7045 	STATE_LOOKUP(kif, &key, *state, pd);
7046 
7047 	if (pd->dir == (*state)->direction) {
7048 		src = &(*state)->src;
7049 		dst = &(*state)->dst;
7050 		psrc = PF_PEER_SRC;
7051 		pdst = PF_PEER_DST;
7052 	} else {
7053 		src = &(*state)->dst;
7054 		dst = &(*state)->src;
7055 		psrc = PF_PEER_DST;
7056 		pdst = PF_PEER_SRC;
7057 	}
7058 
7059 	/* update states */
7060 	if (src->state < PFOTHERS_SINGLE)
7061 		pf_set_protostate(*state, psrc, PFOTHERS_SINGLE);
7062 	if (dst->state == PFOTHERS_SINGLE)
7063 		pf_set_protostate(*state, pdst, PFOTHERS_MULTIPLE);
7064 
7065 	/* update expire time */
7066 	(*state)->expire = pf_get_uptime();
7067 	if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
7068 		(*state)->timeout = PFTM_OTHER_MULTIPLE;
7069 	else
7070 		(*state)->timeout = PFTM_OTHER_SINGLE;
7071 
7072 	/* translate source/destination address, if necessary */
7073 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
7074 		struct pf_state_key *nk = (*state)->key[pd->didx];
7075 
7076 		KASSERT(nk, ("%s: nk is null", __func__));
7077 		KASSERT(pd, ("%s: pd is null", __func__));
7078 		KASSERT(pd->src, ("%s: pd->src is null", __func__));
7079 		KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
7080 		switch (pd->af) {
7081 #ifdef INET
7082 		case AF_INET:
7083 			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
7084 				pf_change_a(&pd->src->v4.s_addr,
7085 				    pd->ip_sum,
7086 				    nk->addr[pd->sidx].v4.s_addr,
7087 				    0);
7088 
7089 			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
7090 				pf_change_a(&pd->dst->v4.s_addr,
7091 				    pd->ip_sum,
7092 				    nk->addr[pd->didx].v4.s_addr,
7093 				    0);
7094 
7095 			break;
7096 #endif /* INET */
7097 #ifdef INET6
7098 		case AF_INET6:
7099 			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
7100 				PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
7101 
7102 			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
7103 				PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
7104 #endif /* INET6 */
7105 		}
7106 	}
7107 	return (PF_PASS);
7108 }
7109 
7110 /*
7111  * ipoff and off are measured from the start of the mbuf chain.
7112  * h must be at "ipoff" on the mbuf chain.
7113  */
7114 void *
7115 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
7116     u_short *actionp, u_short *reasonp, sa_family_t af)
7117 {
7118 	switch (af) {
7119 #ifdef INET
7120 	case AF_INET: {
7121 		struct ip	*h = mtod(m, struct ip *);
7122 		u_int16_t	 fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
7123 
7124 		if (fragoff) {
7125 			if (fragoff >= len)
7126 				ACTION_SET(actionp, PF_PASS);
7127 			else {
7128 				ACTION_SET(actionp, PF_DROP);
7129 				REASON_SET(reasonp, PFRES_FRAG);
7130 			}
7131 			return (NULL);
7132 		}
7133 		if (m->m_pkthdr.len < off + len ||
7134 		    ntohs(h->ip_len) < off + len) {
7135 			ACTION_SET(actionp, PF_DROP);
7136 			REASON_SET(reasonp, PFRES_SHORT);
7137 			return (NULL);
7138 		}
7139 		break;
7140 	}
7141 #endif /* INET */
7142 #ifdef INET6
7143 	case AF_INET6: {
7144 		struct ip6_hdr	*h = mtod(m, struct ip6_hdr *);
7145 
7146 		if (m->m_pkthdr.len < off + len ||
7147 		    (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
7148 		    (unsigned)(off + len)) {
7149 			ACTION_SET(actionp, PF_DROP);
7150 			REASON_SET(reasonp, PFRES_SHORT);
7151 			return (NULL);
7152 		}
7153 		break;
7154 	}
7155 #endif /* INET6 */
7156 	}
7157 	m_copydata(m, off, len, p);
7158 	return (p);
7159 }
7160 
7161 int
7162 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kkif *kif,
7163     int rtableid)
7164 {
7165 	struct ifnet		*ifp;
7166 
7167 	/*
7168 	 * Skip check for addresses with embedded interface scope,
7169 	 * as they would always match anyway.
7170 	 */
7171 	if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
7172 		return (1);
7173 
7174 	if (af != AF_INET && af != AF_INET6)
7175 		return (0);
7176 
7177 	if (kif == V_pfi_all)
7178 		return (1);
7179 
7180 	/* Skip checks for ipsec interfaces */
7181 	if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
7182 		return (1);
7183 
7184 	ifp = (kif != NULL) ? kif->pfik_ifp : NULL;
7185 
7186 	switch (af) {
7187 #ifdef INET6
7188 	case AF_INET6:
7189 		return (fib6_check_urpf(rtableid, &addr->v6, 0, NHR_NONE,
7190 		    ifp));
7191 #endif
7192 #ifdef INET
7193 	case AF_INET:
7194 		return (fib4_check_urpf(rtableid, addr->v4, 0, NHR_NONE,
7195 		    ifp));
7196 #endif
7197 	}
7198 
7199 	return (0);
7200 }
7201 
7202 #ifdef INET
7203 static void
7204 pf_route(struct mbuf **m, struct pf_krule *r, struct ifnet *oifp,
7205     struct pf_kstate *s, struct pf_pdesc *pd, struct inpcb *inp)
7206 {
7207 	struct mbuf		*m0, *m1, *md;
7208 	struct sockaddr_in	dst;
7209 	struct ip		*ip;
7210 	struct pfi_kkif		*nkif = NULL;
7211 	struct ifnet		*ifp = NULL;
7212 	struct pf_addr		 naddr;
7213 	struct pf_ksrc_node	*sn = NULL;
7214 	int			 error = 0;
7215 	uint16_t		 ip_len, ip_off;
7216 	int			 r_rt, r_dir;
7217 
7218 	KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
7219 
7220 	if (s) {
7221 		r_rt = s->rt;
7222 		r_dir = s->direction;
7223 	} else {
7224 		r_rt = r->rt;
7225 		r_dir = r->direction;
7226 	}
7227 
7228 	KASSERT(pd->dir == PF_IN || pd->dir == PF_OUT ||
7229 	    r_dir == PF_IN || r_dir == PF_OUT, ("%s: invalid direction",
7230 	    __func__));
7231 
7232 	if ((pd->pf_mtag == NULL &&
7233 	    ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
7234 	    pd->pf_mtag->routed++ > 3) {
7235 		m0 = *m;
7236 		*m = NULL;
7237 		goto bad_locked;
7238 	}
7239 
7240 	if (r_rt == PF_DUPTO) {
7241 		if ((pd->pf_mtag->flags & PF_MTAG_FLAG_DUPLICATED)) {
7242 			if (s == NULL) {
7243 				ifp = r->rpool.cur->kif ?
7244 				    r->rpool.cur->kif->pfik_ifp : NULL;
7245 			} else {
7246 				ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
7247 				/* If pfsync'd */
7248 				if (ifp == NULL && r->rpool.cur != NULL)
7249 					ifp = r->rpool.cur->kif ?
7250 					    r->rpool.cur->kif->pfik_ifp : NULL;
7251 				PF_STATE_UNLOCK(s);
7252 			}
7253 			if (ifp == oifp) {
7254 				/* When the 2nd interface is not skipped */
7255 				return;
7256 			} else {
7257 				m0 = *m;
7258 				*m = NULL;
7259 				goto bad;
7260 			}
7261 		} else {
7262 			pd->pf_mtag->flags |= PF_MTAG_FLAG_DUPLICATED;
7263 			if (((m0 = m_dup(*m, M_NOWAIT)) == NULL)) {
7264 				if (s)
7265 					PF_STATE_UNLOCK(s);
7266 				return;
7267 			}
7268 		}
7269 	} else {
7270 		if ((r_rt == PF_REPLYTO) == (r_dir == pd->dir)) {
7271 			pf_dummynet(pd, s, r, m);
7272 			if (s)
7273 				PF_STATE_UNLOCK(s);
7274 			return;
7275 		}
7276 		m0 = *m;
7277 	}
7278 
7279 	ip = mtod(m0, struct ip *);
7280 
7281 	bzero(&dst, sizeof(dst));
7282 	dst.sin_family = AF_INET;
7283 	dst.sin_len = sizeof(dst);
7284 	dst.sin_addr = ip->ip_dst;
7285 
7286 	bzero(&naddr, sizeof(naddr));
7287 
7288 	if (s == NULL) {
7289 		if (TAILQ_EMPTY(&r->rpool.list)) {
7290 			DPFPRINTF(PF_DEBUG_URGENT,
7291 			    ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
7292 			goto bad_locked;
7293 		}
7294 		pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
7295 		    &naddr, &nkif, NULL, &sn);
7296 		if (!PF_AZERO(&naddr, AF_INET))
7297 			dst.sin_addr.s_addr = naddr.v4.s_addr;
7298 		ifp = nkif ? nkif->pfik_ifp : NULL;
7299 	} else {
7300 		if (!PF_AZERO(&s->rt_addr, AF_INET))
7301 			dst.sin_addr.s_addr =
7302 			    s->rt_addr.v4.s_addr;
7303 		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
7304 		/* If pfsync'd */
7305 		if (ifp == NULL && r->rpool.cur != NULL) {
7306 			ifp = r->rpool.cur->kif ?
7307 			    r->rpool.cur->kif->pfik_ifp : NULL;
7308 		}
7309 		PF_STATE_UNLOCK(s);
7310 	}
7311 
7312 	if (ifp == NULL)
7313 		goto bad;
7314 
7315 	if (pd->dir == PF_IN) {
7316 		if (pf_test(PF_OUT, 0, ifp, &m0, inp, &pd->act) != PF_PASS)
7317 			goto bad;
7318 		else if (m0 == NULL)
7319 			goto done;
7320 		if (m0->m_len < sizeof(struct ip)) {
7321 			DPFPRINTF(PF_DEBUG_URGENT,
7322 			    ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
7323 			goto bad;
7324 		}
7325 		ip = mtod(m0, struct ip *);
7326 	}
7327 
7328 	if (ifp->if_flags & IFF_LOOPBACK)
7329 		m0->m_flags |= M_SKIP_FIREWALL;
7330 
7331 	ip_len = ntohs(ip->ip_len);
7332 	ip_off = ntohs(ip->ip_off);
7333 
7334 	/* Copied from FreeBSD 10.0-CURRENT ip_output. */
7335 	m0->m_pkthdr.csum_flags |= CSUM_IP;
7336 	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
7337 		in_delayed_cksum(m0);
7338 		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
7339 	}
7340 	if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
7341 		pf_sctp_checksum(m0, (uint32_t)(ip->ip_hl << 2));
7342 		m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
7343 	}
7344 
7345 	/*
7346 	 * If small enough for interface, or the interface will take
7347 	 * care of the fragmentation for us, we can just send directly.
7348 	 */
7349 	if (ip_len <= ifp->if_mtu ||
7350 	    (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
7351 		ip->ip_sum = 0;
7352 		if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
7353 			ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
7354 			m0->m_pkthdr.csum_flags &= ~CSUM_IP;
7355 		}
7356 		m_clrprotoflags(m0);	/* Avoid confusing lower layers. */
7357 
7358 		md = m0;
7359 		error = pf_dummynet_route(pd, s, r, ifp, sintosa(&dst), &md);
7360 		if (md != NULL)
7361 			error = (*ifp->if_output)(ifp, md, sintosa(&dst), NULL);
7362 		goto done;
7363 	}
7364 
7365 	/* Balk when DF bit is set or the interface didn't support TSO. */
7366 	if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
7367 		error = EMSGSIZE;
7368 		KMOD_IPSTAT_INC(ips_cantfrag);
7369 		if (r_rt != PF_DUPTO) {
7370 			if (s && pd->nat_rule != NULL)
7371 				PACKET_UNDO_NAT(m0, pd,
7372 				    (ip->ip_hl << 2) + (ip_off & IP_OFFMASK),
7373 				    s);
7374 
7375 			icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
7376 			    ifp->if_mtu);
7377 			goto done;
7378 		} else
7379 			goto bad;
7380 	}
7381 
7382 	error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
7383 	if (error)
7384 		goto bad;
7385 
7386 	for (; m0; m0 = m1) {
7387 		m1 = m0->m_nextpkt;
7388 		m0->m_nextpkt = NULL;
7389 		if (error == 0) {
7390 			m_clrprotoflags(m0);
7391 			md = m0;
7392 			error = pf_dummynet_route(pd, s, r, ifp,
7393 			    sintosa(&dst), &md);
7394 			if (md != NULL)
7395 				error = (*ifp->if_output)(ifp, md,
7396 				    sintosa(&dst), NULL);
7397 		} else
7398 			m_freem(m0);
7399 	}
7400 
7401 	if (error == 0)
7402 		KMOD_IPSTAT_INC(ips_fragmented);
7403 
7404 done:
7405 	if (r_rt != PF_DUPTO)
7406 		*m = NULL;
7407 	return;
7408 
7409 bad_locked:
7410 	if (s)
7411 		PF_STATE_UNLOCK(s);
7412 bad:
7413 	m_freem(m0);
7414 	goto done;
7415 }
7416 #endif /* INET */
7417 
7418 #ifdef INET6
7419 static void
7420 pf_route6(struct mbuf **m, struct pf_krule *r, struct ifnet *oifp,
7421     struct pf_kstate *s, struct pf_pdesc *pd, struct inpcb *inp)
7422 {
7423 	struct mbuf		*m0, *md;
7424 	struct sockaddr_in6	dst;
7425 	struct ip6_hdr		*ip6;
7426 	struct pfi_kkif		*nkif = NULL;
7427 	struct ifnet		*ifp = NULL;
7428 	struct pf_addr		 naddr;
7429 	struct pf_ksrc_node	*sn = NULL;
7430 	int			 r_rt, r_dir;
7431 
7432 	KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
7433 
7434 	if (s) {
7435 		r_rt = s->rt;
7436 		r_dir = s->direction;
7437 	} else {
7438 		r_rt = r->rt;
7439 		r_dir = r->direction;
7440 	}
7441 
7442 	KASSERT(pd->dir == PF_IN || pd->dir == PF_OUT ||
7443 	    r_dir == PF_IN || r_dir == PF_OUT, ("%s: invalid direction",
7444 	    __func__));
7445 
7446 	if ((pd->pf_mtag == NULL &&
7447 	    ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
7448 	    pd->pf_mtag->routed++ > 3) {
7449 		m0 = *m;
7450 		*m = NULL;
7451 		goto bad_locked;
7452 	}
7453 
7454 	if (r_rt == PF_DUPTO) {
7455 		if ((pd->pf_mtag->flags & PF_MTAG_FLAG_DUPLICATED)) {
7456 			if (s == NULL) {
7457 				ifp = r->rpool.cur->kif ?
7458 				    r->rpool.cur->kif->pfik_ifp : NULL;
7459 			} else {
7460 				ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
7461 				/* If pfsync'd */
7462 				if (ifp == NULL && r->rpool.cur != NULL)
7463 					ifp = r->rpool.cur->kif ?
7464 					    r->rpool.cur->kif->pfik_ifp : NULL;
7465 				PF_STATE_UNLOCK(s);
7466 			}
7467 			if (ifp == oifp) {
7468 				/* When the 2nd interface is not skipped */
7469 				return;
7470 			} else {
7471 				m0 = *m;
7472 				*m = NULL;
7473 				goto bad;
7474 			}
7475 		} else {
7476 			pd->pf_mtag->flags |= PF_MTAG_FLAG_DUPLICATED;
7477 			if (((m0 = m_dup(*m, M_NOWAIT)) == NULL)) {
7478 				if (s)
7479 					PF_STATE_UNLOCK(s);
7480 				return;
7481 			}
7482 		}
7483 	} else {
7484 		if ((r_rt == PF_REPLYTO) == (r_dir == pd->dir)) {
7485 			pf_dummynet(pd, s, r, m);
7486 			if (s)
7487 				PF_STATE_UNLOCK(s);
7488 			return;
7489 		}
7490 		m0 = *m;
7491 	}
7492 
7493 	ip6 = mtod(m0, struct ip6_hdr *);
7494 
7495 	bzero(&dst, sizeof(dst));
7496 	dst.sin6_family = AF_INET6;
7497 	dst.sin6_len = sizeof(dst);
7498 	dst.sin6_addr = ip6->ip6_dst;
7499 
7500 	bzero(&naddr, sizeof(naddr));
7501 
7502 	if (s == NULL) {
7503 		if (TAILQ_EMPTY(&r->rpool.list)) {
7504 			DPFPRINTF(PF_DEBUG_URGENT,
7505 			    ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
7506 			goto bad_locked;
7507 		}
7508 		pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
7509 		    &naddr, &nkif, NULL, &sn);
7510 		if (!PF_AZERO(&naddr, AF_INET6))
7511 			PF_ACPY((struct pf_addr *)&dst.sin6_addr,
7512 			    &naddr, AF_INET6);
7513 		ifp = nkif ? nkif->pfik_ifp : NULL;
7514 	} else {
7515 		if (!PF_AZERO(&s->rt_addr, AF_INET6))
7516 			PF_ACPY((struct pf_addr *)&dst.sin6_addr,
7517 			    &s->rt_addr, AF_INET6);
7518 		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
7519 		/* If pfsync'd */
7520 		if (ifp == NULL && r->rpool.cur != NULL)
7521 			ifp = r->rpool.cur->kif ?
7522 			    r->rpool.cur->kif->pfik_ifp : NULL;
7523 	}
7524 
7525 	if (s)
7526 		PF_STATE_UNLOCK(s);
7527 
7528 	if (ifp == NULL)
7529 		goto bad;
7530 
7531 	if (pd->dir == PF_IN) {
7532 		if (pf_test6(PF_OUT, 0, ifp, &m0, inp, &pd->act) != PF_PASS)
7533 			goto bad;
7534 		else if (m0 == NULL)
7535 			goto done;
7536 		if (m0->m_len < sizeof(struct ip6_hdr)) {
7537 			DPFPRINTF(PF_DEBUG_URGENT,
7538 			    ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
7539 			    __func__));
7540 			goto bad;
7541 		}
7542 		ip6 = mtod(m0, struct ip6_hdr *);
7543 	}
7544 
7545 	if (ifp->if_flags & IFF_LOOPBACK)
7546 		m0->m_flags |= M_SKIP_FIREWALL;
7547 
7548 	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
7549 	    ~ifp->if_hwassist) {
7550 		uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
7551 		in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
7552 		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
7553 	}
7554 
7555 	/*
7556 	 * If the packet is too large for the outgoing interface,
7557 	 * send back an icmp6 error.
7558 	 */
7559 	if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
7560 		dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
7561 	if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu) {
7562 		md = m0;
7563 		pf_dummynet_route(pd, s, r, ifp, sintosa(&dst), &md);
7564 		if (md != NULL)
7565 			nd6_output_ifp(ifp, ifp, md, &dst, NULL);
7566 	}
7567 	else {
7568 		in6_ifstat_inc(ifp, ifs6_in_toobig);
7569 		if (r_rt != PF_DUPTO) {
7570 			if (s && pd->nat_rule != NULL)
7571 				PACKET_UNDO_NAT(m0, pd,
7572 				    ((caddr_t)ip6 - m0->m_data) +
7573 				    sizeof(struct ip6_hdr), s);
7574 
7575 			icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
7576 		} else
7577 			goto bad;
7578 	}
7579 
7580 done:
7581 	if (r_rt != PF_DUPTO)
7582 		*m = NULL;
7583 	return;
7584 
7585 bad_locked:
7586 	if (s)
7587 		PF_STATE_UNLOCK(s);
7588 bad:
7589 	m_freem(m0);
7590 	goto done;
7591 }
7592 #endif /* INET6 */
7593 
7594 /*
7595  * FreeBSD supports cksum offloads for the following drivers.
7596  *  em(4), fxp(4), lge(4), nge(4), re(4), ti(4), txp(4), xl(4)
7597  *
7598  * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
7599  *  network driver performed cksum including pseudo header, need to verify
7600  *   csum_data
7601  * CSUM_DATA_VALID :
7602  *  network driver performed cksum, needs to additional pseudo header
7603  *  cksum computation with partial csum_data(i.e. lack of H/W support for
7604  *  pseudo header, for instance sk(4) and possibly gem(4))
7605  *
7606  * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
7607  * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
7608  * TCP/UDP layer.
7609  * Also, set csum_data to 0xffff to force cksum validation.
7610  */
7611 static int
7612 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
7613 {
7614 	u_int16_t sum = 0;
7615 	int hw_assist = 0;
7616 	struct ip *ip;
7617 
7618 	if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
7619 		return (1);
7620 	if (m->m_pkthdr.len < off + len)
7621 		return (1);
7622 
7623 	switch (p) {
7624 	case IPPROTO_TCP:
7625 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
7626 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
7627 				sum = m->m_pkthdr.csum_data;
7628 			} else {
7629 				ip = mtod(m, struct ip *);
7630 				sum = in_pseudo(ip->ip_src.s_addr,
7631 				ip->ip_dst.s_addr, htonl((u_short)len +
7632 				m->m_pkthdr.csum_data + IPPROTO_TCP));
7633 			}
7634 			sum ^= 0xffff;
7635 			++hw_assist;
7636 		}
7637 		break;
7638 	case IPPROTO_UDP:
7639 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
7640 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
7641 				sum = m->m_pkthdr.csum_data;
7642 			} else {
7643 				ip = mtod(m, struct ip *);
7644 				sum = in_pseudo(ip->ip_src.s_addr,
7645 				ip->ip_dst.s_addr, htonl((u_short)len +
7646 				m->m_pkthdr.csum_data + IPPROTO_UDP));
7647 			}
7648 			sum ^= 0xffff;
7649 			++hw_assist;
7650 		}
7651 		break;
7652 	case IPPROTO_ICMP:
7653 #ifdef INET6
7654 	case IPPROTO_ICMPV6:
7655 #endif /* INET6 */
7656 		break;
7657 	default:
7658 		return (1);
7659 	}
7660 
7661 	if (!hw_assist) {
7662 		switch (af) {
7663 		case AF_INET:
7664 			if (p == IPPROTO_ICMP) {
7665 				if (m->m_len < off)
7666 					return (1);
7667 				m->m_data += off;
7668 				m->m_len -= off;
7669 				sum = in_cksum(m, len);
7670 				m->m_data -= off;
7671 				m->m_len += off;
7672 			} else {
7673 				if (m->m_len < sizeof(struct ip))
7674 					return (1);
7675 				sum = in4_cksum(m, p, off, len);
7676 			}
7677 			break;
7678 #ifdef INET6
7679 		case AF_INET6:
7680 			if (m->m_len < sizeof(struct ip6_hdr))
7681 				return (1);
7682 			sum = in6_cksum(m, p, off, len);
7683 			break;
7684 #endif /* INET6 */
7685 		default:
7686 			return (1);
7687 		}
7688 	}
7689 	if (sum) {
7690 		switch (p) {
7691 		case IPPROTO_TCP:
7692 		    {
7693 			KMOD_TCPSTAT_INC(tcps_rcvbadsum);
7694 			break;
7695 		    }
7696 		case IPPROTO_UDP:
7697 		    {
7698 			KMOD_UDPSTAT_INC(udps_badsum);
7699 			break;
7700 		    }
7701 #ifdef INET
7702 		case IPPROTO_ICMP:
7703 		    {
7704 			KMOD_ICMPSTAT_INC(icps_checksum);
7705 			break;
7706 		    }
7707 #endif
7708 #ifdef INET6
7709 		case IPPROTO_ICMPV6:
7710 		    {
7711 			KMOD_ICMP6STAT_INC(icp6s_checksum);
7712 			break;
7713 		    }
7714 #endif /* INET6 */
7715 		}
7716 		return (1);
7717 	} else {
7718 		if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
7719 			m->m_pkthdr.csum_flags |=
7720 			    (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
7721 			m->m_pkthdr.csum_data = 0xffff;
7722 		}
7723 	}
7724 	return (0);
7725 }
7726 
7727 static bool
7728 pf_pdesc_to_dnflow(const struct pf_pdesc *pd, const struct pf_krule *r,
7729     const struct pf_kstate *s, struct ip_fw_args *dnflow)
7730 {
7731 	int dndir = r->direction;
7732 
7733 	if (s && dndir == PF_INOUT) {
7734 		dndir = s->direction;
7735 	} else if (dndir == PF_INOUT) {
7736 		/* Assume primary direction. Happens when we've set dnpipe in
7737 		 * the ethernet level code. */
7738 		dndir = pd->dir;
7739 	}
7740 
7741 	memset(dnflow, 0, sizeof(*dnflow));
7742 
7743 	if (pd->dport != NULL)
7744 		dnflow->f_id.dst_port = ntohs(*pd->dport);
7745 	if (pd->sport != NULL)
7746 		dnflow->f_id.src_port = ntohs(*pd->sport);
7747 
7748 	if (pd->dir == PF_IN)
7749 		dnflow->flags |= IPFW_ARGS_IN;
7750 	else
7751 		dnflow->flags |= IPFW_ARGS_OUT;
7752 
7753 	if (pd->dir != dndir && pd->act.dnrpipe) {
7754 		dnflow->rule.info = pd->act.dnrpipe;
7755 	}
7756 	else if (pd->dir == dndir && pd->act.dnpipe) {
7757 		dnflow->rule.info = pd->act.dnpipe;
7758 	}
7759 	else {
7760 		return (false);
7761 	}
7762 
7763 	dnflow->rule.info |= IPFW_IS_DUMMYNET;
7764 	if (r->free_flags & PFRULE_DN_IS_PIPE || pd->act.flags & PFSTATE_DN_IS_PIPE)
7765 		dnflow->rule.info |= IPFW_IS_PIPE;
7766 
7767 	dnflow->f_id.proto = pd->proto;
7768 	dnflow->f_id.extra = dnflow->rule.info;
7769 	switch (pd->af) {
7770 	case AF_INET:
7771 		dnflow->f_id.addr_type = 4;
7772 		dnflow->f_id.src_ip = ntohl(pd->src->v4.s_addr);
7773 		dnflow->f_id.dst_ip = ntohl(pd->dst->v4.s_addr);
7774 		break;
7775 	case AF_INET6:
7776 		dnflow->flags |= IPFW_ARGS_IP6;
7777 		dnflow->f_id.addr_type = 6;
7778 		dnflow->f_id.src_ip6 = pd->src->v6;
7779 		dnflow->f_id.dst_ip6 = pd->dst->v6;
7780 		break;
7781 	default:
7782 		panic("Invalid AF");
7783 		break;
7784 	}
7785 
7786 	return (true);
7787 }
7788 
7789 int
7790 pf_test_eth(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0,
7791     struct inpcb *inp)
7792 {
7793 	struct pfi_kkif		*kif;
7794 	struct mbuf		*m = *m0;
7795 
7796 	M_ASSERTPKTHDR(m);
7797 	MPASS(ifp->if_vnet == curvnet);
7798 	NET_EPOCH_ASSERT();
7799 
7800 	if (!V_pf_status.running)
7801 		return (PF_PASS);
7802 
7803 	kif = (struct pfi_kkif *)ifp->if_pf_kif;
7804 
7805 	if (kif == NULL) {
7806 		DPFPRINTF(PF_DEBUG_URGENT,
7807 		    ("%s: kif == NULL, if_xname %s\n", __func__, ifp->if_xname));
7808 		return (PF_DROP);
7809 	}
7810 	if (kif->pfik_flags & PFI_IFLAG_SKIP)
7811 		return (PF_PASS);
7812 
7813 	if (m->m_flags & M_SKIP_FIREWALL)
7814 		return (PF_PASS);
7815 
7816 	/* Stateless! */
7817 	return (pf_test_eth_rule(dir, kif, m0));
7818 }
7819 
7820 static __inline void
7821 pf_dummynet_flag_remove(struct mbuf *m, struct pf_mtag *pf_mtag)
7822 {
7823 	struct m_tag *mtag;
7824 
7825 	pf_mtag->flags &= ~PF_MTAG_FLAG_DUMMYNET;
7826 
7827 	/* dummynet adds this tag, but pf does not need it,
7828 	 * and keeping it creates unexpected behavior,
7829 	 * e.g. in case of divert(4) usage right after dummynet. */
7830 	mtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL);
7831 	if (mtag != NULL)
7832 		m_tag_delete(m, mtag);
7833 }
7834 
7835 static int
7836 pf_dummynet(struct pf_pdesc *pd, struct pf_kstate *s,
7837     struct pf_krule *r, struct mbuf **m0)
7838 {
7839 	return (pf_dummynet_route(pd, s, r, NULL, NULL, m0));
7840 }
7841 
7842 static int
7843 pf_dummynet_route(struct pf_pdesc *pd, struct pf_kstate *s,
7844     struct pf_krule *r, struct ifnet *ifp, struct sockaddr *sa,
7845     struct mbuf **m0)
7846 {
7847 	NET_EPOCH_ASSERT();
7848 
7849 	if (pd->act.dnpipe || pd->act.dnrpipe) {
7850 		struct ip_fw_args dnflow;
7851 		if (ip_dn_io_ptr == NULL) {
7852 			m_freem(*m0);
7853 			*m0 = NULL;
7854 			return (ENOMEM);
7855 		}
7856 
7857 		if (pd->pf_mtag == NULL &&
7858 		    ((pd->pf_mtag = pf_get_mtag(*m0)) == NULL)) {
7859 			m_freem(*m0);
7860 			*m0 = NULL;
7861 			return (ENOMEM);
7862 		}
7863 
7864 		if (ifp != NULL) {
7865 			pd->pf_mtag->flags |= PF_MTAG_FLAG_ROUTE_TO;
7866 
7867 			pd->pf_mtag->if_index = ifp->if_index;
7868 			pd->pf_mtag->if_idxgen = ifp->if_idxgen;
7869 
7870 			MPASS(sa != NULL);
7871 
7872 			if (pd->af == AF_INET)
7873 				memcpy(&pd->pf_mtag->dst, sa,
7874 				    sizeof(struct sockaddr_in));
7875 			else
7876 				memcpy(&pd->pf_mtag->dst, sa,
7877 				    sizeof(struct sockaddr_in6));
7878 		}
7879 
7880 		if (pf_pdesc_to_dnflow(pd, r, s, &dnflow)) {
7881 			pd->pf_mtag->flags |= PF_MTAG_FLAG_DUMMYNET;
7882 			ip_dn_io_ptr(m0, &dnflow);
7883 			if (*m0 != NULL) {
7884 				pd->pf_mtag->flags &= ~PF_MTAG_FLAG_ROUTE_TO;
7885 				pf_dummynet_flag_remove(*m0, pd->pf_mtag);
7886 			}
7887 		}
7888 	}
7889 
7890 	return (0);
7891 }
7892 
7893 #ifdef INET
7894 int
7895 pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0,
7896     struct inpcb *inp, struct pf_rule_actions *default_actions)
7897 {
7898 	struct pfi_kkif		*kif;
7899 	u_short			 action, reason = 0;
7900 	struct mbuf		*m = *m0;
7901 	struct ip		*h = NULL;
7902 	struct m_tag		*mtag;
7903 	struct pf_krule		*a = NULL, *r = &V_pf_default_rule, *tr, *nr;
7904 	struct pf_kstate	*s = NULL;
7905 	struct pf_kruleset	*ruleset = NULL;
7906 	struct pf_pdesc		 pd;
7907 	int			 off, dirndx, use_2nd_queue = 0;
7908 	uint16_t		 tag;
7909 	uint8_t			 rt;
7910 
7911 	PF_RULES_RLOCK_TRACKER;
7912 	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: bad direction %d\n", __func__, dir));
7913 	M_ASSERTPKTHDR(m);
7914 
7915 	if (!V_pf_status.running)
7916 		return (PF_PASS);
7917 
7918 	PF_RULES_RLOCK();
7919 
7920 	kif = (struct pfi_kkif *)ifp->if_pf_kif;
7921 
7922 	if (__predict_false(kif == NULL)) {
7923 		DPFPRINTF(PF_DEBUG_URGENT,
7924 		    ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
7925 		PF_RULES_RUNLOCK();
7926 		return (PF_DROP);
7927 	}
7928 	if (kif->pfik_flags & PFI_IFLAG_SKIP) {
7929 		PF_RULES_RUNLOCK();
7930 		return (PF_PASS);
7931 	}
7932 
7933 	if (m->m_flags & M_SKIP_FIREWALL) {
7934 		PF_RULES_RUNLOCK();
7935 		return (PF_PASS);
7936 	}
7937 
7938 	memset(&pd, 0, sizeof(pd));
7939 	TAILQ_INIT(&pd.sctp_multihome_jobs);
7940 	if (default_actions != NULL)
7941 		memcpy(&pd.act, default_actions, sizeof(pd.act));
7942 	pd.pf_mtag = pf_find_mtag(m);
7943 
7944 	if (pd.pf_mtag != NULL && (pd.pf_mtag->flags & PF_MTAG_FLAG_ROUTE_TO)) {
7945 		pd.pf_mtag->flags &= ~PF_MTAG_FLAG_ROUTE_TO;
7946 
7947 		ifp = ifnet_byindexgen(pd.pf_mtag->if_index,
7948 		    pd.pf_mtag->if_idxgen);
7949 		if (ifp == NULL || ifp->if_flags & IFF_DYING) {
7950 			PF_RULES_RUNLOCK();
7951 			m_freem(*m0);
7952 			*m0 = NULL;
7953 			return (PF_PASS);
7954 		}
7955 		PF_RULES_RUNLOCK();
7956 		(ifp->if_output)(ifp, m, sintosa(&pd.pf_mtag->dst), NULL);
7957 		*m0 = NULL;
7958 		return (PF_PASS);
7959 	}
7960 
7961 	if (pd.pf_mtag && pd.pf_mtag->dnpipe) {
7962 		pd.act.dnpipe = pd.pf_mtag->dnpipe;
7963 		pd.act.flags = pd.pf_mtag->dnflags;
7964 	}
7965 
7966 	if (ip_dn_io_ptr != NULL && pd.pf_mtag != NULL &&
7967 	    pd.pf_mtag->flags & PF_MTAG_FLAG_DUMMYNET) {
7968 		/* Dummynet re-injects packets after they've
7969 		 * completed their delay. We've already
7970 		 * processed them, so pass unconditionally. */
7971 
7972 		/* But only once. We may see the packet multiple times (e.g.
7973 		 * PFIL_IN/PFIL_OUT). */
7974 		pf_dummynet_flag_remove(m, pd.pf_mtag);
7975 		PF_RULES_RUNLOCK();
7976 
7977 		return (PF_PASS);
7978 	}
7979 
7980 	pd.sport = pd.dport = NULL;
7981 	pd.proto_sum = NULL;
7982 	pd.dir = dir;
7983 	pd.sidx = (dir == PF_IN) ? 0 : 1;
7984 	pd.didx = (dir == PF_IN) ? 1 : 0;
7985 	pd.af = AF_INET;
7986 	pd.act.rtableid = -1;
7987 
7988 	h = mtod(m, struct ip *);
7989 	off = h->ip_hl << 2;
7990 
7991 	if (__predict_false(ip_divert_ptr != NULL) &&
7992 	    ((mtag = m_tag_locate(m, MTAG_PF_DIVERT, 0, NULL)) != NULL)) {
7993 		struct pf_divert_mtag *dt = (struct pf_divert_mtag *)(mtag+1);
7994 		if ((dt->idir == PF_DIVERT_MTAG_DIR_IN && dir == PF_IN) ||
7995 		    (dt->idir == PF_DIVERT_MTAG_DIR_OUT && dir == PF_OUT)) {
7996 			if (pd.pf_mtag == NULL &&
7997 			    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
7998 				action = PF_DROP;
7999 				goto done;
8000 			}
8001 			pd.pf_mtag->flags |= PF_MTAG_FLAG_PACKET_LOOPED;
8002 		}
8003 		if (pd.pf_mtag && pd.pf_mtag->flags & PF_MTAG_FLAG_FASTFWD_OURS_PRESENT) {
8004 			m->m_flags |= M_FASTFWD_OURS;
8005 			pd.pf_mtag->flags &= ~PF_MTAG_FLAG_FASTFWD_OURS_PRESENT;
8006 		}
8007 		m_tag_delete(m, mtag);
8008 
8009 		mtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL);
8010 		if (mtag != NULL)
8011 			m_tag_delete(m, mtag);
8012 	} else if (pf_normalize_ip(m0, kif, &reason, &pd) != PF_PASS) {
8013 		/* We do IP header normalization and packet reassembly here */
8014 		action = PF_DROP;
8015 		goto done;
8016 	}
8017 	m = *m0;	/* pf_normalize messes with m0 */
8018 	h = mtod(m, struct ip *);
8019 
8020 	off = h->ip_hl << 2;
8021 	if (off < (int)sizeof(struct ip)) {
8022 		action = PF_DROP;
8023 		REASON_SET(&reason, PFRES_SHORT);
8024 		pd.act.log = PF_LOG_FORCE;
8025 		goto done;
8026 	}
8027 
8028 	pd.src = (struct pf_addr *)&h->ip_src;
8029 	pd.dst = (struct pf_addr *)&h->ip_dst;
8030 	pd.ip_sum = &h->ip_sum;
8031 	pd.proto = h->ip_p;
8032 	pd.tos = h->ip_tos & ~IPTOS_ECN_MASK;
8033 	pd.tot_len = ntohs(h->ip_len);
8034 
8035 	/* handle fragments that didn't get reassembled by normalization */
8036 	if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
8037 		action = pf_test_fragment(&r, kif, m, h, &pd, &a, &ruleset);
8038 		goto done;
8039 	}
8040 
8041 	switch (h->ip_p) {
8042 	case IPPROTO_TCP: {
8043 		if (!pf_pull_hdr(m, off, &pd.hdr.tcp, sizeof(pd.hdr.tcp),
8044 		    &action, &reason, AF_INET)) {
8045 			if (action != PF_PASS)
8046 				pd.act.log = PF_LOG_FORCE;
8047 			goto done;
8048 		}
8049 		pd.p_len = pd.tot_len - off - (pd.hdr.tcp.th_off << 2);
8050 
8051 		pd.sport = &pd.hdr.tcp.th_sport;
8052 		pd.dport = &pd.hdr.tcp.th_dport;
8053 
8054 		/* Respond to SYN with a syncookie. */
8055 		if ((pd.hdr.tcp.th_flags & (TH_SYN|TH_ACK|TH_RST)) == TH_SYN &&
8056 		    pd.dir == PF_IN && pf_synflood_check(&pd)) {
8057 			pf_syncookie_send(m, off, &pd);
8058 			action = PF_DROP;
8059 			break;
8060 		}
8061 
8062 		if ((pd.hdr.tcp.th_flags & TH_ACK) && pd.p_len == 0)
8063 			use_2nd_queue = 1;
8064 		action = pf_normalize_tcp(kif, m, 0, off, h, &pd);
8065 		if (action == PF_DROP)
8066 			goto done;
8067 		action = pf_test_state_tcp(&s, kif, m, off, h, &pd, &reason);
8068 		if (action == PF_PASS) {
8069 			if (V_pfsync_update_state_ptr != NULL)
8070 				V_pfsync_update_state_ptr(s);
8071 			r = s->rule.ptr;
8072 			a = s->anchor.ptr;
8073 		} else if (s == NULL) {
8074 			/* Validate remote SYN|ACK, re-create original SYN if
8075 			 * valid. */
8076 			if ((pd.hdr.tcp.th_flags & (TH_SYN|TH_ACK|TH_RST)) ==
8077 			    TH_ACK && pf_syncookie_validate(&pd) &&
8078 			    pd.dir == PF_IN) {
8079 				struct mbuf *msyn;
8080 
8081 				msyn = pf_syncookie_recreate_syn(h->ip_ttl, off,
8082 				    &pd);
8083 				if (msyn == NULL) {
8084 					action = PF_DROP;
8085 					break;
8086 				}
8087 
8088 				action = pf_test(dir, pflags, ifp, &msyn, inp,
8089 				    &pd.act);
8090 				m_freem(msyn);
8091 				if (action != PF_PASS)
8092 					break;
8093 
8094 				action = pf_test_state_tcp(&s, kif, m, off, h,
8095 				    &pd, &reason);
8096 				if (action != PF_PASS || s == NULL) {
8097 					action = PF_DROP;
8098 					break;
8099 				}
8100 
8101 				s->src.seqhi = ntohl(pd.hdr.tcp.th_ack) - 1;
8102 				s->src.seqlo = ntohl(pd.hdr.tcp.th_seq) - 1;
8103 				pf_set_protostate(s, PF_PEER_SRC, PF_TCPS_PROXY_DST);
8104 				action = pf_synproxy(&pd, &s, &reason);
8105 				break;
8106 			} else {
8107 				action = pf_test_rule(&r, &s, kif, m, off, &pd,
8108 				    &a, &ruleset, inp);
8109 			}
8110 		}
8111 		break;
8112 	}
8113 
8114 	case IPPROTO_UDP: {
8115 		if (!pf_pull_hdr(m, off, &pd.hdr.udp, sizeof(pd.hdr.udp),
8116 		    &action, &reason, AF_INET)) {
8117 			if (action != PF_PASS)
8118 				pd.act.log = PF_LOG_FORCE;
8119 			goto done;
8120 		}
8121 		pd.sport = &pd.hdr.udp.uh_sport;
8122 		pd.dport = &pd.hdr.udp.uh_dport;
8123 		if (pd.hdr.udp.uh_dport == 0 ||
8124 		    ntohs(pd.hdr.udp.uh_ulen) > m->m_pkthdr.len - off ||
8125 		    ntohs(pd.hdr.udp.uh_ulen) < sizeof(struct udphdr)) {
8126 			action = PF_DROP;
8127 			REASON_SET(&reason, PFRES_SHORT);
8128 			goto done;
8129 		}
8130 		action = pf_test_state_udp(&s, kif, m, off, h, &pd);
8131 		if (action == PF_PASS) {
8132 			if (V_pfsync_update_state_ptr != NULL)
8133 				V_pfsync_update_state_ptr(s);
8134 			r = s->rule.ptr;
8135 			a = s->anchor.ptr;
8136 		} else if (s == NULL)
8137 			action = pf_test_rule(&r, &s, kif, m, off, &pd,
8138 			    &a, &ruleset, inp);
8139 		break;
8140 	}
8141 
8142 	case IPPROTO_SCTP: {
8143 		if (!pf_pull_hdr(m, off, &pd.hdr.sctp, sizeof(pd.hdr.sctp),
8144 		    &action, &reason, AF_INET)) {
8145 			if (action != PF_PASS)
8146 				pd.act.log |= PF_LOG_FORCE;
8147 			goto done;
8148 		}
8149 		pd.p_len = pd.tot_len - off;
8150 
8151 		pd.sport = &pd.hdr.sctp.src_port;
8152 		pd.dport = &pd.hdr.sctp.dest_port;
8153 		if (pd.hdr.sctp.src_port == 0 || pd.hdr.sctp.dest_port == 0) {
8154 			action = PF_DROP;
8155 			REASON_SET(&reason, PFRES_SHORT);
8156 			goto done;
8157 		}
8158 		action = pf_normalize_sctp(dir, kif, m, 0, off, h, &pd);
8159 		if (action == PF_DROP)
8160 			goto done;
8161 		action = pf_test_state_sctp(&s, kif, m, off, h, &pd,
8162 		    &reason);
8163 		if (action == PF_PASS) {
8164 			if (V_pfsync_update_state_ptr != NULL)
8165 				V_pfsync_update_state_ptr(s);
8166 			r = s->rule.ptr;
8167 			a = s->anchor.ptr;
8168 		} else {
8169 			action = pf_test_rule(&r, &s, kif, m, off,
8170 			    &pd, &a, &ruleset, inp);
8171 		}
8172 		break;
8173 	}
8174 
8175 	case IPPROTO_ICMP: {
8176 		if (!pf_pull_hdr(m, off, &pd.hdr.icmp, ICMP_MINLEN,
8177 		    &action, &reason, AF_INET)) {
8178 			if (action != PF_PASS)
8179 				pd.act.log = PF_LOG_FORCE;
8180 			goto done;
8181 		}
8182 		action = pf_test_state_icmp(&s, kif, m, off, h, &pd, &reason);
8183 		if (action == PF_PASS) {
8184 			if (V_pfsync_update_state_ptr != NULL)
8185 				V_pfsync_update_state_ptr(s);
8186 			r = s->rule.ptr;
8187 			a = s->anchor.ptr;
8188 		} else if (s == NULL)
8189 			action = pf_test_rule(&r, &s, kif, m, off, &pd,
8190 			    &a, &ruleset, inp);
8191 		break;
8192 	}
8193 
8194 #ifdef INET6
8195 	case IPPROTO_ICMPV6: {
8196 		action = PF_DROP;
8197 		DPFPRINTF(PF_DEBUG_MISC,
8198 		    ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
8199 		goto done;
8200 	}
8201 #endif
8202 
8203 	default:
8204 		action = pf_test_state_other(&s, kif, m, &pd);
8205 		if (action == PF_PASS) {
8206 			if (V_pfsync_update_state_ptr != NULL)
8207 				V_pfsync_update_state_ptr(s);
8208 			r = s->rule.ptr;
8209 			a = s->anchor.ptr;
8210 		} else if (s == NULL)
8211 			action = pf_test_rule(&r, &s, kif, m, off, &pd,
8212 			    &a, &ruleset, inp);
8213 		break;
8214 	}
8215 
8216 done:
8217 	PF_RULES_RUNLOCK();
8218 	if (action == PF_PASS && h->ip_hl > 5 &&
8219 	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
8220 		action = PF_DROP;
8221 		REASON_SET(&reason, PFRES_IPOPTIONS);
8222 		pd.act.log = PF_LOG_FORCE;
8223 		DPFPRINTF(PF_DEBUG_MISC,
8224 		    ("pf: dropping packet with ip options\n"));
8225 	}
8226 
8227 	if (s) {
8228 		uint8_t log = pd.act.log;
8229 		memcpy(&pd.act, &s->act, sizeof(struct pf_rule_actions));
8230 		pd.act.log |= log;
8231 		tag = s->tag;
8232 		rt = s->rt;
8233 	} else {
8234 		tag = r->tag;
8235 		rt = r->rt;
8236 	}
8237 
8238 	if (tag > 0 && pf_tag_packet(m, &pd, tag)) {
8239 		action = PF_DROP;
8240 		REASON_SET(&reason, PFRES_MEMORY);
8241 	}
8242 
8243 	pf_scrub_ip(&m, &pd);
8244 	if (pd.proto == IPPROTO_TCP && pd.act.max_mss)
8245 		pf_normalize_mss(m, off, &pd);
8246 
8247 	if (pd.act.rtableid >= 0)
8248 		M_SETFIB(m, pd.act.rtableid);
8249 
8250 	if (pd.act.flags & PFSTATE_SETPRIO) {
8251 		if (pd.tos & IPTOS_LOWDELAY)
8252 			use_2nd_queue = 1;
8253 		if (vlan_set_pcp(m, pd.act.set_prio[use_2nd_queue])) {
8254 			action = PF_DROP;
8255 			REASON_SET(&reason, PFRES_MEMORY);
8256 			pd.act.log = PF_LOG_FORCE;
8257 			DPFPRINTF(PF_DEBUG_MISC,
8258 			    ("pf: failed to allocate 802.1q mtag\n"));
8259 		}
8260 	}
8261 
8262 #ifdef ALTQ
8263 	if (action == PF_PASS && pd.act.qid) {
8264 		if (pd.pf_mtag == NULL &&
8265 		    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
8266 			action = PF_DROP;
8267 			REASON_SET(&reason, PFRES_MEMORY);
8268 		} else {
8269 			if (s != NULL)
8270 				pd.pf_mtag->qid_hash = pf_state_hash(s);
8271 			if (use_2nd_queue || (pd.tos & IPTOS_LOWDELAY))
8272 				pd.pf_mtag->qid = pd.act.pqid;
8273 			else
8274 				pd.pf_mtag->qid = pd.act.qid;
8275 			/* Add hints for ecn. */
8276 			pd.pf_mtag->hdr = h;
8277 		}
8278 	}
8279 #endif /* ALTQ */
8280 
8281 	/*
8282 	 * connections redirected to loopback should not match sockets
8283 	 * bound specifically to loopback due to security implications,
8284 	 * see tcp_input() and in_pcblookup_listen().
8285 	 */
8286 	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
8287 	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
8288 	    (s->nat_rule.ptr->action == PF_RDR ||
8289 	    s->nat_rule.ptr->action == PF_BINAT) &&
8290 	    IN_LOOPBACK(ntohl(pd.dst->v4.s_addr)))
8291 		m->m_flags |= M_SKIP_FIREWALL;
8292 
8293 	if (__predict_false(ip_divert_ptr != NULL) && action == PF_PASS &&
8294 	    r->divert.port && !PACKET_LOOPED(&pd)) {
8295 		mtag = m_tag_alloc(MTAG_PF_DIVERT, 0,
8296 		    sizeof(struct pf_divert_mtag), M_NOWAIT | M_ZERO);
8297 		if (mtag != NULL) {
8298 			((struct pf_divert_mtag *)(mtag+1))->port =
8299 			    ntohs(r->divert.port);
8300 			((struct pf_divert_mtag *)(mtag+1))->idir =
8301 			    (dir == PF_IN) ? PF_DIVERT_MTAG_DIR_IN :
8302 			    PF_DIVERT_MTAG_DIR_OUT;
8303 
8304 			if (s)
8305 				PF_STATE_UNLOCK(s);
8306 
8307 			m_tag_prepend(m, mtag);
8308 			if (m->m_flags & M_FASTFWD_OURS) {
8309 				if (pd.pf_mtag == NULL &&
8310 				    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
8311 					action = PF_DROP;
8312 					REASON_SET(&reason, PFRES_MEMORY);
8313 					pd.act.log = PF_LOG_FORCE;
8314 					DPFPRINTF(PF_DEBUG_MISC,
8315 					    ("pf: failed to allocate tag\n"));
8316 				} else {
8317 					pd.pf_mtag->flags |=
8318 					    PF_MTAG_FLAG_FASTFWD_OURS_PRESENT;
8319 					m->m_flags &= ~M_FASTFWD_OURS;
8320 				}
8321 			}
8322 			ip_divert_ptr(*m0, dir == PF_IN);
8323 			*m0 = NULL;
8324 
8325 			return (action);
8326 		} else {
8327 			/* XXX: ipfw has the same behaviour! */
8328 			action = PF_DROP;
8329 			REASON_SET(&reason, PFRES_MEMORY);
8330 			pd.act.log = PF_LOG_FORCE;
8331 			DPFPRINTF(PF_DEBUG_MISC,
8332 			    ("pf: failed to allocate divert tag\n"));
8333 		}
8334 	}
8335 	/* this flag will need revising if the pkt is forwarded */
8336 	if (pd.pf_mtag)
8337 		pd.pf_mtag->flags &= ~PF_MTAG_FLAG_PACKET_LOOPED;
8338 
8339 	if (pd.act.log) {
8340 		struct pf_krule		*lr;
8341 		struct pf_krule_item	*ri;
8342 
8343 		if (s != NULL && s->nat_rule.ptr != NULL &&
8344 		    s->nat_rule.ptr->log & PF_LOG_ALL)
8345 			lr = s->nat_rule.ptr;
8346 		else
8347 			lr = r;
8348 
8349 		if (pd.act.log & PF_LOG_FORCE || lr->log & PF_LOG_ALL)
8350 			PFLOG_PACKET(kif, m, AF_INET, action, reason, lr, a,
8351 			    ruleset, &pd, (s == NULL));
8352 		if (s) {
8353 			SLIST_FOREACH(ri, &s->match_rules, entry)
8354 				if (ri->r->log & PF_LOG_ALL)
8355 					PFLOG_PACKET(kif, m, AF_INET, action,
8356 					    reason, ri->r, a, ruleset, &pd, 0);
8357 		}
8358 	}
8359 
8360 	pf_counter_u64_critical_enter();
8361 	pf_counter_u64_add_protected(&kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS],
8362 	    pd.tot_len);
8363 	pf_counter_u64_add_protected(&kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS],
8364 	    1);
8365 
8366 	if (action == PF_PASS || r->action == PF_DROP) {
8367 		dirndx = (dir == PF_OUT);
8368 		pf_counter_u64_add_protected(&r->packets[dirndx], 1);
8369 		pf_counter_u64_add_protected(&r->bytes[dirndx], pd.tot_len);
8370 		pf_update_timestamp(r);
8371 
8372 		if (a != NULL) {
8373 			pf_counter_u64_add_protected(&a->packets[dirndx], 1);
8374 			pf_counter_u64_add_protected(&a->bytes[dirndx], pd.tot_len);
8375 		}
8376 		if (s != NULL) {
8377 			struct pf_krule_item	*ri;
8378 
8379 			if (s->nat_rule.ptr != NULL) {
8380 				pf_counter_u64_add_protected(&s->nat_rule.ptr->packets[dirndx],
8381 				    1);
8382 				pf_counter_u64_add_protected(&s->nat_rule.ptr->bytes[dirndx],
8383 				    pd.tot_len);
8384 			}
8385 			if (s->src_node != NULL) {
8386 				counter_u64_add(s->src_node->packets[dirndx],
8387 				    1);
8388 				counter_u64_add(s->src_node->bytes[dirndx],
8389 				    pd.tot_len);
8390 			}
8391 			if (s->nat_src_node != NULL) {
8392 				counter_u64_add(s->nat_src_node->packets[dirndx],
8393 				    1);
8394 				counter_u64_add(s->nat_src_node->bytes[dirndx],
8395 				    pd.tot_len);
8396 			}
8397 			dirndx = (dir == s->direction) ? 0 : 1;
8398 			s->packets[dirndx]++;
8399 			s->bytes[dirndx] += pd.tot_len;
8400 			SLIST_FOREACH(ri, &s->match_rules, entry) {
8401 				pf_counter_u64_add_protected(&ri->r->packets[dirndx], 1);
8402 				pf_counter_u64_add_protected(&ri->r->bytes[dirndx], pd.tot_len);
8403 			}
8404 		}
8405 		tr = r;
8406 		nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
8407 		if (nr != NULL && r == &V_pf_default_rule)
8408 			tr = nr;
8409 		if (tr->src.addr.type == PF_ADDR_TABLE)
8410 			pfr_update_stats(tr->src.addr.p.tbl,
8411 			    (s == NULL) ? pd.src :
8412 			    &s->key[(s->direction == PF_IN)]->
8413 				addr[(s->direction == PF_OUT)],
8414 			    pd.af, pd.tot_len, dir == PF_OUT,
8415 			    r->action == PF_PASS, tr->src.neg);
8416 		if (tr->dst.addr.type == PF_ADDR_TABLE)
8417 			pfr_update_stats(tr->dst.addr.p.tbl,
8418 			    (s == NULL) ? pd.dst :
8419 			    &s->key[(s->direction == PF_IN)]->
8420 				addr[(s->direction == PF_IN)],
8421 			    pd.af, pd.tot_len, dir == PF_OUT,
8422 			    r->action == PF_PASS, tr->dst.neg);
8423 	}
8424 	pf_counter_u64_critical_exit();
8425 
8426 	switch (action) {
8427 	case PF_SYNPROXY_DROP:
8428 		m_freem(*m0);
8429 	case PF_DEFER:
8430 		*m0 = NULL;
8431 		action = PF_PASS;
8432 		break;
8433 	case PF_DROP:
8434 		m_freem(*m0);
8435 		*m0 = NULL;
8436 		break;
8437 	default:
8438 		/* pf_route() returns unlocked. */
8439 		if (rt) {
8440 			pf_route(m0, r, kif->pfik_ifp, s, &pd, inp);
8441 			goto out;
8442 		}
8443 		if (pf_dummynet(&pd, s, r, m0) != 0) {
8444 			action = PF_DROP;
8445 			REASON_SET(&reason, PFRES_MEMORY);
8446 		}
8447 		break;
8448 	}
8449 
8450 	SDT_PROBE4(pf, ip, test, done, action, reason, r, s);
8451 
8452 	if (s && action != PF_DROP) {
8453 		if (!s->if_index_in && dir == PF_IN)
8454 			s->if_index_in = ifp->if_index;
8455 		else if (!s->if_index_out && dir == PF_OUT)
8456 			s->if_index_out = ifp->if_index;
8457 	}
8458 
8459 	if (s)
8460 		PF_STATE_UNLOCK(s);
8461 
8462 out:
8463 	pf_sctp_multihome_delayed(&pd, off, kif, s, action);
8464 
8465 	return (action);
8466 }
8467 #endif /* INET */
8468 
8469 #ifdef INET6
8470 int
8471 pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp,
8472     struct pf_rule_actions *default_actions)
8473 {
8474 	struct pfi_kkif		*kif;
8475 	u_short			 action, reason = 0;
8476 	struct mbuf		*m = *m0, *n = NULL;
8477 	struct m_tag		*mtag;
8478 	struct ip6_hdr		*h = NULL;
8479 	struct pf_krule		*a = NULL, *r = &V_pf_default_rule, *tr, *nr;
8480 	struct pf_kstate	*s = NULL;
8481 	struct pf_kruleset	*ruleset = NULL;
8482 	struct pf_pdesc		 pd;
8483 	int			 off, terminal = 0, dirndx, rh_cnt = 0, use_2nd_queue = 0;
8484 	uint16_t		 tag;
8485 	uint8_t			 rt;
8486 
8487 	PF_RULES_RLOCK_TRACKER;
8488 	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: bad direction %d\n", __func__, dir));
8489 	M_ASSERTPKTHDR(m);
8490 
8491 	if (!V_pf_status.running)
8492 		return (PF_PASS);
8493 
8494 	PF_RULES_RLOCK();
8495 
8496 	kif = (struct pfi_kkif *)ifp->if_pf_kif;
8497 	if (__predict_false(kif == NULL)) {
8498 		DPFPRINTF(PF_DEBUG_URGENT,
8499 		    ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
8500 		PF_RULES_RUNLOCK();
8501 		return (PF_DROP);
8502 	}
8503 	if (kif->pfik_flags & PFI_IFLAG_SKIP) {
8504 		PF_RULES_RUNLOCK();
8505 		return (PF_PASS);
8506 	}
8507 
8508 	if (m->m_flags & M_SKIP_FIREWALL) {
8509 		PF_RULES_RUNLOCK();
8510 		return (PF_PASS);
8511 	}
8512 
8513 	/*
8514 	 * If we end up changing IP addresses (e.g. binat) the stack may get
8515 	 * confused and fail to send the icmp6 packet too big error. Just send
8516 	 * it here, before we do any NAT.
8517 	 */
8518 	if (dir == PF_OUT && pflags & PFIL_FWD && IN6_LINKMTU(ifp) < pf_max_frag_size(m)) {
8519 		PF_RULES_RUNLOCK();
8520 		*m0 = NULL;
8521 		icmp6_error(m, ICMP6_PACKET_TOO_BIG, 0, IN6_LINKMTU(ifp));
8522 		return (PF_DROP);
8523 	}
8524 
8525 	memset(&pd, 0, sizeof(pd));
8526 	TAILQ_INIT(&pd.sctp_multihome_jobs);
8527 	if (default_actions != NULL)
8528 		memcpy(&pd.act, default_actions, sizeof(pd.act));
8529 	pd.pf_mtag = pf_find_mtag(m);
8530 
8531 	if (pd.pf_mtag != NULL && (pd.pf_mtag->flags & PF_MTAG_FLAG_ROUTE_TO)) {
8532 		pd.pf_mtag->flags &= ~PF_MTAG_FLAG_ROUTE_TO;
8533 
8534 		ifp = ifnet_byindexgen(pd.pf_mtag->if_index,
8535 		    pd.pf_mtag->if_idxgen);
8536 		if (ifp == NULL || ifp->if_flags & IFF_DYING) {
8537 			PF_RULES_RUNLOCK();
8538 			m_freem(*m0);
8539 			*m0 = NULL;
8540 			return (PF_PASS);
8541 		}
8542 		PF_RULES_RUNLOCK();
8543 		nd6_output_ifp(ifp, ifp, m,
8544                     (struct sockaddr_in6 *)&pd.pf_mtag->dst, NULL);
8545 		*m0 = NULL;
8546 		return (PF_PASS);
8547 	}
8548 
8549 	if (pd.pf_mtag && pd.pf_mtag->dnpipe) {
8550 		pd.act.dnpipe = pd.pf_mtag->dnpipe;
8551 		pd.act.flags = pd.pf_mtag->dnflags;
8552 	}
8553 
8554 	if (ip_dn_io_ptr != NULL && pd.pf_mtag != NULL &&
8555 	    pd.pf_mtag->flags & PF_MTAG_FLAG_DUMMYNET) {
8556 		pf_dummynet_flag_remove(m, pd.pf_mtag);
8557 		/* Dummynet re-injects packets after they've
8558 		 * completed their delay. We've already
8559 		 * processed them, so pass unconditionally. */
8560 		PF_RULES_RUNLOCK();
8561 		return (PF_PASS);
8562 	}
8563 
8564 	pd.sport = pd.dport = NULL;
8565 	pd.ip_sum = NULL;
8566 	pd.proto_sum = NULL;
8567 	pd.dir = dir;
8568 	pd.sidx = (dir == PF_IN) ? 0 : 1;
8569 	pd.didx = (dir == PF_IN) ? 1 : 0;
8570 	pd.af = AF_INET6;
8571 	pd.act.rtableid = -1;
8572 
8573 	h = mtod(m, struct ip6_hdr *);
8574 	off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
8575 
8576 	/* We do IP header normalization and packet reassembly here */
8577 	if (pf_normalize_ip6(m0, kif, &reason, &pd) != PF_PASS) {
8578 		action = PF_DROP;
8579 		goto done;
8580 	}
8581 	m = *m0;	/* pf_normalize messes with m0 */
8582 	h = mtod(m, struct ip6_hdr *);
8583 	off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
8584 
8585 	/*
8586 	 * we do not support jumbogram.  if we keep going, zero ip6_plen
8587 	 * will do something bad, so drop the packet for now.
8588 	 */
8589 	if (htons(h->ip6_plen) == 0) {
8590 		action = PF_DROP;
8591 		REASON_SET(&reason, PFRES_NORM);	/*XXX*/
8592 		goto done;
8593 	}
8594 
8595 	pd.src = (struct pf_addr *)&h->ip6_src;
8596 	pd.dst = (struct pf_addr *)&h->ip6_dst;
8597 	pd.tos = IPV6_DSCP(h);
8598 	pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
8599 
8600 	pd.proto = h->ip6_nxt;
8601 	do {
8602 		switch (pd.proto) {
8603 		case IPPROTO_FRAGMENT:
8604 			action = pf_test_fragment(&r, kif, m, h, &pd, &a,
8605 			    &ruleset);
8606 			if (action == PF_DROP)
8607 				REASON_SET(&reason, PFRES_FRAG);
8608 			goto done;
8609 		case IPPROTO_ROUTING: {
8610 			struct ip6_rthdr rthdr;
8611 
8612 			if (rh_cnt++) {
8613 				DPFPRINTF(PF_DEBUG_MISC,
8614 				    ("pf: IPv6 more than one rthdr\n"));
8615 				action = PF_DROP;
8616 				REASON_SET(&reason, PFRES_IPOPTIONS);
8617 				pd.act.log = PF_LOG_FORCE;
8618 				goto done;
8619 			}
8620 			if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
8621 			    &reason, pd.af)) {
8622 				DPFPRINTF(PF_DEBUG_MISC,
8623 				    ("pf: IPv6 short rthdr\n"));
8624 				action = PF_DROP;
8625 				REASON_SET(&reason, PFRES_SHORT);
8626 				pd.act.log = PF_LOG_FORCE;
8627 				goto done;
8628 			}
8629 			if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
8630 				DPFPRINTF(PF_DEBUG_MISC,
8631 				    ("pf: IPv6 rthdr0\n"));
8632 				action = PF_DROP;
8633 				REASON_SET(&reason, PFRES_IPOPTIONS);
8634 				pd.act.log = PF_LOG_FORCE;
8635 				goto done;
8636 			}
8637 			/* FALLTHROUGH */
8638 		}
8639 		case IPPROTO_AH:
8640 		case IPPROTO_HOPOPTS:
8641 		case IPPROTO_DSTOPTS: {
8642 			/* get next header and header length */
8643 			struct ip6_ext	opt6;
8644 
8645 			if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
8646 			    NULL, &reason, pd.af)) {
8647 				DPFPRINTF(PF_DEBUG_MISC,
8648 				    ("pf: IPv6 short opt\n"));
8649 				action = PF_DROP;
8650 				pd.act.log = PF_LOG_FORCE;
8651 				goto done;
8652 			}
8653 			if (pd.proto == IPPROTO_AH)
8654 				off += (opt6.ip6e_len + 2) * 4;
8655 			else
8656 				off += (opt6.ip6e_len + 1) * 8;
8657 			pd.proto = opt6.ip6e_nxt;
8658 			/* goto the next header */
8659 			break;
8660 		}
8661 		default:
8662 			terminal++;
8663 			break;
8664 		}
8665 	} while (!terminal);
8666 
8667 	/* if there's no routing header, use unmodified mbuf for checksumming */
8668 	if (!n)
8669 		n = m;
8670 
8671 	switch (pd.proto) {
8672 	case IPPROTO_TCP: {
8673 		if (!pf_pull_hdr(m, off, &pd.hdr.tcp, sizeof(pd.hdr.tcp),
8674 		    &action, &reason, AF_INET6)) {
8675 			if (action != PF_PASS)
8676 				pd.act.log |= PF_LOG_FORCE;
8677 			goto done;
8678 		}
8679 		pd.p_len = pd.tot_len - off - (pd.hdr.tcp.th_off << 2);
8680 		pd.sport = &pd.hdr.tcp.th_sport;
8681 		pd.dport = &pd.hdr.tcp.th_dport;
8682 
8683 		/* Respond to SYN with a syncookie. */
8684 		if ((pd.hdr.tcp.th_flags & (TH_SYN|TH_ACK|TH_RST)) == TH_SYN &&
8685 		    pd.dir == PF_IN && pf_synflood_check(&pd)) {
8686 			pf_syncookie_send(m, off, &pd);
8687 			action = PF_DROP;
8688 			break;
8689 		}
8690 
8691 		action = pf_normalize_tcp(kif, m, 0, off, h, &pd);
8692 		if (action == PF_DROP)
8693 			goto done;
8694 		action = pf_test_state_tcp(&s, kif, m, off, h, &pd, &reason);
8695 		if (action == PF_PASS) {
8696 			if (V_pfsync_update_state_ptr != NULL)
8697 				V_pfsync_update_state_ptr(s);
8698 			r = s->rule.ptr;
8699 			a = s->anchor.ptr;
8700 		} else if (s == NULL) {
8701 			/* Validate remote SYN|ACK, re-create original SYN if
8702 			 * valid. */
8703 			if ((pd.hdr.tcp.th_flags & (TH_SYN|TH_ACK|TH_RST)) ==
8704 			    TH_ACK && pf_syncookie_validate(&pd) &&
8705 			    pd.dir == PF_IN) {
8706 				struct mbuf *msyn;
8707 
8708 				msyn = pf_syncookie_recreate_syn(h->ip6_hlim,
8709 				    off, &pd);
8710 				if (msyn == NULL) {
8711 					action = PF_DROP;
8712 					break;
8713 				}
8714 
8715 				action = pf_test6(dir, pflags, ifp, &msyn, inp,
8716 				    &pd.act);
8717 				m_freem(msyn);
8718 				if (action != PF_PASS)
8719 					break;
8720 
8721 				action = pf_test_state_tcp(&s, kif, m, off, h,
8722 				    &pd, &reason);
8723 				if (action != PF_PASS || s == NULL) {
8724 					action = PF_DROP;
8725 					break;
8726 				}
8727 
8728 				s->src.seqhi = ntohl(pd.hdr.tcp.th_ack) - 1;
8729 				s->src.seqlo = ntohl(pd.hdr.tcp.th_seq) - 1;
8730 				pf_set_protostate(s, PF_PEER_SRC, PF_TCPS_PROXY_DST);
8731 
8732 				action = pf_synproxy(&pd, &s, &reason);
8733 				break;
8734 			} else {
8735 				action = pf_test_rule(&r, &s, kif, m, off, &pd,
8736 				    &a, &ruleset, inp);
8737 			}
8738 		}
8739 		break;
8740 	}
8741 
8742 	case IPPROTO_UDP: {
8743 		if (!pf_pull_hdr(m, off, &pd.hdr.udp, sizeof(pd.hdr.udp),
8744 		    &action, &reason, AF_INET6)) {
8745 			if (action != PF_PASS)
8746 				pd.act.log |= PF_LOG_FORCE;
8747 			goto done;
8748 		}
8749 		pd.sport = &pd.hdr.udp.uh_sport;
8750 		pd.dport = &pd.hdr.udp.uh_dport;
8751 		if (pd.hdr.udp.uh_dport == 0 ||
8752 		    ntohs(pd.hdr.udp.uh_ulen) > m->m_pkthdr.len - off ||
8753 		    ntohs(pd.hdr.udp.uh_ulen) < sizeof(struct udphdr)) {
8754 			action = PF_DROP;
8755 			REASON_SET(&reason, PFRES_SHORT);
8756 			goto done;
8757 		}
8758 		action = pf_test_state_udp(&s, kif, m, off, h, &pd);
8759 		if (action == PF_PASS) {
8760 			if (V_pfsync_update_state_ptr != NULL)
8761 				V_pfsync_update_state_ptr(s);
8762 			r = s->rule.ptr;
8763 			a = s->anchor.ptr;
8764 		} else if (s == NULL)
8765 			action = pf_test_rule(&r, &s, kif, m, off, &pd,
8766 			    &a, &ruleset, inp);
8767 		break;
8768 	}
8769 
8770 	case IPPROTO_SCTP: {
8771 		if (!pf_pull_hdr(m, off, &pd.hdr.sctp, sizeof(pd.hdr.sctp),
8772 		    &action, &reason, AF_INET6)) {
8773 			if (action != PF_PASS)
8774 				pd.act.log |= PF_LOG_FORCE;
8775 			goto done;
8776 		}
8777 		pd.sport = &pd.hdr.sctp.src_port;
8778 		pd.dport = &pd.hdr.sctp.dest_port;
8779 		if (pd.hdr.sctp.src_port == 0 || pd.hdr.sctp.dest_port == 0) {
8780 			action = PF_DROP;
8781 			REASON_SET(&reason, PFRES_SHORT);
8782 			goto done;
8783 		}
8784 		action = pf_normalize_sctp(dir, kif, m, 0, off, h, &pd);
8785 		if (action == PF_DROP)
8786 			goto done;
8787 		action = pf_test_state_sctp(&s, kif, m, off, h, &pd,
8788 		    &reason);
8789 		if (action == PF_PASS) {
8790 			if (V_pfsync_update_state_ptr != NULL)
8791 				V_pfsync_update_state_ptr(s);
8792 			r = s->rule.ptr;
8793 			a = s->anchor.ptr;
8794 		} else {
8795 			action = pf_test_rule(&r, &s, kif, m, off,
8796 			    &pd, &a, &ruleset, inp);
8797 		}
8798 		break;
8799 	}
8800 
8801 	case IPPROTO_ICMP: {
8802 		action = PF_DROP;
8803 		DPFPRINTF(PF_DEBUG_MISC,
8804 		    ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
8805 		goto done;
8806 	}
8807 
8808 	case IPPROTO_ICMPV6: {
8809 		if (!pf_pull_hdr(m, off, &pd.hdr.icmp6, sizeof(pd.hdr.icmp6),
8810 		    &action, &reason, AF_INET6)) {
8811 			if (action != PF_PASS)
8812 				pd.act.log |= PF_LOG_FORCE;
8813 			goto done;
8814 		}
8815 		action = pf_test_state_icmp(&s, kif, m, off, h, &pd, &reason);
8816 		if (action == PF_PASS) {
8817 			if (V_pfsync_update_state_ptr != NULL)
8818 				V_pfsync_update_state_ptr(s);
8819 			r = s->rule.ptr;
8820 			a = s->anchor.ptr;
8821 		} else if (s == NULL)
8822 			action = pf_test_rule(&r, &s, kif, m, off, &pd,
8823 			    &a, &ruleset, inp);
8824 		break;
8825 	}
8826 
8827 	default:
8828 		action = pf_test_state_other(&s, kif, m, &pd);
8829 		if (action == PF_PASS) {
8830 			if (V_pfsync_update_state_ptr != NULL)
8831 				V_pfsync_update_state_ptr(s);
8832 			r = s->rule.ptr;
8833 			a = s->anchor.ptr;
8834 		} else if (s == NULL)
8835 			action = pf_test_rule(&r, &s, kif, m, off, &pd,
8836 			    &a, &ruleset, inp);
8837 		break;
8838 	}
8839 
8840 done:
8841 	PF_RULES_RUNLOCK();
8842 	if (n != m) {
8843 		m_freem(n);
8844 		n = NULL;
8845 	}
8846 
8847 	/* handle dangerous IPv6 extension headers. */
8848 	if (action == PF_PASS && rh_cnt &&
8849 	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
8850 		action = PF_DROP;
8851 		REASON_SET(&reason, PFRES_IPOPTIONS);
8852 		pd.act.log = r->log;
8853 		DPFPRINTF(PF_DEBUG_MISC,
8854 		    ("pf: dropping packet with dangerous v6 headers\n"));
8855 	}
8856 
8857 	if (s) {
8858 		uint8_t log = pd.act.log;
8859 		memcpy(&pd.act, &s->act, sizeof(struct pf_rule_actions));
8860 		pd.act.log |= log;
8861 		tag = s->tag;
8862 		rt = s->rt;
8863 	} else {
8864 		tag = r->tag;
8865 		rt = r->rt;
8866 	}
8867 
8868 	if (tag > 0 && pf_tag_packet(m, &pd, tag)) {
8869 		action = PF_DROP;
8870 		REASON_SET(&reason, PFRES_MEMORY);
8871 	}
8872 
8873 	pf_scrub_ip6(&m, &pd);
8874 	if (pd.proto == IPPROTO_TCP && pd.act.max_mss)
8875 		pf_normalize_mss(m, off, &pd);
8876 
8877 	if (pd.act.rtableid >= 0)
8878 		M_SETFIB(m, pd.act.rtableid);
8879 
8880 	if (pd.act.flags & PFSTATE_SETPRIO) {
8881 		if (pd.tos & IPTOS_LOWDELAY)
8882 			use_2nd_queue = 1;
8883 		if (vlan_set_pcp(m, pd.act.set_prio[use_2nd_queue])) {
8884 			action = PF_DROP;
8885 			REASON_SET(&reason, PFRES_MEMORY);
8886 			pd.act.log = PF_LOG_FORCE;
8887 			DPFPRINTF(PF_DEBUG_MISC,
8888 			    ("pf: failed to allocate 802.1q mtag\n"));
8889 		}
8890 	}
8891 
8892 #ifdef ALTQ
8893 	if (action == PF_PASS && pd.act.qid) {
8894 		if (pd.pf_mtag == NULL &&
8895 		    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
8896 			action = PF_DROP;
8897 			REASON_SET(&reason, PFRES_MEMORY);
8898 		} else {
8899 			if (s != NULL)
8900 				pd.pf_mtag->qid_hash = pf_state_hash(s);
8901 			if (pd.tos & IPTOS_LOWDELAY)
8902 				pd.pf_mtag->qid = pd.act.pqid;
8903 			else
8904 				pd.pf_mtag->qid = pd.act.qid;
8905 			/* Add hints for ecn. */
8906 			pd.pf_mtag->hdr = h;
8907 		}
8908 	}
8909 #endif /* ALTQ */
8910 
8911 	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
8912 	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
8913 	    (s->nat_rule.ptr->action == PF_RDR ||
8914 	    s->nat_rule.ptr->action == PF_BINAT) &&
8915 	    IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
8916 		m->m_flags |= M_SKIP_FIREWALL;
8917 
8918 	/* XXX: Anybody working on it?! */
8919 	if (r->divert.port)
8920 		printf("pf: divert(9) is not supported for IPv6\n");
8921 
8922 	if (pd.act.log) {
8923 		struct pf_krule		*lr;
8924 		struct pf_krule_item	*ri;
8925 
8926 		if (s != NULL && s->nat_rule.ptr != NULL &&
8927 		    s->nat_rule.ptr->log & PF_LOG_ALL)
8928 			lr = s->nat_rule.ptr;
8929 		else
8930 			lr = r;
8931 
8932 		if (pd.act.log & PF_LOG_FORCE || lr->log & PF_LOG_ALL)
8933 			PFLOG_PACKET(kif, m, AF_INET6, action, reason, lr, a, ruleset,
8934 			    &pd, (s == NULL));
8935 		if (s) {
8936 			SLIST_FOREACH(ri, &s->match_rules, entry)
8937 				if (ri->r->log & PF_LOG_ALL)
8938 					PFLOG_PACKET(kif, m, AF_INET6, action, reason,
8939 					    ri->r, a, ruleset, &pd, 0);
8940 		}
8941 	}
8942 
8943 	pf_counter_u64_critical_enter();
8944 	pf_counter_u64_add_protected(&kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS],
8945 	    pd.tot_len);
8946 	pf_counter_u64_add_protected(&kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS],
8947 	    1);
8948 
8949 	if (action == PF_PASS || r->action == PF_DROP) {
8950 		dirndx = (dir == PF_OUT);
8951 		pf_counter_u64_add_protected(&r->packets[dirndx], 1);
8952 		pf_counter_u64_add_protected(&r->bytes[dirndx], pd.tot_len);
8953 		if (a != NULL) {
8954 			pf_counter_u64_add_protected(&a->packets[dirndx], 1);
8955 			pf_counter_u64_add_protected(&a->bytes[dirndx], pd.tot_len);
8956 		}
8957 		if (s != NULL) {
8958 			if (s->nat_rule.ptr != NULL) {
8959 				pf_counter_u64_add_protected(&s->nat_rule.ptr->packets[dirndx],
8960 				    1);
8961 				pf_counter_u64_add_protected(&s->nat_rule.ptr->bytes[dirndx],
8962 				    pd.tot_len);
8963 			}
8964 			if (s->src_node != NULL) {
8965 				counter_u64_add(s->src_node->packets[dirndx],
8966 				    1);
8967 				counter_u64_add(s->src_node->bytes[dirndx],
8968 				    pd.tot_len);
8969 			}
8970 			if (s->nat_src_node != NULL) {
8971 				counter_u64_add(s->nat_src_node->packets[dirndx],
8972 				    1);
8973 				counter_u64_add(s->nat_src_node->bytes[dirndx],
8974 				    pd.tot_len);
8975 			}
8976 			dirndx = (dir == s->direction) ? 0 : 1;
8977 			s->packets[dirndx]++;
8978 			s->bytes[dirndx] += pd.tot_len;
8979 		}
8980 		tr = r;
8981 		nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
8982 		if (nr != NULL && r == &V_pf_default_rule)
8983 			tr = nr;
8984 		if (tr->src.addr.type == PF_ADDR_TABLE)
8985 			pfr_update_stats(tr->src.addr.p.tbl,
8986 			    (s == NULL) ? pd.src :
8987 			    &s->key[(s->direction == PF_IN)]->addr[0],
8988 			    pd.af, pd.tot_len, dir == PF_OUT,
8989 			    r->action == PF_PASS, tr->src.neg);
8990 		if (tr->dst.addr.type == PF_ADDR_TABLE)
8991 			pfr_update_stats(tr->dst.addr.p.tbl,
8992 			    (s == NULL) ? pd.dst :
8993 			    &s->key[(s->direction == PF_IN)]->addr[1],
8994 			    pd.af, pd.tot_len, dir == PF_OUT,
8995 			    r->action == PF_PASS, tr->dst.neg);
8996 	}
8997 	pf_counter_u64_critical_exit();
8998 
8999 	switch (action) {
9000 	case PF_SYNPROXY_DROP:
9001 		m_freem(*m0);
9002 	case PF_DEFER:
9003 		*m0 = NULL;
9004 		action = PF_PASS;
9005 		break;
9006 	case PF_DROP:
9007 		m_freem(*m0);
9008 		*m0 = NULL;
9009 		break;
9010 	default:
9011 		/* pf_route6() returns unlocked. */
9012 		if (rt) {
9013 			pf_route6(m0, r, kif->pfik_ifp, s, &pd, inp);
9014 			goto out;
9015 		}
9016 		if (pf_dummynet(&pd, s, r, m0) != 0) {
9017 			action = PF_DROP;
9018 			REASON_SET(&reason, PFRES_MEMORY);
9019 		}
9020 		break;
9021 	}
9022 
9023 	if (s && action != PF_DROP) {
9024 		if (!s->if_index_in && dir == PF_IN)
9025 			s->if_index_in = ifp->if_index;
9026 		else if (!s->if_index_out && dir == PF_OUT)
9027 			s->if_index_out = ifp->if_index;
9028 	}
9029 
9030 	if (s)
9031 		PF_STATE_UNLOCK(s);
9032 
9033 	/* If reassembled packet passed, create new fragments. */
9034 	if (action == PF_PASS && *m0 && dir == PF_OUT &&
9035 	    (mtag = m_tag_find(m, PACKET_TAG_PF_REASSEMBLED, NULL)) != NULL)
9036 		action = pf_refragment6(ifp, m0, mtag, pflags & PFIL_FWD);
9037 
9038 out:
9039 	SDT_PROBE4(pf, ip, test6, done, action, reason, r, s);
9040 
9041 	pf_sctp_multihome_delayed(&pd, off, kif, s, action);
9042 
9043 	return (action);
9044 }
9045 #endif /* INET6 */
9046