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