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