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