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