xref: /netbsd-src/sys/external/bsd/ipf/netinet/fil.c (revision 2d8e86c2f207da6fbbd50f11b6f33765ebdfa0e9)
1 /*	$NetBSD: fil.c,v 1.29 2019/06/28 23:25:12 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 #if defined(__NetBSD__)
137 #include <netinet/in_offload.h>
138 #endif
139 /* END OF INCLUDES */
140 
141 #if !defined(lint)
142 #if defined(__NetBSD__)
143 #include <sys/cdefs.h>
144 __KERNEL_RCSID(0, "$NetBSD: fil.c,v 1.29 2019/06/28 23:25:12 christos Exp $");
145 #else
146 static const char sccsid[] = "@(#)fil.c	1.36 6/5/96 (C) 1993-2000 Darren Reed";
147 static const char rcsid[] = "@(#)Id: fil.c,v 1.1.1.2 2012/07/22 13:45:07 darrenr Exp $";
148 #endif
149 #endif
150 
151 #ifndef	_KERNEL
152 # include "ipf.h"
153 # include "ipt.h"
154 extern	int	opts;
155 extern	int	blockreason;
156 #endif /* _KERNEL */
157 
158 #define	LBUMP(x)	softc->x++
159 #define	LBUMPD(x, y)	do { softc->x.y++; DT(y); } while (0)
160 
161 static	INLINE int	ipf_check_ipf(fr_info_t *, frentry_t *, int);
162 static	u_32_t		ipf_checkcipso(fr_info_t *, u_char *, int);
163 static	u_32_t		ipf_checkripso(u_char *);
164 static	u_32_t		ipf_decaps(fr_info_t *, u_32_t, int);
165 #ifdef	IPFILTER_LOG
166 static	frentry_t	*ipf_dolog(fr_info_t *, u_32_t *);
167 #endif
168 static	int		ipf_flushlist(ipf_main_softc_t *, int *, frentry_t **);
169 static	int		ipf_flush_groups(ipf_main_softc_t *, frgroup_t **, int);
170 static	ipfunc_t	ipf_findfunc(ipfunc_t);
171 static	void		*ipf_findlookup(ipf_main_softc_t *, int, frentry_t *,
172 					i6addr_t *, i6addr_t *);
173 static	frentry_t	*ipf_firewall(fr_info_t *, u_32_t *);
174 static	int		ipf_fr_matcharray(fr_info_t *, int *);
175 static	int		ipf_frruleiter(ipf_main_softc_t *, void *, int, void *);
176 static	void		ipf_funcfini(ipf_main_softc_t *, frentry_t *);;
177 static	int		ipf_funcinit(ipf_main_softc_t *, frentry_t *);
178 static	int		ipf_geniter(ipf_main_softc_t *, ipftoken_t *,
179 				    ipfgeniter_t *);
180 static	void		ipf_getstat(ipf_main_softc_t *,
181 				    struct friostat *, int);
182 static	int		ipf_group_flush(ipf_main_softc_t *, frgroup_t *);
183 static	void		ipf_group_free(frgroup_t *);
184 static	int		ipf_grpmapfini(struct ipf_main_softc_s *, frentry_t *);
185 static	int		ipf_grpmapinit(struct ipf_main_softc_s *, frentry_t *);
186 static	frentry_t	*ipf_nextrule(ipf_main_softc_t *, int, int,
187 					frentry_t *, int);
188 static	int		ipf_portcheck(frpcmp_t *, u_32_t);
189 static	INLINE int	ipf_pr_ah(fr_info_t *);
190 static	INLINE void	ipf_pr_esp(fr_info_t *);
191 static	INLINE void	ipf_pr_gre(fr_info_t *);
192 static	INLINE void	ipf_pr_udp(fr_info_t *);
193 static	INLINE void	ipf_pr_tcp(fr_info_t *);
194 static	INLINE void	ipf_pr_icmp(fr_info_t *);
195 static	INLINE void	ipf_pr_ipv4hdr(fr_info_t *);
196 static	INLINE void	ipf_pr_short(fr_info_t *, int);
197 static	INLINE int	ipf_pr_tcpcommon(fr_info_t *);
198 static	INLINE int	ipf_pr_udpcommon(fr_info_t *);
199 static	void		ipf_rule_delete(ipf_main_softc_t *, frentry_t *f,
200 					int, int);
201 static	void		ipf_rule_expire_insert(ipf_main_softc_t *,
202 					       frentry_t *, int);
203 static	int		ipf_synclist(ipf_main_softc_t *, frentry_t *, void *);
204 static	void		ipf_token_flush(ipf_main_softc_t *);
205 static	void		ipf_token_unlink(ipf_main_softc_t *, ipftoken_t *);
206 static	ipftuneable_t	*ipf_tune_findbyname(ipftuneable_t *, const char *);
207 static	ipftuneable_t	*ipf_tune_findbycookie(ipftuneable_t **, void *,
208 					       void **);
209 static	int		ipf_updateipid(fr_info_t *);
210 static	int		ipf_settimeout(struct ipf_main_softc_s *,
211 				       struct ipftuneable *, ipftuneval_t *);
212 
213 
214 /*
215  * bit values for identifying presence of individual IP options
216  * All of these tables should be ordered by increasing key value on the left
217  * hand side to allow for binary searching of the array and include a trailer
218  * with a 0 for the bitmask for linear searches to easily find the end with.
219  */
220 static const	struct	optlist	ipopts[20] = {
221 	{ IPOPT_NOP,	0x000001 },
222 	{ IPOPT_RR,	0x000002 },
223 	{ IPOPT_ZSU,	0x000004 },
224 	{ IPOPT_MTUP,	0x000008 },
225 	{ IPOPT_MTUR,	0x000010 },
226 	{ IPOPT_ENCODE,	0x000020 },
227 	{ IPOPT_TS,	0x000040 },
228 	{ IPOPT_TR,	0x000080 },
229 	{ IPOPT_SECURITY, 0x000100 },
230 	{ IPOPT_LSRR,	0x000200 },
231 	{ IPOPT_E_SEC,	0x000400 },
232 	{ IPOPT_CIPSO,	0x000800 },
233 	{ IPOPT_SATID,	0x001000 },
234 	{ IPOPT_SSRR,	0x002000 },
235 	{ IPOPT_ADDEXT,	0x004000 },
236 	{ IPOPT_VISA,	0x008000 },
237 	{ IPOPT_IMITD,	0x010000 },
238 	{ IPOPT_EIP,	0x020000 },
239 	{ IPOPT_FINN,	0x040000 },
240 	{ 0,		0x000000 }
241 };
242 
243 #ifdef USE_INET6
244 static const struct optlist ip6exthdr[] = {
245 	{ IPPROTO_HOPOPTS,		0x000001 },
246 	{ IPPROTO_IPV6,			0x000002 },
247 	{ IPPROTO_ROUTING,		0x000004 },
248 	{ IPPROTO_FRAGMENT,		0x000008 },
249 	{ IPPROTO_ESP,			0x000010 },
250 	{ IPPROTO_AH,			0x000020 },
251 	{ IPPROTO_NONE,			0x000040 },
252 	{ IPPROTO_DSTOPTS,		0x000080 },
253 	{ IPPROTO_MOBILITY,		0x000100 },
254 	{ 0,				0 }
255 };
256 #endif
257 
258 /*
259  * bit values for identifying presence of individual IP security options
260  */
261 static const	struct	optlist	secopt[8] = {
262 	{ IPSO_CLASS_RES4,	0x01 },
263 	{ IPSO_CLASS_TOPS,	0x02 },
264 	{ IPSO_CLASS_SECR,	0x04 },
265 	{ IPSO_CLASS_RES3,	0x08 },
266 	{ IPSO_CLASS_CONF,	0x10 },
267 	{ IPSO_CLASS_UNCL,	0x20 },
268 	{ IPSO_CLASS_RES2,	0x40 },
269 	{ IPSO_CLASS_RES1,	0x80 }
270 };
271 
272 char	ipfilter_version[] = IPL_VERSION;
273 
274 int	ipf_features = 0
275 #ifdef	IPFILTER_LKM
276 		| IPF_FEAT_LKM
277 #endif
278 #ifdef	IPFILTER_LOG
279 		| IPF_FEAT_LOG
280 #endif
281 		| IPF_FEAT_LOOKUP
282 #ifdef	IPFILTER_BPF
283 		| IPF_FEAT_BPF
284 #endif
285 #ifdef	IPFILTER_COMPILED
286 		| IPF_FEAT_COMPILED
287 #endif
288 #ifdef	IPFILTER_CKSUM
289 		| IPF_FEAT_CKSUM
290 #endif
291 		| IPF_FEAT_SYNC
292 #ifdef	IPFILTER_SCAN
293 		| IPF_FEAT_SCAN
294 #endif
295 #ifdef	USE_INET6
296 		| IPF_FEAT_IPV6
297 #endif
298 	;
299 
300 
301 /*
302  * Table of functions available for use with call rules.
303  */
304 static ipfunc_resolve_t ipf_availfuncs[] = {
305 	{ "srcgrpmap", ipf_srcgrpmap, ipf_grpmapinit, ipf_grpmapfini },
306 	{ "dstgrpmap", ipf_dstgrpmap, ipf_grpmapinit, ipf_grpmapfini },
307 	{ "",	       NULL,	      NULL,	      NULL }
308 };
309 
310 static const ipftuneable_t ipf_main_tuneables[] = {
311 	{ { (void *)offsetof(struct ipf_main_softc_s, ipf_flags) },
312 		"ipf_flags",		0,	0xffffffff,
313 		stsizeof(ipf_main_softc_t, ipf_flags),
314 		0,			NULL,	NULL },
315 	{ { (void *)offsetof(struct ipf_main_softc_s, ipf_active) },
316 		"active",		0,	0,
317 		stsizeof(ipf_main_softc_t, ipf_active),
318 		IPFT_RDONLY,		NULL,	NULL },
319 	{ { (void *)offsetof(ipf_main_softc_t, ipf_control_forwarding) },
320 		"control_forwarding",	0, 1,
321 		stsizeof(ipf_main_softc_t, ipf_control_forwarding),
322 		0,			NULL,	NULL },
323 	{ { (void *)offsetof(ipf_main_softc_t, ipf_update_ipid) },
324 		"update_ipid",		0,	1,
325 		stsizeof(ipf_main_softc_t, ipf_update_ipid),
326 		0,			NULL,	NULL },
327 	{ { (void *)offsetof(ipf_main_softc_t, ipf_chksrc) },
328 		"chksrc",		0,	1,
329 		stsizeof(ipf_main_softc_t, ipf_chksrc),
330 		0,			NULL,	NULL },
331 	{ { (void *)offsetof(ipf_main_softc_t, ipf_minttl) },
332 		"min_ttl",		0,	1,
333 		stsizeof(ipf_main_softc_t, ipf_minttl),
334 		0,			NULL,	NULL },
335 	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmpminfragmtu) },
336 		"icmp_minfragmtu",	0,	1,
337 		stsizeof(ipf_main_softc_t, ipf_icmpminfragmtu),
338 		0,			NULL,	NULL },
339 	{ { (void *)offsetof(ipf_main_softc_t, ipf_pass) },
340 		"default_pass",		0,	0xffffffff,
341 		stsizeof(ipf_main_softc_t, ipf_pass),
342 		0,			NULL,	NULL },
343 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpidletimeout) },
344 		"tcp_idle_timeout",	1,	0x7fffffff,
345 		stsizeof(ipf_main_softc_t, ipf_tcpidletimeout),
346 		0,			NULL,	ipf_settimeout },
347 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosewait) },
348 		"tcp_close_wait",	1,	0x7fffffff,
349 		stsizeof(ipf_main_softc_t, ipf_tcpclosewait),
350 		0,			NULL,	ipf_settimeout },
351 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcplastack) },
352 		"tcp_last_ack",		1,	0x7fffffff,
353 		stsizeof(ipf_main_softc_t, ipf_tcplastack),
354 		0,			NULL,	ipf_settimeout },
355 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcptimeout) },
356 		"tcp_timeout",		1,	0x7fffffff,
357 		stsizeof(ipf_main_softc_t, ipf_tcptimeout),
358 		0,			NULL,	ipf_settimeout },
359 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynsent) },
360 		"tcp_syn_sent",		1,	0x7fffffff,
361 		stsizeof(ipf_main_softc_t, ipf_tcpsynsent),
362 		0,			NULL,	ipf_settimeout },
363 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynrecv) },
364 		"tcp_syn_received",	1,	0x7fffffff,
365 		stsizeof(ipf_main_softc_t, ipf_tcpsynrecv),
366 		0,			NULL,	ipf_settimeout },
367 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosed) },
368 		"tcp_closed",		1,	0x7fffffff,
369 		stsizeof(ipf_main_softc_t, ipf_tcpclosed),
370 		0,			NULL,	ipf_settimeout },
371 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcphalfclosed) },
372 		"tcp_half_closed",	1,	0x7fffffff,
373 		stsizeof(ipf_main_softc_t, ipf_tcphalfclosed),
374 		0,			NULL,	ipf_settimeout },
375 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcptimewait) },
376 		"tcp_time_wait",	1,	0x7fffffff,
377 		stsizeof(ipf_main_softc_t, ipf_tcptimewait),
378 		0,			NULL,	ipf_settimeout },
379 	{ { (void *)offsetof(ipf_main_softc_t, ipf_udptimeout) },
380 		"udp_timeout",		1,	0x7fffffff,
381 		stsizeof(ipf_main_softc_t, ipf_udptimeout),
382 		0,			NULL,	ipf_settimeout },
383 	{ { (void *)offsetof(ipf_main_softc_t, ipf_udpacktimeout) },
384 		"udp_ack_timeout",	1,	0x7fffffff,
385 		stsizeof(ipf_main_softc_t, ipf_udpacktimeout),
386 		0,			NULL,	ipf_settimeout },
387 	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmptimeout) },
388 		"icmp_timeout",		1,	0x7fffffff,
389 		stsizeof(ipf_main_softc_t, ipf_icmptimeout),
390 		0,			NULL,	ipf_settimeout },
391 	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmpacktimeout) },
392 		"icmp_ack_timeout",	1,	0x7fffffff,
393 		stsizeof(ipf_main_softc_t, ipf_icmpacktimeout),
394 		0,			NULL,	ipf_settimeout },
395 	{ { (void *)offsetof(ipf_main_softc_t, ipf_iptimeout) },
396 		"ip_timeout",		1,	0x7fffffff,
397 		stsizeof(ipf_main_softc_t, ipf_iptimeout),
398 		0,			NULL,	ipf_settimeout },
399 #if defined(INSTANCES) && defined(_KERNEL)
400 	{ { (void *)offsetof(ipf_main_softc_t, ipf_get_loopback) },
401 		"intercept_loopback",	0,	1,
402 		stsizeof(ipf_main_softc_t, ipf_get_loopback),
403 		0,			NULL,	ipf_set_loopback },
404 #endif
405 	{ { 0 },
406 		NULL,			0,	0,
407 		0,
408 		0,			NULL,	NULL }
409 };
410 
411 
412 /*
413  * The next section of code is a a collection of small routines that set
414  * fields in the fr_info_t structure passed based on properties of the
415  * current packet.  There are different routines for the same protocol
416  * for each of IPv4 and IPv6.  Adding a new protocol, for which there
417  * will "special" inspection for setup, is now more easily done by adding
418  * a new routine and expanding the ipf_pr_ipinit*() function rather than by
419  * adding more code to a growing switch statement.
420  */
421 #ifdef USE_INET6
422 static	INLINE int	ipf_pr_ah6(fr_info_t *);
423 static	INLINE void	ipf_pr_esp6(fr_info_t *);
424 static	INLINE void	ipf_pr_gre6(fr_info_t *);
425 static	INLINE void	ipf_pr_udp6(fr_info_t *);
426 static	INLINE void	ipf_pr_tcp6(fr_info_t *);
427 static	INLINE void	ipf_pr_icmp6(fr_info_t *);
428 static	INLINE void	ipf_pr_ipv6hdr(fr_info_t *);
429 static	INLINE void	ipf_pr_short6(fr_info_t *, int);
430 static	INLINE int	ipf_pr_hopopts6(fr_info_t *);
431 static	INLINE int	ipf_pr_mobility6(fr_info_t *);
432 static	INLINE int	ipf_pr_routing6(fr_info_t *);
433 static	INLINE int	ipf_pr_dstopts6(fr_info_t *);
434 static	INLINE int	ipf_pr_fragment6(fr_info_t *);
435 static	INLINE struct ip6_ext *ipf_pr_ipv6exthdr(fr_info_t *, int, int);
436 
437 
438 /* ------------------------------------------------------------------------ */
439 /* Function:    ipf_pr_short6                                               */
440 /* Returns:     void                                                        */
441 /* Parameters:  fin(I)  - pointer to packet information                     */
442 /*              xmin(I) - minimum header size                               */
443 /*                                                                          */
444 /* IPv6 Only                                                                */
445 /* This is function enforces the 'is a packet too short to be legit' rule   */
446 /* for IPv6 and marks the packet with FI_SHORT if so.  See function comment */
447 /* for ipf_pr_short() for more details.                                     */
448 /* ------------------------------------------------------------------------ */
449 static INLINE void
450 ipf_pr_short6(fr_info_t *fin, int xmin)
451 {
452 
453 	if (fin->fin_dlen < xmin)
454 		fin->fin_flx |= FI_SHORT;
455 }
456 
457 
458 /* ------------------------------------------------------------------------ */
459 /* Function:    ipf_pr_ipv6hdr                                              */
460 /* Returns:     void                                                        */
461 /* Parameters:  fin(I) - pointer to packet information                      */
462 /*                                                                          */
463 /* IPv6 Only                                                                */
464 /* Copy values from the IPv6 header into the fr_info_t struct and call the  */
465 /* per-protocol analyzer if it exists.  In validating the packet, a protocol*/
466 /* analyzer may pullup or free the packet itself so we need to be vigiliant */
467 /* of that possibility arising.                                             */
468 /* ------------------------------------------------------------------------ */
469 static INLINE void
470 ipf_pr_ipv6hdr(fr_info_t *fin)
471 {
472 	ip6_t *ip6 = (ip6_t *)fin->fin_ip;
473 	int p, go = 1, i, hdrcount;
474 	fr_ip_t *fi = &fin->fin_fi;
475 
476 	fin->fin_off = 0;
477 
478 	fi->fi_tos = 0;
479 	fi->fi_optmsk = 0;
480 	fi->fi_secmsk = 0;
481 	fi->fi_auth = 0;
482 
483 	p = ip6->ip6_nxt;
484 	fin->fin_crc = p;
485 	fi->fi_ttl = ip6->ip6_hlim;
486 	fi->fi_src.in6 = ip6->ip6_src;
487 	fin->fin_crc += fi->fi_src.i6[0];
488 	fin->fin_crc += fi->fi_src.i6[1];
489 	fin->fin_crc += fi->fi_src.i6[2];
490 	fin->fin_crc += fi->fi_src.i6[3];
491 	fi->fi_dst.in6 = ip6->ip6_dst;
492 	fin->fin_crc += fi->fi_dst.i6[0];
493 	fin->fin_crc += fi->fi_dst.i6[1];
494 	fin->fin_crc += fi->fi_dst.i6[2];
495 	fin->fin_crc += fi->fi_dst.i6[3];
496 	fin->fin_id = 0;
497 	if (IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
498 		fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
499 
500 	hdrcount = 0;
501 	while (go && !(fin->fin_flx & FI_SHORT)) {
502 		switch (p)
503 		{
504 		case IPPROTO_UDP :
505 			ipf_pr_udp6(fin);
506 			go = 0;
507 			break;
508 
509 		case IPPROTO_TCP :
510 			ipf_pr_tcp6(fin);
511 			go = 0;
512 			break;
513 
514 		case IPPROTO_ICMPV6 :
515 			ipf_pr_icmp6(fin);
516 			go = 0;
517 			break;
518 
519 		case IPPROTO_GRE :
520 			ipf_pr_gre6(fin);
521 			go = 0;
522 			break;
523 
524 		case IPPROTO_HOPOPTS :
525 			p = ipf_pr_hopopts6(fin);
526 			break;
527 
528 		case IPPROTO_MOBILITY :
529 			p = ipf_pr_mobility6(fin);
530 			break;
531 
532 		case IPPROTO_DSTOPTS :
533 			p = ipf_pr_dstopts6(fin);
534 			break;
535 
536 		case IPPROTO_ROUTING :
537 			p = ipf_pr_routing6(fin);
538 			break;
539 
540 		case IPPROTO_AH :
541 			p = ipf_pr_ah6(fin);
542 			break;
543 
544 		case IPPROTO_ESP :
545 			ipf_pr_esp6(fin);
546 			go = 0;
547 			break;
548 
549 		case IPPROTO_IPV6 :
550 			for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
551 				if (ip6exthdr[i].ol_val == p) {
552 					fin->fin_flx |= ip6exthdr[i].ol_bit;
553 					break;
554 				}
555 			go = 0;
556 			break;
557 
558 		case IPPROTO_NONE :
559 			go = 0;
560 			break;
561 
562 		case IPPROTO_FRAGMENT :
563 			p = ipf_pr_fragment6(fin);
564 			/*
565 			 * Given that the only fragments we want to let through
566 			 * (where fin_off != 0) are those where the non-first
567 			 * fragments only have data, we can safely stop looking
568 			 * at headers if this is a non-leading fragment.
569 			 */
570 			if (fin->fin_off != 0)
571 				go = 0;
572 			break;
573 
574 		default :
575 			go = 0;
576 			break;
577 		}
578 		hdrcount++;
579 
580 		/*
581 		 * It is important to note that at this point, for the
582 		 * extension headers (go != 0), the entire header may not have
583 		 * been pulled up when the code gets to this point.  This is
584 		 * only done for "go != 0" because the other header handlers
585 		 * will all pullup their complete header.  The other indicator
586 		 * of an incomplete packet is that this was just an extension
587 		 * header.
588 		 */
589 		if ((go != 0) && (p != IPPROTO_NONE) &&
590 		    (ipf_pr_pullup(fin, 0) == -1)) {
591 			p = IPPROTO_NONE;
592 			break;
593 		}
594 	}
595 
596 	/*
597 	 * Some of the above functions, like ipf_pr_esp6(), can call ipf_pullup
598 	 * and destroy whatever packet was here.  The caller of this function
599 	 * expects us to return if there is a problem with ipf_pullup.
600 	 */
601 	if (fin->fin_m == NULL) {
602 		ipf_main_softc_t *softc = fin->fin_main_soft;
603 
604 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_bad);
605 		return;
606 	}
607 
608 	fi->fi_p = p;
609 
610 	/*
611 	 * IPv6 fragment case 1 - see comment for ipf_pr_fragment6().
612 	 * "go != 0" imples the above loop hasn't arrived at a layer 4 header.
613 	 */
614 	if ((go != 0) && (fin->fin_flx & FI_FRAG) && (fin->fin_off == 0)) {
615 		ipf_main_softc_t *softc = fin->fin_main_soft;
616 
617 		fin->fin_flx |= FI_BAD;
618 		DT2(ipf_fi_bad_ipv6_frag_1, fr_info_t *, fin, int, go);
619 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_badfrag);
620 		LBUMP(ipf_stats[fin->fin_out].fr_v6_bad);
621 	}
622 }
623 
624 
625 /* ------------------------------------------------------------------------ */
626 /* Function:    ipf_pr_ipv6exthdr                                           */
627 /* Returns:     struct ip6_ext * - pointer to the start of the next header  */
628 /*                                 or NULL if there is a prolblem.          */
629 /* Parameters:  fin(I)      - pointer to packet information                 */
630 /*              multiple(I) - flag indicating yes/no if multiple occurances */
631 /*                            of this extension header are allowed.         */
632 /*              proto(I)    - protocol number for this extension header     */
633 /*                                                                          */
634 /* IPv6 Only                                                                */
635 /* This function embodies a number of common checks that all IPv6 extension */
636 /* headers must be subjected to.  For example, making sure the packet is    */
637 /* big enough for it to be in, checking if it is repeated and setting a     */
638 /* flag to indicate its presence.                                           */
639 /* ------------------------------------------------------------------------ */
640 static INLINE struct ip6_ext *
641 ipf_pr_ipv6exthdr(fr_info_t *fin, int multiple, int proto)
642 {
643 	ipf_main_softc_t *softc = fin->fin_main_soft;
644 	struct ip6_ext *hdr;
645 	u_short shift;
646 	int i;
647 
648 	fin->fin_flx |= FI_V6EXTHDR;
649 
650 				/* 8 is default length of extension hdr */
651 	if ((fin->fin_dlen - 8) < 0) {
652 		fin->fin_flx |= FI_SHORT;
653 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_short);
654 		return NULL;
655 	}
656 
657 	if (ipf_pr_pullup(fin, 8) == -1) {
658 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_pullup);
659 		return NULL;
660 	}
661 
662 	hdr = fin->fin_dp;
663 	switch (proto)
664 	{
665 	case IPPROTO_FRAGMENT :
666 		shift = 8;
667 		break;
668 	default :
669 		shift = 8 + (hdr->ip6e_len << 3);
670 		break;
671 	}
672 
673 	if (shift > fin->fin_dlen) {	/* Nasty extension header length? */
674 		fin->fin_flx |= FI_BAD;
675 		DT3(ipf_fi_bad_pr_ipv6exthdr_len, fr_info_t *, fin, u_short, shift, u_short, fin->fin_dlen);
676 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_hlen);
677 		return NULL;
678 	}
679 
680 	fin->fin_dp = (char *)fin->fin_dp + shift;
681 	fin->fin_dlen -= shift;
682 
683 	/*
684 	 * If we have seen a fragment header, do not set any flags to indicate
685 	 * the presence of this extension header as it has no impact on the
686 	 * end result until after it has been defragmented.
687 	 */
688 	if (fin->fin_flx & FI_FRAG)
689 		return hdr;
690 
691 	for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
692 		if (ip6exthdr[i].ol_val == proto) {
693 			/*
694 			 * Most IPv6 extension headers are only allowed once.
695 			 */
696 			if ((multiple == 0) &&
697 			    ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0)) {
698 				fin->fin_flx |= FI_BAD;
699 				DT2(ipf_fi_bad_ipv6exthdr_once, fr_info_t *, fin, u_int, (fin->fin_optmsk & ip6exthdr[i].ol_bit));
700 			} else
701 				fin->fin_optmsk |= ip6exthdr[i].ol_bit;
702 			break;
703 		}
704 
705 	return hdr;
706 }
707 
708 
709 /* ------------------------------------------------------------------------ */
710 /* Function:    ipf_pr_hopopts6                                             */
711 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
712 /* Parameters:  fin(I) - pointer to packet information                      */
713 /*                                                                          */
714 /* IPv6 Only                                                                */
715 /* This is function checks pending hop by hop options extension header      */
716 /* ------------------------------------------------------------------------ */
717 static INLINE int
718 ipf_pr_hopopts6(fr_info_t *fin)
719 {
720 	struct ip6_ext *hdr;
721 
722 	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
723 	if (hdr == NULL)
724 		return IPPROTO_NONE;
725 	return hdr->ip6e_nxt;
726 }
727 
728 
729 /* ------------------------------------------------------------------------ */
730 /* Function:    ipf_pr_mobility6                                            */
731 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
732 /* Parameters:  fin(I) - pointer to packet information                      */
733 /*                                                                          */
734 /* IPv6 Only                                                                */
735 /* This is function checks the IPv6 mobility extension header               */
736 /* ------------------------------------------------------------------------ */
737 static INLINE int
738 ipf_pr_mobility6(fr_info_t *fin)
739 {
740 	struct ip6_ext *hdr;
741 
742 	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_MOBILITY);
743 	if (hdr == NULL)
744 		return IPPROTO_NONE;
745 	return hdr->ip6e_nxt;
746 }
747 
748 
749 /* ------------------------------------------------------------------------ */
750 /* Function:    ipf_pr_routing6                                             */
751 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
752 /* Parameters:  fin(I) - pointer to packet information                      */
753 /*                                                                          */
754 /* IPv6 Only                                                                */
755 /* This is function checks pending routing extension header                 */
756 /* ------------------------------------------------------------------------ */
757 static INLINE int
758 ipf_pr_routing6(fr_info_t *fin)
759 {
760 	struct ip6_routing *hdr;
761 
762 	hdr = (struct ip6_routing *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_ROUTING);
763 	if (hdr == NULL)
764 		return IPPROTO_NONE;
765 
766 	switch (hdr->ip6r_type)
767 	{
768 	case 0 :
769 		/*
770 		 * Nasty extension header length?
771 		 */
772 		if (((hdr->ip6r_len >> 1) < hdr->ip6r_segleft) ||
773 		    (hdr->ip6r_segleft && (hdr->ip6r_len & 1))) {
774 			ipf_main_softc_t *softc = fin->fin_main_soft;
775 
776 			fin->fin_flx |= FI_BAD;
777 			DT1(ipf_fi_bad_routing6, fr_info_t *, fin);
778 			LBUMPD(ipf_stats[fin->fin_out], fr_v6_rh_bad);
779 			return IPPROTO_NONE;
780 		}
781 		break;
782 
783 	default :
784 		break;
785 	}
786 
787 	return hdr->ip6r_nxt;
788 }
789 
790 
791 /* ------------------------------------------------------------------------ */
792 /* Function:    ipf_pr_fragment6                                            */
793 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
794 /* Parameters:  fin(I) - pointer to packet information                      */
795 /*                                                                          */
796 /* IPv6 Only                                                                */
797 /* Examine the IPv6 fragment header and extract fragment offset information.*/
798 /*                                                                          */
799 /* Fragments in IPv6 are extraordinarily difficult to deal with - much more */
800 /* so than in IPv4.  There are 5 cases of fragments with IPv6 that all      */
801 /* packets with a fragment header can fit into.  They are as follows:       */
802 /*                                                                          */
803 /* 1.  [IPv6][0-n EH][FH][0-n EH] (no L4HDR present)                        */
804 /* 2.  [IPV6][0-n EH][FH][0-n EH][L4HDR part] (short)                       */
805 /* 3.  [IPV6][0-n EH][FH][L4HDR part][0-n data] (short)                     */
806 /* 4.  [IPV6][0-n EH][FH][0-n EH][L4HDR][0-n data]                          */
807 /* 5.  [IPV6][0-n EH][FH][data]                                             */
808 /*                                                                          */
809 /* IPV6 = IPv6 header, FH = Fragment Header,                                */
810 /* 0-n EH = 0 or more extension headers, 0-n data = 0 or more bytes of data */
811 /*                                                                          */
812 /* Packets that match 1, 2, 3 will be dropped as the only reasonable        */
813 /* scenario in which they happen is in extreme circumstances that are most  */
814 /* likely to be an indication of an attack rather than normal traffic.      */
815 /* A type 3 packet may be sent by an attacked after a type 4 packet.  There */
816 /* are two rules that can be used to guard against type 3 packets: L4       */
817 /* headers must always be in a packet that has the offset field set to 0    */
818 /* and no packet is allowed to overlay that where offset = 0.               */
819 /* ------------------------------------------------------------------------ */
820 static INLINE int
821 ipf_pr_fragment6(fr_info_t *fin)
822 {
823 	ipf_main_softc_t *softc = fin->fin_main_soft;
824 	struct ip6_frag *frag;
825 
826 	fin->fin_flx |= FI_FRAG;
827 
828 	frag = (struct ip6_frag *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT);
829 	if (frag == NULL) {
830 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_frag_bad);
831 		return IPPROTO_NONE;
832 	}
833 
834 	if ((frag->ip6f_offlg & IP6F_MORE_FRAG) != 0) {
835 		/*
836 		 * Any fragment that isn't the last fragment must have its
837 		 * length as a multiple of 8.
838 		 */
839 		if ((fin->fin_plen & 7) != 0) {
840 			fin->fin_flx |= FI_BAD;
841 			DT2(ipf_fi_bad_frag_not_8, fr_info_t *, fin, u_int, (fin->fin_plen & 7));
842 		}
843 	}
844 
845 	fin->fin_fraghdr = frag;
846 	fin->fin_id = frag->ip6f_ident;
847 	fin->fin_off = ntohs(frag->ip6f_offlg & IP6F_OFF_MASK);
848 	if (fin->fin_off != 0)
849 		fin->fin_flx |= FI_FRAGBODY;
850 
851 	/*
852 	 * Jumbograms aren't handled, so the max. length is 64k
853 	 */
854 	if ((fin->fin_off << 3) + fin->fin_dlen > 65535) {
855 		  fin->fin_flx |= FI_BAD;
856 		  DT2(ipf_fi_bad_jumbogram, fr_info_t *, fin, u_int, ((fin->fin_off << 3) + fin->fin_dlen));
857 	}
858 
859 	/*
860 	 * We don't know where the transport layer header (or whatever is next
861 	 * is), as it could be behind destination options (amongst others) so
862 	 * return the fragment header as the type of packet this is.  Note that
863 	 * this effectively disables the fragment cache for > 1 protocol at a
864 	 * time.
865 	 */
866 	return frag->ip6f_nxt;
867 }
868 
869 
870 /* ------------------------------------------------------------------------ */
871 /* Function:    ipf_pr_dstopts6                                             */
872 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
873 /* Parameters:  fin(I) - pointer to packet information                      */
874 /*                                                                          */
875 /* IPv6 Only                                                                */
876 /* This is function checks pending destination options extension header     */
877 /* ------------------------------------------------------------------------ */
878 static INLINE int
879 ipf_pr_dstopts6(fr_info_t *fin)
880 {
881 	ipf_main_softc_t *softc = fin->fin_main_soft;
882 	struct ip6_ext *hdr;
883 
884 	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_DSTOPTS);
885 	if (hdr == NULL) {
886 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_dst_bad);
887 		return IPPROTO_NONE;
888 	}
889 	return hdr->ip6e_nxt;
890 }
891 
892 
893 /* ------------------------------------------------------------------------ */
894 /* Function:    ipf_pr_icmp6                                                */
895 /* Returns:     void                                                        */
896 /* Parameters:  fin(I) - pointer to packet information                      */
897 /*                                                                          */
898 /* IPv6 Only                                                                */
899 /* This routine is mainly concerned with determining the minimum valid size */
900 /* for an ICMPv6 packet.                                                    */
901 /* ------------------------------------------------------------------------ */
902 static INLINE void
903 ipf_pr_icmp6(fr_info_t *fin)
904 {
905 	int minicmpsz = sizeof(struct icmp6_hdr);
906 	struct icmp6_hdr *icmp6;
907 
908 	if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1) {
909 		ipf_main_softc_t *softc = fin->fin_main_soft;
910 
911 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_icmp6_pullup);
912 		return;
913 	}
914 
915 	if (fin->fin_dlen > 1) {
916 		ip6_t *ip6;
917 
918 		icmp6 = fin->fin_dp;
919 
920 		fin->fin_data[0] = *(u_short *)icmp6;
921 
922 		if ((icmp6->icmp6_type & ICMP6_INFOMSG_MASK) != 0)
923 			fin->fin_flx |= FI_ICMPQUERY;
924 
925 		switch (icmp6->icmp6_type)
926 		{
927 		case ICMP6_ECHO_REPLY :
928 		case ICMP6_ECHO_REQUEST :
929 			if (fin->fin_dlen >= 6)
930 				fin->fin_data[1] = icmp6->icmp6_id;
931 			minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
932 			break;
933 
934 		case ICMP6_DST_UNREACH :
935 		case ICMP6_PACKET_TOO_BIG :
936 		case ICMP6_TIME_EXCEEDED :
937 		case ICMP6_PARAM_PROB :
938 			fin->fin_flx |= FI_ICMPERR;
939 			minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
940 			if (fin->fin_plen < ICMP6ERR_IPICMPHLEN)
941 				break;
942 
943 			if (M_LEN(fin->fin_m) < fin->fin_plen) {
944 				if (ipf_coalesce(fin) != 1)
945 					return;
946 			}
947 
948 			if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN) == -1)
949 				return;
950 
951 			/*
952 			 * If the destination of this packet doesn't match the
953 			 * source of the original packet then this packet is
954 			 * not correct.
955 			 */
956 			icmp6 = fin->fin_dp;
957 			ip6 = (ip6_t *)((char *)icmp6 + ICMPERR_ICMPHLEN);
958 			if (IP6_NEQ(&fin->fin_fi.fi_dst,
959 				    &ip6->ip6_src)) {
960 				fin->fin_flx |= FI_BAD;
961 				DT1(ipf_fi_bad_icmp6, fr_info_t *, fin);
962 			}
963 			break;
964 		default :
965 			break;
966 		}
967 	}
968 
969 	ipf_pr_short6(fin, minicmpsz);
970 	if ((fin->fin_flx & (FI_SHORT|FI_BAD)) == 0) {
971 		u_char p = fin->fin_p;
972 
973 		fin->fin_p = IPPROTO_ICMPV6;
974 		ipf_checkv6sum(fin);
975 		fin->fin_p = p;
976 	}
977 }
978 
979 
980 /* ------------------------------------------------------------------------ */
981 /* Function:    ipf_pr_udp6                                                 */
982 /* Returns:     void                                                        */
983 /* Parameters:  fin(I) - pointer to packet information                      */
984 /*                                                                          */
985 /* IPv6 Only                                                                */
986 /* Analyse the packet for IPv6/UDP properties.                              */
987 /* Is not expected to be called for fragmented packets.                     */
988 /* ------------------------------------------------------------------------ */
989 static INLINE void
990 ipf_pr_udp6(fr_info_t *fin)
991 {
992 
993 	if (ipf_pr_udpcommon(fin) == 0) {
994 		u_char p = fin->fin_p;
995 
996 		fin->fin_p = IPPROTO_UDP;
997 		ipf_checkv6sum(fin);
998 		fin->fin_p = p;
999 	}
1000 }
1001 
1002 
1003 /* ------------------------------------------------------------------------ */
1004 /* Function:    ipf_pr_tcp6                                                 */
1005 /* Returns:     void                                                        */
1006 /* Parameters:  fin(I) - pointer to packet information                      */
1007 /*                                                                          */
1008 /* IPv6 Only                                                                */
1009 /* Analyse the packet for IPv6/TCP properties.                              */
1010 /* Is not expected to be called for fragmented packets.                     */
1011 /* ------------------------------------------------------------------------ */
1012 static INLINE void
1013 ipf_pr_tcp6(fr_info_t *fin)
1014 {
1015 
1016 	if (ipf_pr_tcpcommon(fin) == 0) {
1017 		u_char p = fin->fin_p;
1018 
1019 		fin->fin_p = IPPROTO_TCP;
1020 		ipf_checkv6sum(fin);
1021 		fin->fin_p = p;
1022 	}
1023 }
1024 
1025 
1026 /* ------------------------------------------------------------------------ */
1027 /* Function:    ipf_pr_esp6                                                 */
1028 /* Returns:     void                                                        */
1029 /* Parameters:  fin(I) - pointer to packet information                      */
1030 /*                                                                          */
1031 /* IPv6 Only                                                                */
1032 /* Analyse the packet for ESP properties.                                   */
1033 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
1034 /* even though the newer ESP packets must also have a sequence number that  */
1035 /* is 32bits as well, it is not possible(?) to determine the version from a */
1036 /* simple packet header.                                                    */
1037 /* ------------------------------------------------------------------------ */
1038 static INLINE void
1039 ipf_pr_esp6(fr_info_t *fin)
1040 {
1041 
1042 	if ((fin->fin_off == 0) && (ipf_pr_pullup(fin, 8) == -1)) {
1043 		ipf_main_softc_t *softc = fin->fin_main_soft;
1044 
1045 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_esp_pullup);
1046 		return;
1047 	}
1048 }
1049 
1050 
1051 /* ------------------------------------------------------------------------ */
1052 /* Function:    ipf_pr_ah6                                                  */
1053 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
1054 /* Parameters:  fin(I) - pointer to packet information                      */
1055 /*                                                                          */
1056 /* IPv6 Only                                                                */
1057 /* Analyse the packet for AH properties.                                    */
1058 /* The minimum length is taken to be the combination of all fields in the   */
1059 /* header being present and no authentication data (null algorithm used.)   */
1060 /* ------------------------------------------------------------------------ */
1061 static INLINE int
1062 ipf_pr_ah6(fr_info_t *fin)
1063 {
1064 	authhdr_t *ah;
1065 
1066 	fin->fin_flx |= FI_AH;
1067 
1068 	ah = (authhdr_t *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
1069 	if (ah == NULL) {
1070 		ipf_main_softc_t *softc = fin->fin_main_soft;
1071 
1072 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ah_bad);
1073 		return IPPROTO_NONE;
1074 	}
1075 
1076 	ipf_pr_short6(fin, sizeof(*ah));
1077 
1078 	/*
1079 	 * No need for another pullup, ipf_pr_ipv6exthdr() will pullup
1080 	 * enough data to satisfy ah_next (the very first one.)
1081 	 */
1082 	return ah->ah_next;
1083 }
1084 
1085 
1086 /* ------------------------------------------------------------------------ */
1087 /* Function:    ipf_pr_gre6                                                 */
1088 /* Returns:     void                                                        */
1089 /* Parameters:  fin(I) - pointer to packet information                      */
1090 /*                                                                          */
1091 /* Analyse the packet for GRE properties.                                   */
1092 /* ------------------------------------------------------------------------ */
1093 static INLINE void
1094 ipf_pr_gre6(fr_info_t *fin)
1095 {
1096 	grehdr_t *gre;
1097 
1098 	if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1099 		ipf_main_softc_t *softc = fin->fin_main_soft;
1100 
1101 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_gre_pullup);
1102 		return;
1103 	}
1104 
1105 	gre = fin->fin_dp;
1106 	if (GRE_REV(gre->gr_flags) == 1)
1107 		fin->fin_data[0] = gre->gr_call;
1108 }
1109 #endif	/* USE_INET6 */
1110 
1111 
1112 /* ------------------------------------------------------------------------ */
1113 /* Function:    ipf_pr_pullup                                               */
1114 /* Returns:     int     - 0 == pullup succeeded, -1 == failure              */
1115 /* Parameters:  fin(I)  - pointer to packet information                     */
1116 /*              plen(I) - length (excluding L3 header) to pullup            */
1117 /*                                                                          */
1118 /* Short inline function to cut down on code duplication to perform a call  */
1119 /* to ipf_pullup to ensure there is the required amount of data,            */
1120 /* consecutively in the packet buffer.                                      */
1121 /*                                                                          */
1122 /* This function pulls up 'extra' data at the location of fin_dp.  fin_dp   */
1123 /* points to the first byte after the complete layer 3 header, which will   */
1124 /* include all of the known extension headers for IPv6 or options for IPv4. */
1125 /*                                                                          */
1126 /* Since fr_pullup() expects the total length of bytes to be pulled up, it  */
1127 /* is necessary to add those we can already assume to be pulled up (fin_dp  */
1128 /* - fin_ip) to what is passed through.                                     */
1129 /* ------------------------------------------------------------------------ */
1130 int
1131 ipf_pr_pullup(fr_info_t *fin, int plen)
1132 {
1133 	ipf_main_softc_t *softc = fin->fin_main_soft;
1134 
1135 	if (fin->fin_m != NULL) {
1136 		if (fin->fin_dp != NULL)
1137 			plen += (char *)fin->fin_dp -
1138 				((char *)fin->fin_ip + fin->fin_hlen);
1139 		plen += fin->fin_hlen;
1140 		if (M_LEN(fin->fin_m) < plen + fin->fin_ipoff) {
1141 #if defined(_KERNEL)
1142 			if (ipf_pullup(fin->fin_m, fin, plen) == NULL) {
1143 				DT(ipf_pullup_fail);
1144 				LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1145 				return -1;
1146 			}
1147 			LBUMP(ipf_stats[fin->fin_out].fr_pull[0]);
1148 #else
1149 			LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1150 			/*
1151 			 * Fake ipf_pullup failing
1152 			 */
1153 			fin->fin_reason = FRB_PULLUP;
1154 			*fin->fin_mp = NULL;
1155 			fin->fin_m = NULL;
1156 			fin->fin_ip = NULL;
1157 			return -1;
1158 #endif
1159 		}
1160 	}
1161 	return 0;
1162 }
1163 
1164 
1165 /* ------------------------------------------------------------------------ */
1166 /* Function:    ipf_pr_short                                                */
1167 /* Returns:     void                                                        */
1168 /* Parameters:  fin(I)  - pointer to packet information                     */
1169 /*              xmin(I) - minimum header size                               */
1170 /*                                                                          */
1171 /* Check if a packet is "short" as defined by xmin.  The rule we are        */
1172 /* applying here is that the packet must not be fragmented within the layer */
1173 /* 4 header.  That is, it must not be a fragment that has its offset set to */
1174 /* start within the layer 4 header (hdrmin) or if it is at offset 0, the    */
1175 /* entire layer 4 header must be present (min).                             */
1176 /* ------------------------------------------------------------------------ */
1177 static INLINE void
1178 ipf_pr_short(fr_info_t *fin, int xmin)
1179 {
1180 
1181 	if (fin->fin_off == 0) {
1182 		if (fin->fin_dlen < xmin)
1183 			fin->fin_flx |= FI_SHORT;
1184 	} else if (fin->fin_off < xmin) {
1185 		fin->fin_flx |= FI_SHORT;
1186 	}
1187 }
1188 
1189 
1190 /* ------------------------------------------------------------------------ */
1191 /* Function:    ipf_pr_icmp                                                 */
1192 /* Returns:     void                                                        */
1193 /* Parameters:  fin(I) - pointer to packet information                      */
1194 /*                                                                          */
1195 /* IPv4 Only                                                                */
1196 /* Do a sanity check on the packet for ICMP (v4).  In nearly all cases,     */
1197 /* except extrememly bad packets, both type and code will be present.       */
1198 /* The expected minimum size of an ICMP packet is very much dependent on    */
1199 /* the type of it.                                                          */
1200 /*                                                                          */
1201 /* XXX - other ICMP sanity checks?                                          */
1202 /* ------------------------------------------------------------------------ */
1203 static INLINE void
1204 ipf_pr_icmp(fr_info_t *fin)
1205 {
1206 	ipf_main_softc_t *softc = fin->fin_main_soft;
1207 	int minicmpsz = sizeof(struct icmp);
1208 	icmphdr_t *icmp;
1209 	ip_t *oip;
1210 
1211 	ipf_pr_short(fin, ICMPERR_ICMPHLEN);
1212 
1213 	if (fin->fin_off != 0) {
1214 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_frag);
1215 		return;
1216 	}
1217 
1218 	if (ipf_pr_pullup(fin, ICMPERR_ICMPHLEN) == -1) {
1219 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_pullup);
1220 		return;
1221 	}
1222 
1223 	icmp = fin->fin_dp;
1224 
1225 	fin->fin_data[0] = *(u_short *)icmp;
1226 	fin->fin_data[1] = icmp->icmp_id;
1227 
1228 	switch (icmp->icmp_type)
1229 	{
1230 	case ICMP_ECHOREPLY :
1231 	case ICMP_ECHO :
1232 	/* Router discovery messaes - RFC 1256 */
1233 	case ICMP_ROUTERADVERT :
1234 	case ICMP_ROUTERSOLICIT :
1235 		fin->fin_flx |= FI_ICMPQUERY;
1236 		minicmpsz = ICMP_MINLEN;
1237 		break;
1238 	/*
1239 	 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1240 	 * 3 * timestamp(3 * 4)
1241 	 */
1242 	case ICMP_TSTAMP :
1243 	case ICMP_TSTAMPREPLY :
1244 		fin->fin_flx |= FI_ICMPQUERY;
1245 		minicmpsz = 20;
1246 		break;
1247 	/*
1248 	 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1249 	 * mask(4)
1250 	 */
1251 	case ICMP_IREQ :
1252 	case ICMP_IREQREPLY :
1253 	case ICMP_MASKREQ :
1254 	case ICMP_MASKREPLY :
1255 		fin->fin_flx |= FI_ICMPQUERY;
1256 		minicmpsz = 12;
1257 		break;
1258 	/*
1259 	 * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
1260 	 */
1261 	case ICMP_UNREACH :
1262 #ifdef icmp_nextmtu
1263 		if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
1264 			if (icmp->icmp_nextmtu < softc->ipf_icmpminfragmtu) {
1265 				fin->fin_flx |= FI_BAD;
1266 				DT3(ipf_fi_bad_icmp_nextmtu, fr_info_t *, fin, u_int, icmp->icmp_nextmtu, u_int, softc->ipf_icmpminfragmtu);
1267 			}
1268 		}
1269 #endif
1270 		/* FALLTHROUGH */
1271 	case ICMP_SOURCEQUENCH :
1272 	case ICMP_REDIRECT :
1273 	case ICMP_TIMXCEED :
1274 	case ICMP_PARAMPROB :
1275 		fin->fin_flx |= FI_ICMPERR;
1276 		if (ipf_coalesce(fin) != 1) {
1277 			LBUMPD(ipf_stats[fin->fin_out], fr_icmp_coalesce);
1278 			return;
1279 		}
1280 
1281 		/*
1282 		 * ICMP error packets should not be generated for IP
1283 		 * packets that are a fragment that isn't the first
1284 		 * fragment.
1285 		 */
1286 		oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
1287 		if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0) {
1288 			fin->fin_flx |= FI_BAD;
1289 			DT2(ipf_fi_bad_icmp_err, fr_info_t, fin, u_int, (ntohs(oip->ip_off) & IP_OFFMASK));
1290 		}
1291 
1292 		/*
1293 		 * If the destination of this packet doesn't match the
1294 		 * source of the original packet then this packet is
1295 		 * not correct.
1296 		 */
1297 		if (oip->ip_src.s_addr != fin->fin_daddr) {
1298 			fin->fin_flx |= FI_BAD;
1299 			DT1(ipf_fi_bad_src_ne_dst, fr_info_t *, fin);
1300 		}
1301 		break;
1302 	default :
1303 		break;
1304 	}
1305 
1306 	ipf_pr_short(fin, minicmpsz);
1307 
1308 	ipf_checkv4sum(fin);
1309 }
1310 
1311 
1312 /* ------------------------------------------------------------------------ */
1313 /* Function:    ipf_pr_tcpcommon                                            */
1314 /* Returns:     int    - 0 = header ok, 1 = bad packet, -1 = buffer error   */
1315 /* Parameters:  fin(I) - pointer to packet information                      */
1316 /*                                                                          */
1317 /* TCP header sanity checking.  Look for bad combinations of TCP flags,     */
1318 /* and make some checks with how they interact with other fields.           */
1319 /* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is     */
1320 /* valid and mark the packet as bad if not.                                 */
1321 /* ------------------------------------------------------------------------ */
1322 static INLINE int
1323 ipf_pr_tcpcommon(fr_info_t *fin)
1324 {
1325 	ipf_main_softc_t *softc = fin->fin_main_soft;
1326 	int flags, tlen;
1327 	tcphdr_t *tcp;
1328 
1329 	fin->fin_flx |= FI_TCPUDP;
1330 	if (fin->fin_off != 0) {
1331 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_frag);
1332 		return 0;
1333 	}
1334 
1335 	if (ipf_pr_pullup(fin, sizeof(*tcp)) == -1) {
1336 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1337 		return -1;
1338 	}
1339 
1340 	tcp = fin->fin_dp;
1341 	if (fin->fin_dlen > 3) {
1342 		fin->fin_sport = ntohs(tcp->th_sport);
1343 		fin->fin_dport = ntohs(tcp->th_dport);
1344 	}
1345 
1346 	if ((fin->fin_flx & FI_SHORT) != 0) {
1347 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_short);
1348 		return 1;
1349 	}
1350 
1351 	/*
1352 	 * Use of the TCP data offset *must* result in a value that is at
1353 	 * least the same size as the TCP header.
1354 	 */
1355 	tlen = TCP_OFF(tcp) << 2;
1356 	if (tlen < sizeof(tcphdr_t)) {
1357 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_small);
1358 		fin->fin_flx |= FI_BAD;
1359 		DT3(ipf_fi_bad_tlen, fr_info_t, fin, u_int, tlen, u_int, sizeof(tcphdr_t));
1360 		return 1;
1361 	}
1362 
1363 	flags = tcp->th_flags;
1364 	fin->fin_tcpf = tcp->th_flags;
1365 
1366 	/*
1367 	 * If the urgent flag is set, then the urgent pointer must
1368 	 * also be set and vice versa.  Good TCP packets do not have
1369 	 * just one of these set.
1370 	 */
1371 	if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
1372 		fin->fin_flx |= FI_BAD;
1373 		DT3(ipf_fi_bad_th_urg, fr_info_t*, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1374 #if 0
1375 	} else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
1376 		/*
1377 		 * Ignore this case (#if 0) as it shows up in "real"
1378 		 * traffic with bogus values in the urgent pointer field.
1379 		 */
1380 		fin->fin_flx |= FI_BAD;
1381 		DT3(ipf_fi_bad_th_urg0, fr_info_t *, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1382 #endif
1383 	} else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
1384 		   ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
1385 		/* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
1386 		fin->fin_flx |= FI_BAD;
1387 		DT1(ipf_fi_bad_th_fin_rst_ack, fr_info_t, fin);
1388 #if 1
1389 	} else if (((flags & TH_SYN) != 0) &&
1390 		   ((flags & (TH_URG|TH_PUSH)) != 0)) {
1391 		/*
1392 		 * SYN with URG and PUSH set is not for normal TCP but it is
1393 		 * possible(?) with T/TCP...but who uses T/TCP?
1394 		 */
1395 		fin->fin_flx |= FI_BAD;
1396 		DT1(ipf_fi_bad_th_syn_urg_psh, fr_info_t *, fin);
1397 #endif
1398 	} else if (!(flags & TH_ACK)) {
1399 		/*
1400 		 * If the ack bit isn't set, then either the SYN or
1401 		 * RST bit must be set.  If the SYN bit is set, then
1402 		 * we expect the ACK field to be 0.  If the ACK is
1403 		 * not set and if URG, PSH or FIN are set, consdier
1404 		 * that to indicate a bad TCP packet.
1405 		 */
1406 		if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
1407 			/*
1408 			 * Cisco PIX sets the ACK field to a random value.
1409 			 * In light of this, do not set FI_BAD until a patch
1410 			 * is available from Cisco to ensure that
1411 			 * interoperability between existing systems is
1412 			 * achieved.
1413 			 */
1414 			/*fin->fin_flx |= FI_BAD*/;
1415 			/*DT1(ipf_fi_bad_th_syn_ack, fr_info_t *, fin);*/
1416 		} else if (!(flags & (TH_RST|TH_SYN))) {
1417 			fin->fin_flx |= FI_BAD;
1418 			DT1(ipf_fi_bad_th_rst_syn, fr_info_t *, fin);
1419 		} else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
1420 			fin->fin_flx |= FI_BAD;
1421 			DT1(ipf_fi_bad_th_urg_push_fin, fr_info_t *, fin);
1422 		}
1423 	}
1424 	if (fin->fin_flx & FI_BAD) {
1425 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_bad_flags);
1426 		return 1;
1427 	}
1428 
1429 	/*
1430 	 * At this point, it's not exactly clear what is to be gained by
1431 	 * marking up which TCP options are and are not present.  The one we
1432 	 * are most interested in is the TCP window scale.  This is only in
1433 	 * a SYN packet [RFC1323] so we don't need this here...?
1434 	 * Now if we were to analyse the header for passive fingerprinting,
1435 	 * then that might add some weight to adding this...
1436 	 */
1437 	if (tlen == sizeof(tcphdr_t)) {
1438 		return 0;
1439 	}
1440 
1441 	if (ipf_pr_pullup(fin, tlen) == -1) {
1442 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1443 		return -1;
1444 	}
1445 
1446 #if 0
1447 	tcp = fin->fin_dp;
1448 	ip = fin->fin_ip;
1449 	s = (u_char *)(tcp + 1);
1450 	off = IP_HL(ip) << 2;
1451 # ifdef _KERNEL
1452 	if (fin->fin_mp != NULL) {
1453 		mb_t *m = *fin->fin_mp;
1454 
1455 		if (off + tlen > M_LEN(m))
1456 			return;
1457 	}
1458 # endif
1459 	for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
1460 		opt = *s;
1461 		if (opt == '\0')
1462 			break;
1463 		else if (opt == TCPOPT_NOP)
1464 			ol = 1;
1465 		else {
1466 			if (tlen < 2)
1467 				break;
1468 			ol = (int)*(s + 1);
1469 			if (ol < 2 || ol > tlen)
1470 				break;
1471 		}
1472 
1473 		for (i = 9, mv = 4; mv >= 0; ) {
1474 			op = ipopts + i;
1475 			if (opt == (u_char)op->ol_val) {
1476 				optmsk |= op->ol_bit;
1477 				break;
1478 			}
1479 		}
1480 		tlen -= ol;
1481 		s += ol;
1482 	}
1483 #endif /* 0 */
1484 
1485 	return 0;
1486 }
1487 
1488 
1489 
1490 /* ------------------------------------------------------------------------ */
1491 /* Function:    ipf_pr_udpcommon                                            */
1492 /* Returns:     int    - 0 = header ok, 1 = bad packet                      */
1493 /* Parameters:  fin(I) - pointer to packet information                      */
1494 /*                                                                          */
1495 /* Extract the UDP source and destination ports, if present.  If compiled   */
1496 /* with IPFILTER_CKSUM, check to see if the UDP checksum is valid.          */
1497 /* ------------------------------------------------------------------------ */
1498 static INLINE int
1499 ipf_pr_udpcommon(fr_info_t *fin)
1500 {
1501 	udphdr_t *udp;
1502 
1503 	fin->fin_flx |= FI_TCPUDP;
1504 
1505 	if (!fin->fin_off && (fin->fin_dlen > 3)) {
1506 		if (ipf_pr_pullup(fin, sizeof(*udp)) == -1) {
1507 			ipf_main_softc_t *softc = fin->fin_main_soft;
1508 
1509 			fin->fin_flx |= FI_SHORT;
1510 			LBUMPD(ipf_stats[fin->fin_out], fr_udp_pullup);
1511 			return 1;
1512 		}
1513 
1514 		udp = fin->fin_dp;
1515 
1516 		fin->fin_sport = ntohs(udp->uh_sport);
1517 		fin->fin_dport = ntohs(udp->uh_dport);
1518 	}
1519 
1520 	return 0;
1521 }
1522 
1523 
1524 /* ------------------------------------------------------------------------ */
1525 /* Function:    ipf_pr_tcp                                                  */
1526 /* Returns:     void                                                        */
1527 /* Parameters:  fin(I) - pointer to packet information                      */
1528 /*                                                                          */
1529 /* IPv4 Only                                                                */
1530 /* Analyse the packet for IPv4/TCP properties.                              */
1531 /* ------------------------------------------------------------------------ */
1532 static INLINE void
1533 ipf_pr_tcp(fr_info_t *fin)
1534 {
1535 
1536 	ipf_pr_short(fin, sizeof(tcphdr_t));
1537 
1538 	if (ipf_pr_tcpcommon(fin) == 0)
1539 		ipf_checkv4sum(fin);
1540 }
1541 
1542 
1543 /* ------------------------------------------------------------------------ */
1544 /* Function:    ipf_pr_udp                                                  */
1545 /* Returns:     void                                                        */
1546 /* Parameters:  fin(I) - pointer to packet information                      */
1547 /*                                                                          */
1548 /* IPv4 Only                                                                */
1549 /* Analyse the packet for IPv4/UDP properties.                              */
1550 /* ------------------------------------------------------------------------ */
1551 static INLINE void
1552 ipf_pr_udp(fr_info_t *fin)
1553 {
1554 
1555 	ipf_pr_short(fin, sizeof(udphdr_t));
1556 
1557 	if (ipf_pr_udpcommon(fin) == 0)
1558 		ipf_checkv4sum(fin);
1559 }
1560 
1561 
1562 /* ------------------------------------------------------------------------ */
1563 /* Function:    ipf_pr_esp                                                  */
1564 /* Returns:     void                                                        */
1565 /* Parameters:  fin(I) - pointer to packet information                      */
1566 /*                                                                          */
1567 /* Analyse the packet for ESP properties.                                   */
1568 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
1569 /* even though the newer ESP packets must also have a sequence number that  */
1570 /* is 32bits as well, it is not possible(?) to determine the version from a */
1571 /* simple packet header.                                                    */
1572 /* ------------------------------------------------------------------------ */
1573 static INLINE void
1574 ipf_pr_esp(fr_info_t *fin)
1575 {
1576 
1577 	if (fin->fin_off == 0) {
1578 		ipf_pr_short(fin, 8);
1579 		if (ipf_pr_pullup(fin, 8) == -1) {
1580 			ipf_main_softc_t *softc = fin->fin_main_soft;
1581 
1582 			LBUMPD(ipf_stats[fin->fin_out], fr_v4_esp_pullup);
1583 		}
1584 	}
1585 }
1586 
1587 
1588 /* ------------------------------------------------------------------------ */
1589 /* Function:    ipf_pr_ah                                                   */
1590 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
1591 /* Parameters:  fin(I) - pointer to packet information                      */
1592 /*                                                                          */
1593 /* Analyse the packet for AH properties.                                    */
1594 /* The minimum length is taken to be the combination of all fields in the   */
1595 /* header being present and no authentication data (null algorithm used.)   */
1596 /* ------------------------------------------------------------------------ */
1597 static INLINE int
1598 ipf_pr_ah(fr_info_t *fin)
1599 {
1600 	ipf_main_softc_t *softc = fin->fin_main_soft;
1601 	authhdr_t *ah;
1602 	int len;
1603 
1604 	fin->fin_flx |= FI_AH;
1605 	ipf_pr_short(fin, sizeof(*ah));
1606 
1607 	if (((fin->fin_flx & FI_SHORT) != 0) || (fin->fin_off != 0)) {
1608 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_ah_bad);
1609 		return IPPROTO_NONE;
1610 	}
1611 
1612 	if (ipf_pr_pullup(fin, sizeof(*ah)) == -1) {
1613 		DT(fr_v4_ah_pullup_1);
1614 		LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1615 		return IPPROTO_NONE;
1616 	}
1617 
1618 	ah = (authhdr_t *)fin->fin_dp;
1619 
1620 	len = (ah->ah_plen + 2) << 2;
1621 	ipf_pr_short(fin, len);
1622 	if (ipf_pr_pullup(fin, len) == -1) {
1623 		DT(fr_v4_ah_pullup_2);
1624 		LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1625 		return IPPROTO_NONE;
1626 	}
1627 
1628 	/*
1629 	 * Adjust fin_dp and fin_dlen for skipping over the authentication
1630 	 * header.
1631 	 */
1632 	fin->fin_dp = (char *)fin->fin_dp + len;
1633 	fin->fin_dlen -= len;
1634 	return ah->ah_next;
1635 }
1636 
1637 
1638 /* ------------------------------------------------------------------------ */
1639 /* Function:    ipf_pr_gre                                                  */
1640 /* Returns:     void                                                        */
1641 /* Parameters:  fin(I) - pointer to packet information                      */
1642 /*                                                                          */
1643 /* Analyse the packet for GRE properties.                                   */
1644 /* ------------------------------------------------------------------------ */
1645 static INLINE void
1646 ipf_pr_gre(fr_info_t *fin)
1647 {
1648 	ipf_main_softc_t *softc = fin->fin_main_soft;
1649 	grehdr_t *gre;
1650 
1651 	ipf_pr_short(fin, sizeof(grehdr_t));
1652 
1653 	if (fin->fin_off != 0) {
1654 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_frag);
1655 		return;
1656 	}
1657 
1658 	if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1659 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_pullup);
1660 		return;
1661 	}
1662 
1663 	gre = fin->fin_dp;
1664 	if (GRE_REV(gre->gr_flags) == 1)
1665 		fin->fin_data[0] = gre->gr_call;
1666 }
1667 
1668 
1669 /* ------------------------------------------------------------------------ */
1670 /* Function:    ipf_pr_ipv4hdr                                              */
1671 /* Returns:     void                                                        */
1672 /* Parameters:  fin(I) - pointer to packet information                      */
1673 /*                                                                          */
1674 /* IPv4 Only                                                                */
1675 /* Analyze the IPv4 header and set fields in the fr_info_t structure.       */
1676 /* Check all options present and flag their presence if any exist.          */
1677 /* ------------------------------------------------------------------------ */
1678 static INLINE void
1679 ipf_pr_ipv4hdr(fr_info_t *fin)
1680 {
1681 	u_short optmsk = 0, secmsk = 0, auth = 0;
1682 	int hlen, ol, mv, p, i;
1683 	const struct optlist *op;
1684 	u_char *s, opt;
1685 	u_short off;
1686 	fr_ip_t *fi;
1687 	ip_t *ip;
1688 
1689 	fi = &fin->fin_fi;
1690 	hlen = fin->fin_hlen;
1691 
1692 	ip = fin->fin_ip;
1693 	p = ip->ip_p;
1694 	fi->fi_p = p;
1695 	fin->fin_crc = p;
1696 	fi->fi_tos = ip->ip_tos;
1697 	fin->fin_id = ip->ip_id;
1698 	off = ntohs(ip->ip_off);
1699 
1700 	/* Get both TTL and protocol */
1701 	fi->fi_p = ip->ip_p;
1702 	fi->fi_ttl = ip->ip_ttl;
1703 
1704 	/* Zero out bits not used in IPv6 address */
1705 	fi->fi_src.i6[1] = 0;
1706 	fi->fi_src.i6[2] = 0;
1707 	fi->fi_src.i6[3] = 0;
1708 	fi->fi_dst.i6[1] = 0;
1709 	fi->fi_dst.i6[2] = 0;
1710 	fi->fi_dst.i6[3] = 0;
1711 
1712 	fi->fi_saddr = ip->ip_src.s_addr;
1713 	fin->fin_crc += fi->fi_saddr;
1714 	fi->fi_daddr = ip->ip_dst.s_addr;
1715 	fin->fin_crc += fi->fi_daddr;
1716 	if (IN_CLASSD(fi->fi_daddr))
1717 		fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
1718 
1719 	/*
1720 	 * set packet attribute flags based on the offset and
1721 	 * calculate the byte offset that it represents.
1722 	 */
1723 	off &= IP_MF|IP_OFFMASK;
1724 	if (off != 0) {
1725 		fi->fi_flx |= FI_FRAG;
1726 		off &= IP_OFFMASK;
1727 		if (off != 0) {
1728 			int morefrag = off & IP_MF;
1729 
1730 			if (off == 1 && p == IPPROTO_TCP) {
1731 				fin->fin_flx |= FI_SHORT;       /* RFC 3128 */
1732 				DT1(ipf_fi_tcp_frag_off_1, fr_info_t *, fin);
1733 			}
1734 
1735 			fin->fin_flx |= FI_FRAGBODY;
1736 			off <<= 3;
1737 			if ((off + fin->fin_dlen > 65535) ||
1738 			    (fin->fin_dlen == 0) ||
1739 			    ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
1740 				/*
1741 				 * The length of the packet, starting at its
1742 				 * offset cannot exceed 65535 (0xffff) as the
1743 				 * length of an IP packet is only 16 bits.
1744 				 *
1745 				 * Any fragment that isn't the last fragment
1746 				 * must have a length greater than 0 and it
1747 				 * must be an even multiple of 8.
1748 				 */
1749 				fi->fi_flx |= FI_BAD;
1750 				DT1(ipf_fi_bad_fragbody_gt_65535, fr_info_t *, fin);
1751 			}
1752 		}
1753 	}
1754 	fin->fin_off = off;
1755 
1756 	/*
1757 	 * Call per-protocol setup and checking
1758 	 */
1759 	if (p == IPPROTO_AH) {
1760 		/*
1761 		 * Treat AH differently because we expect there to be another
1762 		 * layer 4 header after it.
1763 		 */
1764 		p = ipf_pr_ah(fin);
1765 	}
1766 
1767 	switch (p)
1768 	{
1769 	case IPPROTO_UDP :
1770 		ipf_pr_udp(fin);
1771 		break;
1772 	case IPPROTO_TCP :
1773 		ipf_pr_tcp(fin);
1774 		break;
1775 	case IPPROTO_ICMP :
1776 		ipf_pr_icmp(fin);
1777 		break;
1778 	case IPPROTO_ESP :
1779 		ipf_pr_esp(fin);
1780 		break;
1781 	case IPPROTO_GRE :
1782 		ipf_pr_gre(fin);
1783 		break;
1784 	}
1785 
1786 	ip = fin->fin_ip;
1787 	if (ip == NULL)
1788 		return;
1789 
1790 	/*
1791 	 * If it is a standard IP header (no options), set the flag fields
1792 	 * which relate to options to 0.
1793 	 */
1794 	if (hlen == sizeof(*ip)) {
1795 		fi->fi_optmsk = 0;
1796 		fi->fi_secmsk = 0;
1797 		fi->fi_auth = 0;
1798 		return;
1799 	}
1800 
1801 	/*
1802 	 * So the IP header has some IP options attached.  Walk the entire
1803 	 * list of options present with this packet and set flags to indicate
1804 	 * which ones are here and which ones are not.  For the somewhat out
1805 	 * of date and obscure security classification options, set a flag to
1806 	 * represent which classification is present.
1807 	 */
1808 	fi->fi_flx |= FI_OPTIONS;
1809 
1810 	for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1811 		opt = *s;
1812 		if (opt == '\0')
1813 			break;
1814 		else if (opt == IPOPT_NOP)
1815 			ol = 1;
1816 		else {
1817 			if (hlen < 2)
1818 				break;
1819 			ol = (int)*(s + 1);
1820 			if (ol < 2 || ol > hlen)
1821 				break;
1822 		}
1823 		for (i = 9, mv = 4; mv >= 0; ) {
1824 			op = ipopts + i;
1825 
1826 			if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1827 				u_32_t doi;
1828 
1829 				switch (opt)
1830 				{
1831 				case IPOPT_SECURITY :
1832 					if (optmsk & op->ol_bit) {
1833 						fin->fin_flx |= FI_BAD;
1834 						DT2(ipf_fi_bad_ipopt_security, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1835 					} else {
1836 						doi = ipf_checkripso(s);
1837 						secmsk = doi >> 16;
1838 						auth = doi & 0xffff;
1839 					}
1840 					break;
1841 
1842 				case IPOPT_CIPSO :
1843 
1844 					if (optmsk & op->ol_bit) {
1845 						fin->fin_flx |= FI_BAD;
1846 						DT2(ipf_fi_bad_ipopt_cipso, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1847 					} else {
1848 						doi = ipf_checkcipso(fin,
1849 								     s, ol);
1850 						secmsk = doi >> 16;
1851 						auth = doi & 0xffff;
1852 					}
1853 					break;
1854 				}
1855 				optmsk |= op->ol_bit;
1856 			}
1857 
1858 			if (opt < op->ol_val)
1859 				i -= mv;
1860 			else
1861 				i += mv;
1862 			mv--;
1863 		}
1864 		hlen -= ol;
1865 		s += ol;
1866 	}
1867 
1868 	/*
1869 	 *
1870 	 */
1871 	if (auth && !(auth & 0x0100))
1872 		auth &= 0xff00;
1873 	fi->fi_optmsk = optmsk;
1874 	fi->fi_secmsk = secmsk;
1875 	fi->fi_auth = auth;
1876 }
1877 
1878 
1879 /* ------------------------------------------------------------------------ */
1880 /* Function:    ipf_checkripso                                              */
1881 /* Returns:     void                                                        */
1882 /* Parameters:  s(I)   - pointer to start of RIPSO option                   */
1883 /*                                                                          */
1884 /* ------------------------------------------------------------------------ */
1885 static u_32_t
1886 ipf_checkripso(u_char *s)
1887 {
1888 	const struct optlist *sp;
1889 	u_short secmsk = 0, auth = 0;
1890 	u_char sec;
1891 	int j, m;
1892 
1893 	sec = *(s + 2);	/* classification */
1894 	for (j = 3, m = 2; m >= 0; ) {
1895 		sp = secopt + j;
1896 		if (sec == sp->ol_val) {
1897 			secmsk |= sp->ol_bit;
1898 			auth = *(s + 3);
1899 			auth *= 256;
1900 			auth += *(s + 4);
1901 			break;
1902 		}
1903 		if (sec < sp->ol_val)
1904 			j -= m;
1905 		else
1906 			j += m;
1907 		m--;
1908 	}
1909 
1910 	return (secmsk << 16) | auth;
1911 }
1912 
1913 
1914 /* ------------------------------------------------------------------------ */
1915 /* Function:    ipf_checkcipso                                              */
1916 /* Returns:     u_32_t  - 0 = failure, else the doi from the header         */
1917 /* Parameters:  fin(IO) - pointer to packet information                     */
1918 /*              s(I)    - pointer to start of CIPSO option                  */
1919 /*              ol(I)   - length of CIPSO option field                      */
1920 /*                                                                          */
1921 /* This function returns the domain of integrity (DOI) field from the CIPSO */
1922 /* header and returns that whilst also storing the highest sensitivity      */
1923 /* value found in the fr_info_t structure.                                  */
1924 /*                                                                          */
1925 /* No attempt is made to extract the category bitmaps as these are defined  */
1926 /* by the user (rather than the protocol) and can be rather numerous on the */
1927 /* end nodes.                                                               */
1928 /* ------------------------------------------------------------------------ */
1929 static u_32_t
1930 ipf_checkcipso(fr_info_t *fin, u_char *s, int ol)
1931 {
1932 	ipf_main_softc_t *softc = fin->fin_main_soft;
1933 	fr_ip_t *fi;
1934 	u_32_t doi;
1935 	u_char *t, tag, tlen, sensitivity;
1936 	int len;
1937 
1938 	if (ol < 6 || ol > 40) {
1939 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
1940 		fin->fin_flx |= FI_BAD;
1941 		DT2(ipf_fi_bad_checkcipso_ol, fr_info_t *, fin, u_int, ol);
1942 		return 0;
1943 	}
1944 
1945 	fi = &fin->fin_fi;
1946 	fi->fi_sensitivity = 0;
1947 	/*
1948 	 * The DOI field MUST be there.
1949 	 */
1950 	bcopy(s + 2, &doi, sizeof(doi));
1951 
1952 	t = (u_char *)s + 6;
1953 	for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
1954 		tag = *t;
1955 		tlen = *(t + 1);
1956 		if (tlen > len || tlen < 4 || tlen > 34) {
1957 			LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
1958 			fin->fin_flx |= FI_BAD;
1959 			DT2(ipf_fi_bad_checkcipso_tlen, fr_info_t *, fin, u_int, tlen);
1960 			return 0;
1961 		}
1962 
1963 		sensitivity = 0;
1964 		/*
1965 		 * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
1966 		 * draft (16 July 1992) that has expired.
1967 		 */
1968 		if (tag == 0) {
1969 			fin->fin_flx |= FI_BAD;
1970 			DT2(ipf_fi_bad_checkcipso_tag, fr_info_t *, fin, u_int, tag);
1971 			continue;
1972 		} else if (tag == 1) {
1973 			if (*(t + 2) != 0) {
1974 				fin->fin_flx |= FI_BAD;
1975 				DT2(ipf_fi_bad_checkcipso_tag1_t2, fr_info_t *, fin, u_int, (*t + 2));
1976 				continue;
1977 			}
1978 			sensitivity = *(t + 3);
1979 			/* Category bitmap for categories 0-239 */
1980 
1981 		} else if (tag == 4) {
1982 			if (*(t + 2) != 0) {
1983 				fin->fin_flx |= FI_BAD;
1984 				DT2(ipf_fi_bad_checkcipso_tag4_t2, fr_info_t *, fin, u_int, (*t + 2));
1985 				continue;
1986 			}
1987 			sensitivity = *(t + 3);
1988 			/* Enumerated categories, 16bits each, upto 15 */
1989 
1990 		} else if (tag == 5) {
1991 			if (*(t + 2) != 0) {
1992 				fin->fin_flx |= FI_BAD;
1993 				DT2(ipf_fi_bad_checkcipso_tag5_t2, fr_info_t *, fin, u_int, (*t + 2));
1994 				continue;
1995 			}
1996 			sensitivity = *(t + 3);
1997 			/* Range of categories (2*16bits), up to 7 pairs */
1998 
1999 		} else if (tag > 127) {
2000 			/* Custom defined DOI */
2001 			;
2002 		} else {
2003 			DT2(ipf_fi_bad_checkcipso_tag127, fr_info_t *, fin, u_int, tag);
2004 			fin->fin_flx |= FI_BAD;
2005 			continue;
2006 		}
2007 
2008 		if (sensitivity > fi->fi_sensitivity)
2009 			fi->fi_sensitivity = sensitivity;
2010 	}
2011 
2012 	return doi;
2013 }
2014 
2015 
2016 /* ------------------------------------------------------------------------ */
2017 /* Function:    ipf_makefrip                                                */
2018 /* Returns:     int     - 0 == packet ok, -1 == packet freed                */
2019 /* Parameters:  hlen(I) - length of IP packet header                        */
2020 /*              ip(I)   - pointer to the IP header                          */
2021 /*              fin(IO) - pointer to packet information                     */
2022 /*                                                                          */
2023 /* Compact the IP header into a structure which contains just the info.     */
2024 /* which is useful for comparing IP headers with and store this information */
2025 /* in the fr_info_t structure pointer to by fin.  At present, it is assumed */
2026 /* this function will be called with either an IPv4 or IPv6 packet.         */
2027 /* ------------------------------------------------------------------------ */
2028 int
2029 ipf_makefrip(int hlen, ip_t *ip, fr_info_t *fin)
2030 {
2031 	ipf_main_softc_t *softc = fin->fin_main_soft;
2032 	int v;
2033 
2034 	fin->fin_depth = 0;
2035 	fin->fin_hlen = (u_short)hlen;
2036 	fin->fin_ip = ip;
2037 	fin->fin_rule = 0xffffffff;
2038 	fin->fin_group[0] = -1;
2039 	fin->fin_group[1] = '\0';
2040 	fin->fin_dp = (char *)ip + hlen;
2041 
2042 	v = fin->fin_v;
2043 	if (v == 4) {
2044 		fin->fin_plen = ntohs(ip->ip_len);
2045 		fin->fin_dlen = fin->fin_plen - hlen;
2046 		ipf_pr_ipv4hdr(fin);
2047 #ifdef	USE_INET6
2048 	} else if (v == 6) {
2049 		fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
2050 		fin->fin_dlen = fin->fin_plen;
2051 		fin->fin_plen += hlen;
2052 
2053 		ipf_pr_ipv6hdr(fin);
2054 #endif
2055 	}
2056 	if (fin->fin_ip == NULL) {
2057 		LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
2058 		return -1;
2059 	}
2060 	return 0;
2061 }
2062 
2063 
2064 /* ------------------------------------------------------------------------ */
2065 /* Function:    ipf_portcheck                                               */
2066 /* Returns:     int - 1 == port matched, 0 == port match failed             */
2067 /* Parameters:  frp(I) - pointer to port check `expression'                 */
2068 /*              pop(I) - port number to evaluate                            */
2069 /*                                                                          */
2070 /* Perform a comparison of a port number against some other(s), using a     */
2071 /* structure with compare information stored in it.                         */
2072 /* ------------------------------------------------------------------------ */
2073 static INLINE int
2074 ipf_portcheck(frpcmp_t *frp, u_32_t pop)
2075 {
2076 	int err = 1;
2077 	u_32_t po;
2078 
2079 	po = frp->frp_port;
2080 
2081 	/*
2082 	 * Do opposite test to that required and continue if that succeeds.
2083 	 */
2084 	switch (frp->frp_cmp)
2085 	{
2086 	case FR_EQUAL :
2087 		if (pop != po) /* EQUAL */
2088 			err = 0;
2089 		break;
2090 	case FR_NEQUAL :
2091 		if (pop == po) /* NOTEQUAL */
2092 			err = 0;
2093 		break;
2094 	case FR_LESST :
2095 		if (pop >= po) /* LESSTHAN */
2096 			err = 0;
2097 		break;
2098 	case FR_GREATERT :
2099 		if (pop <= po) /* GREATERTHAN */
2100 			err = 0;
2101 		break;
2102 	case FR_LESSTE :
2103 		if (pop > po) /* LT or EQ */
2104 			err = 0;
2105 		break;
2106 	case FR_GREATERTE :
2107 		if (pop < po) /* GT or EQ */
2108 			err = 0;
2109 		break;
2110 	case FR_OUTRANGE :
2111 		if (pop >= po && pop <= frp->frp_top) /* Out of range */
2112 			err = 0;
2113 		break;
2114 	case FR_INRANGE :
2115 		if (pop <= po || pop >= frp->frp_top) /* In range */
2116 			err = 0;
2117 		break;
2118 	case FR_INCRANGE :
2119 		if (pop < po || pop > frp->frp_top) /* Inclusive range */
2120 			err = 0;
2121 		break;
2122 	default :
2123 		break;
2124 	}
2125 	return err;
2126 }
2127 
2128 
2129 /* ------------------------------------------------------------------------ */
2130 /* Function:    ipf_tcpudpchk                                               */
2131 /* Returns:     int - 1 == protocol matched, 0 == check failed              */
2132 /* Parameters:  fda(I) - pointer to packet information                      */
2133 /*              ft(I)  - pointer to structure with comparison data          */
2134 /*                                                                          */
2135 /* Compares the current pcket (assuming it is TCP/UDP) information with a   */
2136 /* structure containing information that we want to match against.          */
2137 /* ------------------------------------------------------------------------ */
2138 int
2139 ipf_tcpudpchk(fr_ip_t *fi, frtuc_t *ft)
2140 {
2141 	int err = 1;
2142 
2143 	/*
2144 	 * Both ports should *always* be in the first fragment.
2145 	 * So far, I cannot find any cases where they can not be.
2146 	 *
2147 	 * compare destination ports
2148 	 */
2149 	if (ft->ftu_dcmp)
2150 		err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
2151 
2152 	/*
2153 	 * compare source ports
2154 	 */
2155 	if (err && ft->ftu_scmp)
2156 		err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
2157 
2158 	/*
2159 	 * If we don't have all the TCP/UDP header, then how can we
2160 	 * expect to do any sort of match on it ?  If we were looking for
2161 	 * TCP flags, then NO match.  If not, then match (which should
2162 	 * satisfy the "short" class too).
2163 	 */
2164 	if (err && (fi->fi_p == IPPROTO_TCP)) {
2165 		if (fi->fi_flx & FI_SHORT)
2166 			return !(ft->ftu_tcpf | ft->ftu_tcpfm);
2167 		/*
2168 		 * Match the flags ?  If not, abort this match.
2169 		 */
2170 		if (ft->ftu_tcpfm &&
2171 		    ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
2172 			FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
2173 				 ft->ftu_tcpfm, ft->ftu_tcpf));
2174 			err = 0;
2175 		}
2176 	}
2177 	return err;
2178 }
2179 
2180 
2181 /* ------------------------------------------------------------------------ */
2182 /* Function:    ipf_check_ipf                                               */
2183 /* Returns:     int - 0 == match, else no match                             */
2184 /* Parameters:  fin(I)     - pointer to packet information                  */
2185 /*              fr(I)      - pointer to filter rule                         */
2186 /*              portcmp(I) - flag indicating whether to attempt matching on */
2187 /*                           TCP/UDP port data.                             */
2188 /*                                                                          */
2189 /* Check to see if a packet matches an IPFilter rule.  Checks of addresses, */
2190 /* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
2191 /* this function.                                                           */
2192 /* ------------------------------------------------------------------------ */
2193 static INLINE int
2194 ipf_check_ipf(fr_info_t *fin, frentry_t *fr, int portcmp)
2195 {
2196 	u_32_t	*ld, *lm, *lip;
2197 	fripf_t *fri;
2198 	fr_ip_t *fi;
2199 	int i;
2200 
2201 	fi = &fin->fin_fi;
2202 	fri = fr->fr_ipf;
2203 	lip = (u_32_t *)fi;
2204 	lm = (u_32_t *)&fri->fri_mip;
2205 	ld = (u_32_t *)&fri->fri_ip;
2206 
2207 	/*
2208 	 * first 32 bits to check coversion:
2209 	 * IP version, TOS, TTL, protocol
2210 	 */
2211 	i = ((*lip & *lm) != *ld);
2212 	FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
2213 		   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2214 	if (i)
2215 		return 1;
2216 
2217 	/*
2218 	 * Next 32 bits is a constructed bitmask indicating which IP options
2219 	 * are present (if any) in this packet.
2220 	 */
2221 	lip++, lm++, ld++;
2222 	i = ((*lip & *lm) != *ld);
2223 	FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
2224 		   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2225 	if (i != 0)
2226 		return 1;
2227 
2228 	lip++, lm++, ld++;
2229 	/*
2230 	 * Unrolled loops (4 each, for 32 bits) for address checks.
2231 	 */
2232 	/*
2233 	 * Check the source address.
2234 	 */
2235 	if (fr->fr_satype == FRI_LOOKUP) {
2236 		i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
2237 				      fi->fi_v, lip, fin->fin_plen);
2238 		if (i == -1)
2239 			return 1;
2240 		lip += 3;
2241 		lm += 3;
2242 		ld += 3;
2243 	} else {
2244 		i = ((*lip & *lm) != *ld);
2245 		FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
2246 			   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2247 		if (fi->fi_v == 6) {
2248 			lip++, lm++, ld++;
2249 			i |= ((*lip & *lm) != *ld);
2250 			FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
2251 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2252 			lip++, lm++, ld++;
2253 			i |= ((*lip & *lm) != *ld);
2254 			FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
2255 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2256 			lip++, lm++, ld++;
2257 			i |= ((*lip & *lm) != *ld);
2258 			FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
2259 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2260 		} else {
2261 			lip += 3;
2262 			lm += 3;
2263 			ld += 3;
2264 		}
2265 	}
2266 	i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
2267 	if (i != 0)
2268 		return 1;
2269 
2270 	/*
2271 	 * Check the destination address.
2272 	 */
2273 	lip++, lm++, ld++;
2274 	if (fr->fr_datype == FRI_LOOKUP) {
2275 		i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
2276 				      fi->fi_v, lip, fin->fin_plen);
2277 		if (i == -1)
2278 			return 1;
2279 		lip += 3;
2280 		lm += 3;
2281 		ld += 3;
2282 	} else {
2283 		i = ((*lip & *lm) != *ld);
2284 		FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
2285 			   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2286 		if (fi->fi_v == 6) {
2287 			lip++, lm++, ld++;
2288 			i |= ((*lip & *lm) != *ld);
2289 			FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
2290 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2291 			lip++, lm++, ld++;
2292 			i |= ((*lip & *lm) != *ld);
2293 			FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
2294 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2295 			lip++, lm++, ld++;
2296 			i |= ((*lip & *lm) != *ld);
2297 			FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
2298 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2299 		} else {
2300 			lip += 3;
2301 			lm += 3;
2302 			ld += 3;
2303 		}
2304 	}
2305 	i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
2306 	if (i != 0)
2307 		return 1;
2308 	/*
2309 	 * IP addresses matched.  The next 32bits contains:
2310 	 * mast of old IP header security & authentication bits.
2311 	 */
2312 	lip++, lm++, ld++;
2313 	i = (*ld - (*lip & *lm));
2314 	FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2315 
2316 	/*
2317 	 * Next we have 32 bits of packet flags.
2318 	 */
2319 	lip++, lm++, ld++;
2320 	i |= (*ld - (*lip & *lm));
2321 	FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2322 
2323 	if (i == 0) {
2324 		/*
2325 		 * If a fragment, then only the first has what we're
2326 		 * looking for here...
2327 		 */
2328 		if (portcmp) {
2329 			if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
2330 				i = 1;
2331 		} else {
2332 			if (fr->fr_dcmp || fr->fr_scmp ||
2333 			    fr->fr_tcpf || fr->fr_tcpfm)
2334 				i = 1;
2335 			if (fr->fr_icmpm || fr->fr_icmp) {
2336 				if (((fi->fi_p != IPPROTO_ICMP) &&
2337 				     (fi->fi_p != IPPROTO_ICMPV6)) ||
2338 				    fin->fin_off || (fin->fin_dlen < 2))
2339 					i = 1;
2340 				else if ((fin->fin_data[0] & fr->fr_icmpm) !=
2341 					 fr->fr_icmp) {
2342 					FR_DEBUG(("i. %#x & %#x != %#x\n",
2343 						 fin->fin_data[0],
2344 						 fr->fr_icmpm, fr->fr_icmp));
2345 					i = 1;
2346 				}
2347 			}
2348 		}
2349 	}
2350 	return i;
2351 }
2352 
2353 
2354 /* ------------------------------------------------------------------------ */
2355 /* Function:    ipf_scanlist                                                */
2356 /* Returns:     int - result flags of scanning filter list                  */
2357 /* Parameters:  fin(I) - pointer to packet information                      */
2358 /*              pass(I) - default result to return for filtering            */
2359 /*                                                                          */
2360 /* Check the input/output list of rules for a match to the current packet.  */
2361 /* If a match is found, the value of fr_flags from the rule becomes the     */
2362 /* return value and fin->fin_fr points to the matched rule.                 */
2363 /*                                                                          */
2364 /* This function may be called recusively upto 16 times (limit inbuilt.)    */
2365 /* When unwinding, it should finish up with fin_depth as 0.                 */
2366 /*                                                                          */
2367 /* Could be per interface, but this gets real nasty when you don't have,    */
2368 /* or can't easily change, the kernel source code to .                      */
2369 /* ------------------------------------------------------------------------ */
2370 int
2371 ipf_scanlist(fr_info_t *fin, u_32_t pass)
2372 {
2373 	ipf_main_softc_t *softc = fin->fin_main_soft;
2374 	int rulen, portcmp, off, skip;
2375 	struct frentry *fr, *fnext;
2376 	u_32_t passt, passo;
2377 
2378 	/*
2379 	 * Do not allow nesting deeper than 16 levels.
2380 	 */
2381 	if (fin->fin_depth >= 16)
2382 		return pass;
2383 
2384 	fr = fin->fin_fr;
2385 
2386 	/*
2387 	 * If there are no rules in this list, return now.
2388 	 */
2389 	if (fr == NULL)
2390 		return pass;
2391 
2392 	skip = 0;
2393 	portcmp = 0;
2394 	fin->fin_depth++;
2395 	fin->fin_fr = NULL;
2396 	off = fin->fin_off;
2397 
2398 	if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
2399 		portcmp = 1;
2400 
2401 	for (rulen = 0; fr; fr = fnext, rulen++) {
2402 		fnext = fr->fr_next;
2403 		if (skip != 0) {
2404 			FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
2405 			skip--;
2406 			continue;
2407 		}
2408 
2409 		/*
2410 		 * In all checks below, a null (zero) value in the
2411 		 * filter struture is taken to mean a wildcard.
2412 		 *
2413 		 * check that we are working for the right interface
2414 		 */
2415 #ifdef	_KERNEL
2416 		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2417 			continue;
2418 #else
2419 		if (opts & (OPT_VERBOSE|OPT_DEBUG))
2420 			printf("\n");
2421 		FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
2422 				  FR_ISPASS(pass) ? 'p' :
2423 				  FR_ISACCOUNT(pass) ? 'A' :
2424 				  FR_ISAUTH(pass) ? 'a' :
2425 				  (pass & FR_NOMATCH) ? 'n' :'b'));
2426 		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2427 			continue;
2428 		FR_VERBOSE((":i"));
2429 #endif
2430 
2431 		switch (fr->fr_type)
2432 		{
2433 		case FR_T_IPF :
2434 		case FR_T_IPF_BUILTIN :
2435 			if (ipf_check_ipf(fin, fr, portcmp))
2436 				continue;
2437 			break;
2438 #if defined(IPFILTER_BPF)
2439 		case FR_T_BPFOPC :
2440 		case FR_T_BPFOPC_BUILTIN :
2441 		    {
2442 			u_char *mc;
2443 			int wlen;
2444 
2445 			if (*fin->fin_mp == NULL)
2446 				continue;
2447 			if (fin->fin_family != fr->fr_family)
2448 				continue;
2449 			mc = (u_char *)fin->fin_m;
2450 			wlen = fin->fin_dlen + fin->fin_hlen;
2451 			if (!bpf_filter(fr->fr_data, mc, wlen, 0))
2452 				continue;
2453 			break;
2454 		    }
2455 #endif
2456 		case FR_T_CALLFUNC_BUILTIN :
2457 		    {
2458 			frentry_t *f;
2459 
2460 			f = (*fr->fr_func)(fin, &pass);
2461 			if (f != NULL)
2462 				fr = f;
2463 			else
2464 				continue;
2465 			break;
2466 		    }
2467 
2468 		case FR_T_IPFEXPR :
2469 		case FR_T_IPFEXPR_BUILTIN :
2470 			if (fin->fin_family != fr->fr_family)
2471 				continue;
2472 			if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
2473 				continue;
2474 			break;
2475 
2476 		default :
2477 			break;
2478 		}
2479 
2480 		if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2481 			if (fin->fin_nattag == NULL)
2482 				continue;
2483 			if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
2484 				continue;
2485 		}
2486 		FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
2487 
2488 		passt = fr->fr_flags;
2489 
2490 		/*
2491 		 * If the rule is a "call now" rule, then call the function
2492 		 * in the rule, if it exists and use the results from that.
2493 		 * If the function pointer is bad, just make like we ignore
2494 		 * it, except for increasing the hit counter.
2495 		 */
2496 		if ((passt & FR_CALLNOW) != 0) {
2497 			frentry_t *frs;
2498 
2499 			ATOMIC_INC64(fr->fr_hits);
2500 			if ((fr->fr_func == NULL) ||
2501 			    (fr->fr_func == (ipfunc_t)-1))
2502 				continue;
2503 
2504 			frs = fin->fin_fr;
2505 			fin->fin_fr = fr;
2506 			fr = (*fr->fr_func)(fin, &passt);
2507 			if (fr == NULL) {
2508 				fin->fin_fr = frs;
2509 				continue;
2510 			}
2511 			passt = fr->fr_flags;
2512 		}
2513 		fin->fin_fr = fr;
2514 
2515 #ifdef  IPFILTER_LOG
2516 		/*
2517 		 * Just log this packet...
2518 		 */
2519 		if ((passt & FR_LOGMASK) == FR_LOG) {
2520 			if (ipf_log_pkt(fin, passt) == -1) {
2521 				if (passt & FR_LOGORBLOCK) {
2522 					DT(frb_logfail);
2523 					passt &= ~FR_CMDMASK;
2524 					passt |= FR_BLOCK|FR_QUICK;
2525 					fin->fin_reason = FRB_LOGFAIL;
2526 				}
2527 			}
2528 		}
2529 #endif /* IPFILTER_LOG */
2530 
2531 		MUTEX_ENTER(&fr->fr_lock);
2532 		fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2533 		fr->fr_hits++;
2534 		MUTEX_EXIT(&fr->fr_lock);
2535 		fin->fin_rule = rulen;
2536 
2537 		passo = pass;
2538 		if (FR_ISSKIP(passt)) {
2539 			skip = fr->fr_arg;
2540 			continue;
2541 		} else if (((passt & FR_LOGMASK) != FR_LOG) &&
2542 			   ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
2543 			pass = passt;
2544 		}
2545 
2546 		if (passt & (FR_RETICMP|FR_FAKEICMP))
2547 			fin->fin_icode = fr->fr_icode;
2548 
2549 		if (fr->fr_group != -1) {
2550 			(void) strncpy(fin->fin_group,
2551 				       FR_NAME(fr, fr_group),
2552 				       strlen(FR_NAME(fr, fr_group)));
2553 		} else {
2554 			fin->fin_group[0] = '\0';
2555 		}
2556 
2557 		FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
2558 
2559 		if (fr->fr_grphead != NULL) {
2560 			fin->fin_fr = fr->fr_grphead->fg_start;
2561 			FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
2562 
2563 			if (FR_ISDECAPS(passt))
2564 				passt = ipf_decaps(fin, pass, fr->fr_icode);
2565 			else
2566 				passt = ipf_scanlist(fin, pass);
2567 
2568 			if (fin->fin_fr == NULL) {
2569 				fin->fin_rule = rulen;
2570 				if (fr->fr_group != -1)
2571 					(void) strncpy(fin->fin_group,
2572 						       fr->fr_names +
2573 						       fr->fr_group,
2574 						       strlen(fr->fr_names +
2575 							      fr->fr_group));
2576 				fin->fin_fr = fr;
2577 				passt = pass;
2578 			}
2579 			pass = passt;
2580 		}
2581 
2582 		if (pass & FR_QUICK) {
2583 			/*
2584 			 * Finally, if we've asked to track state for this
2585 			 * packet, set it up.  Add state for "quick" rules
2586 			 * here so that if the action fails we can consider
2587 			 * the rule to "not match" and keep on processing
2588 			 * filter rules.
2589 			 */
2590 			if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
2591 			    !(fin->fin_flx & FI_STATE)) {
2592 				int out = fin->fin_out;
2593 
2594 				fin->fin_fr = fr;
2595 				if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2596 					LBUMPD(ipf_stats[out], fr_ads);
2597 				} else {
2598 					LBUMPD(ipf_stats[out], fr_bads);
2599 					pass = passo;
2600 					continue;
2601 				}
2602 			}
2603 			break;
2604 		}
2605 	}
2606 	fin->fin_depth--;
2607 	return pass;
2608 }
2609 
2610 
2611 /* ------------------------------------------------------------------------ */
2612 /* Function:    ipf_acctpkt                                                 */
2613 /* Returns:     frentry_t* - always returns NULL                            */
2614 /* Parameters:  fin(I) - pointer to packet information                      */
2615 /*              passp(IO) - pointer to current/new filter decision (unused) */
2616 /*                                                                          */
2617 /* Checks a packet against accounting rules, if there are any for the given */
2618 /* IP protocol version.                                                     */
2619 /*                                                                          */
2620 /* N.B.: this function returns NULL to match the prototype used by other    */
2621 /* functions called from the IPFilter "mainline" in ipf_check().            */
2622 /* ------------------------------------------------------------------------ */
2623 frentry_t *
2624 ipf_acctpkt(fr_info_t *fin, u_32_t *passp)
2625 {
2626 	ipf_main_softc_t *softc = fin->fin_main_soft;
2627 	char group[FR_GROUPLEN];
2628 	frentry_t *fr, *frsave;
2629 	u_32_t pass, rulen;
2630 
2631 	passp = passp;
2632 	fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
2633 
2634 	if (fr != NULL) {
2635 		frsave = fin->fin_fr;
2636 		bcopy(fin->fin_group, group, FR_GROUPLEN);
2637 		rulen = fin->fin_rule;
2638 		fin->fin_fr = fr;
2639 		pass = ipf_scanlist(fin, FR_NOMATCH);
2640 		if (FR_ISACCOUNT(pass)) {
2641 			LBUMPD(ipf_stats[0], fr_acct);
2642 		}
2643 		fin->fin_fr = frsave;
2644 		bcopy(group, fin->fin_group, FR_GROUPLEN);
2645 		fin->fin_rule = rulen;
2646 	}
2647 	return NULL;
2648 }
2649 
2650 
2651 /* ------------------------------------------------------------------------ */
2652 /* Function:    ipf_firewall                                                */
2653 /* Returns:     frentry_t* - returns pointer to matched rule, if no matches */
2654 /*                           were found, returns NULL.                      */
2655 /* Parameters:  fin(I) - pointer to packet information                      */
2656 /*              passp(IO) - pointer to current/new filter decision (unused) */
2657 /*                                                                          */
2658 /* Applies an appropriate set of firewall rules to the packet, to see if    */
2659 /* there are any matches.  The first check is to see if a match can be seen */
2660 /* in the cache.  If not, then search an appropriate list of rules.  Once a */
2661 /* matching rule is found, take any appropriate actions as defined by the   */
2662 /* rule - except logging.                                                   */
2663 /* ------------------------------------------------------------------------ */
2664 static frentry_t *
2665 ipf_firewall(fr_info_t *fin, u_32_t *passp)
2666 {
2667 	ipf_main_softc_t *softc = fin->fin_main_soft;
2668 	frentry_t *fr;
2669 	u_32_t pass;
2670 	int out;
2671 
2672 	out = fin->fin_out;
2673 	pass = *passp;
2674 
2675 	/*
2676 	 * This rule cache will only affect packets that are not being
2677 	 * statefully filtered.
2678 	 */
2679 	fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
2680 	if (fin->fin_fr != NULL)
2681 		pass = ipf_scanlist(fin, softc->ipf_pass);
2682 
2683 	if ((pass & FR_NOMATCH)) {
2684 		LBUMPD(ipf_stats[out], fr_nom);
2685 	}
2686 	fr = fin->fin_fr;
2687 
2688 	/*
2689 	 * Apply packets per second rate-limiting to a rule as required.
2690 	 */
2691 	if ((fr != NULL) && (fr->fr_pps != 0) &&
2692 	    !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2693 		DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
2694 		pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
2695 		pass |= FR_BLOCK;
2696 		LBUMPD(ipf_stats[out], fr_ppshit);
2697 		fin->fin_reason = FRB_PPSRATE;
2698 	}
2699 
2700 	/*
2701 	 * If we fail to add a packet to the authorization queue, then we
2702 	 * drop the packet later.  However, if it was added then pretend
2703 	 * we've dropped it already.
2704 	 */
2705 	if (FR_ISAUTH(pass)) {
2706 		if (ipf_auth_new(fin->fin_m, fin) != 0) {
2707 			DT1(frb_authnew, fr_info_t *, fin);
2708 			fin->fin_m = *fin->fin_mp = NULL;
2709 			fin->fin_reason = FRB_AUTHNEW;
2710 			fin->fin_error = 0;
2711 		} else {
2712 			IPFERROR(1);
2713 			fin->fin_error = ENOSPC;
2714 		}
2715 	}
2716 
2717 	if ((fr != NULL) && (fr->fr_func != NULL) &&
2718 	    (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2719 		(void) (*fr->fr_func)(fin, &pass);
2720 
2721 	/*
2722 	 * If a rule is a pre-auth rule, check again in the list of rules
2723 	 * loaded for authenticated use.  It does not particulary matter
2724 	 * if this search fails because a "preauth" result, from a rule,
2725 	 * is treated as "not a pass", hence the packet is blocked.
2726 	 */
2727 	if (FR_ISPREAUTH(pass)) {
2728 		pass = ipf_auth_pre_scanlist(softc, fin, pass);
2729 	}
2730 
2731 	/*
2732 	 * If the rule has "keep frag" and the packet is actually a fragment,
2733 	 * then create a fragment state entry.
2734 	 */
2735 	if (pass & FR_KEEPFRAG) {
2736 		if (fin->fin_flx & FI_FRAG) {
2737 			if (ipf_frag_new(softc, fin, pass) == -1) {
2738 				LBUMP(ipf_stats[out].fr_bnfr);
2739 			} else {
2740 				LBUMP(ipf_stats[out].fr_nfr);
2741 			}
2742 		} else {
2743 			LBUMP(ipf_stats[out].fr_cfr);
2744 		}
2745 	}
2746 
2747 	fr = fin->fin_fr;
2748 	*passp = pass;
2749 
2750 	return fr;
2751 }
2752 
2753 
2754 /* ------------------------------------------------------------------------ */
2755 /* Function:    ipf_check                                                   */
2756 /* Returns:     int -  0 == packet allowed through,                         */
2757 /*              User space:                                                 */
2758 /*                    -1 == packet blocked                                  */
2759 /*                     1 == packet not matched                              */
2760 /*                    -2 == requires authentication                         */
2761 /*              Kernel:                                                     */
2762 /*                   > 0 == filter error # for packet                       */
2763 /* Parameters: ip(I)   - pointer to start of IPv4/6 packet                  */
2764 /*             hlen(I) - length of header                                   */
2765 /*             ifp(I)  - pointer to interface this packet is on             */
2766 /*             out(I)  - 0 == packet going in, 1 == packet going out        */
2767 /*             mp(IO)  - pointer to caller's buffer pointer that holds this */
2768 /*                       IP packet.                                         */
2769 /* Solaris & HP-UX ONLY :                                                   */
2770 /*             qpi(I)  - pointer to STREAMS queue information for this      */
2771 /*                       interface & direction.                             */
2772 /*                                                                          */
2773 /* ipf_check() is the master function for all IPFilter packet processing.   */
2774 /* It orchestrates: Network Address Translation (NAT), checking for packet  */
2775 /* authorisation (or pre-authorisation), presence of related state info.,   */
2776 /* generating log entries, IP packet accounting, routing of packets as      */
2777 /* directed by firewall rules and of course whether or not to allow the     */
2778 /* packet to be further processed by the kernel.                            */
2779 /*                                                                          */
2780 /* For packets blocked, the contents of "mp" will be NULL'd and the buffer  */
2781 /* freed.  Packets passed may be returned with the pointer pointed to by    */
2782 /* by "mp" changed to a new buffer.                                         */
2783 /* ------------------------------------------------------------------------ */
2784 int
2785 ipf_check(void *ctx, ip_t *ip, int hlen, void *ifp, int out,
2786 #if defined(_KERNEL) && defined(MENTAT)
2787     void *qif,
2788 #endif
2789     mb_t **mp)
2790 {
2791 	/*
2792 	 * The above really sucks, but short of writing a diff
2793 	 */
2794 	ipf_main_softc_t *softc = ctx;
2795 	fr_info_t frinfo;
2796 	fr_info_t *fin = &frinfo;
2797 	u_32_t pass = softc->ipf_pass;
2798 	frentry_t *fr = NULL;
2799 	int v = IP_V(ip);
2800 	mb_t *mc = NULL;
2801 	mb_t *m;
2802 	/*
2803 	 * The first part of ipf_check() deals with making sure that what goes
2804 	 * into the filtering engine makes some sense.  Information about the
2805 	 * the packet is distilled, collected into a fr_info_t structure and
2806 	 * the an attempt to ensure the buffer the packet is in is big enough
2807 	 * to hold all the required packet headers.
2808 	 */
2809 #ifdef	_KERNEL
2810 # ifdef MENTAT
2811 	qpktinfo_t *qpi = qif;
2812 
2813 #  ifdef __sparc
2814 	if ((u_int)ip & 0x3)
2815 		return 2;
2816 #  endif
2817 # else
2818 	SPL_INT(s);
2819 # endif
2820 
2821 	if (softc->ipf_running <= 0) {
2822 		return 0;
2823 	}
2824 
2825 	bzero((char *)fin, sizeof(*fin));
2826 
2827 # ifdef MENTAT
2828 	if (qpi->qpi_flags & QF_BROADCAST)
2829 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2830 	if (qpi->qpi_flags & QF_MULTICAST)
2831 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2832 	m = qpi->qpi_m;
2833 	fin->fin_qfm = m;
2834 	fin->fin_qpi = qpi;
2835 # else /* MENTAT */
2836 
2837 	m = *mp;
2838 
2839 #  if defined(M_MCAST)
2840 	if ((m->m_flags & M_MCAST) != 0)
2841 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2842 #  endif
2843 #  if defined(M_MLOOP)
2844 	if ((m->m_flags & M_MLOOP) != 0)
2845 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2846 #  endif
2847 #  if defined(M_BCAST)
2848 	if ((m->m_flags & M_BCAST) != 0)
2849 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2850 #  endif
2851 #  ifdef M_CANFASTFWD
2852 	/*
2853 	 * XXX For now, IP Filter and fast-forwarding of cached flows
2854 	 * XXX are mutually exclusive.  Eventually, IP Filter should
2855 	 * XXX get a "can-fast-forward" filter rule.
2856 	 */
2857 	m->m_flags &= ~M_CANFASTFWD;
2858 #  endif /* M_CANFASTFWD */
2859 #  if defined(CSUM_DELAY_DATA) && (!defined(__FreeBSD_version) || \
2860 				   (__FreeBSD_version < 501108))
2861 	/*
2862 	 * disable delayed checksums.
2863 	 */
2864 	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2865 		in_undefer_cksum_tcpudp(m);
2866 		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2867 	}
2868 #  endif /* CSUM_DELAY_DATA */
2869 # endif /* MENTAT */
2870 #else
2871 	bzero((char *)fin, sizeof(*fin));
2872 	m = *mp;
2873 # if defined(M_MCAST)
2874 	if ((m->m_flags & M_MCAST) != 0)
2875 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2876 # endif
2877 # if defined(M_MLOOP)
2878 	if ((m->m_flags & M_MLOOP) != 0)
2879 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2880 # endif
2881 # if defined(M_BCAST)
2882 	if ((m->m_flags & M_BCAST) != 0)
2883 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2884 # endif
2885 #endif /* _KERNEL */
2886 
2887 	fin->fin_v = v;
2888 	fin->fin_m = m;
2889 	fin->fin_ip = ip;
2890 	fin->fin_mp = mp;
2891 	fin->fin_out = out;
2892 	fin->fin_ifp = ifp;
2893 	fin->fin_error = ENETUNREACH;
2894 	fin->fin_hlen = (u_short)hlen;
2895 	fin->fin_dp = (char *)ip + hlen;
2896 	fin->fin_main_soft = softc;
2897 
2898 	fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2899 
2900 	SPL_NET(s);
2901 
2902 #ifdef	USE_INET6
2903 	if (v == 6) {
2904 		LBUMP(ipf_stats[out].fr_ipv6);
2905 		/*
2906 		 * Jumbo grams are quite likely too big for internal buffer
2907 		 * structures to handle comfortably, for now, so just drop
2908 		 * them.
2909 		 */
2910 		if (((ip6_t *)ip)->ip6_plen == 0) {
2911 			DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
2912 			pass = FR_BLOCK|FR_NOMATCH;
2913 			fin->fin_reason = FRB_JUMBO;
2914 			goto finished;
2915 		}
2916 		fin->fin_family = AF_INET6;
2917 	} else
2918 #endif
2919 	{
2920 		fin->fin_family = AF_INET;
2921 	}
2922 
2923 	if (ipf_makefrip(hlen, ip, fin) == -1) {
2924 		DT1(frb_makefrip, fr_info_t *, fin);
2925 		pass = FR_BLOCK|FR_NOMATCH;
2926 		fin->fin_reason = FRB_MAKEFRIP;
2927 		goto finished;
2928 	}
2929 
2930 	/*
2931 	 * For at least IPv6 packets, if a m_pullup() fails then this pointer
2932 	 * becomes NULL and so we have no packet to free.
2933 	 */
2934 	if (*fin->fin_mp == NULL)
2935 		goto finished;
2936 
2937 	if (!out) {
2938 		if (v == 4) {
2939 			if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
2940 				LBUMPD(ipf_stats[0], fr_v4_badsrc);
2941 				fin->fin_flx |= FI_BADSRC;
2942 			}
2943 			if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
2944 				LBUMPD(ipf_stats[0], fr_v4_badttl);
2945 				fin->fin_flx |= FI_LOWTTL;
2946 			}
2947 		}
2948 #ifdef USE_INET6
2949 		else  if (v == 6) {
2950 			if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
2951 				LBUMPD(ipf_stats[0], fr_v6_badttl);
2952 				fin->fin_flx |= FI_LOWTTL;
2953 			}
2954 		}
2955 #endif
2956 	}
2957 
2958 	if (fin->fin_flx & FI_SHORT) {
2959 		LBUMPD(ipf_stats[out], fr_short);
2960 	}
2961 
2962 	READ_ENTER(&softc->ipf_mutex);
2963 
2964 	if (!out) {
2965 		switch (fin->fin_v)
2966 		{
2967 		case 4 :
2968 			if (ipf_nat_checkin(fin, &pass) == -1) {
2969 				goto filterdone;
2970 			}
2971 			break;
2972 #ifdef USE_INET6
2973 		case 6 :
2974 			if (ipf_nat6_checkin(fin, &pass) == -1) {
2975 				goto filterdone;
2976 			}
2977 			break;
2978 #endif
2979 		default :
2980 			break;
2981 		}
2982 	}
2983 	/*
2984 	 * Check auth now.
2985 	 * If a packet is found in the auth table, then skip checking
2986 	 * the access lists for permission but we do need to consider
2987 	 * the result as if it were from the ACL's.  In addition, being
2988 	 * found in the auth table means it has been seen before, so do
2989 	 * not pass it through accounting (again), lest it be counted twice.
2990 	 */
2991 	fr = ipf_auth_check(fin, &pass);
2992 	if (!out && (fr == NULL))
2993 		(void) ipf_acctpkt(fin, NULL);
2994 
2995 	if (fr == NULL) {
2996 		if ((fin->fin_flx & FI_FRAG) != 0)
2997 			fr = ipf_frag_known(fin, &pass);
2998 
2999 		if (fr == NULL)
3000 			fr = ipf_state_check(fin, &pass);
3001 	}
3002 
3003 	if ((pass & FR_NOMATCH) || (fr == NULL))
3004 		fr = ipf_firewall(fin, &pass);
3005 
3006 	/*
3007 	 * If we've asked to track state for this packet, set it up.
3008 	 * Here rather than ipf_firewall because ipf_checkauth may decide
3009 	 * to return a packet for "keep state"
3010 	 */
3011 	if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
3012 	    !(fin->fin_flx & FI_STATE)) {
3013 		if (ipf_state_add(softc, fin, NULL, 0) == 0) {
3014 			LBUMP(ipf_stats[out].fr_ads);
3015 		} else {
3016 			LBUMP(ipf_stats[out].fr_bads);
3017 			if (FR_ISPASS(pass)) {
3018 				DT(frb_stateadd);
3019 				pass &= ~FR_CMDMASK;
3020 				pass |= FR_BLOCK;
3021 				fin->fin_reason = FRB_STATEADD;
3022 			}
3023 		}
3024 	}
3025 
3026 	fin->fin_fr = fr;
3027 	if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
3028 		fin->fin_dif = &fr->fr_dif;
3029 		fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
3030 	}
3031 
3032 	/*
3033 	 * Only count/translate packets which will be passed on, out the
3034 	 * interface.
3035 	 */
3036 	if (out && FR_ISPASS(pass)) {
3037 		(void) ipf_acctpkt(fin, NULL);
3038 
3039 		switch (fin->fin_v)
3040 		{
3041 		case 4 :
3042 			if (ipf_nat_checkout(fin, &pass) == -1) {
3043 				;
3044 			} else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
3045 				if (ipf_updateipid(fin) == -1) {
3046 					DT(frb_updateipid);
3047 					LBUMP(ipf_stats[1].fr_ipud);
3048 					pass &= ~FR_CMDMASK;
3049 					pass |= FR_BLOCK;
3050 					fin->fin_reason = FRB_UPDATEIPID;
3051 				} else {
3052 					LBUMP(ipf_stats[0].fr_ipud);
3053 				}
3054 			}
3055 			break;
3056 #ifdef USE_INET6
3057 		case 6 :
3058 			(void) ipf_nat6_checkout(fin, &pass);
3059 			break;
3060 #endif
3061 		default :
3062 			break;
3063 		}
3064 	}
3065 
3066 filterdone:
3067 #ifdef	IPFILTER_LOG
3068 	if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
3069 		(void) ipf_dolog(fin, &pass);
3070 	}
3071 #endif
3072 
3073 	/*
3074 	 * The FI_STATE flag is cleared here so that calling ipf_state_check
3075 	 * will work when called from inside of fr_fastroute.  Although
3076 	 * there is a similar flag, FI_NATED, for NAT, it does have the same
3077 	 * impact on code execution.
3078 	 */
3079 	fin->fin_flx &= ~FI_STATE;
3080 
3081 #if defined(FASTROUTE_RECURSION)
3082 	/*
3083 	 * Up the reference on fr_lock and exit ipf_mutex. The generation of
3084 	 * a packet below can sometimes cause a recursive call into IPFilter.
3085 	 * On those platforms where that does happen, we need to hang onto
3086 	 * the filter rule just in case someone decides to remove or flush it
3087 	 * in the meantime.
3088 	 */
3089 	if (fr != NULL) {
3090 		MUTEX_ENTER(&fr->fr_lock);
3091 		fr->fr_ref++;
3092 		MUTEX_EXIT(&fr->fr_lock);
3093 	}
3094 
3095 	RWLOCK_EXIT(&softc->ipf_mutex);
3096 #endif
3097 
3098 	if ((pass & FR_RETMASK) != 0) {
3099 		/*
3100 		 * Should we return an ICMP packet to indicate error
3101 		 * status passing through the packet filter ?
3102 		 * WARNING: ICMP error packets AND TCP RST packets should
3103 		 * ONLY be sent in repsonse to incoming packets.  Sending
3104 		 * them in response to outbound packets can result in a
3105 		 * panic on some operating systems.
3106 		 */
3107 		if (!out) {
3108 			if (pass & FR_RETICMP) {
3109 				int dst;
3110 
3111 				if ((pass & FR_RETMASK) == FR_FAKEICMP)
3112 					dst = 1;
3113 				else
3114 					dst = 0;
3115 				(void) ipf_send_icmp_err(ICMP_UNREACH, fin,
3116 							 dst);
3117 				LBUMP(ipf_stats[0].fr_ret);
3118 			} else if (((pass & FR_RETMASK) == FR_RETRST) &&
3119 				   !(fin->fin_flx & FI_SHORT)) {
3120 				if (((fin->fin_flx & FI_OOW) != 0) ||
3121 				    (ipf_send_reset(fin) == 0)) {
3122 					LBUMP(ipf_stats[1].fr_ret);
3123 				}
3124 			}
3125 
3126 			/*
3127 			 * When using return-* with auth rules, the auth code
3128 			 * takes over disposing of this packet.
3129 			 */
3130 			if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
3131 				DT1(frb_authcapture, fr_info_t *, fin);
3132 				fin->fin_m = *fin->fin_mp = NULL;
3133 				fin->fin_reason = FRB_AUTHCAPTURE;
3134 				m = NULL;
3135 			}
3136 		} else {
3137 			if (pass & FR_RETRST) {
3138 				fin->fin_error = ECONNRESET;
3139 			}
3140 		}
3141 	}
3142 
3143 	/*
3144 	 * After the above so that ICMP unreachables and TCP RSTs get
3145 	 * created properly.
3146 	 */
3147 	if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
3148 		ipf_nat_uncreate(fin);
3149 
3150 	/*
3151 	 * If we didn't drop off the bottom of the list of rules (and thus
3152 	 * the 'current' rule fr is not NULL), then we may have some extra
3153 	 * instructions about what to do with a packet.
3154 	 * Once we're finished return to our caller, freeing the packet if
3155 	 * we are dropping it.
3156 	 */
3157 	if (fr != NULL) {
3158 		frdest_t *fdp;
3159 
3160 		/*
3161 		 * Generate a duplicated packet first because ipf_fastroute
3162 		 * can lead to fin_m being free'd... not good.
3163 		 */
3164 		fdp = fin->fin_dif;
3165 		if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3166 		    (fdp->fd_ptr != (void *)-1) && (fin->fin_m != NULL)) {
3167 			mc = M_COPY(fin->fin_m);
3168 			if (mc != NULL)
3169 				ipf_fastroute(mc, &mc, fin, fdp);
3170 		}
3171 
3172 		fdp = fin->fin_tif;
3173 		if (!out && (pass & FR_FASTROUTE)) {
3174 			/*
3175 			 * For fastroute rule, no destination interface defined
3176 			 * so pass NULL as the frdest_t parameter
3177 			 */
3178 			(void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
3179 			m = *mp = NULL;
3180 		} else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3181 			   (fdp->fd_ptr != (struct ifnet *)-1)) {
3182 			/* this is for to rules: */
3183 			ipf_fastroute(fin->fin_m, mp, fin, fdp);
3184 			m = *mp = NULL;
3185 		}
3186 
3187 #if defined(FASTROUTE_RECURSION)
3188 		(void) ipf_derefrule(softc, &fr);
3189 #endif
3190 	}
3191 #if !defined(FASTROUTE_RECURSION)
3192 	RWLOCK_EXIT(&softc->ipf_mutex);
3193 #endif
3194 
3195 finished:
3196 	if (!FR_ISPASS(pass)) {
3197 		LBUMP(ipf_stats[out].fr_block);
3198 		if (*mp != NULL) {
3199 #ifdef _KERNEL
3200 			FREE_MB_T(*mp);
3201 #endif
3202 			m = *mp = NULL;
3203 		}
3204 	} else {
3205 		LBUMP(ipf_stats[out].fr_pass);
3206 #if defined(_KERNEL) && defined(__sgi)
3207 		if ((fin->fin_hbuf != NULL) &&
3208 		    (mtod(fin->fin_m, struct ip *) != fin->fin_ip)) {
3209 			COPYBACK(fin->fin_m, 0, fin->fin_plen, fin->fin_hbuf);
3210 		}
3211 #endif
3212 	}
3213 
3214 	SPL_X(s);
3215 
3216 #ifdef _KERNEL
3217 	if (FR_ISPASS(pass))
3218 		return 0;
3219 	LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3220 	return fin->fin_error;
3221 #else /* _KERNEL */
3222 	if (*mp != NULL)
3223 		(*mp)->mb_ifp = fin->fin_ifp;
3224 	blockreason = fin->fin_reason;
3225 	FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
3226 	/*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
3227 		if ((pass & FR_NOMATCH) != 0)
3228 			return 1;
3229 
3230 	if ((pass & FR_RETMASK) != 0)
3231 		switch (pass & FR_RETMASK)
3232 		{
3233 		case FR_RETRST :
3234 			return 3;
3235 		case FR_RETICMP :
3236 			return 4;
3237 		case FR_FAKEICMP :
3238 			return 5;
3239 		}
3240 
3241 	switch (pass & FR_CMDMASK)
3242 	{
3243 	case FR_PASS :
3244 		return 0;
3245 	case FR_BLOCK :
3246 		return -1;
3247 	case FR_AUTH :
3248 		return -2;
3249 	case FR_ACCOUNT :
3250 		return -3;
3251 	case FR_PREAUTH :
3252 		return -4;
3253 	}
3254 	return 2;
3255 #endif /* _KERNEL */
3256 }
3257 
3258 
3259 #ifdef	IPFILTER_LOG
3260 /* ------------------------------------------------------------------------ */
3261 /* Function:    ipf_dolog                                                   */
3262 /* Returns:     frentry_t* - returns contents of fin_fr (no change made)    */
3263 /* Parameters:  fin(I) - pointer to packet information                      */
3264 /*              passp(IO) - pointer to current/new filter decision (unused) */
3265 /*                                                                          */
3266 /* Checks flags set to see how a packet should be logged, if it is to be    */
3267 /* logged.  Adjust statistics based on its success or not.                  */
3268 /* ------------------------------------------------------------------------ */
3269 frentry_t *
3270 ipf_dolog(fr_info_t *fin, u_32_t *passp)
3271 {
3272 	ipf_main_softc_t *softc = fin->fin_main_soft;
3273 	u_32_t pass;
3274 	int out;
3275 
3276 	out = fin->fin_out;
3277 	pass = *passp;
3278 
3279 	if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
3280 		pass |= FF_LOGNOMATCH;
3281 		LBUMPD(ipf_stats[out], fr_npkl);
3282 		goto logit;
3283 
3284 	} else if (((pass & FR_LOGMASK) == FR_LOGP) ||
3285 	    (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
3286 		if ((pass & FR_LOGMASK) != FR_LOGP)
3287 			pass |= FF_LOGPASS;
3288 		LBUMPD(ipf_stats[out], fr_ppkl);
3289 		goto logit;
3290 
3291 	} else if (((pass & FR_LOGMASK) == FR_LOGB) ||
3292 		   (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
3293 		if ((pass & FR_LOGMASK) != FR_LOGB)
3294 			pass |= FF_LOGBLOCK;
3295 		LBUMPD(ipf_stats[out], fr_bpkl);
3296 
3297 logit:
3298 		if (ipf_log_pkt(fin, pass) == -1) {
3299 			/*
3300 			 * If the "or-block" option has been used then
3301 			 * block the packet if we failed to log it.
3302 			 */
3303 			if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
3304 				DT1(frb_logfail2, u_int, pass);
3305 				pass &= ~FR_CMDMASK;
3306 				pass |= FR_BLOCK;
3307 				fin->fin_reason = FRB_LOGFAIL2;
3308 			}
3309 		}
3310 		*passp = pass;
3311 	}
3312 
3313 	return fin->fin_fr;
3314 }
3315 #endif /* IPFILTER_LOG */
3316 
3317 
3318 /* ------------------------------------------------------------------------ */
3319 /* Function:    ipf_cksum                                                   */
3320 /* Returns:     u_short - IP header checksum                                */
3321 /* Parameters:  addr(I) - pointer to start of buffer to checksum            */
3322 /*              len(I)  - length of buffer in bytes                         */
3323 /*                                                                          */
3324 /* Calculate the two's complement 16 bit checksum of the buffer passed.     */
3325 /*                                                                          */
3326 /* N.B.: addr should be 16bit aligned.                                      */
3327 /* ------------------------------------------------------------------------ */
3328 u_short
3329 ipf_cksum(u_short *addr, int len)
3330 {
3331 	u_32_t sum = 0;
3332 
3333 	for (sum = 0; len > 1; len -= 2)
3334 		sum += *addr++;
3335 
3336 	/* mop up an odd byte, if necessary */
3337 	if (len == 1)
3338 		sum += *(u_char *)addr;
3339 
3340 	/*
3341 	 * add back carry outs from top 16 bits to low 16 bits
3342 	 */
3343 	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
3344 	sum += (sum >> 16);			/* add carry */
3345 	return (u_short)(~sum);
3346 }
3347 
3348 
3349 /* ------------------------------------------------------------------------ */
3350 /* Function:    fr_cksum                                                    */
3351 /* Returns:     u_short - layer 4 checksum                                  */
3352 /* Parameters:  fin(I)     - pointer to packet information                  */
3353 /*              ip(I)      - pointer to IP header                           */
3354 /*              l4proto(I) - protocol to caclulate checksum for             */
3355 /*              l4hdr(I)   - pointer to layer 4 header                      */
3356 /*                                                                          */
3357 /* Calculates the TCP checksum for the packet held in "m", using the data   */
3358 /* in the IP header "ip" to seed it.                                        */
3359 /*                                                                          */
3360 /* NB: This function assumes we've pullup'd enough for all of the IP header */
3361 /* and the TCP header.  We also assume that data blocks aren't allocated in */
3362 /* odd sizes.                                                               */
3363 /*                                                                          */
3364 /* Expects ip_len and ip_off to be in network byte order when called.       */
3365 /* ------------------------------------------------------------------------ */
3366 u_short
3367 fr_cksum(fr_info_t *fin, ip_t *ip, int l4proto, void *l4hdr)
3368 {
3369 	u_short *sp, slen, sumsave, *csump;
3370 	u_int sum, sum2;
3371 	int hlen;
3372 	int off;
3373 #ifdef	USE_INET6
3374 	ip6_t *ip6;
3375 #endif
3376 
3377 	csump = NULL;
3378 	sumsave = 0;
3379 	sp = NULL;
3380 	slen = 0;
3381 	hlen = 0;
3382 	sum = 0;
3383 
3384 	sum = htons((u_short)l4proto);
3385 	/*
3386 	 * Add up IP Header portion
3387 	 */
3388 #ifdef	USE_INET6
3389 	if (IP_V(ip) == 4) {
3390 #endif
3391 		hlen = IP_HL(ip) << 2;
3392 		off = hlen;
3393 		sp = (u_short *)&ip->ip_src;
3394 		sum += *sp++;	/* ip_src */
3395 		sum += *sp++;
3396 		sum += *sp++;	/* ip_dst */
3397 		sum += *sp++;
3398 #ifdef	USE_INET6
3399 	} else if (IP_V(ip) == 6) {
3400 		ip6 = (ip6_t *)ip;
3401 		hlen = sizeof(*ip6);
3402 		off = ((char *)fin->fin_dp - (char *)fin->fin_ip);
3403 		sp = (u_short *)&ip6->ip6_src;
3404 		sum += *sp++;	/* ip6_src */
3405 		sum += *sp++;
3406 		sum += *sp++;
3407 		sum += *sp++;
3408 		sum += *sp++;
3409 		sum += *sp++;
3410 		sum += *sp++;
3411 		sum += *sp++;
3412 		/* This needs to be routing header aware. */
3413 		sum += *sp++;	/* ip6_dst */
3414 		sum += *sp++;
3415 		sum += *sp++;
3416 		sum += *sp++;
3417 		sum += *sp++;
3418 		sum += *sp++;
3419 		sum += *sp++;
3420 		sum += *sp++;
3421 	} else {
3422 		return 0xffff;
3423 	}
3424 #endif
3425 	slen = fin->fin_plen - off;
3426 	sum += htons(slen);
3427 
3428 	switch (l4proto)
3429 	{
3430 	case IPPROTO_UDP :
3431 		csump = &((udphdr_t *)l4hdr)->uh_sum;
3432 		break;
3433 
3434 	case IPPROTO_TCP :
3435 		csump = &((tcphdr_t *)l4hdr)->th_sum;
3436 		break;
3437 	case IPPROTO_ICMP :
3438 		csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
3439 		sum = 0;	/* Pseudo-checksum is not included */
3440 		break;
3441 #ifdef USE_INET6
3442 	case IPPROTO_ICMPV6 :
3443 		csump = &((struct icmp6_hdr *)l4hdr)->icmp6_cksum;
3444 		break;
3445 #endif
3446 	default :
3447 		break;
3448 	}
3449 
3450 	if (csump != NULL) {
3451 		sumsave = *csump;
3452 		*csump = 0;
3453 	}
3454 
3455 	sum2 = ipf_pcksum(fin, off, sum);
3456 	if (csump != NULL)
3457 		*csump = sumsave;
3458 	return sum2;
3459 }
3460 
3461 
3462 /* ------------------------------------------------------------------------ */
3463 /* Function:    ipf_findgroup                                               */
3464 /* Returns:     frgroup_t * - NULL = group not found, else pointer to group */
3465 /* Parameters:  softc(I) - pointer to soft context main structure           */
3466 /*              group(I) - group name to search for                         */
3467 /*              unit(I)  - device to which this group belongs               */
3468 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3469 /*              fgpp(O)  - pointer to place to store pointer to the pointer */
3470 /*                         to where to add the next (last) group or where   */
3471 /*                         to delete group from.                            */
3472 /*                                                                          */
3473 /* Search amongst the defined groups for a particular group number.         */
3474 /* ------------------------------------------------------------------------ */
3475 frgroup_t *
3476 ipf_findgroup(ipf_main_softc_t *softc, char *group, minor_t unit, int set,
3477     frgroup_t ***fgpp)
3478 {
3479 	frgroup_t *fg, **fgp;
3480 
3481 	/*
3482 	 * Which list of groups to search in is dependent on which list of
3483 	 * rules are being operated on.
3484 	 */
3485 	fgp = &softc->ipf_groups[unit][set];
3486 
3487 	while ((fg = *fgp) != NULL) {
3488 		if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3489 			break;
3490 		else
3491 			fgp = &fg->fg_next;
3492 	}
3493 	if (fgpp != NULL)
3494 		*fgpp = fgp;
3495 	return fg;
3496 }
3497 
3498 
3499 /* ------------------------------------------------------------------------ */
3500 /* Function:    ipf_group_add                                               */
3501 /* Returns:     frgroup_t * - NULL == did not create group,                 */
3502 /*                            != NULL == pointer to the group               */
3503 /* Parameters:  softc(I) - pointer to soft context main structure           */
3504 /*              num(I)   - group number to add                              */
3505 /*              head(I)  - rule pointer that is using this as the head      */
3506 /*              flags(I) - rule flags which describe the type of rule it is */
3507 /*              unit(I)  - device to which this group will belong to        */
3508 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3509 /* Write Locks: ipf_mutex                                                   */
3510 /*                                                                          */
3511 /* Add a new group head, or if it already exists, increase the reference    */
3512 /* count to it.                                                             */
3513 /* ------------------------------------------------------------------------ */
3514 frgroup_t *
3515 ipf_group_add(ipf_main_softc_t *softc, char *group, void *head, u_32_t flags,
3516     minor_t unit, int set)
3517 {
3518 	frgroup_t *fg, **fgp;
3519 	u_32_t gflags;
3520 
3521 	if (group == NULL)
3522 		return NULL;
3523 
3524 	if (unit == IPL_LOGIPF && *group == '\0')
3525 		return NULL;
3526 
3527 	fgp = NULL;
3528 	gflags = flags & FR_INOUT;
3529 
3530 	fg = ipf_findgroup(softc, group, unit, set, &fgp);
3531 	if (fg != NULL) {
3532 		if (fg->fg_head == NULL && head != NULL)
3533 			fg->fg_head = head;
3534 		if (fg->fg_flags == 0)
3535 			fg->fg_flags = gflags;
3536 		else if (gflags != fg->fg_flags)
3537 			return NULL;
3538 		fg->fg_ref++;
3539 		return fg;
3540 	}
3541 
3542 	KMALLOC(fg, frgroup_t *);
3543 	if (fg != NULL) {
3544 		fg->fg_head = head;
3545 		fg->fg_start = NULL;
3546 		fg->fg_next = *fgp;
3547 		bcopy(group, fg->fg_name, strlen(group) + 1);
3548 		fg->fg_flags = gflags;
3549 		fg->fg_ref = 1;
3550 		fg->fg_set = &softc->ipf_groups[unit][set];
3551 		*fgp = fg;
3552 	}
3553 	return fg;
3554 }
3555 
3556 
3557 /* ------------------------------------------------------------------------ */
3558 /* Function:    ipf_group_del                                               */
3559 /* Returns:     int      - number of rules deleted                          */
3560 /* Parameters:  softc(I) - pointer to soft context main structure           */
3561 /*              group(I) - group name to delete                             */
3562 /*              fr(I)    - filter rule from which group is referenced       */
3563 /* Write Locks: ipf_mutex                                                   */
3564 /*                                                                          */
3565 /* This function is called whenever a reference to a group is to be dropped */
3566 /* and thus its reference count needs to be lowered and the group free'd if */
3567 /* the reference count reaches zero. Passing in fr is really for the sole   */
3568 /* purpose of knowing when the head rule is being deleted.                  */
3569 /* ------------------------------------------------------------------------ */
3570 void
3571 ipf_group_del(ipf_main_softc_t *softc, frgroup_t *group, frentry_t *fr)
3572 {
3573 
3574 	if (group->fg_head == fr)
3575 		group->fg_head = NULL;
3576 
3577 	group->fg_ref--;
3578 	if ((group->fg_ref == 0) && (group->fg_start == NULL))
3579 		ipf_group_free(group);
3580 }
3581 
3582 
3583 /* ------------------------------------------------------------------------ */
3584 /* Function:    ipf_group_free                                              */
3585 /* Returns:     Nil                                                         */
3586 /* Parameters:  group(I) - pointer to filter rule group                     */
3587 /*                                                                          */
3588 /* Remove the group from the list of groups and free it.                    */
3589 /* ------------------------------------------------------------------------ */
3590 static void
3591 ipf_group_free(frgroup_t *group)
3592 {
3593 	frgroup_t **gp;
3594 
3595 	for (gp = group->fg_set; *gp != NULL; gp = &(*gp)->fg_next) {
3596 		if (*gp == group) {
3597 			*gp = group->fg_next;
3598 			break;
3599 		}
3600 	}
3601 	KFREE(group);
3602 }
3603 
3604 
3605 /* ------------------------------------------------------------------------ */
3606 /* Function:    ipf_group_flush                                             */
3607 /* Returns:     int      - number of rules flush from group                 */
3608 /* Parameters:  softc(I) - pointer to soft context main structure           */
3609 /* Parameters:  group(I) - pointer to filter rule group                     */
3610 /*                                                                          */
3611 /* Remove all of the rules that currently are listed under the given group. */
3612 /* ------------------------------------------------------------------------ */
3613 static int
3614 ipf_group_flush(ipf_main_softc_t *softc, frgroup_t *group)
3615 {
3616 	int gone = 0;
3617 
3618 	(void) ipf_flushlist(softc, &gone, &group->fg_start);
3619 
3620 	return gone;
3621 }
3622 
3623 
3624 /* ------------------------------------------------------------------------ */
3625 /* Function:    ipf_getrulen                                                */
3626 /* Returns:     frentry_t * - NULL == not found, else pointer to rule n     */
3627 /* Parameters:  softc(I) - pointer to soft context main structure           */
3628 /* Parameters:  unit(I)  - device for which to count the rule's number      */
3629 /*              flags(I) - which set of rules to find the rule in           */
3630 /*              group(I) - group name                                       */
3631 /*              n(I)     - rule number to find                              */
3632 /*                                                                          */
3633 /* Find rule # n in group # g and return a pointer to it.  Return NULl if   */
3634 /* group # g doesn't exist or there are less than n rules in the group.     */
3635 /* ------------------------------------------------------------------------ */
3636 frentry_t *
3637 ipf_getrulen(ipf_main_softc_t *softc, int unit, char *group, u_32_t n)
3638 {
3639 	frentry_t *fr;
3640 	frgroup_t *fg;
3641 
3642 	fg = ipf_findgroup(softc, group, unit, softc->ipf_active, NULL);
3643 	if (fg == NULL)
3644 		return NULL;
3645 	for (fr = fg->fg_start; fr && n; fr = fr->fr_next, n--)
3646 		;
3647 	if (n != 0)
3648 		return NULL;
3649 	return fr;
3650 }
3651 
3652 
3653 /* ------------------------------------------------------------------------ */
3654 /* Function:    ipf_flushlist                                               */
3655 /* Returns:     int - >= 0 - number of flushed rules                        */
3656 /* Parameters:  softc(I)   - pointer to soft context main structure         */
3657 /*              nfreedp(O) - pointer to int where flush count is stored     */
3658 /*              listp(I)   - pointer to list to flush pointer               */
3659 /* Write Locks: ipf_mutex                                                   */
3660 /*                                                                          */
3661 /* Recursively flush rules from the list, descending groups as they are     */
3662 /* encountered.  if a rule is the head of a group and it has lost all its   */
3663 /* group members, then also delete the group reference.  nfreedp is needed  */
3664 /* to store the accumulating count of rules removed, whereas the returned   */
3665 /* value is just the number removed from the current list.  The latter is   */
3666 /* needed to correctly adjust reference counts on rules that define groups. */
3667 /*                                                                          */
3668 /* NOTE: Rules not loaded from user space cannot be flushed.                */
3669 /* ------------------------------------------------------------------------ */
3670 static int
3671 ipf_flushlist(ipf_main_softc_t *softc, int *nfreedp, frentry_t **listp)
3672 {
3673 	int freed = 0;
3674 	frentry_t *fp;
3675 
3676 	while ((fp = *listp) != NULL) {
3677 		if ((fp->fr_type & FR_T_BUILTIN) ||
3678 		    !(fp->fr_flags & FR_COPIED)) {
3679 			listp = &fp->fr_next;
3680 			continue;
3681 		}
3682 		*listp = fp->fr_next;
3683 		if (fp->fr_next != NULL)
3684 			fp->fr_next->fr_pnext = fp->fr_pnext;
3685 		fp->fr_pnext = NULL;
3686 
3687 		if (fp->fr_grphead != NULL) {
3688 			freed += ipf_group_flush(softc, fp->fr_grphead);
3689 			fp->fr_names[fp->fr_grhead] = '\0';
3690 		}
3691 
3692 		if (fp->fr_icmpgrp != NULL) {
3693 			freed += ipf_group_flush(softc, fp->fr_icmpgrp);
3694 			fp->fr_names[fp->fr_icmphead] = '\0';
3695 		}
3696 
3697 		if (fp->fr_srctrack.ht_max_nodes)
3698 			ipf_rb_ht_flush(&fp->fr_srctrack);
3699 
3700 		fp->fr_next = NULL;
3701 
3702 		ASSERT(fp->fr_ref > 0);
3703 		if (ipf_derefrule(softc, &fp) == 0)
3704 			freed++;
3705 	}
3706 	*nfreedp += freed;
3707 	return freed;
3708 }
3709 
3710 
3711 /* ------------------------------------------------------------------------ */
3712 /* Function:    ipf_flush                                                   */
3713 /* Returns:     int - >= 0 - number of flushed rules                        */
3714 /* Parameters:  softc(I) - pointer to soft context main structure           */
3715 /*              unit(I)  - device for which to flush rules                  */
3716 /*              flags(I) - which set of rules to flush                      */
3717 /*                                                                          */
3718 /* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3719 /* and IPv6) as defined by the value of flags.                              */
3720 /* ------------------------------------------------------------------------ */
3721 int
3722 ipf_flush(ipf_main_softc_t *softc, minor_t unit, int flags)
3723 {
3724 	int flushed = 0, set;
3725 
3726 	WRITE_ENTER(&softc->ipf_mutex);
3727 
3728 	set = softc->ipf_active;
3729 	if ((flags & FR_INACTIVE) == FR_INACTIVE)
3730 		set = 1 - set;
3731 
3732 	if (flags & FR_OUTQUE) {
3733 		ipf_flushlist(softc, &flushed, &softc->ipf_rules[1][set]);
3734 		ipf_flushlist(softc, &flushed, &softc->ipf_acct[1][set]);
3735 	}
3736 	if (flags & FR_INQUE) {
3737 		ipf_flushlist(softc, &flushed, &softc->ipf_rules[0][set]);
3738 		ipf_flushlist(softc, &flushed, &softc->ipf_acct[0][set]);
3739 	}
3740 
3741 	flushed += ipf_flush_groups(softc, &softc->ipf_groups[unit][set],
3742 				    flags & (FR_INQUE|FR_OUTQUE));
3743 
3744 	RWLOCK_EXIT(&softc->ipf_mutex);
3745 
3746 	if (unit == IPL_LOGIPF) {
3747 		int tmp;
3748 
3749 		tmp = ipf_flush(softc, IPL_LOGCOUNT, flags);
3750 		if (tmp >= 0)
3751 			flushed += tmp;
3752 	}
3753 	return flushed;
3754 }
3755 
3756 
3757 /* ------------------------------------------------------------------------ */
3758 /* Function:    ipf_flush_groups                                            */
3759 /* Returns:     int - >= 0 - number of flushed rules                        */
3760 /* Parameters:  softc(I)  - soft context pointerto work with                */
3761 /*              grhead(I) - pointer to the start of the group list to flush */
3762 /*              flags(I)  - which set of rules to flush                     */
3763 /*                                                                          */
3764 /* Walk through all of the groups under the given group head and remove all */
3765 /* of those that match the flags passed in. The for loop here is bit more   */
3766 /* complicated than usual because the removal of a rule with ipf_derefrule  */
3767 /* may end up removing not only the structure pointed to by "fg" but also   */
3768 /* what is fg_next and fg_next after that. So if a filter rule is actually  */
3769 /* removed from the group then it is necessary to start again.              */
3770 /* ------------------------------------------------------------------------ */
3771 static int
3772 ipf_flush_groups( ipf_main_softc_t *softc, frgroup_t **grhead, int flags)
3773 {
3774 	frentry_t *fr, **frp;
3775 	frgroup_t *fg, **fgp;
3776 	int flushed = 0;
3777 	int removed = 0;
3778 
3779 	for (fgp = grhead; (fg = *fgp) != NULL; ) {
3780 		while ((fg != NULL) && ((fg->fg_flags & flags) == 0))
3781 			fg = fg->fg_next;
3782 		if (fg == NULL)
3783 			break;
3784 		removed = 0;
3785 		frp = &fg->fg_start;
3786 		while ((removed == 0) && ((fr = *frp) != NULL)) {
3787 			if ((fr->fr_flags & flags) == 0) {
3788 				frp = &fr->fr_next;
3789 			} else {
3790 				if (fr->fr_next != NULL)
3791 					fr->fr_next->fr_pnext = fr->fr_pnext;
3792 				*frp = fr->fr_next;
3793 				fr->fr_pnext = NULL;
3794 				fr->fr_next = NULL;
3795 				(void) ipf_derefrule(softc, &fr);
3796 				flushed++;
3797 				removed++;
3798 			}
3799 		}
3800 		if (removed == 0)
3801 			fgp = &fg->fg_next;
3802 	}
3803 	return flushed;
3804 }
3805 
3806 
3807 /* ------------------------------------------------------------------------ */
3808 /* Function:    memstr                                                      */
3809 /* Returns:     char *  - NULL if failed, != NULL pointer to matching bytes */
3810 /* Parameters:  src(I)  - pointer to byte sequence to match                 */
3811 /*              dst(I)  - pointer to byte sequence to search                */
3812 /*              slen(I) - match length                                      */
3813 /*              dlen(I) - length available to search in                     */
3814 /*                                                                          */
3815 /* Search dst for a sequence of bytes matching those at src and extend for  */
3816 /* slen bytes.                                                              */
3817 /* ------------------------------------------------------------------------ */
3818 char *
3819 memstr(const char *src, char *dst, size_t slen, size_t dlen)
3820 {
3821 	char *s = NULL;
3822 
3823 	while (dlen >= slen) {
3824 		if (memcmp(src, dst, slen) == 0) {
3825 			s = dst;
3826 			break;
3827 		}
3828 		dst++;
3829 		dlen--;
3830 	}
3831 	return s;
3832 }
3833 
3834 
3835 /* ------------------------------------------------------------------------ */
3836 /* Function:    ipf_fixskip                                                 */
3837 /* Returns:     Nil                                                         */
3838 /* Parameters:  listp(IO)    - pointer to start of list with skip rule      */
3839 /*              rp(I)        - rule added/removed with skip in it.          */
3840 /*              addremove(I) - adjustment (-1/+1) to make to skip count,    */
3841 /*                             depending on whether a rule was just added   */
3842 /*                             or removed.                                  */
3843 /*                                                                          */
3844 /* Adjust all the rules in a list which would have skip'd past the position */
3845 /* where we are inserting to skip to the right place given the change.      */
3846 /* ------------------------------------------------------------------------ */
3847 void
3848 ipf_fixskip(frentry_t **listp, frentry_t *rp, int addremove)
3849 {
3850 	int rules, rn;
3851 	frentry_t *fp;
3852 
3853 	rules = 0;
3854 	for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3855 		rules++;
3856 
3857 	if (!fp)
3858 		return;
3859 
3860 	for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3861 		if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3862 			fp->fr_arg += addremove;
3863 }
3864 
3865 
3866 #ifdef	_KERNEL
3867 /* ------------------------------------------------------------------------ */
3868 /* Function:    count4bits                                                  */
3869 /* Returns:     int - >= 0 - number of consecutive bits in input            */
3870 /* Parameters:  ip(I) - 32bit IP address                                    */
3871 /*                                                                          */
3872 /* IPv4 ONLY                                                                */
3873 /* count consecutive 1's in bit mask.  If the mask generated by counting    */
3874 /* consecutive 1's is different to that passed, return -1, else return #    */
3875 /* of bits.                                                                 */
3876 /* ------------------------------------------------------------------------ */
3877 int
3878 count4bits(u_32_t ip)
3879 {
3880 	u_32_t	ipn;
3881 	int	cnt = 0, i, j;
3882 
3883 	ip = ipn = ntohl(ip);
3884 	for (i = 32; i; i--, ipn *= 2)
3885 		if (ipn & 0x80000000)
3886 			cnt++;
3887 		else
3888 			break;
3889 	ipn = 0;
3890 	for (i = 32, j = cnt; i; i--, j--) {
3891 		ipn *= 2;
3892 		if (j > 0)
3893 			ipn++;
3894 	}
3895 	if (ipn == ip)
3896 		return cnt;
3897 	return -1;
3898 }
3899 
3900 
3901 /* ------------------------------------------------------------------------ */
3902 /* Function:    count6bits                                                  */
3903 /* Returns:     int - >= 0 - number of consecutive bits in input            */
3904 /* Parameters:  msk(I) - pointer to start of IPv6 bitmask                   */
3905 /*                                                                          */
3906 /* IPv6 ONLY                                                                */
3907 /* count consecutive 1's in bit mask.                                       */
3908 /* ------------------------------------------------------------------------ */
3909 # ifdef USE_INET6
3910 int
3911 count6bits(u_32_t *msk)
3912 {
3913 	int i = 0, k;
3914 	u_32_t j;
3915 
3916 	for (k = 3; k >= 0; k--)
3917 		if (msk[k] == 0xffffffff)
3918 			i += 32;
3919 		else {
3920 			for (j = msk[k]; j; j <<= 1)
3921 				if (j & 0x80000000)
3922 					i++;
3923 		}
3924 	return i;
3925 }
3926 # endif
3927 #endif /* _KERNEL */
3928 
3929 
3930 /* ------------------------------------------------------------------------ */
3931 /* Function:    ipf_synclist                                                */
3932 /* Returns:     int    - 0 = no failures, else indication of first failure  */
3933 /* Parameters:  fr(I)  - start of filter list to sync interface names for   */
3934 /*              ifp(I) - interface pointer for limiting sync lookups        */
3935 /* Write Locks: ipf_mutex                                                   */
3936 /*                                                                          */
3937 /* Walk through a list of filter rules and resolve any interface names into */
3938 /* pointers.  Where dynamic addresses are used, also update the IP address  */
3939 /* used in the rule.  The interface pointer is used to limit the lookups to */
3940 /* a specific set of matching names if it is non-NULL.                      */
3941 /* Errors can occur when resolving the destination name of to/dup-to fields */
3942 /* when the name points to a pool and that pool doest not exist. If this    */
3943 /* does happen then it is necessary to check if there are any lookup refs   */
3944 /* that need to be dropped before returning with an error.                  */
3945 /* ------------------------------------------------------------------------ */
3946 static int
3947 ipf_synclist(ipf_main_softc_t *softc, frentry_t *fr, void *ifp)
3948 {
3949 	frentry_t *frt, *start = fr;
3950 	frdest_t *fdp;
3951 	char *name;
3952 	int error;
3953 	void *ifa;
3954 	int v, i;
3955 
3956 	error = 0;
3957 
3958 	for (; fr; fr = fr->fr_next) {
3959 		if (fr->fr_family == AF_INET)
3960 			v = 4;
3961 		else if (fr->fr_family == AF_INET6)
3962 			v = 6;
3963 		else
3964 			v = 0;
3965 
3966 		/*
3967 		 * Lookup all the interface names that are part of the rule.
3968 		 */
3969 		for (i = 0; i < 4; i++) {
3970 			if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
3971 				continue;
3972 			if (fr->fr_ifnames[i] == -1)
3973 				continue;
3974 			name = FR_NAME(fr, fr_ifnames[i]);
3975 			fr->fr_ifas[i] = ipf_resolvenic(softc, name, v);
3976 		}
3977 
3978 		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
3979 			if (fr->fr_satype != FRI_NORMAL &&
3980 			    fr->fr_satype != FRI_LOOKUP) {
3981 				ifa = ipf_resolvenic(softc, fr->fr_names +
3982 						     fr->fr_sifpidx, v);
3983 				ipf_ifpaddr(softc, v, fr->fr_satype, ifa,
3984 					    &fr->fr_src6, &fr->fr_smsk6);
3985 			}
3986 			if (fr->fr_datype != FRI_NORMAL &&
3987 			    fr->fr_datype != FRI_LOOKUP) {
3988 				ifa = ipf_resolvenic(softc, fr->fr_names +
3989 						     fr->fr_sifpidx, v);
3990 				ipf_ifpaddr(softc, v, fr->fr_datype, ifa,
3991 					    &fr->fr_dst6, &fr->fr_dmsk6);
3992 			}
3993 		}
3994 
3995 		fdp = &fr->fr_tifs[0];
3996 		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
3997 			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
3998 			if (error != 0)
3999 				goto unwind;
4000 		}
4001 
4002 		fdp = &fr->fr_tifs[1];
4003 		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4004 			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4005 			if (error != 0)
4006 				goto unwind;
4007 		}
4008 
4009 		fdp = &fr->fr_dif;
4010 		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4011 			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4012 			if (error != 0)
4013 				goto unwind;
4014 		}
4015 
4016 		if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4017 		    (fr->fr_satype == FRI_LOOKUP) && (fr->fr_srcptr == NULL)) {
4018 			fr->fr_srcptr = ipf_lookup_res_num(softc,
4019 							   fr->fr_srctype,
4020 							   IPL_LOGIPF,
4021 							   fr->fr_srcnum,
4022 							   &fr->fr_srcfunc);
4023 		}
4024 		if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4025 		    (fr->fr_datype == FRI_LOOKUP) && (fr->fr_dstptr == NULL)) {
4026 			fr->fr_dstptr = ipf_lookup_res_num(softc,
4027 							   fr->fr_dsttype,
4028 							   IPL_LOGIPF,
4029 							   fr->fr_dstnum,
4030 							   &fr->fr_dstfunc);
4031 		}
4032 	}
4033 	return 0;
4034 
4035 unwind:
4036 	for (frt = start; frt != fr; fr = fr->fr_next) {
4037 		if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4038 		    (frt->fr_satype == FRI_LOOKUP) && (frt->fr_srcptr != NULL))
4039 				ipf_lookup_deref(softc, frt->fr_srctype,
4040 						 frt->fr_srcptr);
4041 		if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4042 		    (frt->fr_datype == FRI_LOOKUP) && (frt->fr_dstptr != NULL))
4043 				ipf_lookup_deref(softc, frt->fr_dsttype,
4044 						 frt->fr_dstptr);
4045 	}
4046 	return error;
4047 }
4048 
4049 
4050 /* ------------------------------------------------------------------------ */
4051 /* Function:    ipf_sync                                                    */
4052 /* Returns:     void                                                        */
4053 /* Parameters:  Nil                                                         */
4054 /*                                                                          */
4055 /* ipf_sync() is called when we suspect that the interface list or          */
4056 /* information about interfaces (like IP#) has changed.  Go through all     */
4057 /* filter rules, NAT entries and the state table and check if anything      */
4058 /* needs to be changed/updated.                                             */
4059 /* ------------------------------------------------------------------------ */
4060 int
4061 ipf_sync(ipf_main_softc_t *softc, void *ifp)
4062 {
4063 	int i;
4064 
4065 # if !SOLARIS
4066 	ipf_nat_sync(softc, ifp);
4067 	ipf_state_sync(softc, ifp);
4068 	ipf_lookup_sync(softc, ifp);
4069 # endif
4070 
4071 	WRITE_ENTER(&softc->ipf_mutex);
4072 	(void) ipf_synclist(softc, softc->ipf_acct[0][softc->ipf_active], ifp);
4073 	(void) ipf_synclist(softc, softc->ipf_acct[1][softc->ipf_active], ifp);
4074 	(void) ipf_synclist(softc, softc->ipf_rules[0][softc->ipf_active], ifp);
4075 	(void) ipf_synclist(softc, softc->ipf_rules[1][softc->ipf_active], ifp);
4076 
4077 	for (i = 0; i < IPL_LOGSIZE; i++) {
4078 		frgroup_t *g;
4079 
4080 		for (g = softc->ipf_groups[i][0]; g != NULL; g = g->fg_next)
4081 			(void) ipf_synclist(softc, g->fg_start, ifp);
4082 		for (g = softc->ipf_groups[i][1]; g != NULL; g = g->fg_next)
4083 			(void) ipf_synclist(softc, g->fg_start, ifp);
4084 	}
4085 	RWLOCK_EXIT(&softc->ipf_mutex);
4086 
4087 	return 0;
4088 }
4089 
4090 
4091 /*
4092  * In the functions below, bcopy() is called because the pointer being
4093  * copied _from_ in this instance is a pointer to a char buf (which could
4094  * end up being unaligned) and on the kernel's local stack.
4095  */
4096 /* ------------------------------------------------------------------------ */
4097 /* Function:    copyinptr                                                   */
4098 /* Returns:     int - 0 = success, else failure                             */
4099 /* Parameters:  src(I)  - pointer to the source address                     */
4100 /*              dst(I)  - destination address                               */
4101 /*              size(I) - number of bytes to copy                           */
4102 /*                                                                          */
4103 /* Copy a block of data in from user space, given a pointer to the pointer  */
4104 /* to start copying from (src) and a pointer to where to store it (dst).    */
4105 /* NB: src - pointer to user space pointer, dst - kernel space pointer      */
4106 /* ------------------------------------------------------------------------ */
4107 int
4108 copyinptr(ipf_main_softc_t *softc, void *src, void *dst, size_t size)
4109 {
4110 	void *ca;
4111 	int error;
4112 
4113 # if SOLARIS
4114 	error = COPYIN(src, &ca, sizeof(ca));
4115 	if (error != 0)
4116 		return error;
4117 # else
4118 	bcopy(src, (void *)&ca, sizeof(ca));
4119 # endif
4120 	error = COPYIN(ca, dst, size);
4121 	if (error != 0) {
4122 		IPFERROR(3);
4123 		error = EFAULT;
4124 	}
4125 	return error;
4126 }
4127 
4128 
4129 /* ------------------------------------------------------------------------ */
4130 /* Function:    copyoutptr                                                  */
4131 /* Returns:     int - 0 = success, else failure                             */
4132 /* Parameters:  src(I)  - pointer to the source address                     */
4133 /*              dst(I)  - destination address                               */
4134 /*              size(I) - number of bytes to copy                           */
4135 /*                                                                          */
4136 /* Copy a block of data out to user space, given a pointer to the pointer   */
4137 /* to start copying from (src) and a pointer to where to store it (dst).    */
4138 /* NB: src - kernel space pointer, dst - pointer to user space pointer.     */
4139 /* ------------------------------------------------------------------------ */
4140 int
4141 copyoutptr(ipf_main_softc_t *softc, void *src, void *dst, size_t size)
4142 {
4143 	void *ca;
4144 	int error;
4145 
4146 	bcopy(dst, &ca, sizeof(ca));
4147 	error = COPYOUT(src, ca, size);
4148 	if (error != 0) {
4149 		IPFERROR(4);
4150 		error = EFAULT;
4151 	}
4152 	return error;
4153 }
4154 #ifdef	_KERNEL
4155 #endif
4156 
4157 
4158 /* ------------------------------------------------------------------------ */
4159 /* Function:    ipf_lock                                                    */
4160 /* Returns:     int      - 0 = success, else error                          */
4161 /* Parameters:  data(I)  - pointer to lock value to set                     */
4162 /*              lockp(O) - pointer to location to store old lock value      */
4163 /*                                                                          */
4164 /* Get the new value for the lock integer, set it and return the old value  */
4165 /* in *lockp.                                                               */
4166 /* ------------------------------------------------------------------------ */
4167 int
4168 ipf_lock(void *data, int *lockp)
4169 {
4170 	int arg, err;
4171 
4172 	err = BCOPYIN(data, &arg, sizeof(arg));
4173 	if (err != 0)
4174 		return EFAULT;
4175 	err = BCOPYOUT(lockp, data, sizeof(*lockp));
4176 	if (err != 0)
4177 		return EFAULT;
4178 	*lockp = arg;
4179 	return 0;
4180 }
4181 
4182 
4183 /* ------------------------------------------------------------------------ */
4184 /* Function:    ipf_getstat                                                 */
4185 /* Returns:     Nil                                                         */
4186 /* Parameters:  softc(I) - pointer to soft context main structure           */
4187 /*              fiop(I)  - pointer to ipfilter stats structure              */
4188 /*              rev(I)   - version claim by program doing ioctl             */
4189 /*                                                                          */
4190 /* Stores a copy of current pointers, counters, etc, in the friostat        */
4191 /* structure.                                                               */
4192 /* If IPFILTER_COMPAT is compiled, we pretend to be whatever version the    */
4193 /* program is looking for. This ensure that validation of the version it    */
4194 /* expects will always succeed. Thus kernels with IPFILTER_COMPAT will      */
4195 /* allow older binaries to work but kernels without it will not.            */
4196 /* ------------------------------------------------------------------------ */
4197 /*ARGSUSED*/
4198 static void
4199 ipf_getstat(ipf_main_softc_t *softc, friostat_t *fiop, int rev)
4200 {
4201 	int i;
4202 
4203 	bcopy((char *)softc->ipf_stats, (char *)fiop->f_st,
4204 	      sizeof(ipf_statistics_t) * 2);
4205 	fiop->f_locks[IPL_LOGSTATE] = -1;
4206 	fiop->f_locks[IPL_LOGNAT] = -1;
4207 	fiop->f_locks[IPL_LOGIPF] = -1;
4208 	fiop->f_locks[IPL_LOGAUTH] = -1;
4209 
4210 	fiop->f_ipf[0][0] = softc->ipf_rules[0][0];
4211 	fiop->f_acct[0][0] = softc->ipf_acct[0][0];
4212 	fiop->f_ipf[0][1] = softc->ipf_rules[0][1];
4213 	fiop->f_acct[0][1] = softc->ipf_acct[0][1];
4214 	fiop->f_ipf[1][0] = softc->ipf_rules[1][0];
4215 	fiop->f_acct[1][0] = softc->ipf_acct[1][0];
4216 	fiop->f_ipf[1][1] = softc->ipf_rules[1][1];
4217 	fiop->f_acct[1][1] = softc->ipf_acct[1][1];
4218 
4219 	fiop->f_ticks = softc->ipf_ticks;
4220 	fiop->f_active = softc->ipf_active;
4221 	fiop->f_froute[0] = softc->ipf_frouteok[0];
4222 	fiop->f_froute[1] = softc->ipf_frouteok[1];
4223 	fiop->f_rb_no_mem = softc->ipf_rb_no_mem;
4224 	fiop->f_rb_node_max = softc->ipf_rb_node_max;
4225 
4226 	fiop->f_running = softc->ipf_running;
4227 	for (i = 0; i < IPL_LOGSIZE; i++) {
4228 		fiop->f_groups[i][0] = softc->ipf_groups[i][0];
4229 		fiop->f_groups[i][1] = softc->ipf_groups[i][1];
4230 	}
4231 #ifdef  IPFILTER_LOG
4232 	fiop->f_log_ok = ipf_log_logok(softc, IPL_LOGIPF);
4233 	fiop->f_log_fail = ipf_log_failures(softc, IPL_LOGIPF);
4234 	fiop->f_logging = 1;
4235 #else
4236 	fiop->f_log_ok = 0;
4237 	fiop->f_log_fail = 0;
4238 	fiop->f_logging = 0;
4239 #endif
4240 	fiop->f_defpass = softc->ipf_pass;
4241 	fiop->f_features = ipf_features;
4242 
4243 #ifdef IPFILTER_COMPAT
4244 	snprintf(fiop->f_version, sizeof(fiop->f_version),
4245 		 "IP Filter: v%d.%d.%d", (rev / 1000000) % 100,
4246 		 (rev / 10000) % 100, (rev / 100) % 100);
4247 #else
4248 	rev = rev;
4249 	(void) strncpy(fiop->f_version, ipfilter_version,
4250 		       sizeof(fiop->f_version));
4251         fiop->f_version[sizeof(fiop->f_version) - 1] = '\0';
4252 #endif
4253 }
4254 
4255 
4256 #ifdef	USE_INET6
4257 int icmptoicmp6types[ICMP_MAXTYPE+1] = {
4258 	ICMP6_ECHO_REPLY,	/* 0: ICMP_ECHOREPLY */
4259 	-1,			/* 1: UNUSED */
4260 	-1,			/* 2: UNUSED */
4261 	ICMP6_DST_UNREACH,	/* 3: ICMP_UNREACH */
4262 	-1,			/* 4: ICMP_SOURCEQUENCH */
4263 	ND_REDIRECT,		/* 5: ICMP_REDIRECT */
4264 	-1,			/* 6: UNUSED */
4265 	-1,			/* 7: UNUSED */
4266 	ICMP6_ECHO_REQUEST,	/* 8: ICMP_ECHO */
4267 	-1,			/* 9: UNUSED */
4268 	-1,			/* 10: UNUSED */
4269 	ICMP6_TIME_EXCEEDED,	/* 11: ICMP_TIMXCEED */
4270 	ICMP6_PARAM_PROB,	/* 12: ICMP_PARAMPROB */
4271 	-1,			/* 13: ICMP_TSTAMP */
4272 	-1,			/* 14: ICMP_TSTAMPREPLY */
4273 	-1,			/* 15: ICMP_IREQ */
4274 	-1,			/* 16: ICMP_IREQREPLY */
4275 	-1,			/* 17: ICMP_MASKREQ */
4276 	-1,			/* 18: ICMP_MASKREPLY */
4277 };
4278 
4279 
4280 int	icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
4281 	ICMP6_DST_UNREACH_ADDR,		/* 0: ICMP_UNREACH_NET */
4282 	ICMP6_DST_UNREACH_ADDR,		/* 1: ICMP_UNREACH_HOST */
4283 	-1,				/* 2: ICMP_UNREACH_PROTOCOL */
4284 	ICMP6_DST_UNREACH_NOPORT,	/* 3: ICMP_UNREACH_PORT */
4285 	-1,				/* 4: ICMP_UNREACH_NEEDFRAG */
4286 	ICMP6_DST_UNREACH_NOTNEIGHBOR,	/* 5: ICMP_UNREACH_SRCFAIL */
4287 	ICMP6_DST_UNREACH_ADDR,		/* 6: ICMP_UNREACH_NET_UNKNOWN */
4288 	ICMP6_DST_UNREACH_ADDR,		/* 7: ICMP_UNREACH_HOST_UNKNOWN */
4289 	-1,				/* 8: ICMP_UNREACH_ISOLATED */
4290 	ICMP6_DST_UNREACH_ADMIN,	/* 9: ICMP_UNREACH_NET_PROHIB */
4291 	ICMP6_DST_UNREACH_ADMIN,	/* 10: ICMP_UNREACH_HOST_PROHIB */
4292 	-1,				/* 11: ICMP_UNREACH_TOSNET */
4293 	-1,				/* 12: ICMP_UNREACH_TOSHOST */
4294 	ICMP6_DST_UNREACH_ADMIN,	/* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
4295 };
4296 int	icmpreplytype6[ICMP6_MAXTYPE + 1];
4297 #endif
4298 
4299 int	icmpreplytype4[ICMP_MAXTYPE + 1];
4300 
4301 
4302 /* ------------------------------------------------------------------------ */
4303 /* Function:    ipf_matchicmpqueryreply                                     */
4304 /* Returns:     int - 1 if "icmp" is a valid reply to "ic" else 0.          */
4305 /* Parameters:  v(I)    - IP protocol version (4 or 6)                      */
4306 /*              ic(I)   - ICMP information                                  */
4307 /*              icmp(I) - ICMP packet header                                */
4308 /*              rev(I)  - direction (0 = forward/1 = reverse) of packet     */
4309 /*                                                                          */
4310 /* Check if the ICMP packet defined by the header pointed to by icmp is a   */
4311 /* reply to one as described by what's in ic.  If it is a match, return 1,  */
4312 /* else return 0 for no match.                                              */
4313 /* ------------------------------------------------------------------------ */
4314 int
4315 ipf_matchicmpqueryreply(int v, icmpinfo_t *ic, icmphdr_t *icmp, int rev)
4316 {
4317 	int ictype;
4318 
4319 	ictype = ic->ici_type;
4320 
4321 	if (v == 4) {
4322 		/*
4323 		 * If we matched its type on the way in, then when going out
4324 		 * it will still be the same type.
4325 		 */
4326 		if ((!rev && (icmp->icmp_type == ictype)) ||
4327 		    (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4328 			if (icmp->icmp_type != ICMP_ECHOREPLY)
4329 				return 1;
4330 			if (icmp->icmp_id == ic->ici_id)
4331 				return 1;
4332 		}
4333 	}
4334 #ifdef	USE_INET6
4335 	else if (v == 6) {
4336 		if ((!rev && (icmp->icmp_type == ictype)) ||
4337 		    (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4338 			if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4339 				return 1;
4340 			if (icmp->icmp_id == ic->ici_id)
4341 				return 1;
4342 		}
4343 	}
4344 #endif
4345 	return 0;
4346 }
4347 
4348 /* ------------------------------------------------------------------------ */
4349 /* Function:    ipf_rule_compare                                            */
4350 /* Parameters:  fr1(I) - first rule structure to compare                    */
4351 /*              fr2(I) - second rule structure to compare                   */
4352 /* Returns:     int    - 0 == rules are the same, else mismatch             */
4353 /*                                                                          */
4354 /* Compare two rules and return 0 if they match or a number indicating      */
4355 /* which of the individual checks failed.                                   */
4356 /* ------------------------------------------------------------------------ */
4357 static int
4358 ipf_rule_compare(frentry_t *fr1, frentry_t *fr2)
4359 {
4360 	if (fr1->fr_cksum != fr2->fr_cksum)
4361 		return 1;
4362 	if (fr1->fr_size != fr2->fr_size)
4363 		return 2;
4364 	if (fr1->fr_dsize != fr2->fr_dsize)
4365 		return 3;
4366 	if (memcmp(&fr1->fr_func, &fr2->fr_func,
4367 		 fr1->fr_size - offsetof(struct frentry, fr_func)) != 0)
4368 		return 4;
4369 	if (fr1->fr_data && !fr2->fr_data)
4370 		return 5;
4371 	if (!fr1->fr_data && fr2->fr_data)
4372 		return 6;
4373 	if (fr1->fr_data) {
4374 		if (memcmp(fr1->fr_caddr, fr2->fr_caddr, fr1->fr_dsize))
4375 			return 7;
4376 	}
4377 	return 0;
4378 }
4379 
4380 
4381 /* ------------------------------------------------------------------------ */
4382 /* Function:    frrequest                                                   */
4383 /* Returns:     int - 0 == success, > 0 == errno value                      */
4384 /* Parameters:  unit(I)     - device for which this is for                  */
4385 /*              req(I)      - ioctl command (SIOC*)                         */
4386 /*              data(I)     - pointr to ioctl data                          */
4387 /*              set(I)      - 1 or 0 (filter set)                           */
4388 /*              makecopy(I) - flag indicating whether data points to a rule */
4389 /*                            in kernel space & hence doesn't need copying. */
4390 /*                                                                          */
4391 /* This function handles all the requests which operate on the list of      */
4392 /* filter rules.  This includes adding, deleting, insertion.  It is also    */
4393 /* responsible for creating groups when a "head" rule is loaded.  Interface */
4394 /* names are resolved here and other sanity checks are made on the content  */
4395 /* of the rule structure being loaded.  If a rule has user defined timeouts */
4396 /* then make sure they are created and initialised before exiting.          */
4397 /* ------------------------------------------------------------------------ */
4398 int
4399 frrequest(ipf_main_softc_t *softc, int unit, ioctlcmd_t req, void *data,
4400     int set, int makecopy)
4401 {
4402 	int error = 0, in, family, addrem, need_free = 0;
4403 	frentry_t frd, *fp, *f, **fprev, **ftail;
4404 	void *ptr, *uptr;
4405 	u_int *p, *pp;
4406 	frgroup_t *fg;
4407 	char *group;
4408 
4409 	ptr = NULL;
4410 	fg = NULL;
4411 	fp = &frd;
4412 	if (makecopy != 0) {
4413 		bzero(fp, sizeof(frd));
4414 		error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
4415 		if (error) {
4416 			return error;
4417 		}
4418 		if ((fp->fr_type & FR_T_BUILTIN) != 0) {
4419 			IPFERROR(6);
4420 			return EINVAL;
4421 		}
4422 		KMALLOCS(f, frentry_t *, fp->fr_size);
4423 		if (f == NULL) {
4424 			IPFERROR(131);
4425 			return ENOMEM;
4426 		}
4427 		bzero(f, fp->fr_size);
4428 		error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
4429 				    fp->fr_size);
4430 		if (error) {
4431 			KFREES(f, fp->fr_size);
4432 			return error;
4433 		}
4434 
4435 		fp = f;
4436 		f = NULL;
4437 		fp->fr_next = NULL;
4438 		fp->fr_dnext = NULL;
4439 		fp->fr_pnext = NULL;
4440 		fp->fr_pdnext = NULL;
4441 		fp->fr_grp = NULL;
4442 		fp->fr_grphead = NULL;
4443 		fp->fr_icmpgrp = NULL;
4444 		fp->fr_isc = (void *)-1;
4445 		fp->fr_ptr = NULL;
4446 		fp->fr_ref = 0;
4447 		fp->fr_flags |= FR_COPIED;
4448 	} else {
4449 		fp = (frentry_t *)data;
4450 		if ((fp->fr_type & FR_T_BUILTIN) == 0) {
4451 			IPFERROR(7);
4452 			return EINVAL;
4453 		}
4454 		fp->fr_flags &= ~FR_COPIED;
4455 	}
4456 
4457 	if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4458 	    ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
4459 		IPFERROR(8);
4460 		error = EINVAL;
4461 		goto donenolock;
4462 	}
4463 
4464 	family = fp->fr_family;
4465 	uptr = fp->fr_data;
4466 
4467 	if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
4468 	    req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
4469 		addrem = 0;
4470 	else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
4471 		addrem = 1;
4472 	else if (req == (ioctlcmd_t)SIOCZRLST)
4473 		addrem = 2;
4474 	else {
4475 		IPFERROR(9);
4476 		error = EINVAL;
4477 		goto donenolock;
4478 	}
4479 
4480 	/*
4481 	 * Only filter rules for IPv4 or IPv6 are accepted.
4482 	 */
4483 	if (family == AF_INET) {
4484 		/*EMPTY*/;
4485 #ifdef	USE_INET6
4486 	} else if (family == AF_INET6) {
4487 		/*EMPTY*/;
4488 #endif
4489 	} else if (family != 0) {
4490 		IPFERROR(10);
4491 		error = EINVAL;
4492 		goto donenolock;
4493 	}
4494 
4495 	/*
4496 	 * If the rule is being loaded from user space, i.e. we had to copy it
4497 	 * into kernel space, then do not trust the function pointer in the
4498 	 * rule.
4499 	 */
4500 	if ((makecopy == 1) && (fp->fr_func != NULL)) {
4501 		if (ipf_findfunc(fp->fr_func) == NULL) {
4502 			IPFERROR(11);
4503 			error = ESRCH;
4504 			goto donenolock;
4505 		}
4506 
4507 		if (addrem == 0) {
4508 			error = ipf_funcinit(softc, fp);
4509 			if (error != 0)
4510 				goto donenolock;
4511 		}
4512 	}
4513 	if ((fp->fr_flags & FR_CALLNOW) &&
4514 	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4515 		IPFERROR(142);
4516 		error = ESRCH;
4517 		goto donenolock;
4518 	}
4519 	if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
4520 	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4521 		IPFERROR(143);
4522 		error = ESRCH;
4523 		goto donenolock;
4524 	}
4525 
4526 	ptr = NULL;
4527 
4528 	if (FR_ISACCOUNT(fp->fr_flags))
4529 		unit = IPL_LOGCOUNT;
4530 
4531 	/*
4532 	 * Check that each group name in the rule has a start index that
4533 	 * is valid.
4534 	 */
4535 	if (fp->fr_icmphead != -1) {
4536 		if ((fp->fr_icmphead < 0) ||
4537 		    (fp->fr_icmphead >= fp->fr_namelen)) {
4538 			IPFERROR(136);
4539 			error = EINVAL;
4540 			goto donenolock;
4541 		}
4542 		if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
4543 			fp->fr_names[fp->fr_icmphead] = '\0';
4544 	}
4545 
4546 	if (fp->fr_grhead != -1) {
4547 		if ((fp->fr_grhead < 0) ||
4548 		    (fp->fr_grhead >= fp->fr_namelen)) {
4549 			IPFERROR(137);
4550 			error = EINVAL;
4551 			goto donenolock;
4552 		}
4553 		if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
4554 			fp->fr_names[fp->fr_grhead] = '\0';
4555 	}
4556 
4557 	if (fp->fr_group != -1) {
4558 		if ((fp->fr_group < 0) ||
4559 		    (fp->fr_group >= fp->fr_namelen)) {
4560 			IPFERROR(138);
4561 			error = EINVAL;
4562 			goto donenolock;
4563 		}
4564 		if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
4565 			/*
4566 			 * Allow loading rules that are in groups to cause
4567 			 * them to be created if they don't already exit.
4568 			 */
4569 			group = FR_NAME(fp, fr_group);
4570 			if (addrem == 0) {
4571 				fg = ipf_group_add(softc, group, NULL,
4572 						   fp->fr_flags, unit, set);
4573 				if (fg == NULL) {
4574 					IPFERROR(152);
4575 					error = ESRCH;
4576 					goto donenolock;
4577 				}
4578 				fp->fr_grp = fg;
4579 			} else {
4580 				fg = ipf_findgroup(softc, group, unit,
4581 						   set, NULL);
4582 				if (fg == NULL) {
4583 					IPFERROR(12);
4584 					error = ESRCH;
4585 					goto donenolock;
4586 				}
4587 			}
4588 
4589 			if (fg->fg_flags == 0) {
4590 				fg->fg_flags = fp->fr_flags & FR_INOUT;
4591 			} else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
4592 				IPFERROR(13);
4593 				error = ESRCH;
4594 				goto donenolock;
4595 			}
4596 		}
4597 	} else {
4598 		/*
4599 		 * If a rule is going to be part of a group then it does
4600 		 * not matter whether it is an in or out rule, but if it
4601 		 * isn't in a group, then it does...
4602 		 */
4603 		if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
4604 			IPFERROR(14);
4605 			error = EINVAL;
4606 			goto donenolock;
4607 		}
4608 	}
4609 	in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4610 
4611 	/*
4612 	 * Work out which rule list this change is being applied to.
4613 	 */
4614 	ftail = NULL;
4615 	fprev = NULL;
4616 	if (unit == IPL_LOGAUTH) {
4617 		if ((fp->fr_tifs[0].fd_ptr != NULL) ||
4618 		    (fp->fr_tifs[1].fd_ptr != NULL) ||
4619 		    (fp->fr_dif.fd_ptr != NULL) ||
4620 		    (fp->fr_flags & FR_FASTROUTE)) {
4621 			IPFERROR(145);
4622 			error = EINVAL;
4623 			goto donenolock;
4624 		}
4625 		fprev = ipf_auth_rulehead(softc);
4626 	} else {
4627 		if (FR_ISACCOUNT(fp->fr_flags))
4628 			fprev = &softc->ipf_acct[in][set];
4629 		else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4630 			fprev = &softc->ipf_rules[in][set];
4631 	}
4632 	if (fprev == NULL) {
4633 		IPFERROR(15);
4634 		error = ESRCH;
4635 		goto donenolock;
4636 	}
4637 
4638 	if (fg != NULL)
4639 		fprev = &fg->fg_start;
4640 
4641 	/*
4642 	 * Copy in extra data for the rule.
4643 	 */
4644 	if (fp->fr_dsize != 0) {
4645 		if (makecopy != 0) {
4646 			KMALLOCS(ptr, void *, fp->fr_dsize);
4647 			if (ptr == NULL) {
4648 				IPFERROR(16);
4649 				error = ENOMEM;
4650 				goto donenolock;
4651 			}
4652 
4653 			/*
4654 			 * The bcopy case is for when the data is appended
4655 			 * to the rule by ipf_in_compat().
4656 			 */
4657 			if (uptr >= (void *)fp &&
4658 			    uptr < (void *)((char *)fp + fp->fr_size)) {
4659 				bcopy(uptr, ptr, fp->fr_dsize);
4660 				error = 0;
4661 			} else {
4662 				error = COPYIN(uptr, ptr, fp->fr_dsize);
4663 				if (error != 0) {
4664 					IPFERROR(17);
4665 					error = EFAULT;
4666 					goto donenolock;
4667 				}
4668 			}
4669 		} else {
4670 			ptr = uptr;
4671 		}
4672 		fp->fr_data = ptr;
4673 	} else {
4674 		fp->fr_data = NULL;
4675 	}
4676 
4677 	/*
4678 	 * Perform per-rule type sanity checks of their members.
4679 	 * All code after this needs to be aware that allocated memory
4680 	 * may need to be free'd before exiting.
4681 	 */
4682 	switch (fp->fr_type & ~FR_T_BUILTIN)
4683 	{
4684 #if defined(IPFILTER_BPF)
4685 	case FR_T_BPFOPC :
4686 		if (fp->fr_dsize == 0) {
4687 			IPFERROR(19);
4688 			error = EINVAL;
4689 			break;
4690 		}
4691 		if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4692 			IPFERROR(20);
4693 			error = EINVAL;
4694 			break;
4695 		}
4696 		break;
4697 #endif
4698 	case FR_T_IPF :
4699 		/*
4700 		 * Preparation for error case at the bottom of this function.
4701 		 */
4702 		if (fp->fr_datype == FRI_LOOKUP)
4703 			fp->fr_dstptr = NULL;
4704 		if (fp->fr_satype == FRI_LOOKUP)
4705 			fp->fr_srcptr = NULL;
4706 
4707 		if (fp->fr_dsize != sizeof(fripf_t)) {
4708 			IPFERROR(21);
4709 			error = EINVAL;
4710 			break;
4711 		}
4712 
4713 		/*
4714 		 * Allowing a rule with both "keep state" and "with oow" is
4715 		 * pointless because adding a state entry to the table will
4716 		 * fail with the out of window (oow) flag set.
4717 		 */
4718 		if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
4719 			IPFERROR(22);
4720 			error = EINVAL;
4721 			break;
4722 		}
4723 
4724 		switch (fp->fr_satype)
4725 		{
4726 		case FRI_BROADCAST :
4727 		case FRI_DYNAMIC :
4728 		case FRI_NETWORK :
4729 		case FRI_NETMASKED :
4730 		case FRI_PEERADDR :
4731 			if (fp->fr_sifpidx < 0) {
4732 				IPFERROR(23);
4733 				error = EINVAL;
4734 			}
4735 			break;
4736 		case FRI_LOOKUP :
4737 			fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
4738 						       &fp->fr_src6,
4739 						       &fp->fr_smsk6);
4740 			if (fp->fr_srcfunc == NULL) {
4741 				IPFERROR(132);
4742 				error = ESRCH;
4743 				break;
4744 			}
4745 			break;
4746 		case FRI_NORMAL :
4747 			break;
4748 		default :
4749 			IPFERROR(133);
4750 			error = EINVAL;
4751 			break;
4752 		}
4753 		if (error != 0)
4754 			break;
4755 
4756 		switch (fp->fr_datype)
4757 		{
4758 		case FRI_BROADCAST :
4759 		case FRI_DYNAMIC :
4760 		case FRI_NETWORK :
4761 		case FRI_NETMASKED :
4762 		case FRI_PEERADDR :
4763 			if (fp->fr_difpidx < 0) {
4764 				IPFERROR(24);
4765 				error = EINVAL;
4766 			}
4767 			break;
4768 		case FRI_LOOKUP :
4769 			fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
4770 						       &fp->fr_dst6,
4771 						       &fp->fr_dmsk6);
4772 			if (fp->fr_dstfunc == NULL) {
4773 				IPFERROR(134);
4774 				error = ESRCH;
4775 			}
4776 			break;
4777 		case FRI_NORMAL :
4778 			break;
4779 		default :
4780 			IPFERROR(135);
4781 			error = EINVAL;
4782 		}
4783 		break;
4784 
4785 	case FR_T_NONE :
4786 	case FR_T_CALLFUNC :
4787 	case FR_T_COMPIPF :
4788 		break;
4789 
4790 	case FR_T_IPFEXPR :
4791 		if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
4792 			IPFERROR(25);
4793 			error = EINVAL;
4794 		}
4795 		break;
4796 
4797 	default :
4798 		IPFERROR(26);
4799 		error = EINVAL;
4800 		break;
4801 	}
4802 	if (error != 0)
4803 		goto donenolock;
4804 
4805 	if (fp->fr_tif.fd_name != -1) {
4806 		if ((fp->fr_tif.fd_name < 0) ||
4807 		    (fp->fr_tif.fd_name >= fp->fr_namelen)) {
4808 			IPFERROR(139);
4809 			error = EINVAL;
4810 			goto donenolock;
4811 		}
4812 	}
4813 
4814 	if (fp->fr_dif.fd_name != -1) {
4815 		if ((fp->fr_dif.fd_name < 0) ||
4816 		    (fp->fr_dif.fd_name >= fp->fr_namelen)) {
4817 			IPFERROR(140);
4818 			error = EINVAL;
4819 			goto donenolock;
4820 		}
4821 	}
4822 
4823 	if (fp->fr_rif.fd_name != -1) {
4824 		if ((fp->fr_rif.fd_name < 0) ||
4825 		    (fp->fr_rif.fd_name >= fp->fr_namelen)) {
4826 			IPFERROR(141);
4827 			error = EINVAL;
4828 			goto donenolock;
4829 		}
4830 	}
4831 
4832 	/*
4833 	 * Lookup all the interface names that are part of the rule.
4834 	 */
4835 	error = ipf_synclist(softc, fp, NULL);
4836 	if (error != 0)
4837 		goto donenolock;
4838 	fp->fr_statecnt = 0;
4839 	if (fp->fr_srctrack.ht_max_nodes != 0)
4840 		ipf_rb_ht_init(&fp->fr_srctrack);
4841 
4842 	/*
4843 	 * Look for an existing matching filter rule, but don't include the
4844 	 * next or interface pointer in the comparison (fr_next, fr_ifa).
4845 	 * This elminates rules which are indentical being loaded.  Checksum
4846 	 * the constant part of the filter rule to make comparisons quicker
4847 	 * (this meaning no pointers are included).
4848 	 */
4849 	for (fp->fr_cksum = 0, p = (u_int *)&fp->fr_func, pp = &fp->fr_cksum;
4850 	     p < pp; p++)
4851 		fp->fr_cksum += *p;
4852 	pp = (u_int *)((char *)fp->fr_caddr + fp->fr_dsize);
4853 	for (p = (u_int *)fp->fr_data; p < pp; p++)
4854 		fp->fr_cksum += *p;
4855 
4856 	WRITE_ENTER(&softc->ipf_mutex);
4857 
4858 	/*
4859 	 * Now that the filter rule lists are locked, we can walk the
4860 	 * chain of them without fear.
4861 	 */
4862 	ftail = fprev;
4863 	for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4864 		if (fp->fr_collect <= f->fr_collect) {
4865 			ftail = fprev;
4866 			f = NULL;
4867 			break;
4868 		}
4869 		fprev = ftail;
4870 	}
4871 
4872 	for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4873 		DT2(rule_cmp, frentry_t *, fp, frentry_t *, f);
4874 		if (ipf_rule_compare(fp, f) == 0)
4875 			break;
4876 	}
4877 
4878 	/*
4879 	 * If zero'ing statistics, copy current to caller and zero.
4880 	 */
4881 	if (addrem == 2) {
4882 		if (f == NULL) {
4883 			IPFERROR(27);
4884 			error = ESRCH;
4885 		} else {
4886 			/*
4887 			 * Copy and reduce lock because of impending copyout.
4888 			 * Well we should, but if we do then the atomicity of
4889 			 * this call and the correctness of fr_hits and
4890 			 * fr_bytes cannot be guaranteed.  As it is, this code
4891 			 * only resets them to 0 if they are successfully
4892 			 * copied out into user space.
4893 			 */
4894 			bcopy((char *)f, (char *)fp, f->fr_size);
4895 			/* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
4896 
4897 			/*
4898 			 * When we copy this rule back out, set the data
4899 			 * pointer to be what it was in user space.
4900 			 */
4901 			fp->fr_data = uptr;
4902 			error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
4903 
4904 			if (error == 0) {
4905 				if ((f->fr_dsize != 0) && (uptr != NULL)) {
4906 					error = COPYOUT(f->fr_data, uptr,
4907 							f->fr_dsize);
4908 					if (error != 0) {
4909 						IPFERROR(28);
4910 						error = EFAULT;
4911 					}
4912 				}
4913 				if (error == 0) {
4914 					f->fr_hits = 0;
4915 					f->fr_bytes = 0;
4916 				}
4917 			}
4918 		}
4919 
4920 		if (makecopy != 0) {
4921 			if (ptr != NULL) {
4922 				KFREES(ptr, fp->fr_dsize);
4923 			}
4924 			KFREES(fp, fp->fr_size);
4925 		}
4926 		RWLOCK_EXIT(&softc->ipf_mutex);
4927 		return error;
4928 	}
4929 
4930   	if (!f) {
4931 		/*
4932 		 * At the end of this, ftail must point to the place where the
4933 		 * new rule is to be saved/inserted/added.
4934 		 * For SIOCAD*FR, this should be the last rule in the group of
4935 		 * rules that have equal fr_collect fields.
4936 		 * For SIOCIN*FR, ...
4937 		 */
4938 		if (req == (ioctlcmd_t)SIOCADAFR ||
4939 		    req == (ioctlcmd_t)SIOCADIFR) {
4940 
4941 			for (ftail = fprev; (f = *ftail) != NULL; ) {
4942 				if (f->fr_collect > fp->fr_collect)
4943 					break;
4944 				ftail = &f->fr_next;
4945 				fprev = ftail;
4946 			}
4947 			ftail = fprev;
4948 			f = NULL;
4949 			ptr = NULL;
4950 		} else if (req == (ioctlcmd_t)SIOCINAFR ||
4951 			   req == (ioctlcmd_t)SIOCINIFR) {
4952 			while ((f = *fprev) != NULL) {
4953 				if (f->fr_collect >= fp->fr_collect)
4954 					break;
4955 				fprev = &f->fr_next;
4956 			}
4957   			ftail = fprev;
4958   			if (fp->fr_hits != 0) {
4959 				while (fp->fr_hits && (f = *ftail)) {
4960 					if (f->fr_collect != fp->fr_collect)
4961 						break;
4962 					fprev = ftail;
4963   					ftail = &f->fr_next;
4964 					fp->fr_hits--;
4965 				}
4966   			}
4967   			f = NULL;
4968   			ptr = NULL;
4969 		}
4970 	}
4971 
4972 	/*
4973 	 * Request to remove a rule.
4974 	 */
4975 	if (addrem == 1) {
4976 		if (!f) {
4977 			IPFERROR(29);
4978 			error = ESRCH;
4979 		} else {
4980 			/*
4981 			 * Do not allow activity from user space to interfere
4982 			 * with rules not loaded that way.
4983 			 */
4984 			if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
4985 				IPFERROR(30);
4986 				error = EPERM;
4987 				goto done;
4988 			}
4989 
4990 			/*
4991 			 * Return EBUSY if the rule is being reference by
4992 			 * something else (eg state information.)
4993 			 */
4994 			if (f->fr_ref > 1) {
4995 				IPFERROR(31);
4996 				error = EBUSY;
4997 				goto done;
4998 			}
4999 #ifdef	IPFILTER_SCAN
5000 			if (f->fr_isctag != -1 &&
5001 			    (f->fr_isc != (struct ipscan *)-1))
5002 				ipf_scan_detachfr(f);
5003 #endif
5004 
5005 			if (unit == IPL_LOGAUTH) {
5006 				error = ipf_auth_precmd(softc, req, f, ftail);
5007 				goto done;
5008 			}
5009 
5010 			ipf_rule_delete(softc, f, unit, set);
5011 
5012 			need_free = makecopy;
5013 		}
5014 	} else {
5015 		/*
5016 		 * Not removing, so we must be adding/inserting a rule.
5017 		 */
5018 		if (f != NULL) {
5019 			IPFERROR(32);
5020 			error = EEXIST;
5021 			goto done;
5022 		}
5023 		if (unit == IPL_LOGAUTH) {
5024 			error = ipf_auth_precmd(softc, req, fp, ftail);
5025 			goto done;
5026 		}
5027 
5028 		MUTEX_NUKE(&fp->fr_lock);
5029 		MUTEX_INIT(&fp->fr_lock, "filter rule lock");
5030 		if (fp->fr_die != 0)
5031 			ipf_rule_expire_insert(softc, fp, set);
5032 
5033 		fp->fr_hits = 0;
5034 		if (makecopy != 0)
5035 			fp->fr_ref = 1;
5036 		fp->fr_pnext = ftail;
5037 		fp->fr_next = *ftail;
5038 		if (fp->fr_next != NULL)
5039 			fp->fr_next->fr_pnext = &fp->fr_next;
5040 		*ftail = fp;
5041 		if (addrem == 0)
5042 			ipf_fixskip(ftail, fp, 1);
5043 
5044 		fp->fr_icmpgrp = NULL;
5045 		if (fp->fr_icmphead != -1) {
5046 			group = FR_NAME(fp, fr_icmphead);
5047 			fg = ipf_group_add(softc, group, fp, 0, unit, set);
5048 			fp->fr_icmpgrp = fg;
5049 		}
5050 
5051 		fp->fr_grphead = NULL;
5052 		if (fp->fr_grhead != -1) {
5053 			group = FR_NAME(fp, fr_grhead);
5054 			fg = ipf_group_add(softc, group, fp, fp->fr_flags,
5055 					   unit, set);
5056 			fp->fr_grphead = fg;
5057 		}
5058 	}
5059 done:
5060 	RWLOCK_EXIT(&softc->ipf_mutex);
5061 donenolock:
5062 	if (need_free || (error != 0)) {
5063 		if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
5064 			if ((fp->fr_satype == FRI_LOOKUP) &&
5065 			    (fp->fr_srcptr != NULL))
5066 				ipf_lookup_deref(softc, fp->fr_srctype,
5067 						 fp->fr_srcptr);
5068 			if ((fp->fr_datype == FRI_LOOKUP) &&
5069 			    (fp->fr_dstptr != NULL))
5070 				ipf_lookup_deref(softc, fp->fr_dsttype,
5071 						 fp->fr_dstptr);
5072 		}
5073 		if (fp->fr_grp != NULL) {
5074 			WRITE_ENTER(&softc->ipf_mutex);
5075 			ipf_group_del(softc, fp->fr_grp, fp);
5076 			RWLOCK_EXIT(&softc->ipf_mutex);
5077 		}
5078 		if ((ptr != NULL) && (makecopy != 0)) {
5079 			KFREES(ptr, fp->fr_dsize);
5080 		}
5081 		KFREES(fp, fp->fr_size);
5082 	}
5083 	return (error);
5084 }
5085 
5086 
5087 /* ------------------------------------------------------------------------ */
5088 /* Function:   ipf_rule_delete                                              */
5089 /* Returns:    Nil                                                          */
5090 /* Parameters: softc(I) - pointer to soft context main structure            */
5091 /*             f(I)     - pointer to the rule being deleted                 */
5092 /*             ftail(I) - pointer to the pointer to f                       */
5093 /*             unit(I)  - device for which this is for                      */
5094 /*             set(I)   - 1 or 0 (filter set)                               */
5095 /*                                                                          */
5096 /* This function attempts to do what it can to delete a filter rule: remove */
5097 /* it from any linked lists and remove any groups it is responsible for.    */
5098 /* But in the end, removing a rule can only drop the reference count - we   */
5099 /* must use that as the guide for whether or not it can be freed.           */
5100 /* ------------------------------------------------------------------------ */
5101 static void
5102 ipf_rule_delete(ipf_main_softc_t *softc, frentry_t *f, int unit, int set)
5103 {
5104 
5105 	/*
5106 	 * If fr_pdnext is set, then the rule is on the expire list, so
5107 	 * remove it from there.
5108 	 */
5109 	if (f->fr_pdnext != NULL) {
5110 		*f->fr_pdnext = f->fr_dnext;
5111 		if (f->fr_dnext != NULL)
5112 			f->fr_dnext->fr_pdnext = f->fr_pdnext;
5113 		f->fr_pdnext = NULL;
5114 		f->fr_dnext = NULL;
5115 	}
5116 
5117 	ipf_fixskip(f->fr_pnext, f, -1);
5118 	if (f->fr_pnext != NULL)
5119 		*f->fr_pnext = f->fr_next;
5120 	if (f->fr_next != NULL)
5121 		f->fr_next->fr_pnext = f->fr_pnext;
5122 	f->fr_pnext = NULL;
5123 	f->fr_next = NULL;
5124 
5125 	(void) ipf_derefrule(softc, &f);
5126 }
5127 
5128 /* ------------------------------------------------------------------------ */
5129 /* Function:   ipf_rule_expire_insert                                       */
5130 /* Returns:    Nil                                                          */
5131 /* Parameters: softc(I) - pointer to soft context main structure            */
5132 /*             f(I)     - pointer to rule to be added to expire list        */
5133 /*             set(I)   - 1 or 0 (filter set)                               */
5134 /*                                                                          */
5135 /* If the new rule has a given expiration time, insert it into the list of  */
5136 /* expiring rules with the ones to be removed first added to the front of   */
5137 /* the list. The insertion is O(n) but it is kept sorted for quick scans at */
5138 /* expiration interval checks.                                              */
5139 /* ------------------------------------------------------------------------ */
5140 static void
5141 ipf_rule_expire_insert(ipf_main_softc_t *softc, frentry_t *f, int set)
5142 {
5143 	frentry_t *fr;
5144 
5145 	/*
5146 	 */
5147 
5148 	f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
5149 	for (fr = softc->ipf_rule_explist[set]; fr != NULL;
5150 	     fr = fr->fr_dnext) {
5151 		if (f->fr_die < fr->fr_die)
5152 			break;
5153 		if (fr->fr_dnext == NULL) {
5154 			/*
5155 			 * We've got to the last rule and everything
5156 			 * wanted to be expired before this new node,
5157 			 * so we have to tack it on the end...
5158 			 */
5159 			fr->fr_dnext = f;
5160 			f->fr_pdnext = &fr->fr_dnext;
5161 			fr = NULL;
5162 			break;
5163 		}
5164 	}
5165 
5166 	if (softc->ipf_rule_explist[set] == NULL) {
5167 		softc->ipf_rule_explist[set] = f;
5168 		f->fr_pdnext = &softc->ipf_rule_explist[set];
5169 	} else if (fr != NULL) {
5170 		f->fr_dnext = fr;
5171 		f->fr_pdnext = fr->fr_pdnext;
5172 		fr->fr_pdnext = &f->fr_dnext;
5173 	}
5174 }
5175 
5176 
5177 /* ------------------------------------------------------------------------ */
5178 /* Function:   ipf_findlookup                                               */
5179 /* Returns:    NULL = failure, else success                                 */
5180 /* Parameters: softc(I) - pointer to soft context main structure            */
5181 /*             unit(I)  - ipf device we want to find match for              */
5182 /*             fp(I)    - rule for which lookup is for                      */
5183 /*             addrp(I) - pointer to lookup information in address struct   */
5184 /*             maskp(O) - pointer to lookup information for storage         */
5185 /*                                                                          */
5186 /* When using pools and hash tables to store addresses for matching in      */
5187 /* rules, it is necessary to resolve both the object referred to by the     */
5188 /* name or address (and return that pointer) and also provide the means by  */
5189 /* which to determine if an address belongs to that object to make the      */
5190 /* packet matching quicker.                                                 */
5191 /* ------------------------------------------------------------------------ */
5192 static void *
5193 ipf_findlookup(ipf_main_softc_t *softc, int unit, frentry_t *fr,
5194     i6addr_t *addrp, i6addr_t *maskp)
5195 {
5196 	void *ptr = NULL;
5197 
5198 	switch (addrp->iplookupsubtype)
5199 	{
5200 	case 0 :
5201 		ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
5202 					 addrp->iplookupnum,
5203 					 &maskp->iplookupfunc);
5204 		break;
5205 	case 1 :
5206 		if (addrp->iplookupname < 0)
5207 			break;
5208 		if (addrp->iplookupname >= fr->fr_namelen)
5209 			break;
5210 		ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
5211 					  fr->fr_names + addrp->iplookupname,
5212 					  &maskp->iplookupfunc);
5213 		break;
5214 	default :
5215 		break;
5216 	}
5217 
5218 	return ptr;
5219 }
5220 
5221 
5222 /* ------------------------------------------------------------------------ */
5223 /* Function:    ipf_funcinit                                                */
5224 /* Returns:     int - 0 == success, else ESRCH: cannot resolve rule details */
5225 /* Parameters:  softc(I) - pointer to soft context main structure           */
5226 /*              fr(I)    - pointer to filter rule                           */
5227 /*                                                                          */
5228 /* If a rule is a call rule, then check if the function it points to needs  */
5229 /* an init function to be called now the rule has been loaded.              */
5230 /* ------------------------------------------------------------------------ */
5231 static int
5232 ipf_funcinit(ipf_main_softc_t *softc, frentry_t *fr)
5233 {
5234 	ipfunc_resolve_t *ft;
5235 	int err;
5236 
5237 	IPFERROR(34);
5238 	err = ESRCH;
5239 
5240 	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5241 		if (ft->ipfu_addr == fr->fr_func) {
5242 			err = 0;
5243 			if (ft->ipfu_init != NULL)
5244 				err = (*ft->ipfu_init)(softc, fr);
5245 			break;
5246 		}
5247 	return err;
5248 }
5249 
5250 
5251 /* ------------------------------------------------------------------------ */
5252 /* Function:    ipf_funcfini                                                */
5253 /* Returns:     Nil                                                         */
5254 /* Parameters:  softc(I) - pointer to soft context main structure           */
5255 /*              fr(I)    - pointer to filter rule                           */
5256 /*                                                                          */
5257 /* For a given filter rule, call the matching "fini" function if the rule   */
5258 /* is using a known function that would have resulted in the "init" being   */
5259 /* called for ealier.                                                       */
5260 /* ------------------------------------------------------------------------ */
5261 static void
5262 ipf_funcfini(ipf_main_softc_t *softc, frentry_t *fr)
5263 {
5264 	ipfunc_resolve_t *ft;
5265 
5266 	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5267 		if (ft->ipfu_addr == fr->fr_func) {
5268 			if (ft->ipfu_fini != NULL)
5269 				(void) (*ft->ipfu_fini)(softc, fr);
5270 			break;
5271 		}
5272 }
5273 
5274 
5275 /* ------------------------------------------------------------------------ */
5276 /* Function:    ipf_findfunc                                                */
5277 /* Returns:     ipfunc_t - pointer to function if found, else NULL          */
5278 /* Parameters:  funcptr(I) - function pointer to lookup                     */
5279 /*                                                                          */
5280 /* Look for a function in the table of known functions.                     */
5281 /* ------------------------------------------------------------------------ */
5282 static ipfunc_t
5283 ipf_findfunc(ipfunc_t funcptr)
5284 {
5285 	ipfunc_resolve_t *ft;
5286 
5287 	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5288 		if (ft->ipfu_addr == funcptr)
5289 			return funcptr;
5290 	return NULL;
5291 }
5292 
5293 
5294 /* ------------------------------------------------------------------------ */
5295 /* Function:    ipf_resolvefunc                                             */
5296 /* Returns:     int - 0 == success, else error                              */
5297 /* Parameters:  data(IO) - ioctl data pointer to ipfunc_resolve_t struct    */
5298 /*                                                                          */
5299 /* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
5300 /* This will either be the function name (if the pointer is set) or the     */
5301 /* function pointer if the name is set.  When found, fill in the other one  */
5302 /* so that the entire, complete, structure can be copied back to user space.*/
5303 /* ------------------------------------------------------------------------ */
5304 int
5305 ipf_resolvefunc(ipf_main_softc_t *softc, void *data)
5306 {
5307 	ipfunc_resolve_t res, *ft;
5308 	int error;
5309 
5310 	error = BCOPYIN(data, &res, sizeof(res));
5311 	if (error != 0) {
5312 		IPFERROR(123);
5313 		return EFAULT;
5314 	}
5315 
5316 	if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
5317 		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5318 			if (strncmp(res.ipfu_name, ft->ipfu_name,
5319 				    sizeof(res.ipfu_name)) == 0) {
5320 				res.ipfu_addr = ft->ipfu_addr;
5321 				res.ipfu_init = ft->ipfu_init;
5322 				if (COPYOUT(&res, data, sizeof(res)) != 0) {
5323 					IPFERROR(35);
5324 					return EFAULT;
5325 				}
5326 				return 0;
5327 			}
5328 	}
5329 	if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
5330 		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5331 			if (ft->ipfu_addr == res.ipfu_addr) {
5332 				(void) strncpy(res.ipfu_name, ft->ipfu_name,
5333 					       sizeof(res.ipfu_name));
5334 				res.ipfu_init = ft->ipfu_init;
5335 				if (COPYOUT(&res, data, sizeof(res)) != 0) {
5336 					IPFERROR(36);
5337 					return EFAULT;
5338 				}
5339 				return 0;
5340 			}
5341 	}
5342 	IPFERROR(37);
5343 	return ESRCH;
5344 }
5345 
5346 
5347 #if !defined(_KERNEL) || (!defined(__NetBSD__) && !defined(__OpenBSD__) && \
5348      !defined(__FreeBSD__)) || \
5349     FREEBSD_LT_REV(501000) || NETBSD_LT_REV(105000000) || \
5350     OPENBSD_LT_REV(200006)
5351 /*
5352  * From: NetBSD
5353  * ppsratecheck(): packets (or events) per second limitation.
5354  */
5355 int
5356 ppsratecheck(lasttime, curpps, maxpps)
5357 	struct timeval *lasttime;
5358 	int *curpps;
5359 	int maxpps;	/* maximum pps allowed */
5360 {
5361 	struct timeval tv, delta;
5362 	int rv;
5363 
5364 	GETKTIME(&tv);
5365 
5366 	delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
5367 	delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
5368 	if (delta.tv_usec < 0) {
5369 		delta.tv_sec--;
5370 		delta.tv_usec += 1000000;
5371 	}
5372 
5373 	/*
5374 	 * check for 0,0 is so that the message will be seen at least once.
5375 	 * if more than one second have passed since the last update of
5376 	 * lasttime, reset the counter.
5377 	 *
5378 	 * we do increment *curpps even in *curpps < maxpps case, as some may
5379 	 * try to use *curpps for stat purposes as well.
5380 	 */
5381 	if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
5382 	    delta.tv_sec >= 1) {
5383 		*lasttime = tv;
5384 		*curpps = 0;
5385 		rv = 1;
5386 	} else if (maxpps < 0)
5387 		rv = 1;
5388 	else if (*curpps < maxpps)
5389 		rv = 1;
5390 	else
5391 		rv = 0;
5392 	*curpps = *curpps + 1;
5393 
5394 	return (rv);
5395 }
5396 #endif
5397 
5398 
5399 /* ------------------------------------------------------------------------ */
5400 /* Function:    ipf_derefrule                                               */
5401 /* Returns:     int   - 0 == rule freed up, else rule not freed             */
5402 /* Parameters:  fr(I) - pointer to filter rule                              */
5403 /*                                                                          */
5404 /* Decrement the reference counter to a rule by one.  If it reaches zero,   */
5405 /* free it and any associated storage space being used by it.               */
5406 /* ------------------------------------------------------------------------ */
5407 int
5408 ipf_derefrule(ipf_main_softc_t *softc, frentry_t **frp)
5409 {
5410 	frentry_t *fr;
5411 	frdest_t *fdp;
5412 
5413 	fr = *frp;
5414 	*frp = NULL;
5415 
5416 	MUTEX_ENTER(&fr->fr_lock);
5417 	fr->fr_ref--;
5418 	if (fr->fr_ref == 0) {
5419 		MUTEX_EXIT(&fr->fr_lock);
5420 		MUTEX_DESTROY(&fr->fr_lock);
5421 
5422 		ipf_funcfini(softc, fr);
5423 
5424 		fdp = &fr->fr_tif;
5425 		if (fdp->fd_type == FRD_DSTLIST)
5426 			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5427 
5428 		fdp = &fr->fr_rif;
5429 		if (fdp->fd_type == FRD_DSTLIST)
5430 			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5431 
5432 		fdp = &fr->fr_dif;
5433 		if (fdp->fd_type == FRD_DSTLIST)
5434 			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5435 
5436 		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5437 		    fr->fr_satype == FRI_LOOKUP)
5438 			ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
5439 		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5440 		    fr->fr_datype == FRI_LOOKUP)
5441 			ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
5442 
5443 		if (fr->fr_grp != NULL)
5444 			ipf_group_del(softc, fr->fr_grp, fr);
5445 
5446 		if (fr->fr_grphead != NULL)
5447 			ipf_group_del(softc, fr->fr_grphead, fr);
5448 
5449 		if (fr->fr_icmpgrp != NULL)
5450 			ipf_group_del(softc, fr->fr_icmpgrp, fr);
5451 
5452 		if ((fr->fr_flags & FR_COPIED) != 0) {
5453 			if (fr->fr_dsize) {
5454 				KFREES(fr->fr_data, fr->fr_dsize);
5455 			}
5456 			KFREES(fr, fr->fr_size);
5457 			return 0;
5458 		}
5459 		return 1;
5460 	} else {
5461 		MUTEX_EXIT(&fr->fr_lock);
5462 	}
5463 	return -1;
5464 }
5465 
5466 
5467 /* ------------------------------------------------------------------------ */
5468 /* Function:    ipf_grpmapinit                                              */
5469 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5470 /* Parameters:  fr(I) - pointer to rule to find hash table for              */
5471 /*                                                                          */
5472 /* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr.  */
5473 /* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap.                 */
5474 /* ------------------------------------------------------------------------ */
5475 static int
5476 ipf_grpmapinit(ipf_main_softc_t *softc, frentry_t *fr)
5477 {
5478 	char name[FR_GROUPLEN];
5479 	iphtable_t *iph;
5480 
5481 	(void) snprintf(name, sizeof(name), "%d", fr->fr_arg);
5482 	iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
5483 	if (iph == NULL) {
5484 		IPFERROR(38);
5485 		return ESRCH;
5486 	}
5487 	if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
5488 		IPFERROR(39);
5489 		return ESRCH;
5490 	}
5491 	iph->iph_ref++;
5492 	fr->fr_ptr = iph;
5493 	return 0;
5494 }
5495 
5496 
5497 /* ------------------------------------------------------------------------ */
5498 /* Function:    ipf_grpmapfini                                              */
5499 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5500 /* Parameters:  softc(I) - pointer to soft context main structure           */
5501 /*              fr(I)    - pointer to rule to release hash table for        */
5502 /*                                                                          */
5503 /* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
5504 /* be called to undo what ipf_grpmapinit caused to be done.                 */
5505 /* ------------------------------------------------------------------------ */
5506 static int
5507 ipf_grpmapfini(ipf_main_softc_t *softc, frentry_t *fr)
5508 {
5509 	iphtable_t *iph;
5510 	iph = fr->fr_ptr;
5511 	if (iph != NULL)
5512 		ipf_lookup_deref(softc, IPLT_HASH, iph);
5513 	return 0;
5514 }
5515 
5516 
5517 /* ------------------------------------------------------------------------ */
5518 /* Function:    ipf_srcgrpmap                                               */
5519 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5520 /* Parameters:  fin(I)    - pointer to packet information                   */
5521 /*              passp(IO) - pointer to current/new filter decision (unused) */
5522 /*                                                                          */
5523 /* Look for a rule group head in a hash table, using the source address as  */
5524 /* the key, and descend into that group and continue matching rules against */
5525 /* the packet.                                                              */
5526 /* ------------------------------------------------------------------------ */
5527 frentry_t *
5528 ipf_srcgrpmap(fr_info_t *fin, u_32_t *passp)
5529 {
5530 	frgroup_t *fg;
5531 	void *rval;
5532 
5533 	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5534 				 &fin->fin_src);
5535 	if (rval == NULL)
5536 		return NULL;
5537 
5538 	fg = rval;
5539 	fin->fin_fr = fg->fg_start;
5540 	(void) ipf_scanlist(fin, *passp);
5541 	return fin->fin_fr;
5542 }
5543 
5544 
5545 /* ------------------------------------------------------------------------ */
5546 /* Function:    ipf_dstgrpmap                                               */
5547 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5548 /* Parameters:  fin(I)    - pointer to packet information                   */
5549 /*              passp(IO) - pointer to current/new filter decision (unused) */
5550 /*                                                                          */
5551 /* Look for a rule group head in a hash table, using the destination        */
5552 /* address as the key, and descend into that group and continue matching    */
5553 /* rules against  the packet.                                               */
5554 /* ------------------------------------------------------------------------ */
5555 frentry_t *
5556 ipf_dstgrpmap(fr_info_t *fin, u_32_t *passp)
5557 {
5558 	frgroup_t *fg;
5559 	void *rval;
5560 
5561 	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5562 				 &fin->fin_dst);
5563 	if (rval == NULL)
5564 		return NULL;
5565 
5566 	fg = rval;
5567 	fin->fin_fr = fg->fg_start;
5568 	(void) ipf_scanlist(fin, *passp);
5569 	return fin->fin_fr;
5570 }
5571 
5572 /*
5573  * Queue functions
5574  * ===============
5575  * These functions manage objects on queues for efficient timeouts.  There
5576  * are a number of system defined queues as well as user defined timeouts.
5577  * It is expected that a lock is held in the domain in which the queue
5578  * belongs (i.e. either state or NAT) when calling any of these functions
5579  * that prevents ipf_freetimeoutqueue() from being called at the same time
5580  * as any other.
5581  */
5582 
5583 
5584 /* ------------------------------------------------------------------------ */
5585 /* Function:    ipf_addtimeoutqueue                                         */
5586 /* Returns:     struct ifqtq * - NULL if malloc fails, else pointer to      */
5587 /*                               timeout queue with given interval.         */
5588 /* Parameters:  parent(I)  - pointer to pointer to parent node of this list */
5589 /*                           of interface queues.                           */
5590 /*              seconds(I) - timeout value in seconds for this queue.       */
5591 /*                                                                          */
5592 /* This routine first looks for a timeout queue that matches the interval   */
5593 /* being requested.  If it finds one, increments the reference counter and  */
5594 /* returns a pointer to it.  If none are found, it allocates a new one and  */
5595 /* inserts it at the top of the list.                                       */
5596 /*                                                                          */
5597 /* Locking.                                                                 */
5598 /* It is assumed that the caller of this function has an appropriate lock   */
5599 /* held (exclusively) in the domain that encompases 'parent'.               */
5600 /* ------------------------------------------------------------------------ */
5601 ipftq_t *
5602 ipf_addtimeoutqueue(ipf_main_softc_t *softc, ipftq_t **parent, u_int seconds)
5603 {
5604 	ipftq_t *ifq;
5605 	u_int period;
5606 
5607 	period = seconds * IPF_HZ_DIVIDE;
5608 
5609 	MUTEX_ENTER(&softc->ipf_timeoutlock);
5610 	for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
5611 		if (ifq->ifq_ttl == period) {
5612 			/*
5613 			 * Reset the delete flag, if set, so the structure
5614 			 * gets reused rather than freed and reallocated.
5615 			 */
5616 			MUTEX_ENTER(&ifq->ifq_lock);
5617 			ifq->ifq_flags &= ~IFQF_DELETE;
5618 			ifq->ifq_ref++;
5619 			MUTEX_EXIT(&ifq->ifq_lock);
5620 			MUTEX_EXIT(&softc->ipf_timeoutlock);
5621 
5622 			return ifq;
5623 		}
5624 	}
5625 
5626 	KMALLOC(ifq, ipftq_t *);
5627 	if (ifq != NULL) {
5628 		MUTEX_NUKE(&ifq->ifq_lock);
5629 		IPFTQ_INIT(ifq, period, "ipftq mutex");
5630 		ifq->ifq_next = *parent;
5631 		ifq->ifq_pnext = parent;
5632 		ifq->ifq_flags = IFQF_USER;
5633 		ifq->ifq_ref++;
5634 		*parent = ifq;
5635 		softc->ipf_userifqs++;
5636 	}
5637 	MUTEX_EXIT(&softc->ipf_timeoutlock);
5638 	return ifq;
5639 }
5640 
5641 
5642 /* ------------------------------------------------------------------------ */
5643 /* Function:    ipf_deletetimeoutqueue                                      */
5644 /* Returns:     int    - new reference count value of the timeout queue     */
5645 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5646 /* Locks:       ifq->ifq_lock                                               */
5647 /*                                                                          */
5648 /* This routine must be called when we're discarding a pointer to a timeout */
5649 /* queue object, taking care of the reference counter.                      */
5650 /*                                                                          */
5651 /* Now that this just sets a DELETE flag, it requires the expire code to    */
5652 /* check the list of user defined timeout queues and call the free function */
5653 /* below (currently commented out) to stop memory leaking.  It is done this */
5654 /* way because the locking may not be sufficient to safely do a free when   */
5655 /* this function is called.                                                 */
5656 /* ------------------------------------------------------------------------ */
5657 int
5658 ipf_deletetimeoutqueue(ipftq_t *ifq)
5659 {
5660 
5661 	ifq->ifq_ref--;
5662 	if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
5663 		ifq->ifq_flags |= IFQF_DELETE;
5664 	}
5665 
5666 	return ifq->ifq_ref;
5667 }
5668 
5669 
5670 /* ------------------------------------------------------------------------ */
5671 /* Function:    ipf_freetimeoutqueue                                        */
5672 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5673 /* Returns:     Nil                                                         */
5674 /*                                                                          */
5675 /* Locking:                                                                 */
5676 /* It is assumed that the caller of this function has an appropriate lock   */
5677 /* held (exclusively) in the domain that encompases the callers "domain".   */
5678 /* The ifq_lock for this structure should not be held.                      */
5679 /*                                                                          */
5680 /* Remove a user defined timeout queue from the list of queues it is in and */
5681 /* tidy up after this is done.                                              */
5682 /* ------------------------------------------------------------------------ */
5683 void
5684 ipf_freetimeoutqueue(ipf_main_softc_t *softc, ipftq_t *ifq)
5685 {
5686 
5687 	if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5688 	    ((ifq->ifq_flags & IFQF_USER) == 0)) {
5689 		printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5690 		       (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5691 		       ifq->ifq_ref);
5692 		return;
5693 	}
5694 
5695 	/*
5696 	 * Remove from its position in the list.
5697 	 */
5698 	*ifq->ifq_pnext = ifq->ifq_next;
5699 	if (ifq->ifq_next != NULL)
5700 		ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5701 	ifq->ifq_next = NULL;
5702 	ifq->ifq_pnext = NULL;
5703 
5704 	MUTEX_DESTROY(&ifq->ifq_lock);
5705 	ATOMIC_DEC(softc->ipf_userifqs);
5706 	KFREE(ifq);
5707 }
5708 
5709 
5710 /* ------------------------------------------------------------------------ */
5711 /* Function:    ipf_deletequeueentry                                        */
5712 /* Returns:     Nil                                                         */
5713 /* Parameters:  tqe(I) - timeout queue entry to delete                      */
5714 /*                                                                          */
5715 /* Remove a tail queue entry from its queue and make it an orphan.          */
5716 /* ipf_deletetimeoutqueue is called to make sure the reference count on the */
5717 /* queue is correct.  We can't, however, call ipf_freetimeoutqueue because  */
5718 /* the correct lock(s) may not be held that would make it safe to do so.    */
5719 /* ------------------------------------------------------------------------ */
5720 void
5721 ipf_deletequeueentry(ipftqent_t *tqe)
5722 {
5723 	ipftq_t *ifq;
5724 
5725 	ifq = tqe->tqe_ifq;
5726 
5727 	MUTEX_ENTER(&ifq->ifq_lock);
5728 
5729 	if (tqe->tqe_pnext != NULL) {
5730 		*tqe->tqe_pnext = tqe->tqe_next;
5731 		if (tqe->tqe_next != NULL)
5732 			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5733 		else    /* we must be the tail anyway */
5734 			ifq->ifq_tail = tqe->tqe_pnext;
5735 
5736 		tqe->tqe_pnext = NULL;
5737 		tqe->tqe_ifq = NULL;
5738 	}
5739 
5740 	(void) ipf_deletetimeoutqueue(ifq);
5741 	ASSERT(ifq->ifq_ref > 0);
5742 
5743 	MUTEX_EXIT(&ifq->ifq_lock);
5744 }
5745 
5746 
5747 /* ------------------------------------------------------------------------ */
5748 /* Function:    ipf_queuefront                                              */
5749 /* Returns:     Nil                                                         */
5750 /* Parameters:  tqe(I) - pointer to timeout queue entry                     */
5751 /*                                                                          */
5752 /* Move a queue entry to the front of the queue, if it isn't already there. */
5753 /* ------------------------------------------------------------------------ */
5754 void
5755 ipf_queuefront(ipftqent_t *tqe)
5756 {
5757 	ipftq_t *ifq;
5758 
5759 	ifq = tqe->tqe_ifq;
5760 	if (ifq == NULL)
5761 		return;
5762 
5763 	MUTEX_ENTER(&ifq->ifq_lock);
5764 	if (ifq->ifq_head != tqe) {
5765 		*tqe->tqe_pnext = tqe->tqe_next;
5766 		if (tqe->tqe_next)
5767 			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5768 		else
5769 			ifq->ifq_tail = tqe->tqe_pnext;
5770 
5771 		tqe->tqe_next = ifq->ifq_head;
5772 		ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5773 		ifq->ifq_head = tqe;
5774 		tqe->tqe_pnext = &ifq->ifq_head;
5775 	}
5776 	MUTEX_EXIT(&ifq->ifq_lock);
5777 }
5778 
5779 
5780 /* ------------------------------------------------------------------------ */
5781 /* Function:    ipf_queueback                                               */
5782 /* Returns:     Nil                                                         */
5783 /* Parameters:  ticks(I) - ipf tick time to use with this call              */
5784 /*              tqe(I)   - pointer to timeout queue entry                   */
5785 /*                                                                          */
5786 /* Move a queue entry to the back of the queue, if it isn't already there.  */
5787 /* We use use ticks to calculate the expiration and mark for when we last   */
5788 /* touched the structure.                                                   */
5789 /* ------------------------------------------------------------------------ */
5790 void
5791 ipf_queueback(u_long ticks, ipftqent_t *tqe)
5792 {
5793 	ipftq_t *ifq;
5794 
5795 	ifq = tqe->tqe_ifq;
5796 	if (ifq == NULL)
5797 		return;
5798 	tqe->tqe_die = ticks + ifq->ifq_ttl;
5799 	tqe->tqe_touched = ticks;
5800 
5801 	MUTEX_ENTER(&ifq->ifq_lock);
5802 	if (tqe->tqe_next != NULL) {		/* at the end already ? */
5803 		/*
5804 		 * Remove from list
5805 		 */
5806 		*tqe->tqe_pnext = tqe->tqe_next;
5807 		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5808 
5809 		/*
5810 		 * Make it the last entry.
5811 		 */
5812 		tqe->tqe_next = NULL;
5813 		tqe->tqe_pnext = ifq->ifq_tail;
5814 		*ifq->ifq_tail = tqe;
5815 		ifq->ifq_tail = &tqe->tqe_next;
5816 	}
5817 	MUTEX_EXIT(&ifq->ifq_lock);
5818 }
5819 
5820 
5821 /* ------------------------------------------------------------------------ */
5822 /* Function:    ipf_queueappend                                             */
5823 /* Returns:     Nil                                                         */
5824 /* Parameters:  ticks(I)  - ipf tick time to use with this call             */
5825 /*              tqe(I)    - pointer to timeout queue entry                  */
5826 /*              ifq(I)    - pointer to timeout queue                        */
5827 /*              parent(I) - owing object pointer                            */
5828 /*                                                                          */
5829 /* Add a new item to this queue and put it on the very end.                 */
5830 /* We use use ticks to calculate the expiration and mark for when we last   */
5831 /* touched the structure.                                                   */
5832 /* ------------------------------------------------------------------------ */
5833 void
5834 ipf_queueappend(u_long ticks, ipftqent_t *tqe, ipftq_t *ifq, void *parent)
5835 {
5836 
5837 	MUTEX_ENTER(&ifq->ifq_lock);
5838 	tqe->tqe_parent = parent;
5839 	tqe->tqe_pnext = ifq->ifq_tail;
5840 	*ifq->ifq_tail = tqe;
5841 	ifq->ifq_tail = &tqe->tqe_next;
5842 	tqe->tqe_next = NULL;
5843 	tqe->tqe_ifq = ifq;
5844 	tqe->tqe_die = ticks + ifq->ifq_ttl;
5845 	tqe->tqe_touched = ticks;
5846 	ifq->ifq_ref++;
5847 	MUTEX_EXIT(&ifq->ifq_lock);
5848 }
5849 
5850 
5851 /* ------------------------------------------------------------------------ */
5852 /* Function:    ipf_movequeue                                               */
5853 /* Returns:     Nil                                                         */
5854 /* Parameters:  tq(I)   - pointer to timeout queue information              */
5855 /*              oifp(I) - old timeout queue entry was on                    */
5856 /*              nifp(I) - new timeout queue to put entry on                 */
5857 /*                                                                          */
5858 /* Move a queue entry from one timeout queue to another timeout queue.      */
5859 /* If it notices that the current entry is already last and does not need   */
5860 /* to move queue, the return.                                               */
5861 /* ------------------------------------------------------------------------ */
5862 void
5863 ipf_movequeue(u_long ticks, ipftqent_t *tqe, ipftq_t *oifq, ipftq_t *nifq)
5864 {
5865 
5866 	/*
5867 	 * If the queue hasn't changed and we last touched this entry at the
5868 	 * same ipf time, then we're not going to achieve anything by either
5869 	 * changing the ttl or moving it on the queue.
5870 	 */
5871 	if (oifq == nifq && tqe->tqe_touched == ticks)
5872 		return;
5873 
5874 	/*
5875 	 * For any of this to be outside the lock, there is a risk that two
5876 	 * packets entering simultaneously, with one changing to a different
5877 	 * queue and one not, could end up with things in a bizarre state.
5878 	 */
5879 	MUTEX_ENTER(&oifq->ifq_lock);
5880 
5881 	tqe->tqe_touched = ticks;
5882 	tqe->tqe_die = ticks + nifq->ifq_ttl;
5883 	/*
5884 	 * Is the operation here going to be a no-op ?
5885 	 */
5886 	if (oifq == nifq) {
5887 		if ((tqe->tqe_next == NULL) ||
5888 		    (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
5889 			MUTEX_EXIT(&oifq->ifq_lock);
5890 			return;
5891 		}
5892 	}
5893 
5894 	/*
5895 	 * Remove from the old queue
5896 	 */
5897 	*tqe->tqe_pnext = tqe->tqe_next;
5898 	if (tqe->tqe_next)
5899 		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5900 	else
5901 		oifq->ifq_tail = tqe->tqe_pnext;
5902 	tqe->tqe_next = NULL;
5903 
5904 	/*
5905 	 * If we're moving from one queue to another, release the
5906 	 * lock on the old queue and get a lock on the new queue.
5907 	 * For user defined queues, if we're moving off it, call
5908 	 * delete in case it can now be freed.
5909 	 */
5910 	if (oifq != nifq) {
5911 		tqe->tqe_ifq = NULL;
5912 
5913 		(void) ipf_deletetimeoutqueue(oifq);
5914 
5915 		MUTEX_EXIT(&oifq->ifq_lock);
5916 
5917 		MUTEX_ENTER(&nifq->ifq_lock);
5918 
5919 		tqe->tqe_ifq = nifq;
5920 		nifq->ifq_ref++;
5921 	}
5922 
5923 	/*
5924 	 * Add to the bottom of the new queue
5925 	 */
5926 	tqe->tqe_pnext = nifq->ifq_tail;
5927 	*nifq->ifq_tail = tqe;
5928 	nifq->ifq_tail = &tqe->tqe_next;
5929 	MUTEX_EXIT(&nifq->ifq_lock);
5930 }
5931 
5932 
5933 /* ------------------------------------------------------------------------ */
5934 /* Function:    ipf_updateipid                                              */
5935 /* Returns:     int - 0 == success, -1 == error (packet should be droppped) */
5936 /* Parameters:  fin(I) - pointer to packet information                      */
5937 /*                                                                          */
5938 /* When we are doing NAT, change the IP of every packet to represent a      */
5939 /* single sequence of packets coming from the host, hiding any host         */
5940 /* specific sequencing that might otherwise be revealed.  If the packet is  */
5941 /* a fragment, then store the 'new' IPid in the fragment cache and look up  */
5942 /* the fragment cache for non-leading fragments.  If a non-leading fragment */
5943 /* has no match in the cache, return an error.                              */
5944 /* ------------------------------------------------------------------------ */
5945 static int
5946 ipf_updateipid(fr_info_t *fin)
5947 {
5948 	u_short id, ido, sums;
5949 	u_32_t sumd, sum;
5950 	ip_t *ip;
5951 
5952 	if (fin->fin_off != 0) {
5953 		sum = ipf_frag_ipidknown(fin);
5954 		if (sum == 0xffffffff)
5955 			return -1;
5956 		sum &= 0xffff;
5957 		id = (u_short)sum;
5958 	} else {
5959 		id = ipf_nextipid(fin);
5960 		if (fin->fin_off == 0 && (fin->fin_flx & FI_FRAG) != 0)
5961 			(void) ipf_frag_ipidnew(fin, (u_32_t)id);
5962 	}
5963 
5964 	ip = fin->fin_ip;
5965 	ido = ntohs(ip->ip_id);
5966 	if (id == ido)
5967 		return 0;
5968 	ip->ip_id = htons(id);
5969 	CALC_SUMD(ido, id, sumd);	/* DESTRUCTIVE MACRO! id,ido change */
5970 	sum = (~ntohs(ip->ip_sum)) & 0xffff;
5971 	sum += sumd;
5972 	sum = (sum >> 16) + (sum & 0xffff);
5973 	sum = (sum >> 16) + (sum & 0xffff);
5974 	sums = ~(u_short)sum;
5975 	ip->ip_sum = htons(sums);
5976 	return 0;
5977 }
5978 
5979 
5980 #ifdef	NEED_FRGETIFNAME
5981 /* ------------------------------------------------------------------------ */
5982 /* Function:    ipf_getifname                                               */
5983 /* Returns:     char *    - pointer to interface name                       */
5984 /* Parameters:  ifp(I)    - pointer to network interface                    */
5985 /*              buffer(O) - pointer to where to store interface name        */
5986 /*                                                                          */
5987 /* Constructs an interface name in the buffer passed.  The buffer passed is */
5988 /* expected to be at least LIFNAMSIZ in bytes big.  If buffer is passed in  */
5989 /* as a NULL pointer then return a pointer to a static array.               */
5990 /* ------------------------------------------------------------------------ */
5991 char *
5992 ipf_getifname(ifp, buffer)
5993 	struct ifnet *ifp;
5994 	char *buffer;
5995 {
5996 	static char namebuf[LIFNAMSIZ];
5997 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
5998      defined(__sgi) || defined(linux) || defined(_AIX51) || \
5999      (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
6000 	int unit, space;
6001 	char temp[20];
6002 	char *s;
6003 # endif
6004 
6005 	if (buffer == NULL)
6006 		buffer = namebuf;
6007 	(void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
6008 	buffer[LIFNAMSIZ - 1] = '\0';
6009 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
6010      defined(__sgi) || defined(_AIX51) || \
6011      (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
6012 	for (s = buffer; *s; s++)
6013 		;
6014 	unit = ifp->if_unit;
6015 	space = LIFNAMSIZ - (s - buffer);
6016 	if ((space > 0) && (unit >= 0)) {
6017 		snprintf(temp, sizeof(temp), "%d", unit);
6018 		(void) strncpy(s, temp, space);
6019 		s[space - 1] = '\0';
6020 	}
6021 # endif
6022 	return buffer;
6023 }
6024 #endif
6025 
6026 
6027 /* ------------------------------------------------------------------------ */
6028 /* Function:    ipf_ioctlswitch                                             */
6029 /* Returns:     int     - -1 continue processing, else ioctl return value   */
6030 /* Parameters:  unit(I) - device unit opened                                */
6031 /*              data(I) - pointer to ioctl data                             */
6032 /*              cmd(I)  - ioctl command                                     */
6033 /*              mode(I) - mode value                                        */
6034 /*              uid(I)  - uid making the ioctl call                         */
6035 /*              ctx(I)  - pointer to context data                           */
6036 /*                                                                          */
6037 /* Based on the value of unit, call the appropriate ioctl handler or return */
6038 /* EIO if ipfilter is not running.   Also checks if write perms are req'd   */
6039 /* for the device in order to execute the ioctl.  A special case is made    */
6040 /* SIOCIPFINTERROR so that the same code isn't required in every handler.   */
6041 /* The context data pointer is passed through as this is used as the key    */
6042 /* for locating a matching token for continued access for walking lists,    */
6043 /* etc.                                                                     */
6044 /* ------------------------------------------------------------------------ */
6045 int
6046 ipf_ioctlswitch(ipf_main_softc_t *softc, int unit, void *data, ioctlcmd_t cmd,
6047     int mode, int uid, void *ctx)
6048 {
6049 	int error = 0;
6050 
6051 	switch (cmd)
6052 	{
6053 	case SIOCIPFINTERROR :
6054 		error = BCOPYOUT(&softc->ipf_interror, data,
6055 				 sizeof(softc->ipf_interror));
6056 		if (error != 0) {
6057 			IPFERROR(40);
6058 			error = EFAULT;
6059 		}
6060 		return error;
6061 	default :
6062 		break;
6063 	}
6064 
6065 	switch (unit)
6066 	{
6067 	case IPL_LOGIPF :
6068 		error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
6069 		break;
6070 	case IPL_LOGNAT :
6071 		if (softc->ipf_running > 0) {
6072 			error = ipf_nat_ioctl(softc, data, cmd, mode,
6073 					      uid, ctx);
6074 		} else {
6075 			IPFERROR(42);
6076 			error = EIO;
6077 		}
6078 		break;
6079 	case IPL_LOGSTATE :
6080 		if (softc->ipf_running > 0) {
6081 			error = ipf_state_ioctl(softc, data, cmd, mode,
6082 						uid, ctx);
6083 		} else {
6084 			IPFERROR(43);
6085 			error = EIO;
6086 		}
6087 		break;
6088 	case IPL_LOGAUTH :
6089 		if (softc->ipf_running > 0) {
6090 			error = ipf_auth_ioctl(softc, data, cmd, mode,
6091 					       uid, ctx);
6092 		} else {
6093 			IPFERROR(44);
6094 			error = EIO;
6095 		}
6096 		break;
6097 	case IPL_LOGSYNC :
6098 		if (softc->ipf_running > 0) {
6099 			error = ipf_sync_ioctl(softc, data, cmd, mode,
6100 					       uid, ctx);
6101 		} else {
6102 			error = EIO;
6103 			IPFERROR(45);
6104 		}
6105 		break;
6106 	case IPL_LOGSCAN :
6107 #ifdef IPFILTER_SCAN
6108 		if (softc->ipf_running > 0)
6109 			error = ipf_scan_ioctl(softc, data, cmd, mode,
6110 					       uid, ctx);
6111 		else
6112 #endif
6113 		{
6114 			error = EIO;
6115 			IPFERROR(46);
6116 		}
6117 		break;
6118 	case IPL_LOGLOOKUP :
6119 		if (softc->ipf_running > 0) {
6120 			error = ipf_lookup_ioctl(softc, data, cmd, mode,
6121 						 uid, ctx);
6122 		} else {
6123 			error = EIO;
6124 			IPFERROR(47);
6125 		}
6126 		break;
6127 	default :
6128 		IPFERROR(48);
6129 		error = EIO;
6130 		break;
6131 	}
6132 
6133 	return error;
6134 }
6135 
6136 
6137 /*
6138  * This array defines the expected size of objects coming into the kernel
6139  * for the various recognised object types. The first column is flags (see
6140  * below), 2nd column is current size, 3rd column is the version number of
6141  * when the current size became current.
6142  * Flags:
6143  * 1 = minimum size, not absolute size
6144  */
6145 static	int	ipf_objbytes[IPFOBJ_COUNT][3] = {
6146 	{ 1,	sizeof(struct frentry),		5010000 },	/* 0 */
6147 	{ 1,	sizeof(struct friostat),	5010000 },
6148 	{ 0,	sizeof(struct fr_info),		5010000 },
6149 	{ 0,	sizeof(struct ipf_authstat),	4010100 },
6150 	{ 0,	sizeof(struct ipfrstat),	5010000 },
6151 	{ 1,	sizeof(struct ipnat),		5010000 },	/* 5 */
6152 	{ 0,	sizeof(struct natstat),		5010000 },
6153 	{ 0,	sizeof(struct ipstate_save),	5010000 },
6154 	{ 1,	sizeof(struct nat_save),	5010000 },
6155 	{ 0,	sizeof(struct natlookup),	5010000 },
6156 	{ 1,	sizeof(struct ipstate),		5010000 },	/* 10 */
6157 	{ 0,	sizeof(struct ips_stat),	5010000 },
6158 	{ 0,	sizeof(struct frauth),		5010000 },
6159 	{ 0,	sizeof(struct ipftune),		4010100 },
6160 	{ 0,	sizeof(struct nat),		5010000 },
6161 	{ 0,	sizeof(struct ipfruleiter),	4011400 },	/* 15 */
6162 	{ 0,	sizeof(struct ipfgeniter),	4011400 },
6163 	{ 0,	sizeof(struct ipftable),	4011400 },
6164 	{ 0,	sizeof(struct ipflookupiter),	4011400 },
6165 	{ 0,	sizeof(struct ipftq) * IPF_TCP_NSTATES },
6166 	{ 1,	0,				0	}, /* IPFEXPR */
6167 	{ 0,	0,				0	}, /* PROXYCTL */
6168 	{ 0,	sizeof (struct fripf),		5010000	}
6169 };
6170 
6171 
6172 /* ------------------------------------------------------------------------ */
6173 /* Function:    ipf_inobj                                                   */
6174 /* Returns:     int     - 0 = success, else failure                         */
6175 /* Parameters:  softc(I) - soft context pointerto work with                 */
6176 /*              data(I)  - pointer to ioctl data                            */
6177 /*              objp(O)  - where to store ipfobj structure                  */
6178 /*              ptr(I)   - pointer to data to copy out                      */
6179 /*              type(I)  - type of structure being moved                    */
6180 /*                                                                          */
6181 /* Copy in the contents of what the ipfobj_t points to.  In future, we      */
6182 /* add things to check for version numbers, sizes, etc, to make it backward */
6183 /* compatible at the ABI for user land.                                     */
6184 /* If objp is not NULL then we assume that the caller wants to see what is  */
6185 /* in the ipfobj_t structure being copied in. As an example, this can tell  */
6186 /* the caller what version of ipfilter the ioctl program was written to.    */
6187 /* ------------------------------------------------------------------------ */
6188 int
6189 ipf_inobj(ipf_main_softc_t *softc, void *data, ipfobj_t *objp, void *ptr,
6190     int type)
6191 {
6192 	ipfobj_t obj;
6193 	int error;
6194 	int size;
6195 
6196 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6197 		IPFERROR(49);
6198 		return EINVAL;
6199 	}
6200 
6201 	if (objp == NULL)
6202 		objp = &obj;
6203 	error = BCOPYIN(data, objp, sizeof(*objp));
6204 	if (error != 0) {
6205 		IPFERROR(124);
6206 		return EFAULT;
6207 	}
6208 
6209 	if (objp->ipfo_type != type) {
6210 		IPFERROR(50);
6211 		return EINVAL;
6212 	}
6213 
6214 	if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
6215 		if ((ipf_objbytes[type][0] & 1) != 0) {
6216 			if (objp->ipfo_size < ipf_objbytes[type][1]) {
6217 				IPFERROR(51);
6218 				return EINVAL;
6219 			}
6220 			size =  ipf_objbytes[type][1];
6221 		} else if (objp->ipfo_size == ipf_objbytes[type][1]) {
6222 			size =  objp->ipfo_size;
6223 		} else {
6224 			IPFERROR(52);
6225 			return EINVAL;
6226 		}
6227 		error = COPYIN(objp->ipfo_ptr, ptr, size);
6228 		if (error != 0) {
6229 			IPFERROR(55);
6230 			error = EFAULT;
6231 		}
6232 	} else {
6233 #ifdef  IPFILTER_COMPAT
6234 		error = ipf_in_compat(softc, objp, ptr, 0);
6235 #else
6236 		IPFERROR(54);
6237 		error = EINVAL;
6238 #endif
6239 	}
6240 	return error;
6241 }
6242 
6243 
6244 /* ------------------------------------------------------------------------ */
6245 /* Function:    ipf_inobjsz                                                 */
6246 /* Returns:     int     - 0 = success, else failure                         */
6247 /* Parameters:  softc(I) - soft context pointerto work with                 */
6248 /*              data(I)  - pointer to ioctl data                            */
6249 /*              ptr(I)   - pointer to store real data in                    */
6250 /*              type(I)  - type of structure being moved                    */
6251 /*              sz(I)    - size of data to copy                             */
6252 /*                                                                          */
6253 /* As per ipf_inobj, except the size of the object to copy in is passed in  */
6254 /* but it must not be smaller than the size defined for the type and the    */
6255 /* type must allow for varied sized objects.  The extra requirement here is */
6256 /* that sz must match the size of the object being passed in - this is not  */
6257 /* not possible nor required in ipf_inobj().                                */
6258 /* ------------------------------------------------------------------------ */
6259 int
6260 ipf_inobjsz(ipf_main_softc_t *softc, void *data, void *ptr, int type, int sz)
6261 {
6262 	ipfobj_t obj;
6263 	int error;
6264 
6265 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6266 		IPFERROR(56);
6267 		return EINVAL;
6268 	}
6269 
6270 	error = BCOPYIN(data, &obj, sizeof(obj));
6271 	if (error != 0) {
6272 		IPFERROR(125);
6273 		return EFAULT;
6274 	}
6275 
6276 	if (obj.ipfo_type != type) {
6277 		IPFERROR(58);
6278 		return EINVAL;
6279 	}
6280 
6281 	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6282 		if (((ipf_objbytes[type][0] & 1) == 0) ||
6283 		    (sz < ipf_objbytes[type][1])) {
6284 			IPFERROR(57);
6285 			return EINVAL;
6286 		}
6287 		error = COPYIN(obj.ipfo_ptr, ptr, sz);
6288 		if (error != 0) {
6289 			IPFERROR(61);
6290 			error = EFAULT;
6291 		}
6292 	} else {
6293 #ifdef	IPFILTER_COMPAT
6294 		error = ipf_in_compat(softc, &obj, ptr, sz);
6295 #else
6296 		IPFERROR(60);
6297 		error = EINVAL;
6298 #endif
6299 	}
6300 	return error;
6301 }
6302 
6303 
6304 /* ------------------------------------------------------------------------ */
6305 /* Function:    ipf_outobjsz                                                */
6306 /* Returns:     int     - 0 = success, else failure                         */
6307 /* Parameters:  data(I) - pointer to ioctl data                             */
6308 /*              ptr(I)  - pointer to store real data in                     */
6309 /*              type(I) - type of structure being moved                     */
6310 /*              sz(I)   - size of data to copy                              */
6311 /*                                                                          */
6312 /* As per ipf_outobj, except the size of the object to copy out is passed in*/
6313 /* but it must not be smaller than the size defined for the type and the    */
6314 /* type must allow for varied sized objects.  The extra requirement here is */
6315 /* that sz must match the size of the object being passed in - this is not  */
6316 /* not possible nor required in ipf_outobj().                               */
6317 /* ------------------------------------------------------------------------ */
6318 int
6319 ipf_outobjsz(ipf_main_softc_t *softc, void *data, void *ptr, int type, int sz)
6320 {
6321 	ipfobj_t obj;
6322 	int error;
6323 
6324 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6325 		IPFERROR(62);
6326 		return EINVAL;
6327 	}
6328 
6329 	error = BCOPYIN(data, &obj, sizeof(obj));
6330 	if (error != 0) {
6331 		IPFERROR(127);
6332 		return EFAULT;
6333 	}
6334 
6335 	if (obj.ipfo_type != type) {
6336 		IPFERROR(63);
6337 		return EINVAL;
6338 	}
6339 
6340 	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6341 		if (((ipf_objbytes[type][0] & 1) == 0) ||
6342 		    (sz < ipf_objbytes[type][1])) {
6343 			IPFERROR(146);
6344 			return EINVAL;
6345 		}
6346 		error = COPYOUT(ptr, obj.ipfo_ptr, sz);
6347 		if (error != 0) {
6348 			IPFERROR(66);
6349 			error = EFAULT;
6350 		}
6351 	} else {
6352 #ifdef	IPFILTER_COMPAT
6353 		error = ipf_out_compat(softc, &obj, ptr);
6354 #else
6355 		IPFERROR(65);
6356 		error = EINVAL;
6357 #endif
6358 	}
6359 	return error;
6360 }
6361 
6362 
6363 /* ------------------------------------------------------------------------ */
6364 /* Function:    ipf_outobj                                                  */
6365 /* Returns:     int     - 0 = success, else failure                         */
6366 /* Parameters:  data(I) - pointer to ioctl data                             */
6367 /*              ptr(I)  - pointer to store real data in                     */
6368 /*              type(I) - type of structure being moved                     */
6369 /*                                                                          */
6370 /* Copy out the contents of what ptr is to where ipfobj points to.  In      */
6371 /* future, we add things to check for version numbers, sizes, etc, to make  */
6372 /* it backward  compatible at the ABI for user land.                        */
6373 /* ------------------------------------------------------------------------ */
6374 int
6375 ipf_outobj(ipf_main_softc_t *softc, void *data, void *ptr, int type)
6376 {
6377 	ipfobj_t obj;
6378 	int error;
6379 
6380 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6381 		IPFERROR(67);
6382 		return EINVAL;
6383 	}
6384 
6385 	error = BCOPYIN(data, &obj, sizeof(obj));
6386 	if (error != 0) {
6387 		IPFERROR(126);
6388 		return EFAULT;
6389 	}
6390 
6391 	if (obj.ipfo_type != type) {
6392 		IPFERROR(68);
6393 		return EINVAL;
6394 	}
6395 
6396 	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6397 		if ((ipf_objbytes[type][0] & 1) != 0) {
6398 			if (obj.ipfo_size < ipf_objbytes[type][1]) {
6399 				IPFERROR(69);
6400 				return EINVAL;
6401 			}
6402 		} else if (obj.ipfo_size != ipf_objbytes[type][1]) {
6403 			IPFERROR(70);
6404 			return EINVAL;
6405 		}
6406 
6407 		error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
6408 		if (error != 0) {
6409 			IPFERROR(73);
6410 			error = EFAULT;
6411 		}
6412 	} else {
6413 #ifdef	IPFILTER_COMPAT
6414 		error = ipf_out_compat(softc, &obj, ptr);
6415 #else
6416 		IPFERROR(72);
6417 		error = EINVAL;
6418 #endif
6419 	}
6420 	return error;
6421 }
6422 
6423 
6424 /* ------------------------------------------------------------------------ */
6425 /* Function:    ipf_outobjk                                                 */
6426 /* Returns:     int     - 0 = success, else failure                         */
6427 /* Parameters:  obj(I)  - pointer to data description structure             */
6428 /*              ptr(I)  - pointer to kernel data to copy out                */
6429 /*                                                                          */
6430 /* In the above functions, the ipfobj_t structure is copied into the kernel,*/
6431 /* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
6432 /* already populated with information and now we just need to use it.       */
6433 /* There is no need for this function to have a "type" parameter as there   */
6434 /* is no point in validating information that comes from the kernel with    */
6435 /* itself.                                                                  */
6436 /* ------------------------------------------------------------------------ */
6437 int
6438 ipf_outobjk(ipf_main_softc_t *softc, ipfobj_t *obj, void *ptr)
6439 {
6440 	int type = obj->ipfo_type;
6441 	int error;
6442 
6443 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6444 		IPFERROR(147);
6445 		return EINVAL;
6446 	}
6447 
6448 	if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
6449 		if ((ipf_objbytes[type][0] & 1) != 0) {
6450 			if (obj->ipfo_size < ipf_objbytes[type][1]) {
6451 				IPFERROR(148);
6452 				return EINVAL;
6453 			}
6454 
6455 		} else if (obj->ipfo_size != ipf_objbytes[type][1]) {
6456 			IPFERROR(149);
6457 			return EINVAL;
6458 		}
6459 
6460 		error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
6461 		if (error != 0) {
6462 			IPFERROR(150);
6463 			error = EFAULT;
6464 		}
6465 	} else {
6466 #ifdef  IPFILTER_COMPAT
6467 		error = ipf_out_compat(softc, obj, ptr);
6468 #else
6469 		IPFERROR(151);
6470 		error = EINVAL;
6471 #endif
6472 	}
6473 	return error;
6474 }
6475 
6476 
6477 /* ------------------------------------------------------------------------ */
6478 /* Function:    ipf_checkl4sum                                              */
6479 /* Returns:     int     - 0 = good, -1 = bad, 1 = cannot check              */
6480 /* Parameters:  fin(I) - pointer to packet information                      */
6481 /*                                                                          */
6482 /* If possible, calculate the layer 4 checksum for the packet.  If this is  */
6483 /* not possible, return without indicating a failure or success but in a    */
6484 /* way that is ditinguishable. This function should only be called by the   */
6485 /* ipf_checkv6sum() for each platform.                                      */
6486 /* ------------------------------------------------------------------------ */
6487 int
6488 ipf_checkl4sum(fr_info_t *fin)
6489 {
6490 	u_short sum, hdrsum, *csump;
6491 	udphdr_t *udp;
6492 	int dosum;
6493 
6494 	/*
6495 	 * If the TCP packet isn't a fragment, isn't too short and otherwise
6496 	 * isn't already considered "bad", then validate the checksum.  If
6497 	 * this check fails then considered the packet to be "bad".
6498 	 */
6499 	if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
6500 		return 1;
6501 
6502 	csump = NULL;
6503 	hdrsum = 0;
6504 	dosum = 0;
6505 	sum = 0;
6506 
6507 	switch (fin->fin_p)
6508 	{
6509 	case IPPROTO_TCP :
6510 		csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
6511 		dosum = 1;
6512 		break;
6513 
6514 	case IPPROTO_UDP :
6515 		udp = fin->fin_dp;
6516 		if (udp->uh_sum != 0) {
6517 			csump = &udp->uh_sum;
6518 			dosum = 1;
6519 		}
6520 		break;
6521 
6522 #ifdef USE_INET6
6523 	case IPPROTO_ICMPV6 :
6524 		csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
6525 		dosum = 1;
6526 		break;
6527 #endif
6528 
6529 	case IPPROTO_ICMP :
6530 		csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
6531 		dosum = 1;
6532 		break;
6533 
6534 	default :
6535 		return 1;
6536 		/*NOTREACHED*/
6537 	}
6538 
6539 	if (csump != NULL)
6540 		hdrsum = *csump;
6541 
6542 	if (dosum) {
6543 		sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
6544 	}
6545 #if !defined(_KERNEL)
6546 	if (sum == hdrsum) {
6547 		FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
6548 	} else {
6549 		FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
6550 	}
6551 #endif
6552 	DT2(l4sums, u_short, hdrsum, u_short, sum);
6553 	if (hdrsum == sum) {
6554 		fin->fin_cksum = FI_CK_SUMOK;
6555 		return 0;
6556 	}
6557 	fin->fin_cksum = FI_CK_BAD;
6558 	return -1;
6559 }
6560 
6561 
6562 /* ------------------------------------------------------------------------ */
6563 /* Function:    ipf_ifpfillv4addr                                           */
6564 /* Returns:     int     - 0 = address update, -1 = address not updated      */
6565 /* Parameters:  atype(I)   - type of network address update to perform      */
6566 /*              sin(I)     - pointer to source of address information       */
6567 /*              mask(I)    - pointer to source of netmask information       */
6568 /*              inp(I)     - pointer to destination address store           */
6569 /*              inpmask(I) - pointer to destination netmask store           */
6570 /*                                                                          */
6571 /* Given a type of network address update (atype) to perform, copy          */
6572 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6573 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6574 /* which case the operation fails.  For all values of atype other than      */
6575 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6576 /* value.                                                                   */
6577 /* ------------------------------------------------------------------------ */
6578 int
6579 ipf_ifpfillv4addr(int atype, struct sockaddr_in *sin, struct sockaddr_in *mask,
6580     struct in_addr *inp, struct in_addr *inpmask)
6581 {
6582 	if (inpmask != NULL && atype != FRI_NETMASKED)
6583 		inpmask->s_addr = 0xffffffff;
6584 
6585 	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6586 		if (atype == FRI_NETMASKED) {
6587 			if (inpmask == NULL)
6588 				return -1;
6589 			inpmask->s_addr = mask->sin_addr.s_addr;
6590 		}
6591 		inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
6592 	} else {
6593 		inp->s_addr = sin->sin_addr.s_addr;
6594 	}
6595 	return 0;
6596 }
6597 
6598 
6599 #ifdef	USE_INET6
6600 /* ------------------------------------------------------------------------ */
6601 /* Function:    ipf_ifpfillv6addr                                           */
6602 /* Returns:     int     - 0 = address update, -1 = address not updated      */
6603 /* Parameters:  atype(I)   - type of network address update to perform      */
6604 /*              sin(I)     - pointer to source of address information       */
6605 /*              mask(I)    - pointer to source of netmask information       */
6606 /*              inp(I)     - pointer to destination address store           */
6607 /*              inpmask(I) - pointer to destination netmask store           */
6608 /*                                                                          */
6609 /* Given a type of network address update (atype) to perform, copy          */
6610 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6611 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6612 /* which case the operation fails.  For all values of atype other than      */
6613 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6614 /* value.                                                                   */
6615 /* ------------------------------------------------------------------------ */
6616 int
6617 ipf_ifpfillv6addr(int atype, struct sockaddr_in6 *sin,
6618     struct sockaddr_in6 *mask, i6addr_t *inp, i6addr_t *inpmask)
6619 {
6620 	i6addr_t *src, *and;
6621 
6622 	src = (i6addr_t *)&sin->sin6_addr;
6623 	and = (i6addr_t *)&mask->sin6_addr;
6624 
6625 	if (inpmask != NULL && atype != FRI_NETMASKED) {
6626 		inpmask->i6[0] = 0xffffffff;
6627 		inpmask->i6[1] = 0xffffffff;
6628 		inpmask->i6[2] = 0xffffffff;
6629 		inpmask->i6[3] = 0xffffffff;
6630 	}
6631 
6632 	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6633 		if (atype == FRI_NETMASKED) {
6634 			if (inpmask == NULL)
6635 				return -1;
6636 			inpmask->i6[0] = and->i6[0];
6637 			inpmask->i6[1] = and->i6[1];
6638 			inpmask->i6[2] = and->i6[2];
6639 			inpmask->i6[3] = and->i6[3];
6640 		}
6641 
6642 		inp->i6[0] = src->i6[0] & and->i6[0];
6643 		inp->i6[1] = src->i6[1] & and->i6[1];
6644 		inp->i6[2] = src->i6[2] & and->i6[2];
6645 		inp->i6[3] = src->i6[3] & and->i6[3];
6646 	} else {
6647 		inp->i6[0] = src->i6[0];
6648 		inp->i6[1] = src->i6[1];
6649 		inp->i6[2] = src->i6[2];
6650 		inp->i6[3] = src->i6[3];
6651 	}
6652 	return 0;
6653 }
6654 #endif
6655 
6656 
6657 /* ------------------------------------------------------------------------ */
6658 /* Function:    ipf_matchtag                                                */
6659 /* Returns:     0 == mismatch, 1 == match.                                  */
6660 /* Parameters:  tag1(I) - pointer to first tag to compare                   */
6661 /*              tag2(I) - pointer to second tag to compare                  */
6662 /*                                                                          */
6663 /* Returns true (non-zero) or false(0) if the two tag structures can be     */
6664 /* considered to be a match or not match, respectively.  The tag is 16      */
6665 /* bytes long (16 characters) but that is overlayed with 4 32bit ints so    */
6666 /* compare the ints instead, for speed. tag1 is the master of the           */
6667 /* comparison.  This function should only be called with both tag1 and tag2 */
6668 /* as non-NULL pointers.                                                    */
6669 /* ------------------------------------------------------------------------ */
6670 int
6671 ipf_matchtag(ipftag_t *tag1, ipftag_t *tag2)
6672 {
6673 	if (tag1 == tag2)
6674 		return 1;
6675 
6676 	if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
6677 		return 1;
6678 
6679 	if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
6680 	    (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
6681 	    (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
6682 	    (tag1->ipt_num[3] == tag2->ipt_num[3]))
6683 		return 1;
6684 	return 0;
6685 }
6686 
6687 
6688 /* ------------------------------------------------------------------------ */
6689 /* Function:    ipf_coalesce                                                */
6690 /* Returns:     1 == success, -1 == failure, 0 == no change                 */
6691 /* Parameters:  fin(I) - pointer to packet information                      */
6692 /*                                                                          */
6693 /* Attempt to get all of the packet data into a single, contiguous buffer.  */
6694 /* If this call returns a failure then the buffers have also been freed.    */
6695 /* ------------------------------------------------------------------------ */
6696 int
6697 ipf_coalesce(fr_info_t *fin)
6698 {
6699 
6700 	if ((fin->fin_flx & FI_COALESCE) != 0)
6701 		return 1;
6702 
6703 	/*
6704 	 * If the mbuf pointers indicate that there is no mbuf to work with,
6705 	 * return but do not indicate success or failure.
6706 	 */
6707 	if (fin->fin_m == NULL || fin->fin_mp == NULL)
6708 		return 0;
6709 
6710 #if defined(_KERNEL)
6711 	if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
6712 		ipf_main_softc_t *softc = fin->fin_main_soft;
6713 
6714 		DT1(frb_coalesce, fr_info_t *, fin);
6715 		LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
6716 # ifdef MENTAT
6717 		FREE_MB_T(*fin->fin_mp);
6718 # endif
6719 		fin->fin_reason = FRB_COALESCE;
6720 		*fin->fin_mp = NULL;
6721 		fin->fin_m = NULL;
6722 		return -1;
6723 	}
6724 #else
6725 	fin = fin;	/* LINT */
6726 #endif
6727 	return 1;
6728 }
6729 
6730 
6731 /*
6732  * The following table lists all of the tunable variables that can be
6733  * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt.  The format of each row
6734  * in the table below is as follows:
6735  *
6736  * pointer to value, name of value, minimum, maximum, size of the value's
6737  *     container, value attribute flags
6738  *
6739  * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
6740  * means the value can only be written to when IPFilter is loaded but disabled.
6741  * The obvious implication is if neither of these are set then the value can be
6742  * changed at any time without harm.
6743  */
6744 
6745 
6746 /* ------------------------------------------------------------------------ */
6747 /* Function:    ipf_tune_findbycookie                                       */
6748 /* Returns:     NULL = search failed, else pointer to tune struct           */
6749 /* Parameters:  cookie(I) - cookie value to search for amongst tuneables    */
6750 /*              next(O)   - pointer to place to store the cookie for the    */
6751 /*                          "next" tuneable, if it is desired.              */
6752 /*                                                                          */
6753 /* This function is used to walk through all of the existing tunables with  */
6754 /* successive calls.  It searches the known tunables for the one which has  */
6755 /* a matching value for "cookie" - ie its address.  When returning a match, */
6756 /* the next one to be found may be returned inside next.                    */
6757 /* ------------------------------------------------------------------------ */
6758 static ipftuneable_t *
6759 ipf_tune_findbycookie(ipftuneable_t **ptop, void *cookie, void **next)
6760 {
6761 	ipftuneable_t *ta, **tap;
6762 
6763 	for (ta = *ptop; ta->ipft_name != NULL; ta++)
6764 		if (ta == cookie) {
6765 			if (next != NULL) {
6766 				/*
6767 				 * If the next entry in the array has a name
6768 				 * present, then return a pointer to it for
6769 				 * where to go next, else return a pointer to
6770 				 * the dynaminc list as a key to search there
6771 				 * next.  This facilitates a weak linking of
6772 				 * the two "lists" together.
6773 				 */
6774 				if ((ta + 1)->ipft_name != NULL)
6775 					*next = ta + 1;
6776 				else
6777 					*next = ptop;
6778 			}
6779 			return ta;
6780 		}
6781 
6782 	for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
6783 		if (tap == cookie) {
6784 			if (next != NULL)
6785 				*next = &ta->ipft_next;
6786 			return ta;
6787 		}
6788 
6789 	if (next != NULL)
6790 		*next = NULL;
6791 	return NULL;
6792 }
6793 
6794 
6795 /* ------------------------------------------------------------------------ */
6796 /* Function:    ipf_tune_findbyname                                         */
6797 /* Returns:     NULL = search failed, else pointer to tune struct           */
6798 /* Parameters:  name(I) - name of the tuneable entry to find.               */
6799 /*                                                                          */
6800 /* Search the static array of tuneables and the list of dynamic tuneables   */
6801 /* for an entry with a matching name.  If we can find one, return a pointer */
6802 /* to the matching structure.                                               */
6803 /* ------------------------------------------------------------------------ */
6804 static ipftuneable_t *
6805 ipf_tune_findbyname(ipftuneable_t *top, const char *name)
6806 {
6807 	ipftuneable_t *ta;
6808 
6809 	for (ta = top; ta != NULL; ta = ta->ipft_next)
6810 		if (!strcmp(ta->ipft_name, name)) {
6811 			return ta;
6812 		}
6813 
6814 	return NULL;
6815 }
6816 
6817 
6818 /* ------------------------------------------------------------------------ */
6819 /* Function:    ipf_tune_add_array                                          */
6820 /* Returns:     int - 0 == success, else failure                            */
6821 /* Parameters:  newtune - pointer to new tune array to add to tuneables     */
6822 /*                                                                          */
6823 /* Appends tune structures from the array passed in (newtune) to the end of */
6824 /* the current list of "dynamic" tuneable parameters.                       */
6825 /* If any entry to be added is already present (by name) then the operation */
6826 /* is aborted - entries that have been added are removed before returning.  */
6827 /* An entry with no name (NULL) is used as the indication that the end of   */
6828 /* the array has been reached.                                              */
6829 /* ------------------------------------------------------------------------ */
6830 int
6831 ipf_tune_add_array(ipf_main_softc_t *softc, ipftuneable_t *newtune)
6832 {
6833 	ipftuneable_t *nt, *dt;
6834 	int error = 0;
6835 
6836 	for (nt = newtune; nt->ipft_name != NULL; nt++) {
6837 		error = ipf_tune_add(softc, nt);
6838 		if (error != 0) {
6839 			for (dt = newtune; dt != nt; dt++) {
6840 				(void) ipf_tune_del(softc, dt);
6841 			}
6842 		}
6843 	}
6844 
6845 	return error;
6846 }
6847 
6848 
6849 /* ------------------------------------------------------------------------ */
6850 /* Function:    ipf_tune_array_link                                         */
6851 /* Returns:     0 == success, -1 == failure                                 */
6852 /* Parameters:  softc(I) - soft context pointerto work with                 */
6853 /*              array(I) - pointer to an array of tuneables                 */
6854 /*                                                                          */
6855 /* Given an array of tunables (array), append them to the current list of   */
6856 /* tuneables for this context (softc->ipf_tuners.) To properly prepare the  */
6857 /* the array for being appended to the list, initialise all of the next     */
6858 /* pointers so we don't need to walk parts of it with ++ and others with    */
6859 /* next. The array is expected to have an entry with a NULL name as the     */
6860 /* terminator. Trying to add an array with no non-NULL names will return as */
6861 /* a failure.                                                               */
6862 /* ------------------------------------------------------------------------ */
6863 int
6864 ipf_tune_array_link(ipf_main_softc_t *softc, ipftuneable_t *array)
6865 {
6866 	ipftuneable_t *t, **p;
6867 
6868 	t = array;
6869 	if (t->ipft_name == NULL)
6870 		return -1;
6871 
6872 	for (; t[1].ipft_name != NULL; t++)
6873 		t[0].ipft_next = &t[1];
6874 	t->ipft_next = NULL;
6875 
6876 	/*
6877 	 * Since a pointer to the last entry isn't kept, we need to find it
6878 	 * each time we want to add new variables to the list.
6879 	 */
6880 	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
6881 		if (t->ipft_name == NULL)
6882 			break;
6883 	*p = array;
6884 
6885 	return 0;
6886 }
6887 
6888 
6889 /* ------------------------------------------------------------------------ */
6890 /* Function:    ipf_tune_array_unlink                                       */
6891 /* Returns:     0 == success, -1 == failure                                 */
6892 /* Parameters:  softc(I) - soft context pointerto work with                 */
6893 /*              array(I) - pointer to an array of tuneables                 */
6894 /*                                                                          */
6895 /* ------------------------------------------------------------------------ */
6896 int
6897 ipf_tune_array_unlink(ipf_main_softc_t *softc, ipftuneable_t *array)
6898 {
6899 	ipftuneable_t *t, **p;
6900 
6901 	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
6902 		if (t == array)
6903 			break;
6904 	if (t == NULL)
6905 		return -1;
6906 
6907 	for (; t[1].ipft_name != NULL; t++)
6908 		;
6909 
6910 	*p = t->ipft_next;
6911 
6912 	return 0;
6913 }
6914 
6915 
6916 /* ------------------------------------------------------------------------ */
6917 /* Function:   ipf_tune_array_copy                                          */
6918 /* Returns:    NULL = failure, else pointer to new array                    */
6919 /* Parameters: base(I)     - pointer to structure base                      */
6920 /*             size(I)     - size of the array at template                  */
6921 /*             template(I) - original array to copy                         */
6922 /*                                                                          */
6923 /* Allocate memory for a new set of tuneable values and copy everything     */
6924 /* from template into the new region of memory.  The new region is full of  */
6925 /* uninitialised pointers (ipft_next) so set them up.  Now, ipftp_offset... */
6926 /*                                                                          */
6927 /* NOTE: the following assumes that sizeof(long) == sizeof(void *)          */
6928 /* In the array template, ipftp_offset is the offset (in bytes) of the      */
6929 /* location of the tuneable value inside the structure pointed to by base.  */
6930 /* As ipftp_offset is a union over the pointers to the tuneable values, if  */
6931 /* we add base to the copy's ipftp_offset, copy ends up with a pointer in   */
6932 /* ipftp_void that points to the stored value.                              */
6933 /* ------------------------------------------------------------------------ */
6934 ipftuneable_t *
6935 ipf_tune_array_copy(void *base, size_t size, const ipftuneable_t *template)
6936 {
6937 	ipftuneable_t *copy;
6938 	int i;
6939 
6940 
6941 	KMALLOCS(copy, ipftuneable_t *, size);
6942 	if (copy == NULL) {
6943 		return NULL;
6944 	}
6945 	bcopy(template, copy, size);
6946 
6947 	for (i = 0; copy[i].ipft_name; i++) {
6948 		copy[i].ipft_una.ipftp_offset += (u_long)base;
6949 		copy[i].ipft_next = copy + i + 1;
6950 	}
6951 
6952 	return copy;
6953 }
6954 
6955 
6956 /* ------------------------------------------------------------------------ */
6957 /* Function:    ipf_tune_add                                                */
6958 /* Returns:     int - 0 == success, else failure                            */
6959 /* Parameters:  newtune - pointer to new tune entry to add to tuneables     */
6960 /*                                                                          */
6961 /* Appends tune structures from the array passed in (newtune) to the end of */
6962 /* the current list of "dynamic" tuneable parameters.  Once added, the      */
6963 /* owner of the object is not expected to ever change "ipft_next".          */
6964 /* ------------------------------------------------------------------------ */
6965 int
6966 ipf_tune_add(ipf_main_softc_t *softc, ipftuneable_t *newtune)
6967 {
6968 	ipftuneable_t *ta, **tap;
6969 
6970 	ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
6971 	if (ta != NULL) {
6972 		IPFERROR(74);
6973 		return EEXIST;
6974 	}
6975 
6976 	for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
6977 		;
6978 
6979 	newtune->ipft_next = NULL;
6980 	*tap = newtune;
6981 	return 0;
6982 }
6983 
6984 
6985 /* ------------------------------------------------------------------------ */
6986 /* Function:    ipf_tune_del                                                */
6987 /* Returns:     int - 0 == success, else failure                            */
6988 /* Parameters:  oldtune - pointer to tune entry to remove from the list of  */
6989 /*                        current dynamic tuneables                         */
6990 /*                                                                          */
6991 /* Search for the tune structure, by pointer, in the list of those that are */
6992 /* dynamically added at run time.  If found, adjust the list so that this   */
6993 /* structure is no longer part of it.                                       */
6994 /* ------------------------------------------------------------------------ */
6995 int
6996 ipf_tune_del(ipf_main_softc_t *softc, ipftuneable_t *oldtune)
6997 {
6998 	ipftuneable_t *ta, **tap;
6999 	int error = 0;
7000 
7001 	for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
7002 	     tap = &ta->ipft_next) {
7003 		if (ta == oldtune) {
7004 			*tap = oldtune->ipft_next;
7005 			oldtune->ipft_next = NULL;
7006 			break;
7007 		}
7008 	}
7009 
7010 	if (ta == NULL) {
7011 		error = ESRCH;
7012 		IPFERROR(75);
7013 	}
7014 	return error;
7015 }
7016 
7017 
7018 /* ------------------------------------------------------------------------ */
7019 /* Function:    ipf_tune_del_array                                          */
7020 /* Returns:     int - 0 == success, else failure                            */
7021 /* Parameters:  oldtune - pointer to tuneables array                        */
7022 /*                                                                          */
7023 /* Remove each tuneable entry in the array from the list of "dynamic"       */
7024 /* tunables.  If one entry should fail to be found, an error will be        */
7025 /* returned and no further ones removed.                                    */
7026 /* An entry with a NULL name is used as the indicator of the last entry in  */
7027 /* the array.                                                               */
7028 /* ------------------------------------------------------------------------ */
7029 int
7030 ipf_tune_del_array(ipf_main_softc_t *softc, ipftuneable_t *oldtune)
7031 {
7032 	ipftuneable_t *ot;
7033 	int error = 0;
7034 
7035 	for (ot = oldtune; ot->ipft_name != NULL; ot++) {
7036 		error = ipf_tune_del(softc, ot);
7037 		if (error != 0)
7038 			break;
7039 	}
7040 
7041 	return error;
7042 
7043 }
7044 
7045 
7046 /* ------------------------------------------------------------------------ */
7047 /* Function:    ipf_tune                                                    */
7048 /* Returns:     int - 0 == success, else failure                            */
7049 /* Parameters:  cmd(I)  - ioctl command number                              */
7050 /*              data(I) - pointer to ioctl data structure                   */
7051 /*                                                                          */
7052 /* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET.  These  */
7053 /* three ioctls provide the means to access and control global variables    */
7054 /* within IPFilter, allowing (for example) timeouts and table sizes to be   */
7055 /* changed without rebooting, reloading or recompiling.  The initialisation */
7056 /* and 'destruction' routines of the various components of ipfilter are all */
7057 /* each responsible for handling their own values being too big.            */
7058 /* ------------------------------------------------------------------------ */
7059 int
7060 ipf_ipftune(ipf_main_softc_t *softc, ioctlcmd_t cmd, void *data)
7061 {
7062 	ipftuneable_t *ta;
7063 	ipftune_t tu;
7064 	void *cookie;
7065 	int error;
7066 
7067 	error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
7068 	if (error != 0)
7069 		return error;
7070 
7071 	tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
7072 	cookie = tu.ipft_cookie;
7073 	ta = NULL;
7074 
7075 	switch (cmd)
7076 	{
7077 	case SIOCIPFGETNEXT :
7078 		/*
7079 		 * If cookie is non-NULL, assume it to be a pointer to the last
7080 		 * entry we looked at, so find it (if possible) and return a
7081 		 * pointer to the next one after it.  The last entry in the
7082 		 * the table is a NULL entry, so when we get to it, set cookie
7083 		 * to NULL and return that, indicating end of list, erstwhile
7084 		 * if we come in with cookie set to NULL, we are starting anew
7085 		 * at the front of the list.
7086 		 */
7087 		if (cookie != NULL) {
7088 			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7089 						   cookie, &tu.ipft_cookie);
7090 		} else {
7091 			ta = softc->ipf_tuners;
7092 			tu.ipft_cookie = ta + 1;
7093 		}
7094 		if (ta != NULL) {
7095 			/*
7096 			 * Entry found, but does the data pointed to by that
7097 			 * row fit in what we can return?
7098 			 */
7099 			if (ta->ipft_sz > sizeof(tu.ipft_un)) {
7100 				IPFERROR(76);
7101 				return EINVAL;
7102 			}
7103 
7104 			tu.ipft_vlong = 0;
7105 			if (ta->ipft_sz == sizeof(u_long))
7106 				tu.ipft_vlong = *ta->ipft_plong;
7107 			else if (ta->ipft_sz == sizeof(u_int))
7108 				tu.ipft_vint = *ta->ipft_pint;
7109 			else if (ta->ipft_sz == sizeof(u_short))
7110 				tu.ipft_vshort = *ta->ipft_pshort;
7111 			else if (ta->ipft_sz == sizeof(u_char))
7112 				tu.ipft_vchar = *ta->ipft_pchar;
7113 
7114 			tu.ipft_sz = ta->ipft_sz;
7115 			tu.ipft_min = ta->ipft_min;
7116 			tu.ipft_max = ta->ipft_max;
7117 			tu.ipft_flags = ta->ipft_flags;
7118 			bcopy(ta->ipft_name, tu.ipft_name,
7119 			      MIN(sizeof(tu.ipft_name),
7120 				  strlen(ta->ipft_name) + 1));
7121 		}
7122 		error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7123 		break;
7124 
7125 	case SIOCIPFGET :
7126 	case SIOCIPFSET :
7127 		/*
7128 		 * Search by name or by cookie value for a particular entry
7129 		 * in the tuning paramter table.
7130 		 */
7131 		IPFERROR(77);
7132 		error = ESRCH;
7133 		if (cookie != NULL) {
7134 			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7135 						   cookie, NULL);
7136 			if (ta != NULL)
7137 				error = 0;
7138 		} else if (tu.ipft_name[0] != '\0') {
7139 			ta = ipf_tune_findbyname(softc->ipf_tuners,
7140 						 tu.ipft_name);
7141 			if (ta != NULL)
7142 				error = 0;
7143 		}
7144 		if (error != 0)
7145 			break;
7146 
7147 		if (cmd == (ioctlcmd_t)SIOCIPFGET) {
7148 			/*
7149 			 * Fetch the tuning parameters for a particular value
7150 			 */
7151 			tu.ipft_vlong = 0;
7152 			if (ta->ipft_sz == sizeof(u_long))
7153 				tu.ipft_vlong = *ta->ipft_plong;
7154 			else if (ta->ipft_sz == sizeof(u_int))
7155 				tu.ipft_vint = *ta->ipft_pint;
7156 			else if (ta->ipft_sz == sizeof(u_short))
7157 				tu.ipft_vshort = *ta->ipft_pshort;
7158 			else if (ta->ipft_sz == sizeof(u_char))
7159 				tu.ipft_vchar = *ta->ipft_pchar;
7160 			tu.ipft_cookie = ta;
7161 			tu.ipft_sz = ta->ipft_sz;
7162 			tu.ipft_min = ta->ipft_min;
7163 			tu.ipft_max = ta->ipft_max;
7164 			tu.ipft_flags = ta->ipft_flags;
7165 			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7166 
7167 		} else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
7168 			/*
7169 			 * Set an internal parameter.  The hard part here is
7170 			 * getting the new value safely and correctly out of
7171 			 * the kernel (given we only know its size, not type.)
7172 			 */
7173 			u_long in;
7174 
7175 			if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
7176 			    (softc->ipf_running > 0)) {
7177 				IPFERROR(78);
7178 				error = EBUSY;
7179 				break;
7180 			}
7181 
7182 			in = tu.ipft_vlong;
7183 			if (in < ta->ipft_min || in > ta->ipft_max) {
7184 				IPFERROR(79);
7185 				error = EINVAL;
7186 				break;
7187 			}
7188 
7189 			if (ta->ipft_func != NULL) {
7190 				SPL_INT(s);
7191 
7192 				SPL_NET(s);
7193 				error = (*ta->ipft_func)(softc, ta,
7194 							 &tu.ipft_un);
7195 				SPL_X(s);
7196 
7197 			} else if (ta->ipft_sz == sizeof(u_long)) {
7198 				tu.ipft_vlong = *ta->ipft_plong;
7199 				*ta->ipft_plong = in;
7200 
7201 			} else if (ta->ipft_sz == sizeof(u_int)) {
7202 				tu.ipft_vint = *ta->ipft_pint;
7203 				*ta->ipft_pint = (u_int)(in & 0xffffffff);
7204 
7205 			} else if (ta->ipft_sz == sizeof(u_short)) {
7206 				tu.ipft_vshort = *ta->ipft_pshort;
7207 				*ta->ipft_pshort = (u_short)(in & 0xffff);
7208 
7209 			} else if (ta->ipft_sz == sizeof(u_char)) {
7210 				tu.ipft_vchar = *ta->ipft_pchar;
7211 				*ta->ipft_pchar = (u_char)(in & 0xff);
7212 			}
7213 			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7214 		}
7215 		break;
7216 
7217 	default :
7218 		IPFERROR(80);
7219 		error = EINVAL;
7220 		break;
7221 	}
7222 
7223 	return error;
7224 }
7225 
7226 
7227 /* ------------------------------------------------------------------------ */
7228 /* Function:    ipf_zerostats                                               */
7229 /* Returns:     int - 0 = success, else failure                             */
7230 /* Parameters:  data(O) - pointer to pointer for copying data back to       */
7231 /*                                                                          */
7232 /* Copies the current statistics out to userspace and then zero's the       */
7233 /* current ones in the kernel. The lock is only held across the bzero() as  */
7234 /* the copyout may result in paging (ie network activity.)                  */
7235 /* ------------------------------------------------------------------------ */
7236 int
7237 ipf_zerostats(ipf_main_softc_t *softc, void *data)
7238 {
7239 	friostat_t fio;
7240 	ipfobj_t obj;
7241 	int error;
7242 
7243 	error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
7244 	if (error != 0)
7245 		return error;
7246 	ipf_getstat(softc, &fio, obj.ipfo_rev);
7247 	error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
7248 	if (error != 0)
7249 		return error;
7250 
7251 	WRITE_ENTER(&softc->ipf_mutex);
7252 	bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
7253 	RWLOCK_EXIT(&softc->ipf_mutex);
7254 
7255 	return 0;
7256 }
7257 
7258 
7259 /* ------------------------------------------------------------------------ */
7260 /* Function:    ipf_resolvedest                                             */
7261 /* Returns:     Nil                                                         */
7262 /* Parameters:  softc(I) - pointer to soft context main structure           */
7263 /*              base(I)  - where strings are stored                         */
7264 /*              fdp(IO)  - pointer to destination information to resolve    */
7265 /*              v(I)     - IP protocol version to match                     */
7266 /*                                                                          */
7267 /* Looks up an interface name in the frdest structure pointed to by fdp and */
7268 /* if a matching name can be found for the particular IP protocol version   */
7269 /* then store the interface pointer in the frdest struct.  If no match is   */
7270 /* found, then set the interface pointer to be -1 as NULL is considered to  */
7271 /* indicate there is no information at all in the structure.                */
7272 /* ------------------------------------------------------------------------ */
7273 int
7274 ipf_resolvedest(ipf_main_softc_t *softc, char *base, frdest_t *fdp, int v)
7275 {
7276 	int errval = 0;
7277 	void *ifp;
7278 
7279 	ifp = NULL;
7280 
7281 	if (fdp->fd_name != -1) {
7282 		if (fdp->fd_type == FRD_DSTLIST) {
7283 			ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
7284 						  IPLT_DSTLIST,
7285 						  base + fdp->fd_name,
7286 						  NULL);
7287 			if (ifp == NULL) {
7288 				IPFERROR(144);
7289 				errval = ESRCH;
7290 			}
7291 		} else {
7292 			ifp = GETIFP(base + fdp->fd_name, v);
7293 		}
7294 	}
7295 	fdp->fd_ptr = ifp;
7296 
7297 	return errval;
7298 }
7299 
7300 
7301 /* ------------------------------------------------------------------------ */
7302 /* Function:    ipf_resolvenic                                              */
7303 /* Returns:     void* - NULL = wildcard name, -1 = failed to find NIC, else */
7304 /*                      pointer to interface structure for NIC              */
7305 /* Parameters:  softc(I)- pointer to soft context main structure            */
7306 /*              name(I) - complete interface name                           */
7307 /*              v(I)    - IP protocol version                               */
7308 /*                                                                          */
7309 /* Look for a network interface structure that firstly has a matching name  */
7310 /* to that passed in and that is also being used for that IP protocol       */
7311 /* version (necessary on some platforms where there are separate listings   */
7312 /* for both IPv4 and IPv6 on the same physical NIC.                         */
7313 /*                                                                          */
7314 /* ------------------------------------------------------------------------ */
7315 void *
7316 ipf_resolvenic(ipf_main_softc_t *softc, char *name, int v)
7317 {
7318 	void *nic;
7319 
7320 	softc = softc;	/* gcc -Wextra */
7321 	if (name[0] == '\0')
7322 		return NULL;
7323 
7324 	if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
7325 		return NULL;
7326 	}
7327 
7328 	nic = GETIFP(name, v);
7329 	if (nic == NULL)
7330 		nic = (void *)-1;
7331 	return nic;
7332 }
7333 
7334 
7335 /* ------------------------------------------------------------------------ */
7336 /* Function:    ipf_token_expire                                            */
7337 /* Returns:     None.                                                       */
7338 /* Parameters:  softc(I) - pointer to soft context main structure           */
7339 /*                                                                          */
7340 /* This function is run every ipf tick to see if there are any tokens that  */
7341 /* have been held for too long and need to be freed up.                     */
7342 /* ------------------------------------------------------------------------ */
7343 void
7344 ipf_token_expire(ipf_main_softc_t *softc)
7345 {
7346 	ipftoken_t *it;
7347 
7348 	WRITE_ENTER(&softc->ipf_tokens);
7349 	while ((it = softc->ipf_token_head) != NULL) {
7350 		if (it->ipt_die > softc->ipf_ticks)
7351 			break;
7352 
7353 		ipf_token_deref(softc, it);
7354 	}
7355 	RWLOCK_EXIT(&softc->ipf_tokens);
7356 }
7357 
7358 
7359 /* ------------------------------------------------------------------------ */
7360 /* Function:    ipf_token_flush                                             */
7361 /* Returns:     None.                                                       */
7362 /* Parameters:  softc(I) - pointer to soft context main structure           */
7363 /*                                                                          */
7364 /* Loop through all of the existing tokens and call deref to see if they    */
7365 /* can be freed. Normally a function like this might just loop on           */
7366 /* ipf_token_head but there is a chance that a token might have a ref count */
7367 /* of greater than one and in that case the the reference would drop twice  */
7368 /* by code that is only entitled to drop it once.                           */
7369 /* ------------------------------------------------------------------------ */
7370 static void
7371 ipf_token_flush(ipf_main_softc_t *softc)
7372 {
7373 	ipftoken_t *it, *next;
7374 
7375 	WRITE_ENTER(&softc->ipf_tokens);
7376 	for (it = softc->ipf_token_head; it != NULL; it = next) {
7377 		next = it->ipt_next;
7378 		(void) ipf_token_deref(softc, it);
7379 	}
7380 	RWLOCK_EXIT(&softc->ipf_tokens);
7381 }
7382 
7383 
7384 /* ------------------------------------------------------------------------ */
7385 /* Function:    ipf_token_del                                               */
7386 /* Returns:     int     - 0 = success, else error                           */
7387 /* Parameters:  softc(I)- pointer to soft context main structure            */
7388 /*              type(I) - the token type to match                           */
7389 /*              uid(I)  - uid owning the token                              */
7390 /*              ptr(I)  - context pointer for the token                     */
7391 /*                                                                          */
7392 /* This function looks for a a token in the current list that matches up    */
7393 /* the fields (type, uid, ptr).  If none is found, ESRCH is returned, else  */
7394 /* call ipf_token_dewref() to remove it from the list. In the event that    */
7395 /* the token has a reference held elsewhere, setting ipt_complete to 2      */
7396 /* enables debugging to distinguish between the two paths that ultimately   */
7397 /* lead to a token to be deleted.                                           */
7398 /* ------------------------------------------------------------------------ */
7399 int
7400 ipf_token_del(ipf_main_softc_t *softc, int type, int uid, void *ptr)
7401 {
7402 	ipftoken_t *it;
7403 	int error;
7404 
7405 	IPFERROR(82);
7406 	error = ESRCH;
7407 
7408 	WRITE_ENTER(&softc->ipf_tokens);
7409 	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7410 		if (ptr == it->ipt_ctx && type == it->ipt_type &&
7411 		    uid == it->ipt_uid) {
7412 			it->ipt_complete = 2;
7413 			ipf_token_deref(softc, it);
7414 			error = 0;
7415 			break;
7416 		}
7417 	}
7418 	RWLOCK_EXIT(&softc->ipf_tokens);
7419 
7420 	return error;
7421 }
7422 
7423 
7424 /* ------------------------------------------------------------------------ */
7425 /* Function:    ipf_token_mark_complete                                     */
7426 /* Returns:     None.                                                       */
7427 /* Parameters:  token(I) - pointer to token structure                       */
7428 /*                                                                          */
7429 /* Mark a token as being ineligable for being found with ipf_token_find.    */
7430 /* ------------------------------------------------------------------------ */
7431 void
7432 ipf_token_mark_complete(ipftoken_t *token)
7433 {
7434 	if (token->ipt_complete == 0)
7435 		token->ipt_complete = 1;
7436 }
7437 
7438 
7439 /* ------------------------------------------------------------------------ */
7440 /* Function:    ipf_token_find                                               */
7441 /* Returns:     ipftoken_t * - NULL if no memory, else pointer to token     */
7442 /* Parameters:  softc(I)- pointer to soft context main structure            */
7443 /*              type(I) - the token type to match                           */
7444 /*              uid(I)  - uid owning the token                              */
7445 /*              ptr(I)  - context pointer for the token                     */
7446 /*                                                                          */
7447 /* This function looks for a live token in the list of current tokens that  */
7448 /* matches the tuple (type, uid, ptr).  If one cannot be found then one is  */
7449 /* allocated.  If one is found then it is moved to the top of the list of   */
7450 /* currently active tokens.                                                 */
7451 /* ------------------------------------------------------------------------ */
7452 ipftoken_t *
7453 ipf_token_find(ipf_main_softc_t *softc, int type, int uid, void *ptr)
7454 {
7455 	ipftoken_t *it, *new;
7456 
7457 	KMALLOC(new, ipftoken_t *);
7458 	if (new != NULL)
7459 		bzero((char *)new, sizeof(*new));
7460 
7461 	WRITE_ENTER(&softc->ipf_tokens);
7462 	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7463 		if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
7464 		    (uid == it->ipt_uid) && (it->ipt_complete < 2))
7465 			break;
7466 	}
7467 
7468 	if (it == NULL) {
7469 		it = new;
7470 		new = NULL;
7471 		if (it == NULL) {
7472 			RWLOCK_EXIT(&softc->ipf_tokens);
7473 			return NULL;
7474 		}
7475 		it->ipt_ctx = ptr;
7476 		it->ipt_uid = uid;
7477 		it->ipt_type = type;
7478 		it->ipt_ref = 1;
7479 	} else {
7480 		if (new != NULL) {
7481 			KFREE(new);
7482 			new = NULL;
7483 		}
7484 
7485 		if (it->ipt_complete > 0)
7486 			it = NULL;
7487 		else
7488 			ipf_token_unlink(softc, it);
7489 	}
7490 
7491 	if (it != NULL) {
7492 		it->ipt_pnext = softc->ipf_token_tail;
7493 		*softc->ipf_token_tail = it;
7494 		softc->ipf_token_tail = &it->ipt_next;
7495 		it->ipt_next = NULL;
7496 		it->ipt_ref++;
7497 
7498 		it->ipt_die = softc->ipf_ticks + 20;
7499 	}
7500 
7501 	RWLOCK_EXIT(&softc->ipf_tokens);
7502 
7503 	return it;
7504 }
7505 
7506 
7507 /* ------------------------------------------------------------------------ */
7508 /* Function:    ipf_token_unlink                                            */
7509 /* Returns:     None.                                                       */
7510 /* Parameters:  softc(I) - pointer to soft context main structure           */
7511 /*              token(I) - pointer to token structure                       */
7512 /* Write Locks: ipf_tokens                                                  */
7513 /*                                                                          */
7514 /* This function unlinks a token structure from the linked list of tokens   */
7515 /* that "own" it.  The head pointer never needs to be explicitly adjusted   */
7516 /* but the tail does due to the linked list implementation.                 */
7517 /* ------------------------------------------------------------------------ */
7518 static void
7519 ipf_token_unlink(ipf_main_softc_t *softc, ipftoken_t *token)
7520 {
7521 
7522 	if (softc->ipf_token_tail == &token->ipt_next)
7523 		softc->ipf_token_tail = token->ipt_pnext;
7524 
7525 	*token->ipt_pnext = token->ipt_next;
7526 	if (token->ipt_next != NULL)
7527 		token->ipt_next->ipt_pnext = token->ipt_pnext;
7528 	token->ipt_next = NULL;
7529 	token->ipt_pnext = NULL;
7530 }
7531 
7532 
7533 /* ------------------------------------------------------------------------ */
7534 /* Function:    ipf_token_deref                                             */
7535 /* Returns:     int      - 0 == token freed, else reference count           */
7536 /* Parameters:  softc(I) - pointer to soft context main structure           */
7537 /*              token(I) - pointer to token structure                       */
7538 /* Write Locks: ipf_tokens                                                  */
7539 /*                                                                          */
7540 /* Drop the reference count on the token structure and if it drops to zero, */
7541 /* call the dereference function for the token type because it is then      */
7542 /* possible to free the token data structure.                               */
7543 /* ------------------------------------------------------------------------ */
7544 int
7545 ipf_token_deref(ipf_main_softc_t *softc, ipftoken_t *token)
7546 {
7547 	void *data, **datap;
7548 
7549 	ASSERT(token->ipt_ref > 0);
7550 	token->ipt_ref--;
7551 	if (token->ipt_ref > 0)
7552 		return token->ipt_ref;
7553 
7554 	data = token->ipt_data;
7555 	datap = &data;
7556 
7557 	if ((data != NULL) && (data != (void *)-1)) {
7558 		switch (token->ipt_type)
7559 		{
7560 		case IPFGENITER_IPF :
7561 			(void) ipf_derefrule(softc, (frentry_t **)datap);
7562 			break;
7563 		case IPFGENITER_IPNAT :
7564 			WRITE_ENTER(&softc->ipf_nat);
7565 			ipf_nat_rule_deref(softc, (ipnat_t **)datap);
7566 			RWLOCK_EXIT(&softc->ipf_nat);
7567 			break;
7568 		case IPFGENITER_NAT :
7569 			ipf_nat_deref(softc, (nat_t **)datap);
7570 			break;
7571 		case IPFGENITER_STATE :
7572 			ipf_state_deref(softc, (ipstate_t **)datap);
7573 			break;
7574 		case IPFGENITER_FRAG :
7575 			ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
7576 			break;
7577 		case IPFGENITER_NATFRAG :
7578 			ipf_frag_nat_deref(softc, (ipfr_t **)datap);
7579 			break;
7580 		case IPFGENITER_HOSTMAP :
7581 			WRITE_ENTER(&softc->ipf_nat);
7582 			ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
7583 			RWLOCK_EXIT(&softc->ipf_nat);
7584 			break;
7585 		default :
7586 			ipf_lookup_iterderef(softc, token->ipt_type, data);
7587 			break;
7588 		}
7589 	}
7590 
7591 	ipf_token_unlink(softc, token);
7592 	KFREE(token);
7593 	return 0;
7594 }
7595 
7596 
7597 /* ------------------------------------------------------------------------ */
7598 /* Function:    ipf_nextrule                                                */
7599 /* Returns:     frentry_t * - NULL == no more rules, else pointer to next   */
7600 /* Parameters:  softc(I)    - pointer to soft context main structure        */
7601 /*              fr(I)       - pointer to filter rule                        */
7602 /*              out(I)      - 1 == out rules, 0 == input rules              */
7603 /*                                                                          */
7604 /* Starting with "fr", find the next rule to visit. This includes visiting  */
7605 /* the list of rule groups if either fr is NULL (empty list) or it is the   */
7606 /* last rule in the list. When walking rule lists, it is either input or    */
7607 /* output rules that are returned, never both.                              */
7608 /* ------------------------------------------------------------------------ */
7609 static frentry_t *
7610 ipf_nextrule(ipf_main_softc_t *softc, int active, int unit,
7611     frentry_t *fr, int out)
7612 {
7613 	frentry_t *next;
7614 	frgroup_t *fg;
7615 
7616 	if (fr != NULL && fr->fr_group != -1) {
7617 		fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
7618 				   unit, active, NULL);
7619 		if (fg != NULL)
7620 			fg = fg->fg_next;
7621 	} else {
7622 		fg = softc->ipf_groups[unit][active];
7623 	}
7624 
7625 	while (fg != NULL) {
7626 		next = fg->fg_start;
7627 		while (next != NULL) {
7628 			if (out) {
7629 				if (next->fr_flags & FR_OUTQUE)
7630 					return next;
7631 			} else if (next->fr_flags & FR_INQUE) {
7632 				return next;
7633 			}
7634 			next = next->fr_next;
7635 		}
7636 		if (next == NULL)
7637 			fg = fg->fg_next;
7638 	}
7639 
7640 	return NULL;
7641 }
7642 
7643 /* ------------------------------------------------------------------------ */
7644 /* Function:    ipf_getnextrule                                             */
7645 /* Returns:     int - 0 = success, else error                               */
7646 /* Parameters:  softc(I)- pointer to soft context main structure            */
7647 /*              t(I)   - pointer to destination information to resolve      */
7648 /*              ptr(I) - pointer to ipfobj_t to copyin from user space      */
7649 /*                                                                          */
7650 /* This function's first job is to bring in the ipfruleiter_t structure via */
7651 /* the ipfobj_t structure to determine what should be the next rule to      */
7652 /* return. Once the ipfruleiter_t has been brought in, it then tries to     */
7653 /* find the 'next rule'.  This may include searching rule group lists or    */
7654 /* just be as simple as looking at the 'next' field in the rule structure.  */
7655 /* When we have found the rule to return, increase its reference count and  */
7656 /* if we used an existing rule to get here, decrease its reference count.   */
7657 /* ------------------------------------------------------------------------ */
7658 int
7659 ipf_getnextrule(ipf_main_softc_t *softc, ipftoken_t *t, void *ptr)
7660 {
7661 	frentry_t *fr, *next, zero;
7662 	ipfruleiter_t it;
7663 	int error, out;
7664 	frgroup_t *fg;
7665 	ipfobj_t obj;
7666 	int predict;
7667 	char *dst;
7668 	int unit;
7669 
7670 	if (t == NULL || ptr == NULL) {
7671 		IPFERROR(84);
7672 		return EFAULT;
7673 	}
7674 
7675 	error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
7676 	if (error != 0)
7677 		return error;
7678 
7679 	if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
7680 		IPFERROR(85);
7681 		return EINVAL;
7682 	}
7683 	if ((it.iri_active != 0) && (it.iri_active != 1)) {
7684 		IPFERROR(86);
7685 		return EINVAL;
7686 	}
7687 	if (it.iri_nrules == 0) {
7688 		IPFERROR(87);
7689 		return ENOSPC;
7690 	}
7691 	if (it.iri_rule == NULL) {
7692 		IPFERROR(88);
7693 		return EFAULT;
7694 	}
7695 
7696 	fg = NULL;
7697 	fr = t->ipt_data;
7698 	if ((it.iri_inout & F_OUT) != 0)
7699 		out = 1;
7700 	else
7701 		out = 0;
7702 	if ((it.iri_inout & F_ACIN) != 0)
7703 		unit = IPL_LOGCOUNT;
7704 	else
7705 		unit = IPL_LOGIPF;
7706 
7707 	READ_ENTER(&softc->ipf_mutex);
7708 	if (fr == NULL) {
7709 		if (*it.iri_group == '\0') {
7710 			if (unit == IPL_LOGCOUNT) {
7711 				next = softc->ipf_acct[out][it.iri_active];
7712 			} else {
7713 				next = softc->ipf_rules[out][it.iri_active];
7714 			}
7715 			if (next == NULL)
7716 				next = ipf_nextrule(softc, it.iri_active,
7717 						    unit, NULL, out);
7718 		} else {
7719 			fg = ipf_findgroup(softc, it.iri_group, unit,
7720 					   it.iri_active, NULL);
7721 			if (fg != NULL)
7722 				next = fg->fg_start;
7723 			else
7724 				next = NULL;
7725 		}
7726 	} else {
7727 		next = fr->fr_next;
7728 		if (next == NULL)
7729 			next = ipf_nextrule(softc, it.iri_active, unit,
7730 					    fr, out);
7731 	}
7732 
7733 	if (next != NULL && next->fr_next != NULL)
7734 		predict = 1;
7735 	else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
7736 		predict = 1;
7737 	else
7738 		predict = 0;
7739 
7740 	if (fr != NULL)
7741 		(void) ipf_derefrule(softc, &fr);
7742 
7743 	obj.ipfo_type = IPFOBJ_FRENTRY;
7744 	dst = (char *)it.iri_rule;
7745 
7746 	if (next != NULL) {
7747 		obj.ipfo_size = next->fr_size;
7748 		MUTEX_ENTER(&next->fr_lock);
7749 		next->fr_ref++;
7750 		MUTEX_EXIT(&next->fr_lock);
7751 		t->ipt_data = next;
7752 	} else {
7753 		obj.ipfo_size = sizeof(frentry_t);
7754 		bzero(&zero, sizeof(zero));
7755 		next = &zero;
7756 		t->ipt_data = NULL;
7757 	}
7758 	it.iri_rule = predict ? next : NULL;
7759 	if (predict == 0)
7760 		ipf_token_mark_complete(t);
7761 
7762 	RWLOCK_EXIT(&softc->ipf_mutex);
7763 
7764 	obj.ipfo_ptr = dst;
7765 	error = ipf_outobjk(softc, &obj, next);
7766 	if (error == 0 && t->ipt_data != NULL) {
7767 		dst += obj.ipfo_size;
7768 		if (next->fr_data != NULL) {
7769 			ipfobj_t dobj;
7770 
7771 			if (next->fr_type == FR_T_IPFEXPR)
7772 				dobj.ipfo_type = IPFOBJ_IPFEXPR;
7773 			else
7774 				dobj.ipfo_type = IPFOBJ_FRIPF;
7775 			dobj.ipfo_size = next->fr_dsize;
7776 			dobj.ipfo_rev = obj.ipfo_rev;
7777 			dobj.ipfo_ptr = dst;
7778 			error = ipf_outobjk(softc, &dobj, next->fr_data);
7779 		}
7780 	}
7781 
7782 	if ((fr != NULL) && (next == &zero))
7783 		(void) ipf_derefrule(softc, &fr);
7784 
7785 	return error;
7786 }
7787 
7788 
7789 /* ------------------------------------------------------------------------ */
7790 /* Function:    ipf_frruleiter                                              */
7791 /* Returns:     int - 0 = success, else error                               */
7792 /* Parameters:  softc(I)- pointer to soft context main structure            */
7793 /*              data(I) - the token type to match                           */
7794 /*              uid(I)  - uid owning the token                              */
7795 /*              ptr(I)  - context pointer for the token                     */
7796 /*                                                                          */
7797 /* This function serves as a stepping stone between ipf_ipf_ioctl and       */
7798 /* ipf_getnextrule.  It's role is to find the right token in the kernel for */
7799 /* the process doing the ioctl and use that to ask for the next rule.       */
7800 /* ------------------------------------------------------------------------ */
7801 static int
7802 ipf_frruleiter(ipf_main_softc_t *softc, void *data, int uid, void *ctx)
7803 {
7804 	ipftoken_t *token;
7805 	ipfruleiter_t it;
7806 	ipfobj_t obj;
7807 	int error;
7808 
7809 	token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
7810 	if (token != NULL) {
7811 		error = ipf_getnextrule(softc, token, data);
7812 		WRITE_ENTER(&softc->ipf_tokens);
7813 		ipf_token_deref(softc, token);
7814 		RWLOCK_EXIT(&softc->ipf_tokens);
7815 	} else {
7816 		error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
7817 		if (error != 0)
7818 			return error;
7819 		it.iri_rule = NULL;
7820 		error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
7821 	}
7822 
7823 	return error;
7824 }
7825 
7826 
7827 /* ------------------------------------------------------------------------ */
7828 /* Function:    ipf_geniter                                                 */
7829 /* Returns:     int - 0 = success, else error                               */
7830 /* Parameters:  softc(I) - pointer to soft context main structure           */
7831 /*              token(I) - pointer to ipftoken_t structure                  */
7832 /*              itp(I)   - pointer to iterator data                         */
7833 /*                                                                          */
7834 /* Decide which iterator function to call using information passed through  */
7835 /* the ipfgeniter_t structure at itp.                                       */
7836 /* ------------------------------------------------------------------------ */
7837 static int
7838 ipf_geniter(ipf_main_softc_t *softc, ipftoken_t *token, ipfgeniter_t *itp)
7839 {
7840 	int error;
7841 
7842 	switch (itp->igi_type)
7843 	{
7844 	case IPFGENITER_FRAG :
7845 		error = ipf_frag_pkt_next(softc, token, itp);
7846 		break;
7847 	default :
7848 		IPFERROR(92);
7849 		error = EINVAL;
7850 		break;
7851 	}
7852 
7853 	return error;
7854 }
7855 
7856 
7857 /* ------------------------------------------------------------------------ */
7858 /* Function:    ipf_genericiter                                             */
7859 /* Returns:     int - 0 = success, else error                               */
7860 /* Parameters:  softc(I)- pointer to soft context main structure            */
7861 /*              data(I) - the token type to match                           */
7862 /*              uid(I)  - uid owning the token                              */
7863 /*              ptr(I)  - context pointer for the token                     */
7864 /*                                                                          */
7865 /* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role   */
7866 /* ------------------------------------------------------------------------ */
7867 int
7868 ipf_genericiter(ipf_main_softc_t *softc, void *data, int uid, void *ctx)
7869 {
7870 	ipftoken_t *token;
7871 	ipfgeniter_t iter;
7872 	int error;
7873 
7874 	error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
7875 	if (error != 0)
7876 		return error;
7877 
7878 	token = ipf_token_find(softc, iter.igi_type, uid, ctx);
7879 	if (token != NULL) {
7880 		token->ipt_subtype = iter.igi_type;
7881 		error = ipf_geniter(softc, token, &iter);
7882 		WRITE_ENTER(&softc->ipf_tokens);
7883 		ipf_token_deref(softc, token);
7884 		RWLOCK_EXIT(&softc->ipf_tokens);
7885 	} else {
7886 		IPFERROR(93);
7887 		error = 0;
7888 	}
7889 
7890 	return error;
7891 }
7892 
7893 
7894 /* ------------------------------------------------------------------------ */
7895 /* Function:    ipf_ipf_ioctl                                               */
7896 /* Returns:     int - 0 = success, else error                               */
7897 /* Parameters:  softc(I)- pointer to soft context main structure           */
7898 /*              data(I) - the token type to match                           */
7899 /*              cmd(I)  - the ioctl command number                          */
7900 /*              mode(I) - mode flags for the ioctl                          */
7901 /*              uid(I)  - uid owning the token                              */
7902 /*              ptr(I)  - context pointer for the token                     */
7903 /*                                                                          */
7904 /* This function handles all of the ioctl command that are actually isssued */
7905 /* to the /dev/ipl device.                                                  */
7906 /* ------------------------------------------------------------------------ */
7907 int
7908 ipf_ipf_ioctl(ipf_main_softc_t *softc, void *data, ioctlcmd_t cmd, int mode,
7909     int uid, void *ctx)
7910 {
7911 	friostat_t fio;
7912 	int error, tmp;
7913 	ipfobj_t obj;
7914 	SPL_INT(s);
7915 
7916 	switch (cmd)
7917 	{
7918 	case SIOCFRENB :
7919 		if (!(mode & FWRITE)) {
7920 			IPFERROR(94);
7921 			error = EPERM;
7922 		} else {
7923 			error = BCOPYIN(data, &tmp, sizeof(tmp));
7924 			if (error != 0) {
7925 				IPFERROR(95);
7926 				error = EFAULT;
7927 				break;
7928 			}
7929 
7930 			WRITE_ENTER(&softc->ipf_global);
7931 			if (tmp) {
7932 				if (softc->ipf_running > 0)
7933 					error = 0;
7934 				else
7935 					error = ipfattach(softc);
7936 				if (error == 0)
7937 					softc->ipf_running = 1;
7938 				else
7939 					(void) ipfdetach(softc);
7940 			} else {
7941 				if (softc->ipf_running == 1)
7942 					error = ipfdetach(softc);
7943 				else
7944 					error = 0;
7945 				if (error == 0)
7946 					softc->ipf_running = -1;
7947 			}
7948 			RWLOCK_EXIT(&softc->ipf_global);
7949 		}
7950 		break;
7951 
7952 	case SIOCIPFSET :
7953 		if (!(mode & FWRITE)) {
7954 			IPFERROR(96);
7955 			error = EPERM;
7956 			break;
7957 		}
7958 		/* FALLTHRU */
7959 	case SIOCIPFGETNEXT :
7960 	case SIOCIPFGET :
7961 		error = ipf_ipftune(softc, cmd, (void *)data);
7962 		break;
7963 
7964 	case SIOCSETFF :
7965 		if (!(mode & FWRITE)) {
7966 			IPFERROR(97);
7967 			error = EPERM;
7968 		} else {
7969 			error = BCOPYIN(data, &softc->ipf_flags,
7970 					sizeof(softc->ipf_flags));
7971 			if (error != 0) {
7972 				IPFERROR(98);
7973 				error = EFAULT;
7974 			}
7975 		}
7976 		break;
7977 
7978 	case SIOCGETFF :
7979 		error = BCOPYOUT(&softc->ipf_flags, data,
7980 				 sizeof(softc->ipf_flags));
7981 		if (error != 0) {
7982 			IPFERROR(99);
7983 			error = EFAULT;
7984 		}
7985 		break;
7986 
7987 	case SIOCFUNCL :
7988 		error = ipf_resolvefunc(softc, (void *)data);
7989 		break;
7990 
7991 	case SIOCINAFR :
7992 	case SIOCRMAFR :
7993 	case SIOCADAFR :
7994 	case SIOCZRLST :
7995 		if (!(mode & FWRITE)) {
7996 			IPFERROR(100);
7997 			error = EPERM;
7998 		} else {
7999 			error = frrequest(softc, IPL_LOGIPF, cmd, data,
8000 					  softc->ipf_active, 1);
8001 		}
8002 		break;
8003 
8004 	case SIOCINIFR :
8005 	case SIOCRMIFR :
8006 	case SIOCADIFR :
8007 		if (!(mode & FWRITE)) {
8008 			IPFERROR(101);
8009 			error = EPERM;
8010 		} else {
8011 			error = frrequest(softc, IPL_LOGIPF, cmd, data,
8012 					  1 - softc->ipf_active, 1);
8013 		}
8014 		break;
8015 
8016 	case SIOCSWAPA :
8017 		if (!(mode & FWRITE)) {
8018 			IPFERROR(102);
8019 			error = EPERM;
8020 		} else {
8021 			WRITE_ENTER(&softc->ipf_mutex);
8022 			error = BCOPYOUT(&softc->ipf_active, data,
8023 					 sizeof(softc->ipf_active));
8024 			if (error != 0) {
8025 				IPFERROR(103);
8026 				error = EFAULT;
8027 			} else {
8028 				softc->ipf_active = 1 - softc->ipf_active;
8029 			}
8030 			RWLOCK_EXIT(&softc->ipf_mutex);
8031 		}
8032 		break;
8033 
8034 	case SIOCGETFS :
8035 		error = ipf_inobj(softc, (void *)data, &obj, &fio,
8036 				  IPFOBJ_IPFSTAT);
8037 		if (error != 0)
8038 			break;
8039 		ipf_getstat(softc, &fio, obj.ipfo_rev);
8040 		error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
8041 		break;
8042 
8043 	case SIOCFRZST :
8044 		if (!(mode & FWRITE)) {
8045 			IPFERROR(104);
8046 			error = EPERM;
8047 		} else
8048 			error = ipf_zerostats(softc, data);
8049 		break;
8050 
8051 	case SIOCIPFFL :
8052 		if (!(mode & FWRITE)) {
8053 			IPFERROR(105);
8054 			error = EPERM;
8055 		} else {
8056 			error = BCOPYIN(data, &tmp, sizeof(tmp));
8057 			if (!error) {
8058 				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8059 				error = BCOPYOUT(&tmp, data, sizeof(tmp));
8060 				if (error != 0) {
8061 					IPFERROR(106);
8062 					error = EFAULT;
8063 				}
8064 			} else {
8065 				IPFERROR(107);
8066 				error = EFAULT;
8067 			}
8068 		}
8069 		break;
8070 
8071 #ifdef USE_INET6
8072 	case SIOCIPFL6 :
8073 		if (!(mode & FWRITE)) {
8074 			IPFERROR(108);
8075 			error = EPERM;
8076 		} else {
8077 			error = BCOPYIN(data, &tmp, sizeof(tmp));
8078 			if (!error) {
8079 				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8080 				error = BCOPYOUT(&tmp, data, sizeof(tmp));
8081 				if (error != 0) {
8082 					IPFERROR(109);
8083 					error = EFAULT;
8084 				}
8085 			} else {
8086 				IPFERROR(110);
8087 				error = EFAULT;
8088 			}
8089 		}
8090 		break;
8091 #endif
8092 
8093 	case SIOCSTLCK :
8094 		if (!(mode & FWRITE)) {
8095 			IPFERROR(122);
8096 			error = EPERM;
8097 		} else {
8098 			error = BCOPYIN(data, &tmp, sizeof(tmp));
8099 			if (error == 0) {
8100 				ipf_state_setlock(softc->ipf_state_soft, tmp);
8101 				ipf_nat_setlock(softc->ipf_nat_soft, tmp);
8102 				ipf_frag_setlock(softc->ipf_frag_soft, tmp);
8103 				ipf_auth_setlock(softc->ipf_auth_soft, tmp);
8104 			} else {
8105 				IPFERROR(111);
8106 				error = EFAULT;
8107 			}
8108 		}
8109 		break;
8110 
8111 #ifdef	IPFILTER_LOG
8112 	case SIOCIPFFB :
8113 		if (!(mode & FWRITE)) {
8114 			IPFERROR(112);
8115 			error = EPERM;
8116 		} else {
8117 			tmp = ipf_log_clear(softc, IPL_LOGIPF);
8118 			error = BCOPYOUT(&tmp, data, sizeof(tmp));
8119 			if (error) {
8120 				IPFERROR(113);
8121 				error = EFAULT;
8122 			}
8123 		}
8124 		break;
8125 #endif /* IPFILTER_LOG */
8126 
8127 	case SIOCFRSYN :
8128 		if (!(mode & FWRITE)) {
8129 			IPFERROR(114);
8130 			error = EPERM;
8131 		} else {
8132 			WRITE_ENTER(&softc->ipf_global);
8133 #if (defined(MENTAT) && defined(_KERNEL)) && !defined(INSTANCES)
8134 			error = ipfsync();
8135 #else
8136 			ipf_sync(softc, NULL);
8137 			error = 0;
8138 #endif
8139 			RWLOCK_EXIT(&softc->ipf_global);
8140 
8141 		}
8142 		break;
8143 
8144 	case SIOCGFRST :
8145 		error = ipf_outobj(softc, (void *)data,
8146 				   ipf_frag_stats(softc->ipf_frag_soft),
8147 				   IPFOBJ_FRAGSTAT);
8148 		break;
8149 
8150 #ifdef	IPFILTER_LOG
8151 	case FIONREAD :
8152 		tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
8153 		error = BCOPYOUT(&tmp, data, sizeof(tmp));
8154 		break;
8155 #endif
8156 
8157 	case SIOCIPFITER :
8158 		SPL_SCHED(s);
8159 		error = ipf_frruleiter(softc, data, uid, ctx);
8160 		SPL_X(s);
8161 		break;
8162 
8163 	case SIOCGENITER :
8164 		SPL_SCHED(s);
8165 		error = ipf_genericiter(softc, data, uid, ctx);
8166 		SPL_X(s);
8167 		break;
8168 
8169 	case SIOCIPFDELTOK :
8170 		error = BCOPYIN(data, &tmp, sizeof(tmp));
8171 		if (error == 0) {
8172 			SPL_SCHED(s);
8173 			error = ipf_token_del(softc, tmp, uid, ctx);
8174 			SPL_X(s);
8175 		}
8176 		break;
8177 
8178 	default :
8179 		IPFERROR(115);
8180 		error = EINVAL;
8181 		break;
8182 	}
8183 
8184 	return error;
8185 }
8186 
8187 
8188 /* ------------------------------------------------------------------------ */
8189 /* Function:    ipf_decaps                                                  */
8190 /* Returns:     int        - -1 == decapsulation failed, else bit mask of   */
8191 /*                           flags indicating packet filtering decision.    */
8192 /* Parameters:  fin(I)     - pointer to packet information                  */
8193 /*              pass(I)    - IP protocol version to match                   */
8194 /*              l5proto(I) - layer 5 protocol to decode UDP data as.        */
8195 /*                                                                          */
8196 /* This function is called for packets that are wrapt up in other packets,  */
8197 /* for example, an IP packet that is the entire data segment for another IP */
8198 /* packet.  If the basic constraints for this are satisfied, change the     */
8199 /* buffer to point to the start of the inner packet and start processing    */
8200 /* rules belonging to the head group this rule specifies.                   */
8201 /* ------------------------------------------------------------------------ */
8202 u_32_t
8203 ipf_decaps(fr_info_t *fin, u_32_t pass, int l5proto)
8204 {
8205 	fr_info_t fin2, *fino = NULL;
8206 	int elen, hlen, nh;
8207 	grehdr_t gre;
8208 	ip_t *ip;
8209 	mb_t *m;
8210 
8211 	if ((fin->fin_flx & FI_COALESCE) == 0)
8212 		if (ipf_coalesce(fin) == -1)
8213 			goto cantdecaps;
8214 
8215 	m = fin->fin_m;
8216 	hlen = fin->fin_hlen;
8217 
8218 	switch (fin->fin_p)
8219 	{
8220 	case IPPROTO_UDP :
8221 		/*
8222 		 * In this case, the specific protocol being decapsulated
8223 		 * inside UDP frames comes from the rule.
8224 		 */
8225 		nh = fin->fin_fr->fr_icode;
8226 		break;
8227 
8228 	case IPPROTO_GRE :	/* 47 */
8229 		bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
8230 		hlen += sizeof(grehdr_t);
8231 		if (gre.gr_R|gre.gr_s)
8232 			goto cantdecaps;
8233 		if (gre.gr_C)
8234 			hlen += 4;
8235 		if (gre.gr_K)
8236 			hlen += 4;
8237 		if (gre.gr_S)
8238 			hlen += 4;
8239 
8240 		nh = IPPROTO_IP;
8241 
8242 		/*
8243 		 * If the routing options flag is set, validate that it is
8244 		 * there and bounce over it.
8245 		 */
8246 #if 0
8247 		/* This is really heavy weight and lots of room for error, */
8248 		/* so for now, put it off and get the simple stuff right.  */
8249 		if (gre.gr_R) {
8250 			u_char off, len, *s;
8251 			u_short af;
8252 			int end;
8253 
8254 			end = 0;
8255 			s = fin->fin_dp;
8256 			s += hlen;
8257 			aplen = fin->fin_plen - hlen;
8258 			while (aplen > 3) {
8259 				af = (s[0] << 8) | s[1];
8260 				off = s[2];
8261 				len = s[3];
8262 				aplen -= 4;
8263 				s += 4;
8264 				if (af == 0 && len == 0) {
8265 					end = 1;
8266 					break;
8267 				}
8268 				if (aplen < len)
8269 					break;
8270 				s += len;
8271 				aplen -= len;
8272 			}
8273 			if (end != 1)
8274 				goto cantdecaps;
8275 			hlen = s - (u_char *)fin->fin_dp;
8276 		}
8277 #endif
8278 		break;
8279 
8280 #ifdef IPPROTO_IPIP
8281 	case IPPROTO_IPIP :	/* 4 */
8282 #endif
8283 		nh = IPPROTO_IP;
8284 		break;
8285 
8286 	default :	/* Includes ESP, AH is special for IPv4 */
8287 		goto cantdecaps;
8288 	}
8289 
8290 	switch (nh)
8291 	{
8292 	case IPPROTO_IP :
8293 	case IPPROTO_IPV6 :
8294 		break;
8295 	default :
8296 		goto cantdecaps;
8297 	}
8298 
8299 	bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
8300 	fino = fin;
8301 	fin = &fin2;
8302 	elen = hlen;
8303 #if defined(MENTAT) && defined(_KERNEL)
8304 	m->b_rptr += elen;
8305 #else
8306 	m->m_data += elen;
8307 	m->m_len -= elen;
8308 #endif
8309 	fin->fin_plen -= elen;
8310 
8311 	ip = (ip_t *)((char *)fin->fin_ip + elen);
8312 
8313 	/*
8314 	 * Make sure we have at least enough data for the network layer
8315 	 * header.
8316 	 */
8317 	if (IP_V(ip) == 4)
8318 		hlen = IP_HL(ip) << 2;
8319 #ifdef USE_INET6
8320 	else if (IP_V(ip) == 6)
8321 		hlen = sizeof(ip6_t);
8322 #endif
8323 	else
8324 		goto cantdecaps2;
8325 
8326 	if (fin->fin_plen < hlen)
8327 		goto cantdecaps2;
8328 
8329 	fin->fin_dp = (char *)ip + hlen;
8330 
8331 	if (IP_V(ip) == 4) {
8332 		/*
8333 		 * Perform IPv4 header checksum validation.
8334 		 */
8335 		if (ipf_cksum((u_short *)ip, hlen))
8336 			goto cantdecaps2;
8337 	}
8338 
8339 	if (ipf_makefrip(hlen, ip, fin) == -1) {
8340 cantdecaps2:
8341 		if (m != NULL) {
8342 #if defined(MENTAT) && defined(_KERNEL)
8343 			m->b_rptr -= elen;
8344 #else
8345 			m->m_data -= elen;
8346 			m->m_len += elen;
8347 #endif
8348 		}
8349 cantdecaps:
8350 		DT1(frb_decapfrip, fr_info_t *, fin);
8351 		pass &= ~FR_CMDMASK;
8352 		pass |= FR_BLOCK|FR_QUICK;
8353 		fin->fin_reason = FRB_DECAPFRIP;
8354 		return -1;
8355 	}
8356 
8357 	pass = ipf_scanlist(fin, pass);
8358 
8359 	/*
8360 	 * Copy the packet filter "result" fields out of the fr_info_t struct
8361 	 * that is local to the decapsulation processing and back into the
8362 	 * one we were called with.
8363 	 */
8364 	fino->fin_flx = fin->fin_flx;
8365 	fino->fin_rev = fin->fin_rev;
8366 	fino->fin_icode = fin->fin_icode;
8367 	fino->fin_rule = fin->fin_rule;
8368 	(void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
8369 	fino->fin_fr = fin->fin_fr;
8370 	fino->fin_error = fin->fin_error;
8371 	fino->fin_mp = fin->fin_mp;
8372 	fino->fin_m = fin->fin_m;
8373 	m = fin->fin_m;
8374 	if (m != NULL) {
8375 #if defined(MENTAT) && defined(_KERNEL)
8376 		m->b_rptr -= elen;
8377 #else
8378 		m->m_data -= elen;
8379 		m->m_len += elen;
8380 #endif
8381 	}
8382 	return pass;
8383 }
8384 
8385 
8386 /* ------------------------------------------------------------------------ */
8387 /* Function:    ipf_matcharray_load                                         */
8388 /* Returns:     int         - 0 = success, else error                       */
8389 /* Parameters:  softc(I)    - pointer to soft context main structure        */
8390 /*              data(I)     - pointer to ioctl data                         */
8391 /*              objp(I)     - ipfobj_t structure to load data into          */
8392 /*              arrayptr(I) - pointer to location to store array pointer    */
8393 /*                                                                          */
8394 /* This function loads in a mathing array through the ipfobj_t struct that  */
8395 /* describes it.  Sanity checking and array size limitations are enforced   */
8396 /* in this function to prevent userspace from trying to load in something   */
8397 /* that is insanely big.  Once the size of the array is known, the memory   */
8398 /* required is malloc'd and returned through changing *arrayptr.  The       */
8399 /* contents of the array are verified before returning.  Only in the event  */
8400 /* of a successful call is the caller required to free up the malloc area.  */
8401 /* ------------------------------------------------------------------------ */
8402 int
8403 ipf_matcharray_load(ipf_main_softc_t *softc, void *data, ipfobj_t *objp,
8404     int **arrayptr)
8405 {
8406 	int arraysize, *array, error;
8407 
8408 	*arrayptr = NULL;
8409 
8410 	error = BCOPYIN(data, objp, sizeof(*objp));
8411 	if (error != 0) {
8412 		IPFERROR(116);
8413 		return EFAULT;
8414 	}
8415 
8416 	if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
8417 		IPFERROR(117);
8418 		return EINVAL;
8419 	}
8420 
8421 	if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
8422 	    (objp->ipfo_size > 1024)) {
8423 		IPFERROR(118);
8424 		return EINVAL;
8425 	}
8426 
8427 	arraysize = objp->ipfo_size * sizeof(*array);
8428 	KMALLOCS(array, int *, arraysize);
8429 	if (array == NULL) {
8430 		IPFERROR(119);
8431 		return ENOMEM;
8432 	}
8433 
8434 	error = COPYIN(objp->ipfo_ptr, array, arraysize);
8435 	if (error != 0) {
8436 		KFREES(array, arraysize);
8437 		IPFERROR(120);
8438 		return EFAULT;
8439 	}
8440 
8441 	if (ipf_matcharray_verify(array, arraysize) != 0) {
8442 		KFREES(array, arraysize);
8443 		IPFERROR(121);
8444 		return EINVAL;
8445 	}
8446 
8447 	*arrayptr = array;
8448 	return 0;
8449 }
8450 
8451 
8452 /* ------------------------------------------------------------------------ */
8453 /* Function:    ipf_matcharray_verify                                       */
8454 /* Returns:     Nil                                                         */
8455 /* Parameters:  array(I)     - pointer to matching array                    */
8456 /*              arraysize(I) - number of elements in the array              */
8457 /*                                                                          */
8458 /* Verify the contents of a matching array by stepping through each element */
8459 /* in it.  The actual commands in the array are not verified for            */
8460 /* correctness, only that all of the sizes are correctly within limits.     */
8461 /* ------------------------------------------------------------------------ */
8462 int
8463 ipf_matcharray_verify(int *array, int arraysize)
8464 {
8465 	int i, nelem, maxidx;
8466 	ipfexp_t *e;
8467 
8468 	nelem = arraysize / sizeof(*array);
8469 
8470 	/*
8471 	 * Currently, it makes no sense to have an array less than 6
8472 	 * elements long - the initial size at the from, a single operation
8473 	 * (minimum 4 in length) and a trailer, for a total of 6.
8474 	 */
8475 	if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
8476 		return -1;
8477 	}
8478 
8479 	/*
8480 	 * Verify the size of data pointed to by array with how long
8481 	 * the array claims to be itself.
8482 	 */
8483 	if (array[0] * sizeof(*array) != arraysize) {
8484 		return -1;
8485 	}
8486 
8487 	maxidx = nelem - 1;
8488 	/*
8489 	 * The last opcode in this array should be an IPF_EXP_END.
8490 	 */
8491 	if (array[maxidx] != IPF_EXP_END) {
8492 		return -1;
8493 	}
8494 
8495 	for (i = 1; i < maxidx; ) {
8496 		e = (ipfexp_t *)(array + i);
8497 
8498 		/*
8499 		 * The length of the bits to check must be at least 1
8500 		 * (or else there is nothing to comapre with!) and it
8501 		 * cannot exceed the length of the data present.
8502 		 */
8503 		if ((e->ipfe_size < 1 ) ||
8504 		    (e->ipfe_size + i > maxidx)) {
8505 			return -1;
8506 		}
8507 		i += e->ipfe_size;
8508 	}
8509 	return 0;
8510 }
8511 
8512 
8513 /* ------------------------------------------------------------------------ */
8514 /* Function:    ipf_fr_matcharray                                           */
8515 /* Returns:     int      - 0 = match failed, else positive match            */
8516 /* Parameters:  fin(I)   - pointer to packet information                    */
8517 /*              array(I) - pointer to matching array                        */
8518 /*                                                                          */
8519 /* This function is used to apply a matching array against a packet and     */
8520 /* return an indication of whether or not the packet successfully matches   */
8521 /* all of the commands in it.                                               */
8522 /* ------------------------------------------------------------------------ */
8523 static int
8524 ipf_fr_matcharray(fr_info_t *fin, int *array)
8525 {
8526 	int i, n, *x, rv, p;
8527 	ipfexp_t *e;
8528 
8529 	rv = 0;
8530 	n = array[0];
8531 	x = array + 1;
8532 
8533 	for (; n > 0; x += 3 + x[3], rv = 0) {
8534 		e = (ipfexp_t *)x;
8535 		if (e->ipfe_cmd == IPF_EXP_END)
8536 			break;
8537 		n -= e->ipfe_size;
8538 
8539 		/*
8540 		 * The upper 16 bits currently store the protocol value.
8541 		 * This is currently used with TCP and UDP port compares and
8542 		 * allows "tcp.port = 80" without requiring an explicit
8543 		 " "ip.pr = tcp" first.
8544 		 */
8545 		p = e->ipfe_cmd >> 16;
8546 		if ((p != 0) && (p != fin->fin_p))
8547 			break;
8548 
8549 		switch (e->ipfe_cmd)
8550 		{
8551 		case IPF_EXP_IP_PR :
8552 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8553 				rv |= (fin->fin_p == e->ipfe_arg0[i]);
8554 			}
8555 			break;
8556 
8557 		case IPF_EXP_IP_SRCADDR :
8558 			if (fin->fin_v != 4)
8559 				break;
8560 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8561 				rv |= ((fin->fin_saddr &
8562 					e->ipfe_arg0[i * 2 + 1]) ==
8563 				       e->ipfe_arg0[i * 2]);
8564 			}
8565 			break;
8566 
8567 		case IPF_EXP_IP_DSTADDR :
8568 			if (fin->fin_v != 4)
8569 				break;
8570 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8571 				rv |= ((fin->fin_daddr &
8572 					e->ipfe_arg0[i * 2 + 1]) ==
8573 				       e->ipfe_arg0[i * 2]);
8574 			}
8575 			break;
8576 
8577 		case IPF_EXP_IP_ADDR :
8578 			if (fin->fin_v != 4)
8579 				break;
8580 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8581 				rv |= ((fin->fin_saddr &
8582 					e->ipfe_arg0[i * 2 + 1]) ==
8583 				       e->ipfe_arg0[i * 2]) ||
8584 				      ((fin->fin_daddr &
8585 					e->ipfe_arg0[i * 2 + 1]) ==
8586 				       e->ipfe_arg0[i * 2]);
8587 			}
8588 			break;
8589 
8590 #ifdef USE_INET6
8591 		case IPF_EXP_IP6_SRCADDR :
8592 			if (fin->fin_v != 6)
8593 				break;
8594 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8595 				rv |= IP6_MASKEQ(&fin->fin_src6,
8596 						 &e->ipfe_arg0[i * 8 + 4],
8597 						 &e->ipfe_arg0[i * 8]);
8598 			}
8599 			break;
8600 
8601 		case IPF_EXP_IP6_DSTADDR :
8602 			if (fin->fin_v != 6)
8603 				break;
8604 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8605 				rv |= IP6_MASKEQ(&fin->fin_dst6,
8606 						 &e->ipfe_arg0[i * 8 + 4],
8607 						 &e->ipfe_arg0[i * 8]);
8608 			}
8609 			break;
8610 
8611 		case IPF_EXP_IP6_ADDR :
8612 			if (fin->fin_v != 6)
8613 				break;
8614 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8615 				rv |= IP6_MASKEQ(&fin->fin_src6,
8616 						 &e->ipfe_arg0[i * 8 + 4],
8617 						 &e->ipfe_arg0[i * 8]) ||
8618 				      IP6_MASKEQ(&fin->fin_dst6,
8619 						 &e->ipfe_arg0[i * 8 + 4],
8620 						 &e->ipfe_arg0[i * 8]);
8621 			}
8622 			break;
8623 #endif
8624 
8625 		case IPF_EXP_UDP_PORT :
8626 		case IPF_EXP_TCP_PORT :
8627 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8628 				rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
8629 				      (fin->fin_dport == e->ipfe_arg0[i]);
8630 			}
8631 			break;
8632 
8633 		case IPF_EXP_UDP_SPORT :
8634 		case IPF_EXP_TCP_SPORT :
8635 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8636 				rv |= (fin->fin_sport == e->ipfe_arg0[i]);
8637 			}
8638 			break;
8639 
8640 		case IPF_EXP_UDP_DPORT :
8641 		case IPF_EXP_TCP_DPORT :
8642 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8643 				rv |= (fin->fin_dport == e->ipfe_arg0[i]);
8644 			}
8645 			break;
8646 
8647 		case IPF_EXP_TCP_FLAGS :
8648 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8649 				rv |= ((fin->fin_tcpf &
8650 					e->ipfe_arg0[i * 2 + 1]) ==
8651 				       e->ipfe_arg0[i * 2]);
8652 			}
8653 			break;
8654 		}
8655 		rv ^= e->ipfe_not;
8656 
8657 		if (rv == 0)
8658 			break;
8659 	}
8660 
8661 	return rv;
8662 }
8663 
8664 
8665 /* ------------------------------------------------------------------------ */
8666 /* Function:    ipf_queueflush                                              */
8667 /* Returns:     int - number of entries flushed (0 = none)                  */
8668 /* Parameters:  softc(I)    - pointer to soft context main structure        */
8669 /*              deletefn(I) - function to call to delete entry              */
8670 /*              ipfqs(I)    - top of the list of ipf internal queues        */
8671 /*              userqs(I)   - top of the list of user defined timeouts      */
8672 /*                                                                          */
8673 /* This fucntion gets called when the state/NAT hash tables fill up and we  */
8674 /* need to try a bit harder to free up some space.  The algorithm used here */
8675 /* split into two parts but both halves have the same goal: to reduce the   */
8676 /* number of connections considered to be "active" to the low watermark.    */
8677 /* There are two steps in doing this:                                       */
8678 /* 1) Remove any TCP connections that are already considered to be "closed" */
8679 /*    but have not yet been removed from the state table.  The two states   */
8680 /*    TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect       */
8681 /*    candidates for this style of removal.  If freeing up entries in       */
8682 /*    CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark,   */
8683 /*    we do not go on to step 2.                                            */
8684 /*                                                                          */
8685 /* 2) Look for the oldest entries on each timeout queue and free them if    */
8686 /*    they are within the given window we are considering.  Where the       */
8687 /*    window starts and the steps taken to increase its size depend upon    */
8688 /*    how long ipf has been running (ipf_ticks.)  Anything modified in the  */
8689 /*    last 30 seconds is not touched.                                       */
8690 /*                                              touched                     */
8691 /*         die     ipf_ticks  30*1.5    1800*1.5   |  43200*1.5             */
8692 /*           |          |        |           |     |     |                  */
8693 /* future <--+----------+--------+-----------+-----+-----+-----------> past */
8694 /*                     now        \_int=30s_/ \_int=1hr_/ \_int=12hr        */
8695 /*                                                                          */
8696 /* Points to note:                                                          */
8697 /* - tqe_die is the time, in the future, when entries die.                  */
8698 /* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
8699 /*   ticks.                                                                 */
8700 /* - tqe_touched is when the entry was last used by NAT/state               */
8701 /* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be    */
8702 /*   ipf_ticks any given timeout queue and vice versa.                      */
8703 /* - both tqe_die and tqe_touched increase over time                        */
8704 /* - timeout queues are sorted with the highest value of tqe_die at the     */
8705 /*   bottom and therefore the smallest values of each are at the top        */
8706 /* - the pointer passed in as ipfqs should point to an array of timeout     */
8707 /*   queues representing each of the TCP states                             */
8708 /*                                                                          */
8709 /* We start by setting up a maximum range to scan for things to move of     */
8710 /* iend (newest) to istart (oldest) in chunks of "interval".  If nothing is */
8711 /* found in that range, "interval" is adjusted (so long as it isn't 30) and */
8712 /* we start again with a new value for "iend" and "istart".  This is        */
8713 /* continued until we either finish the scan of 30 second intervals or the  */
8714 /* low water mark is reached.                                               */
8715 /* ------------------------------------------------------------------------ */
8716 int
8717 ipf_queueflush(ipf_main_softc_t *softc, ipftq_delete_fn_t deletefn,
8718     ipftq_t *ipfqs, ipftq_t *userqs, u_int *activep, int size, int low)
8719 {
8720 	u_long interval, istart, iend;
8721 	ipftq_t *ifq, *ifqnext;
8722 	ipftqent_t *tqe, *tqn;
8723 	int removed = 0;
8724 
8725 	for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
8726 		tqn = tqe->tqe_next;
8727 		if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8728 			removed++;
8729 	}
8730 	if ((*activep * 100 / size) > low) {
8731 		for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
8732 		     ((tqe = tqn) != NULL); ) {
8733 			tqn = tqe->tqe_next;
8734 			if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8735 				removed++;
8736 		}
8737 	}
8738 
8739 	if ((*activep * 100 / size) <= low) {
8740 		return removed;
8741 	}
8742 
8743 	/*
8744 	 * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
8745 	 *       used then the operations are upgraded to floating point
8746 	 *       and kernels don't like floating point...
8747 	 */
8748 	if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
8749 		istart = IPF_TTLVAL(86400 * 4);
8750 		interval = IPF_TTLVAL(43200);
8751 	} else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
8752 		istart = IPF_TTLVAL(43200);
8753 		interval = IPF_TTLVAL(1800);
8754 	} else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
8755 		istart = IPF_TTLVAL(1800);
8756 		interval = IPF_TTLVAL(30);
8757 	} else {
8758 		return 0;
8759 	}
8760 	if (istart > softc->ipf_ticks) {
8761 		if (softc->ipf_ticks - interval < interval)
8762 			istart = interval;
8763 		else
8764 			istart = (softc->ipf_ticks / interval) * interval;
8765 	}
8766 
8767 	iend = softc->ipf_ticks - interval;
8768 
8769 	while ((*activep * 100 / size) > low) {
8770 		u_long try;
8771 
8772 		try = softc->ipf_ticks - istart;
8773 
8774 		for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
8775 			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
8776 				if (try < tqe->tqe_touched)
8777 					break;
8778 				tqn = tqe->tqe_next;
8779 				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8780 					removed++;
8781 			}
8782 		}
8783 
8784 		for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
8785 			ifqnext = ifq->ifq_next;
8786 
8787 			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
8788 				if (try < tqe->tqe_touched)
8789 					break;
8790 				tqn = tqe->tqe_next;
8791 				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8792 					removed++;
8793 			}
8794 		}
8795 
8796 		if (try >= iend) {
8797 			if (interval == IPF_TTLVAL(43200)) {
8798 				interval = IPF_TTLVAL(1800);
8799 			} else if (interval == IPF_TTLVAL(1800)) {
8800 				interval = IPF_TTLVAL(30);
8801 			} else {
8802 				break;
8803 			}
8804 			if (interval >= softc->ipf_ticks)
8805 				break;
8806 
8807 			iend = softc->ipf_ticks - interval;
8808 		}
8809 		istart -= interval;
8810 	}
8811 
8812 	return removed;
8813 }
8814 
8815 
8816 /* ------------------------------------------------------------------------ */
8817 /* Function:    ipf_deliverlocal                                            */
8818 /* Returns:     int - 1 = local address, 0 = non-local address              */
8819 /* Parameters:  softc(I)     - pointer to soft context main structure       */
8820 /*              ipversion(I) - IP protocol version (4 or 6)                 */
8821 /*              ifp(I)       - network interface pointer                    */
8822 /*              ipaddr(I)    - IPv4/6 destination address                   */
8823 /*                                                                          */
8824 /* This fucntion is used to determine in the address "ipaddr" belongs to    */
8825 /* the network interface represented by ifp.                                */
8826 /* ------------------------------------------------------------------------ */
8827 int
8828 ipf_deliverlocal(ipf_main_softc_t *softc, int ipversion, void *ifp,
8829     i6addr_t *ipaddr)
8830 {
8831 	i6addr_t addr;
8832 	int islocal = 0;
8833 
8834 	if (ipversion == 4) {
8835 		if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
8836 			if (addr.in4.s_addr == ipaddr->in4.s_addr)
8837 				islocal = 1;
8838 		}
8839 
8840 #ifdef USE_INET6
8841 	} else if (ipversion == 6) {
8842 		if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
8843 			if (IP6_EQ(&addr, ipaddr))
8844 				islocal = 1;
8845 		}
8846 #endif
8847 	}
8848 
8849 	return islocal;
8850 }
8851 
8852 
8853 /* ------------------------------------------------------------------------ */
8854 /* Function:    ipf_settimeout                                              */
8855 /* Returns:     int - 0 = success, -1 = failure                             */
8856 /* Parameters:  softc(I) - pointer to soft context main structure           */
8857 /*              t(I)     - pointer to tuneable array entry                  */
8858 /*              p(I)     - pointer to values passed in to apply             */
8859 /*                                                                          */
8860 /* This function is called to set the timeout values for each distinct      */
8861 /* queue timeout that is available.  When called, it calls into both the    */
8862 /* state and NAT code, telling them to update their timeout queues.         */
8863 /* ------------------------------------------------------------------------ */
8864 static int
8865 ipf_settimeout(struct ipf_main_softc_s *softc, ipftuneable_t *t,
8866     ipftuneval_t *p)
8867 {
8868 
8869 	/*
8870 	 * ipf_interror should be set by the functions called here, not
8871 	 * by this function - it's just a middle man.
8872 	 */
8873 	if (ipf_state_settimeout(softc, t, p) == -1)
8874 		return -1;
8875 	if (ipf_nat_settimeout(softc, t, p) == -1)
8876 		return -1;
8877 	return 0;
8878 }
8879 
8880 
8881 /* ------------------------------------------------------------------------ */
8882 /* Function:    ipf_apply_timeout                                           */
8883 /* Returns:     int - 0 = success, -1 = failure                             */
8884 /* Parameters:  head(I)    - pointer to tuneable array entry                */
8885 /*              seconds(I) - pointer to values passed in to apply           */
8886 /*                                                                          */
8887 /* This function applies a timeout of "seconds" to the timeout queue that   */
8888 /* is pointed to by "head".  All entries on this list have an expiration    */
8889 /* set to be the current tick value of ipf plus the ttl.  Given that this   */
8890 /* function should only be called when the delta is non-zero, the task is   */
8891 /* to walk the entire list and apply the change.  The sort order will not   */
8892 /* change.  The only catch is that this is O(n) across the list, so if the  */
8893 /* queue has lots of entries (10s of thousands or 100s of thousands), it    */
8894 /* could take a relatively long time to work through them all.              */
8895 /* ------------------------------------------------------------------------ */
8896 void
8897 ipf_apply_timeout(ipftq_t *head, u_int seconds)
8898 {
8899 	u_int oldtimeout, newtimeout;
8900 	ipftqent_t *tqe;
8901 	int delta;
8902 
8903 	MUTEX_ENTER(&head->ifq_lock);
8904 	oldtimeout = head->ifq_ttl;
8905 	newtimeout = IPF_TTLVAL(seconds);
8906 	delta = oldtimeout - newtimeout;
8907 
8908 	head->ifq_ttl = newtimeout;
8909 
8910 	for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
8911 		tqe->tqe_die += delta;
8912 	}
8913 	MUTEX_EXIT(&head->ifq_lock);
8914 }
8915 
8916 
8917 /* ------------------------------------------------------------------------ */
8918 /* Function:   ipf_settimeout_tcp                                           */
8919 /* Returns:    int - 0 = successfully applied, -1 = failed                  */
8920 /* Parameters: t(I)   - pointer to tuneable to change                       */
8921 /*             p(I)   - pointer to new timeout information                  */
8922 /*             tab(I) - pointer to table of TCP queues                      */
8923 /*                                                                          */
8924 /* This function applies the new timeout (p) to the TCP tunable (t) and     */
8925 /* updates all of the entries on the relevant timeout queue by calling      */
8926 /* ipf_apply_timeout().                                                     */
8927 /* ------------------------------------------------------------------------ */
8928 int
8929 ipf_settimeout_tcp(ipftuneable_t *t, ipftuneval_t *p, ipftq_t *tab)
8930 {
8931 	if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
8932 	    !strcmp(t->ipft_name, "tcp_established")) {
8933 		ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
8934 	} else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
8935 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
8936 	} else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
8937 		ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
8938 	} else if (!strcmp(t->ipft_name, "tcp_timeout")) {
8939 		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
8940 		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
8941 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
8942 	} else if (!strcmp(t->ipft_name, "tcp_listen")) {
8943 		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
8944 	} else if (!strcmp(t->ipft_name, "tcp_half_established")) {
8945 		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
8946 	} else if (!strcmp(t->ipft_name, "tcp_closing")) {
8947 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
8948 	} else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
8949 		ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
8950 	} else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
8951 		ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
8952 	} else if (!strcmp(t->ipft_name, "tcp_closed")) {
8953 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
8954 	} else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
8955 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
8956 	} else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
8957 		ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
8958 	} else {
8959 		/*
8960 		 * ipf_interror isn't set here because it should be set
8961 		 * by whatever called this function.
8962 		 */
8963 		return -1;
8964 	}
8965 	return 0;
8966 }
8967 
8968 
8969 /* ------------------------------------------------------------------------ */
8970 /* Function:   ipf_main_soft_create                                         */
8971 /* Returns:    NULL = failure, else success                                 */
8972 /* Parameters: arg(I) - pointer to soft context structure if already allocd */
8973 /*                                                                          */
8974 /* Create the foundation soft context structure. In circumstances where it  */
8975 /* is not required to dynamically allocate the context, a pointer can be    */
8976 /* passed in (rather than NULL) to a structure to be initialised.           */
8977 /* The main thing of interest is that a number of locks are initialised     */
8978 /* here instead of in the where might be expected - in the relevant create  */
8979 /* function elsewhere.  This is done because the current locking design has */
8980 /* some areas where these locks are used outside of their module.           */
8981 /* Possibly the most important exercise that is done here is setting of all */
8982 /* the timeout values, allowing them to be changed before init().           */
8983 /* ------------------------------------------------------------------------ */
8984 void *
8985 ipf_main_soft_create(void *arg)
8986 {
8987 	ipf_main_softc_t *softc;
8988 
8989 	if (arg == NULL) {
8990 		KMALLOC(softc, ipf_main_softc_t *);
8991 		if (softc == NULL)
8992 			return NULL;
8993 	} else {
8994 		softc = arg;
8995 	}
8996 
8997 	bzero((char *)softc, sizeof(*softc));
8998 
8999 	/*
9000 	 * This serves as a flag as to whether or not the softc should be
9001 	 * free'd when _destroy is called.
9002 	 */
9003 	softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
9004 
9005 	softc->ipf_tuners = ipf_tune_array_copy(softc,
9006 						sizeof(ipf_main_tuneables),
9007 						ipf_main_tuneables);
9008 	if (softc->ipf_tuners == NULL) {
9009 		ipf_main_soft_destroy(softc);
9010 		return NULL;
9011 	}
9012 
9013 	MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
9014 	MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
9015 	RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
9016 	RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
9017 	RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
9018 	RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
9019 	RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
9020 	RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
9021 	RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
9022 
9023 	softc->ipf_token_head = NULL;
9024 	softc->ipf_token_tail = &softc->ipf_token_head;
9025 
9026 	softc->ipf_tcpidletimeout = FIVE_DAYS;
9027 	softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
9028 	softc->ipf_tcplastack = IPF_TTLVAL(30);
9029 	softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
9030 	softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
9031 	softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
9032 	softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
9033 	softc->ipf_tcpclosed = IPF_TTLVAL(30);
9034 	softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
9035 	softc->ipf_udptimeout = IPF_TTLVAL(120);
9036 	softc->ipf_udpacktimeout = IPF_TTLVAL(12);
9037 	softc->ipf_icmptimeout = IPF_TTLVAL(60);
9038 	softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
9039 	softc->ipf_iptimeout = IPF_TTLVAL(60);
9040 
9041 #if defined(IPFILTER_DEFAULT_BLOCK)
9042 	softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
9043 #else
9044 	softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
9045 #endif
9046 	softc->ipf_minttl = 4;
9047 	softc->ipf_icmpminfragmtu = 68;
9048 	softc->ipf_flags = IPF_LOGGING;
9049 
9050 	return softc;
9051 }
9052 
9053 /* ------------------------------------------------------------------------ */
9054 /* Function:   ipf_main_soft_init                                           */
9055 /* Returns:    0 = success, -1 = failure                                    */
9056 /* Parameters: softc(I) - pointer to soft context main structure            */
9057 /*                                                                          */
9058 /* A null-op function that exists as a placeholder so that the flow in      */
9059 /* other functions is obvious.                                              */
9060 /* ------------------------------------------------------------------------ */
9061 /*ARGSUSED*/
9062 int
9063 ipf_main_soft_init(ipf_main_softc_t *softc)
9064 {
9065 	return 0;
9066 }
9067 
9068 
9069 /* ------------------------------------------------------------------------ */
9070 /* Function:   ipf_main_soft_destroy                                        */
9071 /* Returns:    void                                                         */
9072 /* Parameters: softc(I) - pointer to soft context main structure            */
9073 /*                                                                          */
9074 /* Undo everything that we did in ipf_main_soft_create.                     */
9075 /*                                                                          */
9076 /* The most important check that needs to be made here is whether or not    */
9077 /* the structure was allocated by ipf_main_soft_create() by checking what   */
9078 /* value is stored in ipf_dynamic_main.                                     */
9079 /* ------------------------------------------------------------------------ */
9080 /*ARGSUSED*/
9081 void
9082 ipf_main_soft_destroy(ipf_main_softc_t *softc)
9083 {
9084 
9085 	RW_DESTROY(&softc->ipf_frag);
9086 	RW_DESTROY(&softc->ipf_poolrw);
9087 	RW_DESTROY(&softc->ipf_nat);
9088 	RW_DESTROY(&softc->ipf_state);
9089 	RW_DESTROY(&softc->ipf_tokens);
9090 	RW_DESTROY(&softc->ipf_mutex);
9091 	RW_DESTROY(&softc->ipf_global);
9092 	MUTEX_DESTROY(&softc->ipf_timeoutlock);
9093 	MUTEX_DESTROY(&softc->ipf_rw);
9094 
9095 	if (softc->ipf_tuners != NULL) {
9096 		KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
9097 	}
9098 	if (softc->ipf_dynamic_softc == 1) {
9099 		KFREE(softc);
9100 	}
9101 }
9102 
9103 
9104 /* ------------------------------------------------------------------------ */
9105 /* Function:   ipf_main_soft_fini                                           */
9106 /* Returns:    0 = success, -1 = failure                                    */
9107 /* Parameters: softc(I) - pointer to soft context main structure            */
9108 /*                                                                          */
9109 /* Clean out the rules which have been added since _init was last called,   */
9110 /* the only dynamic part of the mainline.                                   */
9111 /* ------------------------------------------------------------------------ */
9112 int
9113 ipf_main_soft_fini(ipf_main_softc_t *softc)
9114 {
9115 	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9116 	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
9117 	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9118 	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
9119 
9120 	return 0;
9121 }
9122 
9123 
9124 /* ------------------------------------------------------------------------ */
9125 /* Function:   ipf_main_load                                                */
9126 /* Returns:    0 = success, -1 = failure                                    */
9127 /* Parameters: none                                                         */
9128 /*                                                                          */
9129 /* Handle global initialisation that needs to be done for the base part of  */
9130 /* IPFilter. At present this just amounts to initialising some ICMP lookup  */
9131 /* arrays that get used by the state/NAT code.                              */
9132 /* ------------------------------------------------------------------------ */
9133 int
9134 ipf_main_load(void)
9135 {
9136 	int i;
9137 
9138 	/* fill icmp reply type table */
9139 	for (i = 0; i <= ICMP_MAXTYPE; i++)
9140 		icmpreplytype4[i] = -1;
9141 	icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
9142 	icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
9143 	icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
9144 	icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
9145 
9146 #ifdef  USE_INET6
9147 	/* fill icmp reply type table */
9148 	for (i = 0; i <= ICMP6_MAXTYPE; i++)
9149 		icmpreplytype6[i] = -1;
9150 	icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
9151 	icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
9152 	icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
9153 	icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
9154 	icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
9155 #endif
9156 
9157 	return 0;
9158 }
9159 
9160 
9161 /* ------------------------------------------------------------------------ */
9162 /* Function:   ipf_main_unload                                              */
9163 /* Returns:    0 = success, -1 = failure                                    */
9164 /* Parameters: none                                                         */
9165 /*                                                                          */
9166 /* A null-op function that exists as a placeholder so that the flow in      */
9167 /* other functions is obvious.                                              */
9168 /* ------------------------------------------------------------------------ */
9169 int
9170 ipf_main_unload(void)
9171 {
9172 	return 0;
9173 }
9174 
9175 
9176 /* ------------------------------------------------------------------------ */
9177 /* Function:   ipf_load_all                                                 */
9178 /* Returns:    0 = success, -1 = failure                                    */
9179 /* Parameters: none                                                         */
9180 /*                                                                          */
9181 /* Work through all of the subsystems inside IPFilter and call the load     */
9182 /* function for each in an order that won't lead to a crash :)              */
9183 /* ------------------------------------------------------------------------ */
9184 int
9185 ipf_load_all(void)
9186 {
9187 	if (ipf_main_load() == -1)
9188 		return -1;
9189 
9190 	if (ipf_state_main_load() == -1)
9191 		return -1;
9192 
9193 	if (ipf_nat_main_load() == -1)
9194 		return -1;
9195 
9196 	if (ipf_frag_main_load() == -1)
9197 		return -1;
9198 
9199 	if (ipf_auth_main_load() == -1)
9200 		return -1;
9201 
9202 	if (ipf_proxy_main_load() == -1)
9203 		return -1;
9204 
9205 	return 0;
9206 }
9207 
9208 
9209 /* ------------------------------------------------------------------------ */
9210 /* Function:   ipf_unload_all                                               */
9211 /* Returns:    0 = success, -1 = failure                                    */
9212 /* Parameters: none                                                         */
9213 /*                                                                          */
9214 /* Work through all of the subsystems inside IPFilter and call the unload   */
9215 /* function for each in an order that won't lead to a crash :)              */
9216 /* ------------------------------------------------------------------------ */
9217 int
9218 ipf_unload_all(void)
9219 {
9220 	if (ipf_proxy_main_unload() == -1)
9221 		return -1;
9222 
9223 	if (ipf_auth_main_unload() == -1)
9224 		return -1;
9225 
9226 	if (ipf_frag_main_unload() == -1)
9227 		return -1;
9228 
9229 	if (ipf_nat_main_unload() == -1)
9230 		return -1;
9231 
9232 	if (ipf_state_main_unload() == -1)
9233 		return -1;
9234 
9235 	if (ipf_main_unload() == -1)
9236 		return -1;
9237 
9238 	return 0;
9239 }
9240 
9241 
9242 /* ------------------------------------------------------------------------ */
9243 /* Function:   ipf_create_all                                               */
9244 /* Returns:    NULL = failure, else success                                 */
9245 /* Parameters: arg(I) - pointer to soft context main structure              */
9246 /*                                                                          */
9247 /* Work through all of the subsystems inside IPFilter and call the create   */
9248 /* function for each in an order that won't lead to a crash :)              */
9249 /* ------------------------------------------------------------------------ */
9250 ipf_main_softc_t *
9251 ipf_create_all(void *arg)
9252 {
9253 	ipf_main_softc_t *softc;
9254 
9255 	softc = ipf_main_soft_create(arg);
9256 	if (softc == NULL)
9257 		return NULL;
9258 
9259 #ifdef IPFILTER_LOG
9260 	softc->ipf_log_soft = ipf_log_soft_create(softc);
9261 	if (softc->ipf_log_soft == NULL) {
9262 		ipf_destroy_all(softc);
9263 		return NULL;
9264 	}
9265 #endif
9266 
9267 	softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
9268 	if (softc->ipf_lookup_soft == NULL) {
9269 		ipf_destroy_all(softc);
9270 		return NULL;
9271 	}
9272 
9273 	softc->ipf_sync_soft = ipf_sync_soft_create(softc);
9274 	if (softc->ipf_sync_soft == NULL) {
9275 		ipf_destroy_all(softc);
9276 		return NULL;
9277 	}
9278 
9279 	softc->ipf_state_soft = ipf_state_soft_create(softc);
9280 	if (softc->ipf_state_soft == NULL) {
9281 		ipf_destroy_all(softc);
9282 		return NULL;
9283 	}
9284 
9285 	softc->ipf_nat_soft = ipf_nat_soft_create(softc);
9286 	if (softc->ipf_nat_soft == NULL) {
9287 		ipf_destroy_all(softc);
9288 		return NULL;
9289 	}
9290 
9291 	softc->ipf_frag_soft = ipf_frag_soft_create(softc);
9292 	if (softc->ipf_frag_soft == NULL) {
9293 		ipf_destroy_all(softc);
9294 		return NULL;
9295 	}
9296 
9297 	softc->ipf_auth_soft = ipf_auth_soft_create(softc);
9298 	if (softc->ipf_auth_soft == NULL) {
9299 		ipf_destroy_all(softc);
9300 		return NULL;
9301 	}
9302 
9303 	softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
9304 	if (softc->ipf_proxy_soft == NULL) {
9305 		ipf_destroy_all(softc);
9306 		return NULL;
9307 	}
9308 
9309 	return softc;
9310 }
9311 
9312 
9313 /* ------------------------------------------------------------------------ */
9314 /* Function:   ipf_destroy_all                                              */
9315 /* Returns:    void                                                         */
9316 /* Parameters: softc(I) - pointer to soft context main structure            */
9317 /*                                                                          */
9318 /* Work through all of the subsystems inside IPFilter and call the destroy  */
9319 /* function for each in an order that won't lead to a crash :)              */
9320 /*                                                                          */
9321 /* Every one of these functions is expected to succeed, so there is no      */
9322 /* checking of return values.                                               */
9323 /* ------------------------------------------------------------------------ */
9324 void
9325 ipf_destroy_all(ipf_main_softc_t *softc)
9326 {
9327 
9328 	if (softc->ipf_state_soft != NULL) {
9329 		ipf_state_soft_destroy(softc, softc->ipf_state_soft);
9330 		softc->ipf_state_soft = NULL;
9331 	}
9332 
9333 	if (softc->ipf_nat_soft != NULL) {
9334 		ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
9335 		softc->ipf_nat_soft = NULL;
9336 	}
9337 
9338 	if (softc->ipf_frag_soft != NULL) {
9339 		ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
9340 		softc->ipf_frag_soft = NULL;
9341 	}
9342 
9343 	if (softc->ipf_auth_soft != NULL) {
9344 		ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
9345 		softc->ipf_auth_soft = NULL;
9346 	}
9347 
9348 	if (softc->ipf_proxy_soft != NULL) {
9349 		ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
9350 		softc->ipf_proxy_soft = NULL;
9351 	}
9352 
9353 	if (softc->ipf_sync_soft != NULL) {
9354 		ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
9355 		softc->ipf_sync_soft = NULL;
9356 	}
9357 
9358 	if (softc->ipf_lookup_soft != NULL) {
9359 		ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
9360 		softc->ipf_lookup_soft = NULL;
9361 	}
9362 
9363 #ifdef IPFILTER_LOG
9364 	if (softc->ipf_log_soft != NULL) {
9365 		ipf_log_soft_destroy(softc, softc->ipf_log_soft);
9366 		softc->ipf_log_soft = NULL;
9367 	}
9368 #endif
9369 
9370 	ipf_main_soft_destroy(softc);
9371 }
9372 
9373 
9374 /* ------------------------------------------------------------------------ */
9375 /* Function:   ipf_init_all                                                 */
9376 /* Returns:    0 = success, -1 = failure                                    */
9377 /* Parameters: softc(I) - pointer to soft context main structure            */
9378 /*                                                                          */
9379 /* Work through all of the subsystems inside IPFilter and call the init     */
9380 /* function for each in an order that won't lead to a crash :)              */
9381 /* ------------------------------------------------------------------------ */
9382 int
9383 ipf_init_all(ipf_main_softc_t *softc)
9384 {
9385 
9386 	if (ipf_main_soft_init(softc) == -1)
9387 		return -1;
9388 
9389 #ifdef IPFILTER_LOG
9390 	if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
9391 		return -1;
9392 #endif
9393 
9394 	if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
9395 		return -1;
9396 
9397 	if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
9398 		return -1;
9399 
9400 	if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
9401 		return -1;
9402 
9403 	if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
9404 		return -1;
9405 
9406 	if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
9407 		return -1;
9408 
9409 	if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
9410 		return -1;
9411 
9412 	if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
9413 		return -1;
9414 
9415 	return 0;
9416 }
9417 
9418 
9419 /* ------------------------------------------------------------------------ */
9420 /* Function:   ipf_fini_all                                                 */
9421 /* Returns:    0 = success, -1 = failure                                    */
9422 /* Parameters: softc(I) - pointer to soft context main structure            */
9423 /*                                                                          */
9424 /* Work through all of the subsystems inside IPFilter and call the fini     */
9425 /* function for each in an order that won't lead to a crash :)              */
9426 /* ------------------------------------------------------------------------ */
9427 int
9428 ipf_fini_all(ipf_main_softc_t *softc)
9429 {
9430 
9431 	ipf_token_flush(softc);
9432 
9433 	if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
9434 		return -1;
9435 
9436 	if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
9437 		return -1;
9438 
9439 	if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
9440 		return -1;
9441 
9442 	if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
9443 		return -1;
9444 
9445 	if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
9446 		return -1;
9447 
9448 	if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
9449 		return -1;
9450 
9451 	if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
9452 		return -1;
9453 
9454 #ifdef IPFILTER_LOG
9455 	if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
9456 		return -1;
9457 #endif
9458 
9459 	if (ipf_main_soft_fini(softc) == -1)
9460 		return -1;
9461 
9462 	return 0;
9463 }
9464 
9465 
9466 /* ------------------------------------------------------------------------ */
9467 /* Function:    ipf_rule_expire                                             */
9468 /* Returns:     Nil                                                         */
9469 /* Parameters:  softc(I) - pointer to soft context main structure           */
9470 /*                                                                          */
9471 /* At present this function exists just to support temporary addition of    */
9472 /* firewall rules. Both inactive and active lists are scanned for items to  */
9473 /* purge, as by rights, the expiration is computed as soon as the rule is   */
9474 /* loaded in.                                                               */
9475 /* ------------------------------------------------------------------------ */
9476 void
9477 ipf_rule_expire(ipf_main_softc_t *softc)
9478 {
9479 	frentry_t *fr;
9480 
9481 	if ((softc->ipf_rule_explist[0] == NULL) &&
9482 	    (softc->ipf_rule_explist[1] == NULL))
9483 		return;
9484 
9485 	WRITE_ENTER(&softc->ipf_mutex);
9486 
9487 	while ((fr = softc->ipf_rule_explist[0]) != NULL) {
9488 		/*
9489 		 * Because the list is kept sorted on insertion, the fist
9490 		 * one that dies in the future means no more work to do.
9491 		 */
9492 		if (fr->fr_die > softc->ipf_ticks)
9493 			break;
9494 		ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
9495 	}
9496 
9497 	while ((fr = softc->ipf_rule_explist[1]) != NULL) {
9498 		/*
9499 		 * Because the list is kept sorted on insertion, the fist
9500 		 * one that dies in the future means no more work to do.
9501 		 */
9502 		if (fr->fr_die > softc->ipf_ticks)
9503 			break;
9504 		ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
9505 	}
9506 
9507 	RWLOCK_EXIT(&softc->ipf_mutex);
9508 }
9509 
9510 
9511 static int ipf_ht_node_cmp(const struct host_node_s *, const struct host_node_s *);
9512 static void ipf_ht_node_make_key(host_track_t *, host_node_t *, int,
9513 				 i6addr_t *);
9514 
9515 RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
9516 
9517 
9518 /* ------------------------------------------------------------------------ */
9519 /* Function:    ipf_ht_node_cmp                                             */
9520 /* Returns:     int   - 0 == nodes are the same, ..                         */
9521 /* Parameters:  k1(I) - pointer to first key to compare                     */
9522 /*              k2(I) - pointer to second key to compare                    */
9523 /*                                                                          */
9524 /* The "key" for the node is a combination of two fields: the address       */
9525 /* family and the address itself.                                           */
9526 /*                                                                          */
9527 /* Because we're not actually interpreting the address data, it isn't       */
9528 /* necessary to convert them to/from network/host byte order. The mask is   */
9529 /* just used to remove bits that aren't significant - it doesn't matter     */
9530 /* where they are, as long as they're always in the same place.             */
9531 /*                                                                          */
9532 /* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because    */
9533 /* this is where individual ones will differ the most - but not true for    */
9534 /* for /48's, etc.                                                          */
9535 /* ------------------------------------------------------------------------ */
9536 static int
9537 ipf_ht_node_cmp(const struct host_node_s *k1, const struct host_node_s *k2)
9538 {
9539 	int i;
9540 
9541 	i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
9542 	if (i != 0)
9543 		return i;
9544 
9545 	if (k1->hn_addr.adf_family == AF_INET)
9546 		return (k2->hn_addr.adf_addr.in4.s_addr -
9547 			k1->hn_addr.adf_addr.in4.s_addr);
9548 
9549 	i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
9550 	if (i != 0)
9551 		return i;
9552 	i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
9553 	if (i != 0)
9554 		return i;
9555 	i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
9556 	if (i != 0)
9557 		return i;
9558 	i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
9559 	return i;
9560 }
9561 
9562 
9563 /* ------------------------------------------------------------------------ */
9564 /* Function:    ipf_ht_node_make_key                                        */
9565 /* Returns:     Nil                                                         */
9566 /* parameters:  htp(I)    - pointer to address tracking structure           */
9567 /*              key(I)    - where to store masked address for lookup        */
9568 /*              family(I) - protocol family of address                      */
9569 /*              addr(I)   - pointer to network address                      */
9570 /*                                                                          */
9571 /* Using the "netmask" (number of bits) stored parent host tracking struct, */
9572 /* copy the address passed in into the key structure whilst masking out the */
9573 /* bits that we don't want.                                                 */
9574 /*                                                                          */
9575 /* Because the parser will set ht_netmask to 128 if there is no protocol    */
9576 /* specified (the parser doesn't know if it should be a v4 or v6 rule), we  */
9577 /* have to be wary of that and not allow 32-128 to happen.                  */
9578 /* ------------------------------------------------------------------------ */
9579 static void
9580 ipf_ht_node_make_key(host_track_t *htp, host_node_t *key, int family,
9581     i6addr_t *addr)
9582 {
9583 	key->hn_addr.adf_family = family;
9584 	if (family == AF_INET) {
9585 		u_32_t mask;
9586 		int bits;
9587 
9588 		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
9589 		bits = htp->ht_netmask;
9590 		if (bits >= 32) {
9591 			mask = 0xffffffff;
9592 		} else {
9593 			mask = htonl(0xffffffff << (32 - bits));
9594 		}
9595 		key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
9596 #ifdef USE_INET6
9597 	} else {
9598 		int bits = htp->ht_netmask;
9599 
9600 		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
9601 		if (bits > 96) {
9602 			key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
9603 					     htonl(0xffffffff << (128 - bits));
9604 			key->hn_addr.adf_addr.i6[2] = addr->i6[2];
9605 			key->hn_addr.adf_addr.i6[1] = addr->i6[2];
9606 			key->hn_addr.adf_addr.i6[0] = addr->i6[2];
9607 		} else if (bits > 64) {
9608 			key->hn_addr.adf_addr.i6[3] = 0;
9609 			key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
9610 					     htonl(0xffffffff << (96 - bits));
9611 			key->hn_addr.adf_addr.i6[1] = addr->i6[1];
9612 			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9613 		} else if (bits > 32) {
9614 			key->hn_addr.adf_addr.i6[3] = 0;
9615 			key->hn_addr.adf_addr.i6[2] = 0;
9616 			key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
9617 					     htonl(0xffffffff << (64 - bits));
9618 			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9619 		} else {
9620 			key->hn_addr.adf_addr.i6[3] = 0;
9621 			key->hn_addr.adf_addr.i6[2] = 0;
9622 			key->hn_addr.adf_addr.i6[1] = 0;
9623 			key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
9624 					     htonl(0xffffffff << (32 - bits));
9625 		}
9626 #endif
9627 	}
9628 }
9629 
9630 
9631 /* ------------------------------------------------------------------------ */
9632 /* Function:    ipf_ht_node_add                                             */
9633 /* Returns:     int       - 0 == success,  -1 == failure                    */
9634 /* Parameters:  softc(I)  - pointer to soft context main structure          */
9635 /*              htp(I)    - pointer to address tracking structure           */
9636 /*              family(I) - protocol family of address                      */
9637 /*              addr(I)   - pointer to network address                      */
9638 /*                                                                          */
9639 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
9640 /*       ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
9641 /*                                                                          */
9642 /* After preparing the key with the address information to find, look in    */
9643 /* the red-black tree to see if the address is known. A successful call to  */
9644 /* this function can mean one of two things: a new node was added to the    */
9645 /* tree or a matching node exists and we're able to bump up its activity.   */
9646 /* ------------------------------------------------------------------------ */
9647 int
9648 ipf_ht_node_add(ipf_main_softc_t *softc, host_track_t *htp, int family,
9649     i6addr_t *addr)
9650 {
9651 	host_node_t *h;
9652 	host_node_t k;
9653 
9654 	ipf_ht_node_make_key(htp, &k, family, addr);
9655 
9656 	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9657 	if (h == NULL) {
9658 		if (htp->ht_cur_nodes >= htp->ht_max_nodes)
9659 			return -1;
9660 		KMALLOC(h, host_node_t *);
9661 		if (h == NULL) {
9662 			DT(ipf_rb_no_mem);
9663 			LBUMP(ipf_rb_no_mem);
9664 			return -1;
9665 		}
9666 
9667 		/*
9668 		 * If there was a macro to initialise the RB node then that
9669 		 * would get used here, but there isn't...
9670 		 */
9671 		bzero((char *)h, sizeof(*h));
9672 		h->hn_addr = k.hn_addr;
9673 		h->hn_addr.adf_family = k.hn_addr.adf_family;
9674 		RBI_INSERT(ipf_rb, &htp->ht_root, h);
9675 		htp->ht_cur_nodes++;
9676 	} else {
9677 		if ((htp->ht_max_per_node != 0) &&
9678 		    (h->hn_active >= htp->ht_max_per_node)) {
9679 			DT(ipf_rb_node_max);
9680 			LBUMP(ipf_rb_node_max);
9681 			return -1;
9682 		}
9683 	}
9684 
9685 	h->hn_active++;
9686 
9687 	return 0;
9688 }
9689 
9690 
9691 /* ------------------------------------------------------------------------ */
9692 /* Function:    ipf_ht_node_del                                             */
9693 /* Returns:     int       - 0 == success,  -1 == failure                    */
9694 /* parameters:  htp(I)    - pointer to address tracking structure           */
9695 /*              family(I) - protocol family of address                      */
9696 /*              addr(I)   - pointer to network address                      */
9697 /*                                                                          */
9698 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
9699 /*       ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
9700 /*                                                                          */
9701 /* Try and find the address passed in amongst the leaves on this tree to    */
9702 /* be friend. If found then drop the active account for that node drops by  */
9703 /* one. If that count reaches 0, it is time to free it all up.              */
9704 /* ------------------------------------------------------------------------ */
9705 int
9706 ipf_ht_node_del(host_track_t *htp, int family, i6addr_t *addr)
9707 {
9708 	host_node_t *h;
9709 	host_node_t k;
9710 
9711 	ipf_ht_node_make_key(htp, &k, family, addr);
9712 
9713 	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9714 	if (h == NULL) {
9715 		return -1;
9716 	} else {
9717 		h->hn_active--;
9718 		if (h->hn_active == 0) {
9719 			(void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
9720 			htp->ht_cur_nodes--;
9721 			KFREE(h);
9722 		}
9723 	}
9724 
9725 	return 0;
9726 }
9727 
9728 
9729 /* ------------------------------------------------------------------------ */
9730 /* Function:    ipf_rb_ht_init                                              */
9731 /* Returns:     Nil                                                         */
9732 /* Parameters:  head(I) - pointer to host tracking structure                */
9733 /*                                                                          */
9734 /* Initialise the host tracking structure to be ready for use above.        */
9735 /* ------------------------------------------------------------------------ */
9736 void
9737 ipf_rb_ht_init(host_track_t *head)
9738 {
9739 	memset(head, 0, sizeof(*head));
9740 	RBI_INIT(ipf_rb, &head->ht_root);
9741 }
9742 
9743 
9744 /* ------------------------------------------------------------------------ */
9745 /* Function:    ipf_rb_ht_freenode                                          */
9746 /* Returns:     Nil                                                         */
9747 /* Parameters:  head(I) - pointer to host tracking structure                */
9748 /*              arg(I)  - additional argument from walk caller              */
9749 /*                                                                          */
9750 /* Free an actual host_node_t structure.                                    */
9751 /* ------------------------------------------------------------------------ */
9752 void
9753 ipf_rb_ht_freenode(host_node_t *node, void *arg)
9754 {
9755 	KFREE(node);
9756 }
9757 
9758 
9759 /* ------------------------------------------------------------------------ */
9760 /* Function:    ipf_rb_ht_flush                                             */
9761 /* Returns:     Nil                                                         */
9762 /* Parameters:  head(I) - pointer to host tracking structure                */
9763 /*                                                                          */
9764 /* Remove all of the nodes in the tree tracking hosts by calling a walker   */
9765 /* and free'ing each one.                                                   */
9766 /* ------------------------------------------------------------------------ */
9767 void
9768 ipf_rb_ht_flush(host_track_t *head)
9769 {
9770 	/* XXX - May use node members after freeing the node. */
9771 	RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
9772 }
9773 
9774 
9775 /* ------------------------------------------------------------------------ */
9776 /* Function:    ipf_slowtimer                                               */
9777 /* Returns:     Nil                                                         */
9778 /* Parameters:  ptr(I) - pointer to main ipf soft context structure         */
9779 /*                                                                          */
9780 /* Slowly expire held state for fragments.  Timeouts are set * in           */
9781 /* expectation of this being called twice per second.                       */
9782 /* ------------------------------------------------------------------------ */
9783 void
9784 ipf_slowtimer(ipf_main_softc_t *softc)
9785 {
9786 
9787 	ipf_token_expire(softc);
9788 	ipf_frag_expire(softc);
9789 	ipf_state_expire(softc);
9790 	ipf_nat_expire(softc);
9791 	ipf_auth_expire(softc);
9792 	ipf_lookup_expire(softc);
9793 	ipf_rule_expire(softc);
9794 	ipf_sync_expire(softc);
9795 	softc->ipf_ticks++;
9796 #   if defined(__OpenBSD__)
9797 	timeout_add(&ipf_slowtimer_ch, hz/2);
9798 #   endif
9799 }
9800 
9801 
9802 /* ------------------------------------------------------------------------ */
9803 /* Function:    ipf_inet_mask_add                                           */
9804 /* Returns:     Nil                                                         */
9805 /* Parameters:  bits(I) - pointer to nat context information                */
9806 /*              mtab(I) - pointer to mask hash table structure              */
9807 /*                                                                          */
9808 /* When called, bits represents the mask of a new NAT rule that has just    */
9809 /* been added. This function inserts a bitmask into the array of masks to   */
9810 /* search when searching for a matching NAT rule for a packet.              */
9811 /* Prevention of duplicate masks is achieved by checking the use count for  */
9812 /* a given netmask.                                                         */
9813 /* ------------------------------------------------------------------------ */
9814 void
9815 ipf_inet_mask_add(int bits, ipf_v4_masktab_t *mtab)
9816 {
9817 	u_32_t mask;
9818 	int i, j;
9819 
9820 	mtab->imt4_masks[bits]++;
9821 	if (mtab->imt4_masks[bits] > 1)
9822 		return;
9823 
9824 	if (bits == 0)
9825 		mask = 0;
9826 	else
9827 		mask = 0xffffffff << (32 - bits);
9828 
9829 	for (i = 0; i < 33; i++) {
9830 		if (ntohl(mtab->imt4_active[i]) < mask) {
9831 			for (j = 32; j > i; j--)
9832 				mtab->imt4_active[j] = mtab->imt4_active[j - 1];
9833 			mtab->imt4_active[i] = htonl(mask);
9834 			break;
9835 		}
9836 	}
9837 	mtab->imt4_max++;
9838 }
9839 
9840 
9841 /* ------------------------------------------------------------------------ */
9842 /* Function:    ipf_inet_mask_del                                           */
9843 /* Returns:     Nil                                                         */
9844 /* Parameters:  bits(I) - number of bits set in the netmask                 */
9845 /*              mtab(I) - pointer to mask hash table structure              */
9846 /*                                                                          */
9847 /* Remove the 32bit bitmask represented by "bits" from the collection of    */
9848 /* netmasks stored inside of mtab.                                          */
9849 /* ------------------------------------------------------------------------ */
9850 void
9851 ipf_inet_mask_del(int bits, ipf_v4_masktab_t *mtab)
9852 {
9853 	u_32_t mask;
9854 	int i, j;
9855 
9856 	mtab->imt4_masks[bits]--;
9857 	if (mtab->imt4_masks[bits] > 0)
9858 		return;
9859 
9860 	mask = htonl(0xffffffff << (32 - bits));
9861 	for (i = 0; i < 33; i++) {
9862 		if (mtab->imt4_active[i] == mask) {
9863 			for (j = i + 1; j < 33; j++)
9864 				mtab->imt4_active[j - 1] = mtab->imt4_active[j];
9865 			break;
9866 		}
9867 	}
9868 	mtab->imt4_max--;
9869 	ASSERT(mtab->imt4_max >= 0);
9870 }
9871 
9872 
9873 #ifdef USE_INET6
9874 /* ------------------------------------------------------------------------ */
9875 /* Function:    ipf_inet6_mask_add                                          */
9876 /* Returns:     Nil                                                         */
9877 /* Parameters:  bits(I) - number of bits set in mask                        */
9878 /*              mask(I) - pointer to mask to add                            */
9879 /*              mtab(I) - pointer to mask hash table structure              */
9880 /*                                                                          */
9881 /* When called, bitcount represents the mask of a IPv6 NAT map rule that    */
9882 /* has just been added. This function inserts a bitmask into the array of   */
9883 /* masks to search when searching for a matching NAT rule for a packet.     */
9884 /* Prevention of duplicate masks is achieved by checking the use count for  */
9885 /* a given netmask.                                                         */
9886 /* ------------------------------------------------------------------------ */
9887 void
9888 ipf_inet6_mask_add(int bits, i6addr_t *mask, ipf_v6_masktab_t *mtab)
9889 {
9890 	i6addr_t zero;
9891 	int i, j;
9892 
9893 	mtab->imt6_masks[bits]++;
9894 	if (mtab->imt6_masks[bits] > 1)
9895 		return;
9896 
9897 	if (bits == 0) {
9898 		mask = &zero;
9899 		zero.i6[0] = 0;
9900 		zero.i6[1] = 0;
9901 		zero.i6[2] = 0;
9902 		zero.i6[3] = 0;
9903 	}
9904 
9905 	for (i = 0; i < 129; i++) {
9906 		if (IP6_LT(&mtab->imt6_active[i], mask)) {
9907 			for (j = 128; j > i; j--)
9908 				mtab->imt6_active[j] = mtab->imt6_active[j - 1];
9909 			mtab->imt6_active[i] = *mask;
9910 			break;
9911 		}
9912 	}
9913 	mtab->imt6_max++;
9914 }
9915 
9916 
9917 /* ------------------------------------------------------------------------ */
9918 /* Function:    ipf_inet6_mask_del                                          */
9919 /* Returns:     Nil                                                         */
9920 /* Parameters:  bits(I) - number of bits set in mask                        */
9921 /*              mask(I) - pointer to mask to remove                         */
9922 /*              mtab(I) - pointer to mask hash table structure              */
9923 /*                                                                          */
9924 /* Remove the 128bit bitmask represented by "bits" from the collection of   */
9925 /* netmasks stored inside of mtab.                                          */
9926 /* ------------------------------------------------------------------------ */
9927 void
9928 ipf_inet6_mask_del(int bits, i6addr_t *mask, ipf_v6_masktab_t *mtab)
9929 {
9930 	i6addr_t zero;
9931 	int i, j;
9932 
9933 	mtab->imt6_masks[bits]--;
9934 	if (mtab->imt6_masks[bits] > 0)
9935 		return;
9936 
9937 	if (bits == 0)
9938 		mask = &zero;
9939 	zero.i6[0] = 0;
9940 	zero.i6[1] = 0;
9941 	zero.i6[2] = 0;
9942 	zero.i6[3] = 0;
9943 
9944 	for (i = 0; i < 129; i++) {
9945 		if (IP6_EQ(&mtab->imt6_active[i], mask)) {
9946 			for (j = i + 1; j < 129; j++) {
9947 				mtab->imt6_active[j - 1] = mtab->imt6_active[j];
9948 				if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
9949 					break;
9950 			}
9951 			break;
9952 		}
9953 	}
9954 	mtab->imt6_max--;
9955 	ASSERT(mtab->imt6_max >= 0);
9956 }
9957 #endif
9958