xref: /netbsd-src/sys/external/bsd/ipf/netinet/fil.c (revision b7b7574d3bf8eeb51a1fa3977b59142ec6434a55)
1 /*	$NetBSD: fil.c,v 1.15 2014/06/16 12:38:32 christos Exp $	*/
2 
3 /*
4  * Copyright (C) 2012 by Darren Reed.
5  *
6  * See the IPFILTER.LICENCE file for details on licencing.
7  *
8  * Id: fil.c,v 1.1.1.2 2012/07/22 13:45:07 darrenr Exp $
9  *
10  */
11 #if defined(KERNEL) || defined(_KERNEL)
12 # undef KERNEL
13 # undef _KERNEL
14 # define        KERNEL	1
15 # define        _KERNEL	1
16 #endif
17 #include <sys/errno.h>
18 #include <sys/types.h>
19 #include <sys/param.h>
20 #include <sys/time.h>
21 #if defined(_KERNEL) && defined(__FreeBSD_version) && \
22     (__FreeBSD_version >= 220000)
23 # if (__FreeBSD_version >= 400000)
24 #  if !defined(IPFILTER_LKM)
25 #   include "opt_inet6.h"
26 #  endif
27 #  if (__FreeBSD_version == 400019)
28 #   define CSUM_DELAY_DATA
29 #  endif
30 # endif
31 # include <sys/filio.h>
32 #else
33 # include <sys/ioctl.h>
34 #endif
35 #if (defined(__SVR4) || defined(__svr4__)) && defined(sun)
36 # include <sys/filio.h>
37 #endif
38 #if !defined(_AIX51)
39 # include <sys/fcntl.h>
40 #endif
41 #if defined(_KERNEL)
42 # include <sys/systm.h>
43 # include <sys/file.h>
44 #else
45 # include <stdio.h>
46 # include <string.h>
47 # include <stdlib.h>
48 # include <stddef.h>
49 # include <sys/file.h>
50 # define _KERNEL
51 # ifdef __OpenBSD__
52 struct file;
53 # endif
54 # include <sys/uio.h>
55 # undef _KERNEL
56 #endif
57 #if !defined(__SVR4) && !defined(__svr4__) && !defined(__hpux) && \
58     !defined(linux)
59 # include <sys/mbuf.h>
60 #else
61 # if !defined(linux)
62 #  include <sys/byteorder.h>
63 # endif
64 # if (SOLARIS2 < 5) && defined(sun)
65 #  include <sys/dditypes.h>
66 # endif
67 #endif
68 #ifdef __hpux
69 # define _NET_ROUTE_INCLUDED
70 #endif
71 #if !defined(linux)
72 # include <sys/protosw.h>
73 #endif
74 #include <sys/socket.h>
75 #include <net/if.h>
76 #ifdef sun
77 # include <net/af.h>
78 #endif
79 #include <netinet/in.h>
80 #include <netinet/in_systm.h>
81 #include <netinet/ip.h>
82 #if defined(__sgi) && defined(IFF_DRVRLOCK) /* IRIX 6 */
83 # include <sys/hashing.h>
84 # include <netinet/in_var.h>
85 #endif
86 #include <netinet/tcp.h>
87 #if (!defined(__sgi) && !defined(AIX)) || defined(_KERNEL)
88 # include <netinet/udp.h>
89 # include <netinet/ip_icmp.h>
90 #endif
91 #ifdef __hpux
92 # undef _NET_ROUTE_INCLUDED
93 #endif
94 #ifdef __osf__
95 # undef _RADIX_H_
96 #endif
97 #include "netinet/ip_compat.h"
98 #ifdef	USE_INET6
99 # include <netinet/icmp6.h>
100 # if !SOLARIS && defined(_KERNEL) && !defined(__osf__) && !defined(__hpux)
101 #  include <netinet6/in6_var.h>
102 # endif
103 #endif
104 #include "netinet/ip_fil.h"
105 #include "netinet/ip_nat.h"
106 #include "netinet/ip_frag.h"
107 #include "netinet/ip_state.h"
108 #include "netinet/ip_proxy.h"
109 #include "netinet/ip_auth.h"
110 #ifdef IPFILTER_SCAN
111 # include "netinet/ip_scan.h"
112 #endif
113 #include "netinet/ip_sync.h"
114 #include "netinet/ip_lookup.h"
115 #include "netinet/ip_pool.h"
116 #include "netinet/ip_htable.h"
117 #ifdef IPFILTER_COMPILED
118 # include "netinet/ip_rules.h"
119 #endif
120 #if defined(IPFILTER_BPF) && defined(_KERNEL)
121 # include <net/bpf.h>
122 #endif
123 #if defined(__FreeBSD_version) && (__FreeBSD_version >= 300000)
124 # include <sys/malloc.h>
125 #endif
126 #include "netinet/ipl.h"
127 
128 #if defined(__NetBSD__) && (__NetBSD_Version__ >= 104230000)
129 # include <sys/callout.h>
130 extern struct callout ipf_slowtimer_ch;
131 #endif
132 #if defined(__OpenBSD__)
133 # include <sys/timeout.h>
134 extern struct timeout ipf_slowtimer_ch;
135 #endif
136 /* END OF INCLUDES */
137 
138 #if !defined(lint)
139 #if defined(__NetBSD__)
140 #include <sys/cdefs.h>
141 __KERNEL_RCSID(0, "$NetBSD: fil.c,v 1.15 2014/06/16 12:38:32 christos Exp $");
142 #else
143 static const char sccsid[] = "@(#)fil.c	1.36 6/5/96 (C) 1993-2000 Darren Reed";
144 static const char rcsid[] = "@(#)Id: fil.c,v 1.1.1.2 2012/07/22 13:45:07 darrenr Exp $";
145 #endif
146 #endif
147 
148 #ifndef	_KERNEL
149 # include "ipf.h"
150 # include "ipt.h"
151 extern	int	opts;
152 extern	int	blockreason;
153 #endif /* _KERNEL */
154 
155 #define	LBUMP(x)	softc->x++
156 #define	LBUMPD(x, y)	do { softc->x.y++; DT(y); } while (0)
157 
158 static	INLINE int	ipf_check_ipf(fr_info_t *, frentry_t *, int);
159 static	u_32_t		ipf_checkcipso(fr_info_t *, u_char *, int);
160 static	u_32_t		ipf_checkripso(u_char *);
161 static	u_32_t		ipf_decaps(fr_info_t *, u_32_t, int);
162 #ifdef	IPFILTER_LOG
163 static	frentry_t	*ipf_dolog(fr_info_t *, u_32_t *);
164 #endif
165 static	int		ipf_flushlist(ipf_main_softc_t *, int *, frentry_t **);
166 static	int		ipf_flush_groups(ipf_main_softc_t *, frgroup_t **, int);
167 static	ipfunc_t	ipf_findfunc(ipfunc_t);
168 static	void		*ipf_findlookup(ipf_main_softc_t *, int, frentry_t *,
169 					i6addr_t *, i6addr_t *);
170 static	frentry_t	*ipf_firewall(fr_info_t *, u_32_t *);
171 static	int		ipf_fr_matcharray(fr_info_t *, int *);
172 static	int		ipf_frruleiter(ipf_main_softc_t *, void *, int, void *);
173 static	void		ipf_funcfini(ipf_main_softc_t *, frentry_t *);;
174 static	int		ipf_funcinit(ipf_main_softc_t *, frentry_t *);
175 static	int		ipf_geniter(ipf_main_softc_t *, ipftoken_t *,
176 				    ipfgeniter_t *);
177 static	void		ipf_getstat(ipf_main_softc_t *,
178 				    struct friostat *, int);
179 static	int		ipf_group_flush(ipf_main_softc_t *, frgroup_t *);
180 static	void		ipf_group_free(frgroup_t *);
181 static	int		ipf_grpmapfini(struct ipf_main_softc_s *, frentry_t *);
182 static	int		ipf_grpmapinit(struct ipf_main_softc_s *, frentry_t *);
183 static	frentry_t	*ipf_nextrule(ipf_main_softc_t *, int, int,
184 					frentry_t *, int);
185 static	int		ipf_portcheck(frpcmp_t *, u_32_t);
186 static	INLINE int	ipf_pr_ah(fr_info_t *);
187 static	INLINE void	ipf_pr_esp(fr_info_t *);
188 static	INLINE void	ipf_pr_gre(fr_info_t *);
189 static	INLINE void	ipf_pr_udp(fr_info_t *);
190 static	INLINE void	ipf_pr_tcp(fr_info_t *);
191 static	INLINE void	ipf_pr_icmp(fr_info_t *);
192 static	INLINE void	ipf_pr_ipv4hdr(fr_info_t *);
193 static	INLINE void	ipf_pr_short(fr_info_t *, int);
194 static	INLINE int	ipf_pr_tcpcommon(fr_info_t *);
195 static	INLINE int	ipf_pr_udpcommon(fr_info_t *);
196 static	void		ipf_rule_delete(ipf_main_softc_t *, frentry_t *f,
197 					int, int);
198 static	void		ipf_rule_expire_insert(ipf_main_softc_t *,
199 					       frentry_t *, int);
200 static	int		ipf_synclist(ipf_main_softc_t *, frentry_t *, void *);
201 static	void		ipf_token_flush(ipf_main_softc_t *);
202 static	void		ipf_token_unlink(ipf_main_softc_t *, ipftoken_t *);
203 static	ipftuneable_t	*ipf_tune_findbyname(ipftuneable_t *, const char *);
204 static	ipftuneable_t	*ipf_tune_findbycookie(ipftuneable_t **, void *,
205 					       void **);
206 static	int		ipf_updateipid(fr_info_t *);
207 static	int		ipf_settimeout(struct ipf_main_softc_s *,
208 				       struct ipftuneable *, ipftuneval_t *);
209 
210 
211 /*
212  * bit values for identifying presence of individual IP options
213  * All of these tables should be ordered by increasing key value on the left
214  * hand side to allow for binary searching of the array and include a trailer
215  * with a 0 for the bitmask for linear searches to easily find the end with.
216  */
217 static const	struct	optlist	ipopts[20] = {
218 	{ IPOPT_NOP,	0x000001 },
219 	{ IPOPT_RR,	0x000002 },
220 	{ IPOPT_ZSU,	0x000004 },
221 	{ IPOPT_MTUP,	0x000008 },
222 	{ IPOPT_MTUR,	0x000010 },
223 	{ IPOPT_ENCODE,	0x000020 },
224 	{ IPOPT_TS,	0x000040 },
225 	{ IPOPT_TR,	0x000080 },
226 	{ IPOPT_SECURITY, 0x000100 },
227 	{ IPOPT_LSRR,	0x000200 },
228 	{ IPOPT_E_SEC,	0x000400 },
229 	{ IPOPT_CIPSO,	0x000800 },
230 	{ IPOPT_SATID,	0x001000 },
231 	{ IPOPT_SSRR,	0x002000 },
232 	{ IPOPT_ADDEXT,	0x004000 },
233 	{ IPOPT_VISA,	0x008000 },
234 	{ IPOPT_IMITD,	0x010000 },
235 	{ IPOPT_EIP,	0x020000 },
236 	{ IPOPT_FINN,	0x040000 },
237 	{ 0,		0x000000 }
238 };
239 
240 #ifdef USE_INET6
241 static struct optlist ip6exthdr[] = {
242 	{ IPPROTO_HOPOPTS,		0x000001 },
243 	{ IPPROTO_IPV6,			0x000002 },
244 	{ IPPROTO_ROUTING,		0x000004 },
245 	{ IPPROTO_FRAGMENT,		0x000008 },
246 	{ IPPROTO_ESP,			0x000010 },
247 	{ IPPROTO_AH,			0x000020 },
248 	{ IPPROTO_NONE,			0x000040 },
249 	{ IPPROTO_DSTOPTS,		0x000080 },
250 	{ IPPROTO_MOBILITY,		0x000100 },
251 	{ 0,				0 }
252 };
253 #endif
254 
255 /*
256  * bit values for identifying presence of individual IP security options
257  */
258 static const	struct	optlist	secopt[8] = {
259 	{ IPSO_CLASS_RES4,	0x01 },
260 	{ IPSO_CLASS_TOPS,	0x02 },
261 	{ IPSO_CLASS_SECR,	0x04 },
262 	{ IPSO_CLASS_RES3,	0x08 },
263 	{ IPSO_CLASS_CONF,	0x10 },
264 	{ IPSO_CLASS_UNCL,	0x20 },
265 	{ IPSO_CLASS_RES2,	0x40 },
266 	{ IPSO_CLASS_RES1,	0x80 }
267 };
268 
269 char	ipfilter_version[] = IPL_VERSION;
270 
271 int	ipf_features = 0
272 #ifdef	IPFILTER_LKM
273 		| IPF_FEAT_LKM
274 #endif
275 #ifdef	IPFILTER_LOG
276 		| IPF_FEAT_LOG
277 #endif
278 		| IPF_FEAT_LOOKUP
279 #ifdef	IPFILTER_BPF
280 		| IPF_FEAT_BPF
281 #endif
282 #ifdef	IPFILTER_COMPILED
283 		| IPF_FEAT_COMPILED
284 #endif
285 #ifdef	IPFILTER_CKSUM
286 		| IPF_FEAT_CKSUM
287 #endif
288 		| IPF_FEAT_SYNC
289 #ifdef	IPFILTER_SCAN
290 		| IPF_FEAT_SCAN
291 #endif
292 #ifdef	USE_INET6
293 		| IPF_FEAT_IPV6
294 #endif
295 	;
296 
297 
298 /*
299  * Table of functions available for use with call rules.
300  */
301 static ipfunc_resolve_t ipf_availfuncs[] = {
302 	{ "srcgrpmap", ipf_srcgrpmap, ipf_grpmapinit, ipf_grpmapfini },
303 	{ "dstgrpmap", ipf_dstgrpmap, ipf_grpmapinit, ipf_grpmapfini },
304 	{ "",	       NULL,	      NULL,	      NULL }
305 };
306 
307 static ipftuneable_t ipf_main_tuneables[] = {
308 	{ { (void *)offsetof(struct ipf_main_softc_s, ipf_flags) },
309 		"ipf_flags",		0,	0xffffffff,
310 		stsizeof(ipf_main_softc_t, ipf_flags),
311 		0,			NULL,	NULL },
312 	{ { (void *)offsetof(struct ipf_main_softc_s, ipf_active) },
313 		"active",		0,	0,
314 		stsizeof(ipf_main_softc_t, ipf_active),
315 		IPFT_RDONLY,		NULL,	NULL },
316 	{ { (void *)offsetof(ipf_main_softc_t, ipf_control_forwarding) },
317 		"control_forwarding",	0, 1,
318 		stsizeof(ipf_main_softc_t, ipf_control_forwarding),
319 		0,			NULL,	NULL },
320 	{ { (void *)offsetof(ipf_main_softc_t, ipf_update_ipid) },
321 		"update_ipid",		0,	1,
322 		stsizeof(ipf_main_softc_t, ipf_update_ipid),
323 		0,			NULL,	NULL },
324 	{ { (void *)offsetof(ipf_main_softc_t, ipf_chksrc) },
325 		"chksrc",		0,	1,
326 		stsizeof(ipf_main_softc_t, ipf_chksrc),
327 		0,			NULL,	NULL },
328 	{ { (void *)offsetof(ipf_main_softc_t, ipf_minttl) },
329 		"min_ttl",		0,	1,
330 		stsizeof(ipf_main_softc_t, ipf_minttl),
331 		0,			NULL,	NULL },
332 	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmpminfragmtu) },
333 		"icmp_minfragmtu",	0,	1,
334 		stsizeof(ipf_main_softc_t, ipf_icmpminfragmtu),
335 		0,			NULL,	NULL },
336 	{ { (void *)offsetof(ipf_main_softc_t, ipf_pass) },
337 		"default_pass",		0,	0xffffffff,
338 		stsizeof(ipf_main_softc_t, ipf_pass),
339 		0,			NULL,	NULL },
340 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpidletimeout) },
341 		"tcp_idle_timeout",	1,	0x7fffffff,
342 		stsizeof(ipf_main_softc_t, ipf_tcpidletimeout),
343 		0,			NULL,	ipf_settimeout },
344 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosewait) },
345 		"tcp_close_wait",	1,	0x7fffffff,
346 		stsizeof(ipf_main_softc_t, ipf_tcpclosewait),
347 		0,			NULL,	ipf_settimeout },
348 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcplastack) },
349 		"tcp_last_ack",		1,	0x7fffffff,
350 		stsizeof(ipf_main_softc_t, ipf_tcplastack),
351 		0,			NULL,	ipf_settimeout },
352 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcptimeout) },
353 		"tcp_timeout",		1,	0x7fffffff,
354 		stsizeof(ipf_main_softc_t, ipf_tcptimeout),
355 		0,			NULL,	ipf_settimeout },
356 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynsent) },
357 		"tcp_syn_sent",		1,	0x7fffffff,
358 		stsizeof(ipf_main_softc_t, ipf_tcpsynsent),
359 		0,			NULL,	ipf_settimeout },
360 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynrecv) },
361 		"tcp_syn_received",	1,	0x7fffffff,
362 		stsizeof(ipf_main_softc_t, ipf_tcpsynrecv),
363 		0,			NULL,	ipf_settimeout },
364 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosed) },
365 		"tcp_closed",		1,	0x7fffffff,
366 		stsizeof(ipf_main_softc_t, ipf_tcpclosed),
367 		0,			NULL,	ipf_settimeout },
368 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcphalfclosed) },
369 		"tcp_half_closed",	1,	0x7fffffff,
370 		stsizeof(ipf_main_softc_t, ipf_tcphalfclosed),
371 		0,			NULL,	ipf_settimeout },
372 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcptimewait) },
373 		"tcp_time_wait",	1,	0x7fffffff,
374 		stsizeof(ipf_main_softc_t, ipf_tcptimewait),
375 		0,			NULL,	ipf_settimeout },
376 	{ { (void *)offsetof(ipf_main_softc_t, ipf_udptimeout) },
377 		"udp_timeout",		1,	0x7fffffff,
378 		stsizeof(ipf_main_softc_t, ipf_udptimeout),
379 		0,			NULL,	ipf_settimeout },
380 	{ { (void *)offsetof(ipf_main_softc_t, ipf_udpacktimeout) },
381 		"udp_ack_timeout",	1,	0x7fffffff,
382 		stsizeof(ipf_main_softc_t, ipf_udpacktimeout),
383 		0,			NULL,	ipf_settimeout },
384 	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmptimeout) },
385 		"icmp_timeout",		1,	0x7fffffff,
386 		stsizeof(ipf_main_softc_t, ipf_icmptimeout),
387 		0,			NULL,	ipf_settimeout },
388 	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmpacktimeout) },
389 		"icmp_ack_timeout",	1,	0x7fffffff,
390 		stsizeof(ipf_main_softc_t, ipf_icmpacktimeout),
391 		0,			NULL,	ipf_settimeout },
392 	{ { (void *)offsetof(ipf_main_softc_t, ipf_iptimeout) },
393 		"ip_timeout",		1,	0x7fffffff,
394 		stsizeof(ipf_main_softc_t, ipf_iptimeout),
395 		0,			NULL,	ipf_settimeout },
396 #if defined(INSTANCES) && defined(_KERNEL)
397 	{ { (void *)offsetof(ipf_main_softc_t, ipf_get_loopback) },
398 		"intercept_loopback",	0,	1,
399 		stsizeof(ipf_main_softc_t, ipf_get_loopback),
400 		0,			NULL,	ipf_set_loopback },
401 #endif
402 	{ { 0 },
403 		NULL,			0,	0,
404 		0,
405 		0,			NULL,	NULL }
406 };
407 
408 
409 /*
410  * The next section of code is a a collection of small routines that set
411  * fields in the fr_info_t structure passed based on properties of the
412  * current packet.  There are different routines for the same protocol
413  * for each of IPv4 and IPv6.  Adding a new protocol, for which there
414  * will "special" inspection for setup, is now more easily done by adding
415  * a new routine and expanding the ipf_pr_ipinit*() function rather than by
416  * adding more code to a growing switch statement.
417  */
418 #ifdef USE_INET6
419 static	INLINE int	ipf_pr_ah6(fr_info_t *);
420 static	INLINE void	ipf_pr_esp6(fr_info_t *);
421 static	INLINE void	ipf_pr_gre6(fr_info_t *);
422 static	INLINE void	ipf_pr_udp6(fr_info_t *);
423 static	INLINE void	ipf_pr_tcp6(fr_info_t *);
424 static	INLINE void	ipf_pr_icmp6(fr_info_t *);
425 static	INLINE void	ipf_pr_ipv6hdr(fr_info_t *);
426 static	INLINE void	ipf_pr_short6(fr_info_t *, int);
427 static	INLINE int	ipf_pr_hopopts6(fr_info_t *);
428 static	INLINE int	ipf_pr_mobility6(fr_info_t *);
429 static	INLINE int	ipf_pr_routing6(fr_info_t *);
430 static	INLINE int	ipf_pr_dstopts6(fr_info_t *);
431 static	INLINE int	ipf_pr_fragment6(fr_info_t *);
432 static	INLINE struct ip6_ext *ipf_pr_ipv6exthdr(fr_info_t *, int, int);
433 
434 
435 /* ------------------------------------------------------------------------ */
436 /* Function:    ipf_pr_short6                                               */
437 /* Returns:     void                                                        */
438 /* Parameters:  fin(I)  - pointer to packet information                     */
439 /*              xmin(I) - minimum header size                               */
440 /*                                                                          */
441 /* IPv6 Only                                                                */
442 /* This is function enforces the 'is a packet too short to be legit' rule   */
443 /* for IPv6 and marks the packet with FI_SHORT if so.  See function comment */
444 /* for ipf_pr_short() for more details.                                     */
445 /* ------------------------------------------------------------------------ */
446 static INLINE void
447 ipf_pr_short6(fr_info_t *fin, int xmin)
448 {
449 
450 	if (fin->fin_dlen < xmin)
451 		fin->fin_flx |= FI_SHORT;
452 }
453 
454 
455 /* ------------------------------------------------------------------------ */
456 /* Function:    ipf_pr_ipv6hdr                                              */
457 /* Returns:     void                                                        */
458 /* Parameters:  fin(I) - pointer to packet information                      */
459 /*                                                                          */
460 /* IPv6 Only                                                                */
461 /* Copy values from the IPv6 header into the fr_info_t struct and call the  */
462 /* per-protocol analyzer if it exists.  In validating the packet, a protocol*/
463 /* analyzer may pullup or free the packet itself so we need to be vigiliant */
464 /* of that possibility arising.                                             */
465 /* ------------------------------------------------------------------------ */
466 static INLINE void
467 ipf_pr_ipv6hdr(fr_info_t *fin)
468 {
469 	ip6_t *ip6 = (ip6_t *)fin->fin_ip;
470 	int p, go = 1, i, hdrcount;
471 	fr_ip_t *fi = &fin->fin_fi;
472 
473 	fin->fin_off = 0;
474 
475 	fi->fi_tos = 0;
476 	fi->fi_optmsk = 0;
477 	fi->fi_secmsk = 0;
478 	fi->fi_auth = 0;
479 
480 	p = ip6->ip6_nxt;
481 	fin->fin_crc = p;
482 	fi->fi_ttl = ip6->ip6_hlim;
483 	fi->fi_src.in6 = ip6->ip6_src;
484 	fin->fin_crc += fi->fi_src.i6[0];
485 	fin->fin_crc += fi->fi_src.i6[1];
486 	fin->fin_crc += fi->fi_src.i6[2];
487 	fin->fin_crc += fi->fi_src.i6[3];
488 	fi->fi_dst.in6 = ip6->ip6_dst;
489 	fin->fin_crc += fi->fi_dst.i6[0];
490 	fin->fin_crc += fi->fi_dst.i6[1];
491 	fin->fin_crc += fi->fi_dst.i6[2];
492 	fin->fin_crc += fi->fi_dst.i6[3];
493 	fin->fin_id = 0;
494 	if (IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
495 		fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
496 
497 	hdrcount = 0;
498 	while (go && !(fin->fin_flx & FI_SHORT)) {
499 		switch (p)
500 		{
501 		case IPPROTO_UDP :
502 			ipf_pr_udp6(fin);
503 			go = 0;
504 			break;
505 
506 		case IPPROTO_TCP :
507 			ipf_pr_tcp6(fin);
508 			go = 0;
509 			break;
510 
511 		case IPPROTO_ICMPV6 :
512 			ipf_pr_icmp6(fin);
513 			go = 0;
514 			break;
515 
516 		case IPPROTO_GRE :
517 			ipf_pr_gre6(fin);
518 			go = 0;
519 			break;
520 
521 		case IPPROTO_HOPOPTS :
522 			p = ipf_pr_hopopts6(fin);
523 			break;
524 
525 		case IPPROTO_MOBILITY :
526 			p = ipf_pr_mobility6(fin);
527 			break;
528 
529 		case IPPROTO_DSTOPTS :
530 			p = ipf_pr_dstopts6(fin);
531 			break;
532 
533 		case IPPROTO_ROUTING :
534 			p = ipf_pr_routing6(fin);
535 			break;
536 
537 		case IPPROTO_AH :
538 			p = ipf_pr_ah6(fin);
539 			break;
540 
541 		case IPPROTO_ESP :
542 			ipf_pr_esp6(fin);
543 			go = 0;
544 			break;
545 
546 		case IPPROTO_IPV6 :
547 			for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
548 				if (ip6exthdr[i].ol_val == p) {
549 					fin->fin_flx |= ip6exthdr[i].ol_bit;
550 					break;
551 				}
552 			go = 0;
553 			break;
554 
555 		case IPPROTO_NONE :
556 			go = 0;
557 			break;
558 
559 		case IPPROTO_FRAGMENT :
560 			p = ipf_pr_fragment6(fin);
561 			/*
562 			 * Given that the only fragments we want to let through
563 			 * (where fin_off != 0) are those where the non-first
564 			 * fragments only have data, we can safely stop looking
565 			 * at headers if this is a non-leading fragment.
566 			 */
567 			if (fin->fin_off != 0)
568 				go = 0;
569 			break;
570 
571 		default :
572 			go = 0;
573 			break;
574 		}
575 		hdrcount++;
576 
577 		/*
578 		 * It is important to note that at this point, for the
579 		 * extension headers (go != 0), the entire header may not have
580 		 * been pulled up when the code gets to this point.  This is
581 		 * only done for "go != 0" because the other header handlers
582 		 * will all pullup their complete header.  The other indicator
583 		 * of an incomplete packet is that this was just an extension
584 		 * header.
585 		 */
586 		if ((go != 0) && (p != IPPROTO_NONE) &&
587 		    (ipf_pr_pullup(fin, 0) == -1)) {
588 			p = IPPROTO_NONE;
589 			break;
590 		}
591 	}
592 
593 	/*
594 	 * Some of the above functions, like ipf_pr_esp6(), can call ipf_pullup
595 	 * and destroy whatever packet was here.  The caller of this function
596 	 * expects us to return if there is a problem with ipf_pullup.
597 	 */
598 	if (fin->fin_m == NULL) {
599 		ipf_main_softc_t *softc = fin->fin_main_soft;
600 
601 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_bad);
602 		return;
603 	}
604 
605 	fi->fi_p = p;
606 
607 	/*
608 	 * IPv6 fragment case 1 - see comment for ipf_pr_fragment6().
609 	 * "go != 0" imples the above loop hasn't arrived at a layer 4 header.
610 	 */
611 	if ((go != 0) && (fin->fin_flx & FI_FRAG) && (fin->fin_off == 0)) {
612 		ipf_main_softc_t *softc = fin->fin_main_soft;
613 
614 		fin->fin_flx |= FI_BAD;
615 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_badfrag);
616 		LBUMP(ipf_stats[fin->fin_out].fr_v6_bad);
617 	}
618 }
619 
620 
621 /* ------------------------------------------------------------------------ */
622 /* Function:    ipf_pr_ipv6exthdr                                           */
623 /* Returns:     struct ip6_ext * - pointer to the start of the next header  */
624 /*                                 or NULL if there is a prolblem.          */
625 /* Parameters:  fin(I)      - pointer to packet information                 */
626 /*              multiple(I) - flag indicating yes/no if multiple occurances */
627 /*                            of this extension header are allowed.         */
628 /*              proto(I)    - protocol number for this extension header     */
629 /*                                                                          */
630 /* IPv6 Only                                                                */
631 /* This function embodies a number of common checks that all IPv6 extension */
632 /* headers must be subjected to.  For example, making sure the packet is    */
633 /* big enough for it to be in, checking if it is repeated and setting a     */
634 /* flag to indicate its presence.                                           */
635 /* ------------------------------------------------------------------------ */
636 static INLINE struct ip6_ext *
637 ipf_pr_ipv6exthdr(fr_info_t *fin, int multiple, int proto)
638 {
639 	ipf_main_softc_t *softc = fin->fin_main_soft;
640 	struct ip6_ext *hdr;
641 	u_short shift;
642 	int i;
643 
644 	fin->fin_flx |= FI_V6EXTHDR;
645 
646 				/* 8 is default length of extension hdr */
647 	if ((fin->fin_dlen - 8) < 0) {
648 		fin->fin_flx |= FI_SHORT;
649 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_short);
650 		return NULL;
651 	}
652 
653 	if (ipf_pr_pullup(fin, 8) == -1) {
654 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_pullup);
655 		return NULL;
656 	}
657 
658 	hdr = fin->fin_dp;
659 	switch (proto)
660 	{
661 	case IPPROTO_FRAGMENT :
662 		shift = 8;
663 		break;
664 	default :
665 		shift = 8 + (hdr->ip6e_len << 3);
666 		break;
667 	}
668 
669 	if (shift > fin->fin_dlen) {	/* Nasty extension header length? */
670 		fin->fin_flx |= FI_BAD;
671 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_hlen);
672 		return NULL;
673 	}
674 
675 	fin->fin_dp = (char *)fin->fin_dp + shift;
676 	fin->fin_dlen -= shift;
677 
678 	/*
679 	 * If we have seen a fragment header, do not set any flags to indicate
680 	 * the presence of this extension header as it has no impact on the
681 	 * end result until after it has been defragmented.
682 	 */
683 	if (fin->fin_flx & FI_FRAG)
684 		return hdr;
685 
686 	for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
687 		if (ip6exthdr[i].ol_val == proto) {
688 			/*
689 			 * Most IPv6 extension headers are only allowed once.
690 			 */
691 			if ((multiple == 0) &&
692 			    ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0))
693 				fin->fin_flx |= FI_BAD;
694 			else
695 				fin->fin_optmsk |= ip6exthdr[i].ol_bit;
696 			break;
697 		}
698 
699 	return hdr;
700 }
701 
702 
703 /* ------------------------------------------------------------------------ */
704 /* Function:    ipf_pr_hopopts6                                             */
705 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
706 /* Parameters:  fin(I) - pointer to packet information                      */
707 /*                                                                          */
708 /* IPv6 Only                                                                */
709 /* This is function checks pending hop by hop options extension header      */
710 /* ------------------------------------------------------------------------ */
711 static INLINE int
712 ipf_pr_hopopts6(fr_info_t *fin)
713 {
714 	struct ip6_ext *hdr;
715 
716 	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
717 	if (hdr == NULL)
718 		return IPPROTO_NONE;
719 	return hdr->ip6e_nxt;
720 }
721 
722 
723 /* ------------------------------------------------------------------------ */
724 /* Function:    ipf_pr_mobility6                                            */
725 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
726 /* Parameters:  fin(I) - pointer to packet information                      */
727 /*                                                                          */
728 /* IPv6 Only                                                                */
729 /* This is function checks the IPv6 mobility extension header               */
730 /* ------------------------------------------------------------------------ */
731 static INLINE int
732 ipf_pr_mobility6(fr_info_t *fin)
733 {
734 	struct ip6_ext *hdr;
735 
736 	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_MOBILITY);
737 	if (hdr == NULL)
738 		return IPPROTO_NONE;
739 	return hdr->ip6e_nxt;
740 }
741 
742 
743 /* ------------------------------------------------------------------------ */
744 /* Function:    ipf_pr_routing6                                             */
745 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
746 /* Parameters:  fin(I) - pointer to packet information                      */
747 /*                                                                          */
748 /* IPv6 Only                                                                */
749 /* This is function checks pending routing extension header                 */
750 /* ------------------------------------------------------------------------ */
751 static INLINE int
752 ipf_pr_routing6(fr_info_t *fin)
753 {
754 	struct ip6_routing *hdr;
755 
756 	hdr = (struct ip6_routing *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_ROUTING);
757 	if (hdr == NULL)
758 		return IPPROTO_NONE;
759 
760 	switch (hdr->ip6r_type)
761 	{
762 	case 0 :
763 		/*
764 		 * Nasty extension header length?
765 		 */
766 		if (((hdr->ip6r_len >> 1) < hdr->ip6r_segleft) ||
767 		    (hdr->ip6r_segleft && (hdr->ip6r_len & 1))) {
768 			ipf_main_softc_t *softc = fin->fin_main_soft;
769 
770 			fin->fin_flx |= FI_BAD;
771 			LBUMPD(ipf_stats[fin->fin_out], fr_v6_rh_bad);
772 			return IPPROTO_NONE;
773 		}
774 		break;
775 
776 	default :
777 		break;
778 	}
779 
780 	return hdr->ip6r_nxt;
781 }
782 
783 
784 /* ------------------------------------------------------------------------ */
785 /* Function:    ipf_pr_fragment6                                            */
786 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
787 /* Parameters:  fin(I) - pointer to packet information                      */
788 /*                                                                          */
789 /* IPv6 Only                                                                */
790 /* Examine the IPv6 fragment header and extract fragment offset information.*/
791 /*                                                                          */
792 /* Fragments in IPv6 are extraordinarily difficult to deal with - much more */
793 /* so than in IPv4.  There are 5 cases of fragments with IPv6 that all      */
794 /* packets with a fragment header can fit into.  They are as follows:       */
795 /*                                                                          */
796 /* 1.  [IPv6][0-n EH][FH][0-n EH] (no L4HDR present)                        */
797 /* 2.  [IPV6][0-n EH][FH][0-n EH][L4HDR part] (short)                       */
798 /* 3.  [IPV6][0-n EH][FH][L4HDR part][0-n data] (short)                     */
799 /* 4.  [IPV6][0-n EH][FH][0-n EH][L4HDR][0-n data]                          */
800 /* 5.  [IPV6][0-n EH][FH][data]                                             */
801 /*                                                                          */
802 /* IPV6 = IPv6 header, FH = Fragment Header,                                */
803 /* 0-n EH = 0 or more extension headers, 0-n data = 0 or more bytes of data */
804 /*                                                                          */
805 /* Packets that match 1, 2, 3 will be dropped as the only reasonable        */
806 /* scenario in which they happen is in extreme circumstances that are most  */
807 /* likely to be an indication of an attack rather than normal traffic.      */
808 /* A type 3 packet may be sent by an attacked after a type 4 packet.  There */
809 /* are two rules that can be used to guard against type 3 packets: L4       */
810 /* headers must always be in a packet that has the offset field set to 0    */
811 /* and no packet is allowed to overlay that where offset = 0.               */
812 /* ------------------------------------------------------------------------ */
813 static INLINE int
814 ipf_pr_fragment6(fr_info_t *fin)
815 {
816 	ipf_main_softc_t *softc = fin->fin_main_soft;
817 	struct ip6_frag *frag;
818 
819 	fin->fin_flx |= FI_FRAG;
820 
821 	frag = (struct ip6_frag *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT);
822 	if (frag == NULL) {
823 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_frag_bad);
824 		return IPPROTO_NONE;
825 	}
826 
827 	if ((frag->ip6f_offlg & IP6F_MORE_FRAG) != 0) {
828 		/*
829 		 * Any fragment that isn't the last fragment must have its
830 		 * length as a multiple of 8.
831 		 */
832 		if ((fin->fin_plen & 7) != 0)
833 			fin->fin_flx |= FI_BAD;
834 	}
835 
836 	fin->fin_fraghdr = frag;
837 	fin->fin_id = frag->ip6f_ident;
838 	fin->fin_off = ntohs(frag->ip6f_offlg & IP6F_OFF_MASK);
839 	if (fin->fin_off != 0)
840 		fin->fin_flx |= FI_FRAGBODY;
841 
842 	/*
843 	 * Jumbograms aren't handled, so the max. length is 64k
844 	 */
845 	if ((fin->fin_off << 3) + fin->fin_dlen > 65535)
846 		  fin->fin_flx |= FI_BAD;
847 
848 	/*
849 	 * We don't know where the transport layer header (or whatever is next
850 	 * is), as it could be behind destination options (amongst others) so
851 	 * return the fragment header as the type of packet this is.  Note that
852 	 * this effectively disables the fragment cache for > 1 protocol at a
853 	 * time.
854 	 */
855 	return frag->ip6f_nxt;
856 }
857 
858 
859 /* ------------------------------------------------------------------------ */
860 /* Function:    ipf_pr_dstopts6                                             */
861 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
862 /* Parameters:  fin(I) - pointer to packet information                      */
863 /*                                                                          */
864 /* IPv6 Only                                                                */
865 /* This is function checks pending destination options extension header     */
866 /* ------------------------------------------------------------------------ */
867 static INLINE int
868 ipf_pr_dstopts6(fr_info_t *fin)
869 {
870 	ipf_main_softc_t *softc = fin->fin_main_soft;
871 	struct ip6_ext *hdr;
872 
873 	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_DSTOPTS);
874 	if (hdr == NULL) {
875 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_dst_bad);
876 		return IPPROTO_NONE;
877 	}
878 	return hdr->ip6e_nxt;
879 }
880 
881 
882 /* ------------------------------------------------------------------------ */
883 /* Function:    ipf_pr_icmp6                                                */
884 /* Returns:     void                                                        */
885 /* Parameters:  fin(I) - pointer to packet information                      */
886 /*                                                                          */
887 /* IPv6 Only                                                                */
888 /* This routine is mainly concerned with determining the minimum valid size */
889 /* for an ICMPv6 packet.                                                    */
890 /* ------------------------------------------------------------------------ */
891 static INLINE void
892 ipf_pr_icmp6(fr_info_t *fin)
893 {
894 	int minicmpsz = sizeof(struct icmp6_hdr);
895 	struct icmp6_hdr *icmp6;
896 
897 	if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1) {
898 		ipf_main_softc_t *softc = fin->fin_main_soft;
899 
900 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_icmp6_pullup);
901 		return;
902 	}
903 
904 	if (fin->fin_dlen > 1) {
905 		ip6_t *ip6;
906 
907 		icmp6 = fin->fin_dp;
908 
909 		fin->fin_data[0] = *(u_short *)icmp6;
910 
911 		if ((icmp6->icmp6_type & ICMP6_INFOMSG_MASK) != 0)
912 			fin->fin_flx |= FI_ICMPQUERY;
913 
914 		switch (icmp6->icmp6_type)
915 		{
916 		case ICMP6_ECHO_REPLY :
917 		case ICMP6_ECHO_REQUEST :
918 			if (fin->fin_dlen >= 6)
919 				fin->fin_data[1] = icmp6->icmp6_id;
920 			minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
921 			break;
922 
923 		case ICMP6_DST_UNREACH :
924 		case ICMP6_PACKET_TOO_BIG :
925 		case ICMP6_TIME_EXCEEDED :
926 		case ICMP6_PARAM_PROB :
927 			fin->fin_flx |= FI_ICMPERR;
928 			minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
929 			if (fin->fin_plen < ICMP6ERR_IPICMPHLEN)
930 				break;
931 
932 			if (M_LEN(fin->fin_m) < fin->fin_plen) {
933 				if (ipf_coalesce(fin) != 1)
934 					return;
935 			}
936 
937 			if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN) == -1)
938 				return;
939 
940 			/*
941 			 * If the destination of this packet doesn't match the
942 			 * source of the original packet then this packet is
943 			 * not correct.
944 			 */
945 			icmp6 = fin->fin_dp;
946 			ip6 = (ip6_t *)((char *)icmp6 + ICMPERR_ICMPHLEN);
947 			if (IP6_NEQ(&fin->fin_fi.fi_dst,
948 				    &ip6->ip6_src))
949 				fin->fin_flx |= FI_BAD;
950 			break;
951 		default :
952 			break;
953 		}
954 	}
955 
956 	ipf_pr_short6(fin, minicmpsz);
957 	if ((fin->fin_flx & (FI_SHORT|FI_BAD)) == 0) {
958 		u_char p = fin->fin_p;
959 
960 		fin->fin_p = IPPROTO_ICMPV6;
961 		ipf_checkv6sum(fin);
962 		fin->fin_p = p;
963 	}
964 }
965 
966 
967 /* ------------------------------------------------------------------------ */
968 /* Function:    ipf_pr_udp6                                                 */
969 /* Returns:     void                                                        */
970 /* Parameters:  fin(I) - pointer to packet information                      */
971 /*                                                                          */
972 /* IPv6 Only                                                                */
973 /* Analyse the packet for IPv6/UDP properties.                              */
974 /* Is not expected to be called for fragmented packets.                     */
975 /* ------------------------------------------------------------------------ */
976 static INLINE void
977 ipf_pr_udp6(fr_info_t *fin)
978 {
979 
980 	if (ipf_pr_udpcommon(fin) == 0) {
981 		u_char p = fin->fin_p;
982 
983 		fin->fin_p = IPPROTO_UDP;
984 		ipf_checkv6sum(fin);
985 		fin->fin_p = p;
986 	}
987 }
988 
989 
990 /* ------------------------------------------------------------------------ */
991 /* Function:    ipf_pr_tcp6                                                 */
992 /* Returns:     void                                                        */
993 /* Parameters:  fin(I) - pointer to packet information                      */
994 /*                                                                          */
995 /* IPv6 Only                                                                */
996 /* Analyse the packet for IPv6/TCP properties.                              */
997 /* Is not expected to be called for fragmented packets.                     */
998 /* ------------------------------------------------------------------------ */
999 static INLINE void
1000 ipf_pr_tcp6(fr_info_t *fin)
1001 {
1002 
1003 	if (ipf_pr_tcpcommon(fin) == 0) {
1004 		u_char p = fin->fin_p;
1005 
1006 		fin->fin_p = IPPROTO_TCP;
1007 		ipf_checkv6sum(fin);
1008 		fin->fin_p = p;
1009 	}
1010 }
1011 
1012 
1013 /* ------------------------------------------------------------------------ */
1014 /* Function:    ipf_pr_esp6                                                 */
1015 /* Returns:     void                                                        */
1016 /* Parameters:  fin(I) - pointer to packet information                      */
1017 /*                                                                          */
1018 /* IPv6 Only                                                                */
1019 /* Analyse the packet for ESP properties.                                   */
1020 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
1021 /* even though the newer ESP packets must also have a sequence number that  */
1022 /* is 32bits as well, it is not possible(?) to determine the version from a */
1023 /* simple packet header.                                                    */
1024 /* ------------------------------------------------------------------------ */
1025 static INLINE void
1026 ipf_pr_esp6(fr_info_t *fin)
1027 {
1028 
1029 	if ((fin->fin_off == 0) && (ipf_pr_pullup(fin, 8) == -1)) {
1030 		ipf_main_softc_t *softc = fin->fin_main_soft;
1031 
1032 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_esp_pullup);
1033 		return;
1034 	}
1035 }
1036 
1037 
1038 /* ------------------------------------------------------------------------ */
1039 /* Function:    ipf_pr_ah6                                                  */
1040 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
1041 /* Parameters:  fin(I) - pointer to packet information                      */
1042 /*                                                                          */
1043 /* IPv6 Only                                                                */
1044 /* Analyse the packet for AH properties.                                    */
1045 /* The minimum length is taken to be the combination of all fields in the   */
1046 /* header being present and no authentication data (null algorithm used.)   */
1047 /* ------------------------------------------------------------------------ */
1048 static INLINE int
1049 ipf_pr_ah6(fr_info_t *fin)
1050 {
1051 	authhdr_t *ah;
1052 
1053 	fin->fin_flx |= FI_AH;
1054 
1055 	ah = (authhdr_t *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
1056 	if (ah == NULL) {
1057 		ipf_main_softc_t *softc = fin->fin_main_soft;
1058 
1059 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ah_bad);
1060 		return IPPROTO_NONE;
1061 	}
1062 
1063 	ipf_pr_short6(fin, sizeof(*ah));
1064 
1065 	/*
1066 	 * No need for another pullup, ipf_pr_ipv6exthdr() will pullup
1067 	 * enough data to satisfy ah_next (the very first one.)
1068 	 */
1069 	return ah->ah_next;
1070 }
1071 
1072 
1073 /* ------------------------------------------------------------------------ */
1074 /* Function:    ipf_pr_gre6                                                 */
1075 /* Returns:     void                                                        */
1076 /* Parameters:  fin(I) - pointer to packet information                      */
1077 /*                                                                          */
1078 /* Analyse the packet for GRE properties.                                   */
1079 /* ------------------------------------------------------------------------ */
1080 static INLINE void
1081 ipf_pr_gre6(fr_info_t *fin)
1082 {
1083 	grehdr_t *gre;
1084 
1085 	if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1086 		ipf_main_softc_t *softc = fin->fin_main_soft;
1087 
1088 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_gre_pullup);
1089 		return;
1090 	}
1091 
1092 	gre = fin->fin_dp;
1093 	if (GRE_REV(gre->gr_flags) == 1)
1094 		fin->fin_data[0] = gre->gr_call;
1095 }
1096 #endif	/* USE_INET6 */
1097 
1098 
1099 /* ------------------------------------------------------------------------ */
1100 /* Function:    ipf_pr_pullup                                               */
1101 /* Returns:     int     - 0 == pullup succeeded, -1 == failure              */
1102 /* Parameters:  fin(I)  - pointer to packet information                     */
1103 /*              plen(I) - length (excluding L3 header) to pullup            */
1104 /*                                                                          */
1105 /* Short inline function to cut down on code duplication to perform a call  */
1106 /* to ipf_pullup to ensure there is the required amount of data,            */
1107 /* consecutively in the packet buffer.                                      */
1108 /*                                                                          */
1109 /* This function pulls up 'extra' data at the location of fin_dp.  fin_dp   */
1110 /* points to the first byte after the complete layer 3 header, which will   */
1111 /* include all of the known extension headers for IPv6 or options for IPv4. */
1112 /*                                                                          */
1113 /* Since fr_pullup() expects the total length of bytes to be pulled up, it  */
1114 /* is necessary to add those we can already assume to be pulled up (fin_dp  */
1115 /* - fin_ip) to what is passed through.                                     */
1116 /* ------------------------------------------------------------------------ */
1117 int
1118 ipf_pr_pullup(fr_info_t *fin, int plen)
1119 {
1120 	ipf_main_softc_t *softc = fin->fin_main_soft;
1121 
1122 	if (fin->fin_m != NULL) {
1123 		if (fin->fin_dp != NULL)
1124 			plen += (char *)fin->fin_dp -
1125 				((char *)fin->fin_ip + fin->fin_hlen);
1126 		plen += fin->fin_hlen;
1127 		if (M_LEN(fin->fin_m) < plen + fin->fin_ipoff) {
1128 #if defined(_KERNEL)
1129 			if (ipf_pullup(fin->fin_m, fin, plen) == NULL) {
1130 				DT(ipf_pullup_fail);
1131 				LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1132 				return -1;
1133 			}
1134 			LBUMP(ipf_stats[fin->fin_out].fr_pull[0]);
1135 #else
1136 			LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1137 			/*
1138 			 * Fake ipf_pullup failing
1139 			 */
1140 			fin->fin_reason = FRB_PULLUP;
1141 			*fin->fin_mp = NULL;
1142 			fin->fin_m = NULL;
1143 			fin->fin_ip = NULL;
1144 			return -1;
1145 #endif
1146 		}
1147 	}
1148 	return 0;
1149 }
1150 
1151 
1152 /* ------------------------------------------------------------------------ */
1153 /* Function:    ipf_pr_short                                                */
1154 /* Returns:     void                                                        */
1155 /* Parameters:  fin(I)  - pointer to packet information                     */
1156 /*              xmin(I) - minimum header size                               */
1157 /*                                                                          */
1158 /* Check if a packet is "short" as defined by xmin.  The rule we are        */
1159 /* applying here is that the packet must not be fragmented within the layer */
1160 /* 4 header.  That is, it must not be a fragment that has its offset set to */
1161 /* start within the layer 4 header (hdrmin) or if it is at offset 0, the    */
1162 /* entire layer 4 header must be present (min).                             */
1163 /* ------------------------------------------------------------------------ */
1164 static INLINE void
1165 ipf_pr_short(fr_info_t *fin, int xmin)
1166 {
1167 
1168 	if (fin->fin_off == 0) {
1169 		if (fin->fin_dlen < xmin)
1170 			fin->fin_flx |= FI_SHORT;
1171 	} else if (fin->fin_off < xmin) {
1172 		fin->fin_flx |= FI_SHORT;
1173 	}
1174 }
1175 
1176 
1177 /* ------------------------------------------------------------------------ */
1178 /* Function:    ipf_pr_icmp                                                 */
1179 /* Returns:     void                                                        */
1180 /* Parameters:  fin(I) - pointer to packet information                      */
1181 /*                                                                          */
1182 /* IPv4 Only                                                                */
1183 /* Do a sanity check on the packet for ICMP (v4).  In nearly all cases,     */
1184 /* except extrememly bad packets, both type and code will be present.       */
1185 /* The expected minimum size of an ICMP packet is very much dependent on    */
1186 /* the type of it.                                                          */
1187 /*                                                                          */
1188 /* XXX - other ICMP sanity checks?                                          */
1189 /* ------------------------------------------------------------------------ */
1190 static INLINE void
1191 ipf_pr_icmp(fr_info_t *fin)
1192 {
1193 	ipf_main_softc_t *softc = fin->fin_main_soft;
1194 	int minicmpsz = sizeof(struct icmp);
1195 	icmphdr_t *icmp;
1196 	ip_t *oip;
1197 
1198 	ipf_pr_short(fin, ICMPERR_ICMPHLEN);
1199 
1200 	if (fin->fin_off != 0) {
1201 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_frag);
1202 		return;
1203 	}
1204 
1205 	if (ipf_pr_pullup(fin, ICMPERR_ICMPHLEN) == -1) {
1206 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_pullup);
1207 		return;
1208 	}
1209 
1210 	icmp = fin->fin_dp;
1211 
1212 	fin->fin_data[0] = *(u_short *)icmp;
1213 	fin->fin_data[1] = icmp->icmp_id;
1214 
1215 	switch (icmp->icmp_type)
1216 	{
1217 	case ICMP_ECHOREPLY :
1218 	case ICMP_ECHO :
1219 	/* Router discovery messaes - RFC 1256 */
1220 	case ICMP_ROUTERADVERT :
1221 	case ICMP_ROUTERSOLICIT :
1222 		fin->fin_flx |= FI_ICMPQUERY;
1223 		minicmpsz = ICMP_MINLEN;
1224 		break;
1225 	/*
1226 	 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1227 	 * 3 * timestamp(3 * 4)
1228 	 */
1229 	case ICMP_TSTAMP :
1230 	case ICMP_TSTAMPREPLY :
1231 		fin->fin_flx |= FI_ICMPQUERY;
1232 		minicmpsz = 20;
1233 		break;
1234 	/*
1235 	 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1236 	 * mask(4)
1237 	 */
1238 	case ICMP_IREQ :
1239 	case ICMP_IREQREPLY :
1240 	case ICMP_MASKREQ :
1241 	case ICMP_MASKREPLY :
1242 		fin->fin_flx |= FI_ICMPQUERY;
1243 		minicmpsz = 12;
1244 		break;
1245 	/*
1246 	 * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
1247 	 */
1248 	case ICMP_UNREACH :
1249 #ifdef icmp_nextmtu
1250 		if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
1251 			if (icmp->icmp_nextmtu < softc->ipf_icmpminfragmtu)
1252 				fin->fin_flx |= FI_BAD;
1253 		}
1254 #endif
1255 	case ICMP_SOURCEQUENCH :
1256 	case ICMP_REDIRECT :
1257 	case ICMP_TIMXCEED :
1258 	case ICMP_PARAMPROB :
1259 		fin->fin_flx |= FI_ICMPERR;
1260 		if (ipf_coalesce(fin) != 1) {
1261 			LBUMPD(ipf_stats[fin->fin_out], fr_icmp_coalesce);
1262 			return;
1263 		}
1264 
1265 		/*
1266 		 * ICMP error packets should not be generated for IP
1267 		 * packets that are a fragment that isn't the first
1268 		 * fragment.
1269 		 */
1270 		oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
1271 		if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0)
1272 			fin->fin_flx |= FI_BAD;
1273 
1274 		/*
1275 		 * If the destination of this packet doesn't match the
1276 		 * source of the original packet then this packet is
1277 		 * not correct.
1278 		 */
1279 		if (oip->ip_src.s_addr != fin->fin_daddr)
1280 			fin->fin_flx |= FI_BAD;
1281 		break;
1282 	default :
1283 		break;
1284 	}
1285 
1286 	ipf_pr_short(fin, minicmpsz);
1287 
1288 	ipf_checkv4sum(fin);
1289 }
1290 
1291 
1292 /* ------------------------------------------------------------------------ */
1293 /* Function:    ipf_pr_tcpcommon                                            */
1294 /* Returns:     int    - 0 = header ok, 1 = bad packet, -1 = buffer error   */
1295 /* Parameters:  fin(I) - pointer to packet information                      */
1296 /*                                                                          */
1297 /* TCP header sanity checking.  Look for bad combinations of TCP flags,     */
1298 /* and make some checks with how they interact with other fields.           */
1299 /* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is     */
1300 /* valid and mark the packet as bad if not.                                 */
1301 /* ------------------------------------------------------------------------ */
1302 static INLINE int
1303 ipf_pr_tcpcommon(fr_info_t *fin)
1304 {
1305 	ipf_main_softc_t *softc = fin->fin_main_soft;
1306 	int flags, tlen;
1307 	tcphdr_t *tcp;
1308 
1309 	fin->fin_flx |= FI_TCPUDP;
1310 	if (fin->fin_off != 0) {
1311 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_frag);
1312 		return 0;
1313 	}
1314 
1315 	if (ipf_pr_pullup(fin, sizeof(*tcp)) == -1) {
1316 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1317 		return -1;
1318 	}
1319 
1320 	tcp = fin->fin_dp;
1321 	if (fin->fin_dlen > 3) {
1322 		fin->fin_sport = ntohs(tcp->th_sport);
1323 		fin->fin_dport = ntohs(tcp->th_dport);
1324 	}
1325 
1326 	if ((fin->fin_flx & FI_SHORT) != 0) {
1327 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_short);
1328 		return 1;
1329 	}
1330 
1331 	/*
1332 	 * Use of the TCP data offset *must* result in a value that is at
1333 	 * least the same size as the TCP header.
1334 	 */
1335 	tlen = TCP_OFF(tcp) << 2;
1336 	if (tlen < sizeof(tcphdr_t)) {
1337 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_small);
1338 		fin->fin_flx |= FI_BAD;
1339 		return 1;
1340 	}
1341 
1342 	flags = tcp->th_flags;
1343 	fin->fin_tcpf = tcp->th_flags;
1344 
1345 	/*
1346 	 * If the urgent flag is set, then the urgent pointer must
1347 	 * also be set and vice versa.  Good TCP packets do not have
1348 	 * just one of these set.
1349 	 */
1350 	if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
1351 		fin->fin_flx |= FI_BAD;
1352 #if 0
1353 	} else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
1354 		/*
1355 		 * Ignore this case (#if 0) as it shows up in "real"
1356 		 * traffic with bogus values in the urgent pointer field.
1357 		 */
1358 		fin->fin_flx |= FI_BAD;
1359 #endif
1360 	} else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
1361 		   ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
1362 		/* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
1363 		fin->fin_flx |= FI_BAD;
1364 #if 1
1365 	} else if (((flags & TH_SYN) != 0) &&
1366 		   ((flags & (TH_URG|TH_PUSH)) != 0)) {
1367 		/*
1368 		 * SYN with URG and PUSH set is not for normal TCP but it is
1369 		 * possible(?) with T/TCP...but who uses T/TCP?
1370 		 */
1371 		fin->fin_flx |= FI_BAD;
1372 #endif
1373 	} else if (!(flags & TH_ACK)) {
1374 		/*
1375 		 * If the ack bit isn't set, then either the SYN or
1376 		 * RST bit must be set.  If the SYN bit is set, then
1377 		 * we expect the ACK field to be 0.  If the ACK is
1378 		 * not set and if URG, PSH or FIN are set, consdier
1379 		 * that to indicate a bad TCP packet.
1380 		 */
1381 		if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
1382 			/*
1383 			 * Cisco PIX sets the ACK field to a random value.
1384 			 * In light of this, do not set FI_BAD until a patch
1385 			 * is available from Cisco to ensure that
1386 			 * interoperability between existing systems is
1387 			 * achieved.
1388 			 */
1389 			/*fin->fin_flx |= FI_BAD*/;
1390 		} else if (!(flags & (TH_RST|TH_SYN))) {
1391 			fin->fin_flx |= FI_BAD;
1392 		} else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
1393 			fin->fin_flx |= FI_BAD;
1394 		}
1395 	}
1396 	if (fin->fin_flx & FI_BAD) {
1397 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_bad_flags);
1398 		return 1;
1399 	}
1400 
1401 	/*
1402 	 * At this point, it's not exactly clear what is to be gained by
1403 	 * marking up which TCP options are and are not present.  The one we
1404 	 * are most interested in is the TCP window scale.  This is only in
1405 	 * a SYN packet [RFC1323] so we don't need this here...?
1406 	 * Now if we were to analyse the header for passive fingerprinting,
1407 	 * then that might add some weight to adding this...
1408 	 */
1409 	if (tlen == sizeof(tcphdr_t)) {
1410 		return 0;
1411 	}
1412 
1413 	if (ipf_pr_pullup(fin, tlen) == -1) {
1414 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1415 		return -1;
1416 	}
1417 
1418 #if 0
1419 	tcp = fin->fin_dp;
1420 	ip = fin->fin_ip;
1421 	s = (u_char *)(tcp + 1);
1422 	off = IP_HL(ip) << 2;
1423 # ifdef _KERNEL
1424 	if (fin->fin_mp != NULL) {
1425 		mb_t *m = *fin->fin_mp;
1426 
1427 		if (off + tlen > M_LEN(m))
1428 			return;
1429 	}
1430 # endif
1431 	for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
1432 		opt = *s;
1433 		if (opt == '\0')
1434 			break;
1435 		else if (opt == TCPOPT_NOP)
1436 			ol = 1;
1437 		else {
1438 			if (tlen < 2)
1439 				break;
1440 			ol = (int)*(s + 1);
1441 			if (ol < 2 || ol > tlen)
1442 				break;
1443 		}
1444 
1445 		for (i = 9, mv = 4; mv >= 0; ) {
1446 			op = ipopts + i;
1447 			if (opt == (u_char)op->ol_val) {
1448 				optmsk |= op->ol_bit;
1449 				break;
1450 			}
1451 		}
1452 		tlen -= ol;
1453 		s += ol;
1454 	}
1455 #endif /* 0 */
1456 
1457 	return 0;
1458 }
1459 
1460 
1461 
1462 /* ------------------------------------------------------------------------ */
1463 /* Function:    ipf_pr_udpcommon                                            */
1464 /* Returns:     int    - 0 = header ok, 1 = bad packet                      */
1465 /* Parameters:  fin(I) - pointer to packet information                      */
1466 /*                                                                          */
1467 /* Extract the UDP source and destination ports, if present.  If compiled   */
1468 /* with IPFILTER_CKSUM, check to see if the UDP checksum is valid.          */
1469 /* ------------------------------------------------------------------------ */
1470 static INLINE int
1471 ipf_pr_udpcommon(fr_info_t *fin)
1472 {
1473 	udphdr_t *udp;
1474 
1475 	fin->fin_flx |= FI_TCPUDP;
1476 
1477 	if (!fin->fin_off && (fin->fin_dlen > 3)) {
1478 		if (ipf_pr_pullup(fin, sizeof(*udp)) == -1) {
1479 			ipf_main_softc_t *softc = fin->fin_main_soft;
1480 
1481 			fin->fin_flx |= FI_SHORT;
1482 			LBUMPD(ipf_stats[fin->fin_out], fr_udp_pullup);
1483 			return 1;
1484 		}
1485 
1486 		udp = fin->fin_dp;
1487 
1488 		fin->fin_sport = ntohs(udp->uh_sport);
1489 		fin->fin_dport = ntohs(udp->uh_dport);
1490 	}
1491 
1492 	return 0;
1493 }
1494 
1495 
1496 /* ------------------------------------------------------------------------ */
1497 /* Function:    ipf_pr_tcp                                                  */
1498 /* Returns:     void                                                        */
1499 /* Parameters:  fin(I) - pointer to packet information                      */
1500 /*                                                                          */
1501 /* IPv4 Only                                                                */
1502 /* Analyse the packet for IPv4/TCP properties.                              */
1503 /* ------------------------------------------------------------------------ */
1504 static INLINE void
1505 ipf_pr_tcp(fr_info_t *fin)
1506 {
1507 
1508 	ipf_pr_short(fin, sizeof(tcphdr_t));
1509 
1510 	if (ipf_pr_tcpcommon(fin) == 0)
1511 		ipf_checkv4sum(fin);
1512 }
1513 
1514 
1515 /* ------------------------------------------------------------------------ */
1516 /* Function:    ipf_pr_udp                                                  */
1517 /* Returns:     void                                                        */
1518 /* Parameters:  fin(I) - pointer to packet information                      */
1519 /*                                                                          */
1520 /* IPv4 Only                                                                */
1521 /* Analyse the packet for IPv4/UDP properties.                              */
1522 /* ------------------------------------------------------------------------ */
1523 static INLINE void
1524 ipf_pr_udp(fr_info_t *fin)
1525 {
1526 
1527 	ipf_pr_short(fin, sizeof(udphdr_t));
1528 
1529 	if (ipf_pr_udpcommon(fin) == 0)
1530 		ipf_checkv4sum(fin);
1531 }
1532 
1533 
1534 /* ------------------------------------------------------------------------ */
1535 /* Function:    ipf_pr_esp                                                  */
1536 /* Returns:     void                                                        */
1537 /* Parameters:  fin(I) - pointer to packet information                      */
1538 /*                                                                          */
1539 /* Analyse the packet for ESP properties.                                   */
1540 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
1541 /* even though the newer ESP packets must also have a sequence number that  */
1542 /* is 32bits as well, it is not possible(?) to determine the version from a */
1543 /* simple packet header.                                                    */
1544 /* ------------------------------------------------------------------------ */
1545 static INLINE void
1546 ipf_pr_esp(fr_info_t *fin)
1547 {
1548 
1549 	if (fin->fin_off == 0) {
1550 		ipf_pr_short(fin, 8);
1551 		if (ipf_pr_pullup(fin, 8) == -1) {
1552 			ipf_main_softc_t *softc = fin->fin_main_soft;
1553 
1554 			LBUMPD(ipf_stats[fin->fin_out], fr_v4_esp_pullup);
1555 		}
1556 	}
1557 }
1558 
1559 
1560 /* ------------------------------------------------------------------------ */
1561 /* Function:    ipf_pr_ah                                                   */
1562 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
1563 /* Parameters:  fin(I) - pointer to packet information                      */
1564 /*                                                                          */
1565 /* Analyse the packet for AH properties.                                    */
1566 /* The minimum length is taken to be the combination of all fields in the   */
1567 /* header being present and no authentication data (null algorithm used.)   */
1568 /* ------------------------------------------------------------------------ */
1569 static INLINE int
1570 ipf_pr_ah(fr_info_t *fin)
1571 {
1572 	ipf_main_softc_t *softc = fin->fin_main_soft;
1573 	authhdr_t *ah;
1574 	int len;
1575 
1576 	fin->fin_flx |= FI_AH;
1577 	ipf_pr_short(fin, sizeof(*ah));
1578 
1579 	if (((fin->fin_flx & FI_SHORT) != 0) || (fin->fin_off != 0)) {
1580 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_ah_bad);
1581 		return IPPROTO_NONE;
1582 	}
1583 
1584 	if (ipf_pr_pullup(fin, sizeof(*ah)) == -1) {
1585 		DT(fr_v4_ah_pullup_1);
1586 		LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1587 		return IPPROTO_NONE;
1588 	}
1589 
1590 	ah = (authhdr_t *)fin->fin_dp;
1591 
1592 	len = (ah->ah_plen + 2) << 2;
1593 	ipf_pr_short(fin, len);
1594 	if (ipf_pr_pullup(fin, len) == -1) {
1595 		DT(fr_v4_ah_pullup_2);
1596 		LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1597 		return IPPROTO_NONE;
1598 	}
1599 
1600 	/*
1601 	 * Adjust fin_dp and fin_dlen for skipping over the authentication
1602 	 * header.
1603 	 */
1604 	fin->fin_dp = (char *)fin->fin_dp + len;
1605 	fin->fin_dlen -= len;
1606 	return ah->ah_next;
1607 }
1608 
1609 
1610 /* ------------------------------------------------------------------------ */
1611 /* Function:    ipf_pr_gre                                                  */
1612 /* Returns:     void                                                        */
1613 /* Parameters:  fin(I) - pointer to packet information                      */
1614 /*                                                                          */
1615 /* Analyse the packet for GRE properties.                                   */
1616 /* ------------------------------------------------------------------------ */
1617 static INLINE void
1618 ipf_pr_gre(fr_info_t *fin)
1619 {
1620 	ipf_main_softc_t *softc = fin->fin_main_soft;
1621 	grehdr_t *gre;
1622 
1623 	ipf_pr_short(fin, sizeof(grehdr_t));
1624 
1625 	if (fin->fin_off != 0) {
1626 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_frag);
1627 		return;
1628 	}
1629 
1630 	if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1631 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_pullup);
1632 		return;
1633 	}
1634 
1635 	gre = fin->fin_dp;
1636 	if (GRE_REV(gre->gr_flags) == 1)
1637 		fin->fin_data[0] = gre->gr_call;
1638 }
1639 
1640 
1641 /* ------------------------------------------------------------------------ */
1642 /* Function:    ipf_pr_ipv4hdr                                              */
1643 /* Returns:     void                                                        */
1644 /* Parameters:  fin(I) - pointer to packet information                      */
1645 /*                                                                          */
1646 /* IPv4 Only                                                                */
1647 /* Analyze the IPv4 header and set fields in the fr_info_t structure.       */
1648 /* Check all options present and flag their presence if any exist.          */
1649 /* ------------------------------------------------------------------------ */
1650 static INLINE void
1651 ipf_pr_ipv4hdr(fr_info_t *fin)
1652 {
1653 	u_short optmsk = 0, secmsk = 0, auth = 0;
1654 	int hlen, ol, mv, p, i;
1655 	const struct optlist *op;
1656 	u_char *s, opt;
1657 	u_short off;
1658 	fr_ip_t *fi;
1659 	ip_t *ip;
1660 
1661 	fi = &fin->fin_fi;
1662 	hlen = fin->fin_hlen;
1663 
1664 	ip = fin->fin_ip;
1665 	p = ip->ip_p;
1666 	fi->fi_p = p;
1667 	fin->fin_crc = p;
1668 	fi->fi_tos = ip->ip_tos;
1669 	fin->fin_id = ip->ip_id;
1670 	off = ntohs(ip->ip_off);
1671 
1672 	/* Get both TTL and protocol */
1673 	fi->fi_p = ip->ip_p;
1674 	fi->fi_ttl = ip->ip_ttl;
1675 
1676 	/* Zero out bits not used in IPv6 address */
1677 	fi->fi_src.i6[1] = 0;
1678 	fi->fi_src.i6[2] = 0;
1679 	fi->fi_src.i6[3] = 0;
1680 	fi->fi_dst.i6[1] = 0;
1681 	fi->fi_dst.i6[2] = 0;
1682 	fi->fi_dst.i6[3] = 0;
1683 
1684 	fi->fi_saddr = ip->ip_src.s_addr;
1685 	fin->fin_crc += fi->fi_saddr;
1686 	fi->fi_daddr = ip->ip_dst.s_addr;
1687 	fin->fin_crc += fi->fi_daddr;
1688 	if (IN_CLASSD(fi->fi_daddr))
1689 		fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
1690 
1691 	/*
1692 	 * set packet attribute flags based on the offset and
1693 	 * calculate the byte offset that it represents.
1694 	 */
1695 	off &= IP_MF|IP_OFFMASK;
1696 	if (off != 0) {
1697 		int morefrag = off & IP_MF;
1698 
1699 		fi->fi_flx |= FI_FRAG;
1700 		off &= IP_OFFMASK;
1701 		if (off != 0) {
1702 			fin->fin_flx |= FI_FRAGBODY;
1703 			off <<= 3;
1704 			if ((off + fin->fin_dlen > 65535) ||
1705 			    (fin->fin_dlen == 0) ||
1706 			    ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
1707 				/*
1708 				 * The length of the packet, starting at its
1709 				 * offset cannot exceed 65535 (0xffff) as the
1710 				 * length of an IP packet is only 16 bits.
1711 				 *
1712 				 * Any fragment that isn't the last fragment
1713 				 * must have a length greater than 0 and it
1714 				 * must be an even multiple of 8.
1715 				 */
1716 				fi->fi_flx |= FI_BAD;
1717 			}
1718 		}
1719 	}
1720 	fin->fin_off = off;
1721 
1722 	/*
1723 	 * Call per-protocol setup and checking
1724 	 */
1725 	if (p == IPPROTO_AH) {
1726 		/*
1727 		 * Treat AH differently because we expect there to be another
1728 		 * layer 4 header after it.
1729 		 */
1730 		p = ipf_pr_ah(fin);
1731 	}
1732 
1733 	switch (p)
1734 	{
1735 	case IPPROTO_UDP :
1736 		ipf_pr_udp(fin);
1737 		break;
1738 	case IPPROTO_TCP :
1739 		ipf_pr_tcp(fin);
1740 		break;
1741 	case IPPROTO_ICMP :
1742 		ipf_pr_icmp(fin);
1743 		break;
1744 	case IPPROTO_ESP :
1745 		ipf_pr_esp(fin);
1746 		break;
1747 	case IPPROTO_GRE :
1748 		ipf_pr_gre(fin);
1749 		break;
1750 	}
1751 
1752 	ip = fin->fin_ip;
1753 	if (ip == NULL)
1754 		return;
1755 
1756 	/*
1757 	 * If it is a standard IP header (no options), set the flag fields
1758 	 * which relate to options to 0.
1759 	 */
1760 	if (hlen == sizeof(*ip)) {
1761 		fi->fi_optmsk = 0;
1762 		fi->fi_secmsk = 0;
1763 		fi->fi_auth = 0;
1764 		return;
1765 	}
1766 
1767 	/*
1768 	 * So the IP header has some IP options attached.  Walk the entire
1769 	 * list of options present with this packet and set flags to indicate
1770 	 * which ones are here and which ones are not.  For the somewhat out
1771 	 * of date and obscure security classification options, set a flag to
1772 	 * represent which classification is present.
1773 	 */
1774 	fi->fi_flx |= FI_OPTIONS;
1775 
1776 	for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1777 		opt = *s;
1778 		if (opt == '\0')
1779 			break;
1780 		else if (opt == IPOPT_NOP)
1781 			ol = 1;
1782 		else {
1783 			if (hlen < 2)
1784 				break;
1785 			ol = (int)*(s + 1);
1786 			if (ol < 2 || ol > hlen)
1787 				break;
1788 		}
1789 		for (i = 9, mv = 4; mv >= 0; ) {
1790 			op = ipopts + i;
1791 
1792 			if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1793 				u_32_t doi;
1794 
1795 				switch (opt)
1796 				{
1797 				case IPOPT_SECURITY :
1798 					if (optmsk & op->ol_bit) {
1799 						fin->fin_flx |= FI_BAD;
1800 					} else {
1801 						doi = ipf_checkripso(s);
1802 						secmsk = doi >> 16;
1803 						auth = doi & 0xffff;
1804 					}
1805 					break;
1806 
1807 				case IPOPT_CIPSO :
1808 
1809 					if (optmsk & op->ol_bit) {
1810 						fin->fin_flx |= FI_BAD;
1811 					} else {
1812 						doi = ipf_checkcipso(fin,
1813 								     s, ol);
1814 						secmsk = doi >> 16;
1815 						auth = doi & 0xffff;
1816 					}
1817 					break;
1818 				}
1819 				optmsk |= op->ol_bit;
1820 			}
1821 
1822 			if (opt < op->ol_val)
1823 				i -= mv;
1824 			else
1825 				i += mv;
1826 			mv--;
1827 		}
1828 		hlen -= ol;
1829 		s += ol;
1830 	}
1831 
1832 	/*
1833 	 *
1834 	 */
1835 	if (auth && !(auth & 0x0100))
1836 		auth &= 0xff00;
1837 	fi->fi_optmsk = optmsk;
1838 	fi->fi_secmsk = secmsk;
1839 	fi->fi_auth = auth;
1840 }
1841 
1842 
1843 /* ------------------------------------------------------------------------ */
1844 /* Function:    ipf_checkripso                                              */
1845 /* Returns:     void                                                        */
1846 /* Parameters:  s(I)   - pointer to start of RIPSO option                   */
1847 /*                                                                          */
1848 /* ------------------------------------------------------------------------ */
1849 static u_32_t
1850 ipf_checkripso(u_char *s)
1851 {
1852 	const struct optlist *sp;
1853 	u_short secmsk = 0, auth = 0;
1854 	u_char sec;
1855 	int j, m;
1856 
1857 	sec = *(s + 2);	/* classification */
1858 	for (j = 3, m = 2; m >= 0; ) {
1859 		sp = secopt + j;
1860 		if (sec == sp->ol_val) {
1861 			secmsk |= sp->ol_bit;
1862 			auth = *(s + 3);
1863 			auth *= 256;
1864 			auth += *(s + 4);
1865 			break;
1866 		}
1867 		if (sec < sp->ol_val)
1868 			j -= m;
1869 		else
1870 			j += m;
1871 		m--;
1872 	}
1873 
1874 	return (secmsk << 16) | auth;
1875 }
1876 
1877 
1878 /* ------------------------------------------------------------------------ */
1879 /* Function:    ipf_checkcipso                                              */
1880 /* Returns:     u_32_t  - 0 = failure, else the doi from the header         */
1881 /* Parameters:  fin(IO) - pointer to packet information                     */
1882 /*              s(I)    - pointer to start of CIPSO option                  */
1883 /*              ol(I)   - length of CIPSO option field                      */
1884 /*                                                                          */
1885 /* This function returns the domain of integrity (DOI) field from the CIPSO */
1886 /* header and returns that whilst also storing the highest sensitivity      */
1887 /* value found in the fr_info_t structure.                                  */
1888 /*                                                                          */
1889 /* No attempt is made to extract the category bitmaps as these are defined  */
1890 /* by the user (rather than the protocol) and can be rather numerous on the */
1891 /* end nodes.                                                               */
1892 /* ------------------------------------------------------------------------ */
1893 static u_32_t
1894 ipf_checkcipso(fr_info_t *fin, u_char *s, int ol)
1895 {
1896 	ipf_main_softc_t *softc = fin->fin_main_soft;
1897 	fr_ip_t *fi;
1898 	u_32_t doi;
1899 	u_char *t, tag, tlen, sensitivity;
1900 	int len;
1901 
1902 	if (ol < 6 || ol > 40) {
1903 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
1904 		fin->fin_flx |= FI_BAD;
1905 		return 0;
1906 	}
1907 
1908 	fi = &fin->fin_fi;
1909 	fi->fi_sensitivity = 0;
1910 	/*
1911 	 * The DOI field MUST be there.
1912 	 */
1913 	bcopy(s + 2, &doi, sizeof(doi));
1914 
1915 	t = (u_char *)s + 6;
1916 	for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
1917 		tag = *t;
1918 		tlen = *(t + 1);
1919 		if (tlen > len || tlen < 4 || tlen > 34) {
1920 			LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
1921 			fin->fin_flx |= FI_BAD;
1922 			return 0;
1923 		}
1924 
1925 		sensitivity = 0;
1926 		/*
1927 		 * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
1928 		 * draft (16 July 1992) that has expired.
1929 		 */
1930 		if (tag == 0) {
1931 			fin->fin_flx |= FI_BAD;
1932 			continue;
1933 		} else if (tag == 1) {
1934 			if (*(t + 2) != 0) {
1935 				fin->fin_flx |= FI_BAD;
1936 				continue;
1937 			}
1938 			sensitivity = *(t + 3);
1939 			/* Category bitmap for categories 0-239 */
1940 
1941 		} else if (tag == 4) {
1942 			if (*(t + 2) != 0) {
1943 				fin->fin_flx |= FI_BAD;
1944 				continue;
1945 			}
1946 			sensitivity = *(t + 3);
1947 			/* Enumerated categories, 16bits each, upto 15 */
1948 
1949 		} else if (tag == 5) {
1950 			if (*(t + 2) != 0) {
1951 				fin->fin_flx |= FI_BAD;
1952 				continue;
1953 			}
1954 			sensitivity = *(t + 3);
1955 			/* Range of categories (2*16bits), up to 7 pairs */
1956 
1957 		} else if (tag > 127) {
1958 			/* Custom defined DOI */
1959 			;
1960 		} else {
1961 			fin->fin_flx |= FI_BAD;
1962 			continue;
1963 		}
1964 
1965 		if (sensitivity > fi->fi_sensitivity)
1966 			fi->fi_sensitivity = sensitivity;
1967 	}
1968 
1969 	return doi;
1970 }
1971 
1972 
1973 /* ------------------------------------------------------------------------ */
1974 /* Function:    ipf_makefrip                                                */
1975 /* Returns:     int     - 0 == packet ok, -1 == packet freed                */
1976 /* Parameters:  hlen(I) - length of IP packet header                        */
1977 /*              ip(I)   - pointer to the IP header                          */
1978 /*              fin(IO) - pointer to packet information                     */
1979 /*                                                                          */
1980 /* Compact the IP header into a structure which contains just the info.     */
1981 /* which is useful for comparing IP headers with and store this information */
1982 /* in the fr_info_t structure pointer to by fin.  At present, it is assumed */
1983 /* this function will be called with either an IPv4 or IPv6 packet.         */
1984 /* ------------------------------------------------------------------------ */
1985 int
1986 ipf_makefrip(int hlen, ip_t *ip, fr_info_t *fin)
1987 {
1988 	ipf_main_softc_t *softc = fin->fin_main_soft;
1989 	int v;
1990 
1991 	fin->fin_depth = 0;
1992 	fin->fin_hlen = (u_short)hlen;
1993 	fin->fin_ip = ip;
1994 	fin->fin_rule = 0xffffffff;
1995 	fin->fin_group[0] = -1;
1996 	fin->fin_group[1] = '\0';
1997 	fin->fin_dp = (char *)ip + hlen;
1998 
1999 	v = fin->fin_v;
2000 	if (v == 4) {
2001 		fin->fin_plen = ntohs(ip->ip_len);
2002 		fin->fin_dlen = fin->fin_plen - hlen;
2003 		ipf_pr_ipv4hdr(fin);
2004 #ifdef	USE_INET6
2005 	} else if (v == 6) {
2006 		fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
2007 		fin->fin_dlen = fin->fin_plen;
2008 		fin->fin_plen += hlen;
2009 
2010 		ipf_pr_ipv6hdr(fin);
2011 #endif
2012 	}
2013 	if (fin->fin_ip == NULL) {
2014 		LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
2015 		return -1;
2016 	}
2017 	return 0;
2018 }
2019 
2020 
2021 /* ------------------------------------------------------------------------ */
2022 /* Function:    ipf_portcheck                                               */
2023 /* Returns:     int - 1 == port matched, 0 == port match failed             */
2024 /* Parameters:  frp(I) - pointer to port check `expression'                 */
2025 /*              pop(I) - port number to evaluate                            */
2026 /*                                                                          */
2027 /* Perform a comparison of a port number against some other(s), using a     */
2028 /* structure with compare information stored in it.                         */
2029 /* ------------------------------------------------------------------------ */
2030 static INLINE int
2031 ipf_portcheck(frpcmp_t *frp, u_32_t pop)
2032 {
2033 	int err = 1;
2034 	u_32_t po;
2035 
2036 	po = frp->frp_port;
2037 
2038 	/*
2039 	 * Do opposite test to that required and continue if that succeeds.
2040 	 */
2041 	switch (frp->frp_cmp)
2042 	{
2043 	case FR_EQUAL :
2044 		if (pop != po) /* EQUAL */
2045 			err = 0;
2046 		break;
2047 	case FR_NEQUAL :
2048 		if (pop == po) /* NOTEQUAL */
2049 			err = 0;
2050 		break;
2051 	case FR_LESST :
2052 		if (pop >= po) /* LESSTHAN */
2053 			err = 0;
2054 		break;
2055 	case FR_GREATERT :
2056 		if (pop <= po) /* GREATERTHAN */
2057 			err = 0;
2058 		break;
2059 	case FR_LESSTE :
2060 		if (pop > po) /* LT or EQ */
2061 			err = 0;
2062 		break;
2063 	case FR_GREATERTE :
2064 		if (pop < po) /* GT or EQ */
2065 			err = 0;
2066 		break;
2067 	case FR_OUTRANGE :
2068 		if (pop >= po && pop <= frp->frp_top) /* Out of range */
2069 			err = 0;
2070 		break;
2071 	case FR_INRANGE :
2072 		if (pop <= po || pop >= frp->frp_top) /* In range */
2073 			err = 0;
2074 		break;
2075 	case FR_INCRANGE :
2076 		if (pop < po || pop > frp->frp_top) /* Inclusive range */
2077 			err = 0;
2078 		break;
2079 	default :
2080 		break;
2081 	}
2082 	return err;
2083 }
2084 
2085 
2086 /* ------------------------------------------------------------------------ */
2087 /* Function:    ipf_tcpudpchk                                               */
2088 /* Returns:     int - 1 == protocol matched, 0 == check failed              */
2089 /* Parameters:  fda(I) - pointer to packet information                      */
2090 /*              ft(I)  - pointer to structure with comparison data          */
2091 /*                                                                          */
2092 /* Compares the current pcket (assuming it is TCP/UDP) information with a   */
2093 /* structure containing information that we want to match against.          */
2094 /* ------------------------------------------------------------------------ */
2095 int
2096 ipf_tcpudpchk(fr_ip_t *fi, frtuc_t *ft)
2097 {
2098 	int err = 1;
2099 
2100 	/*
2101 	 * Both ports should *always* be in the first fragment.
2102 	 * So far, I cannot find any cases where they can not be.
2103 	 *
2104 	 * compare destination ports
2105 	 */
2106 	if (ft->ftu_dcmp)
2107 		err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
2108 
2109 	/*
2110 	 * compare source ports
2111 	 */
2112 	if (err && ft->ftu_scmp)
2113 		err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
2114 
2115 	/*
2116 	 * If we don't have all the TCP/UDP header, then how can we
2117 	 * expect to do any sort of match on it ?  If we were looking for
2118 	 * TCP flags, then NO match.  If not, then match (which should
2119 	 * satisfy the "short" class too).
2120 	 */
2121 	if (err && (fi->fi_p == IPPROTO_TCP)) {
2122 		if (fi->fi_flx & FI_SHORT)
2123 			return !(ft->ftu_tcpf | ft->ftu_tcpfm);
2124 		/*
2125 		 * Match the flags ?  If not, abort this match.
2126 		 */
2127 		if (ft->ftu_tcpfm &&
2128 		    ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
2129 			FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
2130 				 ft->ftu_tcpfm, ft->ftu_tcpf));
2131 			err = 0;
2132 		}
2133 	}
2134 	return err;
2135 }
2136 
2137 
2138 /* ------------------------------------------------------------------------ */
2139 /* Function:    ipf_check_ipf                                               */
2140 /* Returns:     int - 0 == match, else no match                             */
2141 /* Parameters:  fin(I)     - pointer to packet information                  */
2142 /*              fr(I)      - pointer to filter rule                         */
2143 /*              portcmp(I) - flag indicating whether to attempt matching on */
2144 /*                           TCP/UDP port data.                             */
2145 /*                                                                          */
2146 /* Check to see if a packet matches an IPFilter rule.  Checks of addresses, */
2147 /* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
2148 /* this function.                                                           */
2149 /* ------------------------------------------------------------------------ */
2150 static INLINE int
2151 ipf_check_ipf(fr_info_t *fin, frentry_t *fr, int portcmp)
2152 {
2153 	u_32_t	*ld, *lm, *lip;
2154 	fripf_t *fri;
2155 	fr_ip_t *fi;
2156 	int i;
2157 
2158 	fi = &fin->fin_fi;
2159 	fri = fr->fr_ipf;
2160 	lip = (u_32_t *)fi;
2161 	lm = (u_32_t *)&fri->fri_mip;
2162 	ld = (u_32_t *)&fri->fri_ip;
2163 
2164 	/*
2165 	 * first 32 bits to check coversion:
2166 	 * IP version, TOS, TTL, protocol
2167 	 */
2168 	i = ((*lip & *lm) != *ld);
2169 	FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
2170 		   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2171 	if (i)
2172 		return 1;
2173 
2174 	/*
2175 	 * Next 32 bits is a constructed bitmask indicating which IP options
2176 	 * are present (if any) in this packet.
2177 	 */
2178 	lip++, lm++, ld++;
2179 	i = ((*lip & *lm) != *ld);
2180 	FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
2181 		   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2182 	if (i != 0)
2183 		return 1;
2184 
2185 	lip++, lm++, ld++;
2186 	/*
2187 	 * Unrolled loops (4 each, for 32 bits) for address checks.
2188 	 */
2189 	/*
2190 	 * Check the source address.
2191 	 */
2192 	if (fr->fr_satype == FRI_LOOKUP) {
2193 		i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
2194 				      fi->fi_v, lip, fin->fin_plen);
2195 		if (i == -1)
2196 			return 1;
2197 		lip += 3;
2198 		lm += 3;
2199 		ld += 3;
2200 	} else {
2201 		i = ((*lip & *lm) != *ld);
2202 		FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
2203 			   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2204 		if (fi->fi_v == 6) {
2205 			lip++, lm++, ld++;
2206 			i |= ((*lip & *lm) != *ld);
2207 			FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
2208 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2209 			lip++, lm++, ld++;
2210 			i |= ((*lip & *lm) != *ld);
2211 			FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
2212 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2213 			lip++, lm++, ld++;
2214 			i |= ((*lip & *lm) != *ld);
2215 			FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
2216 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2217 		} else {
2218 			lip += 3;
2219 			lm += 3;
2220 			ld += 3;
2221 		}
2222 	}
2223 	i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
2224 	if (i != 0)
2225 		return 1;
2226 
2227 	/*
2228 	 * Check the destination address.
2229 	 */
2230 	lip++, lm++, ld++;
2231 	if (fr->fr_datype == FRI_LOOKUP) {
2232 		i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
2233 				      fi->fi_v, lip, fin->fin_plen);
2234 		if (i == -1)
2235 			return 1;
2236 		lip += 3;
2237 		lm += 3;
2238 		ld += 3;
2239 	} else {
2240 		i = ((*lip & *lm) != *ld);
2241 		FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
2242 			   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2243 		if (fi->fi_v == 6) {
2244 			lip++, lm++, ld++;
2245 			i |= ((*lip & *lm) != *ld);
2246 			FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
2247 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2248 			lip++, lm++, ld++;
2249 			i |= ((*lip & *lm) != *ld);
2250 			FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
2251 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2252 			lip++, lm++, ld++;
2253 			i |= ((*lip & *lm) != *ld);
2254 			FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
2255 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2256 		} else {
2257 			lip += 3;
2258 			lm += 3;
2259 			ld += 3;
2260 		}
2261 	}
2262 	i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
2263 	if (i != 0)
2264 		return 1;
2265 	/*
2266 	 * IP addresses matched.  The next 32bits contains:
2267 	 * mast of old IP header security & authentication bits.
2268 	 */
2269 	lip++, lm++, ld++;
2270 	i = (*ld - (*lip & *lm));
2271 	FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2272 
2273 	/*
2274 	 * Next we have 32 bits of packet flags.
2275 	 */
2276 	lip++, lm++, ld++;
2277 	i |= (*ld - (*lip & *lm));
2278 	FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2279 
2280 	if (i == 0) {
2281 		/*
2282 		 * If a fragment, then only the first has what we're
2283 		 * looking for here...
2284 		 */
2285 		if (portcmp) {
2286 			if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
2287 				i = 1;
2288 		} else {
2289 			if (fr->fr_dcmp || fr->fr_scmp ||
2290 			    fr->fr_tcpf || fr->fr_tcpfm)
2291 				i = 1;
2292 			if (fr->fr_icmpm || fr->fr_icmp) {
2293 				if (((fi->fi_p != IPPROTO_ICMP) &&
2294 				     (fi->fi_p != IPPROTO_ICMPV6)) ||
2295 				    fin->fin_off || (fin->fin_dlen < 2))
2296 					i = 1;
2297 				else if ((fin->fin_data[0] & fr->fr_icmpm) !=
2298 					 fr->fr_icmp) {
2299 					FR_DEBUG(("i. %#x & %#x != %#x\n",
2300 						 fin->fin_data[0],
2301 						 fr->fr_icmpm, fr->fr_icmp));
2302 					i = 1;
2303 				}
2304 			}
2305 		}
2306 	}
2307 	return i;
2308 }
2309 
2310 
2311 /* ------------------------------------------------------------------------ */
2312 /* Function:    ipf_scanlist                                                */
2313 /* Returns:     int - result flags of scanning filter list                  */
2314 /* Parameters:  fin(I) - pointer to packet information                      */
2315 /*              pass(I) - default result to return for filtering            */
2316 /*                                                                          */
2317 /* Check the input/output list of rules for a match to the current packet.  */
2318 /* If a match is found, the value of fr_flags from the rule becomes the     */
2319 /* return value and fin->fin_fr points to the matched rule.                 */
2320 /*                                                                          */
2321 /* This function may be called recusively upto 16 times (limit inbuilt.)    */
2322 /* When unwinding, it should finish up with fin_depth as 0.                 */
2323 /*                                                                          */
2324 /* Could be per interface, but this gets real nasty when you don't have,    */
2325 /* or can't easily change, the kernel source code to .                      */
2326 /* ------------------------------------------------------------------------ */
2327 int
2328 ipf_scanlist(fr_info_t *fin, u_32_t pass)
2329 {
2330 	ipf_main_softc_t *softc = fin->fin_main_soft;
2331 	int rulen, portcmp, off, skip;
2332 	struct frentry *fr, *fnext;
2333 	u_32_t passt, passo;
2334 
2335 	/*
2336 	 * Do not allow nesting deeper than 16 levels.
2337 	 */
2338 	if (fin->fin_depth >= 16)
2339 		return pass;
2340 
2341 	fr = fin->fin_fr;
2342 
2343 	/*
2344 	 * If there are no rules in this list, return now.
2345 	 */
2346 	if (fr == NULL)
2347 		return pass;
2348 
2349 	skip = 0;
2350 	portcmp = 0;
2351 	fin->fin_depth++;
2352 	fin->fin_fr = NULL;
2353 	off = fin->fin_off;
2354 
2355 	if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
2356 		portcmp = 1;
2357 
2358 	for (rulen = 0; fr; fr = fnext, rulen++) {
2359 		fnext = fr->fr_next;
2360 		if (skip != 0) {
2361 			FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
2362 			skip--;
2363 			continue;
2364 		}
2365 
2366 		/*
2367 		 * In all checks below, a null (zero) value in the
2368 		 * filter struture is taken to mean a wildcard.
2369 		 *
2370 		 * check that we are working for the right interface
2371 		 */
2372 #ifdef	_KERNEL
2373 		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2374 			continue;
2375 #else
2376 		if (opts & (OPT_VERBOSE|OPT_DEBUG))
2377 			printf("\n");
2378 		FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
2379 				  FR_ISPASS(pass) ? 'p' :
2380 				  FR_ISACCOUNT(pass) ? 'A' :
2381 				  FR_ISAUTH(pass) ? 'a' :
2382 				  (pass & FR_NOMATCH) ? 'n' :'b'));
2383 		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2384 			continue;
2385 		FR_VERBOSE((":i"));
2386 #endif
2387 
2388 		switch (fr->fr_type)
2389 		{
2390 		case FR_T_IPF :
2391 		case FR_T_IPF_BUILTIN :
2392 			if (ipf_check_ipf(fin, fr, portcmp))
2393 				continue;
2394 			break;
2395 #if defined(IPFILTER_BPF)
2396 		case FR_T_BPFOPC :
2397 		case FR_T_BPFOPC_BUILTIN :
2398 		    {
2399 			u_char *mc;
2400 			int wlen;
2401 
2402 			if (*fin->fin_mp == NULL)
2403 				continue;
2404 			if (fin->fin_family != fr->fr_family)
2405 				continue;
2406 			mc = (u_char *)fin->fin_m;
2407 			wlen = fin->fin_dlen + fin->fin_hlen;
2408 			if (!bpf_filter(fr->fr_data, mc, wlen, 0))
2409 				continue;
2410 			break;
2411 		    }
2412 #endif
2413 		case FR_T_CALLFUNC_BUILTIN :
2414 		    {
2415 			frentry_t *f;
2416 
2417 			f = (*fr->fr_func)(fin, &pass);
2418 			if (f != NULL)
2419 				fr = f;
2420 			else
2421 				continue;
2422 			break;
2423 		    }
2424 
2425 		case FR_T_IPFEXPR :
2426 		case FR_T_IPFEXPR_BUILTIN :
2427 			if (fin->fin_family != fr->fr_family)
2428 				continue;
2429 			if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
2430 				continue;
2431 			break;
2432 
2433 		default :
2434 			break;
2435 		}
2436 
2437 		if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2438 			if (fin->fin_nattag == NULL)
2439 				continue;
2440 			if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
2441 				continue;
2442 		}
2443 		FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
2444 
2445 		passt = fr->fr_flags;
2446 
2447 		/*
2448 		 * If the rule is a "call now" rule, then call the function
2449 		 * in the rule, if it exists and use the results from that.
2450 		 * If the function pointer is bad, just make like we ignore
2451 		 * it, except for increasing the hit counter.
2452 		 */
2453 		if ((passt & FR_CALLNOW) != 0) {
2454 			frentry_t *frs;
2455 
2456 			ATOMIC_INC64(fr->fr_hits);
2457 			if ((fr->fr_func == NULL) ||
2458 			    (fr->fr_func == (ipfunc_t)-1))
2459 				continue;
2460 
2461 			frs = fin->fin_fr;
2462 			fin->fin_fr = fr;
2463 			fr = (*fr->fr_func)(fin, &passt);
2464 			if (fr == NULL) {
2465 				fin->fin_fr = frs;
2466 				continue;
2467 			}
2468 			passt = fr->fr_flags;
2469 		}
2470 		fin->fin_fr = fr;
2471 
2472 #ifdef  IPFILTER_LOG
2473 		/*
2474 		 * Just log this packet...
2475 		 */
2476 		if ((passt & FR_LOGMASK) == FR_LOG) {
2477 			if (ipf_log_pkt(fin, passt) == -1) {
2478 				if (passt & FR_LOGORBLOCK) {
2479 					DT(frb_logfail);
2480 					passt &= ~FR_CMDMASK;
2481 					passt |= FR_BLOCK|FR_QUICK;
2482 					fin->fin_reason = FRB_LOGFAIL;
2483 				}
2484 			}
2485 		}
2486 #endif /* IPFILTER_LOG */
2487 
2488 		MUTEX_ENTER(&fr->fr_lock);
2489 		fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2490 		fr->fr_hits++;
2491 		MUTEX_EXIT(&fr->fr_lock);
2492 		fin->fin_rule = rulen;
2493 
2494 		passo = pass;
2495 		if (FR_ISSKIP(passt)) {
2496 			skip = fr->fr_arg;
2497 			continue;
2498 		} else if (((passt & FR_LOGMASK) != FR_LOG) &&
2499 			   ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
2500 			pass = passt;
2501 		}
2502 
2503 		if (passt & (FR_RETICMP|FR_FAKEICMP))
2504 			fin->fin_icode = fr->fr_icode;
2505 
2506 		if (fr->fr_group != -1) {
2507 			(void) strncpy(fin->fin_group,
2508 				       FR_NAME(fr, fr_group),
2509 				       strlen(FR_NAME(fr, fr_group)));
2510 		} else {
2511 			fin->fin_group[0] = '\0';
2512 		}
2513 
2514 		FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
2515 
2516 		if (fr->fr_grphead != NULL) {
2517 			fin->fin_fr = fr->fr_grphead->fg_start;
2518 			FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
2519 
2520 			if (FR_ISDECAPS(passt))
2521 				passt = ipf_decaps(fin, pass, fr->fr_icode);
2522 			else
2523 				passt = ipf_scanlist(fin, pass);
2524 
2525 			if (fin->fin_fr == NULL) {
2526 				fin->fin_rule = rulen;
2527 				if (fr->fr_group != -1)
2528 					(void) strncpy(fin->fin_group,
2529 						       fr->fr_names +
2530 						       fr->fr_group,
2531 						       strlen(fr->fr_names +
2532 							      fr->fr_group));
2533 				fin->fin_fr = fr;
2534 				passt = pass;
2535 			}
2536 			pass = passt;
2537 		}
2538 
2539 		if (pass & FR_QUICK) {
2540 			/*
2541 			 * Finally, if we've asked to track state for this
2542 			 * packet, set it up.  Add state for "quick" rules
2543 			 * here so that if the action fails we can consider
2544 			 * the rule to "not match" and keep on processing
2545 			 * filter rules.
2546 			 */
2547 			if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
2548 			    !(fin->fin_flx & FI_STATE)) {
2549 				int out = fin->fin_out;
2550 
2551 				fin->fin_fr = fr;
2552 				if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2553 					LBUMPD(ipf_stats[out], fr_ads);
2554 				} else {
2555 					LBUMPD(ipf_stats[out], fr_bads);
2556 					pass = passo;
2557 					continue;
2558 				}
2559 			}
2560 			break;
2561 		}
2562 	}
2563 	fin->fin_depth--;
2564 	return pass;
2565 }
2566 
2567 
2568 /* ------------------------------------------------------------------------ */
2569 /* Function:    ipf_acctpkt                                                 */
2570 /* Returns:     frentry_t* - always returns NULL                            */
2571 /* Parameters:  fin(I) - pointer to packet information                      */
2572 /*              passp(IO) - pointer to current/new filter decision (unused) */
2573 /*                                                                          */
2574 /* Checks a packet against accounting rules, if there are any for the given */
2575 /* IP protocol version.                                                     */
2576 /*                                                                          */
2577 /* N.B.: this function returns NULL to match the prototype used by other    */
2578 /* functions called from the IPFilter "mainline" in ipf_check().            */
2579 /* ------------------------------------------------------------------------ */
2580 frentry_t *
2581 ipf_acctpkt(fr_info_t *fin, u_32_t *passp)
2582 {
2583 	ipf_main_softc_t *softc = fin->fin_main_soft;
2584 	char group[FR_GROUPLEN];
2585 	frentry_t *fr, *frsave;
2586 	u_32_t pass, rulen;
2587 
2588 	passp = passp;
2589 	fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
2590 
2591 	if (fr != NULL) {
2592 		frsave = fin->fin_fr;
2593 		bcopy(fin->fin_group, group, FR_GROUPLEN);
2594 		rulen = fin->fin_rule;
2595 		fin->fin_fr = fr;
2596 		pass = ipf_scanlist(fin, FR_NOMATCH);
2597 		if (FR_ISACCOUNT(pass)) {
2598 			LBUMPD(ipf_stats[0], fr_acct);
2599 		}
2600 		fin->fin_fr = frsave;
2601 		bcopy(group, fin->fin_group, FR_GROUPLEN);
2602 		fin->fin_rule = rulen;
2603 	}
2604 	return NULL;
2605 }
2606 
2607 
2608 /* ------------------------------------------------------------------------ */
2609 /* Function:    ipf_firewall                                                */
2610 /* Returns:     frentry_t* - returns pointer to matched rule, if no matches */
2611 /*                           were found, returns NULL.                      */
2612 /* Parameters:  fin(I) - pointer to packet information                      */
2613 /*              passp(IO) - pointer to current/new filter decision (unused) */
2614 /*                                                                          */
2615 /* Applies an appropriate set of firewall rules to the packet, to see if    */
2616 /* there are any matches.  The first check is to see if a match can be seen */
2617 /* in the cache.  If not, then search an appropriate list of rules.  Once a */
2618 /* matching rule is found, take any appropriate actions as defined by the   */
2619 /* rule - except logging.                                                   */
2620 /* ------------------------------------------------------------------------ */
2621 static frentry_t *
2622 ipf_firewall(fr_info_t *fin, u_32_t *passp)
2623 {
2624 	ipf_main_softc_t *softc = fin->fin_main_soft;
2625 	frentry_t *fr;
2626 	u_32_t pass;
2627 	int out;
2628 
2629 	out = fin->fin_out;
2630 	pass = *passp;
2631 
2632 	/*
2633 	 * This rule cache will only affect packets that are not being
2634 	 * statefully filtered.
2635 	 */
2636 	fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
2637 	if (fin->fin_fr != NULL)
2638 		pass = ipf_scanlist(fin, softc->ipf_pass);
2639 
2640 	if ((pass & FR_NOMATCH)) {
2641 		LBUMPD(ipf_stats[out], fr_nom);
2642 	}
2643 	fr = fin->fin_fr;
2644 
2645 	/*
2646 	 * Apply packets per second rate-limiting to a rule as required.
2647 	 */
2648 	if ((fr != NULL) && (fr->fr_pps != 0) &&
2649 	    !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2650 		DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
2651 		pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
2652 		pass |= FR_BLOCK;
2653 		LBUMPD(ipf_stats[out], fr_ppshit);
2654 		fin->fin_reason = FRB_PPSRATE;
2655 	}
2656 
2657 	/*
2658 	 * If we fail to add a packet to the authorization queue, then we
2659 	 * drop the packet later.  However, if it was added then pretend
2660 	 * we've dropped it already.
2661 	 */
2662 	if (FR_ISAUTH(pass)) {
2663 		if (ipf_auth_new(fin->fin_m, fin) != 0) {
2664 			DT1(frb_authnew, fr_info_t *, fin);
2665 			fin->fin_m = *fin->fin_mp = NULL;
2666 			fin->fin_reason = FRB_AUTHNEW;
2667 			fin->fin_error = 0;
2668 		} else {
2669 			IPFERROR(1);
2670 			fin->fin_error = ENOSPC;
2671 		}
2672 	}
2673 
2674 	if ((fr != NULL) && (fr->fr_func != NULL) &&
2675 	    (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2676 		(void) (*fr->fr_func)(fin, &pass);
2677 
2678 	/*
2679 	 * If a rule is a pre-auth rule, check again in the list of rules
2680 	 * loaded for authenticated use.  It does not particulary matter
2681 	 * if this search fails because a "preauth" result, from a rule,
2682 	 * is treated as "not a pass", hence the packet is blocked.
2683 	 */
2684 	if (FR_ISPREAUTH(pass)) {
2685 		pass = ipf_auth_pre_scanlist(softc, fin, pass);
2686 	}
2687 
2688 	/*
2689 	 * If the rule has "keep frag" and the packet is actually a fragment,
2690 	 * then create a fragment state entry.
2691 	 */
2692 	if ((pass & (FR_KEEPFRAG|FR_KEEPSTATE)) == FR_KEEPFRAG) {
2693 		if (fin->fin_flx & FI_FRAG) {
2694 			if (ipf_frag_new(softc, fin, pass) == -1) {
2695 				LBUMP(ipf_stats[out].fr_bnfr);
2696 			} else {
2697 				LBUMP(ipf_stats[out].fr_nfr);
2698 			}
2699 		} else {
2700 			LBUMP(ipf_stats[out].fr_cfr);
2701 		}
2702 	}
2703 
2704 	fr = fin->fin_fr;
2705 	*passp = pass;
2706 
2707 	return fr;
2708 }
2709 
2710 
2711 /* ------------------------------------------------------------------------ */
2712 /* Function:    ipf_check                                                   */
2713 /* Returns:     int -  0 == packet allowed through,                         */
2714 /*              User space:                                                 */
2715 /*                    -1 == packet blocked                                  */
2716 /*                     1 == packet not matched                              */
2717 /*                    -2 == requires authentication                         */
2718 /*              Kernel:                                                     */
2719 /*                   > 0 == filter error # for packet                       */
2720 /* Parameters: ip(I)   - pointer to start of IPv4/6 packet                  */
2721 /*             hlen(I) - length of header                                   */
2722 /*             ifp(I)  - pointer to interface this packet is on             */
2723 /*             out(I)  - 0 == packet going in, 1 == packet going out        */
2724 /*             mp(IO)  - pointer to caller's buffer pointer that holds this */
2725 /*                       IP packet.                                         */
2726 /* Solaris & HP-UX ONLY :                                                   */
2727 /*             qpi(I)  - pointer to STREAMS queue information for this      */
2728 /*                       interface & direction.                             */
2729 /*                                                                          */
2730 /* ipf_check() is the master function for all IPFilter packet processing.   */
2731 /* It orchestrates: Network Address Translation (NAT), checking for packet  */
2732 /* authorisation (or pre-authorisation), presence of related state info.,   */
2733 /* generating log entries, IP packet accounting, routing of packets as      */
2734 /* directed by firewall rules and of course whether or not to allow the     */
2735 /* packet to be further processed by the kernel.                            */
2736 /*                                                                          */
2737 /* For packets blocked, the contents of "mp" will be NULL'd and the buffer  */
2738 /* freed.  Packets passed may be returned with the pointer pointed to by    */
2739 /* by "mp" changed to a new buffer.                                         */
2740 /* ------------------------------------------------------------------------ */
2741 int
2742 ipf_check(void *ctx, ip_t *ip, int hlen, void *ifp, int out,
2743 #if defined(_KERNEL) && defined(MENTAT)
2744     void *qif,
2745 #endif
2746     mb_t **mp)
2747 {
2748 	/*
2749 	 * The above really sucks, but short of writing a diff
2750 	 */
2751 	ipf_main_softc_t *softc = ctx;
2752 	fr_info_t frinfo;
2753 	fr_info_t *fin = &frinfo;
2754 	u_32_t pass = softc->ipf_pass;
2755 	frentry_t *fr = NULL;
2756 	int v = IP_V(ip);
2757 	mb_t *mc = NULL;
2758 	mb_t *m;
2759 	/*
2760 	 * The first part of ipf_check() deals with making sure that what goes
2761 	 * into the filtering engine makes some sense.  Information about the
2762 	 * the packet is distilled, collected into a fr_info_t structure and
2763 	 * the an attempt to ensure the buffer the packet is in is big enough
2764 	 * to hold all the required packet headers.
2765 	 */
2766 #ifdef	_KERNEL
2767 # ifdef MENTAT
2768 	qpktinfo_t *qpi = qif;
2769 
2770 #  ifdef __sparc
2771 	if ((u_int)ip & 0x3)
2772 		return 2;
2773 #  endif
2774 # else
2775 	SPL_INT(s);
2776 # endif
2777 
2778 	if (softc->ipf_running <= 0) {
2779 		return 0;
2780 	}
2781 
2782 	bzero((char *)fin, sizeof(*fin));
2783 
2784 # ifdef MENTAT
2785 	if (qpi->qpi_flags & QF_BROADCAST)
2786 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2787 	if (qpi->qpi_flags & QF_MULTICAST)
2788 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2789 	m = qpi->qpi_m;
2790 	fin->fin_qfm = m;
2791 	fin->fin_qpi = qpi;
2792 # else /* MENTAT */
2793 
2794 	m = *mp;
2795 
2796 #  if defined(M_MCAST)
2797 	if ((m->m_flags & M_MCAST) != 0)
2798 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2799 #  endif
2800 #  if defined(M_MLOOP)
2801 	if ((m->m_flags & M_MLOOP) != 0)
2802 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2803 #  endif
2804 #  if defined(M_BCAST)
2805 	if ((m->m_flags & M_BCAST) != 0)
2806 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2807 #  endif
2808 #  ifdef M_CANFASTFWD
2809 	/*
2810 	 * XXX For now, IP Filter and fast-forwarding of cached flows
2811 	 * XXX are mutually exclusive.  Eventually, IP Filter should
2812 	 * XXX get a "can-fast-forward" filter rule.
2813 	 */
2814 	m->m_flags &= ~M_CANFASTFWD;
2815 #  endif /* M_CANFASTFWD */
2816 #  if defined(CSUM_DELAY_DATA) && (!defined(__FreeBSD_version) || \
2817 				   (__FreeBSD_version < 501108))
2818 	/*
2819 	 * disable delayed checksums.
2820 	 */
2821 	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2822 		in_delayed_cksum(m);
2823 		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2824 	}
2825 #  endif /* CSUM_DELAY_DATA */
2826 # endif /* MENTAT */
2827 #else
2828 	bzero((char *)fin, sizeof(*fin));
2829 	m = *mp;
2830 # if defined(M_MCAST)
2831 	if ((m->m_flags & M_MCAST) != 0)
2832 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2833 # endif
2834 # if defined(M_MLOOP)
2835 	if ((m->m_flags & M_MLOOP) != 0)
2836 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2837 # endif
2838 # if defined(M_BCAST)
2839 	if ((m->m_flags & M_BCAST) != 0)
2840 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2841 # endif
2842 #endif /* _KERNEL */
2843 
2844 	fin->fin_v = v;
2845 	fin->fin_m = m;
2846 	fin->fin_ip = ip;
2847 	fin->fin_mp = mp;
2848 	fin->fin_out = out;
2849 	fin->fin_ifp = ifp;
2850 	fin->fin_error = ENETUNREACH;
2851 	fin->fin_hlen = (u_short)hlen;
2852 	fin->fin_dp = (char *)ip + hlen;
2853 	fin->fin_main_soft = softc;
2854 
2855 	fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2856 
2857 	SPL_NET(s);
2858 
2859 #ifdef	USE_INET6
2860 	if (v == 6) {
2861 		LBUMP(ipf_stats[out].fr_ipv6);
2862 		/*
2863 		 * Jumbo grams are quite likely too big for internal buffer
2864 		 * structures to handle comfortably, for now, so just drop
2865 		 * them.
2866 		 */
2867 		if (((ip6_t *)ip)->ip6_plen == 0) {
2868 			DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
2869 			pass = FR_BLOCK|FR_NOMATCH;
2870 			fin->fin_reason = FRB_JUMBO;
2871 			goto finished;
2872 		}
2873 		fin->fin_family = AF_INET6;
2874 	} else
2875 #endif
2876 	{
2877 		fin->fin_family = AF_INET;
2878 	}
2879 
2880 	if (ipf_makefrip(hlen, ip, fin) == -1) {
2881 		DT1(frb_makefrip, fr_info_t *, fin);
2882 		pass = FR_BLOCK|FR_NOMATCH;
2883 		fin->fin_reason = FRB_MAKEFRIP;
2884 		goto finished;
2885 	}
2886 
2887 	/*
2888 	 * For at least IPv6 packets, if a m_pullup() fails then this pointer
2889 	 * becomes NULL and so we have no packet to free.
2890 	 */
2891 	if (*fin->fin_mp == NULL)
2892 		goto finished;
2893 
2894 	if (!out) {
2895 		if (v == 4) {
2896 			if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
2897 				LBUMPD(ipf_stats[0], fr_v4_badsrc);
2898 				fin->fin_flx |= FI_BADSRC;
2899 			}
2900 			if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
2901 				LBUMPD(ipf_stats[0], fr_v4_badttl);
2902 				fin->fin_flx |= FI_LOWTTL;
2903 			}
2904 		}
2905 #ifdef USE_INET6
2906 		else  if (v == 6) {
2907 			if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
2908 				LBUMPD(ipf_stats[0], fr_v6_badttl);
2909 				fin->fin_flx |= FI_LOWTTL;
2910 			}
2911 		}
2912 #endif
2913 	}
2914 
2915 	if (fin->fin_flx & FI_SHORT) {
2916 		LBUMPD(ipf_stats[out], fr_short);
2917 	}
2918 
2919 	READ_ENTER(&softc->ipf_mutex);
2920 
2921 	if (!out) {
2922 		switch (fin->fin_v)
2923 		{
2924 		case 4 :
2925 			if (ipf_nat_checkin(fin, &pass) == -1) {
2926 				goto filterdone;
2927 			}
2928 			break;
2929 #ifdef USE_INET6
2930 		case 6 :
2931 			if (ipf_nat6_checkin(fin, &pass) == -1) {
2932 				goto filterdone;
2933 			}
2934 			break;
2935 #endif
2936 		default :
2937 			break;
2938 		}
2939 	}
2940 	/*
2941 	 * Check auth now.
2942 	 * If a packet is found in the auth table, then skip checking
2943 	 * the access lists for permission but we do need to consider
2944 	 * the result as if it were from the ACL's.  In addition, being
2945 	 * found in the auth table means it has been seen before, so do
2946 	 * not pass it through accounting (again), lest it be counted twice.
2947 	 */
2948 	fr = ipf_auth_check(fin, &pass);
2949 	if (!out && (fr == NULL))
2950 		(void) ipf_acctpkt(fin, NULL);
2951 
2952 	if (fr == NULL) {
2953 		if ((fin->fin_flx & FI_FRAG) != 0)
2954 			fr = ipf_frag_known(fin, &pass);
2955 
2956 		if (fr == NULL)
2957 			fr = ipf_state_check(fin, &pass);
2958 	}
2959 
2960 	if ((pass & FR_NOMATCH) || (fr == NULL))
2961 		fr = ipf_firewall(fin, &pass);
2962 
2963 	/*
2964 	 * If we've asked to track state for this packet, set it up.
2965 	 * Here rather than ipf_firewall because ipf_checkauth may decide
2966 	 * to return a packet for "keep state"
2967 	 */
2968 	if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
2969 	    !(fin->fin_flx & FI_STATE)) {
2970 		if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2971 			LBUMP(ipf_stats[out].fr_ads);
2972 		} else {
2973 			LBUMP(ipf_stats[out].fr_bads);
2974 			if (FR_ISPASS(pass)) {
2975 				DT(frb_stateadd);
2976 				pass &= ~FR_CMDMASK;
2977 				pass |= FR_BLOCK;
2978 				fin->fin_reason = FRB_STATEADD;
2979 			}
2980 		}
2981 	}
2982 
2983 	fin->fin_fr = fr;
2984 	if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
2985 		fin->fin_dif = &fr->fr_dif;
2986 		fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
2987 	}
2988 
2989 	/*
2990 	 * Only count/translate packets which will be passed on, out the
2991 	 * interface.
2992 	 */
2993 	if (out && FR_ISPASS(pass)) {
2994 		(void) ipf_acctpkt(fin, NULL);
2995 
2996 		switch (fin->fin_v)
2997 		{
2998 		case 4 :
2999 			if (ipf_nat_checkout(fin, &pass) == -1) {
3000 				;
3001 			} else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
3002 				if (ipf_updateipid(fin) == -1) {
3003 					DT(frb_updateipid);
3004 					LBUMP(ipf_stats[1].fr_ipud);
3005 					pass &= ~FR_CMDMASK;
3006 					pass |= FR_BLOCK;
3007 					fin->fin_reason = FRB_UPDATEIPID;
3008 				} else {
3009 					LBUMP(ipf_stats[0].fr_ipud);
3010 				}
3011 			}
3012 			break;
3013 #ifdef USE_INET6
3014 		case 6 :
3015 			(void) ipf_nat6_checkout(fin, &pass);
3016 			break;
3017 #endif
3018 		default :
3019 			break;
3020 		}
3021 	}
3022 
3023 filterdone:
3024 #ifdef	IPFILTER_LOG
3025 	if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
3026 		(void) ipf_dolog(fin, &pass);
3027 	}
3028 #endif
3029 
3030 	/*
3031 	 * The FI_STATE flag is cleared here so that calling ipf_state_check
3032 	 * will work when called from inside of fr_fastroute.  Although
3033 	 * there is a similar flag, FI_NATED, for NAT, it does have the same
3034 	 * impact on code execution.
3035 	 */
3036 	fin->fin_flx &= ~FI_STATE;
3037 
3038 #if defined(FASTROUTE_RECURSION)
3039 	/*
3040 	 * Up the reference on fr_lock and exit ipf_mutex. The generation of
3041 	 * a packet below can sometimes cause a recursive call into IPFilter.
3042 	 * On those platforms where that does happen, we need to hang onto
3043 	 * the filter rule just in case someone decides to remove or flush it
3044 	 * in the meantime.
3045 	 */
3046 	if (fr != NULL) {
3047 		MUTEX_ENTER(&fr->fr_lock);
3048 		fr->fr_ref++;
3049 		MUTEX_EXIT(&fr->fr_lock);
3050 	}
3051 
3052 	RWLOCK_EXIT(&softc->ipf_mutex);
3053 #endif
3054 
3055 	if ((pass & FR_RETMASK) != 0) {
3056 		/*
3057 		 * Should we return an ICMP packet to indicate error
3058 		 * status passing through the packet filter ?
3059 		 * WARNING: ICMP error packets AND TCP RST packets should
3060 		 * ONLY be sent in repsonse to incoming packets.  Sending
3061 		 * them in response to outbound packets can result in a
3062 		 * panic on some operating systems.
3063 		 */
3064 		if (!out) {
3065 			if (pass & FR_RETICMP) {
3066 				int dst;
3067 
3068 				if ((pass & FR_RETMASK) == FR_FAKEICMP)
3069 					dst = 1;
3070 				else
3071 					dst = 0;
3072 				(void) ipf_send_icmp_err(ICMP_UNREACH, fin,
3073 							 dst);
3074 				LBUMP(ipf_stats[0].fr_ret);
3075 			} else if (((pass & FR_RETMASK) == FR_RETRST) &&
3076 				   !(fin->fin_flx & FI_SHORT)) {
3077 				if (((fin->fin_flx & FI_OOW) != 0) ||
3078 				    (ipf_send_reset(fin) == 0)) {
3079 					LBUMP(ipf_stats[1].fr_ret);
3080 				}
3081 			}
3082 
3083 			/*
3084 			 * When using return-* with auth rules, the auth code
3085 			 * takes over disposing of this packet.
3086 			 */
3087 			if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
3088 				DT1(frb_authcapture, fr_info_t *, fin);
3089 				fin->fin_m = *fin->fin_mp = NULL;
3090 				fin->fin_reason = FRB_AUTHCAPTURE;
3091 				m = NULL;
3092 			}
3093 		} else {
3094 			if (pass & FR_RETRST) {
3095 				fin->fin_error = ECONNRESET;
3096 			}
3097 		}
3098 	}
3099 
3100 	/*
3101 	 * After the above so that ICMP unreachables and TCP RSTs get
3102 	 * created properly.
3103 	 */
3104 	if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
3105 		ipf_nat_uncreate(fin);
3106 
3107 	/*
3108 	 * If we didn't drop off the bottom of the list of rules (and thus
3109 	 * the 'current' rule fr is not NULL), then we may have some extra
3110 	 * instructions about what to do with a packet.
3111 	 * Once we're finished return to our caller, freeing the packet if
3112 	 * we are dropping it.
3113 	 */
3114 	if (fr != NULL) {
3115 		frdest_t *fdp;
3116 
3117 		/*
3118 		 * Generate a duplicated packet first because ipf_fastroute
3119 		 * can lead to fin_m being free'd... not good.
3120 		 */
3121 		fdp = fin->fin_dif;
3122 		if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3123 		    (fdp->fd_ptr != (void *)-1) && (fin->fin_m != NULL)) {
3124 			mc = M_COPY(fin->fin_m);
3125 			if (mc != NULL)
3126 				ipf_fastroute(mc, &mc, fin, fdp);
3127 		}
3128 
3129 		fdp = fin->fin_tif;
3130 		if (!out && (pass & FR_FASTROUTE)) {
3131 			/*
3132 			 * For fastroute rule, no destination interface defined
3133 			 * so pass NULL as the frdest_t parameter
3134 			 */
3135 			(void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
3136 			m = *mp = NULL;
3137 		} else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3138 			   (fdp->fd_ptr != (struct ifnet *)-1)) {
3139 			/* this is for to rules: */
3140 			ipf_fastroute(fin->fin_m, mp, fin, fdp);
3141 			m = *mp = NULL;
3142 		}
3143 
3144 #if defined(FASTROUTE_RECURSION)
3145 		(void) ipf_derefrule(softc, &fr);
3146 #endif
3147 	}
3148 #if !defined(FASTROUTE_RECURSION)
3149 	RWLOCK_EXIT(&softc->ipf_mutex);
3150 #endif
3151 
3152 finished:
3153 	if (!FR_ISPASS(pass)) {
3154 		LBUMP(ipf_stats[out].fr_block);
3155 		if (*mp != NULL) {
3156 #ifdef _KERNEL
3157 			FREE_MB_T(*mp);
3158 #endif
3159 			m = *mp = NULL;
3160 		}
3161 	} else {
3162 		LBUMP(ipf_stats[out].fr_pass);
3163 #if defined(_KERNEL) && defined(__sgi)
3164 		if ((fin->fin_hbuf != NULL) &&
3165 		    (mtod(fin->fin_m, struct ip *) != fin->fin_ip)) {
3166 			COPYBACK(fin->fin_m, 0, fin->fin_plen, fin->fin_hbuf);
3167 		}
3168 #endif
3169 	}
3170 
3171 	SPL_X(s);
3172 
3173 #ifdef _KERNEL
3174 	if (FR_ISPASS(pass))
3175 		return 0;
3176 	LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3177 	return fin->fin_error;
3178 #else /* _KERNEL */
3179 	if (*mp != NULL)
3180 		(*mp)->mb_ifp = fin->fin_ifp;
3181 	blockreason = fin->fin_reason;
3182 	FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
3183 	/*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
3184 		if ((pass & FR_NOMATCH) != 0)
3185 			return 1;
3186 
3187 	if ((pass & FR_RETMASK) != 0)
3188 		switch (pass & FR_RETMASK)
3189 		{
3190 		case FR_RETRST :
3191 			return 3;
3192 		case FR_RETICMP :
3193 			return 4;
3194 		case FR_FAKEICMP :
3195 			return 5;
3196 		}
3197 
3198 	switch (pass & FR_CMDMASK)
3199 	{
3200 	case FR_PASS :
3201 		return 0;
3202 	case FR_BLOCK :
3203 		return -1;
3204 	case FR_AUTH :
3205 		return -2;
3206 	case FR_ACCOUNT :
3207 		return -3;
3208 	case FR_PREAUTH :
3209 		return -4;
3210 	}
3211 	return 2;
3212 #endif /* _KERNEL */
3213 }
3214 
3215 
3216 #ifdef	IPFILTER_LOG
3217 /* ------------------------------------------------------------------------ */
3218 /* Function:    ipf_dolog                                                   */
3219 /* Returns:     frentry_t* - returns contents of fin_fr (no change made)    */
3220 /* Parameters:  fin(I) - pointer to packet information                      */
3221 /*              passp(IO) - pointer to current/new filter decision (unused) */
3222 /*                                                                          */
3223 /* Checks flags set to see how a packet should be logged, if it is to be    */
3224 /* logged.  Adjust statistics based on its success or not.                  */
3225 /* ------------------------------------------------------------------------ */
3226 frentry_t *
3227 ipf_dolog(fr_info_t *fin, u_32_t *passp)
3228 {
3229 	ipf_main_softc_t *softc = fin->fin_main_soft;
3230 	u_32_t pass;
3231 	int out;
3232 
3233 	out = fin->fin_out;
3234 	pass = *passp;
3235 
3236 	if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
3237 		pass |= FF_LOGNOMATCH;
3238 		LBUMPD(ipf_stats[out], fr_npkl);
3239 		goto logit;
3240 
3241 	} else if (((pass & FR_LOGMASK) == FR_LOGP) ||
3242 	    (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
3243 		if ((pass & FR_LOGMASK) != FR_LOGP)
3244 			pass |= FF_LOGPASS;
3245 		LBUMPD(ipf_stats[out], fr_ppkl);
3246 		goto logit;
3247 
3248 	} else if (((pass & FR_LOGMASK) == FR_LOGB) ||
3249 		   (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
3250 		if ((pass & FR_LOGMASK) != FR_LOGB)
3251 			pass |= FF_LOGBLOCK;
3252 		LBUMPD(ipf_stats[out], fr_bpkl);
3253 
3254 logit:
3255 		if (ipf_log_pkt(fin, pass) == -1) {
3256 			/*
3257 			 * If the "or-block" option has been used then
3258 			 * block the packet if we failed to log it.
3259 			 */
3260 			if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
3261 				DT1(frb_logfail2, u_int, pass);
3262 				pass &= ~FR_CMDMASK;
3263 				pass |= FR_BLOCK;
3264 				fin->fin_reason = FRB_LOGFAIL2;
3265 			}
3266 		}
3267 		*passp = pass;
3268 	}
3269 
3270 	return fin->fin_fr;
3271 }
3272 #endif /* IPFILTER_LOG */
3273 
3274 
3275 /* ------------------------------------------------------------------------ */
3276 /* Function:    ipf_cksum                                                   */
3277 /* Returns:     u_short - IP header checksum                                */
3278 /* Parameters:  addr(I) - pointer to start of buffer to checksum            */
3279 /*              len(I)  - length of buffer in bytes                         */
3280 /*                                                                          */
3281 /* Calculate the two's complement 16 bit checksum of the buffer passed.     */
3282 /*                                                                          */
3283 /* N.B.: addr should be 16bit aligned.                                      */
3284 /* ------------------------------------------------------------------------ */
3285 u_short
3286 ipf_cksum(u_short *addr, int len)
3287 {
3288 	u_32_t sum = 0;
3289 
3290 	for (sum = 0; len > 1; len -= 2)
3291 		sum += *addr++;
3292 
3293 	/* mop up an odd byte, if necessary */
3294 	if (len == 1)
3295 		sum += *(u_char *)addr;
3296 
3297 	/*
3298 	 * add back carry outs from top 16 bits to low 16 bits
3299 	 */
3300 	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
3301 	sum += (sum >> 16);			/* add carry */
3302 	return (u_short)(~sum);
3303 }
3304 
3305 
3306 /* ------------------------------------------------------------------------ */
3307 /* Function:    fr_cksum                                                    */
3308 /* Returns:     u_short - layer 4 checksum                                  */
3309 /* Parameters:  fin(I)     - pointer to packet information                  */
3310 /*              ip(I)      - pointer to IP header                           */
3311 /*              l4proto(I) - protocol to caclulate checksum for             */
3312 /*              l4hdr(I)   - pointer to layer 4 header                      */
3313 /*                                                                          */
3314 /* Calculates the TCP checksum for the packet held in "m", using the data   */
3315 /* in the IP header "ip" to seed it.                                        */
3316 /*                                                                          */
3317 /* NB: This function assumes we've pullup'd enough for all of the IP header */
3318 /* and the TCP header.  We also assume that data blocks aren't allocated in */
3319 /* odd sizes.                                                               */
3320 /*                                                                          */
3321 /* Expects ip_len and ip_off to be in network byte order when called.       */
3322 /* ------------------------------------------------------------------------ */
3323 u_short
3324 fr_cksum(fr_info_t *fin, ip_t *ip, int l4proto, void *l4hdr)
3325 {
3326 	u_short *sp, slen, sumsave, *csump;
3327 	u_int sum, sum2;
3328 	int hlen;
3329 	int off;
3330 #ifdef	USE_INET6
3331 	ip6_t *ip6;
3332 #endif
3333 
3334 	csump = NULL;
3335 	sumsave = 0;
3336 	sp = NULL;
3337 	slen = 0;
3338 	hlen = 0;
3339 	sum = 0;
3340 
3341 	sum = htons((u_short)l4proto);
3342 	/*
3343 	 * Add up IP Header portion
3344 	 */
3345 #ifdef	USE_INET6
3346 	if (IP_V(ip) == 4) {
3347 #endif
3348 		hlen = IP_HL(ip) << 2;
3349 		off = hlen;
3350 		sp = (u_short *)&ip->ip_src;
3351 		sum += *sp++;	/* ip_src */
3352 		sum += *sp++;
3353 		sum += *sp++;	/* ip_dst */
3354 		sum += *sp++;
3355 #ifdef	USE_INET6
3356 	} else if (IP_V(ip) == 6) {
3357 		ip6 = (ip6_t *)ip;
3358 		hlen = sizeof(*ip6);
3359 		off = ((char *)fin->fin_dp - (char *)fin->fin_ip);
3360 		sp = (u_short *)&ip6->ip6_src;
3361 		sum += *sp++;	/* ip6_src */
3362 		sum += *sp++;
3363 		sum += *sp++;
3364 		sum += *sp++;
3365 		sum += *sp++;
3366 		sum += *sp++;
3367 		sum += *sp++;
3368 		sum += *sp++;
3369 		/* This needs to be routing header aware. */
3370 		sum += *sp++;	/* ip6_dst */
3371 		sum += *sp++;
3372 		sum += *sp++;
3373 		sum += *sp++;
3374 		sum += *sp++;
3375 		sum += *sp++;
3376 		sum += *sp++;
3377 		sum += *sp++;
3378 	} else {
3379 		return 0xffff;
3380 	}
3381 #endif
3382 	slen = fin->fin_plen - off;
3383 	sum += htons(slen);
3384 
3385 	switch (l4proto)
3386 	{
3387 	case IPPROTO_UDP :
3388 		csump = &((udphdr_t *)l4hdr)->uh_sum;
3389 		break;
3390 
3391 	case IPPROTO_TCP :
3392 		csump = &((tcphdr_t *)l4hdr)->th_sum;
3393 		break;
3394 	case IPPROTO_ICMP :
3395 		csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
3396 		sum = 0;	/* Pseudo-checksum is not included */
3397 		break;
3398 #ifdef USE_INET6
3399 	case IPPROTO_ICMPV6 :
3400 		csump = &((struct icmp6_hdr *)l4hdr)->icmp6_cksum;
3401 		break;
3402 #endif
3403 	default :
3404 		break;
3405 	}
3406 
3407 	if (csump != NULL) {
3408 		sumsave = *csump;
3409 		*csump = 0;
3410 	}
3411 
3412 	sum2 = ipf_pcksum(fin, off, sum);
3413 	if (csump != NULL)
3414 		*csump = sumsave;
3415 	return sum2;
3416 }
3417 
3418 
3419 /* ------------------------------------------------------------------------ */
3420 /* Function:    ipf_findgroup                                               */
3421 /* Returns:     frgroup_t * - NULL = group not found, else pointer to group */
3422 /* Parameters:  softc(I) - pointer to soft context main structure           */
3423 /*              group(I) - group name to search for                         */
3424 /*              unit(I)  - device to which this group belongs               */
3425 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3426 /*              fgpp(O)  - pointer to place to store pointer to the pointer */
3427 /*                         to where to add the next (last) group or where   */
3428 /*                         to delete group from.                            */
3429 /*                                                                          */
3430 /* Search amongst the defined groups for a particular group number.         */
3431 /* ------------------------------------------------------------------------ */
3432 frgroup_t *
3433 ipf_findgroup(ipf_main_softc_t *softc, char *group, minor_t unit, int set,
3434     frgroup_t ***fgpp)
3435 {
3436 	frgroup_t *fg, **fgp;
3437 
3438 	/*
3439 	 * Which list of groups to search in is dependent on which list of
3440 	 * rules are being operated on.
3441 	 */
3442 	fgp = &softc->ipf_groups[unit][set];
3443 
3444 	while ((fg = *fgp) != NULL) {
3445 		if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3446 			break;
3447 		else
3448 			fgp = &fg->fg_next;
3449 	}
3450 	if (fgpp != NULL)
3451 		*fgpp = fgp;
3452 	return fg;
3453 }
3454 
3455 
3456 /* ------------------------------------------------------------------------ */
3457 /* Function:    ipf_group_add                                               */
3458 /* Returns:     frgroup_t * - NULL == did not create group,                 */
3459 /*                            != NULL == pointer to the group               */
3460 /* Parameters:  softc(I) - pointer to soft context main structure           */
3461 /*              num(I)   - group number to add                              */
3462 /*              head(I)  - rule pointer that is using this as the head      */
3463 /*              flags(I) - rule flags which describe the type of rule it is */
3464 /*              unit(I)  - device to which this group will belong to        */
3465 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3466 /* Write Locks: ipf_mutex                                                   */
3467 /*                                                                          */
3468 /* Add a new group head, or if it already exists, increase the reference    */
3469 /* count to it.                                                             */
3470 /* ------------------------------------------------------------------------ */
3471 frgroup_t *
3472 ipf_group_add(ipf_main_softc_t *softc, char *group, void *head, u_32_t flags,
3473     minor_t unit, int set)
3474 {
3475 	frgroup_t *fg, **fgp;
3476 	u_32_t gflags;
3477 
3478 	if (group == NULL)
3479 		return NULL;
3480 
3481 	if (unit == IPL_LOGIPF && *group == '\0')
3482 		return NULL;
3483 
3484 	fgp = NULL;
3485 	gflags = flags & FR_INOUT;
3486 
3487 	fg = ipf_findgroup(softc, group, unit, set, &fgp);
3488 	if (fg != NULL) {
3489 		if (fg->fg_head == NULL && head != NULL)
3490 			fg->fg_head = head;
3491 		if (fg->fg_flags == 0)
3492 			fg->fg_flags = gflags;
3493 		else if (gflags != fg->fg_flags)
3494 			return NULL;
3495 		fg->fg_ref++;
3496 		return fg;
3497 	}
3498 
3499 	KMALLOC(fg, frgroup_t *);
3500 	if (fg != NULL) {
3501 		fg->fg_head = head;
3502 		fg->fg_start = NULL;
3503 		fg->fg_next = *fgp;
3504 		bcopy(group, fg->fg_name, strlen(group) + 1);
3505 		fg->fg_flags = gflags;
3506 		fg->fg_ref = 1;
3507 		fg->fg_set = &softc->ipf_groups[unit][set];
3508 		*fgp = fg;
3509 	}
3510 	return fg;
3511 }
3512 
3513 
3514 /* ------------------------------------------------------------------------ */
3515 /* Function:    ipf_group_del                                               */
3516 /* Returns:     int      - number of rules deleted                          */
3517 /* Parameters:  softc(I) - pointer to soft context main structure           */
3518 /*              group(I) - group name to delete                             */
3519 /*              fr(I)    - filter rule from which group is referenced       */
3520 /* Write Locks: ipf_mutex                                                   */
3521 /*                                                                          */
3522 /* This function is called whenever a reference to a group is to be dropped */
3523 /* and thus its reference count needs to be lowered and the group free'd if */
3524 /* the reference count reaches zero. Passing in fr is really for the sole   */
3525 /* purpose of knowing when the head rule is being deleted.                  */
3526 /* ------------------------------------------------------------------------ */
3527 void
3528 ipf_group_del(ipf_main_softc_t *softc, frgroup_t *group, frentry_t *fr)
3529 {
3530 
3531 	if (group->fg_head == fr)
3532 		group->fg_head = NULL;
3533 
3534 	group->fg_ref--;
3535 	if ((group->fg_ref == 0) && (group->fg_start == NULL))
3536 		ipf_group_free(group);
3537 }
3538 
3539 
3540 /* ------------------------------------------------------------------------ */
3541 /* Function:    ipf_group_free                                              */
3542 /* Returns:     Nil                                                         */
3543 /* Parameters:  group(I) - pointer to filter rule group                     */
3544 /*                                                                          */
3545 /* Remove the group from the list of groups and free it.                    */
3546 /* ------------------------------------------------------------------------ */
3547 static void
3548 ipf_group_free(frgroup_t *group)
3549 {
3550 	frgroup_t **gp;
3551 
3552 	for (gp = group->fg_set; *gp != NULL; gp = &(*gp)->fg_next) {
3553 		if (*gp == group) {
3554 			*gp = group->fg_next;
3555 			break;
3556 		}
3557 	}
3558 	KFREE(group);
3559 }
3560 
3561 
3562 /* ------------------------------------------------------------------------ */
3563 /* Function:    ipf_group_flush                                             */
3564 /* Returns:     int      - number of rules flush from group                 */
3565 /* Parameters:  softc(I) - pointer to soft context main structure           */
3566 /* Parameters:  group(I) - pointer to filter rule group                     */
3567 /*                                                                          */
3568 /* Remove all of the rules that currently are listed under the given group. */
3569 /* ------------------------------------------------------------------------ */
3570 static int
3571 ipf_group_flush(ipf_main_softc_t *softc, frgroup_t *group)
3572 {
3573 	int gone = 0;
3574 
3575 	(void) ipf_flushlist(softc, &gone, &group->fg_start);
3576 
3577 	return gone;
3578 }
3579 
3580 
3581 /* ------------------------------------------------------------------------ */
3582 /* Function:    ipf_getrulen                                                */
3583 /* Returns:     frentry_t * - NULL == not found, else pointer to rule n     */
3584 /* Parameters:  softc(I) - pointer to soft context main structure           */
3585 /* Parameters:  unit(I)  - device for which to count the rule's number      */
3586 /*              flags(I) - which set of rules to find the rule in           */
3587 /*              group(I) - group name                                       */
3588 /*              n(I)     - rule number to find                              */
3589 /*                                                                          */
3590 /* Find rule # n in group # g and return a pointer to it.  Return NULl if   */
3591 /* group # g doesn't exist or there are less than n rules in the group.     */
3592 /* ------------------------------------------------------------------------ */
3593 frentry_t *
3594 ipf_getrulen(ipf_main_softc_t *softc, int unit, char *group, u_32_t n)
3595 {
3596 	frentry_t *fr;
3597 	frgroup_t *fg;
3598 
3599 	fg = ipf_findgroup(softc, group, unit, softc->ipf_active, NULL);
3600 	if (fg == NULL)
3601 		return NULL;
3602 	for (fr = fg->fg_start; fr && n; fr = fr->fr_next, n--)
3603 		;
3604 	if (n != 0)
3605 		return NULL;
3606 	return fr;
3607 }
3608 
3609 
3610 /* ------------------------------------------------------------------------ */
3611 /* Function:    ipf_flushlist                                               */
3612 /* Returns:     int - >= 0 - number of flushed rules                        */
3613 /* Parameters:  softc(I)   - pointer to soft context main structure         */
3614 /*              nfreedp(O) - pointer to int where flush count is stored     */
3615 /*              listp(I)   - pointer to list to flush pointer               */
3616 /* Write Locks: ipf_mutex                                                   */
3617 /*                                                                          */
3618 /* Recursively flush rules from the list, descending groups as they are     */
3619 /* encountered.  if a rule is the head of a group and it has lost all its   */
3620 /* group members, then also delete the group reference.  nfreedp is needed  */
3621 /* to store the accumulating count of rules removed, whereas the returned   */
3622 /* value is just the number removed from the current list.  The latter is   */
3623 /* needed to correctly adjust reference counts on rules that define groups. */
3624 /*                                                                          */
3625 /* NOTE: Rules not loaded from user space cannot be flushed.                */
3626 /* ------------------------------------------------------------------------ */
3627 static int
3628 ipf_flushlist(ipf_main_softc_t *softc, int *nfreedp, frentry_t **listp)
3629 {
3630 	int freed = 0;
3631 	frentry_t *fp;
3632 
3633 	while ((fp = *listp) != NULL) {
3634 		if ((fp->fr_type & FR_T_BUILTIN) ||
3635 		    !(fp->fr_flags & FR_COPIED)) {
3636 			listp = &fp->fr_next;
3637 			continue;
3638 		}
3639 		*listp = fp->fr_next;
3640 		if (fp->fr_next != NULL)
3641 			fp->fr_next->fr_pnext = fp->fr_pnext;
3642 		fp->fr_pnext = NULL;
3643 
3644 		if (fp->fr_grphead != NULL) {
3645 			freed += ipf_group_flush(softc, fp->fr_grphead);
3646 			fp->fr_names[fp->fr_grhead] = '\0';
3647 		}
3648 
3649 		if (fp->fr_icmpgrp != NULL) {
3650 			freed += ipf_group_flush(softc, fp->fr_icmpgrp);
3651 			fp->fr_names[fp->fr_icmphead] = '\0';
3652 		}
3653 
3654 		if (fp->fr_srctrack.ht_max_nodes)
3655 			ipf_rb_ht_flush(&fp->fr_srctrack);
3656 
3657 		fp->fr_next = NULL;
3658 
3659 		ASSERT(fp->fr_ref > 0);
3660 		if (ipf_derefrule(softc, &fp) == 0)
3661 			freed++;
3662 	}
3663 	*nfreedp += freed;
3664 	return freed;
3665 }
3666 
3667 
3668 /* ------------------------------------------------------------------------ */
3669 /* Function:    ipf_flush                                                   */
3670 /* Returns:     int - >= 0 - number of flushed rules                        */
3671 /* Parameters:  softc(I) - pointer to soft context main structure           */
3672 /*              unit(I)  - device for which to flush rules                  */
3673 /*              flags(I) - which set of rules to flush                      */
3674 /*                                                                          */
3675 /* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3676 /* and IPv6) as defined by the value of flags.                              */
3677 /* ------------------------------------------------------------------------ */
3678 int
3679 ipf_flush(ipf_main_softc_t *softc, minor_t unit, int flags)
3680 {
3681 	int flushed = 0, set;
3682 
3683 	WRITE_ENTER(&softc->ipf_mutex);
3684 
3685 	set = softc->ipf_active;
3686 	if ((flags & FR_INACTIVE) == FR_INACTIVE)
3687 		set = 1 - set;
3688 
3689 	if (flags & FR_OUTQUE) {
3690 		ipf_flushlist(softc, &flushed, &softc->ipf_rules[1][set]);
3691 		ipf_flushlist(softc, &flushed, &softc->ipf_acct[1][set]);
3692 	}
3693 	if (flags & FR_INQUE) {
3694 		ipf_flushlist(softc, &flushed, &softc->ipf_rules[0][set]);
3695 		ipf_flushlist(softc, &flushed, &softc->ipf_acct[0][set]);
3696 	}
3697 
3698 	flushed += ipf_flush_groups(softc, &softc->ipf_groups[unit][set],
3699 				    flags & (FR_INQUE|FR_OUTQUE));
3700 
3701 	RWLOCK_EXIT(&softc->ipf_mutex);
3702 
3703 	if (unit == IPL_LOGIPF) {
3704 		int tmp;
3705 
3706 		tmp = ipf_flush(softc, IPL_LOGCOUNT, flags);
3707 		if (tmp >= 0)
3708 			flushed += tmp;
3709 	}
3710 	return flushed;
3711 }
3712 
3713 
3714 /* ------------------------------------------------------------------------ */
3715 /* Function:    ipf_flush_groups                                            */
3716 /* Returns:     int - >= 0 - number of flushed rules                        */
3717 /* Parameters:  softc(I)  - soft context pointerto work with                */
3718 /*              grhead(I) - pointer to the start of the group list to flush */
3719 /*              flags(I)  - which set of rules to flush                     */
3720 /*                                                                          */
3721 /* Walk through all of the groups under the given group head and remove all */
3722 /* of those that match the flags passed in. The for loop here is bit more   */
3723 /* complicated than usual because the removal of a rule with ipf_derefrule  */
3724 /* may end up removing not only the structure pointed to by "fg" but also   */
3725 /* what is fg_next and fg_next after that. So if a filter rule is actually  */
3726 /* removed from the group then it is necessary to start again.              */
3727 /* ------------------------------------------------------------------------ */
3728 static int
3729 ipf_flush_groups( ipf_main_softc_t *softc, frgroup_t **grhead, int flags)
3730 {
3731 	frentry_t *fr, **frp;
3732 	frgroup_t *fg, **fgp;
3733 	int flushed = 0;
3734 	int removed = 0;
3735 
3736 	for (fgp = grhead; (fg = *fgp) != NULL; ) {
3737 		while ((fg != NULL) && ((fg->fg_flags & flags) == 0))
3738 			fg = fg->fg_next;
3739 		if (fg == NULL)
3740 			break;
3741 		removed = 0;
3742 		frp = &fg->fg_start;
3743 		while ((removed == 0) && ((fr = *frp) != NULL)) {
3744 			if ((fr->fr_flags & flags) == 0) {
3745 				frp = &fr->fr_next;
3746 			} else {
3747 				if (fr->fr_next != NULL)
3748 					fr->fr_next->fr_pnext = fr->fr_pnext;
3749 				*frp = fr->fr_next;
3750 				fr->fr_pnext = NULL;
3751 				fr->fr_next = NULL;
3752 				(void) ipf_derefrule(softc, &fr);
3753 				flushed++;
3754 				removed++;
3755 			}
3756 		}
3757 		if (removed == 0)
3758 			fgp = &fg->fg_next;
3759 	}
3760 	return flushed;
3761 }
3762 
3763 
3764 /* ------------------------------------------------------------------------ */
3765 /* Function:    memstr                                                      */
3766 /* Returns:     char *  - NULL if failed, != NULL pointer to matching bytes */
3767 /* Parameters:  src(I)  - pointer to byte sequence to match                 */
3768 /*              dst(I)  - pointer to byte sequence to search                */
3769 /*              slen(I) - match length                                      */
3770 /*              dlen(I) - length available to search in                     */
3771 /*                                                                          */
3772 /* Search dst for a sequence of bytes matching those at src and extend for  */
3773 /* slen bytes.                                                              */
3774 /* ------------------------------------------------------------------------ */
3775 char *
3776 memstr(const char *src, char *dst, size_t slen, size_t dlen)
3777 {
3778 	char *s = NULL;
3779 
3780 	while (dlen >= slen) {
3781 		if (memcmp(src, dst, slen) == 0) {
3782 			s = dst;
3783 			break;
3784 		}
3785 		dst++;
3786 		dlen--;
3787 	}
3788 	return s;
3789 }
3790 
3791 
3792 /* ------------------------------------------------------------------------ */
3793 /* Function:    ipf_fixskip                                                 */
3794 /* Returns:     Nil                                                         */
3795 /* Parameters:  listp(IO)    - pointer to start of list with skip rule      */
3796 /*              rp(I)        - rule added/removed with skip in it.          */
3797 /*              addremove(I) - adjustment (-1/+1) to make to skip count,    */
3798 /*                             depending on whether a rule was just added   */
3799 /*                             or removed.                                  */
3800 /*                                                                          */
3801 /* Adjust all the rules in a list which would have skip'd past the position */
3802 /* where we are inserting to skip to the right place given the change.      */
3803 /* ------------------------------------------------------------------------ */
3804 void
3805 ipf_fixskip(frentry_t **listp, frentry_t *rp, int addremove)
3806 {
3807 	int rules, rn;
3808 	frentry_t *fp;
3809 
3810 	rules = 0;
3811 	for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3812 		rules++;
3813 
3814 	if (!fp)
3815 		return;
3816 
3817 	for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3818 		if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3819 			fp->fr_arg += addremove;
3820 }
3821 
3822 
3823 #ifdef	_KERNEL
3824 /* ------------------------------------------------------------------------ */
3825 /* Function:    count4bits                                                  */
3826 /* Returns:     int - >= 0 - number of consecutive bits in input            */
3827 /* Parameters:  ip(I) - 32bit IP address                                    */
3828 /*                                                                          */
3829 /* IPv4 ONLY                                                                */
3830 /* count consecutive 1's in bit mask.  If the mask generated by counting    */
3831 /* consecutive 1's is different to that passed, return -1, else return #    */
3832 /* of bits.                                                                 */
3833 /* ------------------------------------------------------------------------ */
3834 int
3835 count4bits(u_32_t ip)
3836 {
3837 	u_32_t	ipn;
3838 	int	cnt = 0, i, j;
3839 
3840 	ip = ipn = ntohl(ip);
3841 	for (i = 32; i; i--, ipn *= 2)
3842 		if (ipn & 0x80000000)
3843 			cnt++;
3844 		else
3845 			break;
3846 	ipn = 0;
3847 	for (i = 32, j = cnt; i; i--, j--) {
3848 		ipn *= 2;
3849 		if (j > 0)
3850 			ipn++;
3851 	}
3852 	if (ipn == ip)
3853 		return cnt;
3854 	return -1;
3855 }
3856 
3857 
3858 /* ------------------------------------------------------------------------ */
3859 /* Function:    count6bits                                                  */
3860 /* Returns:     int - >= 0 - number of consecutive bits in input            */
3861 /* Parameters:  msk(I) - pointer to start of IPv6 bitmask                   */
3862 /*                                                                          */
3863 /* IPv6 ONLY                                                                */
3864 /* count consecutive 1's in bit mask.                                       */
3865 /* ------------------------------------------------------------------------ */
3866 # ifdef USE_INET6
3867 int
3868 count6bits(u_32_t *msk)
3869 {
3870 	int i = 0, k;
3871 	u_32_t j;
3872 
3873 	for (k = 3; k >= 0; k--)
3874 		if (msk[k] == 0xffffffff)
3875 			i += 32;
3876 		else {
3877 			for (j = msk[k]; j; j <<= 1)
3878 				if (j & 0x80000000)
3879 					i++;
3880 		}
3881 	return i;
3882 }
3883 # endif
3884 #endif /* _KERNEL */
3885 
3886 
3887 /* ------------------------------------------------------------------------ */
3888 /* Function:    ipf_synclist                                                */
3889 /* Returns:     int    - 0 = no failures, else indication of first failure  */
3890 /* Parameters:  fr(I)  - start of filter list to sync interface names for   */
3891 /*              ifp(I) - interface pointer for limiting sync lookups        */
3892 /* Write Locks: ipf_mutex                                                   */
3893 /*                                                                          */
3894 /* Walk through a list of filter rules and resolve any interface names into */
3895 /* pointers.  Where dynamic addresses are used, also update the IP address  */
3896 /* used in the rule.  The interface pointer is used to limit the lookups to */
3897 /* a specific set of matching names if it is non-NULL.                      */
3898 /* Errors can occur when resolving the destination name of to/dup-to fields */
3899 /* when the name points to a pool and that pool doest not exist. If this    */
3900 /* does happen then it is necessary to check if there are any lookup refs   */
3901 /* that need to be dropped before returning with an error.                  */
3902 /* ------------------------------------------------------------------------ */
3903 static int
3904 ipf_synclist(ipf_main_softc_t *softc, frentry_t *fr, void *ifp)
3905 {
3906 	frentry_t *frt, *start = fr;
3907 	frdest_t *fdp;
3908 	char *name;
3909 	int error;
3910 	void *ifa;
3911 	int v, i;
3912 
3913 	error = 0;
3914 
3915 	for (; fr; fr = fr->fr_next) {
3916 		if (fr->fr_family == AF_INET)
3917 			v = 4;
3918 		else if (fr->fr_family == AF_INET6)
3919 			v = 6;
3920 		else
3921 			v = 0;
3922 
3923 		/*
3924 		 * Lookup all the interface names that are part of the rule.
3925 		 */
3926 		for (i = 0; i < 4; i++) {
3927 			if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
3928 				continue;
3929 			if (fr->fr_ifnames[i] == -1)
3930 				continue;
3931 			name = FR_NAME(fr, fr_ifnames[i]);
3932 			fr->fr_ifas[i] = ipf_resolvenic(softc, name, v);
3933 		}
3934 
3935 		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
3936 			if (fr->fr_satype != FRI_NORMAL &&
3937 			    fr->fr_satype != FRI_LOOKUP) {
3938 				ifa = ipf_resolvenic(softc, fr->fr_names +
3939 						     fr->fr_sifpidx, v);
3940 				ipf_ifpaddr(softc, v, fr->fr_satype, ifa,
3941 					    &fr->fr_src6, &fr->fr_smsk6);
3942 			}
3943 			if (fr->fr_datype != FRI_NORMAL &&
3944 			    fr->fr_datype != FRI_LOOKUP) {
3945 				ifa = ipf_resolvenic(softc, fr->fr_names +
3946 						     fr->fr_sifpidx, v);
3947 				ipf_ifpaddr(softc, v, fr->fr_datype, ifa,
3948 					    &fr->fr_dst6, &fr->fr_dmsk6);
3949 			}
3950 		}
3951 
3952 		fdp = &fr->fr_tifs[0];
3953 		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
3954 			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
3955 			if (error != 0)
3956 				goto unwind;
3957 		}
3958 
3959 		fdp = &fr->fr_tifs[1];
3960 		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
3961 			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
3962 			if (error != 0)
3963 				goto unwind;
3964 		}
3965 
3966 		fdp = &fr->fr_dif;
3967 		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
3968 			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
3969 			if (error != 0)
3970 				goto unwind;
3971 		}
3972 
3973 		if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
3974 		    (fr->fr_satype == FRI_LOOKUP) && (fr->fr_srcptr == NULL)) {
3975 			fr->fr_srcptr = ipf_lookup_res_num(softc,
3976 							   fr->fr_srctype,
3977 							   IPL_LOGIPF,
3978 							   fr->fr_srcnum,
3979 							   &fr->fr_srcfunc);
3980 		}
3981 		if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
3982 		    (fr->fr_datype == FRI_LOOKUP) && (fr->fr_dstptr == NULL)) {
3983 			fr->fr_dstptr = ipf_lookup_res_num(softc,
3984 							   fr->fr_dsttype,
3985 							   IPL_LOGIPF,
3986 							   fr->fr_dstnum,
3987 							   &fr->fr_dstfunc);
3988 		}
3989 	}
3990 	return 0;
3991 
3992 unwind:
3993 	for (frt = start; frt != fr; fr = fr->fr_next) {
3994 		if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
3995 		    (frt->fr_satype == FRI_LOOKUP) && (frt->fr_srcptr != NULL))
3996 				ipf_lookup_deref(softc, frt->fr_srctype,
3997 						 frt->fr_srcptr);
3998 		if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
3999 		    (frt->fr_datype == FRI_LOOKUP) && (frt->fr_dstptr != NULL))
4000 				ipf_lookup_deref(softc, frt->fr_dsttype,
4001 						 frt->fr_dstptr);
4002 	}
4003 	return error;
4004 }
4005 
4006 
4007 /* ------------------------------------------------------------------------ */
4008 /* Function:    ipf_sync                                                    */
4009 /* Returns:     void                                                        */
4010 /* Parameters:  Nil                                                         */
4011 /*                                                                          */
4012 /* ipf_sync() is called when we suspect that the interface list or          */
4013 /* information about interfaces (like IP#) has changed.  Go through all     */
4014 /* filter rules, NAT entries and the state table and check if anything      */
4015 /* needs to be changed/updated.                                             */
4016 /* ------------------------------------------------------------------------ */
4017 int
4018 ipf_sync(ipf_main_softc_t *softc, void *ifp)
4019 {
4020 	int i;
4021 
4022 # if !SOLARIS
4023 	ipf_nat_sync(softc, ifp);
4024 	ipf_state_sync(softc, ifp);
4025 	ipf_lookup_sync(softc, ifp);
4026 # endif
4027 
4028 	WRITE_ENTER(&softc->ipf_mutex);
4029 	(void) ipf_synclist(softc, softc->ipf_acct[0][softc->ipf_active], ifp);
4030 	(void) ipf_synclist(softc, softc->ipf_acct[1][softc->ipf_active], ifp);
4031 	(void) ipf_synclist(softc, softc->ipf_rules[0][softc->ipf_active], ifp);
4032 	(void) ipf_synclist(softc, softc->ipf_rules[1][softc->ipf_active], ifp);
4033 
4034 	for (i = 0; i < IPL_LOGSIZE; i++) {
4035 		frgroup_t *g;
4036 
4037 		for (g = softc->ipf_groups[i][0]; g != NULL; g = g->fg_next)
4038 			(void) ipf_synclist(softc, g->fg_start, ifp);
4039 		for (g = softc->ipf_groups[i][1]; g != NULL; g = g->fg_next)
4040 			(void) ipf_synclist(softc, g->fg_start, ifp);
4041 	}
4042 	RWLOCK_EXIT(&softc->ipf_mutex);
4043 
4044 	return 0;
4045 }
4046 
4047 
4048 /*
4049  * In the functions below, bcopy() is called because the pointer being
4050  * copied _from_ in this instance is a pointer to a char buf (which could
4051  * end up being unaligned) and on the kernel's local stack.
4052  */
4053 /* ------------------------------------------------------------------------ */
4054 /* Function:    copyinptr                                                   */
4055 /* Returns:     int - 0 = success, else failure                             */
4056 /* Parameters:  src(I)  - pointer to the source address                     */
4057 /*              dst(I)  - destination address                               */
4058 /*              size(I) - number of bytes to copy                           */
4059 /*                                                                          */
4060 /* Copy a block of data in from user space, given a pointer to the pointer  */
4061 /* to start copying from (src) and a pointer to where to store it (dst).    */
4062 /* NB: src - pointer to user space pointer, dst - kernel space pointer      */
4063 /* ------------------------------------------------------------------------ */
4064 int
4065 copyinptr(ipf_main_softc_t *softc, void *src, void *dst, size_t size)
4066 {
4067 	void *ca;
4068 	int error;
4069 
4070 # if SOLARIS
4071 	error = COPYIN(src, &ca, sizeof(ca));
4072 	if (error != 0)
4073 		return error;
4074 # else
4075 	bcopy(src, (void *)&ca, sizeof(ca));
4076 # endif
4077 	error = COPYIN(ca, dst, size);
4078 	if (error != 0) {
4079 		IPFERROR(3);
4080 		error = EFAULT;
4081 	}
4082 	return error;
4083 }
4084 
4085 
4086 /* ------------------------------------------------------------------------ */
4087 /* Function:    copyoutptr                                                  */
4088 /* Returns:     int - 0 = success, else failure                             */
4089 /* Parameters:  src(I)  - pointer to the source address                     */
4090 /*              dst(I)  - destination address                               */
4091 /*              size(I) - number of bytes to copy                           */
4092 /*                                                                          */
4093 /* Copy a block of data out to user space, given a pointer to the pointer   */
4094 /* to start copying from (src) and a pointer to where to store it (dst).    */
4095 /* NB: src - kernel space pointer, dst - pointer to user space pointer.     */
4096 /* ------------------------------------------------------------------------ */
4097 int
4098 copyoutptr(ipf_main_softc_t *softc, void *src, void *dst, size_t size)
4099 {
4100 	void *ca;
4101 	int error;
4102 
4103 	bcopy(dst, &ca, sizeof(ca));
4104 	error = COPYOUT(src, ca, size);
4105 	if (error != 0) {
4106 		IPFERROR(4);
4107 		error = EFAULT;
4108 	}
4109 	return error;
4110 }
4111 #ifdef	_KERNEL
4112 #endif
4113 
4114 
4115 /* ------------------------------------------------------------------------ */
4116 /* Function:    ipf_lock                                                    */
4117 /* Returns:     int      - 0 = success, else error                          */
4118 /* Parameters:  data(I)  - pointer to lock value to set                     */
4119 /*              lockp(O) - pointer to location to store old lock value      */
4120 /*                                                                          */
4121 /* Get the new value for the lock integer, set it and return the old value  */
4122 /* in *lockp.                                                               */
4123 /* ------------------------------------------------------------------------ */
4124 int
4125 ipf_lock(void *data, int *lockp)
4126 {
4127 	int arg, err;
4128 
4129 	err = BCOPYIN(data, &arg, sizeof(arg));
4130 	if (err != 0)
4131 		return EFAULT;
4132 	err = BCOPYOUT(lockp, data, sizeof(*lockp));
4133 	if (err != 0)
4134 		return EFAULT;
4135 	*lockp = arg;
4136 	return 0;
4137 }
4138 
4139 
4140 /* ------------------------------------------------------------------------ */
4141 /* Function:    ipf_getstat                                                 */
4142 /* Returns:     Nil                                                         */
4143 /* Parameters:  softc(I) - pointer to soft context main structure           */
4144 /*              fiop(I)  - pointer to ipfilter stats structure              */
4145 /*              rev(I)   - version claim by program doing ioctl             */
4146 /*                                                                          */
4147 /* Stores a copy of current pointers, counters, etc, in the friostat        */
4148 /* structure.                                                               */
4149 /* If IPFILTER_COMPAT is compiled, we pretend to be whatever version the    */
4150 /* program is looking for. This ensure that validation of the version it    */
4151 /* expects will always succeed. Thus kernels with IPFILTER_COMPAT will      */
4152 /* allow older binaries to work but kernels without it will not.            */
4153 /* ------------------------------------------------------------------------ */
4154 /*ARGSUSED*/
4155 static void
4156 ipf_getstat(ipf_main_softc_t *softc, friostat_t *fiop, int rev)
4157 {
4158 	int i;
4159 
4160 	bcopy((char *)softc->ipf_stats, (char *)fiop->f_st,
4161 	      sizeof(ipf_statistics_t) * 2);
4162 	fiop->f_locks[IPL_LOGSTATE] = -1;
4163 	fiop->f_locks[IPL_LOGNAT] = -1;
4164 	fiop->f_locks[IPL_LOGIPF] = -1;
4165 	fiop->f_locks[IPL_LOGAUTH] = -1;
4166 
4167 	fiop->f_ipf[0][0] = softc->ipf_rules[0][0];
4168 	fiop->f_acct[0][0] = softc->ipf_acct[0][0];
4169 	fiop->f_ipf[0][1] = softc->ipf_rules[0][1];
4170 	fiop->f_acct[0][1] = softc->ipf_acct[0][1];
4171 	fiop->f_ipf[1][0] = softc->ipf_rules[1][0];
4172 	fiop->f_acct[1][0] = softc->ipf_acct[1][0];
4173 	fiop->f_ipf[1][1] = softc->ipf_rules[1][1];
4174 	fiop->f_acct[1][1] = softc->ipf_acct[1][1];
4175 
4176 	fiop->f_ticks = softc->ipf_ticks;
4177 	fiop->f_active = softc->ipf_active;
4178 	fiop->f_froute[0] = softc->ipf_frouteok[0];
4179 	fiop->f_froute[1] = softc->ipf_frouteok[1];
4180 	fiop->f_rb_no_mem = softc->ipf_rb_no_mem;
4181 	fiop->f_rb_node_max = softc->ipf_rb_node_max;
4182 
4183 	fiop->f_running = softc->ipf_running;
4184 	for (i = 0; i < IPL_LOGSIZE; i++) {
4185 		fiop->f_groups[i][0] = softc->ipf_groups[i][0];
4186 		fiop->f_groups[i][1] = softc->ipf_groups[i][1];
4187 	}
4188 #ifdef  IPFILTER_LOG
4189 	fiop->f_log_ok = ipf_log_logok(softc, IPL_LOGIPF);
4190 	fiop->f_log_fail = ipf_log_failures(softc, IPL_LOGIPF);
4191 	fiop->f_logging = 1;
4192 #else
4193 	fiop->f_log_ok = 0;
4194 	fiop->f_log_fail = 0;
4195 	fiop->f_logging = 0;
4196 #endif
4197 	fiop->f_defpass = softc->ipf_pass;
4198 	fiop->f_features = ipf_features;
4199 
4200 #ifdef IPFILTER_COMPAT
4201 	snprintf(fiop->f_version, sizeof(fiop->f_version),
4202 		 "IP Filter: v%d.%d.%d", (rev / 1000000) % 100,
4203 		 (rev / 10000) % 100, (rev / 100) % 100);
4204 #else
4205 	rev = rev;
4206 	(void) strncpy(fiop->f_version, ipfilter_version,
4207 		       sizeof(fiop->f_version));
4208         fiop->f_version[sizeof(fiop->f_version) - 1] = '\0';
4209 #endif
4210 }
4211 
4212 
4213 #ifdef	USE_INET6
4214 int icmptoicmp6types[ICMP_MAXTYPE+1] = {
4215 	ICMP6_ECHO_REPLY,	/* 0: ICMP_ECHOREPLY */
4216 	-1,			/* 1: UNUSED */
4217 	-1,			/* 2: UNUSED */
4218 	ICMP6_DST_UNREACH,	/* 3: ICMP_UNREACH */
4219 	-1,			/* 4: ICMP_SOURCEQUENCH */
4220 	ND_REDIRECT,		/* 5: ICMP_REDIRECT */
4221 	-1,			/* 6: UNUSED */
4222 	-1,			/* 7: UNUSED */
4223 	ICMP6_ECHO_REQUEST,	/* 8: ICMP_ECHO */
4224 	-1,			/* 9: UNUSED */
4225 	-1,			/* 10: UNUSED */
4226 	ICMP6_TIME_EXCEEDED,	/* 11: ICMP_TIMXCEED */
4227 	ICMP6_PARAM_PROB,	/* 12: ICMP_PARAMPROB */
4228 	-1,			/* 13: ICMP_TSTAMP */
4229 	-1,			/* 14: ICMP_TSTAMPREPLY */
4230 	-1,			/* 15: ICMP_IREQ */
4231 	-1,			/* 16: ICMP_IREQREPLY */
4232 	-1,			/* 17: ICMP_MASKREQ */
4233 	-1,			/* 18: ICMP_MASKREPLY */
4234 };
4235 
4236 
4237 int	icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
4238 	ICMP6_DST_UNREACH_ADDR,		/* 0: ICMP_UNREACH_NET */
4239 	ICMP6_DST_UNREACH_ADDR,		/* 1: ICMP_UNREACH_HOST */
4240 	-1,				/* 2: ICMP_UNREACH_PROTOCOL */
4241 	ICMP6_DST_UNREACH_NOPORT,	/* 3: ICMP_UNREACH_PORT */
4242 	-1,				/* 4: ICMP_UNREACH_NEEDFRAG */
4243 	ICMP6_DST_UNREACH_NOTNEIGHBOR,	/* 5: ICMP_UNREACH_SRCFAIL */
4244 	ICMP6_DST_UNREACH_ADDR,		/* 6: ICMP_UNREACH_NET_UNKNOWN */
4245 	ICMP6_DST_UNREACH_ADDR,		/* 7: ICMP_UNREACH_HOST_UNKNOWN */
4246 	-1,				/* 8: ICMP_UNREACH_ISOLATED */
4247 	ICMP6_DST_UNREACH_ADMIN,	/* 9: ICMP_UNREACH_NET_PROHIB */
4248 	ICMP6_DST_UNREACH_ADMIN,	/* 10: ICMP_UNREACH_HOST_PROHIB */
4249 	-1,				/* 11: ICMP_UNREACH_TOSNET */
4250 	-1,				/* 12: ICMP_UNREACH_TOSHOST */
4251 	ICMP6_DST_UNREACH_ADMIN,	/* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
4252 };
4253 int	icmpreplytype6[ICMP6_MAXTYPE + 1];
4254 #endif
4255 
4256 int	icmpreplytype4[ICMP_MAXTYPE + 1];
4257 
4258 
4259 /* ------------------------------------------------------------------------ */
4260 /* Function:    ipf_matchicmpqueryreply                                     */
4261 /* Returns:     int - 1 if "icmp" is a valid reply to "ic" else 0.          */
4262 /* Parameters:  v(I)    - IP protocol version (4 or 6)                      */
4263 /*              ic(I)   - ICMP information                                  */
4264 /*              icmp(I) - ICMP packet header                                */
4265 /*              rev(I)  - direction (0 = forward/1 = reverse) of packet     */
4266 /*                                                                          */
4267 /* Check if the ICMP packet defined by the header pointed to by icmp is a   */
4268 /* reply to one as described by what's in ic.  If it is a match, return 1,  */
4269 /* else return 0 for no match.                                              */
4270 /* ------------------------------------------------------------------------ */
4271 int
4272 ipf_matchicmpqueryreply(int v, icmpinfo_t *ic, icmphdr_t *icmp, int rev)
4273 {
4274 	int ictype;
4275 
4276 	ictype = ic->ici_type;
4277 
4278 	if (v == 4) {
4279 		/*
4280 		 * If we matched its type on the way in, then when going out
4281 		 * it will still be the same type.
4282 		 */
4283 		if ((!rev && (icmp->icmp_type == ictype)) ||
4284 		    (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4285 			if (icmp->icmp_type != ICMP_ECHOREPLY)
4286 				return 1;
4287 			if (icmp->icmp_id == ic->ici_id)
4288 				return 1;
4289 		}
4290 	}
4291 #ifdef	USE_INET6
4292 	else if (v == 6) {
4293 		if ((!rev && (icmp->icmp_type == ictype)) ||
4294 		    (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4295 			if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4296 				return 1;
4297 			if (icmp->icmp_id == ic->ici_id)
4298 				return 1;
4299 		}
4300 	}
4301 #endif
4302 	return 0;
4303 }
4304 
4305 
4306 /* ------------------------------------------------------------------------ */
4307 /* Function:    frrequest                                                   */
4308 /* Returns:     int - 0 == success, > 0 == errno value                      */
4309 /* Parameters:  unit(I)     - device for which this is for                  */
4310 /*              req(I)      - ioctl command (SIOC*)                         */
4311 /*              data(I)     - pointr to ioctl data                          */
4312 /*              set(I)      - 1 or 0 (filter set)                           */
4313 /*              makecopy(I) - flag indicating whether data points to a rule */
4314 /*                            in kernel space & hence doesn't need copying. */
4315 /*                                                                          */
4316 /* This function handles all the requests which operate on the list of      */
4317 /* filter rules.  This includes adding, deleting, insertion.  It is also    */
4318 /* responsible for creating groups when a "head" rule is loaded.  Interface */
4319 /* names are resolved here and other sanity checks are made on the content  */
4320 /* of the rule structure being loaded.  If a rule has user defined timeouts */
4321 /* then make sure they are created and initialised before exiting.          */
4322 /* ------------------------------------------------------------------------ */
4323 int
4324 frrequest(ipf_main_softc_t *softc, int unit, ioctlcmd_t req, void *data,
4325     int set, int makecopy)
4326 {
4327 	int error = 0, in, family, addrem, need_free = 0;
4328 	frentry_t frd, *fp, *f, **fprev, **ftail;
4329 	void *ptr, *uptr;
4330 	u_int *p, *pp;
4331 	frgroup_t *fg;
4332 	char *group;
4333 
4334 	ptr = NULL;
4335 	fg = NULL;
4336 	fp = &frd;
4337 	if (makecopy != 0) {
4338 		bzero(fp, sizeof(frd));
4339 		error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
4340 		if (error) {
4341 			return error;
4342 		}
4343 		if ((fp->fr_type & FR_T_BUILTIN) != 0) {
4344 			IPFERROR(6);
4345 			return EINVAL;
4346 		}
4347 		KMALLOCS(f, frentry_t *, fp->fr_size);
4348 		if (f == NULL) {
4349 			IPFERROR(131);
4350 			return ENOMEM;
4351 		}
4352 		bzero(f, fp->fr_size);
4353 		error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
4354 				    fp->fr_size);
4355 		if (error) {
4356 			KFREES(f, fp->fr_size);
4357 			return error;
4358 		}
4359 
4360 		fp = f;
4361 		f = NULL;
4362 		fp->fr_next = NULL;
4363 		fp->fr_dnext = NULL;
4364 		fp->fr_pnext = NULL;
4365 		fp->fr_pdnext = NULL;
4366 		fp->fr_grp = NULL;
4367 		fp->fr_grphead = NULL;
4368 		fp->fr_icmpgrp = NULL;
4369 		fp->fr_isc = (void *)-1;
4370 		fp->fr_ptr = NULL;
4371 		fp->fr_ref = 0;
4372 		fp->fr_flags |= FR_COPIED;
4373 	} else {
4374 		fp = (frentry_t *)data;
4375 		if ((fp->fr_type & FR_T_BUILTIN) == 0) {
4376 			IPFERROR(7);
4377 			return EINVAL;
4378 		}
4379 		fp->fr_flags &= ~FR_COPIED;
4380 	}
4381 
4382 	if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4383 	    ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
4384 		IPFERROR(8);
4385 		error = EINVAL;
4386 		goto donenolock;
4387 	}
4388 
4389 	family = fp->fr_family;
4390 	uptr = fp->fr_data;
4391 
4392 	if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
4393 	    req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
4394 		addrem = 0;
4395 	else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
4396 		addrem = 1;
4397 	else if (req == (ioctlcmd_t)SIOCZRLST)
4398 		addrem = 2;
4399 	else {
4400 		IPFERROR(9);
4401 		error = EINVAL;
4402 		goto donenolock;
4403 	}
4404 
4405 	/*
4406 	 * Only filter rules for IPv4 or IPv6 are accepted.
4407 	 */
4408 	if (family == AF_INET) {
4409 		/*EMPTY*/;
4410 #ifdef	USE_INET6
4411 	} else if (family == AF_INET6) {
4412 		/*EMPTY*/;
4413 #endif
4414 	} else if (family != 0) {
4415 		IPFERROR(10);
4416 		error = EINVAL;
4417 		goto donenolock;
4418 	}
4419 
4420 	/*
4421 	 * If the rule is being loaded from user space, i.e. we had to copy it
4422 	 * into kernel space, then do not trust the function pointer in the
4423 	 * rule.
4424 	 */
4425 	if ((makecopy == 1) && (fp->fr_func != NULL)) {
4426 		if (ipf_findfunc(fp->fr_func) == NULL) {
4427 			IPFERROR(11);
4428 			error = ESRCH;
4429 			goto donenolock;
4430 		}
4431 
4432 		if (addrem == 0) {
4433 			error = ipf_funcinit(softc, fp);
4434 			if (error != 0)
4435 				goto donenolock;
4436 		}
4437 	}
4438 	if ((fp->fr_flags & FR_CALLNOW) &&
4439 	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4440 		IPFERROR(142);
4441 		error = ESRCH;
4442 		goto donenolock;
4443 	}
4444 	if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
4445 	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4446 		IPFERROR(143);
4447 		error = ESRCH;
4448 		goto donenolock;
4449 	}
4450 
4451 	ptr = NULL;
4452 
4453 	if (FR_ISACCOUNT(fp->fr_flags))
4454 		unit = IPL_LOGCOUNT;
4455 
4456 	/*
4457 	 * Check that each group name in the rule has a start index that
4458 	 * is valid.
4459 	 */
4460 	if (fp->fr_icmphead != -1) {
4461 		if ((fp->fr_icmphead < 0) ||
4462 		    (fp->fr_icmphead >= fp->fr_namelen)) {
4463 			IPFERROR(136);
4464 			error = EINVAL;
4465 			goto donenolock;
4466 		}
4467 		if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
4468 			fp->fr_names[fp->fr_icmphead] = '\0';
4469 	}
4470 
4471 	if (fp->fr_grhead != -1) {
4472 		if ((fp->fr_grhead < 0) ||
4473 		    (fp->fr_grhead >= fp->fr_namelen)) {
4474 			IPFERROR(137);
4475 			error = EINVAL;
4476 			goto donenolock;
4477 		}
4478 		if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
4479 			fp->fr_names[fp->fr_grhead] = '\0';
4480 	}
4481 
4482 	if (fp->fr_group != -1) {
4483 		if ((fp->fr_group < 0) ||
4484 		    (fp->fr_group >= fp->fr_namelen)) {
4485 			IPFERROR(138);
4486 			error = EINVAL;
4487 			goto donenolock;
4488 		}
4489 		if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
4490 			/*
4491 			 * Allow loading rules that are in groups to cause
4492 			 * them to be created if they don't already exit.
4493 			 */
4494 			group = FR_NAME(fp, fr_group);
4495 			if (addrem == 0) {
4496 				fg = ipf_group_add(softc, group, NULL,
4497 						   fp->fr_flags, unit, set);
4498 				fp->fr_grp = fg;
4499 			} else {
4500 				fg = ipf_findgroup(softc, group, unit,
4501 						   set, NULL);
4502 				if (fg == NULL) {
4503 					IPFERROR(12);
4504 					error = ESRCH;
4505 					goto donenolock;
4506 				}
4507 			}
4508 
4509 			if (fg->fg_flags == 0) {
4510 				fg->fg_flags = fp->fr_flags & FR_INOUT;
4511 			} else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
4512 				IPFERROR(13);
4513 				error = ESRCH;
4514 				goto donenolock;
4515 			}
4516 		}
4517 	} else {
4518 		/*
4519 		 * If a rule is going to be part of a group then it does
4520 		 * not matter whether it is an in or out rule, but if it
4521 		 * isn't in a group, then it does...
4522 		 */
4523 		if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
4524 			IPFERROR(14);
4525 			error = EINVAL;
4526 			goto donenolock;
4527 		}
4528 	}
4529 	in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4530 
4531 	/*
4532 	 * Work out which rule list this change is being applied to.
4533 	 */
4534 	ftail = NULL;
4535 	fprev = NULL;
4536 	if (unit == IPL_LOGAUTH) {
4537 		if ((fp->fr_tifs[0].fd_ptr != NULL) ||
4538 		    (fp->fr_tifs[1].fd_ptr != NULL) ||
4539 		    (fp->fr_dif.fd_ptr != NULL) ||
4540 		    (fp->fr_flags & FR_FASTROUTE)) {
4541 			IPFERROR(145);
4542 			error = EINVAL;
4543 			goto donenolock;
4544 		}
4545 		fprev = ipf_auth_rulehead(softc);
4546 	} else {
4547 		if (FR_ISACCOUNT(fp->fr_flags))
4548 			fprev = &softc->ipf_acct[in][set];
4549 		else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4550 			fprev = &softc->ipf_rules[in][set];
4551 	}
4552 	if (fprev == NULL) {
4553 		IPFERROR(15);
4554 		error = ESRCH;
4555 		goto donenolock;
4556 	}
4557 
4558 	if (fg != NULL)
4559 		fprev = &fg->fg_start;
4560 
4561 	/*
4562 	 * Copy in extra data for the rule.
4563 	 */
4564 	if (fp->fr_dsize != 0) {
4565 		if (makecopy != 0) {
4566 			KMALLOCS(ptr, void *, fp->fr_dsize);
4567 			if (ptr == NULL) {
4568 				IPFERROR(16);
4569 				error = ENOMEM;
4570 				goto donenolock;
4571 			}
4572 
4573 			/*
4574 			 * The bcopy case is for when the data is appended
4575 			 * to the rule by ipf_in_compat().
4576 			 */
4577 			if (uptr >= (void *)fp &&
4578 			    uptr < (void *)((char *)fp + fp->fr_size)) {
4579 				bcopy(uptr, ptr, fp->fr_dsize);
4580 				error = 0;
4581 			} else {
4582 				error = COPYIN(uptr, ptr, fp->fr_dsize);
4583 				if (error != 0) {
4584 					IPFERROR(17);
4585 					error = EFAULT;
4586 					goto donenolock;
4587 				}
4588 			}
4589 		} else {
4590 			ptr = uptr;
4591 		}
4592 		fp->fr_data = ptr;
4593 	} else {
4594 		fp->fr_data = NULL;
4595 	}
4596 
4597 	/*
4598 	 * Perform per-rule type sanity checks of their members.
4599 	 * All code after this needs to be aware that allocated memory
4600 	 * may need to be free'd before exiting.
4601 	 */
4602 	switch (fp->fr_type & ~FR_T_BUILTIN)
4603 	{
4604 #if defined(IPFILTER_BPF)
4605 	case FR_T_BPFOPC :
4606 		if (fp->fr_dsize == 0) {
4607 			IPFERROR(19);
4608 			error = EINVAL;
4609 			break;
4610 		}
4611 		if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4612 			IPFERROR(20);
4613 			error = EINVAL;
4614 			break;
4615 		}
4616 		break;
4617 #endif
4618 	case FR_T_IPF :
4619 		/*
4620 		 * Preparation for error case at the bottom of this function.
4621 		 */
4622 		if (fp->fr_datype == FRI_LOOKUP)
4623 			fp->fr_dstptr = NULL;
4624 		if (fp->fr_satype == FRI_LOOKUP)
4625 			fp->fr_srcptr = NULL;
4626 
4627 		if (fp->fr_dsize != sizeof(fripf_t)) {
4628 			IPFERROR(21);
4629 			error = EINVAL;
4630 			break;
4631 		}
4632 
4633 		/*
4634 		 * Allowing a rule with both "keep state" and "with oow" is
4635 		 * pointless because adding a state entry to the table will
4636 		 * fail with the out of window (oow) flag set.
4637 		 */
4638 		if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
4639 			IPFERROR(22);
4640 			error = EINVAL;
4641 			break;
4642 		}
4643 
4644 		switch (fp->fr_satype)
4645 		{
4646 		case FRI_BROADCAST :
4647 		case FRI_DYNAMIC :
4648 		case FRI_NETWORK :
4649 		case FRI_NETMASKED :
4650 		case FRI_PEERADDR :
4651 			if (fp->fr_sifpidx < 0) {
4652 				IPFERROR(23);
4653 				error = EINVAL;
4654 			}
4655 			break;
4656 		case FRI_LOOKUP :
4657 			fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
4658 						       &fp->fr_src6,
4659 						       &fp->fr_smsk6);
4660 			if (fp->fr_srcfunc == NULL) {
4661 				IPFERROR(132);
4662 				error = ESRCH;
4663 				break;
4664 			}
4665 			break;
4666 		case FRI_NORMAL :
4667 			break;
4668 		default :
4669 			IPFERROR(133);
4670 			error = EINVAL;
4671 			break;
4672 		}
4673 		if (error != 0)
4674 			break;
4675 
4676 		switch (fp->fr_datype)
4677 		{
4678 		case FRI_BROADCAST :
4679 		case FRI_DYNAMIC :
4680 		case FRI_NETWORK :
4681 		case FRI_NETMASKED :
4682 		case FRI_PEERADDR :
4683 			if (fp->fr_difpidx < 0) {
4684 				IPFERROR(24);
4685 				error = EINVAL;
4686 			}
4687 			break;
4688 		case FRI_LOOKUP :
4689 			fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
4690 						       &fp->fr_dst6,
4691 						       &fp->fr_dmsk6);
4692 			if (fp->fr_dstfunc == NULL) {
4693 				IPFERROR(134);
4694 				error = ESRCH;
4695 			}
4696 			break;
4697 		case FRI_NORMAL :
4698 			break;
4699 		default :
4700 			IPFERROR(135);
4701 			error = EINVAL;
4702 		}
4703 		break;
4704 
4705 	case FR_T_NONE :
4706 	case FR_T_CALLFUNC :
4707 	case FR_T_COMPIPF :
4708 		break;
4709 
4710 	case FR_T_IPFEXPR :
4711 		if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
4712 			IPFERROR(25);
4713 			error = EINVAL;
4714 		}
4715 		break;
4716 
4717 	default :
4718 		IPFERROR(26);
4719 		error = EINVAL;
4720 		break;
4721 	}
4722 	if (error != 0)
4723 		goto donenolock;
4724 
4725 	if (fp->fr_tif.fd_name != -1) {
4726 		if ((fp->fr_tif.fd_name < 0) ||
4727 		    (fp->fr_tif.fd_name >= fp->fr_namelen)) {
4728 			IPFERROR(139);
4729 			error = EINVAL;
4730 			goto donenolock;
4731 		}
4732 	}
4733 
4734 	if (fp->fr_dif.fd_name != -1) {
4735 		if ((fp->fr_dif.fd_name < 0) ||
4736 		    (fp->fr_dif.fd_name >= fp->fr_namelen)) {
4737 			IPFERROR(140);
4738 			error = EINVAL;
4739 			goto donenolock;
4740 		}
4741 	}
4742 
4743 	if (fp->fr_rif.fd_name != -1) {
4744 		if ((fp->fr_rif.fd_name < 0) ||
4745 		    (fp->fr_rif.fd_name >= fp->fr_namelen)) {
4746 			IPFERROR(141);
4747 			error = EINVAL;
4748 			goto donenolock;
4749 		}
4750 	}
4751 
4752 	/*
4753 	 * Lookup all the interface names that are part of the rule.
4754 	 */
4755 	error = ipf_synclist(softc, fp, NULL);
4756 	if (error != 0)
4757 		goto donenolock;
4758 	fp->fr_statecnt = 0;
4759 	if (fp->fr_srctrack.ht_max_nodes != 0)
4760 		ipf_rb_ht_init(&fp->fr_srctrack);
4761 
4762 	/*
4763 	 * Look for an existing matching filter rule, but don't include the
4764 	 * next or interface pointer in the comparison (fr_next, fr_ifa).
4765 	 * This elminates rules which are indentical being loaded.  Checksum
4766 	 * the constant part of the filter rule to make comparisons quicker
4767 	 * (this meaning no pointers are included).
4768 	 */
4769 	for (fp->fr_cksum = 0, p = (u_int *)&fp->fr_func, pp = &fp->fr_cksum;
4770 	     p < pp; p++)
4771 		fp->fr_cksum += *p;
4772 	pp = (u_int *)((char *)fp->fr_caddr + fp->fr_dsize);
4773 	for (p = (u_int *)fp->fr_data; p < pp; p++)
4774 		fp->fr_cksum += *p;
4775 
4776 	WRITE_ENTER(&softc->ipf_mutex);
4777 
4778 	/*
4779 	 * Now that the filter rule lists are locked, we can walk the
4780 	 * chain of them without fear.
4781 	 */
4782 	ftail = fprev;
4783 	for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4784 		if (fp->fr_collect <= f->fr_collect) {
4785 			ftail = fprev;
4786 			f = NULL;
4787 			break;
4788 		}
4789 		fprev = ftail;
4790 	}
4791 
4792 	for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4793 		DT2(rule_cmp, frentry_t *, fp, frentry_t *, f);
4794 		if ((fp->fr_cksum != f->fr_cksum) ||
4795 		    (fp->fr_size != f->fr_size) ||
4796 		    (f->fr_dsize != fp->fr_dsize))
4797 			continue;
4798 		if (bcmp((char *)&f->fr_func, (char *)&fp->fr_func,
4799 			 fp->fr_size - offsetof(struct frentry, fr_func)) != 0)
4800 			continue;
4801 		if ((!ptr && !f->fr_data) ||
4802 		    (ptr && f->fr_data &&
4803 		     !bcmp((char *)ptr, (char *)f->fr_data, f->fr_dsize)))
4804 			break;
4805 	}
4806 
4807 	/*
4808 	 * If zero'ing statistics, copy current to caller and zero.
4809 	 */
4810 	if (addrem == 2) {
4811 		if (f == NULL) {
4812 			IPFERROR(27);
4813 			error = ESRCH;
4814 		} else {
4815 			/*
4816 			 * Copy and reduce lock because of impending copyout.
4817 			 * Well we should, but if we do then the atomicity of
4818 			 * this call and the correctness of fr_hits and
4819 			 * fr_bytes cannot be guaranteed.  As it is, this code
4820 			 * only resets them to 0 if they are successfully
4821 			 * copied out into user space.
4822 			 */
4823 			bcopy((char *)f, (char *)fp, f->fr_size);
4824 			/* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
4825 
4826 			/*
4827 			 * When we copy this rule back out, set the data
4828 			 * pointer to be what it was in user space.
4829 			 */
4830 			fp->fr_data = uptr;
4831 			error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
4832 
4833 			if (error == 0) {
4834 				if ((f->fr_dsize != 0) && (uptr != NULL))
4835 					error = COPYOUT(f->fr_data, uptr,
4836 							f->fr_dsize);
4837 					if (error != 0) {
4838 						IPFERROR(28);
4839 						error = EFAULT;
4840 					}
4841 				if (error == 0) {
4842 					f->fr_hits = 0;
4843 					f->fr_bytes = 0;
4844 				}
4845 			}
4846 		}
4847 
4848 		if (makecopy != 0) {
4849 			if (ptr != NULL) {
4850 				KFREES(ptr, fp->fr_dsize);
4851 			}
4852 			KFREES(fp, fp->fr_size);
4853 		}
4854 		RWLOCK_EXIT(&softc->ipf_mutex);
4855 		return error;
4856 	}
4857 
4858   	if (!f) {
4859 		/*
4860 		 * At the end of this, ftail must point to the place where the
4861 		 * new rule is to be saved/inserted/added.
4862 		 * For SIOCAD*FR, this should be the last rule in the group of
4863 		 * rules that have equal fr_collect fields.
4864 		 * For SIOCIN*FR, ...
4865 		 */
4866 		if (req == (ioctlcmd_t)SIOCADAFR ||
4867 		    req == (ioctlcmd_t)SIOCADIFR) {
4868 
4869 			for (ftail = fprev; (f = *ftail) != NULL; ) {
4870 				if (f->fr_collect > fp->fr_collect)
4871 					break;
4872 				ftail = &f->fr_next;
4873 				fprev = ftail;
4874 			}
4875 			ftail = fprev;
4876 			f = NULL;
4877 			ptr = NULL;
4878 		} else if (req == (ioctlcmd_t)SIOCINAFR ||
4879 			   req == (ioctlcmd_t)SIOCINIFR) {
4880 			while ((f = *fprev) != NULL) {
4881 				if (f->fr_collect >= fp->fr_collect)
4882 					break;
4883 				fprev = &f->fr_next;
4884 			}
4885   			ftail = fprev;
4886   			if (fp->fr_hits != 0) {
4887 				while (fp->fr_hits && (f = *ftail)) {
4888 					if (f->fr_collect != fp->fr_collect)
4889 						break;
4890 					fprev = ftail;
4891   					ftail = &f->fr_next;
4892 					fp->fr_hits--;
4893 				}
4894   			}
4895   			f = NULL;
4896   			ptr = NULL;
4897 		}
4898 	}
4899 
4900 	/*
4901 	 * Request to remove a rule.
4902 	 */
4903 	if (addrem == 1) {
4904 		if (!f) {
4905 			IPFERROR(29);
4906 			error = ESRCH;
4907 		} else {
4908 			/*
4909 			 * Do not allow activity from user space to interfere
4910 			 * with rules not loaded that way.
4911 			 */
4912 			if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
4913 				IPFERROR(30);
4914 				error = EPERM;
4915 				goto done;
4916 			}
4917 
4918 			/*
4919 			 * Return EBUSY if the rule is being reference by
4920 			 * something else (eg state information.)
4921 			 */
4922 			if (f->fr_ref > 1) {
4923 				IPFERROR(31);
4924 				error = EBUSY;
4925 				goto done;
4926 			}
4927 #ifdef	IPFILTER_SCAN
4928 			if (f->fr_isctag != -1 &&
4929 			    (f->fr_isc != (struct ipscan *)-1))
4930 				ipf_scan_detachfr(f);
4931 #endif
4932 
4933 			if (unit == IPL_LOGAUTH) {
4934 				error = ipf_auth_precmd(softc, req, f, ftail);
4935 				goto done;
4936 			}
4937 
4938 			ipf_rule_delete(softc, f, unit, set);
4939 
4940 			need_free = makecopy;
4941 		}
4942 	} else {
4943 		/*
4944 		 * Not removing, so we must be adding/inserting a rule.
4945 		 */
4946 		if (f != NULL) {
4947 			IPFERROR(32);
4948 			error = EEXIST;
4949 			goto done;
4950 		}
4951 		if (unit == IPL_LOGAUTH) {
4952 			error = ipf_auth_precmd(softc, req, fp, ftail);
4953 			goto done;
4954 		}
4955 
4956 		MUTEX_NUKE(&fp->fr_lock);
4957 		MUTEX_INIT(&fp->fr_lock, "filter rule lock");
4958 		if (fp->fr_die != 0)
4959 			ipf_rule_expire_insert(softc, fp, set);
4960 
4961 		fp->fr_hits = 0;
4962 		if (makecopy != 0)
4963 			fp->fr_ref = 1;
4964 		fp->fr_pnext = ftail;
4965 		fp->fr_next = *ftail;
4966 		if (fp->fr_next != NULL)
4967 			fp->fr_next->fr_pnext = &fp->fr_next;
4968 		*ftail = fp;
4969 		if (addrem == 0)
4970 			ipf_fixskip(ftail, fp, 1);
4971 
4972 		fp->fr_icmpgrp = NULL;
4973 		if (fp->fr_icmphead != -1) {
4974 			group = FR_NAME(fp, fr_icmphead);
4975 			fg = ipf_group_add(softc, group, fp, 0, unit, set);
4976 			fp->fr_icmpgrp = fg;
4977 		}
4978 
4979 		fp->fr_grphead = NULL;
4980 		if (fp->fr_grhead != -1) {
4981 			group = FR_NAME(fp, fr_grhead);
4982 			fg = ipf_group_add(softc, group, fp, fp->fr_flags,
4983 					   unit, set);
4984 			fp->fr_grphead = fg;
4985 		}
4986 	}
4987 done:
4988 	RWLOCK_EXIT(&softc->ipf_mutex);
4989 donenolock:
4990 	if (need_free || (error != 0)) {
4991 		if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
4992 			if ((fp->fr_satype == FRI_LOOKUP) &&
4993 			    (fp->fr_srcptr != NULL))
4994 				ipf_lookup_deref(softc, fp->fr_srctype,
4995 						 fp->fr_srcptr);
4996 			if ((fp->fr_datype == FRI_LOOKUP) &&
4997 			    (fp->fr_dstptr != NULL))
4998 				ipf_lookup_deref(softc, fp->fr_dsttype,
4999 						 fp->fr_dstptr);
5000 		}
5001 		if (fp->fr_grp != NULL) {
5002 			WRITE_ENTER(&softc->ipf_mutex);
5003 			ipf_group_del(softc, fp->fr_grp, fp);
5004 			RWLOCK_EXIT(&softc->ipf_mutex);
5005 		}
5006 		if ((ptr != NULL) && (makecopy != 0)) {
5007 			KFREES(ptr, fp->fr_dsize);
5008 		}
5009 		KFREES(fp, fp->fr_size);
5010 	}
5011 	return (error);
5012 }
5013 
5014 
5015 /* ------------------------------------------------------------------------ */
5016 /* Function:   ipf_rule_delete                                              */
5017 /* Returns:    Nil                                                          */
5018 /* Parameters: softc(I) - pointer to soft context main structure            */
5019 /*             f(I)     - pointer to the rule being deleted                 */
5020 /*             ftail(I) - pointer to the pointer to f                       */
5021 /*             unit(I)  - device for which this is for                      */
5022 /*             set(I)   - 1 or 0 (filter set)                               */
5023 /*                                                                          */
5024 /* This function attempts to do what it can to delete a filter rule: remove */
5025 /* it from any linked lists and remove any groups it is responsible for.    */
5026 /* But in the end, removing a rule can only drop the reference count - we   */
5027 /* must use that as the guide for whether or not it can be freed.           */
5028 /* ------------------------------------------------------------------------ */
5029 static void
5030 ipf_rule_delete(ipf_main_softc_t *softc, frentry_t *f, int unit, int set)
5031 {
5032 
5033 	/*
5034 	 * If fr_pdnext is set, then the rule is on the expire list, so
5035 	 * remove it from there.
5036 	 */
5037 	if (f->fr_pdnext != NULL) {
5038 		*f->fr_pdnext = f->fr_dnext;
5039 		if (f->fr_dnext != NULL)
5040 			f->fr_dnext->fr_pdnext = f->fr_pdnext;
5041 		f->fr_pdnext = NULL;
5042 		f->fr_dnext = NULL;
5043 	}
5044 
5045 	ipf_fixskip(f->fr_pnext, f, -1);
5046 	if (f->fr_pnext != NULL)
5047 		*f->fr_pnext = f->fr_next;
5048 	if (f->fr_next != NULL)
5049 		f->fr_next->fr_pnext = f->fr_pnext;
5050 	f->fr_pnext = NULL;
5051 	f->fr_next = NULL;
5052 
5053 	(void) ipf_derefrule(softc, &f);
5054 }
5055 
5056 /* ------------------------------------------------------------------------ */
5057 /* Function:   ipf_rule_expire_insert                                       */
5058 /* Returns:    Nil                                                          */
5059 /* Parameters: softc(I) - pointer to soft context main structure            */
5060 /*             f(I)     - pointer to rule to be added to expire list        */
5061 /*             set(I)   - 1 or 0 (filter set)                               */
5062 /*                                                                          */
5063 /* If the new rule has a given expiration time, insert it into the list of  */
5064 /* expiring rules with the ones to be removed first added to the front of   */
5065 /* the list. The insertion is O(n) but it is kept sorted for quick scans at */
5066 /* expiration interval checks.                                              */
5067 /* ------------------------------------------------------------------------ */
5068 static void
5069 ipf_rule_expire_insert(ipf_main_softc_t *softc, frentry_t *f, int set)
5070 {
5071 	frentry_t *fr;
5072 
5073 	/*
5074 	 */
5075 
5076 	f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
5077 	for (fr = softc->ipf_rule_explist[set]; fr != NULL;
5078 	     fr = fr->fr_dnext) {
5079 		if (f->fr_die < fr->fr_die)
5080 			break;
5081 		if (fr->fr_dnext == NULL) {
5082 			/*
5083 			 * We've got to the last rule and everything
5084 			 * wanted to be expired before this new node,
5085 			 * so we have to tack it on the end...
5086 			 */
5087 			fr->fr_dnext = f;
5088 			f->fr_pdnext = &fr->fr_dnext;
5089 			fr = NULL;
5090 			break;
5091 		}
5092 	}
5093 
5094 	if (softc->ipf_rule_explist[set] == NULL) {
5095 		softc->ipf_rule_explist[set] = f;
5096 		f->fr_pdnext = &softc->ipf_rule_explist[set];
5097 	} else if (fr != NULL) {
5098 		f->fr_dnext = fr;
5099 		f->fr_pdnext = fr->fr_pdnext;
5100 		fr->fr_pdnext = &f->fr_dnext;
5101 	}
5102 }
5103 
5104 
5105 /* ------------------------------------------------------------------------ */
5106 /* Function:   ipf_findlookup                                               */
5107 /* Returns:    NULL = failure, else success                                 */
5108 /* Parameters: softc(I) - pointer to soft context main structure            */
5109 /*             unit(I)  - ipf device we want to find match for              */
5110 /*             fp(I)    - rule for which lookup is for                      */
5111 /*             addrp(I) - pointer to lookup information in address struct   */
5112 /*             maskp(O) - pointer to lookup information for storage         */
5113 /*                                                                          */
5114 /* When using pools and hash tables to store addresses for matching in      */
5115 /* rules, it is necessary to resolve both the object referred to by the     */
5116 /* name or address (and return that pointer) and also provide the means by  */
5117 /* which to determine if an address belongs to that object to make the      */
5118 /* packet matching quicker.                                                 */
5119 /* ------------------------------------------------------------------------ */
5120 static void *
5121 ipf_findlookup(ipf_main_softc_t *softc, int unit, frentry_t *fr,
5122     i6addr_t *addrp, i6addr_t *maskp)
5123 {
5124 	void *ptr = NULL;
5125 
5126 	switch (addrp->iplookupsubtype)
5127 	{
5128 	case 0 :
5129 		ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
5130 					 addrp->iplookupnum,
5131 					 &maskp->iplookupfunc);
5132 		break;
5133 	case 1 :
5134 		if (addrp->iplookupname < 0)
5135 			break;
5136 		if (addrp->iplookupname >= fr->fr_namelen)
5137 			break;
5138 		ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
5139 					  fr->fr_names + addrp->iplookupname,
5140 					  &maskp->iplookupfunc);
5141 		break;
5142 	default :
5143 		break;
5144 	}
5145 
5146 	return ptr;
5147 }
5148 
5149 
5150 /* ------------------------------------------------------------------------ */
5151 /* Function:    ipf_funcinit                                                */
5152 /* Returns:     int - 0 == success, else ESRCH: cannot resolve rule details */
5153 /* Parameters:  softc(I) - pointer to soft context main structure           */
5154 /*              fr(I)    - pointer to filter rule                           */
5155 /*                                                                          */
5156 /* If a rule is a call rule, then check if the function it points to needs  */
5157 /* an init function to be called now the rule has been loaded.              */
5158 /* ------------------------------------------------------------------------ */
5159 static int
5160 ipf_funcinit(ipf_main_softc_t *softc, frentry_t *fr)
5161 {
5162 	ipfunc_resolve_t *ft;
5163 	int err;
5164 
5165 	IPFERROR(34);
5166 	err = ESRCH;
5167 
5168 	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5169 		if (ft->ipfu_addr == fr->fr_func) {
5170 			err = 0;
5171 			if (ft->ipfu_init != NULL)
5172 				err = (*ft->ipfu_init)(softc, fr);
5173 			break;
5174 		}
5175 	return err;
5176 }
5177 
5178 
5179 /* ------------------------------------------------------------------------ */
5180 /* Function:    ipf_funcfini                                                */
5181 /* Returns:     Nil                                                         */
5182 /* Parameters:  softc(I) - pointer to soft context main structure           */
5183 /*              fr(I)    - pointer to filter rule                           */
5184 /*                                                                          */
5185 /* For a given filter rule, call the matching "fini" function if the rule   */
5186 /* is using a known function that would have resulted in the "init" being   */
5187 /* called for ealier.                                                       */
5188 /* ------------------------------------------------------------------------ */
5189 static void
5190 ipf_funcfini(ipf_main_softc_t *softc, frentry_t *fr)
5191 {
5192 	ipfunc_resolve_t *ft;
5193 
5194 	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5195 		if (ft->ipfu_addr == fr->fr_func) {
5196 			if (ft->ipfu_fini != NULL)
5197 				(void) (*ft->ipfu_fini)(softc, fr);
5198 			break;
5199 		}
5200 }
5201 
5202 
5203 /* ------------------------------------------------------------------------ */
5204 /* Function:    ipf_findfunc                                                */
5205 /* Returns:     ipfunc_t - pointer to function if found, else NULL          */
5206 /* Parameters:  funcptr(I) - function pointer to lookup                     */
5207 /*                                                                          */
5208 /* Look for a function in the table of known functions.                     */
5209 /* ------------------------------------------------------------------------ */
5210 static ipfunc_t
5211 ipf_findfunc(ipfunc_t funcptr)
5212 {
5213 	ipfunc_resolve_t *ft;
5214 
5215 	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5216 		if (ft->ipfu_addr == funcptr)
5217 			return funcptr;
5218 	return NULL;
5219 }
5220 
5221 
5222 /* ------------------------------------------------------------------------ */
5223 /* Function:    ipf_resolvefunc                                             */
5224 /* Returns:     int - 0 == success, else error                              */
5225 /* Parameters:  data(IO) - ioctl data pointer to ipfunc_resolve_t struct    */
5226 /*                                                                          */
5227 /* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
5228 /* This will either be the function name (if the pointer is set) or the     */
5229 /* function pointer if the name is set.  When found, fill in the other one  */
5230 /* so that the entire, complete, structure can be copied back to user space.*/
5231 /* ------------------------------------------------------------------------ */
5232 int
5233 ipf_resolvefunc(ipf_main_softc_t *softc, void *data)
5234 {
5235 	ipfunc_resolve_t res, *ft;
5236 	int error;
5237 
5238 	error = BCOPYIN(data, &res, sizeof(res));
5239 	if (error != 0) {
5240 		IPFERROR(123);
5241 		return EFAULT;
5242 	}
5243 
5244 	if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
5245 		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5246 			if (strncmp(res.ipfu_name, ft->ipfu_name,
5247 				    sizeof(res.ipfu_name)) == 0) {
5248 				res.ipfu_addr = ft->ipfu_addr;
5249 				res.ipfu_init = ft->ipfu_init;
5250 				if (COPYOUT(&res, data, sizeof(res)) != 0) {
5251 					IPFERROR(35);
5252 					return EFAULT;
5253 				}
5254 				return 0;
5255 			}
5256 	}
5257 	if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
5258 		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5259 			if (ft->ipfu_addr == res.ipfu_addr) {
5260 				(void) strncpy(res.ipfu_name, ft->ipfu_name,
5261 					       sizeof(res.ipfu_name));
5262 				res.ipfu_init = ft->ipfu_init;
5263 				if (COPYOUT(&res, data, sizeof(res)) != 0) {
5264 					IPFERROR(36);
5265 					return EFAULT;
5266 				}
5267 				return 0;
5268 			}
5269 	}
5270 	IPFERROR(37);
5271 	return ESRCH;
5272 }
5273 
5274 
5275 #if !defined(_KERNEL) || (!defined(__NetBSD__) && !defined(__OpenBSD__) && \
5276      !defined(__FreeBSD__)) || \
5277     FREEBSD_LT_REV(501000) || NETBSD_LT_REV(105000000) || \
5278     OPENBSD_LT_REV(200006)
5279 /*
5280  * From: NetBSD
5281  * ppsratecheck(): packets (or events) per second limitation.
5282  */
5283 int
5284 ppsratecheck(lasttime, curpps, maxpps)
5285 	struct timeval *lasttime;
5286 	int *curpps;
5287 	int maxpps;	/* maximum pps allowed */
5288 {
5289 	struct timeval tv, delta;
5290 	int rv;
5291 
5292 	GETKTIME(&tv);
5293 
5294 	delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
5295 	delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
5296 	if (delta.tv_usec < 0) {
5297 		delta.tv_sec--;
5298 		delta.tv_usec += 1000000;
5299 	}
5300 
5301 	/*
5302 	 * check for 0,0 is so that the message will be seen at least once.
5303 	 * if more than one second have passed since the last update of
5304 	 * lasttime, reset the counter.
5305 	 *
5306 	 * we do increment *curpps even in *curpps < maxpps case, as some may
5307 	 * try to use *curpps for stat purposes as well.
5308 	 */
5309 	if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
5310 	    delta.tv_sec >= 1) {
5311 		*lasttime = tv;
5312 		*curpps = 0;
5313 		rv = 1;
5314 	} else if (maxpps < 0)
5315 		rv = 1;
5316 	else if (*curpps < maxpps)
5317 		rv = 1;
5318 	else
5319 		rv = 0;
5320 	*curpps = *curpps + 1;
5321 
5322 	return (rv);
5323 }
5324 #endif
5325 
5326 
5327 /* ------------------------------------------------------------------------ */
5328 /* Function:    ipf_derefrule                                               */
5329 /* Returns:     int   - 0 == rule freed up, else rule not freed             */
5330 /* Parameters:  fr(I) - pointer to filter rule                              */
5331 /*                                                                          */
5332 /* Decrement the reference counter to a rule by one.  If it reaches zero,   */
5333 /* free it and any associated storage space being used by it.               */
5334 /* ------------------------------------------------------------------------ */
5335 int
5336 ipf_derefrule(ipf_main_softc_t *softc, frentry_t **frp)
5337 {
5338 	frentry_t *fr;
5339 	frdest_t *fdp;
5340 
5341 	fr = *frp;
5342 	*frp = NULL;
5343 
5344 	MUTEX_ENTER(&fr->fr_lock);
5345 	fr->fr_ref--;
5346 	if (fr->fr_ref == 0) {
5347 		MUTEX_EXIT(&fr->fr_lock);
5348 		MUTEX_DESTROY(&fr->fr_lock);
5349 
5350 		ipf_funcfini(softc, fr);
5351 
5352 		fdp = &fr->fr_tif;
5353 		if (fdp->fd_type == FRD_DSTLIST)
5354 			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5355 
5356 		fdp = &fr->fr_rif;
5357 		if (fdp->fd_type == FRD_DSTLIST)
5358 			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5359 
5360 		fdp = &fr->fr_dif;
5361 		if (fdp->fd_type == FRD_DSTLIST)
5362 			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5363 
5364 		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5365 		    fr->fr_satype == FRI_LOOKUP)
5366 			ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
5367 		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5368 		    fr->fr_datype == FRI_LOOKUP)
5369 			ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
5370 
5371 		if (fr->fr_grp != NULL)
5372 			ipf_group_del(softc, fr->fr_grp, fr);
5373 
5374 		if (fr->fr_grphead != NULL)
5375 			ipf_group_del(softc, fr->fr_grphead, fr);
5376 
5377 		if (fr->fr_icmpgrp != NULL)
5378 			ipf_group_del(softc, fr->fr_icmpgrp, fr);
5379 
5380 		if ((fr->fr_flags & FR_COPIED) != 0) {
5381 			if (fr->fr_dsize) {
5382 				KFREES(fr->fr_data, fr->fr_dsize);
5383 			}
5384 			KFREES(fr, fr->fr_size);
5385 			return 0;
5386 		}
5387 		return 1;
5388 	} else {
5389 		MUTEX_EXIT(&fr->fr_lock);
5390 	}
5391 	return -1;
5392 }
5393 
5394 
5395 /* ------------------------------------------------------------------------ */
5396 /* Function:    ipf_grpmapinit                                              */
5397 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5398 /* Parameters:  fr(I) - pointer to rule to find hash table for              */
5399 /*                                                                          */
5400 /* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr.  */
5401 /* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap.                 */
5402 /* ------------------------------------------------------------------------ */
5403 static int
5404 ipf_grpmapinit(ipf_main_softc_t *softc, frentry_t *fr)
5405 {
5406 	char name[FR_GROUPLEN];
5407 	iphtable_t *iph;
5408 
5409 	(void) snprintf(name, sizeof(name), "%d", fr->fr_arg);
5410 	iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
5411 	if (iph == NULL) {
5412 		IPFERROR(38);
5413 		return ESRCH;
5414 	}
5415 	if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
5416 		IPFERROR(39);
5417 		return ESRCH;
5418 	}
5419 	iph->iph_ref++;
5420 	fr->fr_ptr = iph;
5421 	return 0;
5422 }
5423 
5424 
5425 /* ------------------------------------------------------------------------ */
5426 /* Function:    ipf_grpmapfini                                              */
5427 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5428 /* Parameters:  softc(I) - pointer to soft context main structure           */
5429 /*              fr(I)    - pointer to rule to release hash table for        */
5430 /*                                                                          */
5431 /* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
5432 /* be called to undo what ipf_grpmapinit caused to be done.                 */
5433 /* ------------------------------------------------------------------------ */
5434 static int
5435 ipf_grpmapfini(ipf_main_softc_t *softc, frentry_t *fr)
5436 {
5437 	iphtable_t *iph;
5438 	iph = fr->fr_ptr;
5439 	if (iph != NULL)
5440 		ipf_lookup_deref(softc, IPLT_HASH, iph);
5441 	return 0;
5442 }
5443 
5444 
5445 /* ------------------------------------------------------------------------ */
5446 /* Function:    ipf_srcgrpmap                                               */
5447 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5448 /* Parameters:  fin(I)    - pointer to packet information                   */
5449 /*              passp(IO) - pointer to current/new filter decision (unused) */
5450 /*                                                                          */
5451 /* Look for a rule group head in a hash table, using the source address as  */
5452 /* the key, and descend into that group and continue matching rules against */
5453 /* the packet.                                                              */
5454 /* ------------------------------------------------------------------------ */
5455 frentry_t *
5456 ipf_srcgrpmap(fr_info_t *fin, u_32_t *passp)
5457 {
5458 	frgroup_t *fg;
5459 	void *rval;
5460 
5461 	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5462 				 &fin->fin_src);
5463 	if (rval == NULL)
5464 		return NULL;
5465 
5466 	fg = rval;
5467 	fin->fin_fr = fg->fg_start;
5468 	(void) ipf_scanlist(fin, *passp);
5469 	return fin->fin_fr;
5470 }
5471 
5472 
5473 /* ------------------------------------------------------------------------ */
5474 /* Function:    ipf_dstgrpmap                                               */
5475 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5476 /* Parameters:  fin(I)    - pointer to packet information                   */
5477 /*              passp(IO) - pointer to current/new filter decision (unused) */
5478 /*                                                                          */
5479 /* Look for a rule group head in a hash table, using the destination        */
5480 /* address as the key, and descend into that group and continue matching    */
5481 /* rules against  the packet.                                               */
5482 /* ------------------------------------------------------------------------ */
5483 frentry_t *
5484 ipf_dstgrpmap(fr_info_t *fin, u_32_t *passp)
5485 {
5486 	frgroup_t *fg;
5487 	void *rval;
5488 
5489 	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5490 				 &fin->fin_dst);
5491 	if (rval == NULL)
5492 		return NULL;
5493 
5494 	fg = rval;
5495 	fin->fin_fr = fg->fg_start;
5496 	(void) ipf_scanlist(fin, *passp);
5497 	return fin->fin_fr;
5498 }
5499 
5500 /*
5501  * Queue functions
5502  * ===============
5503  * These functions manage objects on queues for efficient timeouts.  There
5504  * are a number of system defined queues as well as user defined timeouts.
5505  * It is expected that a lock is held in the domain in which the queue
5506  * belongs (i.e. either state or NAT) when calling any of these functions
5507  * that prevents ipf_freetimeoutqueue() from being called at the same time
5508  * as any other.
5509  */
5510 
5511 
5512 /* ------------------------------------------------------------------------ */
5513 /* Function:    ipf_addtimeoutqueue                                         */
5514 /* Returns:     struct ifqtq * - NULL if malloc fails, else pointer to      */
5515 /*                               timeout queue with given interval.         */
5516 /* Parameters:  parent(I)  - pointer to pointer to parent node of this list */
5517 /*                           of interface queues.                           */
5518 /*              seconds(I) - timeout value in seconds for this queue.       */
5519 /*                                                                          */
5520 /* This routine first looks for a timeout queue that matches the interval   */
5521 /* being requested.  If it finds one, increments the reference counter and  */
5522 /* returns a pointer to it.  If none are found, it allocates a new one and  */
5523 /* inserts it at the top of the list.                                       */
5524 /*                                                                          */
5525 /* Locking.                                                                 */
5526 /* It is assumed that the caller of this function has an appropriate lock   */
5527 /* held (exclusively) in the domain that encompases 'parent'.               */
5528 /* ------------------------------------------------------------------------ */
5529 ipftq_t *
5530 ipf_addtimeoutqueue(ipf_main_softc_t *softc, ipftq_t **parent, u_int seconds)
5531 {
5532 	ipftq_t *ifq;
5533 	u_int period;
5534 
5535 	period = seconds * IPF_HZ_DIVIDE;
5536 
5537 	MUTEX_ENTER(&softc->ipf_timeoutlock);
5538 	for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
5539 		if (ifq->ifq_ttl == period) {
5540 			/*
5541 			 * Reset the delete flag, if set, so the structure
5542 			 * gets reused rather than freed and reallocated.
5543 			 */
5544 			MUTEX_ENTER(&ifq->ifq_lock);
5545 			ifq->ifq_flags &= ~IFQF_DELETE;
5546 			ifq->ifq_ref++;
5547 			MUTEX_EXIT(&ifq->ifq_lock);
5548 			MUTEX_EXIT(&softc->ipf_timeoutlock);
5549 
5550 			return ifq;
5551 		}
5552 	}
5553 
5554 	KMALLOC(ifq, ipftq_t *);
5555 	if (ifq != NULL) {
5556 		MUTEX_NUKE(&ifq->ifq_lock);
5557 		IPFTQ_INIT(ifq, period, "ipftq mutex");
5558 		ifq->ifq_next = *parent;
5559 		ifq->ifq_pnext = parent;
5560 		ifq->ifq_flags = IFQF_USER;
5561 		ifq->ifq_ref++;
5562 		*parent = ifq;
5563 		softc->ipf_userifqs++;
5564 	}
5565 	MUTEX_EXIT(&softc->ipf_timeoutlock);
5566 	return ifq;
5567 }
5568 
5569 
5570 /* ------------------------------------------------------------------------ */
5571 /* Function:    ipf_deletetimeoutqueue                                      */
5572 /* Returns:     int    - new reference count value of the timeout queue     */
5573 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5574 /* Locks:       ifq->ifq_lock                                               */
5575 /*                                                                          */
5576 /* This routine must be called when we're discarding a pointer to a timeout */
5577 /* queue object, taking care of the reference counter.                      */
5578 /*                                                                          */
5579 /* Now that this just sets a DELETE flag, it requires the expire code to    */
5580 /* check the list of user defined timeout queues and call the free function */
5581 /* below (currently commented out) to stop memory leaking.  It is done this */
5582 /* way because the locking may not be sufficient to safely do a free when   */
5583 /* this function is called.                                                 */
5584 /* ------------------------------------------------------------------------ */
5585 int
5586 ipf_deletetimeoutqueue(ipftq_t *ifq)
5587 {
5588 
5589 	ifq->ifq_ref--;
5590 	if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
5591 		ifq->ifq_flags |= IFQF_DELETE;
5592 	}
5593 
5594 	return ifq->ifq_ref;
5595 }
5596 
5597 
5598 /* ------------------------------------------------------------------------ */
5599 /* Function:    ipf_freetimeoutqueue                                        */
5600 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5601 /* Returns:     Nil                                                         */
5602 /*                                                                          */
5603 /* Locking:                                                                 */
5604 /* It is assumed that the caller of this function has an appropriate lock   */
5605 /* held (exclusively) in the domain that encompases the callers "domain".   */
5606 /* The ifq_lock for this structure should not be held.                      */
5607 /*                                                                          */
5608 /* Remove a user defined timeout queue from the list of queues it is in and */
5609 /* tidy up after this is done.                                              */
5610 /* ------------------------------------------------------------------------ */
5611 void
5612 ipf_freetimeoutqueue(ipf_main_softc_t *softc, ipftq_t *ifq)
5613 {
5614 
5615 	if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5616 	    ((ifq->ifq_flags & IFQF_USER) == 0)) {
5617 		printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5618 		       (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5619 		       ifq->ifq_ref);
5620 		return;
5621 	}
5622 
5623 	/*
5624 	 * Remove from its position in the list.
5625 	 */
5626 	*ifq->ifq_pnext = ifq->ifq_next;
5627 	if (ifq->ifq_next != NULL)
5628 		ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5629 	ifq->ifq_next = NULL;
5630 	ifq->ifq_pnext = NULL;
5631 
5632 	MUTEX_DESTROY(&ifq->ifq_lock);
5633 	ATOMIC_DEC(softc->ipf_userifqs);
5634 	KFREE(ifq);
5635 }
5636 
5637 
5638 /* ------------------------------------------------------------------------ */
5639 /* Function:    ipf_deletequeueentry                                        */
5640 /* Returns:     Nil                                                         */
5641 /* Parameters:  tqe(I) - timeout queue entry to delete                      */
5642 /*                                                                          */
5643 /* Remove a tail queue entry from its queue and make it an orphan.          */
5644 /* ipf_deletetimeoutqueue is called to make sure the reference count on the */
5645 /* queue is correct.  We can't, however, call ipf_freetimeoutqueue because  */
5646 /* the correct lock(s) may not be held that would make it safe to do so.    */
5647 /* ------------------------------------------------------------------------ */
5648 void
5649 ipf_deletequeueentry(ipftqent_t *tqe)
5650 {
5651 	ipftq_t *ifq;
5652 
5653 	ifq = tqe->tqe_ifq;
5654 
5655 	MUTEX_ENTER(&ifq->ifq_lock);
5656 
5657 	if (tqe->tqe_pnext != NULL) {
5658 		*tqe->tqe_pnext = tqe->tqe_next;
5659 		if (tqe->tqe_next != NULL)
5660 			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5661 		else    /* we must be the tail anyway */
5662 			ifq->ifq_tail = tqe->tqe_pnext;
5663 
5664 		tqe->tqe_pnext = NULL;
5665 		tqe->tqe_ifq = NULL;
5666 	}
5667 
5668 	(void) ipf_deletetimeoutqueue(ifq);
5669 	ASSERT(ifq->ifq_ref > 0);
5670 
5671 	MUTEX_EXIT(&ifq->ifq_lock);
5672 }
5673 
5674 
5675 /* ------------------------------------------------------------------------ */
5676 /* Function:    ipf_queuefront                                              */
5677 /* Returns:     Nil                                                         */
5678 /* Parameters:  tqe(I) - pointer to timeout queue entry                     */
5679 /*                                                                          */
5680 /* Move a queue entry to the front of the queue, if it isn't already there. */
5681 /* ------------------------------------------------------------------------ */
5682 void
5683 ipf_queuefront(ipftqent_t *tqe)
5684 {
5685 	ipftq_t *ifq;
5686 
5687 	ifq = tqe->tqe_ifq;
5688 	if (ifq == NULL)
5689 		return;
5690 
5691 	MUTEX_ENTER(&ifq->ifq_lock);
5692 	if (ifq->ifq_head != tqe) {
5693 		*tqe->tqe_pnext = tqe->tqe_next;
5694 		if (tqe->tqe_next)
5695 			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5696 		else
5697 			ifq->ifq_tail = tqe->tqe_pnext;
5698 
5699 		tqe->tqe_next = ifq->ifq_head;
5700 		ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5701 		ifq->ifq_head = tqe;
5702 		tqe->tqe_pnext = &ifq->ifq_head;
5703 	}
5704 	MUTEX_EXIT(&ifq->ifq_lock);
5705 }
5706 
5707 
5708 /* ------------------------------------------------------------------------ */
5709 /* Function:    ipf_queueback                                               */
5710 /* Returns:     Nil                                                         */
5711 /* Parameters:  ticks(I) - ipf tick time to use with this call              */
5712 /*              tqe(I)   - pointer to timeout queue entry                   */
5713 /*                                                                          */
5714 /* Move a queue entry to the back of the queue, if it isn't already there.  */
5715 /* We use use ticks to calculate the expiration and mark for when we last   */
5716 /* touched the structure.                                                   */
5717 /* ------------------------------------------------------------------------ */
5718 void
5719 ipf_queueback(u_long ticks, ipftqent_t *tqe)
5720 {
5721 	ipftq_t *ifq;
5722 
5723 	ifq = tqe->tqe_ifq;
5724 	if (ifq == NULL)
5725 		return;
5726 	tqe->tqe_die = ticks + ifq->ifq_ttl;
5727 	tqe->tqe_touched = ticks;
5728 
5729 	MUTEX_ENTER(&ifq->ifq_lock);
5730 	if (tqe->tqe_next != NULL) {		/* at the end already ? */
5731 		/*
5732 		 * Remove from list
5733 		 */
5734 		*tqe->tqe_pnext = tqe->tqe_next;
5735 		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5736 
5737 		/*
5738 		 * Make it the last entry.
5739 		 */
5740 		tqe->tqe_next = NULL;
5741 		tqe->tqe_pnext = ifq->ifq_tail;
5742 		*ifq->ifq_tail = tqe;
5743 		ifq->ifq_tail = &tqe->tqe_next;
5744 	}
5745 	MUTEX_EXIT(&ifq->ifq_lock);
5746 }
5747 
5748 
5749 /* ------------------------------------------------------------------------ */
5750 /* Function:    ipf_queueappend                                             */
5751 /* Returns:     Nil                                                         */
5752 /* Parameters:  ticks(I)  - ipf tick time to use with this call             */
5753 /*              tqe(I)    - pointer to timeout queue entry                  */
5754 /*              ifq(I)    - pointer to timeout queue                        */
5755 /*              parent(I) - owing object pointer                            */
5756 /*                                                                          */
5757 /* Add a new item to this queue and put it on the very end.                 */
5758 /* We use use ticks to calculate the expiration and mark for when we last   */
5759 /* touched the structure.                                                   */
5760 /* ------------------------------------------------------------------------ */
5761 void
5762 ipf_queueappend(u_long ticks, ipftqent_t *tqe, ipftq_t *ifq, void *parent)
5763 {
5764 
5765 	MUTEX_ENTER(&ifq->ifq_lock);
5766 	tqe->tqe_parent = parent;
5767 	tqe->tqe_pnext = ifq->ifq_tail;
5768 	*ifq->ifq_tail = tqe;
5769 	ifq->ifq_tail = &tqe->tqe_next;
5770 	tqe->tqe_next = NULL;
5771 	tqe->tqe_ifq = ifq;
5772 	tqe->tqe_die = ticks + ifq->ifq_ttl;
5773 	tqe->tqe_touched = ticks;
5774 	ifq->ifq_ref++;
5775 	MUTEX_EXIT(&ifq->ifq_lock);
5776 }
5777 
5778 
5779 /* ------------------------------------------------------------------------ */
5780 /* Function:    ipf_movequeue                                               */
5781 /* Returns:     Nil                                                         */
5782 /* Parameters:  tq(I)   - pointer to timeout queue information              */
5783 /*              oifp(I) - old timeout queue entry was on                    */
5784 /*              nifp(I) - new timeout queue to put entry on                 */
5785 /*                                                                          */
5786 /* Move a queue entry from one timeout queue to another timeout queue.      */
5787 /* If it notices that the current entry is already last and does not need   */
5788 /* to move queue, the return.                                               */
5789 /* ------------------------------------------------------------------------ */
5790 void
5791 ipf_movequeue(u_long ticks, ipftqent_t *tqe, ipftq_t *oifq, ipftq_t *nifq)
5792 {
5793 
5794 	/*
5795 	 * If the queue hasn't changed and we last touched this entry at the
5796 	 * same ipf time, then we're not going to achieve anything by either
5797 	 * changing the ttl or moving it on the queue.
5798 	 */
5799 	if (oifq == nifq && tqe->tqe_touched == ticks)
5800 		return;
5801 
5802 	/*
5803 	 * For any of this to be outside the lock, there is a risk that two
5804 	 * packets entering simultaneously, with one changing to a different
5805 	 * queue and one not, could end up with things in a bizarre state.
5806 	 */
5807 	MUTEX_ENTER(&oifq->ifq_lock);
5808 
5809 	tqe->tqe_touched = ticks;
5810 	tqe->tqe_die = ticks + nifq->ifq_ttl;
5811 	/*
5812 	 * Is the operation here going to be a no-op ?
5813 	 */
5814 	if (oifq == nifq) {
5815 		if ((tqe->tqe_next == NULL) ||
5816 		    (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
5817 			MUTEX_EXIT(&oifq->ifq_lock);
5818 			return;
5819 		}
5820 	}
5821 
5822 	/*
5823 	 * Remove from the old queue
5824 	 */
5825 	*tqe->tqe_pnext = tqe->tqe_next;
5826 	if (tqe->tqe_next)
5827 		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5828 	else
5829 		oifq->ifq_tail = tqe->tqe_pnext;
5830 	tqe->tqe_next = NULL;
5831 
5832 	/*
5833 	 * If we're moving from one queue to another, release the
5834 	 * lock on the old queue and get a lock on the new queue.
5835 	 * For user defined queues, if we're moving off it, call
5836 	 * delete in case it can now be freed.
5837 	 */
5838 	if (oifq != nifq) {
5839 		tqe->tqe_ifq = NULL;
5840 
5841 		(void) ipf_deletetimeoutqueue(oifq);
5842 
5843 		MUTEX_EXIT(&oifq->ifq_lock);
5844 
5845 		MUTEX_ENTER(&nifq->ifq_lock);
5846 
5847 		tqe->tqe_ifq = nifq;
5848 		nifq->ifq_ref++;
5849 	}
5850 
5851 	/*
5852 	 * Add to the bottom of the new queue
5853 	 */
5854 	tqe->tqe_pnext = nifq->ifq_tail;
5855 	*nifq->ifq_tail = tqe;
5856 	nifq->ifq_tail = &tqe->tqe_next;
5857 	MUTEX_EXIT(&nifq->ifq_lock);
5858 }
5859 
5860 
5861 /* ------------------------------------------------------------------------ */
5862 /* Function:    ipf_updateipid                                              */
5863 /* Returns:     int - 0 == success, -1 == error (packet should be droppped) */
5864 /* Parameters:  fin(I) - pointer to packet information                      */
5865 /*                                                                          */
5866 /* When we are doing NAT, change the IP of every packet to represent a      */
5867 /* single sequence of packets coming from the host, hiding any host         */
5868 /* specific sequencing that might otherwise be revealed.  If the packet is  */
5869 /* a fragment, then store the 'new' IPid in the fragment cache and look up  */
5870 /* the fragment cache for non-leading fragments.  If a non-leading fragment */
5871 /* has no match in the cache, return an error.                              */
5872 /* ------------------------------------------------------------------------ */
5873 static int
5874 ipf_updateipid(fr_info_t *fin)
5875 {
5876 	u_short id, ido, sums;
5877 	u_32_t sumd, sum;
5878 	ip_t *ip;
5879 
5880 	if (fin->fin_off != 0) {
5881 		sum = ipf_frag_ipidknown(fin);
5882 		if (sum == 0xffffffff)
5883 			return -1;
5884 		sum &= 0xffff;
5885 		id = (u_short)sum;
5886 	} else {
5887 		id = ipf_nextipid(fin);
5888 		if (fin->fin_off == 0 && (fin->fin_flx & FI_FRAG) != 0)
5889 			(void) ipf_frag_ipidnew(fin, (u_32_t)id);
5890 	}
5891 
5892 	ip = fin->fin_ip;
5893 	ido = ntohs(ip->ip_id);
5894 	if (id == ido)
5895 		return 0;
5896 	ip->ip_id = htons(id);
5897 	CALC_SUMD(ido, id, sumd);	/* DESTRUCTIVE MACRO! id,ido change */
5898 	sum = (~ntohs(ip->ip_sum)) & 0xffff;
5899 	sum += sumd;
5900 	sum = (sum >> 16) + (sum & 0xffff);
5901 	sum = (sum >> 16) + (sum & 0xffff);
5902 	sums = ~(u_short)sum;
5903 	ip->ip_sum = htons(sums);
5904 	return 0;
5905 }
5906 
5907 
5908 #ifdef	NEED_FRGETIFNAME
5909 /* ------------------------------------------------------------------------ */
5910 /* Function:    ipf_getifname                                               */
5911 /* Returns:     char *    - pointer to interface name                       */
5912 /* Parameters:  ifp(I)    - pointer to network interface                    */
5913 /*              buffer(O) - pointer to where to store interface name        */
5914 /*                                                                          */
5915 /* Constructs an interface name in the buffer passed.  The buffer passed is */
5916 /* expected to be at least LIFNAMSIZ in bytes big.  If buffer is passed in  */
5917 /* as a NULL pointer then return a pointer to a static array.               */
5918 /* ------------------------------------------------------------------------ */
5919 char *
5920 ipf_getifname(ifp, buffer)
5921 	struct ifnet *ifp;
5922 	char *buffer;
5923 {
5924 	static char namebuf[LIFNAMSIZ];
5925 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
5926      defined(__sgi) || defined(linux) || defined(_AIX51) || \
5927      (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
5928 	int unit, space;
5929 	char temp[20];
5930 	char *s;
5931 # endif
5932 
5933 	if (buffer == NULL)
5934 		buffer = namebuf;
5935 	(void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
5936 	buffer[LIFNAMSIZ - 1] = '\0';
5937 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
5938      defined(__sgi) || defined(_AIX51) || \
5939      (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
5940 	for (s = buffer; *s; s++)
5941 		;
5942 	unit = ifp->if_unit;
5943 	space = LIFNAMSIZ - (s - buffer);
5944 	if ((space > 0) && (unit >= 0)) {
5945 		snprintf(temp, sizeof(temp), "%d", unit);
5946 		(void) strncpy(s, temp, space);
5947 		s[space - 1] = '\0';
5948 	}
5949 # endif
5950 	return buffer;
5951 }
5952 #endif
5953 
5954 
5955 /* ------------------------------------------------------------------------ */
5956 /* Function:    ipf_ioctlswitch                                             */
5957 /* Returns:     int     - -1 continue processing, else ioctl return value   */
5958 /* Parameters:  unit(I) - device unit opened                                */
5959 /*              data(I) - pointer to ioctl data                             */
5960 /*              cmd(I)  - ioctl command                                     */
5961 /*              mode(I) - mode value                                        */
5962 /*              uid(I)  - uid making the ioctl call                         */
5963 /*              ctx(I)  - pointer to context data                           */
5964 /*                                                                          */
5965 /* Based on the value of unit, call the appropriate ioctl handler or return */
5966 /* EIO if ipfilter is not running.   Also checks if write perms are req'd   */
5967 /* for the device in order to execute the ioctl.  A special case is made    */
5968 /* SIOCIPFINTERROR so that the same code isn't required in every handler.   */
5969 /* The context data pointer is passed through as this is used as the key    */
5970 /* for locating a matching token for continued access for walking lists,    */
5971 /* etc.                                                                     */
5972 /* ------------------------------------------------------------------------ */
5973 int
5974 ipf_ioctlswitch(ipf_main_softc_t *softc, int unit, void *data, ioctlcmd_t cmd,
5975     int mode, int uid, void *ctx)
5976 {
5977 	int error = 0;
5978 
5979 	switch (cmd)
5980 	{
5981 	case SIOCIPFINTERROR :
5982 		error = BCOPYOUT(&softc->ipf_interror, data,
5983 				 sizeof(softc->ipf_interror));
5984 		if (error != 0) {
5985 			IPFERROR(40);
5986 			error = EFAULT;
5987 		}
5988 		return error;
5989 	default :
5990 		break;
5991 	}
5992 
5993 	switch (unit)
5994 	{
5995 	case IPL_LOGIPF :
5996 		error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
5997 		break;
5998 	case IPL_LOGNAT :
5999 		if (softc->ipf_running > 0) {
6000 			error = ipf_nat_ioctl(softc, data, cmd, mode,
6001 					      uid, ctx);
6002 		} else {
6003 			IPFERROR(42);
6004 			error = EIO;
6005 		}
6006 		break;
6007 	case IPL_LOGSTATE :
6008 		if (softc->ipf_running > 0) {
6009 			error = ipf_state_ioctl(softc, data, cmd, mode,
6010 						uid, ctx);
6011 		} else {
6012 			IPFERROR(43);
6013 			error = EIO;
6014 		}
6015 		break;
6016 	case IPL_LOGAUTH :
6017 		if (softc->ipf_running > 0) {
6018 			error = ipf_auth_ioctl(softc, data, cmd, mode,
6019 					       uid, ctx);
6020 		} else {
6021 			IPFERROR(44);
6022 			error = EIO;
6023 		}
6024 		break;
6025 	case IPL_LOGSYNC :
6026 		if (softc->ipf_running > 0) {
6027 			error = ipf_sync_ioctl(softc, data, cmd, mode,
6028 					       uid, ctx);
6029 		} else {
6030 			error = EIO;
6031 			IPFERROR(45);
6032 		}
6033 		break;
6034 	case IPL_LOGSCAN :
6035 #ifdef IPFILTER_SCAN
6036 		if (softc->ipf_running > 0)
6037 			error = ipf_scan_ioctl(softc, data, cmd, mode,
6038 					       uid, ctx);
6039 		else
6040 #endif
6041 		{
6042 			error = EIO;
6043 			IPFERROR(46);
6044 		}
6045 		break;
6046 	case IPL_LOGLOOKUP :
6047 		if (softc->ipf_running > 0) {
6048 			error = ipf_lookup_ioctl(softc, data, cmd, mode,
6049 						 uid, ctx);
6050 		} else {
6051 			error = EIO;
6052 			IPFERROR(47);
6053 		}
6054 		break;
6055 	default :
6056 		IPFERROR(48);
6057 		error = EIO;
6058 		break;
6059 	}
6060 
6061 	return error;
6062 }
6063 
6064 
6065 /*
6066  * This array defines the expected size of objects coming into the kernel
6067  * for the various recognised object types. The first column is flags (see
6068  * below), 2nd column is current size, 3rd column is the version number of
6069  * when the current size became current.
6070  * Flags:
6071  * 1 = minimum size, not absolute size
6072  */
6073 static	int	ipf_objbytes[IPFOBJ_COUNT][3] = {
6074 	{ 1,	sizeof(struct frentry),		5010000 },	/* 0 */
6075 	{ 1,	sizeof(struct friostat),	5010000 },
6076 	{ 0,	sizeof(struct fr_info),		5010000 },
6077 	{ 0,	sizeof(struct ipf_authstat),	4010100 },
6078 	{ 0,	sizeof(struct ipfrstat),	5010000 },
6079 	{ 1,	sizeof(struct ipnat),		5010000 },	/* 5 */
6080 	{ 0,	sizeof(struct natstat),		5010000 },
6081 	{ 0,	sizeof(struct ipstate_save),	5010000 },
6082 	{ 1,	sizeof(struct nat_save),	5010000 },
6083 	{ 0,	sizeof(struct natlookup),	5010000 },
6084 	{ 1,	sizeof(struct ipstate),		5010000 },	/* 10 */
6085 	{ 0,	sizeof(struct ips_stat),	5010000 },
6086 	{ 0,	sizeof(struct frauth),		5010000 },
6087 	{ 0,	sizeof(struct ipftune),		4010100 },
6088 	{ 0,	sizeof(struct nat),		5010000 },
6089 	{ 0,	sizeof(struct ipfruleiter),	4011400 },	/* 15 */
6090 	{ 0,	sizeof(struct ipfgeniter),	4011400 },
6091 	{ 0,	sizeof(struct ipftable),	4011400 },
6092 	{ 0,	sizeof(struct ipflookupiter),	4011400 },
6093 	{ 0,	sizeof(struct ipftq) * IPF_TCP_NSTATES },
6094 	{ 1,	0,				0	}, /* IPFEXPR */
6095 	{ 0,	0,				0	}, /* PROXYCTL */
6096 	{ 0,	sizeof (struct fripf),		5010000	}
6097 };
6098 
6099 
6100 /* ------------------------------------------------------------------------ */
6101 /* Function:    ipf_inobj                                                   */
6102 /* Returns:     int     - 0 = success, else failure                         */
6103 /* Parameters:  softc(I) - soft context pointerto work with                 */
6104 /*              data(I)  - pointer to ioctl data                            */
6105 /*              objp(O)  - where to store ipfobj structure                  */
6106 /*              ptr(I)   - pointer to data to copy out                      */
6107 /*              type(I)  - type of structure being moved                    */
6108 /*                                                                          */
6109 /* Copy in the contents of what the ipfobj_t points to.  In future, we      */
6110 /* add things to check for version numbers, sizes, etc, to make it backward */
6111 /* compatible at the ABI for user land.                                     */
6112 /* If objp is not NULL then we assume that the caller wants to see what is  */
6113 /* in the ipfobj_t structure being copied in. As an example, this can tell  */
6114 /* the caller what version of ipfilter the ioctl program was written to.    */
6115 /* ------------------------------------------------------------------------ */
6116 int
6117 ipf_inobj(ipf_main_softc_t *softc, void *data, ipfobj_t *objp, void *ptr,
6118     int type)
6119 {
6120 	ipfobj_t obj;
6121 	int error;
6122 	int size;
6123 
6124 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6125 		IPFERROR(49);
6126 		return EINVAL;
6127 	}
6128 
6129 	if (objp == NULL)
6130 		objp = &obj;
6131 	error = BCOPYIN(data, objp, sizeof(*objp));
6132 	if (error != 0) {
6133 		IPFERROR(124);
6134 		return EFAULT;
6135 	}
6136 
6137 	if (objp->ipfo_type != type) {
6138 		IPFERROR(50);
6139 		return EINVAL;
6140 	}
6141 
6142 	if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
6143 		if ((ipf_objbytes[type][0] & 1) != 0) {
6144 			if (objp->ipfo_size < ipf_objbytes[type][1]) {
6145 				IPFERROR(51);
6146 				return EINVAL;
6147 			}
6148 			size =  ipf_objbytes[type][1];
6149 		} else if (objp->ipfo_size == ipf_objbytes[type][1]) {
6150 			size =  objp->ipfo_size;
6151 		} else {
6152 			IPFERROR(52);
6153 			return EINVAL;
6154 		}
6155 		error = COPYIN(objp->ipfo_ptr, ptr, size);
6156 		if (error != 0) {
6157 			IPFERROR(55);
6158 			error = EFAULT;
6159 		}
6160 	} else {
6161 #ifdef  IPFILTER_COMPAT
6162 		error = ipf_in_compat(softc, objp, ptr, 0);
6163 #else
6164 		IPFERROR(54);
6165 		error = EINVAL;
6166 #endif
6167 	}
6168 	return error;
6169 }
6170 
6171 
6172 /* ------------------------------------------------------------------------ */
6173 /* Function:    ipf_inobjsz                                                 */
6174 /* Returns:     int     - 0 = success, else failure                         */
6175 /* Parameters:  softc(I) - soft context pointerto work with                 */
6176 /*              data(I)  - pointer to ioctl data                            */
6177 /*              ptr(I)   - pointer to store real data in                    */
6178 /*              type(I)  - type of structure being moved                    */
6179 /*              sz(I)    - size of data to copy                             */
6180 /*                                                                          */
6181 /* As per ipf_inobj, except the size of the object to copy in is passed in  */
6182 /* but it must not be smaller than the size defined for the type and the    */
6183 /* type must allow for varied sized objects.  The extra requirement here is */
6184 /* that sz must match the size of the object being passed in - this is not  */
6185 /* not possible nor required in ipf_inobj().                                */
6186 /* ------------------------------------------------------------------------ */
6187 int
6188 ipf_inobjsz(ipf_main_softc_t *softc, void *data, void *ptr, int type, int sz)
6189 {
6190 	ipfobj_t obj;
6191 	int error;
6192 
6193 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6194 		IPFERROR(56);
6195 		return EINVAL;
6196 	}
6197 
6198 	error = BCOPYIN(data, &obj, sizeof(obj));
6199 	if (error != 0) {
6200 		IPFERROR(125);
6201 		return EFAULT;
6202 	}
6203 
6204 	if (obj.ipfo_type != type) {
6205 		IPFERROR(58);
6206 		return EINVAL;
6207 	}
6208 
6209 	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6210 		if (((ipf_objbytes[type][0] & 1) == 0) ||
6211 		    (sz < ipf_objbytes[type][1])) {
6212 			IPFERROR(57);
6213 			return EINVAL;
6214 		}
6215 		error = COPYIN(obj.ipfo_ptr, ptr, sz);
6216 		if (error != 0) {
6217 			IPFERROR(61);
6218 			error = EFAULT;
6219 		}
6220 	} else {
6221 #ifdef	IPFILTER_COMPAT
6222 		error = ipf_in_compat(softc, &obj, ptr, sz);
6223 #else
6224 		IPFERROR(60);
6225 		error = EINVAL;
6226 #endif
6227 	}
6228 	return error;
6229 }
6230 
6231 
6232 /* ------------------------------------------------------------------------ */
6233 /* Function:    ipf_outobjsz                                                */
6234 /* Returns:     int     - 0 = success, else failure                         */
6235 /* Parameters:  data(I) - pointer to ioctl data                             */
6236 /*              ptr(I)  - pointer to store real data in                     */
6237 /*              type(I) - type of structure being moved                     */
6238 /*              sz(I)   - size of data to copy                              */
6239 /*                                                                          */
6240 /* As per ipf_outobj, except the size of the object to copy out is passed in*/
6241 /* but it must not be smaller than the size defined for the type and the    */
6242 /* type must allow for varied sized objects.  The extra requirement here is */
6243 /* that sz must match the size of the object being passed in - this is not  */
6244 /* not possible nor required in ipf_outobj().                               */
6245 /* ------------------------------------------------------------------------ */
6246 int
6247 ipf_outobjsz(ipf_main_softc_t *softc, void *data, void *ptr, int type, int sz)
6248 {
6249 	ipfobj_t obj;
6250 	int error;
6251 
6252 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6253 		IPFERROR(62);
6254 		return EINVAL;
6255 	}
6256 
6257 	error = BCOPYIN(data, &obj, sizeof(obj));
6258 	if (error != 0) {
6259 		IPFERROR(127);
6260 		return EFAULT;
6261 	}
6262 
6263 	if (obj.ipfo_type != type) {
6264 		IPFERROR(63);
6265 		return EINVAL;
6266 	}
6267 
6268 	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6269 		if (((ipf_objbytes[type][0] & 1) == 0) ||
6270 		    (sz < ipf_objbytes[type][1])) {
6271 			IPFERROR(146);
6272 			return EINVAL;
6273 		}
6274 		error = COPYOUT(ptr, obj.ipfo_ptr, sz);
6275 		if (error != 0) {
6276 			IPFERROR(66);
6277 			error = EFAULT;
6278 		}
6279 	} else {
6280 #ifdef	IPFILTER_COMPAT
6281 		error = ipf_out_compat(softc, &obj, ptr);
6282 #else
6283 		IPFERROR(65);
6284 		error = EINVAL;
6285 #endif
6286 	}
6287 	return error;
6288 }
6289 
6290 
6291 /* ------------------------------------------------------------------------ */
6292 /* Function:    ipf_outobj                                                  */
6293 /* Returns:     int     - 0 = success, else failure                         */
6294 /* Parameters:  data(I) - pointer to ioctl data                             */
6295 /*              ptr(I)  - pointer to store real data in                     */
6296 /*              type(I) - type of structure being moved                     */
6297 /*                                                                          */
6298 /* Copy out the contents of what ptr is to where ipfobj points to.  In      */
6299 /* future, we add things to check for version numbers, sizes, etc, to make  */
6300 /* it backward  compatible at the ABI for user land.                        */
6301 /* ------------------------------------------------------------------------ */
6302 int
6303 ipf_outobj(ipf_main_softc_t *softc, void *data, void *ptr, int type)
6304 {
6305 	ipfobj_t obj;
6306 	int error;
6307 
6308 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6309 		IPFERROR(67);
6310 		return EINVAL;
6311 	}
6312 
6313 	error = BCOPYIN(data, &obj, sizeof(obj));
6314 	if (error != 0) {
6315 		IPFERROR(126);
6316 		return EFAULT;
6317 	}
6318 
6319 	if (obj.ipfo_type != type) {
6320 		IPFERROR(68);
6321 		return EINVAL;
6322 	}
6323 
6324 	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6325 		if ((ipf_objbytes[type][0] & 1) != 0) {
6326 			if (obj.ipfo_size < ipf_objbytes[type][1]) {
6327 				IPFERROR(69);
6328 				return EINVAL;
6329 			}
6330 		} else if (obj.ipfo_size != ipf_objbytes[type][1]) {
6331 			IPFERROR(70);
6332 			return EINVAL;
6333 		}
6334 
6335 		error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
6336 		if (error != 0) {
6337 			IPFERROR(73);
6338 			error = EFAULT;
6339 		}
6340 	} else {
6341 #ifdef	IPFILTER_COMPAT
6342 		error = ipf_out_compat(softc, &obj, ptr);
6343 #else
6344 		IPFERROR(72);
6345 		error = EINVAL;
6346 #endif
6347 	}
6348 	return error;
6349 }
6350 
6351 
6352 /* ------------------------------------------------------------------------ */
6353 /* Function:    ipf_outobjk                                                 */
6354 /* Returns:     int     - 0 = success, else failure                         */
6355 /* Parameters:  obj(I)  - pointer to data description structure             */
6356 /*              ptr(I)  - pointer to kernel data to copy out                */
6357 /*                                                                          */
6358 /* In the above functions, the ipfobj_t structure is copied into the kernel,*/
6359 /* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
6360 /* already populated with information and now we just need to use it.       */
6361 /* There is no need for this function to have a "type" parameter as there   */
6362 /* is no point in validating information that comes from the kernel with    */
6363 /* itself.                                                                  */
6364 /* ------------------------------------------------------------------------ */
6365 int
6366 ipf_outobjk(ipf_main_softc_t *softc, ipfobj_t *obj, void *ptr)
6367 {
6368 	int type = obj->ipfo_type;
6369 	int error;
6370 
6371 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6372 		IPFERROR(147);
6373 		return EINVAL;
6374 	}
6375 
6376 	if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
6377 		if ((ipf_objbytes[type][0] & 1) != 0) {
6378 			if (obj->ipfo_size < ipf_objbytes[type][1]) {
6379 				IPFERROR(148);
6380 				return EINVAL;
6381 			}
6382 
6383 		} else if (obj->ipfo_size != ipf_objbytes[type][1]) {
6384 			IPFERROR(149);
6385 			return EINVAL;
6386 		}
6387 
6388 		error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
6389 		if (error != 0) {
6390 			IPFERROR(150);
6391 			error = EFAULT;
6392 		}
6393 	} else {
6394 #ifdef  IPFILTER_COMPAT
6395 		error = ipf_out_compat(softc, obj, ptr);
6396 #else
6397 		IPFERROR(151);
6398 		error = EINVAL;
6399 #endif
6400 	}
6401 	return error;
6402 }
6403 
6404 
6405 /* ------------------------------------------------------------------------ */
6406 /* Function:    ipf_checkl4sum                                              */
6407 /* Returns:     int     - 0 = good, -1 = bad, 1 = cannot check              */
6408 /* Parameters:  fin(I) - pointer to packet information                      */
6409 /*                                                                          */
6410 /* If possible, calculate the layer 4 checksum for the packet.  If this is  */
6411 /* not possible, return without indicating a failure or success but in a    */
6412 /* way that is ditinguishable. This function should only be called by the   */
6413 /* ipf_checkv6sum() for each platform.                                      */
6414 /* ------------------------------------------------------------------------ */
6415 int
6416 ipf_checkl4sum(fr_info_t *fin)
6417 {
6418 	u_short sum, hdrsum, *csump;
6419 	udphdr_t *udp;
6420 	int dosum;
6421 
6422 	/*
6423 	 * If the TCP packet isn't a fragment, isn't too short and otherwise
6424 	 * isn't already considered "bad", then validate the checksum.  If
6425 	 * this check fails then considered the packet to be "bad".
6426 	 */
6427 	if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
6428 		return 1;
6429 
6430 	csump = NULL;
6431 	hdrsum = 0;
6432 	dosum = 0;
6433 	sum = 0;
6434 
6435 	switch (fin->fin_p)
6436 	{
6437 	case IPPROTO_TCP :
6438 		csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
6439 		dosum = 1;
6440 		break;
6441 
6442 	case IPPROTO_UDP :
6443 		udp = fin->fin_dp;
6444 		if (udp->uh_sum != 0) {
6445 			csump = &udp->uh_sum;
6446 			dosum = 1;
6447 		}
6448 		break;
6449 
6450 #ifdef USE_INET6
6451 	case IPPROTO_ICMPV6 :
6452 		csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
6453 		dosum = 1;
6454 		break;
6455 #endif
6456 
6457 	case IPPROTO_ICMP :
6458 		csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
6459 		dosum = 1;
6460 		break;
6461 
6462 	default :
6463 		return 1;
6464 		/*NOTREACHED*/
6465 	}
6466 
6467 	if (csump != NULL)
6468 		hdrsum = *csump;
6469 
6470 	if (dosum) {
6471 		sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
6472 	}
6473 #if !defined(_KERNEL)
6474 	if (sum == hdrsum) {
6475 		FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
6476 	} else {
6477 		FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
6478 	}
6479 #endif
6480 	DT2(l4sums, u_short, hdrsum, u_short, sum);
6481 	if (hdrsum == sum) {
6482 		fin->fin_cksum = FI_CK_SUMOK;
6483 		return 0;
6484 	}
6485 	fin->fin_cksum = FI_CK_BAD;
6486 	return -1;
6487 }
6488 
6489 
6490 /* ------------------------------------------------------------------------ */
6491 /* Function:    ipf_ifpfillv4addr                                           */
6492 /* Returns:     int     - 0 = address update, -1 = address not updated      */
6493 /* Parameters:  atype(I)   - type of network address update to perform      */
6494 /*              sin(I)     - pointer to source of address information       */
6495 /*              mask(I)    - pointer to source of netmask information       */
6496 /*              inp(I)     - pointer to destination address store           */
6497 /*              inpmask(I) - pointer to destination netmask store           */
6498 /*                                                                          */
6499 /* Given a type of network address update (atype) to perform, copy          */
6500 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6501 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6502 /* which case the operation fails.  For all values of atype other than      */
6503 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6504 /* value.                                                                   */
6505 /* ------------------------------------------------------------------------ */
6506 int
6507 ipf_ifpfillv4addr(int atype, struct sockaddr_in *sin, struct sockaddr_in *mask,
6508     struct in_addr *inp, struct in_addr *inpmask)
6509 {
6510 	if (inpmask != NULL && atype != FRI_NETMASKED)
6511 		inpmask->s_addr = 0xffffffff;
6512 
6513 	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6514 		if (atype == FRI_NETMASKED) {
6515 			if (inpmask == NULL)
6516 				return -1;
6517 			inpmask->s_addr = mask->sin_addr.s_addr;
6518 		}
6519 		inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
6520 	} else {
6521 		inp->s_addr = sin->sin_addr.s_addr;
6522 	}
6523 	return 0;
6524 }
6525 
6526 
6527 #ifdef	USE_INET6
6528 /* ------------------------------------------------------------------------ */
6529 /* Function:    ipf_ifpfillv6addr                                           */
6530 /* Returns:     int     - 0 = address update, -1 = address not updated      */
6531 /* Parameters:  atype(I)   - type of network address update to perform      */
6532 /*              sin(I)     - pointer to source of address information       */
6533 /*              mask(I)    - pointer to source of netmask information       */
6534 /*              inp(I)     - pointer to destination address store           */
6535 /*              inpmask(I) - pointer to destination netmask store           */
6536 /*                                                                          */
6537 /* Given a type of network address update (atype) to perform, copy          */
6538 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6539 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6540 /* which case the operation fails.  For all values of atype other than      */
6541 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6542 /* value.                                                                   */
6543 /* ------------------------------------------------------------------------ */
6544 int
6545 ipf_ifpfillv6addr(int atype, struct sockaddr_in6 *sin,
6546     struct sockaddr_in6 *mask, i6addr_t *inp, i6addr_t *inpmask)
6547 {
6548 	i6addr_t *src, *and;
6549 
6550 	src = (i6addr_t *)&sin->sin6_addr;
6551 	and = (i6addr_t *)&mask->sin6_addr;
6552 
6553 	if (inpmask != NULL && atype != FRI_NETMASKED) {
6554 		inpmask->i6[0] = 0xffffffff;
6555 		inpmask->i6[1] = 0xffffffff;
6556 		inpmask->i6[2] = 0xffffffff;
6557 		inpmask->i6[3] = 0xffffffff;
6558 	}
6559 
6560 	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6561 		if (atype == FRI_NETMASKED) {
6562 			if (inpmask == NULL)
6563 				return -1;
6564 			inpmask->i6[0] = and->i6[0];
6565 			inpmask->i6[1] = and->i6[1];
6566 			inpmask->i6[2] = and->i6[2];
6567 			inpmask->i6[3] = and->i6[3];
6568 		}
6569 
6570 		inp->i6[0] = src->i6[0] & and->i6[0];
6571 		inp->i6[1] = src->i6[1] & and->i6[1];
6572 		inp->i6[2] = src->i6[2] & and->i6[2];
6573 		inp->i6[3] = src->i6[3] & and->i6[3];
6574 	} else {
6575 		inp->i6[0] = src->i6[0];
6576 		inp->i6[1] = src->i6[1];
6577 		inp->i6[2] = src->i6[2];
6578 		inp->i6[3] = src->i6[3];
6579 	}
6580 	return 0;
6581 }
6582 #endif
6583 
6584 
6585 /* ------------------------------------------------------------------------ */
6586 /* Function:    ipf_matchtag                                                */
6587 /* Returns:     0 == mismatch, 1 == match.                                  */
6588 /* Parameters:  tag1(I) - pointer to first tag to compare                   */
6589 /*              tag2(I) - pointer to second tag to compare                  */
6590 /*                                                                          */
6591 /* Returns true (non-zero) or false(0) if the two tag structures can be     */
6592 /* considered to be a match or not match, respectively.  The tag is 16      */
6593 /* bytes long (16 characters) but that is overlayed with 4 32bit ints so    */
6594 /* compare the ints instead, for speed. tag1 is the master of the           */
6595 /* comparison.  This function should only be called with both tag1 and tag2 */
6596 /* as non-NULL pointers.                                                    */
6597 /* ------------------------------------------------------------------------ */
6598 int
6599 ipf_matchtag(ipftag_t *tag1, ipftag_t *tag2)
6600 {
6601 	if (tag1 == tag2)
6602 		return 1;
6603 
6604 	if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
6605 		return 1;
6606 
6607 	if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
6608 	    (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
6609 	    (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
6610 	    (tag1->ipt_num[3] == tag2->ipt_num[3]))
6611 		return 1;
6612 	return 0;
6613 }
6614 
6615 
6616 /* ------------------------------------------------------------------------ */
6617 /* Function:    ipf_coalesce                                                */
6618 /* Returns:     1 == success, -1 == failure, 0 == no change                 */
6619 /* Parameters:  fin(I) - pointer to packet information                      */
6620 /*                                                                          */
6621 /* Attempt to get all of the packet data into a single, contiguous buffer.  */
6622 /* If this call returns a failure then the buffers have also been freed.    */
6623 /* ------------------------------------------------------------------------ */
6624 int
6625 ipf_coalesce(fr_info_t *fin)
6626 {
6627 
6628 	if ((fin->fin_flx & FI_COALESCE) != 0)
6629 		return 1;
6630 
6631 	/*
6632 	 * If the mbuf pointers indicate that there is no mbuf to work with,
6633 	 * return but do not indicate success or failure.
6634 	 */
6635 	if (fin->fin_m == NULL || fin->fin_mp == NULL)
6636 		return 0;
6637 
6638 #if defined(_KERNEL)
6639 	if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
6640 		ipf_main_softc_t *softc = fin->fin_main_soft;
6641 
6642 		DT1(frb_coalesce, fr_info_t *, fin);
6643 		LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
6644 # ifdef MENTAT
6645 		FREE_MB_T(*fin->fin_mp);
6646 # endif
6647 		fin->fin_reason = FRB_COALESCE;
6648 		*fin->fin_mp = NULL;
6649 		fin->fin_m = NULL;
6650 		return -1;
6651 	}
6652 #else
6653 	fin = fin;	/* LINT */
6654 #endif
6655 	return 1;
6656 }
6657 
6658 
6659 /*
6660  * The following table lists all of the tunable variables that can be
6661  * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt.  The format of each row
6662  * in the table below is as follows:
6663  *
6664  * pointer to value, name of value, minimum, maximum, size of the value's
6665  *     container, value attribute flags
6666  *
6667  * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
6668  * means the value can only be written to when IPFilter is loaded but disabled.
6669  * The obvious implication is if neither of these are set then the value can be
6670  * changed at any time without harm.
6671  */
6672 
6673 
6674 /* ------------------------------------------------------------------------ */
6675 /* Function:    ipf_tune_findbycookie                                       */
6676 /* Returns:     NULL = search failed, else pointer to tune struct           */
6677 /* Parameters:  cookie(I) - cookie value to search for amongst tuneables    */
6678 /*              next(O)   - pointer to place to store the cookie for the    */
6679 /*                          "next" tuneable, if it is desired.              */
6680 /*                                                                          */
6681 /* This function is used to walk through all of the existing tunables with  */
6682 /* successive calls.  It searches the known tunables for the one which has  */
6683 /* a matching value for "cookie" - ie its address.  When returning a match, */
6684 /* the next one to be found may be returned inside next.                    */
6685 /* ------------------------------------------------------------------------ */
6686 static ipftuneable_t *
6687 ipf_tune_findbycookie(ipftuneable_t **ptop, void *cookie, void **next)
6688 {
6689 	ipftuneable_t *ta, **tap;
6690 
6691 	for (ta = *ptop; ta->ipft_name != NULL; ta++)
6692 		if (ta == cookie) {
6693 			if (next != NULL) {
6694 				/*
6695 				 * If the next entry in the array has a name
6696 				 * present, then return a pointer to it for
6697 				 * where to go next, else return a pointer to
6698 				 * the dynaminc list as a key to search there
6699 				 * next.  This facilitates a weak linking of
6700 				 * the two "lists" together.
6701 				 */
6702 				if ((ta + 1)->ipft_name != NULL)
6703 					*next = ta + 1;
6704 				else
6705 					*next = ptop;
6706 			}
6707 			return ta;
6708 		}
6709 
6710 	for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
6711 		if (tap == cookie) {
6712 			if (next != NULL)
6713 				*next = &ta->ipft_next;
6714 			return ta;
6715 		}
6716 
6717 	if (next != NULL)
6718 		*next = NULL;
6719 	return NULL;
6720 }
6721 
6722 
6723 /* ------------------------------------------------------------------------ */
6724 /* Function:    ipf_tune_findbyname                                         */
6725 /* Returns:     NULL = search failed, else pointer to tune struct           */
6726 /* Parameters:  name(I) - name of the tuneable entry to find.               */
6727 /*                                                                          */
6728 /* Search the static array of tuneables and the list of dynamic tuneables   */
6729 /* for an entry with a matching name.  If we can find one, return a pointer */
6730 /* to the matching structure.                                               */
6731 /* ------------------------------------------------------------------------ */
6732 static ipftuneable_t *
6733 ipf_tune_findbyname(ipftuneable_t *top, const char *name)
6734 {
6735 	ipftuneable_t *ta;
6736 
6737 	for (ta = top; ta != NULL; ta = ta->ipft_next)
6738 		if (!strcmp(ta->ipft_name, name)) {
6739 			return ta;
6740 		}
6741 
6742 	return NULL;
6743 }
6744 
6745 
6746 /* ------------------------------------------------------------------------ */
6747 /* Function:    ipf_tune_add_array                                          */
6748 /* Returns:     int - 0 == success, else failure                            */
6749 /* Parameters:  newtune - pointer to new tune array to add to tuneables     */
6750 /*                                                                          */
6751 /* Appends tune structures from the array passed in (newtune) to the end of */
6752 /* the current list of "dynamic" tuneable parameters.                       */
6753 /* If any entry to be added is already present (by name) then the operation */
6754 /* is aborted - entries that have been added are removed before returning.  */
6755 /* An entry with no name (NULL) is used as the indication that the end of   */
6756 /* the array has been reached.                                              */
6757 /* ------------------------------------------------------------------------ */
6758 int
6759 ipf_tune_add_array(ipf_main_softc_t *softc, ipftuneable_t *newtune)
6760 {
6761 	ipftuneable_t *nt, *dt;
6762 	int error = 0;
6763 
6764 	for (nt = newtune; nt->ipft_name != NULL; nt++) {
6765 		error = ipf_tune_add(softc, nt);
6766 		if (error != 0) {
6767 			for (dt = newtune; dt != nt; dt++) {
6768 				(void) ipf_tune_del(softc, dt);
6769 			}
6770 		}
6771 	}
6772 
6773 	return error;
6774 }
6775 
6776 
6777 /* ------------------------------------------------------------------------ */
6778 /* Function:    ipf_tune_array_link                                         */
6779 /* Returns:     0 == success, -1 == failure                                 */
6780 /* Parameters:  softc(I) - soft context pointerto work with                 */
6781 /*              array(I) - pointer to an array of tuneables                 */
6782 /*                                                                          */
6783 /* Given an array of tunables (array), append them to the current list of   */
6784 /* tuneables for this context (softc->ipf_tuners.) To properly prepare the  */
6785 /* the array for being appended to the list, initialise all of the next     */
6786 /* pointers so we don't need to walk parts of it with ++ and others with    */
6787 /* next. The array is expected to have an entry with a NULL name as the     */
6788 /* terminator. Trying to add an array with no non-NULL names will return as */
6789 /* a failure.                                                               */
6790 /* ------------------------------------------------------------------------ */
6791 int
6792 ipf_tune_array_link(ipf_main_softc_t *softc, ipftuneable_t *array)
6793 {
6794 	ipftuneable_t *t, **p;
6795 
6796 	t = array;
6797 	if (t->ipft_name == NULL)
6798 		return -1;
6799 
6800 	for (; t[1].ipft_name != NULL; t++)
6801 		t[0].ipft_next = &t[1];
6802 	t->ipft_next = NULL;
6803 
6804 	/*
6805 	 * Since a pointer to the last entry isn't kept, we need to find it
6806 	 * each time we want to add new variables to the list.
6807 	 */
6808 	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
6809 		if (t->ipft_name == NULL)
6810 			break;
6811 	*p = array;
6812 
6813 	return 0;
6814 }
6815 
6816 
6817 /* ------------------------------------------------------------------------ */
6818 /* Function:    ipf_tune_array_unlink                                       */
6819 /* Returns:     0 == success, -1 == failure                                 */
6820 /* Parameters:  softc(I) - soft context pointerto work with                 */
6821 /*              array(I) - pointer to an array of tuneables                 */
6822 /*                                                                          */
6823 /* ------------------------------------------------------------------------ */
6824 int
6825 ipf_tune_array_unlink(ipf_main_softc_t *softc, ipftuneable_t *array)
6826 {
6827 	ipftuneable_t *t, **p;
6828 
6829 	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
6830 		if (t == array)
6831 			break;
6832 	if (t == NULL)
6833 		return -1;
6834 
6835 	for (; t[1].ipft_name != NULL; t++)
6836 		;
6837 
6838 	*p = t->ipft_next;
6839 
6840 	return 0;
6841 }
6842 
6843 
6844 /* ------------------------------------------------------------------------ */
6845 /* Function:   ipf_tune_array_copy                                          */
6846 /* Returns:    NULL = failure, else pointer to new array                    */
6847 /* Parameters: base(I)     - pointer to structure base                      */
6848 /*             size(I)     - size of the array at template                  */
6849 /*             template(I) - original array to copy                         */
6850 /*                                                                          */
6851 /* Allocate memory for a new set of tuneable values and copy everything     */
6852 /* from template into the new region of memory.  The new region is full of  */
6853 /* uninitialised pointers (ipft_next) so set them up.  Now, ipftp_offset... */
6854 /*                                                                          */
6855 /* NOTE: the following assumes that sizeof(long) == sizeof(void *)          */
6856 /* In the array template, ipftp_offset is the offset (in bytes) of the      */
6857 /* location of the tuneable value inside the structure pointed to by base.  */
6858 /* As ipftp_offset is a union over the pointers to the tuneable values, if  */
6859 /* we add base to the copy's ipftp_offset, copy ends up with a pointer in   */
6860 /* ipftp_void that points to the stored value.                              */
6861 /* ------------------------------------------------------------------------ */
6862 ipftuneable_t *
6863 ipf_tune_array_copy(void *base, size_t size, ipftuneable_t *template)
6864 {
6865 	ipftuneable_t *copy;
6866 	int i;
6867 
6868 
6869 	KMALLOCS(copy, ipftuneable_t *, size);
6870 	if (copy == NULL) {
6871 		return NULL;
6872 	}
6873 	bcopy(template, copy, size);
6874 
6875 	for (i = 0; copy[i].ipft_name; i++) {
6876 		copy[i].ipft_una.ipftp_offset += (u_long)base;
6877 		copy[i].ipft_next = copy + i + 1;
6878 	}
6879 
6880 	return copy;
6881 }
6882 
6883 
6884 /* ------------------------------------------------------------------------ */
6885 /* Function:    ipf_tune_add                                                */
6886 /* Returns:     int - 0 == success, else failure                            */
6887 /* Parameters:  newtune - pointer to new tune entry to add to tuneables     */
6888 /*                                                                          */
6889 /* Appends tune structures from the array passed in (newtune) to the end of */
6890 /* the current list of "dynamic" tuneable parameters.  Once added, the      */
6891 /* owner of the object is not expected to ever change "ipft_next".          */
6892 /* ------------------------------------------------------------------------ */
6893 int
6894 ipf_tune_add(ipf_main_softc_t *softc, ipftuneable_t *newtune)
6895 {
6896 	ipftuneable_t *ta, **tap;
6897 
6898 	ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
6899 	if (ta != NULL) {
6900 		IPFERROR(74);
6901 		return EEXIST;
6902 	}
6903 
6904 	for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
6905 		;
6906 
6907 	newtune->ipft_next = NULL;
6908 	*tap = newtune;
6909 	return 0;
6910 }
6911 
6912 
6913 /* ------------------------------------------------------------------------ */
6914 /* Function:    ipf_tune_del                                                */
6915 /* Returns:     int - 0 == success, else failure                            */
6916 /* Parameters:  oldtune - pointer to tune entry to remove from the list of  */
6917 /*                        current dynamic tuneables                         */
6918 /*                                                                          */
6919 /* Search for the tune structure, by pointer, in the list of those that are */
6920 /* dynamically added at run time.  If found, adjust the list so that this   */
6921 /* structure is no longer part of it.                                       */
6922 /* ------------------------------------------------------------------------ */
6923 int
6924 ipf_tune_del(ipf_main_softc_t *softc, ipftuneable_t *oldtune)
6925 {
6926 	ipftuneable_t *ta, **tap;
6927 	int error = 0;
6928 
6929 	for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
6930 	     tap = &ta->ipft_next) {
6931 		if (ta == oldtune) {
6932 			*tap = oldtune->ipft_next;
6933 			oldtune->ipft_next = NULL;
6934 			break;
6935 		}
6936 	}
6937 
6938 	if (ta == NULL) {
6939 		error = ESRCH;
6940 		IPFERROR(75);
6941 	}
6942 	return error;
6943 }
6944 
6945 
6946 /* ------------------------------------------------------------------------ */
6947 /* Function:    ipf_tune_del_array                                          */
6948 /* Returns:     int - 0 == success, else failure                            */
6949 /* Parameters:  oldtune - pointer to tuneables array                        */
6950 /*                                                                          */
6951 /* Remove each tuneable entry in the array from the list of "dynamic"       */
6952 /* tunables.  If one entry should fail to be found, an error will be        */
6953 /* returned and no further ones removed.                                    */
6954 /* An entry with a NULL name is used as the indicator of the last entry in  */
6955 /* the array.                                                               */
6956 /* ------------------------------------------------------------------------ */
6957 int
6958 ipf_tune_del_array(ipf_main_softc_t *softc, ipftuneable_t *oldtune)
6959 {
6960 	ipftuneable_t *ot;
6961 	int error = 0;
6962 
6963 	for (ot = oldtune; ot->ipft_name != NULL; ot++) {
6964 		error = ipf_tune_del(softc, ot);
6965 		if (error != 0)
6966 			break;
6967 	}
6968 
6969 	return error;
6970 
6971 }
6972 
6973 
6974 /* ------------------------------------------------------------------------ */
6975 /* Function:    ipf_tune                                                    */
6976 /* Returns:     int - 0 == success, else failure                            */
6977 /* Parameters:  cmd(I)  - ioctl command number                              */
6978 /*              data(I) - pointer to ioctl data structure                   */
6979 /*                                                                          */
6980 /* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET.  These  */
6981 /* three ioctls provide the means to access and control global variables    */
6982 /* within IPFilter, allowing (for example) timeouts and table sizes to be   */
6983 /* changed without rebooting, reloading or recompiling.  The initialisation */
6984 /* and 'destruction' routines of the various components of ipfilter are all */
6985 /* each responsible for handling their own values being too big.            */
6986 /* ------------------------------------------------------------------------ */
6987 int
6988 ipf_ipftune(ipf_main_softc_t *softc, ioctlcmd_t cmd, void *data)
6989 {
6990 	ipftuneable_t *ta;
6991 	ipftune_t tu;
6992 	void *cookie;
6993 	int error;
6994 
6995 	error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
6996 	if (error != 0)
6997 		return error;
6998 
6999 	tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
7000 	cookie = tu.ipft_cookie;
7001 	ta = NULL;
7002 
7003 	switch (cmd)
7004 	{
7005 	case SIOCIPFGETNEXT :
7006 		/*
7007 		 * If cookie is non-NULL, assume it to be a pointer to the last
7008 		 * entry we looked at, so find it (if possible) and return a
7009 		 * pointer to the next one after it.  The last entry in the
7010 		 * the table is a NULL entry, so when we get to it, set cookie
7011 		 * to NULL and return that, indicating end of list, erstwhile
7012 		 * if we come in with cookie set to NULL, we are starting anew
7013 		 * at the front of the list.
7014 		 */
7015 		if (cookie != NULL) {
7016 			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7017 						   cookie, &tu.ipft_cookie);
7018 		} else {
7019 			ta = softc->ipf_tuners;
7020 			tu.ipft_cookie = ta + 1;
7021 		}
7022 		if (ta != NULL) {
7023 			/*
7024 			 * Entry found, but does the data pointed to by that
7025 			 * row fit in what we can return?
7026 			 */
7027 			if (ta->ipft_sz > sizeof(tu.ipft_un)) {
7028 				IPFERROR(76);
7029 				return EINVAL;
7030 			}
7031 
7032 			tu.ipft_vlong = 0;
7033 			if (ta->ipft_sz == sizeof(u_long))
7034 				tu.ipft_vlong = *ta->ipft_plong;
7035 			else if (ta->ipft_sz == sizeof(u_int))
7036 				tu.ipft_vint = *ta->ipft_pint;
7037 			else if (ta->ipft_sz == sizeof(u_short))
7038 				tu.ipft_vshort = *ta->ipft_pshort;
7039 			else if (ta->ipft_sz == sizeof(u_char))
7040 				tu.ipft_vchar = *ta->ipft_pchar;
7041 
7042 			tu.ipft_sz = ta->ipft_sz;
7043 			tu.ipft_min = ta->ipft_min;
7044 			tu.ipft_max = ta->ipft_max;
7045 			tu.ipft_flags = ta->ipft_flags;
7046 			bcopy(ta->ipft_name, tu.ipft_name,
7047 			      MIN(sizeof(tu.ipft_name),
7048 				  strlen(ta->ipft_name) + 1));
7049 		}
7050 		error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7051 		break;
7052 
7053 	case SIOCIPFGET :
7054 	case SIOCIPFSET :
7055 		/*
7056 		 * Search by name or by cookie value for a particular entry
7057 		 * in the tuning paramter table.
7058 		 */
7059 		IPFERROR(77);
7060 		error = ESRCH;
7061 		if (cookie != NULL) {
7062 			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7063 						   cookie, NULL);
7064 			if (ta != NULL)
7065 				error = 0;
7066 		} else if (tu.ipft_name[0] != '\0') {
7067 			ta = ipf_tune_findbyname(softc->ipf_tuners,
7068 						 tu.ipft_name);
7069 			if (ta != NULL)
7070 				error = 0;
7071 		}
7072 		if (error != 0)
7073 			break;
7074 
7075 		if (cmd == (ioctlcmd_t)SIOCIPFGET) {
7076 			/*
7077 			 * Fetch the tuning parameters for a particular value
7078 			 */
7079 			tu.ipft_vlong = 0;
7080 			if (ta->ipft_sz == sizeof(u_long))
7081 				tu.ipft_vlong = *ta->ipft_plong;
7082 			else if (ta->ipft_sz == sizeof(u_int))
7083 				tu.ipft_vint = *ta->ipft_pint;
7084 			else if (ta->ipft_sz == sizeof(u_short))
7085 				tu.ipft_vshort = *ta->ipft_pshort;
7086 			else if (ta->ipft_sz == sizeof(u_char))
7087 				tu.ipft_vchar = *ta->ipft_pchar;
7088 			tu.ipft_cookie = ta;
7089 			tu.ipft_sz = ta->ipft_sz;
7090 			tu.ipft_min = ta->ipft_min;
7091 			tu.ipft_max = ta->ipft_max;
7092 			tu.ipft_flags = ta->ipft_flags;
7093 			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7094 
7095 		} else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
7096 			/*
7097 			 * Set an internal parameter.  The hard part here is
7098 			 * getting the new value safely and correctly out of
7099 			 * the kernel (given we only know its size, not type.)
7100 			 */
7101 			u_long in;
7102 
7103 			if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
7104 			    (softc->ipf_running > 0)) {
7105 				IPFERROR(78);
7106 				error = EBUSY;
7107 				break;
7108 			}
7109 
7110 			in = tu.ipft_vlong;
7111 			if (in < ta->ipft_min || in > ta->ipft_max) {
7112 				IPFERROR(79);
7113 				error = EINVAL;
7114 				break;
7115 			}
7116 
7117 			if (ta->ipft_func != NULL) {
7118 				SPL_INT(s);
7119 
7120 				SPL_NET(s);
7121 				error = (*ta->ipft_func)(softc, ta,
7122 							 &tu.ipft_un);
7123 				SPL_X(s);
7124 
7125 			} else if (ta->ipft_sz == sizeof(u_long)) {
7126 				tu.ipft_vlong = *ta->ipft_plong;
7127 				*ta->ipft_plong = in;
7128 
7129 			} else if (ta->ipft_sz == sizeof(u_int)) {
7130 				tu.ipft_vint = *ta->ipft_pint;
7131 				*ta->ipft_pint = (u_int)(in & 0xffffffff);
7132 
7133 			} else if (ta->ipft_sz == sizeof(u_short)) {
7134 				tu.ipft_vshort = *ta->ipft_pshort;
7135 				*ta->ipft_pshort = (u_short)(in & 0xffff);
7136 
7137 			} else if (ta->ipft_sz == sizeof(u_char)) {
7138 				tu.ipft_vchar = *ta->ipft_pchar;
7139 				*ta->ipft_pchar = (u_char)(in & 0xff);
7140 			}
7141 			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7142 		}
7143 		break;
7144 
7145 	default :
7146 		IPFERROR(80);
7147 		error = EINVAL;
7148 		break;
7149 	}
7150 
7151 	return error;
7152 }
7153 
7154 
7155 /* ------------------------------------------------------------------------ */
7156 /* Function:    ipf_zerostats                                               */
7157 /* Returns:     int - 0 = success, else failure                             */
7158 /* Parameters:  data(O) - pointer to pointer for copying data back to       */
7159 /*                                                                          */
7160 /* Copies the current statistics out to userspace and then zero's the       */
7161 /* current ones in the kernel. The lock is only held across the bzero() as  */
7162 /* the copyout may result in paging (ie network activity.)                  */
7163 /* ------------------------------------------------------------------------ */
7164 int
7165 ipf_zerostats(ipf_main_softc_t *softc, void *data)
7166 {
7167 	friostat_t fio;
7168 	ipfobj_t obj;
7169 	int error;
7170 
7171 	error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
7172 	if (error != 0)
7173 		return error;
7174 	ipf_getstat(softc, &fio, obj.ipfo_rev);
7175 	error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
7176 	if (error != 0)
7177 		return error;
7178 
7179 	WRITE_ENTER(&softc->ipf_mutex);
7180 	bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
7181 	RWLOCK_EXIT(&softc->ipf_mutex);
7182 
7183 	return 0;
7184 }
7185 
7186 
7187 /* ------------------------------------------------------------------------ */
7188 /* Function:    ipf_resolvedest                                             */
7189 /* Returns:     Nil                                                         */
7190 /* Parameters:  softc(I) - pointer to soft context main structure           */
7191 /*              base(I)  - where strings are stored                         */
7192 /*              fdp(IO)  - pointer to destination information to resolve    */
7193 /*              v(I)     - IP protocol version to match                     */
7194 /*                                                                          */
7195 /* Looks up an interface name in the frdest structure pointed to by fdp and */
7196 /* if a matching name can be found for the particular IP protocol version   */
7197 /* then store the interface pointer in the frdest struct.  If no match is   */
7198 /* found, then set the interface pointer to be -1 as NULL is considered to  */
7199 /* indicate there is no information at all in the structure.                */
7200 /* ------------------------------------------------------------------------ */
7201 int
7202 ipf_resolvedest(ipf_main_softc_t *softc, char *base, frdest_t *fdp, int v)
7203 {
7204 	int errval = 0;
7205 	void *ifp;
7206 
7207 	ifp = NULL;
7208 
7209 	if (fdp->fd_name != -1) {
7210 		if (fdp->fd_type == FRD_DSTLIST) {
7211 			ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
7212 						  IPLT_DSTLIST,
7213 						  base + fdp->fd_name,
7214 						  NULL);
7215 			if (ifp == NULL) {
7216 				IPFERROR(144);
7217 				errval = ESRCH;
7218 			}
7219 		} else {
7220 			ifp = GETIFP(base + fdp->fd_name, v);
7221 			if (ifp == NULL)
7222 				ifp = (void *)-1;
7223 			if ((ifp != NULL) && (ifp != (void *)-1))
7224 				fdp->fd_local = ipf_deliverlocal(softc, v, ifp,
7225 								 &fdp->fd_ip6);
7226 		}
7227 	}
7228 	fdp->fd_ptr = ifp;
7229 
7230 	return errval;
7231 }
7232 
7233 
7234 /* ------------------------------------------------------------------------ */
7235 /* Function:    ipf_resolvenic                                              */
7236 /* Returns:     void* - NULL = wildcard name, -1 = failed to find NIC, else */
7237 /*                      pointer to interface structure for NIC              */
7238 /* Parameters:  softc(I)- pointer to soft context main structure            */
7239 /*              name(I) - complete interface name                           */
7240 /*              v(I)    - IP protocol version                               */
7241 /*                                                                          */
7242 /* Look for a network interface structure that firstly has a matching name  */
7243 /* to that passed in and that is also being used for that IP protocol       */
7244 /* version (necessary on some platforms where there are separate listings   */
7245 /* for both IPv4 and IPv6 on the same physical NIC.                         */
7246 /*                                                                          */
7247 /* ------------------------------------------------------------------------ */
7248 void *
7249 ipf_resolvenic(ipf_main_softc_t *softc, char *name, int v)
7250 {
7251 	void *nic;
7252 
7253 	softc = softc;	/* gcc -Wextra */
7254 	if (name[0] == '\0')
7255 		return NULL;
7256 
7257 	if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
7258 		return NULL;
7259 	}
7260 
7261 	nic = GETIFP(name, v);
7262 	if (nic == NULL)
7263 		nic = (void *)-1;
7264 	return nic;
7265 }
7266 
7267 
7268 /* ------------------------------------------------------------------------ */
7269 /* Function:    ipf_token_expire                                            */
7270 /* Returns:     None.                                                       */
7271 /* Parameters:  softc(I) - pointer to soft context main structure           */
7272 /*                                                                          */
7273 /* This function is run every ipf tick to see if there are any tokens that  */
7274 /* have been held for too long and need to be freed up.                     */
7275 /* ------------------------------------------------------------------------ */
7276 void
7277 ipf_token_expire(ipf_main_softc_t *softc)
7278 {
7279 	ipftoken_t *it;
7280 
7281 	WRITE_ENTER(&softc->ipf_tokens);
7282 	while ((it = softc->ipf_token_head) != NULL) {
7283 		if (it->ipt_die > softc->ipf_ticks)
7284 			break;
7285 
7286 		ipf_token_deref(softc, it);
7287 	}
7288 	RWLOCK_EXIT(&softc->ipf_tokens);
7289 }
7290 
7291 
7292 /* ------------------------------------------------------------------------ */
7293 /* Function:    ipf_token_flush                                             */
7294 /* Returns:     None.                                                       */
7295 /* Parameters:  softc(I) - pointer to soft context main structure           */
7296 /*                                                                          */
7297 /* Loop through all of the existing tokens and call deref to see if they    */
7298 /* can be freed. Normally a function like this might just loop on           */
7299 /* ipf_token_head but there is a chance that a token might have a ref count */
7300 /* of greater than one and in that case the the reference would drop twice  */
7301 /* by code that is only entitled to drop it once.                           */
7302 /* ------------------------------------------------------------------------ */
7303 static void
7304 ipf_token_flush(ipf_main_softc_t *softc)
7305 {
7306 	ipftoken_t *it, *next;
7307 
7308 	WRITE_ENTER(&softc->ipf_tokens);
7309 	for (it = softc->ipf_token_head; it != NULL; it = next) {
7310 		next = it->ipt_next;
7311 		(void) ipf_token_deref(softc, it);
7312 	}
7313 	RWLOCK_EXIT(&softc->ipf_tokens);
7314 }
7315 
7316 
7317 /* ------------------------------------------------------------------------ */
7318 /* Function:    ipf_token_del                                               */
7319 /* Returns:     int     - 0 = success, else error                           */
7320 /* Parameters:  softc(I)- pointer to soft context main structure            */
7321 /*              type(I) - the token type to match                           */
7322 /*              uid(I)  - uid owning the token                              */
7323 /*              ptr(I)  - context pointer for the token                     */
7324 /*                                                                          */
7325 /* This function looks for a a token in the current list that matches up    */
7326 /* the fields (type, uid, ptr).  If none is found, ESRCH is returned, else  */
7327 /* call ipf_token_dewref() to remove it from the list. In the event that    */
7328 /* the token has a reference held elsewhere, setting ipt_complete to 2      */
7329 /* enables debugging to distinguish between the two paths that ultimately   */
7330 /* lead to a token to be deleted.                                           */
7331 /* ------------------------------------------------------------------------ */
7332 int
7333 ipf_token_del(ipf_main_softc_t *softc, int type, int uid, void *ptr)
7334 {
7335 	ipftoken_t *it;
7336 	int error;
7337 
7338 	IPFERROR(82);
7339 	error = ESRCH;
7340 
7341 	WRITE_ENTER(&softc->ipf_tokens);
7342 	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7343 		if (ptr == it->ipt_ctx && type == it->ipt_type &&
7344 		    uid == it->ipt_uid) {
7345 			it->ipt_complete = 2;
7346 			ipf_token_deref(softc, it);
7347 			error = 0;
7348 			break;
7349 		}
7350 	}
7351 	RWLOCK_EXIT(&softc->ipf_tokens);
7352 
7353 	return error;
7354 }
7355 
7356 
7357 /* ------------------------------------------------------------------------ */
7358 /* Function:    ipf_token_mark_complete                                     */
7359 /* Returns:     None.                                                       */
7360 /* Parameters:  token(I) - pointer to token structure                       */
7361 /*                                                                          */
7362 /* Mark a token as being ineligable for being found with ipf_token_find.    */
7363 /* ------------------------------------------------------------------------ */
7364 void
7365 ipf_token_mark_complete(ipftoken_t *token)
7366 {
7367 	if (token->ipt_complete == 0)
7368 		token->ipt_complete = 1;
7369 }
7370 
7371 
7372 /* ------------------------------------------------------------------------ */
7373 /* Function:    ipf_token_find                                               */
7374 /* Returns:     ipftoken_t * - NULL if no memory, else pointer to token     */
7375 /* Parameters:  softc(I)- pointer to soft context main structure            */
7376 /*              type(I) - the token type to match                           */
7377 /*              uid(I)  - uid owning the token                              */
7378 /*              ptr(I)  - context pointer for the token                     */
7379 /*                                                                          */
7380 /* This function looks for a live token in the list of current tokens that  */
7381 /* matches the tuple (type, uid, ptr).  If one cannot be found then one is  */
7382 /* allocated.  If one is found then it is moved to the top of the list of   */
7383 /* currently active tokens.                                                 */
7384 /* ------------------------------------------------------------------------ */
7385 ipftoken_t *
7386 ipf_token_find(ipf_main_softc_t *softc, int type, int uid, void *ptr)
7387 {
7388 	ipftoken_t *it, *new;
7389 
7390 	KMALLOC(new, ipftoken_t *);
7391 	if (new != NULL)
7392 		bzero((char *)new, sizeof(*new));
7393 
7394 	WRITE_ENTER(&softc->ipf_tokens);
7395 	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7396 		if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
7397 		    (uid == it->ipt_uid) && (it->ipt_complete < 2))
7398 			break;
7399 	}
7400 
7401 	if (it == NULL) {
7402 		it = new;
7403 		new = NULL;
7404 		if (it == NULL) {
7405 			RWLOCK_EXIT(&softc->ipf_tokens);
7406 			return NULL;
7407 		}
7408 		it->ipt_ctx = ptr;
7409 		it->ipt_uid = uid;
7410 		it->ipt_type = type;
7411 		it->ipt_ref = 1;
7412 	} else {
7413 		if (new != NULL) {
7414 			KFREE(new);
7415 			new = NULL;
7416 		}
7417 
7418 		if (it->ipt_complete > 0)
7419 			it = NULL;
7420 		else
7421 			ipf_token_unlink(softc, it);
7422 	}
7423 
7424 	if (it != NULL) {
7425 		it->ipt_pnext = softc->ipf_token_tail;
7426 		*softc->ipf_token_tail = it;
7427 		softc->ipf_token_tail = &it->ipt_next;
7428 		it->ipt_next = NULL;
7429 		it->ipt_ref++;
7430 
7431 		it->ipt_die = softc->ipf_ticks + 20;
7432 	}
7433 
7434 	RWLOCK_EXIT(&softc->ipf_tokens);
7435 
7436 	return it;
7437 }
7438 
7439 
7440 /* ------------------------------------------------------------------------ */
7441 /* Function:    ipf_token_unlink                                            */
7442 /* Returns:     None.                                                       */
7443 /* Parameters:  softc(I) - pointer to soft context main structure           */
7444 /*              token(I) - pointer to token structure                       */
7445 /* Write Locks: ipf_tokens                                                  */
7446 /*                                                                          */
7447 /* This function unlinks a token structure from the linked list of tokens   */
7448 /* that "own" it.  The head pointer never needs to be explicitly adjusted   */
7449 /* but the tail does due to the linked list implementation.                 */
7450 /* ------------------------------------------------------------------------ */
7451 static void
7452 ipf_token_unlink(ipf_main_softc_t *softc, ipftoken_t *token)
7453 {
7454 
7455 	if (softc->ipf_token_tail == &token->ipt_next)
7456 		softc->ipf_token_tail = token->ipt_pnext;
7457 
7458 	*token->ipt_pnext = token->ipt_next;
7459 	if (token->ipt_next != NULL)
7460 		token->ipt_next->ipt_pnext = token->ipt_pnext;
7461 	token->ipt_next = NULL;
7462 	token->ipt_pnext = NULL;
7463 }
7464 
7465 
7466 /* ------------------------------------------------------------------------ */
7467 /* Function:    ipf_token_deref                                             */
7468 /* Returns:     int      - 0 == token freed, else reference count           */
7469 /* Parameters:  softc(I) - pointer to soft context main structure           */
7470 /*              token(I) - pointer to token structure                       */
7471 /* Write Locks: ipf_tokens                                                  */
7472 /*                                                                          */
7473 /* Drop the reference count on the token structure and if it drops to zero, */
7474 /* call the dereference function for the token type because it is then      */
7475 /* possible to free the token data structure.                               */
7476 /* ------------------------------------------------------------------------ */
7477 int
7478 ipf_token_deref(ipf_main_softc_t *softc, ipftoken_t *token)
7479 {
7480 	void *data, **datap;
7481 
7482 	ASSERT(token->ipt_ref > 0);
7483 	token->ipt_ref--;
7484 	if (token->ipt_ref > 0)
7485 		return token->ipt_ref;
7486 
7487 	data = token->ipt_data;
7488 	datap = &data;
7489 
7490 	if ((data != NULL) && (data != (void *)-1)) {
7491 		switch (token->ipt_type)
7492 		{
7493 		case IPFGENITER_IPF :
7494 			(void) ipf_derefrule(softc, (frentry_t **)datap);
7495 			break;
7496 		case IPFGENITER_IPNAT :
7497 			WRITE_ENTER(&softc->ipf_nat);
7498 			ipf_nat_rule_deref(softc, (ipnat_t **)datap);
7499 			RWLOCK_EXIT(&softc->ipf_nat);
7500 			break;
7501 		case IPFGENITER_NAT :
7502 			ipf_nat_deref(softc, (nat_t **)datap);
7503 			break;
7504 		case IPFGENITER_STATE :
7505 			ipf_state_deref(softc, (ipstate_t **)datap);
7506 			break;
7507 		case IPFGENITER_FRAG :
7508 			ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
7509 			break;
7510 		case IPFGENITER_NATFRAG :
7511 			ipf_frag_nat_deref(softc, (ipfr_t **)datap);
7512 			break;
7513 		case IPFGENITER_HOSTMAP :
7514 			WRITE_ENTER(&softc->ipf_nat);
7515 			ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
7516 			RWLOCK_EXIT(&softc->ipf_nat);
7517 			break;
7518 		default :
7519 			ipf_lookup_iterderef(softc, token->ipt_type, data);
7520 			break;
7521 		}
7522 	}
7523 
7524 	ipf_token_unlink(softc, token);
7525 	KFREE(token);
7526 	return 0;
7527 }
7528 
7529 
7530 /* ------------------------------------------------------------------------ */
7531 /* Function:    ipf_nextrule                                                */
7532 /* Returns:     frentry_t * - NULL == no more rules, else pointer to next   */
7533 /* Parameters:  softc(I)    - pointer to soft context main structure        */
7534 /*              fr(I)       - pointer to filter rule                        */
7535 /*              out(I)      - 1 == out rules, 0 == input rules              */
7536 /*                                                                          */
7537 /* Starting with "fr", find the next rule to visit. This includes visiting  */
7538 /* the list of rule groups if either fr is NULL (empty list) or it is the   */
7539 /* last rule in the list. When walking rule lists, it is either input or    */
7540 /* output rules that are returned, never both.                              */
7541 /* ------------------------------------------------------------------------ */
7542 static frentry_t *
7543 ipf_nextrule(ipf_main_softc_t *softc, int active, int unit,
7544     frentry_t *fr, int out)
7545 {
7546 	frentry_t *next;
7547 	frgroup_t *fg;
7548 
7549 	if (fr != NULL && fr->fr_group != -1) {
7550 		fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
7551 				   unit, active, NULL);
7552 		if (fg != NULL)
7553 			fg = fg->fg_next;
7554 	} else {
7555 		fg = softc->ipf_groups[unit][active];
7556 	}
7557 
7558 	while (fg != NULL) {
7559 		next = fg->fg_start;
7560 		while (next != NULL) {
7561 			if (out) {
7562 				if (next->fr_flags & FR_OUTQUE)
7563 					return next;
7564 			} else if (next->fr_flags & FR_INQUE) {
7565 				return next;
7566 			}
7567 			next = next->fr_next;
7568 		}
7569 		if (next == NULL)
7570 			fg = fg->fg_next;
7571 	}
7572 
7573 	return NULL;
7574 }
7575 
7576 /* ------------------------------------------------------------------------ */
7577 /* Function:    ipf_getnextrule                                             */
7578 /* Returns:     int - 0 = success, else error                               */
7579 /* Parameters:  softc(I)- pointer to soft context main structure            */
7580 /*              t(I)   - pointer to destination information to resolve      */
7581 /*              ptr(I) - pointer to ipfobj_t to copyin from user space      */
7582 /*                                                                          */
7583 /* This function's first job is to bring in the ipfruleiter_t structure via */
7584 /* the ipfobj_t structure to determine what should be the next rule to      */
7585 /* return. Once the ipfruleiter_t has been brought in, it then tries to     */
7586 /* find the 'next rule'.  This may include searching rule group lists or    */
7587 /* just be as simple as looking at the 'next' field in the rule structure.  */
7588 /* When we have found the rule to return, increase its reference count and  */
7589 /* if we used an existing rule to get here, decrease its reference count.   */
7590 /* ------------------------------------------------------------------------ */
7591 int
7592 ipf_getnextrule(ipf_main_softc_t *softc, ipftoken_t *t, void *ptr)
7593 {
7594 	frentry_t *fr, *next, zero;
7595 	ipfruleiter_t it;
7596 	int error, out;
7597 	frgroup_t *fg;
7598 	ipfobj_t obj;
7599 	int predict;
7600 	char *dst;
7601 	int unit;
7602 
7603 	if (t == NULL || ptr == NULL) {
7604 		IPFERROR(84);
7605 		return EFAULT;
7606 	}
7607 
7608 	error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
7609 	if (error != 0)
7610 		return error;
7611 
7612 	if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
7613 		IPFERROR(85);
7614 		return EINVAL;
7615 	}
7616 	if ((it.iri_active != 0) && (it.iri_active != 1)) {
7617 		IPFERROR(86);
7618 		return EINVAL;
7619 	}
7620 	if (it.iri_nrules == 0) {
7621 		IPFERROR(87);
7622 		return ENOSPC;
7623 	}
7624 	if (it.iri_rule == NULL) {
7625 		IPFERROR(88);
7626 		return EFAULT;
7627 	}
7628 
7629 	fg = NULL;
7630 	fr = t->ipt_data;
7631 	if ((it.iri_inout & F_OUT) != 0)
7632 		out = 1;
7633 	else
7634 		out = 0;
7635 	if ((it.iri_inout & F_ACIN) != 0)
7636 		unit = IPL_LOGCOUNT;
7637 	else
7638 		unit = IPL_LOGIPF;
7639 
7640 	READ_ENTER(&softc->ipf_mutex);
7641 	if (fr == NULL) {
7642 		if (*it.iri_group == '\0') {
7643 			if (unit == IPL_LOGCOUNT) {
7644 				next = softc->ipf_acct[out][it.iri_active];
7645 			} else {
7646 				next = softc->ipf_rules[out][it.iri_active];
7647 			}
7648 			if (next == NULL)
7649 				next = ipf_nextrule(softc, it.iri_active,
7650 						    unit, NULL, out);
7651 		} else {
7652 			fg = ipf_findgroup(softc, it.iri_group, unit,
7653 					   it.iri_active, NULL);
7654 			if (fg != NULL)
7655 				next = fg->fg_start;
7656 			else
7657 				next = NULL;
7658 		}
7659 	} else {
7660 		next = fr->fr_next;
7661 		if (next == NULL)
7662 			next = ipf_nextrule(softc, it.iri_active, unit,
7663 					    fr, out);
7664 	}
7665 
7666 	if (next != NULL && next->fr_next != NULL)
7667 		predict = 1;
7668 	else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
7669 		predict = 1;
7670 	else
7671 		predict = 0;
7672 
7673 	if (fr != NULL)
7674 		(void) ipf_derefrule(softc, &fr);
7675 
7676 	obj.ipfo_type = IPFOBJ_FRENTRY;
7677 	dst = (char *)it.iri_rule;
7678 
7679 	if (next != NULL) {
7680 		obj.ipfo_size = next->fr_size;
7681 		MUTEX_ENTER(&next->fr_lock);
7682 		next->fr_ref++;
7683 		MUTEX_EXIT(&next->fr_lock);
7684 		t->ipt_data = next;
7685 	} else {
7686 		obj.ipfo_size = sizeof(frentry_t);
7687 		bzero(&zero, sizeof(zero));
7688 		next = &zero;
7689 		t->ipt_data = NULL;
7690 	}
7691 	it.iri_rule = predict ? next : NULL;
7692 	if (predict == 0)
7693 		ipf_token_mark_complete(t);
7694 
7695 	RWLOCK_EXIT(&softc->ipf_mutex);
7696 
7697 	obj.ipfo_ptr = dst;
7698 	error = ipf_outobjk(softc, &obj, next);
7699 	if (error == 0 && t->ipt_data != NULL) {
7700 		dst += obj.ipfo_size;
7701 		if (next->fr_data != NULL) {
7702 			ipfobj_t dobj;
7703 
7704 			if (next->fr_type == FR_T_IPFEXPR)
7705 				dobj.ipfo_type = IPFOBJ_IPFEXPR;
7706 			else
7707 				dobj.ipfo_type = IPFOBJ_FRIPF;
7708 			dobj.ipfo_size = next->fr_dsize;
7709 			dobj.ipfo_rev = obj.ipfo_rev;
7710 			dobj.ipfo_ptr = dst;
7711 			error = ipf_outobjk(softc, &dobj, next->fr_data);
7712 		}
7713 	}
7714 
7715 	if ((fr != NULL) && (next == &zero))
7716 		(void) ipf_derefrule(softc, &fr);
7717 
7718 	return error;
7719 }
7720 
7721 
7722 /* ------------------------------------------------------------------------ */
7723 /* Function:    ipf_frruleiter                                              */
7724 /* Returns:     int - 0 = success, else error                               */
7725 /* Parameters:  softc(I)- pointer to soft context main structure            */
7726 /*              data(I) - the token type to match                           */
7727 /*              uid(I)  - uid owning the token                              */
7728 /*              ptr(I)  - context pointer for the token                     */
7729 /*                                                                          */
7730 /* This function serves as a stepping stone between ipf_ipf_ioctl and       */
7731 /* ipf_getnextrule.  It's role is to find the right token in the kernel for */
7732 /* the process doing the ioctl and use that to ask for the next rule.       */
7733 /* ------------------------------------------------------------------------ */
7734 static int
7735 ipf_frruleiter(ipf_main_softc_t *softc, void *data, int uid, void *ctx)
7736 {
7737 	ipftoken_t *token;
7738 	ipfruleiter_t it;
7739 	ipfobj_t obj;
7740 	int error;
7741 
7742 	token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
7743 	if (token != NULL) {
7744 		error = ipf_getnextrule(softc, token, data);
7745 		WRITE_ENTER(&softc->ipf_tokens);
7746 		ipf_token_deref(softc, token);
7747 		RWLOCK_EXIT(&softc->ipf_tokens);
7748 	} else {
7749 		error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
7750 		if (error != 0)
7751 			return error;
7752 		it.iri_rule = NULL;
7753 		error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
7754 	}
7755 
7756 	return error;
7757 }
7758 
7759 
7760 /* ------------------------------------------------------------------------ */
7761 /* Function:    ipf_geniter                                                 */
7762 /* Returns:     int - 0 = success, else error                               */
7763 /* Parameters:  softc(I) - pointer to soft context main structure           */
7764 /*              token(I) - pointer to ipftoken_t structure                  */
7765 /*              itp(I)   - pointer to iterator data                         */
7766 /*                                                                          */
7767 /* Decide which iterator function to call using information passed through  */
7768 /* the ipfgeniter_t structure at itp.                                       */
7769 /* ------------------------------------------------------------------------ */
7770 static int
7771 ipf_geniter(ipf_main_softc_t *softc, ipftoken_t *token, ipfgeniter_t *itp)
7772 {
7773 	int error;
7774 
7775 	switch (itp->igi_type)
7776 	{
7777 	case IPFGENITER_FRAG :
7778 		error = ipf_frag_pkt_next(softc, token, itp);
7779 		break;
7780 	default :
7781 		IPFERROR(92);
7782 		error = EINVAL;
7783 		break;
7784 	}
7785 
7786 	return error;
7787 }
7788 
7789 
7790 /* ------------------------------------------------------------------------ */
7791 /* Function:    ipf_genericiter                                             */
7792 /* Returns:     int - 0 = success, else error                               */
7793 /* Parameters:  softc(I)- pointer to soft context main structure            */
7794 /*              data(I) - the token type to match                           */
7795 /*              uid(I)  - uid owning the token                              */
7796 /*              ptr(I)  - context pointer for the token                     */
7797 /*                                                                          */
7798 /* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role   */
7799 /* ------------------------------------------------------------------------ */
7800 int
7801 ipf_genericiter(ipf_main_softc_t *softc, void *data, int uid, void *ctx)
7802 {
7803 	ipftoken_t *token;
7804 	ipfgeniter_t iter;
7805 	int error;
7806 
7807 	error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
7808 	if (error != 0)
7809 		return error;
7810 
7811 	token = ipf_token_find(softc, iter.igi_type, uid, ctx);
7812 	if (token != NULL) {
7813 		token->ipt_subtype = iter.igi_type;
7814 		error = ipf_geniter(softc, token, &iter);
7815 		WRITE_ENTER(&softc->ipf_tokens);
7816 		ipf_token_deref(softc, token);
7817 		RWLOCK_EXIT(&softc->ipf_tokens);
7818 	} else {
7819 		IPFERROR(93);
7820 		error = 0;
7821 	}
7822 
7823 	return error;
7824 }
7825 
7826 
7827 /* ------------------------------------------------------------------------ */
7828 /* Function:    ipf_ipf_ioctl                                               */
7829 /* Returns:     int - 0 = success, else error                               */
7830 /* Parameters:  softc(I)- pointer to soft context main structure           */
7831 /*              data(I) - the token type to match                           */
7832 /*              cmd(I)  - the ioctl command number                          */
7833 /*              mode(I) - mode flags for the ioctl                          */
7834 /*              uid(I)  - uid owning the token                              */
7835 /*              ptr(I)  - context pointer for the token                     */
7836 /*                                                                          */
7837 /* This function handles all of the ioctl command that are actually isssued */
7838 /* to the /dev/ipl device.                                                  */
7839 /* ------------------------------------------------------------------------ */
7840 int
7841 ipf_ipf_ioctl(ipf_main_softc_t *softc, void *data, ioctlcmd_t cmd, int mode,
7842     int uid, void *ctx)
7843 {
7844 	friostat_t fio;
7845 	int error, tmp;
7846 	ipfobj_t obj;
7847 	SPL_INT(s);
7848 
7849 	switch (cmd)
7850 	{
7851 	case SIOCFRENB :
7852 		if (!(mode & FWRITE)) {
7853 			IPFERROR(94);
7854 			error = EPERM;
7855 		} else {
7856 			error = BCOPYIN(data, &tmp, sizeof(tmp));
7857 			if (error != 0) {
7858 				IPFERROR(95);
7859 				error = EFAULT;
7860 				break;
7861 			}
7862 
7863 			WRITE_ENTER(&softc->ipf_global);
7864 			if (tmp) {
7865 				if (softc->ipf_running > 0)
7866 					error = 0;
7867 				else
7868 					error = ipfattach(softc);
7869 				if (error == 0)
7870 					softc->ipf_running = 1;
7871 				else
7872 					(void) ipfdetach(softc);
7873 			} else {
7874 				if (softc->ipf_running == 1)
7875 					error = ipfdetach(softc);
7876 				else
7877 					error = 0;
7878 				if (error == 0)
7879 					softc->ipf_running = -1;
7880 			}
7881 			RWLOCK_EXIT(&softc->ipf_global);
7882 		}
7883 		break;
7884 
7885 	case SIOCIPFSET :
7886 		if (!(mode & FWRITE)) {
7887 			IPFERROR(96);
7888 			error = EPERM;
7889 			break;
7890 		}
7891 		/* FALLTHRU */
7892 	case SIOCIPFGETNEXT :
7893 	case SIOCIPFGET :
7894 		error = ipf_ipftune(softc, cmd, (void *)data);
7895 		break;
7896 
7897 	case SIOCSETFF :
7898 		if (!(mode & FWRITE)) {
7899 			IPFERROR(97);
7900 			error = EPERM;
7901 		} else {
7902 			error = BCOPYIN(data, &softc->ipf_flags,
7903 					sizeof(softc->ipf_flags));
7904 			if (error != 0) {
7905 				IPFERROR(98);
7906 				error = EFAULT;
7907 			}
7908 		}
7909 		break;
7910 
7911 	case SIOCGETFF :
7912 		error = BCOPYOUT(&softc->ipf_flags, data,
7913 				 sizeof(softc->ipf_flags));
7914 		if (error != 0) {
7915 			IPFERROR(99);
7916 			error = EFAULT;
7917 		}
7918 		break;
7919 
7920 	case SIOCFUNCL :
7921 		error = ipf_resolvefunc(softc, (void *)data);
7922 		break;
7923 
7924 	case SIOCINAFR :
7925 	case SIOCRMAFR :
7926 	case SIOCADAFR :
7927 	case SIOCZRLST :
7928 		if (!(mode & FWRITE)) {
7929 			IPFERROR(100);
7930 			error = EPERM;
7931 		} else {
7932 			error = frrequest(softc, IPL_LOGIPF, cmd, data,
7933 					  softc->ipf_active, 1);
7934 		}
7935 		break;
7936 
7937 	case SIOCINIFR :
7938 	case SIOCRMIFR :
7939 	case SIOCADIFR :
7940 		if (!(mode & FWRITE)) {
7941 			IPFERROR(101);
7942 			error = EPERM;
7943 		} else {
7944 			error = frrequest(softc, IPL_LOGIPF, cmd, data,
7945 					  1 - softc->ipf_active, 1);
7946 		}
7947 		break;
7948 
7949 	case SIOCSWAPA :
7950 		if (!(mode & FWRITE)) {
7951 			IPFERROR(102);
7952 			error = EPERM;
7953 		} else {
7954 			WRITE_ENTER(&softc->ipf_mutex);
7955 			error = BCOPYOUT(&softc->ipf_active, data,
7956 					 sizeof(softc->ipf_active));
7957 			if (error != 0) {
7958 				IPFERROR(103);
7959 				error = EFAULT;
7960 			} else {
7961 				softc->ipf_active = 1 - softc->ipf_active;
7962 			}
7963 			RWLOCK_EXIT(&softc->ipf_mutex);
7964 		}
7965 		break;
7966 
7967 	case SIOCGETFS :
7968 		error = ipf_inobj(softc, (void *)data, &obj, &fio,
7969 				  IPFOBJ_IPFSTAT);
7970 		if (error != 0)
7971 			break;
7972 		ipf_getstat(softc, &fio, obj.ipfo_rev);
7973 		error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
7974 		break;
7975 
7976 	case SIOCFRZST :
7977 		if (!(mode & FWRITE)) {
7978 			IPFERROR(104);
7979 			error = EPERM;
7980 		} else
7981 			error = ipf_zerostats(softc, data);
7982 		break;
7983 
7984 	case SIOCIPFFL :
7985 		if (!(mode & FWRITE)) {
7986 			IPFERROR(105);
7987 			error = EPERM;
7988 		} else {
7989 			error = BCOPYIN(data, &tmp, sizeof(tmp));
7990 			if (!error) {
7991 				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
7992 				error = BCOPYOUT(&tmp, data, sizeof(tmp));
7993 				if (error != 0) {
7994 					IPFERROR(106);
7995 					error = EFAULT;
7996 				}
7997 			} else {
7998 				IPFERROR(107);
7999 				error = EFAULT;
8000 			}
8001 		}
8002 		break;
8003 
8004 #ifdef USE_INET6
8005 	case SIOCIPFL6 :
8006 		if (!(mode & FWRITE)) {
8007 			IPFERROR(108);
8008 			error = EPERM;
8009 		} else {
8010 			error = BCOPYIN(data, &tmp, sizeof(tmp));
8011 			if (!error) {
8012 				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8013 				error = BCOPYOUT(&tmp, data, sizeof(tmp));
8014 				if (error != 0) {
8015 					IPFERROR(109);
8016 					error = EFAULT;
8017 				}
8018 			} else {
8019 				IPFERROR(110);
8020 				error = EFAULT;
8021 			}
8022 		}
8023 		break;
8024 #endif
8025 
8026 	case SIOCSTLCK :
8027 		if (!(mode & FWRITE)) {
8028 			IPFERROR(122);
8029 			error = EPERM;
8030 		} else {
8031 			error = BCOPYIN(data, &tmp, sizeof(tmp));
8032 			if (error == 0) {
8033 				ipf_state_setlock(softc->ipf_state_soft, tmp);
8034 				ipf_nat_setlock(softc->ipf_nat_soft, tmp);
8035 				ipf_frag_setlock(softc->ipf_frag_soft, tmp);
8036 				ipf_auth_setlock(softc->ipf_auth_soft, tmp);
8037 			} else {
8038 				IPFERROR(111);
8039 				error = EFAULT;
8040 			}
8041 		}
8042 		break;
8043 
8044 #ifdef	IPFILTER_LOG
8045 	case SIOCIPFFB :
8046 		if (!(mode & FWRITE)) {
8047 			IPFERROR(112);
8048 			error = EPERM;
8049 		} else {
8050 			tmp = ipf_log_clear(softc, IPL_LOGIPF);
8051 			error = BCOPYOUT(&tmp, data, sizeof(tmp));
8052 			if (error) {
8053 				IPFERROR(113);
8054 				error = EFAULT;
8055 			}
8056 		}
8057 		break;
8058 #endif /* IPFILTER_LOG */
8059 
8060 	case SIOCFRSYN :
8061 		if (!(mode & FWRITE)) {
8062 			IPFERROR(114);
8063 			error = EPERM;
8064 		} else {
8065 			WRITE_ENTER(&softc->ipf_global);
8066 #if (defined(MENTAT) && defined(_KERNEL)) && !defined(INSTANCES)
8067 			error = ipfsync();
8068 #else
8069 			ipf_sync(softc, NULL);
8070 			error = 0;
8071 #endif
8072 			RWLOCK_EXIT(&softc->ipf_global);
8073 
8074 		}
8075 		break;
8076 
8077 	case SIOCGFRST :
8078 		error = ipf_outobj(softc, (void *)data,
8079 				   ipf_frag_stats(softc->ipf_frag_soft),
8080 				   IPFOBJ_FRAGSTAT);
8081 		break;
8082 
8083 #ifdef	IPFILTER_LOG
8084 	case FIONREAD :
8085 		tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
8086 		error = BCOPYOUT(&tmp, data, sizeof(tmp));
8087 		break;
8088 #endif
8089 
8090 	case SIOCIPFITER :
8091 		SPL_SCHED(s);
8092 		error = ipf_frruleiter(softc, data, uid, ctx);
8093 		SPL_X(s);
8094 		break;
8095 
8096 	case SIOCGENITER :
8097 		SPL_SCHED(s);
8098 		error = ipf_genericiter(softc, data, uid, ctx);
8099 		SPL_X(s);
8100 		break;
8101 
8102 	case SIOCIPFDELTOK :
8103 		error = BCOPYIN(data, &tmp, sizeof(tmp));
8104 		if (error == 0) {
8105 			SPL_SCHED(s);
8106 			error = ipf_token_del(softc, tmp, uid, ctx);
8107 			SPL_X(s);
8108 		}
8109 		break;
8110 
8111 	default :
8112 		IPFERROR(115);
8113 		error = EINVAL;
8114 		break;
8115 	}
8116 
8117 	return error;
8118 }
8119 
8120 
8121 /* ------------------------------------------------------------------------ */
8122 /* Function:    ipf_decaps                                                  */
8123 /* Returns:     int        - -1 == decapsulation failed, else bit mask of   */
8124 /*                           flags indicating packet filtering decision.    */
8125 /* Parameters:  fin(I)     - pointer to packet information                  */
8126 /*              pass(I)    - IP protocol version to match                   */
8127 /*              l5proto(I) - layer 5 protocol to decode UDP data as.        */
8128 /*                                                                          */
8129 /* This function is called for packets that are wrapt up in other packets,  */
8130 /* for example, an IP packet that is the entire data segment for another IP */
8131 /* packet.  If the basic constraints for this are satisfied, change the     */
8132 /* buffer to point to the start of the inner packet and start processing    */
8133 /* rules belonging to the head group this rule specifies.                   */
8134 /* ------------------------------------------------------------------------ */
8135 u_32_t
8136 ipf_decaps(fr_info_t *fin, u_32_t pass, int l5proto)
8137 {
8138 	fr_info_t fin2, *fino = NULL;
8139 	int elen, hlen, nh;
8140 	grehdr_t gre;
8141 	ip_t *ip;
8142 	mb_t *m;
8143 
8144 	if ((fin->fin_flx & FI_COALESCE) == 0)
8145 		if (ipf_coalesce(fin) == -1)
8146 			goto cantdecaps;
8147 
8148 	m = fin->fin_m;
8149 	hlen = fin->fin_hlen;
8150 
8151 	switch (fin->fin_p)
8152 	{
8153 	case IPPROTO_UDP :
8154 		/*
8155 		 * In this case, the specific protocol being decapsulated
8156 		 * inside UDP frames comes from the rule.
8157 		 */
8158 		nh = fin->fin_fr->fr_icode;
8159 		break;
8160 
8161 	case IPPROTO_GRE :	/* 47 */
8162 		bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
8163 		hlen += sizeof(grehdr_t);
8164 		if (gre.gr_R|gre.gr_s)
8165 			goto cantdecaps;
8166 		if (gre.gr_C)
8167 			hlen += 4;
8168 		if (gre.gr_K)
8169 			hlen += 4;
8170 		if (gre.gr_S)
8171 			hlen += 4;
8172 
8173 		nh = IPPROTO_IP;
8174 
8175 		/*
8176 		 * If the routing options flag is set, validate that it is
8177 		 * there and bounce over it.
8178 		 */
8179 #if 0
8180 		/* This is really heavy weight and lots of room for error, */
8181 		/* so for now, put it off and get the simple stuff right.  */
8182 		if (gre.gr_R) {
8183 			u_char off, len, *s;
8184 			u_short af;
8185 			int end;
8186 
8187 			end = 0;
8188 			s = fin->fin_dp;
8189 			s += hlen;
8190 			aplen = fin->fin_plen - hlen;
8191 			while (aplen > 3) {
8192 				af = (s[0] << 8) | s[1];
8193 				off = s[2];
8194 				len = s[3];
8195 				aplen -= 4;
8196 				s += 4;
8197 				if (af == 0 && len == 0) {
8198 					end = 1;
8199 					break;
8200 				}
8201 				if (aplen < len)
8202 					break;
8203 				s += len;
8204 				aplen -= len;
8205 			}
8206 			if (end != 1)
8207 				goto cantdecaps;
8208 			hlen = s - (u_char *)fin->fin_dp;
8209 		}
8210 #endif
8211 		break;
8212 
8213 #ifdef IPPROTO_IPIP
8214 	case IPPROTO_IPIP :	/* 4 */
8215 #endif
8216 		nh = IPPROTO_IP;
8217 		break;
8218 
8219 	default :	/* Includes ESP, AH is special for IPv4 */
8220 		goto cantdecaps;
8221 	}
8222 
8223 	switch (nh)
8224 	{
8225 	case IPPROTO_IP :
8226 	case IPPROTO_IPV6 :
8227 		break;
8228 	default :
8229 		goto cantdecaps;
8230 	}
8231 
8232 	bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
8233 	fino = fin;
8234 	fin = &fin2;
8235 	elen = hlen;
8236 #if defined(MENTAT) && defined(_KERNEL)
8237 	m->b_rptr += elen;
8238 #else
8239 	m->m_data += elen;
8240 	m->m_len -= elen;
8241 #endif
8242 	fin->fin_plen -= elen;
8243 
8244 	ip = (ip_t *)((char *)fin->fin_ip + elen);
8245 
8246 	/*
8247 	 * Make sure we have at least enough data for the network layer
8248 	 * header.
8249 	 */
8250 	if (IP_V(ip) == 4)
8251 		hlen = IP_HL(ip) << 2;
8252 #ifdef USE_INET6
8253 	else if (IP_V(ip) == 6)
8254 		hlen = sizeof(ip6_t);
8255 #endif
8256 	else
8257 		goto cantdecaps2;
8258 
8259 	if (fin->fin_plen < hlen)
8260 		goto cantdecaps2;
8261 
8262 	fin->fin_dp = (char *)ip + hlen;
8263 
8264 	if (IP_V(ip) == 4) {
8265 		/*
8266 		 * Perform IPv4 header checksum validation.
8267 		 */
8268 		if (ipf_cksum((u_short *)ip, hlen))
8269 			goto cantdecaps2;
8270 	}
8271 
8272 	if (ipf_makefrip(hlen, ip, fin) == -1) {
8273 cantdecaps2:
8274 		if (m != NULL) {
8275 #if defined(MENTAT) && defined(_KERNEL)
8276 			m->b_rptr -= elen;
8277 #else
8278 			m->m_data -= elen;
8279 			m->m_len += elen;
8280 #endif
8281 		}
8282 cantdecaps:
8283 		DT1(frb_decapfrip, fr_info_t *, fin);
8284 		pass &= ~FR_CMDMASK;
8285 		pass |= FR_BLOCK|FR_QUICK;
8286 		fin->fin_reason = FRB_DECAPFRIP;
8287 		return -1;
8288 	}
8289 
8290 	pass = ipf_scanlist(fin, pass);
8291 
8292 	/*
8293 	 * Copy the packet filter "result" fields out of the fr_info_t struct
8294 	 * that is local to the decapsulation processing and back into the
8295 	 * one we were called with.
8296 	 */
8297 	fino->fin_flx = fin->fin_flx;
8298 	fino->fin_rev = fin->fin_rev;
8299 	fino->fin_icode = fin->fin_icode;
8300 	fino->fin_rule = fin->fin_rule;
8301 	(void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
8302 	fino->fin_fr = fin->fin_fr;
8303 	fino->fin_error = fin->fin_error;
8304 	fino->fin_mp = fin->fin_mp;
8305 	fino->fin_m = fin->fin_m;
8306 	m = fin->fin_m;
8307 	if (m != NULL) {
8308 #if defined(MENTAT) && defined(_KERNEL)
8309 		m->b_rptr -= elen;
8310 #else
8311 		m->m_data -= elen;
8312 		m->m_len += elen;
8313 #endif
8314 	}
8315 	return pass;
8316 }
8317 
8318 
8319 /* ------------------------------------------------------------------------ */
8320 /* Function:    ipf_matcharray_load                                         */
8321 /* Returns:     int         - 0 = success, else error                       */
8322 /* Parameters:  softc(I)    - pointer to soft context main structure        */
8323 /*              data(I)     - pointer to ioctl data                         */
8324 /*              objp(I)     - ipfobj_t structure to load data into          */
8325 /*              arrayptr(I) - pointer to location to store array pointer    */
8326 /*                                                                          */
8327 /* This function loads in a mathing array through the ipfobj_t struct that  */
8328 /* describes it.  Sanity checking and array size limitations are enforced   */
8329 /* in this function to prevent userspace from trying to load in something   */
8330 /* that is insanely big.  Once the size of the array is known, the memory   */
8331 /* required is malloc'd and returned through changing *arrayptr.  The       */
8332 /* contents of the array are verified before returning.  Only in the event  */
8333 /* of a successful call is the caller required to free up the malloc area.  */
8334 /* ------------------------------------------------------------------------ */
8335 int
8336 ipf_matcharray_load(ipf_main_softc_t *softc, void *data, ipfobj_t *objp,
8337     int **arrayptr)
8338 {
8339 	int arraysize, *array, error;
8340 
8341 	*arrayptr = NULL;
8342 
8343 	error = BCOPYIN(data, objp, sizeof(*objp));
8344 	if (error != 0) {
8345 		IPFERROR(116);
8346 		return EFAULT;
8347 	}
8348 
8349 	if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
8350 		IPFERROR(117);
8351 		return EINVAL;
8352 	}
8353 
8354 	if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
8355 	    (objp->ipfo_size > 1024)) {
8356 		IPFERROR(118);
8357 		return EINVAL;
8358 	}
8359 
8360 	arraysize = objp->ipfo_size * sizeof(*array);
8361 	KMALLOCS(array, int *, arraysize);
8362 	if (array == NULL) {
8363 		IPFERROR(119);
8364 		return ENOMEM;
8365 	}
8366 
8367 	error = COPYIN(objp->ipfo_ptr, array, arraysize);
8368 	if (error != 0) {
8369 		KFREES(array, arraysize);
8370 		IPFERROR(120);
8371 		return EFAULT;
8372 	}
8373 
8374 	if (ipf_matcharray_verify(array, arraysize) != 0) {
8375 		KFREES(array, arraysize);
8376 		IPFERROR(121);
8377 		return EINVAL;
8378 	}
8379 
8380 	*arrayptr = array;
8381 	return 0;
8382 }
8383 
8384 
8385 /* ------------------------------------------------------------------------ */
8386 /* Function:    ipf_matcharray_verify                                       */
8387 /* Returns:     Nil                                                         */
8388 /* Parameters:  array(I)     - pointer to matching array                    */
8389 /*              arraysize(I) - number of elements in the array              */
8390 /*                                                                          */
8391 /* Verify the contents of a matching array by stepping through each element */
8392 /* in it.  The actual commands in the array are not verified for            */
8393 /* correctness, only that all of the sizes are correctly within limits.     */
8394 /* ------------------------------------------------------------------------ */
8395 int
8396 ipf_matcharray_verify(int *array, int arraysize)
8397 {
8398 	int i, nelem, maxidx;
8399 	ipfexp_t *e;
8400 
8401 	nelem = arraysize / sizeof(*array);
8402 
8403 	/*
8404 	 * Currently, it makes no sense to have an array less than 6
8405 	 * elements long - the initial size at the from, a single operation
8406 	 * (minimum 4 in length) and a trailer, for a total of 6.
8407 	 */
8408 	if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
8409 		return -1;
8410 	}
8411 
8412 	/*
8413 	 * Verify the size of data pointed to by array with how long
8414 	 * the array claims to be itself.
8415 	 */
8416 	if (array[0] * sizeof(*array) != arraysize) {
8417 		return -1;
8418 	}
8419 
8420 	maxidx = nelem - 1;
8421 	/*
8422 	 * The last opcode in this array should be an IPF_EXP_END.
8423 	 */
8424 	if (array[maxidx] != IPF_EXP_END) {
8425 		return -1;
8426 	}
8427 
8428 	for (i = 1; i < maxidx; ) {
8429 		e = (ipfexp_t *)(array + i);
8430 
8431 		/*
8432 		 * The length of the bits to check must be at least 1
8433 		 * (or else there is nothing to comapre with!) and it
8434 		 * cannot exceed the length of the data present.
8435 		 */
8436 		if ((e->ipfe_size < 1 ) ||
8437 		    (e->ipfe_size + i > maxidx)) {
8438 			return -1;
8439 		}
8440 		i += e->ipfe_size;
8441 	}
8442 	return 0;
8443 }
8444 
8445 
8446 /* ------------------------------------------------------------------------ */
8447 /* Function:    ipf_fr_matcharray                                           */
8448 /* Returns:     int      - 0 = match failed, else positive match            */
8449 /* Parameters:  fin(I)   - pointer to packet information                    */
8450 /*              array(I) - pointer to matching array                        */
8451 /*                                                                          */
8452 /* This function is used to apply a matching array against a packet and     */
8453 /* return an indication of whether or not the packet successfully matches   */
8454 /* all of the commands in it.                                               */
8455 /* ------------------------------------------------------------------------ */
8456 static int
8457 ipf_fr_matcharray(fr_info_t *fin, int *array)
8458 {
8459 	int i, n, *x, rv, p;
8460 	ipfexp_t *e;
8461 
8462 	rv = 0;
8463 	n = array[0];
8464 	x = array + 1;
8465 
8466 	for (; n > 0; x += 3 + x[3], rv = 0) {
8467 		e = (ipfexp_t *)x;
8468 		if (e->ipfe_cmd == IPF_EXP_END)
8469 			break;
8470 		n -= e->ipfe_size;
8471 
8472 		/*
8473 		 * The upper 16 bits currently store the protocol value.
8474 		 * This is currently used with TCP and UDP port compares and
8475 		 * allows "tcp.port = 80" without requiring an explicit
8476 		 " "ip.pr = tcp" first.
8477 		 */
8478 		p = e->ipfe_cmd >> 16;
8479 		if ((p != 0) && (p != fin->fin_p))
8480 			break;
8481 
8482 		switch (e->ipfe_cmd)
8483 		{
8484 		case IPF_EXP_IP_PR :
8485 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8486 				rv |= (fin->fin_p == e->ipfe_arg0[i]);
8487 			}
8488 			break;
8489 
8490 		case IPF_EXP_IP_SRCADDR :
8491 			if (fin->fin_v != 4)
8492 				break;
8493 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8494 				rv |= ((fin->fin_saddr &
8495 					e->ipfe_arg0[i * 2 + 1]) ==
8496 				       e->ipfe_arg0[i * 2]);
8497 			}
8498 			break;
8499 
8500 		case IPF_EXP_IP_DSTADDR :
8501 			if (fin->fin_v != 4)
8502 				break;
8503 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8504 				rv |= ((fin->fin_daddr &
8505 					e->ipfe_arg0[i * 2 + 1]) ==
8506 				       e->ipfe_arg0[i * 2]);
8507 			}
8508 			break;
8509 
8510 		case IPF_EXP_IP_ADDR :
8511 			if (fin->fin_v != 4)
8512 				break;
8513 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8514 				rv |= ((fin->fin_saddr &
8515 					e->ipfe_arg0[i * 2 + 1]) ==
8516 				       e->ipfe_arg0[i * 2]) ||
8517 				      ((fin->fin_daddr &
8518 					e->ipfe_arg0[i * 2 + 1]) ==
8519 				       e->ipfe_arg0[i * 2]);
8520 			}
8521 			break;
8522 
8523 #ifdef USE_INET6
8524 		case IPF_EXP_IP6_SRCADDR :
8525 			if (fin->fin_v != 6)
8526 				break;
8527 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8528 				rv |= IP6_MASKEQ(&fin->fin_src6,
8529 						 &e->ipfe_arg0[i * 8 + 4],
8530 						 &e->ipfe_arg0[i * 8]);
8531 			}
8532 			break;
8533 
8534 		case IPF_EXP_IP6_DSTADDR :
8535 			if (fin->fin_v != 6)
8536 				break;
8537 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8538 				rv |= IP6_MASKEQ(&fin->fin_dst6,
8539 						 &e->ipfe_arg0[i * 8 + 4],
8540 						 &e->ipfe_arg0[i * 8]);
8541 			}
8542 			break;
8543 
8544 		case IPF_EXP_IP6_ADDR :
8545 			if (fin->fin_v != 6)
8546 				break;
8547 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8548 				rv |= IP6_MASKEQ(&fin->fin_src6,
8549 						 &e->ipfe_arg0[i * 8 + 4],
8550 						 &e->ipfe_arg0[i * 8]) ||
8551 				      IP6_MASKEQ(&fin->fin_dst6,
8552 						 &e->ipfe_arg0[i * 8 + 4],
8553 						 &e->ipfe_arg0[i * 8]);
8554 			}
8555 			break;
8556 #endif
8557 
8558 		case IPF_EXP_UDP_PORT :
8559 		case IPF_EXP_TCP_PORT :
8560 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8561 				rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
8562 				      (fin->fin_dport == e->ipfe_arg0[i]);
8563 			}
8564 			break;
8565 
8566 		case IPF_EXP_UDP_SPORT :
8567 		case IPF_EXP_TCP_SPORT :
8568 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8569 				rv |= (fin->fin_sport == e->ipfe_arg0[i]);
8570 			}
8571 			break;
8572 
8573 		case IPF_EXP_UDP_DPORT :
8574 		case IPF_EXP_TCP_DPORT :
8575 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8576 				rv |= (fin->fin_dport == e->ipfe_arg0[i]);
8577 			}
8578 			break;
8579 
8580 		case IPF_EXP_TCP_FLAGS :
8581 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8582 				rv |= ((fin->fin_tcpf &
8583 					e->ipfe_arg0[i * 2 + 1]) ==
8584 				       e->ipfe_arg0[i * 2]);
8585 			}
8586 			break;
8587 		}
8588 		rv ^= e->ipfe_not;
8589 
8590 		if (rv == 0)
8591 			break;
8592 	}
8593 
8594 	return rv;
8595 }
8596 
8597 
8598 /* ------------------------------------------------------------------------ */
8599 /* Function:    ipf_queueflush                                              */
8600 /* Returns:     int - number of entries flushed (0 = none)                  */
8601 /* Parameters:  softc(I)    - pointer to soft context main structure        */
8602 /*              deletefn(I) - function to call to delete entry              */
8603 /*              ipfqs(I)    - top of the list of ipf internal queues        */
8604 /*              userqs(I)   - top of the list of user defined timeouts      */
8605 /*                                                                          */
8606 /* This fucntion gets called when the state/NAT hash tables fill up and we  */
8607 /* need to try a bit harder to free up some space.  The algorithm used here */
8608 /* split into two parts but both halves have the same goal: to reduce the   */
8609 /* number of connections considered to be "active" to the low watermark.    */
8610 /* There are two steps in doing this:                                       */
8611 /* 1) Remove any TCP connections that are already considered to be "closed" */
8612 /*    but have not yet been removed from the state table.  The two states   */
8613 /*    TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect       */
8614 /*    candidates for this style of removal.  If freeing up entries in       */
8615 /*    CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark,   */
8616 /*    we do not go on to step 2.                                            */
8617 /*                                                                          */
8618 /* 2) Look for the oldest entries on each timeout queue and free them if    */
8619 /*    they are within the given window we are considering.  Where the       */
8620 /*    window starts and the steps taken to increase its size depend upon    */
8621 /*    how long ipf has been running (ipf_ticks.)  Anything modified in the  */
8622 /*    last 30 seconds is not touched.                                       */
8623 /*                                              touched                     */
8624 /*         die     ipf_ticks  30*1.5    1800*1.5   |  43200*1.5             */
8625 /*           |          |        |           |     |     |                  */
8626 /* future <--+----------+--------+-----------+-----+-----+-----------> past */
8627 /*                     now        \_int=30s_/ \_int=1hr_/ \_int=12hr        */
8628 /*                                                                          */
8629 /* Points to note:                                                          */
8630 /* - tqe_die is the time, in the future, when entries die.                  */
8631 /* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
8632 /*   ticks.                                                                 */
8633 /* - tqe_touched is when the entry was last used by NAT/state               */
8634 /* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be    */
8635 /*   ipf_ticks any given timeout queue and vice versa.                      */
8636 /* - both tqe_die and tqe_touched increase over time                        */
8637 /* - timeout queues are sorted with the highest value of tqe_die at the     */
8638 /*   bottom and therefore the smallest values of each are at the top        */
8639 /* - the pointer passed in as ipfqs should point to an array of timeout     */
8640 /*   queues representing each of the TCP states                             */
8641 /*                                                                          */
8642 /* We start by setting up a maximum range to scan for things to move of     */
8643 /* iend (newest) to istart (oldest) in chunks of "interval".  If nothing is */
8644 /* found in that range, "interval" is adjusted (so long as it isn't 30) and */
8645 /* we start again with a new value for "iend" and "istart".  This is        */
8646 /* continued until we either finish the scan of 30 second intervals or the  */
8647 /* low water mark is reached.                                               */
8648 /* ------------------------------------------------------------------------ */
8649 int
8650 ipf_queueflush(ipf_main_softc_t *softc, ipftq_delete_fn_t deletefn,
8651     ipftq_t *ipfqs, ipftq_t *userqs, u_int *activep, int size, int low)
8652 {
8653 	u_long interval, istart, iend;
8654 	ipftq_t *ifq, *ifqnext;
8655 	ipftqent_t *tqe, *tqn;
8656 	int removed = 0;
8657 
8658 	for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
8659 		tqn = tqe->tqe_next;
8660 		if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8661 			removed++;
8662 	}
8663 	if ((*activep * 100 / size) > low) {
8664 		for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
8665 		     ((tqe = tqn) != NULL); ) {
8666 			tqn = tqe->tqe_next;
8667 			if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8668 				removed++;
8669 		}
8670 	}
8671 
8672 	if ((*activep * 100 / size) <= low) {
8673 		return removed;
8674 	}
8675 
8676 	/*
8677 	 * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
8678 	 *       used then the operations are upgraded to floating point
8679 	 *       and kernels don't like floating point...
8680 	 */
8681 	if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
8682 		istart = IPF_TTLVAL(86400 * 4);
8683 		interval = IPF_TTLVAL(43200);
8684 	} else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
8685 		istart = IPF_TTLVAL(43200);
8686 		interval = IPF_TTLVAL(1800);
8687 	} else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
8688 		istart = IPF_TTLVAL(1800);
8689 		interval = IPF_TTLVAL(30);
8690 	} else {
8691 		return 0;
8692 	}
8693 	if (istart > softc->ipf_ticks) {
8694 		if (softc->ipf_ticks - interval < interval)
8695 			istart = interval;
8696 		else
8697 			istart = (softc->ipf_ticks / interval) * interval;
8698 	}
8699 
8700 	iend = softc->ipf_ticks - interval;
8701 
8702 	while ((*activep * 100 / size) > low) {
8703 		u_long try;
8704 
8705 		try = softc->ipf_ticks - istart;
8706 
8707 		for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
8708 			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
8709 				if (try < tqe->tqe_touched)
8710 					break;
8711 				tqn = tqe->tqe_next;
8712 				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8713 					removed++;
8714 			}
8715 		}
8716 
8717 		for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
8718 			ifqnext = ifq->ifq_next;
8719 
8720 			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
8721 				if (try < tqe->tqe_touched)
8722 					break;
8723 				tqn = tqe->tqe_next;
8724 				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8725 					removed++;
8726 			}
8727 		}
8728 
8729 		if (try >= iend) {
8730 			if (interval == IPF_TTLVAL(43200)) {
8731 				interval = IPF_TTLVAL(1800);
8732 			} else if (interval == IPF_TTLVAL(1800)) {
8733 				interval = IPF_TTLVAL(30);
8734 			} else {
8735 				break;
8736 			}
8737 			if (interval >= softc->ipf_ticks)
8738 				break;
8739 
8740 			iend = softc->ipf_ticks - interval;
8741 		}
8742 		istart -= interval;
8743 	}
8744 
8745 	return removed;
8746 }
8747 
8748 
8749 /* ------------------------------------------------------------------------ */
8750 /* Function:    ipf_deliverlocal                                            */
8751 /* Returns:     int - 1 = local address, 0 = non-local address              */
8752 /* Parameters:  softc(I)     - pointer to soft context main structure       */
8753 /*              ipversion(I) - IP protocol version (4 or 6)                 */
8754 /*              ifp(I)       - network interface pointer                    */
8755 /*              ipaddr(I)    - IPv4/6 destination address                   */
8756 /*                                                                          */
8757 /* This fucntion is used to determine in the address "ipaddr" belongs to    */
8758 /* the network interface represented by ifp.                                */
8759 /* ------------------------------------------------------------------------ */
8760 int
8761 ipf_deliverlocal(ipf_main_softc_t *softc, int ipversion, void *ifp,
8762     i6addr_t *ipaddr)
8763 {
8764 	i6addr_t addr;
8765 	int islocal = 0;
8766 
8767 	if (ipversion == 4) {
8768 		if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
8769 			if (addr.in4.s_addr == ipaddr->in4.s_addr)
8770 				islocal = 1;
8771 		}
8772 
8773 #ifdef USE_INET6
8774 	} else if (ipversion == 6) {
8775 		if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
8776 			if (IP6_EQ(&addr, ipaddr))
8777 				islocal = 1;
8778 		}
8779 #endif
8780 	}
8781 
8782 	return islocal;
8783 }
8784 
8785 
8786 /* ------------------------------------------------------------------------ */
8787 /* Function:    ipf_settimeout                                              */
8788 /* Returns:     int - 0 = success, -1 = failure                             */
8789 /* Parameters:  softc(I) - pointer to soft context main structure           */
8790 /*              t(I)     - pointer to tuneable array entry                  */
8791 /*              p(I)     - pointer to values passed in to apply             */
8792 /*                                                                          */
8793 /* This function is called to set the timeout values for each distinct      */
8794 /* queue timeout that is available.  When called, it calls into both the    */
8795 /* state and NAT code, telling them to update their timeout queues.         */
8796 /* ------------------------------------------------------------------------ */
8797 static int
8798 ipf_settimeout(struct ipf_main_softc_s *softc, ipftuneable_t *t,
8799     ipftuneval_t *p)
8800 {
8801 
8802 	/*
8803 	 * ipf_interror should be set by the functions called here, not
8804 	 * by this function - it's just a middle man.
8805 	 */
8806 	if (ipf_state_settimeout(softc, t, p) == -1)
8807 		return -1;
8808 	if (ipf_nat_settimeout(softc, t, p) == -1)
8809 		return -1;
8810 	return 0;
8811 }
8812 
8813 
8814 /* ------------------------------------------------------------------------ */
8815 /* Function:    ipf_apply_timeout                                           */
8816 /* Returns:     int - 0 = success, -1 = failure                             */
8817 /* Parameters:  head(I)    - pointer to tuneable array entry                */
8818 /*              seconds(I) - pointer to values passed in to apply           */
8819 /*                                                                          */
8820 /* This function applies a timeout of "seconds" to the timeout queue that   */
8821 /* is pointed to by "head".  All entries on this list have an expiration    */
8822 /* set to be the current tick value of ipf plus the ttl.  Given that this   */
8823 /* function should only be called when the delta is non-zero, the task is   */
8824 /* to walk the entire list and apply the change.  The sort order will not   */
8825 /* change.  The only catch is that this is O(n) across the list, so if the  */
8826 /* queue has lots of entries (10s of thousands or 100s of thousands), it    */
8827 /* could take a relatively long time to work through them all.              */
8828 /* ------------------------------------------------------------------------ */
8829 void
8830 ipf_apply_timeout(ipftq_t *head, u_int seconds)
8831 {
8832 	u_int oldtimeout, newtimeout;
8833 	ipftqent_t *tqe;
8834 	int delta;
8835 
8836 	MUTEX_ENTER(&head->ifq_lock);
8837 	oldtimeout = head->ifq_ttl;
8838 	newtimeout = IPF_TTLVAL(seconds);
8839 	delta = oldtimeout - newtimeout;
8840 
8841 	head->ifq_ttl = newtimeout;
8842 
8843 	for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
8844 		tqe->tqe_die += delta;
8845 	}
8846 	MUTEX_EXIT(&head->ifq_lock);
8847 }
8848 
8849 
8850 /* ------------------------------------------------------------------------ */
8851 /* Function:   ipf_settimeout_tcp                                           */
8852 /* Returns:    int - 0 = successfully applied, -1 = failed                  */
8853 /* Parameters: t(I)   - pointer to tuneable to change                       */
8854 /*             p(I)   - pointer to new timeout information                  */
8855 /*             tab(I) - pointer to table of TCP queues                      */
8856 /*                                                                          */
8857 /* This function applies the new timeout (p) to the TCP tunable (t) and     */
8858 /* updates all of the entries on the relevant timeout queue by calling      */
8859 /* ipf_apply_timeout().                                                     */
8860 /* ------------------------------------------------------------------------ */
8861 int
8862 ipf_settimeout_tcp(ipftuneable_t *t, ipftuneval_t *p, ipftq_t *tab)
8863 {
8864 	if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
8865 	    !strcmp(t->ipft_name, "tcp_established")) {
8866 		ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
8867 	} else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
8868 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
8869 	} else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
8870 		ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
8871 	} else if (!strcmp(t->ipft_name, "tcp_timeout")) {
8872 		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
8873 		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
8874 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
8875 	} else if (!strcmp(t->ipft_name, "tcp_listen")) {
8876 		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
8877 	} else if (!strcmp(t->ipft_name, "tcp_half_established")) {
8878 		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
8879 	} else if (!strcmp(t->ipft_name, "tcp_closing")) {
8880 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
8881 	} else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
8882 		ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
8883 	} else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
8884 		ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
8885 	} else if (!strcmp(t->ipft_name, "tcp_closed")) {
8886 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
8887 	} else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
8888 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
8889 	} else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
8890 		ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
8891 	} else {
8892 		/*
8893 		 * ipf_interror isn't set here because it should be set
8894 		 * by whatever called this function.
8895 		 */
8896 		return -1;
8897 	}
8898 	return 0;
8899 }
8900 
8901 
8902 /* ------------------------------------------------------------------------ */
8903 /* Function:   ipf_main_soft_create                                         */
8904 /* Returns:    NULL = failure, else success                                 */
8905 /* Parameters: arg(I) - pointer to soft context structure if already allocd */
8906 /*                                                                          */
8907 /* Create the foundation soft context structure. In circumstances where it  */
8908 /* is not required to dynamically allocate the context, a pointer can be    */
8909 /* passed in (rather than NULL) to a structure to be initialised.           */
8910 /* The main thing of interest is that a number of locks are initialised     */
8911 /* here instead of in the where might be expected - in the relevant create  */
8912 /* function elsewhere.  This is done because the current locking design has */
8913 /* some areas where these locks are used outside of their module.           */
8914 /* Possibly the most important exercise that is done here is setting of all */
8915 /* the timeout values, allowing them to be changed before init().           */
8916 /* ------------------------------------------------------------------------ */
8917 void *
8918 ipf_main_soft_create(void *arg)
8919 {
8920 	ipf_main_softc_t *softc;
8921 
8922 	if (arg == NULL) {
8923 		KMALLOC(softc, ipf_main_softc_t *);
8924 		if (softc == NULL)
8925 			return NULL;
8926 	} else {
8927 		softc = arg;
8928 	}
8929 
8930 	bzero((char *)softc, sizeof(*softc));
8931 
8932 	/*
8933 	 * This serves as a flag as to whether or not the softc should be
8934 	 * free'd when _destroy is called.
8935 	 */
8936 	softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
8937 
8938 	softc->ipf_tuners = ipf_tune_array_copy(softc,
8939 						sizeof(ipf_main_tuneables),
8940 						ipf_main_tuneables);
8941 	if (softc->ipf_tuners == NULL) {
8942 		ipf_main_soft_destroy(softc);
8943 		return NULL;
8944 	}
8945 
8946 	MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
8947 	MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
8948 	RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
8949 	RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
8950 	RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
8951 	RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
8952 	RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
8953 	RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
8954 	RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
8955 
8956 	softc->ipf_token_head = NULL;
8957 	softc->ipf_token_tail = &softc->ipf_token_head;
8958 
8959 	softc->ipf_tcpidletimeout = FIVE_DAYS;
8960 	softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
8961 	softc->ipf_tcplastack = IPF_TTLVAL(30);
8962 	softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
8963 	softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
8964 	softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
8965 	softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
8966 	softc->ipf_tcpclosed = IPF_TTLVAL(30);
8967 	softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
8968 	softc->ipf_udptimeout = IPF_TTLVAL(120);
8969 	softc->ipf_udpacktimeout = IPF_TTLVAL(12);
8970 	softc->ipf_icmptimeout = IPF_TTLVAL(60);
8971 	softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
8972 	softc->ipf_iptimeout = IPF_TTLVAL(60);
8973 
8974 #if defined(IPFILTER_DEFAULT_BLOCK)
8975 	softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
8976 #else
8977 	softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
8978 #endif
8979 	softc->ipf_minttl = 4;
8980 	softc->ipf_icmpminfragmtu = 68;
8981 	softc->ipf_flags = IPF_LOGGING;
8982 
8983 	return softc;
8984 }
8985 
8986 /* ------------------------------------------------------------------------ */
8987 /* Function:   ipf_main_soft_init                                           */
8988 /* Returns:    0 = success, -1 = failure                                    */
8989 /* Parameters: softc(I) - pointer to soft context main structure            */
8990 /*                                                                          */
8991 /* A null-op function that exists as a placeholder so that the flow in      */
8992 /* other functions is obvious.                                              */
8993 /* ------------------------------------------------------------------------ */
8994 /*ARGSUSED*/
8995 int
8996 ipf_main_soft_init(ipf_main_softc_t *softc)
8997 {
8998 	return 0;
8999 }
9000 
9001 
9002 /* ------------------------------------------------------------------------ */
9003 /* Function:   ipf_main_soft_destroy                                        */
9004 /* Returns:    void                                                         */
9005 /* Parameters: softc(I) - pointer to soft context main structure            */
9006 /*                                                                          */
9007 /* Undo everything that we did in ipf_main_soft_create.                     */
9008 /*                                                                          */
9009 /* The most important check that needs to be made here is whether or not    */
9010 /* the structure was allocated by ipf_main_soft_create() by checking what   */
9011 /* value is stored in ipf_dynamic_main.                                     */
9012 /* ------------------------------------------------------------------------ */
9013 /*ARGSUSED*/
9014 void
9015 ipf_main_soft_destroy(ipf_main_softc_t *softc)
9016 {
9017 
9018 	RW_DESTROY(&softc->ipf_frag);
9019 	RW_DESTROY(&softc->ipf_poolrw);
9020 	RW_DESTROY(&softc->ipf_nat);
9021 	RW_DESTROY(&softc->ipf_state);
9022 	RW_DESTROY(&softc->ipf_tokens);
9023 	RW_DESTROY(&softc->ipf_mutex);
9024 	RW_DESTROY(&softc->ipf_global);
9025 	MUTEX_DESTROY(&softc->ipf_timeoutlock);
9026 	MUTEX_DESTROY(&softc->ipf_rw);
9027 
9028 	if (softc->ipf_tuners != NULL) {
9029 		KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
9030 	}
9031 	if (softc->ipf_dynamic_softc == 1) {
9032 		KFREE(softc);
9033 	}
9034 }
9035 
9036 
9037 /* ------------------------------------------------------------------------ */
9038 /* Function:   ipf_main_soft_fini                                           */
9039 /* Returns:    0 = success, -1 = failure                                    */
9040 /* Parameters: softc(I) - pointer to soft context main structure            */
9041 /*                                                                          */
9042 /* Clean out the rules which have been added since _init was last called,   */
9043 /* the only dynamic part of the mainline.                                   */
9044 /* ------------------------------------------------------------------------ */
9045 int
9046 ipf_main_soft_fini(ipf_main_softc_t *softc)
9047 {
9048 	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9049 	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
9050 	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9051 	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
9052 
9053 	return 0;
9054 }
9055 
9056 
9057 /* ------------------------------------------------------------------------ */
9058 /* Function:   ipf_main_load                                                */
9059 /* Returns:    0 = success, -1 = failure                                    */
9060 /* Parameters: none                                                         */
9061 /*                                                                          */
9062 /* Handle global initialisation that needs to be done for the base part of  */
9063 /* IPFilter. At present this just amounts to initialising some ICMP lookup  */
9064 /* arrays that get used by the state/NAT code.                              */
9065 /* ------------------------------------------------------------------------ */
9066 int
9067 ipf_main_load(void)
9068 {
9069 	int i;
9070 
9071 	/* fill icmp reply type table */
9072 	for (i = 0; i <= ICMP_MAXTYPE; i++)
9073 		icmpreplytype4[i] = -1;
9074 	icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
9075 	icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
9076 	icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
9077 	icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
9078 
9079 #ifdef  USE_INET6
9080 	/* fill icmp reply type table */
9081 	for (i = 0; i <= ICMP6_MAXTYPE; i++)
9082 		icmpreplytype6[i] = -1;
9083 	icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
9084 	icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
9085 	icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
9086 	icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
9087 	icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
9088 #endif
9089 
9090 	return 0;
9091 }
9092 
9093 
9094 /* ------------------------------------------------------------------------ */
9095 /* Function:   ipf_main_unload                                              */
9096 /* Returns:    0 = success, -1 = failure                                    */
9097 /* Parameters: none                                                         */
9098 /*                                                                          */
9099 /* A null-op function that exists as a placeholder so that the flow in      */
9100 /* other functions is obvious.                                              */
9101 /* ------------------------------------------------------------------------ */
9102 int
9103 ipf_main_unload(void)
9104 {
9105 	return 0;
9106 }
9107 
9108 
9109 /* ------------------------------------------------------------------------ */
9110 /* Function:   ipf_load_all                                                 */
9111 /* Returns:    0 = success, -1 = failure                                    */
9112 /* Parameters: none                                                         */
9113 /*                                                                          */
9114 /* Work through all of the subsystems inside IPFilter and call the load     */
9115 /* function for each in an order that won't lead to a crash :)              */
9116 /* ------------------------------------------------------------------------ */
9117 int
9118 ipf_load_all(void)
9119 {
9120 	if (ipf_main_load() == -1)
9121 		return -1;
9122 
9123 	if (ipf_state_main_load() == -1)
9124 		return -1;
9125 
9126 	if (ipf_nat_main_load() == -1)
9127 		return -1;
9128 
9129 	if (ipf_frag_main_load() == -1)
9130 		return -1;
9131 
9132 	if (ipf_auth_main_load() == -1)
9133 		return -1;
9134 
9135 	if (ipf_proxy_main_load() == -1)
9136 		return -1;
9137 
9138 	return 0;
9139 }
9140 
9141 
9142 /* ------------------------------------------------------------------------ */
9143 /* Function:   ipf_unload_all                                               */
9144 /* Returns:    0 = success, -1 = failure                                    */
9145 /* Parameters: none                                                         */
9146 /*                                                                          */
9147 /* Work through all of the subsystems inside IPFilter and call the unload   */
9148 /* function for each in an order that won't lead to a crash :)              */
9149 /* ------------------------------------------------------------------------ */
9150 int
9151 ipf_unload_all(void)
9152 {
9153 	if (ipf_proxy_main_unload() == -1)
9154 		return -1;
9155 
9156 	if (ipf_auth_main_unload() == -1)
9157 		return -1;
9158 
9159 	if (ipf_frag_main_unload() == -1)
9160 		return -1;
9161 
9162 	if (ipf_nat_main_unload() == -1)
9163 		return -1;
9164 
9165 	if (ipf_state_main_unload() == -1)
9166 		return -1;
9167 
9168 	if (ipf_main_unload() == -1)
9169 		return -1;
9170 
9171 	return 0;
9172 }
9173 
9174 
9175 /* ------------------------------------------------------------------------ */
9176 /* Function:   ipf_create_all                                               */
9177 /* Returns:    NULL = failure, else success                                 */
9178 /* Parameters: arg(I) - pointer to soft context main structure              */
9179 /*                                                                          */
9180 /* Work through all of the subsystems inside IPFilter and call the create   */
9181 /* function for each in an order that won't lead to a crash :)              */
9182 /* ------------------------------------------------------------------------ */
9183 ipf_main_softc_t *
9184 ipf_create_all(void *arg)
9185 {
9186 	ipf_main_softc_t *softc;
9187 
9188 	softc = ipf_main_soft_create(arg);
9189 	if (softc == NULL)
9190 		return NULL;
9191 
9192 #ifdef IPFILTER_LOG
9193 	softc->ipf_log_soft = ipf_log_soft_create(softc);
9194 	if (softc->ipf_log_soft == NULL) {
9195 		ipf_destroy_all(softc);
9196 		return NULL;
9197 	}
9198 #endif
9199 
9200 	softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
9201 	if (softc->ipf_lookup_soft == NULL) {
9202 		ipf_destroy_all(softc);
9203 		return NULL;
9204 	}
9205 
9206 	softc->ipf_sync_soft = ipf_sync_soft_create(softc);
9207 	if (softc->ipf_sync_soft == NULL) {
9208 		ipf_destroy_all(softc);
9209 		return NULL;
9210 	}
9211 
9212 	softc->ipf_state_soft = ipf_state_soft_create(softc);
9213 	if (softc->ipf_state_soft == NULL) {
9214 		ipf_destroy_all(softc);
9215 		return NULL;
9216 	}
9217 
9218 	softc->ipf_nat_soft = ipf_nat_soft_create(softc);
9219 	if (softc->ipf_nat_soft == NULL) {
9220 		ipf_destroy_all(softc);
9221 		return NULL;
9222 	}
9223 
9224 	softc->ipf_frag_soft = ipf_frag_soft_create(softc);
9225 	if (softc->ipf_frag_soft == NULL) {
9226 		ipf_destroy_all(softc);
9227 		return NULL;
9228 	}
9229 
9230 	softc->ipf_auth_soft = ipf_auth_soft_create(softc);
9231 	if (softc->ipf_auth_soft == NULL) {
9232 		ipf_destroy_all(softc);
9233 		return NULL;
9234 	}
9235 
9236 	softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
9237 	if (softc->ipf_proxy_soft == NULL) {
9238 		ipf_destroy_all(softc);
9239 		return NULL;
9240 	}
9241 
9242 	return softc;
9243 }
9244 
9245 
9246 /* ------------------------------------------------------------------------ */
9247 /* Function:   ipf_destroy_all                                              */
9248 /* Returns:    void                                                         */
9249 /* Parameters: softc(I) - pointer to soft context main structure            */
9250 /*                                                                          */
9251 /* Work through all of the subsystems inside IPFilter and call the destroy  */
9252 /* function for each in an order that won't lead to a crash :)              */
9253 /*                                                                          */
9254 /* Every one of these functions is expected to succeed, so there is no      */
9255 /* checking of return values.                                               */
9256 /* ------------------------------------------------------------------------ */
9257 void
9258 ipf_destroy_all(ipf_main_softc_t *softc)
9259 {
9260 
9261 	if (softc->ipf_state_soft != NULL) {
9262 		ipf_state_soft_destroy(softc, softc->ipf_state_soft);
9263 		softc->ipf_state_soft = NULL;
9264 	}
9265 
9266 	if (softc->ipf_nat_soft != NULL) {
9267 		ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
9268 		softc->ipf_nat_soft = NULL;
9269 	}
9270 
9271 	if (softc->ipf_frag_soft != NULL) {
9272 		ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
9273 		softc->ipf_frag_soft = NULL;
9274 	}
9275 
9276 	if (softc->ipf_auth_soft != NULL) {
9277 		ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
9278 		softc->ipf_auth_soft = NULL;
9279 	}
9280 
9281 	if (softc->ipf_proxy_soft != NULL) {
9282 		ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
9283 		softc->ipf_proxy_soft = NULL;
9284 	}
9285 
9286 	if (softc->ipf_sync_soft != NULL) {
9287 		ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
9288 		softc->ipf_sync_soft = NULL;
9289 	}
9290 
9291 	if (softc->ipf_lookup_soft != NULL) {
9292 		ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
9293 		softc->ipf_lookup_soft = NULL;
9294 	}
9295 
9296 #ifdef IPFILTER_LOG
9297 	if (softc->ipf_log_soft != NULL) {
9298 		ipf_log_soft_destroy(softc, softc->ipf_log_soft);
9299 		softc->ipf_log_soft = NULL;
9300 	}
9301 #endif
9302 
9303 	ipf_main_soft_destroy(softc);
9304 }
9305 
9306 
9307 /* ------------------------------------------------------------------------ */
9308 /* Function:   ipf_init_all                                                 */
9309 /* Returns:    0 = success, -1 = failure                                    */
9310 /* Parameters: softc(I) - pointer to soft context main structure            */
9311 /*                                                                          */
9312 /* Work through all of the subsystems inside IPFilter and call the init     */
9313 /* function for each in an order that won't lead to a crash :)              */
9314 /* ------------------------------------------------------------------------ */
9315 int
9316 ipf_init_all(ipf_main_softc_t *softc)
9317 {
9318 
9319 	if (ipf_main_soft_init(softc) == -1)
9320 		return -1;
9321 
9322 #ifdef IPFILTER_LOG
9323 	if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
9324 		return -1;
9325 #endif
9326 
9327 	if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
9328 		return -1;
9329 
9330 	if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
9331 		return -1;
9332 
9333 	if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
9334 		return -1;
9335 
9336 	if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
9337 		return -1;
9338 
9339 	if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
9340 		return -1;
9341 
9342 	if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
9343 		return -1;
9344 
9345 	if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
9346 		return -1;
9347 
9348 	return 0;
9349 }
9350 
9351 
9352 /* ------------------------------------------------------------------------ */
9353 /* Function:   ipf_fini_all                                                 */
9354 /* Returns:    0 = success, -1 = failure                                    */
9355 /* Parameters: softc(I) - pointer to soft context main structure            */
9356 /*                                                                          */
9357 /* Work through all of the subsystems inside IPFilter and call the fini     */
9358 /* function for each in an order that won't lead to a crash :)              */
9359 /* ------------------------------------------------------------------------ */
9360 int
9361 ipf_fini_all(ipf_main_softc_t *softc)
9362 {
9363 
9364 	ipf_token_flush(softc);
9365 
9366 	if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
9367 		return -1;
9368 
9369 	if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
9370 		return -1;
9371 
9372 	if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
9373 		return -1;
9374 
9375 	if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
9376 		return -1;
9377 
9378 	if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
9379 		return -1;
9380 
9381 	if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
9382 		return -1;
9383 
9384 	if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
9385 		return -1;
9386 
9387 #ifdef IPFILTER_LOG
9388 	if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
9389 		return -1;
9390 #endif
9391 
9392 	if (ipf_main_soft_fini(softc) == -1)
9393 		return -1;
9394 
9395 	return 0;
9396 }
9397 
9398 
9399 /* ------------------------------------------------------------------------ */
9400 /* Function:    ipf_rule_expire                                             */
9401 /* Returns:     Nil                                                         */
9402 /* Parameters:  softc(I) - pointer to soft context main structure           */
9403 /*                                                                          */
9404 /* At present this function exists just to support temporary addition of    */
9405 /* firewall rules. Both inactive and active lists are scanned for items to  */
9406 /* purge, as by rights, the expiration is computed as soon as the rule is   */
9407 /* loaded in.                                                               */
9408 /* ------------------------------------------------------------------------ */
9409 void
9410 ipf_rule_expire(ipf_main_softc_t *softc)
9411 {
9412 	frentry_t *fr;
9413 
9414 	if ((softc->ipf_rule_explist[0] == NULL) &&
9415 	    (softc->ipf_rule_explist[1] == NULL))
9416 		return;
9417 
9418 	WRITE_ENTER(&softc->ipf_mutex);
9419 
9420 	while ((fr = softc->ipf_rule_explist[0]) != NULL) {
9421 		/*
9422 		 * Because the list is kept sorted on insertion, the fist
9423 		 * one that dies in the future means no more work to do.
9424 		 */
9425 		if (fr->fr_die > softc->ipf_ticks)
9426 			break;
9427 		ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
9428 	}
9429 
9430 	while ((fr = softc->ipf_rule_explist[1]) != NULL) {
9431 		/*
9432 		 * Because the list is kept sorted on insertion, the fist
9433 		 * one that dies in the future means no more work to do.
9434 		 */
9435 		if (fr->fr_die > softc->ipf_ticks)
9436 			break;
9437 		ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
9438 	}
9439 
9440 	RWLOCK_EXIT(&softc->ipf_mutex);
9441 }
9442 
9443 
9444 static int ipf_ht_node_cmp(const struct host_node_s *, const struct host_node_s *);
9445 static void ipf_ht_node_make_key(host_track_t *, host_node_t *, int,
9446 				 i6addr_t *);
9447 
9448 RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
9449 
9450 
9451 /* ------------------------------------------------------------------------ */
9452 /* Function:    ipf_ht_node_cmp                                             */
9453 /* Returns:     int   - 0 == nodes are the same, ..                         */
9454 /* Parameters:  k1(I) - pointer to first key to compare                     */
9455 /*              k2(I) - pointer to second key to compare                    */
9456 /*                                                                          */
9457 /* The "key" for the node is a combination of two fields: the address       */
9458 /* family and the address itself.                                           */
9459 /*                                                                          */
9460 /* Because we're not actually interpreting the address data, it isn't       */
9461 /* necessary to convert them to/from network/host byte order. The mask is   */
9462 /* just used to remove bits that aren't significant - it doesn't matter     */
9463 /* where they are, as long as they're always in the same place.             */
9464 /*                                                                          */
9465 /* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because    */
9466 /* this is where individual ones will differ the most - but not true for    */
9467 /* for /48's, etc.                                                          */
9468 /* ------------------------------------------------------------------------ */
9469 static int
9470 ipf_ht_node_cmp(const struct host_node_s *k1, const struct host_node_s *k2)
9471 {
9472 	int i;
9473 
9474 	i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
9475 	if (i != 0)
9476 		return i;
9477 
9478 	if (k1->hn_addr.adf_family == AF_INET)
9479 		return (k2->hn_addr.adf_addr.in4.s_addr -
9480 			k1->hn_addr.adf_addr.in4.s_addr);
9481 
9482 	i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
9483 	if (i != 0)
9484 		return i;
9485 	i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
9486 	if (i != 0)
9487 		return i;
9488 	i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
9489 	if (i != 0)
9490 		return i;
9491 	i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
9492 	return i;
9493 }
9494 
9495 
9496 /* ------------------------------------------------------------------------ */
9497 /* Function:    ipf_ht_node_make_key                                        */
9498 /* Returns:     Nil                                                         */
9499 /* parameters:  htp(I)    - pointer to address tracking structure           */
9500 /*              key(I)    - where to store masked address for lookup        */
9501 /*              family(I) - protocol family of address                      */
9502 /*              addr(I)   - pointer to network address                      */
9503 /*                                                                          */
9504 /* Using the "netmask" (number of bits) stored parent host tracking struct, */
9505 /* copy the address passed in into the key structure whilst masking out the */
9506 /* bits that we don't want.                                                 */
9507 /*                                                                          */
9508 /* Because the parser will set ht_netmask to 128 if there is no protocol    */
9509 /* specified (the parser doesn't know if it should be a v4 or v6 rule), we  */
9510 /* have to be wary of that and not allow 32-128 to happen.                  */
9511 /* ------------------------------------------------------------------------ */
9512 static void
9513 ipf_ht_node_make_key(host_track_t *htp, host_node_t *key, int family,
9514     i6addr_t *addr)
9515 {
9516 	key->hn_addr.adf_family = family;
9517 	if (family == AF_INET) {
9518 		u_32_t mask;
9519 		int bits;
9520 
9521 		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
9522 		bits = htp->ht_netmask;
9523 		if (bits >= 32) {
9524 			mask = 0xffffffff;
9525 		} else {
9526 			mask = htonl(0xffffffff << (32 - bits));
9527 		}
9528 		key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
9529 #ifdef USE_INET6
9530 	} else {
9531 		int bits = htp->ht_netmask;
9532 
9533 		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
9534 		if (bits > 96) {
9535 			key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
9536 					     htonl(0xffffffff << (128 - bits));
9537 			key->hn_addr.adf_addr.i6[2] = addr->i6[2];
9538 			key->hn_addr.adf_addr.i6[1] = addr->i6[2];
9539 			key->hn_addr.adf_addr.i6[0] = addr->i6[2];
9540 		} else if (bits > 64) {
9541 			key->hn_addr.adf_addr.i6[3] = 0;
9542 			key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
9543 					     htonl(0xffffffff << (96 - bits));
9544 			key->hn_addr.adf_addr.i6[1] = addr->i6[1];
9545 			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9546 		} else if (bits > 32) {
9547 			key->hn_addr.adf_addr.i6[3] = 0;
9548 			key->hn_addr.adf_addr.i6[2] = 0;
9549 			key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
9550 					     htonl(0xffffffff << (64 - bits));
9551 			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9552 		} else {
9553 			key->hn_addr.adf_addr.i6[3] = 0;
9554 			key->hn_addr.adf_addr.i6[2] = 0;
9555 			key->hn_addr.adf_addr.i6[1] = 0;
9556 			key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
9557 					     htonl(0xffffffff << (32 - bits));
9558 		}
9559 #endif
9560 	}
9561 }
9562 
9563 
9564 /* ------------------------------------------------------------------------ */
9565 /* Function:    ipf_ht_node_add                                             */
9566 /* Returns:     int       - 0 == success,  -1 == failure                    */
9567 /* Parameters:  softc(I)  - pointer to soft context main structure          */
9568 /*              htp(I)    - pointer to address tracking structure           */
9569 /*              family(I) - protocol family of address                      */
9570 /*              addr(I)   - pointer to network address                      */
9571 /*                                                                          */
9572 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
9573 /*       ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
9574 /*                                                                          */
9575 /* After preparing the key with the address information to find, look in    */
9576 /* the red-black tree to see if the address is known. A successful call to  */
9577 /* this function can mean one of two things: a new node was added to the    */
9578 /* tree or a matching node exists and we're able to bump up its activity.   */
9579 /* ------------------------------------------------------------------------ */
9580 int
9581 ipf_ht_node_add(ipf_main_softc_t *softc, host_track_t *htp, int family,
9582     i6addr_t *addr)
9583 {
9584 	host_node_t *h;
9585 	host_node_t k;
9586 
9587 	ipf_ht_node_make_key(htp, &k, family, addr);
9588 
9589 	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9590 	if (h == NULL) {
9591 		if (htp->ht_cur_nodes >= htp->ht_max_nodes)
9592 			return -1;
9593 		KMALLOC(h, host_node_t *);
9594 		if (h == NULL) {
9595 			DT(ipf_rb_no_mem);
9596 			LBUMP(ipf_rb_no_mem);
9597 			return -1;
9598 		}
9599 
9600 		/*
9601 		 * If there was a macro to initialise the RB node then that
9602 		 * would get used here, but there isn't...
9603 		 */
9604 		bzero((char *)h, sizeof(*h));
9605 		h->hn_addr = k.hn_addr;
9606 		h->hn_addr.adf_family = k.hn_addr.adf_family;
9607 		RBI_INSERT(ipf_rb, &htp->ht_root, h);
9608 		htp->ht_cur_nodes++;
9609 	} else {
9610 		if ((htp->ht_max_per_node != 0) &&
9611 		    (h->hn_active >= htp->ht_max_per_node)) {
9612 			DT(ipf_rb_node_max);
9613 			LBUMP(ipf_rb_node_max);
9614 			return -1;
9615 		}
9616 	}
9617 
9618 	h->hn_active++;
9619 
9620 	return 0;
9621 }
9622 
9623 
9624 /* ------------------------------------------------------------------------ */
9625 /* Function:    ipf_ht_node_del                                             */
9626 /* Returns:     int       - 0 == success,  -1 == failure                    */
9627 /* parameters:  htp(I)    - pointer to address tracking structure           */
9628 /*              family(I) - protocol family of address                      */
9629 /*              addr(I)   - pointer to network address                      */
9630 /*                                                                          */
9631 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
9632 /*       ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
9633 /*                                                                          */
9634 /* Try and find the address passed in amongst the leaves on this tree to    */
9635 /* be friend. If found then drop the active account for that node drops by  */
9636 /* one. If that count reaches 0, it is time to free it all up.              */
9637 /* ------------------------------------------------------------------------ */
9638 int
9639 ipf_ht_node_del(host_track_t *htp, int family, i6addr_t *addr)
9640 {
9641 	host_node_t *h;
9642 	host_node_t k;
9643 
9644 	ipf_ht_node_make_key(htp, &k, family, addr);
9645 
9646 	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9647 	if (h == NULL) {
9648 		return -1;
9649 	} else {
9650 		h->hn_active--;
9651 		if (h->hn_active == 0) {
9652 			(void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
9653 			htp->ht_cur_nodes--;
9654 			KFREE(h);
9655 		}
9656 	}
9657 
9658 	return 0;
9659 }
9660 
9661 
9662 /* ------------------------------------------------------------------------ */
9663 /* Function:    ipf_rb_ht_init                                              */
9664 /* Returns:     Nil                                                         */
9665 /* Parameters:  head(I) - pointer to host tracking structure                */
9666 /*                                                                          */
9667 /* Initialise the host tracking structure to be ready for use above.        */
9668 /* ------------------------------------------------------------------------ */
9669 void
9670 ipf_rb_ht_init(host_track_t *head)
9671 {
9672 	memset(head, 0, sizeof(*head));
9673 	RBI_INIT(ipf_rb, &head->ht_root);
9674 }
9675 
9676 
9677 /* ------------------------------------------------------------------------ */
9678 /* Function:    ipf_rb_ht_freenode                                          */
9679 /* Returns:     Nil                                                         */
9680 /* Parameters:  head(I) - pointer to host tracking structure                */
9681 /*              arg(I)  - additional argument from walk caller              */
9682 /*                                                                          */
9683 /* Free an actual host_node_t structure.                                    */
9684 /* ------------------------------------------------------------------------ */
9685 void
9686 ipf_rb_ht_freenode(host_node_t *node, void *arg)
9687 {
9688 	KFREE(node);
9689 }
9690 
9691 
9692 /* ------------------------------------------------------------------------ */
9693 /* Function:    ipf_rb_ht_flush                                             */
9694 /* Returns:     Nil                                                         */
9695 /* Parameters:  head(I) - pointer to host tracking structure                */
9696 /*                                                                          */
9697 /* Remove all of the nodes in the tree tracking hosts by calling a walker   */
9698 /* and free'ing each one.                                                   */
9699 /* ------------------------------------------------------------------------ */
9700 void
9701 ipf_rb_ht_flush(host_track_t *head)
9702 {
9703 	/* XXX - May use node members after freeing the node. */
9704 	RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
9705 }
9706 
9707 
9708 /* ------------------------------------------------------------------------ */
9709 /* Function:    ipf_slowtimer                                               */
9710 /* Returns:     Nil                                                         */
9711 /* Parameters:  ptr(I) - pointer to main ipf soft context structure         */
9712 /*                                                                          */
9713 /* Slowly expire held state for fragments.  Timeouts are set * in           */
9714 /* expectation of this being called twice per second.                       */
9715 /* ------------------------------------------------------------------------ */
9716 void
9717 ipf_slowtimer(ipf_main_softc_t *softc)
9718 {
9719 
9720 	ipf_token_expire(softc);
9721 	ipf_frag_expire(softc);
9722 	ipf_state_expire(softc);
9723 	ipf_nat_expire(softc);
9724 	ipf_auth_expire(softc);
9725 	ipf_lookup_expire(softc);
9726 	ipf_rule_expire(softc);
9727 	ipf_sync_expire(softc);
9728 	softc->ipf_ticks++;
9729 #   if defined(__OpenBSD__)
9730 	timeout_add(&ipf_slowtimer_ch, hz/2);
9731 #   endif
9732 }
9733 
9734 
9735 /* ------------------------------------------------------------------------ */
9736 /* Function:    ipf_inet_mask_add                                           */
9737 /* Returns:     Nil                                                         */
9738 /* Parameters:  bits(I) - pointer to nat context information                */
9739 /*              mtab(I) - pointer to mask hash table structure              */
9740 /*                                                                          */
9741 /* When called, bits represents the mask of a new NAT rule that has just    */
9742 /* been added. This function inserts a bitmask into the array of masks to   */
9743 /* search when searching for a matching NAT rule for a packet.              */
9744 /* Prevention of duplicate masks is achieved by checking the use count for  */
9745 /* a given netmask.                                                         */
9746 /* ------------------------------------------------------------------------ */
9747 void
9748 ipf_inet_mask_add(int bits, ipf_v4_masktab_t *mtab)
9749 {
9750 	u_32_t mask;
9751 	int i, j;
9752 
9753 	mtab->imt4_masks[bits]++;
9754 	if (mtab->imt4_masks[bits] > 1)
9755 		return;
9756 
9757 	if (bits == 0)
9758 		mask = 0;
9759 	else
9760 		mask = 0xffffffff << (32 - bits);
9761 
9762 	for (i = 0; i < 33; i++) {
9763 		if (ntohl(mtab->imt4_active[i]) < mask) {
9764 			for (j = 32; j > i; j--)
9765 				mtab->imt4_active[j] = mtab->imt4_active[j - 1];
9766 			mtab->imt4_active[i] = htonl(mask);
9767 			break;
9768 		}
9769 	}
9770 	mtab->imt4_max++;
9771 }
9772 
9773 
9774 /* ------------------------------------------------------------------------ */
9775 /* Function:    ipf_inet_mask_del                                           */
9776 /* Returns:     Nil                                                         */
9777 /* Parameters:  bits(I) - number of bits set in the netmask                 */
9778 /*              mtab(I) - pointer to mask hash table structure              */
9779 /*                                                                          */
9780 /* Remove the 32bit bitmask represented by "bits" from the collection of    */
9781 /* netmasks stored inside of mtab.                                          */
9782 /* ------------------------------------------------------------------------ */
9783 void
9784 ipf_inet_mask_del(int bits, ipf_v4_masktab_t *mtab)
9785 {
9786 	u_32_t mask;
9787 	int i, j;
9788 
9789 	mtab->imt4_masks[bits]--;
9790 	if (mtab->imt4_masks[bits] > 0)
9791 		return;
9792 
9793 	mask = htonl(0xffffffff << (32 - bits));
9794 	for (i = 0; i < 33; i++) {
9795 		if (mtab->imt4_active[i] == mask) {
9796 			for (j = i + 1; j < 33; j++)
9797 				mtab->imt4_active[j - 1] = mtab->imt4_active[j];
9798 			break;
9799 		}
9800 	}
9801 	mtab->imt4_max--;
9802 	ASSERT(mtab->imt4_max >= 0);
9803 }
9804 
9805 
9806 #ifdef USE_INET6
9807 /* ------------------------------------------------------------------------ */
9808 /* Function:    ipf_inet6_mask_add                                          */
9809 /* Returns:     Nil                                                         */
9810 /* Parameters:  bits(I) - number of bits set in mask                        */
9811 /*              mask(I) - pointer to mask to add                            */
9812 /*              mtab(I) - pointer to mask hash table structure              */
9813 /*                                                                          */
9814 /* When called, bitcount represents the mask of a IPv6 NAT map rule that    */
9815 /* has just been added. This function inserts a bitmask into the array of   */
9816 /* masks to search when searching for a matching NAT rule for a packet.     */
9817 /* Prevention of duplicate masks is achieved by checking the use count for  */
9818 /* a given netmask.                                                         */
9819 /* ------------------------------------------------------------------------ */
9820 void
9821 ipf_inet6_mask_add(int bits, i6addr_t *mask, ipf_v6_masktab_t *mtab)
9822 {
9823 	i6addr_t zero;
9824 	int i, j;
9825 
9826 	mtab->imt6_masks[bits]++;
9827 	if (mtab->imt6_masks[bits] > 1)
9828 		return;
9829 
9830 	if (bits == 0) {
9831 		mask = &zero;
9832 		zero.i6[0] = 0;
9833 		zero.i6[1] = 0;
9834 		zero.i6[2] = 0;
9835 		zero.i6[3] = 0;
9836 	}
9837 
9838 	for (i = 0; i < 129; i++) {
9839 		if (IP6_LT(&mtab->imt6_active[i], mask)) {
9840 			for (j = 128; j > i; j--)
9841 				mtab->imt6_active[j] = mtab->imt6_active[j - 1];
9842 			mtab->imt6_active[i] = *mask;
9843 			break;
9844 		}
9845 	}
9846 	mtab->imt6_max++;
9847 }
9848 
9849 
9850 /* ------------------------------------------------------------------------ */
9851 /* Function:    ipf_inet6_mask_del                                          */
9852 /* Returns:     Nil                                                         */
9853 /* Parameters:  bits(I) - number of bits set in mask                        */
9854 /*              mask(I) - pointer to mask to remove                         */
9855 /*              mtab(I) - pointer to mask hash table structure              */
9856 /*                                                                          */
9857 /* Remove the 128bit bitmask represented by "bits" from the collection of   */
9858 /* netmasks stored inside of mtab.                                          */
9859 /* ------------------------------------------------------------------------ */
9860 void
9861 ipf_inet6_mask_del(int bits, i6addr_t *mask, ipf_v6_masktab_t *mtab)
9862 {
9863 	i6addr_t zero;
9864 	int i, j;
9865 
9866 	mtab->imt6_masks[bits]--;
9867 	if (mtab->imt6_masks[bits] > 0)
9868 		return;
9869 
9870 	if (bits == 0)
9871 		mask = &zero;
9872 	zero.i6[0] = 0;
9873 	zero.i6[1] = 0;
9874 	zero.i6[2] = 0;
9875 	zero.i6[3] = 0;
9876 
9877 	for (i = 0; i < 129; i++) {
9878 		if (IP6_EQ(&mtab->imt6_active[i], mask)) {
9879 			for (j = i + 1; j < 129; j++) {
9880 				mtab->imt6_active[j - 1] = mtab->imt6_active[j];
9881 				if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
9882 					break;
9883 			}
9884 			break;
9885 		}
9886 	}
9887 	mtab->imt6_max--;
9888 	ASSERT(mtab->imt6_max >= 0);
9889 }
9890 #endif
9891