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