1287984Scy/*	$FreeBSD: releng/10.3/sys/contrib/ipfilter/netinet/ip_state.c 289628 2015-10-20 13:20:29Z cy $ */
2145522Sdarrenr
353642Sguido/*
4255332Scy * Copyright (C) 2012 by Darren Reed.
553642Sguido *
680482Sdarrenr * See the IPFILTER.LICENCE file for details on licencing.
7255332Scy *
8255332Scy * Copyright 2008 Sun Microsystems.
9255332Scy *
10255332Scy * $Id$
1153642Sguido */
12145522Sdarrenr#if defined(KERNEL) || defined(_KERNEL)
13145522Sdarrenr# undef KERNEL
14145522Sdarrenr# undef _KERNEL
15145522Sdarrenr# define        KERNEL	1
16145522Sdarrenr# define        _KERNEL	1
1792685Sdarrenr#endif
1853642Sguido#include <sys/errno.h>
1953642Sguido#include <sys/types.h>
2053642Sguido#include <sys/param.h>
2153642Sguido#include <sys/file.h>
2260854Sdarrenr#if defined(_KERNEL) && defined(__FreeBSD_version) && \
2360854Sdarrenr    (__FreeBSD_version >= 400000) && !defined(KLD_MODULE)
2460854Sdarrenr#include "opt_inet6.h"
2560854Sdarrenr#endif
26145522Sdarrenr#if !defined(_KERNEL) && !defined(__KERNEL__)
2753642Sguido# include <stdio.h>
2853642Sguido# include <stdlib.h>
2953642Sguido# include <string.h>
30145522Sdarrenr# define _KERNEL
31145522Sdarrenr# ifdef __OpenBSD__
32145522Sdarrenrstruct file;
3353642Sguido# endif
34145522Sdarrenr# include <sys/uio.h>
35145522Sdarrenr# undef _KERNEL
3653642Sguido#endif
37145522Sdarrenr#if defined(_KERNEL) && (__FreeBSD_version >= 220000)
3853642Sguido# include <sys/filio.h>
3953642Sguido# include <sys/fcntl.h>
4053642Sguido#else
4153642Sguido# include <sys/ioctl.h>
4253642Sguido#endif
4353642Sguido#include <sys/time.h>
44145522Sdarrenr#if !defined(linux)
4553642Sguido# include <sys/protosw.h>
4653642Sguido#endif
4753642Sguido#include <sys/socket.h>
48145522Sdarrenr#if defined(_KERNEL)
4953642Sguido# include <sys/systm.h>
50145522Sdarrenr# if !defined(__SVR4) && !defined(__svr4__)
5153642Sguido#  include <sys/mbuf.h>
5253642Sguido# endif
53145522Sdarrenr#endif
54145522Sdarrenr#if defined(__SVR4) || defined(__svr4__)
5553642Sguido# include <sys/filio.h>
5653642Sguido# include <sys/byteorder.h>
5753642Sguido# ifdef _KERNEL
5853642Sguido#  include <sys/dditypes.h>
5953642Sguido# endif
6053642Sguido# include <sys/stream.h>
6153642Sguido# include <sys/kmem.h>
6253642Sguido#endif
6353642Sguido
6453642Sguido#include <net/if.h>
6553642Sguido#ifdef sun
6653642Sguido# include <net/af.h>
6753642Sguido#endif
6853642Sguido#include <netinet/in.h>
6953642Sguido#include <netinet/in_systm.h>
7053642Sguido#include <netinet/ip.h>
7153642Sguido#include <netinet/tcp.h>
72145522Sdarrenr#if !defined(__hpux) && !defined(linux)
7353642Sguido# include <netinet/tcp_fsm.h>
7453642Sguido#endif
7553642Sguido#include <netinet/udp.h>
7653642Sguido#include <netinet/ip_icmp.h>
77255332Scy#if !defined(_KERNEL)
78255332Scy# include "ipf.h"
79255332Scy#endif
8053642Sguido#include "netinet/ip_compat.h"
8153642Sguido#include "netinet/ip_fil.h"
8253642Sguido#include "netinet/ip_nat.h"
8353642Sguido#include "netinet/ip_frag.h"
8453642Sguido#include "netinet/ip_state.h"
85145522Sdarrenr#include "netinet/ip_proxy.h"
86255332Scy#include "netinet/ip_lookup.h"
87255332Scy#include "netinet/ip_dstlist.h"
88145522Sdarrenr#include "netinet/ip_sync.h"
8960854Sdarrenr#ifdef	USE_INET6
9060854Sdarrenr#include <netinet/icmp6.h>
9160854Sdarrenr#endif
92255332Scy#if FREEBSD_GE_REV(300000)
9353642Sguido# include <sys/malloc.h>
94145522Sdarrenr# if defined(_KERNEL) && !defined(IPFILTER_LKM)
9553642Sguido#  include <sys/libkern.h>
9653642Sguido#  include <sys/systm.h>
9753642Sguido# endif
9853642Sguido#endif
99145522Sdarrenr/* END OF INCLUDES */
10053642Sguido
101145522Sdarrenr
10280482Sdarrenr#if !defined(lint)
10380482Sdarrenrstatic const char sccsid[] = "@(#)ip_state.c	1.8 6/5/96 (C) 1993-2000 Darren Reed";
104255332Scystatic const char rcsid[] = "@(#)$Id$";
10580482Sdarrenr#endif
10680482Sdarrenr
10753642Sguido
108255332Scystatic ipftuneable_t ipf_state_tuneables[] = {
109255332Scy	{ { (void *)offsetof(ipf_state_softc_t, ipf_state_max) },
110255332Scy		"state_max",		1,	0x7fffffff,
111255332Scy		stsizeof(ipf_state_softc_t, ipf_state_max),
112255332Scy		0,			NULL,	NULL },
113255332Scy	{ { (void *)offsetof(ipf_state_softc_t, ipf_state_size) },
114255332Scy		"state_size",		1,	0x7fffffff,
115255332Scy		stsizeof(ipf_state_softc_t, ipf_state_size),
116255332Scy		0,			NULL,	ipf_state_rehash },
117255332Scy	{ { (void *)offsetof(ipf_state_softc_t, ipf_state_lock) },
118255332Scy		"state_lock",		0,	1,
119255332Scy		stsizeof(ipf_state_softc_t, ipf_state_lock),
120255332Scy		IPFT_RDONLY,		NULL,	NULL },
121255332Scy	{ { (void *)offsetof(ipf_state_softc_t, ipf_state_maxbucket) },
122255332Scy		"state_maxbucket",	1,	0x7fffffff,
123255332Scy		stsizeof(ipf_state_softc_t, ipf_state_maxbucket),
124255332Scy		0,			NULL,	NULL },
125255332Scy	{ { (void *)offsetof(ipf_state_softc_t, ipf_state_logging) },
126255332Scy		"state_logging",0,	1,
127255332Scy		stsizeof(ipf_state_softc_t, ipf_state_logging),
128255332Scy		0,			NULL,	NULL },
129255332Scy	{ { (void *)offsetof(ipf_state_softc_t, ipf_state_wm_high) },
130255332Scy		"state_wm_high",2,	100,
131255332Scy		stsizeof(ipf_state_softc_t, ipf_state_wm_high),
132255332Scy		0,			NULL,	NULL },
133255332Scy	{ { (void *)offsetof(ipf_state_softc_t, ipf_state_wm_low) },
134255332Scy		"state_wm_low",	1,	99,
135255332Scy		stsizeof(ipf_state_softc_t, ipf_state_wm_low),
136255332Scy		0,			NULL,	NULL },
137255332Scy	{ { (void *)offsetof(ipf_state_softc_t, ipf_state_wm_freq) },
138255332Scy		"state_wm_freq",2,	999999,
139255332Scy		stsizeof(ipf_state_softc_t, ipf_state_wm_freq),
140255332Scy		0,			NULL,	NULL },
141255332Scy	{ { NULL },
142255332Scy		NULL,			0,	0,
143255332Scy		0,
144255332Scy		0,	NULL, NULL }
145255332Scy};
146255332Scy
147255332Scy#define	SINCL(x)	ATOMIC_INCL(softs->x)
148255332Scy#define	SBUMP(x)	(softs->x)++
149255332Scy#define	SBUMPD(x, y)	do { (softs->x.y)++; DT(y); } while (0)
150255332Scy#define	SBUMPDX(x, y, z)do { (softs->x.y)++; DT(z); } while (0)
151255332Scy
15260854Sdarrenr#ifdef	USE_INET6
153255332Scystatic ipstate_t *ipf_checkicmp6matchingstate __P((fr_info_t *));
15460854Sdarrenr#endif
155255332Scystatic int ipf_allowstateicmp __P((fr_info_t *, ipstate_t *, i6addr_t *));
156255332Scystatic ipstate_t *ipf_matchsrcdst __P((fr_info_t *, ipstate_t *, i6addr_t *,
157145522Sdarrenr				      i6addr_t *, tcphdr_t *, u_32_t));
158255332Scystatic ipstate_t *ipf_checkicmpmatchingstate __P((fr_info_t *));
159255332Scystatic int ipf_state_flush_entry __P((ipf_main_softc_t *, void *));
160255332Scystatic ips_stat_t *ipf_state_stats __P((ipf_main_softc_t *));
161255332Scystatic int ipf_state_del __P((ipf_main_softc_t *, ipstate_t *, int));
162255332Scystatic int ipf_state_remove __P((ipf_main_softc_t *, caddr_t));
163255332Scystatic int ipf_state_match __P((ipstate_t *is1, ipstate_t *is2));
164255332Scystatic int ipf_state_matchaddresses __P((ipstate_t *is1, ipstate_t *is2));
165255332Scystatic int ipf_state_matchipv4addrs __P((ipstate_t *is1, ipstate_t *is2));
166255332Scystatic int ipf_state_matchipv6addrs __P((ipstate_t *is1, ipstate_t *is2));
167255332Scystatic int ipf_state_matchisps __P((ipstate_t *is1, ipstate_t *is2));
168255332Scystatic int ipf_state_matchports __P((udpinfo_t *is1, udpinfo_t *is2));
169255332Scystatic int ipf_state_matcharray __P((ipstate_t *, int *, u_long));
170255332Scystatic void ipf_ipsmove __P((ipf_state_softc_t *, ipstate_t *, u_int));
171255332Scystatic int ipf_state_tcp __P((ipf_main_softc_t *, ipf_state_softc_t *,
172255332Scy			      fr_info_t *, tcphdr_t *, ipstate_t *));
173255332Scystatic int ipf_tcpoptions __P((ipf_state_softc_t *, fr_info_t *,
174255332Scy			       tcphdr_t *, tcpdata_t *));
175255332Scystatic ipstate_t *ipf_state_clone __P((fr_info_t *, tcphdr_t *, ipstate_t *));
176255332Scystatic void ipf_fixinisn __P((fr_info_t *, ipstate_t *));
177255332Scystatic void ipf_fixoutisn __P((fr_info_t *, ipstate_t *));
178255332Scystatic void ipf_checknewisn __P((fr_info_t *, ipstate_t *));
179255332Scystatic int ipf_state_iter __P((ipf_main_softc_t *, ipftoken_t *,
180255332Scy			       ipfgeniter_t *, ipfobj_t *));
181255332Scystatic int ipf_state_gettable __P((ipf_main_softc_t *, ipf_state_softc_t *,
182255332Scy				   char *));
183255332Scystatic	int ipf_state_tcpinwindow __P((struct fr_info *, struct tcpdata *,
184255332Scy				       struct tcpdata *, tcphdr_t *, int));
185145522Sdarrenr
186255332Scystatic int ipf_state_getent __P((ipf_main_softc_t *, ipf_state_softc_t *,
187255332Scy				 caddr_t));
188255332Scystatic int ipf_state_putent __P((ipf_main_softc_t *, ipf_state_softc_t *,
189255332Scy				 caddr_t));
19053642Sguido
191145522Sdarrenr#define	ONE_DAY		IPF_TTLVAL(1 * 86400)	/* 1 day */
192145522Sdarrenr#define	FIVE_DAYS	(5 * ONE_DAY)
193255332Scy#define	DOUBLE_HASH(x)	(((x) + softs->ipf_state_seed[(x) % \
194255332Scy			 softs->ipf_state_size]) % softs->ipf_state_size)
19553642Sguido
196255332Scy
197255332Scy/* ------------------------------------------------------------------------ */
198255332Scy/* Function:    ipf_state_main_load                                         */
199255332Scy/* Returns:     int - 0 == success, -1 == failure                           */
200255332Scy/* Parameters:  Nil                                                         */
201255332Scy/*                                                                          */
202255332Scy/* A null-op function that exists as a placeholder so that the flow in      */
203255332Scy/* other functions is obvious.                                              */
204255332Scy/* ------------------------------------------------------------------------ */
205255332Scyint
206255332Scyipf_state_main_load()
207255332Scy{
208255332Scy	return 0;
209255332Scy}
210255332Scy
211255332Scy
212255332Scy/* ------------------------------------------------------------------------ */
213255332Scy/* Function:    ipf_state_main_unload                                       */
214255332Scy/* Returns:     int - 0 == success, -1 == failure                           */
215255332Scy/* Parameters:  Nil                                                         */
216255332Scy/*                                                                          */
217255332Scy/* A null-op function that exists as a placeholder so that the flow in      */
218255332Scy/* other functions is obvious.                                              */
219255332Scy/* ------------------------------------------------------------------------ */
220255332Scyint
221255332Scyipf_state_main_unload()
222255332Scy{
223255332Scy	return 0;
224255332Scy}
225255332Scy
226255332Scy
227255332Scy/* ------------------------------------------------------------------------ */
228255332Scy/* Function:    ipf_state_soft_create                                       */
229255332Scy/* Returns:     void *   - NULL = failure, else pointer to soft context     */
230255332Scy/* Parameters:  softc(I) - pointer to soft context main structure           */
231255332Scy/*                                                                          */
232255332Scy/* Create a new state soft context structure and populate it with the list  */
233255332Scy/* of tunables and other default settings.                                  */
234255332Scy/* ------------------------------------------------------------------------ */
235255332Scyvoid *
236255332Scyipf_state_soft_create(softc)
237255332Scy	ipf_main_softc_t *softc;
238255332Scy{
239255332Scy	ipf_state_softc_t *softs;
240255332Scy
241255332Scy	KMALLOC(softs, ipf_state_softc_t *);
242255332Scy	if (softs == NULL)
243255332Scy		return NULL;
244255332Scy
245255332Scy	bzero((char *)softs, sizeof(*softs));
246255332Scy
247255332Scy	softs->ipf_state_tune = ipf_tune_array_copy(softs,
248255332Scy						    sizeof(ipf_state_tuneables),
249255332Scy						    ipf_state_tuneables);
250255332Scy	if (softs->ipf_state_tune == NULL) {
251255332Scy		ipf_state_soft_destroy(softc, softs);
252255332Scy		return NULL;
253255332Scy	}
254255332Scy	if (ipf_tune_array_link(softc, softs->ipf_state_tune) == -1) {
255255332Scy		ipf_state_soft_destroy(softc, softs);
256255332Scy		return NULL;
257255332Scy	}
258255332Scy
259145522Sdarrenr#ifdef	IPFILTER_LOG
260255332Scy	softs->ipf_state_logging = 1;
261145522Sdarrenr#else
262255332Scy	softs->ipf_state_logging = 0;
263145522Sdarrenr#endif
264255332Scy	softs->ipf_state_size = IPSTATE_SIZE,
265255332Scy	softs->ipf_state_maxbucket = 0;
266255332Scy	softs->ipf_state_wm_freq = IPF_TTLVAL(10);
267255332Scy	softs->ipf_state_max = IPSTATE_MAX;
268255332Scy	softs->ipf_state_wm_last = 0;
269255332Scy	softs->ipf_state_wm_high = 99;
270255332Scy	softs->ipf_state_wm_low = 90;
271255332Scy	softs->ipf_state_inited = 0;
272255332Scy	softs->ipf_state_lock = 0;
273255332Scy	softs->ipf_state_doflush = 0;
27453642Sguido
275255332Scy	return softs;
276255332Scy}
27753642Sguido
278255332Scy
279145522Sdarrenr/* ------------------------------------------------------------------------ */
280255332Scy/* Function:    ipf_state_soft_destroy                                      */
281255332Scy/* Returns:     Nil                                                         */
282255332Scy/* Parameters:  softc(I) - pointer to soft context main structure           */
283255332Scy/*              arg(I)   - pointer to local context to use                  */
284145522Sdarrenr/*                                                                          */
285255332Scy/* Undo only what we did in soft create: unlink and free the tunables and   */
286255332Scy/* free the soft context structure itself.                                  */
287145522Sdarrenr/* ------------------------------------------------------------------------ */
288255332Scyvoid
289255332Scyipf_state_soft_destroy(softc, arg)
290255332Scy	ipf_main_softc_t *softc;
291255332Scy	void *arg;
29253642Sguido{
293255332Scy	ipf_state_softc_t *softs = arg;
294255332Scy
295255332Scy	if (softs->ipf_state_tune != NULL) {
296255332Scy		ipf_tune_array_unlink(softc, softs->ipf_state_tune);
297255332Scy		KFREES(softs->ipf_state_tune, sizeof(ipf_state_tuneables));
298255332Scy		softs->ipf_state_tune = NULL;
299255332Scy	}
300255332Scy
301255332Scy	KFREE(softs);
302255332Scy}
303255332Scy
304255332Scy
305255332Scy/* ------------------------------------------------------------------------ */
306255332Scy/* Function:    ipf_state_soft_init                                         */
307255332Scy/* Returns:     int      - 0 == success, -1 == failure                      */
308255332Scy/* Parameters:  softc(I) - pointer to soft context main structure           */
309255332Scy/*              arg(I)   - pointer to local context to use                  */
310255332Scy/*                                                                          */
311255332Scy/* Initialise the state soft context structure so it is ready for use.      */
312255332Scy/* This involves:                                                           */
313255332Scy/* - allocating a hash table and zero'ing it out                            */
314255332Scy/* - building a secondary table of seeds for double hashing to make it more */
315255332Scy/*   difficult to attempt to attack the hash table itself (for DoS)         */
316255332Scy/* - initialise all of the timeout queues, including a table for TCP, some  */
317255332Scy/*   pairs of query/response for UDP and other IP protocols (typically the  */
318255332Scy/*   reply queue has a shorter timeout than the query)                      */
319255332Scy/* ------------------------------------------------------------------------ */
320255332Scyint
321255332Scyipf_state_soft_init(softc, arg)
322255332Scy	ipf_main_softc_t *softc;
323255332Scy	void *arg;
324255332Scy{
325255332Scy	ipf_state_softc_t *softs = arg;
32660854Sdarrenr	int i;
32760854Sdarrenr
328255332Scy	KMALLOCS(softs->ipf_state_table,
329255332Scy		 ipstate_t **, softs->ipf_state_size * sizeof(ipstate_t *));
330255332Scy	if (softs->ipf_state_table == NULL)
33153642Sguido		return -1;
33260854Sdarrenr
333255332Scy	bzero((char *)softs->ipf_state_table,
334255332Scy	      softs->ipf_state_size * sizeof(ipstate_t *));
335255332Scy
336255332Scy	KMALLOCS(softs->ipf_state_seed, u_long *,
337255332Scy		 softs->ipf_state_size * sizeof(*softs->ipf_state_seed));
338255332Scy	if (softs->ipf_state_seed == NULL)
339145522Sdarrenr		return -2;
340255332Scy
341255332Scy	for (i = 0; i < softs->ipf_state_size; i++) {
342145522Sdarrenr		/*
343255332Scy		 * XXX - ipf_state_seed[X] should be a random number of sorts.
344145522Sdarrenr		 */
345255332Scy#if  FREEBSD_GE_REV(400000)
346255332Scy		softs->ipf_state_seed[i] = arc4random();
347145522Sdarrenr#else
348255332Scy		softs->ipf_state_seed[i] = ((u_long)softs->ipf_state_seed + i) *
349255332Scy				    softs->ipf_state_size;
350255332Scy		softs->ipf_state_seed[i] ^= 0xa5a55a5a;
351255332Scy		softs->ipf_state_seed[i] *= (u_long)softs->ipf_state_seed;
352255332Scy		softs->ipf_state_seed[i] ^= 0x5a5aa5a5;
353255332Scy		softs->ipf_state_seed[i] *= softs->ipf_state_max;
354145522Sdarrenr#endif
355145522Sdarrenr	}
356145522Sdarrenr
357255332Scy	KMALLOCS(softs->ipf_state_stats.iss_bucketlen, u_int *,
358255332Scy		 softs->ipf_state_size * sizeof(u_int));
359255332Scy	if (softs->ipf_state_stats.iss_bucketlen == NULL)
360255332Scy		return -3;
36160854Sdarrenr
362255332Scy	bzero((char *)softs->ipf_state_stats.iss_bucketlen,
363255332Scy	      softs->ipf_state_size * sizeof(u_int));
364145522Sdarrenr
365255332Scy	if (softs->ipf_state_maxbucket == 0) {
366255332Scy		for (i = softs->ipf_state_size; i > 0; i >>= 1)
367255332Scy			softs->ipf_state_maxbucket++;
368255332Scy		softs->ipf_state_maxbucket *= 2;
369145522Sdarrenr	}
370145522Sdarrenr
371255332Scy	ipf_sttab_init(softc, softs->ipf_state_tcptq);
372255332Scy	softs->ipf_state_stats.iss_tcptab = softs->ipf_state_tcptq;
373255332Scy	softs->ipf_state_tcptq[IPF_TCP_NSTATES - 1].ifq_next =
374255332Scy						&softs->ipf_state_udptq;
375145522Sdarrenr
376255332Scy	IPFTQ_INIT(&softs->ipf_state_udptq, softc->ipf_udptimeout,
377255332Scy		   "ipftq udp tab");
378255332Scy	softs->ipf_state_udptq.ifq_next = &softs->ipf_state_udpacktq;
379145522Sdarrenr
380255332Scy	IPFTQ_INIT(&softs->ipf_state_udpacktq, softc->ipf_udpacktimeout,
381255332Scy		   "ipftq udpack tab");
382255332Scy	softs->ipf_state_udpacktq.ifq_next = &softs->ipf_state_icmptq;
383255332Scy
384255332Scy	IPFTQ_INIT(&softs->ipf_state_icmptq, softc->ipf_icmptimeout,
385255332Scy		   "ipftq icmp tab");
386255332Scy	softs->ipf_state_icmptq.ifq_next = &softs->ipf_state_icmpacktq;
387255332Scy
388255332Scy	IPFTQ_INIT(&softs->ipf_state_icmpacktq, softc->ipf_icmpacktimeout,
389255332Scy		  "ipftq icmpack tab");
390255332Scy	softs->ipf_state_icmpacktq.ifq_next = &softs->ipf_state_iptq;
391255332Scy
392255332Scy	IPFTQ_INIT(&softs->ipf_state_iptq, softc->ipf_iptimeout,
393255332Scy		   "ipftq iptimeout tab");
394255332Scy	softs->ipf_state_iptq.ifq_next = &softs->ipf_state_pending;
395255332Scy
396255332Scy	IPFTQ_INIT(&softs->ipf_state_pending, IPF_HZ_DIVIDE, "ipftq pending");
397255332Scy	softs->ipf_state_pending.ifq_next = &softs->ipf_state_deletetq;
398255332Scy
399255332Scy	IPFTQ_INIT(&softs->ipf_state_deletetq, 1, "ipftq delete");
400255332Scy	softs->ipf_state_deletetq.ifq_next = NULL;
401255332Scy
402255332Scy	MUTEX_INIT(&softs->ipf_stinsert, "ipf state insert mutex");
403255332Scy
404255332Scy
405255332Scy	softs->ipf_state_wm_last = softc->ipf_ticks;
406255332Scy	softs->ipf_state_inited = 1;
407255332Scy
40853642Sguido	return 0;
40953642Sguido}
41053642Sguido
41153642Sguido
412145522Sdarrenr/* ------------------------------------------------------------------------ */
413255332Scy/* Function:    ipf_state_soft_fini                                         */
414255332Scy/* Returns:     int      - 0 = success, -1 = failure                        */
415255332Scy/* Parameters:  softc(I) - pointer to soft context main structure           */
416255332Scy/*              arg(I)   - pointer to local context to use                  */
417145522Sdarrenr/*                                                                          */
418145522Sdarrenr/* Release and destroy any resources acquired or initialised so that        */
419145522Sdarrenr/* IPFilter can be unloaded or re-initialised.                              */
420145522Sdarrenr/* ------------------------------------------------------------------------ */
421255332Scyint
422255332Scyipf_state_soft_fini(softc, arg)
423255332Scy	ipf_main_softc_t *softc;
424255332Scy	void *arg;
42553642Sguido{
426255332Scy	ipf_state_softc_t *softs = arg;
427145522Sdarrenr	ipftq_t *ifq, *ifqnext;
428145522Sdarrenr	ipstate_t *is;
42953642Sguido
430255332Scy	while ((is = softs->ipf_state_list) != NULL)
431255332Scy		ipf_state_del(softc, is, ISL_UNLOAD);
43253642Sguido
433145522Sdarrenr	/*
434145522Sdarrenr	 * Proxy timeout queues are not cleaned here because although they
435255332Scy	 * exist on the state list, appr_unload is called after
436255332Scy	 * ipf_state_unload and the proxies actually are responsible for them
437255332Scy	 * being created. Should the proxy timeouts have their own list?
438255332Scy	 * There's no real justification as this is the only complication.
439145522Sdarrenr	 */
440255332Scy	for (ifq = softs->ipf_state_usertq; ifq != NULL; ifq = ifqnext) {
441145522Sdarrenr		ifqnext = ifq->ifq_next;
442255332Scy
443255332Scy		if (ipf_deletetimeoutqueue(ifq) == 0)
444255332Scy			ipf_freetimeoutqueue(softc, ifq);
445145522Sdarrenr	}
44653642Sguido
447255332Scy	softs->ipf_state_stats.iss_inuse = 0;
448255332Scy	softs->ipf_state_stats.iss_active = 0;
44953642Sguido
450255332Scy	if (softs->ipf_state_inited == 1) {
451255332Scy		softs->ipf_state_inited = 0;
452255332Scy		ipf_sttab_destroy(softs->ipf_state_tcptq);
453255332Scy		MUTEX_DESTROY(&softs->ipf_state_udptq.ifq_lock);
454255332Scy		MUTEX_DESTROY(&softs->ipf_state_icmptq.ifq_lock);
455255332Scy		MUTEX_DESTROY(&softs->ipf_state_udpacktq.ifq_lock);
456255332Scy		MUTEX_DESTROY(&softs->ipf_state_icmpacktq.ifq_lock);
457255332Scy		MUTEX_DESTROY(&softs->ipf_state_iptq.ifq_lock);
458255332Scy		MUTEX_DESTROY(&softs->ipf_state_deletetq.ifq_lock);
459255332Scy		MUTEX_DESTROY(&softs->ipf_state_pending.ifq_lock);
460255332Scy		MUTEX_DESTROY(&softs->ipf_stinsert);
461145522Sdarrenr	}
462110916Sdarrenr
463255332Scy	if (softs->ipf_state_table != NULL) {
464255332Scy		KFREES(softs->ipf_state_table,
465255332Scy		       softs->ipf_state_size * sizeof(*softs->ipf_state_table));
466255332Scy		softs->ipf_state_table = NULL;
467145522Sdarrenr	}
46853642Sguido
469255332Scy	if (softs->ipf_state_seed != NULL) {
470255332Scy		KFREES(softs->ipf_state_seed,
471255332Scy		       softs->ipf_state_size * sizeof(*softs->ipf_state_seed));
472255332Scy		softs->ipf_state_seed = NULL;
47360854Sdarrenr	}
47492685Sdarrenr
475255332Scy	if (softs->ipf_state_stats.iss_bucketlen != NULL) {
476255332Scy		KFREES(softs->ipf_state_stats.iss_bucketlen,
477255332Scy		       softs->ipf_state_size * sizeof(u_int));
478255332Scy		softs->ipf_state_stats.iss_bucketlen = NULL;
47992685Sdarrenr	}
48092685Sdarrenr
481255332Scy	return 0;
482255332Scy}
483145522Sdarrenr
484255332Scy
485255332Scy/* ------------------------------------------------------------------------ */
486255332Scy/* Function:    ipf_state_set_lock                                          */
487255332Scy/* Returns:     Nil                                                         */
488255332Scy/* Parameters:  arg(I) - pointer to local context to use                    */
489255332Scy/*              tmp(I) - new value for lock                                 */
490255332Scy/*                                                                          */
491255332Scy/* Stub function that allows for external manipulation of ipf_state_lock    */
492255332Scy/* ------------------------------------------------------------------------ */
493255332Scyvoid
494255332Scyipf_state_setlock(arg, tmp)
495255332Scy	void *arg;
496255332Scy	int tmp;
497255332Scy{
498255332Scy	ipf_state_softc_t *softs = arg;
499255332Scy
500255332Scy	softs->ipf_state_lock = tmp;
50153642Sguido}
50253642Sguido
50353642Sguido
504145522Sdarrenr/* ------------------------------------------------------------------------ */
505255332Scy/* Function:    ipf_state_stats                                             */
506145522Sdarrenr/* Returns:     ips_state_t* - pointer to state stats structure             */
507255332Scy/* Parameters:  softc(I) - pointer to soft context main structure           */
508145522Sdarrenr/*                                                                          */
509145522Sdarrenr/* Put all the current numbers and pointers into a single struct and return */
510145522Sdarrenr/* a pointer to it.                                                         */
511145522Sdarrenr/* ------------------------------------------------------------------------ */
512255332Scystatic ips_stat_t *
513255332Scyipf_state_stats(softc)
514255332Scy	ipf_main_softc_t *softc;
515145522Sdarrenr{
516255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
517255332Scy	ips_stat_t *issp = &softs->ipf_state_stats;
518255332Scy
519255332Scy	issp->iss_state_size = softs->ipf_state_size;
520255332Scy	issp->iss_state_max = softs->ipf_state_max;
521255332Scy	issp->iss_table = softs->ipf_state_table;
522255332Scy	issp->iss_list = softs->ipf_state_list;
523255332Scy	issp->iss_ticks = softc->ipf_ticks;
524255332Scy
525255332Scy#ifdef IPFILTER_LOGGING
526255332Scy	issp->iss_log_ok = ipf_log_logok(softc, IPF_LOGSTATE);
527255332Scy	issp->iss_log_fail = ipf_log_failures(softc, IPF_LOGSTATE);
528255332Scy#else
529255332Scy	issp->iss_log_ok = 0;
530255332Scy	issp->iss_log_fail = 0;
531255332Scy#endif
532255332Scy	return issp;
533145522Sdarrenr}
534145522Sdarrenr
535145522Sdarrenr/* ------------------------------------------------------------------------ */
536255332Scy/* Function:    ipf_state_remove                                            */
537145522Sdarrenr/* Returns:     int - 0 == success, != 0 == failure                         */
538255332Scy/* Parameters:  softc(I) - pointer to soft context main structure           */
539255332Scy/*              data(I)  - pointer to state structure to delete from table  */
540145522Sdarrenr/*                                                                          */
541145522Sdarrenr/* Search for a state structure that matches the one passed, according to   */
542145522Sdarrenr/* the IP addresses and other protocol specific information.                */
543145522Sdarrenr/* ------------------------------------------------------------------------ */
544255332Scystatic int
545255332Scyipf_state_remove(softc, data)
546255332Scy	ipf_main_softc_t *softc;
547255332Scy	caddr_t data;
54860854Sdarrenr{
549255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
55060854Sdarrenr	ipstate_t *sp, st;
55160854Sdarrenr	int error;
55260854Sdarrenr
55360854Sdarrenr	sp = &st;
554255332Scy	error = ipf_inobj(softc, data, NULL, &st, IPFOBJ_IPSTATE);
55560854Sdarrenr	if (error)
55660854Sdarrenr		return EFAULT;
55760854Sdarrenr
558255332Scy	WRITE_ENTER(&softc->ipf_state);
559255332Scy	for (sp = softs->ipf_state_list; sp; sp = sp->is_next)
56060854Sdarrenr		if ((sp->is_p == st.is_p) && (sp->is_v == st.is_v) &&
561145522Sdarrenr		    !bcmp((caddr_t)&sp->is_src, (caddr_t)&st.is_src,
56267614Sdarrenr			  sizeof(st.is_src)) &&
563255332Scy		    !bcmp((caddr_t)&sp->is_dst, (caddr_t)&st.is_dst,
56467614Sdarrenr			  sizeof(st.is_dst)) &&
565145522Sdarrenr		    !bcmp((caddr_t)&sp->is_ps, (caddr_t)&st.is_ps,
56667614Sdarrenr			  sizeof(st.is_ps))) {
567255332Scy			ipf_state_del(softc, sp, ISL_REMOVE);
568255332Scy			RWLOCK_EXIT(&softc->ipf_state);
56960854Sdarrenr			return 0;
57060854Sdarrenr		}
571255332Scy	RWLOCK_EXIT(&softc->ipf_state);
572255332Scy
573255332Scy	IPFERROR(100001);
57460854Sdarrenr	return ESRCH;
57560854Sdarrenr}
57660854Sdarrenr
57760854Sdarrenr
578145522Sdarrenr/* ------------------------------------------------------------------------ */
579255332Scy/* Function:    ipf_state_ioctl                                             */
580145522Sdarrenr/* Returns:     int - 0 == success, != 0 == failure                         */
581255332Scy/* Parameters:  softc(I) - pointer to soft context main structure           */
582255332Scy/*              data(I)  - pointer to ioctl data                            */
583255332Scy/*              cmd(I)   - ioctl command integer                            */
584255332Scy/*              mode(I)  - file mode bits used with open                    */
585255332Scy/*              uid(I)   - uid of process making the ioctl call             */
586255332Scy/*              ctx(I)   - pointer specific to context of the call          */
587145522Sdarrenr/*                                                                          */
588145522Sdarrenr/* Processes an ioctl call made to operate on the IP Filter state device.   */
589145522Sdarrenr/* ------------------------------------------------------------------------ */
590255332Scyint
591255332Scyipf_state_ioctl(softc, data, cmd, mode, uid, ctx)
592255332Scy	ipf_main_softc_t *softc;
593255332Scy	caddr_t data;
594255332Scy	ioctlcmd_t cmd;
595255332Scy	int mode, uid;
596255332Scy	void *ctx;
59753642Sguido{
598255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
59960854Sdarrenr	int arg, ret, error = 0;
600170268Sdarrenr	SPL_INT(s);
60153642Sguido
60253642Sguido	switch (cmd)
60353642Sguido	{
604145522Sdarrenr	/*
605145522Sdarrenr	 * Delete an entry from the state table.
606145522Sdarrenr	 */
60760854Sdarrenr	case SIOCDELST :
608255332Scy		error = ipf_state_remove(softc, data);
60960854Sdarrenr		break;
610170268Sdarrenr
611145522Sdarrenr	/*
612145522Sdarrenr	 * Flush the state table
613145522Sdarrenr	 */
61453642Sguido	case SIOCIPFFL :
615255332Scy		error = BCOPYIN(data, &arg, sizeof(arg));
616170268Sdarrenr		if (error != 0) {
617255332Scy			IPFERROR(100002);
618170268Sdarrenr			error = EFAULT;
619255332Scy
620170268Sdarrenr		} else {
621255332Scy			WRITE_ENTER(&softc->ipf_state);
622255332Scy			ret = ipf_state_flush(softc, arg, 4);
623255332Scy			RWLOCK_EXIT(&softc->ipf_state);
624255332Scy
625255332Scy			error = BCOPYOUT(&ret, data, sizeof(ret));
626255332Scy			if (error != 0) {
627255332Scy				IPFERROR(100003);
628170268Sdarrenr				error = EFAULT;
629255332Scy			}
630170268Sdarrenr		}
63153642Sguido		break;
632170268Sdarrenr
633145522Sdarrenr#ifdef	USE_INET6
634110916Sdarrenr	case SIOCIPFL6 :
635255332Scy		error = BCOPYIN(data, &arg, sizeof(arg));
636170268Sdarrenr		if (error != 0) {
637255332Scy			IPFERROR(100004);
638170268Sdarrenr			error = EFAULT;
639255332Scy
640170268Sdarrenr		} else {
641255332Scy			WRITE_ENTER(&softc->ipf_state);
642255332Scy			ret = ipf_state_flush(softc, arg, 6);
643255332Scy			RWLOCK_EXIT(&softc->ipf_state);
644255332Scy
645255332Scy			error = BCOPYOUT(&ret, data, sizeof(ret));
646255332Scy			if (error != 0) {
647255332Scy				IPFERROR(100005);
648170268Sdarrenr				error = EFAULT;
649255332Scy			}
650170268Sdarrenr		}
651110916Sdarrenr		break;
652110916Sdarrenr#endif
653255332Scy
654255332Scy	case SIOCMATCHFLUSH :
655255332Scy		WRITE_ENTER(&softc->ipf_state);
656255332Scy		error = ipf_state_matchflush(softc, data);
657255332Scy		RWLOCK_EXIT(&softc->ipf_state);
658255332Scy		break;
659255332Scy
66055929Sguido#ifdef	IPFILTER_LOG
661145522Sdarrenr	/*
662145522Sdarrenr	 * Flush the state log.
663145522Sdarrenr	 */
66455929Sguido	case SIOCIPFFB :
665255332Scy		if (!(mode & FWRITE)) {
666255332Scy			IPFERROR(100008);
66755929Sguido			error = EPERM;
668255332Scy		} else {
66960854Sdarrenr			int tmp;
67060854Sdarrenr
671255332Scy			tmp = ipf_log_clear(softc, IPL_LOGSTATE);
672255332Scy			error = BCOPYOUT(&tmp, data, sizeof(tmp));
673255332Scy			if (error != 0) {
674255332Scy				IPFERROR(100009);
675170268Sdarrenr				error = EFAULT;
676255332Scy			}
67760854Sdarrenr		}
67855929Sguido		break;
679170268Sdarrenr
680145522Sdarrenr	/*
681145522Sdarrenr	 * Turn logging of state information on/off.
682145522Sdarrenr	 */
683145522Sdarrenr	case SIOCSETLG :
684255332Scy		if (!(mode & FWRITE)) {
685255332Scy			IPFERROR(100010);
686145522Sdarrenr			error = EPERM;
687255332Scy		} else {
688255332Scy			error = BCOPYIN(data, &softs->ipf_state_logging,
689255332Scy					sizeof(softs->ipf_state_logging));
690255332Scy			if (error != 0) {
691255332Scy				IPFERROR(100011);
692170268Sdarrenr				error = EFAULT;
693255332Scy			}
694145522Sdarrenr		}
69553642Sguido		break;
696170268Sdarrenr
697145522Sdarrenr	/*
698145522Sdarrenr	 * Return the current state of logging.
699145522Sdarrenr	 */
700145522Sdarrenr	case SIOCGETLG :
701255332Scy		error = BCOPYOUT(&softs->ipf_state_logging, data,
702255332Scy				 sizeof(softs->ipf_state_logging));
703255332Scy		if (error != 0) {
704255332Scy			IPFERROR(100012);
705170268Sdarrenr			error = EFAULT;
706255332Scy		}
707145522Sdarrenr		break;
708170268Sdarrenr
709145522Sdarrenr	/*
710145522Sdarrenr	 * Return the number of bytes currently waiting to be read.
711145522Sdarrenr	 */
71253642Sguido	case FIONREAD :
713255332Scy		arg = ipf_log_bytesused(softc, IPL_LOGSTATE);
714255332Scy		error = BCOPYOUT(&arg, data, sizeof(arg));
715255332Scy		if (error != 0) {
716255332Scy			IPFERROR(100013);
717170268Sdarrenr			error = EFAULT;
718255332Scy		}
719145522Sdarrenr		break;
72053642Sguido#endif
721170268Sdarrenr
722145522Sdarrenr	/*
723145522Sdarrenr	 * Get the current state statistics.
724145522Sdarrenr	 */
725145522Sdarrenr	case SIOCGETFS :
726255332Scy		error = ipf_outobj(softc, data, ipf_state_stats(softc),
727255332Scy				   IPFOBJ_STATESTAT);
72853642Sguido		break;
729170268Sdarrenr
730145522Sdarrenr	/*
731145522Sdarrenr	 * Lock/Unlock the state table.  (Locking prevents any changes, which
732145522Sdarrenr	 * means no packets match).
733145522Sdarrenr	 */
73460854Sdarrenr	case SIOCSTLCK :
735153876Sguido		if (!(mode & FWRITE)) {
736255332Scy			IPFERROR(100014);
737153876Sguido			error = EPERM;
738153876Sguido		} else {
739255332Scy			error = ipf_lock(data, &softs->ipf_state_lock);
740153876Sguido		}
74160854Sdarrenr		break;
742170268Sdarrenr
743145522Sdarrenr	/*
744145522Sdarrenr	 * Add an entry to the current state table.
745145522Sdarrenr	 */
74660854Sdarrenr	case SIOCSTPUT :
747255332Scy		if (!softs->ipf_state_lock || !(mode &FWRITE)) {
748255332Scy			IPFERROR(100015);
74960854Sdarrenr			error = EACCES;
75060854Sdarrenr			break;
75160854Sdarrenr		}
752255332Scy		error = ipf_state_putent(softc, softs, data);
75360854Sdarrenr		break;
754170268Sdarrenr
755145522Sdarrenr	/*
756145522Sdarrenr	 * Get a state table entry.
757145522Sdarrenr	 */
75860854Sdarrenr	case SIOCSTGET :
759255332Scy		if (!softs->ipf_state_lock) {
760255332Scy			IPFERROR(100016);
76160854Sdarrenr			error = EACCES;
76260854Sdarrenr			break;
76360854Sdarrenr		}
764255332Scy		error = ipf_state_getent(softc, softs, data);
76560854Sdarrenr		break;
766170268Sdarrenr
767170268Sdarrenr	/*
768170268Sdarrenr	 * Return a copy of the hash table bucket lengths
769170268Sdarrenr	 */
770170268Sdarrenr	case SIOCSTAT1 :
771255332Scy		error = BCOPYOUT(softs->ipf_state_stats.iss_bucketlen, data,
772255332Scy				 softs->ipf_state_size * sizeof(u_int));
773255332Scy		if (error != 0) {
774255332Scy			IPFERROR(100017);
775170268Sdarrenr			error = EFAULT;
776255332Scy		}
777170268Sdarrenr		break;
778170268Sdarrenr
779170268Sdarrenr	case SIOCGENITER :
780170268Sdarrenr	    {
781170268Sdarrenr		ipftoken_t *token;
782170268Sdarrenr		ipfgeniter_t iter;
783255332Scy		ipfobj_t obj;
784170268Sdarrenr
785255332Scy		error = ipf_inobj(softc, data, &obj, &iter, IPFOBJ_GENITER);
786170268Sdarrenr		if (error != 0)
787170268Sdarrenr			break;
788170268Sdarrenr
789170268Sdarrenr		SPL_SCHED(s);
790255332Scy		token = ipf_token_find(softc, IPFGENITER_STATE, uid, ctx);
791255332Scy		if (token != NULL) {
792255332Scy			error = ipf_state_iter(softc, token, &iter, &obj);
793255332Scy			WRITE_ENTER(&softc->ipf_tokens);
794255332Scy			ipf_token_deref(softc, token);
795255332Scy			RWLOCK_EXIT(&softc->ipf_tokens);
796255332Scy		} else {
797255332Scy			IPFERROR(100018);
798170268Sdarrenr			error = ESRCH;
799255332Scy		}
800170268Sdarrenr		SPL_X(s);
801170268Sdarrenr		break;
802170268Sdarrenr	    }
803170268Sdarrenr
804170268Sdarrenr	case SIOCGTABL :
805255332Scy		error = ipf_state_gettable(softc, softs, data);
806170268Sdarrenr		break;
807170268Sdarrenr
808170268Sdarrenr	case SIOCIPFDELTOK :
809255332Scy		error = BCOPYIN(data, &arg, sizeof(arg));
810170268Sdarrenr		if (error != 0) {
811255332Scy			IPFERROR(100019);
812170268Sdarrenr			error = EFAULT;
813170268Sdarrenr		} else {
814170268Sdarrenr			SPL_SCHED(s);
815255332Scy			error = ipf_token_del(softc, arg, uid, ctx);
816170268Sdarrenr			SPL_X(s);
817170268Sdarrenr		}
818170268Sdarrenr		break;
819170268Sdarrenr
820170268Sdarrenr	case SIOCGTQTAB :
821255332Scy		error = ipf_outobj(softc, data, softs->ipf_state_tcptq,
822255332Scy				   IPFOBJ_STATETQTAB);
823170268Sdarrenr		break;
824170268Sdarrenr
82553642Sguido	default :
826255332Scy		IPFERROR(100020);
82753642Sguido		error = EINVAL;
82853642Sguido		break;
82953642Sguido	}
83053642Sguido	return error;
83153642Sguido}
83253642Sguido
83353642Sguido
834145522Sdarrenr/* ------------------------------------------------------------------------ */
835255332Scy/* Function:    ipf_state_getent                                            */
836145522Sdarrenr/* Returns:     int - 0 == success, != 0 == failure                         */
837255332Scy/* Parameters:  softc(I) - pointer to soft context main structure           */
838255332Scy/*              softs(I) - pointer to state context structure               */
839255332Scy/*              data(I)  - pointer to state structure to retrieve from table*/
840145522Sdarrenr/*                                                                          */
841145522Sdarrenr/* Copy out state information from the kernel to a user space process.  If  */
842145522Sdarrenr/* there is a filter rule associated with the state entry, copy that out    */
843145522Sdarrenr/* as well.  The entry to copy out is taken from the value of "ips_next" in */
844145522Sdarrenr/* the struct passed in and if not null and not found in the list of current*/
845145522Sdarrenr/* state entries, the retrieval fails.                                      */
846145522Sdarrenr/* ------------------------------------------------------------------------ */
847255332Scystatic int
848255332Scyipf_state_getent(softc, softs, data)
849255332Scy	ipf_main_softc_t *softc;
850255332Scy	ipf_state_softc_t *softs;
851255332Scy	caddr_t data;
85260854Sdarrenr{
853145522Sdarrenr	ipstate_t *is, *isn;
85492685Sdarrenr	ipstate_save_t ips;
85560854Sdarrenr	int error;
85660854Sdarrenr
857255332Scy	error = ipf_inobj(softc, data, NULL, &ips, IPFOBJ_STATESAVE);
858255332Scy	if (error)
859255332Scy		return EFAULT;
86060854Sdarrenr
861255332Scy	READ_ENTER(&softc->ipf_state);
86260854Sdarrenr	isn = ips.ips_next;
863145522Sdarrenr	if (isn == NULL) {
864255332Scy		isn = softs->ipf_state_list;
86560854Sdarrenr		if (isn == NULL) {
866255332Scy			if (ips.ips_next == NULL) {
867255332Scy				RWLOCK_EXIT(&softc->ipf_state);
868255332Scy				IPFERROR(100021);
86960854Sdarrenr				return ENOENT;
870255332Scy			}
87160854Sdarrenr			return 0;
87260854Sdarrenr		}
87360854Sdarrenr	} else {
87460854Sdarrenr		/*
87560854Sdarrenr		 * Make sure the pointer we're copying from exists in the
87660854Sdarrenr		 * current list of entries.  Security precaution to prevent
87760854Sdarrenr		 * copying of random kernel data.
87860854Sdarrenr		 */
879255332Scy		for (is = softs->ipf_state_list; is; is = is->is_next)
88060854Sdarrenr			if (is == isn)
88160854Sdarrenr				break;
882255332Scy		if (!is) {
883255332Scy			RWLOCK_EXIT(&softc->ipf_state);
884255332Scy			IPFERROR(100022);
88560854Sdarrenr			return ESRCH;
886173181Sdarrenr		}
88760854Sdarrenr	}
88860854Sdarrenr	ips.ips_next = isn->is_next;
88960854Sdarrenr	bcopy((char *)isn, (char *)&ips.ips_is, sizeof(ips.ips_is));
890145522Sdarrenr	ips.ips_rule = isn->is_rule;
891145522Sdarrenr	if (isn->is_rule != NULL)
89260854Sdarrenr		bcopy((char *)isn->is_rule, (char *)&ips.ips_fr,
89360854Sdarrenr		      sizeof(ips.ips_fr));
894255332Scy	RWLOCK_EXIT(&softc->ipf_state);
895255332Scy	error = ipf_outobj(softc, data, &ips, IPFOBJ_STATESAVE);
896172776Sdarrenr	return error;
89760854Sdarrenr}
89860854Sdarrenr
89960854Sdarrenr
900145522Sdarrenr/* ------------------------------------------------------------------------ */
901255332Scy/* Function:    ipf_state_putent                                            */
902145522Sdarrenr/* Returns:     int - 0 == success, != 0 == failure                         */
903255332Scy/* Parameters:  softc(I) - pointer to soft context main structure           */
904255332Scy/*              softs(I) - pointer to state context structure               */
905255332Scy/*              data(I)  - pointer to state information struct              */
906145522Sdarrenr/*                                                                          */
907145522Sdarrenr/* This function implements the SIOCSTPUT ioctl: insert a state entry into  */
908145522Sdarrenr/* the state table.  If the state info. includes a pointer to a filter rule */
909145522Sdarrenr/* then also add in an orphaned rule (will not show up in any "ipfstat -io" */
910145522Sdarrenr/* output.                                                                  */
911145522Sdarrenr/* ------------------------------------------------------------------------ */
912255332Scyint
913255332Scyipf_state_putent(softc, softs, data)
914255332Scy	ipf_main_softc_t *softc;
915255332Scy	ipf_state_softc_t *softs;
916255332Scy	caddr_t data;
91760854Sdarrenr{
918145522Sdarrenr	ipstate_t *is, *isn;
91992685Sdarrenr	ipstate_save_t ips;
92092685Sdarrenr	int error, out, i;
92160854Sdarrenr	frentry_t *fr;
92292685Sdarrenr	char *name;
92360854Sdarrenr
924255332Scy	error = ipf_inobj(softc, data, NULL, &ips, IPFOBJ_STATESAVE);
925255332Scy	if (error != 0)
926255332Scy		return error;
92760854Sdarrenr
92860854Sdarrenr	KMALLOC(isn, ipstate_t *);
929255332Scy	if (isn == NULL) {
930255332Scy		IPFERROR(100023);
93160854Sdarrenr		return ENOMEM;
932255332Scy	}
93360854Sdarrenr
93460854Sdarrenr	bcopy((char *)&ips.ips_is, (char *)isn, sizeof(*isn));
935145522Sdarrenr	bzero((char *)isn, offsetof(struct ipstate, is_pkts));
936145522Sdarrenr	isn->is_sti.tqe_pnext = NULL;
937145522Sdarrenr	isn->is_sti.tqe_next = NULL;
938145522Sdarrenr	isn->is_sti.tqe_ifq = NULL;
939145522Sdarrenr	isn->is_sti.tqe_parent = isn;
940145522Sdarrenr	isn->is_ifp[0] = NULL;
941145522Sdarrenr	isn->is_ifp[1] = NULL;
942145522Sdarrenr	isn->is_ifp[2] = NULL;
943145522Sdarrenr	isn->is_ifp[3] = NULL;
944145522Sdarrenr	isn->is_sync = NULL;
945145522Sdarrenr	fr = ips.ips_rule;
94692685Sdarrenr
947145522Sdarrenr	if (fr == NULL) {
948255332Scy		int inserr;
949255332Scy
950255332Scy		READ_ENTER(&softc->ipf_state);
951255332Scy		inserr = ipf_state_insert(softc, isn, 0);
952153876Sguido		MUTEX_EXIT(&isn->is_lock);
953255332Scy		RWLOCK_EXIT(&softc->ipf_state);
954255332Scy
955255332Scy		return inserr;
956145522Sdarrenr	}
957145522Sdarrenr
958145522Sdarrenr	if (isn->is_flags & SI_NEWFR) {
959145522Sdarrenr		KMALLOC(fr, frentry_t *);
960145522Sdarrenr		if (fr == NULL) {
961145522Sdarrenr			KFREE(isn);
962255332Scy			IPFERROR(100024);
963145522Sdarrenr			return ENOMEM;
964145522Sdarrenr		}
965145522Sdarrenr		bcopy((char *)&ips.ips_fr, (char *)fr, sizeof(*fr));
966145522Sdarrenr		out = fr->fr_flags & FR_OUTQUE ? 1 : 0;
967145522Sdarrenr		isn->is_rule = fr;
968145522Sdarrenr		ips.ips_is.is_rule = fr;
969145522Sdarrenr		MUTEX_NUKE(&fr->fr_lock);
970145522Sdarrenr		MUTEX_INIT(&fr->fr_lock, "state filter rule lock");
971145522Sdarrenr
972145522Sdarrenr		/*
973145522Sdarrenr		 * Look up all the interface names in the rule.
974145522Sdarrenr		 */
975145522Sdarrenr		for (i = 0; i < 4; i++) {
976255332Scy			if (fr->fr_ifnames[i] == -1) {
977255332Scy				fr->fr_ifas[i] = NULL;
978255332Scy				continue;
979255332Scy			}
980255332Scy			name = fr->fr_names + fr->fr_ifnames[i];
981255332Scy			fr->fr_ifas[i] = ipf_resolvenic(softc, name,
982255332Scy							fr->fr_family);
983255332Scy		}
984255332Scy
985255332Scy		for (i = 0; i < 4; i++) {
986145522Sdarrenr			name = isn->is_ifname[i];
987255332Scy			isn->is_ifp[i] = ipf_resolvenic(softc, name,
988255332Scy							isn->is_v);
989145522Sdarrenr		}
990145522Sdarrenr
991145522Sdarrenr		fr->fr_ref = 0;
992145522Sdarrenr		fr->fr_dsize = 0;
993145522Sdarrenr		fr->fr_data = NULL;
994161356Sguido		fr->fr_type = FR_T_NONE;
995145522Sdarrenr
996255332Scy		(void) ipf_resolvedest(softc, fr->fr_names, &fr->fr_tifs[0],
997255332Scy				fr->fr_family);
998255332Scy		(void) ipf_resolvedest(softc, fr->fr_names, &fr->fr_tifs[1],
999255332Scy				fr->fr_family);
1000255332Scy		(void) ipf_resolvedest(softc, fr->fr_names, &fr->fr_dif,
1001255332Scy				fr->fr_family);
1002145522Sdarrenr
1003145522Sdarrenr		/*
1004145522Sdarrenr		 * send a copy back to userland of what we ended up
1005145522Sdarrenr		 * to allow for verification.
1006145522Sdarrenr		 */
1007255332Scy		error = ipf_outobj(softc, data, &ips, IPFOBJ_STATESAVE);
1008255332Scy		if (error != 0) {
1009145522Sdarrenr			KFREE(isn);
1010145522Sdarrenr			MUTEX_DESTROY(&fr->fr_lock);
1011145522Sdarrenr			KFREE(fr);
1012255332Scy			IPFERROR(100025);
1013145522Sdarrenr			return EFAULT;
1014145522Sdarrenr		}
1015255332Scy		READ_ENTER(&softc->ipf_state);
1016255332Scy		error = ipf_state_insert(softc, isn, 0);
1017153876Sguido		MUTEX_EXIT(&isn->is_lock);
1018255332Scy		RWLOCK_EXIT(&softc->ipf_state);
1019145522Sdarrenr
1020145522Sdarrenr	} else {
1021255332Scy		READ_ENTER(&softc->ipf_state);
1022255332Scy		for (is = softs->ipf_state_list; is; is = is->is_next)
1023145522Sdarrenr			if (is->is_rule == fr) {
1024255332Scy				error = ipf_state_insert(softc, isn, 0);
1025153876Sguido				MUTEX_EXIT(&isn->is_lock);
1026145522Sdarrenr				break;
102792685Sdarrenr			}
102892685Sdarrenr
1029145522Sdarrenr		if (is == NULL) {
1030145522Sdarrenr			KFREE(isn);
1031145522Sdarrenr			isn = NULL;
103260854Sdarrenr		}
1033255332Scy		RWLOCK_EXIT(&softc->ipf_state);
1034145522Sdarrenr
1035255332Scy		if (isn == NULL) {
1036255332Scy			IPFERROR(100033);
1037255332Scy			error = ESRCH;
1038255332Scy		}
103960854Sdarrenr	}
1040145522Sdarrenr
1041255332Scy	return error;
104260854Sdarrenr}
104360854Sdarrenr
104460854Sdarrenr
1045145522Sdarrenr/* ------------------------------------------------------------------------ */
1046255332Scy/* Function:    ipf_state_insert                                            */
1047255332Scy/* Returns:     int    - 0 == success, -1 == failure                        */
1048255332Scy/* Parameters:  softc(I) - pointer to soft context main structure           */
1049255332Scy/* Parameters:  is(I)    - pointer to state structure                       */
1050255332Scy/*              rev(I) - flag indicating direction of packet                */
1051145522Sdarrenr/*                                                                          */
1052145522Sdarrenr/* Inserts a state structure into the hash table (for lookups) and the list */
1053145522Sdarrenr/* of state entries (for enumeration).  Resolves all of the interface names */
1054145522Sdarrenr/* to pointers and adjusts running stats for the hash table as appropriate. */
1055145522Sdarrenr/*                                                                          */
1056255332Scy/* This function can fail if the filter rule has had a population policy of */
1057287984Scy/* IP addresses used with stateful filtering assigned to it.                */
1058255332Scy/*                                                                          */
1059145522Sdarrenr/* Locking: it is assumed that some kind of lock on ipf_state is held.      */
1060255332Scy/*          Exits with is_lock initialised and held - *EVEN IF ERROR*.      */
1061145522Sdarrenr/* ------------------------------------------------------------------------ */
1062255332Scyint
1063255332Scyipf_state_insert(softc, is, rev)
1064255332Scy	ipf_main_softc_t *softc;
1065255332Scy	ipstate_t *is;
1066255332Scy	int rev;
106760854Sdarrenr{
1068255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
1069145522Sdarrenr	frentry_t *fr;
1070145522Sdarrenr	u_int hv;
107192685Sdarrenr	int i;
107260854Sdarrenr
107392685Sdarrenr	/*
107492685Sdarrenr	 * Look up all the interface names in the state entry.
107592685Sdarrenr	 */
107692685Sdarrenr	for (i = 0; i < 4; i++) {
1077145522Sdarrenr		if (is->is_ifp[i] != NULL)
1078145522Sdarrenr			continue;
1079255332Scy		is->is_ifp[i] = ipf_resolvenic(softc, is->is_ifname[i],
1080255332Scy					       is->is_v);
108160854Sdarrenr	}
108260854Sdarrenr
1083145522Sdarrenr	/*
1084287984Scy	 * If we could trust is_hv, then the modulus would not be needed,
1085255332Scy	 * but when running with IPFILTER_SYNC, this stops bad values.
1086145522Sdarrenr	 */
1087255332Scy	hv = is->is_hv % softs->ipf_state_size;
1088255332Scy	/* TRACE is, hv */
1089145522Sdarrenr	is->is_hv = hv;
109092685Sdarrenr
109160854Sdarrenr	/*
1092145522Sdarrenr	 * We need to get both of these locks...the first because it is
1093145522Sdarrenr	 * possible that once the insert is complete another packet might
1094145522Sdarrenr	 * come along, match the entry and want to update it.
1095145522Sdarrenr	 */
1096255332Scy	MUTEX_INIT(&is->is_lock, "ipf state entry");
1097145522Sdarrenr	MUTEX_ENTER(&is->is_lock);
1098255332Scy	MUTEX_ENTER(&softs->ipf_stinsert);
1099145522Sdarrenr
1100255332Scy	fr = is->is_rule;
1101255332Scy	if (fr != NULL) {
1102255332Scy		if ((fr->fr_srctrack.ht_max_nodes != 0) &&
1103255332Scy		    (ipf_ht_node_add(softc, &fr->fr_srctrack,
1104255332Scy				     is->is_family, &is->is_src) == -1)) {
1105255332Scy			SBUMPD(ipf_state_stats, iss_max_track);
1106255332Scy			MUTEX_EXIT(&softs->ipf_stinsert);
1107255332Scy			return -1;
1108255332Scy		}
1109255332Scy
1110255332Scy		MUTEX_ENTER(&fr->fr_lock);
1111255332Scy		fr->fr_ref++;
1112255332Scy		MUTEX_EXIT(&fr->fr_lock);
1113255332Scy		fr->fr_statecnt++;
1114255332Scy	}
1115255332Scy
1116255332Scy	if (is->is_flags & (SI_WILDP|SI_WILDA)) {
1117255332Scy		DT(iss_wild_plus_one);
1118255332Scy		SINCL(ipf_state_stats.iss_wild);
1119255332Scy	}
1120255332Scy
1121255332Scy	SBUMP(ipf_state_stats.iss_proto[is->is_p]);
1122255332Scy	SBUMP(ipf_state_stats.iss_active_proto[is->is_p]);
1123255332Scy
1124145522Sdarrenr	/*
112560854Sdarrenr	 * add into list table.
112660854Sdarrenr	 */
1127255332Scy	if (softs->ipf_state_list != NULL)
1128255332Scy		softs->ipf_state_list->is_pnext = &is->is_next;
1129255332Scy	is->is_pnext = &softs->ipf_state_list;
1130255332Scy	is->is_next = softs->ipf_state_list;
1131255332Scy	softs->ipf_state_list = is;
1132145522Sdarrenr
1133255332Scy	if (softs->ipf_state_table[hv] != NULL)
1134255332Scy		softs->ipf_state_table[hv]->is_phnext = &is->is_hnext;
113560854Sdarrenr	else
1136255332Scy		softs->ipf_state_stats.iss_inuse++;
1137255332Scy	is->is_phnext = softs->ipf_state_table + hv;
1138255332Scy	is->is_hnext = softs->ipf_state_table[hv];
1139255332Scy	softs->ipf_state_table[hv] = is;
1140255332Scy	softs->ipf_state_stats.iss_bucketlen[hv]++;
1141255332Scy	softs->ipf_state_stats.iss_active++;
1142255332Scy	MUTEX_EXIT(&softs->ipf_stinsert);
1143145522Sdarrenr
1144255332Scy	ipf_state_setqueue(softc, is, rev);
1145255332Scy
1146255332Scy	return 0;
114760854Sdarrenr}
114860854Sdarrenr
114960854Sdarrenr
1150145522Sdarrenr/* ------------------------------------------------------------------------ */
1151255332Scy/* Function:    ipf_state_matchipv4addrs                                    */
1152255332Scy/* Returns:     int - 2 addresses match (strong match), 1 reverse match,    */
1153255332Scy/*                    0 no match                                            */
1154255332Scy/* Parameters:  is1, is2 pointers to states we are checking                 */
1155255332Scy/*                                                                          */
1156255332Scy/* Function matches IPv4 addresses it returns strong match for ICMP proto   */
1157255332Scy/* even there is only reverse match                                         */
1158255332Scy/* ------------------------------------------------------------------------ */
1159255332Scystatic int
1160255332Scyipf_state_matchipv4addrs(is1, is2)
1161255332Scy	ipstate_t *is1, *is2;
1162255332Scy{
1163255332Scy	int	rv;
1164255332Scy
1165255332Scy	if (is1->is_saddr == is2->is_saddr && is1->is_daddr == is2->is_daddr)
1166255332Scy		rv = 2;
1167255332Scy	else if (is1->is_saddr == is2->is_daddr &&
1168255332Scy	    is1->is_daddr == is2->is_saddr) {
1169255332Scy		/* force strong match for ICMP protocol */
1170255332Scy		rv = (is1->is_p == IPPROTO_ICMP) ? 2 : 1;
1171255332Scy	}
1172255332Scy	else
1173255332Scy		rv = 0;
1174255332Scy
1175255332Scy	return (rv);
1176255332Scy}
1177255332Scy
1178255332Scy
1179255332Scy/* ------------------------------------------------------------------------ */
1180255332Scy/* Function:    ipf_state_matchipv6addrs                                    */
1181255332Scy/* Returns:     int - 2 addresses match (strong match), 1 reverse match,    */
1182255332Scy/*                    0 no match                                            */
1183255332Scy/* Parameters:  is1, is2 pointers to states we are checking                 */
1184255332Scy/*                                                                          */
1185255332Scy/* Function matches IPv6 addresses it returns strong match for ICMP proto   */
1186255332Scy/* even there is only reverse match                                         */
1187255332Scy/* ------------------------------------------------------------------------ */
1188255332Scystatic int
1189255332Scyipf_state_matchipv6addrs(is1, is2)
1190255332Scy	ipstate_t *is1, *is2;
1191255332Scy{
1192255332Scy	int	rv;
1193255332Scy
1194255332Scy	if (IP6_EQ(&is1->is_src, &is2->is_src) &&
1195255332Scy	    IP6_EQ(&is1->is_dst, &is2->is_dst))
1196255332Scy		rv = 2;
1197255332Scy	else if (IP6_EQ(&is1->is_src, &is2->is_dst) &&
1198255332Scy	    IP6_EQ(&is1->is_dst, &is2->is_src)) {
1199255332Scy		/* force strong match for ICMPv6 protocol */
1200255332Scy		rv = (is1->is_p == IPPROTO_ICMPV6) ? 2 : 1;
1201255332Scy	}
1202255332Scy	else
1203255332Scy		rv = 0;
1204255332Scy
1205255332Scy	return (rv);
1206255332Scy}
1207255332Scy
1208255332Scy
1209255332Scy/* ------------------------------------------------------------------------ */
1210255332Scy/* Function:    ipf_state_matchaddresses                                    */
1211255332Scy/* Returns:     int - 2 addresses match, 1 reverse match, zero no match     */
1212255332Scy/* Parameters:  is1, is2 pointers to states we are checking                 */
1213255332Scy/*                                                                          */
1214255332Scy/* function retruns true if two pairs of addresses belong to single         */
1215255332Scy/* connection. suppose there are two endpoints:                             */
1216255332Scy/*      endpoint1 1.1.1.1                                                   */
1217255332Scy/*      endpoint2 1.1.1.2                                                   */
1218255332Scy/*                                                                          */
1219255332Scy/* the state is established by packet flying from .1 to .2 so we see:       */
1220255332Scy/*      is1->src = 1.1.1.1                                                  */
1221255332Scy/*      is1->dst = 1.1.1.2                                                  */
1222255332Scy/* now endpoint 1.1.1.2 sends answer                                        */
1223255332Scy/* retreives is1 record created by first packat and compares it with is2    */
1224255332Scy/* temporal record, is2 is initialized as follows:                          */
1225255332Scy/*      is2->src = 1.1.1.2                                                  */
1226255332Scy/*      is2->dst = 1.1.1.1                                                  */
1227255332Scy/* in this case 1 will be returned                                          */
1228255332Scy/*                                                                          */
1229255332Scy/* the ipf_matchaddresses() assumes those two records to be same. of course */
1230255332Scy/* the ipf_matchaddresses() also assume records are same in case you pass   */
1231255332Scy/* identical arguments (i.e. ipf_matchaddress(is1, is1) would return 2      */
1232255332Scy/* ------------------------------------------------------------------------ */
1233255332Scystatic int
1234255332Scyipf_state_matchaddresses(is1, is2)
1235255332Scy	ipstate_t *is1, *is2;
1236255332Scy{
1237255332Scy	int	rv;
1238255332Scy
1239255332Scy	if (is1->is_v == 4) {
1240255332Scy		rv = ipf_state_matchipv4addrs(is1, is2);
1241255332Scy	}
1242255332Scy	else {
1243255332Scy		rv = ipf_state_matchipv6addrs(is1, is2);
1244255332Scy	}
1245255332Scy
1246255332Scy	return (rv);
1247255332Scy}
1248255332Scy
1249255332Scy
1250255332Scy/* ------------------------------------------------------------------------ */
1251255332Scy/* Function:    ipf_matchports                                              */
1252255332Scy/* Returns:     int - 2 match, 1 rverse match, 0 no match                   */
1253255332Scy/* Parameters:  ppairs1, ppairs - src, dst ports we want to match           */
1254255332Scy/*                                                                          */
1255255332Scy/* performs the same match for isps members as for addresses                */
1256255332Scy/* ------------------------------------------------------------------------ */
1257255332Scystatic int
1258255332Scyipf_state_matchports(ppairs1, ppairs2)
1259255332Scy	udpinfo_t *ppairs1, *ppairs2;
1260255332Scy{
1261255332Scy	int	rv;
1262255332Scy
1263255332Scy	if (ppairs1->us_sport == ppairs2->us_sport &&
1264255332Scy	    ppairs1->us_dport == ppairs2->us_dport)
1265255332Scy		rv = 2;
1266255332Scy	else if (ppairs1->us_sport == ppairs2->us_dport &&
1267255332Scy		    ppairs1->us_dport == ppairs2->us_sport)
1268255332Scy		rv = 1;
1269255332Scy	else
1270255332Scy		rv = 0;
1271255332Scy
1272255332Scy	return (rv);
1273255332Scy}
1274255332Scy
1275255332Scy
1276255332Scy/* ------------------------------------------------------------------------ */
1277255332Scy/* Function:    ipf_matchisps                                               */
1278255332Scy/* Returns:     int - nonzero if isps members match, 0 nomatch              */
1279255332Scy/* Parameters:  is1, is2 - states we want to match                          */
1280255332Scy/*                                                                          */
1281255332Scy/* performs the same match for isps members as for addresses                */
1282255332Scy/* ------------------------------------------------------------------------ */
1283255332Scystatic int
1284255332Scyipf_state_matchisps(is1, is2)
1285255332Scy	ipstate_t *is1, *is2;
1286255332Scy{
1287255332Scy	int	rv;
1288255332Scy
1289255332Scy	if (is1->is_p == is2->is_p) {
1290255332Scy		switch (is1->is_p)
1291255332Scy		{
1292255332Scy		case IPPROTO_TCP :
1293255332Scy		case IPPROTO_UDP :
1294255332Scy		case IPPROTO_GRE :
1295255332Scy			/* greinfo_t can be also interprted as port pair */
1296255332Scy			rv = ipf_state_matchports(&is1->is_ps.is_us,
1297255332Scy						  &is2->is_ps.is_us);
1298255332Scy			break;
1299255332Scy
1300255332Scy		case IPPROTO_ICMP :
1301255332Scy		case IPPROTO_ICMPV6 :
1302255332Scy			/* force strong match for ICMP datagram. */
1303255332Scy			if (bcmp(&is1->is_ps, &is2->is_ps,
1304255332Scy				 sizeof(icmpinfo_t)) == 0)  {
1305255332Scy				rv = 2;
1306255332Scy			} else {
1307255332Scy				rv = 0;
1308255332Scy			}
1309255332Scy			break;
1310255332Scy
1311255332Scy		default:
1312255332Scy			rv = 0;
1313255332Scy		}
1314255332Scy	} else {
1315255332Scy		rv = 0;
1316255332Scy	}
1317255332Scy
1318255332Scy	return (rv);
1319255332Scy}
1320255332Scy
1321255332Scy
1322255332Scy/* ------------------------------------------------------------------------ */
1323255332Scy/* Function:    ipf_state_match                                             */
1324255332Scy/* Returns:     int - nonzero match, zero no match                          */
1325255332Scy/* Parameters:  is1, is2 - states we want to match                          */
1326255332Scy/*                                                                          */
1327255332Scy/* ------------------------------------------------------------------------ */
1328255332Scystatic int
1329255332Scyipf_state_match(is1, is2)
1330255332Scy	ipstate_t *is1, *is2;
1331255332Scy{
1332255332Scy	int	rv;
1333255332Scy	int	amatch;
1334255332Scy	int	pomatch;
1335255332Scy
1336255332Scy	if (bcmp(&is1->is_pass, &is2->is_pass,
1337255332Scy		 offsetof(struct ipstate, is_authmsk) -
1338255332Scy		 offsetof(struct ipstate, is_pass)) == 0) {
1339255332Scy
1340255332Scy		pomatch = ipf_state_matchisps(is1, is2);
1341255332Scy		amatch = ipf_state_matchaddresses(is1, is2);
1342255332Scy		rv = (amatch != 0) && (amatch == pomatch);
1343255332Scy	} else {
1344255332Scy		rv = 0;
1345255332Scy	}
1346255332Scy
1347255332Scy	return (rv);
1348255332Scy}
1349255332Scy
1350255332Scy/* ------------------------------------------------------------------------ */
1351255332Scy/* Function:    ipf_state_add                                               */
1352255332Scy/* Returns:     ipstate_t - 0 = success                                     */
1353255332Scy/* Parameters:  softc(I)  - pointer to soft context main structure          */
1354255332Scy/*              fin(I)    - pointer to packet information                   */
1355145522Sdarrenr/*              stsave(O) - pointer to place to save pointer to created     */
1356145522Sdarrenr/*                          state structure.                                */
1357145522Sdarrenr/*              flags(I)  - flags to use when creating the structure        */
1358145522Sdarrenr/*                                                                          */
1359145522Sdarrenr/* Creates a new IP state structure from the packet information collected.  */
1360145522Sdarrenr/* Inserts it into the state table and appends to the bottom of the active  */
1361145522Sdarrenr/* list.  If the capacity of the table has reached the maximum allowed then */
1362145522Sdarrenr/* the call will fail and a flush is scheduled for the next timeout call.   */
1363161356Sguido/*                                                                          */
1364161356Sguido/* NOTE: The use of stsave to point to nat_state will result in memory      */
1365161356Sguido/*       corruption.  It should only be used to point to objects that will  */
1366161356Sguido/*       either outlive this (not expired) or will deref the ip_state_t     */
1367161356Sguido/*       when they are deleted.                                             */
1368145522Sdarrenr/* ------------------------------------------------------------------------ */
1369255332Scyint
1370255332Scyipf_state_add(softc, fin, stsave, flags)
1371255332Scy	ipf_main_softc_t *softc;
1372255332Scy	fr_info_t *fin;
1373255332Scy	ipstate_t **stsave;
1374255332Scy	u_int flags;
137553642Sguido{
1376255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
1377145522Sdarrenr	ipstate_t *is, ips;
137892685Sdarrenr	struct icmp *ic;
1379145522Sdarrenr	u_int pass, hv;
1380145522Sdarrenr	frentry_t *fr;
1381145522Sdarrenr	tcphdr_t *tcp;
1382255332Scy	frdest_t *fdp;
1383145522Sdarrenr	int out;
138453642Sguido
1385255332Scy	/*
1386255332Scy	 * If a packet that was created locally is trying to go out but we
1387255332Scy	 * do not match here here because of this lock, it is likely that
1388255332Scy	 * the policy will block it and return network unreachable back up
1389255332Scy	 * the stack. To mitigate this error, EAGAIN is returned instead,
1390255332Scy	 * telling the IP stack to try sending this packet again later.
1391255332Scy	 */
1392255332Scy	if (softs->ipf_state_lock) {
1393255332Scy		SBUMPD(ipf_state_stats, iss_add_locked);
1394255332Scy		fin->fin_error = EAGAIN;
1395255332Scy		return -1;
1396255332Scy	}
1397145522Sdarrenr
1398255332Scy	if (fin->fin_flx & (FI_SHORT|FI_STATE|FI_FRAGBODY|FI_BAD)) {
1399255332Scy		SBUMPD(ipf_state_stats, iss_add_bad);
1400255332Scy		return -1;
1401255332Scy	}
1402145522Sdarrenr
1403255332Scy	if ((fin->fin_flx & FI_OOW) && !(fin->fin_tcpf & TH_SYN)) {
1404255332Scy		SBUMPD(ipf_state_stats, iss_add_oow);
1405255332Scy		return -1;
1406255332Scy	}
1407255332Scy
1408255332Scy	if ((softs->ipf_state_stats.iss_active * 100 / softs->ipf_state_max) >
1409255332Scy	    softs->ipf_state_wm_high) {
1410255332Scy		softs->ipf_state_doflush = 1;
1411255332Scy	}
1412255332Scy
1413145522Sdarrenr	/*
1414145522Sdarrenr	 * If a "keep state" rule has reached the maximum number of references
1415145522Sdarrenr	 * to it, then schedule an automatic flush in case we can clear out
1416161356Sguido	 * some "dead old wood".  Note that because the lock isn't held on
1417161356Sguido	 * fr it is possible that we could overflow.  The cost of overflowing
1418161356Sguido	 * is being ignored here as the number by which it can overflow is
1419161356Sguido	 * a product of the number of simultaneous threads that could be
1420161356Sguido	 * executing in here, so a limit of 100 won't result in 200, but could
1421161356Sguido	 * result in 101 or 102.
1422145522Sdarrenr	 */
1423161356Sguido	fr = fin->fin_fr;
1424161356Sguido	if (fr != NULL) {
1425255332Scy		if ((softs->ipf_state_stats.iss_active >=
1426255332Scy		     softs->ipf_state_max) && (fr->fr_statemax == 0)) {
1427255332Scy			SBUMPD(ipf_state_stats, iss_max);
1428255332Scy			return 1;
1429161356Sguido		}
1430161356Sguido		if ((fr->fr_statemax != 0) &&
1431161356Sguido		    (fr->fr_statecnt >= fr->fr_statemax)) {
1432255332Scy			SBUMPD(ipf_state_stats, iss_max_ref);
1433255332Scy			return 2;
1434161356Sguido		}
1435145522Sdarrenr	}
1436145522Sdarrenr
1437255332Scy	is = &ips;
1438255332Scy	if (fr == NULL) {
1439255332Scy		pass = softc->ipf_flags;
1440255332Scy		is->is_tag = FR_NOLOGTAG;
1441255332Scy	} else {
1442255332Scy		pass = fr->fr_flags;
1443255332Scy	}
1444145522Sdarrenr
1445145522Sdarrenr	ic = NULL;
1446145522Sdarrenr	tcp = NULL;
144760854Sdarrenr	out = fin->fin_out;
144853642Sguido	bzero((char *)is, sizeof(*is));
1449255332Scy	is->is_die = 1 + softc->ipf_ticks;
1450255332Scy	/*
1451255332Scy	 * We want to check everything that is a property of this packet,
1452255332Scy	 * but we don't (automatically) care about it's fragment status as
1453255332Scy	 * this may change.
1454255332Scy	 */
1455255332Scy	is->is_pass = pass;
1456255332Scy	is->is_v = fin->fin_v;
1457255332Scy	is->is_sec = fin->fin_secmsk;
1458255332Scy	is->is_secmsk = 0xffff;
1459255332Scy	is->is_auth = fin->fin_auth;
1460255332Scy	is->is_authmsk = 0xffff;
1461255332Scy	is->is_family = fin->fin_family;
1462255332Scy	is->is_opt[0] = fin->fin_optmsk;
1463255332Scy	is->is_optmsk[0] = 0xffffffff;
1464255332Scy	if (is->is_v == 6) {
1465255332Scy		is->is_opt[0] &= ~0x8;
1466255332Scy		is->is_optmsk[0] &= ~0x8;
1467255332Scy	}
1468145522Sdarrenr
146953642Sguido	/*
147053642Sguido	 * Copy and calculate...
147153642Sguido	 */
147260854Sdarrenr	hv = (is->is_p = fin->fin_fi.fi_p);
147360854Sdarrenr	is->is_src = fin->fin_fi.fi_src;
147460854Sdarrenr	hv += is->is_saddr;
147560854Sdarrenr	is->is_dst = fin->fin_fi.fi_dst;
147660854Sdarrenr	hv += is->is_daddr;
147760854Sdarrenr#ifdef	USE_INET6
147860854Sdarrenr	if (fin->fin_v == 6) {
1479145522Sdarrenr		/*
1480145522Sdarrenr		 * For ICMPv6, we check to see if the destination address is
1481145522Sdarrenr		 * a multicast address.  If it is, do not include it in the
1482145522Sdarrenr		 * calculation of the hash because the correct reply will come
1483145522Sdarrenr		 * back from a real address, not a multicast address.
1484145522Sdarrenr		 */
148592685Sdarrenr		if ((is->is_p == IPPROTO_ICMPV6) &&
148692685Sdarrenr		    IN6_IS_ADDR_MULTICAST(&is->is_dst.in6)) {
148792685Sdarrenr			/*
148892685Sdarrenr			 * So you can do keep state with neighbour discovery.
1489145522Sdarrenr			 *
1490145522Sdarrenr			 * Here we could use the address from the neighbour
1491145522Sdarrenr			 * solicit message to put in the state structure and
1492145522Sdarrenr			 * we could use that without a wildcard flag too...
149392685Sdarrenr			 */
1494145522Sdarrenr			flags |= SI_W_DADDR;
149592685Sdarrenr			hv -= is->is_daddr;
149692685Sdarrenr		} else {
149792685Sdarrenr			hv += is->is_dst.i6[1];
149892685Sdarrenr			hv += is->is_dst.i6[2];
149992685Sdarrenr			hv += is->is_dst.i6[3];
150060854Sdarrenr		}
150192685Sdarrenr		hv += is->is_src.i6[1];
150292685Sdarrenr		hv += is->is_src.i6[2];
150392685Sdarrenr		hv += is->is_src.i6[3];
150460854Sdarrenr	}
150560854Sdarrenr#endif
1506172776Sdarrenr	if ((fin->fin_v == 4) &&
1507172776Sdarrenr	    (fin->fin_flx & (FI_MULTICAST|FI_BROADCAST|FI_MBCAST))) {
1508255332Scy		flags |= SI_W_DADDR;
1509255332Scy		hv -= is->is_daddr;
1510172776Sdarrenr	}
151153642Sguido
151260854Sdarrenr	switch (is->is_p)
151353642Sguido	{
151460854Sdarrenr#ifdef	USE_INET6
151560854Sdarrenr	case IPPROTO_ICMPV6 :
1516145522Sdarrenr		ic = fin->fin_dp;
151753642Sguido
151853642Sguido		switch (ic->icmp_type)
151953642Sguido		{
152060854Sdarrenr		case ICMP6_ECHO_REQUEST :
1521145522Sdarrenr			hv += (is->is_icmp.ici_id = ic->icmp_id);
1522255332Scy			/*FALLTHROUGH*/
152360854Sdarrenr		case ICMP6_MEMBERSHIP_QUERY :
152460854Sdarrenr		case ND_ROUTER_SOLICIT :
152560854Sdarrenr		case ND_NEIGHBOR_SOLICIT :
152692685Sdarrenr		case ICMP6_NI_QUERY :
1527145522Sdarrenr			is->is_icmp.ici_type = ic->icmp_type;
152860854Sdarrenr			break;
152992685Sdarrenr		default :
1530255332Scy			SBUMPD(ipf_state_stats, iss_icmp6_notquery);
1531255332Scy			return -2;
153292685Sdarrenr		}
153392685Sdarrenr		break;
153460854Sdarrenr#endif
153592685Sdarrenr	case IPPROTO_ICMP :
1536145522Sdarrenr		ic = fin->fin_dp;
153792685Sdarrenr
153892685Sdarrenr		switch (ic->icmp_type)
153992685Sdarrenr		{
154060854Sdarrenr		case ICMP_ECHO :
154153642Sguido		case ICMP_TSTAMP :
154253642Sguido		case ICMP_IREQ :
154353642Sguido		case ICMP_MASKREQ :
1544145522Sdarrenr			is->is_icmp.ici_type = ic->icmp_type;
1545145522Sdarrenr			hv += (is->is_icmp.ici_id = ic->icmp_id);
154653642Sguido			break;
154753642Sguido		default :
1548255332Scy			SBUMPD(ipf_state_stats, iss_icmp_notquery);
1549255332Scy			return -3;
155053642Sguido		}
155153642Sguido		break;
1552145522Sdarrenr
1553255332Scy#if 0
1554145522Sdarrenr	case IPPROTO_GRE :
1555145522Sdarrenr		gre = fin->fin_dp;
1556145522Sdarrenr
1557145522Sdarrenr		is->is_gre.gs_flags = gre->gr_flags;
1558145522Sdarrenr		is->is_gre.gs_ptype = gre->gr_ptype;
1559145522Sdarrenr		if (GRE_REV(is->is_gre.gs_flags) == 1) {
1560145522Sdarrenr			is->is_call[0] = fin->fin_data[0];
1561145522Sdarrenr			is->is_call[1] = fin->fin_data[1];
1562145522Sdarrenr		}
1563145522Sdarrenr		break;
1564255332Scy#endif
1565145522Sdarrenr
156653642Sguido	case IPPROTO_TCP :
1567145522Sdarrenr		tcp = fin->fin_dp;
156853642Sguido
1569255332Scy		if (tcp->th_flags & TH_RST) {
1570255332Scy			SBUMPD(ipf_state_stats, iss_tcp_rstadd);
1571255332Scy			return -4;
1572255332Scy		}
1573255332Scy
1574255332Scy		/* TRACE is, flags, hv */
1575255332Scy
157653642Sguido		/*
157753642Sguido		 * The endian of the ports doesn't matter, but the ack and
157853642Sguido		 * sequence numbers do as we do mathematics on them later.
157953642Sguido		 */
158092685Sdarrenr		is->is_sport = htons(fin->fin_data[0]);
158192685Sdarrenr		is->is_dport = htons(fin->fin_data[1]);
1582145522Sdarrenr		if ((flags & (SI_W_DPORT|SI_W_SPORT)) == 0) {
158392685Sdarrenr			hv += is->is_sport;
158492685Sdarrenr			hv += is->is_dport;
158553642Sguido		}
1586145522Sdarrenr
1587255332Scy		/* TRACE is, flags, hv */
1588255332Scy
1589145522Sdarrenr		/*
1590145522Sdarrenr		 * If this is a real packet then initialise fields in the
1591145522Sdarrenr		 * state information structure from the TCP header information.
1592145522Sdarrenr		 */
1593145522Sdarrenr
1594145522Sdarrenr		is->is_maxdwin = 1;
1595145522Sdarrenr		is->is_maxswin = ntohs(tcp->th_win);
1596145522Sdarrenr		if (is->is_maxswin == 0)
1597145522Sdarrenr			is->is_maxswin = 1;
1598145522Sdarrenr
1599145522Sdarrenr		if ((fin->fin_flx & FI_IGNORE) == 0) {
160095563Sdarrenr			is->is_send = ntohl(tcp->th_seq) + fin->fin_dlen -
1601145522Sdarrenr				      (TCP_OFF(tcp) << 2) +
160295563Sdarrenr				      ((tcp->th_flags & TH_SYN) ? 1 : 0) +
160395563Sdarrenr				      ((tcp->th_flags & TH_FIN) ? 1 : 0);
160495563Sdarrenr			is->is_maxsend = is->is_send;
160595563Sdarrenr
1606145522Sdarrenr			/*
1607145522Sdarrenr			 * Window scale option is only present in
1608145522Sdarrenr			 * SYN/SYN-ACK packet.
1609145522Sdarrenr			 */
1610145522Sdarrenr			if ((tcp->th_flags & ~(TH_FIN|TH_ACK|TH_ECNALL)) ==
1611145522Sdarrenr			    TH_SYN &&
1612145522Sdarrenr			    (TCP_OFF(tcp) > (sizeof(tcphdr_t) >> 2))) {
1613255332Scy				if (ipf_tcpoptions(softs, fin, tcp,
1614255332Scy					      &is->is_tcp.ts_data[0]) == -1)
1615153876Sguido					fin->fin_flx |= FI_BAD;
161698004Sdarrenr			}
161795563Sdarrenr
1618145522Sdarrenr			if ((fin->fin_out != 0) && (pass & FR_NEWISN) != 0) {
1619255332Scy				ipf_checknewisn(fin, is);
1620255332Scy				ipf_fixoutisn(fin, is);
1621145522Sdarrenr			}
162295418Sdarrenr
1623145522Sdarrenr			if ((tcp->th_flags & TH_OPENING) == TH_SYN)
1624145522Sdarrenr				flags |= IS_TCPFSM;
1625145522Sdarrenr			else {
1626145522Sdarrenr				is->is_maxdwin = is->is_maxswin * 2;
1627145522Sdarrenr				is->is_dend = ntohl(tcp->th_ack);
1628145522Sdarrenr				is->is_maxdend = ntohl(tcp->th_ack);
1629145522Sdarrenr				is->is_maxdwin *= 2;
1630145522Sdarrenr			}
1631145522Sdarrenr		}
163295418Sdarrenr
163353642Sguido		/*
1634255332Scy		 * If we're creating state for a starting connection, start
1635255332Scy		 * the timer on it as we'll never see an error if it fails
1636255332Scy		 * to connect.
163753642Sguido		 */
163853642Sguido		break;
163992685Sdarrenr
164053642Sguido	case IPPROTO_UDP :
1641145522Sdarrenr		tcp = fin->fin_dp;
164253642Sguido
164392685Sdarrenr		is->is_sport = htons(fin->fin_data[0]);
164492685Sdarrenr		is->is_dport = htons(fin->fin_data[1]);
1645145522Sdarrenr		if ((flags & (SI_W_DPORT|SI_W_SPORT)) == 0) {
1646145522Sdarrenr			hv += tcp->th_dport;
1647145522Sdarrenr			hv += tcp->th_sport;
164853642Sguido		}
164953642Sguido		break;
1650145522Sdarrenr
165153642Sguido	default :
165292685Sdarrenr		break;
165353642Sguido	}
1654145522Sdarrenr	hv = DOUBLE_HASH(hv);
1655145522Sdarrenr	is->is_hv = hv;
165653642Sguido
1657145522Sdarrenr	/*
1658145522Sdarrenr	 * Look for identical state.
1659145522Sdarrenr	 */
1660255332Scy	for (is = softs->ipf_state_table[hv % softs->ipf_state_size];
1661255332Scy	     is != NULL; is = is->is_hnext) {
1662255332Scy		if (ipf_state_match(&ips, is) == 1)
1663145522Sdarrenr			break;
1664145522Sdarrenr	}
1665255332Scy	if (is != NULL) {
1666255332Scy		SBUMPD(ipf_state_stats, iss_add_dup);
1667255332Scy		return 3;
1668255332Scy	}
1669145522Sdarrenr
1670255332Scy	if (softs->ipf_state_stats.iss_bucketlen[hv] >=
1671255332Scy	    softs->ipf_state_maxbucket) {
1672255332Scy		SBUMPD(ipf_state_stats, iss_bucket_full);
1673255332Scy		return 4;
1674145522Sdarrenr	}
1675287984Scy
1676287984Scy	/*
1677287984Scy	 * No existing state; create new
1678287984Scy	 */
167953642Sguido	KMALLOC(is, ipstate_t *);
168053642Sguido	if (is == NULL) {
1681255332Scy		SBUMPD(ipf_state_stats, iss_nomem);
1682255332Scy		return 5;
168353642Sguido	}
168453642Sguido	bcopy((char *)&ips, (char *)is, sizeof(*is));
1685255332Scy	is->is_flags = flags & IS_INHERITED;
1686255332Scy	is->is_rulen = fin->fin_rule;
1687255332Scy	is->is_rule = fr;
1688255332Scy
1689145522Sdarrenr	/*
1690287984Scy	 * Do not do the modulus here, it is done in ipf_state_insert().
1691145522Sdarrenr	 */
1692145522Sdarrenr	if (fr != NULL) {
1693255332Scy		ipftq_t *tq;
1694255332Scy
1695255332Scy		(void) strncpy(is->is_group, FR_NAME(fr, fr_group),
1696255332Scy			       FR_GROUPLEN);
1697145522Sdarrenr		if (fr->fr_age[0] != 0) {
1698255332Scy			tq = ipf_addtimeoutqueue(softc,
1699255332Scy						 &softs->ipf_state_usertq,
1700255332Scy						 fr->fr_age[0]);
1701255332Scy			is->is_tqehead[0] = tq;
1702145522Sdarrenr			is->is_sti.tqe_flags |= TQE_RULEBASED;
1703145522Sdarrenr		}
1704145522Sdarrenr		if (fr->fr_age[1] != 0) {
1705255332Scy			tq = ipf_addtimeoutqueue(softc,
1706255332Scy						 &softs->ipf_state_usertq,
1707255332Scy						 fr->fr_age[1]);
1708255332Scy			is->is_tqehead[1] = tq;
1709145522Sdarrenr			is->is_sti.tqe_flags |= TQE_RULEBASED;
1710145522Sdarrenr		}
171192685Sdarrenr
1712145522Sdarrenr		is->is_tag = fr->fr_logtag;
1713145522Sdarrenr	}
171492685Sdarrenr
1715145522Sdarrenr	/*
1716255332Scy	 * It may seem strange to set is_ref to 2, but if stsave is not NULL
1717255332Scy	 * then a copy of the pointer is being stored somewhere else and in
1718287984Scy	 * the end, it will expect to be able to do something with it.
1719145522Sdarrenr	 */
1720255332Scy	is->is_me = stsave;
1721255332Scy	if (stsave != NULL) {
1722255332Scy		*stsave = is;
1723255332Scy		is->is_ref = 2;
1724255332Scy	} else {
1725255332Scy		is->is_ref = 1;
1726255332Scy	}
1727145522Sdarrenr	is->is_pkts[0] = 0, is->is_bytes[0] = 0;
1728145522Sdarrenr	is->is_pkts[1] = 0, is->is_bytes[1] = 0;
1729145522Sdarrenr	is->is_pkts[2] = 0, is->is_bytes[2] = 0;
1730145522Sdarrenr	is->is_pkts[3] = 0, is->is_bytes[3] = 0;
1731145522Sdarrenr	if ((fin->fin_flx & FI_IGNORE) == 0) {
1732145522Sdarrenr		is->is_pkts[out] = 1;
1733255332Scy		fin->fin_pktnum = 1;
1734145522Sdarrenr		is->is_bytes[out] = fin->fin_plen;
1735145522Sdarrenr		is->is_flx[out][0] = fin->fin_flx & FI_CMP;
1736145522Sdarrenr		is->is_flx[out][0] &= ~FI_OOW;
173792685Sdarrenr	}
1738145522Sdarrenr
1739255332Scy	if (pass & FR_STLOOSE)
1740255332Scy		is->is_flags |= IS_LOOSE;
1741255332Scy
1742145522Sdarrenr	if (pass & FR_STSTRICT)
1743145522Sdarrenr		is->is_flags |= IS_STRICT;
1744145522Sdarrenr
1745145522Sdarrenr	if (pass & FR_STATESYNC)
1746145522Sdarrenr		is->is_flags |= IS_STATESYNC;
1747145522Sdarrenr
1748255332Scy	if (pass & FR_LOGFIRST)
1749255332Scy		is->is_pass &= ~(FR_LOGFIRST|FR_LOG);
1750255332Scy
1751255332Scy	READ_ENTER(&softc->ipf_state);
1752255332Scy
1753255332Scy	if (ipf_state_insert(softc, is, fin->fin_rev) == -1) {
1754255332Scy		RWLOCK_EXIT(&softc->ipf_state);
1755255332Scy		/*
1756255332Scy		 * This is a bit more manual than it should be but
1757255332Scy		 * ipf_state_del cannot be called.
1758255332Scy		 */
1759255332Scy		MUTEX_EXIT(&is->is_lock);
1760255332Scy		MUTEX_DESTROY(&is->is_lock);
1761255332Scy		if (is->is_tqehead[0] != NULL) {
1762255332Scy			if (ipf_deletetimeoutqueue(is->is_tqehead[0]) == 0)
1763255332Scy				ipf_freetimeoutqueue(softc, is->is_tqehead[0]);
1764255332Scy			is->is_tqehead[0] = NULL;
1765255332Scy		}
1766255332Scy		if (is->is_tqehead[1] != NULL) {
1767255332Scy			if (ipf_deletetimeoutqueue(is->is_tqehead[1]) == 0)
1768255332Scy				ipf_freetimeoutqueue(softc, is->is_tqehead[1]);
1769255332Scy			is->is_tqehead[1] = NULL;
1770255332Scy		}
1771255332Scy		KFREE(is);
1772255332Scy		return -1;
1773255332Scy	}
1774255332Scy
177553642Sguido	/*
1776255332Scy	 * Filling in the interface name is after the insert so that an
1777255332Scy	 * event (such as add/delete) of an interface that is referenced
1778255332Scy	 * by this rule will see this state entry.
177953642Sguido	 */
1780255332Scy	if (fr != NULL) {
1781255332Scy		/*
1782255332Scy		 * The name '-' is special for network interfaces and causes
1783255332Scy		 * a NULL name to be present, always, allowing packets to
1784255332Scy		 * match it, regardless of their interface.
1785255332Scy		 */
1786255332Scy		if ((fin->fin_ifp == NULL) ||
1787255332Scy		    (fr->fr_ifnames[out << 1] != -1 &&
1788255332Scy		     fr->fr_names[fr->fr_ifnames[out << 1] + 0] == '-' &&
1789255332Scy		     fr->fr_names[fr->fr_ifnames[out << 1] + 1] == '\0')) {
1790255332Scy			is->is_ifp[out << 1] = fr->fr_ifas[0];
1791255332Scy			strncpy(is->is_ifname[out << 1],
1792255332Scy				fr->fr_names + fr->fr_ifnames[0],
1793255332Scy				sizeof(fr->fr_ifnames[0]));
1794255332Scy		} else {
1795255332Scy			is->is_ifp[out << 1] = fin->fin_ifp;
1796255332Scy			COPYIFNAME(fin->fin_v, fin->fin_ifp,
1797255332Scy				   is->is_ifname[out << 1]);
1798255332Scy		}
179992685Sdarrenr
1800255332Scy		is->is_ifp[(out << 1) + 1] = fr->fr_ifas[1];
1801255332Scy		if (fr->fr_ifnames[1] != -1) {
1802255332Scy			strncpy(is->is_ifname[(out << 1) + 1],
1803255332Scy				fr->fr_names + fr->fr_ifnames[1],
1804255332Scy				sizeof(fr->fr_ifnames[1]));
1805255332Scy		}
1806145522Sdarrenr
1807255332Scy		is->is_ifp[(1 - out) << 1] = fr->fr_ifas[2];
1808255332Scy		if (fr->fr_ifnames[2] != -1) {
1809255332Scy			strncpy(is->is_ifname[((1 - out) << 1)],
1810255332Scy				fr->fr_names + fr->fr_ifnames[2],
1811255332Scy				sizeof(fr->fr_ifnames[2]));
1812255332Scy		}
1813145522Sdarrenr
1814255332Scy		is->is_ifp[((1 - out) << 1) + 1] = fr->fr_ifas[3];
1815255332Scy		if (fr->fr_ifnames[3] != -1) {
1816255332Scy			strncpy(is->is_ifname[((1 - out) << 1) + 1],
1817255332Scy				fr->fr_names + fr->fr_ifnames[3],
1818255332Scy				sizeof(fr->fr_ifnames[3]));
1819255332Scy		}
1820255332Scy	} else {
1821255332Scy		if (fin->fin_ifp != NULL) {
1822255332Scy			is->is_ifp[out << 1] = fin->fin_ifp;
1823255332Scy			COPYIFNAME(fin->fin_v, fin->fin_ifp,
1824255332Scy				   is->is_ifname[out << 1]);
1825255332Scy		}
1826255332Scy	}
1827145522Sdarrenr
1828145522Sdarrenr	if (fin->fin_p == IPPROTO_TCP) {
1829145522Sdarrenr		/*
1830145522Sdarrenr		* If we're creating state for a starting connection, start the
1831145522Sdarrenr		* timer on it as we'll never see an error if it fails to
1832145522Sdarrenr		* connect.
1833145522Sdarrenr		*/
1834255332Scy		(void) ipf_tcp_age(&is->is_sti, fin, softs->ipf_state_tcptq,
1835255332Scy				   is->is_flags, 2);
183660854Sdarrenr	}
1837255332Scy	MUTEX_EXIT(&is->is_lock);
1838145522Sdarrenr	if ((is->is_flags & IS_STATESYNC) && ((is->is_flags & SI_CLONE) == 0))
1839255332Scy		is->is_sync = ipf_sync_new(softc, SMC_STATE, fin, is);
1840255332Scy	if (softs->ipf_state_logging)
1841255332Scy		ipf_state_log(softc, is, ISL_NEW);
1842145522Sdarrenr
1843255332Scy	RWLOCK_EXIT(&softc->ipf_state);
1844255332Scy
1845145522Sdarrenr	fin->fin_flx |= FI_STATE;
1846145522Sdarrenr	if (fin->fin_flx & FI_FRAG)
1847255332Scy		(void) ipf_frag_new(softc, fin, pass);
1848145522Sdarrenr
1849255332Scy	fdp = &fr->fr_tifs[0];
1850255332Scy	if (fdp->fd_type == FRD_DSTLIST) {
1851255332Scy		ipf_dstlist_select_node(fin, fdp->fd_ptr, NULL,
1852255332Scy					&is->is_tifs[0]);
1853255332Scy	} else {
1854255332Scy		bcopy(fdp, &is->is_tifs[0], sizeof(*fdp));
1855255332Scy	}
1856255332Scy
1857255332Scy	fdp = &fr->fr_tifs[1];
1858255332Scy	if (fdp->fd_type == FRD_DSTLIST) {
1859255332Scy		ipf_dstlist_select_node(fin, fdp->fd_ptr, NULL,
1860255332Scy					&is->is_tifs[1]);
1861255332Scy	} else {
1862255332Scy		bcopy(fdp, &is->is_tifs[1], sizeof(*fdp));
1863255332Scy	}
1864255332Scy	fin->fin_tif = &is->is_tifs[fin->fin_rev];
1865255332Scy
1866255332Scy	fdp = &fr->fr_dif;
1867255332Scy	if (fdp->fd_type == FRD_DSTLIST) {
1868255332Scy		ipf_dstlist_select_node(fin, fdp->fd_ptr, NULL,
1869255332Scy					&is->is_dif);
1870255332Scy	} else {
1871255332Scy		bcopy(fdp, &is->is_dif, sizeof(*fdp));
1872255332Scy	}
1873255332Scy	fin->fin_dif = &is->is_dif;
1874255332Scy
1875255332Scy	return 0;
187653642Sguido}
187753642Sguido
187853642Sguido
1879145522Sdarrenr/* ------------------------------------------------------------------------ */
1880255332Scy/* Function:    ipf_tcpoptions                                              */
1881153876Sguido/* Returns:     int - 1 == packet matches state entry, 0 == it does not,    */
1882153876Sguido/*                   -1 == packet has bad TCP options data                  */
1883255332Scy/* Parameters:  softs(I) - pointer to state context structure               */
1884255332Scy/*              fin(I) - pointer to packet information                      */
1885145522Sdarrenr/*              tcp(I) - pointer to TCP packet header                       */
1886145522Sdarrenr/*              td(I)  - pointer to TCP data held as part of the state      */
1887145522Sdarrenr/*                                                                          */
1888145522Sdarrenr/* Look after the TCP header for any options and deal with those that are   */
1889145522Sdarrenr/* present.  Record details about those that we recogise.                   */
1890145522Sdarrenr/* ------------------------------------------------------------------------ */
1891255332Scystatic int
1892255332Scyipf_tcpoptions(softs, fin, tcp, td)
1893255332Scy	ipf_state_softc_t *softs;
1894255332Scy	fr_info_t *fin;
1895255332Scy	tcphdr_t *tcp;
1896255332Scy	tcpdata_t *td;
189795418Sdarrenr{
1898145522Sdarrenr	int off, mlen, ol, i, len, retval;
1899145522Sdarrenr	char buf[64], *s, opt;
1900145522Sdarrenr	mb_t *m = NULL;
190153642Sguido
1902153876Sguido	len = (TCP_OFF(tcp) << 2);
1903255332Scy	if (fin->fin_dlen < len) {
1904255332Scy		SBUMPD(ipf_state_stats, iss_tcp_toosmall);
1905145522Sdarrenr		return 0;
1906255332Scy	}
1907153876Sguido	len -= sizeof(*tcp);
190895418Sdarrenr
1909153876Sguido	off = fin->fin_plen - fin->fin_dlen + sizeof(*tcp) + fin->fin_ipoff;
1910153876Sguido
1911145522Sdarrenr	m = fin->fin_m;
1912145522Sdarrenr	mlen = MSGDSIZE(m) - off;
1913145522Sdarrenr	if (len > mlen) {
1914145522Sdarrenr		len = mlen;
1915145522Sdarrenr		retval = 0;
1916145522Sdarrenr	} else {
1917145522Sdarrenr		retval = 1;
1918145522Sdarrenr	}
191995418Sdarrenr
1920145522Sdarrenr	COPYDATA(m, off, len, buf);
1921145522Sdarrenr
1922145522Sdarrenr	for (s = buf; len > 0; ) {
1923145522Sdarrenr		opt = *s;
1924145522Sdarrenr		if (opt == TCPOPT_EOL)
192595418Sdarrenr			break;
1926145522Sdarrenr		else if (opt == TCPOPT_NOP)
1927145522Sdarrenr			ol = 1;
1928145522Sdarrenr		else {
1929145522Sdarrenr			if (len < 2)
193095418Sdarrenr				break;
1931145522Sdarrenr			ol = (int)*(s + 1);
1932145522Sdarrenr			if (ol < 2 || ol > len)
1933145522Sdarrenr				break;
1934145522Sdarrenr
1935145522Sdarrenr			/*
1936145522Sdarrenr			 * Extract the TCP options we are interested in out of
1937145522Sdarrenr			 * the header and store them in the the tcpdata struct.
1938145522Sdarrenr			 */
1939145522Sdarrenr			switch (opt)
1940145522Sdarrenr			{
1941145522Sdarrenr			case TCPOPT_WINDOW :
1942145522Sdarrenr				if (ol == TCPOLEN_WINDOW) {
1943145522Sdarrenr					i = (int)*(s + 2);
1944145522Sdarrenr					if (i > TCP_WSCALE_MAX)
1945145522Sdarrenr						i = TCP_WSCALE_MAX;
1946145522Sdarrenr					else if (i < 0)
1947145522Sdarrenr						i = 0;
1948145522Sdarrenr					td->td_winscale = i;
1949153876Sguido					td->td_winflags |= TCP_WSCALE_SEEN|
1950153876Sguido							   TCP_WSCALE_FIRST;
1951153876Sguido				} else
1952153876Sguido					retval = -1;
1953145522Sdarrenr				break;
1954145522Sdarrenr			case TCPOPT_MAXSEG :
1955145522Sdarrenr				/*
1956145522Sdarrenr				 * So, if we wanted to set the TCP MAXSEG,
1957145522Sdarrenr				 * it should be done here...
1958145522Sdarrenr				 */
1959145522Sdarrenr				if (ol == TCPOLEN_MAXSEG) {
1960145522Sdarrenr					i = (int)*(s + 2);
1961145522Sdarrenr					i <<= 8;
1962145522Sdarrenr					i += (int)*(s + 3);
1963145522Sdarrenr					td->td_maxseg = i;
1964153876Sguido				} else
1965153876Sguido					retval = -1;
1966145522Sdarrenr				break;
1967153876Sguido			case TCPOPT_SACK_PERMITTED :
1968153876Sguido				if (ol == TCPOLEN_SACK_PERMITTED)
1969153876Sguido					td->td_winflags |= TCP_SACK_PERMIT;
1970153876Sguido				else
1971153876Sguido					retval = -1;
1972153876Sguido				break;
1973145522Sdarrenr			}
197495418Sdarrenr		}
1975145522Sdarrenr		len -= ol;
1976145522Sdarrenr		s += ol;
197795418Sdarrenr	}
1978255332Scy	if (retval == -1) {
1979255332Scy		SBUMPD(ipf_state_stats, iss_tcp_badopt);
1980255332Scy	}
1981145522Sdarrenr	return retval;
198295418Sdarrenr}
198395418Sdarrenr
198495418Sdarrenr
1985145522Sdarrenr/* ------------------------------------------------------------------------ */
1986255332Scy/* Function:    ipf_state_tcp                                               */
1987145522Sdarrenr/* Returns:     int - 1 == packet matches state entry, 0 == it does not     */
1988255332Scy/* Parameters:  softc(I)  - pointer to soft context main structure          */
1989255332Scy/*              softs(I) - pointer to state context structure               */
1990255332Scy/*              fin(I)   - pointer to packet information                    */
1991145522Sdarrenr/*              tcp(I)   - pointer to TCP packet header                     */
1992145522Sdarrenr/*              is(I)  - pointer to master state structure                  */
1993145522Sdarrenr/*                                                                          */
1994145522Sdarrenr/* Check to see if a packet with TCP headers fits within the TCP window.    */
1995145522Sdarrenr/* Change timeout depending on whether new packet is a SYN-ACK returning    */
1996145522Sdarrenr/* for a SYN or a RST or FIN which indicate time to close up shop.          */
1997145522Sdarrenr/* ------------------------------------------------------------------------ */
1998255332Scystatic int
1999255332Scyipf_state_tcp(softc, softs, fin, tcp, is)
2000255332Scy	ipf_main_softc_t *softc;
2001255332Scy	ipf_state_softc_t *softs;
2002255332Scy	fr_info_t *fin;
2003255332Scy	tcphdr_t *tcp;
2004255332Scy	ipstate_t *is;
200553642Sguido{
200653642Sguido	tcpdata_t  *fdata, *tdata;
2007255332Scy	int source, ret, flags;
200853642Sguido
2009145522Sdarrenr	source = !fin->fin_rev;
2010255332Scy	if (((is->is_flags & IS_TCPFSM) != 0) && (source == 1) &&
2011145522Sdarrenr	    (ntohs(is->is_sport) != fin->fin_data[0]))
2012145522Sdarrenr		source = 0;
2013145522Sdarrenr	fdata = &is->is_tcp.ts_data[!source];
2014145522Sdarrenr	tdata = &is->is_tcp.ts_data[source];
2015145522Sdarrenr
2016145522Sdarrenr	MUTEX_ENTER(&is->is_lock);
2017170268Sdarrenr
2018170268Sdarrenr	/*
2019170268Sdarrenr	 * If a SYN packet is received for a connection that is on the way out
2020170268Sdarrenr	 * but hasn't yet departed then advance this session along the way.
2021170268Sdarrenr	 */
2022170268Sdarrenr	if ((tcp->th_flags & TH_OPENING) == TH_SYN) {
2023170268Sdarrenr		if ((is->is_state[0] > IPF_TCPS_ESTABLISHED) &&
2024170268Sdarrenr		    (is->is_state[1] > IPF_TCPS_ESTABLISHED)) {
2025170268Sdarrenr			is->is_state[!source] = IPF_TCPS_CLOSED;
2026255332Scy			ipf_movequeue(softc->ipf_ticks, &is->is_sti,
2027255332Scy				      is->is_sti.tqe_ifq,
2028255332Scy				      &softs->ipf_state_deletetq);
2029172776Sdarrenr			MUTEX_EXIT(&is->is_lock);
2030255332Scy			DT1(iss_tcp_closing, ipstate_t *, is);
2031255332Scy			SBUMP(ipf_state_stats.iss_tcp_closing);
2032170268Sdarrenr			return 0;
2033170268Sdarrenr		}
2034170268Sdarrenr	}
2035170268Sdarrenr
2036255332Scy	if (is->is_flags & IS_LOOSE)
2037255332Scy		ret = 1;
2038255332Scy	else
2039255332Scy		ret = ipf_state_tcpinwindow(fin, fdata, tdata, tcp,
2040255332Scy					    is->is_flags);
2041172776Sdarrenr	if (ret > 0) {
2042145522Sdarrenr		/*
2043145522Sdarrenr		 * Nearing end of connection, start timeout.
2044145522Sdarrenr		 */
2045255332Scy		ret = ipf_tcp_age(&is->is_sti, fin, softs->ipf_state_tcptq,
2046255332Scy				  is->is_flags, ret);
2047145522Sdarrenr		if (ret == 0) {
2048145522Sdarrenr			MUTEX_EXIT(&is->is_lock);
2049255332Scy			DT2(iss_tcp_fsm, fr_info_t *, fin, ipstate_t *, is);
2050255332Scy			SBUMP(ipf_state_stats.iss_tcp_fsm);
2051145522Sdarrenr			return 0;
2052145522Sdarrenr		}
2053145522Sdarrenr
2054255332Scy		if (softs->ipf_state_logging > 4)
2055255332Scy			ipf_state_log(softc, is, ISL_STATECHANGE);
2056255332Scy
2057145522Sdarrenr		/*
2058145522Sdarrenr		 * set s0's as appropriate.  Use syn-ack packet as it
2059145522Sdarrenr		 * contains both pieces of required information.
2060145522Sdarrenr		 */
2061145522Sdarrenr		/*
2062145522Sdarrenr		 * Window scale option is only present in SYN/SYN-ACK packet.
2063145522Sdarrenr		 * Compare with ~TH_FIN to mask out T/TCP setups.
2064145522Sdarrenr		 */
2065145522Sdarrenr		flags = tcp->th_flags & ~(TH_FIN|TH_ECNALL);
2066145522Sdarrenr		if (flags == (TH_SYN|TH_ACK)) {
2067145522Sdarrenr			is->is_s0[source] = ntohl(tcp->th_ack);
2068145522Sdarrenr			is->is_s0[!source] = ntohl(tcp->th_seq) + 1;
2069165515Sdarrenr			if ((TCP_OFF(tcp) > (sizeof(tcphdr_t) >> 2))) {
2070255332Scy				if (ipf_tcpoptions(softs, fin, tcp,
2071255332Scy						   fdata) == -1)
2072153876Sguido					fin->fin_flx |= FI_BAD;
2073145522Sdarrenr			}
2074145522Sdarrenr			if ((fin->fin_out != 0) && (is->is_pass & FR_NEWISN))
2075255332Scy				ipf_checknewisn(fin, is);
2076145522Sdarrenr		} else if (flags == TH_SYN) {
2077145522Sdarrenr			is->is_s0[source] = ntohl(tcp->th_seq) + 1;
2078153876Sguido			if ((TCP_OFF(tcp) > (sizeof(tcphdr_t) >> 2))) {
2079255332Scy				if (ipf_tcpoptions(softs, fin, tcp,
2080255332Scy						   fdata) == -1)
2081153876Sguido					fin->fin_flx |= FI_BAD;
2082153876Sguido			}
2083145522Sdarrenr
2084145522Sdarrenr			if ((fin->fin_out != 0) && (is->is_pass & FR_NEWISN))
2085255332Scy				ipf_checknewisn(fin, is);
2086145522Sdarrenr
2087145522Sdarrenr		}
2088145522Sdarrenr		ret = 1;
2089170268Sdarrenr	} else {
2090255332Scy		DT2(iss_tcp_oow, fr_info_t *, fin, ipstate_t *, is);
2091255332Scy		SBUMP(ipf_state_stats.iss_tcp_oow);
2092255332Scy		ret = 0;
2093170268Sdarrenr	}
2094145522Sdarrenr	MUTEX_EXIT(&is->is_lock);
2095145522Sdarrenr	return ret;
2096145522Sdarrenr}
2097145522Sdarrenr
2098145522Sdarrenr
2099145522Sdarrenr/* ------------------------------------------------------------------------ */
2100255332Scy/* Function:    ipf_checknewisn                                             */
2101145522Sdarrenr/* Returns:     Nil                                                         */
2102145522Sdarrenr/* Parameters:  fin(I)   - pointer to packet information                    */
2103145522Sdarrenr/*              is(I)  - pointer to master state structure                  */
2104145522Sdarrenr/*                                                                          */
2105145522Sdarrenr/* Check to see if this TCP connection is expecting and needs a new         */
2106145522Sdarrenr/* sequence number for a particular direction of the connection.            */
2107145522Sdarrenr/*                                                                          */
2108145522Sdarrenr/* NOTE: This does not actually change the sequence numbers, only gets new  */
2109145522Sdarrenr/* one ready.                                                               */
2110145522Sdarrenr/* ------------------------------------------------------------------------ */
2111255332Scystatic void
2112255332Scyipf_checknewisn(fin, is)
2113255332Scy	fr_info_t *fin;
2114255332Scy	ipstate_t *is;
2115145522Sdarrenr{
2116145522Sdarrenr	u_32_t sumd, old, new;
2117145522Sdarrenr	tcphdr_t *tcp;
2118145522Sdarrenr	int i;
2119145522Sdarrenr
2120145522Sdarrenr	i = fin->fin_rev;
2121145522Sdarrenr	tcp = fin->fin_dp;
2122145522Sdarrenr
2123145522Sdarrenr	if (((i == 0) && !(is->is_flags & IS_ISNSYN)) ||
2124145522Sdarrenr	    ((i == 1) && !(is->is_flags & IS_ISNACK))) {
2125145522Sdarrenr		old = ntohl(tcp->th_seq);
2126255332Scy		new = ipf_newisn(fin);
2127145522Sdarrenr		is->is_isninc[i] = new - old;
2128145522Sdarrenr		CALC_SUMD(old, new, sumd);
2129145522Sdarrenr		is->is_sumd[i] = (sumd & 0xffff) + (sumd >> 16);
2130145522Sdarrenr
2131145522Sdarrenr		is->is_flags |= ((i == 0) ? IS_ISNSYN : IS_ISNACK);
2132145522Sdarrenr	}
2133145522Sdarrenr}
2134145522Sdarrenr
2135145522Sdarrenr
2136145522Sdarrenr/* ------------------------------------------------------------------------ */
2137255332Scy/* Function:    ipf_state_tcpinwindow                                       */
2138255332Scy/* Returns:     int - 1 == packet inside TCP "window", 0 == not inside.     */
2139145522Sdarrenr/* Parameters:  fin(I)   - pointer to packet information                    */
2140145522Sdarrenr/*              fdata(I) - pointer to tcp state informatio (forward)        */
2141145522Sdarrenr/*              tdata(I) - pointer to tcp state informatio (reverse)        */
2142145522Sdarrenr/*              tcp(I)   - pointer to TCP packet header                     */
2143145522Sdarrenr/*                                                                          */
2144145522Sdarrenr/* Given a packet has matched addresses and ports, check to see if it is    */
2145145522Sdarrenr/* within the TCP data window.  In a show of generosity, allow packets that */
2146145522Sdarrenr/* are within the window space behind the current sequence # as well.       */
2147145522Sdarrenr/* ------------------------------------------------------------------------ */
2148255332Scystatic int
2149255332Scyipf_state_tcpinwindow(fin, fdata, tdata, tcp, flags)
2150255332Scy	fr_info_t *fin;
2151255332Scy	tcpdata_t  *fdata, *tdata;
2152255332Scy	tcphdr_t *tcp;
2153255332Scy	int flags;
2154145522Sdarrenr{
2155255332Scy	ipf_main_softc_t *softc = fin->fin_main_soft;
2156255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
2157145522Sdarrenr	tcp_seq seq, ack, end;
2158145522Sdarrenr	int ackskew, tcpflags;
2159145522Sdarrenr	u_32_t win, maxwin;
2160153876Sguido	int dsize, inseq;
2161145522Sdarrenr
216253642Sguido	/*
216353642Sguido	 * Find difference between last checked packet and this packet.
216453642Sguido	 */
2165145522Sdarrenr	tcpflags = tcp->th_flags;
216653642Sguido	seq = ntohl(tcp->th_seq);
216753642Sguido	ack = ntohl(tcp->th_ack);
2168145522Sdarrenr	if (tcpflags & TH_SYN)
2169145522Sdarrenr		win = ntohs(tcp->th_win);
217095418Sdarrenr	else
2171145522Sdarrenr		win = ntohs(tcp->th_win) << fdata->td_winscale;
2172153876Sguido
2173153876Sguido	/*
2174153876Sguido	 * A window of 0 produces undesirable behaviour from this function.
2175153876Sguido	 */
2176145522Sdarrenr	if (win == 0)
2177145522Sdarrenr		win = 1;
217895418Sdarrenr
2179153876Sguido	dsize = fin->fin_dlen - (TCP_OFF(tcp) << 2) +
2180153876Sguido	        ((tcpflags & TH_SYN) ? 1 : 0) + ((tcpflags & TH_FIN) ? 1 : 0);
2181153876Sguido
2182145522Sdarrenr	/*
2183145522Sdarrenr	 * if window scaling is present, the scaling is only allowed
2184145522Sdarrenr	 * for windows not in the first SYN packet. In that packet the
2185145522Sdarrenr	 * window is 65535 to specify the largest window possible
2186145522Sdarrenr	 * for receivers not implementing the window scale option.
2187145522Sdarrenr	 * Currently, we do not assume TTCP here. That means that
2188145522Sdarrenr	 * if we see a second packet from a host (after the initial
2189145522Sdarrenr	 * SYN), we can assume that the receiver of the SYN did
2190145522Sdarrenr	 * already send back the SYN/ACK (and thus that we know if
2191145522Sdarrenr	 * the receiver also does window scaling)
2192145522Sdarrenr	 */
2193145522Sdarrenr	if (!(tcpflags & TH_SYN) && (fdata->td_winflags & TCP_WSCALE_FIRST)) {
2194165515Sdarrenr		fdata->td_winflags &= ~TCP_WSCALE_FIRST;
2195165515Sdarrenr		fdata->td_maxwin = win;
2196145522Sdarrenr	}
219795418Sdarrenr
2198153876Sguido	end = seq + dsize;
219995418Sdarrenr
220095418Sdarrenr	if ((fdata->td_end == 0) &&
2201145522Sdarrenr	    (!(flags & IS_TCPFSM) ||
2202145522Sdarrenr	     ((tcpflags & TH_OPENING) == TH_OPENING))) {
220353642Sguido		/*
220453642Sguido		 * Must be a (outgoing) SYN-ACK in reply to a SYN.
220553642Sguido		 */
2206153876Sguido		fdata->td_end = end - 1;
220753642Sguido		fdata->td_maxwin = 1;
220898004Sdarrenr		fdata->td_maxend = end + win;
220953642Sguido	}
221053642Sguido
2211145522Sdarrenr	if (!(tcpflags & TH_ACK)) {  /* Pretend an ack was sent */
221253642Sguido		ack = tdata->td_end;
2213145522Sdarrenr	} else if (((tcpflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) &&
221453642Sguido		   (ack == 0)) {
221553642Sguido		/* gross hack to get around certain broken tcp stacks */
221653642Sguido		ack = tdata->td_end;
221753642Sguido	}
221853642Sguido
221953642Sguido	maxwin = tdata->td_maxwin;
222053642Sguido	ackskew = tdata->td_end - ack;
222153642Sguido
2222145522Sdarrenr	/*
2223145522Sdarrenr	 * Strict sequencing only allows in-order delivery.
2224145522Sdarrenr	 */
2225255332Scy	if ((flags & IS_STRICT) != 0) {
2226255332Scy		if (seq != fdata->td_end) {
2227255332Scy			DT2(iss_tcp_struct, tcpdata_t *, fdata, int, seq);
2228255332Scy			SBUMP(ipf_state_stats.iss_tcp_strict);
2229255332Scy			fin->fin_flx |= FI_OOW;
2230145522Sdarrenr			return 0;
2231145522Sdarrenr		}
2232145522Sdarrenr	}
2233145522Sdarrenr
2234255332Scy#define	SEQ_GE(a,b)	((int)((a) - (b)) >= 0)
2235255332Scy#define	SEQ_GT(a,b)	((int)((a) - (b)) > 0)
2236153876Sguido	inseq = 0;
2237153876Sguido	if ((SEQ_GE(fdata->td_maxend, end)) &&
223857096Sguido	    (SEQ_GE(seq, fdata->td_end - maxwin)) &&
223953642Sguido/* XXX what about big packets */
224053642Sguido#define MAXACKWINDOW 66000
2241165515Sdarrenr	    (-ackskew <= (MAXACKWINDOW)) &&
2242145522Sdarrenr	    ( ackskew <= (MAXACKWINDOW << fdata->td_winscale))) {
2243153876Sguido		inseq = 1;
2244153876Sguido	/*
2245153876Sguido	 * Microsoft Windows will send the next packet to the right of the
2246153876Sguido	 * window if SACK is in use.
2247153876Sguido	 */
2248153876Sguido	} else if ((seq == fdata->td_maxend) && (ackskew == 0) &&
2249153876Sguido	    (fdata->td_winflags & TCP_SACK_PERMIT) &&
2250153876Sguido	    (tdata->td_winflags & TCP_SACK_PERMIT)) {
2251255332Scy		DT2(iss_sinsack, tcpdata_t *, fdata, int, seq);
2252255332Scy		SBUMP(ipf_state_stats.iss_winsack);
2253153876Sguido		inseq = 1;
2254161356Sguido	/*
2255161356Sguido	 * Sometimes a TCP RST will be generated with only the ACK field
2256161356Sguido	 * set to non-zero.
2257161356Sguido	 */
2258161356Sguido	} else if ((seq == 0) && (tcpflags == (TH_RST|TH_ACK)) &&
2259161356Sguido		   (ackskew >= -1) && (ackskew <= 1)) {
2260161356Sguido		inseq = 1;
2261161356Sguido	} else if (!(flags & IS_TCPFSM)) {
2262161356Sguido		int i;
2263161356Sguido
2264161356Sguido		i = (fin->fin_rev << 1) + fin->fin_out;
2265161356Sguido
2266161356Sguido#if 0
2267161356Sguido		if (is_pkts[i]0 == 0) {
2268161356Sguido			/*
2269161356Sguido			 * Picking up a connection in the middle, the "next"
2270161356Sguido			 * packet seen from a direction that is new should be
2271161356Sguido			 * accepted, even if it appears out of sequence.
2272161356Sguido			 */
2273161356Sguido			inseq = 1;
2274255332Scy		} else
2275161356Sguido#endif
2276161356Sguido		if (!(fdata->td_winflags &
2277161356Sguido			    (TCP_WSCALE_SEEN|TCP_WSCALE_FIRST))) {
2278161356Sguido			/*
2279161356Sguido			 * No TCPFSM and no window scaling, so make some
2280161356Sguido			 * extra guesses.
2281161356Sguido			 */
2282161356Sguido			if ((seq == fdata->td_maxend) && (ackskew == 0))
2283161356Sguido				inseq = 1;
2284161356Sguido			else if (SEQ_GE(seq + maxwin, fdata->td_end - maxwin))
2285161356Sguido				inseq = 1;
2286161356Sguido		}
2287153876Sguido	}
2288130886Sdarrenr
2289165515Sdarrenr	/* TRACE(inseq, fdata, tdata, seq, end, ack, ackskew, win, maxwin) */
2290165515Sdarrenr
2291153876Sguido	if (inseq) {
2292130886Sdarrenr		/* if ackskew < 0 then this should be due to fragmented
229353642Sguido		 * packets. There is no way to know the length of the
229453642Sguido		 * total packet in advance.
229553642Sguido		 * We do know the total length from the fragment cache though.
229653642Sguido		 * Note however that there might be more sessions with
2297130886Sdarrenr		 * exactly the same source and destination parameters in the
229853642Sguido		 * state cache (and source and destination is the only stuff
229953642Sguido		 * that is saved in the fragment cache). Note further that
230053642Sguido		 * some TCP connections in the state cache are hashed with
230153642Sguido		 * sport and dport as well which makes it not worthwhile to
230253642Sguido		 * look for them.
230353642Sguido		 * Thus, when ackskew is negative but still seems to belong
230453642Sguido		 * to this session, we bump up the destinations end value.
230553642Sguido		 */
2306145522Sdarrenr		if (ackskew < 0)
2307145522Sdarrenr			tdata->td_end = ack;
230895418Sdarrenr
2309145522Sdarrenr		/* update max window seen */
2310145522Sdarrenr		if (fdata->td_maxwin < win)
2311145522Sdarrenr			fdata->td_maxwin = win;
2312145522Sdarrenr		if (SEQ_GT(end, fdata->td_end))
2313145522Sdarrenr			fdata->td_end = end;
2314145522Sdarrenr		if (SEQ_GE(ack + win, tdata->td_maxend))
2315145522Sdarrenr			tdata->td_maxend = ack + win;
2316145522Sdarrenr		return 1;
2317145522Sdarrenr	}
2318255332Scy	SBUMP(ipf_state_stats.iss_oow);
2319255332Scy	fin->fin_flx |= FI_OOW;
2320145522Sdarrenr	return 0;
2321145522Sdarrenr}
232295418Sdarrenr
2323145522Sdarrenr
2324145522Sdarrenr/* ------------------------------------------------------------------------ */
2325255332Scy/* Function:    ipf_state_clone                                             */
2326145522Sdarrenr/* Returns:     ipstate_t* - NULL == cloning failed,                        */
2327145522Sdarrenr/*                           else pointer to new state structure            */
2328145522Sdarrenr/* Parameters:  fin(I) - pointer to packet information                      */
2329145522Sdarrenr/*              tcp(I) - pointer to TCP/UDP header                          */
2330145522Sdarrenr/*              is(I)  - pointer to master state structure                  */
2331145522Sdarrenr/*                                                                          */
2332145522Sdarrenr/* Create a "duplcate" state table entry from the master.                   */
2333145522Sdarrenr/* ------------------------------------------------------------------------ */
2334255332Scystatic ipstate_t *
2335255332Scyipf_state_clone(fin, tcp, is)
2336255332Scy	fr_info_t *fin;
2337255332Scy	tcphdr_t *tcp;
2338255332Scy	ipstate_t *is;
2339145522Sdarrenr{
2340255332Scy	ipf_main_softc_t *softc = fin->fin_main_soft;
2341255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
2342145522Sdarrenr	ipstate_t *clone;
2343145522Sdarrenr	u_32_t send;
2344145522Sdarrenr
2345255332Scy	if (softs->ipf_state_stats.iss_active == softs->ipf_state_max) {
2346255332Scy		SBUMPD(ipf_state_stats, iss_max);
2347255332Scy		softs->ipf_state_doflush = 1;
2348145522Sdarrenr		return NULL;
234953642Sguido	}
2350145522Sdarrenr	KMALLOC(clone, ipstate_t *);
2351255332Scy	if (clone == NULL) {
2352255332Scy		SBUMPD(ipf_state_stats, iss_clone_nomem);
2353145522Sdarrenr		return NULL;
2354255332Scy	}
2355145522Sdarrenr	bcopy((char *)is, (char *)clone, sizeof(*clone));
2356145522Sdarrenr
2357145522Sdarrenr	MUTEX_NUKE(&clone->is_lock);
2358255332Scy	/*
2359255332Scy	 * It has not yet been placed on any timeout queue, so make sure
2360255332Scy	 * all of that data is zero'd out.
2361255332Scy	 */
2362255332Scy	clone->is_sti.tqe_pnext = NULL;
2363255332Scy	clone->is_sti.tqe_next = NULL;
2364255332Scy	clone->is_sti.tqe_ifq = NULL;
2365255332Scy	clone->is_sti.tqe_parent = clone;
2366145522Sdarrenr
2367255332Scy	clone->is_die = ONE_DAY + softc->ipf_ticks;
2368145522Sdarrenr	clone->is_state[0] = 0;
2369145522Sdarrenr	clone->is_state[1] = 0;
2370145522Sdarrenr	send = ntohl(tcp->th_seq) + fin->fin_dlen - (TCP_OFF(tcp) << 2) +
2371145522Sdarrenr		((tcp->th_flags & TH_SYN) ? 1 : 0) +
2372145522Sdarrenr		((tcp->th_flags & TH_FIN) ? 1 : 0);
2373145522Sdarrenr
2374145522Sdarrenr	if (fin->fin_rev == 1) {
2375145522Sdarrenr		clone->is_dend = send;
2376145522Sdarrenr		clone->is_maxdend = send;
2377145522Sdarrenr		clone->is_send = 0;
2378145522Sdarrenr		clone->is_maxswin = 1;
2379145522Sdarrenr		clone->is_maxdwin = ntohs(tcp->th_win);
2380145522Sdarrenr		if (clone->is_maxdwin == 0)
2381145522Sdarrenr			clone->is_maxdwin = 1;
2382145522Sdarrenr	} else {
2383145522Sdarrenr		clone->is_send = send;
2384145522Sdarrenr		clone->is_maxsend = send;
2385145522Sdarrenr		clone->is_dend = 0;
2386145522Sdarrenr		clone->is_maxdwin = 1;
2387145522Sdarrenr		clone->is_maxswin = ntohs(tcp->th_win);
2388145522Sdarrenr		if (clone->is_maxswin == 0)
2389145522Sdarrenr			clone->is_maxswin = 1;
2390145522Sdarrenr	}
2391145522Sdarrenr
2392145522Sdarrenr	clone->is_flags &= ~SI_CLONE;
2393145522Sdarrenr	clone->is_flags |= SI_CLONED;
2394255332Scy	if (ipf_state_insert(softc, clone, fin->fin_rev) == -1) {
2395255332Scy		KFREE(clone);
2396255332Scy		return NULL;
2397255332Scy	}
2398255332Scy
2399255332Scy	clone->is_ref = 1;
2400145522Sdarrenr	if (clone->is_p == IPPROTO_TCP) {
2401255332Scy		(void) ipf_tcp_age(&clone->is_sti, fin, softs->ipf_state_tcptq,
2402255332Scy				   clone->is_flags, 2);
2403145522Sdarrenr	}
2404145522Sdarrenr	MUTEX_EXIT(&clone->is_lock);
2405145522Sdarrenr	if (is->is_flags & IS_STATESYNC)
2406255332Scy		clone->is_sync = ipf_sync_new(softc, SMC_STATE, fin, clone);
2407255332Scy	DT2(iss_clone, ipstate_t *, is, ipstate_t *, clone);
2408255332Scy	SBUMP(ipf_state_stats.iss_cloned);
2409145522Sdarrenr	return clone;
241053642Sguido}
241153642Sguido
241253642Sguido
2413145522Sdarrenr/* ------------------------------------------------------------------------ */
2414255332Scy/* Function:    ipf_matchsrcdst                                             */
2415145522Sdarrenr/* Returns:     Nil                                                         */
2416255332Scy/* Parameters:  fin(I)   - pointer to packet information                    */
2417255332Scy/*              is(I)    - pointer to state structure                       */
2418255332Scy/*              src(I)   - pointer to source address                        */
2419255332Scy/*              dst(I)   - pointer to destination address                   */
2420255332Scy/*              tcp(I)   - pointer to TCP/UDP header                        */
2421255332Scy/*              cmask(I) - mask of FI_* bits to check                       */
2422145522Sdarrenr/*                                                                          */
2423145522Sdarrenr/* Match a state table entry against an IP packet.  The logic below is that */
2424145522Sdarrenr/* ret gets set to one if the match succeeds, else remains 0.  If it is     */
2425145522Sdarrenr/* still 0 after the test. no match.                                        */
2426145522Sdarrenr/* ------------------------------------------------------------------------ */
2427255332Scystatic ipstate_t *
2428255332Scyipf_matchsrcdst(fin, is, src, dst, tcp, cmask)
2429255332Scy	fr_info_t *fin;
2430255332Scy	ipstate_t *is;
2431255332Scy	i6addr_t *src, *dst;
2432255332Scy	tcphdr_t *tcp;
2433255332Scy	u_32_t cmask;
243453642Sguido{
2435255332Scy	ipf_main_softc_t *softc = fin->fin_main_soft;
2436255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
2437145522Sdarrenr	int ret = 0, rev, out, flags, flx = 0, idx;
243853642Sguido	u_short sp, dp;
2439145522Sdarrenr	u_32_t cflx;
244053642Sguido	void *ifp;
244153642Sguido
2442255332Scy	/*
2443255332Scy	 * If a connection is about to be deleted, no packets
2444255332Scy	 * are allowed to match it.
2445255332Scy	 */
2446255332Scy	if (is->is_sti.tqe_ifq == &softs->ipf_state_deletetq)
2447255332Scy		return NULL;
2448255332Scy
2449145522Sdarrenr	rev = IP6_NEQ(&is->is_dst, dst);
245053642Sguido	ifp = fin->fin_ifp;
245153642Sguido	out = fin->fin_out;
2452145522Sdarrenr	flags = is->is_flags;
245392685Sdarrenr	sp = 0;
245492685Sdarrenr	dp = 0;
245553642Sguido
245653642Sguido	if (tcp != NULL) {
2457145522Sdarrenr		sp = htons(fin->fin_sport);
2458145522Sdarrenr		dp = ntohs(fin->fin_dport);
2459145522Sdarrenr	}
2460145522Sdarrenr	if (!rev) {
2461145522Sdarrenr		if (tcp != NULL) {
2462145522Sdarrenr			if (!(flags & SI_W_SPORT) && (sp != is->is_sport))
246380482Sdarrenr				rev = 1;
2464145522Sdarrenr			else if (!(flags & SI_W_DPORT) && (dp != is->is_dport))
246580482Sdarrenr				rev = 1;
246680482Sdarrenr		}
246753642Sguido	}
246853642Sguido
246992685Sdarrenr	idx = (out << 1) + rev;
247092685Sdarrenr
2471145522Sdarrenr	/*
2472145522Sdarrenr	 * If the interface for this 'direction' is set, make sure it matches.
2473145522Sdarrenr	 * An interface name that is not set matches any, as does a name of *.
2474145522Sdarrenr	 */
2475170268Sdarrenr	if ((is->is_ifp[idx] == ifp) || (is->is_ifp[idx] == NULL &&
2476170268Sdarrenr	    (*is->is_ifname[idx] == '\0' || *is->is_ifname[idx] == '-' ||
2477170268Sdarrenr	     *is->is_ifname[idx] == '*')))
247892685Sdarrenr		ret = 1;
247992685Sdarrenr
2480255332Scy	if (ret == 0) {
2481255332Scy		DT2(iss_lookup_badifp, fr_info_t *, fin, ipstate_t *, is);
2482255332Scy		SBUMP(ipf_state_stats.iss_lookup_badifp);
2483255332Scy		/* TRACE is, out, rev, idx */
2484145522Sdarrenr		return NULL;
2485255332Scy	}
248653642Sguido	ret = 0;
248753642Sguido
2488145522Sdarrenr	/*
2489145522Sdarrenr	 * Match addresses and ports.
2490145522Sdarrenr	 */
249153642Sguido	if (rev == 0) {
2492145522Sdarrenr		if ((IP6_EQ(&is->is_dst, dst) || (flags & SI_W_DADDR)) &&
2493145522Sdarrenr		    (IP6_EQ(&is->is_src, src) || (flags & SI_W_SADDR))) {
2494145522Sdarrenr			if (tcp) {
2495255332Scy				if ((sp == is->is_sport || flags & SI_W_SPORT)
2496255332Scy				    &&
2497145522Sdarrenr				    (dp == is->is_dport || flags & SI_W_DPORT))
2498145522Sdarrenr					ret = 1;
2499145522Sdarrenr			} else {
2500145522Sdarrenr				ret = 1;
2501145522Sdarrenr			}
250253642Sguido		}
250353642Sguido	} else {
2504145522Sdarrenr		if ((IP6_EQ(&is->is_dst, src) || (flags & SI_W_DADDR)) &&
2505145522Sdarrenr		    (IP6_EQ(&is->is_src, dst) || (flags & SI_W_SADDR))) {
2506145522Sdarrenr			if (tcp) {
2507255332Scy				if ((dp == is->is_sport || flags & SI_W_SPORT)
2508255332Scy				    &&
2509145522Sdarrenr				    (sp == is->is_dport || flags & SI_W_DPORT))
2510145522Sdarrenr					ret = 1;
2511145522Sdarrenr			} else {
2512145522Sdarrenr				ret = 1;
2513145522Sdarrenr			}
251453642Sguido		}
251553642Sguido	}
2516145522Sdarrenr
2517255332Scy	if (ret == 0) {
2518255332Scy		SBUMP(ipf_state_stats.iss_lookup_badport);
2519255332Scy		DT2(iss_lookup_badport, fr_info_t *, fin, ipstate_t *, is);
2520255332Scy		/* TRACE rev, is, sp, dp, src, dst */
2521145522Sdarrenr		return NULL;
2522255332Scy	}
252353642Sguido
252453642Sguido	/*
252553642Sguido	 * Whether or not this should be here, is questionable, but the aim
252653642Sguido	 * is to get this out of the main line.
252753642Sguido	 */
252853642Sguido	if (tcp == NULL)
2529145522Sdarrenr		flags = is->is_flags & ~(SI_WILDP|SI_NEWFR|SI_CLONE|SI_CLONED);
253053642Sguido
2531145522Sdarrenr	/*
2532145522Sdarrenr	 * Only one of the source or destination address can be flaged as a
2533145522Sdarrenr	 * wildcard.  Fill in the missing address, if set.
2534145522Sdarrenr	 * For IPv6, if the address being copied in is multicast, then
2535145522Sdarrenr	 * don't reset the wild flag - multicast causes it to be set in the
2536145522Sdarrenr	 * first place!
2537145522Sdarrenr	 */
2538145522Sdarrenr	if ((flags & (SI_W_SADDR|SI_W_DADDR))) {
2539145522Sdarrenr		fr_ip_t *fi = &fin->fin_fi;
254053642Sguido
2541145522Sdarrenr		if ((flags & SI_W_SADDR) != 0) {
254292685Sdarrenr			if (rev == 0) {
2543255332Scy				is->is_src = fi->fi_src;
2544255332Scy				is->is_flags &= ~SI_W_SADDR;
254592685Sdarrenr			} else {
2546255332Scy				if (!(fin->fin_flx & (FI_MULTICAST|FI_MBCAST))){
2547145522Sdarrenr					is->is_src = fi->fi_dst;
2548145522Sdarrenr					is->is_flags &= ~SI_W_SADDR;
2549145522Sdarrenr				}
255092685Sdarrenr			}
2551145522Sdarrenr		} else if ((flags & SI_W_DADDR) != 0) {
255292685Sdarrenr			if (rev == 0) {
2553255332Scy				if (!(fin->fin_flx & (FI_MULTICAST|FI_MBCAST))){
2554145522Sdarrenr					is->is_dst = fi->fi_dst;
2555145522Sdarrenr					is->is_flags &= ~SI_W_DADDR;
2556145522Sdarrenr				}
255792685Sdarrenr			} else {
2558255332Scy				is->is_dst = fi->fi_src;
2559255332Scy				is->is_flags &= ~SI_W_DADDR;
256092685Sdarrenr			}
256192685Sdarrenr		}
2562145522Sdarrenr		if ((is->is_flags & (SI_WILDA|SI_WILDP)) == 0) {
2563255332Scy			ATOMIC_DECL(softs->ipf_state_stats.iss_wild);
2564145522Sdarrenr		}
256592685Sdarrenr	}
256692685Sdarrenr
2567145522Sdarrenr	flx = fin->fin_flx & cmask;
2568145522Sdarrenr	cflx = is->is_flx[out][rev];
2569145522Sdarrenr
2570145522Sdarrenr	/*
2571145522Sdarrenr	 * Match up any flags set from IP options.
2572145522Sdarrenr	 */
2573145522Sdarrenr	if ((cflx && (flx != (cflx & cmask))) ||
2574153876Sguido	    ((fin->fin_optmsk & is->is_optmsk[rev]) != is->is_opt[rev]) ||
2575145522Sdarrenr	    ((fin->fin_secmsk & is->is_secmsk) != is->is_sec) ||
2576255332Scy	    ((fin->fin_auth & is->is_authmsk) != is->is_auth)) {
2577255332Scy		SBUMPD(ipf_state_stats, iss_miss_mask);
2578145522Sdarrenr		return NULL;
2579255332Scy	}
2580145522Sdarrenr
2581255332Scy	if ((fin->fin_flx & FI_IGNORE) != 0) {
2582255332Scy		fin->fin_rev = rev;
2583255332Scy		return is;
2584255332Scy	}
2585255332Scy
2586145522Sdarrenr	/*
2587145522Sdarrenr	 * Only one of the source or destination port can be flagged as a
2588145522Sdarrenr	 * wildcard.  When filling it in, fill in a copy of the matched entry
2589145522Sdarrenr	 * if it has the cloning flag set.
2590145522Sdarrenr	 */
2591145522Sdarrenr	if ((flags & (SI_W_SPORT|SI_W_DPORT))) {
2592145522Sdarrenr		if ((flags & SI_CLONE) != 0) {
2593153876Sguido			ipstate_t *clone;
2594153876Sguido
2595255332Scy			clone = ipf_state_clone(fin, tcp, is);
2596153876Sguido			if (clone == NULL)
2597145522Sdarrenr				return NULL;
2598153876Sguido			is = clone;
2599145522Sdarrenr		} else {
2600255332Scy			ATOMIC_DECL(softs->ipf_state_stats.iss_wild);
2601145522Sdarrenr		}
2602145522Sdarrenr
2603145522Sdarrenr		if ((flags & SI_W_SPORT) != 0) {
260453642Sguido			if (rev == 0) {
260553642Sguido				is->is_sport = sp;
2606145522Sdarrenr				is->is_send = ntohl(tcp->th_seq);
260753642Sguido			} else {
260853642Sguido				is->is_sport = dp;
2609145522Sdarrenr				is->is_send = ntohl(tcp->th_ack);
261053642Sguido			}
261153642Sguido			is->is_maxsend = is->is_send + 1;
2612145522Sdarrenr		} else if ((flags & SI_W_DPORT) != 0) {
261353642Sguido			if (rev == 0) {
261453642Sguido				is->is_dport = dp;
2615145522Sdarrenr				is->is_dend = ntohl(tcp->th_ack);
261653642Sguido			} else {
261753642Sguido				is->is_dport = sp;
2618145522Sdarrenr				is->is_dend = ntohl(tcp->th_seq);
261953642Sguido			}
262053642Sguido			is->is_maxdend = is->is_dend + 1;
262153642Sguido		}
2622145522Sdarrenr		is->is_flags &= ~(SI_W_SPORT|SI_W_DPORT);
2623255332Scy		if ((flags & SI_CLONED) && softs->ipf_state_logging)
2624255332Scy			ipf_state_log(softc, is, ISL_CLONE);
262553642Sguido	}
262653642Sguido
262760854Sdarrenr	ret = -1;
262860854Sdarrenr
2629153876Sguido	if (is->is_flx[out][rev] == 0) {
2630145522Sdarrenr		is->is_flx[out][rev] = flx;
2631255332Scy		if (rev == 1 && is->is_optmsk[1] == 0) {
2632255332Scy			is->is_opt[1] = fin->fin_optmsk;
2633255332Scy			is->is_optmsk[1] = 0xffffffff;
2634255332Scy			if (is->is_v == 6) {
2635255332Scy				is->is_opt[1] &= ~0x8;
2636255332Scy				is->is_optmsk[1] &= ~0x8;
2637255332Scy			}
2638153876Sguido		}
2639153876Sguido	}
2640145522Sdarrenr
2641145522Sdarrenr	/*
2642145522Sdarrenr	 * Check if the interface name for this "direction" is set and if not,
2643145522Sdarrenr	 * fill it in.
2644145522Sdarrenr	 */
264592685Sdarrenr	if (is->is_ifp[idx] == NULL &&
2646145522Sdarrenr	    (*is->is_ifname[idx] == '\0' || *is->is_ifname[idx] == '*')) {
2647145522Sdarrenr		is->is_ifp[idx] = ifp;
2648255332Scy		COPYIFNAME(fin->fin_v, ifp, is->is_ifname[idx]);
264960854Sdarrenr	}
265080482Sdarrenr	fin->fin_rev = rev;
2651145522Sdarrenr	return is;
265253642Sguido}
265353642Sguido
265460854Sdarrenr
2655145522Sdarrenr/* ------------------------------------------------------------------------ */
2656255332Scy/* Function:    ipf_checkicmpmatchingstate                                  */
2657145522Sdarrenr/* Returns:     Nil                                                         */
2658145522Sdarrenr/* Parameters:  fin(I) - pointer to packet information                      */
2659145522Sdarrenr/*                                                                          */
2660145522Sdarrenr/* If we've got an ICMP error message, using the information stored in the  */
2661145522Sdarrenr/* ICMP packet, look for a matching state table entry.                      */
2662145522Sdarrenr/*                                                                          */
2663145522Sdarrenr/* If we return NULL then no lock on ipf_state is held.                     */
2664145522Sdarrenr/* If we return non-null then a read-lock on ipf_state is held.             */
2665145522Sdarrenr/* ------------------------------------------------------------------------ */
2666255332Scystatic ipstate_t *
2667255332Scyipf_checkicmpmatchingstate(fin)
2668255332Scy	fr_info_t *fin;
266953642Sguido{
2670255332Scy	ipf_main_softc_t *softc = fin->fin_main_soft;
2671255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
2672145522Sdarrenr	ipstate_t *is, **isp;
2673145522Sdarrenr	i6addr_t dst, src;
267453642Sguido	struct icmp *ic;
2675145522Sdarrenr	u_short savelen;
267664580Sdarrenr	icmphdr_t *icmp;
267753642Sguido	fr_info_t ofin;
2678145522Sdarrenr	tcphdr_t *tcp;
267964580Sdarrenr	int type, len;
2680255332Scy	u_char	pr;
268153642Sguido	ip_t *oip;
268255929Sguido	u_int hv;
268353642Sguido
268457096Sguido	/*
268557096Sguido	 * Does it at least have the return (basic) IP header ?
2686153876Sguido	 * Is it an actual recognised ICMP error type?
268753642Sguido	 * Only a basic IP header (no options) should be with
268853642Sguido	 * an ICMP error header.
268953642Sguido	 */
2690145522Sdarrenr	if ((fin->fin_v != 4) || (fin->fin_hlen != sizeof(ip_t)) ||
2691153876Sguido	    (fin->fin_plen < ICMPERR_MINPKTLEN) ||
2692255332Scy	    !(fin->fin_flx & FI_ICMPERR)) {
2693255332Scy		SBUMPD(ipf_state_stats, iss_icmp_bad);
269453642Sguido		return NULL;
2695255332Scy	}
2696145522Sdarrenr	ic = fin->fin_dp;
269753642Sguido	type = ic->icmp_type;
269853642Sguido
269960854Sdarrenr	oip = (ip_t *)((char *)ic + ICMPERR_ICMPHLEN);
2700130886Sdarrenr	/*
2701130886Sdarrenr	 * Check if the at least the old IP header (with options) and
2702130886Sdarrenr	 * 8 bytes of payload is present.
2703130886Sdarrenr	 */
2704255332Scy	if (fin->fin_plen < ICMPERR_MAXPKTLEN + ((IP_HL(oip) - 5) << 2)) {
2705255332Scy		SBUMPDX(ipf_state_stats, iss_icmp_short, iss_icmp_short_1);
270653642Sguido		return NULL;
2707255332Scy	}
270855929Sguido
270964580Sdarrenr	/*
2710145522Sdarrenr	 * Sanity Checks.
271164580Sdarrenr	 */
271264580Sdarrenr	len = fin->fin_dlen - ICMPERR_ICMPHLEN;
2713255332Scy	if ((len <= 0) || ((IP_HL(oip) << 2) > len)) {
2714255332Scy		DT2(iss_icmp_len, fr_info_t *, fin, struct ip*, oip);
2715255332Scy		SBUMPDX(ipf_state_stats, iss_icmp_short, iss_icmp_short_1);
271664580Sdarrenr		return NULL;
2717255332Scy	}
271864580Sdarrenr
271964580Sdarrenr	/*
272064580Sdarrenr	 * Is the buffer big enough for all of it ?  It's the size of the IP
272164580Sdarrenr	 * header claimed in the encapsulated part which is of concern.  It
272264580Sdarrenr	 * may be too big to be in this buffer but not so big that it's
272364580Sdarrenr	 * outside the ICMP packet, leading to TCP deref's causing problems.
272464580Sdarrenr	 * This is possible because we don't know how big oip_hl is when we
2725255332Scy	 * do the pullup early in ipf_check() and thus can't guarantee it is
272664580Sdarrenr	 * all here now.
272764580Sdarrenr	 */
272864580Sdarrenr#ifdef  _KERNEL
272964580Sdarrenr	{
273064580Sdarrenr	mb_t *m;
273164580Sdarrenr
2732145522Sdarrenr	m = fin->fin_m;
2733145522Sdarrenr# if defined(MENTAT)
2734255332Scy	if ((char *)oip + len > (char *)m->b_wptr) {
2735255332Scy		SBUMPDX(ipf_state_stats, iss_icmp_short, iss_icmp_short_2);
273664580Sdarrenr		return NULL;
2737255332Scy	}
273864580Sdarrenr# else
2739255332Scy	if ((char *)oip + len > (char *)fin->fin_ip + m->m_len) {
2740255332Scy		SBUMPDX(ipf_state_stats, iss_icmp_short, iss_icmp_short_3);
274164580Sdarrenr		return NULL;
2742255332Scy	}
274364580Sdarrenr# endif
274464580Sdarrenr	}
274564580Sdarrenr#endif
2746255332Scy
2747170268Sdarrenr	bcopy((char *)fin, (char *)&ofin, sizeof(*fin));
274864580Sdarrenr
274964580Sdarrenr	/*
275064580Sdarrenr	 * in the IPv4 case we must zero the i6addr union otherwise
2751145522Sdarrenr	 * the IP6_EQ and IP6_NEQ macros produce the wrong results because
275264580Sdarrenr	 * of the 'junk' in the unused part of the union
275364580Sdarrenr	 */
275467614Sdarrenr	bzero((char *)&src, sizeof(src));
275567614Sdarrenr	bzero((char *)&dst, sizeof(dst));
2756145522Sdarrenr
2757130886Sdarrenr	/*
2758145522Sdarrenr	 * we make an fin entry to be able to feed it to
2759145522Sdarrenr	 * matchsrcdst note that not all fields are encessary
2760145522Sdarrenr	 * but this is the cleanest way. Note further we fill
2761145522Sdarrenr	 * in fin_mp such that if someone uses it we'll get
2762255332Scy	 * a kernel panic. ipf_matchsrcdst does not use this.
2763145522Sdarrenr	 *
2764130886Sdarrenr	 * watch out here, as ip is in host order and oip in network
2765130886Sdarrenr	 * order. Any change we make must be undone afterwards, like
2766255332Scy	 * oip->ip_len.
2767130886Sdarrenr	 */
2768130886Sdarrenr	savelen = oip->ip_len;
2769255332Scy	oip->ip_len = htons(len);
2770145522Sdarrenr
2771145522Sdarrenr	ofin.fin_flx = FI_NOCKSUM;
2772145522Sdarrenr	ofin.fin_v = 4;
2773145522Sdarrenr	ofin.fin_ip = oip;
2774145522Sdarrenr	ofin.fin_m = NULL;	/* if dereferenced, panic XXX */
2775145522Sdarrenr	ofin.fin_mp = NULL;	/* if dereferenced, panic XXX */
2776255332Scy	(void) ipf_makefrip(IP_HL(oip) << 2, oip, &ofin);
2777145522Sdarrenr	ofin.fin_ifp = fin->fin_ifp;
2778145522Sdarrenr	ofin.fin_out = !fin->fin_out;
2779255332Scy
2780255332Scy	hv = (pr = oip->ip_p);
2781255332Scy	src.in4 = oip->ip_src;
2782255332Scy	hv += src.in4.s_addr;
2783255332Scy	dst.in4 = oip->ip_dst;
2784255332Scy	hv += dst.in4.s_addr;
2785255332Scy
2786130886Sdarrenr	/*
2787255332Scy	 * Reset the short and bad flag here because in ipf_matchsrcdst()
2788145522Sdarrenr	 * the flags for the current packet (fin_flx) are compared against
2789145522Sdarrenr	 * those for the existing session.
2790130886Sdarrenr	 */
2791145522Sdarrenr	ofin.fin_flx &= ~(FI_BAD|FI_SHORT);
2792130886Sdarrenr
2793130886Sdarrenr	/*
2794255332Scy	 * Put old values of ip_len back as we don't know
2795255332Scy	 * if we have to forward the packet or process it again.
2796130886Sdarrenr	 */
2797130886Sdarrenr	oip->ip_len = savelen;
2798130886Sdarrenr
279992685Sdarrenr	switch (oip->ip_p)
280092685Sdarrenr	{
280192685Sdarrenr	case IPPROTO_ICMP :
280255929Sguido		/*
2803130886Sdarrenr		 * an ICMP error can only be generated as a result of an
280455929Sguido		 * ICMP query, not as the response on an ICMP error
280555929Sguido		 *
280655929Sguido		 * XXX theoretically ICMP_ECHOREP and the other reply's are
280755929Sguido		 * ICMP query's as well, but adding them here seems strange XXX
280855929Sguido		 */
2809255332Scy		if ((ofin.fin_flx & FI_ICMPERR) != 0) {
2810255332Scy			DT1(iss_icmp_icmperr, fr_info_t *, &ofin);
2811255332Scy			SBUMP(ipf_state_stats.iss_icmp_icmperr);
281255929Sguido		    	return NULL;
2813255332Scy		}
281455929Sguido
281557096Sguido		/*
281655929Sguido		 * perform a lookup of the ICMP packet in the state table
281755929Sguido		 */
2818153876Sguido		icmp = (icmphdr_t *)((char *)oip + (IP_HL(oip) << 2));
281960854Sdarrenr		hv += icmp->icmp_id;
2820145522Sdarrenr		hv = DOUBLE_HASH(hv);
282155929Sguido
2822255332Scy		READ_ENTER(&softc->ipf_state);
2823255332Scy		for (isp = &softs->ipf_state_table[hv];
2824255332Scy		     ((is = *isp) != NULL); ) {
2825145522Sdarrenr			isp = &is->is_hnext;
2826145522Sdarrenr			if ((is->is_p != pr) || (is->is_v != 4))
2827145522Sdarrenr				continue;
2828145522Sdarrenr			if (is->is_pass & FR_NOICMPERR)
2829145522Sdarrenr				continue;
2830255332Scy
2831255332Scy			is = ipf_matchsrcdst(&ofin, is, &src, &dst,
2832145522Sdarrenr					    NULL, FI_ICMPCMP);
2833255332Scy			if ((is != NULL) && !ipf_allowstateicmp(fin, is, &src))
2834145522Sdarrenr				return is;
2835145522Sdarrenr		}
2836255332Scy		RWLOCK_EXIT(&softc->ipf_state);
2837255332Scy		SBUMPDX(ipf_state_stats, iss_icmp_miss, iss_icmp_miss_1);
2838145522Sdarrenr		return NULL;
283992685Sdarrenr	case IPPROTO_TCP :
284092685Sdarrenr	case IPPROTO_UDP :
284192685Sdarrenr		break;
284292685Sdarrenr	default :
2843255332Scy		SBUMPDX(ipf_state_stats, iss_icmp_miss, iss_icmp_miss_2);
284455929Sguido		return NULL;
284592685Sdarrenr	}
284655929Sguido
2847145522Sdarrenr	tcp = (tcphdr_t *)((char *)oip + (IP_HL(oip) << 2));
284853642Sguido
2849255332Scy	hv += tcp->th_dport;;
2850255332Scy	hv += tcp->th_sport;;
2851145522Sdarrenr	hv = DOUBLE_HASH(hv);
2852130886Sdarrenr
2853255332Scy	READ_ENTER(&softc->ipf_state);
2854255332Scy	for (isp = &softs->ipf_state_table[hv]; ((is = *isp) != NULL); ) {
2855145522Sdarrenr		isp = &is->is_hnext;
285653642Sguido		/*
285753642Sguido		 * Only allow this icmp though if the
285853642Sguido		 * encapsulated packet was allowed through the
285953642Sguido		 * other way around. Note that the minimal amount
286053642Sguido		 * of info present does not allow for checking against
2861145522Sdarrenr		 * tcp internals such as seq and ack numbers.   Only the
2862130886Sdarrenr		 * ports are known to be present and can be even if the
2863130886Sdarrenr		 * short flag is set.
286453642Sguido		 */
286560854Sdarrenr		if ((is->is_p == pr) && (is->is_v == 4) &&
2866255332Scy		    (is = ipf_matchsrcdst(&ofin, is, &src, &dst,
2867255332Scy					  tcp, FI_ICMPCMP))) {
2868255332Scy			if (ipf_allowstateicmp(fin, is, &src) == 0)
2869255332Scy				return is;
287053642Sguido		}
287153642Sguido	}
2872255332Scy	RWLOCK_EXIT(&softc->ipf_state);
2873255332Scy	SBUMPDX(ipf_state_stats, iss_icmp_miss, iss_icmp_miss_3);
2874145522Sdarrenr	return NULL;
287553642Sguido}
287653642Sguido
287767614Sdarrenr
2878145522Sdarrenr/* ------------------------------------------------------------------------ */
2879255332Scy/* Function:    ipf_allowstateicmp                                          */
2880255332Scy/* Returns:     int - 1 = packet denied, 0 = packet allowed                 */
2881255332Scy/* Parameters:  fin(I) - pointer to packet information                      */
2882255332Scy/*              is(I)  - pointer to state table entry                       */
2883255332Scy/*              src(I) - source address to check permission for             */
2884255332Scy/*                                                                          */
2885255332Scy/* For an ICMP packet that has so far matched a state table entry, check if */
2886255332Scy/* there are any further refinements that might mean we want to block this  */
2887255332Scy/* packet.  This code isn't specific to either IPv4 or IPv6.                */
2888255332Scy/* ------------------------------------------------------------------------ */
2889255332Scystatic int
2890255332Scyipf_allowstateicmp(fin, is, src)
2891255332Scy	fr_info_t *fin;
2892255332Scy	ipstate_t *is;
2893255332Scy	i6addr_t *src;
2894255332Scy{
2895255332Scy	ipf_main_softc_t *softc = fin->fin_main_soft;
2896255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
2897255332Scy	frentry_t *savefr;
2898255332Scy	frentry_t *fr;
2899255332Scy	u_32_t ipass;
2900255332Scy	int backward;
2901255332Scy	int oi;
2902255332Scy	int i;
2903255332Scy
2904255332Scy	fr = is->is_rule;
2905255332Scy	if (fr != NULL && fr->fr_icmpgrp != NULL) {
2906255332Scy		savefr = fin->fin_fr;
2907255332Scy		fin->fin_fr = fr->fr_icmpgrp->fg_start;
2908255332Scy
2909255332Scy		ipass = ipf_scanlist(fin, softc->ipf_pass);
2910255332Scy		fin->fin_fr = savefr;
2911255332Scy		if (FR_ISBLOCK(ipass)) {
2912255332Scy			SBUMPD(ipf_state_stats, iss_icmp_headblock);
2913255332Scy			return 1;
2914255332Scy		}
2915255332Scy	}
2916255332Scy
2917255332Scy	/*
2918255332Scy	 * i  : the index of this packet (the icmp unreachable)
2919255332Scy	 * oi : the index of the original packet found in the
2920255332Scy	 *      icmp header (i.e. the packet causing this icmp)
2921255332Scy	 * backward : original packet was backward compared to
2922255332Scy	 *            the state
2923255332Scy	 */
2924255332Scy	backward = IP6_NEQ(&is->is_src, src);
2925255332Scy	fin->fin_rev = !backward;
2926255332Scy	i = (!backward << 1) + fin->fin_out;
2927255332Scy	oi = (backward << 1) + !fin->fin_out;
2928255332Scy
2929255332Scy	if (is->is_pass & FR_NOICMPERR) {
2930255332Scy		SBUMPD(ipf_state_stats, iss_icmp_banned);
2931255332Scy		return 1;
2932255332Scy	}
2933255332Scy	if (is->is_icmppkts[i] > is->is_pkts[oi]) {
2934255332Scy		SBUMPD(ipf_state_stats, iss_icmp_toomany);
2935255332Scy		return 1;
2936255332Scy	}
2937255332Scy
2938255332Scy	DT2(iss_icmp_hits, fr_info_t *, fin, ipstate_t *, is);
2939255332Scy	SBUMP(ipf_state_stats.iss_icmp_hits);
2940255332Scy	is->is_icmppkts[i]++;
2941255332Scy
2942255332Scy	/*
2943255332Scy	 * we deliberately do not touch the timeouts
2944255332Scy	 * for the accompanying state table entry.
2945255332Scy	 * It remains to be seen if that is correct. XXX
2946255332Scy	 */
2947255332Scy	return 0;
2948255332Scy}
2949255332Scy
2950255332Scy
2951255332Scy/* ------------------------------------------------------------------------ */
2952255332Scy/* Function:    ipf_ipsmove                                                 */
2953145522Sdarrenr/* Returns:     Nil                                                         */
2954145522Sdarrenr/* Parameters:  is(I) - pointer to state table entry                        */
2955145522Sdarrenr/*              hv(I) - new hash value for state table entry                */
2956145522Sdarrenr/* Write Locks: ipf_state                                                   */
2957145522Sdarrenr/*                                                                          */
2958145522Sdarrenr/* Move a state entry from one position in the hash table to another.       */
2959145522Sdarrenr/* ------------------------------------------------------------------------ */
2960255332Scystatic void
2961255332Scyipf_ipsmove(softs, is, hv)
2962255332Scy	ipf_state_softc_t *softs;
2963255332Scy	ipstate_t *is;
2964255332Scy	u_int hv;
296567614Sdarrenr{
2966145522Sdarrenr	ipstate_t **isp;
296767614Sdarrenr	u_int hvm;
296867614Sdarrenr
296967614Sdarrenr	hvm = is->is_hv;
2970255332Scy
2971255332Scy	/* TRACE is, is_hv, hvm */
2972255332Scy
297367614Sdarrenr	/*
297467614Sdarrenr	 * Remove the hash from the old location...
297567614Sdarrenr	 */
2976145522Sdarrenr	isp = is->is_phnext;
297767614Sdarrenr	if (is->is_hnext)
297867614Sdarrenr		is->is_hnext->is_phnext = isp;
297967614Sdarrenr	*isp = is->is_hnext;
2980255332Scy	if (softs->ipf_state_table[hvm] == NULL)
2981255332Scy		softs->ipf_state_stats.iss_inuse--;
2982255332Scy	softs->ipf_state_stats.iss_bucketlen[hvm]--;
298367614Sdarrenr
298467614Sdarrenr	/*
298567614Sdarrenr	 * ...and put the hash in the new one.
298667614Sdarrenr	 */
2987145522Sdarrenr	hvm = DOUBLE_HASH(hv);
298867853Sdarrenr	is->is_hv = hvm;
2989255332Scy
2990255332Scy	/* TRACE is, hv, is_hv, hvm */
2991255332Scy
2992255332Scy	isp = &softs->ipf_state_table[hvm];
299367614Sdarrenr	if (*isp)
299467614Sdarrenr		(*isp)->is_phnext = &is->is_hnext;
299567614Sdarrenr	else
2996255332Scy		softs->ipf_state_stats.iss_inuse++;
2997255332Scy	softs->ipf_state_stats.iss_bucketlen[hvm]++;
299867614Sdarrenr	is->is_phnext = isp;
299967614Sdarrenr	is->is_hnext = *isp;
300067614Sdarrenr	*isp = is;
300167614Sdarrenr}
300267614Sdarrenr
300367614Sdarrenr
3004145522Sdarrenr/* ------------------------------------------------------------------------ */
3005255332Scy/* Function:    ipf_state_lookup                                            */
3006145522Sdarrenr/* Returns:     ipstate_t* - NULL == no matching state found,               */
3007145522Sdarrenr/*                           else pointer to state information is returned  */
3008255332Scy/* Parameters:  fin(I)  - pointer to packet information                     */
3009255332Scy/*              tcp(I)  - pointer to TCP/UDP header.                        */
3010255332Scy/*              ifqp(O) - pointer for storing tailq timeout                 */
3011145522Sdarrenr/*                                                                          */
3012145522Sdarrenr/* Search the state table for a matching entry to the packet described by   */
3013255332Scy/* the contents of *fin. For certain protocols, when a match is found the   */
3014255332Scy/* timeout queue is also selected and stored in ifpq if it is non-NULL.     */
3015145522Sdarrenr/*                                                                          */
3016145522Sdarrenr/* If we return NULL then no lock on ipf_state is held.                     */
3017145522Sdarrenr/* If we return non-null then a read-lock on ipf_state is held.             */
3018145522Sdarrenr/* ------------------------------------------------------------------------ */
3019255332Scyipstate_t *
3020255332Scyipf_state_lookup(fin, tcp, ifqp)
3021255332Scy	fr_info_t *fin;
3022255332Scy	tcphdr_t *tcp;
3023255332Scy	ipftq_t **ifqp;
302453642Sguido{
3025255332Scy	ipf_main_softc_t *softc = fin->fin_main_soft;
3026255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
3027145522Sdarrenr	u_int hv, hvm, pr, v, tryagain;
3028145522Sdarrenr	ipstate_t *is, **isp;
3029145522Sdarrenr	u_short dport, sport;
3030145522Sdarrenr	i6addr_t src, dst;
303153642Sguido	struct icmp *ic;
3032145522Sdarrenr	ipftq_t *ifq;
3033145522Sdarrenr	int oow;
303453642Sguido
303553642Sguido	is = NULL;
3036145522Sdarrenr	ifq = NULL;
3037145522Sdarrenr	tcp = fin->fin_dp;
303853642Sguido	ic = (struct icmp *)tcp;
303960854Sdarrenr	hv = (pr = fin->fin_fi.fi_p);
304060854Sdarrenr	src = fin->fin_fi.fi_src;
304160854Sdarrenr	dst = fin->fin_fi.fi_dst;
304260854Sdarrenr	hv += src.in4.s_addr;
304360854Sdarrenr	hv += dst.in4.s_addr;
304453642Sguido
304560854Sdarrenr	v = fin->fin_fi.fi_v;
304692685Sdarrenr#ifdef	USE_INET6
304792685Sdarrenr	if (v == 6) {
3048145522Sdarrenr		hv  += fin->fin_fi.fi_src.i6[1];
3049145522Sdarrenr		hv  += fin->fin_fi.fi_src.i6[2];
3050145522Sdarrenr		hv  += fin->fin_fi.fi_src.i6[3];
305192685Sdarrenr
305292685Sdarrenr		if ((fin->fin_p == IPPROTO_ICMPV6) &&
305392685Sdarrenr		    IN6_IS_ADDR_MULTICAST(&fin->fin_fi.fi_dst.in6)) {
305492685Sdarrenr			hv -= dst.in4.s_addr;
305592685Sdarrenr		} else {
305692685Sdarrenr			hv += fin->fin_fi.fi_dst.i6[1];
305792685Sdarrenr			hv += fin->fin_fi.fi_dst.i6[2];
305892685Sdarrenr			hv += fin->fin_fi.fi_dst.i6[3];
305992685Sdarrenr		}
306092685Sdarrenr	}
306192685Sdarrenr#endif
3062172776Sdarrenr	if ((v == 4) &&
3063172776Sdarrenr	    (fin->fin_flx & (FI_MULTICAST|FI_BROADCAST|FI_MBCAST))) {
3064172776Sdarrenr		if (fin->fin_out == 0) {
3065172776Sdarrenr			hv -= src.in4.s_addr;
3066172776Sdarrenr		} else {
3067172776Sdarrenr			hv -= dst.in4.s_addr;
3068172776Sdarrenr		}
3069172776Sdarrenr	}
307092685Sdarrenr
3071255332Scy	/* TRACE fin_saddr, fin_daddr, hv */
3072255332Scy
3073145522Sdarrenr	/*
3074145522Sdarrenr	 * Search the hash table for matching packet header info.
3075145522Sdarrenr	 */
3076145522Sdarrenr	switch (pr)
307753642Sguido	{
307860854Sdarrenr#ifdef	USE_INET6
307960854Sdarrenr	case IPPROTO_ICMPV6 :
308092685Sdarrenr		tryagain = 0;
308160854Sdarrenr		if (v == 6) {
308260854Sdarrenr			if ((ic->icmp_type == ICMP6_ECHO_REQUEST) ||
308360854Sdarrenr			    (ic->icmp_type == ICMP6_ECHO_REPLY)) {
308460854Sdarrenr				hv += ic->icmp_id;
308560854Sdarrenr			}
308660854Sdarrenr		}
3087255332Scy		READ_ENTER(&softc->ipf_state);
308892685Sdarrenricmp6again:
3089145522Sdarrenr		hvm = DOUBLE_HASH(hv);
3090255332Scy		for (isp = &softs->ipf_state_table[hvm];
3091255332Scy		     ((is = *isp) != NULL); ) {
3092145522Sdarrenr			isp = &is->is_hnext;
3093145522Sdarrenr			if ((is->is_p != pr) || (is->is_v != v))
3094145522Sdarrenr				continue;
3095255332Scy			is = ipf_matchsrcdst(fin, is, &src, &dst, NULL, FI_CMP);
3096145522Sdarrenr			if (is != NULL &&
3097255332Scy			    ipf_matchicmpqueryreply(v, &is->is_icmp,
3098145522Sdarrenr						   ic, fin->fin_rev)) {
3099145522Sdarrenr				if (fin->fin_rev)
3100255332Scy					ifq = &softs->ipf_state_icmpacktq;
310192685Sdarrenr				else
3102255332Scy					ifq = &softs->ipf_state_icmptq;
310392685Sdarrenr				break;
310492685Sdarrenr			}
3105145522Sdarrenr		}
310692685Sdarrenr
310792685Sdarrenr		if (is != NULL) {
3108145522Sdarrenr			if ((tryagain != 0) && !(is->is_flags & SI_W_DADDR)) {
310992685Sdarrenr				hv += fin->fin_fi.fi_src.i6[0];
311092685Sdarrenr				hv += fin->fin_fi.fi_src.i6[1];
311192685Sdarrenr				hv += fin->fin_fi.fi_src.i6[2];
311292685Sdarrenr				hv += fin->fin_fi.fi_src.i6[3];
3113255332Scy				ipf_ipsmove(softs, is, hv);
3114255332Scy				MUTEX_DOWNGRADE(&softc->ipf_state);
311592685Sdarrenr			}
311692685Sdarrenr			break;
311792685Sdarrenr		}
3118255332Scy		RWLOCK_EXIT(&softc->ipf_state);
311992685Sdarrenr
312092685Sdarrenr		/*
312192685Sdarrenr		 * No matching icmp state entry. Perhaps this is a
312292685Sdarrenr		 * response to another state entry.
3123145522Sdarrenr		 *
3124145522Sdarrenr		 * XXX With some ICMP6 packets, the "other" address is already
3125145522Sdarrenr		 * in the packet, after the ICMP6 header, and this could be
3126145522Sdarrenr		 * used in place of the multicast address.  However, taking
3127145522Sdarrenr		 * advantage of this requires some significant code changes
3128145522Sdarrenr		 * to handle the specific types where that is the case.
312992685Sdarrenr		 */
3130255332Scy		if ((softs->ipf_state_stats.iss_wild != 0) &&
3131255332Scy		    ((fin->fin_flx & FI_NOWILD) == 0) &&
3132255332Scy		    (v == 6) && (tryagain == 0)) {
313392685Sdarrenr			hv -= fin->fin_fi.fi_src.i6[0];
313492685Sdarrenr			hv -= fin->fin_fi.fi_src.i6[1];
313592685Sdarrenr			hv -= fin->fin_fi.fi_src.i6[2];
313692685Sdarrenr			hv -= fin->fin_fi.fi_src.i6[3];
313792685Sdarrenr			tryagain = 1;
3138255332Scy			WRITE_ENTER(&softc->ipf_state);
313992685Sdarrenr			goto icmp6again;
314092685Sdarrenr		}
314192685Sdarrenr
3142255332Scy		is = ipf_checkicmp6matchingstate(fin);
3143145522Sdarrenr		if (is != NULL)
3144145522Sdarrenr			return is;
314592685Sdarrenr		break;
314660854Sdarrenr#endif
3147145522Sdarrenr
314853642Sguido	case IPPROTO_ICMP :
314960854Sdarrenr		if (v == 4) {
315055929Sguido			hv += ic->icmp_id;
315155929Sguido		}
3152145522Sdarrenr		hv = DOUBLE_HASH(hv);
3153255332Scy		READ_ENTER(&softc->ipf_state);
3154255332Scy		for (isp = &softs->ipf_state_table[hv];
3155255332Scy		     ((is = *isp) != NULL); ) {
3156145522Sdarrenr			isp = &is->is_hnext;
3157145522Sdarrenr			if ((is->is_p != pr) || (is->is_v != v))
3158145522Sdarrenr				continue;
3159255332Scy			is = ipf_matchsrcdst(fin, is, &src, &dst, NULL, FI_CMP);
3160161356Sguido			if ((is != NULL) &&
3161161356Sguido			    (ic->icmp_id == is->is_icmp.ici_id) &&
3162255332Scy			    ipf_matchicmpqueryreply(v, &is->is_icmp,
3163145522Sdarrenr						   ic, fin->fin_rev)) {
3164145522Sdarrenr				if (fin->fin_rev)
3165255332Scy					ifq = &softs->ipf_state_icmpacktq;
316680482Sdarrenr				else
3167255332Scy					ifq = &softs->ipf_state_icmptq;
316853642Sguido				break;
316953642Sguido			}
3170145522Sdarrenr		}
3171145522Sdarrenr		if (is == NULL) {
3172255332Scy			RWLOCK_EXIT(&softc->ipf_state);
3173145522Sdarrenr		}
3174145522Sdarrenr		break;
317592685Sdarrenr
317653642Sguido	case IPPROTO_TCP :
317767614Sdarrenr	case IPPROTO_UDP :
3178145522Sdarrenr		ifqp = NULL;
3179145522Sdarrenr		sport = htons(fin->fin_data[0]);
3180145522Sdarrenr		hv += sport;
3181145522Sdarrenr		dport = htons(fin->fin_data[1]);
3182145522Sdarrenr		hv += dport;
3183145522Sdarrenr		oow = 0;
318453642Sguido		tryagain = 0;
3185255332Scy		READ_ENTER(&softc->ipf_state);
318667614Sdarrenrretry_tcpudp:
3187145522Sdarrenr		hvm = DOUBLE_HASH(hv);
3188255332Scy
3189255332Scy		/* TRACE hv, hvm */
3190255332Scy
3191255332Scy		for (isp = &softs->ipf_state_table[hvm];
3192255332Scy		     ((is = *isp) != NULL); ) {
3193145522Sdarrenr			isp = &is->is_hnext;
3194145522Sdarrenr			if ((is->is_p != pr) || (is->is_v != v))
3195145522Sdarrenr				continue;
3196145522Sdarrenr			fin->fin_flx &= ~FI_OOW;
3197255332Scy			is = ipf_matchsrcdst(fin, is, &src, &dst, tcp, FI_CMP);
3198145522Sdarrenr			if (is != NULL) {
3199145522Sdarrenr				if (pr == IPPROTO_TCP) {
3200255332Scy					if (!ipf_state_tcp(softc, softs, fin,
3201255332Scy							   tcp, is)) {
3202145522Sdarrenr						oow |= fin->fin_flx & FI_OOW;
3203145522Sdarrenr						continue;
3204145522Sdarrenr					}
320567614Sdarrenr				}
320653642Sguido				break;
320753642Sguido			}
3208145522Sdarrenr		}
320967614Sdarrenr		if (is != NULL) {
321067614Sdarrenr			if (tryagain &&
3211145522Sdarrenr			    !(is->is_flags & (SI_CLONE|SI_WILDP|SI_WILDA))) {
321267614Sdarrenr				hv += dport;
321367614Sdarrenr				hv += sport;
3214255332Scy				ipf_ipsmove(softs, is, hv);
3215255332Scy				MUTEX_DOWNGRADE(&softc->ipf_state);
321667614Sdarrenr			}
321753642Sguido			break;
321867614Sdarrenr		}
3219255332Scy		RWLOCK_EXIT(&softc->ipf_state);
322095418Sdarrenr
3221255332Scy		if ((softs->ipf_state_stats.iss_wild != 0) &&
3222255332Scy		    ((fin->fin_flx & FI_NOWILD) == 0)) {
3223172776Sdarrenr			if (tryagain == 0) {
3224172776Sdarrenr				hv -= dport;
3225172776Sdarrenr				hv -= sport;
3226172776Sdarrenr			} else if (tryagain == 1) {
3227172776Sdarrenr				hv = fin->fin_fi.fi_p;
3228172776Sdarrenr				/*
3229172776Sdarrenr				 * If we try to pretend this is a reply to a
3230172776Sdarrenr				 * multicast/broadcast packet then we need to
3231172776Sdarrenr				 * exclude part of the address from the hash
3232172776Sdarrenr				 * calculation.
3233172776Sdarrenr				 */
3234172776Sdarrenr				if (fin->fin_out == 0) {
3235172776Sdarrenr					hv += src.in4.s_addr;
3236172776Sdarrenr				} else {
3237172776Sdarrenr					hv += dst.in4.s_addr;
3238172776Sdarrenr				}
3239172776Sdarrenr				hv += dport;
3240172776Sdarrenr				hv += sport;
3241172776Sdarrenr			}
3242172776Sdarrenr			tryagain++;
3243172776Sdarrenr			if (tryagain <= 2) {
3244255332Scy				WRITE_ENTER(&softc->ipf_state);
3245172776Sdarrenr				goto retry_tcpudp;
3246172776Sdarrenr			}
324753642Sguido		}
3248145522Sdarrenr		fin->fin_flx |= oow;
324953642Sguido		break;
3250145522Sdarrenr
3251145522Sdarrenr#if 0
3252145522Sdarrenr	case IPPROTO_GRE :
3253145522Sdarrenr		gre = fin->fin_dp;
3254145522Sdarrenr		if (GRE_REV(gre->gr_flags) == 1) {
3255145522Sdarrenr			hv += gre->gr_call;
3256145522Sdarrenr		}
3257145522Sdarrenr		/* FALLTHROUGH */
3258145522Sdarrenr#endif
325953642Sguido	default :
3260145522Sdarrenr		ifqp = NULL;
3261145522Sdarrenr		hvm = DOUBLE_HASH(hv);
3262255332Scy		READ_ENTER(&softc->ipf_state);
3263255332Scy		for (isp = &softs->ipf_state_table[hvm];
3264255332Scy		     ((is = *isp) != NULL); ) {
3265145522Sdarrenr			isp = &is->is_hnext;
3266145522Sdarrenr			if ((is->is_p != pr) || (is->is_v != v))
3267145522Sdarrenr				continue;
3268255332Scy			is = ipf_matchsrcdst(fin, is, &src, &dst, NULL, FI_CMP);
3269145522Sdarrenr			if (is != NULL) {
3270255332Scy				ifq = &softs->ipf_state_iptq;
327192685Sdarrenr				break;
327292685Sdarrenr			}
327392685Sdarrenr		}
327492685Sdarrenr		if (is == NULL) {
3275255332Scy			RWLOCK_EXIT(&softc->ipf_state);
327692685Sdarrenr		}
327753642Sguido		break;
327853642Sguido	}
327992685Sdarrenr
3280161356Sguido	if (is != NULL) {
3281161356Sguido		if (((is->is_sti.tqe_flags & TQE_RULEBASED) != 0) &&
3282161356Sguido		    (is->is_tqehead[fin->fin_rev] != NULL))
3283161356Sguido			ifq = is->is_tqehead[fin->fin_rev];
3284161356Sguido		if (ifq != NULL && ifqp != NULL)
3285161356Sguido			*ifqp = ifq;
3286255332Scy	} else {
3287255332Scy		SBUMP(ipf_state_stats.iss_lookup_miss);
3288161356Sguido	}
3289145522Sdarrenr	return is;
3290145522Sdarrenr}
3291145522Sdarrenr
3292145522Sdarrenr
3293145522Sdarrenr/* ------------------------------------------------------------------------ */
3294255332Scy/* Function:    ipf_state_check                                             */
3295145522Sdarrenr/* Returns:     frentry_t* - NULL == search failed,                         */
3296145522Sdarrenr/*                           else pointer to rule for matching state        */
3297255332Scy/* Parameters:  fin(I)   - pointer to packet information                    */
3298145522Sdarrenr/*              passp(I) - pointer to filtering result flags                */
3299145522Sdarrenr/*                                                                          */
3300145522Sdarrenr/* Check if a packet is associated with an entry in the state table.        */
3301145522Sdarrenr/* ------------------------------------------------------------------------ */
3302255332Scyfrentry_t *
3303255332Scyipf_state_check(fin, passp)
3304255332Scy	fr_info_t *fin;
3305255332Scy	u_32_t *passp;
3306145522Sdarrenr{
3307255332Scy	ipf_main_softc_t *softc = fin->fin_main_soft;
3308255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
3309255332Scy	ipftqent_t *tqe;
3310145522Sdarrenr	ipstate_t *is;
3311145522Sdarrenr	frentry_t *fr;
3312145522Sdarrenr	tcphdr_t *tcp;
3313145522Sdarrenr	ipftq_t *ifq;
3314145522Sdarrenr	u_int pass;
3315255332Scy	int inout;
3316145522Sdarrenr
3317255332Scy	if (softs->ipf_state_lock || (softs->ipf_state_list == NULL))
3318145522Sdarrenr		return NULL;
3319145522Sdarrenr
3320255332Scy	if (fin->fin_flx & (FI_SHORT|FI_FRAGBODY|FI_BAD)) {
3321255332Scy		SBUMPD(ipf_state_stats, iss_check_bad);
3322255332Scy		return NULL;
3323255332Scy	}
3324255332Scy
3325145522Sdarrenr	if ((fin->fin_flx & FI_TCPUDP) ||
3326145522Sdarrenr	    (fin->fin_fi.fi_p == IPPROTO_ICMP)
3327145522Sdarrenr#ifdef	USE_INET6
3328145522Sdarrenr	    || (fin->fin_fi.fi_p == IPPROTO_ICMPV6)
3329145522Sdarrenr#endif
3330145522Sdarrenr	    )
3331145522Sdarrenr		tcp = fin->fin_dp;
3332145522Sdarrenr	else
3333145522Sdarrenr		tcp = NULL;
3334145522Sdarrenr
3335255332Scy	ifq = NULL;
3336145522Sdarrenr	/*
3337145522Sdarrenr	 * Search the hash table for matching packet header info.
3338145522Sdarrenr	 */
3339255332Scy	is = ipf_state_lookup(fin, tcp, &ifq);
3340255332Scy
3341145522Sdarrenr	switch (fin->fin_p)
3342145522Sdarrenr	{
3343145522Sdarrenr#ifdef	USE_INET6
3344145522Sdarrenr	case IPPROTO_ICMPV6 :
3345145522Sdarrenr		if (is != NULL)
3346145522Sdarrenr			break;
3347145522Sdarrenr		if (fin->fin_v == 6) {
3348255332Scy			is = ipf_checkicmp6matchingstate(fin);
3349145522Sdarrenr		}
3350145522Sdarrenr		break;
3351145522Sdarrenr#endif
3352145522Sdarrenr	case IPPROTO_ICMP :
3353145522Sdarrenr		if (is != NULL)
3354145522Sdarrenr			break;
3355145522Sdarrenr		/*
3356145522Sdarrenr		 * No matching icmp state entry. Perhaps this is a
3357145522Sdarrenr		 * response to another state entry.
3358145522Sdarrenr		 */
3359255332Scy		is = ipf_checkicmpmatchingstate(fin);
3360145522Sdarrenr		break;
3361255332Scy
3362145522Sdarrenr	case IPPROTO_TCP :
3363145522Sdarrenr		if (is == NULL)
3364145522Sdarrenr			break;
3365145522Sdarrenr
3366145522Sdarrenr		if (is->is_pass & FR_NEWISN) {
3367145522Sdarrenr			if (fin->fin_out == 0)
3368255332Scy				ipf_fixinisn(fin, is);
3369145522Sdarrenr			else if (fin->fin_out == 1)
3370255332Scy				ipf_fixoutisn(fin, is);
3371145522Sdarrenr		}
3372145522Sdarrenr		break;
3373145522Sdarrenr	default :
3374145522Sdarrenr		if (fin->fin_rev)
3375255332Scy			ifq = &softs->ipf_state_udpacktq;
3376145522Sdarrenr		else
3377255332Scy			ifq = &softs->ipf_state_udptq;
3378145522Sdarrenr		break;
3379145522Sdarrenr	}
338053642Sguido	if (is == NULL) {
3381255332Scy		SBUMP(ipf_state_stats.iss_check_miss);
338253642Sguido		return NULL;
338353642Sguido	}
338492685Sdarrenr
338553642Sguido	fr = is->is_rule;
338692685Sdarrenr	if (fr != NULL) {
3387145522Sdarrenr		if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
3388255332Scy			if (fin->fin_nattag == NULL) {
3389255332Scy				RWLOCK_EXIT(&softc->ipf_state);
3390255332Scy				SBUMPD(ipf_state_stats, iss_check_notag);
3391145522Sdarrenr				return NULL;
3392255332Scy			}
3393255332Scy			if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag)!=0) {
3394255332Scy				RWLOCK_EXIT(&softc->ipf_state);
3395255332Scy				SBUMPD(ipf_state_stats, iss_check_nattag);
3396145522Sdarrenr				return NULL;
3397255332Scy			}
3398145522Sdarrenr		}
3399255332Scy		(void) strncpy(fin->fin_group, FR_NAME(fr, fr_group),
3400255332Scy			       FR_GROUPLEN);
340192685Sdarrenr		fin->fin_icode = fr->fr_icode;
340292685Sdarrenr	}
3403145522Sdarrenr
3404145522Sdarrenr	fin->fin_rule = is->is_rulen;
3405255332Scy	fin->fin_fr = fr;
3406145522Sdarrenr
3407255332Scy	/*
3408255332Scy	 * If this packet is a fragment and the rule says to track fragments,
3409255332Scy	 * then create a new fragment cache entry.
3410255332Scy	 */
3411255332Scy	if ((fin->fin_flx & FI_FRAG) && FR_ISPASS(is->is_pass))
3412255332Scy		(void) ipf_frag_new(softc, fin, is->is_pass);
3413255332Scy
3414255332Scy	/*
3415255332Scy	 * For TCP packets, ifq == NULL.  For all others, check if this new
3416255332Scy	 * queue is different to the last one it was on and move it if so.
3417255332Scy	 */
3418255332Scy	tqe = &is->is_sti;
3419255332Scy	if ((tqe->tqe_flags & TQE_RULEBASED) != 0)
3420255332Scy		ifq = is->is_tqehead[fin->fin_rev];
3421255332Scy
3422145522Sdarrenr	MUTEX_ENTER(&is->is_lock);
3423255332Scy
3424255332Scy	if (ifq != NULL)
3425255332Scy		ipf_movequeue(softc->ipf_ticks, tqe, tqe->tqe_ifq, ifq);
3426255332Scy
3427255332Scy	inout = (fin->fin_rev << 1) + fin->fin_out;
3428255332Scy	is->is_pkts[inout]++;
3429255332Scy	is->is_bytes[inout] += fin->fin_plen;
3430255332Scy	fin->fin_pktnum = is->is_pkts[inout] + is->is_icmppkts[inout];
3431255332Scy
3432145522Sdarrenr	MUTEX_EXIT(&is->is_lock);
3433255332Scy
3434255332Scy	pass = is->is_pass;
3435255332Scy
3436255332Scy	if (is->is_flags & IS_STATESYNC)
3437255332Scy		ipf_sync_update(softc, SMC_STATE, fin, is->is_sync);
3438255332Scy
3439255332Scy	RWLOCK_EXIT(&softc->ipf_state);
3440255332Scy
3441255332Scy	SBUMP(ipf_state_stats.iss_hits);
3442255332Scy
3443255332Scy	fin->fin_dif = &is->is_dif;
3444255332Scy	fin->fin_tif = &is->is_tifs[fin->fin_rev];
3445145522Sdarrenr	fin->fin_flx |= FI_STATE;
3446145522Sdarrenr	if ((pass & FR_LOGFIRST) != 0)
3447145522Sdarrenr		pass &= ~(FR_LOGFIRST|FR_LOG);
3448145522Sdarrenr	*passp = pass;
344953642Sguido	return fr;
345053642Sguido}
345153642Sguido
345253642Sguido
3453145522Sdarrenr/* ------------------------------------------------------------------------ */
3454255332Scy/* Function:    ipf_fixoutisn                                               */
3455145522Sdarrenr/* Returns:     Nil                                                         */
3456255332Scy/* Parameters:  fin(I) - pointer to packet information                      */
3457145522Sdarrenr/*              is(I)  - pointer to master state structure                  */
3458145522Sdarrenr/*                                                                          */
3459145522Sdarrenr/* Called only for outbound packets, adjusts the sequence number and the    */
3460145522Sdarrenr/* TCP checksum to match that change.                                       */
3461145522Sdarrenr/* ------------------------------------------------------------------------ */
3462255332Scystatic void
3463255332Scyipf_fixoutisn(fin, is)
3464255332Scy	fr_info_t *fin;
3465255332Scy	ipstate_t *is;
3466145522Sdarrenr{
3467145522Sdarrenr	tcphdr_t *tcp;
3468145522Sdarrenr	int rev;
3469145522Sdarrenr	u_32_t seq;
3470145522Sdarrenr
3471145522Sdarrenr	tcp = fin->fin_dp;
3472145522Sdarrenr	rev = fin->fin_rev;
3473145522Sdarrenr	if ((is->is_flags & IS_ISNSYN) != 0) {
3474255332Scy		if ((rev == 0) && (fin->fin_cksum < FI_CK_L4PART)) {
3475145522Sdarrenr			seq = ntohl(tcp->th_seq);
3476145522Sdarrenr			seq += is->is_isninc[0];
3477145522Sdarrenr			tcp->th_seq = htonl(seq);
3478255332Scy			ipf_fix_outcksum(0, &tcp->th_sum, is->is_sumd[0], 0);
3479145522Sdarrenr		}
3480145522Sdarrenr	}
3481145522Sdarrenr	if ((is->is_flags & IS_ISNACK) != 0) {
3482255332Scy		if ((rev == 1) && (fin->fin_cksum < FI_CK_L4PART)) {
3483145522Sdarrenr			seq = ntohl(tcp->th_seq);
3484145522Sdarrenr			seq += is->is_isninc[1];
3485145522Sdarrenr			tcp->th_seq = htonl(seq);
3486255332Scy			ipf_fix_outcksum(0, &tcp->th_sum, is->is_sumd[1], 0);
3487145522Sdarrenr		}
3488145522Sdarrenr	}
3489145522Sdarrenr}
3490145522Sdarrenr
3491145522Sdarrenr
3492145522Sdarrenr/* ------------------------------------------------------------------------ */
3493255332Scy/* Function:    ipf_fixinisn                                                */
3494145522Sdarrenr/* Returns:     Nil                                                         */
3495145522Sdarrenr/* Parameters:  fin(I)   - pointer to packet information                    */
3496145522Sdarrenr/*              is(I)  - pointer to master state structure                  */
3497145522Sdarrenr/*                                                                          */
3498145522Sdarrenr/* Called only for inbound packets, adjusts the acknowledge number and the  */
3499145522Sdarrenr/* TCP checksum to match that change.                                       */
3500145522Sdarrenr/* ------------------------------------------------------------------------ */
3501255332Scystatic void
3502255332Scyipf_fixinisn(fin, is)
3503255332Scy	fr_info_t *fin;
3504255332Scy	ipstate_t *is;
3505145522Sdarrenr{
3506145522Sdarrenr	tcphdr_t *tcp;
3507145522Sdarrenr	int rev;
3508145522Sdarrenr	u_32_t ack;
3509145522Sdarrenr
3510145522Sdarrenr	tcp = fin->fin_dp;
3511145522Sdarrenr	rev = fin->fin_rev;
3512145522Sdarrenr	if ((is->is_flags & IS_ISNSYN) != 0) {
3513255332Scy		if ((rev == 1) && (fin->fin_cksum < FI_CK_L4PART)) {
3514145522Sdarrenr			ack = ntohl(tcp->th_ack);
3515145522Sdarrenr			ack -= is->is_isninc[0];
3516145522Sdarrenr			tcp->th_ack = htonl(ack);
3517255332Scy			ipf_fix_incksum(0, &tcp->th_sum, is->is_sumd[0], 0);
3518145522Sdarrenr		}
3519145522Sdarrenr	}
3520145522Sdarrenr	if ((is->is_flags & IS_ISNACK) != 0) {
3521255332Scy		if ((rev == 0) && (fin->fin_cksum < FI_CK_L4PART)) {
3522145522Sdarrenr			ack = ntohl(tcp->th_ack);
3523145522Sdarrenr			ack -= is->is_isninc[1];
3524145522Sdarrenr			tcp->th_ack = htonl(ack);
3525255332Scy			ipf_fix_incksum(0, &tcp->th_sum, is->is_sumd[1], 0);
3526145522Sdarrenr		}
3527145522Sdarrenr	}
3528145522Sdarrenr}
3529145522Sdarrenr
3530145522Sdarrenr
3531145522Sdarrenr/* ------------------------------------------------------------------------ */
3532255332Scy/* Function:    ipf_state_sync                                              */
3533145522Sdarrenr/* Returns:     Nil                                                         */
3534255332Scy/* Parameters:  softc(I) - pointer to soft context main structure           */
3535255332Scy/*              ifp(I)   - pointer to interface                             */
3536145522Sdarrenr/*                                                                          */
3537145522Sdarrenr/* Walk through all state entries and if an interface pointer match is      */
3538145522Sdarrenr/* found then look it up again, based on its name in case the pointer has   */
3539145522Sdarrenr/* changed since last time.                                                 */
3540145522Sdarrenr/*                                                                          */
3541145522Sdarrenr/* If ifp is passed in as being non-null then we are only doing updates for */
3542145522Sdarrenr/* existing, matching, uses of it.                                          */
3543145522Sdarrenr/* ------------------------------------------------------------------------ */
3544255332Scyvoid
3545255332Scyipf_state_sync(softc, ifp)
3546255332Scy	ipf_main_softc_t *softc;
3547255332Scy	void *ifp;
354860854Sdarrenr{
3549255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
3550145522Sdarrenr	ipstate_t *is;
355192685Sdarrenr	int i;
355260854Sdarrenr
3553255332Scy	if (softc->ipf_running <= 0)
3554145522Sdarrenr		return;
3555145522Sdarrenr
3556255332Scy	WRITE_ENTER(&softc->ipf_state);
3557145522Sdarrenr
3558255332Scy	if (softc->ipf_running <= 0) {
3559255332Scy		RWLOCK_EXIT(&softc->ipf_state);
3560145522Sdarrenr		return;
3561145522Sdarrenr	}
3562145522Sdarrenr
3563255332Scy	for (is = softs->ipf_state_list; is; is = is->is_next) {
3564145522Sdarrenr		/*
3565145522Sdarrenr		 * Look up all the interface names in the state entry.
3566145522Sdarrenr		 */
356792685Sdarrenr		for (i = 0; i < 4; i++) {
3568145522Sdarrenr			if (ifp == NULL || ifp == is->is_ifp[i])
3569255332Scy				is->is_ifp[i] = ipf_resolvenic(softc,
3570255332Scy							      is->is_ifname[i],
3571145522Sdarrenr							      is->is_v);
357260854Sdarrenr		}
357360854Sdarrenr	}
3574255332Scy	RWLOCK_EXIT(&softc->ipf_state);
357560854Sdarrenr}
357660854Sdarrenr
357760854Sdarrenr
3578145522Sdarrenr/* ------------------------------------------------------------------------ */
3579255332Scy/* Function:    ipf_state_del                                               */
3580255332Scy/* Returns:     int    - 0 = deleted, else refernce count on active struct  */
3581255332Scy/* Parameters:  softc(I) - pointer to soft context main structure           */
3582255332Scy/*              is(I)  - pointer to state structure to delete               */
3583145522Sdarrenr/*              why(I) - if not 0, log reason why it was deleted            */
3584145522Sdarrenr/* Write Locks: ipf_state                                                   */
3585145522Sdarrenr/*                                                                          */
3586145522Sdarrenr/* Deletes a state entry from the enumerated list as well as the hash table */
3587145522Sdarrenr/* and timeout queue lists.  Make adjustments to hash table statistics and  */
3588145522Sdarrenr/* global counters as required.                                             */
3589145522Sdarrenr/* ------------------------------------------------------------------------ */
3590255332Scystatic int
3591255332Scyipf_state_del(softc, is, why)
3592255332Scy	ipf_main_softc_t *softc;
3593255332Scy	ipstate_t *is;
3594255332Scy	int why;
359553642Sguido{
3596255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
3597255332Scy	int orphan = 1;
3598255332Scy	frentry_t *fr;
359953642Sguido
3600145522Sdarrenr	/*
3601145522Sdarrenr	 * Since we want to delete this, remove it from the state table,
3602145522Sdarrenr	 * where it can be found & used, first.
3603145522Sdarrenr	 */
3604145522Sdarrenr	if (is->is_phnext != NULL) {
3605145522Sdarrenr		*is->is_phnext = is->is_hnext;
3606145522Sdarrenr		if (is->is_hnext != NULL)
3607145522Sdarrenr			is->is_hnext->is_phnext = is->is_phnext;
3608255332Scy		if (softs->ipf_state_table[is->is_hv] == NULL)
3609255332Scy			softs->ipf_state_stats.iss_inuse--;
3610255332Scy		softs->ipf_state_stats.iss_bucketlen[is->is_hv]--;
3611145522Sdarrenr
3612145522Sdarrenr		is->is_phnext = NULL;
3613145522Sdarrenr		is->is_hnext = NULL;
3614255332Scy		orphan = 0;
3615145522Sdarrenr	}
3616145522Sdarrenr
3617145522Sdarrenr	/*
3618255332Scy	 * Because ipf_state_stats.iss_wild is a count of entries in the state
3619145522Sdarrenr	 * table that have wildcard flags set, only decerement it once
3620145522Sdarrenr	 * and do it here.
3621145522Sdarrenr	 */
3622145522Sdarrenr	if (is->is_flags & (SI_WILDP|SI_WILDA)) {
3623145522Sdarrenr		if (!(is->is_flags & SI_CLONED)) {
3624255332Scy			ATOMIC_DECL(softs->ipf_state_stats.iss_wild);
362572006Sdarrenr		}
3626145522Sdarrenr		is->is_flags &= ~(SI_WILDP|SI_WILDA);
362753642Sguido	}
3628145522Sdarrenr
3629145522Sdarrenr	/*
3630145522Sdarrenr	 * Next, remove it from the timeout queue it is in.
3631145522Sdarrenr	 */
3632170268Sdarrenr	if (is->is_sti.tqe_ifq != NULL)
3633255332Scy		ipf_deletequeueentry(&is->is_sti);
3634145522Sdarrenr
3635145522Sdarrenr	/*
3636145522Sdarrenr	 * If it is still in use by something else, do not go any further,
3637170268Sdarrenr	 * but note that at this point it is now an orphan.  How can this
3638255332Scy	 * be?  ipf_state_flush() calls ipf_delete() directly because it wants
3639170268Sdarrenr	 * to empty the table out and if something has a hold on a state
3640170268Sdarrenr	 * entry (such as ipfstat), it'll do the deref path that'll bring
3641170268Sdarrenr	 * us back here to do the real delete & free.
3642145522Sdarrenr	 */
3643172776Sdarrenr	MUTEX_ENTER(&is->is_lock);
3644255332Scy	if (is->is_me != NULL) {
3645255332Scy		*is->is_me = NULL;
3646255332Scy		is->is_me = NULL;
3647255332Scy		is->is_ref--;
3648255332Scy	}
3649288250Scy	is->is_ref--;
3650288250Scy	if (is->is_ref > 0) {
3651255332Scy		int refs;
3652255332Scy
3653255332Scy		refs = is->is_ref;
3654172776Sdarrenr		MUTEX_EXIT(&is->is_lock);
3655255332Scy		if (!orphan)
3656255332Scy			softs->ipf_state_stats.iss_orphan++;
3657255332Scy		return refs;
3658172776Sdarrenr	}
3659145522Sdarrenr
3660255332Scy	fr = is->is_rule;
3661255332Scy	is->is_rule = NULL;
3662255332Scy	if (fr != NULL) {
3663255332Scy		if (fr->fr_srctrack.ht_max_nodes != 0) {
3664255332Scy			(void) ipf_ht_node_del(&fr->fr_srctrack,
3665255332Scy					       is->is_family, &is->is_src);
3666255332Scy		}
3667255332Scy	}
3668255332Scy
3669289628Scy	ASSERT(is->is_ref == 0);
3670287984Scy	MUTEX_EXIT(&is->is_lock);
3671172776Sdarrenr
3672145522Sdarrenr	if (is->is_tqehead[0] != NULL) {
3673255332Scy		if (ipf_deletetimeoutqueue(is->is_tqehead[0]) == 0)
3674255332Scy			ipf_freetimeoutqueue(softc, is->is_tqehead[0]);
3675145522Sdarrenr	}
3676145522Sdarrenr	if (is->is_tqehead[1] != NULL) {
3677255332Scy		if (ipf_deletetimeoutqueue(is->is_tqehead[1]) == 0)
3678255332Scy			ipf_freetimeoutqueue(softc, is->is_tqehead[1]);
3679145522Sdarrenr	}
3680145522Sdarrenr
3681145522Sdarrenr	if (is->is_sync)
3682255332Scy		ipf_sync_del_state(softc->ipf_sync_soft, is->is_sync);
3683145522Sdarrenr
3684170268Sdarrenr	/*
3685170268Sdarrenr	 * Now remove it from the linked list of known states
3686170268Sdarrenr	 */
3687170268Sdarrenr	if (is->is_pnext != NULL) {
3688170268Sdarrenr		*is->is_pnext = is->is_next;
3689170268Sdarrenr
3690170268Sdarrenr		if (is->is_next != NULL)
3691170268Sdarrenr			is->is_next->is_pnext = is->is_pnext;
3692170268Sdarrenr
3693170268Sdarrenr		is->is_pnext = NULL;
3694170268Sdarrenr		is->is_next = NULL;
3695170268Sdarrenr	}
3696170268Sdarrenr
3697255332Scy	if (softs->ipf_state_logging != 0 && why != 0)
3698255332Scy		ipf_state_log(softc, is, why);
3699145522Sdarrenr
3700153876Sguido	if (is->is_p == IPPROTO_TCP)
3701255332Scy		softs->ipf_state_stats.iss_fin++;
3702153876Sguido	else
3703255332Scy		softs->ipf_state_stats.iss_expire++;
3704255332Scy	if (orphan)
3705255332Scy		softs->ipf_state_stats.iss_orphan--;
3706153876Sguido
3707255332Scy	if (fr != NULL) {
3708255332Scy		fr->fr_statecnt--;
3709255332Scy		(void) ipf_derefrule(softc, &fr);
3710145522Sdarrenr	}
3711145522Sdarrenr
3712255332Scy	softs->ipf_state_stats.iss_active_proto[is->is_p]--;
3713180778Sdarrenr
371460854Sdarrenr	MUTEX_DESTROY(&is->is_lock);
371553642Sguido	KFREE(is);
3716255332Scy	softs->ipf_state_stats.iss_active--;
3717170268Sdarrenr
3718170268Sdarrenr	return 0;
371953642Sguido}
372053642Sguido
372153642Sguido
3722145522Sdarrenr/* ------------------------------------------------------------------------ */
3723255332Scy/* Function:    ipf_state_expire                                            */
3724145522Sdarrenr/* Returns:     Nil                                                         */
3725255332Scy/* Parameters:  softc(I) - pointer to soft context main structure           */
3726145522Sdarrenr/*                                                                          */
3727145522Sdarrenr/* Slowly expire held state for thingslike UDP and ICMP.  The algorithm     */
3728145522Sdarrenr/* used here is to keep the queue sorted with the oldest things at the top  */
3729145522Sdarrenr/* and the youngest at the bottom.  So if the top one doesn't need to be    */
3730145522Sdarrenr/* expired then neither will any under it.                                  */
3731145522Sdarrenr/* ------------------------------------------------------------------------ */
3732255332Scyvoid
3733255332Scyipf_state_expire(softc)
3734255332Scy	ipf_main_softc_t *softc;
373553642Sguido{
3736255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
3737145522Sdarrenr	ipftq_t *ifq, *ifqnext;
3738145522Sdarrenr	ipftqent_t *tqe, *tqn;
3739145522Sdarrenr	ipstate_t *is;
3740153876Sguido	SPL_INT(s);
374153642Sguido
3742145522Sdarrenr	SPL_NET(s);
3743255332Scy	WRITE_ENTER(&softc->ipf_state);
3744255332Scy	for (ifq = softs->ipf_state_tcptq; ifq != NULL; ifq = ifq->ifq_next)
3745145522Sdarrenr		for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
3746255332Scy			if (tqe->tqe_die > softc->ipf_ticks)
3747145522Sdarrenr				break;
3748145522Sdarrenr			tqn = tqe->tqe_next;
3749145522Sdarrenr			is = tqe->tqe_parent;
3750255332Scy			ipf_state_del(softc, is, ISL_EXPIRE);
3751145522Sdarrenr		}
3752145522Sdarrenr
3753255332Scy	for (ifq = softs->ipf_state_usertq; ifq != NULL; ifq = ifqnext) {
3754145522Sdarrenr		ifqnext = ifq->ifq_next;
3755145522Sdarrenr
3756145522Sdarrenr		for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
3757255332Scy			if (tqe->tqe_die > softc->ipf_ticks)
3758145522Sdarrenr				break;
3759145522Sdarrenr			tqn = tqe->tqe_next;
3760145522Sdarrenr			is = tqe->tqe_parent;
3761255332Scy			ipf_state_del(softc, is, ISL_EXPIRE);
3762145522Sdarrenr		}
3763145522Sdarrenr	}
3764145522Sdarrenr
3765255332Scy	for (ifq = softs->ipf_state_usertq; ifq != NULL; ifq = ifqnext) {
3766145522Sdarrenr		ifqnext = ifq->ifq_next;
3767145522Sdarrenr
3768145522Sdarrenr		if (((ifq->ifq_flags & IFQF_DELETE) != 0) &&
3769145522Sdarrenr		    (ifq->ifq_ref == 0)) {
3770255332Scy			ipf_freetimeoutqueue(softc, ifq);
3771145522Sdarrenr		}
3772145522Sdarrenr	}
3773145522Sdarrenr
3774255332Scy	if (softs->ipf_state_doflush) {
3775255332Scy		(void) ipf_state_flush(softc, 2, 0);
3776255332Scy		softs->ipf_state_doflush = 0;
3777255332Scy		softs->ipf_state_wm_last = softc->ipf_ticks;
3778145522Sdarrenr	}
3779145522Sdarrenr
3780255332Scy	RWLOCK_EXIT(&softc->ipf_state);
3781145522Sdarrenr	SPL_X(s);
378253642Sguido}
378353642Sguido
378453642Sguido
3785145522Sdarrenr/* ------------------------------------------------------------------------ */
3786255332Scy/* Function:    ipf_state_flush                                             */
3787145522Sdarrenr/* Returns:     int - 0 == success, -1 == failure                           */
3788255332Scy/* Parameters:  softc(I) - pointer to soft context main structure           */
3789255332Scy/*              which(I) - which flush action to perform                    */
3790255332Scy/*              proto(I) - which protocol to flush (0 == ALL)               */
3791145522Sdarrenr/* Write Locks: ipf_state                                                   */
3792145522Sdarrenr/*                                                                          */
3793145522Sdarrenr/* Flush state tables.  Three actions currently defined:                    */
3794145522Sdarrenr/* which == 0 : flush all state table entries                               */
3795145522Sdarrenr/* which == 1 : flush TCP connections which have started to close but are   */
3796145522Sdarrenr/*	      stuck for some reason.                                        */
3797145522Sdarrenr/* which == 2 : flush TCP connections which have been idle for a long time, */
3798145522Sdarrenr/*	      starting at > 4 days idle and working back in successive half-*/
3799145522Sdarrenr/*	      days to at most 12 hours old.  If this fails to free enough   */
3800145522Sdarrenr/*            slots then work backwards in half hour slots to 30 minutes.   */
3801145522Sdarrenr/*            If that too fails, then work backwards in 30 second intervals */
3802145522Sdarrenr/*            for the last 30 minutes to at worst 30 seconds idle.          */
3803145522Sdarrenr/* ------------------------------------------------------------------------ */
3804255332Scyint
3805255332Scyipf_state_flush(softc, which, proto)
3806255332Scy	ipf_main_softc_t *softc;
3807255332Scy	int which, proto;
380853642Sguido{
3809255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
3810145522Sdarrenr	ipftqent_t *tqe, *tqn;
3811145522Sdarrenr	ipstate_t *is, **isp;
3812255332Scy	ipftq_t *ifq;
3813170268Sdarrenr	int removed;
3814153876Sguido	SPL_INT(s);
381553642Sguido
3816145522Sdarrenr	removed = 0;
3817145522Sdarrenr
381853642Sguido	SPL_NET(s);
3819145522Sdarrenr
3820170268Sdarrenr	switch (which)
3821170268Sdarrenr	{
3822170268Sdarrenr	case 0 :
3823255332Scy		SBUMP(ipf_state_stats.iss_flush_all);
3824170268Sdarrenr		/*
3825170268Sdarrenr		 * Style 0 flush removes everything...
3826170268Sdarrenr		 */
3827255332Scy		for (isp = &softs->ipf_state_list; ((is = *isp) != NULL); ) {
3828170268Sdarrenr			if ((proto != 0) && (is->is_v != proto)) {
3829170268Sdarrenr				isp = &is->is_next;
3830170268Sdarrenr				continue;
3831170268Sdarrenr			}
3832255332Scy			if (ipf_state_del(softc, is, ISL_FLUSH) == 0)
3833170268Sdarrenr				removed++;
3834170268Sdarrenr			else
3835170268Sdarrenr				isp = &is->is_next;
3836145522Sdarrenr		}
3837170268Sdarrenr		break;
3838145522Sdarrenr
3839170268Sdarrenr	case 1 :
3840255332Scy		SBUMP(ipf_state_stats.iss_flush_closing);
3841170268Sdarrenr		/*
3842170268Sdarrenr		 * Since we're only interested in things that are closing,
3843170268Sdarrenr		 * we can start with the appropriate timeout queue.
3844170268Sdarrenr		 */
3845255332Scy		for (ifq = softs->ipf_state_tcptq + IPF_TCPS_CLOSE_WAIT;
3846255332Scy		     ifq != NULL; ifq = ifq->ifq_next) {
3847170268Sdarrenr
3848170268Sdarrenr			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
3849170268Sdarrenr				tqn = tqe->tqe_next;
3850170268Sdarrenr				is = tqe->tqe_parent;
3851170268Sdarrenr				if (is->is_p != IPPROTO_TCP)
3852170268Sdarrenr					break;
3853255332Scy				if (ipf_state_del(softc, is, ISL_FLUSH) == 0)
3854170268Sdarrenr					removed++;
3855170268Sdarrenr			}
3856145522Sdarrenr		}
3857145522Sdarrenr
3858170268Sdarrenr		/*
3859170268Sdarrenr		 * Also need to look through the user defined queues.
3860170268Sdarrenr		 */
3861255332Scy		for (ifq = softs->ipf_state_usertq; ifq != NULL;
3862255332Scy		     ifq = ifq->ifq_next) {
3863170268Sdarrenr			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
3864170268Sdarrenr				tqn = tqe->tqe_next;
3865170268Sdarrenr				is = tqe->tqe_parent;
3866170268Sdarrenr				if (is->is_p != IPPROTO_TCP)
3867170268Sdarrenr					continue;
3868170268Sdarrenr
3869170268Sdarrenr				if ((is->is_state[0] > IPF_TCPS_ESTABLISHED) &&
3870170268Sdarrenr				    (is->is_state[1] > IPF_TCPS_ESTABLISHED)) {
3871255332Scy					if (ipf_state_del(softc, is,
3872255332Scy							  ISL_FLUSH) == 0)
3873170268Sdarrenr						removed++;
3874170268Sdarrenr				}
3875170268Sdarrenr			}
3876170268Sdarrenr		}
3877170268Sdarrenr		break;
3878170268Sdarrenr
3879170268Sdarrenr	case 2 :
3880170268Sdarrenr		break;
3881170268Sdarrenr
3882255332Scy		/*
3883170268Sdarrenr		 * Args 5-11 correspond to flushing those particular states
3884170268Sdarrenr		 * for TCP connections.
3885170268Sdarrenr		 */
3886170268Sdarrenr	case IPF_TCPS_CLOSE_WAIT :
3887170268Sdarrenr	case IPF_TCPS_FIN_WAIT_1 :
3888170268Sdarrenr	case IPF_TCPS_CLOSING :
3889170268Sdarrenr	case IPF_TCPS_LAST_ACK :
3890170268Sdarrenr	case IPF_TCPS_FIN_WAIT_2 :
3891170268Sdarrenr	case IPF_TCPS_TIME_WAIT :
3892170268Sdarrenr	case IPF_TCPS_CLOSED :
3893255332Scy		SBUMP(ipf_state_stats.iss_flush_queue);
3894255332Scy		tqn = softs->ipf_state_tcptq[which].ifq_head;
3895170268Sdarrenr		while (tqn != NULL) {
3896170268Sdarrenr			tqe = tqn;
3897170268Sdarrenr			tqn = tqe->tqe_next;
3898170268Sdarrenr			is = tqe->tqe_parent;
3899255332Scy			if (ipf_state_del(softc, is, ISL_FLUSH) == 0)
3900170268Sdarrenr				removed++;
3901170268Sdarrenr		}
3902170268Sdarrenr		break;
3903170268Sdarrenr
3904170268Sdarrenr	default :
3905170268Sdarrenr		if (which < 30)
3906170268Sdarrenr			break;
3907170268Sdarrenr
3908255332Scy		SBUMP(ipf_state_stats.iss_flush_state);
3909255332Scy		/*
3910170268Sdarrenr		 * Take a large arbitrary number to mean the number of seconds
3911170268Sdarrenr		 * for which which consider to be the maximum value we'll allow
3912170268Sdarrenr		 * the expiration to be.
3913170268Sdarrenr		 */
3914170268Sdarrenr		which = IPF_TTLVAL(which);
3915255332Scy		for (isp = &softs->ipf_state_list; ((is = *isp) != NULL); ) {
3916170268Sdarrenr			if ((proto == 0) || (is->is_v == proto)) {
3917255332Scy				if (softc->ipf_ticks - is->is_touched > which) {
3918255332Scy					if (ipf_state_del(softc, is,
3919255332Scy							  ISL_FLUSH) == 0) {
3920170268Sdarrenr						removed++;
3921170268Sdarrenr						continue;
3922170268Sdarrenr					}
3923170268Sdarrenr				}
3924170268Sdarrenr			}
392560854Sdarrenr			isp = &is->is_next;
3926170268Sdarrenr		}
3927170268Sdarrenr		break;
392855929Sguido	}
392953642Sguido
3930145522Sdarrenr	if (which != 2) {
3931145522Sdarrenr		SPL_X(s);
3932145522Sdarrenr		return removed;
3933145522Sdarrenr	}
393453642Sguido
3935255332Scy	SBUMP(ipf_state_stats.iss_flush_timeout);
3936145522Sdarrenr	/*
3937255332Scy	 * Asked to remove inactive entries because the table is full, try
3938255332Scy	 * again, 3 times, if first attempt failed with a different criteria
3939255332Scy	 * each time.  The order tried in must be in decreasing age.
3940255332Scy	 * Another alternative is to implement random drop and drop N entries
3941255332Scy	 * at random until N have been freed up.
3942145522Sdarrenr	 */
3943255332Scy	if (softc->ipf_ticks - softs->ipf_state_wm_last >
3944255332Scy	    softs->ipf_state_wm_freq) {
3945255332Scy		removed = ipf_queueflush(softc, ipf_state_flush_entry,
3946255332Scy					 softs->ipf_state_tcptq,
3947255332Scy					 softs->ipf_state_usertq,
3948255332Scy					 &softs->ipf_state_stats.iss_active,
3949255332Scy					 softs->ipf_state_size,
3950255332Scy					 softs->ipf_state_wm_low);
3951255332Scy		softs->ipf_state_wm_last = softc->ipf_ticks;
3952170268Sdarrenr	}
395353642Sguido
3954145522Sdarrenr	SPL_X(s);
3955145522Sdarrenr	return removed;
3956145522Sdarrenr}
395764580Sdarrenr
395864580Sdarrenr
3959170268Sdarrenr/* ------------------------------------------------------------------------ */
3960255332Scy/* Function:    ipf_state_flush_entry                                       */
3961170268Sdarrenr/* Returns:     int - 0 = entry deleted, else not deleted                   */
3962255332Scy/* Parameters:  softc(I) - pointer to soft context main structure           */
3963255332Scy/*              entry(I)  - pointer to state structure to delete            */
3964170268Sdarrenr/* Write Locks: ipf_state                                                   */
3965170268Sdarrenr/*                                                                          */
3966170268Sdarrenr/* This function is a stepping stone between ipf_queueflush() and           */
3967255332Scy/* ipf_state_del().  It is used so we can provide a uniform interface via   */
3968255332Scy/* the ipf_queueflush() function.                                           */
3969170268Sdarrenr/* ------------------------------------------------------------------------ */
3970255332Scystatic int
3971255332Scyipf_state_flush_entry(softc, entry)
3972255332Scy	ipf_main_softc_t *softc;
3973255332Scy	void *entry;
3974170268Sdarrenr{
3975255332Scy	return ipf_state_del(softc, entry, ISL_FLUSH);
3976255332Scy}
397764580Sdarrenr
3978170268Sdarrenr
3979145522Sdarrenr/* ------------------------------------------------------------------------ */
3980255332Scy/* Function:    ipf_tcp_age                                                 */
3981145522Sdarrenr/* Returns:     int - 1 == state transition made, 0 == no change (rejected) */
3982255332Scy/* Parameters:  tqe(I)   - pointer to timeout queue information             */
3983145522Sdarrenr/*              fin(I)   - pointer to packet information                    */
3984145522Sdarrenr/*              tqtab(I) - TCP timeout queue table this is in               */
3985145522Sdarrenr/*              flags(I) - flags from state/NAT entry                       */
3986255332Scy/*              ok(I)    - can we advance state                             */
3987145522Sdarrenr/*                                                                          */
3988145522Sdarrenr/* Rewritten by Arjan de Vet <Arjan.deVet@adv.iae.nl>, 2000-07-29:          */
3989145522Sdarrenr/*                                                                          */
3990145522Sdarrenr/* - (try to) base state transitions on real evidence only,                 */
3991145522Sdarrenr/*   i.e. packets that are sent and have been received by ipfilter;         */
3992145522Sdarrenr/*   diagram 18.12 of TCP/IP volume 1 by W. Richard Stevens was used.       */
3993145522Sdarrenr/*                                                                          */
3994145522Sdarrenr/* - deal with half-closed connections correctly;                           */
3995145522Sdarrenr/*                                                                          */
3996145522Sdarrenr/* - store the state of the source in state[0] such that ipfstat            */
3997145522Sdarrenr/*   displays the state as source/dest instead of dest/source; the calls    */
3998255332Scy/*   to ipf_tcp_age have been changed accordingly.                          */
3999145522Sdarrenr/*                                                                          */
4000145522Sdarrenr/* Internal Parameters:                                                     */
4001145522Sdarrenr/*                                                                          */
4002145522Sdarrenr/*    state[0] = state of source (host that initiated connection)           */
4003145522Sdarrenr/*    state[1] = state of dest   (host that accepted the connection)        */
4004145522Sdarrenr/*                                                                          */
4005145522Sdarrenr/*    dir == 0 : a packet from source to dest                               */
4006145522Sdarrenr/*    dir == 1 : a packet from dest to source                               */
4007145522Sdarrenr/*                                                                          */
4008170268Sdarrenr/* A typical procession for a connection is as follows:                     */
4009170268Sdarrenr/*                                                                          */
4010170268Sdarrenr/* +--------------+-------------------+                                     */
4011170268Sdarrenr/* | Side '0'     | Side '1'          |                                     */
4012170268Sdarrenr/* +--------------+-------------------+                                     */
4013170268Sdarrenr/* | 0 -> 1 (SYN) |                   |                                     */
4014170268Sdarrenr/* |              | 0 -> 2 (SYN-ACK)  |                                     */
4015170268Sdarrenr/* | 1 -> 3 (ACK) |                   |                                     */
4016170268Sdarrenr/* |              | 2 -> 4 (ACK-PUSH) |                                     */
4017170268Sdarrenr/* | 3 -> 4 (ACK) |                   |                                     */
4018170268Sdarrenr/* |   ...        |   ...             |                                     */
4019170268Sdarrenr/* |              | 4 -> 6 (FIN-ACK)  |                                     */
4020170268Sdarrenr/* | 4 -> 5 (ACK) |                   |                                     */
4021170268Sdarrenr/* |              | 6 -> 6 (ACK-PUSH) |                                     */
4022170268Sdarrenr/* | 5 -> 5 (ACK) |                   |                                     */
4023170268Sdarrenr/* | 5 -> 8 (FIN) |                   |                                     */
4024170268Sdarrenr/* |              | 6 -> 10 (ACK)     |                                     */
4025170268Sdarrenr/* +--------------+-------------------+                                     */
4026170268Sdarrenr/*                                                                          */
4027145522Sdarrenr/* Locking: it is assumed that the parent of the tqe structure is locked.   */
4028145522Sdarrenr/* ------------------------------------------------------------------------ */
4029255332Scyint
4030255332Scyipf_tcp_age(tqe, fin, tqtab, flags, ok)
4031255332Scy	ipftqent_t *tqe;
4032255332Scy	fr_info_t *fin;
4033255332Scy	ipftq_t *tqtab;
4034255332Scy	int flags, ok;
4035145522Sdarrenr{
4036255332Scy	ipf_main_softc_t *softc = fin->fin_main_soft;
4037145522Sdarrenr	int dlen, ostate, nstate, rval, dir;
4038145522Sdarrenr	u_char tcpflags;
4039145522Sdarrenr	tcphdr_t *tcp;
4040145522Sdarrenr
4041145522Sdarrenr	tcp = fin->fin_dp;
4042145522Sdarrenr
4043145522Sdarrenr	rval = 0;
4044145522Sdarrenr	dir = fin->fin_rev;
4045145522Sdarrenr	tcpflags = tcp->th_flags;
4046153876Sguido	dlen = fin->fin_dlen - (TCP_OFF(tcp) << 2);
4047255332Scy	ostate = tqe->tqe_state[1 - dir];
4048255332Scy	nstate = tqe->tqe_state[dir];
4049145522Sdarrenr
4050145522Sdarrenr	if (tcpflags & TH_RST) {
4051145522Sdarrenr		if (!(tcpflags & TH_PUSH) && !dlen)
4052145522Sdarrenr			nstate = IPF_TCPS_CLOSED;
4053145522Sdarrenr		else
4054145522Sdarrenr			nstate = IPF_TCPS_CLOSE_WAIT;
4055255332Scy
4056255332Scy		if (ostate <= IPF_TCPS_ESTABLISHED) {
4057255332Scy			tqe->tqe_state[1 - dir] = IPF_TCPS_CLOSE_WAIT;
4058255332Scy		}
4059145522Sdarrenr		rval = 1;
4060145522Sdarrenr	} else {
4061145522Sdarrenr		switch (nstate)
4062145522Sdarrenr		{
4063170268Sdarrenr		case IPF_TCPS_LISTEN: /* 0 */
4064145522Sdarrenr			if ((tcpflags & TH_OPENING) == TH_OPENING) {
4065145522Sdarrenr				/*
4066145522Sdarrenr				 * 'dir' received an S and sends SA in
4067170268Sdarrenr				 * response, LISTEN -> SYN_RECEIVED
4068145522Sdarrenr				 */
4069145522Sdarrenr				nstate = IPF_TCPS_SYN_RECEIVED;
4070145522Sdarrenr				rval = 1;
4071145522Sdarrenr			} else if ((tcpflags & TH_OPENING) == TH_SYN) {
4072170268Sdarrenr				/* 'dir' sent S, LISTEN -> SYN_SENT */
4073145522Sdarrenr				nstate = IPF_TCPS_SYN_SENT;
4074145522Sdarrenr				rval = 1;
4075145522Sdarrenr			}
407664580Sdarrenr			/*
4077145522Sdarrenr			 * the next piece of code makes it possible to get
4078145522Sdarrenr			 * already established connections into the state table
4079145522Sdarrenr			 * after a restart or reload of the filter rules; this
4080145522Sdarrenr			 * does not work when a strict 'flags S keep state' is
4081145522Sdarrenr			 * used for tcp connections of course
408264580Sdarrenr			 */
4083145522Sdarrenr			if (((flags & IS_TCPFSM) == 0) &&
4084145522Sdarrenr			    ((tcpflags & TH_ACKMASK) == TH_ACK)) {
4085145522Sdarrenr				/*
4086145522Sdarrenr				 * we saw an A, guess 'dir' is in ESTABLISHED
4087145522Sdarrenr				 * mode
4088145522Sdarrenr				 */
4089145522Sdarrenr				switch (ostate)
4090145522Sdarrenr				{
4091170268Sdarrenr				case IPF_TCPS_LISTEN :
4092145522Sdarrenr				case IPF_TCPS_SYN_RECEIVED :
4093145522Sdarrenr					nstate = IPF_TCPS_HALF_ESTAB;
4094145522Sdarrenr					rval = 1;
4095145522Sdarrenr					break;
4096145522Sdarrenr				case IPF_TCPS_HALF_ESTAB :
4097145522Sdarrenr				case IPF_TCPS_ESTABLISHED :
4098145522Sdarrenr					nstate = IPF_TCPS_ESTABLISHED;
4099145522Sdarrenr					rval = 1;
4100145522Sdarrenr					break;
4101145522Sdarrenr				default :
4102145522Sdarrenr					break;
4103145522Sdarrenr				}
4104145522Sdarrenr			}
410595563Sdarrenr			/*
4106145522Sdarrenr			 * TODO: besides regular ACK packets we can have other
4107145522Sdarrenr			 * packets as well; it is yet to be determined how we
4108145522Sdarrenr			 * should initialize the states in those cases
410995563Sdarrenr			 */
4110145522Sdarrenr			break;
411164580Sdarrenr
4112170268Sdarrenr		case IPF_TCPS_SYN_SENT: /* 1 */
4113145522Sdarrenr			if ((tcpflags & ~(TH_ECN|TH_CWR)) == TH_SYN) {
411464580Sdarrenr				/*
4115145522Sdarrenr				 * A retransmitted SYN packet.  We do not reset
4116255332Scy				 * the timeout here to ipf_tcptimeout because a
4117145522Sdarrenr				 * connection connect timeout does not renew
4118145522Sdarrenr				 * after every packet that is sent.  We need to
4119145522Sdarrenr				 * set rval so as to indicate the packet has
4120145522Sdarrenr				 * passed the check for its flags being valid
4121145522Sdarrenr				 * in the TCP FSM.  Setting rval to 2 has the
4122145522Sdarrenr				 * result of not resetting the timeout.
412364580Sdarrenr				 */
4124145522Sdarrenr				rval = 2;
4125145522Sdarrenr			} else if ((tcpflags & (TH_SYN|TH_FIN|TH_ACK)) ==
4126145522Sdarrenr				   TH_ACK) {
412764580Sdarrenr				/*
4128145522Sdarrenr				 * we see an A from 'dir' which is in SYN_SENT
4129145522Sdarrenr				 * state: 'dir' sent an A in response to an SA
4130145522Sdarrenr				 * which it received, SYN_SENT -> ESTABLISHED
413164580Sdarrenr				 */
4132145522Sdarrenr				nstate = IPF_TCPS_ESTABLISHED;
4133145522Sdarrenr				rval = 1;
4134145522Sdarrenr			} else if (tcpflags & TH_FIN) {
4135145522Sdarrenr				/*
4136145522Sdarrenr				 * we see an F from 'dir' which is in SYN_SENT
4137145522Sdarrenr				 * state and wants to close its side of the
4138145522Sdarrenr				 * connection; SYN_SENT -> FIN_WAIT_1
4139145522Sdarrenr				 */
4140145522Sdarrenr				nstate = IPF_TCPS_FIN_WAIT_1;
4141145522Sdarrenr				rval = 1;
4142145522Sdarrenr			} else if ((tcpflags & TH_OPENING) == TH_OPENING) {
4143145522Sdarrenr				/*
4144145522Sdarrenr				 * we see an SA from 'dir' which is already in
4145145522Sdarrenr				 * SYN_SENT state, this means we have a
4146145522Sdarrenr				 * simultaneous open; SYN_SENT -> SYN_RECEIVED
4147145522Sdarrenr				 */
4148145522Sdarrenr				nstate = IPF_TCPS_SYN_RECEIVED;
4149145522Sdarrenr				rval = 1;
4150145522Sdarrenr			}
4151145522Sdarrenr			break;
415264580Sdarrenr
4153170268Sdarrenr		case IPF_TCPS_SYN_RECEIVED: /* 2 */
4154145522Sdarrenr			if ((tcpflags & (TH_SYN|TH_FIN|TH_ACK)) == TH_ACK) {
4155145522Sdarrenr				/*
4156145522Sdarrenr				 * we see an A from 'dir' which was in
4157145522Sdarrenr				 * SYN_RECEIVED state so it must now be in
4158145522Sdarrenr				 * established state, SYN_RECEIVED ->
4159145522Sdarrenr				 * ESTABLISHED
4160145522Sdarrenr				 */
4161145522Sdarrenr				nstate = IPF_TCPS_ESTABLISHED;
4162145522Sdarrenr				rval = 1;
4163145522Sdarrenr			} else if ((tcpflags & ~(TH_ECN|TH_CWR)) ==
4164145522Sdarrenr				   TH_OPENING) {
4165145522Sdarrenr				/*
4166145522Sdarrenr				 * We see an SA from 'dir' which is already in
4167145522Sdarrenr				 * SYN_RECEIVED state.
4168145522Sdarrenr				 */
4169145522Sdarrenr				rval = 2;
4170145522Sdarrenr			} else if (tcpflags & TH_FIN) {
4171145522Sdarrenr				/*
4172145522Sdarrenr				 * we see an F from 'dir' which is in
4173145522Sdarrenr				 * SYN_RECEIVED state and wants to close its
4174145522Sdarrenr				 * side of the connection; SYN_RECEIVED ->
4175145522Sdarrenr				 * FIN_WAIT_1
4176145522Sdarrenr				 */
4177145522Sdarrenr				nstate = IPF_TCPS_FIN_WAIT_1;
4178145522Sdarrenr				rval = 1;
4179145522Sdarrenr			}
4180145522Sdarrenr			break;
418164580Sdarrenr
4182170268Sdarrenr		case IPF_TCPS_HALF_ESTAB: /* 3 */
4183153876Sguido			if (tcpflags & TH_FIN) {
4184153876Sguido				nstate = IPF_TCPS_FIN_WAIT_1;
4185153876Sguido				rval = 1;
4186153876Sguido			} else if ((tcpflags & TH_ACKMASK) == TH_ACK) {
4187153876Sguido				/*
4188153876Sguido				 * If we've picked up a connection in mid
4189153876Sguido				 * flight, we could be looking at a follow on
4190153876Sguido				 * packet from the same direction as the one
4191153876Sguido				 * that created this state.  Recognise it but
4192153876Sguido				 * do not advance the entire connection's
4193153876Sguido				 * state.
4194153876Sguido				 */
4195153876Sguido				switch (ostate)
4196153876Sguido				{
4197170268Sdarrenr				case IPF_TCPS_LISTEN :
4198153876Sguido				case IPF_TCPS_SYN_SENT :
4199153876Sguido				case IPF_TCPS_SYN_RECEIVED :
4200153876Sguido					rval = 1;
4201153876Sguido					break;
4202153876Sguido				case IPF_TCPS_HALF_ESTAB :
4203153876Sguido				case IPF_TCPS_ESTABLISHED :
4204145522Sdarrenr					nstate = IPF_TCPS_ESTABLISHED;
4205145522Sdarrenr					rval = 1;
4206153876Sguido					break;
4207153876Sguido				default :
4208153876Sguido					break;
4209145522Sdarrenr				}
4210145522Sdarrenr			}
4211145522Sdarrenr			break;
421264580Sdarrenr
4213170268Sdarrenr		case IPF_TCPS_ESTABLISHED: /* 4 */
4214145522Sdarrenr			rval = 1;
4215145522Sdarrenr			if (tcpflags & TH_FIN) {
4216145522Sdarrenr				/*
4217145522Sdarrenr				 * 'dir' closed its side of the connection;
4218145522Sdarrenr				 * this gives us a half-closed connection;
4219145522Sdarrenr				 * ESTABLISHED -> FIN_WAIT_1
4220145522Sdarrenr				 */
4221170268Sdarrenr				if (ostate == IPF_TCPS_FIN_WAIT_1) {
4222170268Sdarrenr					nstate = IPF_TCPS_CLOSING;
4223170268Sdarrenr				} else {
4224170268Sdarrenr					nstate = IPF_TCPS_FIN_WAIT_1;
4225170268Sdarrenr				}
4226145522Sdarrenr			} else if (tcpflags & TH_ACK) {
4227145522Sdarrenr				/*
4228145522Sdarrenr				 * an ACK, should we exclude other flags here?
4229145522Sdarrenr				 */
4230145522Sdarrenr				if (ostate == IPF_TCPS_FIN_WAIT_1) {
4231145522Sdarrenr					/*
4232145522Sdarrenr					 * We know the other side did an active
4233145522Sdarrenr					 * close, so we are ACKing the recvd
4234145522Sdarrenr					 * FIN packet (does the window matching
4235145522Sdarrenr					 * code guarantee this?) and go into
4236145522Sdarrenr					 * CLOSE_WAIT state; this gives us a
4237145522Sdarrenr					 * half-closed connection
4238145522Sdarrenr					 */
4239145522Sdarrenr					nstate = IPF_TCPS_CLOSE_WAIT;
4240145522Sdarrenr				} else if (ostate < IPF_TCPS_CLOSE_WAIT) {
4241145522Sdarrenr					/*
4242145522Sdarrenr					 * still a fully established
4243145522Sdarrenr					 * connection reset timeout
4244145522Sdarrenr					 */
4245145522Sdarrenr					nstate = IPF_TCPS_ESTABLISHED;
4246145522Sdarrenr				}
4247145522Sdarrenr			}
4248145522Sdarrenr			break;
424964580Sdarrenr
4250170268Sdarrenr		case IPF_TCPS_CLOSE_WAIT: /* 5 */
4251145522Sdarrenr			rval = 1;
4252145522Sdarrenr			if (tcpflags & TH_FIN) {
425364580Sdarrenr				/*
4254145522Sdarrenr				 * application closed and 'dir' sent a FIN,
4255145522Sdarrenr				 * we're now going into LAST_ACK state
425664580Sdarrenr				 */
4257145522Sdarrenr				nstate = IPF_TCPS_LAST_ACK;
4258145522Sdarrenr			} else {
4259145522Sdarrenr				/*
4260145522Sdarrenr				 * we remain in CLOSE_WAIT because the other
4261145522Sdarrenr				 * side has closed already and we did not
4262145522Sdarrenr				 * close our side yet; reset timeout
4263145522Sdarrenr				 */
4264145522Sdarrenr				nstate = IPF_TCPS_CLOSE_WAIT;
4265145522Sdarrenr			}
4266145522Sdarrenr			break;
426764580Sdarrenr
4268170268Sdarrenr		case IPF_TCPS_FIN_WAIT_1: /* 6 */
4269145522Sdarrenr			rval = 1;
4270145522Sdarrenr			if ((tcpflags & TH_ACK) &&
4271145522Sdarrenr			    ostate > IPF_TCPS_CLOSE_WAIT) {
4272145522Sdarrenr				/*
4273145522Sdarrenr				 * if the other side is not active anymore
4274145522Sdarrenr				 * it has sent us a FIN packet that we are
4275145522Sdarrenr				 * ack'ing now with an ACK; this means both
4276145522Sdarrenr				 * sides have now closed the connection and
4277145522Sdarrenr				 * we go into TIME_WAIT
4278145522Sdarrenr				 */
4279145522Sdarrenr				/*
4280145522Sdarrenr				 * XXX: how do we know we really are ACKing
4281145522Sdarrenr				 * the FIN packet here? does the window code
4282145522Sdarrenr				 * guarantee that?
4283145522Sdarrenr				 */
4284255332Scy				nstate = IPF_TCPS_LAST_ACK;
4285145522Sdarrenr			} else {
4286145522Sdarrenr				/*
4287145522Sdarrenr				 * we closed our side of the connection
4288145522Sdarrenr				 * already but the other side is still active
4289145522Sdarrenr				 * (ESTABLISHED/CLOSE_WAIT); continue with
4290145522Sdarrenr				 * this half-closed connection
4291145522Sdarrenr				 */
4292145522Sdarrenr				nstate = IPF_TCPS_FIN_WAIT_1;
4293145522Sdarrenr			}
4294145522Sdarrenr			break;
429564580Sdarrenr
4296170268Sdarrenr		case IPF_TCPS_CLOSING: /* 7 */
4297170268Sdarrenr			if ((tcpflags & (TH_FIN|TH_ACK)) == TH_ACK) {
4298170268Sdarrenr				nstate = IPF_TCPS_TIME_WAIT;
4299170268Sdarrenr			}
4300255332Scy			rval = 1;
4301145522Sdarrenr			break;
4302145522Sdarrenr
4303170268Sdarrenr		case IPF_TCPS_LAST_ACK: /* 8 */
4304145522Sdarrenr			if (tcpflags & TH_ACK) {
4305255332Scy				rval = 1;
4306145522Sdarrenr			}
4307145522Sdarrenr			/*
4308255332Scy			 * we cannot detect when we go out of LAST_ACK state
4309255332Scy			 * to CLOSED because that is based on the reception
4310255332Scy			 * of ACK packets; ipfilter can only detect that a
4311255332Scy			 * packet has been sent by a host
4312145522Sdarrenr			 */
4313145522Sdarrenr			break;
4314145522Sdarrenr
4315170268Sdarrenr		case IPF_TCPS_FIN_WAIT_2: /* 9 */
4316170268Sdarrenr			/* NOT USED */
4317145522Sdarrenr			break;
4318145522Sdarrenr
4319170268Sdarrenr		case IPF_TCPS_TIME_WAIT: /* 10 */
4320145522Sdarrenr			/* we're in 2MSL timeout now */
4321170268Sdarrenr			if (ostate == IPF_TCPS_LAST_ACK) {
4322170268Sdarrenr				nstate = IPF_TCPS_CLOSED;
4323255332Scy				rval = 1;
4324255332Scy			} else {
4325255332Scy				rval = 2;
4326170268Sdarrenr			}
4327145522Sdarrenr			break;
4328145522Sdarrenr
4329170268Sdarrenr		case IPF_TCPS_CLOSED: /* 11 */
4330170268Sdarrenr			rval = 2;
4331170268Sdarrenr			break;
4332170268Sdarrenr
4333145522Sdarrenr		default :
4334255332Scy#if !defined(_KERNEL)
4335145522Sdarrenr			abort();
4336145522Sdarrenr#endif
4337145522Sdarrenr			break;
4338145522Sdarrenr		}
433953642Sguido	}
434095418Sdarrenr
4341145522Sdarrenr	/*
4342145522Sdarrenr	 * If rval == 2 then do not update the queue position, but treat the
4343145522Sdarrenr	 * packet as being ok.
4344145522Sdarrenr	 */
4345145522Sdarrenr	if (rval == 2)
4346145522Sdarrenr		rval = 1;
4347145522Sdarrenr	else if (rval == 1) {
4348255332Scy		if (ok)
4349255332Scy			tqe->tqe_state[dir] = nstate;
4350145522Sdarrenr		if ((tqe->tqe_flags & TQE_RULEBASED) == 0)
4351255332Scy			ipf_movequeue(softc->ipf_ticks, tqe, tqe->tqe_ifq,
4352255332Scy				      tqtab + nstate);
435395418Sdarrenr	}
4354145522Sdarrenr
4355145522Sdarrenr	return rval;
435653642Sguido}
435753642Sguido
435853642Sguido
4359145522Sdarrenr/* ------------------------------------------------------------------------ */
4360255332Scy/* Function:    ipf_state_log                                               */
4361145522Sdarrenr/* Returns:     Nil                                                         */
4362255332Scy/* Parameters:  softc(I) - pointer to soft context main structure           */
4363255332Scy/*              is(I)    - pointer to state structure                       */
4364255332Scy/*              type(I)  - type of log entry to create                      */
4365145522Sdarrenr/*                                                                          */
4366145522Sdarrenr/* Creates a state table log entry using the state structure and type info. */
4367145522Sdarrenr/* passed in.  Log packet/byte counts, source/destination address and other */
4368145522Sdarrenr/* protocol specific information.                                           */
4369145522Sdarrenr/* ------------------------------------------------------------------------ */
4370255332Scyvoid
4371255332Scyipf_state_log(softc, is, type)
4372255332Scy	ipf_main_softc_t *softc;
4373255332Scy	struct ipstate *is;
4374255332Scy	u_int type;
437553642Sguido{
4376145522Sdarrenr#ifdef	IPFILTER_LOG
437753642Sguido	struct	ipslog	ipsl;
4378145522Sdarrenr	size_t sizes[1];
437953642Sguido	void *items[1];
438053642Sguido	int types[1];
438153642Sguido
4382145522Sdarrenr	/*
4383145522Sdarrenr	 * Copy information out of the ipstate_t structure and into the
4384145522Sdarrenr	 * structure used for logging.
4385145522Sdarrenr	 */
438653642Sguido	ipsl.isl_type = type;
4387145522Sdarrenr	ipsl.isl_pkts[0] = is->is_pkts[0] + is->is_icmppkts[0];
4388145522Sdarrenr	ipsl.isl_bytes[0] = is->is_bytes[0];
4389145522Sdarrenr	ipsl.isl_pkts[1] = is->is_pkts[1] + is->is_icmppkts[1];
4390145522Sdarrenr	ipsl.isl_bytes[1] = is->is_bytes[1];
4391145522Sdarrenr	ipsl.isl_pkts[2] = is->is_pkts[2] + is->is_icmppkts[2];
4392145522Sdarrenr	ipsl.isl_bytes[2] = is->is_bytes[2];
4393145522Sdarrenr	ipsl.isl_pkts[3] = is->is_pkts[3] + is->is_icmppkts[3];
4394145522Sdarrenr	ipsl.isl_bytes[3] = is->is_bytes[3];
439553642Sguido	ipsl.isl_src = is->is_src;
439653642Sguido	ipsl.isl_dst = is->is_dst;
439753642Sguido	ipsl.isl_p = is->is_p;
439860854Sdarrenr	ipsl.isl_v = is->is_v;
439953642Sguido	ipsl.isl_flags = is->is_flags;
4400145522Sdarrenr	ipsl.isl_tag = is->is_tag;
4401102520Sdarrenr	ipsl.isl_rulen = is->is_rulen;
4402145522Sdarrenr	(void) strncpy(ipsl.isl_group, is->is_group, FR_GROUPLEN);
4403145522Sdarrenr
440453642Sguido	if (ipsl.isl_p == IPPROTO_TCP || ipsl.isl_p == IPPROTO_UDP) {
440553642Sguido		ipsl.isl_sport = is->is_sport;
440653642Sguido		ipsl.isl_dport = is->is_dport;
440753642Sguido		if (ipsl.isl_p == IPPROTO_TCP) {
440853642Sguido			ipsl.isl_state[0] = is->is_state[0];
440953642Sguido			ipsl.isl_state[1] = is->is_state[1];
441053642Sguido		}
441192685Sdarrenr	} else if (ipsl.isl_p == IPPROTO_ICMP) {
4412145522Sdarrenr		ipsl.isl_itype = is->is_icmp.ici_type;
441392685Sdarrenr	} else if (ipsl.isl_p == IPPROTO_ICMPV6) {
4414145522Sdarrenr		ipsl.isl_itype = is->is_icmp.ici_type;
441592685Sdarrenr	} else {
441653642Sguido		ipsl.isl_ps.isl_filler[0] = 0;
441753642Sguido		ipsl.isl_ps.isl_filler[1] = 0;
441853642Sguido	}
4419145522Sdarrenr
442053642Sguido	items[0] = &ipsl;
442153642Sguido	sizes[0] = sizeof(ipsl);
442253642Sguido	types[0] = 0;
442353642Sguido
4424255332Scy	(void) ipf_log_items(softc, IPL_LOGSTATE, NULL, items, sizes, types, 1);
4425145522Sdarrenr#endif
442653642Sguido}
442757096Sguido
442857096Sguido
442960854Sdarrenr#ifdef	USE_INET6
4430145522Sdarrenr/* ------------------------------------------------------------------------ */
4431255332Scy/* Function:    ipf_checkicmp6matchingstate                                 */
4432145522Sdarrenr/* Returns:     ipstate_t* - NULL == no match found,                        */
4433145522Sdarrenr/*                           else  pointer to matching state entry          */
4434145522Sdarrenr/* Parameters:  fin(I) - pointer to packet information                      */
4435145522Sdarrenr/* Locks:       NULL == no locks, else Read Lock on ipf_state               */
4436145522Sdarrenr/*                                                                          */
4437145522Sdarrenr/* If we've got an ICMPv6 error message, using the information stored in    */
4438145522Sdarrenr/* the ICMPv6 packet, look for a matching state table entry.                */
4439145522Sdarrenr/* ------------------------------------------------------------------------ */
4440255332Scystatic ipstate_t *
4441255332Scyipf_checkicmp6matchingstate(fin)
4442255332Scy	fr_info_t *fin;
444357096Sguido{
4444255332Scy	ipf_main_softc_t *softc = fin->fin_main_soft;
4445255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
4446145522Sdarrenr	struct icmp6_hdr *ic6, *oic;
4447145522Sdarrenr	ipstate_t *is, **isp;
4448145522Sdarrenr	u_short sport, dport;
4449145522Sdarrenr	i6addr_t dst, src;
445060854Sdarrenr	u_short savelen;
4451145522Sdarrenr	icmpinfo_t *ic;
445260854Sdarrenr	fr_info_t ofin;
445360854Sdarrenr	tcphdr_t *tcp;
4454145522Sdarrenr	ip6_t *oip6;
4455255332Scy	u_char pr;
445660854Sdarrenr	u_int hv;
4457255332Scy	int type;
445857096Sguido
445960854Sdarrenr	/*
446060854Sdarrenr	 * Does it at least have the return (basic) IP header ?
4461153876Sguido	 * Is it an actual recognised ICMP error type?
446260854Sdarrenr	 * Only a basic IP header (no options) should be with
446360854Sdarrenr	 * an ICMP error header.
446460854Sdarrenr	 */
4465153876Sguido	if ((fin->fin_v != 6) || (fin->fin_plen < ICMP6ERR_MINPKTLEN) ||
4466255332Scy	    !(fin->fin_flx & FI_ICMPERR)) {
4467255332Scy		SBUMPD(ipf_state_stats, iss_icmp_bad);
446860854Sdarrenr		return NULL;
4469255332Scy	}
4470145522Sdarrenr
4471145522Sdarrenr	ic6 = fin->fin_dp;
4472145522Sdarrenr	type = ic6->icmp6_type;
447360854Sdarrenr
4474145522Sdarrenr	oip6 = (ip6_t *)((char *)ic6 + ICMPERR_ICMPHLEN);
4475255332Scy	if (fin->fin_plen < sizeof(*oip6)) {
4476255332Scy		SBUMPD(ipf_state_stats, iss_icmp_short);
447760854Sdarrenr		return NULL;
4478255332Scy	}
447960854Sdarrenr
4480170268Sdarrenr	bcopy((char *)fin, (char *)&ofin, sizeof(*fin));
4481145522Sdarrenr	ofin.fin_v = 6;
4482145522Sdarrenr	ofin.fin_ifp = fin->fin_ifp;
4483145522Sdarrenr	ofin.fin_out = !fin->fin_out;
4484145522Sdarrenr	ofin.fin_m = NULL;	/* if dereferenced, panic XXX */
4485145522Sdarrenr	ofin.fin_mp = NULL;	/* if dereferenced, panic XXX */
448695563Sdarrenr
4487130886Sdarrenr	/*
4488130886Sdarrenr	 * We make a fin entry to be able to feed it to
4489130886Sdarrenr	 * matchsrcdst. Note that not all fields are necessary
4490130886Sdarrenr	 * but this is the cleanest way. Note further we fill
4491130886Sdarrenr	 * in fin_mp such that if someone uses it we'll get
4492255332Scy	 * a kernel panic. ipf_matchsrcdst does not use this.
4493130886Sdarrenr	 *
4494145522Sdarrenr	 * watch out here, as ip is in host order and oip6 in network
4495130886Sdarrenr	 * order. Any change we make must be undone afterwards.
4496130886Sdarrenr	 */
4497145522Sdarrenr	savelen = oip6->ip6_plen;
4498255332Scy	oip6->ip6_plen = htons(fin->fin_dlen - ICMPERR_ICMPHLEN);
4499145522Sdarrenr	ofin.fin_flx = FI_NOCKSUM;
4500145522Sdarrenr	ofin.fin_ip = (ip_t *)oip6;
4501255332Scy	(void) ipf_makefrip(sizeof(*oip6), (ip_t *)oip6, &ofin);
4502145522Sdarrenr	ofin.fin_flx &= ~(FI_BAD|FI_SHORT);
4503145522Sdarrenr	oip6->ip6_plen = savelen;
4504255332Scy	pr = ofin.fin_p;
450595563Sdarrenr
4506255332Scy	/*
4507255332Scy	 * an ICMP error can never generate an ICMP error in response.
4508255332Scy	 */
4509255332Scy	if (ofin.fin_flx & FI_ICMPERR) {
4510255332Scy		DT1(iss_icmp6_icmperr, fr_info_t *, &ofin);
4511255332Scy		SBUMP(ipf_state_stats.iss_icmp6_icmperr);
4512255332Scy		return NULL;
4513255332Scy	}
4514255332Scy
4515145522Sdarrenr	if (oip6->ip6_nxt == IPPROTO_ICMPV6) {
4516255332Scy		oic = ofin.fin_dp;
451760854Sdarrenr		/*
4518130886Sdarrenr		 * an ICMP error can only be generated as a result of an
451960854Sdarrenr		 * ICMP query, not as the response on an ICMP error
452060854Sdarrenr		 *
452160854Sdarrenr		 * XXX theoretically ICMP_ECHOREP and the other reply's are
452260854Sdarrenr		 * ICMP query's as well, but adding them here seems strange XXX
452360854Sdarrenr		 */
4524255332Scy		 if (!(oic->icmp6_type & ICMP6_INFOMSG_MASK)) {
4525255332Scy			DT1(iss_icmp6_notinfo, fr_info_t *, &ofin);
4526255332Scy			SBUMP(ipf_state_stats.iss_icmp6_notinfo);
4527255332Scy			return NULL;
4528255332Scy		}
452960854Sdarrenr
453060854Sdarrenr		/*
453160854Sdarrenr		 * perform a lookup of the ICMP packet in the state table
453260854Sdarrenr		 */
4533145522Sdarrenr		hv = (pr = oip6->ip6_nxt);
4534145522Sdarrenr		src.in6 = oip6->ip6_src;
453560854Sdarrenr		hv += src.in4.s_addr;
4536145522Sdarrenr		dst.in6 = oip6->ip6_dst;
453760854Sdarrenr		hv += dst.in4.s_addr;
453860854Sdarrenr		hv += oic->icmp6_id;
453960854Sdarrenr		hv += oic->icmp6_seq;
4540145522Sdarrenr		hv = DOUBLE_HASH(hv);
454160854Sdarrenr
4542255332Scy		READ_ENTER(&softc->ipf_state);
4543255332Scy		for (isp = &softs->ipf_state_table[hv];
4544255332Scy		     ((is = *isp) != NULL); ) {
4545145522Sdarrenr			ic = &is->is_icmp;
4546145522Sdarrenr			isp = &is->is_hnext;
454760854Sdarrenr			if ((is->is_p == pr) &&
4548145522Sdarrenr			    !(is->is_pass & FR_NOICMPERR) &&
4549145522Sdarrenr			    (oic->icmp6_id == ic->ici_id) &&
4550145522Sdarrenr			    (oic->icmp6_seq == ic->ici_seq) &&
4551255332Scy			    (is = ipf_matchsrcdst(&ofin, is, &src,
4552145522Sdarrenr						 &dst, NULL, FI_ICMPCMP))) {
455360854Sdarrenr			    	/*
455460854Sdarrenr			    	 * in the state table ICMP query's are stored
455560854Sdarrenr			    	 * with the type of the corresponding ICMP
455660854Sdarrenr			    	 * response. Correct here
455760854Sdarrenr			    	 */
4558145522Sdarrenr				if (((ic->ici_type == ICMP6_ECHO_REPLY) &&
455960854Sdarrenr				     (oic->icmp6_type == ICMP6_ECHO_REQUEST)) ||
4560145522Sdarrenr				     (ic->ici_type - 1 == oic->icmp6_type )) {
4561255332Scy					if (!ipf_allowstateicmp(fin, is, &src))
4562255332Scy						return is;
456360854Sdarrenr				}
456460854Sdarrenr			}
4565145522Sdarrenr		}
4566255332Scy		RWLOCK_EXIT(&softc->ipf_state);
4567255332Scy		SBUMPD(ipf_state_stats, iss_icmp6_miss);
456860854Sdarrenr		return NULL;
456995563Sdarrenr	}
457060854Sdarrenr
4571145522Sdarrenr	hv = (pr = oip6->ip6_nxt);
4572145522Sdarrenr	src.in6 = oip6->ip6_src;
4573145522Sdarrenr	hv += src.i6[0];
457495418Sdarrenr	hv += src.i6[1];
457595418Sdarrenr	hv += src.i6[2];
457695418Sdarrenr	hv += src.i6[3];
4577145522Sdarrenr	dst.in6 = oip6->ip6_dst;
4578145522Sdarrenr	hv += dst.i6[0];
457995418Sdarrenr	hv += dst.i6[1];
458095418Sdarrenr	hv += dst.i6[2];
458195418Sdarrenr	hv += dst.i6[3];
4582130886Sdarrenr
4583255332Scy	tcp = NULL;
4584255332Scy
4585255332Scy	switch (oip6->ip6_nxt)
4586255332Scy	{
4587255332Scy	case IPPROTO_TCP :
4588255332Scy	case IPPROTO_UDP :
4589145522Sdarrenr		tcp = (tcphdr_t *)(oip6 + 1);
4590145522Sdarrenr		dport = tcp->th_dport;
4591145522Sdarrenr		sport = tcp->th_sport;
4592145522Sdarrenr		hv += dport;
4593145522Sdarrenr		hv += sport;
4594255332Scy		break;
4595255332Scy
4596255332Scy	case IPPROTO_ICMPV6 :
4597255332Scy		oic = (struct icmp6_hdr *)(oip6 + 1);
4598255332Scy		hv += oic->icmp6_id;
4599255332Scy		hv += oic->icmp6_seq;
4600255332Scy		break;
4601255332Scy
4602255332Scy	default :
4603255332Scy		break;
4604255332Scy	}
4605255332Scy
4606145522Sdarrenr	hv = DOUBLE_HASH(hv);
4607145522Sdarrenr
4608255332Scy	READ_ENTER(&softc->ipf_state);
4609255332Scy	for (isp = &softs->ipf_state_table[hv]; ((is = *isp) != NULL); ) {
4610145522Sdarrenr		isp = &is->is_hnext;
461160854Sdarrenr		/*
461260854Sdarrenr		 * Only allow this icmp though if the
461360854Sdarrenr		 * encapsulated packet was allowed through the
461460854Sdarrenr		 * other way around. Note that the minimal amount
461560854Sdarrenr		 * of info present does not allow for checking against
461660854Sdarrenr		 * tcp internals such as seq and ack numbers.
461760854Sdarrenr		 */
4618145522Sdarrenr		if ((is->is_p != pr) || (is->is_v != 6) ||
4619145522Sdarrenr		    (is->is_pass & FR_NOICMPERR))
4620145522Sdarrenr			continue;
4621255332Scy		is = ipf_matchsrcdst(&ofin, is, &src, &dst, tcp, FI_ICMPCMP);
4622255332Scy		if ((is != NULL) && (ipf_allowstateicmp(fin, is, &src) == 0))
4623145522Sdarrenr			return is;
462460854Sdarrenr	}
4625255332Scy	RWLOCK_EXIT(&softc->ipf_state);
4626255332Scy	SBUMPD(ipf_state_stats, iss_icmp_miss);
462760854Sdarrenr	return NULL;
462857096Sguido}
462960854Sdarrenr#endif
4630145522Sdarrenr
4631145522Sdarrenr
4632145522Sdarrenr/* ------------------------------------------------------------------------ */
4633255332Scy/* Function:    ipf_sttab_init                                              */
4634145522Sdarrenr/* Returns:     Nil                                                         */
4635255332Scy/* Parameters:  softc(I) - pointer to soft context main structure           */
4636255332Scy/*              tqp(I)   - pointer to an array of timeout queues for TCP    */
4637145522Sdarrenr/*                                                                          */
4638145522Sdarrenr/* Initialise the array of timeout queues for TCP.                          */
4639145522Sdarrenr/* ------------------------------------------------------------------------ */
4640255332Scyvoid
4641255332Scyipf_sttab_init(softc, tqp)
4642255332Scy	ipf_main_softc_t *softc;
4643255332Scy	ipftq_t *tqp;
4644145522Sdarrenr{
4645145522Sdarrenr	int i;
4646145522Sdarrenr
4647145522Sdarrenr	for (i = IPF_TCP_NSTATES - 1; i >= 0; i--) {
4648255332Scy		IPFTQ_INIT(&tqp[i], 0, "ipftq tcp tab");
4649145522Sdarrenr		tqp[i].ifq_next = tqp + i + 1;
4650145522Sdarrenr	}
4651145522Sdarrenr	tqp[IPF_TCP_NSTATES - 1].ifq_next = NULL;
4652255332Scy	tqp[IPF_TCPS_CLOSED].ifq_ttl = softc->ipf_tcpclosed;
4653255332Scy	tqp[IPF_TCPS_LISTEN].ifq_ttl = softc->ipf_tcptimeout;
4654255332Scy	tqp[IPF_TCPS_SYN_SENT].ifq_ttl = softc->ipf_tcpsynsent;
4655255332Scy	tqp[IPF_TCPS_SYN_RECEIVED].ifq_ttl = softc->ipf_tcpsynrecv;
4656255332Scy	tqp[IPF_TCPS_ESTABLISHED].ifq_ttl = softc->ipf_tcpidletimeout;
4657255332Scy	tqp[IPF_TCPS_CLOSE_WAIT].ifq_ttl = softc->ipf_tcphalfclosed;
4658255332Scy	tqp[IPF_TCPS_FIN_WAIT_1].ifq_ttl = softc->ipf_tcphalfclosed;
4659255332Scy	tqp[IPF_TCPS_CLOSING].ifq_ttl = softc->ipf_tcptimeout;
4660255332Scy	tqp[IPF_TCPS_LAST_ACK].ifq_ttl = softc->ipf_tcplastack;
4661255332Scy	tqp[IPF_TCPS_FIN_WAIT_2].ifq_ttl = softc->ipf_tcpclosewait;
4662255332Scy	tqp[IPF_TCPS_TIME_WAIT].ifq_ttl = softc->ipf_tcptimewait;
4663255332Scy	tqp[IPF_TCPS_HALF_ESTAB].ifq_ttl = softc->ipf_tcptimeout;
4664145522Sdarrenr}
4665145522Sdarrenr
4666145522Sdarrenr
4667145522Sdarrenr/* ------------------------------------------------------------------------ */
4668255332Scy/* Function:    ipf_sttab_destroy                                           */
4669145522Sdarrenr/* Returns:     Nil                                                         */
4670145522Sdarrenr/* Parameters:  tqp(I) - pointer to an array of timeout queues for TCP      */
4671145522Sdarrenr/*                                                                          */
4672145522Sdarrenr/* Do whatever is necessary to "destroy" each of the entries in the array   */
4673145522Sdarrenr/* of timeout queues for TCP.                                               */
4674145522Sdarrenr/* ------------------------------------------------------------------------ */
4675255332Scyvoid
4676255332Scyipf_sttab_destroy(tqp)
4677255332Scy	ipftq_t *tqp;
4678145522Sdarrenr{
4679145522Sdarrenr	int i;
4680145522Sdarrenr
4681145522Sdarrenr	for (i = IPF_TCP_NSTATES - 1; i >= 0; i--)
4682145522Sdarrenr		MUTEX_DESTROY(&tqp[i].ifq_lock);
4683145522Sdarrenr}
4684145522Sdarrenr
4685145522Sdarrenr
4686145522Sdarrenr/* ------------------------------------------------------------------------ */
4687255332Scy/* Function:    ipf_state_deref                                             */
4688145522Sdarrenr/* Returns:     Nil                                                         */
4689255332Scy/* Parameters:  softc(I) - pointer to soft context main structure           */
4690255332Scy/*              isp(I) - pointer to pointer to state table entry            */
4691145522Sdarrenr/*                                                                          */
4692145522Sdarrenr/* Decrement the reference counter for this state table entry and free it   */
4693145522Sdarrenr/* if there are no more things using it.                                    */
4694145522Sdarrenr/*                                                                          */
4695172776Sdarrenr/* This function is only called when cleaning up after increasing is_ref by */
4696172776Sdarrenr/* one earlier in the 'code path' so if is_ref is 1 when entering, we do    */
4697172776Sdarrenr/* have an orphan, otherwise not.  However there is a possible race between */
4698172776Sdarrenr/* the entry being deleted via flushing with an ioctl call (that calls the  */
4699172776Sdarrenr/* delete function directly) and the tail end of packet processing so we    */
4700172776Sdarrenr/* need to grab is_lock before doing the check to synchronise the two code  */
4701172776Sdarrenr/* paths.                                                                   */
4702172776Sdarrenr/*                                                                          */
4703145522Sdarrenr/* When operating in userland (ipftest), we have no timers to clear a state */
4704145522Sdarrenr/* entry.  Therefore, we make a few simple tests before deleting an entry   */
4705145522Sdarrenr/* outright.  We compare states on each side looking for a combination of   */
4706145522Sdarrenr/* TIME_WAIT (should really be FIN_WAIT_2?) and LAST_ACK.  Then we factor   */
4707145522Sdarrenr/* in packet direction with the interface list to make sure we don't        */
4708145522Sdarrenr/* prematurely delete an entry on a final inbound packet that's we're also  */
4709145522Sdarrenr/* supposed to route elsewhere.                                             */
4710145522Sdarrenr/*                                                                          */
4711145522Sdarrenr/* Internal parameters:                                                     */
4712145522Sdarrenr/*    state[0] = state of source (host that initiated connection)           */
4713145522Sdarrenr/*    state[1] = state of dest   (host that accepted the connection)        */
4714145522Sdarrenr/*                                                                          */
4715145522Sdarrenr/*    dir == 0 : a packet from source to dest                               */
4716145522Sdarrenr/*    dir == 1 : a packet from dest to source                               */
4717145522Sdarrenr/* ------------------------------------------------------------------------ */
4718255332Scyvoid
4719255332Scyipf_state_deref(softc, isp)
4720255332Scy	ipf_main_softc_t *softc;
4721255332Scy	ipstate_t **isp;
4722145522Sdarrenr{
4723255332Scy	ipstate_t *is = *isp;
4724145522Sdarrenr
4725145522Sdarrenr	is = *isp;
4726145522Sdarrenr	*isp = NULL;
4727172776Sdarrenr
4728172776Sdarrenr	MUTEX_ENTER(&is->is_lock);
4729172776Sdarrenr	if (is->is_ref > 1) {
4730172776Sdarrenr		is->is_ref--;
4731172776Sdarrenr		MUTEX_EXIT(&is->is_lock);
4732145522Sdarrenr#ifndef	_KERNEL
4733172776Sdarrenr		if ((is->is_sti.tqe_state[0] > IPF_TCPS_ESTABLISHED) ||
4734255332Scy		    (is->is_sti.tqe_state[1] > IPF_TCPS_ESTABLISHED)) {
4735255332Scy			ipf_state_del(softc, is, ISL_EXPIRE);
4736172776Sdarrenr		}
4737145522Sdarrenr#endif
4738172776Sdarrenr		return;
4739145522Sdarrenr	}
4740172776Sdarrenr	MUTEX_EXIT(&is->is_lock);
4741172776Sdarrenr
4742255332Scy	WRITE_ENTER(&softc->ipf_state);
4743255332Scy	ipf_state_del(softc, is, ISL_ORPHAN);
4744255332Scy	RWLOCK_EXIT(&softc->ipf_state);
4745145522Sdarrenr}
4746145522Sdarrenr
4747145522Sdarrenr
4748145522Sdarrenr/* ------------------------------------------------------------------------ */
4749255332Scy/* Function:    ipf_state_setqueue                                          */
4750145522Sdarrenr/* Returns:     Nil                                                         */
4751255332Scy/* Parameters:  softc(I) - pointer to soft context main structure           */
4752255332Scy/*              is(I)    - pointer to state structure                       */
4753255332Scy/*              rev(I)   - forward(0) or reverse(1) direction               */
4754145522Sdarrenr/* Locks:       ipf_state (read or write)                                   */
4755145522Sdarrenr/*                                                                          */
4756145522Sdarrenr/* Put the state entry on its default queue entry, using rev as a helped in */
4757145522Sdarrenr/* determining which queue it should be placed on.                          */
4758145522Sdarrenr/* ------------------------------------------------------------------------ */
4759255332Scyvoid
4760255332Scyipf_state_setqueue(softc, is, rev)
4761255332Scy	ipf_main_softc_t *softc;
4762255332Scy	ipstate_t *is;
4763255332Scy	int rev;
4764145522Sdarrenr{
4765255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
4766145522Sdarrenr	ipftq_t *oifq, *nifq;
4767145522Sdarrenr
4768145522Sdarrenr	if ((is->is_sti.tqe_flags & TQE_RULEBASED) != 0)
4769145522Sdarrenr		nifq = is->is_tqehead[rev];
4770145522Sdarrenr	else
4771145522Sdarrenr		nifq = NULL;
4772145522Sdarrenr
4773145522Sdarrenr	if (nifq == NULL) {
4774145522Sdarrenr		switch (is->is_p)
4775145522Sdarrenr		{
4776145522Sdarrenr#ifdef USE_INET6
4777145522Sdarrenr		case IPPROTO_ICMPV6 :
4778145522Sdarrenr			if (rev == 1)
4779255332Scy				nifq = &softs->ipf_state_icmpacktq;
4780145522Sdarrenr			else
4781255332Scy				nifq = &softs->ipf_state_icmptq;
4782145522Sdarrenr			break;
4783145522Sdarrenr#endif
4784145522Sdarrenr		case IPPROTO_ICMP :
4785145522Sdarrenr			if (rev == 1)
4786255332Scy				nifq = &softs->ipf_state_icmpacktq;
4787145522Sdarrenr			else
4788255332Scy				nifq = &softs->ipf_state_icmptq;
4789145522Sdarrenr			break;
4790145522Sdarrenr		case IPPROTO_TCP :
4791255332Scy			nifq = softs->ipf_state_tcptq + is->is_state[rev];
4792145522Sdarrenr			break;
4793145522Sdarrenr
4794145522Sdarrenr		case IPPROTO_UDP :
4795145522Sdarrenr			if (rev == 1)
4796255332Scy				nifq = &softs->ipf_state_udpacktq;
4797145522Sdarrenr			else
4798255332Scy				nifq = &softs->ipf_state_udptq;
4799145522Sdarrenr			break;
4800145522Sdarrenr
4801145522Sdarrenr		default :
4802255332Scy			nifq = &softs->ipf_state_iptq;
4803145522Sdarrenr			break;
4804145522Sdarrenr		}
4805145522Sdarrenr	}
4806145522Sdarrenr
4807145522Sdarrenr	oifq = is->is_sti.tqe_ifq;
4808145522Sdarrenr	/*
4809145522Sdarrenr	 * If it's currently on a timeout queue, move it from one queue to
4810145522Sdarrenr	 * another, else put it on the end of the newly determined queue.
4811145522Sdarrenr	 */
4812145522Sdarrenr	if (oifq != NULL)
4813255332Scy		ipf_movequeue(softc->ipf_ticks, &is->is_sti, oifq, nifq);
4814145522Sdarrenr	else
4815255332Scy		ipf_queueappend(softc->ipf_ticks, &is->is_sti, nifq, is);
4816145522Sdarrenr	return;
4817145522Sdarrenr}
4818170268Sdarrenr
4819170268Sdarrenr
4820170268Sdarrenr/* ------------------------------------------------------------------------ */
4821255332Scy/* Function:    ipf_state_iter                                              */
4822170268Sdarrenr/* Returns:     int - 0 == success, else error                              */
4823255332Scy/* Parameters:  softc(I) - pointer to main soft context                     */
4824255332Scy/*              token(I) - pointer to ipftoken structure                    */
4825170268Sdarrenr/*              itp(I)   - pointer to ipfgeniter structure                  */
4826255332Scy/*              obj(I)   - pointer to data description structure            */
4827170268Sdarrenr/*                                                                          */
4828170268Sdarrenr/* This function handles the SIOCGENITER ioctl for the state tables and     */
4829255332Scy/* walks through the list of entries in the state table list (softs->ipf_state_list.)    */
4830170268Sdarrenr/* ------------------------------------------------------------------------ */
4831255332Scystatic int
4832255332Scyipf_state_iter(softc, token, itp, obj)
4833255332Scy	ipf_main_softc_t *softc;
4834255332Scy	ipftoken_t *token;
4835255332Scy	ipfgeniter_t *itp;
4836255332Scy	ipfobj_t *obj;
4837170268Sdarrenr{
4838255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
4839170268Sdarrenr	ipstate_t *is, *next, zero;
4840255332Scy	int error;
4841170268Sdarrenr
4842255332Scy	if (itp->igi_data == NULL) {
4843255332Scy		IPFERROR(100026);
4844170268Sdarrenr		return EFAULT;
4845255332Scy	}
4846170268Sdarrenr
4847255332Scy	if (itp->igi_nitems < 1) {
4848255332Scy		IPFERROR(100027);
4849170268Sdarrenr		return ENOSPC;
4850255332Scy	}
4851170268Sdarrenr
4852255332Scy	if (itp->igi_type != IPFGENITER_STATE) {
4853255332Scy		IPFERROR(100028);
4854170268Sdarrenr		return EINVAL;
4855255332Scy	}
4856170268Sdarrenr
4857170268Sdarrenr	is = token->ipt_data;
4858170268Sdarrenr	if (is == (void *)-1) {
4859255332Scy		IPFERROR(100029);
4860170268Sdarrenr		return ESRCH;
4861170268Sdarrenr	}
4862170268Sdarrenr
4863170268Sdarrenr	error = 0;
4864255332Scy	obj->ipfo_type = IPFOBJ_IPSTATE;
4865255332Scy	obj->ipfo_size = sizeof(ipstate_t);
4866170268Sdarrenr
4867255332Scy	READ_ENTER(&softc->ipf_state);
4868255332Scy
4869255332Scy	is = token->ipt_data;
4870170268Sdarrenr	if (is == NULL) {
4871255332Scy		next = softs->ipf_state_list;
4872170268Sdarrenr	} else {
4873170268Sdarrenr		next = is->is_next;
4874170268Sdarrenr	}
4875170268Sdarrenr
4876255332Scy	/*
4877255332Scy	 * If we find a state entry to use, bump its reference count so that
4878255332Scy	 * it can be used for is_next when we come back.
4879255332Scy	 */
4880255332Scy	if (next != NULL) {
4881255332Scy		MUTEX_ENTER(&next->is_lock);
4882255332Scy		next->is_ref++;
4883255332Scy		MUTEX_EXIT(&next->is_lock);
4884255332Scy		token->ipt_data = next;
4885255332Scy	} else {
4886255332Scy		bzero(&zero, sizeof(zero));
4887255332Scy		next = &zero;
4888255332Scy		token->ipt_data = NULL;
4889255332Scy	}
4890255332Scy	if (next->is_next == NULL)
4891255332Scy		ipf_token_mark_complete(token);
4892170268Sdarrenr
4893255332Scy	RWLOCK_EXIT(&softc->ipf_state);
4894170268Sdarrenr
4895255332Scy	obj->ipfo_ptr = itp->igi_data;
4896255332Scy	error = ipf_outobjk(softc, obj, next);
4897255332Scy	if (is != NULL)
4898255332Scy		ipf_state_deref(softc, &is);
4899172776Sdarrenr
4900170268Sdarrenr	return error;
4901170268Sdarrenr}
4902170268Sdarrenr
4903170268Sdarrenr
4904170268Sdarrenr/* ------------------------------------------------------------------------ */
4905255332Scy/* Function:    ipf_state_gettable                                          */
4906170268Sdarrenr/* Returns:     int     - 0 = success, else error                           */
4907255332Scy/* Parameters:  softc(I) - pointer to main soft context                     */
4908255332Scy/*              softs(I) - pointer to state context structure               */
4909255332Scy/*              data(I)  - pointer to ioctl data                             */
4910170268Sdarrenr/*                                                                          */
4911170268Sdarrenr/* This function handles ioctl requests for tables of state information.    */
4912170268Sdarrenr/* At present the only table it deals with is the hash bucket statistics.   */
4913170268Sdarrenr/* ------------------------------------------------------------------------ */
4914255332Scystatic int
4915255332Scyipf_state_gettable(softc, softs, data)
4916255332Scy	ipf_main_softc_t *softc;
4917255332Scy	ipf_state_softc_t *softs;
4918255332Scy	char *data;
4919170268Sdarrenr{
4920170268Sdarrenr	ipftable_t table;
4921170268Sdarrenr	int error;
4922170268Sdarrenr
4923255332Scy	error = ipf_inobj(softc, data, NULL, &table, IPFOBJ_GTABLE);
4924170268Sdarrenr	if (error != 0)
4925170268Sdarrenr		return error;
4926170268Sdarrenr
4927255332Scy	if (table.ita_type != IPFTABLE_BUCKETS) {
4928255332Scy		IPFERROR(100031);
4929170268Sdarrenr		return EINVAL;
4930255332Scy	}
4931170268Sdarrenr
4932255332Scy	error = COPYOUT(softs->ipf_state_stats.iss_bucketlen, table.ita_table,
4933255332Scy			softs->ipf_state_size * sizeof(u_int));
4934255332Scy	if (error != 0) {
4935255332Scy		IPFERROR(100032);
4936170268Sdarrenr		error = EFAULT;
4937255332Scy	}
4938170268Sdarrenr	return error;
4939170268Sdarrenr}
4940255332Scy
4941255332Scy
4942255332Scy/* ------------------------------------------------------------------------ */
4943255332Scy/* Function:    ipf_state_setpending                                        */
4944255332Scy/* Returns:     Nil                                                         */
4945255332Scy/* Parameters:  softc(I) - pointer to main soft context                     */
4946255332Scy/*              is(I)    - pointer to state structure                       */
4947255332Scy/* Locks:       ipf_state (read or write)                                   */
4948255332Scy/*                                                                          */
4949255332Scy/* Put the state entry on to the pending queue - this queue has a very      */
4950255332Scy/* short lifetime where items are put that can't be deleted straight away   */
4951255332Scy/* because of locking issues but we want to delete them ASAP, anyway.       */
4952255332Scy/* ------------------------------------------------------------------------ */
4953255332Scyvoid
4954255332Scyipf_state_setpending(softc, is)
4955255332Scy	ipf_main_softc_t *softc;
4956255332Scy	ipstate_t *is;
4957255332Scy{
4958255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
4959255332Scy	ipftq_t *oifq;
4960255332Scy
4961255332Scy	oifq = is->is_sti.tqe_ifq;
4962255332Scy	if (oifq != NULL)
4963255332Scy		ipf_movequeue(softc->ipf_ticks, &is->is_sti, oifq,
4964255332Scy			      &softs->ipf_state_pending);
4965255332Scy	else
4966255332Scy		ipf_queueappend(softc->ipf_ticks, &is->is_sti,
4967255332Scy				&softs->ipf_state_pending, is);
4968255332Scy
4969255332Scy	MUTEX_ENTER(&is->is_lock);
4970255332Scy	if (is->is_me != NULL) {
4971255332Scy		*is->is_me = NULL;
4972255332Scy		is->is_me = NULL;
4973255332Scy		is->is_ref--;
4974255332Scy	}
4975255332Scy	MUTEX_EXIT(&is->is_lock);
4976255332Scy}
4977255332Scy
4978255332Scy
4979255332Scy/* ------------------------------------------------------------------------ */
4980255332Scy/* Function:    ipf_state_matchflush                                        */
4981255332Scy/* Returns:     Nil                                                         */
4982255332Scy/* Parameters:  softc(I) - pointer to main soft context                     */
4983255332Scy/*              data(I)  - pointer to state structure                       */
4984255332Scy/* Locks:       ipf_state (read or write)                                   */
4985255332Scy/*                                                                          */
4986255332Scy/* Flush all entries from the list of state entries that match the          */
4987255332Scy/* properties in the array loaded.                                          */
4988255332Scy/* ------------------------------------------------------------------------ */
4989255332Scyint
4990255332Scyipf_state_matchflush(softc, data)
4991255332Scy	ipf_main_softc_t *softc;
4992255332Scy	caddr_t data;
4993255332Scy{
4994255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
4995255332Scy	int *array, flushed, error;
4996255332Scy	ipstate_t *state, *statenext;
4997255332Scy	ipfobj_t obj;
4998255332Scy
4999255332Scy	error = ipf_matcharray_load(softc, data, &obj, &array);
5000255332Scy	if (error != 0)
5001255332Scy		return error;
5002255332Scy
5003255332Scy	flushed = 0;
5004255332Scy
5005255332Scy	for (state = softs->ipf_state_list; state != NULL; state = statenext) {
5006255332Scy		statenext = state->is_next;
5007255332Scy		if (ipf_state_matcharray(state, array, softc->ipf_ticks) == 0) {
5008255332Scy			ipf_state_del(softc, state, ISL_FLUSH);
5009255332Scy			flushed++;
5010255332Scy		}
5011255332Scy	}
5012255332Scy
5013255332Scy	obj.ipfo_retval = flushed;
5014255332Scy	error = BCOPYOUT(&obj, data, sizeof(obj));
5015255332Scy
5016255332Scy	KFREES(array, array[0] * sizeof(*array));
5017255332Scy
5018255332Scy	return error;
5019255332Scy}
5020255332Scy
5021255332Scy
5022255332Scy/* ------------------------------------------------------------------------ */
5023255332Scy/* Function:    ipf_state_matcharray                                        */
5024255332Scy/* Returns:     int   - 0 = no match, 1 = match                             */
5025255332Scy/* Parameters:  state(I) - pointer to state structure                       */
5026255332Scy/*              array(I) - pointer to ipf matching expression               */
5027255332Scy/*              ticks(I) - current value of ipfilter tick timer             */
5028255332Scy/* Locks:       ipf_state (read or write)                                   */
5029255332Scy/*                                                                          */
5030255332Scy/* Compare a state entry with the match array passed in and return a value  */
5031255332Scy/* to indicate whether or not the matching was successful.                  */
5032255332Scy/* ------------------------------------------------------------------------ */
5033255332Scystatic int
5034255332Scyipf_state_matcharray(state, array, ticks)
5035255332Scy	ipstate_t *state;
5036255332Scy	int *array;
5037255332Scy	u_long ticks;
5038255332Scy{
5039255332Scy	int i, n, *x, rv, p;
5040255332Scy	ipfexp_t *e;
5041255332Scy
5042255332Scy	rv = 0;
5043255332Scy	n = array[0];
5044255332Scy	x = array + 1;
5045255332Scy
5046255332Scy	for (; n > 0; x += 3 + x[3], rv = 0) {
5047255332Scy		e = (ipfexp_t *)x;
5048255332Scy		n -= e->ipfe_size;
5049255332Scy		if (x[0] == IPF_EXP_END)
5050255332Scy			break;
5051255332Scy
5052255332Scy		/*
5053255332Scy		 * If we need to match the protocol and that doesn't match,
5054255332Scy		 * don't even both with the instruction array.
5055255332Scy		 */
5056255332Scy		p = e->ipfe_cmd >> 16;
5057255332Scy		if ((p != 0) && (p != state->is_p))
5058255332Scy			break;
5059255332Scy
5060255332Scy		switch (e->ipfe_cmd)
5061255332Scy		{
5062255332Scy		case IPF_EXP_IP_PR :
5063255332Scy			for (i = 0; !rv && i < e->ipfe_narg; i++) {
5064255332Scy				rv |= (state->is_p == e->ipfe_arg0[i]);
5065255332Scy			}
5066255332Scy			break;
5067255332Scy
5068255332Scy		case IPF_EXP_IP_SRCADDR :
5069255332Scy			if (state->is_v != 4)
5070255332Scy				break;
5071255332Scy			for (i = 0; !rv && i < e->ipfe_narg; i++) {
5072255332Scy				rv |= ((state->is_saddr &
5073255332Scy					e->ipfe_arg0[i * 2 + 1]) ==
5074255332Scy				      e->ipfe_arg0[i * 2]);
5075255332Scy			}
5076255332Scy			break;
5077255332Scy
5078255332Scy		case IPF_EXP_IP_DSTADDR :
5079255332Scy			if (state->is_v != 4)
5080255332Scy				break;
5081255332Scy			for (i = 0; !rv && i < e->ipfe_narg; i++) {
5082255332Scy				rv |= ((state->is_daddr &
5083255332Scy					e->ipfe_arg0[i * 2 + 1]) ==
5084255332Scy				       e->ipfe_arg0[i * 2]);
5085255332Scy			}
5086255332Scy			break;
5087255332Scy
5088255332Scy		case IPF_EXP_IP_ADDR :
5089255332Scy			if (state->is_v != 4)
5090255332Scy				break;
5091255332Scy			for (i = 0; !rv && i < e->ipfe_narg; i++) {
5092255332Scy				rv |= ((state->is_saddr &
5093255332Scy					e->ipfe_arg0[i * 2 + 1]) ==
5094255332Scy				       e->ipfe_arg0[i * 2]) ||
5095255332Scy				       ((state->is_daddr &
5096255332Scy					e->ipfe_arg0[i * 2 + 1]) ==
5097255332Scy				       e->ipfe_arg0[i * 2]);
5098255332Scy			}
5099255332Scy			break;
5100255332Scy
5101255332Scy#ifdef USE_INET6
5102255332Scy		case IPF_EXP_IP6_SRCADDR :
5103255332Scy			if (state->is_v != 6)
5104255332Scy				break;
5105255332Scy			for (i = 0; !rv && i < x[3]; i++) {
5106255332Scy				rv |= IP6_MASKEQ(&state->is_src.in6,
5107255332Scy						 &e->ipfe_arg0[i * 8 + 4],
5108255332Scy						 &e->ipfe_arg0[i * 8]);
5109255332Scy			}
5110255332Scy			break;
5111255332Scy
5112255332Scy		case IPF_EXP_IP6_DSTADDR :
5113255332Scy			if (state->is_v != 6)
5114255332Scy				break;
5115255332Scy			for (i = 0; !rv && i < x[3]; i++) {
5116255332Scy				rv |= IP6_MASKEQ(&state->is_dst.in6,
5117255332Scy						 &e->ipfe_arg0[i * 8 + 4],
5118255332Scy						 &e->ipfe_arg0[i * 8]);
5119255332Scy			}
5120255332Scy			break;
5121255332Scy
5122255332Scy		case IPF_EXP_IP6_ADDR :
5123255332Scy			if (state->is_v != 6)
5124255332Scy				break;
5125255332Scy			for (i = 0; !rv && i < x[3]; i++) {
5126255332Scy				rv |= IP6_MASKEQ(&state->is_src.in6,
5127255332Scy						 &e->ipfe_arg0[i * 8 + 4],
5128255332Scy						 &e->ipfe_arg0[i * 8]) ||
5129255332Scy				      IP6_MASKEQ(&state->is_dst.in6,
5130255332Scy						 &e->ipfe_arg0[i * 8 + 4],
5131255332Scy						 &e->ipfe_arg0[i * 8]);
5132255332Scy			}
5133255332Scy			break;
5134255332Scy#endif
5135255332Scy
5136255332Scy		case IPF_EXP_UDP_PORT :
5137255332Scy		case IPF_EXP_TCP_PORT :
5138255332Scy			for (i = 0; !rv && i < e->ipfe_narg; i++) {
5139255332Scy				rv |= (state->is_sport == e->ipfe_arg0[i]) ||
5140255332Scy				      (state->is_dport == e->ipfe_arg0[i]);
5141255332Scy			}
5142255332Scy			break;
5143255332Scy
5144255332Scy		case IPF_EXP_UDP_SPORT :
5145255332Scy		case IPF_EXP_TCP_SPORT :
5146255332Scy			for (i = 0; !rv && i < e->ipfe_narg; i++) {
5147255332Scy				rv |= (state->is_sport == e->ipfe_arg0[i]);
5148255332Scy			}
5149255332Scy			break;
5150255332Scy
5151255332Scy		case IPF_EXP_UDP_DPORT :
5152255332Scy		case IPF_EXP_TCP_DPORT :
5153255332Scy			for (i = 0; !rv && i < e->ipfe_narg; i++) {
5154255332Scy				rv |= (state->is_dport == e->ipfe_arg0[i]);
5155255332Scy			}
5156255332Scy			break;
5157255332Scy
5158255332Scy		case IPF_EXP_TCP_STATE :
5159255332Scy			for (i = 0; !rv && i < e->ipfe_narg; i++) {
5160255332Scy				rv |= (state->is_state[0] == e->ipfe_arg0[i]) ||
5161255332Scy				      (state->is_state[1] == e->ipfe_arg0[i]);
5162255332Scy			}
5163255332Scy			break;
5164255332Scy
5165255332Scy		case IPF_EXP_IDLE_GT :
5166255332Scy			rv |= (ticks - state->is_touched > e->ipfe_arg0[0]);
5167255332Scy			break;
5168255332Scy		}
5169255332Scy
5170255332Scy		/*
5171255332Scy		 * Factor in doing a negative match.
5172255332Scy		 */
5173255332Scy		rv ^= e->ipfe_not;
5174255332Scy
5175255332Scy		if (rv == 0)
5176255332Scy			break;
5177255332Scy	}
5178255332Scy
5179255332Scy	return rv;
5180255332Scy}
5181255332Scy
5182255332Scy
5183255332Scy/* ------------------------------------------------------------------------ */
5184255332Scy/* Function:    ipf_state_settimeout                                        */
5185255332Scy/* Returns:     int 0 = success, else failure                               */
5186255332Scy/* Parameters:  softc(I)  - pointer to main soft context                    */
5187255332Scy/*              t(I)      - pointer to tuneable being changed               */
5188255332Scy/*              p(I)      - pointer to the new value                        */
5189255332Scy/*                                                                          */
5190255332Scy/* Sets a timeout value for one of the many timeout queues.  We find the    */
5191255332Scy/* correct queue using a somewhat manual process of comparing the timeout   */
5192255332Scy/* names for each specific value available and calling ipf_apply_timeout on */
5193255332Scy/* that queue so that all of the items on it are updated accordingly.       */
5194255332Scy/* ------------------------------------------------------------------------ */
5195255332Scyint
5196255332Scyipf_state_settimeout(softc, t, p)
5197255332Scy	struct ipf_main_softc_s *softc;
5198255332Scy	ipftuneable_t *t;
5199255332Scy	ipftuneval_t *p;
5200255332Scy{
5201255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
5202255332Scy
5203255332Scy	/*
5204255332Scy	 * In case there is nothing to do...
5205255332Scy	 */
5206255332Scy	if (*t->ipft_pint == p->ipftu_int)
5207255332Scy		return 0;
5208255332Scy
5209255332Scy	if (!strncmp(t->ipft_name, "tcp_", 4))
5210255332Scy		return ipf_settimeout_tcp(t, p, softs->ipf_state_tcptq);
5211255332Scy
5212255332Scy	if (!strcmp(t->ipft_name, "udp_timeout")) {
5213255332Scy		ipf_apply_timeout(&softs->ipf_state_udptq, p->ipftu_int);
5214255332Scy	} else if (!strcmp(t->ipft_name, "udp_ack_timeout")) {
5215255332Scy		ipf_apply_timeout(&softs->ipf_state_udpacktq, p->ipftu_int);
5216255332Scy	} else if (!strcmp(t->ipft_name, "icmp_timeout")) {
5217255332Scy		ipf_apply_timeout(&softs->ipf_state_icmptq, p->ipftu_int);
5218255332Scy	} else if (!strcmp(t->ipft_name, "icmp_ack_timeout")) {
5219255332Scy		ipf_apply_timeout(&softs->ipf_state_icmpacktq, p->ipftu_int);
5220255332Scy	} else if (!strcmp(t->ipft_name, "ip_timeout")) {
5221255332Scy		ipf_apply_timeout(&softs->ipf_state_iptq, p->ipftu_int);
5222255332Scy	} else {
5223255332Scy		IPFERROR(100034);
5224255332Scy		return ESRCH;
5225255332Scy	}
5226255332Scy
5227255332Scy	/*
5228255332Scy	 * Update the tuneable being set.
5229255332Scy	 */
5230255332Scy	*t->ipft_pint = p->ipftu_int;
5231255332Scy
5232255332Scy	return 0;
5233255332Scy}
5234255332Scy
5235255332Scy
5236255332Scy/* ------------------------------------------------------------------------ */
5237255332Scy/* Function:    ipf_state_rehash                                            */
5238255332Scy/* Returns:     int 0 = success, else failure                               */
5239255332Scy/* Parameters:  softc(I)  - pointer to main soft context                    */
5240255332Scy/*              t(I)      - pointer to tuneable being changed               */
5241255332Scy/*              p(I)      - pointer to the new value                        */
5242255332Scy/*                                                                          */
5243255332Scy/* To change the size of the state hash table at runtime, a new table has   */
5244255332Scy/* to be allocated and then all of the existing entries put in it, bumping  */
5245255332Scy/* up the bucketlength for it as we go along.                               */
5246255332Scy/* ------------------------------------------------------------------------ */
5247255332Scyint
5248255332Scyipf_state_rehash(softc, t, p)
5249255332Scy	ipf_main_softc_t *softc;
5250255332Scy	ipftuneable_t *t;
5251255332Scy	ipftuneval_t *p;
5252255332Scy{
5253255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
5254255332Scy	ipstate_t **newtab, *is;
5255255332Scy	u_int *bucketlens;
5256255332Scy	u_int maxbucket;
5257255332Scy	u_int newsize;
5258255332Scy	u_int hv;
5259255332Scy	int i;
5260255332Scy
5261255332Scy	newsize = p->ipftu_int;
5262255332Scy	/*
5263255332Scy	 * In case there is nothing to do...
5264255332Scy	 */
5265255332Scy	if (newsize == softs->ipf_state_size)
5266255332Scy		return 0;
5267255332Scy
5268255332Scy	KMALLOCS(newtab, ipstate_t **, newsize * sizeof(ipstate_t *));
5269255332Scy	if (newtab == NULL) {
5270255332Scy		IPFERROR(100035);
5271255332Scy		return ENOMEM;
5272255332Scy	}
5273255332Scy
5274255332Scy	KMALLOCS(bucketlens, u_int *, newsize * sizeof(u_int));
5275255332Scy	if (bucketlens == NULL) {
5276255332Scy		KFREES(newtab, newsize * sizeof(*softs->ipf_state_table));
5277255332Scy		IPFERROR(100036);
5278255332Scy		return ENOMEM;
5279255332Scy	}
5280255332Scy
5281255332Scy	for (maxbucket = 0, i = newsize; i > 0; i >>= 1)
5282255332Scy		maxbucket++;
5283255332Scy	maxbucket *= 2;
5284255332Scy
5285255332Scy	bzero((char *)newtab, newsize * sizeof(ipstate_t *));
5286255332Scy	bzero((char *)bucketlens, newsize * sizeof(u_int));
5287255332Scy
5288255332Scy	WRITE_ENTER(&softc->ipf_state);
5289255332Scy
5290255332Scy	if (softs->ipf_state_table != NULL) {
5291255332Scy		KFREES(softs->ipf_state_table,
5292255332Scy		       softs->ipf_state_size * sizeof(*softs->ipf_state_table));
5293255332Scy	}
5294255332Scy	softs->ipf_state_table = newtab;
5295255332Scy
5296255332Scy	if (softs->ipf_state_stats.iss_bucketlen != NULL) {
5297255332Scy		KFREES(softs->ipf_state_stats.iss_bucketlen,
5298255332Scy		       softs->ipf_state_size * sizeof(u_int));
5299255332Scy	}
5300255332Scy	softs->ipf_state_stats.iss_bucketlen = bucketlens;
5301255332Scy	softs->ipf_state_maxbucket = maxbucket;
5302255332Scy	softs->ipf_state_size = newsize;
5303255332Scy
5304255332Scy	/*
5305255332Scy	 * Walk through the entire list of state table entries and put them
5306255332Scy	 * in the new state table, somewhere.  Because we have a new table,
5307255332Scy	 * we need to restart the counter of how many chains are in use.
5308255332Scy	 */
5309255332Scy	softs->ipf_state_stats.iss_inuse = 0;
5310255332Scy	for (is = softs->ipf_state_list; is != NULL; is = is->is_next) {
5311255332Scy		is->is_hnext = NULL;
5312255332Scy		is->is_phnext = NULL;
5313255332Scy		hv = is->is_hv % softs->ipf_state_size;
5314255332Scy
5315255332Scy		if (softs->ipf_state_table[hv] != NULL)
5316255332Scy			softs->ipf_state_table[hv]->is_phnext = &is->is_hnext;
5317255332Scy		else
5318255332Scy			softs->ipf_state_stats.iss_inuse++;
5319255332Scy		is->is_phnext = softs->ipf_state_table + hv;
5320255332Scy		is->is_hnext = softs->ipf_state_table[hv];
5321255332Scy		softs->ipf_state_table[hv] = is;
5322255332Scy		softs->ipf_state_stats.iss_bucketlen[hv]++;
5323255332Scy	}
5324255332Scy	RWLOCK_EXIT(&softc->ipf_state);
5325255332Scy
5326255332Scy	return 0;
5327255332Scy}
5328255332Scy
5329255332Scy
5330255332Scy/* ------------------------------------------------------------------------ */
5331255332Scy/* Function:    ipf_state_add_tq                                            */
5332255332Scy/* Returns:     ipftq_t * - NULL = failure, else pointer to new timeout     */
5333255332Scy/*                          queue                                           */
5334255332Scy/* Parameters:  softc(I)  - pointer to main soft context                    */
5335255332Scy/*              ttl(I)    - pointer to the ttl for the new queue            */
5336255332Scy/*                                                                          */
5337255332Scy/* Request a pointer to a timeout queue that has a ttl as given by the      */
5338255332Scy/* value being passed in.  The timeout queue is added tot the list of those */
5339255332Scy/* used internally for stateful filtering.                                  */
5340255332Scy/* ------------------------------------------------------------------------ */
5341255332Scyipftq_t *
5342255332Scyipf_state_add_tq(softc, ttl)
5343255332Scy	ipf_main_softc_t *softc;
5344255332Scy	int ttl;
5345255332Scy{
5346255332Scy	ipf_state_softc_t *softs = softc->ipf_state_soft;
5347255332Scy
5348255332Scy        return ipf_addtimeoutqueue(softc, &softs->ipf_state_usertq, ttl);
5349255332Scy}
5350255332Scy
5351255332Scy
5352255332Scy#ifndef _KERNEL
5353255332Scy/*
5354255332Scy * Display the built up state table rules and mapping entries.
5355255332Scy */
5356255332Scyvoid
5357255332Scyipf_state_dump(softc, arg)
5358255332Scy	ipf_main_softc_t *softc;
5359255332Scy	void *arg;
5360255332Scy{
5361255332Scy	ipf_state_softc_t *softs = arg;
5362255332Scy	ipstate_t *ips;
5363255332Scy
5364255332Scy	printf("List of active state sessions:\n");
5365255332Scy	for (ips = softs->ipf_state_list; ips != NULL; )
5366255332Scy		ips = printstate(ips, opts & (OPT_DEBUG|OPT_VERBOSE),
5367255332Scy				 softc->ipf_ticks);
5368255332Scy}
5369255332Scy#endif
5370