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