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