xref: /netbsd-src/sys/external/bsd/ipf/netinet/ip_state.c (revision 7c192b2a5e1093666e67801684f930ef49b3b363)
1 /*	$NetBSD: ip_state.c,v 1.8 2017/07/01 16:34:17 khorben Exp $	*/
2 
3 /*
4  * Copyright (C) 2012 by Darren Reed.
5  *
6  * See the IPFILTER.LICENCE file for details on licencing.
7  *
8  * Id: ip_state.c,v 1.1.1.2 2012/07/22 13:45:37 darrenr Exp
9  */
10 #if defined(KERNEL) || defined(_KERNEL)
11 # undef KERNEL
12 # undef _KERNEL
13 # define        KERNEL	1
14 # define        _KERNEL	1
15 #endif
16 #include <sys/errno.h>
17 #include <sys/types.h>
18 #include <sys/param.h>
19 #include <sys/file.h>
20 #if defined(_KERNEL) && defined(__FreeBSD_version) && \
21     (__FreeBSD_version >= 400000) && !defined(KLD_MODULE)
22 #include "opt_inet6.h"
23 #endif
24 #if !defined(_KERNEL) && !defined(__KERNEL__)
25 # include <stdio.h>
26 # include <stdlib.h>
27 # include <string.h>
28 # define _KERNEL
29 # ifdef __OpenBSD__
30 struct file;
31 # endif
32 # include <sys/uio.h>
33 # undef _KERNEL
34 #endif
35 #if defined(_KERNEL) && (__FreeBSD_version >= 220000)
36 # include <sys/filio.h>
37 # include <sys/fcntl.h>
38 #else
39 # include <sys/ioctl.h>
40 #endif
41 #include <sys/time.h>
42 #if !defined(linux)
43 # include <sys/protosw.h>
44 #endif
45 #include <sys/socket.h>
46 #if defined(_KERNEL)
47 # include <sys/systm.h>
48 # if !defined(__SVR4) && !defined(__svr4__)
49 #  include <sys/mbuf.h>
50 # endif
51 #endif
52 #if defined(__SVR4) || defined(__svr4__)
53 # include <sys/filio.h>
54 # include <sys/byteorder.h>
55 # ifdef _KERNEL
56 #  include <sys/dditypes.h>
57 # endif
58 # include <sys/stream.h>
59 # include <sys/kmem.h>
60 #endif
61 
62 #include <net/if.h>
63 #ifdef sun
64 # include <net/af.h>
65 #endif
66 #include <netinet/in.h>
67 #include <netinet/in_systm.h>
68 #include <netinet/ip.h>
69 #include <netinet/tcp.h>
70 #if !defined(__hpux) && !defined(linux)
71 # include <netinet/tcp_fsm.h>
72 #endif
73 #include <netinet/udp.h>
74 #include <netinet/ip_icmp.h>
75 #if !defined(_KERNEL)
76 # include "ipf.h"
77 #endif
78 #include "netinet/ip_compat.h"
79 #include "netinet/ip_fil.h"
80 #include "netinet/ip_nat.h"
81 #include "netinet/ip_frag.h"
82 #include "netinet/ip_state.h"
83 #include "netinet/ip_proxy.h"
84 #include "netinet/ip_lookup.h"
85 #include "netinet/ip_dstlist.h"
86 #include "netinet/ip_sync.h"
87 #ifdef	USE_INET6
88 #include <netinet/icmp6.h>
89 #endif
90 #if FREEBSD_GE_REV(300000)
91 # include <sys/malloc.h>
92 # if defined(_KERNEL) && !defined(IPFILTER_LKM)
93 #  include <sys/libkern.h>
94 #  include <sys/systm.h>
95 # endif
96 #endif
97 /* END OF INCLUDES */
98 
99 
100 #if !defined(lint)
101 #if defined(__NetBSD__)
102 #include <sys/cdefs.h>
103 __KERNEL_RCSID(0, "$NetBSD: ip_state.c,v 1.8 2017/07/01 16:34:17 khorben Exp $");
104 #else
105 static const char sccsid[] = "@(#)ip_state.c	1.8 6/5/96 (C) 1993-2000 Darren Reed";
106 static const char rcsid[] = "@(#)Id: ip_state.c,v 1.1.1.2 2012/07/22 13:45:37 darrenr Exp";
107 #endif
108 #endif
109 
110 
111 static ipftuneable_t ipf_state_tuneables[] = {
112 	{ { (void *)offsetof(ipf_state_softc_t, ipf_state_max) },
113 		"state_max",		1,	0x7fffffff,
114 		stsizeof(ipf_state_softc_t, ipf_state_max),
115 		0,			NULL,	NULL },
116 	{ { (void *)offsetof(ipf_state_softc_t, ipf_state_size) },
117 		"state_size",		1,	0x7fffffff,
118 		stsizeof(ipf_state_softc_t, ipf_state_size),
119 		0,			NULL,	ipf_state_rehash },
120 	{ { (void *)offsetof(ipf_state_softc_t, ipf_state_lock) },
121 		"state_lock",		0,	1,
122 		stsizeof(ipf_state_softc_t, ipf_state_lock),
123 		IPFT_RDONLY,		NULL,	NULL },
124 	{ { (void *)offsetof(ipf_state_softc_t, ipf_state_maxbucket) },
125 		"state_maxbucket",	1,	0x7fffffff,
126 		stsizeof(ipf_state_softc_t, ipf_state_maxbucket),
127 		0,			NULL,	NULL },
128 	{ { (void *)offsetof(ipf_state_softc_t, ipf_state_logging) },
129 		"state_logging",0,	1,
130 		stsizeof(ipf_state_softc_t, ipf_state_logging),
131 		0,			NULL,	NULL },
132 	{ { (void *)offsetof(ipf_state_softc_t, ipf_state_wm_high) },
133 		"state_wm_high",2,	100,
134 		stsizeof(ipf_state_softc_t, ipf_state_wm_high),
135 		0,			NULL,	NULL },
136 	{ { (void *)offsetof(ipf_state_softc_t, ipf_state_wm_low) },
137 		"state_wm_low",	1,	99,
138 		stsizeof(ipf_state_softc_t, ipf_state_wm_low),
139 		0,			NULL,	NULL },
140 	{ { (void *)offsetof(ipf_state_softc_t, ipf_state_wm_freq) },
141 		"state_wm_freq",2,	999999,
142 		stsizeof(ipf_state_softc_t, ipf_state_wm_freq),
143 		0,			NULL,	NULL },
144 	{ { NULL },
145 		NULL,			0,	0,
146 		0,
147 		0,	NULL, NULL }
148 };
149 
150 #define	SINCL(x)	ATOMIC_INCL(softs->x)
151 #define	SBUMP(x)	(softs->x)++
152 #define	SBUMPD(x, y)	do { (softs->x.y)++; DT(y); } while (0)
153 #define	SBUMPDX(x, y, z)do { (softs->x.y)++; DT(z); } while (0)
154 
155 #ifdef	USE_INET6
156 static ipstate_t *ipf_checkicmp6matchingstate(fr_info_t *);
157 #endif
158 static int ipf_allowstateicmp(fr_info_t *, ipstate_t *, i6addr_t *);
159 static ipstate_t *ipf_matchsrcdst(fr_info_t *, ipstate_t *, i6addr_t *,
160 				  i6addr_t *, tcphdr_t *, u_32_t);
161 static ipstate_t *ipf_checkicmpmatchingstate(fr_info_t *);
162 static int ipf_state_flush_entry(ipf_main_softc_t *, void *);
163 static ips_stat_t *ipf_state_stats(ipf_main_softc_t *);
164 static int ipf_state_del(ipf_main_softc_t *, ipstate_t *, int);
165 static int ipf_state_remove(ipf_main_softc_t *, void *);
166 static int ipf_state_match(ipstate_t *is1, ipstate_t *is2);
167 static int ipf_state_matchaddresses(ipstate_t *is1, ipstate_t *is2);
168 static int ipf_state_matchipv4addrs(ipstate_t *is1, ipstate_t *is2);
169 static int ipf_state_matchipv6addrs(ipstate_t *is1, ipstate_t *is2);
170 static int ipf_state_matchisps(ipstate_t *is1, ipstate_t *is2);
171 static int ipf_state_matchports(udpinfo_t *is1, udpinfo_t *is2);
172 static int ipf_state_matcharray(ipstate_t *, int *, u_long);
173 static void ipf_ipsmove(ipf_state_softc_t *, ipstate_t *, u_int);
174 static int ipf_state_tcp(ipf_main_softc_t *, ipf_state_softc_t *,
175 			 fr_info_t *, tcphdr_t *, ipstate_t *);
176 static int ipf_tcpoptions(ipf_state_softc_t *, fr_info_t *,
177 			  tcphdr_t *, tcpdata_t *);
178 static ipstate_t *ipf_state_clone(fr_info_t *, tcphdr_t *, ipstate_t *);
179 static void ipf_fixinisn(fr_info_t *, ipstate_t *);
180 static void ipf_fixoutisn(fr_info_t *, ipstate_t *);
181 static void ipf_checknewisn(fr_info_t *, ipstate_t *);
182 static int ipf_state_iter(ipf_main_softc_t *, ipftoken_t *,
183 			  ipfgeniter_t *, ipfobj_t *);
184 static int ipf_state_gettable(ipf_main_softc_t *, ipf_state_softc_t *, char *);
185 static	int ipf_state_tcpinwindow(struct fr_info *, struct tcpdata *,
186 				  struct tcpdata *, tcphdr_t *, int);
187 
188 static int ipf_state_getent(ipf_main_softc_t *, ipf_state_softc_t *, void *);
189 static int ipf_state_putent(ipf_main_softc_t *, ipf_state_softc_t *, void *);
190 
191 #define	ONE_DAY		IPF_TTLVAL(1 * 86400)	/* 1 day */
192 #define	FIVE_DAYS	(5 * ONE_DAY)
193 #define	DOUBLE_HASH(x)	(((x) + softs->ipf_state_seed[(x) % \
194 			 softs->ipf_state_size]) % softs->ipf_state_size)
195 
196 
197 /* ------------------------------------------------------------------------ */
198 /* Function:    ipf_state_main_load                                         */
199 /* Returns:     int - 0 == success, -1 == failure                           */
200 /* Parameters:  Nil                                                         */
201 /*                                                                          */
202 /* A null-op function that exists as a placeholder so that the flow in      */
203 /* other functions is obvious.                                              */
204 /* ------------------------------------------------------------------------ */
205 int
206 ipf_state_main_load(void)
207 {
208 	return 0;
209 }
210 
211 
212 /* ------------------------------------------------------------------------ */
213 /* Function:    ipf_state_main_unload                                       */
214 /* Returns:     int - 0 == success, -1 == failure                           */
215 /* Parameters:  Nil                                                         */
216 /*                                                                          */
217 /* A null-op function that exists as a placeholder so that the flow in      */
218 /* other functions is obvious.                                              */
219 /* ------------------------------------------------------------------------ */
220 int
221 ipf_state_main_unload(void)
222 {
223 	return 0;
224 }
225 
226 
227 /* ------------------------------------------------------------------------ */
228 /* Function:    ipf_state_soft_create                                       */
229 /* Returns:     void *   - NULL = failure, else pointer to soft context     */
230 /* Parameters:  softc(I) - pointer to soft context main structure           */
231 /*                                                                          */
232 /* Create a new state soft context structure and populate it with the list  */
233 /* of tunables and other default settings.                                  */
234 /* ------------------------------------------------------------------------ */
235 void *
236 ipf_state_soft_create(ipf_main_softc_t *softc)
237 {
238 	ipf_state_softc_t *softs;
239 
240 	KMALLOC(softs, ipf_state_softc_t *);
241 	if (softs == NULL)
242 		return NULL;
243 
244 	bzero((char *)softs, sizeof(*softs));
245 
246 	softs->ipf_state_tune = ipf_tune_array_copy(softs,
247 						    sizeof(ipf_state_tuneables),
248 						    ipf_state_tuneables);
249 	if (softs->ipf_state_tune == NULL) {
250 		ipf_state_soft_destroy(softc, softs);
251 		return NULL;
252 	}
253 	if (ipf_tune_array_link(softc, softs->ipf_state_tune) == -1) {
254 		ipf_state_soft_destroy(softc, softs);
255 		return NULL;
256 	}
257 
258 #ifdef	IPFILTER_LOG
259 	softs->ipf_state_logging = 1;
260 #else
261 	softs->ipf_state_logging = 0;
262 #endif
263 	softs->ipf_state_size = IPSTATE_SIZE,
264 	softs->ipf_state_maxbucket = 0;
265 	softs->ipf_state_wm_freq = IPF_TTLVAL(10);
266 	softs->ipf_state_max = IPSTATE_MAX;
267 	softs->ipf_state_wm_last = 0;
268 	softs->ipf_state_wm_high = 99;
269 	softs->ipf_state_wm_low = 90;
270 	softs->ipf_state_inited = 0;
271 	softs->ipf_state_lock = 0;
272 	softs->ipf_state_doflush = 0;
273 
274 	return softs;
275 }
276 
277 
278 /* ------------------------------------------------------------------------ */
279 /* Function:    ipf_state_soft_destroy                                      */
280 /* Returns:     Nil                                                         */
281 /* Parameters:  softc(I) - pointer to soft context main structure           */
282 /*              arg(I)   - pointer to local context to use                  */
283 /*                                                                          */
284 /* Undo only what we did in soft create: unlink and free the tunables and   */
285 /* free the soft context structure itself.                                  */
286 /* ------------------------------------------------------------------------ */
287 void
288 ipf_state_soft_destroy(ipf_main_softc_t *softc, void *arg)
289 {
290 	ipf_state_softc_t *softs = arg;
291 
292 	if (softs->ipf_state_tune != NULL) {
293 		ipf_tune_array_unlink(softc, softs->ipf_state_tune);
294 		KFREES(softs->ipf_state_tune, sizeof(ipf_state_tuneables));
295 		softs->ipf_state_tune = NULL;
296 	}
297 
298 	KFREE(softs);
299 }
300 
301 
302 /* ------------------------------------------------------------------------ */
303 /* Function:    ipf_state_soft_init                                         */
304 /* Returns:     int      - 0 == success, -1 == failure                      */
305 /* Parameters:  softc(I) - pointer to soft context main structure           */
306 /*              arg(I)   - pointer to local context to use                  */
307 /*                                                                          */
308 /* Initialise the state soft context structure so it is ready for use.      */
309 /* This involves:                                                           */
310 /* - allocating a hash table and zero'ing it out                            */
311 /* - building a secondary table of seeds for double hashing to make it more */
312 /*   difficult to attempt to attack the hash table itself (for DoS)         */
313 /* - initialise all of the timeout queues, including a table for TCP, some  */
314 /*   pairs of query/response for UDP and other IP protocols (typically the  */
315 /*   reply queue has a shorter timeout than the query)                      */
316 /* ------------------------------------------------------------------------ */
317 int
318 ipf_state_soft_init(ipf_main_softc_t *softc, void *arg)
319 {
320 	ipf_state_softc_t *softs = arg;
321 	int i;
322 
323 	KMALLOCS(softs->ipf_state_table,
324 		 ipstate_t **, softs->ipf_state_size * sizeof(ipstate_t *));
325 	if (softs->ipf_state_table == NULL)
326 		return -1;
327 
328 	bzero((char *)softs->ipf_state_table,
329 	      softs->ipf_state_size * sizeof(ipstate_t *));
330 
331 	KMALLOCS(softs->ipf_state_seed, u_long *,
332 		 softs->ipf_state_size * sizeof(*softs->ipf_state_seed));
333 	if (softs->ipf_state_seed == NULL)
334 		return -2;
335 
336 	for (i = 0; i < softs->ipf_state_size; i++) {
337 		/*
338 		 * XXX - ipf_state_seed[X] should be a random number of sorts.
339 		 */
340 #if !defined(NEED_LOCAL_RAND) && defined(_KERNEL)
341 		softs->ipf_state_seed[i] = cprng_fast32();
342 #else
343 		softs->ipf_state_seed[i] = ((u_long)softs->ipf_state_seed + i) *
344 				    softs->ipf_state_size;
345 		softs->ipf_state_seed[i] ^= 0xa5a55a5a;
346 		softs->ipf_state_seed[i] *= (u_long)softs->ipf_state_seed;
347 		softs->ipf_state_seed[i] ^= 0x5a5aa5a5;
348 		softs->ipf_state_seed[i] *= softs->ipf_state_max;
349 #endif
350 	}
351 
352 	KMALLOCS(softs->ipf_state_stats.iss_bucketlen, u_int *,
353 		 softs->ipf_state_size * sizeof(u_int));
354 	if (softs->ipf_state_stats.iss_bucketlen == NULL)
355 		return -3;
356 
357 	bzero((char *)softs->ipf_state_stats.iss_bucketlen,
358 	      softs->ipf_state_size * sizeof(u_int));
359 
360 	if (softs->ipf_state_maxbucket == 0) {
361 		for (i = softs->ipf_state_size; i > 0; i >>= 1)
362 			softs->ipf_state_maxbucket++;
363 		softs->ipf_state_maxbucket *= 2;
364 	}
365 
366 	ipf_sttab_init(softc, softs->ipf_state_tcptq);
367 	softs->ipf_state_stats.iss_tcptab = softs->ipf_state_tcptq;
368 	softs->ipf_state_tcptq[IPF_TCP_NSTATES - 1].ifq_next =
369 						&softs->ipf_state_udptq;
370 
371 	IPFTQ_INIT(&softs->ipf_state_udptq, softc->ipf_udptimeout,
372 		   "ipftq udp tab");
373 	softs->ipf_state_udptq.ifq_next = &softs->ipf_state_udpacktq;
374 
375 	IPFTQ_INIT(&softs->ipf_state_udpacktq, softc->ipf_udpacktimeout,
376 		   "ipftq udpack tab");
377 	softs->ipf_state_udpacktq.ifq_next = &softs->ipf_state_icmptq;
378 
379 	IPFTQ_INIT(&softs->ipf_state_icmptq, softc->ipf_icmptimeout,
380 		   "ipftq icmp tab");
381 	softs->ipf_state_icmptq.ifq_next = &softs->ipf_state_icmpacktq;
382 
383 	IPFTQ_INIT(&softs->ipf_state_icmpacktq, softc->ipf_icmpacktimeout,
384 		  "ipftq icmpack tab");
385 	softs->ipf_state_icmpacktq.ifq_next = &softs->ipf_state_iptq;
386 
387 	IPFTQ_INIT(&softs->ipf_state_iptq, softc->ipf_iptimeout,
388 		   "ipftq iptimeout tab");
389 	softs->ipf_state_iptq.ifq_next = &softs->ipf_state_pending;
390 
391 	IPFTQ_INIT(&softs->ipf_state_pending, IPF_HZ_DIVIDE, "ipftq pending");
392 	softs->ipf_state_pending.ifq_next = &softs->ipf_state_deletetq;
393 
394 	IPFTQ_INIT(&softs->ipf_state_deletetq, 1, "ipftq delete");
395 	softs->ipf_state_deletetq.ifq_next = NULL;
396 
397 	MUTEX_INIT(&softs->ipf_stinsert, "ipf state insert mutex");
398 
399 
400 	softs->ipf_state_wm_last = softc->ipf_ticks;
401 	softs->ipf_state_inited = 1;
402 
403 	return 0;
404 }
405 
406 
407 /* ------------------------------------------------------------------------ */
408 /* Function:    ipf_state_soft_fini                                         */
409 /* Returns:     int      - 0 = success, -1 = failure                        */
410 /* Parameters:  softc(I) - pointer to soft context main structure           */
411 /*              arg(I)   - pointer to local context to use                  */
412 /*                                                                          */
413 /* Release and destroy any resources acquired or initialised so that        */
414 /* IPFilter can be unloaded or re-initialised.                              */
415 /* ------------------------------------------------------------------------ */
416 int
417 ipf_state_soft_fini(ipf_main_softc_t *softc, void *arg)
418 {
419 	ipf_state_softc_t *softs = arg;
420 	ipftq_t *ifq, *ifqnext;
421 	ipstate_t *is;
422 
423 	while ((is = softs->ipf_state_list) != NULL)
424 		ipf_state_del(softc, is, ISL_UNLOAD);
425 
426 	/*
427 	 * Proxy timeout queues are not cleaned here because although they
428 	 * exist on the state list, appr_unload is called after
429 	 * ipf_state_unload and the proxies actually are responsible for them
430 	 * being created. Should the proxy timeouts have their own list?
431 	 * There's no real justification as this is the only complication.
432 	 */
433 	for (ifq = softs->ipf_state_usertq; ifq != NULL; ifq = ifqnext) {
434 		ifqnext = ifq->ifq_next;
435 
436 		if (ipf_deletetimeoutqueue(ifq) == 0)
437 			ipf_freetimeoutqueue(softc, ifq);
438 	}
439 
440 	softs->ipf_state_stats.iss_inuse = 0;
441 	softs->ipf_state_stats.iss_active = 0;
442 
443 	if (softs->ipf_state_inited == 1) {
444 		softs->ipf_state_inited = 0;
445 		ipf_sttab_destroy(softs->ipf_state_tcptq);
446 		MUTEX_DESTROY(&softs->ipf_state_udptq.ifq_lock);
447 		MUTEX_DESTROY(&softs->ipf_state_icmptq.ifq_lock);
448 		MUTEX_DESTROY(&softs->ipf_state_udpacktq.ifq_lock);
449 		MUTEX_DESTROY(&softs->ipf_state_icmpacktq.ifq_lock);
450 		MUTEX_DESTROY(&softs->ipf_state_iptq.ifq_lock);
451 		MUTEX_DESTROY(&softs->ipf_state_deletetq.ifq_lock);
452 		MUTEX_DESTROY(&softs->ipf_state_pending.ifq_lock);
453 		MUTEX_DESTROY(&softs->ipf_stinsert);
454 	}
455 
456 	if (softs->ipf_state_table != NULL) {
457 		KFREES(softs->ipf_state_table,
458 		       softs->ipf_state_size * sizeof(*softs->ipf_state_table));
459 		softs->ipf_state_table = NULL;
460 	}
461 
462 	if (softs->ipf_state_seed != NULL) {
463 		KFREES(softs->ipf_state_seed,
464 		       softs->ipf_state_size * sizeof(*softs->ipf_state_seed));
465 		softs->ipf_state_seed = NULL;
466 	}
467 
468 	if (softs->ipf_state_stats.iss_bucketlen != NULL) {
469 		KFREES(softs->ipf_state_stats.iss_bucketlen,
470 		       softs->ipf_state_size * sizeof(u_int));
471 		softs->ipf_state_stats.iss_bucketlen = NULL;
472 	}
473 
474 	return 0;
475 }
476 
477 
478 /* ------------------------------------------------------------------------ */
479 /* Function:    ipf_state_set_lock                                          */
480 /* Returns:     Nil                                                         */
481 /* Parameters:  arg(I) - pointer to local context to use                    */
482 /*              tmp(I) - new value for lock                                 */
483 /*                                                                          */
484 /* Stub function that allows for external manipulation of ipf_state_lock    */
485 /* ------------------------------------------------------------------------ */
486 void
487 ipf_state_setlock(void *arg, int tmp)
488 {
489 	ipf_state_softc_t *softs = arg;
490 
491 	softs->ipf_state_lock = tmp;
492 }
493 
494 
495 /* ------------------------------------------------------------------------ */
496 /* Function:    ipf_state_stats                                             */
497 /* Returns:     ips_state_t* - pointer to state stats structure             */
498 /* Parameters:  softc(I) - pointer to soft context main structure           */
499 /*                                                                          */
500 /* Put all the current numbers and pointers into a single struct and return */
501 /* a pointer to it.                                                         */
502 /* ------------------------------------------------------------------------ */
503 static ips_stat_t *
504 ipf_state_stats(ipf_main_softc_t *softc)
505 {
506 	ipf_state_softc_t *softs = softc->ipf_state_soft;
507 	ips_stat_t *issp = &softs->ipf_state_stats;
508 
509 	issp->iss_state_size = softs->ipf_state_size;
510 	issp->iss_state_max = softs->ipf_state_max;
511 	issp->iss_table = softs->ipf_state_table;
512 	issp->iss_list = softs->ipf_state_list;
513 	issp->iss_ticks = softc->ipf_ticks;
514 
515 #ifdef IPFILTER_LOGGING
516 	issp->iss_log_ok = ipf_log_logok(softc, IPF_LOGSTATE);
517 	issp->iss_log_fail = ipf_log_failures(softc, IPF_LOGSTATE);
518 #else
519 	issp->iss_log_ok = 0;
520 	issp->iss_log_fail = 0;
521 #endif
522 	return issp;
523 }
524 
525 /* ------------------------------------------------------------------------ */
526 /* Function:    ipf_state_remove                                            */
527 /* Returns:     int - 0 == success, != 0 == failure                         */
528 /* Parameters:  softc(I) - pointer to soft context main structure           */
529 /*              data(I)  - pointer to state structure to delete from table  */
530 /*                                                                          */
531 /* Search for a state structure that matches the one passed, according to   */
532 /* the IP addresses and other protocol specific information.                */
533 /* ------------------------------------------------------------------------ */
534 static int
535 ipf_state_remove(ipf_main_softc_t *softc, void *data)
536 {
537 	ipf_state_softc_t *softs = softc->ipf_state_soft;
538 	ipstate_t *sp, st;
539 	int error;
540 
541 	sp = &st;
542 	error = ipf_inobj(softc, data, NULL, &st, IPFOBJ_IPSTATE);
543 	if (error)
544 		return EFAULT;
545 
546 	WRITE_ENTER(&softc->ipf_state);
547 	for (sp = softs->ipf_state_list; sp; sp = sp->is_next)
548 		if ((sp->is_p == st.is_p) && (sp->is_v == st.is_v) &&
549 		    !bcmp((void *)&sp->is_src, (void *)&st.is_src,
550 			  sizeof(st.is_src)) &&
551 		    !bcmp((void *)&sp->is_dst, (void *)&st.is_src,
552 			  sizeof(st.is_dst)) &&
553 		    !bcmp((void *)&sp->is_ps, (void *)&st.is_ps,
554 			  sizeof(st.is_ps))) {
555 			ipf_state_del(softc, sp, ISL_REMOVE);
556 			RWLOCK_EXIT(&softc->ipf_state);
557 			return 0;
558 		}
559 	RWLOCK_EXIT(&softc->ipf_state);
560 
561 	IPFERROR(100001);
562 	return ESRCH;
563 }
564 
565 
566 /* ------------------------------------------------------------------------ */
567 /* Function:    ipf_state_ioctl                                             */
568 /* Returns:     int - 0 == success, != 0 == failure                         */
569 /* Parameters:  softc(I) - pointer to soft context main structure           */
570 /*              data(I)  - pointer to ioctl data                            */
571 /*              cmd(I)   - ioctl command integer                            */
572 /*              mode(I)  - file mode bits used with open                    */
573 /*              uid(I)   - uid of process making the ioctl call             */
574 /*              ctx(I)   - pointer specific to context of the call          */
575 /*                                                                          */
576 /* Processes an ioctl call made to operate on the IP Filter state device.   */
577 /* ------------------------------------------------------------------------ */
578 int
579 ipf_state_ioctl(ipf_main_softc_t *softc, void *data, ioctlcmd_t cmd, int mode,
580     int uid, void *ctx)
581 {
582 	ipf_state_softc_t *softs = softc->ipf_state_soft;
583 	int arg, ret, error = 0;
584 	SPL_INT(s);
585 
586 	switch (cmd)
587 	{
588 	/*
589 	 * Delete an entry from the state table.
590 	 */
591 	case SIOCDELST :
592 		error = ipf_state_remove(softc, data);
593 		break;
594 
595 	/*
596 	 * Flush the state table
597 	 */
598 	case SIOCIPFFL :
599 		error = BCOPYIN(data, &arg, sizeof(arg));
600 		if (error != 0) {
601 			IPFERROR(100002);
602 			error = EFAULT;
603 
604 		} else {
605 			WRITE_ENTER(&softc->ipf_state);
606 			ret = ipf_state_flush(softc, arg, 4);
607 			RWLOCK_EXIT(&softc->ipf_state);
608 
609 			error = BCOPYOUT(&ret, data, sizeof(ret));
610 			if (error != 0) {
611 				IPFERROR(100003);
612 				error = EFAULT;
613 			}
614 		}
615 		break;
616 
617 #ifdef	USE_INET6
618 	case SIOCIPFL6 :
619 		error = BCOPYIN(data, &arg, sizeof(arg));
620 		if (error != 0) {
621 			IPFERROR(100004);
622 			error = EFAULT;
623 
624 		} else {
625 			WRITE_ENTER(&softc->ipf_state);
626 			ret = ipf_state_flush(softc, arg, 6);
627 			RWLOCK_EXIT(&softc->ipf_state);
628 
629 			error = BCOPYOUT(&ret, data, sizeof(ret));
630 			if (error != 0) {
631 				IPFERROR(100005);
632 				error = EFAULT;
633 			}
634 		}
635 		break;
636 #endif
637 
638 	case SIOCMATCHFLUSH :
639 		WRITE_ENTER(&softc->ipf_state);
640 		error = ipf_state_matchflush(softc, data);
641 		RWLOCK_EXIT(&softc->ipf_state);
642 		break;
643 
644 #ifdef	IPFILTER_LOG
645 	/*
646 	 * Flush the state log.
647 	 */
648 	case SIOCIPFFB :
649 		if (!(mode & FWRITE)) {
650 			IPFERROR(100008);
651 			error = EPERM;
652 		} else {
653 			int tmp;
654 
655 			tmp = ipf_log_clear(softc, IPL_LOGSTATE);
656 			error = BCOPYOUT(&tmp, data, sizeof(tmp));
657 			if (error != 0) {
658 				IPFERROR(100009);
659 				error = EFAULT;
660 			}
661 		}
662 		break;
663 
664 	/*
665 	 * Turn logging of state information on/off.
666 	 */
667 	case SIOCSETLG :
668 		if (!(mode & FWRITE)) {
669 			IPFERROR(100010);
670 			error = EPERM;
671 		} else {
672 			error = BCOPYIN(data, &softs->ipf_state_logging,
673 					sizeof(softs->ipf_state_logging));
674 			if (error != 0) {
675 				IPFERROR(100011);
676 				error = EFAULT;
677 			}
678 		}
679 		break;
680 
681 	/*
682 	 * Return the current state of logging.
683 	 */
684 	case SIOCGETLG :
685 		error = BCOPYOUT(&softs->ipf_state_logging, data,
686 				 sizeof(softs->ipf_state_logging));
687 		if (error != 0) {
688 			IPFERROR(100012);
689 			error = EFAULT;
690 		}
691 		break;
692 
693 	/*
694 	 * Return the number of bytes currently waiting to be read.
695 	 */
696 	case FIONREAD :
697 		arg = ipf_log_bytesused(softc, IPL_LOGSTATE);
698 		error = BCOPYOUT(&arg, data, sizeof(arg));
699 		if (error != 0) {
700 			IPFERROR(100013);
701 			error = EFAULT;
702 		}
703 		break;
704 #endif
705 
706 	/*
707 	 * Get the current state statistics.
708 	 */
709 	case SIOCGETFS :
710 		error = ipf_outobj(softc, data, ipf_state_stats(softc),
711 				   IPFOBJ_STATESTAT);
712 		break;
713 
714 	/*
715 	 * Lock/Unlock the state table.  (Locking prevents any changes, which
716 	 * means no packets match).
717 	 */
718 	case SIOCSTLCK :
719 		if (!(mode & FWRITE)) {
720 			IPFERROR(100014);
721 			error = EPERM;
722 		} else {
723 			error = ipf_lock(data, &softs->ipf_state_lock);
724 		}
725 		break;
726 
727 	/*
728 	 * Add an entry to the current state table.
729 	 */
730 	case SIOCSTPUT :
731 		if (!softs->ipf_state_lock || !(mode &FWRITE)) {
732 			IPFERROR(100015);
733 			error = EACCES;
734 			break;
735 		}
736 		error = ipf_state_putent(softc, softs, data);
737 		break;
738 
739 	/*
740 	 * Get a state table entry.
741 	 */
742 	case SIOCSTGET :
743 		if (!softs->ipf_state_lock) {
744 			IPFERROR(100016);
745 			error = EACCES;
746 			break;
747 		}
748 		error = ipf_state_getent(softc, softs, data);
749 		break;
750 
751 	/*
752 	 * Return a copy of the hash table bucket lengths
753 	 */
754 	case SIOCSTAT1 :
755 		error = BCOPYOUT(softs->ipf_state_stats.iss_bucketlen, data,
756 				 softs->ipf_state_size * sizeof(u_int));
757 		if (error != 0) {
758 			IPFERROR(100017);
759 			error = EFAULT;
760 		}
761 		break;
762 
763 	case SIOCGENITER :
764 	    {
765 		ipftoken_t *token;
766 		ipfgeniter_t iter;
767 		ipfobj_t obj;
768 
769 		error = ipf_inobj(softc, data, &obj, &iter, IPFOBJ_GENITER);
770 		if (error != 0)
771 			break;
772 
773 		SPL_SCHED(s);
774 		token = ipf_token_find(softc, IPFGENITER_STATE, uid, ctx);
775 		if (token != NULL) {
776 			error = ipf_state_iter(softc, token, &iter, &obj);
777 			WRITE_ENTER(&softc->ipf_tokens);
778 			ipf_token_deref(softc, token);
779 			RWLOCK_EXIT(&softc->ipf_tokens);
780 		} else {
781 			IPFERROR(100018);
782 			error = ESRCH;
783 		}
784 		SPL_X(s);
785 		break;
786 	    }
787 
788 	case SIOCGTABL :
789 		error = ipf_state_gettable(softc, softs, data);
790 		break;
791 
792 	case SIOCIPFDELTOK :
793 		error = BCOPYIN(data, &arg, sizeof(arg));
794 		if (error != 0) {
795 			IPFERROR(100019);
796 			error = EFAULT;
797 		} else {
798 			SPL_SCHED(s);
799 			error = ipf_token_del(softc, arg, uid, ctx);
800 			SPL_X(s);
801 		}
802 		break;
803 
804 	case SIOCGTQTAB :
805 		error = ipf_outobj(softc, data, softs->ipf_state_tcptq,
806 				   IPFOBJ_STATETQTAB);
807 		break;
808 
809 	default :
810 		IPFERROR(100020);
811 		error = EINVAL;
812 		break;
813 	}
814 	return error;
815 }
816 
817 
818 /* ------------------------------------------------------------------------ */
819 /* Function:    ipf_state_getent                                            */
820 /* Returns:     int - 0 == success, != 0 == failure                         */
821 /* Parameters:  softc(I) - pointer to soft context main structure           */
822 /*              softs(I) - pointer to state context structure               */
823 /*              data(I)  - pointer to state structure to retrieve from table*/
824 /*                                                                          */
825 /* Copy out state information from the kernel to a user space process.  If  */
826 /* there is a filter rule associated with the state entry, copy that out    */
827 /* as well.  The entry to copy out is taken from the value of "ips_next" in */
828 /* the struct passed in and if not null and not found in the list of current*/
829 /* state entries, the retrieval fails.                                      */
830 /* ------------------------------------------------------------------------ */
831 static int
832 ipf_state_getent(ipf_main_softc_t *softc, ipf_state_softc_t *softs, void *data)
833 {
834 	ipstate_t *is, *isn;
835 	ipstate_save_t ips;
836 	int error;
837 
838 	error = ipf_inobj(softc, data, NULL, &ips, IPFOBJ_STATESAVE);
839 	if (error)
840 		return EFAULT;
841 
842 	READ_ENTER(&softc->ipf_state);
843 	isn = ips.ips_next;
844 	if (isn == NULL) {
845 		isn = softs->ipf_state_list;
846 		if (isn == NULL) {
847 			if (ips.ips_next == NULL) {
848 				RWLOCK_EXIT(&softc->ipf_state);
849 				IPFERROR(100021);
850 				return ENOENT;
851 			}
852 			return 0;
853 		}
854 	} else {
855 		/*
856 		 * Make sure the pointer we're copying from exists in the
857 		 * current list of entries.  Security precaution to prevent
858 		 * copying of random kernel data.
859 		 */
860 		for (is = softs->ipf_state_list; is; is = is->is_next)
861 			if (is == isn)
862 				break;
863 		if (!is) {
864 			RWLOCK_EXIT(&softc->ipf_state);
865 			IPFERROR(100022);
866 			return ESRCH;
867 		}
868 	}
869 	ips.ips_next = isn->is_next;
870 	bcopy((char *)isn, (char *)&ips.ips_is, sizeof(ips.ips_is));
871 	ips.ips_rule = isn->is_rule;
872 	if (isn->is_rule != NULL)
873 		bcopy((char *)isn->is_rule, (char *)&ips.ips_fr,
874 		      sizeof(ips.ips_fr));
875 	RWLOCK_EXIT(&softc->ipf_state);
876 	error = ipf_outobj(softc, data, &ips, IPFOBJ_STATESAVE);
877 	return error;
878 }
879 
880 
881 /* ------------------------------------------------------------------------ */
882 /* Function:    ipf_state_putent                                            */
883 /* Returns:     int - 0 == success, != 0 == failure                         */
884 /* Parameters:  softc(I) - pointer to soft context main structure           */
885 /*              softs(I) - pointer to state context structure               */
886 /*              data(I)  - pointer to state information struct              */
887 /*                                                                          */
888 /* This function implements the SIOCSTPUT ioctl: insert a state entry into  */
889 /* the state table.  If the state info. includes a pointer to a filter rule */
890 /* then also add in an orphaned rule (will not show up in any "ipfstat -io" */
891 /* output.                                                                  */
892 /* ------------------------------------------------------------------------ */
893 int
894 ipf_state_putent(ipf_main_softc_t *softc, ipf_state_softc_t *softs, void *data)
895 {
896 	ipstate_t *is, *isn;
897 	ipstate_save_t ips;
898 	int error, i;
899 	frentry_t *fr;
900 	char *name;
901 
902 	error = ipf_inobj(softc, data, NULL, &ips, IPFOBJ_STATESAVE);
903 	if (error != 0)
904 		return error;
905 
906 	KMALLOC(isn, ipstate_t *);
907 	if (isn == NULL) {
908 		IPFERROR(100023);
909 		return ENOMEM;
910 	}
911 
912 	bcopy((char *)&ips.ips_is, (char *)isn, sizeof(*isn));
913 	bzero((char *)isn, offsetof(struct ipstate, is_pkts));
914 	isn->is_sti.tqe_pnext = NULL;
915 	isn->is_sti.tqe_next = NULL;
916 	isn->is_sti.tqe_ifq = NULL;
917 	isn->is_sti.tqe_parent = isn;
918 	isn->is_ifp[0] = NULL;
919 	isn->is_ifp[1] = NULL;
920 	isn->is_ifp[2] = NULL;
921 	isn->is_ifp[3] = NULL;
922 	isn->is_sync = NULL;
923 	fr = ips.ips_rule;
924 
925 	if (fr == NULL) {
926 		int inserr;
927 
928 		READ_ENTER(&softc->ipf_state);
929 		inserr = ipf_state_insert(softc, isn, 0);
930 		MUTEX_EXIT(&isn->is_lock);
931 		RWLOCK_EXIT(&softc->ipf_state);
932 
933 		return inserr;
934 	}
935 
936 	if (isn->is_flags & SI_NEWFR) {
937 		KMALLOC(fr, frentry_t *);
938 		if (fr == NULL) {
939 			KFREE(isn);
940 			IPFERROR(100024);
941 			return ENOMEM;
942 		}
943 		bcopy((char *)&ips.ips_fr, (char *)fr, sizeof(*fr));
944 		isn->is_rule = fr;
945 		ips.ips_is.is_rule = fr;
946 		MUTEX_NUKE(&fr->fr_lock);
947 		MUTEX_INIT(&fr->fr_lock, "state filter rule lock");
948 
949 		/*
950 		 * Look up all the interface names in the rule.
951 		 */
952 		for (i = 0; i < 4; i++) {
953 			if (fr->fr_ifnames[i] == -1) {
954 				fr->fr_ifas[i] = NULL;
955 				continue;
956 			}
957 			name = fr->fr_names + fr->fr_ifnames[i];
958 			fr->fr_ifas[i] = ipf_resolvenic(softc, name,
959 							fr->fr_family);
960 		}
961 
962 		for (i = 0; i < 4; i++) {
963 			name = isn->is_ifname[i];
964 			isn->is_ifp[i] = ipf_resolvenic(softc, name,
965 							isn->is_v);
966 		}
967 
968 		fr->fr_ref = 0;
969 		fr->fr_dsize = 0;
970 		fr->fr_data = NULL;
971 		fr->fr_type = FR_T_NONE;
972 
973 		(void) ipf_resolvedest(softc, fr->fr_names, &fr->fr_tifs[0],
974 				fr->fr_family);
975 		(void) ipf_resolvedest(softc, fr->fr_names, &fr->fr_tifs[1],
976 				fr->fr_family);
977 		(void) ipf_resolvedest(softc, fr->fr_names, &fr->fr_dif,
978 				fr->fr_family);
979 
980 		/*
981 		 * send a copy back to userland of what we ended up
982 		 * to allow for verification.
983 		 */
984 		error = ipf_outobj(softc, data, &ips, IPFOBJ_STATESAVE);
985 		if (error != 0) {
986 			KFREE(isn);
987 			MUTEX_DESTROY(&fr->fr_lock);
988 			KFREE(fr);
989 			IPFERROR(100025);
990 			return EFAULT;
991 		}
992 		READ_ENTER(&softc->ipf_state);
993 		error = ipf_state_insert(softc, isn, 0);
994 		MUTEX_EXIT(&isn->is_lock);
995 		RWLOCK_EXIT(&softc->ipf_state);
996 
997 	} else {
998 		READ_ENTER(&softc->ipf_state);
999 		for (is = softs->ipf_state_list; is; is = is->is_next)
1000 			if (is->is_rule == fr) {
1001 				error = ipf_state_insert(softc, isn, 0);
1002 				MUTEX_EXIT(&isn->is_lock);
1003 				break;
1004 			}
1005 
1006 		if (is == NULL) {
1007 			KFREE(isn);
1008 			isn = NULL;
1009 		}
1010 		RWLOCK_EXIT(&softc->ipf_state);
1011 
1012 		if (isn == NULL) {
1013 			IPFERROR(100033);
1014 			error = ESRCH;
1015 		}
1016 	}
1017 
1018 	return error;
1019 }
1020 
1021 
1022 /* ------------------------------------------------------------------------ */
1023 /* Function:    ipf_state_insert                                            */
1024 /* Returns:     int    - 0 == success, -1 == failure                        */
1025 /* Parameters:  softc(I) - pointer to soft context main structure           */
1026 /* Parameters:  is(I)    - pointer to state structure                       */
1027 /*              rev(I) - flag indicating direction of packet                */
1028 /*                                                                          */
1029 /* Inserts a state structure into the hash table (for lookups) and the list */
1030 /* of state entries (for enumeration).  Resolves all of the interface names */
1031 /* to pointers and adjusts running stats for the hash table as appropriate. */
1032 /*                                                                          */
1033 /* This function can fail if the filter rule has had a population policy of */
1034 /* IP addresses used with stateful filtering assigned to it.                */
1035 /*                                                                          */
1036 /* Locking: it is assumed that some kind of lock on ipf_state is held.      */
1037 /*          Exits with is_lock initialised and held - *EVEN IF ERROR*.      */
1038 /* ------------------------------------------------------------------------ */
1039 int
1040 ipf_state_insert(ipf_main_softc_t *softc, ipstate_t *is, int rev)
1041 {
1042 	ipf_state_softc_t *softs = softc->ipf_state_soft;
1043 	frentry_t *fr;
1044 	u_int hv;
1045 	int i;
1046 
1047 	/*
1048 	 * Look up all the interface names in the state entry.
1049 	 */
1050 	for (i = 0; i < 4; i++) {
1051 		if (is->is_ifp[i] != NULL)
1052 			continue;
1053 		is->is_ifp[i] = ipf_resolvenic(softc, is->is_ifname[i],
1054 					       is->is_v);
1055 	}
1056 
1057 	/*
1058 	 * If we could trust is_hv, then the modulus would not be needed,
1059 	 * but when running with IPFILTER_SYNC, this stops bad values.
1060 	 */
1061 	hv = is->is_hv % softs->ipf_state_size;
1062 	/* TRACE is, hv */
1063 	is->is_hv = hv;
1064 
1065 	/*
1066 	 * We need to get both of these locks...the first because it is
1067 	 * possible that once the insert is complete another packet might
1068 	 * come along, match the entry and want to update it.
1069 	 */
1070 	MUTEX_INIT(&is->is_lock, "ipf state entry");
1071 	MUTEX_ENTER(&is->is_lock);
1072 	MUTEX_ENTER(&softs->ipf_stinsert);
1073 
1074 	fr = is->is_rule;
1075 	if (fr != NULL) {
1076 		if ((fr->fr_srctrack.ht_max_nodes != 0) &&
1077 		    (ipf_ht_node_add(softc, &fr->fr_srctrack,
1078 				     is->is_family, &is->is_src) == -1)) {
1079 			SBUMPD(ipf_state_stats, iss_max_track);
1080 			MUTEX_EXIT(&softs->ipf_stinsert);
1081 			return -1;
1082 		}
1083 
1084 		MUTEX_ENTER(&fr->fr_lock);
1085 		fr->fr_ref++;
1086 		MUTEX_EXIT(&fr->fr_lock);
1087 		fr->fr_statecnt++;
1088 	}
1089 
1090 	if (is->is_flags & (SI_WILDP|SI_WILDA)) {
1091 		DT(iss_wild_plus_one);
1092 		SINCL(ipf_state_stats.iss_wild);
1093 	}
1094 
1095 	SBUMP(ipf_state_stats.iss_proto[is->is_p]);
1096 	SBUMP(ipf_state_stats.iss_active_proto[is->is_p]);
1097 
1098 	/*
1099 	 * add into list table.
1100 	 */
1101 	if (softs->ipf_state_list != NULL)
1102 		softs->ipf_state_list->is_pnext = &is->is_next;
1103 	is->is_pnext = &softs->ipf_state_list;
1104 	is->is_next = softs->ipf_state_list;
1105 	softs->ipf_state_list = is;
1106 
1107 	if (softs->ipf_state_table[hv] != NULL)
1108 		softs->ipf_state_table[hv]->is_phnext = &is->is_hnext;
1109 	else
1110 		softs->ipf_state_stats.iss_inuse++;
1111 	is->is_phnext = softs->ipf_state_table + hv;
1112 	is->is_hnext = softs->ipf_state_table[hv];
1113 	softs->ipf_state_table[hv] = is;
1114 	softs->ipf_state_stats.iss_bucketlen[hv]++;
1115 	softs->ipf_state_stats.iss_active++;
1116 	MUTEX_EXIT(&softs->ipf_stinsert);
1117 
1118 	ipf_state_setqueue(softc, is, rev);
1119 
1120 	return 0;
1121 }
1122 
1123 
1124 /* ------------------------------------------------------------------------ */
1125 /* Function:    ipf_state_matchipv4addrs                                    */
1126 /* Returns:     int - 2 addresses match (strong match), 1 reverse match,    */
1127 /*                    0 no match                                            */
1128 /* Parameters:  is1, is2 pointers to states we are checking                 */
1129 /*                                                                          */
1130 /* Function matches IPv4 addresses it returns strong match for ICMP proto   */
1131 /* even there is only reverse match                                         */
1132 /* ------------------------------------------------------------------------ */
1133 static int
1134 ipf_state_matchipv4addrs(ipstate_t *is1, ipstate_t *is2)
1135 {
1136 	int	rv;
1137 
1138 	if (is1->is_saddr == is2->is_saddr && is1->is_daddr == is2->is_daddr)
1139 		rv = 2;
1140 	else if (is1->is_saddr == is2->is_daddr &&
1141 	    is1->is_daddr == is2->is_saddr) {
1142 		/* force strong match for ICMP protocol */
1143 		rv = (is1->is_p == IPPROTO_ICMP) ? 2 : 1;
1144 	}
1145 	else
1146 		rv = 0;
1147 
1148 	return (rv);
1149 }
1150 
1151 
1152 /* ------------------------------------------------------------------------ */
1153 /* Function:    ipf_state_matchipv6addrs                                    */
1154 /* Returns:     int - 2 addresses match (strong match), 1 reverse match,    */
1155 /*                    0 no match                                            */
1156 /* Parameters:  is1, is2 pointers to states we are checking                 */
1157 /*                                                                          */
1158 /* Function matches IPv6 addresses it returns strong match for ICMP proto   */
1159 /* even there is only reverse match                                         */
1160 /* ------------------------------------------------------------------------ */
1161 static int
1162 ipf_state_matchipv6addrs(ipstate_t *is1, ipstate_t *is2)
1163 {
1164 	int	rv;
1165 
1166 	if (IP6_EQ(&is1->is_src, &is2->is_src) &&
1167 	    IP6_EQ(&is1->is_dst, &is2->is_dst))
1168 		rv = 2;
1169 	else if (IP6_EQ(&is1->is_src, &is2->is_dst) &&
1170 	    IP6_EQ(&is1->is_dst, &is2->is_src)) {
1171 		/* force strong match for ICMPv6 protocol */
1172 		rv = (is1->is_p == IPPROTO_ICMPV6) ? 2 : 1;
1173 	}
1174 	else
1175 		rv = 0;
1176 
1177 	return (rv);
1178 }
1179 
1180 
1181 /* ------------------------------------------------------------------------ */
1182 /* Function:    ipf_state_matchaddresses                                    */
1183 /* Returns:     int - 2 addresses match, 1 reverse match, zero no match     */
1184 /* Parameters:  is1, is2 pointers to states we are checking                 */
1185 /*                                                                          */
1186 /* function retruns true if two pairs of addresses belong to single         */
1187 /* connection. suppose there are two endpoints:                             */
1188 /*      endpoint1 1.1.1.1                                                   */
1189 /*      endpoint2 1.1.1.2                                                   */
1190 /*                                                                          */
1191 /* the state is established by packet flying from .1 to .2 so we see:       */
1192 /*      is1->src = 1.1.1.1                                                  */
1193 /*      is1->dst = 1.1.1.2                                                  */
1194 /* now endpoint 1.1.1.2 sends answer                                        */
1195 /* retreives is1 record created by first packat and compares it with is2    */
1196 /* temporal record, is2 is initialized as follows:                          */
1197 /*      is2->src = 1.1.1.2                                                  */
1198 /*      is2->dst = 1.1.1.1                                                  */
1199 /* in this case 1 will be returned                                          */
1200 /*                                                                          */
1201 /* the ipf_matchaddresses() assumes those two records to be same. of course */
1202 /* the ipf_matchaddresses() also assume records are same in case you pass   */
1203 /* identical arguments (i.e. ipf_matchaddress(is1, is1) would return 2      */
1204 /* ------------------------------------------------------------------------ */
1205 static int
1206 ipf_state_matchaddresses(ipstate_t *is1, ipstate_t *is2)
1207 {
1208 	int	rv;
1209 
1210 	if (is1->is_v == 4) {
1211 		rv = ipf_state_matchipv4addrs(is1, is2);
1212 	}
1213 	else {
1214 		rv = ipf_state_matchipv6addrs(is1, is2);
1215 	}
1216 
1217 	return (rv);
1218 }
1219 
1220 
1221 /* ------------------------------------------------------------------------ */
1222 /* Function:    ipf_matchports                                              */
1223 /* Returns:     int - 2 match, 1 rverse match, 0 no match                   */
1224 /* Parameters:  ppairs1, ppairs - src, dst ports we want to match           */
1225 /*                                                                          */
1226 /* performs the same match for isps members as for addresses                */
1227 /* ------------------------------------------------------------------------ */
1228 static int
1229 ipf_state_matchports(udpinfo_t *ppairs1, udpinfo_t *ppairs2)
1230 {
1231 	int	rv;
1232 
1233 	if (ppairs1->us_sport == ppairs2->us_sport &&
1234 	    ppairs1->us_dport == ppairs2->us_dport)
1235 		rv = 2;
1236 	else if (ppairs1->us_sport == ppairs2->us_dport &&
1237 		    ppairs1->us_dport == ppairs2->us_sport)
1238 		rv = 1;
1239 	else
1240 		rv = 0;
1241 
1242 	return (rv);
1243 }
1244 
1245 
1246 /* ------------------------------------------------------------------------ */
1247 /* Function:    ipf_matchisps                                               */
1248 /* Returns:     int - nonzero if isps members match, 0 nomatch              */
1249 /* Parameters:  is1, is2 - states we want to match                          */
1250 /*                                                                          */
1251 /* performs the same match for isps members as for addresses                */
1252 /* ------------------------------------------------------------------------ */
1253 static int
1254 ipf_state_matchisps(ipstate_t *is1, ipstate_t *is2)
1255 {
1256 	int	rv;
1257 
1258 	if (is1->is_p == is2->is_p) {
1259 		switch (is1->is_p)
1260 		{
1261 		case IPPROTO_TCP :
1262 		case IPPROTO_UDP :
1263 		case IPPROTO_GRE :
1264 			/* greinfo_t can be also interprted as port pair */
1265 			rv = ipf_state_matchports(&is1->is_ps.is_us,
1266 						  &is2->is_ps.is_us);
1267 			break;
1268 
1269 		case IPPROTO_ICMP :
1270 		case IPPROTO_ICMPV6 :
1271 			/* force strong match for ICMP datagram. */
1272 			if (bcmp(&is1->is_ps, &is2->is_ps,
1273 				 sizeof(icmpinfo_t)) == 0)  {
1274 				rv = 2;
1275 			} else {
1276 				rv = 0;
1277 			}
1278 			break;
1279 
1280 		default:
1281 			rv = 0;
1282 		}
1283 	} else {
1284 		rv = 0;
1285 	}
1286 
1287 	return (rv);
1288 }
1289 
1290 
1291 /* ------------------------------------------------------------------------ */
1292 /* Function:    ipf_state_match                                             */
1293 /* Returns:     int - nonzero match, zero no match                          */
1294 /* Parameters:  is1, is2 - states we want to match                          */
1295 /*                                                                          */
1296 /* ------------------------------------------------------------------------ */
1297 static int
1298 ipf_state_match(ipstate_t *is1, ipstate_t *is2)
1299 {
1300 	int	rv;
1301 	int	amatch;
1302 	int	pomatch;
1303 
1304 	if (bcmp(&is1->is_pass, &is2->is_pass,
1305 		 offsetof(struct ipstate, is_authmsk) -
1306 		 offsetof(struct ipstate, is_pass)) == 0) {
1307 
1308 		pomatch = ipf_state_matchisps(is1, is2);
1309 		amatch = ipf_state_matchaddresses(is1, is2);
1310 		rv = (amatch != 0) && (amatch == pomatch);
1311 	} else {
1312 		rv = 0;
1313 	}
1314 
1315 	return (rv);
1316 }
1317 
1318 /* ------------------------------------------------------------------------ */
1319 /* Function:    ipf_state_add                                               */
1320 /* Returns:     ipstate_t - 0 = success                                     */
1321 /* Parameters:  softc(I)  - pointer to soft context main structure          */
1322 /*              fin(I)    - pointer to packet information                   */
1323 /*              stsave(O) - pointer to place to save pointer to created     */
1324 /*                          state structure.                                */
1325 /*              flags(I)  - flags to use when creating the structure        */
1326 /*                                                                          */
1327 /* Creates a new IP state structure from the packet information collected.  */
1328 /* Inserts it into the state table and appends to the bottom of the active  */
1329 /* list.  If the capacity of the table has reached the maximum allowed then */
1330 /* the call will fail and a flush is scheduled for the next timeout call.   */
1331 /*                                                                          */
1332 /* NOTE: The use of stsave to point to nat_state will result in memory      */
1333 /*       corruption.  It should only be used to point to objects that will  */
1334 /*       either outlive this (not expired) or will deref the ip_state_t     */
1335 /*       when they are deleted.                                             */
1336 /* ------------------------------------------------------------------------ */
1337 int
1338 ipf_state_add(ipf_main_softc_t *softc, fr_info_t *fin, ipstate_t **stsave,
1339     u_int flags)
1340 {
1341 	ipf_state_softc_t *softs = softc->ipf_state_soft;
1342 	ipstate_t *is, ips;
1343 	struct icmp *ic;
1344 	u_int pass, hv;
1345 	frentry_t *fr;
1346 	tcphdr_t *tcp;
1347 	frdest_t *fdp;
1348 	int out;
1349 
1350 	/*
1351 	 * If a packet that was created locally is trying to go out but we
1352 	 * do not match here because of this lock, it is likely that
1353 	 * the policy will block it and return network unreachable back up
1354 	 * the stack. To mitigate this error, EAGAIN is returned instead,
1355 	 * telling the IP stack to try sending this packet again later.
1356 	 */
1357 	if (softs->ipf_state_lock) {
1358 		SBUMPD(ipf_state_stats, iss_add_locked);
1359 		fin->fin_error = EAGAIN;
1360 		return -1;
1361 	}
1362 
1363 	if (fin->fin_flx & (FI_SHORT|FI_STATE|FI_FRAGBODY|FI_BAD)) {
1364 		SBUMPD(ipf_state_stats, iss_add_bad);
1365 		return -1;
1366 	}
1367 
1368 	if ((fin->fin_flx & FI_OOW) && !(fin->fin_tcpf & TH_SYN)) {
1369 		SBUMPD(ipf_state_stats, iss_add_oow);
1370 		return -1;
1371 	}
1372 
1373 	if ((softs->ipf_state_stats.iss_active * 100 / softs->ipf_state_max) >
1374 	    softs->ipf_state_wm_high) {
1375 		softs->ipf_state_doflush = 1;
1376 	}
1377 
1378 	/*
1379 	 * If a "keep state" rule has reached the maximum number of references
1380 	 * to it, then schedule an automatic flush in case we can clear out
1381 	 * some "dead old wood".  Note that because the lock isn't held on
1382 	 * fr it is possible that we could overflow.  The cost of overflowing
1383 	 * is being ignored here as the number by which it can overflow is
1384 	 * a product of the number of simultaneous threads that could be
1385 	 * executing in here, so a limit of 100 won't result in 200, but could
1386 	 * result in 101 or 102.
1387 	 */
1388 	fr = fin->fin_fr;
1389 	if (fr != NULL) {
1390 		if ((softs->ipf_state_stats.iss_active >=
1391 		     softs->ipf_state_max) && (fr->fr_statemax == 0)) {
1392 			SBUMPD(ipf_state_stats, iss_max);
1393 			return 1;
1394 		}
1395 		if ((fr->fr_statemax != 0) &&
1396 		    (fr->fr_statecnt >= fr->fr_statemax)) {
1397 			SBUMPD(ipf_state_stats, iss_max_ref);
1398 			return 2;
1399 		}
1400 	}
1401 
1402 	is = &ips;
1403 	if (fr == NULL) {
1404 		pass = softc->ipf_flags;
1405 		is->is_tag = FR_NOLOGTAG;
1406 	} else {
1407 		pass = fr->fr_flags;
1408 	}
1409 
1410 	ic = NULL;
1411 	tcp = NULL;
1412 	out = fin->fin_out;
1413 	bzero((char *)is, sizeof(*is));
1414 	is->is_die = 1 + softc->ipf_ticks;
1415 	/*
1416 	 * We want to check everything that is a property of this packet,
1417 	 * but we don't (automatically) care about its fragment status as
1418 	 * this may change.
1419 	 */
1420 	is->is_pass = pass;
1421 	is->is_v = fin->fin_v;
1422 	is->is_sec = fin->fin_secmsk;
1423 	is->is_secmsk = 0xffff;
1424 	is->is_auth = fin->fin_auth;
1425 	is->is_authmsk = 0xffff;
1426 	is->is_family = fin->fin_family;
1427 	is->is_opt[0] = fin->fin_optmsk;
1428 	is->is_optmsk[0] = 0xffffffff;
1429 	if (is->is_v == 6) {
1430 		is->is_opt[0] &= ~0x8;
1431 		is->is_optmsk[0] &= ~0x8;
1432 	}
1433 
1434 	/*
1435 	 * Copy and calculate...
1436 	 */
1437 	hv = (is->is_p = fin->fin_fi.fi_p);
1438 	is->is_src = fin->fin_fi.fi_src;
1439 	hv += is->is_saddr;
1440 	is->is_dst = fin->fin_fi.fi_dst;
1441 	hv += is->is_daddr;
1442 #ifdef	USE_INET6
1443 	if (fin->fin_v == 6) {
1444 		/*
1445 		 * For ICMPv6, we check to see if the destination address is
1446 		 * a multicast address.  If it is, do not include it in the
1447 		 * calculation of the hash because the correct reply will come
1448 		 * back from a real address, not a multicast address.
1449 		 */
1450 		if ((is->is_p == IPPROTO_ICMPV6) &&
1451 		    IN6_IS_ADDR_MULTICAST(&is->is_dst.in6)) {
1452 			/*
1453 			 * So you can do keep state with neighbour discovery.
1454 			 *
1455 			 * Here we could use the address from the neighbour
1456 			 * solicit message to put in the state structure and
1457 			 * we could use that without a wildcard flag too...
1458 			 */
1459 			flags |= SI_W_DADDR;
1460 			hv -= is->is_daddr;
1461 		} else {
1462 			hv += is->is_dst.i6[1];
1463 			hv += is->is_dst.i6[2];
1464 			hv += is->is_dst.i6[3];
1465 		}
1466 		hv += is->is_src.i6[1];
1467 		hv += is->is_src.i6[2];
1468 		hv += is->is_src.i6[3];
1469 	}
1470 #endif
1471 	if ((fin->fin_v == 4) &&
1472 	    (fin->fin_flx & (FI_MULTICAST|FI_BROADCAST|FI_MBCAST))) {
1473 		flags |= SI_W_DADDR;
1474 		hv -= is->is_daddr;
1475 	}
1476 
1477 	switch (is->is_p)
1478 	{
1479 #ifdef	USE_INET6
1480 	case IPPROTO_ICMPV6 :
1481 		ic = fin->fin_dp;
1482 
1483 		switch (ic->icmp_type)
1484 		{
1485 		case ICMP6_ECHO_REQUEST :
1486 			hv += (is->is_icmp.ici_id = ic->icmp_id);
1487 			/*FALLTHROUGH*/
1488 		case ICMP6_MEMBERSHIP_QUERY :
1489 		case ND_ROUTER_SOLICIT :
1490 		case ND_NEIGHBOR_SOLICIT :
1491 		case ICMP6_NI_QUERY :
1492 			is->is_icmp.ici_type = ic->icmp_type;
1493 			break;
1494 		default :
1495 			SBUMPD(ipf_state_stats, iss_icmp6_notquery);
1496 			return -2;
1497 		}
1498 		break;
1499 #endif
1500 	case IPPROTO_ICMP :
1501 		ic = fin->fin_dp;
1502 
1503 		switch (ic->icmp_type)
1504 		{
1505 		case ICMP_ECHO :
1506 		case ICMP_TSTAMP :
1507 		case ICMP_IREQ :
1508 		case ICMP_MASKREQ :
1509 			is->is_icmp.ici_type = ic->icmp_type;
1510 			hv += (is->is_icmp.ici_id = ic->icmp_id);
1511 			break;
1512 		default :
1513 			SBUMPD(ipf_state_stats, iss_icmp_notquery);
1514 			return -3;
1515 		}
1516 		break;
1517 
1518 #if 0
1519 	case IPPROTO_GRE :
1520 		gre = fin->fin_dp;
1521 
1522 		is->is_gre.gs_flags = gre->gr_flags;
1523 		is->is_gre.gs_ptype = gre->gr_ptype;
1524 		if (GRE_REV(is->is_gre.gs_flags) == 1) {
1525 			is->is_call[0] = fin->fin_data[0];
1526 			is->is_call[1] = fin->fin_data[1];
1527 		}
1528 		break;
1529 #endif
1530 
1531 	case IPPROTO_TCP :
1532 		tcp = fin->fin_dp;
1533 
1534 		if (tcp->th_flags & TH_RST) {
1535 			SBUMPD(ipf_state_stats, iss_tcp_rstadd);
1536 			return -4;
1537 		}
1538 
1539 		/* TRACE is, flags, hv */
1540 
1541 		/*
1542 		 * The endian of the ports doesn't matter, but the ack and
1543 		 * sequence numbers do as we do mathematics on them later.
1544 		 */
1545 		is->is_sport = htons(fin->fin_data[0]);
1546 		is->is_dport = htons(fin->fin_data[1]);
1547 		if ((flags & (SI_W_DPORT|SI_W_SPORT)) == 0) {
1548 			hv += is->is_sport;
1549 			hv += is->is_dport;
1550 		}
1551 
1552 		/* TRACE is, flags, hv */
1553 
1554 		/*
1555 		 * If this is a real packet then initialise fields in the
1556 		 * state information structure from the TCP header information.
1557 		 */
1558 
1559 		is->is_maxdwin = 1;
1560 		is->is_maxswin = ntohs(tcp->th_win);
1561 		if (is->is_maxswin == 0)
1562 			is->is_maxswin = 1;
1563 
1564 		if ((fin->fin_flx & FI_IGNORE) == 0) {
1565 			is->is_send = ntohl(tcp->th_seq) + fin->fin_dlen -
1566 				      (TCP_OFF(tcp) << 2) +
1567 				      ((tcp->th_flags & TH_SYN) ? 1 : 0) +
1568 				      ((tcp->th_flags & TH_FIN) ? 1 : 0);
1569 			is->is_maxsend = is->is_send;
1570 
1571 			/*
1572 			 * Window scale option is only present in
1573 			 * SYN/SYN-ACK packet.
1574 			 */
1575 			if ((tcp->th_flags & ~(TH_FIN|TH_ACK|TH_ECNALL)) ==
1576 			    TH_SYN &&
1577 			    (TCP_OFF(tcp) > (sizeof(tcphdr_t) >> 2))) {
1578 				if (ipf_tcpoptions(softs, fin, tcp,
1579 					      &is->is_tcp.ts_data[0]) == -1)
1580 					fin->fin_flx |= FI_BAD;
1581 			}
1582 
1583 			if ((fin->fin_out != 0) && (pass & FR_NEWISN) != 0) {
1584 				ipf_checknewisn(fin, is);
1585 				ipf_fixoutisn(fin, is);
1586 			}
1587 
1588 			if ((tcp->th_flags & TH_OPENING) == TH_SYN)
1589 				flags |= IS_TCPFSM;
1590 			else {
1591 				is->is_maxdwin = is->is_maxswin * 2;
1592 				is->is_dend = ntohl(tcp->th_ack);
1593 				is->is_maxdend = ntohl(tcp->th_ack);
1594 				is->is_maxdwin *= 2;
1595 			}
1596 		}
1597 
1598 		/*
1599 		 * If we're creating state for a starting connection, start
1600 		 * the timer on it as we'll never see an error if it fails
1601 		 * to connect.
1602 		 */
1603 		break;
1604 
1605 	case IPPROTO_UDP :
1606 		tcp = fin->fin_dp;
1607 
1608 		is->is_sport = htons(fin->fin_data[0]);
1609 		is->is_dport = htons(fin->fin_data[1]);
1610 		if ((flags & (SI_W_DPORT|SI_W_SPORT)) == 0) {
1611 			hv += tcp->th_dport;
1612 			hv += tcp->th_sport;
1613 		}
1614 		break;
1615 
1616 	default :
1617 		break;
1618 	}
1619 	hv = DOUBLE_HASH(hv);
1620 	is->is_hv = hv;
1621 
1622 	/*
1623 	 * Look for identical state.
1624 	 */
1625 	for (is = softs->ipf_state_table[hv % softs->ipf_state_size];
1626 	     is != NULL; is = is->is_hnext) {
1627 		if (ipf_state_match(&ips, is) == 1)
1628 			break;
1629 	}
1630 	if (is != NULL) {
1631 		SBUMPD(ipf_state_stats, iss_add_dup);
1632 		return 3;
1633 	}
1634 
1635 	if (softs->ipf_state_stats.iss_bucketlen[hv] >=
1636 	    softs->ipf_state_maxbucket) {
1637 		SBUMPD(ipf_state_stats, iss_bucket_full);
1638 		return 4;
1639 	}
1640 
1641 	/*
1642 	 * No existing state; create new
1643 	 */
1644 	KMALLOC(is, ipstate_t *);
1645 	if (is == NULL) {
1646 		SBUMPD(ipf_state_stats, iss_nomem);
1647 		return 5;
1648 	}
1649 	bcopy((char *)&ips, (char *)is, sizeof(*is));
1650 	is->is_flags = flags & IS_INHERITED;
1651 	is->is_rulen = fin->fin_rule;
1652 	is->is_rule = fr;
1653 
1654 	/*
1655 	 * Do not do the modulus here, it is done in ipf_state_insert().
1656 	 */
1657 	if (fr != NULL) {
1658 		ipftq_t *tq;
1659 
1660 		(void) strncpy(is->is_group, FR_NAME(fr, fr_group),
1661 			       FR_GROUPLEN);
1662 		if (fr->fr_age[0] != 0) {
1663 			tq = ipf_addtimeoutqueue(softc,
1664 						 &softs->ipf_state_usertq,
1665 						 fr->fr_age[0]);
1666 			is->is_tqehead[0] = tq;
1667 			is->is_sti.tqe_flags |= TQE_RULEBASED;
1668 		}
1669 		if (fr->fr_age[1] != 0) {
1670 			tq = ipf_addtimeoutqueue(softc,
1671 						 &softs->ipf_state_usertq,
1672 						 fr->fr_age[1]);
1673 			is->is_tqehead[1] = tq;
1674 			is->is_sti.tqe_flags |= TQE_RULEBASED;
1675 		}
1676 
1677 		is->is_tag = fr->fr_logtag;
1678 	}
1679 
1680 	/*
1681 	 * It may seem strange to set is_ref to 2, but if stsave is not NULL
1682 	 * then a copy of the pointer is being stored somewhere else and in
1683 	 * the end, it will expect to be able to do something with it.
1684 	 */
1685 	is->is_me = stsave;
1686 	if (stsave != NULL) {
1687 		*stsave = is;
1688 		is->is_ref = 2;
1689 	} else {
1690 		is->is_ref = 1;
1691 	}
1692 	is->is_pkts[0] = 0, is->is_bytes[0] = 0;
1693 	is->is_pkts[1] = 0, is->is_bytes[1] = 0;
1694 	is->is_pkts[2] = 0, is->is_bytes[2] = 0;
1695 	is->is_pkts[3] = 0, is->is_bytes[3] = 0;
1696 	if ((fin->fin_flx & FI_IGNORE) == 0) {
1697 		is->is_pkts[out] = 1;
1698 		fin->fin_pktnum = 1;
1699 		is->is_bytes[out] = fin->fin_plen;
1700 		is->is_flx[out][0] = fin->fin_flx & FI_CMP;
1701 		is->is_flx[out][0] &= ~FI_OOW;
1702 	}
1703 
1704 	if (pass & FR_STLOOSE)
1705 		is->is_flags |= IS_LOOSE;
1706 
1707 	if (pass & FR_STSTRICT)
1708 		is->is_flags |= IS_STRICT;
1709 
1710 	if (pass & FR_STATESYNC)
1711 		is->is_flags |= IS_STATESYNC;
1712 
1713 	if (pass & FR_LOGFIRST)
1714 		is->is_pass &= ~(FR_LOGFIRST|FR_LOG);
1715 
1716 	READ_ENTER(&softc->ipf_state);
1717 
1718 	if (ipf_state_insert(softc, is, fin->fin_rev) == -1) {
1719 		RWLOCK_EXIT(&softc->ipf_state);
1720 		/*
1721 		 * This is a bit more manual than it should be but
1722 		 * ipf_state_del cannot be called.
1723 		 */
1724 		MUTEX_EXIT(&is->is_lock);
1725 		MUTEX_DESTROY(&is->is_lock);
1726 		if (is->is_tqehead[0] != NULL) {
1727 			if (ipf_deletetimeoutqueue(is->is_tqehead[0]) == 0)
1728 				ipf_freetimeoutqueue(softc, is->is_tqehead[0]);
1729 			is->is_tqehead[0] = NULL;
1730 		}
1731 		if (is->is_tqehead[1] != NULL) {
1732 			if (ipf_deletetimeoutqueue(is->is_tqehead[1]) == 0)
1733 				ipf_freetimeoutqueue(softc, is->is_tqehead[1]);
1734 			is->is_tqehead[1] = NULL;
1735 		}
1736 		KFREE(is);
1737 		return -1;
1738 	}
1739 
1740 	/*
1741 	 * Filling in the interface name is after the insert so that an
1742 	 * event (such as add/delete) of an interface that is referenced
1743 	 * by this rule will see this state entry.
1744 	 */
1745 	if (fr != NULL) {
1746 		/*
1747 		 * The name '-' is special for network interfaces and causes
1748 		 * a NULL name to be present, always, allowing packets to
1749 		 * match it, regardless of their interface.
1750 		 */
1751 		if ((fin->fin_ifp == NULL) ||
1752 		    (fr->fr_ifnames[out << 1] != -1 &&
1753 		     fr->fr_names[fr->fr_ifnames[out << 1] + 0] == '-' &&
1754 		     fr->fr_names[fr->fr_ifnames[out << 1] + 1] == '\0')) {
1755 			is->is_ifp[out << 1] = fr->fr_ifas[0];
1756 			strncpy(is->is_ifname[out << 1],
1757 				fr->fr_names + fr->fr_ifnames[0],
1758 				sizeof(fr->fr_ifnames[0]));
1759 		} else {
1760 			is->is_ifp[out << 1] = fin->fin_ifp;
1761 			COPYIFNAME(fin->fin_v, fin->fin_ifp,
1762 				   is->is_ifname[out << 1]);
1763 		}
1764 
1765 		is->is_ifp[(out << 1) + 1] = fr->fr_ifas[1];
1766 		if (fr->fr_ifnames[1] != -1) {
1767 			strncpy(is->is_ifname[(out << 1) + 1],
1768 				fr->fr_names + fr->fr_ifnames[1],
1769 				sizeof(fr->fr_ifnames[1]));
1770 		}
1771 
1772 		is->is_ifp[(1 - out) << 1] = fr->fr_ifas[2];
1773 		if (fr->fr_ifnames[2] != -1) {
1774 			strncpy(is->is_ifname[((1 - out) << 1)],
1775 				fr->fr_names + fr->fr_ifnames[2],
1776 				sizeof(fr->fr_ifnames[2]));
1777 		}
1778 
1779 		is->is_ifp[((1 - out) << 1) + 1] = fr->fr_ifas[3];
1780 		if (fr->fr_ifnames[3] != -1) {
1781 			strncpy(is->is_ifname[((1 - out) << 1) + 1],
1782 				fr->fr_names + fr->fr_ifnames[3],
1783 				sizeof(fr->fr_ifnames[3]));
1784 		}
1785 	} else {
1786 		if (fin->fin_ifp != NULL) {
1787 			is->is_ifp[out << 1] = fin->fin_ifp;
1788 			COPYIFNAME(fin->fin_v, fin->fin_ifp,
1789 				   is->is_ifname[out << 1]);
1790 		}
1791 	}
1792 
1793 	if (fin->fin_p == IPPROTO_TCP) {
1794 		/*
1795 		* If we're creating state for a starting connection, start the
1796 		* timer on it as we'll never see an error if it fails to
1797 		* connect.
1798 		*/
1799 		(void) ipf_tcp_age(&is->is_sti, fin, softs->ipf_state_tcptq,
1800 				   is->is_flags, 2);
1801 	}
1802 	MUTEX_EXIT(&is->is_lock);
1803 	if ((is->is_flags & IS_STATESYNC) && ((is->is_flags & SI_CLONE) == 0))
1804 		is->is_sync = ipf_sync_new(softc, SMC_STATE, fin, is);
1805 	if (softs->ipf_state_logging)
1806 		ipf_state_log(softc, is, ISL_NEW);
1807 
1808 	RWLOCK_EXIT(&softc->ipf_state);
1809 
1810 	fin->fin_flx |= FI_STATE;
1811 	if (fin->fin_flx & FI_FRAG)
1812 		(void) ipf_frag_new(softc, fin, pass);
1813 
1814 	fdp = &fr->fr_tifs[0];
1815 	if (fdp->fd_type == FRD_DSTLIST) {
1816 		ipf_dstlist_select_node(fin, fdp->fd_ptr, NULL,
1817 					&is->is_tifs[0]);
1818 	} else {
1819 		bcopy(fdp, &is->is_tifs[0], sizeof(*fdp));
1820 	}
1821 
1822 	fdp = &fr->fr_tifs[1];
1823 	if (fdp->fd_type == FRD_DSTLIST) {
1824 		ipf_dstlist_select_node(fin, fdp->fd_ptr, NULL,
1825 					&is->is_tifs[1]);
1826 	} else {
1827 		bcopy(fdp, &is->is_tifs[1], sizeof(*fdp));
1828 	}
1829 	fin->fin_tif = &is->is_tifs[fin->fin_rev];
1830 
1831 	fdp = &fr->fr_dif;
1832 	if (fdp->fd_type == FRD_DSTLIST) {
1833 		ipf_dstlist_select_node(fin, fdp->fd_ptr, NULL,
1834 					&is->is_dif);
1835 	} else {
1836 		bcopy(fdp, &is->is_dif, sizeof(*fdp));
1837 	}
1838 	fin->fin_dif = &is->is_dif;
1839 
1840 	return 0;
1841 }
1842 
1843 
1844 /* ------------------------------------------------------------------------ */
1845 /* Function:    ipf_tcpoptions                                              */
1846 /* Returns:     int - 1 == packet matches state entry, 0 == it does not,    */
1847 /*                   -1 == packet has bad TCP options data                  */
1848 /* Parameters:  softs(I) - pointer to state context structure               */
1849 /*              fin(I) - pointer to packet information                      */
1850 /*              tcp(I) - pointer to TCP packet header                       */
1851 /*              td(I)  - pointer to TCP data held as part of the state      */
1852 /*                                                                          */
1853 /* Look after the TCP header for any options and deal with those that are   */
1854 /* present.  Record details about those that we recogise.                   */
1855 /* ------------------------------------------------------------------------ */
1856 static int
1857 ipf_tcpoptions(ipf_state_softc_t *softs, fr_info_t *fin, tcphdr_t *tcp,
1858     tcpdata_t *td)
1859 {
1860 	int off, mlen, ol, i, len, retval;
1861 	char buf[64], *s, opt;
1862 	mb_t *m = NULL;
1863 
1864 	len = (TCP_OFF(tcp) << 2);
1865 	if (fin->fin_dlen < len) {
1866 		SBUMPD(ipf_state_stats, iss_tcp_toosmall);
1867 		return 0;
1868 	}
1869 	len -= sizeof(*tcp);
1870 
1871 	off = fin->fin_plen - fin->fin_dlen + sizeof(*tcp) + fin->fin_ipoff;
1872 
1873 	m = fin->fin_m;
1874 	mlen = MSGDSIZE(m) - off;
1875 	if (len > mlen) {
1876 		len = mlen;
1877 		retval = 0;
1878 	} else {
1879 		retval = 1;
1880 	}
1881 
1882 	COPYDATA(m, off, len, buf);
1883 
1884 	for (s = buf; len > 0; ) {
1885 		opt = *s;
1886 		if (opt == TCPOPT_EOL)
1887 			break;
1888 		else if (opt == TCPOPT_NOP)
1889 			ol = 1;
1890 		else {
1891 			if (len < 2)
1892 				break;
1893 			ol = (int)*(s + 1);
1894 			if (ol < 2 || ol > len)
1895 				break;
1896 
1897 			/*
1898 			 * Extract the TCP options we are interested in out of
1899 			 * the header and store them in the tcpdata struct.
1900 			 */
1901 			switch (opt)
1902 			{
1903 			case TCPOPT_WINDOW :
1904 				if (ol == TCPOLEN_WINDOW) {
1905 					i = (int)*(s + 2);
1906 					if (i > TCP_WSCALE_MAX)
1907 						i = TCP_WSCALE_MAX;
1908 					else if (i < 0)
1909 						i = 0;
1910 					td->td_winscale = i;
1911 					td->td_winflags |= TCP_WSCALE_SEEN|
1912 							   TCP_WSCALE_FIRST;
1913 				} else
1914 					retval = -1;
1915 				break;
1916 			case TCPOPT_MAXSEG :
1917 				/*
1918 				 * So, if we wanted to set the TCP MAXSEG,
1919 				 * it should be done here...
1920 				 */
1921 				if (ol == TCPOLEN_MAXSEG) {
1922 					i = (int)*(s + 2);
1923 					i <<= 8;
1924 					i += (int)*(s + 3);
1925 					td->td_maxseg = i;
1926 				} else
1927 					retval = -1;
1928 				break;
1929 			case TCPOPT_SACK_PERMITTED :
1930 				if (ol == TCPOLEN_SACK_PERMITTED)
1931 					td->td_winflags |= TCP_SACK_PERMIT;
1932 				else
1933 					retval = -1;
1934 				break;
1935 			}
1936 		}
1937 		len -= ol;
1938 		s += ol;
1939 	}
1940 	if (retval == -1) {
1941 		SBUMPD(ipf_state_stats, iss_tcp_badopt);
1942 	}
1943 	return retval;
1944 }
1945 
1946 
1947 /* ------------------------------------------------------------------------ */
1948 /* Function:    ipf_state_tcp                                               */
1949 /* Returns:     int - 1 == packet matches state entry, 0 == it does not     */
1950 /* Parameters:  softc(I)  - pointer to soft context main structure          */
1951 /*              softs(I) - pointer to state context structure               */
1952 /*              fin(I)   - pointer to packet information                    */
1953 /*              tcp(I)   - pointer to TCP packet header                     */
1954 /*              is(I)  - pointer to master state structure                  */
1955 /*                                                                          */
1956 /* Check to see if a packet with TCP headers fits within the TCP window.    */
1957 /* Change timeout depending on whether new packet is a SYN-ACK returning    */
1958 /* for a SYN or a RST or FIN which indicate time to close up shop.          */
1959 /* ------------------------------------------------------------------------ */
1960 static int
1961 ipf_state_tcp(ipf_main_softc_t *softc, ipf_state_softc_t *softs, fr_info_t *fin,
1962     tcphdr_t *tcp, ipstate_t *is)
1963 {
1964 	tcpdata_t  *fdata, *tdata;
1965 	int source, ret, flags;
1966 
1967 	source = !fin->fin_rev;
1968 	if (((is->is_flags & IS_TCPFSM) != 0) && (source == 1) &&
1969 	    (ntohs(is->is_sport) != fin->fin_data[0]))
1970 		source = 0;
1971 	fdata = &is->is_tcp.ts_data[!source];
1972 	tdata = &is->is_tcp.ts_data[source];
1973 
1974 	MUTEX_ENTER(&is->is_lock);
1975 
1976 	/*
1977 	 * If a SYN packet is received for a connection that is on the way out
1978 	 * but hasn't yet departed then advance this session along the way.
1979 	 */
1980 	if ((tcp->th_flags & TH_OPENING) == TH_SYN) {
1981 		if ((is->is_state[0] > IPF_TCPS_ESTABLISHED) &&
1982 		    (is->is_state[1] > IPF_TCPS_ESTABLISHED)) {
1983 			is->is_state[!source] = IPF_TCPS_CLOSED;
1984 			ipf_movequeue(softc->ipf_ticks, &is->is_sti,
1985 				      is->is_sti.tqe_ifq,
1986 				      &softs->ipf_state_deletetq);
1987 			MUTEX_EXIT(&is->is_lock);
1988 			DT1(iss_tcp_closing, ipstate_t *, is);
1989 			SBUMP(ipf_state_stats.iss_tcp_closing);
1990 			return 0;
1991 		}
1992 	}
1993 
1994 	if (is->is_flags & IS_LOOSE)
1995 		ret = 1;
1996 	else
1997 		ret = ipf_state_tcpinwindow(fin, fdata, tdata, tcp,
1998 					    is->is_flags);
1999 	if (ret > 0) {
2000 		/*
2001 		 * Nearing end of connection, start timeout.
2002 		 */
2003 		ret = ipf_tcp_age(&is->is_sti, fin, softs->ipf_state_tcptq,
2004 				  is->is_flags, ret);
2005 		if (ret == 0) {
2006 			MUTEX_EXIT(&is->is_lock);
2007 			DT2(iss_tcp_fsm, fr_info_t *, fin, ipstate_t *, is);
2008 			SBUMP(ipf_state_stats.iss_tcp_fsm);
2009 			return 0;
2010 		}
2011 
2012 		if (softs->ipf_state_logging > 4)
2013 			ipf_state_log(softc, is, ISL_STATECHANGE);
2014 
2015 		/*
2016 		 * set s0's as appropriate.  Use syn-ack packet as it
2017 		 * contains both pieces of required information.
2018 		 */
2019 		/*
2020 		 * Window scale option is only present in SYN/SYN-ACK packet.
2021 		 * Compare with ~TH_FIN to mask out T/TCP setups.
2022 		 */
2023 		flags = tcp->th_flags & ~(TH_FIN|TH_ECNALL);
2024 		if (flags == (TH_SYN|TH_ACK)) {
2025 			is->is_s0[source] = ntohl(tcp->th_ack);
2026 			is->is_s0[!source] = ntohl(tcp->th_seq) + 1;
2027 			if ((TCP_OFF(tcp) > (sizeof(tcphdr_t) >> 2))) {
2028 				if (ipf_tcpoptions(softs, fin, tcp,
2029 						   fdata) == -1)
2030 					fin->fin_flx |= FI_BAD;
2031 			}
2032 			if ((fin->fin_out != 0) && (is->is_pass & FR_NEWISN))
2033 				ipf_checknewisn(fin, is);
2034 		} else if (flags == TH_SYN) {
2035 			is->is_s0[source] = ntohl(tcp->th_seq) + 1;
2036 			if ((TCP_OFF(tcp) > (sizeof(tcphdr_t) >> 2))) {
2037 				if (ipf_tcpoptions(softs, fin, tcp,
2038 						   fdata) == -1)
2039 					fin->fin_flx |= FI_BAD;
2040 			}
2041 
2042 			if ((fin->fin_out != 0) && (is->is_pass & FR_NEWISN))
2043 				ipf_checknewisn(fin, is);
2044 
2045 		}
2046 		ret = 1;
2047 	} else {
2048 		DT2(iss_tcp_oow, fr_info_t *, fin, ipstate_t *, is);
2049 		SBUMP(ipf_state_stats.iss_tcp_oow);
2050 		ret = 0;
2051 	}
2052 	MUTEX_EXIT(&is->is_lock);
2053 	return ret;
2054 }
2055 
2056 
2057 /* ------------------------------------------------------------------------ */
2058 /* Function:    ipf_checknewisn                                             */
2059 /* Returns:     Nil                                                         */
2060 /* Parameters:  fin(I)   - pointer to packet information                    */
2061 /*              is(I)  - pointer to master state structure                  */
2062 /*                                                                          */
2063 /* Check to see if this TCP connection is expecting and needs a new         */
2064 /* sequence number for a particular direction of the connection.            */
2065 /*                                                                          */
2066 /* NOTE: This does not actually change the sequence numbers, only gets new  */
2067 /* one ready.                                                               */
2068 /* ------------------------------------------------------------------------ */
2069 static void
2070 ipf_checknewisn(fr_info_t *fin, ipstate_t *is)
2071 {
2072 	u_32_t sumd, old, new;
2073 	tcphdr_t *tcp;
2074 	int i;
2075 
2076 	i = fin->fin_rev;
2077 	tcp = fin->fin_dp;
2078 
2079 	if (((i == 0) && !(is->is_flags & IS_ISNSYN)) ||
2080 	    ((i == 1) && !(is->is_flags & IS_ISNACK))) {
2081 		old = ntohl(tcp->th_seq);
2082 		new = ipf_newisn(fin);
2083 		is->is_isninc[i] = new - old;
2084 		CALC_SUMD(old, new, sumd);
2085 		is->is_sumd[i] = (sumd & 0xffff) + (sumd >> 16);
2086 
2087 		is->is_flags |= ((i == 0) ? IS_ISNSYN : IS_ISNACK);
2088 	}
2089 }
2090 
2091 
2092 /* ------------------------------------------------------------------------ */
2093 /* Function:    ipf_state_tcpinwindow                                       */
2094 /* Returns:     int - 1 == packet inside TCP "window", 0 == not inside.     */
2095 /* Parameters:  fin(I)   - pointer to packet information                    */
2096 /*              fdata(I) - pointer to tcp state informatio (forward)        */
2097 /*              tdata(I) - pointer to tcp state informatio (reverse)        */
2098 /*              tcp(I)   - pointer to TCP packet header                     */
2099 /*                                                                          */
2100 /* Given a packet has matched addresses and ports, check to see if it is    */
2101 /* within the TCP data window.  In a show of generosity, allow packets that */
2102 /* are within the window space behind the current sequence # as well.       */
2103 /* ------------------------------------------------------------------------ */
2104 static int
2105 ipf_state_tcpinwindow(fr_info_t *fin, tcpdata_t  *fdata, tcpdata_t *tdata,
2106     tcphdr_t *tcp, int flags)
2107 {
2108 	ipf_main_softc_t *softc = fin->fin_main_soft;
2109 	ipf_state_softc_t *softs = softc->ipf_state_soft;
2110 	tcp_seq seq, ack, end;
2111 	int ackskew, tcpflags;
2112 	u_32_t win, maxwin;
2113 	int dsize, inseq;
2114 
2115 	/*
2116 	 * Find difference between last checked packet and this packet.
2117 	 */
2118 	tcpflags = tcp->th_flags;
2119 	seq = ntohl(tcp->th_seq);
2120 	ack = ntohl(tcp->th_ack);
2121 	if (tcpflags & TH_SYN)
2122 		win = ntohs(tcp->th_win);
2123 	else
2124 		win = ntohs(tcp->th_win) << fdata->td_winscale;
2125 
2126 	/*
2127 	 * A window of 0 produces undesirable behaviour from this function.
2128 	 */
2129 	if (win == 0)
2130 		win = 1;
2131 
2132 	dsize = fin->fin_dlen - (TCP_OFF(tcp) << 2) +
2133 	        ((tcpflags & TH_SYN) ? 1 : 0) + ((tcpflags & TH_FIN) ? 1 : 0);
2134 
2135 	/*
2136 	 * if window scaling is present, the scaling is only allowed
2137 	 * for windows not in the first SYN packet. In that packet the
2138 	 * window is 65535 to specify the largest window possible
2139 	 * for receivers not implementing the window scale option.
2140 	 * Currently, we do not assume TTCP here. That means that
2141 	 * if we see a second packet from a host (after the initial
2142 	 * SYN), we can assume that the receiver of the SYN did
2143 	 * already send back the SYN/ACK (and thus that we know if
2144 	 * the receiver also does window scaling)
2145 	 */
2146 	if (!(tcpflags & TH_SYN) && (fdata->td_winflags & TCP_WSCALE_FIRST)) {
2147 		fdata->td_winflags &= ~TCP_WSCALE_FIRST;
2148 		fdata->td_maxwin = win;
2149 	}
2150 
2151 	end = seq + dsize;
2152 
2153 	if ((fdata->td_end == 0) &&
2154 	    (!(flags & IS_TCPFSM) ||
2155 	     ((tcpflags & TH_OPENING) == TH_OPENING))) {
2156 		/*
2157 		 * Must be a (outgoing) SYN-ACK in reply to a SYN.
2158 		 */
2159 		fdata->td_end = end - 1;
2160 		fdata->td_maxwin = 1;
2161 		fdata->td_maxend = end + win;
2162 	}
2163 
2164 	if (!(tcpflags & TH_ACK)) {  /* Pretend an ack was sent */
2165 		ack = tdata->td_end;
2166 	} else if (((tcpflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) &&
2167 		   (ack == 0)) {
2168 		/* gross hack to get around certain broken tcp stacks */
2169 		ack = tdata->td_end;
2170 	}
2171 
2172 	maxwin = tdata->td_maxwin;
2173 	ackskew = tdata->td_end - ack;
2174 
2175 	/*
2176 	 * Strict sequencing only allows in-order delivery.
2177 	 */
2178 	if ((flags & IS_STRICT) != 0) {
2179 		if (seq != fdata->td_end) {
2180 			DT2(iss_tcp_struct, tcpdata_t *, fdata, int, seq);
2181 			SBUMP(ipf_state_stats.iss_tcp_strict);
2182 			fin->fin_flx |= FI_OOW;
2183 			return 0;
2184 		}
2185 	}
2186 
2187 #define	SEQ_GE(a,b)	((int)((a) - (b)) >= 0)
2188 #define	SEQ_GT(a,b)	((int)((a) - (b)) > 0)
2189 	inseq = 0;
2190 	if ((SEQ_GE(fdata->td_maxend, end)) &&
2191 	    (SEQ_GE(seq, fdata->td_end - maxwin)) &&
2192 /* XXX what about big packets */
2193 #define MAXACKWINDOW 66000
2194 	    (-ackskew <= (MAXACKWINDOW)) &&
2195 	    ( ackskew <= (MAXACKWINDOW << fdata->td_winscale))) {
2196 		inseq = 1;
2197 	/*
2198 	 * Microsoft Windows will send the next packet to the right of the
2199 	 * window if SACK is in use.
2200 	 */
2201 	} else if ((seq == fdata->td_maxend) && (ackskew == 0) &&
2202 	    (fdata->td_winflags & TCP_SACK_PERMIT) &&
2203 	    (tdata->td_winflags & TCP_SACK_PERMIT)) {
2204 		DT2(iss_sinsack, tcpdata_t *, fdata, int, seq);
2205 		SBUMP(ipf_state_stats.iss_winsack);
2206 		inseq = 1;
2207 	/*
2208 	 * Sometimes a TCP RST will be generated with only the ACK field
2209 	 * set to non-zero.
2210 	 */
2211 	} else if ((seq == 0) && (tcpflags == (TH_RST|TH_ACK)) &&
2212 		   (ackskew >= -1) && (ackskew <= 1)) {
2213 		inseq = 1;
2214 	} else if (!(flags & IS_TCPFSM)) {
2215 #if 0
2216 		int i;
2217 
2218 		i = (fin->fin_rev << 1) + fin->fin_out;
2219 
2220 		if (is_pkts[i]0 == 0) {
2221 			/*
2222 			 * Picking up a connection in the middle, the "next"
2223 			 * packet seen from a direction that is new should be
2224 			 * accepted, even if it appears out of sequence.
2225 			 */
2226 			inseq = 1;
2227 		} else
2228 #endif
2229 		if (!(fdata->td_winflags &
2230 			    (TCP_WSCALE_SEEN|TCP_WSCALE_FIRST))) {
2231 			/*
2232 			 * No TCPFSM and no window scaling, so make some
2233 			 * extra guesses.
2234 			 */
2235 			if ((seq == fdata->td_maxend) && (ackskew == 0))
2236 				inseq = 1;
2237 			else if (SEQ_GE(seq + maxwin, fdata->td_end - maxwin))
2238 				inseq = 1;
2239 		}
2240 	}
2241 
2242 	/* TRACE(inseq, fdata, tdata, seq, end, ack, ackskew, win, maxwin) */
2243 
2244 	if (inseq) {
2245 		/* if ackskew < 0 then this should be due to fragmented
2246 		 * packets. There is no way to know the length of the
2247 		 * total packet in advance.
2248 		 * We do know the total length from the fragment cache though.
2249 		 * Note however that there might be more sessions with
2250 		 * exactly the same source and destination parameters in the
2251 		 * state cache (and source and destination is the only stuff
2252 		 * that is saved in the fragment cache). Note further that
2253 		 * some TCP connections in the state cache are hashed with
2254 		 * sport and dport as well which makes it not worthwhile to
2255 		 * look for them.
2256 		 * Thus, when ackskew is negative but still seems to belong
2257 		 * to this session, we bump up the destinations end value.
2258 		 */
2259 		if (ackskew < 0)
2260 			tdata->td_end = ack;
2261 
2262 		/* update max window seen */
2263 		if (fdata->td_maxwin < win)
2264 			fdata->td_maxwin = win;
2265 		if (SEQ_GT(end, fdata->td_end))
2266 			fdata->td_end = end;
2267 		if (SEQ_GE(ack + win, tdata->td_maxend))
2268 			tdata->td_maxend = ack + win;
2269 		return 1;
2270 	}
2271 	SBUMP(ipf_state_stats.iss_oow);
2272 	fin->fin_flx |= FI_OOW;
2273 	return 0;
2274 }
2275 
2276 
2277 /* ------------------------------------------------------------------------ */
2278 /* Function:    ipf_state_clone                                             */
2279 /* Returns:     ipstate_t* - NULL == cloning failed,                        */
2280 /*                           else pointer to new state structure            */
2281 /* Parameters:  fin(I) - pointer to packet information                      */
2282 /*              tcp(I) - pointer to TCP/UDP header                          */
2283 /*              is(I)  - pointer to master state structure                  */
2284 /*                                                                          */
2285 /* Create a "duplcate" state table entry from the master.                   */
2286 /* ------------------------------------------------------------------------ */
2287 static ipstate_t *
2288 ipf_state_clone(fr_info_t *fin, tcphdr_t *tcp, ipstate_t *is)
2289 {
2290 	ipf_main_softc_t *softc = fin->fin_main_soft;
2291 	ipf_state_softc_t *softs = softc->ipf_state_soft;
2292 	ipstate_t *clone;
2293 	u_32_t send;
2294 
2295 	if (softs->ipf_state_stats.iss_active == softs->ipf_state_max) {
2296 		SBUMPD(ipf_state_stats, iss_max);
2297 		softs->ipf_state_doflush = 1;
2298 		return NULL;
2299 	}
2300 	KMALLOC(clone, ipstate_t *);
2301 	if (clone == NULL) {
2302 		SBUMPD(ipf_state_stats, iss_clone_nomem);
2303 		return NULL;
2304 	}
2305 	bcopy((char *)is, (char *)clone, sizeof(*clone));
2306 
2307 	MUTEX_NUKE(&clone->is_lock);
2308 	/*
2309 	 * It has not yet been placed on any timeout queue, so make sure
2310 	 * all of that data is zero'd out.
2311 	 */
2312 	clone->is_sti.tqe_pnext = NULL;
2313 	clone->is_sti.tqe_next = NULL;
2314 	clone->is_sti.tqe_ifq = NULL;
2315 	clone->is_sti.tqe_parent = clone;
2316 
2317 	clone->is_die = ONE_DAY + softc->ipf_ticks;
2318 	clone->is_state[0] = 0;
2319 	clone->is_state[1] = 0;
2320 	send = ntohl(tcp->th_seq) + fin->fin_dlen - (TCP_OFF(tcp) << 2) +
2321 		((tcp->th_flags & TH_SYN) ? 1 : 0) +
2322 		((tcp->th_flags & TH_FIN) ? 1 : 0);
2323 
2324 	if (fin->fin_rev == 1) {
2325 		clone->is_dend = send;
2326 		clone->is_maxdend = send;
2327 		clone->is_send = 0;
2328 		clone->is_maxswin = 1;
2329 		clone->is_maxdwin = ntohs(tcp->th_win);
2330 		if (clone->is_maxdwin == 0)
2331 			clone->is_maxdwin = 1;
2332 	} else {
2333 		clone->is_send = send;
2334 		clone->is_maxsend = send;
2335 		clone->is_dend = 0;
2336 		clone->is_maxdwin = 1;
2337 		clone->is_maxswin = ntohs(tcp->th_win);
2338 		if (clone->is_maxswin == 0)
2339 			clone->is_maxswin = 1;
2340 	}
2341 
2342 	clone->is_flags &= ~SI_CLONE;
2343 	clone->is_flags |= SI_CLONED;
2344 	if (ipf_state_insert(softc, clone, fin->fin_rev) == -1) {
2345 		KFREE(clone);
2346 		return NULL;
2347 	}
2348 
2349 	clone->is_ref = 1;
2350 	if (clone->is_p == IPPROTO_TCP) {
2351 		(void) ipf_tcp_age(&clone->is_sti, fin, softs->ipf_state_tcptq,
2352 				   clone->is_flags, 2);
2353 	}
2354 	MUTEX_EXIT(&clone->is_lock);
2355 	if (is->is_flags & IS_STATESYNC)
2356 		clone->is_sync = ipf_sync_new(softc, SMC_STATE, fin, clone);
2357 	DT2(iss_clone, ipstate_t *, is, ipstate_t *, clone);
2358 	SBUMP(ipf_state_stats.iss_cloned);
2359 	return clone;
2360 }
2361 
2362 
2363 /* ------------------------------------------------------------------------ */
2364 /* Function:    ipf_matchsrcdst                                             */
2365 /* Returns:     Nil                                                         */
2366 /* Parameters:  fin(I)   - pointer to packet information                    */
2367 /*              is(I)    - pointer to state structure                       */
2368 /*              src(I)   - pointer to source address                        */
2369 /*              dst(I)   - pointer to destination address                   */
2370 /*              tcp(I)   - pointer to TCP/UDP header                        */
2371 /*              cmask(I) - mask of FI_* bits to check                       */
2372 /*                                                                          */
2373 /* Match a state table entry against an IP packet.  The logic below is that */
2374 /* ret gets set to one if the match succeeds, else remains 0.  If it is     */
2375 /* still 0 after the test. no match.                                        */
2376 /* ------------------------------------------------------------------------ */
2377 static ipstate_t *
2378 ipf_matchsrcdst(fr_info_t *fin, ipstate_t *is, i6addr_t *src, i6addr_t *dst,
2379     tcphdr_t *tcp, u_32_t cmask)
2380 {
2381 	ipf_main_softc_t *softc = fin->fin_main_soft;
2382 	ipf_state_softc_t *softs = softc->ipf_state_soft;
2383 	int ret = 0, rev, out, flags, flx = 0, idx;
2384 	u_short sp, dp;
2385 	u_32_t cflx;
2386 	void *ifp;
2387 
2388 	/*
2389 	 * If a connection is about to be deleted, no packets
2390 	 * are allowed to match it.
2391 	 */
2392 	if (is->is_sti.tqe_ifq == &softs->ipf_state_deletetq)
2393 		return NULL;
2394 
2395 	rev = IP6_NEQ(&is->is_dst, dst);
2396 	ifp = fin->fin_ifp;
2397 	out = fin->fin_out;
2398 	flags = is->is_flags;
2399 	sp = 0;
2400 	dp = 0;
2401 
2402 	if (tcp != NULL) {
2403 		sp = htons(fin->fin_sport);
2404 		dp = ntohs(fin->fin_dport);
2405 	}
2406 	if (!rev) {
2407 		if (tcp != NULL) {
2408 			if (!(flags & SI_W_SPORT) && (sp != is->is_sport))
2409 				rev = 1;
2410 			else if (!(flags & SI_W_DPORT) && (dp != is->is_dport))
2411 				rev = 1;
2412 		}
2413 	}
2414 
2415 	idx = (out << 1) + rev;
2416 
2417 	/*
2418 	 * If the interface for this 'direction' is set, make sure it matches.
2419 	 * An interface name that is not set matches any, as does a name of *.
2420 	 */
2421 	if ((is->is_ifp[idx] == ifp) || (is->is_ifp[idx] == NULL &&
2422 	    (*is->is_ifname[idx] == '\0' || *is->is_ifname[idx] == '-' ||
2423 	     *is->is_ifname[idx] == '*')))
2424 		ret = 1;
2425 
2426 	if (ret == 0) {
2427 		DT2(iss_lookup_badifp, fr_info_t *, fin, ipstate_t *, is);
2428 		SBUMP(ipf_state_stats.iss_lookup_badifp);
2429 		/* TRACE is, out, rev, idx */
2430 		return NULL;
2431 	}
2432 	ret = 0;
2433 
2434 	/*
2435 	 * Match addresses and ports.
2436 	 */
2437 	if (rev == 0) {
2438 		if ((IP6_EQ(&is->is_dst, dst) || (flags & SI_W_DADDR)) &&
2439 		    (IP6_EQ(&is->is_src, src) || (flags & SI_W_SADDR))) {
2440 			if (tcp) {
2441 				if ((sp == is->is_sport || flags & SI_W_SPORT)
2442 				    &&
2443 				    (dp == is->is_dport || flags & SI_W_DPORT))
2444 					ret = 1;
2445 			} else {
2446 				ret = 1;
2447 			}
2448 		}
2449 	} else {
2450 		if ((IP6_EQ(&is->is_dst, src) || (flags & SI_W_DADDR)) &&
2451 		    (IP6_EQ(&is->is_src, dst) || (flags & SI_W_SADDR))) {
2452 			if (tcp) {
2453 				if ((dp == is->is_sport || flags & SI_W_SPORT)
2454 				    &&
2455 				    (sp == is->is_dport || flags & SI_W_DPORT))
2456 					ret = 1;
2457 			} else {
2458 				ret = 1;
2459 			}
2460 		}
2461 	}
2462 
2463 	if (ret == 0) {
2464 		SBUMP(ipf_state_stats.iss_lookup_badport);
2465 		DT2(iss_lookup_badport, fr_info_t *, fin, ipstate_t *, is);
2466 		/* TRACE rev, is, sp, dp, src, dst */
2467 		return NULL;
2468 	}
2469 
2470 	/*
2471 	 * Whether or not this should be here, is questionable, but the aim
2472 	 * is to get this out of the main line.
2473 	 */
2474 	if (tcp == NULL)
2475 		flags = is->is_flags & ~(SI_WILDP|SI_NEWFR|SI_CLONE|SI_CLONED);
2476 
2477 	/*
2478 	 * Only one of the source or destination address can be flaged as a
2479 	 * wildcard.  Fill in the missing address, if set.
2480 	 * For IPv6, if the address being copied in is multicast, then
2481 	 * don't reset the wild flag - multicast causes it to be set in the
2482 	 * first place!
2483 	 */
2484 	if ((flags & (SI_W_SADDR|SI_W_DADDR))) {
2485 		fr_ip_t *fi = &fin->fin_fi;
2486 
2487 		if ((flags & SI_W_SADDR) != 0) {
2488 			if (rev == 0) {
2489 				is->is_src = fi->fi_src;
2490 				is->is_flags &= ~SI_W_SADDR;
2491 			} else {
2492 				if (!(fin->fin_flx & (FI_MULTICAST|FI_MBCAST))){
2493 					is->is_src = fi->fi_dst;
2494 					is->is_flags &= ~SI_W_SADDR;
2495 				}
2496 			}
2497 		} else if ((flags & SI_W_DADDR) != 0) {
2498 			if (rev == 0) {
2499 				if (!(fin->fin_flx & (FI_MULTICAST|FI_MBCAST))){
2500 					is->is_dst = fi->fi_dst;
2501 					is->is_flags &= ~SI_W_DADDR;
2502 				}
2503 			} else {
2504 				is->is_dst = fi->fi_src;
2505 				is->is_flags &= ~SI_W_DADDR;
2506 			}
2507 		}
2508 		if ((is->is_flags & (SI_WILDA|SI_WILDP)) == 0) {
2509 			ATOMIC_DECL(softs->ipf_state_stats.iss_wild);
2510 		}
2511 	}
2512 
2513 	flx = fin->fin_flx & cmask;
2514 	cflx = is->is_flx[out][rev];
2515 
2516 	/*
2517 	 * Match up any flags set from IP options.
2518 	 */
2519 	if ((cflx && (flx != (cflx & cmask))) ||
2520 	    ((fin->fin_optmsk & is->is_optmsk[rev]) != is->is_opt[rev]) ||
2521 	    ((fin->fin_secmsk & is->is_secmsk) != is->is_sec) ||
2522 	    ((fin->fin_auth & is->is_authmsk) != is->is_auth)) {
2523 		SBUMPD(ipf_state_stats, iss_miss_mask);
2524 		return NULL;
2525 	}
2526 
2527 	if ((fin->fin_flx & FI_IGNORE) != 0) {
2528 		fin->fin_rev = rev;
2529 		return is;
2530 	}
2531 
2532 	/*
2533 	 * Only one of the source or destination port can be flagged as a
2534 	 * wildcard.  When filling it in, fill in a copy of the matched entry
2535 	 * if it has the cloning flag set.
2536 	 */
2537 	if ((flags & (SI_W_SPORT|SI_W_DPORT))) {
2538 		if ((flags & SI_CLONE) != 0) {
2539 			ipstate_t *clone;
2540 
2541 			clone = ipf_state_clone(fin, tcp, is);
2542 			if (clone == NULL)
2543 				return NULL;
2544 			is = clone;
2545 		} else {
2546 			ATOMIC_DECL(softs->ipf_state_stats.iss_wild);
2547 		}
2548 
2549 		if ((flags & SI_W_SPORT) != 0) {
2550 			if (rev == 0) {
2551 				is->is_sport = sp;
2552 				is->is_send = ntohl(tcp->th_seq);
2553 			} else {
2554 				is->is_sport = dp;
2555 				is->is_send = ntohl(tcp->th_ack);
2556 			}
2557 			is->is_maxsend = is->is_send + 1;
2558 		} else if ((flags & SI_W_DPORT) != 0) {
2559 			if (rev == 0) {
2560 				is->is_dport = dp;
2561 				is->is_dend = ntohl(tcp->th_ack);
2562 			} else {
2563 				is->is_dport = sp;
2564 				is->is_dend = ntohl(tcp->th_seq);
2565 			}
2566 			is->is_maxdend = is->is_dend + 1;
2567 		}
2568 		is->is_flags &= ~(SI_W_SPORT|SI_W_DPORT);
2569 		if ((flags & SI_CLONED) && softs->ipf_state_logging)
2570 			ipf_state_log(softc, is, ISL_CLONE);
2571 	}
2572 
2573 	ret = -1;
2574 
2575 	if (is->is_flx[out][rev] == 0) {
2576 		is->is_flx[out][rev] = flx;
2577 		if (rev == 1 && is->is_optmsk[1] == 0) {
2578 			is->is_opt[1] = fin->fin_optmsk;
2579 			is->is_optmsk[1] = 0xffffffff;
2580 			if (is->is_v == 6) {
2581 				is->is_opt[1] &= ~0x8;
2582 				is->is_optmsk[1] &= ~0x8;
2583 			}
2584 		}
2585 	}
2586 
2587 	/*
2588 	 * Check if the interface name for this "direction" is set and if not,
2589 	 * fill it in.
2590 	 */
2591 	if (is->is_ifp[idx] == NULL &&
2592 	    (*is->is_ifname[idx] == '\0' || *is->is_ifname[idx] == '*')) {
2593 		is->is_ifp[idx] = ifp;
2594 		COPYIFNAME(fin->fin_v, ifp, is->is_ifname[idx]);
2595 	}
2596 	fin->fin_rev = rev;
2597 	return is;
2598 }
2599 
2600 
2601 /* ------------------------------------------------------------------------ */
2602 /* Function:    ipf_checkicmpmatchingstate                                  */
2603 /* Returns:     Nil                                                         */
2604 /* Parameters:  fin(I) - pointer to packet information                      */
2605 /*                                                                          */
2606 /* If we've got an ICMP error message, using the information stored in the  */
2607 /* ICMP packet, look for a matching state table entry.                      */
2608 /*                                                                          */
2609 /* If we return NULL then no lock on ipf_state is held.                     */
2610 /* If we return non-null then a read-lock on ipf_state is held.             */
2611 /* ------------------------------------------------------------------------ */
2612 static ipstate_t *
2613 ipf_checkicmpmatchingstate(fr_info_t *fin)
2614 {
2615 	ipf_main_softc_t *softc = fin->fin_main_soft;
2616 	ipf_state_softc_t *softs = softc->ipf_state_soft;
2617 	ipstate_t *is, **isp;
2618 	i6addr_t dst, src;
2619 	struct icmp *ic;
2620 	u_short savelen;
2621 	icmphdr_t *icmp;
2622 	fr_info_t ofin;
2623 	tcphdr_t *tcp;
2624 	int len;
2625 	u_char	pr;
2626 	ip_t *oip;
2627 	u_int hv;
2628 
2629 	/*
2630 	 * Does it at least have the return (basic) IP header ?
2631 	 * Is it an actual recognised ICMP error type?
2632 	 * Only a basic IP header (no options) should be with
2633 	 * an ICMP error header.
2634 	 */
2635 	if ((fin->fin_v != 4) || (fin->fin_hlen != sizeof(ip_t)) ||
2636 	    (fin->fin_plen < ICMPERR_MINPKTLEN) ||
2637 	    !(fin->fin_flx & FI_ICMPERR)) {
2638 		SBUMPD(ipf_state_stats, iss_icmp_bad);
2639 		return NULL;
2640 	}
2641 	ic = fin->fin_dp;
2642 
2643 	oip = (ip_t *)((char *)ic + ICMPERR_ICMPHLEN);
2644 	/*
2645 	 * Check if the at least the old IP header (with options) and
2646 	 * 8 bytes of payload is present.
2647 	 */
2648 	if (fin->fin_plen < ICMPERR_MAXPKTLEN + ((IP_HL(oip) - 5) << 2)) {
2649 		SBUMPDX(ipf_state_stats, iss_icmp_short, iss_icmp_short_1);
2650 		return NULL;
2651 	}
2652 
2653 	/*
2654 	 * Sanity Checks.
2655 	 */
2656 	len = fin->fin_dlen - ICMPERR_ICMPHLEN;
2657 	if ((len <= 0) || ((IP_HL(oip) << 2) > len)) {
2658 		DT2(iss_icmp_len, fr_info_t *, fin, struct ip*, oip);
2659 		SBUMPDX(ipf_state_stats, iss_icmp_short, iss_icmp_short_1);
2660 		return NULL;
2661 	}
2662 
2663 	/*
2664 	 * Is the buffer big enough for all of it ?  It's the size of the IP
2665 	 * header claimed in the encapsulated part which is of concern.  It
2666 	 * may be too big to be in this buffer but not so big that it's
2667 	 * outside the ICMP packet, leading to TCP deref's causing problems.
2668 	 * This is possible because we don't know how big oip_hl is when we
2669 	 * do the pullup early in ipf_check() and thus can't guarantee it is
2670 	 * all here now.
2671 	 */
2672 #ifdef  _KERNEL
2673 	{
2674 	mb_t *m;
2675 
2676 	m = fin->fin_m;
2677 # if defined(MENTAT)
2678 	if ((char *)oip + len > (char *)m->b_wptr) {
2679 		SBUMPDX(ipf_state_stats, iss_icmp_short, iss_icmp_short_2);
2680 		return NULL;
2681 	}
2682 # else
2683 	if ((char *)oip + len > (char *)fin->fin_ip + m->m_len) {
2684 		SBUMPDX(ipf_state_stats, iss_icmp_short, iss_icmp_short_3);
2685 		return NULL;
2686 	}
2687 # endif
2688 	}
2689 #endif
2690 
2691 	bcopy((char *)fin, (char *)&ofin, sizeof(*fin));
2692 
2693 	/*
2694 	 * in the IPv4 case we must zero the i6addr union otherwise
2695 	 * the IP6_EQ and IP6_NEQ macros produce the wrong results because
2696 	 * of the 'junk' in the unused part of the union
2697 	 */
2698 	bzero((char *)&src, sizeof(src));
2699 	bzero((char *)&dst, sizeof(dst));
2700 
2701 	/*
2702 	 * we make an fin entry to be able to feed it to
2703 	 * matchsrcdst note that not all fields are encessary
2704 	 * but this is the cleanest way. Note further we fill
2705 	 * in fin_mp such that if someone uses it we'll get
2706 	 * a kernel panic. ipf_matchsrcdst does not use this.
2707 	 *
2708 	 * watch out here, as ip is in host order and oip in network
2709 	 * order. Any change we make must be undone afterwards, like
2710 	 * oip->ip_len.
2711 	 */
2712 	savelen = oip->ip_len;
2713 	oip->ip_len = htons(len);
2714 
2715 	ofin.fin_flx = FI_NOCKSUM;
2716 	ofin.fin_v = 4;
2717 	ofin.fin_ip = oip;
2718 	ofin.fin_m = NULL;	/* if dereferenced, panic XXX */
2719 	ofin.fin_mp = NULL;	/* if dereferenced, panic XXX */
2720 	(void) ipf_makefrip(IP_HL(oip) << 2, oip, &ofin);
2721 	ofin.fin_ifp = fin->fin_ifp;
2722 	ofin.fin_out = !fin->fin_out;
2723 
2724 	hv = (pr = oip->ip_p);
2725 	src.in4 = oip->ip_src;
2726 	hv += src.in4.s_addr;
2727 	dst.in4 = oip->ip_dst;
2728 	hv += dst.in4.s_addr;
2729 
2730 	/*
2731 	 * Reset the short and bad flag here because in ipf_matchsrcdst()
2732 	 * the flags for the current packet (fin_flx) are compared against
2733 	 * those for the existing session.
2734 	 */
2735 	ofin.fin_flx &= ~(FI_BAD|FI_SHORT);
2736 
2737 	/*
2738 	 * Put old values of ip_len back as we don't know
2739 	 * if we have to forward the packet or process it again.
2740 	 */
2741 	oip->ip_len = savelen;
2742 
2743 	switch (oip->ip_p)
2744 	{
2745 	case IPPROTO_ICMP :
2746 		/*
2747 		 * an ICMP error can only be generated as a result of an
2748 		 * ICMP query, not as the response on an ICMP error
2749 		 *
2750 		 * XXX theoretically ICMP_ECHOREP and the other reply's are
2751 		 * ICMP query's as well, but adding them here seems strange XXX
2752 		 */
2753 		if ((ofin.fin_flx & FI_ICMPERR) != 0) {
2754 			DT1(iss_icmp_icmperr, fr_info_t *, &ofin);
2755 			SBUMP(ipf_state_stats.iss_icmp_icmperr);
2756 		    	return NULL;
2757 		}
2758 
2759 		/*
2760 		 * perform a lookup of the ICMP packet in the state table
2761 		 */
2762 		icmp = (icmphdr_t *)((char *)oip + (IP_HL(oip) << 2));
2763 		hv += icmp->icmp_id;
2764 		hv = DOUBLE_HASH(hv);
2765 
2766 		READ_ENTER(&softc->ipf_state);
2767 		for (isp = &softs->ipf_state_table[hv];
2768 		     ((is = *isp) != NULL); ) {
2769 			isp = &is->is_hnext;
2770 			if ((is->is_p != pr) || (is->is_v != 4))
2771 				continue;
2772 			if (is->is_pass & FR_NOICMPERR)
2773 				continue;
2774 
2775 			is = ipf_matchsrcdst(&ofin, is, &src, &dst,
2776 					    NULL, FI_ICMPCMP);
2777 			if ((is != NULL) && !ipf_allowstateicmp(fin, is, &src))
2778 				return is;
2779 		}
2780 		RWLOCK_EXIT(&softc->ipf_state);
2781 		SBUMPDX(ipf_state_stats, iss_icmp_miss, iss_icmp_miss_1);
2782 		return NULL;
2783 	case IPPROTO_TCP :
2784 	case IPPROTO_UDP :
2785 		break;
2786 	default :
2787 		SBUMPDX(ipf_state_stats, iss_icmp_miss, iss_icmp_miss_2);
2788 		return NULL;
2789 	}
2790 
2791 	tcp = (tcphdr_t *)((char *)oip + (IP_HL(oip) << 2));
2792 
2793 	hv += tcp->th_dport;;
2794 	hv += tcp->th_sport;;
2795 	hv = DOUBLE_HASH(hv);
2796 
2797 	READ_ENTER(&softc->ipf_state);
2798 	for (isp = &softs->ipf_state_table[hv]; ((is = *isp) != NULL); ) {
2799 		isp = &is->is_hnext;
2800 		/*
2801 		 * Only allow this icmp though if the
2802 		 * encapsulated packet was allowed through the
2803 		 * other way around. Note that the minimal amount
2804 		 * of info present does not allow for checking against
2805 		 * tcp internals such as seq and ack numbers.   Only the
2806 		 * ports are known to be present and can be even if the
2807 		 * short flag is set.
2808 		 */
2809 		if ((is->is_p == pr) && (is->is_v == 4) &&
2810 		    (is = ipf_matchsrcdst(&ofin, is, &src, &dst,
2811 					  tcp, FI_ICMPCMP))) {
2812 			if (ipf_allowstateicmp(fin, is, &src) == 0)
2813 				return is;
2814 		}
2815 	}
2816 	RWLOCK_EXIT(&softc->ipf_state);
2817 	SBUMPDX(ipf_state_stats, iss_icmp_miss, iss_icmp_miss_3);
2818 	return NULL;
2819 }
2820 
2821 
2822 /* ------------------------------------------------------------------------ */
2823 /* Function:    ipf_allowstateicmp                                          */
2824 /* Returns:     int - 1 = packet denied, 0 = packet allowed                 */
2825 /* Parameters:  fin(I) - pointer to packet information                      */
2826 /*              is(I)  - pointer to state table entry                       */
2827 /*              src(I) - source address to check permission for             */
2828 /*                                                                          */
2829 /* For an ICMP packet that has so far matched a state table entry, check if */
2830 /* there are any further refinements that might mean we want to block this  */
2831 /* packet.  This code isn't specific to either IPv4 or IPv6.                */
2832 /* ------------------------------------------------------------------------ */
2833 static int
2834 ipf_allowstateicmp(fr_info_t *fin, ipstate_t *is, i6addr_t *src)
2835 {
2836 	ipf_main_softc_t *softc = fin->fin_main_soft;
2837 	ipf_state_softc_t *softs = softc->ipf_state_soft;
2838 	frentry_t *savefr;
2839 	frentry_t *fr;
2840 	u_32_t ipass;
2841 	int backward;
2842 	int oi;
2843 	int i;
2844 
2845 	fr = is->is_rule;
2846 	if (fr != NULL && fr->fr_icmpgrp != NULL) {
2847 		savefr = fin->fin_fr;
2848 		fin->fin_fr = fr->fr_icmpgrp->fg_start;
2849 
2850 		ipass = ipf_scanlist(fin, softc->ipf_pass);
2851 		fin->fin_fr = savefr;
2852 		if (FR_ISBLOCK(ipass)) {
2853 			SBUMPD(ipf_state_stats, iss_icmp_headblock);
2854 			return 1;
2855 		}
2856 	}
2857 
2858 	/*
2859 	 * i  : the index of this packet (the icmp unreachable)
2860 	 * oi : the index of the original packet found in the
2861 	 *      icmp header (i.e. the packet causing this icmp)
2862 	 * backward : original packet was backward compared to
2863 	 *            the state
2864 	 */
2865 	backward = IP6_NEQ(&is->is_src, src);
2866 	fin->fin_rev = !backward;
2867 	i = (!backward << 1) + fin->fin_out;
2868 	oi = (backward << 1) + !fin->fin_out;
2869 
2870 	if (is->is_pass & FR_NOICMPERR) {
2871 		SBUMPD(ipf_state_stats, iss_icmp_banned);
2872 		return 1;
2873 	}
2874 	if (is->is_icmppkts[i] > is->is_pkts[oi]) {
2875 		SBUMPD(ipf_state_stats, iss_icmp_toomany);
2876 		return 1;
2877 	}
2878 
2879 	DT2(iss_icmp_hits, fr_info_t *, fin, ipstate_t *, is);
2880 	SBUMP(ipf_state_stats.iss_icmp_hits);
2881 	is->is_icmppkts[i]++;
2882 
2883 	/*
2884 	 * we deliberately do not touch the timeouts
2885 	 * for the accompanying state table entry.
2886 	 * It remains to be seen if that is correct. XXX
2887 	 */
2888 	return 0;
2889 }
2890 
2891 
2892 /* ------------------------------------------------------------------------ */
2893 /* Function:    ipf_ipsmove                                                 */
2894 /* Returns:     Nil                                                         */
2895 /* Parameters:  is(I) - pointer to state table entry                        */
2896 /*              hv(I) - new hash value for state table entry                */
2897 /* Write Locks: ipf_state                                                   */
2898 /*                                                                          */
2899 /* Move a state entry from one position in the hash table to another.       */
2900 /* ------------------------------------------------------------------------ */
2901 static void
2902 ipf_ipsmove(ipf_state_softc_t *softs, ipstate_t *is, u_int hv)
2903 {
2904 	ipstate_t **isp;
2905 	u_int hvm;
2906 
2907 	hvm = is->is_hv;
2908 
2909 	/* TRACE is, is_hv, hvm */
2910 
2911 	/*
2912 	 * Remove the hash from the old location...
2913 	 */
2914 	isp = is->is_phnext;
2915 	if (is->is_hnext)
2916 		is->is_hnext->is_phnext = isp;
2917 	*isp = is->is_hnext;
2918 	if (softs->ipf_state_table[hvm] == NULL)
2919 		softs->ipf_state_stats.iss_inuse--;
2920 	softs->ipf_state_stats.iss_bucketlen[hvm]--;
2921 
2922 	/*
2923 	 * ...and put the hash in the new one.
2924 	 */
2925 	hvm = DOUBLE_HASH(hv);
2926 	is->is_hv = hvm;
2927 
2928 	/* TRACE is, hv, is_hv, hvm */
2929 
2930 	isp = &softs->ipf_state_table[hvm];
2931 	if (*isp)
2932 		(*isp)->is_phnext = &is->is_hnext;
2933 	else
2934 		softs->ipf_state_stats.iss_inuse++;
2935 	softs->ipf_state_stats.iss_bucketlen[hvm]++;
2936 	is->is_phnext = isp;
2937 	is->is_hnext = *isp;
2938 	*isp = is;
2939 }
2940 
2941 
2942 /* ------------------------------------------------------------------------ */
2943 /* Function:    ipf_state_lookup                                            */
2944 /* Returns:     ipstate_t* - NULL == no matching state found,               */
2945 /*                           else pointer to state information is returned  */
2946 /* Parameters:  fin(I)  - pointer to packet information                     */
2947 /*              tcp(I)  - pointer to TCP/UDP header.                        */
2948 /*              ifqp(O) - pointer for storing tailq timeout                 */
2949 /*                                                                          */
2950 /* Search the state table for a matching entry to the packet described by   */
2951 /* the contents of *fin. For certain protocols, when a match is found the   */
2952 /* timeout queue is also selected and stored in ifpq if it is non-NULL.     */
2953 /*                                                                          */
2954 /* If we return NULL then no lock on ipf_state is held.                     */
2955 /* If we return non-null then a read-lock on ipf_state is held.             */
2956 /* ------------------------------------------------------------------------ */
2957 ipstate_t *
2958 ipf_state_lookup(fr_info_t *fin, tcphdr_t *tcp, ipftq_t **ifqp)
2959 {
2960 	ipf_main_softc_t *softc = fin->fin_main_soft;
2961 	ipf_state_softc_t *softs = softc->ipf_state_soft;
2962 	u_int hv, hvm, pr, v, tryagain;
2963 	ipstate_t *is, **isp;
2964 	u_short dport, sport;
2965 	i6addr_t src, dst;
2966 	struct icmp *ic;
2967 	ipftq_t *ifq;
2968 	int oow;
2969 
2970 	is = NULL;
2971 	ifq = NULL;
2972 	tcp = fin->fin_dp;
2973 	ic = (struct icmp *)tcp;
2974 	hv = (pr = fin->fin_fi.fi_p);
2975 	src = fin->fin_fi.fi_src;
2976 	dst = fin->fin_fi.fi_dst;
2977 	hv += src.in4.s_addr;
2978 	hv += dst.in4.s_addr;
2979 
2980 	v = fin->fin_fi.fi_v;
2981 #ifdef	USE_INET6
2982 	if (v == 6) {
2983 		hv  += fin->fin_fi.fi_src.i6[1];
2984 		hv  += fin->fin_fi.fi_src.i6[2];
2985 		hv  += fin->fin_fi.fi_src.i6[3];
2986 
2987 		if ((fin->fin_p == IPPROTO_ICMPV6) &&
2988 		    IN6_IS_ADDR_MULTICAST(&fin->fin_fi.fi_dst.in6)) {
2989 			hv -= dst.in4.s_addr;
2990 		} else {
2991 			hv += fin->fin_fi.fi_dst.i6[1];
2992 			hv += fin->fin_fi.fi_dst.i6[2];
2993 			hv += fin->fin_fi.fi_dst.i6[3];
2994 		}
2995 	}
2996 #endif
2997 	if ((v == 4) &&
2998 	    (fin->fin_flx & (FI_MULTICAST|FI_BROADCAST|FI_MBCAST))) {
2999 		if (fin->fin_out == 0) {
3000 			hv -= src.in4.s_addr;
3001 		} else {
3002 			hv -= dst.in4.s_addr;
3003 		}
3004 	}
3005 
3006 	/* TRACE fin_saddr, fin_daddr, hv */
3007 
3008 	/*
3009 	 * Search the hash table for matching packet header info.
3010 	 */
3011 	switch (pr)
3012 	{
3013 #ifdef	USE_INET6
3014 	case IPPROTO_ICMPV6 :
3015 		tryagain = 0;
3016 		if (v == 6) {
3017 			if ((ic->icmp_type == ICMP6_ECHO_REQUEST) ||
3018 			    (ic->icmp_type == ICMP6_ECHO_REPLY)) {
3019 				hv += ic->icmp_id;
3020 			}
3021 		}
3022 		READ_ENTER(&softc->ipf_state);
3023 icmp6again:
3024 		hvm = DOUBLE_HASH(hv);
3025 		for (isp = &softs->ipf_state_table[hvm];
3026 		     ((is = *isp) != NULL); ) {
3027 			isp = &is->is_hnext;
3028 			if ((is->is_p != pr) || (is->is_v != v))
3029 				continue;
3030 			is = ipf_matchsrcdst(fin, is, &src, &dst, NULL, FI_CMP);
3031 			if (is != NULL &&
3032 			    ipf_matchicmpqueryreply(v, &is->is_icmp,
3033 						   ic, fin->fin_rev)) {
3034 				if (fin->fin_rev)
3035 					ifq = &softs->ipf_state_icmpacktq;
3036 				else
3037 					ifq = &softs->ipf_state_icmptq;
3038 				break;
3039 			}
3040 		}
3041 
3042 		if (is != NULL) {
3043 			if ((tryagain != 0) && !(is->is_flags & SI_W_DADDR)) {
3044 				hv += fin->fin_fi.fi_src.i6[0];
3045 				hv += fin->fin_fi.fi_src.i6[1];
3046 				hv += fin->fin_fi.fi_src.i6[2];
3047 				hv += fin->fin_fi.fi_src.i6[3];
3048 				ipf_ipsmove(softs, is, hv);
3049 				MUTEX_DOWNGRADE(&softc->ipf_state);
3050 			}
3051 			break;
3052 		}
3053 		RWLOCK_EXIT(&softc->ipf_state);
3054 
3055 		/*
3056 		 * No matching icmp state entry. Perhaps this is a
3057 		 * response to another state entry.
3058 		 *
3059 		 * XXX With some ICMP6 packets, the "other" address is already
3060 		 * in the packet, after the ICMP6 header, and this could be
3061 		 * used in place of the multicast address.  However, taking
3062 		 * advantage of this requires some significant code changes
3063 		 * to handle the specific types where that is the case.
3064 		 */
3065 		if ((softs->ipf_state_stats.iss_wild != 0) &&
3066 		    ((fin->fin_flx & FI_NOWILD) == 0) &&
3067 		    (v == 6) && (tryagain == 0)) {
3068 			hv -= fin->fin_fi.fi_src.i6[0];
3069 			hv -= fin->fin_fi.fi_src.i6[1];
3070 			hv -= fin->fin_fi.fi_src.i6[2];
3071 			hv -= fin->fin_fi.fi_src.i6[3];
3072 			tryagain = 1;
3073 			WRITE_ENTER(&softc->ipf_state);
3074 			goto icmp6again;
3075 		}
3076 
3077 		is = ipf_checkicmp6matchingstate(fin);
3078 		if (is != NULL)
3079 			return is;
3080 		break;
3081 #endif
3082 
3083 	case IPPROTO_ICMP :
3084 		if (v == 4) {
3085 			hv += ic->icmp_id;
3086 		}
3087 		hv = DOUBLE_HASH(hv);
3088 		READ_ENTER(&softc->ipf_state);
3089 		for (isp = &softs->ipf_state_table[hv];
3090 		     ((is = *isp) != NULL); ) {
3091 			isp = &is->is_hnext;
3092 			if ((is->is_p != pr) || (is->is_v != v))
3093 				continue;
3094 			is = ipf_matchsrcdst(fin, is, &src, &dst, NULL, FI_CMP);
3095 			if ((is != NULL) &&
3096 			    (ic->icmp_id == is->is_icmp.ici_id) &&
3097 			    ipf_matchicmpqueryreply(v, &is->is_icmp,
3098 						   ic, fin->fin_rev)) {
3099 				if (fin->fin_rev)
3100 					ifq = &softs->ipf_state_icmpacktq;
3101 				else
3102 					ifq = &softs->ipf_state_icmptq;
3103 				break;
3104 			}
3105 		}
3106 		if (is == NULL) {
3107 			RWLOCK_EXIT(&softc->ipf_state);
3108 		}
3109 		break;
3110 
3111 	case IPPROTO_TCP :
3112 	case IPPROTO_UDP :
3113 		ifqp = NULL;
3114 		sport = htons(fin->fin_data[0]);
3115 		hv += sport;
3116 		dport = htons(fin->fin_data[1]);
3117 		hv += dport;
3118 		oow = 0;
3119 		tryagain = 0;
3120 		READ_ENTER(&softc->ipf_state);
3121 retry_tcpudp:
3122 		hvm = DOUBLE_HASH(hv);
3123 
3124 		/* TRACE hv, hvm */
3125 
3126 		for (isp = &softs->ipf_state_table[hvm];
3127 		     ((is = *isp) != NULL); ) {
3128 			isp = &is->is_hnext;
3129 			if ((is->is_p != pr) || (is->is_v != v))
3130 				continue;
3131 			fin->fin_flx &= ~FI_OOW;
3132 			is = ipf_matchsrcdst(fin, is, &src, &dst, tcp, FI_CMP);
3133 			if (is != NULL) {
3134 				if (pr == IPPROTO_TCP) {
3135 					if (!ipf_state_tcp(softc, softs, fin,
3136 							   tcp, is)) {
3137 						oow |= fin->fin_flx & FI_OOW;
3138 						continue;
3139 					}
3140 				}
3141 				break;
3142 			}
3143 		}
3144 		if (is != NULL) {
3145 			if (tryagain &&
3146 			    !(is->is_flags & (SI_CLONE|SI_WILDP|SI_WILDA))) {
3147 				hv += dport;
3148 				hv += sport;
3149 				ipf_ipsmove(softs, is, hv);
3150 				MUTEX_DOWNGRADE(&softc->ipf_state);
3151 			}
3152 			break;
3153 		}
3154 		RWLOCK_EXIT(&softc->ipf_state);
3155 
3156 		if ((softs->ipf_state_stats.iss_wild != 0) &&
3157 		    ((fin->fin_flx & FI_NOWILD) == 0)) {
3158 			if (tryagain == 0) {
3159 				hv -= dport;
3160 				hv -= sport;
3161 			} else if (tryagain == 1) {
3162 				hv = fin->fin_fi.fi_p;
3163 				/*
3164 				 * If we try to pretend this is a reply to a
3165 				 * multicast/broadcast packet then we need to
3166 				 * exclude part of the address from the hash
3167 				 * calculation.
3168 				 */
3169 				if (fin->fin_out == 0) {
3170 					hv += src.in4.s_addr;
3171 				} else {
3172 					hv += dst.in4.s_addr;
3173 				}
3174 				hv += dport;
3175 				hv += sport;
3176 			}
3177 			tryagain++;
3178 			if (tryagain <= 2) {
3179 				WRITE_ENTER(&softc->ipf_state);
3180 				goto retry_tcpudp;
3181 			}
3182 		}
3183 		fin->fin_flx |= oow;
3184 		break;
3185 
3186 #if 0
3187 	case IPPROTO_GRE :
3188 		gre = fin->fin_dp;
3189 		if (GRE_REV(gre->gr_flags) == 1) {
3190 			hv += gre->gr_call;
3191 		}
3192 		/* FALLTHROUGH */
3193 #endif
3194 	default :
3195 		ifqp = NULL;
3196 		hvm = DOUBLE_HASH(hv);
3197 		READ_ENTER(&softc->ipf_state);
3198 		for (isp = &softs->ipf_state_table[hvm];
3199 		     ((is = *isp) != NULL); ) {
3200 			isp = &is->is_hnext;
3201 			if ((is->is_p != pr) || (is->is_v != v))
3202 				continue;
3203 			is = ipf_matchsrcdst(fin, is, &src, &dst, NULL, FI_CMP);
3204 			if (is != NULL) {
3205 				ifq = &softs->ipf_state_iptq;
3206 				break;
3207 			}
3208 		}
3209 		if (is == NULL) {
3210 			RWLOCK_EXIT(&softc->ipf_state);
3211 		}
3212 		break;
3213 	}
3214 
3215 	if (is != NULL) {
3216 		if (((is->is_sti.tqe_flags & TQE_RULEBASED) != 0) &&
3217 		    (is->is_tqehead[fin->fin_rev] != NULL))
3218 			ifq = is->is_tqehead[fin->fin_rev];
3219 		if (ifq != NULL && ifqp != NULL)
3220 			*ifqp = ifq;
3221 	} else {
3222 		SBUMP(ipf_state_stats.iss_lookup_miss);
3223 	}
3224 	return is;
3225 }
3226 
3227 
3228 /* ------------------------------------------------------------------------ */
3229 /* Function:    ipf_state_check                                             */
3230 /* Returns:     frentry_t* - NULL == search failed,                         */
3231 /*                           else pointer to rule for matching state        */
3232 /* Parameters:  fin(I)   - pointer to packet information                    */
3233 /*              passp(I) - pointer to filtering result flags                */
3234 /*                                                                          */
3235 /* Check if a packet is associated with an entry in the state table.        */
3236 /* ------------------------------------------------------------------------ */
3237 frentry_t *
3238 ipf_state_check(fr_info_t *fin, u_32_t *passp)
3239 {
3240 	ipf_main_softc_t *softc = fin->fin_main_soft;
3241 	ipf_state_softc_t *softs = softc->ipf_state_soft;
3242 	ipftqent_t *tqe;
3243 	ipstate_t *is;
3244 	frentry_t *fr;
3245 	tcphdr_t *tcp;
3246 	ipftq_t *ifq;
3247 	u_int pass;
3248 	int inout;
3249 
3250 	if (softs->ipf_state_lock || (softs->ipf_state_list == NULL))
3251 		return NULL;
3252 
3253 	if (fin->fin_flx & (FI_SHORT|FI_FRAGBODY|FI_BAD)) {
3254 		SBUMPD(ipf_state_stats, iss_check_bad);
3255 		return NULL;
3256 	}
3257 
3258 	if ((fin->fin_flx & FI_TCPUDP) ||
3259 	    (fin->fin_fi.fi_p == IPPROTO_ICMP)
3260 #ifdef	USE_INET6
3261 	    || (fin->fin_fi.fi_p == IPPROTO_ICMPV6)
3262 #endif
3263 	    )
3264 		tcp = fin->fin_dp;
3265 	else
3266 		tcp = NULL;
3267 
3268 	ifq = NULL;
3269 	/*
3270 	 * Search the hash table for matching packet header info.
3271 	 */
3272 	is = ipf_state_lookup(fin, tcp, &ifq);
3273 
3274 	switch (fin->fin_p)
3275 	{
3276 #ifdef	USE_INET6
3277 	case IPPROTO_ICMPV6 :
3278 		if (is != NULL)
3279 			break;
3280 		if (fin->fin_v == 6) {
3281 			is = ipf_checkicmp6matchingstate(fin);
3282 		}
3283 		break;
3284 #endif
3285 	case IPPROTO_ICMP :
3286 		if (is != NULL)
3287 			break;
3288 		/*
3289 		 * No matching icmp state entry. Perhaps this is a
3290 		 * response to another state entry.
3291 		 */
3292 		is = ipf_checkicmpmatchingstate(fin);
3293 		break;
3294 
3295 	case IPPROTO_TCP :
3296 		if (is == NULL)
3297 			break;
3298 
3299 		if (is->is_pass & FR_NEWISN) {
3300 			if (fin->fin_out == 0)
3301 				ipf_fixinisn(fin, is);
3302 			else if (fin->fin_out == 1)
3303 				ipf_fixoutisn(fin, is);
3304 		}
3305 		break;
3306 	default :
3307 		if (fin->fin_rev)
3308 			ifq = &softs->ipf_state_udpacktq;
3309 		else
3310 			ifq = &softs->ipf_state_udptq;
3311 		break;
3312 	}
3313 	if (is == NULL) {
3314 		SBUMP(ipf_state_stats.iss_check_miss);
3315 		return NULL;
3316 	}
3317 
3318 	fr = is->is_rule;
3319 	if (fr != NULL) {
3320 		if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
3321 			if (fin->fin_nattag == NULL) {
3322 				RWLOCK_EXIT(&softc->ipf_state);
3323 				SBUMPD(ipf_state_stats, iss_check_notag);
3324 				return NULL;
3325 			}
3326 			if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag)!=0) {
3327 				RWLOCK_EXIT(&softc->ipf_state);
3328 				SBUMPD(ipf_state_stats, iss_check_nattag);
3329 				return NULL;
3330 			}
3331 		}
3332 		(void) strncpy(fin->fin_group, FR_NAME(fr, fr_group),
3333 			       FR_GROUPLEN);
3334 		fin->fin_icode = fr->fr_icode;
3335 	}
3336 
3337 	fin->fin_rule = is->is_rulen;
3338 	fin->fin_fr = fr;
3339 
3340 	/*
3341 	 * If this packet is a fragment and the rule says to track fragments,
3342 	 * then create a new fragment cache entry.
3343 	 */
3344 	if (fin->fin_flx & FI_FRAG && FR_ISPASS(is->is_pass) &&
3345 	   is->is_pass & FR_KEEPFRAG)
3346 		(void) ipf_frag_new(softc, fin, is->is_pass);
3347 
3348 	/*
3349 	 * For TCP packets, ifq == NULL.  For all others, check if this new
3350 	 * queue is different to the last one it was on and move it if so.
3351 	 */
3352 	tqe = &is->is_sti;
3353 	if ((tqe->tqe_flags & TQE_RULEBASED) != 0)
3354 		ifq = is->is_tqehead[fin->fin_rev];
3355 
3356 	MUTEX_ENTER(&is->is_lock);
3357 
3358 	if (ifq != NULL)
3359 		ipf_movequeue(softc->ipf_ticks, tqe, tqe->tqe_ifq, ifq);
3360 
3361 	inout = (fin->fin_rev << 1) + fin->fin_out;
3362 	is->is_pkts[inout]++;
3363 	is->is_bytes[inout] += fin->fin_plen;
3364 	fin->fin_pktnum = is->is_pkts[inout] + is->is_icmppkts[inout];
3365 
3366 	MUTEX_EXIT(&is->is_lock);
3367 
3368 	pass = is->is_pass;
3369 
3370 	if (is->is_flags & IS_STATESYNC)
3371 		ipf_sync_update(softc, SMC_STATE, fin, is->is_sync);
3372 
3373 	RWLOCK_EXIT(&softc->ipf_state);
3374 
3375 	SBUMP(ipf_state_stats.iss_hits);
3376 
3377 	fin->fin_dif = &is->is_dif;
3378 	fin->fin_tif = &is->is_tifs[fin->fin_rev];
3379 	fin->fin_flx |= FI_STATE;
3380 	if ((pass & FR_LOGFIRST) != 0)
3381 		pass &= ~(FR_LOGFIRST|FR_LOG);
3382 	*passp = pass;
3383 	return fr;
3384 }
3385 
3386 
3387 /* ------------------------------------------------------------------------ */
3388 /* Function:    ipf_fixoutisn                                               */
3389 /* Returns:     Nil                                                         */
3390 /* Parameters:  fin(I) - pointer to packet information                      */
3391 /*              is(I)  - pointer to master state structure                  */
3392 /*                                                                          */
3393 /* Called only for outbound packets, adjusts the sequence number and the    */
3394 /* TCP checksum to match that change.                                       */
3395 /* ------------------------------------------------------------------------ */
3396 static void
3397 ipf_fixoutisn(fr_info_t *fin, ipstate_t *is)
3398 {
3399 	tcphdr_t *tcp;
3400 	int rev;
3401 	u_32_t seq;
3402 
3403 	tcp = fin->fin_dp;
3404 	rev = fin->fin_rev;
3405 	if ((is->is_flags & IS_ISNSYN) != 0) {
3406 		if ((rev == 0) && (fin->fin_cksum < FI_CK_L4PART)) {
3407 			seq = ntohl(tcp->th_seq);
3408 			seq += is->is_isninc[0];
3409 			tcp->th_seq = htonl(seq);
3410 			ipf_fix_outcksum(0, &tcp->th_sum, is->is_sumd[0], 0);
3411 		}
3412 	}
3413 	if ((is->is_flags & IS_ISNACK) != 0) {
3414 		if ((rev == 1) && (fin->fin_cksum < FI_CK_L4PART)) {
3415 			seq = ntohl(tcp->th_seq);
3416 			seq += is->is_isninc[1];
3417 			tcp->th_seq = htonl(seq);
3418 			ipf_fix_outcksum(0, &tcp->th_sum, is->is_sumd[1], 0);
3419 		}
3420 	}
3421 }
3422 
3423 
3424 /* ------------------------------------------------------------------------ */
3425 /* Function:    ipf_fixinisn                                                */
3426 /* Returns:     Nil                                                         */
3427 /* Parameters:  fin(I)   - pointer to packet information                    */
3428 /*              is(I)  - pointer to master state structure                  */
3429 /*                                                                          */
3430 /* Called only for inbound packets, adjusts the acknowledge number and the  */
3431 /* TCP checksum to match that change.                                       */
3432 /* ------------------------------------------------------------------------ */
3433 static void
3434 ipf_fixinisn(fr_info_t *fin, ipstate_t *is)
3435 {
3436 	tcphdr_t *tcp;
3437 	int rev;
3438 	u_32_t ack;
3439 
3440 	tcp = fin->fin_dp;
3441 	rev = fin->fin_rev;
3442 	if ((is->is_flags & IS_ISNSYN) != 0) {
3443 		if ((rev == 1) && (fin->fin_cksum < FI_CK_L4PART)) {
3444 			ack = ntohl(tcp->th_ack);
3445 			ack -= is->is_isninc[0];
3446 			tcp->th_ack = htonl(ack);
3447 			ipf_fix_incksum(0, &tcp->th_sum, is->is_sumd[0], 0);
3448 		}
3449 	}
3450 	if ((is->is_flags & IS_ISNACK) != 0) {
3451 		if ((rev == 0) && (fin->fin_cksum < FI_CK_L4PART)) {
3452 			ack = ntohl(tcp->th_ack);
3453 			ack -= is->is_isninc[1];
3454 			tcp->th_ack = htonl(ack);
3455 			ipf_fix_incksum(0, &tcp->th_sum, is->is_sumd[1], 0);
3456 		}
3457 	}
3458 }
3459 
3460 
3461 /* ------------------------------------------------------------------------ */
3462 /* Function:    ipf_state_sync                                              */
3463 /* Returns:     Nil                                                         */
3464 /* Parameters:  softc(I) - pointer to soft context main structure           */
3465 /*              ifp(I)   - pointer to interface                             */
3466 /*                                                                          */
3467 /* Walk through all state entries and if an interface pointer match is      */
3468 /* found then look it up again, based on its name in case the pointer has   */
3469 /* changed since last time.                                                 */
3470 /*                                                                          */
3471 /* If ifp is passed in as being non-null then we are only doing updates for */
3472 /* existing, matching, uses of it.                                          */
3473 /* ------------------------------------------------------------------------ */
3474 void
3475 ipf_state_sync(ipf_main_softc_t *softc, void *ifp)
3476 {
3477 	ipf_state_softc_t *softs = softc->ipf_state_soft;
3478 	ipstate_t *is;
3479 	int i;
3480 
3481 	if (softc->ipf_running <= 0)
3482 		return;
3483 
3484 	WRITE_ENTER(&softc->ipf_state);
3485 
3486 	if (softc->ipf_running <= 0) {
3487 		RWLOCK_EXIT(&softc->ipf_state);
3488 		return;
3489 	}
3490 
3491 	for (is = softs->ipf_state_list; is; is = is->is_next) {
3492 		/*
3493 		 * Look up all the interface names in the state entry.
3494 		 */
3495 		for (i = 0; i < 4; i++) {
3496 			if (ifp == NULL || ifp == is->is_ifp[i])
3497 				is->is_ifp[i] = ipf_resolvenic(softc,
3498 							      is->is_ifname[i],
3499 							      is->is_v);
3500 		}
3501 	}
3502 	RWLOCK_EXIT(&softc->ipf_state);
3503 }
3504 
3505 
3506 /* ------------------------------------------------------------------------ */
3507 /* Function:    ipf_state_del                                               */
3508 /* Returns:     int    - 0 = deleted, else refernce count on active struct  */
3509 /* Parameters:  softc(I) - pointer to soft context main structure           */
3510 /*              is(I)  - pointer to state structure to delete               */
3511 /*              why(I) - if not 0, log reason why it was deleted            */
3512 /* Write Locks: ipf_state                                                   */
3513 /*                                                                          */
3514 /* Deletes a state entry from the enumerated list as well as the hash table */
3515 /* and timeout queue lists.  Make adjustments to hash table statistics and  */
3516 /* global counters as required.                                             */
3517 /* ------------------------------------------------------------------------ */
3518 static int
3519 ipf_state_del(ipf_main_softc_t *softc, ipstate_t *is, int why)
3520 {
3521 	ipf_state_softc_t *softs = softc->ipf_state_soft;
3522 	int orphan = 1;
3523 	frentry_t *fr;
3524 
3525 	/*
3526 	 * Since we want to delete this, remove it from the state table,
3527 	 * where it can be found & used, first.
3528 	 */
3529 	if (is->is_phnext != NULL) {
3530 		*is->is_phnext = is->is_hnext;
3531 		if (is->is_hnext != NULL)
3532 			is->is_hnext->is_phnext = is->is_phnext;
3533 		if (softs->ipf_state_table[is->is_hv] == NULL)
3534 			softs->ipf_state_stats.iss_inuse--;
3535 		softs->ipf_state_stats.iss_bucketlen[is->is_hv]--;
3536 
3537 		is->is_phnext = NULL;
3538 		is->is_hnext = NULL;
3539 		orphan = 0;
3540 	}
3541 
3542 	/*
3543 	 * Because ipf_state_stats.iss_wild is a count of entries in the state
3544 	 * table that have wildcard flags set, only decerement it once
3545 	 * and do it here.
3546 	 */
3547 	if (is->is_flags & (SI_WILDP|SI_WILDA)) {
3548 		if (!(is->is_flags & SI_CLONED)) {
3549 			ATOMIC_DECL(softs->ipf_state_stats.iss_wild);
3550 		}
3551 		is->is_flags &= ~(SI_WILDP|SI_WILDA);
3552 	}
3553 
3554 	/*
3555 	 * Next, remove it from the timeout queue it is in.
3556 	 */
3557 	if (is->is_sti.tqe_ifq != NULL)
3558 		ipf_deletequeueentry(&is->is_sti);
3559 
3560 	/*
3561 	 * If it is still in use by something else, do not go any further,
3562 	 * but note that at this point it is now an orphan.  How can this
3563 	 * be?  ipf_state_flush() calls ipf_delete() directly because it wants
3564 	 * to empty the table out and if something has a hold on a state
3565 	 * entry (such as ipfstat), it'll do the deref path that'll bring
3566 	 * us back here to do the real delete & free.
3567 	 */
3568 	MUTEX_ENTER(&is->is_lock);
3569 	if (is->is_me != NULL) {
3570 		*is->is_me = NULL;
3571 		is->is_me = NULL;
3572 		is->is_ref--;
3573 	}
3574 	is->is_ref--;
3575 	if (is->is_ref > 0) {
3576 		int refs;
3577 
3578 		refs = is->is_ref;
3579 		MUTEX_EXIT(&is->is_lock);
3580 		if (!orphan)
3581 			softs->ipf_state_stats.iss_orphan++;
3582 		return refs;
3583 	}
3584 
3585 	fr = is->is_rule;
3586 	is->is_rule = NULL;
3587 	if (fr != NULL) {
3588 		if (fr->fr_srctrack.ht_max_nodes != 0) {
3589 			(void) ipf_ht_node_del(&fr->fr_srctrack,
3590 					       is->is_family, &is->is_src);
3591 		}
3592 	}
3593 
3594 	ASSERT(is->is_ref == 0);
3595 	MUTEX_EXIT(&is->is_lock);
3596 
3597 	if (is->is_tqehead[0] != NULL) {
3598 		if (ipf_deletetimeoutqueue(is->is_tqehead[0]) == 0)
3599 			ipf_freetimeoutqueue(softc, is->is_tqehead[0]);
3600 	}
3601 	if (is->is_tqehead[1] != NULL) {
3602 		if (ipf_deletetimeoutqueue(is->is_tqehead[1]) == 0)
3603 			ipf_freetimeoutqueue(softc, is->is_tqehead[1]);
3604 	}
3605 
3606 	if (is->is_sync)
3607 		ipf_sync_del_state(softc->ipf_sync_soft, is->is_sync);
3608 
3609 	/*
3610 	 * Now remove it from the linked list of known states
3611 	 */
3612 	if (is->is_pnext != NULL) {
3613 		*is->is_pnext = is->is_next;
3614 
3615 		if (is->is_next != NULL)
3616 			is->is_next->is_pnext = is->is_pnext;
3617 
3618 		is->is_pnext = NULL;
3619 		is->is_next = NULL;
3620 	}
3621 
3622 	if (softs->ipf_state_logging != 0 && why != 0)
3623 		ipf_state_log(softc, is, why);
3624 
3625 	if (is->is_p == IPPROTO_TCP)
3626 		softs->ipf_state_stats.iss_fin++;
3627 	else
3628 		softs->ipf_state_stats.iss_expire++;
3629 	if (orphan)
3630 		softs->ipf_state_stats.iss_orphan--;
3631 
3632 	if (fr != NULL) {
3633 		fr->fr_statecnt--;
3634 		(void) ipf_derefrule(softc, &fr);
3635 	}
3636 
3637 	softs->ipf_state_stats.iss_active_proto[is->is_p]--;
3638 
3639 	MUTEX_DESTROY(&is->is_lock);
3640 	KFREE(is);
3641 	softs->ipf_state_stats.iss_active--;
3642 
3643 	return 0;
3644 }
3645 
3646 
3647 /* ------------------------------------------------------------------------ */
3648 /* Function:    ipf_state_expire                                            */
3649 /* Returns:     Nil                                                         */
3650 /* Parameters:  softc(I) - pointer to soft context main structure           */
3651 /*                                                                          */
3652 /* Slowly expire held state for thingslike UDP and ICMP.  The algorithm     */
3653 /* used here is to keep the queue sorted with the oldest things at the top  */
3654 /* and the youngest at the bottom.  So if the top one doesn't need to be    */
3655 /* expired then neither will any under it.                                  */
3656 /* ------------------------------------------------------------------------ */
3657 void
3658 ipf_state_expire(ipf_main_softc_t *softc)
3659 {
3660 	ipf_state_softc_t *softs = softc->ipf_state_soft;
3661 	ipftq_t *ifq, *ifqnext;
3662 	ipftqent_t *tqe, *tqn;
3663 	ipstate_t *is;
3664 	SPL_INT(s);
3665 
3666 	SPL_NET(s);
3667 	WRITE_ENTER(&softc->ipf_state);
3668 	for (ifq = softs->ipf_state_tcptq; ifq != NULL; ifq = ifq->ifq_next)
3669 		for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
3670 			if (tqe->tqe_die > softc->ipf_ticks)
3671 				break;
3672 			tqn = tqe->tqe_next;
3673 			is = tqe->tqe_parent;
3674 			ipf_state_del(softc, is, ISL_EXPIRE);
3675 		}
3676 
3677 	for (ifq = softs->ipf_state_usertq; ifq != NULL; ifq = ifqnext) {
3678 		ifqnext = ifq->ifq_next;
3679 
3680 		for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
3681 			if (tqe->tqe_die > softc->ipf_ticks)
3682 				break;
3683 			tqn = tqe->tqe_next;
3684 			is = tqe->tqe_parent;
3685 			ipf_state_del(softc, is, ISL_EXPIRE);
3686 		}
3687 	}
3688 
3689 	for (ifq = softs->ipf_state_usertq; ifq != NULL; ifq = ifqnext) {
3690 		ifqnext = ifq->ifq_next;
3691 
3692 		if (((ifq->ifq_flags & IFQF_DELETE) != 0) &&
3693 		    (ifq->ifq_ref == 0)) {
3694 			ipf_freetimeoutqueue(softc, ifq);
3695 		}
3696 	}
3697 
3698 	if (softs->ipf_state_doflush) {
3699 		(void) ipf_state_flush(softc, 2, 0);
3700 		softs->ipf_state_doflush = 0;
3701 		softs->ipf_state_wm_last = softc->ipf_ticks;
3702 	}
3703 
3704 	RWLOCK_EXIT(&softc->ipf_state);
3705 	SPL_X(s);
3706 }
3707 
3708 
3709 /* ------------------------------------------------------------------------ */
3710 /* Function:    ipf_state_flush                                             */
3711 /* Returns:     int - 0 == success, -1 == failure                           */
3712 /* Parameters:  softc(I) - pointer to soft context main structure           */
3713 /*              which(I) - which flush action to perform                    */
3714 /*              proto(I) - which protocol to flush (0 == ALL)               */
3715 /* Write Locks: ipf_state                                                   */
3716 /*                                                                          */
3717 /* Flush state tables.  Three actions currently defined:                    */
3718 /* which == 0 : flush all state table entries                               */
3719 /* which == 1 : flush TCP connections which have started to close but are   */
3720 /*	      stuck for some reason.                                        */
3721 /* which == 2 : flush TCP connections which have been idle for a long time, */
3722 /*	      starting at > 4 days idle and working back in successive half-*/
3723 /*	      days to at most 12 hours old.  If this fails to free enough   */
3724 /*            slots then work backwards in half hour slots to 30 minutes.   */
3725 /*            If that too fails, then work backwards in 30 second intervals */
3726 /*            for the last 30 minutes to at worst 30 seconds idle.          */
3727 /* ------------------------------------------------------------------------ */
3728 int
3729 ipf_state_flush(ipf_main_softc_t *softc, int which, int proto)
3730 {
3731 	ipf_state_softc_t *softs = softc->ipf_state_soft;
3732 	ipftqent_t *tqe, *tqn;
3733 	ipstate_t *is, **isp;
3734 	ipftq_t *ifq;
3735 	int removed;
3736 	SPL_INT(s);
3737 
3738 	removed = 0;
3739 
3740 	SPL_NET(s);
3741 
3742 	switch (which)
3743 	{
3744 	case 0 :
3745 		SBUMP(ipf_state_stats.iss_flush_all);
3746 		/*
3747 		 * Style 0 flush removes everything...
3748 		 */
3749 		for (isp = &softs->ipf_state_list; ((is = *isp) != NULL); ) {
3750 			if ((proto != 0) && (is->is_v != proto)) {
3751 				isp = &is->is_next;
3752 				continue;
3753 			}
3754 			if (ipf_state_del(softc, is, ISL_FLUSH) == 0)
3755 				removed++;
3756 			else
3757 				isp = &is->is_next;
3758 		}
3759 		break;
3760 
3761 	case 1 :
3762 		SBUMP(ipf_state_stats.iss_flush_closing);
3763 		/*
3764 		 * Since we're only interested in things that are closing,
3765 		 * we can start with the appropriate timeout queue.
3766 		 */
3767 		for (ifq = softs->ipf_state_tcptq + IPF_TCPS_CLOSE_WAIT;
3768 		     ifq != NULL; ifq = ifq->ifq_next) {
3769 
3770 			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
3771 				tqn = tqe->tqe_next;
3772 				is = tqe->tqe_parent;
3773 				if (is->is_p != IPPROTO_TCP)
3774 					break;
3775 				if (ipf_state_del(softc, is, ISL_FLUSH) == 0)
3776 					removed++;
3777 			}
3778 		}
3779 
3780 		/*
3781 		 * Also need to look through the user defined queues.
3782 		 */
3783 		for (ifq = softs->ipf_state_usertq; ifq != NULL;
3784 		     ifq = ifq->ifq_next) {
3785 			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
3786 				tqn = tqe->tqe_next;
3787 				is = tqe->tqe_parent;
3788 				if (is->is_p != IPPROTO_TCP)
3789 					continue;
3790 
3791 				if ((is->is_state[0] > IPF_TCPS_ESTABLISHED) &&
3792 				    (is->is_state[1] > IPF_TCPS_ESTABLISHED)) {
3793 					if (ipf_state_del(softc, is,
3794 							  ISL_FLUSH) == 0)
3795 						removed++;
3796 				}
3797 			}
3798 		}
3799 		break;
3800 
3801 	case 2 :
3802 		break;
3803 
3804 		/*
3805 		 * Args 5-11 correspond to flushing those particular states
3806 		 * for TCP connections.
3807 		 */
3808 	case IPF_TCPS_CLOSE_WAIT :
3809 	case IPF_TCPS_FIN_WAIT_1 :
3810 	case IPF_TCPS_CLOSING :
3811 	case IPF_TCPS_LAST_ACK :
3812 	case IPF_TCPS_FIN_WAIT_2 :
3813 	case IPF_TCPS_TIME_WAIT :
3814 	case IPF_TCPS_CLOSED :
3815 		SBUMP(ipf_state_stats.iss_flush_queue);
3816 		tqn = softs->ipf_state_tcptq[which].ifq_head;
3817 		while (tqn != NULL) {
3818 			tqe = tqn;
3819 			tqn = tqe->tqe_next;
3820 			is = tqe->tqe_parent;
3821 			if (ipf_state_del(softc, is, ISL_FLUSH) == 0)
3822 				removed++;
3823 		}
3824 		break;
3825 
3826 	default :
3827 		if (which < 30)
3828 			break;
3829 
3830 		SBUMP(ipf_state_stats.iss_flush_state);
3831 		/*
3832 		 * Take a large arbitrary number to mean the number of seconds
3833 		 * for which which consider to be the maximum value we'll allow
3834 		 * the expiration to be.
3835 		 */
3836 		which = IPF_TTLVAL(which);
3837 		for (isp = &softs->ipf_state_list; ((is = *isp) != NULL); ) {
3838 			if ((proto == 0) || (is->is_v == proto)) {
3839 				if (softc->ipf_ticks - is->is_touched > which) {
3840 					if (ipf_state_del(softc, is,
3841 							  ISL_FLUSH) == 0) {
3842 						removed++;
3843 						continue;
3844 					}
3845 				}
3846 			}
3847 			isp = &is->is_next;
3848 		}
3849 		break;
3850 	}
3851 
3852 	if (which != 2) {
3853 		SPL_X(s);
3854 		return removed;
3855 	}
3856 
3857 	SBUMP(ipf_state_stats.iss_flush_timeout);
3858 	/*
3859 	 * Asked to remove inactive entries because the table is full, try
3860 	 * again, 3 times, if first attempt failed with a different criteria
3861 	 * each time.  The order tried in must be in decreasing age.
3862 	 * Another alternative is to implement random drop and drop N entries
3863 	 * at random until N have been freed up.
3864 	 */
3865 	if (softc->ipf_ticks - softs->ipf_state_wm_last >
3866 	    softs->ipf_state_wm_freq) {
3867 		removed = ipf_queueflush(softc, ipf_state_flush_entry,
3868 					 softs->ipf_state_tcptq,
3869 					 softs->ipf_state_usertq,
3870 					 &softs->ipf_state_stats.iss_active,
3871 					 softs->ipf_state_size,
3872 					 softs->ipf_state_wm_low);
3873 		softs->ipf_state_wm_last = softc->ipf_ticks;
3874 	}
3875 
3876 	SPL_X(s);
3877 	return removed;
3878 }
3879 
3880 
3881 /* ------------------------------------------------------------------------ */
3882 /* Function:    ipf_state_flush_entry                                       */
3883 /* Returns:     int - 0 = entry deleted, else not deleted                   */
3884 /* Parameters:  softc(I) - pointer to soft context main structure           */
3885 /*              entry(I)  - pointer to state structure to delete            */
3886 /* Write Locks: ipf_state                                                   */
3887 /*                                                                          */
3888 /* This function is a stepping stone between ipf_queueflush() and           */
3889 /* ipf_state_del().  It is used so we can provide a uniform interface via   */
3890 /* the ipf_queueflush() function.                                           */
3891 /* ------------------------------------------------------------------------ */
3892 static int
3893 ipf_state_flush_entry(ipf_main_softc_t *softc, void *entry)
3894 {
3895 	return ipf_state_del(softc, entry, ISL_FLUSH);
3896 }
3897 
3898 
3899 /* ------------------------------------------------------------------------ */
3900 /* Function:    ipf_tcp_age                                                 */
3901 /* Returns:     int - 1 == state transition made, 0 == no change (rejected) */
3902 /* Parameters:  tqe(I)   - pointer to timeout queue information             */
3903 /*              fin(I)   - pointer to packet information                    */
3904 /*              tqtab(I) - TCP timeout queue table this is in               */
3905 /*              flags(I) - flags from state/NAT entry                       */
3906 /*              ok(I)    - can we advance state                             */
3907 /*                                                                          */
3908 /* Rewritten by Arjan de Vet <Arjan.deVet@adv.iae.nl>, 2000-07-29:          */
3909 /*                                                                          */
3910 /* - (try to) base state transitions on real evidence only,                 */
3911 /*   i.e. packets that are sent and have been received by ipfilter;         */
3912 /*   diagram 18.12 of TCP/IP volume 1 by W. Richard Stevens was used.       */
3913 /*                                                                          */
3914 /* - deal with half-closed connections correctly;                           */
3915 /*                                                                          */
3916 /* - store the state of the source in state[0] such that ipfstat            */
3917 /*   displays the state as source/dest instead of dest/source; the calls    */
3918 /*   to ipf_tcp_age have been changed accordingly.                          */
3919 /*                                                                          */
3920 /* Internal Parameters:                                                     */
3921 /*                                                                          */
3922 /*    state[0] = state of source (host that initiated connection)           */
3923 /*    state[1] = state of dest   (host that accepted the connection)        */
3924 /*                                                                          */
3925 /*    dir == 0 : a packet from source to dest                               */
3926 /*    dir == 1 : a packet from dest to source                               */
3927 /*                                                                          */
3928 /* A typical procession for a connection is as follows:                     */
3929 /*                                                                          */
3930 /* +--------------+-------------------+                                     */
3931 /* | Side '0'     | Side '1'          |                                     */
3932 /* +--------------+-------------------+                                     */
3933 /* | 0 -> 1 (SYN) |                   |                                     */
3934 /* |              | 0 -> 2 (SYN-ACK)  |                                     */
3935 /* | 1 -> 3 (ACK) |                   |                                     */
3936 /* |              | 2 -> 4 (ACK-PUSH) |                                     */
3937 /* | 3 -> 4 (ACK) |                   |                                     */
3938 /* |   ...        |   ...             |                                     */
3939 /* |              | 4 -> 6 (FIN-ACK)  |                                     */
3940 /* | 4 -> 5 (ACK) |                   |                                     */
3941 /* |              | 6 -> 6 (ACK-PUSH) |                                     */
3942 /* | 5 -> 5 (ACK) |                   |                                     */
3943 /* | 5 -> 8 (FIN) |                   |                                     */
3944 /* |              | 6 -> 10 (ACK)     |                                     */
3945 /* +--------------+-------------------+                                     */
3946 /*                                                                          */
3947 /* Locking: it is assumed that the parent of the tqe structure is locked.   */
3948 /* ------------------------------------------------------------------------ */
3949 int
3950 ipf_tcp_age(ipftqent_t *tqe, fr_info_t *fin, ipftq_t *tqtab, int flags, int ok)
3951 {
3952 	ipf_main_softc_t *softc = fin->fin_main_soft;
3953 	int dlen, ostate, nstate, rval, dir;
3954 	u_char tcpflags;
3955 	tcphdr_t *tcp;
3956 
3957 	tcp = fin->fin_dp;
3958 
3959 	rval = 0;
3960 	dir = fin->fin_rev;
3961 	tcpflags = tcp->th_flags;
3962 	dlen = fin->fin_dlen - (TCP_OFF(tcp) << 2);
3963 	ostate = tqe->tqe_state[1 - dir];
3964 	nstate = tqe->tqe_state[dir];
3965 
3966 	if (tcpflags & TH_RST) {
3967 		if (!(tcpflags & TH_PUSH) && !dlen)
3968 			nstate = IPF_TCPS_CLOSED;
3969 		else
3970 			nstate = IPF_TCPS_CLOSE_WAIT;
3971 
3972 		if (ostate <= IPF_TCPS_ESTABLISHED) {
3973 			tqe->tqe_state[1 - dir] = IPF_TCPS_CLOSE_WAIT;
3974 		}
3975 		rval = 1;
3976 	} else {
3977 		switch (nstate)
3978 		{
3979 		case IPF_TCPS_LISTEN: /* 0 */
3980 			if ((tcpflags & TH_OPENING) == TH_OPENING) {
3981 				/*
3982 				 * 'dir' received an S and sends SA in
3983 				 * response, LISTEN -> SYN_RECEIVED
3984 				 */
3985 				nstate = IPF_TCPS_SYN_RECEIVED;
3986 				rval = 1;
3987 			} else if ((tcpflags & TH_OPENING) == TH_SYN) {
3988 				/* 'dir' sent S, LISTEN -> SYN_SENT */
3989 				nstate = IPF_TCPS_SYN_SENT;
3990 				rval = 1;
3991 			}
3992 			/*
3993 			 * the next piece of code makes it possible to get
3994 			 * already established connections into the state table
3995 			 * after a restart or reload of the filter rules; this
3996 			 * does not work when a strict 'flags S keep state' is
3997 			 * used for tcp connections of course
3998 			 */
3999 			if (((flags & IS_TCPFSM) == 0) &&
4000 			    ((tcpflags & TH_ACKMASK) == TH_ACK)) {
4001 				/*
4002 				 * we saw an A, guess 'dir' is in ESTABLISHED
4003 				 * mode
4004 				 */
4005 				switch (ostate)
4006 				{
4007 				case IPF_TCPS_LISTEN :
4008 				case IPF_TCPS_SYN_RECEIVED :
4009 					nstate = IPF_TCPS_HALF_ESTAB;
4010 					rval = 1;
4011 					break;
4012 				case IPF_TCPS_HALF_ESTAB :
4013 				case IPF_TCPS_ESTABLISHED :
4014 					nstate = IPF_TCPS_ESTABLISHED;
4015 					rval = 1;
4016 					break;
4017 				default :
4018 					break;
4019 				}
4020 			}
4021 			/*
4022 			 * TODO: besides regular ACK packets we can have other
4023 			 * packets as well; it is yet to be determined how we
4024 			 * should initialize the states in those cases
4025 			 */
4026 			break;
4027 
4028 		case IPF_TCPS_SYN_SENT: /* 1 */
4029 			if ((tcpflags & ~(TH_ECN|TH_CWR)) == TH_SYN) {
4030 				/*
4031 				 * A retransmitted SYN packet.  We do not reset
4032 				 * the timeout here to ipf_tcptimeout because a
4033 				 * connection connect timeout does not renew
4034 				 * after every packet that is sent.  We need to
4035 				 * set rval so as to indicate the packet has
4036 				 * passed the check for its flags being valid
4037 				 * in the TCP FSM.  Setting rval to 2 has the
4038 				 * result of not resetting the timeout.
4039 				 */
4040 				rval = 2;
4041 			} else if ((tcpflags & (TH_SYN|TH_FIN|TH_ACK)) ==
4042 				   TH_ACK) {
4043 				/*
4044 				 * we see an A from 'dir' which is in SYN_SENT
4045 				 * state: 'dir' sent an A in response to an SA
4046 				 * which it received, SYN_SENT -> ESTABLISHED
4047 				 */
4048 				nstate = IPF_TCPS_ESTABLISHED;
4049 				rval = 1;
4050 			} else if (tcpflags & TH_FIN) {
4051 				/*
4052 				 * we see an F from 'dir' which is in SYN_SENT
4053 				 * state and wants to close its side of the
4054 				 * connection; SYN_SENT -> FIN_WAIT_1
4055 				 */
4056 				nstate = IPF_TCPS_FIN_WAIT_1;
4057 				rval = 1;
4058 			} else if ((tcpflags & TH_OPENING) == TH_OPENING) {
4059 				/*
4060 				 * we see an SA from 'dir' which is already in
4061 				 * SYN_SENT state, this means we have a
4062 				 * simultaneous open; SYN_SENT -> SYN_RECEIVED
4063 				 */
4064 				nstate = IPF_TCPS_SYN_RECEIVED;
4065 				rval = 1;
4066 			}
4067 			break;
4068 
4069 		case IPF_TCPS_SYN_RECEIVED: /* 2 */
4070 			if ((tcpflags & (TH_SYN|TH_FIN|TH_ACK)) == TH_ACK) {
4071 				/*
4072 				 * we see an A from 'dir' which was in
4073 				 * SYN_RECEIVED state so it must now be in
4074 				 * established state, SYN_RECEIVED ->
4075 				 * ESTABLISHED
4076 				 */
4077 				nstate = IPF_TCPS_ESTABLISHED;
4078 				rval = 1;
4079 			} else if ((tcpflags & ~(TH_ECN|TH_CWR)) ==
4080 				   TH_OPENING) {
4081 				/*
4082 				 * We see an SA from 'dir' which is already in
4083 				 * SYN_RECEIVED state.
4084 				 */
4085 				rval = 2;
4086 			} else if (tcpflags & TH_FIN) {
4087 				/*
4088 				 * we see an F from 'dir' which is in
4089 				 * SYN_RECEIVED state and wants to close its
4090 				 * side of the connection; SYN_RECEIVED ->
4091 				 * FIN_WAIT_1
4092 				 */
4093 				nstate = IPF_TCPS_FIN_WAIT_1;
4094 				rval = 1;
4095 			}
4096 			break;
4097 
4098 		case IPF_TCPS_HALF_ESTAB: /* 3 */
4099 			if (tcpflags & TH_FIN) {
4100 				nstate = IPF_TCPS_FIN_WAIT_1;
4101 				rval = 1;
4102 			} else if ((tcpflags & TH_ACKMASK) == TH_ACK) {
4103 				/*
4104 				 * If we've picked up a connection in mid
4105 				 * flight, we could be looking at a follow on
4106 				 * packet from the same direction as the one
4107 				 * that created this state.  Recognise it but
4108 				 * do not advance the entire connection's
4109 				 * state.
4110 				 */
4111 				switch (ostate)
4112 				{
4113 				case IPF_TCPS_LISTEN :
4114 				case IPF_TCPS_SYN_SENT :
4115 				case IPF_TCPS_SYN_RECEIVED :
4116 					rval = 1;
4117 					break;
4118 				case IPF_TCPS_HALF_ESTAB :
4119 				case IPF_TCPS_ESTABLISHED :
4120 					nstate = IPF_TCPS_ESTABLISHED;
4121 					rval = 1;
4122 					break;
4123 				default :
4124 					break;
4125 				}
4126 			}
4127 			break;
4128 
4129 		case IPF_TCPS_ESTABLISHED: /* 4 */
4130 			rval = 1;
4131 			if (tcpflags & TH_FIN) {
4132 				/*
4133 				 * 'dir' closed its side of the connection;
4134 				 * this gives us a half-closed connection;
4135 				 * ESTABLISHED -> FIN_WAIT_1
4136 				 */
4137 				if (ostate == IPF_TCPS_FIN_WAIT_1) {
4138 					nstate = IPF_TCPS_CLOSING;
4139 				} else {
4140 					nstate = IPF_TCPS_FIN_WAIT_1;
4141 				}
4142 			} else if (tcpflags & TH_ACK) {
4143 				/*
4144 				 * an ACK, should we exclude other flags here?
4145 				 */
4146 				if (ostate == IPF_TCPS_FIN_WAIT_1) {
4147 					/*
4148 					 * We know the other side did an active
4149 					 * close, so we are ACKing the recvd
4150 					 * FIN packet (does the window matching
4151 					 * code guarantee this?) and go into
4152 					 * CLOSE_WAIT state; this gives us a
4153 					 * half-closed connection
4154 					 */
4155 					nstate = IPF_TCPS_CLOSE_WAIT;
4156 				} else if (ostate < IPF_TCPS_CLOSE_WAIT) {
4157 					/*
4158 					 * still a fully established
4159 					 * connection reset timeout
4160 					 */
4161 					nstate = IPF_TCPS_ESTABLISHED;
4162 				}
4163 			}
4164 			break;
4165 
4166 		case IPF_TCPS_CLOSE_WAIT: /* 5 */
4167 			rval = 1;
4168 			if (tcpflags & TH_FIN) {
4169 				/*
4170 				 * application closed and 'dir' sent a FIN,
4171 				 * we're now going into LAST_ACK state
4172 				 */
4173 				nstate = IPF_TCPS_LAST_ACK;
4174 			} else {
4175 				/*
4176 				 * we remain in CLOSE_WAIT because the other
4177 				 * side has closed already and we did not
4178 				 * close our side yet; reset timeout
4179 				 */
4180 				nstate = IPF_TCPS_CLOSE_WAIT;
4181 			}
4182 			break;
4183 
4184 		case IPF_TCPS_FIN_WAIT_1: /* 6 */
4185 			rval = 1;
4186 			if ((tcpflags & TH_ACK) &&
4187 			    ostate > IPF_TCPS_CLOSE_WAIT) {
4188 				/*
4189 				 * if the other side is not active anymore
4190 				 * it has sent us a FIN packet that we are
4191 				 * ack'ing now with an ACK; this means both
4192 				 * sides have now closed the connection and
4193 				 * we go into TIME_WAIT
4194 				 */
4195 				/*
4196 				 * XXX: how do we know we really are ACKing
4197 				 * the FIN packet here? does the window code
4198 				 * guarantee that?
4199 				 */
4200 				nstate = IPF_TCPS_LAST_ACK;
4201 			} else {
4202 				/*
4203 				 * we closed our side of the connection
4204 				 * already but the other side is still active
4205 				 * (ESTABLISHED/CLOSE_WAIT); continue with
4206 				 * this half-closed connection
4207 				 */
4208 				nstate = IPF_TCPS_FIN_WAIT_1;
4209 			}
4210 			break;
4211 
4212 		case IPF_TCPS_CLOSING: /* 7 */
4213 			if ((tcpflags & (TH_FIN|TH_ACK)) == TH_ACK) {
4214 				nstate = IPF_TCPS_TIME_WAIT;
4215 			}
4216 			rval = 1;
4217 			break;
4218 
4219 		case IPF_TCPS_LAST_ACK: /* 8 */
4220 			if (tcpflags & TH_ACK) {
4221 				rval = 1;
4222 			}
4223 			/*
4224 			 * we cannot detect when we go out of LAST_ACK state
4225 			 * to CLOSED because that is based on the reception
4226 			 * of ACK packets; ipfilter can only detect that a
4227 			 * packet has been sent by a host
4228 			 */
4229 			break;
4230 
4231 		case IPF_TCPS_FIN_WAIT_2: /* 9 */
4232 			/* NOT USED */
4233 			break;
4234 
4235 		case IPF_TCPS_TIME_WAIT: /* 10 */
4236 			/* we're in 2MSL timeout now */
4237 			if (ostate == IPF_TCPS_LAST_ACK) {
4238 				nstate = IPF_TCPS_CLOSED;
4239 				rval = 1;
4240 			} else {
4241 				rval = 2;
4242 			}
4243 			break;
4244 
4245 		case IPF_TCPS_CLOSED: /* 11 */
4246 			rval = 2;
4247 			break;
4248 
4249 		default :
4250 #if !defined(_KERNEL)
4251 			abort();
4252 #endif
4253 			break;
4254 		}
4255 	}
4256 
4257 	/*
4258 	 * If rval == 2 then do not update the queue position, but treat the
4259 	 * packet as being ok.
4260 	 */
4261 	if (rval == 2)
4262 		rval = 1;
4263 	else if (rval == 1) {
4264 		if (ok)
4265 			tqe->tqe_state[dir] = nstate;
4266 		if ((tqe->tqe_flags & TQE_RULEBASED) == 0)
4267 			ipf_movequeue(softc->ipf_ticks, tqe, tqe->tqe_ifq,
4268 				      tqtab + nstate);
4269 	}
4270 
4271 	return rval;
4272 }
4273 
4274 
4275 /* ------------------------------------------------------------------------ */
4276 /* Function:    ipf_state_log                                               */
4277 /* Returns:     Nil                                                         */
4278 /* Parameters:  softc(I) - pointer to soft context main structure           */
4279 /*              is(I)    - pointer to state structure                       */
4280 /*              type(I)  - type of log entry to create                      */
4281 /*                                                                          */
4282 /* Creates a state table log entry using the state structure and type info. */
4283 /* passed in.  Log packet/byte counts, source/destination address and other */
4284 /* protocol specific information.                                           */
4285 /* ------------------------------------------------------------------------ */
4286 void
4287 ipf_state_log(ipf_main_softc_t *softc, struct ipstate *is, u_int type)
4288 {
4289 #ifdef	IPFILTER_LOG
4290 	struct	ipslog	ipsl;
4291 	size_t sizes[1];
4292 	void *items[1];
4293 	int types[1];
4294 
4295 	/*
4296 	 * Copy information out of the ipstate_t structure and into the
4297 	 * structure used for logging.
4298 	 */
4299 	ipsl.isl_type = type;
4300 	ipsl.isl_pkts[0] = is->is_pkts[0] + is->is_icmppkts[0];
4301 	ipsl.isl_bytes[0] = is->is_bytes[0];
4302 	ipsl.isl_pkts[1] = is->is_pkts[1] + is->is_icmppkts[1];
4303 	ipsl.isl_bytes[1] = is->is_bytes[1];
4304 	ipsl.isl_pkts[2] = is->is_pkts[2] + is->is_icmppkts[2];
4305 	ipsl.isl_bytes[2] = is->is_bytes[2];
4306 	ipsl.isl_pkts[3] = is->is_pkts[3] + is->is_icmppkts[3];
4307 	ipsl.isl_bytes[3] = is->is_bytes[3];
4308 	ipsl.isl_src = is->is_src;
4309 	ipsl.isl_dst = is->is_dst;
4310 	ipsl.isl_p = is->is_p;
4311 	ipsl.isl_v = is->is_v;
4312 	ipsl.isl_flags = is->is_flags;
4313 	ipsl.isl_tag = is->is_tag;
4314 	ipsl.isl_rulen = is->is_rulen;
4315 	(void) strncpy(ipsl.isl_group, is->is_group, FR_GROUPLEN);
4316 
4317 	if (ipsl.isl_p == IPPROTO_TCP || ipsl.isl_p == IPPROTO_UDP) {
4318 		ipsl.isl_sport = is->is_sport;
4319 		ipsl.isl_dport = is->is_dport;
4320 		if (ipsl.isl_p == IPPROTO_TCP) {
4321 			ipsl.isl_state[0] = is->is_state[0];
4322 			ipsl.isl_state[1] = is->is_state[1];
4323 		}
4324 	} else if (ipsl.isl_p == IPPROTO_ICMP) {
4325 		ipsl.isl_itype = is->is_icmp.ici_type;
4326 	} else if (ipsl.isl_p == IPPROTO_ICMPV6) {
4327 		ipsl.isl_itype = is->is_icmp.ici_type;
4328 	} else {
4329 		ipsl.isl_ps.isl_filler[0] = 0;
4330 		ipsl.isl_ps.isl_filler[1] = 0;
4331 	}
4332 
4333 	items[0] = &ipsl;
4334 	sizes[0] = sizeof(ipsl);
4335 	types[0] = 0;
4336 
4337 	(void) ipf_log_items(softc, IPL_LOGSTATE, NULL, items, sizes, types, 1);
4338 #endif
4339 }
4340 
4341 
4342 #ifdef	USE_INET6
4343 /* ------------------------------------------------------------------------ */
4344 /* Function:    ipf_checkicmp6matchingstate                                 */
4345 /* Returns:     ipstate_t* - NULL == no match found,                        */
4346 /*                           else  pointer to matching state entry          */
4347 /* Parameters:  fin(I) - pointer to packet information                      */
4348 /* Locks:       NULL == no locks, else Read Lock on ipf_state               */
4349 /*                                                                          */
4350 /* If we've got an ICMPv6 error message, using the information stored in    */
4351 /* the ICMPv6 packet, look for a matching state table entry.                */
4352 /* ------------------------------------------------------------------------ */
4353 static ipstate_t *
4354 ipf_checkicmp6matchingstate(fr_info_t *fin)
4355 {
4356 	ipf_main_softc_t *softc = fin->fin_main_soft;
4357 	ipf_state_softc_t *softs = softc->ipf_state_soft;
4358 	struct icmp6_hdr *ic6, *oic;
4359 	ipstate_t *is, **isp;
4360 	u_short sport, dport;
4361 	i6addr_t dst, src;
4362 	u_short savelen;
4363 	icmpinfo_t *ic;
4364 	fr_info_t ofin;
4365 	tcphdr_t *tcp;
4366 	ip6_t *oip6;
4367 	u_char pr;
4368 	u_int hv;
4369 
4370 	/*
4371 	 * Does it at least have the return (basic) IP header ?
4372 	 * Is it an actual recognised ICMP error type?
4373 	 * Only a basic IP header (no options) should be with
4374 	 * an ICMP error header.
4375 	 */
4376 	if ((fin->fin_v != 6) || (fin->fin_plen < ICMP6ERR_MINPKTLEN) ||
4377 	    !(fin->fin_flx & FI_ICMPERR)) {
4378 		SBUMPD(ipf_state_stats, iss_icmp_bad);
4379 		return NULL;
4380 	}
4381 
4382 	ic6 = fin->fin_dp;
4383 
4384 	oip6 = (ip6_t *)((char *)ic6 + ICMPERR_ICMPHLEN);
4385 	if (fin->fin_plen < sizeof(*oip6)) {
4386 		SBUMPD(ipf_state_stats, iss_icmp_short);
4387 		return NULL;
4388 	}
4389 
4390 	bcopy((char *)fin, (char *)&ofin, sizeof(*fin));
4391 	ofin.fin_v = 6;
4392 	ofin.fin_ifp = fin->fin_ifp;
4393 	ofin.fin_out = !fin->fin_out;
4394 	ofin.fin_m = NULL;	/* if dereferenced, panic XXX */
4395 	ofin.fin_mp = NULL;	/* if dereferenced, panic XXX */
4396 
4397 	/*
4398 	 * We make a fin entry to be able to feed it to
4399 	 * matchsrcdst. Note that not all fields are necessary
4400 	 * but this is the cleanest way. Note further we fill
4401 	 * in fin_mp such that if someone uses it we'll get
4402 	 * a kernel panic. ipf_matchsrcdst does not use this.
4403 	 *
4404 	 * watch out here, as ip is in host order and oip6 in network
4405 	 * order. Any change we make must be undone afterwards.
4406 	 */
4407 	savelen = oip6->ip6_plen;
4408 	oip6->ip6_plen = htons(fin->fin_dlen - ICMPERR_ICMPHLEN);
4409 	ofin.fin_flx = FI_NOCKSUM;
4410 	ofin.fin_ip = (ip_t *)oip6;
4411 	(void) ipf_makefrip(sizeof(*oip6), (ip_t *)oip6, &ofin);
4412 	ofin.fin_flx &= ~(FI_BAD|FI_SHORT);
4413 	oip6->ip6_plen = savelen;
4414 	pr = ofin.fin_p;
4415 
4416 	/*
4417 	 * an ICMP error can never generate an ICMP error in response.
4418 	 */
4419 	if (ofin.fin_flx & FI_ICMPERR) {
4420 		DT1(iss_icmp6_icmperr, fr_info_t *, &ofin);
4421 		SBUMP(ipf_state_stats.iss_icmp6_icmperr);
4422 		return NULL;
4423 	}
4424 
4425 	if (oip6->ip6_nxt == IPPROTO_ICMPV6) {
4426 		oic = ofin.fin_dp;
4427 		/*
4428 		 * an ICMP error can only be generated as a result of an
4429 		 * ICMP query, not as the response on an ICMP error
4430 		 *
4431 		 * XXX theoretically ICMP_ECHOREP and the other reply's are
4432 		 * ICMP query's as well, but adding them here seems strange XXX
4433 		 */
4434 		 if (!(oic->icmp6_type & ICMP6_INFOMSG_MASK)) {
4435 			DT1(iss_icmp6_notinfo, fr_info_t *, &ofin);
4436 			SBUMP(ipf_state_stats.iss_icmp6_notinfo);
4437 			return NULL;
4438 		}
4439 
4440 		/*
4441 		 * perform a lookup of the ICMP packet in the state table
4442 		 */
4443 		hv = (pr = oip6->ip6_nxt);
4444 		src.in6 = oip6->ip6_src;
4445 		hv += src.in4.s_addr;
4446 		dst.in6 = oip6->ip6_dst;
4447 		hv += dst.in4.s_addr;
4448 		hv += oic->icmp6_id;
4449 		hv += oic->icmp6_seq;
4450 		hv = DOUBLE_HASH(hv);
4451 
4452 		READ_ENTER(&softc->ipf_state);
4453 		for (isp = &softs->ipf_state_table[hv];
4454 		     ((is = *isp) != NULL); ) {
4455 			ic = &is->is_icmp;
4456 			isp = &is->is_hnext;
4457 			if ((is->is_p == pr) &&
4458 			    !(is->is_pass & FR_NOICMPERR) &&
4459 			    (oic->icmp6_id == ic->ici_id) &&
4460 			    (oic->icmp6_seq == ic->ici_seq) &&
4461 			    (is = ipf_matchsrcdst(&ofin, is, &src,
4462 						 &dst, NULL, FI_ICMPCMP))) {
4463 			    	/*
4464 			    	 * in the state table ICMP query's are stored
4465 			    	 * with the type of the corresponding ICMP
4466 			    	 * response. Correct here
4467 			    	 */
4468 				if (((ic->ici_type == ICMP6_ECHO_REPLY) &&
4469 				     (oic->icmp6_type == ICMP6_ECHO_REQUEST)) ||
4470 				     (ic->ici_type - 1 == oic->icmp6_type )) {
4471 					if (!ipf_allowstateicmp(fin, is, &src))
4472 						return is;
4473 				}
4474 			}
4475 		}
4476 		RWLOCK_EXIT(&softc->ipf_state);
4477 		SBUMPD(ipf_state_stats, iss_icmp6_miss);
4478 		return NULL;
4479 	}
4480 
4481 	hv = (pr = oip6->ip6_nxt);
4482 	src.in6 = oip6->ip6_src;
4483 	hv += src.i6[0];
4484 	hv += src.i6[1];
4485 	hv += src.i6[2];
4486 	hv += src.i6[3];
4487 	dst.in6 = oip6->ip6_dst;
4488 	hv += dst.i6[0];
4489 	hv += dst.i6[1];
4490 	hv += dst.i6[2];
4491 	hv += dst.i6[3];
4492 
4493 	tcp = NULL;
4494 
4495 	switch (oip6->ip6_nxt)
4496 	{
4497 	case IPPROTO_TCP :
4498 	case IPPROTO_UDP :
4499 		tcp = (tcphdr_t *)(oip6 + 1);
4500 		dport = tcp->th_dport;
4501 		sport = tcp->th_sport;
4502 		hv += dport;
4503 		hv += sport;
4504 		break;
4505 
4506 	case IPPROTO_ICMPV6 :
4507 		oic = (struct icmp6_hdr *)(oip6 + 1);
4508 		hv += oic->icmp6_id;
4509 		hv += oic->icmp6_seq;
4510 		break;
4511 
4512 	default :
4513 		break;
4514 	}
4515 
4516 	hv = DOUBLE_HASH(hv);
4517 
4518 	READ_ENTER(&softc->ipf_state);
4519 	for (isp = &softs->ipf_state_table[hv]; ((is = *isp) != NULL); ) {
4520 		isp = &is->is_hnext;
4521 		/*
4522 		 * Only allow this icmp though if the
4523 		 * encapsulated packet was allowed through the
4524 		 * other way around. Note that the minimal amount
4525 		 * of info present does not allow for checking against
4526 		 * tcp internals such as seq and ack numbers.
4527 		 */
4528 		if ((is->is_p != pr) || (is->is_v != 6) ||
4529 		    (is->is_pass & FR_NOICMPERR))
4530 			continue;
4531 		is = ipf_matchsrcdst(&ofin, is, &src, &dst, tcp, FI_ICMPCMP);
4532 		if ((is != NULL) && (ipf_allowstateicmp(fin, is, &src) == 0))
4533 			return is;
4534 	}
4535 	RWLOCK_EXIT(&softc->ipf_state);
4536 	SBUMPD(ipf_state_stats, iss_icmp_miss);
4537 	return NULL;
4538 }
4539 #endif
4540 
4541 
4542 /* ------------------------------------------------------------------------ */
4543 /* Function:    ipf_sttab_init                                              */
4544 /* Returns:     Nil                                                         */
4545 /* Parameters:  softc(I) - pointer to soft context main structure           */
4546 /*              tqp(I)   - pointer to an array of timeout queues for TCP    */
4547 /*                                                                          */
4548 /* Initialise the array of timeout queues for TCP.                          */
4549 /* ------------------------------------------------------------------------ */
4550 void
4551 ipf_sttab_init(ipf_main_softc_t *softc, ipftq_t *tqp)
4552 {
4553 	int i;
4554 
4555 	for (i = IPF_TCP_NSTATES - 1; i >= 0; i--) {
4556 		IPFTQ_INIT(&tqp[i], 0, "ipftq tcp tab");
4557 		tqp[i].ifq_next = tqp + i + 1;
4558 	}
4559 	tqp[IPF_TCP_NSTATES - 1].ifq_next = NULL;
4560 	tqp[IPF_TCPS_CLOSED].ifq_ttl = softc->ipf_tcpclosed;
4561 	tqp[IPF_TCPS_LISTEN].ifq_ttl = softc->ipf_tcptimeout;
4562 	tqp[IPF_TCPS_SYN_SENT].ifq_ttl = softc->ipf_tcpsynsent;
4563 	tqp[IPF_TCPS_SYN_RECEIVED].ifq_ttl = softc->ipf_tcpsynrecv;
4564 	tqp[IPF_TCPS_ESTABLISHED].ifq_ttl = softc->ipf_tcpidletimeout;
4565 	tqp[IPF_TCPS_CLOSE_WAIT].ifq_ttl = softc->ipf_tcphalfclosed;
4566 	tqp[IPF_TCPS_FIN_WAIT_1].ifq_ttl = softc->ipf_tcphalfclosed;
4567 	tqp[IPF_TCPS_CLOSING].ifq_ttl = softc->ipf_tcptimeout;
4568 	tqp[IPF_TCPS_LAST_ACK].ifq_ttl = softc->ipf_tcplastack;
4569 	tqp[IPF_TCPS_FIN_WAIT_2].ifq_ttl = softc->ipf_tcpclosewait;
4570 	tqp[IPF_TCPS_TIME_WAIT].ifq_ttl = softc->ipf_tcptimewait;
4571 	tqp[IPF_TCPS_HALF_ESTAB].ifq_ttl = softc->ipf_tcptimeout;
4572 }
4573 
4574 
4575 /* ------------------------------------------------------------------------ */
4576 /* Function:    ipf_sttab_destroy                                           */
4577 /* Returns:     Nil                                                         */
4578 /* Parameters:  tqp(I) - pointer to an array of timeout queues for TCP      */
4579 /*                                                                          */
4580 /* Do whatever is necessary to "destroy" each of the entries in the array   */
4581 /* of timeout queues for TCP.                                               */
4582 /* ------------------------------------------------------------------------ */
4583 void
4584 ipf_sttab_destroy(ipftq_t *tqp)
4585 {
4586 	int i;
4587 
4588 	for (i = IPF_TCP_NSTATES - 1; i >= 0; i--)
4589 		MUTEX_DESTROY(&tqp[i].ifq_lock);
4590 }
4591 
4592 
4593 /* ------------------------------------------------------------------------ */
4594 /* Function:    ipf_state_deref                                             */
4595 /* Returns:     Nil                                                         */
4596 /* Parameters:  softc(I) - pointer to soft context main structure           */
4597 /*              isp(I) - pointer to pointer to state table entry            */
4598 /*                                                                          */
4599 /* Decrement the reference counter for this state table entry and free it   */
4600 /* if there are no more things using it.                                    */
4601 /*                                                                          */
4602 /* This function is only called when cleaning up after increasing is_ref by */
4603 /* one earlier in the 'code path' so if is_ref is 1 when entering, we do    */
4604 /* have an orphan, otherwise not.  However there is a possible race between */
4605 /* the entry being deleted via flushing with an ioctl call (that calls the  */
4606 /* delete function directly) and the tail end of packet processing so we    */
4607 /* need to grab is_lock before doing the check to synchronise the two code  */
4608 /* paths.                                                                   */
4609 /*                                                                          */
4610 /* When operating in userland (ipftest), we have no timers to clear a state */
4611 /* entry.  Therefore, we make a few simple tests before deleting an entry   */
4612 /* outright.  We compare states on each side looking for a combination of   */
4613 /* TIME_WAIT (should really be FIN_WAIT_2?) and LAST_ACK.  Then we factor   */
4614 /* in packet direction with the interface list to make sure we don't        */
4615 /* prematurely delete an entry on a final inbound packet that's we're also  */
4616 /* supposed to route elsewhere.                                             */
4617 /*                                                                          */
4618 /* Internal parameters:                                                     */
4619 /*    state[0] = state of source (host that initiated connection)           */
4620 /*    state[1] = state of dest   (host that accepted the connection)        */
4621 /*                                                                          */
4622 /*    dir == 0 : a packet from source to dest                               */
4623 /*    dir == 1 : a packet from dest to source                               */
4624 /* ------------------------------------------------------------------------ */
4625 void
4626 ipf_state_deref(ipf_main_softc_t *softc, ipstate_t **isp)
4627 {
4628 	ipstate_t *is = *isp;
4629 
4630 	is = *isp;
4631 	*isp = NULL;
4632 
4633 	MUTEX_ENTER(&is->is_lock);
4634 	if (is->is_ref > 1) {
4635 		is->is_ref--;
4636 		MUTEX_EXIT(&is->is_lock);
4637 #ifndef	_KERNEL
4638 		if ((is->is_sti.tqe_state[0] > IPF_TCPS_ESTABLISHED) ||
4639 		    (is->is_sti.tqe_state[1] > IPF_TCPS_ESTABLISHED)) {
4640 			ipf_state_del(softc, is, ISL_EXPIRE);
4641 		}
4642 #endif
4643 		return;
4644 	}
4645 	MUTEX_EXIT(&is->is_lock);
4646 
4647 	WRITE_ENTER(&softc->ipf_state);
4648 	ipf_state_del(softc, is, ISL_ORPHAN);
4649 	RWLOCK_EXIT(&softc->ipf_state);
4650 }
4651 
4652 
4653 /* ------------------------------------------------------------------------ */
4654 /* Function:    ipf_state_setqueue                                          */
4655 /* Returns:     Nil                                                         */
4656 /* Parameters:  softc(I) - pointer to soft context main structure           */
4657 /*              is(I)    - pointer to state structure                       */
4658 /*              rev(I)   - forward(0) or reverse(1) direction               */
4659 /* Locks:       ipf_state (read or write)                                   */
4660 /*                                                                          */
4661 /* Put the state entry on its default queue entry, using rev as a helped in */
4662 /* determining which queue it should be placed on.                          */
4663 /* ------------------------------------------------------------------------ */
4664 void
4665 ipf_state_setqueue(ipf_main_softc_t *softc, ipstate_t *is, int rev)
4666 {
4667 	ipf_state_softc_t *softs = softc->ipf_state_soft;
4668 	ipftq_t *oifq, *nifq;
4669 
4670 	if ((is->is_sti.tqe_flags & TQE_RULEBASED) != 0)
4671 		nifq = is->is_tqehead[rev];
4672 	else
4673 		nifq = NULL;
4674 
4675 	if (nifq == NULL) {
4676 		switch (is->is_p)
4677 		{
4678 #ifdef USE_INET6
4679 		case IPPROTO_ICMPV6 :
4680 			if (rev == 1)
4681 				nifq = &softs->ipf_state_icmpacktq;
4682 			else
4683 				nifq = &softs->ipf_state_icmptq;
4684 			break;
4685 #endif
4686 		case IPPROTO_ICMP :
4687 			if (rev == 1)
4688 				nifq = &softs->ipf_state_icmpacktq;
4689 			else
4690 				nifq = &softs->ipf_state_icmptq;
4691 			break;
4692 		case IPPROTO_TCP :
4693 			nifq = softs->ipf_state_tcptq + is->is_state[rev];
4694 			break;
4695 
4696 		case IPPROTO_UDP :
4697 			if (rev == 1)
4698 				nifq = &softs->ipf_state_udpacktq;
4699 			else
4700 				nifq = &softs->ipf_state_udptq;
4701 			break;
4702 
4703 		default :
4704 			nifq = &softs->ipf_state_iptq;
4705 			break;
4706 		}
4707 	}
4708 
4709 	oifq = is->is_sti.tqe_ifq;
4710 	/*
4711 	 * If it's currently on a timeout queue, move it from one queue to
4712 	 * another, else put it on the end of the newly determined queue.
4713 	 */
4714 	if (oifq != NULL)
4715 		ipf_movequeue(softc->ipf_ticks, &is->is_sti, oifq, nifq);
4716 	else
4717 		ipf_queueappend(softc->ipf_ticks, &is->is_sti, nifq, is);
4718 	return;
4719 }
4720 
4721 
4722 /* ------------------------------------------------------------------------ */
4723 /* Function:    ipf_state_iter                                              */
4724 /* Returns:     int - 0 == success, else error                              */
4725 /* Parameters:  softc(I) - pointer to main soft context                     */
4726 /*              token(I) - pointer to ipftoken structure                    */
4727 /*              itp(I)   - pointer to ipfgeniter structure                  */
4728 /*              obj(I)   - pointer to data description structure            */
4729 /*                                                                          */
4730 /* This function handles the SIOCGENITER ioctl for the state tables and     */
4731 /* walks through the list of entries in the state table list (softs->ipf_state_list.)    */
4732 /* ------------------------------------------------------------------------ */
4733 static int
4734 ipf_state_iter(ipf_main_softc_t *softc, ipftoken_t *token, ipfgeniter_t *itp,
4735     ipfobj_t *obj)
4736 {
4737 	ipf_state_softc_t *softs = softc->ipf_state_soft;
4738 	ipstate_t *is, *next, zero;
4739 	int error;
4740 
4741 	if (itp->igi_data == NULL) {
4742 		IPFERROR(100026);
4743 		return EFAULT;
4744 	}
4745 
4746 	if (itp->igi_nitems < 1) {
4747 		IPFERROR(100027);
4748 		return ENOSPC;
4749 	}
4750 
4751 	if (itp->igi_type != IPFGENITER_STATE) {
4752 		IPFERROR(100028);
4753 		return EINVAL;
4754 	}
4755 
4756 	is = token->ipt_data;
4757 	if (is == (void *)-1) {
4758 		IPFERROR(100029);
4759 		return ESRCH;
4760 	}
4761 
4762 	error = 0;
4763 	obj->ipfo_type = IPFOBJ_IPSTATE;
4764 	obj->ipfo_size = sizeof(ipstate_t);
4765 
4766 	READ_ENTER(&softc->ipf_state);
4767 
4768 	is = token->ipt_data;
4769 	if (is == NULL) {
4770 		next = softs->ipf_state_list;
4771 	} else {
4772 		next = is->is_next;
4773 	}
4774 
4775 	/*
4776 	 * If we find a state entry to use, bump its reference count so that
4777 	 * it can be used for is_next when we come back.
4778 	 */
4779 	if (next != NULL) {
4780 		MUTEX_ENTER(&next->is_lock);
4781 		next->is_ref++;
4782 		MUTEX_EXIT(&next->is_lock);
4783 		token->ipt_data = next;
4784 	} else {
4785 		bzero(&zero, sizeof(zero));
4786 		next = &zero;
4787 		token->ipt_data = NULL;
4788 	}
4789 	if (next->is_next == NULL)
4790 		ipf_token_mark_complete(token);
4791 
4792 	RWLOCK_EXIT(&softc->ipf_state);
4793 
4794 	obj->ipfo_ptr = itp->igi_data;
4795 	error = ipf_outobjk(softc, obj, next);
4796 	if (is != NULL)
4797 		ipf_state_deref(softc, &is);
4798 
4799 	return error;
4800 }
4801 
4802 
4803 /* ------------------------------------------------------------------------ */
4804 /* Function:    ipf_state_gettable                                          */
4805 /* Returns:     int     - 0 = success, else error                           */
4806 /* Parameters:  softc(I) - pointer to main soft context                     */
4807 /*              softs(I) - pointer to state context structure               */
4808 /*              data(I)  - pointer to ioctl data                             */
4809 /*                                                                          */
4810 /* This function handles ioctl requests for tables of state information.    */
4811 /* At present the only table it deals with is the hash bucket statistics.   */
4812 /* ------------------------------------------------------------------------ */
4813 static int
4814 ipf_state_gettable(ipf_main_softc_t *softc, ipf_state_softc_t *softs,
4815     char *data)
4816 {
4817 	ipftable_t table;
4818 	int error;
4819 
4820 	error = ipf_inobj(softc, data, NULL, &table, IPFOBJ_GTABLE);
4821 	if (error != 0)
4822 		return error;
4823 
4824 	if (table.ita_type != IPFTABLE_BUCKETS) {
4825 		IPFERROR(100031);
4826 		return EINVAL;
4827 	}
4828 
4829 	error = COPYOUT(softs->ipf_state_stats.iss_bucketlen, table.ita_table,
4830 			softs->ipf_state_size * sizeof(u_int));
4831 	if (error != 0) {
4832 		IPFERROR(100032);
4833 		error = EFAULT;
4834 	}
4835 	return error;
4836 }
4837 
4838 
4839 /* ------------------------------------------------------------------------ */
4840 /* Function:    ipf_state_setpending                                        */
4841 /* Returns:     Nil                                                         */
4842 /* Parameters:  softc(I) - pointer to main soft context                     */
4843 /*              is(I)    - pointer to state structure                       */
4844 /* Locks:       ipf_state (read or write)                                   */
4845 /*                                                                          */
4846 /* Put the state entry on to the pending queue - this queue has a very      */
4847 /* short lifetime where items are put that can't be deleted straight away   */
4848 /* because of locking issues but we want to delete them ASAP, anyway.       */
4849 /* ------------------------------------------------------------------------ */
4850 void
4851 ipf_state_setpending(ipf_main_softc_t *softc, ipstate_t *is)
4852 {
4853 	ipf_state_softc_t *softs = softc->ipf_state_soft;
4854 	ipftq_t *oifq;
4855 
4856 	oifq = is->is_sti.tqe_ifq;
4857 	if (oifq != NULL)
4858 		ipf_movequeue(softc->ipf_ticks, &is->is_sti, oifq,
4859 			      &softs->ipf_state_pending);
4860 	else
4861 		ipf_queueappend(softc->ipf_ticks, &is->is_sti,
4862 				&softs->ipf_state_pending, is);
4863 
4864 	MUTEX_ENTER(&is->is_lock);
4865 	if (is->is_me != NULL) {
4866 		*is->is_me = NULL;
4867 		is->is_me = NULL;
4868 		is->is_ref--;
4869 	}
4870 	MUTEX_EXIT(&is->is_lock);
4871 }
4872 
4873 
4874 /* ------------------------------------------------------------------------ */
4875 /* Function:    ipf_state_matchflush                                        */
4876 /* Returns:     Nil                                                         */
4877 /* Parameters:  softc(I) - pointer to main soft context                     */
4878 /*              data(I)  - pointer to state structure                       */
4879 /* Locks:       ipf_state (read or write)                                   */
4880 /*                                                                          */
4881 /* Flush all entries from the list of state entries that match the          */
4882 /* properties in the array loaded.                                          */
4883 /* ------------------------------------------------------------------------ */
4884 int
4885 ipf_state_matchflush(ipf_main_softc_t *softc, void *data)
4886 {
4887 	ipf_state_softc_t *softs = softc->ipf_state_soft;
4888 	int *array, flushed, error;
4889 	ipstate_t *state, *statenext;
4890 	ipfobj_t obj;
4891 
4892 	error = ipf_matcharray_load(softc, data, &obj, &array);
4893 	if (error != 0)
4894 		return error;
4895 
4896 	flushed = 0;
4897 
4898 	for (state = softs->ipf_state_list; state != NULL; state = statenext) {
4899 		statenext = state->is_next;
4900 		if (ipf_state_matcharray(state, array, softc->ipf_ticks) == 0) {
4901 			ipf_state_del(softc, state, ISL_FLUSH);
4902 			flushed++;
4903 		}
4904 	}
4905 
4906 	obj.ipfo_retval = flushed;
4907 	error = BCOPYOUT(&obj, data, sizeof(obj));
4908 
4909 	KFREES(array, array[0] * sizeof(*array));
4910 
4911 	return error;
4912 }
4913 
4914 
4915 /* ------------------------------------------------------------------------ */
4916 /* Function:    ipf_state_matcharray                                        */
4917 /* Returns:     int   - 0 = no match, 1 = match                             */
4918 /* Parameters:  state(I) - pointer to state structure                       */
4919 /*              array(I) - pointer to ipf matching expression               */
4920 /*              ticks(I) - current value of ipfilter tick timer             */
4921 /* Locks:       ipf_state (read or write)                                   */
4922 /*                                                                          */
4923 /* Compare a state entry with the match array passed in and return a value  */
4924 /* to indicate whether or not the matching was successful.                  */
4925 /* ------------------------------------------------------------------------ */
4926 static int
4927 ipf_state_matcharray(ipstate_t *state, int *array, u_long ticks)
4928 {
4929 	int i, n, *x, rv, p;
4930 	ipfexp_t *e;
4931 
4932 	rv = 0;
4933 	n = array[0];
4934 	x = array + 1;
4935 
4936 	for (; n > 0; x += 3 + x[3], rv = 0) {
4937 		e = (ipfexp_t *)x;
4938 		n -= e->ipfe_size;
4939 		if (x[0] == IPF_EXP_END)
4940 			break;
4941 
4942 		/*
4943 		 * If we need to match the protocol and that doesn't match,
4944 		 * don't even both with the instruction array.
4945 		 */
4946 		p = e->ipfe_cmd >> 16;
4947 		if ((p != 0) && (p != state->is_p))
4948 			break;
4949 
4950 		switch (e->ipfe_cmd)
4951 		{
4952 		case IPF_EXP_IP_PR :
4953 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
4954 				rv |= (state->is_p == e->ipfe_arg0[i]);
4955 			}
4956 			break;
4957 
4958 		case IPF_EXP_IP_SRCADDR :
4959 			if (state->is_v != 4)
4960 				break;
4961 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
4962 				rv |= ((state->is_saddr &
4963 					e->ipfe_arg0[i * 2 + 1]) ==
4964 				      e->ipfe_arg0[i * 2]);
4965 			}
4966 			break;
4967 
4968 		case IPF_EXP_IP_DSTADDR :
4969 			if (state->is_v != 4)
4970 				break;
4971 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
4972 				rv |= ((state->is_daddr &
4973 					e->ipfe_arg0[i * 2 + 1]) ==
4974 				       e->ipfe_arg0[i * 2]);
4975 			}
4976 			break;
4977 
4978 		case IPF_EXP_IP_ADDR :
4979 			if (state->is_v != 4)
4980 				break;
4981 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
4982 				rv |= ((state->is_saddr &
4983 					e->ipfe_arg0[i * 2 + 1]) ==
4984 				       e->ipfe_arg0[i * 2]) ||
4985 				       ((state->is_daddr &
4986 					e->ipfe_arg0[i * 2 + 1]) ==
4987 				       e->ipfe_arg0[i * 2]);
4988 			}
4989 			break;
4990 
4991 #ifdef USE_INET6
4992 		case IPF_EXP_IP6_SRCADDR :
4993 			if (state->is_v != 6)
4994 				break;
4995 			for (i = 0; !rv && i < x[3]; i++) {
4996 				rv |= IP6_MASKEQ(&state->is_src.in6,
4997 						 &e->ipfe_arg0[i * 8 + 4],
4998 						 &e->ipfe_arg0[i * 8]);
4999 			}
5000 			break;
5001 
5002 		case IPF_EXP_IP6_DSTADDR :
5003 			if (state->is_v != 6)
5004 				break;
5005 			for (i = 0; !rv && i < x[3]; i++) {
5006 				rv |= IP6_MASKEQ(&state->is_dst.in6,
5007 						 &e->ipfe_arg0[i * 8 + 4],
5008 						 &e->ipfe_arg0[i * 8]);
5009 			}
5010 			break;
5011 
5012 		case IPF_EXP_IP6_ADDR :
5013 			if (state->is_v != 6)
5014 				break;
5015 			for (i = 0; !rv && i < x[3]; i++) {
5016 				rv |= IP6_MASKEQ(&state->is_src.in6,
5017 						 &e->ipfe_arg0[i * 8 + 4],
5018 						 &e->ipfe_arg0[i * 8]) ||
5019 				      IP6_MASKEQ(&state->is_dst.in6,
5020 						 &e->ipfe_arg0[i * 8 + 4],
5021 						 &e->ipfe_arg0[i * 8]);
5022 			}
5023 			break;
5024 #endif
5025 
5026 		case IPF_EXP_UDP_PORT :
5027 		case IPF_EXP_TCP_PORT :
5028 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
5029 				rv |= (state->is_sport == e->ipfe_arg0[i]) ||
5030 				      (state->is_dport == e->ipfe_arg0[i]);
5031 			}
5032 			break;
5033 
5034 		case IPF_EXP_UDP_SPORT :
5035 		case IPF_EXP_TCP_SPORT :
5036 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
5037 				rv |= (state->is_sport == e->ipfe_arg0[i]);
5038 			}
5039 			break;
5040 
5041 		case IPF_EXP_UDP_DPORT :
5042 		case IPF_EXP_TCP_DPORT :
5043 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
5044 				rv |= (state->is_dport == e->ipfe_arg0[i]);
5045 			}
5046 			break;
5047 
5048 		case IPF_EXP_TCP_STATE :
5049 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
5050 				rv |= (state->is_state[0] == e->ipfe_arg0[i]) ||
5051 				      (state->is_state[1] == e->ipfe_arg0[i]);
5052 			}
5053 			break;
5054 
5055 		case IPF_EXP_IDLE_GT :
5056 			rv |= (ticks - state->is_touched > e->ipfe_arg0[0]);
5057 			break;
5058 		}
5059 
5060 		/*
5061 		 * Factor in doing a negative match.
5062 		 */
5063 		rv ^= e->ipfe_not;
5064 
5065 		if (rv == 0)
5066 			break;
5067 	}
5068 
5069 	return rv;
5070 }
5071 
5072 
5073 /* ------------------------------------------------------------------------ */
5074 /* Function:    ipf_state_settimeout                                        */
5075 /* Returns:     int 0 = success, else failure                               */
5076 /* Parameters:  softc(I)  - pointer to main soft context                    */
5077 /*              t(I)      - pointer to tuneable being changed               */
5078 /*              p(I)      - pointer to the new value                        */
5079 /*                                                                          */
5080 /* Sets a timeout value for one of the many timeout queues.  We find the    */
5081 /* correct queue using a somewhat manual process of comparing the timeout   */
5082 /* names for each specific value available and calling ipf_apply_timeout on */
5083 /* that queue so that all of the items on it are updated accordingly.       */
5084 /* ------------------------------------------------------------------------ */
5085 int
5086 ipf_state_settimeout(struct ipf_main_softc_s *softc, ipftuneable_t *t,
5087     ipftuneval_t *p)
5088 {
5089 	ipf_state_softc_t *softs = softc->ipf_state_soft;
5090 
5091 	/*
5092 	 * In case there is nothing to do...
5093 	 */
5094 	if (*t->ipft_pint == p->ipftu_int)
5095 		return 0;
5096 
5097 	if (!strncmp(t->ipft_name, "tcp_", 4))
5098 		return ipf_settimeout_tcp(t, p, softs->ipf_state_tcptq);
5099 
5100 	if (!strcmp(t->ipft_name, "udp_timeout")) {
5101 		ipf_apply_timeout(&softs->ipf_state_udptq, p->ipftu_int);
5102 	} else if (!strcmp(t->ipft_name, "udp_ack_timeout")) {
5103 		ipf_apply_timeout(&softs->ipf_state_udpacktq, p->ipftu_int);
5104 	} else if (!strcmp(t->ipft_name, "icmp_timeout")) {
5105 		ipf_apply_timeout(&softs->ipf_state_icmptq, p->ipftu_int);
5106 	} else if (!strcmp(t->ipft_name, "icmp_ack_timeout")) {
5107 		ipf_apply_timeout(&softs->ipf_state_icmpacktq, p->ipftu_int);
5108 	} else if (!strcmp(t->ipft_name, "ip_timeout")) {
5109 		ipf_apply_timeout(&softs->ipf_state_iptq, p->ipftu_int);
5110 	} else {
5111 		IPFERROR(100034);
5112 		return ESRCH;
5113 	}
5114 
5115 	/*
5116 	 * Update the tuneable being set.
5117 	 */
5118 	*t->ipft_pint = p->ipftu_int;
5119 
5120 	return 0;
5121 }
5122 
5123 
5124 /* ------------------------------------------------------------------------ */
5125 /* Function:    ipf_state_rehash                                            */
5126 /* Returns:     int 0 = success, else failure                               */
5127 /* Parameters:  softc(I)  - pointer to main soft context                    */
5128 /*              t(I)      - pointer to tuneable being changed               */
5129 /*              p(I)      - pointer to the new value                        */
5130 /*                                                                          */
5131 /* To change the size of the state hash table at runtime, a new table has   */
5132 /* to be allocated and then all of the existing entries put in it, bumping  */
5133 /* up the bucketlength for it as we go along.                               */
5134 /* ------------------------------------------------------------------------ */
5135 int
5136 ipf_state_rehash(ipf_main_softc_t *softc, ipftuneable_t *t, ipftuneval_t *p)
5137 {
5138 	ipf_state_softc_t *softs = softc->ipf_state_soft;
5139 	ipstate_t **newtab, *is;
5140 	u_int *bucketlens;
5141 	u_int maxbucket;
5142 	u_int newsize;
5143 	u_int hv;
5144 	int i;
5145 
5146 	newsize = p->ipftu_int;
5147 	/*
5148 	 * In case there is nothing to do...
5149 	 */
5150 	if (newsize == softs->ipf_state_size)
5151 		return 0;
5152 
5153 	KMALLOCS(newtab, ipstate_t **, newsize * sizeof(ipstate_t *));
5154 	if (newtab == NULL) {
5155 		IPFERROR(100035);
5156 		return ENOMEM;
5157 	}
5158 
5159 	KMALLOCS(bucketlens, u_int *, newsize * sizeof(u_int));
5160 	if (bucketlens == NULL) {
5161 		KFREES(newtab, newsize * sizeof(*softs->ipf_state_table));
5162 		IPFERROR(100036);
5163 		return ENOMEM;
5164 	}
5165 
5166 	for (maxbucket = 0, i = newsize; i > 0; i >>= 1)
5167 		maxbucket++;
5168 	maxbucket *= 2;
5169 
5170 	bzero((char *)newtab, newsize * sizeof(ipstate_t *));
5171 	bzero((char *)bucketlens, newsize * sizeof(u_int));
5172 
5173 	WRITE_ENTER(&softc->ipf_state);
5174 
5175 	if (softs->ipf_state_table != NULL) {
5176 		KFREES(softs->ipf_state_table,
5177 		       softs->ipf_state_size * sizeof(*softs->ipf_state_table));
5178 	}
5179 	softs->ipf_state_table = newtab;
5180 
5181 	if (softs->ipf_state_stats.iss_bucketlen != NULL) {
5182 		KFREES(softs->ipf_state_stats.iss_bucketlen,
5183 		       softs->ipf_state_size * sizeof(u_int));
5184 	}
5185 	softs->ipf_state_stats.iss_bucketlen = bucketlens;
5186 	softs->ipf_state_maxbucket = maxbucket;
5187 	softs->ipf_state_size = newsize;
5188 
5189 	/*
5190 	 * Walk through the entire list of state table entries and put them
5191 	 * in the new state table, somewhere.  Because we have a new table,
5192 	 * we need to restart the counter of how many chains are in use.
5193 	 */
5194 	softs->ipf_state_stats.iss_inuse = 0;
5195 	for (is = softs->ipf_state_list; is != NULL; is = is->is_next) {
5196 		is->is_hnext = NULL;
5197 		is->is_phnext = NULL;
5198 		hv = is->is_hv % softs->ipf_state_size;
5199 
5200 		if (softs->ipf_state_table[hv] != NULL)
5201 			softs->ipf_state_table[hv]->is_phnext = &is->is_hnext;
5202 		else
5203 			softs->ipf_state_stats.iss_inuse++;
5204 		is->is_phnext = softs->ipf_state_table + hv;
5205 		is->is_hnext = softs->ipf_state_table[hv];
5206 		softs->ipf_state_table[hv] = is;
5207 		softs->ipf_state_stats.iss_bucketlen[hv]++;
5208 	}
5209 	RWLOCK_EXIT(&softc->ipf_state);
5210 
5211 	return 0;
5212 }
5213 
5214 
5215 /* ------------------------------------------------------------------------ */
5216 /* Function:    ipf_state_add_tq                                            */
5217 /* Returns:     ipftq_t * - NULL = failure, else pointer to new timeout     */
5218 /*                          queue                                           */
5219 /* Parameters:  softc(I)  - pointer to main soft context                    */
5220 /*              ttl(I)    - pointer to the ttl for the new queue            */
5221 /*                                                                          */
5222 /* Request a pointer to a timeout queue that has a ttl as given by the      */
5223 /* value being passed in.  The timeout queue is added tot the list of those */
5224 /* used internally for stateful filtering.                                  */
5225 /* ------------------------------------------------------------------------ */
5226 ipftq_t *
5227 ipf_state_add_tq(ipf_main_softc_t *softc, int ttl)
5228 {
5229 	ipf_state_softc_t *softs = softc->ipf_state_soft;
5230 
5231         return ipf_addtimeoutqueue(softc, &softs->ipf_state_usertq, ttl);
5232 }
5233 
5234 
5235 #ifndef _KERNEL
5236 /*
5237  * Display the built up state table rules and mapping entries.
5238  */
5239 void
5240 ipf_state_dump(ipf_main_softc_t *softc, void *arg)
5241 {
5242 	ipf_state_softc_t *softs = arg;
5243 	ipstate_t *ips;
5244 
5245 	printf("List of active state sessions:\n");
5246 	for (ips = softs->ipf_state_list; ips != NULL; )
5247 		ips = printstate(ips, opts & (OPT_DEBUG|OPT_VERBOSE),
5248 				 softc->ipf_ticks);
5249 }
5250 #endif
5251