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