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