xref: /titanic_50/usr/src/uts/common/inet/ipf/ip_state.c (revision 275c9da86e89f8abf71135cf63d9fc23671b2e60)
1 /*
2  * Copyright (C) 1995-2003 by Darren Reed.
3  *
4  * See the IPFILTER.LICENCE file for details on licencing.
5  *
6  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
7  * Use is subject to license terms.
8  */
9 
10 #pragma ident	"%Z%%M%	%I%	%E% SMI"
11 
12 #if defined(KERNEL) || defined(_KERNEL)
13 # undef KERNEL
14 # undef _KERNEL
15 # define        KERNEL	1
16 # define        _KERNEL	1
17 #endif
18 #include <sys/errno.h>
19 #include <sys/types.h>
20 #include <sys/param.h>
21 #include <sys/file.h>
22 #if defined(__NetBSD__) && (NetBSD >= 199905) && !defined(IPFILTER_LKM) && \
23     defined(_KERNEL)
24 # include "opt_ipfilter_log.h"
25 #endif
26 #if defined(_KERNEL) && defined(__FreeBSD_version) && \
27     (__FreeBSD_version >= 400000) && !defined(KLD_MODULE)
28 #include "opt_inet6.h"
29 #endif
30 #if !defined(_KERNEL) && !defined(__KERNEL__)
31 # include <stdio.h>
32 # include <stdlib.h>
33 # include <string.h>
34 # define _KERNEL
35 # ifdef __OpenBSD__
36 struct file;
37 # endif
38 # include <sys/uio.h>
39 # undef _KERNEL
40 #endif
41 #if defined(_KERNEL) && (__FreeBSD_version >= 220000)
42 # include <sys/filio.h>
43 # include <sys/fcntl.h>
44 # if (__FreeBSD_version >= 300000) && !defined(IPFILTER_LKM)
45 #  include "opt_ipfilter.h"
46 # endif
47 #else
48 # include <sys/ioctl.h>
49 #endif
50 #include <sys/time.h>
51 #if !defined(linux)
52 # include <sys/protosw.h>
53 #endif
54 #include <sys/socket.h>
55 #if defined(_KERNEL)
56 # include <sys/systm.h>
57 # if !defined(__SVR4) && !defined(__svr4__)
58 #  include <sys/mbuf.h>
59 # endif
60 #endif
61 #if defined(__SVR4) || defined(__svr4__)
62 # include <sys/filio.h>
63 # include <sys/byteorder.h>
64 # ifdef _KERNEL
65 #  include <sys/dditypes.h>
66 # endif
67 # include <sys/stream.h>
68 # include <sys/kmem.h>
69 #endif
70 
71 #include <net/if.h>
72 #ifdef sun
73 # include <net/af.h>
74 #endif
75 #include <net/route.h>
76 #include <netinet/in.h>
77 #include <netinet/in_systm.h>
78 #include <netinet/ip.h>
79 #include <netinet/tcp.h>
80 #if !defined(linux)
81 # include <netinet/ip_var.h>
82 #endif
83 #if !defined(__hpux) && !defined(linux)
84 # include <netinet/tcp_fsm.h>
85 #endif
86 #include <netinet/udp.h>
87 #include <netinet/ip_icmp.h>
88 #include "netinet/ip_compat.h"
89 #include <netinet/tcpip.h>
90 #include "netinet/ip_fil.h"
91 #include "netinet/ip_nat.h"
92 #include "netinet/ip_frag.h"
93 #include "netinet/ip_state.h"
94 #include "netinet/ip_proxy.h"
95 #include "netinet/ipf_stack.h"
96 #ifdef	IPFILTER_SYNC
97 #include "netinet/ip_sync.h"
98 #endif
99 #ifdef	IPFILTER_SCAN
100 #include "netinet/ip_scan.h"
101 #endif
102 #ifdef	USE_INET6
103 #include <netinet/icmp6.h>
104 #endif
105 #if (__FreeBSD_version >= 300000)
106 # include <sys/malloc.h>
107 # if defined(_KERNEL) && !defined(IPFILTER_LKM)
108 #  include <sys/libkern.h>
109 #  include <sys/systm.h>
110 # endif
111 #endif
112 /* END OF INCLUDES */
113 
114 
115 #if !defined(lint)
116 static const char sccsid[] = "@(#)ip_state.c	1.8 6/5/96 (C) 1993-2000 Darren Reed";
117 static const char rcsid[] = "@(#)$Id: ip_state.c,v 2.186.2.36 2005/08/11 19:58:03 darrenr Exp $";
118 #endif
119 
120 #ifdef	USE_INET6
121 static ipstate_t *fr_checkicmp6matchingstate __P((fr_info_t *));
122 #endif
123 static ipstate_t *fr_matchsrcdst __P((fr_info_t *, ipstate_t *, i6addr_t *,
124 				      i6addr_t *, tcphdr_t *, u_32_t));
125 static ipstate_t *fr_checkicmpmatchingstate __P((fr_info_t *));
126 static int fr_state_flush __P((int, int, ipf_stack_t *));
127 static ips_stat_t *fr_statetstats __P((ipf_stack_t *));
128 static void fr_delstate __P((ipstate_t *, int, ipf_stack_t *));
129 static int fr_state_remove __P((caddr_t, ipf_stack_t *));
130 static void fr_ipsmove __P((ipstate_t *, u_int, ipf_stack_t *));
131 static int fr_tcpstate __P((fr_info_t *, tcphdr_t *, ipstate_t *));
132 static int fr_tcpoptions __P((fr_info_t *, tcphdr_t *, tcpdata_t *));
133 static ipstate_t *fr_stclone __P((fr_info_t *, tcphdr_t *, ipstate_t *));
134 static void fr_fixinisn __P((fr_info_t *, ipstate_t *));
135 static void fr_fixoutisn __P((fr_info_t *, ipstate_t *));
136 static void fr_checknewisn __P((fr_info_t *, ipstate_t *));
137 static int fr_stateiter __P((ipftoken_t *, ipfgeniter_t *, ipf_stack_t *));
138 
139 int fr_stputent __P((caddr_t, ipf_stack_t *));
140 int fr_stgetent __P((caddr_t, ipf_stack_t *));
141 
142 #define	ONE_DAY		IPF_TTLVAL(1 * 86400)	/* 1 day */
143 #define	FIVE_DAYS	(5 * ONE_DAY)
144 #define	DOUBLE_HASH(x, ifs)	\
145     (((x) + ifs->ifs_ips_seed[(x) % ifs->ifs_fr_statesize]) % ifs->ifs_fr_statesize)
146 
147 
148 
149 /* ------------------------------------------------------------------------ */
150 /* Function:    fr_stateinit                                                */
151 /* Returns:     int - 0 == success, -1 == failure                           */
152 /* Parameters:  Nil                                                         */
153 /*                                                                          */
154 /* Initialise all the global variables used within the state code.          */
155 /* This action also includes initiailising locks.                           */
156 /* ------------------------------------------------------------------------ */
157 int fr_stateinit(ifs)
158 ipf_stack_t *ifs;
159 {
160 	int i;
161 
162 	KMALLOCS(ifs->ifs_ips_table, ipstate_t **,
163 		 ifs->ifs_fr_statesize * sizeof(ipstate_t *));
164 	if (ifs->ifs_ips_table == NULL)
165 		return -1;
166 	bzero((char *)ifs->ifs_ips_table,
167 	      ifs->ifs_fr_statesize * sizeof(ipstate_t *));
168 
169 	KMALLOCS(ifs->ifs_ips_seed, u_long *,
170 		 ifs->ifs_fr_statesize * sizeof(*ifs->ifs_ips_seed));
171 	if (ifs->ifs_ips_seed == NULL)
172 		return -2;
173 	for (i = 0; i < ifs->ifs_fr_statesize; i++) {
174 		/*
175 		 * XXX - ips_seed[X] should be a random number of sorts.
176 		 */
177 #if  (__FreeBSD_version >= 400000)
178 		ifs->ifs_ips_seed[i] = arc4random();
179 #else
180 		ifs->ifs_ips_seed[i] = ((u_long)ifs->ifs_ips_seed + i) *
181 		    ifs->ifs_fr_statesize;
182 		ifs->ifs_ips_seed[i] ^= 0xa5a55a5a;
183 		ifs->ifs_ips_seed[i] *= (u_long)ifs->ifs_ips_seed;
184 		ifs->ifs_ips_seed[i] ^= 0x5a5aa5a5;
185 		ifs->ifs_ips_seed[i] *= ifs->ifs_fr_statemax;
186 #endif
187 	}
188 
189 	/* fill icmp reply type table */
190 	for (i = 0; i <= ICMP_MAXTYPE; i++)
191 		icmpreplytype4[i] = -1;
192 	icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
193 	icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
194 	icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
195 	icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
196 #ifdef	USE_INET6
197 	/* fill icmp reply type table */
198 	for (i = 0; i <= ICMP6_MAXTYPE; i++)
199 		icmpreplytype6[i] = -1;
200 	icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
201 	icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
202 	icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
203 	icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
204 	icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
205 #endif
206 
207 	KMALLOCS(ifs->ifs_ips_stats.iss_bucketlen, u_long *,
208 		 ifs->ifs_fr_statesize * sizeof(u_long));
209 	if (ifs->ifs_ips_stats.iss_bucketlen == NULL)
210 		return -1;
211 	bzero((char *)ifs->ifs_ips_stats.iss_bucketlen,
212 	      ifs->ifs_fr_statesize * sizeof(u_long));
213 
214 	if (ifs->ifs_fr_state_maxbucket == 0) {
215 		for (i = ifs->ifs_fr_statesize; i > 0; i >>= 1)
216 			ifs->ifs_fr_state_maxbucket++;
217 		ifs->ifs_fr_state_maxbucket *= 2;
218 	}
219 
220 	fr_sttab_init(ifs->ifs_ips_tqtqb, ifs);
221 	ifs->ifs_ips_tqtqb[IPF_TCP_NSTATES - 1].ifq_next = &ifs->ifs_ips_udptq;
222 	ifs->ifs_ips_udptq.ifq_ttl = (u_long)ifs->ifs_fr_udptimeout;
223 	ifs->ifs_ips_udptq.ifq_ref = 1;
224 	ifs->ifs_ips_udptq.ifq_head = NULL;
225 	ifs->ifs_ips_udptq.ifq_tail = &ifs->ifs_ips_udptq.ifq_head;
226 	MUTEX_INIT(&ifs->ifs_ips_udptq.ifq_lock, "ipftq udp tab");
227 	ifs->ifs_ips_udptq.ifq_next = &ifs->ifs_ips_udpacktq;
228 	ifs->ifs_ips_udpacktq.ifq_ttl = (u_long)ifs->ifs_fr_udpacktimeout;
229 	ifs->ifs_ips_udpacktq.ifq_ref = 1;
230 	ifs->ifs_ips_udpacktq.ifq_head = NULL;
231 	ifs->ifs_ips_udpacktq.ifq_tail = &ifs->ifs_ips_udpacktq.ifq_head;
232 	MUTEX_INIT(&ifs->ifs_ips_udpacktq.ifq_lock, "ipftq udpack tab");
233 	ifs->ifs_ips_udpacktq.ifq_next = &ifs->ifs_ips_icmptq;
234 	ifs->ifs_ips_icmptq.ifq_ttl = (u_long)ifs->ifs_fr_icmptimeout;
235 	ifs->ifs_ips_icmptq.ifq_ref = 1;
236 	ifs->ifs_ips_icmptq.ifq_head = NULL;
237 	ifs->ifs_ips_icmptq.ifq_tail = &ifs->ifs_ips_icmptq.ifq_head;
238 	MUTEX_INIT(&ifs->ifs_ips_icmptq.ifq_lock, "ipftq icmp tab");
239 	ifs->ifs_ips_icmptq.ifq_next = &ifs->ifs_ips_icmpacktq;
240 	ifs->ifs_ips_icmpacktq.ifq_ttl = (u_long)ifs->ifs_fr_icmpacktimeout;
241 	ifs->ifs_ips_icmpacktq.ifq_ref = 1;
242 	ifs->ifs_ips_icmpacktq.ifq_head = NULL;
243 	ifs->ifs_ips_icmpacktq.ifq_tail = &ifs->ifs_ips_icmpacktq.ifq_head;
244 	MUTEX_INIT(&ifs->ifs_ips_icmpacktq.ifq_lock, "ipftq icmpack tab");
245 	ifs->ifs_ips_icmpacktq.ifq_next = &ifs->ifs_ips_iptq;
246 	ifs->ifs_ips_iptq.ifq_ttl = (u_long)ifs->ifs_fr_iptimeout;
247 	ifs->ifs_ips_iptq.ifq_ref = 1;
248 	ifs->ifs_ips_iptq.ifq_head = NULL;
249 	ifs->ifs_ips_iptq.ifq_tail = &ifs->ifs_ips_iptq.ifq_head;
250 	MUTEX_INIT(&ifs->ifs_ips_iptq.ifq_lock, "ipftq ip tab");
251 	ifs->ifs_ips_iptq.ifq_next = &ifs->ifs_ips_deletetq;
252 	/* entry's ttl in deletetq is just 1 tick */
253 	ifs->ifs_ips_deletetq.ifq_ttl = (u_long) 1;
254 	ifs->ifs_ips_deletetq.ifq_ref = 1;
255 	ifs->ifs_ips_deletetq.ifq_head = NULL;
256 	ifs->ifs_ips_deletetq.ifq_tail = &ifs->ifs_ips_deletetq.ifq_head;
257 	MUTEX_INIT(&ifs->ifs_ips_deletetq.ifq_lock, "state delete queue");
258 	ifs->ifs_ips_deletetq.ifq_next = NULL;
259 
260 	RWLOCK_INIT(&ifs->ifs_ipf_state, "ipf IP state rwlock");
261 	MUTEX_INIT(&ifs->ifs_ipf_stinsert, "ipf state insert mutex");
262 	ifs->ifs_fr_state_init = 1;
263 
264 	ifs->ifs_ips_last_force_flush = ifs->ifs_fr_ticks;
265 	return 0;
266 }
267 
268 
269 /* ------------------------------------------------------------------------ */
270 /* Function:    fr_stateunload                                              */
271 /* Returns:     Nil                                                         */
272 /* Parameters:  Nil                                                         */
273 /*                                                                          */
274 /* Release and destroy any resources acquired or initialised so that        */
275 /* IPFilter can be unloaded or re-initialised.                              */
276 /* ------------------------------------------------------------------------ */
277 void fr_stateunload(ifs)
278 ipf_stack_t *ifs;
279 {
280 	ipftq_t *ifq, *ifqnext;
281 	ipstate_t *is;
282 
283 	while ((is = ifs->ifs_ips_list) != NULL)
284 	    fr_delstate(is, 0, ifs);
285 
286 	/*
287 	 * Proxy timeout queues are not cleaned here because although they
288 	 * exist on the state list, appr_unload is called after fr_stateunload
289 	 * and the proxies actually are responsible for them being created.
290 	 * Should the proxy timeouts have their own list?  There's no real
291 	 * justification as this is the only complicationA
292 	 */
293 	for (ifq = ifs->ifs_ips_utqe; ifq != NULL; ifq = ifqnext) {
294 		ifqnext = ifq->ifq_next;
295 		if (((ifq->ifq_flags & IFQF_PROXY) == 0) &&
296 		    (fr_deletetimeoutqueue(ifq) == 0))
297 			fr_freetimeoutqueue(ifq, ifs);
298 	}
299 
300 	ifs->ifs_ips_stats.iss_inuse = 0;
301 	ifs->ifs_ips_num = 0;
302 
303 	if (ifs->ifs_fr_state_init == 1) {
304 		fr_sttab_destroy(ifs->ifs_ips_tqtqb);
305 		MUTEX_DESTROY(&ifs->ifs_ips_udptq.ifq_lock);
306 		MUTEX_DESTROY(&ifs->ifs_ips_icmptq.ifq_lock);
307 		MUTEX_DESTROY(&ifs->ifs_ips_udpacktq.ifq_lock);
308 		MUTEX_DESTROY(&ifs->ifs_ips_icmpacktq.ifq_lock);
309 		MUTEX_DESTROY(&ifs->ifs_ips_iptq.ifq_lock);
310 		MUTEX_DESTROY(&ifs->ifs_ips_deletetq.ifq_lock);
311 	}
312 
313 	if (ifs->ifs_ips_table != NULL) {
314 		KFREES(ifs->ifs_ips_table,
315 		       ifs->ifs_fr_statesize * sizeof(*ifs->ifs_ips_table));
316 		ifs->ifs_ips_table = NULL;
317 	}
318 
319 	if (ifs->ifs_ips_seed != NULL) {
320 		KFREES(ifs->ifs_ips_seed,
321 		       ifs->ifs_fr_statesize * sizeof(*ifs->ifs_ips_seed));
322 		ifs->ifs_ips_seed = NULL;
323 	}
324 
325 	if (ifs->ifs_ips_stats.iss_bucketlen != NULL) {
326 		KFREES(ifs->ifs_ips_stats.iss_bucketlen,
327 		       ifs->ifs_fr_statesize * sizeof(u_long));
328 		ifs->ifs_ips_stats.iss_bucketlen = NULL;
329 	}
330 
331 	if (ifs->ifs_fr_state_maxbucket_reset == 1)
332 		ifs->ifs_fr_state_maxbucket = 0;
333 
334 	if (ifs->ifs_fr_state_init == 1) {
335 		ifs->ifs_fr_state_init = 0;
336 		RW_DESTROY(&ifs->ifs_ipf_state);
337 		MUTEX_DESTROY(&ifs->ifs_ipf_stinsert);
338 	}
339 }
340 
341 
342 /* ------------------------------------------------------------------------ */
343 /* Function:    fr_statetstats                                              */
344 /* Returns:     ips_state_t* - pointer to state stats structure             */
345 /* Parameters:  Nil                                                         */
346 /*                                                                          */
347 /* Put all the current numbers and pointers into a single struct and return */
348 /* a pointer to it.                                                         */
349 /* ------------------------------------------------------------------------ */
350 static ips_stat_t *fr_statetstats(ifs)
351 ipf_stack_t *ifs;
352 {
353 	ifs->ifs_ips_stats.iss_active = ifs->ifs_ips_num;
354 	ifs->ifs_ips_stats.iss_statesize = ifs->ifs_fr_statesize;
355 	ifs->ifs_ips_stats.iss_statemax = ifs->ifs_fr_statemax;
356 	ifs->ifs_ips_stats.iss_table = ifs->ifs_ips_table;
357 	ifs->ifs_ips_stats.iss_list = ifs->ifs_ips_list;
358 	ifs->ifs_ips_stats.iss_ticks = ifs->ifs_fr_ticks;
359 	return &ifs->ifs_ips_stats;
360 }
361 
362 /* ------------------------------------------------------------------------ */
363 /* Function:    fr_state_remove                                             */
364 /* Returns:     int - 0 == success, != 0 == failure                         */
365 /* Parameters:  data(I) - pointer to state structure to delete from table   */
366 /*                                                                          */
367 /* Search for a state structure that matches the one passed, according to   */
368 /* the IP addresses and other protocol specific information.                */
369 /* ------------------------------------------------------------------------ */
370 static int fr_state_remove(data, ifs)
371 caddr_t data;
372 ipf_stack_t *ifs;
373 {
374 	ipstate_t *sp, st;
375 	int error;
376 
377 	sp = &st;
378 	error = fr_inobj(data, &st, IPFOBJ_IPSTATE);
379 	if (error)
380 		return EFAULT;
381 
382 	WRITE_ENTER(&ifs->ifs_ipf_state);
383 	for (sp = ifs->ifs_ips_list; sp; sp = sp->is_next)
384 		if ((sp->is_p == st.is_p) && (sp->is_v == st.is_v) &&
385 		    !bcmp((caddr_t)&sp->is_src, (caddr_t)&st.is_src,
386 			  sizeof(st.is_src)) &&
387 		    !bcmp((caddr_t)&sp->is_dst, (caddr_t)&st.is_src,
388 			  sizeof(st.is_dst)) &&
389 		    !bcmp((caddr_t)&sp->is_ps, (caddr_t)&st.is_ps,
390 			  sizeof(st.is_ps))) {
391 			fr_delstate(sp, ISL_REMOVE, ifs);
392 			RWLOCK_EXIT(&ifs->ifs_ipf_state);
393 			return 0;
394 		}
395 	RWLOCK_EXIT(&ifs->ifs_ipf_state);
396 	return ESRCH;
397 }
398 
399 
400 /* ------------------------------------------------------------------------ */
401 /* Function:    fr_state_ioctl                                              */
402 /* Returns:     int - 0 == success, != 0 == failure                         */
403 /* Parameters:  data(I) - pointer to ioctl data                             */
404 /*              cmd(I)  - ioctl command integer                             */
405 /*              mode(I) - file mode bits used with open                     */
406 /*                                                                          */
407 /* Processes an ioctl call made to operate on the IP Filter state device.   */
408 /* ------------------------------------------------------------------------ */
409 int fr_state_ioctl(data, cmd, mode, uid, ctx, ifs)
410 caddr_t data;
411 ioctlcmd_t cmd;
412 int mode, uid;
413 void *ctx;
414 ipf_stack_t *ifs;
415 {
416 	int arg, ret, error = 0;
417 
418 	switch (cmd)
419 	{
420 	/*
421 	 * Delete an entry from the state table.
422 	 */
423 	case SIOCDELST :
424 	    error = fr_state_remove(data, ifs);
425 		break;
426 	/*
427 	 * Flush the state table
428 	 */
429 	case SIOCIPFFL :
430 		BCOPYIN(data, (char *)&arg, sizeof(arg));
431 		if (arg == 0 || arg == 1) {
432 			WRITE_ENTER(&ifs->ifs_ipf_state);
433 			ret = fr_state_flush(arg, 4, ifs);
434 			RWLOCK_EXIT(&ifs->ifs_ipf_state);
435 			BCOPYOUT((char *)&ret, data, sizeof(ret));
436 		} else
437 			error = EINVAL;
438 		break;
439 #ifdef	USE_INET6
440 	case SIOCIPFL6 :
441 		BCOPYIN(data, (char *)&arg, sizeof(arg));
442 		if (arg == 0 || arg == 1) {
443 			WRITE_ENTER(&ifs->ifs_ipf_state);
444 			ret = fr_state_flush(arg, 6, ifs);
445 			RWLOCK_EXIT(&ifs->ifs_ipf_state);
446 			BCOPYOUT((char *)&ret, data, sizeof(ret));
447 		} else
448 			error = EINVAL;
449 		break;
450 #endif
451 #ifdef	IPFILTER_LOG
452 	/*
453 	 * Flush the state log.
454 	 */
455 	case SIOCIPFFB :
456 		if (!(mode & FWRITE))
457 			error = EPERM;
458 		else {
459 			int tmp;
460 
461 			tmp = ipflog_clear(IPL_LOGSTATE, ifs);
462 			BCOPYOUT((char *)&tmp, data, sizeof(tmp));
463 		}
464 		break;
465 	/*
466 	 * Turn logging of state information on/off.
467 	 */
468 	case SIOCSETLG :
469 		if (!(mode & FWRITE))
470 			error = EPERM;
471 		else {
472 			BCOPYIN((char *)data,
473 				       (char *)&ifs->ifs_ipstate_logging,
474 				       sizeof(ifs->ifs_ipstate_logging));
475 		}
476 		break;
477 	/*
478 	 * Return the current state of logging.
479 	 */
480 	case SIOCGETLG :
481 		BCOPYOUT((char *)&ifs->ifs_ipstate_logging, (char *)data,
482 			sizeof(ifs->ifs_ipstate_logging));
483 		break;
484 	/*
485 	 * Return the number of bytes currently waiting to be read.
486 	 */
487 	case FIONREAD :
488 		arg = ifs->ifs_iplused[IPL_LOGSTATE]; /* returned in an int */
489 		BCOPYOUT((char *)&arg, data, sizeof(arg));
490 		break;
491 #endif
492 	/*
493 	 * Get the current state statistics.
494 	 */
495 	case SIOCGETFS :
496 		error = fr_outobj(data, fr_statetstats(ifs), IPFOBJ_STATESTAT);
497 		break;
498 	/*
499 	 * Lock/Unlock the state table.  (Locking prevents any changes, which
500 	 * means no packets match).
501 	 */
502 	case SIOCSTLCK :
503 		if (!(mode & FWRITE)) {
504 			error = EPERM;
505 		} else {
506 			fr_lock(data, &ifs->ifs_fr_state_lock);
507 		}
508 		break;
509 	/*
510 	 * Add an entry to the current state table.
511 	 */
512 	case SIOCSTPUT :
513 		if (!ifs->ifs_fr_state_lock || !(mode &FWRITE)) {
514 			error = EACCES;
515 			break;
516 		}
517 		error = fr_stputent(data, ifs);
518 		break;
519 	/*
520 	 * Get a state table entry.
521 	 */
522 	case SIOCSTGET :
523 		if (!ifs->ifs_fr_state_lock) {
524 			error = EACCES;
525 			break;
526 		}
527 		error = fr_stgetent(data, ifs);
528 		break;
529 
530 	case SIOCGENITER :
531 	    {
532 		ipftoken_t *token;
533 		ipfgeniter_t iter;
534 
535 		error = fr_inobj(data, &iter, IPFOBJ_GENITER);
536 		if (error != 0)
537 			break;
538 
539 		token = ipf_findtoken(IPFGENITER_STATE, uid, ctx, ifs);
540 		if (token != NULL)
541 			error = fr_stateiter(token, &iter, ifs);
542 		else
543 			error = ESRCH;
544 		RWLOCK_EXIT(&ifs->ifs_ipf_tokens);
545 		break;
546 	    }
547 
548 	case SIOCIPFDELTOK :
549 		(void) BCOPYIN(data, (char *)&arg, sizeof(arg));
550 		error = ipf_deltoken(arg, uid, ctx, ifs);
551 		break;
552 
553 	default :
554 		error = EINVAL;
555 		break;
556 	}
557 	return error;
558 }
559 
560 
561 /* ------------------------------------------------------------------------ */
562 /* Function:    fr_stgetent                                                 */
563 /* Returns:     int - 0 == success, != 0 == failure                         */
564 /* Parameters:  data(I) - pointer to state structure to retrieve from table */
565 /*                                                                          */
566 /* Copy out state information from the kernel to a user space process.  If  */
567 /* there is a filter rule associated with the state entry, copy that out    */
568 /* as well.  The entry to copy out is taken from the value of "ips_next" in */
569 /* the struct passed in and if not null and not found in the list of current*/
570 /* state entries, the retrieval fails.                                      */
571 /* ------------------------------------------------------------------------ */
572 int fr_stgetent(data, ifs)
573 caddr_t data;
574 ipf_stack_t *ifs;
575 {
576 	ipstate_t *is, *isn;
577 	ipstate_save_t ips;
578 	int error;
579 
580 	error = fr_inobj(data, &ips, IPFOBJ_STATESAVE);
581 	if (error)
582 		return EFAULT;
583 
584 	isn = ips.ips_next;
585 	if (isn == NULL) {
586 		isn = ifs->ifs_ips_list;
587 		if (isn == NULL) {
588 			if (ips.ips_next == NULL)
589 				return ENOENT;
590 			return 0;
591 		}
592 	} else {
593 		/*
594 		 * Make sure the pointer we're copying from exists in the
595 		 * current list of entries.  Security precaution to prevent
596 		 * copying of random kernel data.
597 		 */
598 		for (is = ifs->ifs_ips_list; is; is = is->is_next)
599 			if (is == isn)
600 				break;
601 		if (!is)
602 			return ESRCH;
603 	}
604 	ips.ips_next = isn->is_next;
605 	bcopy((char *)isn, (char *)&ips.ips_is, sizeof(ips.ips_is));
606 	ips.ips_rule = isn->is_rule;
607 	if (isn->is_rule != NULL)
608 		bcopy((char *)isn->is_rule, (char *)&ips.ips_fr,
609 		      sizeof(ips.ips_fr));
610 	error = fr_outobj(data, &ips, IPFOBJ_STATESAVE);
611 	if (error)
612 		return EFAULT;
613 	return 0;
614 }
615 
616 
617 /* ------------------------------------------------------------------------ */
618 /* Function:    fr_stputent                                                 */
619 /* Returns:     int - 0 == success, != 0 == failure                         */
620 /* Parameters:  data(I) - pointer to state information struct               */
621 /*                                                                          */
622 /* This function implements the SIOCSTPUT ioctl: insert a state entry into  */
623 /* the state table.  If the state info. includes a pointer to a filter rule */
624 /* then also add in an orphaned rule (will not show up in any "ipfstat -io" */
625 /* output.                                                                  */
626 /* ------------------------------------------------------------------------ */
627 int fr_stputent(data, ifs)
628 caddr_t data;
629 ipf_stack_t *ifs;
630 {
631 	ipstate_t *is, *isn;
632 	ipstate_save_t ips;
633 	int error, i;
634 	frentry_t *fr;
635 	char *name;
636 
637 	error = fr_inobj(data, &ips, IPFOBJ_STATESAVE);
638 	if (error)
639 		return EFAULT;
640 
641 	KMALLOC(isn, ipstate_t *);
642 	if (isn == NULL)
643 		return ENOMEM;
644 
645 	bcopy((char *)&ips.ips_is, (char *)isn, sizeof(*isn));
646 	bzero((char *)isn, offsetof(struct ipstate, is_pkts));
647 	isn->is_sti.tqe_pnext = NULL;
648 	isn->is_sti.tqe_next = NULL;
649 	isn->is_sti.tqe_ifq = NULL;
650 	isn->is_sti.tqe_parent = isn;
651 	isn->is_ifp[0] = NULL;
652 	isn->is_ifp[1] = NULL;
653 	isn->is_ifp[2] = NULL;
654 	isn->is_ifp[3] = NULL;
655 	isn->is_sync = NULL;
656 	fr = ips.ips_rule;
657 
658 	if (fr == NULL) {
659 		READ_ENTER(&ifs->ifs_ipf_state);
660 		fr_stinsert(isn, 0, ifs);
661 		MUTEX_EXIT(&isn->is_lock);
662 		RWLOCK_EXIT(&ifs->ifs_ipf_state);
663 		return 0;
664 	}
665 
666 	if (isn->is_flags & SI_NEWFR) {
667 		KMALLOC(fr, frentry_t *);
668 		if (fr == NULL) {
669 			KFREE(isn);
670 			return ENOMEM;
671 		}
672 		bcopy((char *)&ips.ips_fr, (char *)fr, sizeof(*fr));
673 		isn->is_rule = fr;
674 		ips.ips_is.is_rule = fr;
675 		MUTEX_NUKE(&fr->fr_lock);
676 		MUTEX_INIT(&fr->fr_lock, "state filter rule lock");
677 
678 		/*
679 		 * Look up all the interface names in the rule.
680 		 */
681 		for (i = 0; i < 4; i++) {
682 			name = fr->fr_ifnames[i];
683 			fr->fr_ifas[i] = fr_resolvenic(name, fr->fr_v, ifs);
684 			name = isn->is_ifname[i];
685 			isn->is_ifp[i] = fr_resolvenic(name, isn->is_v, ifs);
686 		}
687 
688 		fr->fr_ref = 0;
689 		fr->fr_dsize = 0;
690 		fr->fr_data = NULL;
691 
692 		fr_resolvedest(&fr->fr_tif, fr->fr_v, ifs);
693 		fr_resolvedest(&fr->fr_dif, fr->fr_v, ifs);
694 		fr_resolvedest(&fr->fr_rif, fr->fr_v, ifs);
695 
696 		/*
697 		 * send a copy back to userland of what we ended up
698 		 * to allow for verification.
699 		 */
700 		error = fr_outobj(data, &ips, IPFOBJ_STATESAVE);
701 		if (error) {
702 			KFREE(isn);
703 			MUTEX_DESTROY(&fr->fr_lock);
704 			KFREE(fr);
705 			return EFAULT;
706 		}
707 		READ_ENTER(&ifs->ifs_ipf_state);
708 		fr_stinsert(isn, 0, ifs);
709 		MUTEX_EXIT(&isn->is_lock);
710 		RWLOCK_EXIT(&ifs->ifs_ipf_state);
711 
712 	} else {
713 		READ_ENTER(&ifs->ifs_ipf_state);
714 		for (is = ifs->ifs_ips_list; is; is = is->is_next)
715 			if (is->is_rule == fr) {
716 				fr_stinsert(isn, 0, ifs);
717 				MUTEX_EXIT(&isn->is_lock);
718 				break;
719 			}
720 
721 		if (is == NULL) {
722 			KFREE(isn);
723 			isn = NULL;
724 		}
725 		RWLOCK_EXIT(&ifs->ifs_ipf_state);
726 
727 		return (isn == NULL) ? ESRCH : 0;
728 	}
729 
730 	return 0;
731 }
732 
733 
734 /* ------------------------------------------------------------------------ */
735 /* Function:   fr_stinsert                                                  */
736 /* Returns:    Nil                                                          */
737 /* Parameters: is(I)  - pointer to state structure                          */
738 /*             rev(I) - flag indicating forward/reverse direction of packet */
739 /*                                                                          */
740 /* Inserts a state structure into the hash table (for lookups) and the list */
741 /* of state entries (for enumeration).  Resolves all of the interface names */
742 /* to pointers and adjusts running stats for the hash table as appropriate. */
743 /*                                                                          */
744 /* Locking: it is assumed that some kind of lock on ipf_state is held.      */
745 /*          Exits with is_lock initialised and held.                        */
746 /* ------------------------------------------------------------------------ */
747 void fr_stinsert(is, rev, ifs)
748 ipstate_t *is;
749 int rev;
750 ipf_stack_t *ifs;
751 {
752 	frentry_t *fr;
753 	u_int hv;
754 	int i;
755 
756 	MUTEX_INIT(&is->is_lock, "ipf state entry");
757 
758 	fr = is->is_rule;
759 	if (fr != NULL) {
760 		MUTEX_ENTER(&fr->fr_lock);
761 		fr->fr_ref++;
762 		fr->fr_statecnt++;
763 		MUTEX_EXIT(&fr->fr_lock);
764 	}
765 
766 	/*
767 	 * Look up all the interface names in the state entry.
768 	 */
769 	for (i = 0; i < 4; i++) {
770 		if (is->is_ifp[i] != NULL)
771 			continue;
772 		is->is_ifp[i] = fr_resolvenic(is->is_ifname[i], is->is_v, ifs);
773 	}
774 
775 	/*
776 	 * If we could trust is_hv, then the modulous would not be needed, but
777 	 * when running with IPFILTER_SYNC, this stops bad values.
778 	 */
779 	hv = is->is_hv % ifs->ifs_fr_statesize;
780 	is->is_hv = hv;
781 
782 	/*
783 	 * We need to get both of these locks...the first because it is
784 	 * possible that once the insert is complete another packet might
785 	 * come along, match the entry and want to update it.
786 	 */
787 	MUTEX_ENTER(&is->is_lock);
788 	MUTEX_ENTER(&ifs->ifs_ipf_stinsert);
789 
790 	/*
791 	 * add into list table.
792 	 */
793 	if (ifs->ifs_ips_list != NULL)
794 		ifs->ifs_ips_list->is_pnext = &is->is_next;
795 	is->is_pnext = &ifs->ifs_ips_list;
796 	is->is_next = ifs->ifs_ips_list;
797 	ifs->ifs_ips_list = is;
798 
799 	if (ifs->ifs_ips_table[hv] != NULL)
800 		ifs->ifs_ips_table[hv]->is_phnext = &is->is_hnext;
801 	else
802 		ifs->ifs_ips_stats.iss_inuse++;
803 	is->is_phnext = ifs->ifs_ips_table + hv;
804 	is->is_hnext = ifs->ifs_ips_table[hv];
805 	ifs->ifs_ips_table[hv] = is;
806 	ifs->ifs_ips_stats.iss_bucketlen[hv]++;
807 	ifs->ifs_ips_num++;
808 	MUTEX_EXIT(&ifs->ifs_ipf_stinsert);
809 
810 	fr_setstatequeue(is, rev, ifs);
811 }
812 
813 /* ------------------------------------------------------------------------ */
814 /* Function:	fr_match_ipv4addrs					    */
815 /* Returns:	int -	2 strong match (same addresses, same direction)	    */
816 /*			1 weak match (same address, opposite direction)	    */
817 /*			0 no match					    */
818 /*									    */
819 /* Function matches IPv4 addresses.					    */
820 /* ------------------------------------------------------------------------ */
821 static int fr_match_ipv4addrs(is1, is2)
822 ipstate_t *is1;
823 ipstate_t *is2;
824 {
825 	int	rv;
826 
827 	if (is1->is_saddr == is2->is_saddr && is1->is_daddr == is2->is_daddr)
828 		rv = 2;
829 	else if (is1->is_saddr == is2->is_daddr &&
830 	    is1->is_daddr == is2->is_saddr)
831 		rv = 1;
832 	else
833 		rv = 0;
834 
835 	return (rv);
836 }
837 
838 /* ------------------------------------------------------------------------ */
839 /* Function:	fr_match_ipv6addrs					    */
840 /* Returns:	int - 	2 strong match (same addresses, same direction)	    */
841 /*			1 weak match (same addresses, opposite direction)   */
842 /*			0 no match					    */
843 /*									    */
844 /* Function matches IPv6 addresses.					    */
845 /* ------------------------------------------------------------------------ */
846 static int fr_match_ipv6addrs(is1, is2)
847 ipstate_t *is1;
848 ipstate_t *is2;
849 {
850 	int	rv;
851 
852 	if (IP6_EQ(&is1->is_src, &is2->is_src) &&
853 	    IP6_EQ(&is1->is_dst, &is2->is_dst))
854 		rv = 2;
855 	else if (IP6_EQ(&is1->is_src, &is2->is_dst) &&
856 	    IP6_EQ(&is1->is_dst, &is2->is_src)) {
857 		rv = 1;
858 	}
859 	else
860 		rv = 0;
861 
862 	return (rv);
863 }
864 /* ------------------------------------------------------------------------ */
865 /* Function:	fr_match_addresses					    */
866 /* Returns:	int - 	2 strong match (same addresses, same direction)	    */
867 /*			1 weak match (same address, opposite directions)    */
868 /* 			0 no match					    */
869 /* Parameters:	is1, is2 pointers to states we are checking		    */
870 /*									    */
871 /* Matches addresses, function uses fr_match_ipvXaddrs() to deal with IPv4  */
872 /* and IPv6 address format.						    */
873 /* ------------------------------------------------------------------------ */
874 static int fr_match_addresses(is1, is2)
875 ipstate_t *is1;
876 ipstate_t *is2;
877 {
878 	int	rv;
879 
880 	if (is1->is_v == 4) {
881 		rv = fr_match_ipv4addrs(is1, is2);
882 	}
883 	else {
884 		rv = fr_match_ipv6addrs(is1, is2);
885 	}
886 
887 	return (rv);
888 }
889 
890 /* ------------------------------------------------------------------------ */
891 /* Function:	fr_match_ppairs						    */
892 /* Returns:	int - 	2 strong match (same ports, same direction)	    */
893 /*			1 weak match (same ports, different direction)	    */
894 /*			0 no match					    */
895 /* Parameters	ppairs1, ppairs - src, dst ports we want to match.	    */
896 /*									    */
897 /* Matches two port_pair_t types (port pairs). Each port pair contains	    */
898 /* src, dst port, which belong to session (state entry).		    */
899 /* ------------------------------------------------------------------------ */
900 static int fr_match_ppairs(ppairs1, ppairs2)
901 port_pair_t *ppairs1;
902 port_pair_t *ppairs2;
903 {
904 	int	rv;
905 
906 	if (ppairs1->pp_sport == ppairs2->pp_sport &&
907 	    ppairs1->pp_dport == ppairs2->pp_dport)
908 		rv = 2;
909 	else if (ppairs1->pp_sport == ppairs2->pp_dport &&
910 		    ppairs1->pp_dport == ppairs2->pp_sport)
911 		rv = 1;
912 	else
913 		rv = 0;
914 
915 	return (rv);
916 }
917 
918 /* ------------------------------------------------------------------------ */
919 /* Function:	fr_match_l4_hdr						    */
920 /* Returns:	int - 	0 no match, 					    */
921 /*			1 weak match (same ports, different directions)	    */
922 /*			2 strong match (same ports, same direction)	    */
923 /* Parameters	is1, is2 - states we want to match			    */
924 /*									    */
925 /* Function matches L4 header data (source ports for TCP, UDP, CallIds for  */
926 /* GRE protocol).							    */
927 /* ------------------------------------------------------------------------ */
928 static int fr_match_l4_hdr(is1, is2)
929 ipstate_t *is1;
930 ipstate_t *is2;
931 {
932 	int	rv = 0;
933 	port_pair_t	pp1;
934 	port_pair_t	pp2;
935 
936 	if (is1->is_p != is2->is_p)
937 		return (0);
938 
939 	switch (is1->is_p) {
940 		case	IPPROTO_TCP:
941 			pp1.pp_sport = is1->is_ps.is_ts.ts_sport;
942 			pp1.pp_dport = is1->is_ps.is_ts.ts_dport;
943 			pp2.pp_sport = is2->is_ps.is_ts.ts_sport;
944 			pp2.pp_dport = is2->is_ps.is_ts.ts_dport;
945 			rv = fr_match_ppairs(&pp1, &pp2);
946 			break;
947 		case	IPPROTO_UDP:
948 			pp1.pp_sport = is1->is_ps.is_us.us_sport;
949 			pp1.pp_dport = is1->is_ps.is_us.us_dport;
950 			pp2.pp_sport = is2->is_ps.is_us.us_sport;
951 			pp2.pp_dport = is2->is_ps.is_us.us_dport;
952 			rv = fr_match_ppairs(&pp1, &pp2);
953 			break;
954 		case	IPPROTO_GRE:
955 			/* greinfo_t can be also interprted as port pair */
956 			pp1.pp_sport = is1->is_ps.is_ug.gs_call[0];
957 			pp1.pp_dport = is1->is_ps.is_ug.gs_call[1];
958 			pp2.pp_sport = is2->is_ps.is_ug.gs_call[0];
959 			pp2.pp_dport = is2->is_ps.is_ug.gs_call[1];
960 			rv = fr_match_ppairs(&pp1, &pp2);
961 			break;
962 		case	IPPROTO_ICMP:
963 		case	IPPROTO_ICMPV6:
964 			if (bcmp(&is1->is_ps, &is2->is_ps, sizeof(icmpinfo_t)))
965 				rv = 1;
966 			else
967 				rv = 0;
968 			break;
969 		default:
970 			rv = 0;
971 	}
972 
973 	return (rv);
974 }
975 
976 /* ------------------------------------------------------------------------ */
977 /* Function:	fr_matchstates						    */
978 /* Returns:	int - nonzero match, zero no match			    */
979 /* Parameters	is1, is2 - states we want to match			    */
980 /*									    */
981 /* The state entries are equal (identical match) if they belong to the same */
982 /* session. Any time new state entry is being added the fr_addstate() 	    */
983 /* function creates temporal state entry from the data it gets from IP and  */
984 /* L4 header. The fr_matchstats() must be also aware of packet direction,   */
985 /* which is also stored within the state entry. We should keep in mind the  */
986 /* information about packet direction is spread accross L3 (addresses) and  */
987 /* L4 (ports). There are three possible relationships betwee is1, is2:	    */
988 /* 		- no match (match(is1, is2) == 0))			    */
989 /*		- weak match same addresses (ports), but different 	    */
990 /*			directions (1)	(fr_match_xxxx(is1, is2) == 1)	    */
991 /*		- strong match same addresses (ports) and same directions   */
992 /*			 (2) (fr_match_xxxx(is1, is2) == 2)		    */
993 /*									    */
994 /* There are functions, which match match addresses (L3 header) in is1, is2 */
995 /* and functions, which are used to compare ports (L4 header) data. We say  */
996 /* the is1 and is2 are same (identical) if there is a match		    */
997 /* (fr_match_l4_hdr(is1, is2) != 0) and matchlevels are same for entries    */
998 /* (fr_match_l3_hdr(is1, is2) == fr_match_l4_hdr(is1, is2)) for is1, is2.   */
999 /* Such requirement deals with case as follows:				    */
1000 /*	suppose there are two connections between hosts A, B. Connection 1: */
1001 /*			a.a.a.a:12345 <=> b.b.b.b:54321			    */
1002 /*		Connection 2:						    */
1003 /*			a.a.a.a:54321 <=> b.b.b.b:12345			    */
1004 /* since we've introduced match levels into our fr_matchstates(), we are    */
1005 /* able to identify, which packets belong to connection A and which belong  */
1006 /* to connection B.	Assume there are two entries is1, is2. is1 has been */
1007 /* from con. 1 packet, which travelled from A to B:			    */
1008 /*			a.a.a.a:12345 -> b.b.b.b:54321			    */
1009 /* while s2, has been created from packet which belongs to con. 2 and is    */
1010 /* also coming from A to B:						    */
1011 /*			a.a.a.a:54321 -> b.b.b.b:12345			    */
1012 /* fr_match_l3_hdr(is1, is2) == 2 -> strong match, while		    */
1013 /* fr_match_l4_hdr(is1, is2) == 1 -> weak match. Since match levels are	    */
1014 /* different the state entries are not identical -> no match as a final	    */
1015 /* result.								    */
1016 /* ------------------------------------------------------------------------ */
1017 static int fr_matchstates(is1, is2)
1018 ipstate_t *is1;
1019 ipstate_t *is2;
1020 {
1021 	int	rv;
1022 	int	amatch;
1023 	int	pmatch;
1024 
1025 	if (bcmp(&is1->is_pass, &is2->is_pass,
1026 		 offsetof(struct ipstate, is_ps) -
1027 		 offsetof(struct ipstate, is_pass)) == 0) {
1028 
1029 		pmatch = fr_match_l4_hdr(is1, is2);
1030 		amatch = fr_match_addresses(is1, is2);
1031 		/*
1032 		 * If addresses match (amatch != 0), then 'match levels'
1033 		 * must be same for matching entries. If amatch and pmatch
1034 		 * have different values (different match levels), then
1035 		 * is1 and is2 belong to different sessions.
1036 		 */
1037 		rv = (amatch != 0) && (amatch == pmatch);
1038 	}
1039 	else
1040 		rv = 0;
1041 
1042 	return (rv);
1043 }
1044 
1045 /* ------------------------------------------------------------------------ */
1046 /* Function:    fr_addstate                                                 */
1047 /* Returns:     ipstate_t* - NULL == failure, else pointer to new state     */
1048 /* Parameters:  fin(I)    - pointer to packet information                   */
1049 /*              stsave(O) - pointer to place to save pointer to created     */
1050 /*                          state structure.                                */
1051 /*              flags(I)  - flags to use when creating the structure        */
1052 /*                                                                          */
1053 /* Creates a new IP state structure from the packet information collected.  */
1054 /* Inserts it into the state table and appends to the bottom of the active  */
1055 /* list.  If the capacity of the table has reached the maximum allowed then */
1056 /* the call will fail and a flush is scheduled for the next timeout call.   */
1057 /* ------------------------------------------------------------------------ */
1058 ipstate_t *fr_addstate(fin, stsave, flags)
1059 fr_info_t *fin;
1060 ipstate_t **stsave;
1061 u_int flags;
1062 {
1063 	ipstate_t *is, ips;
1064 	struct icmp *ic;
1065 	u_int pass, hv;
1066 	frentry_t *fr;
1067 	tcphdr_t *tcp;
1068 	grehdr_t *gre;
1069 	void *ifp;
1070 	int out;
1071 	ipf_stack_t *ifs = fin->fin_ifs;
1072 
1073 	if (ifs->ifs_fr_state_lock ||
1074 	    (fin->fin_flx & (FI_SHORT|FI_STATE|FI_FRAGBODY|FI_BAD)))
1075 		return NULL;
1076 
1077 	if ((fin->fin_flx & FI_OOW) && !(fin->fin_tcpf & TH_SYN))
1078 		return NULL;
1079 
1080 	/*
1081 	 * If a "keep state" rule has reached the maximum number of references
1082 	 * to it, then schedule an automatic flush in case we can clear out
1083 	 * some "dead old wood".  Note that because the lock isn't held on
1084 	 * fr it is possible that we could overflow.  The cost of overflowing
1085 	 * is being ignored here as the number by which it can overflow is
1086 	 * a product of the number of simultaneous threads that could be
1087 	 * executing in here, so a limit of 100 won't result in 200, but could
1088 	 * result in 101 or 102.
1089 	 */
1090 	fr = fin->fin_fr;
1091 	if (fr != NULL) {
1092 		if ((ifs->ifs_ips_num == ifs->ifs_fr_statemax) && (fr->fr_statemax == 0)) {
1093 			ATOMIC_INCL(ifs->ifs_ips_stats.iss_max);
1094 			ifs->ifs_fr_state_doflush = 1;
1095 			return NULL;
1096 		}
1097 		if ((fr->fr_statemax != 0) &&
1098 		    (fr->fr_statecnt >= fr->fr_statemax)) {
1099 			ATOMIC_INCL(ifs->ifs_ips_stats.iss_maxref);
1100 			ifs->ifs_fr_state_doflush = 1;
1101 			return NULL;
1102 		}
1103 	}
1104 
1105 	ic = NULL;
1106 	tcp = NULL;
1107 	out = fin->fin_out;
1108 	is = &ips;
1109 	bzero((char *)is, sizeof(*is));
1110 
1111 	if (fr == NULL) {
1112 		pass = ifs->ifs_fr_flags;
1113 		is->is_tag = FR_NOLOGTAG;
1114 	}
1115 	else {
1116 		pass = fr->fr_flags;
1117 	}
1118 
1119 	is->is_die = 1 + ifs->ifs_fr_ticks;
1120 	/*
1121 	 * We want to check everything that is a property of this packet,
1122 	 * but we don't (automatically) care about it's fragment status as
1123 	 * this may change.
1124 	 */
1125 	is->is_pass = pass;
1126 	is->is_v = fin->fin_v;
1127 	is->is_opt[0] = fin->fin_optmsk;
1128 	is->is_optmsk[0] = 0xffffffff;
1129 	is->is_optmsk[1] = 0xffffffff;
1130 	if (is->is_v == 6) {
1131 		is->is_opt[0] &= ~0x8;
1132 		is->is_optmsk[0] &= ~0x8;
1133 		is->is_optmsk[1] &= ~0x8;
1134 	}
1135 	is->is_sec = fin->fin_secmsk;
1136 	is->is_secmsk = 0xffff;
1137 	is->is_auth = fin->fin_auth;
1138 	is->is_authmsk = 0xffff;
1139 
1140 	/*
1141 	 * Copy and calculate...
1142 	 */
1143 	hv = (is->is_p = fin->fin_fi.fi_p);
1144 	is->is_src = fin->fin_fi.fi_src;
1145 	hv += is->is_saddr;
1146 	is->is_dst = fin->fin_fi.fi_dst;
1147 	hv += is->is_daddr;
1148 #ifdef	USE_INET6
1149 	if (fin->fin_v == 6) {
1150 		/*
1151 		 * For ICMPv6, we check to see if the destination address is
1152 		 * a multicast address.  If it is, do not include it in the
1153 		 * calculation of the hash because the correct reply will come
1154 		 * back from a real address, not a multicast address.
1155 		 */
1156 		if ((is->is_p == IPPROTO_ICMPV6) &&
1157 		    IN6_IS_ADDR_MULTICAST(&is->is_dst.in6)) {
1158 			/*
1159 			 * So you can do keep state with neighbour discovery.
1160 			 *
1161 			 * Here we could use the address from the neighbour
1162 			 * solicit message to put in the state structure and
1163 			 * we could use that without a wildcard flag too...
1164 			 */
1165 			is->is_flags |= SI_W_DADDR;
1166 			hv -= is->is_daddr;
1167 		} else {
1168 			hv += is->is_dst.i6[1];
1169 			hv += is->is_dst.i6[2];
1170 			hv += is->is_dst.i6[3];
1171 		}
1172 		hv += is->is_src.i6[1];
1173 		hv += is->is_src.i6[2];
1174 		hv += is->is_src.i6[3];
1175 	}
1176 #endif
1177 
1178 	switch (is->is_p)
1179 	{
1180 #ifdef	USE_INET6
1181 	case IPPROTO_ICMPV6 :
1182 		ic = fin->fin_dp;
1183 
1184 		switch (ic->icmp_type)
1185 		{
1186 		case ICMP6_ECHO_REQUEST :
1187 			is->is_icmp.ici_type = ic->icmp_type;
1188 			hv += (is->is_icmp.ici_id = ic->icmp_id);
1189 			break;
1190 		case ICMP6_MEMBERSHIP_QUERY :
1191 		case ND_ROUTER_SOLICIT :
1192 		case ND_NEIGHBOR_SOLICIT :
1193 		case ICMP6_NI_QUERY :
1194 			is->is_icmp.ici_type = ic->icmp_type;
1195 			break;
1196 		default :
1197 			return NULL;
1198 		}
1199 		ATOMIC_INCL(ifs->ifs_ips_stats.iss_icmp);
1200 		break;
1201 #endif
1202 	case IPPROTO_ICMP :
1203 		ic = fin->fin_dp;
1204 
1205 		switch (ic->icmp_type)
1206 		{
1207 		case ICMP_ECHO :
1208 		case ICMP_TSTAMP :
1209 		case ICMP_IREQ :
1210 		case ICMP_MASKREQ :
1211 			is->is_icmp.ici_type = ic->icmp_type;
1212 			hv += (is->is_icmp.ici_id = ic->icmp_id);
1213 			break;
1214 		default :
1215 			return NULL;
1216 		}
1217 		ATOMIC_INCL(ifs->ifs_ips_stats.iss_icmp);
1218 		break;
1219 
1220 	case IPPROTO_GRE :
1221 		gre = fin->fin_dp;
1222 
1223 		is->is_gre.gs_flags = gre->gr_flags;
1224 		is->is_gre.gs_ptype = gre->gr_ptype;
1225 		if (GRE_REV(is->is_gre.gs_flags) == 1) {
1226 			is->is_call[0] = fin->fin_data[0];
1227 			is->is_call[1] = fin->fin_data[1];
1228 		}
1229 		break;
1230 
1231 	case IPPROTO_TCP :
1232 		tcp = fin->fin_dp;
1233 
1234 		if (tcp->th_flags & TH_RST)
1235 			return NULL;
1236 		/*
1237 		 * The endian of the ports doesn't matter, but the ack and
1238 		 * sequence numbers do as we do mathematics on them later.
1239 		 */
1240 		is->is_sport = htons(fin->fin_data[0]);
1241 		is->is_dport = htons(fin->fin_data[1]);
1242 		if ((flags & (SI_W_DPORT|SI_W_SPORT)) == 0) {
1243 			hv += is->is_sport;
1244 			hv += is->is_dport;
1245 		}
1246 
1247 		/*
1248 		 * If this is a real packet then initialise fields in the
1249 		 * state information structure from the TCP header information.
1250 		 */
1251 
1252 		is->is_maxdwin = 1;
1253 		is->is_maxswin = ntohs(tcp->th_win);
1254 		if (is->is_maxswin == 0)
1255 			is->is_maxswin = 1;
1256 
1257 		if ((fin->fin_flx & FI_IGNORE) == 0) {
1258 			is->is_send = ntohl(tcp->th_seq) + fin->fin_dlen -
1259 				      (TCP_OFF(tcp) << 2) +
1260 				      ((tcp->th_flags & TH_SYN) ? 1 : 0) +
1261 				      ((tcp->th_flags & TH_FIN) ? 1 : 0);
1262 			is->is_maxsend = is->is_send;
1263 
1264 			/*
1265 			 * Window scale option is only present in
1266 			 * SYN/SYN-ACK packet.
1267 			 */
1268 			if ((tcp->th_flags & ~(TH_FIN|TH_ACK|TH_ECNALL)) ==
1269 			    TH_SYN &&
1270 			    (TCP_OFF(tcp) > (sizeof(tcphdr_t) >> 2))) {
1271 				if (fr_tcpoptions(fin, tcp,
1272 					      &is->is_tcp.ts_data[0]))
1273 					is->is_swinflags = TCP_WSCALE_SEEN|
1274 							   TCP_WSCALE_FIRST;
1275 			}
1276 
1277 			if ((fin->fin_out != 0) && (pass & FR_NEWISN) != 0) {
1278 				fr_checknewisn(fin, is);
1279 				fr_fixoutisn(fin, is);
1280 			}
1281 
1282 			if ((tcp->th_flags & TH_OPENING) == TH_SYN)
1283 				flags |= IS_TCPFSM;
1284 			else {
1285 				is->is_maxdwin = is->is_maxswin * 2;
1286 				is->is_dend = ntohl(tcp->th_ack);
1287 				is->is_maxdend = ntohl(tcp->th_ack);
1288 				is->is_maxdwin *= 2;
1289 			}
1290 		}
1291 
1292 		/*
1293 		 * If we're creating state for a starting connection, start the
1294 		 * timer on it as we'll never see an error if it fails to
1295 		 * connect.
1296 		 */
1297 		ATOMIC_INCL(ifs->ifs_ips_stats.iss_tcp);
1298 		break;
1299 
1300 	case IPPROTO_UDP :
1301 		tcp = fin->fin_dp;
1302 
1303 		is->is_sport = htons(fin->fin_data[0]);
1304 		is->is_dport = htons(fin->fin_data[1]);
1305 		if ((flags & (SI_W_DPORT|SI_W_SPORT)) == 0) {
1306 			hv += tcp->th_dport;
1307 			hv += tcp->th_sport;
1308 		}
1309 		ATOMIC_INCL(ifs->ifs_ips_stats.iss_udp);
1310 		break;
1311 
1312 	default :
1313 		break;
1314 	}
1315 	hv = DOUBLE_HASH(hv, ifs);
1316 	is->is_hv = hv;
1317 	is->is_rule = fr;
1318 	is->is_flags = flags & IS_INHERITED;
1319 
1320 	/*
1321 	 * Look for identical state.
1322 	 */
1323 	for (is = ifs->ifs_ips_table[is->is_hv % ifs->ifs_fr_statesize];
1324 	     is != NULL;
1325 	     is = is->is_hnext) {
1326 		if (fr_matchstates(&ips, is) == 1)
1327 			break;
1328 	}
1329 
1330 	/*
1331 	 * we've found a matching state -> state already exists,
1332 	 * we are not going to add a duplicate record.
1333 	 */
1334 	if (is != NULL)
1335 		return NULL;
1336 
1337 	if (ifs->ifs_ips_stats.iss_bucketlen[hv] >= ifs->ifs_fr_state_maxbucket) {
1338 		ATOMIC_INCL(ifs->ifs_ips_stats.iss_bucketfull);
1339 		return NULL;
1340 	}
1341 	KMALLOC(is, ipstate_t *);
1342 	if (is == NULL) {
1343 		ATOMIC_INCL(ifs->ifs_ips_stats.iss_nomem);
1344 		return NULL;
1345 	}
1346 	bcopy((char *)&ips, (char *)is, sizeof(*is));
1347 	/*
1348 	 * Do not do the modulous here, it is done in fr_stinsert().
1349 	 */
1350 	if (fr != NULL) {
1351 		(void) strncpy(is->is_group, fr->fr_group, FR_GROUPLEN);
1352 		if (fr->fr_age[0] != 0) {
1353 			is->is_tqehead[0] =
1354 			    fr_addtimeoutqueue(&ifs->ifs_ips_utqe,
1355 					       fr->fr_age[0], ifs);
1356 			is->is_sti.tqe_flags |= TQE_RULEBASED;
1357 		}
1358 		if (fr->fr_age[1] != 0) {
1359 			is->is_tqehead[1] =
1360 			    fr_addtimeoutqueue(&ifs->ifs_ips_utqe,
1361 					       fr->fr_age[1], ifs);
1362 			is->is_sti.tqe_flags |= TQE_RULEBASED;
1363 		}
1364 		is->is_tag = fr->fr_logtag;
1365 
1366 		is->is_ifp[(out << 1) + 1] = fr->fr_ifas[1];
1367 		is->is_ifp[(1 - out) << 1] = fr->fr_ifas[2];
1368 		is->is_ifp[((1 - out) << 1) + 1] = fr->fr_ifas[3];
1369 
1370 		if (((ifp = fr->fr_ifas[1]) != NULL) &&
1371 		    (ifp != (void *)-1)) {
1372 			COPYIFNAME(ifp, is->is_ifname[(out << 1) + 1], fr->fr_v);
1373 		}
1374 		if (((ifp = fr->fr_ifas[2]) != NULL) &&
1375 		    (ifp != (void *)-1)) {
1376 			COPYIFNAME(ifp, is->is_ifname[(1 - out) << 1], fr->fr_v);
1377 		}
1378 		if (((ifp = fr->fr_ifas[3]) != NULL) &&
1379 		    (ifp != (void *)-1)) {
1380 			COPYIFNAME(ifp, is->is_ifname[((1 - out) << 1) + 1], fr->fr_v);
1381 		}
1382 	}
1383 
1384 	is->is_ifp[out << 1] = fin->fin_ifp;
1385 	if (fin->fin_ifp != NULL) {
1386 		COPYIFNAME(fin->fin_ifp, is->is_ifname[out << 1], fr->fr_v);
1387 	}
1388 
1389 	/*
1390 	 * It may seem strange to set is_ref to 2, but fr_check() will call
1391 	 * fr_statederef() after calling fr_addstate() and the idea is to
1392 	 * have it exist at the end of fr_check() with is_ref == 1.
1393 	 */
1394 	is->is_ref = 2;
1395 	is->is_pkts[0] = 0, is->is_bytes[0] = 0;
1396 	is->is_pkts[1] = 0, is->is_bytes[1] = 0;
1397 	is->is_pkts[2] = 0, is->is_bytes[2] = 0;
1398 	is->is_pkts[3] = 0, is->is_bytes[3] = 0;
1399 	if ((fin->fin_flx & FI_IGNORE) == 0) {
1400 		is->is_pkts[out] = 1;
1401 		is->is_bytes[out] = fin->fin_plen;
1402 		is->is_flx[out][0] = fin->fin_flx & FI_CMP;
1403 		is->is_flx[out][0] &= ~FI_OOW;
1404 	}
1405 
1406 	if (pass & FR_STSTRICT)
1407 		is->is_flags |= IS_STRICT;
1408 
1409 	if (pass & FR_STATESYNC)
1410 		is->is_flags |= IS_STATESYNC;
1411 
1412 	if (flags & (SI_WILDP|SI_WILDA)) {
1413 		ATOMIC_INCL(ifs->ifs_ips_stats.iss_wild);
1414 	}
1415 	is->is_rulen = fin->fin_rule;
1416 
1417 
1418 	if (pass & FR_LOGFIRST)
1419 		is->is_pass &= ~(FR_LOGFIRST|FR_LOG);
1420 
1421 	READ_ENTER(&ifs->ifs_ipf_state);
1422 	is->is_me = stsave;
1423 
1424 	fr_stinsert(is, fin->fin_rev, ifs);
1425 
1426 	if (fin->fin_p == IPPROTO_TCP) {
1427 		/*
1428 		* If we're creating state for a starting connection, start the
1429 		* timer on it as we'll never see an error if it fails to
1430 		* connect.
1431 		*/
1432 		(void) fr_tcp_age(&is->is_sti, fin, ifs->ifs_ips_tqtqb,
1433 				  is->is_flags);
1434 		MUTEX_EXIT(&is->is_lock);
1435 #ifdef	IPFILTER_SCAN
1436 		if ((is->is_flags & SI_CLONE) == 0)
1437 			(void) ipsc_attachis(is);
1438 #endif
1439 	} else {
1440 		MUTEX_EXIT(&is->is_lock);
1441 	}
1442 #ifdef	IPFILTER_SYNC
1443 	if ((is->is_flags & IS_STATESYNC) && ((is->is_flags & SI_CLONE) == 0))
1444 		is->is_sync = ipfsync_new(SMC_STATE, fin, is);
1445 #endif
1446 	if (ifs->ifs_ipstate_logging)
1447 		ipstate_log(is, ISL_NEW, ifs);
1448 
1449 	RWLOCK_EXIT(&ifs->ifs_ipf_state);
1450 	fin->fin_state = is;
1451 	fin->fin_rev = IP6_NEQ(&is->is_dst, &fin->fin_daddr);
1452 	fin->fin_flx |= FI_STATE;
1453 	if (fin->fin_flx & FI_FRAG)
1454 		(void) fr_newfrag(fin, pass ^ FR_KEEPSTATE);
1455 
1456 	return is;
1457 }
1458 
1459 
1460 /* ------------------------------------------------------------------------ */
1461 /* Function:    fr_tcpoptions                                               */
1462 /* Returns:     int - 1 == packet matches state entry, 0 == it does not     */
1463 /* Parameters:  fin(I) - pointer to packet information                      */
1464 /*              tcp(I) - pointer to TCP packet header                       */
1465 /*              td(I)  - pointer to TCP data held as part of the state      */
1466 /*                                                                          */
1467 /* Look after the TCP header for any options and deal with those that are   */
1468 /* present.  Record details about those that we recogise.                   */
1469 /* ------------------------------------------------------------------------ */
1470 static int fr_tcpoptions(fin, tcp, td)
1471 fr_info_t *fin;
1472 tcphdr_t *tcp;
1473 tcpdata_t *td;
1474 {
1475 	int off, mlen, ol, i, len, retval;
1476 	char buf[64], *s, opt;
1477 	mb_t *m = NULL;
1478 
1479 	len = (TCP_OFF(tcp) << 2);
1480 	if (fin->fin_dlen < len)
1481 		return 0;
1482 	len -= sizeof(*tcp);
1483 
1484 	off = fin->fin_plen - fin->fin_dlen + sizeof(*tcp) + fin->fin_ipoff;
1485 
1486 	m = fin->fin_m;
1487 	mlen = MSGDSIZE(m) - off;
1488 	if (len > mlen) {
1489 		len = mlen;
1490 		retval = 0;
1491 	} else {
1492 		retval = 1;
1493 	}
1494 
1495 	COPYDATA(m, off, len, buf);
1496 
1497 	for (s = buf; len > 0; ) {
1498 		opt = *s;
1499 		if (opt == TCPOPT_EOL)
1500 			break;
1501 		else if (opt == TCPOPT_NOP)
1502 			ol = 1;
1503 		else {
1504 			if (len < 2)
1505 				break;
1506 			ol = (int)*(s + 1);
1507 			if (ol < 2 || ol > len)
1508 				break;
1509 
1510 			/*
1511 			 * Extract the TCP options we are interested in out of
1512 			 * the header and store them in the the tcpdata struct.
1513 			 */
1514 			switch (opt)
1515 			{
1516 			case TCPOPT_WINDOW :
1517 				if (ol == TCPOLEN_WINDOW) {
1518 					i = (int)*(s + 2);
1519 					if (i > TCP_WSCALE_MAX)
1520 						i = TCP_WSCALE_MAX;
1521 					else if (i < 0)
1522 						i = 0;
1523 					td->td_winscale = i;
1524 				}
1525 				break;
1526 			case TCPOPT_MAXSEG :
1527 				/*
1528 				 * So, if we wanted to set the TCP MAXSEG,
1529 				 * it should be done here...
1530 				 */
1531 				if (ol == TCPOLEN_MAXSEG) {
1532 					i = (int)*(s + 2);
1533 					i <<= 8;
1534 					i += (int)*(s + 3);
1535 					td->td_maxseg = i;
1536 				}
1537 				break;
1538 			}
1539 		}
1540 		len -= ol;
1541 		s += ol;
1542 	}
1543 	return retval;
1544 }
1545 
1546 
1547 /* ------------------------------------------------------------------------ */
1548 /* Function:    fr_tcpstate                                                 */
1549 /* Returns:     int - 1 == packet matches state entry, 0 == it does not     */
1550 /* Parameters:  fin(I)   - pointer to packet information                    */
1551 /*              tcp(I)   - pointer to TCP packet header                     */
1552 /*              is(I)  - pointer to master state structure                  */
1553 /*                                                                          */
1554 /* Check to see if a packet with TCP headers fits within the TCP window.    */
1555 /* Change timeout depending on whether new packet is a SYN-ACK returning    */
1556 /* for a SYN or a RST or FIN which indicate time to close up shop.          */
1557 /* ------------------------------------------------------------------------ */
1558 static int fr_tcpstate(fin, tcp, is)
1559 fr_info_t *fin;
1560 tcphdr_t *tcp;
1561 ipstate_t *is;
1562 {
1563 	int source, ret = 0, flags;
1564 	tcpdata_t  *fdata, *tdata;
1565 	ipf_stack_t *ifs = fin->fin_ifs;
1566 
1567 	source = !fin->fin_rev;
1568 	if (((is->is_flags & IS_TCPFSM) != 0) && (source == 1) &&
1569 	    (ntohs(is->is_sport) != fin->fin_data[0]))
1570 		source = 0;
1571 	fdata = &is->is_tcp.ts_data[!source];
1572 	tdata = &is->is_tcp.ts_data[source];
1573 
1574 	MUTEX_ENTER(&is->is_lock);
1575 
1576 	/*
1577 	 * If a SYN packet is received for a connection that is in a half
1578 	 * closed state, then move its state entry to deletetq. In such case
1579 	 * the SYN packet will be consequently dropped. This allows new state
1580 	 * entry to be created with a retransmited SYN packet.
1581 	 */
1582 	if ((tcp->th_flags & TH_OPENING) == TH_SYN) {
1583 		if (((is->is_state[source] > IPF_TCPS_ESTABLISHED) ||
1584 		    (is->is_state[source] == IPF_TCPS_CLOSED)) &&
1585 		    ((is->is_state[!source] > IPF_TCPS_ESTABLISHED) ||
1586 		    (is->is_state[!source] == IPF_TCPS_CLOSED))) {
1587 			/*
1588 			 * Do not update is->is_sti.tqe_die in case state entry
1589 			 * is already present in deletetq. It prevents state
1590 			 * entry ttl update by retransmitted SYN packets, which
1591 			 * may arrive before timer tick kicks off. The SYN
1592 			 * packet will be dropped again.
1593 			 */
1594 			if (is->is_sti.tqe_ifq != &ifs->ifs_ips_deletetq)
1595 				fr_movequeue(&is->is_sti, is->is_sti.tqe_ifq,
1596 					&fin->fin_ifs->ifs_ips_deletetq,
1597 					fin->fin_ifs);
1598 
1599 			MUTEX_EXIT(&is->is_lock);
1600 			return 0;
1601 		}
1602 	}
1603 
1604 	if (fr_tcpinwindow(fin, fdata, tdata, tcp, is->is_flags)) {
1605 #ifdef	IPFILTER_SCAN
1606 		if (is->is_flags & (IS_SC_CLIENT|IS_SC_SERVER)) {
1607 			ipsc_packet(fin, is);
1608 			if (FR_ISBLOCK(is->is_pass)) {
1609 				MUTEX_EXIT(&is->is_lock);
1610 				return 1;
1611 			}
1612 		}
1613 #endif
1614 
1615 		/*
1616 		 * Nearing end of connection, start timeout.
1617 		 */
1618 		ret = fr_tcp_age(&is->is_sti, fin, ifs->ifs_ips_tqtqb,
1619 				 is->is_flags);
1620 		if (ret == 0) {
1621 			MUTEX_EXIT(&is->is_lock);
1622 			return 0;
1623 		}
1624 
1625 		/*
1626 		 * set s0's as appropriate.  Use syn-ack packet as it
1627 		 * contains both pieces of required information.
1628 		 */
1629 		/*
1630 		 * Window scale option is only present in SYN/SYN-ACK packet.
1631 		 * Compare with ~TH_FIN to mask out T/TCP setups.
1632 		 */
1633 		flags = tcp->th_flags & ~(TH_FIN|TH_ECNALL);
1634 		if (flags == (TH_SYN|TH_ACK)) {
1635 			is->is_s0[source] = ntohl(tcp->th_ack);
1636 			is->is_s0[!source] = ntohl(tcp->th_seq) + 1;
1637 			if ((TCP_OFF(tcp) > (sizeof(tcphdr_t) >> 2)) &&
1638 			    tdata->td_winscale) {
1639 				if (fr_tcpoptions(fin, tcp, fdata)) {
1640 					fdata->td_winflags = TCP_WSCALE_SEEN|
1641 							     TCP_WSCALE_FIRST;
1642 				} else {
1643 					if (!fdata->td_winscale)
1644 						tdata->td_winscale = 0;
1645 				}
1646 			}
1647 			if ((fin->fin_out != 0) && (is->is_pass & FR_NEWISN))
1648 				fr_checknewisn(fin, is);
1649 		} else if (flags == TH_SYN) {
1650 			is->is_s0[source] = ntohl(tcp->th_seq) + 1;
1651 			if ((TCP_OFF(tcp) > (sizeof(tcphdr_t) >> 2)))
1652 				if (fr_tcpoptions(fin, tcp, tdata)) {
1653 					tdata->td_winflags = TCP_WSCALE_SEEN|
1654 							     TCP_WSCALE_FIRST;
1655 				}
1656 
1657 			if ((fin->fin_out != 0) && (is->is_pass & FR_NEWISN))
1658 				fr_checknewisn(fin, is);
1659 
1660 		}
1661 		ret = 1;
1662 	} else
1663 		fin->fin_flx |= FI_OOW;
1664 	MUTEX_EXIT(&is->is_lock);
1665 	return ret;
1666 }
1667 
1668 
1669 /* ------------------------------------------------------------------------ */
1670 /* Function:    fr_checknewisn                                              */
1671 /* Returns:     Nil                                                         */
1672 /* Parameters:  fin(I)   - pointer to packet information                    */
1673 /*              is(I)  - pointer to master state structure                  */
1674 /*                                                                          */
1675 /* Check to see if this TCP connection is expecting and needs a new         */
1676 /* sequence number for a particular direction of the connection.            */
1677 /*                                                                          */
1678 /* NOTE: This does not actually change the sequence numbers, only gets new  */
1679 /* one ready.                                                               */
1680 /* ------------------------------------------------------------------------ */
1681 static void fr_checknewisn(fin, is)
1682 fr_info_t *fin;
1683 ipstate_t *is;
1684 {
1685 	u_32_t sumd, old, new;
1686 	tcphdr_t *tcp;
1687 	int i;
1688 
1689 	i = fin->fin_rev;
1690 	tcp = fin->fin_dp;
1691 
1692 	if (((i == 0) && !(is->is_flags & IS_ISNSYN)) ||
1693 	    ((i == 1) && !(is->is_flags & IS_ISNACK))) {
1694 		old = ntohl(tcp->th_seq);
1695 		new = fr_newisn(fin);
1696 		is->is_isninc[i] = new - old;
1697 		CALC_SUMD(old, new, sumd);
1698 		is->is_sumd[i] = (sumd & 0xffff) + (sumd >> 16);
1699 
1700 		is->is_flags |= ((i == 0) ? IS_ISNSYN : IS_ISNACK);
1701 	}
1702 }
1703 
1704 
1705 /* ------------------------------------------------------------------------ */
1706 /* Function:    fr_tcpinwindow                                              */
1707 /* Returns:     int - 1 == packet inside TCP "window", 0 == not inside.     */
1708 /* Parameters:  fin(I)   - pointer to packet information                    */
1709 /*              fdata(I) - pointer to tcp state informatio (forward)        */
1710 /*              tdata(I) - pointer to tcp state informatio (reverse)        */
1711 /*              tcp(I)   - pointer to TCP packet header                     */
1712 /*                                                                          */
1713 /* Given a packet has matched addresses and ports, check to see if it is    */
1714 /* within the TCP data window.  In a show of generosity, allow packets that */
1715 /* are within the window space behind the current sequence # as well.       */
1716 /* ------------------------------------------------------------------------ */
1717 int fr_tcpinwindow(fin, fdata, tdata, tcp, flags)
1718 fr_info_t *fin;
1719 tcpdata_t  *fdata, *tdata;
1720 tcphdr_t *tcp;
1721 int flags;
1722 {
1723 	tcp_seq seq, ack, end;
1724 	int ackskew, tcpflags;
1725 	u_32_t win, maxwin;
1726 
1727 	/*
1728 	 * Find difference between last checked packet and this packet.
1729 	 */
1730 	tcpflags = tcp->th_flags;
1731 	seq = ntohl(tcp->th_seq);
1732 	ack = ntohl(tcp->th_ack);
1733 	if (tcpflags & TH_SYN)
1734 		win = ntohs(tcp->th_win);
1735 	else
1736 		win = ntohs(tcp->th_win) << fdata->td_winscale;
1737 	if (win == 0)
1738 		win = 1;
1739 
1740 	/*
1741 	 * if window scaling is present, the scaling is only allowed
1742 	 * for windows not in the first SYN packet. In that packet the
1743 	 * window is 65535 to specify the largest window possible
1744 	 * for receivers not implementing the window scale option.
1745 	 * Currently, we do not assume TTCP here. That means that
1746 	 * if we see a second packet from a host (after the initial
1747 	 * SYN), we can assume that the receiver of the SYN did
1748 	 * already send back the SYN/ACK (and thus that we know if
1749 	 * the receiver also does window scaling)
1750 	 */
1751 	if (!(tcpflags & TH_SYN) && (fdata->td_winflags & TCP_WSCALE_FIRST)) {
1752 		if (tdata->td_winflags & TCP_WSCALE_SEEN) {
1753 			fdata->td_winflags &= ~TCP_WSCALE_FIRST;
1754 			fdata->td_maxwin = win;
1755 		} else {
1756 			fdata->td_winscale = 0;
1757 			fdata->td_winflags = 0;
1758 			tdata->td_winscale = 0;
1759 			tdata->td_winflags = 0;
1760 		  }
1761 	}
1762 
1763 	end = seq + fin->fin_dlen - (TCP_OFF(tcp) << 2) +
1764 	      ((tcpflags & TH_SYN) ? 1 : 0) + ((tcpflags & TH_FIN) ? 1 : 0);
1765 
1766 	if ((fdata->td_end == 0) &&
1767 	    (!(flags & IS_TCPFSM) ||
1768 	     ((tcpflags & TH_OPENING) == TH_OPENING))) {
1769 		/*
1770 		 * Must be a (outgoing) SYN-ACK in reply to a SYN.
1771 		 */
1772 		fdata->td_end = end;
1773 		fdata->td_maxwin = 1;
1774 		fdata->td_maxend = end + win;
1775 	}
1776 
1777 	if (!(tcpflags & TH_ACK)) {  /* Pretend an ack was sent */
1778 		ack = tdata->td_end;
1779 	} else if (((tcpflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) &&
1780 		   (ack == 0)) {
1781 		/* gross hack to get around certain broken tcp stacks */
1782 		ack = tdata->td_end;
1783 	}
1784 
1785 	if (seq == end)
1786 		seq = end = fdata->td_end;
1787 
1788 	maxwin = tdata->td_maxwin;
1789 	ackskew = tdata->td_end - ack;
1790 
1791 	/*
1792 	 * Strict sequencing only allows in-order delivery.
1793 	 */
1794 	if ((flags & IS_STRICT) != 0) {
1795 		if (seq != fdata->td_end) {
1796 			return 0;
1797 		}
1798 	}
1799 
1800 #define	SEQ_GE(a,b)	((int)((a) - (b)) >= 0)
1801 #define	SEQ_GT(a,b)	((int)((a) - (b)) > 0)
1802 	if (
1803 #if defined(_KERNEL)
1804 	    (SEQ_GE(fdata->td_maxend, end)) &&
1805 	    (SEQ_GE(seq, fdata->td_end - maxwin)) &&
1806 #endif
1807 /* XXX what about big packets */
1808 #define MAXACKWINDOW 66000
1809 	    (-ackskew <= (MAXACKWINDOW << fdata->td_winscale)) &&
1810 	    ( ackskew <= (MAXACKWINDOW << fdata->td_winscale))) {
1811 
1812 		/* if ackskew < 0 then this should be due to fragmented
1813 		 * packets. There is no way to know the length of the
1814 		 * total packet in advance.
1815 		 * We do know the total length from the fragment cache though.
1816 		 * Note however that there might be more sessions with
1817 		 * exactly the same source and destination parameters in the
1818 		 * state cache (and source and destination is the only stuff
1819 		 * that is saved in the fragment cache). Note further that
1820 		 * some TCP connections in the state cache are hashed with
1821 		 * sport and dport as well which makes it not worthwhile to
1822 		 * look for them.
1823 		 * Thus, when ackskew is negative but still seems to belong
1824 		 * to this session, we bump up the destinations end value.
1825 		 */
1826 		if (ackskew < 0)
1827 			tdata->td_end = ack;
1828 
1829 		/* update max window seen */
1830 		if (fdata->td_maxwin < win)
1831 			fdata->td_maxwin = win;
1832 		if (SEQ_GT(end, fdata->td_end))
1833 			fdata->td_end = end;
1834 		if (SEQ_GE(ack + win, tdata->td_maxend))
1835 			tdata->td_maxend = ack + win;
1836 		return 1;
1837 	}
1838 	return 0;
1839 }
1840 
1841 
1842 /* ------------------------------------------------------------------------ */
1843 /* Function:    fr_stclone                                                  */
1844 /* Returns:     ipstate_t* - NULL == cloning failed,                        */
1845 /*                           else pointer to new state structure            */
1846 /* Parameters:  fin(I) - pointer to packet information                      */
1847 /*              tcp(I) - pointer to TCP/UDP header                          */
1848 /*              is(I)  - pointer to master state structure                  */
1849 /*                                                                          */
1850 /* Create a "duplcate" state table entry from the master.                   */
1851 /* ------------------------------------------------------------------------ */
1852 static ipstate_t *fr_stclone(fin, tcp, is)
1853 fr_info_t *fin;
1854 tcphdr_t *tcp;
1855 ipstate_t *is;
1856 {
1857 	ipstate_t *clone;
1858 	u_32_t send;
1859 	ipf_stack_t *ifs = fin->fin_ifs;
1860 
1861 	if (ifs->ifs_ips_num == ifs->ifs_fr_statemax) {
1862 		ATOMIC_INCL(ifs->ifs_ips_stats.iss_max);
1863 		ifs->ifs_fr_state_doflush = 1;
1864 		return NULL;
1865 	}
1866 	KMALLOC(clone, ipstate_t *);
1867 	if (clone == NULL)
1868 		return NULL;
1869 	bcopy((char *)is, (char *)clone, sizeof(*clone));
1870 
1871 	MUTEX_NUKE(&clone->is_lock);
1872 
1873 	clone->is_die = ONE_DAY + ifs->ifs_fr_ticks;
1874 	clone->is_state[0] = 0;
1875 	clone->is_state[1] = 0;
1876 	send = ntohl(tcp->th_seq) + fin->fin_dlen - (TCP_OFF(tcp) << 2) +
1877 		((tcp->th_flags & TH_SYN) ? 1 : 0) +
1878 		((tcp->th_flags & TH_FIN) ? 1 : 0);
1879 
1880 	if (fin->fin_rev == 1) {
1881 		clone->is_dend = send;
1882 		clone->is_maxdend = send;
1883 		clone->is_send = 0;
1884 		clone->is_maxswin = 1;
1885 		clone->is_maxdwin = ntohs(tcp->th_win);
1886 		if (clone->is_maxdwin == 0)
1887 			clone->is_maxdwin = 1;
1888 	} else {
1889 		clone->is_send = send;
1890 		clone->is_maxsend = send;
1891 		clone->is_dend = 0;
1892 		clone->is_maxdwin = 1;
1893 		clone->is_maxswin = ntohs(tcp->th_win);
1894 		if (clone->is_maxswin == 0)
1895 			clone->is_maxswin = 1;
1896 	}
1897 
1898 	clone->is_flags &= ~SI_CLONE;
1899 	clone->is_flags |= SI_CLONED;
1900 	fr_stinsert(clone, fin->fin_rev, ifs);
1901 	clone->is_ref = 2;
1902 	if (clone->is_p == IPPROTO_TCP) {
1903 		(void) fr_tcp_age(&clone->is_sti, fin, ifs->ifs_ips_tqtqb,
1904 				  clone->is_flags);
1905 	}
1906 	MUTEX_EXIT(&clone->is_lock);
1907 #ifdef	IPFILTER_SCAN
1908 	(void) ipsc_attachis(is);
1909 #endif
1910 #ifdef	IPFILTER_SYNC
1911 	if (is->is_flags & IS_STATESYNC)
1912 		clone->is_sync = ipfsync_new(SMC_STATE, fin, clone);
1913 #endif
1914 	return clone;
1915 }
1916 
1917 
1918 /* ------------------------------------------------------------------------ */
1919 /* Function:    fr_matchsrcdst                                              */
1920 /* Returns:     Nil                                                         */
1921 /* Parameters:  fin(I) - pointer to packet information                      */
1922 /*              is(I)  - pointer to state structure                         */
1923 /*              src(I) - pointer to source address                          */
1924 /*              dst(I) - pointer to destination address                     */
1925 /*              tcp(I) - pointer to TCP/UDP header                          */
1926 /*                                                                          */
1927 /* Match a state table entry against an IP packet.  The logic below is that */
1928 /* ret gets set to one if the match succeeds, else remains 0.  If it is     */
1929 /* still 0 after the test. no match.                                        */
1930 /* ------------------------------------------------------------------------ */
1931 static ipstate_t *fr_matchsrcdst(fin, is, src, dst, tcp, cmask)
1932 fr_info_t *fin;
1933 ipstate_t *is;
1934 i6addr_t *src, *dst;
1935 tcphdr_t *tcp;
1936 u_32_t cmask;
1937 {
1938 	int ret = 0, rev, out, flags, flx = 0, idx;
1939 	u_short sp, dp;
1940 	u_32_t cflx;
1941 	void *ifp;
1942 	ipf_stack_t *ifs = fin->fin_ifs;
1943 
1944 	rev = IP6_NEQ(&is->is_dst, dst);
1945 	ifp = fin->fin_ifp;
1946 	out = fin->fin_out;
1947 	flags = is->is_flags;
1948 	sp = 0;
1949 	dp = 0;
1950 
1951 	if (tcp != NULL) {
1952 		sp = htons(fin->fin_sport);
1953 		dp = ntohs(fin->fin_dport);
1954 	}
1955 	if (!rev) {
1956 		if (tcp != NULL) {
1957 			if (!(flags & SI_W_SPORT) && (sp != is->is_sport))
1958 				rev = 1;
1959 			else if (!(flags & SI_W_DPORT) && (dp != is->is_dport))
1960 				rev = 1;
1961 		}
1962 	}
1963 
1964 	idx = (out << 1) + rev;
1965 
1966 	/*
1967 	 * If the interface for this 'direction' is set, make sure it matches.
1968 	 * An interface name that is not set matches any, as does a name of *.
1969 	 */
1970 	if ((is->is_ifp[idx] == NULL &&
1971 	    (*is->is_ifname[idx] == '\0' || *is->is_ifname[idx] == '*')) ||
1972 	    is->is_ifp[idx] == ifp)
1973 		ret = 1;
1974 
1975 	if (ret == 0)
1976 		return NULL;
1977 	ret = 0;
1978 
1979 	/*
1980 	 * Match addresses and ports.
1981 	 */
1982 	if (rev == 0) {
1983 		if ((IP6_EQ(&is->is_dst, dst) || (flags & SI_W_DADDR)) &&
1984 		    (IP6_EQ(&is->is_src, src) || (flags & SI_W_SADDR))) {
1985 			if (tcp) {
1986 				if ((sp == is->is_sport || flags & SI_W_SPORT)&&
1987 				    (dp == is->is_dport || flags & SI_W_DPORT))
1988 					ret = 1;
1989 			} else {
1990 				ret = 1;
1991 			}
1992 		}
1993 	} else {
1994 		if ((IP6_EQ(&is->is_dst, src) || (flags & SI_W_DADDR)) &&
1995 		    (IP6_EQ(&is->is_src, dst) || (flags & SI_W_SADDR))) {
1996 			if (tcp) {
1997 				if ((dp == is->is_sport || flags & SI_W_SPORT)&&
1998 				    (sp == is->is_dport || flags & SI_W_DPORT))
1999 					ret = 1;
2000 			} else {
2001 				ret = 1;
2002 			}
2003 		}
2004 	}
2005 
2006 	if (ret == 0)
2007 		return NULL;
2008 
2009 	/*
2010 	 * Whether or not this should be here, is questionable, but the aim
2011 	 * is to get this out of the main line.
2012 	 */
2013 	if (tcp == NULL)
2014 		flags = is->is_flags & ~(SI_WILDP|SI_NEWFR|SI_CLONE|SI_CLONED);
2015 
2016 	/*
2017 	 * Only one of the source or destination address can be flaged as a
2018 	 * wildcard.  Fill in the missing address, if set.
2019 	 * For IPv6, if the address being copied in is multicast, then
2020 	 * don't reset the wild flag - multicast causes it to be set in the
2021 	 * first place!
2022 	 */
2023 	if ((flags & (SI_W_SADDR|SI_W_DADDR))) {
2024 		fr_ip_t *fi = &fin->fin_fi;
2025 
2026 		if ((flags & SI_W_SADDR) != 0) {
2027 			if (rev == 0) {
2028 #ifdef USE_INET6
2029 				if (is->is_v == 6 &&
2030 				    IN6_IS_ADDR_MULTICAST(&fi->fi_src.in6))
2031 					/*EMPTY*/;
2032 				else
2033 #endif
2034 				{
2035 					is->is_src = fi->fi_src;
2036 					is->is_flags &= ~SI_W_SADDR;
2037 				}
2038 			} else {
2039 #ifdef USE_INET6
2040 				if (is->is_v == 6 &&
2041 				    IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
2042 					/*EMPTY*/;
2043 				else
2044 #endif
2045 				{
2046 					is->is_src = fi->fi_dst;
2047 					is->is_flags &= ~SI_W_SADDR;
2048 				}
2049 			}
2050 		} else if ((flags & SI_W_DADDR) != 0) {
2051 			if (rev == 0) {
2052 #ifdef USE_INET6
2053 				if (is->is_v == 6 &&
2054 				    IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
2055 					/*EMPTY*/;
2056 				else
2057 #endif
2058 				{
2059 					is->is_dst = fi->fi_dst;
2060 					is->is_flags &= ~SI_W_DADDR;
2061 				}
2062 			} else {
2063 #ifdef USE_INET6
2064 				if (is->is_v == 6 &&
2065 				    IN6_IS_ADDR_MULTICAST(&fi->fi_src.in6))
2066 					/*EMPTY*/;
2067 				else
2068 #endif
2069 				{
2070 					is->is_dst = fi->fi_src;
2071 					is->is_flags &= ~SI_W_DADDR;
2072 				}
2073 			}
2074 		}
2075 		if ((is->is_flags & (SI_WILDA|SI_WILDP)) == 0) {
2076 			ATOMIC_DECL(ifs->ifs_ips_stats.iss_wild);
2077 		}
2078 	}
2079 
2080 	flx = fin->fin_flx & cmask;
2081 	cflx = is->is_flx[out][rev];
2082 
2083 	/*
2084 	 * Match up any flags set from IP options.
2085 	 */
2086 	if ((cflx && (flx != (cflx & cmask))) ||
2087 	    ((fin->fin_optmsk & is->is_optmsk[rev]) != is->is_opt[rev]) ||
2088 	    ((fin->fin_secmsk & is->is_secmsk) != is->is_sec) ||
2089 	    ((fin->fin_auth & is->is_authmsk) != is->is_auth))
2090 		return NULL;
2091 
2092 	/*
2093 	 * Only one of the source or destination port can be flagged as a
2094 	 * wildcard.  When filling it in, fill in a copy of the matched entry
2095 	 * if it has the cloning flag set.
2096 	 */
2097 	if ((fin->fin_flx & FI_IGNORE) != 0) {
2098 		fin->fin_rev = rev;
2099 		return is;
2100 	}
2101 
2102 	if ((flags & (SI_W_SPORT|SI_W_DPORT))) {
2103 		if ((flags & SI_CLONE) != 0) {
2104 			ipstate_t *clone;
2105 
2106 			clone = fr_stclone(fin, tcp, is);
2107 			if (clone == NULL)
2108 				return NULL;
2109 			is = clone;
2110 		} else {
2111 			ATOMIC_DECL(ifs->ifs_ips_stats.iss_wild);
2112 		}
2113 
2114 		if ((flags & SI_W_SPORT) != 0) {
2115 			if (rev == 0) {
2116 				is->is_sport = sp;
2117 				is->is_send = ntohl(tcp->th_seq);
2118 			} else {
2119 				is->is_sport = dp;
2120 				is->is_send = ntohl(tcp->th_ack);
2121 			}
2122 			is->is_maxsend = is->is_send + 1;
2123 		} else if ((flags & SI_W_DPORT) != 0) {
2124 			if (rev == 0) {
2125 				is->is_dport = dp;
2126 				is->is_dend = ntohl(tcp->th_ack);
2127 			} else {
2128 				is->is_dport = sp;
2129 				is->is_dend = ntohl(tcp->th_seq);
2130 			}
2131 			is->is_maxdend = is->is_dend + 1;
2132 		}
2133 		is->is_flags &= ~(SI_W_SPORT|SI_W_DPORT);
2134 		if ((flags & SI_CLONED) && ifs->ifs_ipstate_logging)
2135 			ipstate_log(is, ISL_CLONE, ifs);
2136 	}
2137 
2138 	ret = -1;
2139 
2140 	if (is->is_flx[out][rev] == 0) {
2141 		is->is_flx[out][rev] = flx;
2142 		is->is_opt[rev] = fin->fin_optmsk;
2143 		if (is->is_v == 6) {
2144 			is->is_opt[rev] &= ~0x8;
2145 			is->is_optmsk[rev] &= ~0x8;
2146 		}
2147 	}
2148 
2149 	/*
2150 	 * Check if the interface name for this "direction" is set and if not,
2151 	 * fill it in.
2152 	 */
2153 	if (is->is_ifp[idx] == NULL &&
2154 	    (*is->is_ifname[idx] == '\0' || *is->is_ifname[idx] == '*')) {
2155 		is->is_ifp[idx] = ifp;
2156 		COPYIFNAME(ifp, is->is_ifname[idx], fin->fin_v);
2157 	}
2158 	fin->fin_rev = rev;
2159 	return is;
2160 }
2161 
2162 
2163 /* ------------------------------------------------------------------------ */
2164 /* Function:    fr_checkicmpmatchingstate                                   */
2165 /* Returns:     Nil                                                         */
2166 /* Parameters:  fin(I) - pointer to packet information                      */
2167 /*                                                                          */
2168 /* If we've got an ICMP error message, using the information stored in the  */
2169 /* ICMP packet, look for a matching state table entry.                      */
2170 /*                                                                          */
2171 /* If we return NULL then no lock on ipf_state is held.                     */
2172 /* If we return non-null then a read-lock on ipf_state is held.             */
2173 /* ------------------------------------------------------------------------ */
2174 static ipstate_t *fr_checkicmpmatchingstate(fin)
2175 fr_info_t *fin;
2176 {
2177 	ipstate_t *is, **isp;
2178 	u_short sport, dport;
2179 	u_char	pr;
2180 	int backward, i, oi;
2181 	i6addr_t dst, src;
2182 	struct icmp *ic;
2183 	u_short savelen;
2184 	icmphdr_t *icmp;
2185 	fr_info_t ofin;
2186 	tcphdr_t *tcp;
2187 	int len;
2188 	ip_t *oip;
2189 	u_int hv;
2190 	ipf_stack_t *ifs = fin->fin_ifs;
2191 
2192 	/*
2193 	 * Does it at least have the return (basic) IP header ?
2194 	 * Is it an actual recognised ICMP error type?
2195 	 * Only a basic IP header (no options) should be with
2196 	 * an ICMP error header.
2197 	 */
2198 	if ((fin->fin_v != 4) || (fin->fin_hlen != sizeof(ip_t)) ||
2199 	    (fin->fin_plen < ICMPERR_MINPKTLEN) ||
2200 	    !(fin->fin_flx & FI_ICMPERR))
2201 		return NULL;
2202 	ic = fin->fin_dp;
2203 
2204 	oip = (ip_t *)((char *)ic + ICMPERR_ICMPHLEN);
2205 	/*
2206 	 * Check if the at least the old IP header (with options) and
2207 	 * 8 bytes of payload is present.
2208 	 */
2209 	if (fin->fin_plen < ICMPERR_MAXPKTLEN + ((IP_HL(oip) - 5) << 2))
2210 		return NULL;
2211 
2212 	/*
2213 	 * Sanity Checks.
2214 	 */
2215 	len = fin->fin_dlen - ICMPERR_ICMPHLEN;
2216 	if ((len <= 0) || ((IP_HL(oip) << 2) > len))
2217 		return NULL;
2218 
2219 	/*
2220 	 * Is the buffer big enough for all of it ?  It's the size of the IP
2221 	 * header claimed in the encapsulated part which is of concern.  It
2222 	 * may be too big to be in this buffer but not so big that it's
2223 	 * outside the ICMP packet, leading to TCP deref's causing problems.
2224 	 * This is possible because we don't know how big oip_hl is when we
2225 	 * do the pullup early in fr_check() and thus can't guarantee it is
2226 	 * all here now.
2227 	 */
2228 #ifdef  _KERNEL
2229 	{
2230 	mb_t *m;
2231 
2232 	m = fin->fin_m;
2233 # if defined(MENTAT)
2234 	if ((char *)oip + len > (char *)m->b_wptr)
2235 		return NULL;
2236 # else
2237 	if ((char *)oip + len > (char *)fin->fin_ip + m->m_len)
2238 		return NULL;
2239 # endif
2240 	}
2241 #endif
2242 	bcopy((char *)fin, (char *)&ofin, sizeof(*fin));
2243 
2244 	/*
2245 	 * in the IPv4 case we must zero the i6addr union otherwise
2246 	 * the IP6_EQ and IP6_NEQ macros produce the wrong results because
2247 	 * of the 'junk' in the unused part of the union
2248 	 */
2249 	bzero((char *)&src, sizeof(src));
2250 	bzero((char *)&dst, sizeof(dst));
2251 
2252 	/*
2253 	 * we make an fin entry to be able to feed it to
2254 	 * matchsrcdst note that not all fields are encessary
2255 	 * but this is the cleanest way. Note further we fill
2256 	 * in fin_mp such that if someone uses it we'll get
2257 	 * a kernel panic. fr_matchsrcdst does not use this.
2258 	 *
2259 	 * watch out here, as ip is in host order and oip in network
2260 	 * order. Any change we make must be undone afterwards, like
2261 	 * oip->ip_off - it is still in network byte order so fix it.
2262 	 */
2263 	savelen = oip->ip_len;
2264 	oip->ip_len = len;
2265 	oip->ip_off = ntohs(oip->ip_off);
2266 
2267 	ofin.fin_flx = FI_NOCKSUM;
2268 	ofin.fin_v = 4;
2269 	ofin.fin_ip = oip;
2270 	ofin.fin_m = NULL;	/* if dereferenced, panic XXX */
2271 	ofin.fin_mp = NULL;	/* if dereferenced, panic XXX */
2272 	ofin.fin_plen = fin->fin_dlen - ICMPERR_ICMPHLEN;
2273 	(void) fr_makefrip(IP_HL(oip) << 2, oip, &ofin);
2274 	ofin.fin_ifp = fin->fin_ifp;
2275 	ofin.fin_out = !fin->fin_out;
2276 	/*
2277 	 * Reset the short and bad flag here because in fr_matchsrcdst()
2278 	 * the flags for the current packet (fin_flx) are compared against
2279 	 * those for the existing session.
2280 	 */
2281 	ofin.fin_flx &= ~(FI_BAD|FI_SHORT);
2282 
2283 	/*
2284 	 * Put old values of ip_len and ip_off back as we don't know
2285 	 * if we have to forward the packet (or process it again.
2286 	 */
2287 	oip->ip_len = savelen;
2288 	oip->ip_off = htons(oip->ip_off);
2289 
2290 	switch (oip->ip_p)
2291 	{
2292 	case IPPROTO_ICMP :
2293 		/*
2294 		 * an ICMP error can only be generated as a result of an
2295 		 * ICMP query, not as the response on an ICMP error
2296 		 *
2297 		 * XXX theoretically ICMP_ECHOREP and the other reply's are
2298 		 * ICMP query's as well, but adding them here seems strange XXX
2299 		 */
2300 		if ((ofin.fin_flx & FI_ICMPERR) != 0)
2301 		    	return NULL;
2302 
2303 		/*
2304 		 * perform a lookup of the ICMP packet in the state table
2305 		 */
2306 		icmp = (icmphdr_t *)((char *)oip + (IP_HL(oip) << 2));
2307 		hv = (pr = oip->ip_p);
2308 		src.in4 = oip->ip_src;
2309 		hv += src.in4.s_addr;
2310 		dst.in4 = oip->ip_dst;
2311 		hv += dst.in4.s_addr;
2312 		hv += icmp->icmp_id;
2313 		hv = DOUBLE_HASH(hv, ifs);
2314 
2315 		READ_ENTER(&ifs->ifs_ipf_state);
2316 		for (isp = &ifs->ifs_ips_table[hv]; ((is = *isp) != NULL); ) {
2317 			isp = &is->is_hnext;
2318 			if ((is->is_p != pr) || (is->is_v != 4))
2319 				continue;
2320 			if (is->is_pass & FR_NOICMPERR)
2321 				continue;
2322 			is = fr_matchsrcdst(&ofin, is, &src, &dst,
2323 					    NULL, FI_ICMPCMP);
2324 			if (is != NULL) {
2325 				if ((is->is_pass & FR_NOICMPERR) != 0) {
2326 					RWLOCK_EXIT(&ifs->ifs_ipf_state);
2327 					return NULL;
2328 				}
2329 				/*
2330 				 * i  : the index of this packet (the icmp
2331 				 *      unreachable)
2332 				 * oi : the index of the original packet found
2333 				 *      in the icmp header (i.e. the packet
2334 				 *      causing this icmp)
2335 				 * backward : original packet was backward
2336 				 *      compared to the state
2337 				 */
2338 				backward = IP6_NEQ(&is->is_src, &src);
2339 				fin->fin_rev = !backward;
2340 				i = (!backward << 1) + fin->fin_out;
2341 				oi = (backward << 1) + ofin.fin_out;
2342 				if (is->is_icmppkts[i] > is->is_pkts[oi])
2343 					continue;
2344 				ifs->ifs_ips_stats.iss_hits++;
2345 				is->is_icmppkts[i]++;
2346 				return is;
2347 			}
2348 		}
2349 		RWLOCK_EXIT(&ifs->ifs_ipf_state);
2350 		return NULL;
2351 	case IPPROTO_TCP :
2352 	case IPPROTO_UDP :
2353 		break;
2354 	default :
2355 		return NULL;
2356 	}
2357 
2358 	tcp = (tcphdr_t *)((char *)oip + (IP_HL(oip) << 2));
2359 	dport = tcp->th_dport;
2360 	sport = tcp->th_sport;
2361 
2362 	hv = (pr = oip->ip_p);
2363 	src.in4 = oip->ip_src;
2364 	hv += src.in4.s_addr;
2365 	dst.in4 = oip->ip_dst;
2366 	hv += dst.in4.s_addr;
2367 	hv += dport;
2368 	hv += sport;
2369 	hv = DOUBLE_HASH(hv, ifs);
2370 
2371 	READ_ENTER(&ifs->ifs_ipf_state);
2372 	for (isp = &ifs->ifs_ips_table[hv]; ((is = *isp) != NULL); ) {
2373 		isp = &is->is_hnext;
2374 		/*
2375 		 * Only allow this icmp though if the
2376 		 * encapsulated packet was allowed through the
2377 		 * other way around. Note that the minimal amount
2378 		 * of info present does not allow for checking against
2379 		 * tcp internals such as seq and ack numbers.   Only the
2380 		 * ports are known to be present and can be even if the
2381 		 * short flag is set.
2382 		 */
2383 		if ((is->is_p == pr) && (is->is_v == 4) &&
2384 		    (is = fr_matchsrcdst(&ofin, is, &src, &dst,
2385 					 tcp, FI_ICMPCMP))) {
2386 			/*
2387 			 * i  : the index of this packet (the icmp unreachable)
2388 			 * oi : the index of the original packet found in the
2389 			 *      icmp header (i.e. the packet causing this icmp)
2390 			 * backward : original packet was backward compared to
2391 			 *            the state
2392 			 */
2393 			backward = IP6_NEQ(&is->is_src, &src);
2394 			fin->fin_rev = !backward;
2395 			i = (!backward << 1) + fin->fin_out;
2396 			oi = (backward << 1) + ofin.fin_out;
2397 
2398 			if (((is->is_pass & FR_NOICMPERR) != 0) ||
2399 			    (is->is_icmppkts[i] > is->is_pkts[oi]))
2400 				break;
2401 			ifs->ifs_ips_stats.iss_hits++;
2402 			is->is_icmppkts[i]++;
2403 			/*
2404 			 * we deliberately do not touch the timeouts
2405 			 * for the accompanying state table entry.
2406 			 * It remains to be seen if that is correct. XXX
2407 			 */
2408 			return is;
2409 		}
2410 	}
2411 	RWLOCK_EXIT(&ifs->ifs_ipf_state);
2412 	return NULL;
2413 }
2414 
2415 
2416 /* ------------------------------------------------------------------------ */
2417 /* Function:    fr_ipsmove                                                  */
2418 /* Returns:     Nil                                                         */
2419 /* Parameters:  is(I) - pointer to state table entry                        */
2420 /*              hv(I) - new hash value for state table entry                */
2421 /* Write Locks: ipf_state                                                   */
2422 /*                                                                          */
2423 /* Move a state entry from one position in the hash table to another.       */
2424 /* ------------------------------------------------------------------------ */
2425 static void fr_ipsmove(is, hv, ifs)
2426 ipstate_t *is;
2427 u_int hv;
2428 ipf_stack_t *ifs;
2429 {
2430 	ipstate_t **isp;
2431 	u_int hvm;
2432 
2433 	ASSERT(rw_read_locked(&ifs->ifs_ipf_state.ipf_lk) == 0);
2434 
2435 	hvm = is->is_hv;
2436 	/*
2437 	 * Remove the hash from the old location...
2438 	 */
2439 	isp = is->is_phnext;
2440 	if (is->is_hnext)
2441 		is->is_hnext->is_phnext = isp;
2442 	*isp = is->is_hnext;
2443 	if (ifs->ifs_ips_table[hvm] == NULL)
2444 		ifs->ifs_ips_stats.iss_inuse--;
2445 	ifs->ifs_ips_stats.iss_bucketlen[hvm]--;
2446 
2447 	/*
2448 	 * ...and put the hash in the new one.
2449 	 */
2450 	hvm = DOUBLE_HASH(hv, ifs);
2451 	is->is_hv = hvm;
2452 	isp = &ifs->ifs_ips_table[hvm];
2453 	if (*isp)
2454 		(*isp)->is_phnext = &is->is_hnext;
2455 	else
2456 		ifs->ifs_ips_stats.iss_inuse++;
2457 	ifs->ifs_ips_stats.iss_bucketlen[hvm]++;
2458 	is->is_phnext = isp;
2459 	is->is_hnext = *isp;
2460 	*isp = is;
2461 }
2462 
2463 
2464 /* ------------------------------------------------------------------------ */
2465 /* Function:    fr_stlookup                                                 */
2466 /* Returns:     ipstate_t* - NULL == no matching state found,               */
2467 /*                           else pointer to state information is returned  */
2468 /* Parameters:  fin(I) - pointer to packet information                      */
2469 /*              tcp(I) - pointer to TCP/UDP header.                         */
2470 /*                                                                          */
2471 /* Search the state table for a matching entry to the packet described by   */
2472 /* the contents of *fin.                                                    */
2473 /*                                                                          */
2474 /* If we return NULL then no lock on ipf_state is held.                     */
2475 /* If we return non-null then a read-lock on ipf_state is held.             */
2476 /* ------------------------------------------------------------------------ */
2477 ipstate_t *fr_stlookup(fin, tcp, ifqp)
2478 fr_info_t *fin;
2479 tcphdr_t *tcp;
2480 ipftq_t **ifqp;
2481 {
2482 	u_int hv, hvm, pr, v, tryagain;
2483 	ipstate_t *is, **isp;
2484 	u_short dport, sport;
2485 	i6addr_t src, dst;
2486 	struct icmp *ic;
2487 	ipftq_t *ifq;
2488 	int oow;
2489 	ipf_stack_t *ifs = fin->fin_ifs;
2490 
2491 	is = NULL;
2492 	ifq = NULL;
2493 	tcp = fin->fin_dp;
2494 	ic = (struct icmp *)tcp;
2495 	hv = (pr = fin->fin_fi.fi_p);
2496 	src = fin->fin_fi.fi_src;
2497 	dst = fin->fin_fi.fi_dst;
2498 	hv += src.in4.s_addr;
2499 	hv += dst.in4.s_addr;
2500 
2501 	v = fin->fin_fi.fi_v;
2502 #ifdef	USE_INET6
2503 	if (v == 6) {
2504 		hv  += fin->fin_fi.fi_src.i6[1];
2505 		hv  += fin->fin_fi.fi_src.i6[2];
2506 		hv  += fin->fin_fi.fi_src.i6[3];
2507 
2508 		if ((fin->fin_p == IPPROTO_ICMPV6) &&
2509 		    IN6_IS_ADDR_MULTICAST(&fin->fin_fi.fi_dst.in6)) {
2510 			hv -= dst.in4.s_addr;
2511 		} else {
2512 			hv += fin->fin_fi.fi_dst.i6[1];
2513 			hv += fin->fin_fi.fi_dst.i6[2];
2514 			hv += fin->fin_fi.fi_dst.i6[3];
2515 		}
2516 	}
2517 #endif
2518 
2519 	/*
2520 	 * Search the hash table for matching packet header info.
2521 	 */
2522 	switch (pr)
2523 	{
2524 #ifdef	USE_INET6
2525 	case IPPROTO_ICMPV6 :
2526 		tryagain = 0;
2527 		if (v == 6) {
2528 			if ((ic->icmp_type == ICMP6_ECHO_REQUEST) ||
2529 			    (ic->icmp_type == ICMP6_ECHO_REPLY)) {
2530 				hv += ic->icmp_id;
2531 			}
2532 		}
2533 		READ_ENTER(&ifs->ifs_ipf_state);
2534 icmp6again:
2535 		hvm = DOUBLE_HASH(hv, ifs);
2536 		for (isp = &ifs->ifs_ips_table[hvm]; ((is = *isp) != NULL); ) {
2537 			isp = &is->is_hnext;
2538 			if ((is->is_p != pr) || (is->is_v != v))
2539 				continue;
2540 			is = fr_matchsrcdst(fin, is, &src, &dst, NULL, FI_CMP);
2541 			if (is != NULL &&
2542 			    fr_matchicmpqueryreply(v, &is->is_icmp,
2543 						   ic, fin->fin_rev)) {
2544 				if (fin->fin_rev)
2545 					ifq = &ifs->ifs_ips_icmpacktq;
2546 				else
2547 					ifq = &ifs->ifs_ips_icmptq;
2548 				break;
2549 			}
2550 		}
2551 
2552 		if (is != NULL) {
2553 			if ((tryagain != 0) && !(is->is_flags & SI_W_DADDR)) {
2554 				hv += fin->fin_fi.fi_src.i6[0];
2555 				hv += fin->fin_fi.fi_src.i6[1];
2556 				hv += fin->fin_fi.fi_src.i6[2];
2557 				hv += fin->fin_fi.fi_src.i6[3];
2558 				fr_ipsmove(is, hv, ifs);
2559 				MUTEX_DOWNGRADE(&ifs->ifs_ipf_state);
2560 			}
2561 			break;
2562 		}
2563 		RWLOCK_EXIT(&ifs->ifs_ipf_state);
2564 
2565 		/*
2566 		 * No matching icmp state entry. Perhaps this is a
2567 		 * response to another state entry.
2568 		 *
2569 		 * XXX With some ICMP6 packets, the "other" address is already
2570 		 * in the packet, after the ICMP6 header, and this could be
2571 		 * used in place of the multicast address.  However, taking
2572 		 * advantage of this requires some significant code changes
2573 		 * to handle the specific types where that is the case.
2574 		 */
2575 		if ((ifs->ifs_ips_stats.iss_wild != 0) && (v == 6) && (tryagain == 0) &&
2576 		    !IN6_IS_ADDR_MULTICAST(&fin->fin_fi.fi_src.in6)) {
2577 			hv -= fin->fin_fi.fi_src.i6[0];
2578 			hv -= fin->fin_fi.fi_src.i6[1];
2579 			hv -= fin->fin_fi.fi_src.i6[2];
2580 			hv -= fin->fin_fi.fi_src.i6[3];
2581 			tryagain = 1;
2582 			WRITE_ENTER(&ifs->ifs_ipf_state);
2583 			goto icmp6again;
2584 		}
2585 
2586 		is = fr_checkicmp6matchingstate(fin);
2587 		if (is != NULL)
2588 			return is;
2589 		break;
2590 #endif
2591 
2592 	case IPPROTO_ICMP :
2593 		if (v == 4) {
2594 			hv += ic->icmp_id;
2595 		}
2596 		hv = DOUBLE_HASH(hv, ifs);
2597 		READ_ENTER(&ifs->ifs_ipf_state);
2598 		for (isp = &ifs->ifs_ips_table[hv]; ((is = *isp) != NULL); ) {
2599 			isp = &is->is_hnext;
2600 			if ((is->is_p != pr) || (is->is_v != v))
2601 				continue;
2602 			is = fr_matchsrcdst(fin, is, &src, &dst, NULL, FI_CMP);
2603 			if (is != NULL &&
2604 			    fr_matchicmpqueryreply(v, &is->is_icmp,
2605 						   ic, fin->fin_rev)) {
2606 				if (fin->fin_rev)
2607 					ifq = &ifs->ifs_ips_icmpacktq;
2608 				else
2609 					ifq = &ifs->ifs_ips_icmptq;
2610 				break;
2611 			}
2612 		}
2613 		if (is == NULL) {
2614 			RWLOCK_EXIT(&ifs->ifs_ipf_state);
2615 		}
2616 		break;
2617 
2618 	case IPPROTO_TCP :
2619 	case IPPROTO_UDP :
2620 		ifqp = NULL;
2621 		sport = htons(fin->fin_data[0]);
2622 		hv += sport;
2623 		dport = htons(fin->fin_data[1]);
2624 		hv += dport;
2625 		oow = 0;
2626 		tryagain = 0;
2627 		READ_ENTER(&ifs->ifs_ipf_state);
2628 retry_tcpudp:
2629 		hvm = DOUBLE_HASH(hv, ifs);
2630 		for (isp = &ifs->ifs_ips_table[hvm]; ((is = *isp) != NULL); ) {
2631 			isp = &is->is_hnext;
2632 			if ((is->is_p != pr) || (is->is_v != v))
2633 				continue;
2634 			fin->fin_flx &= ~FI_OOW;
2635 			is = fr_matchsrcdst(fin, is, &src, &dst, tcp, FI_CMP);
2636 			if (is != NULL) {
2637 				if (pr == IPPROTO_TCP) {
2638 					if (!fr_tcpstate(fin, tcp, is)) {
2639 						oow |= fin->fin_flx & FI_OOW;
2640 						continue;
2641 					}
2642 				}
2643 				break;
2644 			}
2645 		}
2646 		if (is != NULL) {
2647 			if (tryagain &&
2648 			    !(is->is_flags & (SI_CLONE|SI_WILDP|SI_WILDA))) {
2649 				hv += dport;
2650 				hv += sport;
2651 				fr_ipsmove(is, hv, ifs);
2652 				MUTEX_DOWNGRADE(&ifs->ifs_ipf_state);
2653 			}
2654 			break;
2655 		}
2656 		RWLOCK_EXIT(&ifs->ifs_ipf_state);
2657 
2658 		if (!tryagain && ifs->ifs_ips_stats.iss_wild) {
2659 			hv -= dport;
2660 			hv -= sport;
2661 			tryagain = 1;
2662 			WRITE_ENTER(&ifs->ifs_ipf_state);
2663 			goto retry_tcpudp;
2664 		}
2665 		fin->fin_flx |= oow;
2666 		break;
2667 
2668 #if 0
2669 	case IPPROTO_GRE :
2670 		gre = fin->fin_dp;
2671 		if (GRE_REV(gre->gr_flags) == 1) {
2672 			hv += gre->gr_call;
2673 		}
2674 		/* FALLTHROUGH */
2675 #endif
2676 	default :
2677 		ifqp = NULL;
2678 		hvm = DOUBLE_HASH(hv, ifs);
2679 		READ_ENTER(&ifs->ifs_ipf_state);
2680 		for (isp = &ifs->ifs_ips_table[hvm]; ((is = *isp) != NULL); ) {
2681 			isp = &is->is_hnext;
2682 			if ((is->is_p != pr) || (is->is_v != v))
2683 				continue;
2684 			is = fr_matchsrcdst(fin, is, &src, &dst, NULL, FI_CMP);
2685 			if (is != NULL) {
2686 				ifq = &ifs->ifs_ips_iptq;
2687 				break;
2688 			}
2689 		}
2690 		if (is == NULL) {
2691 			RWLOCK_EXIT(&ifs->ifs_ipf_state);
2692 		}
2693 		break;
2694 	}
2695 
2696 	if ((is != NULL) && ((is->is_sti.tqe_flags & TQE_RULEBASED) != 0) &&
2697 	    (is->is_tqehead[fin->fin_rev] != NULL))
2698 		ifq = is->is_tqehead[fin->fin_rev];
2699 	if (ifq != NULL && ifqp != NULL)
2700 		*ifqp = ifq;
2701 	return is;
2702 }
2703 
2704 
2705 /* ------------------------------------------------------------------------ */
2706 /* Function:    fr_updatestate                                              */
2707 /* Returns:     Nil                                                         */
2708 /* Parameters:  fin(I) - pointer to packet information                      */
2709 /*              is(I)  - pointer to state table entry                       */
2710 /* Read Locks:  ipf_state                                                   */
2711 /*                                                                          */
2712 /* Updates packet and byte counters for a newly received packet.  Seeds the */
2713 /* fragment cache with a new entry as required.                             */
2714 /* ------------------------------------------------------------------------ */
2715 void fr_updatestate(fin, is, ifq)
2716 fr_info_t *fin;
2717 ipstate_t *is;
2718 ipftq_t *ifq;
2719 {
2720 	ipftqent_t *tqe;
2721 	int i, pass;
2722 	ipf_stack_t *ifs = fin->fin_ifs;
2723 
2724 	i = (fin->fin_rev << 1) + fin->fin_out;
2725 
2726 	/*
2727 	 * For TCP packets, ifq == NULL.  For all others, check if this new
2728 	 * queue is different to the last one it was on and move it if so.
2729 	 */
2730 	tqe = &is->is_sti;
2731 	MUTEX_ENTER(&is->is_lock);
2732 	if ((tqe->tqe_flags & TQE_RULEBASED) != 0)
2733 		ifq = is->is_tqehead[fin->fin_rev];
2734 
2735 	if (ifq != NULL)
2736 		fr_movequeue(tqe, tqe->tqe_ifq, ifq, ifs);
2737 
2738 	is->is_pkts[i]++;
2739 	is->is_bytes[i] += fin->fin_plen;
2740 	MUTEX_EXIT(&is->is_lock);
2741 
2742 #ifdef	IPFILTER_SYNC
2743 	if (is->is_flags & IS_STATESYNC)
2744 		ipfsync_update(SMC_STATE, fin, is->is_sync);
2745 #endif
2746 
2747 	ATOMIC_INCL(ifs->ifs_ips_stats.iss_hits);
2748 
2749 	fin->fin_fr = is->is_rule;
2750 
2751 	/*
2752 	 * If this packet is a fragment and the rule says to track fragments,
2753 	 * then create a new fragment cache entry.
2754 	 */
2755 	pass = is->is_pass;
2756 	if ((fin->fin_flx & FI_FRAG) && FR_ISPASS(pass))
2757 		(void) fr_newfrag(fin, pass ^ FR_KEEPSTATE);
2758 }
2759 
2760 
2761 /* ------------------------------------------------------------------------ */
2762 /* Function:    fr_checkstate                                               */
2763 /* Returns:     frentry_t* - NULL == search failed,                         */
2764 /*                           else pointer to rule for matching state        */
2765 /* Parameters:  ifp(I)   - pointer to interface                             */
2766 /*              passp(I) - pointer to filtering result flags                */
2767 /*                                                                          */
2768 /* Check if a packet is associated with an entry in the state table.        */
2769 /* ------------------------------------------------------------------------ */
2770 frentry_t *fr_checkstate(fin, passp)
2771 fr_info_t *fin;
2772 u_32_t *passp;
2773 {
2774 	ipstate_t *is;
2775 	frentry_t *fr;
2776 	tcphdr_t *tcp;
2777 	ipftq_t *ifq;
2778 	u_int pass;
2779 	ipf_stack_t *ifs = fin->fin_ifs;
2780 
2781 	if (ifs->ifs_fr_state_lock || (ifs->ifs_ips_list == NULL) ||
2782 	    (fin->fin_flx & (FI_SHORT|FI_STATE|FI_FRAGBODY|FI_BAD)))
2783 		return NULL;
2784 
2785 	is = NULL;
2786 	if ((fin->fin_flx & FI_TCPUDP) ||
2787 	    (fin->fin_fi.fi_p == IPPROTO_ICMP)
2788 #ifdef	USE_INET6
2789 	    || (fin->fin_fi.fi_p == IPPROTO_ICMPV6)
2790 #endif
2791 	    )
2792 		tcp = fin->fin_dp;
2793 	else
2794 		tcp = NULL;
2795 
2796 	/*
2797 	 * Search the hash table for matching packet header info.
2798 	 */
2799 	ifq = NULL;
2800 	is = fin->fin_state;
2801 	if (is == NULL)
2802 		is = fr_stlookup(fin, tcp, &ifq);
2803 	switch (fin->fin_p)
2804 	{
2805 #ifdef	USE_INET6
2806 	case IPPROTO_ICMPV6 :
2807 		if (is != NULL)
2808 			break;
2809 		if (fin->fin_v == 6) {
2810 			is = fr_checkicmp6matchingstate(fin);
2811 			if (is != NULL)
2812 				goto matched;
2813 		}
2814 		break;
2815 #endif
2816 	case IPPROTO_ICMP :
2817 		if (is != NULL)
2818 			break;
2819 		/*
2820 		 * No matching icmp state entry. Perhaps this is a
2821 		 * response to another state entry.
2822 		 */
2823 		is = fr_checkicmpmatchingstate(fin);
2824 		if (is != NULL)
2825 			goto matched;
2826 		break;
2827 	case IPPROTO_TCP :
2828 		if (is == NULL)
2829 			break;
2830 
2831 		if (is->is_pass & FR_NEWISN) {
2832 			if (fin->fin_out == 0)
2833 				fr_fixinisn(fin, is);
2834 			else if (fin->fin_out == 1)
2835 				fr_fixoutisn(fin, is);
2836 		}
2837 		break;
2838 	default :
2839 		if (fin->fin_rev)
2840 			ifq = &ifs->ifs_ips_udpacktq;
2841 		else
2842 			ifq = &ifs->ifs_ips_udptq;
2843 		break;
2844 	}
2845 	if (is == NULL) {
2846 		ATOMIC_INCL(ifs->ifs_ips_stats.iss_miss);
2847 		return NULL;
2848 	}
2849 
2850 matched:
2851 	fr = is->is_rule;
2852 	if (fr != NULL) {
2853 		if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2854 			if (fin->fin_nattag == NULL)
2855 				return NULL;
2856 			if (fr_matchtag(&fr->fr_nattag, fin->fin_nattag) != 0)
2857 				return NULL;
2858 		}
2859 		(void) strncpy(fin->fin_group, fr->fr_group, FR_GROUPLEN);
2860 		fin->fin_icode = fr->fr_icode;
2861 	}
2862 
2863 	fin->fin_rule = is->is_rulen;
2864 	pass = is->is_pass;
2865 	fr_updatestate(fin, is, ifq);
2866 	if (fin->fin_out == 1)
2867 		fin->fin_nat = is->is_nat[fin->fin_rev];
2868 
2869 	fin->fin_state = is;
2870 	is->is_touched = ifs->ifs_fr_ticks;
2871 	MUTEX_ENTER(&is->is_lock);
2872 	is->is_ref++;
2873 	MUTEX_EXIT(&is->is_lock);
2874 	RWLOCK_EXIT(&ifs->ifs_ipf_state);
2875 	fin->fin_flx |= FI_STATE;
2876 	if ((pass & FR_LOGFIRST) != 0)
2877 		pass &= ~(FR_LOGFIRST|FR_LOG);
2878 	*passp = pass;
2879 	return fr;
2880 }
2881 
2882 
2883 /* ------------------------------------------------------------------------ */
2884 /* Function:    fr_fixoutisn                                                */
2885 /* Returns:     Nil                                                         */
2886 /* Parameters:  fin(I)   - pointer to packet information                    */
2887 /*              is(I)  - pointer to master state structure                  */
2888 /*                                                                          */
2889 /* Called only for outbound packets, adjusts the sequence number and the    */
2890 /* TCP checksum to match that change.                                       */
2891 /* ------------------------------------------------------------------------ */
2892 static void fr_fixoutisn(fin, is)
2893 fr_info_t *fin;
2894 ipstate_t *is;
2895 {
2896 	tcphdr_t *tcp;
2897 	int rev;
2898 	u_32_t seq;
2899 
2900 	tcp = fin->fin_dp;
2901 	rev = fin->fin_rev;
2902 	if ((is->is_flags & IS_ISNSYN) != 0) {
2903 		if (rev == 0) {
2904 			seq = ntohl(tcp->th_seq);
2905 			seq += is->is_isninc[0];
2906 			tcp->th_seq = htonl(seq);
2907 			fix_outcksum(&tcp->th_sum, is->is_sumd[0]);
2908 		}
2909 	}
2910 	if ((is->is_flags & IS_ISNACK) != 0) {
2911 		if (rev == 1) {
2912 			seq = ntohl(tcp->th_seq);
2913 			seq += is->is_isninc[1];
2914 			tcp->th_seq = htonl(seq);
2915 			fix_outcksum(&tcp->th_sum, is->is_sumd[1]);
2916 		}
2917 	}
2918 }
2919 
2920 
2921 /* ------------------------------------------------------------------------ */
2922 /* Function:    fr_fixinisn                                                 */
2923 /* Returns:     Nil                                                         */
2924 /* Parameters:  fin(I)   - pointer to packet information                    */
2925 /*              is(I)  - pointer to master state structure                  */
2926 /*                                                                          */
2927 /* Called only for inbound packets, adjusts the acknowledge number and the  */
2928 /* TCP checksum to match that change.                                       */
2929 /* ------------------------------------------------------------------------ */
2930 static void fr_fixinisn(fin, is)
2931 fr_info_t *fin;
2932 ipstate_t *is;
2933 {
2934 	tcphdr_t *tcp;
2935 	int rev;
2936 	u_32_t ack;
2937 
2938 	tcp = fin->fin_dp;
2939 	rev = fin->fin_rev;
2940 	if ((is->is_flags & IS_ISNSYN) != 0) {
2941 		if (rev == 1) {
2942 			ack = ntohl(tcp->th_ack);
2943 			ack -= is->is_isninc[0];
2944 			tcp->th_ack = htonl(ack);
2945 			fix_incksum(&tcp->th_sum, is->is_sumd[0]);
2946 		}
2947 	}
2948 	if ((is->is_flags & IS_ISNACK) != 0) {
2949 		if (rev == 0) {
2950 			ack = ntohl(tcp->th_ack);
2951 			ack -= is->is_isninc[1];
2952 			tcp->th_ack = htonl(ack);
2953 			fix_incksum(&tcp->th_sum, is->is_sumd[1]);
2954 		}
2955 	}
2956 }
2957 
2958 
2959 /* ------------------------------------------------------------------------ */
2960 /* Function:    fr_statesync                                                */
2961 /* Returns:     Nil                                                         */
2962 /* Parameters:  action(I) - type of synchronisation to do                   */
2963 /*              v(I)      - IP version being sync'd (v4 or v6)              */
2964 /*              ifp(I)    - interface identifier associated with action     */
2965 /*              name(I)   - name associated with ifp parameter              */
2966 /*                                                                          */
2967 /* Walk through all state entries and if an interface pointer match is      */
2968 /* found then look it up again, based on its name in case the pointer has   */
2969 /* changed since last time.                                                 */
2970 /*                                                                          */
2971 /* If ifp is passed in as being non-null then we are only doing updates for */
2972 /* existing, matching, uses of it.                                          */
2973 /* ------------------------------------------------------------------------ */
2974 void fr_statesync(action, v, ifp, name, ifs)
2975 int action, v;
2976 void *ifp;
2977 char *name;
2978 ipf_stack_t *ifs;
2979 {
2980 	ipstate_t *is;
2981 	int i;
2982 
2983 	if (ifs->ifs_fr_running <= 0)
2984 		return;
2985 
2986 	WRITE_ENTER(&ifs->ifs_ipf_state);
2987 
2988 	if (ifs->ifs_fr_running <= 0) {
2989 		RWLOCK_EXIT(&ifs->ifs_ipf_state);
2990 		return;
2991 	}
2992 
2993 	switch (action)
2994 	{
2995 	case IPFSYNC_RESYNC :
2996 		for (is = ifs->ifs_ips_list; is; is = is->is_next) {
2997 			if (v != 0 && is->is_v != v)
2998 				continue;
2999 			/*
3000 			 * Look up all the interface names in the state entry.
3001 			 */
3002 			for (i = 0; i < 4; i++) {
3003 				is->is_ifp[i] = fr_resolvenic(is->is_ifname[i],
3004 							      is->is_v, ifs);
3005 			}
3006 		}
3007 		break;
3008 	case IPFSYNC_NEWIFP :
3009 		for (is = ifs->ifs_ips_list; is; is = is->is_next) {
3010 			if (v != 0 && is->is_v != v)
3011 				continue;
3012 			/*
3013 			 * Look up all the interface names in the state entry.
3014 			 */
3015 			for (i = 0; i < 4; i++) {
3016 				if (!strncmp(is->is_ifname[i], name,
3017 					     sizeof(is->is_ifname[i])))
3018 					is->is_ifp[i] = ifp;
3019 			}
3020 		}
3021 		break;
3022 	case IPFSYNC_OLDIFP :
3023 		for (is = ifs->ifs_ips_list; is; is = is->is_next) {
3024 			if (v != 0 && is->is_v != v)
3025 				continue;
3026 			/*
3027 			 * Look up all the interface names in the state entry.
3028 			 */
3029 			for (i = 0; i < 4; i++) {
3030 				if (is->is_ifp[i] == ifp)
3031 					is->is_ifp[i] = (void *)-1;
3032 			}
3033 		}
3034 		break;
3035 	}
3036 	RWLOCK_EXIT(&ifs->ifs_ipf_state);
3037 }
3038 
3039 
3040 /* ------------------------------------------------------------------------ */
3041 /* Function:    fr_delstate                                                 */
3042 /* Returns:     Nil                                                         */
3043 /* Parameters:  is(I)  - pointer to state structure to delete               */
3044 /*              why(I) - if not 0, log reason why it was deleted            */
3045 /* Write Locks: ipf_state/ipf_global                                        */
3046 /*                                                                          */
3047 /* Deletes a state entry from the enumerated list as well as the hash table */
3048 /* and timeout queue lists.  Make adjustments to hash table statistics and  */
3049 /* global counters as required.                                             */
3050 /* ------------------------------------------------------------------------ */
3051 static void fr_delstate(is, why, ifs)
3052 ipstate_t *is;
3053 int why;
3054 ipf_stack_t *ifs;
3055 {
3056 
3057 	ASSERT(rw_write_held(&ifs->ifs_ipf_global.ipf_lk) == 0 ||
3058 		rw_write_held(&ifs->ifs_ipf_state.ipf_lk) == 0);
3059 
3060 	/*
3061 	 * Since we want to delete this, remove it from the state table,
3062 	 * where it can be found & used, first.
3063 	 */
3064 	if (is->is_pnext != NULL) {
3065 		*is->is_pnext = is->is_next;
3066 
3067 		if (is->is_next != NULL)
3068 			is->is_next->is_pnext = is->is_pnext;
3069 
3070 		is->is_pnext = NULL;
3071 		is->is_next = NULL;
3072 	}
3073 
3074 	if (is->is_phnext != NULL) {
3075 		*is->is_phnext = is->is_hnext;
3076 		if (is->is_hnext != NULL)
3077 			is->is_hnext->is_phnext = is->is_phnext;
3078 		if (ifs->ifs_ips_table[is->is_hv] == NULL)
3079 			ifs->ifs_ips_stats.iss_inuse--;
3080 		ifs->ifs_ips_stats.iss_bucketlen[is->is_hv]--;
3081 
3082 		is->is_phnext = NULL;
3083 		is->is_hnext = NULL;
3084 	}
3085 
3086 	/*
3087 	 * Because ifs->ifs_ips_stats.iss_wild is a count of entries in the state
3088 	 * table that have wildcard flags set, only decerement it once
3089 	 * and do it here.
3090 	 */
3091 	if (is->is_flags & (SI_WILDP|SI_WILDA)) {
3092 		if (!(is->is_flags & SI_CLONED)) {
3093 			ATOMIC_DECL(ifs->ifs_ips_stats.iss_wild);
3094 		}
3095 		is->is_flags &= ~(SI_WILDP|SI_WILDA);
3096 	}
3097 
3098 	/*
3099 	 * Next, remove it from the timeout queue it is in.
3100 	 */
3101 	fr_deletequeueentry(&is->is_sti);
3102 
3103 	is->is_me = NULL;
3104 
3105 	/*
3106 	 * If it is still in use by something else, do not go any further,
3107 	 * but note that at this point it is now an orphan.
3108 	 */
3109 	MUTEX_ENTER(&is->is_lock);
3110 	if (is->is_ref > 1) {
3111 		is->is_ref--;
3112 		MUTEX_EXIT(&is->is_lock);
3113 		return;
3114 	}
3115 	MUTEX_EXIT(&is->is_lock);
3116 
3117 	is->is_ref = 0;
3118 
3119 	if (is->is_tqehead[0] != NULL)
3120 		(void) fr_deletetimeoutqueue(is->is_tqehead[0]);
3121 
3122 	if (is->is_tqehead[1] != NULL)
3123 		(void) fr_deletetimeoutqueue(is->is_tqehead[1]);
3124 
3125 #ifdef	IPFILTER_SYNC
3126 	if (is->is_sync)
3127 		ipfsync_del(is->is_sync);
3128 #endif
3129 #ifdef	IPFILTER_SCAN
3130 	(void) ipsc_detachis(is);
3131 #endif
3132 
3133 	if (ifs->ifs_ipstate_logging != 0 && why != 0)
3134 		ipstate_log(is, why, ifs);
3135 
3136 	if (is->is_rule != NULL) {
3137 		is->is_rule->fr_statecnt--;
3138 		(void)fr_derefrule(&is->is_rule, ifs);
3139 	}
3140 
3141 	MUTEX_DESTROY(&is->is_lock);
3142 	KFREE(is);
3143 	ifs->ifs_ips_num--;
3144 }
3145 
3146 
3147 /* ------------------------------------------------------------------------ */
3148 /* Function:    fr_timeoutstate                                             */
3149 /* Returns:     Nil                                                         */
3150 /* Parameters:  Nil                                                         */
3151 /*                                                                          */
3152 /* Slowly expire held state for thingslike UDP and ICMP.  The algorithm     */
3153 /* used here is to keep the queue sorted with the oldest things at the top  */
3154 /* and the youngest at the bottom.  So if the top one doesn't need to be    */
3155 /* expired then neither will any under it.                                  */
3156 /* ------------------------------------------------------------------------ */
3157 void fr_timeoutstate(ifs)
3158 ipf_stack_t *ifs;
3159 {
3160 	ipftq_t *ifq, *ifqnext;
3161 	ipftqent_t *tqe, *tqn;
3162 	ipstate_t *is;
3163 	SPL_INT(s);
3164 
3165 	SPL_NET(s);
3166 	WRITE_ENTER(&ifs->ifs_ipf_state);
3167 	for (ifq = ifs->ifs_ips_tqtqb; ifq != NULL; ifq = ifq->ifq_next)
3168 		for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
3169 			if (tqe->tqe_die > ifs->ifs_fr_ticks)
3170 				break;
3171 			tqn = tqe->tqe_next;
3172 			is = tqe->tqe_parent;
3173 			fr_delstate(is, ISL_EXPIRE, ifs);
3174 		}
3175 
3176 	for (ifq = ifs->ifs_ips_utqe; ifq != NULL; ifq = ifq->ifq_next) {
3177 		for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
3178 			if (tqe->tqe_die > ifs->ifs_fr_ticks)
3179 				break;
3180 			tqn = tqe->tqe_next;
3181 			is = tqe->tqe_parent;
3182 			fr_delstate(is, ISL_EXPIRE, ifs);
3183 		}
3184 	}
3185 
3186 	for (ifq = ifs->ifs_ips_utqe; ifq != NULL; ifq = ifqnext) {
3187 		ifqnext = ifq->ifq_next;
3188 
3189 		if (((ifq->ifq_flags & IFQF_DELETE) != 0) &&
3190 		    (ifq->ifq_ref == 0)) {
3191 			fr_freetimeoutqueue(ifq, ifs);
3192 		}
3193 	}
3194 
3195 	if (ifs->ifs_fr_state_doflush) {
3196 		(void) fr_state_flush(2, 0, ifs);
3197 		ifs->ifs_fr_state_doflush = 0;
3198 	}
3199 	RWLOCK_EXIT(&ifs->ifs_ipf_state);
3200 	SPL_X(s);
3201 }
3202 
3203 
3204 /* ------------------------------------------------------------------------ */
3205 /* Function:    fr_state_flush                                              */
3206 /* Returns:     int - 0 == success, -1 == failure                           */
3207 /* Parameters:  Nil                                                         */
3208 /* Write Locks: ipf_state                                                   */
3209 /*                                                                          */
3210 /* Flush state tables.  Three actions currently defined:                    */
3211 /* which == 0 : flush all state table entries                               */
3212 /* which == 1 : flush TCP connections which have started to close but are   */
3213 /*	      stuck for some reason.                                        */
3214 /* which == 2 : flush TCP connections which have been idle for a long time, */
3215 /*	      starting at > 4 days idle and working back in successive half-*/
3216 /*	      days to at most 12 hours old.  If this fails to free enough   */
3217 /*            slots then work backwards in half hour slots to 30 minutes.   */
3218 /*            If that too fails, then work backwards in 30 second intervals */
3219 /*            for the last 30 minutes to at worst 30 seconds idle.          */
3220 /* ------------------------------------------------------------------------ */
3221 static int fr_state_flush(which, proto, ifs)
3222 int which, proto;
3223 ipf_stack_t *ifs;
3224 {
3225 	ipftq_t *ifq, *ifqnext;
3226 	ipftqent_t *tqe, *tqn;
3227 	ipstate_t *is, **isp;
3228 	int delete, removed;
3229 	long try, maxtick;
3230 	u_long interval;
3231 	SPL_INT(s);
3232 
3233 	removed = 0;
3234 
3235 	SPL_NET(s);
3236 	for (isp = &ifs->ifs_ips_list; ((is = *isp) != NULL); ) {
3237 		delete = 0;
3238 
3239 		if ((proto != 0) && (is->is_v != proto)) {
3240 			isp = &is->is_next;
3241 			continue;
3242 		}
3243 
3244 		switch (which)
3245 		{
3246 		case 0 :
3247 			delete = 1;
3248 			break;
3249 		case 1 :
3250 		case 2 :
3251 			if (is->is_p != IPPROTO_TCP)
3252 				break;
3253 			if ((is->is_state[0] != IPF_TCPS_ESTABLISHED) ||
3254 			    (is->is_state[1] != IPF_TCPS_ESTABLISHED))
3255 				delete = 1;
3256 			break;
3257 		}
3258 
3259 		if (delete) {
3260 			if (is->is_p == IPPROTO_TCP)
3261 				ifs->ifs_ips_stats.iss_fin++;
3262 			else
3263 				ifs->ifs_ips_stats.iss_expire++;
3264 			fr_delstate(is, ISL_FLUSH, ifs);
3265 			removed++;
3266 		} else
3267 			isp = &is->is_next;
3268 	}
3269 
3270 	if (which != 2) {
3271 		SPL_X(s);
3272 		return removed;
3273 	}
3274 
3275 	/*
3276 	 * Asked to remove inactive entries because the table is full, try
3277 	 * again, 3 times, if first attempt failed with a different criteria
3278 	 * each time.  The order tried in must be in decreasing age.
3279 	 * Another alternative is to implement random drop and drop N entries
3280 	 * at random until N have been freed up.
3281 	 */
3282 	if (ifs->ifs_fr_ticks - ifs->ifs_ips_last_force_flush < IPF_TTLVAL(5))
3283 		goto force_flush_skipped;
3284 	ifs->ifs_ips_last_force_flush = ifs->ifs_fr_ticks;
3285 
3286 	if (ifs->ifs_fr_ticks > IPF_TTLVAL(43200))
3287 		interval = IPF_TTLVAL(43200);
3288 	else if (ifs->ifs_fr_ticks > IPF_TTLVAL(1800))
3289 		interval = IPF_TTLVAL(1800);
3290 	else if (ifs->ifs_fr_ticks > IPF_TTLVAL(30))
3291 		interval = IPF_TTLVAL(30);
3292 	else
3293 		interval = IPF_TTLVAL(10);
3294 	try = ifs->ifs_fr_ticks - (ifs->ifs_fr_ticks - interval);
3295 	if (try < 0)
3296 		goto force_flush_skipped;
3297 
3298 	while (removed == 0) {
3299 		maxtick = ifs->ifs_fr_ticks - interval;
3300 		if (maxtick < 0)
3301 			break;
3302 
3303 		while (try < maxtick) {
3304 			for (ifq = ifs->ifs_ips_tqtqb; ifq != NULL;
3305 			     ifq = ifq->ifq_next) {
3306 				for (tqn = ifq->ifq_head;
3307 				     ((tqe = tqn) != NULL); ) {
3308 					if (tqe->tqe_die > try)
3309 						break;
3310 					tqn = tqe->tqe_next;
3311 					is = tqe->tqe_parent;
3312 					fr_delstate(is, ISL_EXPIRE, ifs);
3313 					removed++;
3314 				}
3315 			}
3316 
3317 			for (ifq = ifs->ifs_ips_utqe; ifq != NULL; ifq = ifqnext) {
3318 				ifqnext = ifq->ifq_next;
3319 
3320 				for (tqn = ifq->ifq_head;
3321 				     ((tqe = tqn) != NULL); ) {
3322 					if (tqe->tqe_die > try)
3323 						break;
3324 					tqn = tqe->tqe_next;
3325 					is = tqe->tqe_parent;
3326 					fr_delstate(is, ISL_EXPIRE, ifs);
3327 					removed++;
3328 				}
3329 			}
3330 			if (try + interval > maxtick)
3331 				break;
3332 			try += interval;
3333 		}
3334 
3335 		if (removed == 0) {
3336 			if (interval == IPF_TTLVAL(43200)) {
3337 				interval = IPF_TTLVAL(1800);
3338 			} else if (interval == IPF_TTLVAL(1800)) {
3339 				interval = IPF_TTLVAL(30);
3340 			} else if (interval == IPF_TTLVAL(30)) {
3341 				interval = IPF_TTLVAL(10);
3342 			} else {
3343 				break;
3344 			}
3345 		}
3346 	}
3347 force_flush_skipped:
3348 	SPL_X(s);
3349 	return removed;
3350 }
3351 
3352 
3353 
3354 /* ------------------------------------------------------------------------ */
3355 /* Function:    fr_tcp_age                                                  */
3356 /* Returns:     int - 1 == state transition made, 0 == no change (rejected) */
3357 /* Parameters:  tq(I)    - pointer to timeout queue information             */
3358 /*              fin(I)   - pointer to packet information                    */
3359 /*              tqtab(I) - TCP timeout queue table this is in               */
3360 /*              flags(I) - flags from state/NAT entry                       */
3361 /*                                                                          */
3362 /* Rewritten by Arjan de Vet <Arjan.deVet@adv.iae.nl>, 2000-07-29:          */
3363 /*                                                                          */
3364 /* - (try to) base state transitions on real evidence only,                 */
3365 /*   i.e. packets that are sent and have been received by ipfilter;         */
3366 /*   diagram 18.12 of TCP/IP volume 1 by W. Richard Stevens was used.       */
3367 /*                                                                          */
3368 /* - deal with half-closed connections correctly;                           */
3369 /*                                                                          */
3370 /* - store the state of the source in state[0] such that ipfstat            */
3371 /*   displays the state as source/dest instead of dest/source; the calls    */
3372 /*   to fr_tcp_age have been changed accordingly.                           */
3373 /*                                                                          */
3374 /* Internal Parameters:                                                     */
3375 /*                                                                          */
3376 /*    state[0] = state of source (host that initiated connection)           */
3377 /*    state[1] = state of dest   (host that accepted the connection)        */
3378 /*                                                                          */
3379 /*    dir == 0 : a packet from source to dest                               */
3380 /*    dir == 1 : a packet from dest to source                               */
3381 /*                                                                          */
3382 /* Locking: it is assumed that the parent of the tqe structure is locked.   */
3383 /* ------------------------------------------------------------------------ */
3384 int fr_tcp_age(tqe, fin, tqtab, flags)
3385 ipftqent_t *tqe;
3386 fr_info_t *fin;
3387 ipftq_t *tqtab;
3388 int flags;
3389 {
3390 	int dlen, ostate, nstate, rval, dir;
3391 	u_char tcpflags;
3392 	tcphdr_t *tcp;
3393 	ipf_stack_t *ifs = fin->fin_ifs;
3394 
3395 	tcp = fin->fin_dp;
3396 
3397 	rval = 0;
3398 	dir = fin->fin_rev;
3399 	tcpflags = tcp->th_flags;
3400 	dlen = fin->fin_dlen - (TCP_OFF(tcp) << 2);
3401 
3402 	if (tcpflags & TH_RST) {
3403 		if (!(tcpflags & TH_PUSH) && !dlen)
3404 			nstate = IPF_TCPS_CLOSED;
3405 		else
3406 			nstate = IPF_TCPS_CLOSE_WAIT;
3407 		rval = 1;
3408 	} else {
3409 		ostate = tqe->tqe_state[1 - dir];
3410 		nstate = tqe->tqe_state[dir];
3411 
3412 		switch (nstate)
3413 		{
3414 		case IPF_TCPS_CLOSED: /* 0 */
3415 			if ((tcpflags & TH_OPENING) == TH_OPENING) {
3416 				/*
3417 				 * 'dir' received an S and sends SA in
3418 				 * response, CLOSED -> SYN_RECEIVED
3419 				 */
3420 				nstate = IPF_TCPS_SYN_RECEIVED;
3421 				rval = 1;
3422 			} else if ((tcpflags & TH_OPENING) == TH_SYN) {
3423 				/* 'dir' sent S, CLOSED -> SYN_SENT */
3424 				nstate = IPF_TCPS_SYN_SENT;
3425 				rval = 1;
3426 			}
3427 			/*
3428 			 * the next piece of code makes it possible to get
3429 			 * already established connections into the state table
3430 			 * after a restart or reload of the filter rules; this
3431 			 * does not work when a strict 'flags S keep state' is
3432 			 * used for tcp connections of course
3433 			 */
3434 			if (((flags & IS_TCPFSM) == 0) &&
3435 			    ((tcpflags & TH_ACKMASK) == TH_ACK)) {
3436 				/*
3437 				 * we saw an A, guess 'dir' is in ESTABLISHED
3438 				 * mode
3439 				 */
3440 				switch (ostate)
3441 				{
3442 				case IPF_TCPS_CLOSED :
3443 				case IPF_TCPS_SYN_RECEIVED :
3444 					nstate = IPF_TCPS_HALF_ESTAB;
3445 					rval = 1;
3446 					break;
3447 				case IPF_TCPS_HALF_ESTAB :
3448 				case IPF_TCPS_ESTABLISHED :
3449 					nstate = IPF_TCPS_ESTABLISHED;
3450 					rval = 1;
3451 					break;
3452 				default :
3453 					break;
3454 				}
3455 			}
3456 			/*
3457 			 * TODO: besides regular ACK packets we can have other
3458 			 * packets as well; it is yet to be determined how we
3459 			 * should initialize the states in those cases
3460 			 */
3461 			break;
3462 
3463 		case IPF_TCPS_LISTEN: /* 1 */
3464 			/* NOT USED */
3465 			break;
3466 
3467 		case IPF_TCPS_SYN_SENT: /* 2 */
3468 			if ((tcpflags & ~(TH_ECN|TH_CWR)) == TH_SYN) {
3469 				/*
3470 				 * A retransmitted SYN packet.  We do not reset
3471 				 * the timeout here to fr_tcptimeout because a
3472 				 * connection connect timeout does not renew
3473 				 * after every packet that is sent.  We need to
3474 				 * set rval so as to indicate the packet has
3475 				 * passed the check for its flags being valid
3476 				 * in the TCP FSM.  Setting rval to 2 has the
3477 				 * result of not resetting the timeout.
3478 				 */
3479 				rval = 2;
3480 			} else if ((tcpflags & (TH_SYN|TH_FIN|TH_ACK)) ==
3481 				   TH_ACK) {
3482 				/*
3483 				 * we see an A from 'dir' which is in SYN_SENT
3484 				 * state: 'dir' sent an A in response to an SA
3485 				 * which it received, SYN_SENT -> ESTABLISHED
3486 				 */
3487 				nstate = IPF_TCPS_ESTABLISHED;
3488 				rval = 1;
3489 			} else if (tcpflags & TH_FIN) {
3490 				/*
3491 				 * we see an F from 'dir' which is in SYN_SENT
3492 				 * state and wants to close its side of the
3493 				 * connection; SYN_SENT -> FIN_WAIT_1
3494 				 */
3495 				nstate = IPF_TCPS_FIN_WAIT_1;
3496 				rval = 1;
3497 			} else if ((tcpflags & TH_OPENING) == TH_OPENING) {
3498 				/*
3499 				 * we see an SA from 'dir' which is already in
3500 				 * SYN_SENT state, this means we have a
3501 				 * simultaneous open; SYN_SENT -> SYN_RECEIVED
3502 				 */
3503 				nstate = IPF_TCPS_SYN_RECEIVED;
3504 				rval = 1;
3505 			}
3506 			break;
3507 
3508 		case IPF_TCPS_SYN_RECEIVED: /* 3 */
3509 			if ((tcpflags & (TH_SYN|TH_FIN|TH_ACK)) == TH_ACK) {
3510 				/*
3511 				 * we see an A from 'dir' which was in
3512 				 * SYN_RECEIVED state so it must now be in
3513 				 * established state, SYN_RECEIVED ->
3514 				 * ESTABLISHED
3515 				 */
3516 				nstate = IPF_TCPS_ESTABLISHED;
3517 				rval = 1;
3518 			} else if ((tcpflags & ~(TH_ECN|TH_CWR)) ==
3519 				   TH_OPENING) {
3520 				/*
3521 				 * We see an SA from 'dir' which is already in
3522 				 * SYN_RECEIVED state.
3523 				 */
3524 				rval = 2;
3525 			} else if (tcpflags & TH_FIN) {
3526 				/*
3527 				 * we see an F from 'dir' which is in
3528 				 * SYN_RECEIVED state and wants to close its
3529 				 * side of the connection; SYN_RECEIVED ->
3530 				 * FIN_WAIT_1
3531 				 */
3532 				nstate = IPF_TCPS_FIN_WAIT_1;
3533 				rval = 1;
3534 			}
3535 			break;
3536 
3537 		case IPF_TCPS_HALF_ESTAB: /* 4 */
3538 			if (ostate >= IPF_TCPS_HALF_ESTAB) {
3539 				if ((tcpflags & TH_ACKMASK) == TH_ACK) {
3540 					nstate = IPF_TCPS_ESTABLISHED;
3541 					rval = 1;
3542 				}
3543 			}
3544 
3545 			break;
3546 
3547 		case IPF_TCPS_ESTABLISHED: /* 5 */
3548 			rval = 1;
3549 			if (tcpflags & TH_FIN) {
3550 				/*
3551 				 * 'dir' closed its side of the connection;
3552 				 * this gives us a half-closed connection;
3553 				 * ESTABLISHED -> FIN_WAIT_1
3554 				 */
3555 				nstate = IPF_TCPS_FIN_WAIT_1;
3556 			} else if (tcpflags & TH_ACK) {
3557 				/*
3558 				 * an ACK, should we exclude other flags here?
3559 				 */
3560 				if (ostate == IPF_TCPS_FIN_WAIT_1) {
3561 					/*
3562 					 * We know the other side did an active
3563 					 * close, so we are ACKing the recvd
3564 					 * FIN packet (does the window matching
3565 					 * code guarantee this?) and go into
3566 					 * CLOSE_WAIT state; this gives us a
3567 					 * half-closed connection
3568 					 */
3569 					nstate = IPF_TCPS_CLOSE_WAIT;
3570 				} else if (ostate < IPF_TCPS_CLOSE_WAIT) {
3571 					/*
3572 					 * still a fully established
3573 					 * connection reset timeout
3574 					 */
3575 					nstate = IPF_TCPS_ESTABLISHED;
3576 				}
3577 			}
3578 			break;
3579 
3580 		case IPF_TCPS_CLOSE_WAIT: /* 6 */
3581 			rval = 1;
3582 			if (tcpflags & TH_FIN) {
3583 				/*
3584 				 * application closed and 'dir' sent a FIN,
3585 				 * we're now going into LAST_ACK state
3586 				 */
3587 				nstate = IPF_TCPS_LAST_ACK;
3588 			} else {
3589 				/*
3590 				 * we remain in CLOSE_WAIT because the other
3591 				 * side has closed already and we did not
3592 				 * close our side yet; reset timeout
3593 				 */
3594 				nstate = IPF_TCPS_CLOSE_WAIT;
3595 			}
3596 			break;
3597 
3598 		case IPF_TCPS_FIN_WAIT_1: /* 7 */
3599 			rval = 1;
3600 			if ((tcpflags & TH_ACK) &&
3601 			    ostate > IPF_TCPS_CLOSE_WAIT) {
3602 				/*
3603 				 * if the other side is not active anymore
3604 				 * it has sent us a FIN packet that we are
3605 				 * ack'ing now with an ACK; this means both
3606 				 * sides have now closed the connection and
3607 				 * we go into TIME_WAIT
3608 				 */
3609 				/*
3610 				 * XXX: how do we know we really are ACKing
3611 				 * the FIN packet here? does the window code
3612 				 * guarantee that?
3613 				 */
3614 				nstate = IPF_TCPS_TIME_WAIT;
3615 			} else {
3616 				/*
3617 				 * we closed our side of the connection
3618 				 * already but the other side is still active
3619 				 * (ESTABLISHED/CLOSE_WAIT); continue with
3620 				 * this half-closed connection
3621 				 */
3622 				nstate = IPF_TCPS_FIN_WAIT_1;
3623 			}
3624 			break;
3625 
3626 		case IPF_TCPS_CLOSING: /* 8 */
3627 			/* NOT USED */
3628 			break;
3629 
3630 		case IPF_TCPS_LAST_ACK: /* 9 */
3631 			if (tcpflags & TH_ACK) {
3632 				if ((tcpflags & TH_PUSH) || dlen)
3633 					/*
3634 					 * there is still data to be delivered,
3635 					 * reset timeout
3636 					 */
3637 					rval = 1;
3638 				else
3639 					rval = 2;
3640 			}
3641 			/*
3642 			 * we cannot detect when we go out of LAST_ACK state to
3643 			 * CLOSED because that is based on the reception of ACK
3644 			 * packets; ipfilter can only detect that a packet
3645 			 * has been sent by a host
3646 			 */
3647 			break;
3648 
3649 		case IPF_TCPS_FIN_WAIT_2: /* 10 */
3650 			rval = 1;
3651 			if ((tcpflags & TH_OPENING) == TH_OPENING)
3652 				nstate = IPF_TCPS_SYN_RECEIVED;
3653 			else if (tcpflags & TH_SYN)
3654 				nstate = IPF_TCPS_SYN_SENT;
3655 			break;
3656 
3657 		case IPF_TCPS_TIME_WAIT: /* 11 */
3658 			/* we're in 2MSL timeout now */
3659 			rval = 1;
3660 			break;
3661 
3662 		default :
3663 #if defined(_KERNEL)
3664 # if SOLARIS
3665 			cmn_err(CE_NOTE,
3666 				"tcp %lx flags %x si %lx nstate %d ostate %d\n",
3667 				(u_long)tcp, tcpflags, (u_long)tqe,
3668 				nstate, ostate);
3669 # else
3670 			printf("tcp %lx flags %x si %lx nstate %d ostate %d\n",
3671 				(u_long)tcp, tcpflags, (u_long)tqe,
3672 				nstate, ostate);
3673 # endif
3674 #else
3675 			abort();
3676 #endif
3677 			break;
3678 		}
3679 	}
3680 
3681 	/*
3682 	 * If rval == 2 then do not update the queue position, but treat the
3683 	 * packet as being ok.
3684 	 */
3685 	if (rval == 2)
3686 		rval = 1;
3687 	else if (rval == 1) {
3688 		tqe->tqe_state[dir] = nstate;
3689 		if ((tqe->tqe_flags & TQE_RULEBASED) == 0)
3690 			fr_movequeue(tqe, tqe->tqe_ifq, tqtab + nstate, ifs);
3691 	}
3692 
3693 	return rval;
3694 }
3695 
3696 
3697 /* ------------------------------------------------------------------------ */
3698 /* Function:    ipstate_log                                                 */
3699 /* Returns:     Nil                                                         */
3700 /* Parameters:  is(I)   - pointer to state structure                        */
3701 /*              type(I) - type of log entry to create                       */
3702 /*                                                                          */
3703 /* Creates a state table log entry using the state structure and type info. */
3704 /* passed in.  Log packet/byte counts, source/destination address and other */
3705 /* protocol specific information.                                           */
3706 /* ------------------------------------------------------------------------ */
3707 void ipstate_log(is, type, ifs)
3708 struct ipstate *is;
3709 u_int type;
3710 ipf_stack_t *ifs;
3711 {
3712 #ifdef	IPFILTER_LOG
3713 	struct	ipslog	ipsl;
3714 	size_t sizes[1];
3715 	void *items[1];
3716 	int types[1];
3717 
3718 	/*
3719 	 * Copy information out of the ipstate_t structure and into the
3720 	 * structure used for logging.
3721 	 */
3722 	ipsl.isl_type = type;
3723 	ipsl.isl_pkts[0] = is->is_pkts[0] + is->is_icmppkts[0];
3724 	ipsl.isl_bytes[0] = is->is_bytes[0];
3725 	ipsl.isl_pkts[1] = is->is_pkts[1] + is->is_icmppkts[1];
3726 	ipsl.isl_bytes[1] = is->is_bytes[1];
3727 	ipsl.isl_pkts[2] = is->is_pkts[2] + is->is_icmppkts[2];
3728 	ipsl.isl_bytes[2] = is->is_bytes[2];
3729 	ipsl.isl_pkts[3] = is->is_pkts[3] + is->is_icmppkts[3];
3730 	ipsl.isl_bytes[3] = is->is_bytes[3];
3731 	ipsl.isl_src = is->is_src;
3732 	ipsl.isl_dst = is->is_dst;
3733 	ipsl.isl_p = is->is_p;
3734 	ipsl.isl_v = is->is_v;
3735 	ipsl.isl_flags = is->is_flags;
3736 	ipsl.isl_tag = is->is_tag;
3737 	ipsl.isl_rulen = is->is_rulen;
3738 	(void) strncpy(ipsl.isl_group, is->is_group, FR_GROUPLEN);
3739 
3740 	if (ipsl.isl_p == IPPROTO_TCP || ipsl.isl_p == IPPROTO_UDP) {
3741 		ipsl.isl_sport = is->is_sport;
3742 		ipsl.isl_dport = is->is_dport;
3743 		if (ipsl.isl_p == IPPROTO_TCP) {
3744 			ipsl.isl_state[0] = is->is_state[0];
3745 			ipsl.isl_state[1] = is->is_state[1];
3746 		}
3747 	} else if (ipsl.isl_p == IPPROTO_ICMP) {
3748 		ipsl.isl_itype = is->is_icmp.ici_type;
3749 	} else if (ipsl.isl_p == IPPROTO_ICMPV6) {
3750 		ipsl.isl_itype = is->is_icmp.ici_type;
3751 	} else {
3752 		ipsl.isl_ps.isl_filler[0] = 0;
3753 		ipsl.isl_ps.isl_filler[1] = 0;
3754 	}
3755 
3756 	items[0] = &ipsl;
3757 	sizes[0] = sizeof(ipsl);
3758 	types[0] = 0;
3759 
3760 	if (ipllog(IPL_LOGSTATE, NULL, items, sizes, types, 1, ifs)) {
3761 		ATOMIC_INCL(ifs->ifs_ips_stats.iss_logged);
3762 	} else {
3763 		ATOMIC_INCL(ifs->ifs_ips_stats.iss_logfail);
3764 	}
3765 #endif
3766 }
3767 
3768 
3769 #ifdef	USE_INET6
3770 /* ------------------------------------------------------------------------ */
3771 /* Function:    fr_checkicmp6matchingstate                                  */
3772 /* Returns:     ipstate_t* - NULL == no match found,                        */
3773 /*                           else  pointer to matching state entry          */
3774 /* Parameters:  fin(I) - pointer to packet information                      */
3775 /* Locks:       NULL == no locks, else Read Lock on ipf_state               */
3776 /*                                                                          */
3777 /* If we've got an ICMPv6 error message, using the information stored in    */
3778 /* the ICMPv6 packet, look for a matching state table entry.                */
3779 /* ------------------------------------------------------------------------ */
3780 static ipstate_t *fr_checkicmp6matchingstate(fin)
3781 fr_info_t *fin;
3782 {
3783 	struct icmp6_hdr *ic6, *oic;
3784 	int backward, i;
3785 	ipstate_t *is, **isp;
3786 	u_short sport, dport;
3787 	i6addr_t dst, src;
3788 	u_short savelen;
3789 	icmpinfo_t *ic;
3790 	fr_info_t ofin;
3791 	tcphdr_t *tcp;
3792 	ip6_t *oip6;
3793 	u_char	pr;
3794 	u_int hv;
3795 	ipf_stack_t *ifs = fin->fin_ifs;
3796 
3797 	/*
3798 	 * Does it at least have the return (basic) IP header ?
3799 	 * Is it an actual recognised ICMP error type?
3800 	 * Only a basic IP header (no options) should be with
3801 	 * an ICMP error header.
3802 	 */
3803 	if ((fin->fin_v != 6) || (fin->fin_plen < ICMP6ERR_MINPKTLEN) ||
3804 	    !(fin->fin_flx & FI_ICMPERR))
3805 		return NULL;
3806 
3807 	ic6 = fin->fin_dp;
3808 
3809 	oip6 = (ip6_t *)((char *)ic6 + ICMPERR_ICMPHLEN);
3810 	if (fin->fin_plen < sizeof(*oip6))
3811 		return NULL;
3812 
3813 	bcopy((char *)fin, (char *)&ofin, sizeof(*fin));
3814 	ofin.fin_v = 6;
3815 	ofin.fin_ifp = fin->fin_ifp;
3816 	ofin.fin_out = !fin->fin_out;
3817 	ofin.fin_m = NULL;	/* if dereferenced, panic XXX */
3818 	ofin.fin_mp = NULL;	/* if dereferenced, panic XXX */
3819 
3820 	/*
3821 	 * We make a fin entry to be able to feed it to
3822 	 * matchsrcdst. Note that not all fields are necessary
3823 	 * but this is the cleanest way. Note further we fill
3824 	 * in fin_mp such that if someone uses it we'll get
3825 	 * a kernel panic. fr_matchsrcdst does not use this.
3826 	 *
3827 	 * watch out here, as ip is in host order and oip6 in network
3828 	 * order. Any change we make must be undone afterwards.
3829 	 */
3830 	savelen = oip6->ip6_plen;
3831 	oip6->ip6_plen = fin->fin_dlen - ICMPERR_ICMPHLEN;
3832 	ofin.fin_flx = FI_NOCKSUM;
3833 	ofin.fin_ip = (ip_t *)oip6;
3834 	ofin.fin_plen = oip6->ip6_plen;
3835 	(void) fr_makefrip(sizeof(*oip6), (ip_t *)oip6, &ofin);
3836 	ofin.fin_flx &= ~(FI_BAD|FI_SHORT);
3837 	oip6->ip6_plen = savelen;
3838 
3839 	if (oip6->ip6_nxt == IPPROTO_ICMPV6) {
3840 		oic = (struct icmp6_hdr *)(oip6 + 1);
3841 		/*
3842 		 * an ICMP error can only be generated as a result of an
3843 		 * ICMP query, not as the response on an ICMP error
3844 		 *
3845 		 * XXX theoretically ICMP_ECHOREP and the other reply's are
3846 		 * ICMP query's as well, but adding them here seems strange XXX
3847 		 */
3848 		 if (!(oic->icmp6_type & ICMP6_INFOMSG_MASK))
3849 		    	return NULL;
3850 
3851 		/*
3852 		 * perform a lookup of the ICMP packet in the state table
3853 		 */
3854 		hv = (pr = oip6->ip6_nxt);
3855 		src.in6 = oip6->ip6_src;
3856 		hv += src.in4.s_addr;
3857 		dst.in6 = oip6->ip6_dst;
3858 		hv += dst.in4.s_addr;
3859 		hv += oic->icmp6_id;
3860 		hv += oic->icmp6_seq;
3861 		hv = DOUBLE_HASH(hv, ifs);
3862 
3863 		READ_ENTER(&ifs->ifs_ipf_state);
3864 		for (isp = &ifs->ifs_ips_table[hv]; ((is = *isp) != NULL); ) {
3865 			ic = &is->is_icmp;
3866 			isp = &is->is_hnext;
3867 			if ((is->is_p == pr) &&
3868 			    !(is->is_pass & FR_NOICMPERR) &&
3869 			    (oic->icmp6_id == ic->ici_id) &&
3870 			    (oic->icmp6_seq == ic->ici_seq) &&
3871 			    (is = fr_matchsrcdst(&ofin, is, &src,
3872 						 &dst, NULL, FI_ICMPCMP))) {
3873 			    	/*
3874 			    	 * in the state table ICMP query's are stored
3875 			    	 * with the type of the corresponding ICMP
3876 			    	 * response. Correct here
3877 			    	 */
3878 				if (((ic->ici_type == ICMP6_ECHO_REPLY) &&
3879 				     (oic->icmp6_type == ICMP6_ECHO_REQUEST)) ||
3880 				     (ic->ici_type - 1 == oic->icmp6_type )) {
3881 				    	ifs->ifs_ips_stats.iss_hits++;
3882 					backward = IP6_NEQ(&is->is_dst, &src);
3883 					fin->fin_rev = !backward;
3884 					i = (backward << 1) + fin->fin_out;
3885     					is->is_icmppkts[i]++;
3886 					return is;
3887 				}
3888 			}
3889 		}
3890 		RWLOCK_EXIT(&ifs->ifs_ipf_state);
3891 		return NULL;
3892 	}
3893 
3894 	hv = (pr = oip6->ip6_nxt);
3895 	src.in6 = oip6->ip6_src;
3896 	hv += src.i6[0];
3897 	hv += src.i6[1];
3898 	hv += src.i6[2];
3899 	hv += src.i6[3];
3900 	dst.in6 = oip6->ip6_dst;
3901 	hv += dst.i6[0];
3902 	hv += dst.i6[1];
3903 	hv += dst.i6[2];
3904 	hv += dst.i6[3];
3905 
3906 	if ((oip6->ip6_nxt == IPPROTO_TCP) || (oip6->ip6_nxt == IPPROTO_UDP)) {
3907 		tcp = (tcphdr_t *)(oip6 + 1);
3908 		dport = tcp->th_dport;
3909 		sport = tcp->th_sport;
3910 		hv += dport;
3911 		hv += sport;
3912 	} else
3913 		tcp = NULL;
3914 	hv = DOUBLE_HASH(hv, ifs);
3915 
3916 	READ_ENTER(&ifs->ifs_ipf_state);
3917 	for (isp = &ifs->ifs_ips_table[hv]; ((is = *isp) != NULL); ) {
3918 		isp = &is->is_hnext;
3919 		/*
3920 		 * Only allow this icmp though if the
3921 		 * encapsulated packet was allowed through the
3922 		 * other way around. Note that the minimal amount
3923 		 * of info present does not allow for checking against
3924 		 * tcp internals such as seq and ack numbers.
3925 		 */
3926 		if ((is->is_p != pr) || (is->is_v != 6) ||
3927 		    (is->is_pass & FR_NOICMPERR))
3928 			continue;
3929 		is = fr_matchsrcdst(&ofin, is, &src, &dst, tcp, FI_ICMPCMP);
3930 		if (is != NULL) {
3931 			ifs->ifs_ips_stats.iss_hits++;
3932 			backward = IP6_NEQ(&is->is_dst, &src);
3933 			fin->fin_rev = !backward;
3934 			i = (backward << 1) + fin->fin_out;
3935 			is->is_icmppkts[i]++;
3936 			/*
3937 			 * we deliberately do not touch the timeouts
3938 			 * for the accompanying state table entry.
3939 			 * It remains to be seen if that is correct. XXX
3940 			 */
3941 			return is;
3942 		}
3943 	}
3944 	RWLOCK_EXIT(&ifs->ifs_ipf_state);
3945 	return NULL;
3946 }
3947 #endif
3948 
3949 
3950 /* ------------------------------------------------------------------------ */
3951 /* Function:    fr_sttab_init                                               */
3952 /* Returns:     Nil                                                         */
3953 /* Parameters:  tqp(I) - pointer to an array of timeout queues for TCP      */
3954 /*                                                                          */
3955 /* Initialise the array of timeout queues for TCP.                          */
3956 /* ------------------------------------------------------------------------ */
3957 void fr_sttab_init(tqp, ifs)
3958 ipftq_t *tqp;
3959 ipf_stack_t *ifs;
3960 {
3961 	int i;
3962 
3963 	for (i = IPF_TCP_NSTATES - 1; i >= 0; i--) {
3964 		tqp[i].ifq_ttl = 0;
3965 		tqp[i].ifq_ref = 1;
3966 		tqp[i].ifq_head = NULL;
3967 		tqp[i].ifq_tail = &tqp[i].ifq_head;
3968 		tqp[i].ifq_next = tqp + i + 1;
3969 		MUTEX_INIT(&tqp[i].ifq_lock, "ipftq tcp tab");
3970 	}
3971 	tqp[IPF_TCP_NSTATES - 1].ifq_next = NULL;
3972 	tqp[IPF_TCPS_CLOSED].ifq_ttl = ifs->ifs_fr_tcpclosed;
3973 	tqp[IPF_TCPS_LISTEN].ifq_ttl = ifs->ifs_fr_tcptimeout;
3974 	tqp[IPF_TCPS_SYN_SENT].ifq_ttl = ifs->ifs_fr_tcptimeout;
3975 	tqp[IPF_TCPS_SYN_RECEIVED].ifq_ttl = ifs->ifs_fr_tcptimeout;
3976 	tqp[IPF_TCPS_ESTABLISHED].ifq_ttl = ifs->ifs_fr_tcpidletimeout;
3977 	tqp[IPF_TCPS_CLOSE_WAIT].ifq_ttl = ifs->ifs_fr_tcphalfclosed;
3978 	tqp[IPF_TCPS_FIN_WAIT_1].ifq_ttl = ifs->ifs_fr_tcphalfclosed;
3979 	tqp[IPF_TCPS_CLOSING].ifq_ttl = ifs->ifs_fr_tcptimeout;
3980 	tqp[IPF_TCPS_LAST_ACK].ifq_ttl = ifs->ifs_fr_tcplastack;
3981 	tqp[IPF_TCPS_FIN_WAIT_2].ifq_ttl = ifs->ifs_fr_tcpclosewait;
3982 	tqp[IPF_TCPS_TIME_WAIT].ifq_ttl = ifs->ifs_fr_tcptimeout;
3983 	tqp[IPF_TCPS_HALF_ESTAB].ifq_ttl = ifs->ifs_fr_tcptimeout;
3984 }
3985 
3986 
3987 /* ------------------------------------------------------------------------ */
3988 /* Function:    fr_sttab_destroy                                            */
3989 /* Returns:     Nil                                                         */
3990 /* Parameters:  tqp(I) - pointer to an array of timeout queues for TCP      */
3991 /*                                                                          */
3992 /* Do whatever is necessary to "destroy" each of the entries in the array   */
3993 /* of timeout queues for TCP.                                               */
3994 /* ------------------------------------------------------------------------ */
3995 void fr_sttab_destroy(tqp)
3996 ipftq_t *tqp;
3997 {
3998 	int i;
3999 
4000 	for (i = IPF_TCP_NSTATES - 1; i >= 0; i--)
4001 		MUTEX_DESTROY(&tqp[i].ifq_lock);
4002 }
4003 
4004 
4005 /* ------------------------------------------------------------------------ */
4006 /* Function:    fr_statederef                                               */
4007 /* Returns:     Nil                                                         */
4008 /* Parameters:  isp(I) - pointer to pointer to state table entry            */
4009 /*              ifs - ipf stack instance                                    */
4010 /*                                                                          */
4011 /* Decrement the reference counter for this state table entry and free it   */
4012 /* if there are no more things using it.                                    */
4013 /*                                                                          */
4014 /* Internal parameters:                                                     */
4015 /*    state[0] = state of source (host that initiated connection)           */
4016 /*    state[1] = state of dest   (host that accepted the connection)        */
4017 /* ------------------------------------------------------------------------ */
4018 void fr_statederef(isp, ifs)
4019 ipstate_t **isp;
4020 ipf_stack_t *ifs;
4021 {
4022 	ipstate_t *is;
4023 
4024 	is = *isp;
4025 	*isp = NULL;
4026 
4027 	MUTEX_ENTER(&is->is_lock);
4028 	if (is->is_ref > 1) {
4029 		is->is_ref--;
4030 		MUTEX_EXIT(&is->is_lock);
4031 #ifndef	_KERNEL
4032 		if ((is->is_sti.tqe_state[0] > IPF_TCPS_ESTABLISHED) ||
4033 		   (is->is_sti.tqe_state[1] > IPF_TCPS_ESTABLISHED)) {
4034 			fr_delstate(is, ISL_ORPHAN, ifs);
4035 		}
4036 #endif
4037 		return;
4038 	}
4039 	MUTEX_EXIT(&is->is_lock);
4040 
4041 	WRITE_ENTER(&ifs->ifs_ipf_state);
4042 	fr_delstate(is, ISL_EXPIRE, ifs);
4043 	RWLOCK_EXIT(&ifs->ifs_ipf_state);
4044 }
4045 
4046 
4047 /* ------------------------------------------------------------------------ */
4048 /* Function:    fr_setstatequeue                                            */
4049 /* Returns:     Nil                                                         */
4050 /* Parameters:  is(I) - pointer to state structure                          */
4051 /*              rev(I) - forward(0) or reverse(1) direction                 */
4052 /* Locks:       ipf_state (read or write)                                   */
4053 /*                                                                          */
4054 /* Put the state entry on its default queue entry, using rev as a helped in */
4055 /* determining which queue it should be placed on.                          */
4056 /* ------------------------------------------------------------------------ */
4057 void fr_setstatequeue(is, rev, ifs)
4058 ipstate_t *is;
4059 int rev;
4060 ipf_stack_t *ifs;
4061 {
4062 	ipftq_t *oifq, *nifq;
4063 
4064 
4065 	if ((is->is_sti.tqe_flags & TQE_RULEBASED) != 0)
4066 		nifq = is->is_tqehead[rev];
4067 	else
4068 		nifq = NULL;
4069 
4070 	if (nifq == NULL) {
4071 		switch (is->is_p)
4072 		{
4073 #ifdef USE_INET6
4074 		case IPPROTO_ICMPV6 :
4075 			if (rev == 1)
4076 				nifq = &ifs->ifs_ips_icmpacktq;
4077 			else
4078 				nifq = &ifs->ifs_ips_icmptq;
4079 			break;
4080 #endif
4081 		case IPPROTO_ICMP :
4082 			if (rev == 1)
4083 				nifq = &ifs->ifs_ips_icmpacktq;
4084 			else
4085 				nifq = &ifs->ifs_ips_icmptq;
4086 			break;
4087 		case IPPROTO_TCP :
4088 			nifq = ifs->ifs_ips_tqtqb + is->is_state[rev];
4089 			break;
4090 
4091 		case IPPROTO_UDP :
4092 			if (rev == 1)
4093 				nifq = &ifs->ifs_ips_udpacktq;
4094 			else
4095 				nifq = &ifs->ifs_ips_udptq;
4096 			break;
4097 
4098 		default :
4099 			nifq = &ifs->ifs_ips_iptq;
4100 			break;
4101 		}
4102 	}
4103 
4104 	oifq = is->is_sti.tqe_ifq;
4105 	/*
4106 	 * If it's currently on a timeout queue, move it from one queue to
4107 	 * another, else put it on the end of the newly determined queue.
4108 	 */
4109 	if (oifq != NULL)
4110 		fr_movequeue(&is->is_sti, oifq, nifq, ifs);
4111 	else
4112 		fr_queueappend(&is->is_sti, nifq, is, ifs);
4113 	return;
4114 }
4115 
4116 
4117 /* ------------------------------------------------------------------------ */
4118 /* Function:    fr_stateiter                                                */
4119 /* Returns:     int - 0 == success, else error                              */
4120 /* Parameters:  token(I) - pointer to ipftoken structure                    */
4121 /*              itp(I)   - pointer to ipfgeniter structure                  */
4122 /*                                                                          */
4123 /* This function handles the SIOCGENITER ioctl for the state tables and     */
4124 /* walks through the list of entries in the state table list (ips_list.)    */
4125 /* ------------------------------------------------------------------------ */
4126 static int fr_stateiter(token, itp, ifs)
4127 ipftoken_t *token;
4128 ipfgeniter_t *itp;
4129 ipf_stack_t *ifs;
4130 {
4131 	ipstate_t *is, *next, zero;
4132 	int error, count;
4133 	char *dst;
4134 
4135 	if (itp->igi_data == NULL)
4136 		return EFAULT;
4137 
4138 	if (itp->igi_nitems == 0)
4139 		return EINVAL;
4140 
4141 	if (itp->igi_type != IPFGENITER_STATE)
4142 		return EINVAL;
4143 
4144 	is = token->ipt_data;
4145 	if (is == (void *)-1) {
4146 		ipf_freetoken(token, ifs);
4147 		return ESRCH;
4148 	}
4149 
4150 	error = 0;
4151 	dst = itp->igi_data;
4152 
4153 	READ_ENTER(&ifs->ifs_ipf_state);
4154 	if (is == NULL) {
4155 		next = ifs->ifs_ips_list;
4156 	} else {
4157 		next = is->is_next;
4158 	}
4159 
4160 	for (count = itp->igi_nitems; count > 0; count--) {
4161 		if (next != NULL) {
4162 			/*
4163 			 * If we find a state entry to use, bump its
4164 			 * reference count so that it can be used for
4165 			 * is_next when we come back.
4166 			 */
4167 			MUTEX_ENTER(&next->is_lock);
4168 			next->is_ref++;
4169 			MUTEX_EXIT(&next->is_lock);
4170 			token->ipt_data = next;
4171 		} else {
4172 			bzero(&zero, sizeof(zero));
4173 			next = &zero;
4174 			token->ipt_data = (void *)-1;
4175 			count = 1;
4176 		}
4177 		RWLOCK_EXIT(&ifs->ifs_ipf_state);
4178 
4179 		/*
4180 		 * If we had a prior pointer to a state entry, release it.
4181 		 */
4182 		if (is != NULL) {
4183 			fr_statederef(&is, ifs);
4184 		}
4185 
4186 		/*
4187 		 * This should arguably be via fr_outobj() so that the state
4188 		 * structure can (if required) be massaged going out.
4189 		 */
4190 		error = COPYOUT(next, dst, sizeof(*next));
4191 		if (error != 0)
4192 			error = EFAULT;
4193 		if ((count == 1) || (error != 0))
4194 			break;
4195 
4196 		dst += sizeof(*next);
4197 		READ_ENTER(&ifs->ifs_ipf_state);
4198 		is = next;
4199 		next = is->is_next;
4200 	}
4201 
4202 	return error;
4203 }
4204