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